mssql.js 4.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /** @license ms-rest-azure-env
  3. * Copyright (c) Microsoft Corporation. All rights reserved.
  4. * Licensed under the MIT License. See License.txt in the project root for license information.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  9. (factory((global.Azure = {})));
  10. }(this, (function (exports) { 'use strict';
  11. // Copyright (c) Microsoft Corporation. All rights reserved.
  12. // Licensed under the MIT License. See License.txt in the project root for license information.
  13. var Environment = /** @class */ (function () {
  14. function Environment(parameters) {
  15. /**
  16. * Determines whether the authentication endpoint should be validated with Azure AD. Default value is true.
  17. */
  18. this.validateAuthority = true;
  19. if (!parameters || typeof parameters !== "object") {
  20. throw new Error("'parameters' is a required parameter and must be of type 'object'.");
  21. }
  22. // Validate required parameters
  23. var requiredParams = ["name", "portalUrl", "managementEndpointUrl", "resourceManagerEndpointUrl",
  24. "activeDirectoryEndpointUrl", "activeDirectoryResourceId"];
  25. requiredParams.forEach(function (param) {
  26. if (!parameters[param] || typeof parameters[param].valueOf() !== "string") {
  27. throw new Error("Please provide \"" + param + "\" for the environment and it must be of type \"string\".");
  28. }
  29. });
  30. this.name = parameters.name;
  31. this.portalUrl = parameters.portalUrl;
  32. this.managementEndpointUrl = parameters.managementEndpointUrl;
  33. this.resourceManagerEndpointUrl = parameters.resourceManagerEndpointUrl;
  34. this.activeDirectoryEndpointUrl = parameters.activeDirectoryEndpointUrl;
  35. this.activeDirectoryResourceId = parameters.activeDirectoryResourceId;
  36. if (this.activeDirectoryGraphApiVersion) {
  37. this.activeDirectoryGraphApiVersion = parameters.activeDirectoryGraphApiVersion;
  38. }
  39. if (this.activeDirectoryGraphResourceId) {
  40. this.activeDirectoryGraphResourceId = parameters.activeDirectoryGraphResourceId;
  41. }
  42. if (this.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix) {
  43. this.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix = parameters.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix;
  44. }
  45. if (this.azureDataLakeStoreFileSystemEndpointSuffix) {
  46. this.azureDataLakeStoreFileSystemEndpointSuffix = parameters.azureDataLakeStoreFileSystemEndpointSuffix;
  47. }
  48. if (this.batchResourceId) {
  49. this.batchResourceId = parameters.batchResourceId;
  50. }
  51. if (this.galleryEndpointUrl) {
  52. this.galleryEndpointUrl = parameters.galleryEndpointUrl;
  53. }
  54. if (this.keyVaultDnsSuffix) {
  55. this.keyVaultDnsSuffix = parameters.keyVaultDnsSuffix;
  56. }
  57. if (this.publishingProfileUrl) {
  58. this.publishingProfileUrl = parameters.publishingProfileUrl;
  59. }
  60. if (this.sqlManagementEndpointUrl) {
  61. this.sqlManagementEndpointUrl = parameters.sqlManagementEndpointUrl;
  62. }
  63. if (this.sqlServerHostnameSuffix) {
  64. this.sqlServerHostnameSuffix = parameters.sqlServerHostnameSuffix;
  65. }
  66. if (this.storageEndpointSuffix) {
  67. this.storageEndpointSuffix = parameters.storageEndpointSuffix;
  68. }
  69. }
  70. Environment.add = function (parameters) {
  71. var envContainer = {};
  72. var envObj = new Environment(parameters);
  73. envContainer[parameters.name] = envObj;
  74. Object.assign(Environment, envContainer);
  75. return;
  76. };
  77. Environment.get = function (name) {
  78. if (!name) {
  79. throw new TypeError("name cannot be null or undefined and must be of type string.");
  80. }
  81. return Environment[name];
  82. };
  83. Environment.AzureCloud = {
  84. name: "AzureCloud",
  85. portalUrl: "https://portal.azure.com",
  86. publishingProfileUrl: "https://go.microsoft.com/fwlink/?LinkId=254432",
  87. managementEndpointUrl: "https://management.core.windows.net",
  88. resourceManagerEndpointUrl: "https://management.azure.com/",
  89. sqlManagementEndpointUrl: "https://management.core.windows.net:8443/",
  90. sqlServerHostnameSuffix: ".database.windows.net",
  91. galleryEndpointUrl: "https://gallery.azure.com/",
  92. activeDirectoryEndpointUrl: "https://login.microsoftonline.com/",
  93. activeDirectoryResourceId: "https://management.core.windows.net/",
  94. activeDirectoryGraphResourceId: "https://graph.windows.net/",
  95. batchResourceId: "https://batch.core.windows.net/",
  96. activeDirectoryGraphApiVersion: "2013-04-05",
  97. storageEndpointSuffix: ".core.windows.net",
  98. keyVaultDnsSuffix: ".vault.azure.net",
  99. azureDataLakeStoreFileSystemEndpointSuffix: "azuredatalakestore.net",
  100. azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "azuredatalakeanalytics.net",
  101. validateAuthority: true
  102. };
  103. Environment.ChinaCloud = {
  104. name: "AzureChinaCloud",
  105. portalUrl: "https://portal.azure.cn",
  106. publishingProfileUrl: "https://go.microsoft.com/fwlink/?LinkID=301774",
  107. managementEndpointUrl: "https://management.core.chinacloudapi.cn",
  108. resourceManagerEndpointUrl: "https://management.chinacloudapi.cn",
  109. sqlManagementEndpointUrl: "https://management.core.chinacloudapi.cn:8443/",
  110. sqlServerHostnameSuffix: ".database.chinacloudapi.cn",
  111. galleryEndpointUrl: "https://gallery.chinacloudapi.cn/",
  112. activeDirectoryEndpointUrl: "https://login.chinacloudapi.cn/",
  113. activeDirectoryResourceId: "https://management.core.chinacloudapi.cn/",
  114. activeDirectoryGraphResourceId: "https://graph.chinacloudapi.cn/",
  115. activeDirectoryGraphApiVersion: "2013-04-05",
  116. batchResourceId: "https://batch.chinacloudapi.cn/",
  117. storageEndpointSuffix: ".core.chinacloudapi.cn",
  118. keyVaultDnsSuffix: ".vault.azure.cn",
  119. // TODO: add dns suffixes for the china cloud for datalake store and datalake analytics once they are defined.
  120. azureDataLakeStoreFileSystemEndpointSuffix: "N/A",
  121. azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "N/A",
  122. validateAuthority: true
  123. };
  124. Environment.USGovernment = {
  125. name: "AzureUSGovernment",
  126. portalUrl: "https://portal.azure.us",
  127. publishingProfileUrl: "https://manage.windowsazure.us/publishsettings/index",
  128. managementEndpointUrl: "https://management.core.usgovcloudapi.net",
  129. resourceManagerEndpointUrl: "https://management.usgovcloudapi.net",
  130. sqlManagementEndpointUrl: "https://management.core.usgovcloudapi.net:8443/",
  131. sqlServerHostnameSuffix: ".database.usgovcloudapi.net",
  132. galleryEndpointUrl: "https://gallery.usgovcloudapi.net/",
  133. activeDirectoryEndpointUrl: "https://login.microsoftonline.us/",
  134. activeDirectoryResourceId: "https://management.core.usgovcloudapi.net/",
  135. activeDirectoryGraphResourceId: "https://graph.windows.net/",
  136. batchResourceId: "https://batch.core.usgovcloudapi.net/",
  137. activeDirectoryGraphApiVersion: "2013-04-05",
  138. storageEndpointSuffix: ".core.usgovcloudapi.net",
  139. keyVaultDnsSuffix: ".vault.usgovcloudapi.net",
  140. azureDataLakeStoreFileSystemEndpointSuffix: "N/A",
  141. azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "N/A",
  142. validateAuthority: true
  143. };
  144. Environment.GermanCloud = {
  145. name: "AzureGermanCloud",
  146. portalUrl: "https://portal.microsoftazure.de/",
  147. publishingProfileUrl: "https://manage.microsoftazure.de/publishsettings/index",
  148. managementEndpointUrl: "https://management.core.cloudapi.de",
  149. resourceManagerEndpointUrl: "https://management.microsoftazure.de",
  150. sqlManagementEndpointUrl: "https://management.core.cloudapi.de:8443/",
  151. sqlServerHostnameSuffix: ".database.cloudapi.de",
  152. galleryEndpointUrl: "https://gallery.cloudapi.de/",
  153. activeDirectoryEndpointUrl: "https://login.microsoftonline.de/",
  154. activeDirectoryResourceId: "https://management.core.cloudapi.de/",
  155. activeDirectoryGraphResourceId: "https://graph.cloudapi.de/",
  156. batchResourceId: "https://batch.microsoftazure.de/",
  157. activeDirectoryGraphApiVersion: "2013-04-05",
  158. storageEndpointSuffix: ".core.cloudapi.de",
  159. keyVaultDnsSuffix: ".vault.microsoftazure.de",
  160. azureDataLakeStoreFileSystemEndpointSuffix: "N/A",
  161. azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: "N/A",
  162. validateAuthority: true
  163. };
  164. return Environment;
  165. }());
  166. exports.Environment = Environment;
  167. Object.defineProperty(exports, '__esModule', { value: true });
  168. })));
  169. },{}],2:[function(require,module,exports){
  170. (function (process,Buffer){(function (){
  171. /** @license ms-rest-js
  172. * Copyright (c) Microsoft Corporation. All rights reserved.
  173. * Licensed under the MIT License. See License.txt and ThirdPartyNotices.txt in the project root for license information.
  174. */
  175. 'use strict';
  176. Object.defineProperty(exports, '__esModule', { value: true });
  177. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  178. var uuidv4 = _interopDefault(require('uuid/v4'));
  179. var axios = _interopDefault(require('axios'));
  180. var stream = require('stream');
  181. var FormData = _interopDefault(require('form-data'));
  182. var tough = require('tough-cookie');
  183. var tunnel = require('tunnel');
  184. var http = require('http');
  185. var https = require('https');
  186. var xml2js = require('xml2js');
  187. var os = require('os');
  188. var tslib_1 = require('tslib');
  189. // Copyright (c) Microsoft Corporation. All rights reserved.
  190. // Licensed under the MIT License. See License.txt in the project root for license information.
  191. /**
  192. * A collection of HttpHeaders that can be sent with a HTTP request.
  193. */
  194. function getHeaderKey(headerName) {
  195. return headerName.toLowerCase();
  196. }
  197. /**
  198. * A collection of HTTP header key/value pairs.
  199. */
  200. var HttpHeaders = /** @class */ (function () {
  201. function HttpHeaders(rawHeaders) {
  202. this._headersMap = {};
  203. if (rawHeaders) {
  204. for (var headerName in rawHeaders) {
  205. this.set(headerName, rawHeaders[headerName]);
  206. }
  207. }
  208. }
  209. /**
  210. * Set a header in this collection with the provided name and value. The name is
  211. * case-insensitive.
  212. * @param headerName The name of the header to set. This value is case-insensitive.
  213. * @param headerValue The value of the header to set.
  214. */
  215. HttpHeaders.prototype.set = function (headerName, headerValue) {
  216. this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() };
  217. };
  218. /**
  219. * Get the header value for the provided header name, or undefined if no header exists in this
  220. * collection with the provided name.
  221. * @param headerName The name of the header.
  222. */
  223. HttpHeaders.prototype.get = function (headerName) {
  224. var header = this._headersMap[getHeaderKey(headerName)];
  225. return !header ? undefined : header.value;
  226. };
  227. /**
  228. * Get whether or not this header collection contains a header entry for the provided header name.
  229. */
  230. HttpHeaders.prototype.contains = function (headerName) {
  231. return !!this._headersMap[getHeaderKey(headerName)];
  232. };
  233. /**
  234. * Remove the header with the provided headerName. Return whether or not the header existed and
  235. * was removed.
  236. * @param headerName The name of the header to remove.
  237. */
  238. HttpHeaders.prototype.remove = function (headerName) {
  239. var result = this.contains(headerName);
  240. delete this._headersMap[getHeaderKey(headerName)];
  241. return result;
  242. };
  243. /**
  244. * Get the headers that are contained this collection as an object.
  245. */
  246. HttpHeaders.prototype.rawHeaders = function () {
  247. var result = {};
  248. for (var headerKey in this._headersMap) {
  249. var header = this._headersMap[headerKey];
  250. result[header.name.toLowerCase()] = header.value;
  251. }
  252. return result;
  253. };
  254. /**
  255. * Get the headers that are contained in this collection as an array.
  256. */
  257. HttpHeaders.prototype.headersArray = function () {
  258. var headers = [];
  259. for (var headerKey in this._headersMap) {
  260. headers.push(this._headersMap[headerKey]);
  261. }
  262. return headers;
  263. };
  264. /**
  265. * Get the header names that are contained in this collection.
  266. */
  267. HttpHeaders.prototype.headerNames = function () {
  268. var headerNames = [];
  269. var headers = this.headersArray();
  270. for (var i = 0; i < headers.length; ++i) {
  271. headerNames.push(headers[i].name);
  272. }
  273. return headerNames;
  274. };
  275. /**
  276. * Get the header names that are contained in this collection.
  277. */
  278. HttpHeaders.prototype.headerValues = function () {
  279. var headerValues = [];
  280. var headers = this.headersArray();
  281. for (var i = 0; i < headers.length; ++i) {
  282. headerValues.push(headers[i].value);
  283. }
  284. return headerValues;
  285. };
  286. /**
  287. * Get the JSON object representation of this HTTP header collection.
  288. */
  289. HttpHeaders.prototype.toJson = function () {
  290. return this.rawHeaders();
  291. };
  292. /**
  293. * Get the string representation of this HTTP header collection.
  294. */
  295. HttpHeaders.prototype.toString = function () {
  296. return JSON.stringify(this.toJson());
  297. };
  298. /**
  299. * Create a deep clone/copy of this HttpHeaders collection.
  300. */
  301. HttpHeaders.prototype.clone = function () {
  302. return new HttpHeaders(this.rawHeaders());
  303. };
  304. return HttpHeaders;
  305. }());
  306. // Copyright (c) Microsoft Corporation. All rights reserved.
  307. // Licensed under the MIT License. See License.txt in the project root for license information.
  308. /**
  309. * Encodes a string in base64 format.
  310. * @param value the string to encode
  311. */
  312. function encodeString(value) {
  313. return Buffer.from(value).toString("base64");
  314. }
  315. /**
  316. * Encodes a byte array in base64 format.
  317. * @param value the Uint8Aray to encode
  318. */
  319. function encodeByteArray(value) {
  320. // Buffer.from accepts <ArrayBuffer> | <SharedArrayBuffer>-- the TypeScript definition is off here
  321. // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
  322. var bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer);
  323. return bufferValue.toString("base64");
  324. }
  325. /**
  326. * Decodes a base64 string into a byte array.
  327. * @param value the base64 string to decode
  328. */
  329. function decodeString(value) {
  330. return Buffer.from(value, "base64");
  331. }
  332. // Copyright (c) Microsoft Corporation. All rights reserved.
  333. // Licensed under the MIT License. See License.txt in the project root for license information.
  334. var Constants = {
  335. /**
  336. * The ms-rest version
  337. * @const
  338. * @type {string}
  339. */
  340. msRestVersion: "1.9.0",
  341. /**
  342. * Specifies HTTP.
  343. *
  344. * @const
  345. * @type {string}
  346. */
  347. HTTP: "http:",
  348. /**
  349. * Specifies HTTPS.
  350. *
  351. * @const
  352. * @type {string}
  353. */
  354. HTTPS: "https:",
  355. /**
  356. * Specifies HTTP Proxy.
  357. *
  358. * @const
  359. * @type {string}
  360. */
  361. HTTP_PROXY: "HTTP_PROXY",
  362. /**
  363. * Specifies HTTPS Proxy.
  364. *
  365. * @const
  366. * @type {string}
  367. */
  368. HTTPS_PROXY: "HTTPS_PROXY",
  369. HttpConstants: {
  370. /**
  371. * Http Verbs
  372. *
  373. * @const
  374. * @enum {string}
  375. */
  376. HttpVerbs: {
  377. PUT: "PUT",
  378. GET: "GET",
  379. DELETE: "DELETE",
  380. POST: "POST",
  381. MERGE: "MERGE",
  382. HEAD: "HEAD",
  383. PATCH: "PATCH"
  384. },
  385. StatusCodes: {
  386. TooManyRequests: 429
  387. }
  388. },
  389. /**
  390. * Defines constants for use with HTTP headers.
  391. */
  392. HeaderConstants: {
  393. /**
  394. * The Authorization header.
  395. *
  396. * @const
  397. * @type {string}
  398. */
  399. AUTHORIZATION: "authorization",
  400. AUTHORIZATION_SCHEME: "Bearer",
  401. /**
  402. * The Retry-After response-header field can be used with a 503 (Service
  403. * Unavailable) or 349 (Too Many Requests) responses to indicate how long
  404. * the service is expected to be unavailable to the requesting client.
  405. *
  406. * @const
  407. * @type {string}
  408. */
  409. RETRY_AFTER: "Retry-After",
  410. /**
  411. * The UserAgent header.
  412. *
  413. * @const
  414. * @type {string}
  415. */
  416. USER_AGENT: "User-Agent"
  417. }
  418. };
  419. // Copyright (c) Microsoft Corporation. All rights reserved.
  420. /**
  421. * A constant that indicates whether the environment is node.js or browser based.
  422. */
  423. var isNode = (typeof process !== "undefined") && !!process.version && !!process.versions && !!process.versions.node;
  424. /**
  425. * Encodes an URI.
  426. *
  427. * @param {string} uri The URI to be encoded.
  428. * @return {string} The encoded URI.
  429. */
  430. function encodeUri(uri) {
  431. return encodeURIComponent(uri)
  432. .replace(/!/g, "%21")
  433. .replace(/"/g, "%27")
  434. .replace(/\(/g, "%28")
  435. .replace(/\)/g, "%29")
  436. .replace(/\*/g, "%2A");
  437. }
  438. /**
  439. * Returns a stripped version of the Http Response which only contains body,
  440. * headers and the status.
  441. *
  442. * @param {HttpOperationResponse} response The Http Response
  443. *
  444. * @return {object} The stripped version of Http Response.
  445. */
  446. function stripResponse(response) {
  447. var strippedResponse = {};
  448. strippedResponse.body = response.bodyAsText;
  449. strippedResponse.headers = response.headers;
  450. strippedResponse.status = response.status;
  451. return strippedResponse;
  452. }
  453. /**
  454. * Returns a stripped version of the Http Request that does not contain the
  455. * Authorization header.
  456. *
  457. * @param {WebResource} request The Http Request object
  458. *
  459. * @return {WebResource} The stripped version of Http Request.
  460. */
  461. function stripRequest(request) {
  462. var strippedRequest = request.clone();
  463. if (strippedRequest.headers) {
  464. strippedRequest.headers.remove("authorization");
  465. }
  466. return strippedRequest;
  467. }
  468. /**
  469. * Validates the given uuid as a string
  470. *
  471. * @param {string} uuid The uuid as a string that needs to be validated
  472. *
  473. * @return {boolean} True if the uuid is valid; false otherwise.
  474. */
  475. function isValidUuid(uuid) {
  476. var validUuidRegex = new RegExp("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", "ig");
  477. return validUuidRegex.test(uuid);
  478. }
  479. /**
  480. * Generated UUID
  481. *
  482. * @return {string} RFC4122 v4 UUID.
  483. */
  484. function generateUuid() {
  485. return uuidv4();
  486. }
  487. /**
  488. * Executes an array of promises sequentially. Inspiration of this method is here:
  489. * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
  490. *
  491. * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
  492. *
  493. * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
  494. * If not provided then the promise chain starts with undefined.
  495. *
  496. * @return A chain of resolved or rejected promises
  497. */
  498. function executePromisesSequentially(promiseFactories, kickstart) {
  499. var result = Promise.resolve(kickstart);
  500. promiseFactories.forEach(function (promiseFactory) {
  501. result = result.then(promiseFactory);
  502. });
  503. return result;
  504. }
  505. /**
  506. * A wrapper for setTimeout that resolves a promise after t milliseconds.
  507. * @param {number} t The number of milliseconds to be delayed.
  508. * @param {T} value The value to be resolved with after a timeout of t milliseconds.
  509. * @returns {Promise<T>} Resolved promise
  510. */
  511. function delay(t, value) {
  512. return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
  513. }
  514. /**
  515. * Converts a Promise to a callback.
  516. * @param {Promise<any>} promise The Promise to be converted to a callback
  517. * @returns {Function} A function that takes the callback (cb: Function): void
  518. * @deprecated generated code should instead depend on responseToBody
  519. */
  520. function promiseToCallback(promise) {
  521. if (typeof promise.then !== "function") {
  522. throw new Error("The provided input is not a Promise.");
  523. }
  524. return function (cb) {
  525. promise.then(function (data) {
  526. cb(undefined, data);
  527. }, function (err) {
  528. cb(err);
  529. });
  530. };
  531. }
  532. /**
  533. * Converts a Promise to a service callback.
  534. * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
  535. * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
  536. */
  537. function promiseToServiceCallback(promise) {
  538. if (typeof promise.then !== "function") {
  539. throw new Error("The provided input is not a Promise.");
  540. }
  541. return function (cb) {
  542. promise.then(function (data) {
  543. process.nextTick(cb, undefined, data.parsedBody, data.request, data);
  544. }, function (err) {
  545. process.nextTick(cb, err);
  546. });
  547. };
  548. }
  549. function prepareXMLRootList(obj, elementName) {
  550. var _a;
  551. if (!Array.isArray(obj)) {
  552. obj = [obj];
  553. }
  554. return _a = {}, _a[elementName] = obj, _a;
  555. }
  556. /**
  557. * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
  558. * @param {object} targetCtor The target object on which the properties need to be applied.
  559. * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
  560. */
  561. function applyMixins(targetCtor, sourceCtors) {
  562. sourceCtors.forEach(function (sourceCtors) {
  563. Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
  564. targetCtor.prototype[name] = sourceCtors.prototype[name];
  565. });
  566. });
  567. }
  568. var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  569. /**
  570. * Indicates whether the given string is in ISO 8601 format.
  571. * @param {string} value The value to be validated for ISO 8601 duration format.
  572. * @return {boolean} `true` if valid, `false` otherwise.
  573. */
  574. function isDuration(value) {
  575. return validateISODuration.test(value);
  576. }
  577. /**
  578. * Replace all of the instances of searchValue in value with the provided replaceValue.
  579. * @param {string | undefined} value The value to search and replace in.
  580. * @param {string} searchValue The value to search for in the value argument.
  581. * @param {string} replaceValue The value to replace searchValue with in the value argument.
  582. * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
  583. */
  584. function replaceAll(value, searchValue, replaceValue) {
  585. return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
  586. }
  587. // Copyright (c) Microsoft Corporation. All rights reserved.
  588. var Serializer = /** @class */ (function () {
  589. function Serializer(modelMappers, isXML) {
  590. if (modelMappers === void 0) { modelMappers = {}; }
  591. this.modelMappers = modelMappers;
  592. this.isXML = isXML;
  593. }
  594. Serializer.prototype.validateConstraints = function (mapper, value, objectName) {
  595. var failValidation = function (constraintName, constraintValue) {
  596. throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + ".");
  597. };
  598. if (mapper.constraints && (value != undefined)) {
  599. var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems;
  600. if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) {
  601. failValidation("ExclusiveMaximum", ExclusiveMaximum);
  602. }
  603. if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) {
  604. failValidation("ExclusiveMinimum", ExclusiveMinimum);
  605. }
  606. if (InclusiveMaximum != undefined && value > InclusiveMaximum) {
  607. failValidation("InclusiveMaximum", InclusiveMaximum);
  608. }
  609. if (InclusiveMinimum != undefined && value < InclusiveMinimum) {
  610. failValidation("InclusiveMinimum", InclusiveMinimum);
  611. }
  612. if (MaxItems != undefined && value.length > MaxItems) {
  613. failValidation("MaxItems", MaxItems);
  614. }
  615. if (MaxLength != undefined && value.length > MaxLength) {
  616. failValidation("MaxLength", MaxLength);
  617. }
  618. if (MinItems != undefined && value.length < MinItems) {
  619. failValidation("MinItems", MinItems);
  620. }
  621. if (MinLength != undefined && value.length < MinLength) {
  622. failValidation("MinLength", MinLength);
  623. }
  624. if (MultipleOf != undefined && value % MultipleOf !== 0) {
  625. failValidation("MultipleOf", MultipleOf);
  626. }
  627. if (Pattern && value.match(Pattern) === null) {
  628. failValidation("Pattern", Pattern);
  629. }
  630. if (UniqueItems && value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) {
  631. failValidation("UniqueItems", UniqueItems);
  632. }
  633. }
  634. };
  635. /**
  636. * Serialize the given object based on its metadata defined in the mapper
  637. *
  638. * @param {Mapper} mapper The mapper which defines the metadata of the serializable object
  639. *
  640. * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized
  641. *
  642. * @param {string} objectName Name of the serialized object
  643. *
  644. * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object
  645. */
  646. Serializer.prototype.serialize = function (mapper, object, objectName) {
  647. var payload = {};
  648. var mapperType = mapper.type.name;
  649. if (!objectName) {
  650. objectName = mapper.serializedName;
  651. }
  652. if (mapperType.match(/^Sequence$/ig) !== null) {
  653. payload = [];
  654. }
  655. if (object == undefined && (mapper.defaultValue != undefined || mapper.isConstant)) {
  656. object = mapper.defaultValue;
  657. }
  658. // This table of allowed values should help explain
  659. // the mapper.required and mapper.nullable properties.
  660. // X means "neither undefined or null are allowed".
  661. // || required
  662. // || true | false
  663. // nullable || ==========================
  664. // true || null | undefined/null
  665. // false || X | undefined
  666. // undefined || X | undefined/null
  667. var required = mapper.required, nullable = mapper.nullable;
  668. if (required && nullable && object === undefined) {
  669. throw new Error(objectName + " cannot be undefined.");
  670. }
  671. if (required && !nullable && object == undefined) {
  672. throw new Error(objectName + " cannot be null or undefined.");
  673. }
  674. if (!required && nullable === false && object === null) {
  675. throw new Error(objectName + " cannot be null.");
  676. }
  677. if (object == undefined) {
  678. payload = object;
  679. }
  680. else {
  681. // Validate Constraints if any
  682. this.validateConstraints(mapper, object, objectName);
  683. if (mapperType.match(/^any$/ig) !== null) {
  684. payload = object;
  685. }
  686. else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) {
  687. payload = serializeBasicTypes(mapperType, objectName, object);
  688. }
  689. else if (mapperType.match(/^Enum$/ig) !== null) {
  690. var enumMapper = mapper;
  691. payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
  692. }
  693. else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) {
  694. payload = serializeDateTypes(mapperType, object, objectName);
  695. }
  696. else if (mapperType.match(/^ByteArray$/ig) !== null) {
  697. payload = serializeByteArrayType(objectName, object);
  698. }
  699. else if (mapperType.match(/^Base64Url$/ig) !== null) {
  700. payload = serializeBase64UrlType(objectName, object);
  701. }
  702. else if (mapperType.match(/^Sequence$/ig) !== null) {
  703. payload = serializeSequenceType(this, mapper, object, objectName);
  704. }
  705. else if (mapperType.match(/^Dictionary$/ig) !== null) {
  706. payload = serializeDictionaryType(this, mapper, object, objectName);
  707. }
  708. else if (mapperType.match(/^Composite$/ig) !== null) {
  709. payload = serializeCompositeType(this, mapper, object, objectName);
  710. }
  711. }
  712. return payload;
  713. };
  714. /**
  715. * Deserialize the given object based on its metadata defined in the mapper
  716. *
  717. * @param {object} mapper The mapper which defines the metadata of the serializable object
  718. *
  719. * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized
  720. *
  721. * @param {string} objectName Name of the deserialized object
  722. *
  723. * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object
  724. */
  725. Serializer.prototype.deserialize = function (mapper, responseBody, objectName) {
  726. if (responseBody == undefined) {
  727. if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
  728. // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
  729. // between the list being empty versus being missing,
  730. // so let's do the more user-friendly thing and return an empty list.
  731. responseBody = [];
  732. }
  733. return responseBody;
  734. }
  735. var payload;
  736. var mapperType = mapper.type.name;
  737. if (!objectName) {
  738. objectName = mapper.serializedName;
  739. }
  740. if (mapperType.match(/^Composite$/ig) !== null) {
  741. payload = deserializeCompositeType(this, mapper, responseBody, objectName);
  742. }
  743. else {
  744. if (this.isXML) {
  745. /**
  746. * If the mapper specifies this as a non-composite type value but the responseBody contains
  747. * both header ("$") and body ("_") properties, then just reduce the responseBody value to
  748. * the body ("_") property.
  749. */
  750. if (responseBody["$"] != undefined && responseBody["_"] != undefined) {
  751. responseBody = responseBody["_"];
  752. }
  753. }
  754. if (mapperType.match(/^Number$/ig) !== null) {
  755. payload = parseFloat(responseBody);
  756. if (isNaN(payload)) {
  757. payload = responseBody;
  758. }
  759. }
  760. else if (mapperType.match(/^Boolean$/ig) !== null) {
  761. if (responseBody === "true") {
  762. payload = true;
  763. }
  764. else if (responseBody === "false") {
  765. payload = false;
  766. }
  767. else {
  768. payload = responseBody;
  769. }
  770. }
  771. else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) {
  772. payload = responseBody;
  773. }
  774. else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) {
  775. payload = new Date(responseBody);
  776. }
  777. else if (mapperType.match(/^UnixTime$/ig) !== null) {
  778. payload = unixTimeToDate(responseBody);
  779. }
  780. else if (mapperType.match(/^ByteArray$/ig) !== null) {
  781. payload = decodeString(responseBody);
  782. }
  783. else if (mapperType.match(/^Base64Url$/ig) !== null) {
  784. payload = base64UrlToByteArray(responseBody);
  785. }
  786. else if (mapperType.match(/^Sequence$/ig) !== null) {
  787. payload = deserializeSequenceType(this, mapper, responseBody, objectName);
  788. }
  789. else if (mapperType.match(/^Dictionary$/ig) !== null) {
  790. payload = deserializeDictionaryType(this, mapper, responseBody, objectName);
  791. }
  792. }
  793. if (mapper.isConstant) {
  794. payload = mapper.defaultValue;
  795. }
  796. return payload;
  797. };
  798. return Serializer;
  799. }());
  800. function trimEnd(str, ch) {
  801. var len = str.length;
  802. while ((len - 1) >= 0 && str[len - 1] === ch) {
  803. --len;
  804. }
  805. return str.substr(0, len);
  806. }
  807. function bufferToBase64Url(buffer) {
  808. if (!buffer) {
  809. return undefined;
  810. }
  811. if (!(buffer instanceof Uint8Array)) {
  812. throw new Error("Please provide an input of type Uint8Array for converting to Base64Url.");
  813. }
  814. // Uint8Array to Base64.
  815. var str = encodeByteArray(buffer);
  816. // Base64 to Base64Url.
  817. return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
  818. }
  819. function base64UrlToByteArray(str) {
  820. if (!str) {
  821. return undefined;
  822. }
  823. if (str && typeof str.valueOf() !== "string") {
  824. throw new Error("Please provide an input of type string for converting to Uint8Array");
  825. }
  826. // Base64Url to Base64.
  827. str = str.replace(/\-/g, "+").replace(/\_/g, "/");
  828. // Base64 to Uint8Array.
  829. return decodeString(str);
  830. }
  831. function splitSerializeName(prop) {
  832. var classes = [];
  833. var partialclass = "";
  834. if (prop) {
  835. var subwords = prop.split(".");
  836. for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) {
  837. var item = subwords_1[_i];
  838. if (item.charAt(item.length - 1) === "\\") {
  839. partialclass += item.substr(0, item.length - 1) + ".";
  840. }
  841. else {
  842. partialclass += item;
  843. classes.push(partialclass);
  844. partialclass = "";
  845. }
  846. }
  847. }
  848. return classes;
  849. }
  850. function dateToUnixTime(d) {
  851. if (!d) {
  852. return undefined;
  853. }
  854. if (typeof d.valueOf() === "string") {
  855. d = new Date(d);
  856. }
  857. return Math.floor(d.getTime() / 1000);
  858. }
  859. function unixTimeToDate(n) {
  860. if (!n) {
  861. return undefined;
  862. }
  863. return new Date(n * 1000);
  864. }
  865. function serializeBasicTypes(typeName, objectName, value) {
  866. if (value !== null && value !== undefined) {
  867. if (typeName.match(/^Number$/ig) !== null) {
  868. if (typeof value !== "number") {
  869. throw new Error(objectName + " with value " + value + " must be of type number.");
  870. }
  871. }
  872. else if (typeName.match(/^String$/ig) !== null) {
  873. if (typeof value.valueOf() !== "string") {
  874. throw new Error(objectName + " with value \"" + value + "\" must be of type string.");
  875. }
  876. }
  877. else if (typeName.match(/^Uuid$/ig) !== null) {
  878. if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
  879. throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid.");
  880. }
  881. }
  882. else if (typeName.match(/^Boolean$/ig) !== null) {
  883. if (typeof value !== "boolean") {
  884. throw new Error(objectName + " with value " + value + " must be of type boolean.");
  885. }
  886. }
  887. else if (typeName.match(/^Stream$/ig) !== null) {
  888. var objectType = typeof value;
  889. if (objectType !== "string" &&
  890. objectType !== "function" &&
  891. !(value instanceof ArrayBuffer) &&
  892. !ArrayBuffer.isView(value) &&
  893. !(typeof Blob === "function" && value instanceof Blob)) {
  894. throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.");
  895. }
  896. }
  897. }
  898. return value;
  899. }
  900. function serializeEnumType(objectName, allowedValues, value) {
  901. if (!allowedValues) {
  902. throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type.");
  903. }
  904. var isPresent = allowedValues.some(function (item) {
  905. if (typeof item.valueOf() === "string") {
  906. return item.toLowerCase() === value.toLowerCase();
  907. }
  908. return item === value;
  909. });
  910. if (!isPresent) {
  911. throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + ".");
  912. }
  913. return value;
  914. }
  915. function serializeByteArrayType(objectName, value) {
  916. if (value != undefined) {
  917. if (!(value instanceof Uint8Array)) {
  918. throw new Error(objectName + " must be of type Uint8Array.");
  919. }
  920. value = encodeByteArray(value);
  921. }
  922. return value;
  923. }
  924. function serializeBase64UrlType(objectName, value) {
  925. if (value != undefined) {
  926. if (!(value instanceof Uint8Array)) {
  927. throw new Error(objectName + " must be of type Uint8Array.");
  928. }
  929. value = bufferToBase64Url(value);
  930. }
  931. return value;
  932. }
  933. function serializeDateTypes(typeName, value, objectName) {
  934. if (value != undefined) {
  935. if (typeName.match(/^Date$/ig) !== null) {
  936. if (!(value instanceof Date ||
  937. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  938. throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
  939. }
  940. value = (value instanceof Date) ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10);
  941. }
  942. else if (typeName.match(/^DateTime$/ig) !== null) {
  943. if (!(value instanceof Date ||
  944. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  945. throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
  946. }
  947. value = (value instanceof Date) ? value.toISOString() : new Date(value).toISOString();
  948. }
  949. else if (typeName.match(/^DateTimeRfc1123$/ig) !== null) {
  950. if (!(value instanceof Date ||
  951. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  952. throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format.");
  953. }
  954. value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString();
  955. }
  956. else if (typeName.match(/^UnixTime$/ig) !== null) {
  957. if (!(value instanceof Date ||
  958. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  959. throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " +
  960. "for it to be serialized in UnixTime/Epoch format.");
  961. }
  962. value = dateToUnixTime(value);
  963. }
  964. else if (typeName.match(/^TimeSpan$/ig) !== null) {
  965. if (!isDuration(value)) {
  966. throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\".");
  967. }
  968. value = value;
  969. }
  970. }
  971. return value;
  972. }
  973. function serializeSequenceType(serializer, mapper, object, objectName) {
  974. if (!Array.isArray(object)) {
  975. throw new Error(objectName + " must be of type Array.");
  976. }
  977. var elementType = mapper.type.element;
  978. if (!elementType || typeof elementType !== "object") {
  979. throw new Error("element\" metadata for an Array must be defined in the " +
  980. ("mapper and it must of type \"object\" in " + objectName + "."));
  981. }
  982. var tempArray = [];
  983. for (var i = 0; i < object.length; i++) {
  984. tempArray[i] = serializer.serialize(elementType, object[i], objectName);
  985. }
  986. return tempArray;
  987. }
  988. function serializeDictionaryType(serializer, mapper, object, objectName) {
  989. if (typeof object !== "object") {
  990. throw new Error(objectName + " must be of type object.");
  991. }
  992. var valueType = mapper.type.value;
  993. if (!valueType || typeof valueType !== "object") {
  994. throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
  995. ("mapper and it must of type \"object\" in " + objectName + "."));
  996. }
  997. var tempDictionary = {};
  998. for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {
  999. var key = _a[_i];
  1000. tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + "." + key);
  1001. }
  1002. return tempDictionary;
  1003. }
  1004. /**
  1005. * Resolves a composite mapper's modelProperties.
  1006. * @param serializer the serializer containing the entire set of mappers
  1007. * @param mapper the composite mapper to resolve
  1008. */
  1009. function resolveModelProperties(serializer, mapper, objectName) {
  1010. var modelProps = mapper.type.modelProperties;
  1011. if (!modelProps) {
  1012. var className = mapper.type.className;
  1013. if (!className) {
  1014. throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\".");
  1015. }
  1016. var modelMapper = serializer.modelMappers[className];
  1017. if (!modelMapper) {
  1018. throw new Error("mapper() cannot be null or undefined for model \"" + className + "\".");
  1019. }
  1020. modelProps = modelMapper.type.modelProperties;
  1021. if (!modelProps) {
  1022. throw new Error("modelProperties cannot be null or undefined in the " +
  1023. ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + className + "\" for object \"" + objectName + "\"."));
  1024. }
  1025. }
  1026. return modelProps;
  1027. }
  1028. function serializeCompositeType(serializer, mapper, object, objectName) {
  1029. var _a;
  1030. if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
  1031. mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
  1032. }
  1033. if (object != undefined) {
  1034. var payload = {};
  1035. var modelProps = resolveModelProperties(serializer, mapper, objectName);
  1036. for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) {
  1037. var key = _b[_i];
  1038. var propertyMapper = modelProps[key];
  1039. if (propertyMapper.readOnly) {
  1040. continue;
  1041. }
  1042. var propName = void 0;
  1043. var parentObject = payload;
  1044. if (serializer.isXML) {
  1045. if (propertyMapper.xmlIsWrapped) {
  1046. propName = propertyMapper.xmlName;
  1047. }
  1048. else {
  1049. propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
  1050. }
  1051. }
  1052. else {
  1053. var paths = splitSerializeName(propertyMapper.serializedName);
  1054. propName = paths.pop();
  1055. for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) {
  1056. var pathName = paths_1[_c];
  1057. var childObject = parentObject[pathName];
  1058. if ((childObject == undefined) && (object[key] != undefined)) {
  1059. parentObject[pathName] = {};
  1060. }
  1061. parentObject = parentObject[pathName];
  1062. }
  1063. }
  1064. if (parentObject != undefined) {
  1065. var propertyObjectName = propertyMapper.serializedName !== ""
  1066. ? objectName + "." + propertyMapper.serializedName
  1067. : objectName;
  1068. var toSerialize = object[key];
  1069. var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
  1070. if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) {
  1071. toSerialize = mapper.serializedName;
  1072. }
  1073. var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName);
  1074. if (serializedValue !== undefined && propName != undefined) {
  1075. if (propertyMapper.xmlIsAttribute) {
  1076. // $ is the key attributes are kept under in xml2js.
  1077. // This keeps things simple while preventing name collision
  1078. // with names in user documents.
  1079. parentObject.$ = parentObject.$ || {};
  1080. parentObject.$[propName] = serializedValue;
  1081. }
  1082. else if (propertyMapper.xmlIsWrapped) {
  1083. parentObject[propName] = (_a = {}, _a[propertyMapper.xmlElementName] = serializedValue, _a);
  1084. }
  1085. else {
  1086. parentObject[propName] = serializedValue;
  1087. }
  1088. }
  1089. }
  1090. }
  1091. var additionalPropertiesMapper = mapper.type.additionalProperties;
  1092. if (additionalPropertiesMapper) {
  1093. var propNames = Object.keys(modelProps);
  1094. var _loop_1 = function (clientPropName) {
  1095. var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; });
  1096. if (isAdditionalProperty) {
  1097. payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]');
  1098. }
  1099. };
  1100. for (var clientPropName in object) {
  1101. _loop_1(clientPropName);
  1102. }
  1103. }
  1104. return payload;
  1105. }
  1106. return object;
  1107. }
  1108. function isSpecialXmlProperty(propertyName) {
  1109. return ["$", "_"].includes(propertyName);
  1110. }
  1111. function deserializeCompositeType(serializer, mapper, responseBody, objectName) {
  1112. if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
  1113. mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
  1114. }
  1115. var modelProps = resolveModelProperties(serializer, mapper, objectName);
  1116. var instance = {};
  1117. var handledPropertyNames = [];
  1118. for (var _i = 0, _a = Object.keys(modelProps); _i < _a.length; _i++) {
  1119. var key = _a[_i];
  1120. var propertyMapper = modelProps[key];
  1121. var paths = splitSerializeName(modelProps[key].serializedName);
  1122. handledPropertyNames.push(paths[0]);
  1123. var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName;
  1124. var propertyObjectName = objectName;
  1125. if (serializedName !== "" && serializedName !== undefined) {
  1126. propertyObjectName = objectName + "." + serializedName;
  1127. }
  1128. var headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
  1129. if (headerCollectionPrefix) {
  1130. var dictionary = {};
  1131. for (var _b = 0, _c = Object.keys(responseBody); _b < _c.length; _b++) {
  1132. var headerKey = _c[_b];
  1133. if (headerKey.startsWith(headerCollectionPrefix)) {
  1134. dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName);
  1135. }
  1136. handledPropertyNames.push(headerKey);
  1137. }
  1138. instance[key] = dictionary;
  1139. }
  1140. else if (serializer.isXML) {
  1141. if (propertyMapper.xmlIsAttribute && responseBody.$) {
  1142. instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName);
  1143. }
  1144. else {
  1145. var propertyName = xmlElementName || xmlName || serializedName;
  1146. var unwrappedProperty = responseBody[propertyName];
  1147. if (propertyMapper.xmlIsWrapped) {
  1148. unwrappedProperty = responseBody[xmlName];
  1149. unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName];
  1150. var isEmptyWrappedList = unwrappedProperty === undefined;
  1151. if (isEmptyWrappedList) {
  1152. unwrappedProperty = [];
  1153. }
  1154. }
  1155. instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);
  1156. }
  1157. }
  1158. else {
  1159. // deserialize the property if it is present in the provided responseBody instance
  1160. var propertyInstance = void 0;
  1161. var res = responseBody;
  1162. // traversing the object step by step.
  1163. for (var _d = 0, paths_2 = paths; _d < paths_2.length; _d++) {
  1164. var item = paths_2[_d];
  1165. if (!res)
  1166. break;
  1167. res = res[item];
  1168. }
  1169. propertyInstance = res;
  1170. var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
  1171. if (polymorphicDiscriminator && propertyMapper.serializedName === polymorphicDiscriminator.serializedName && propertyInstance == undefined) {
  1172. propertyInstance = mapper.serializedName;
  1173. }
  1174. var serializedValue = void 0;
  1175. // paging
  1176. if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
  1177. propertyInstance = responseBody[key];
  1178. instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
  1179. }
  1180. else if (propertyInstance !== undefined) {
  1181. serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
  1182. instance[key] = serializedValue;
  1183. }
  1184. }
  1185. }
  1186. var additionalPropertiesMapper = mapper.type.additionalProperties;
  1187. if (additionalPropertiesMapper) {
  1188. var isAdditionalProperty = function (responsePropName) {
  1189. for (var clientPropName in modelProps) {
  1190. var paths = splitSerializeName(modelProps[clientPropName].serializedName);
  1191. if (paths[0] === responsePropName) {
  1192. return false;
  1193. }
  1194. }
  1195. return true;
  1196. };
  1197. for (var responsePropName in responseBody) {
  1198. if (isAdditionalProperty(responsePropName)) {
  1199. instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]');
  1200. }
  1201. }
  1202. }
  1203. else if (responseBody) {
  1204. for (var _e = 0, _f = Object.keys(responseBody); _e < _f.length; _e++) {
  1205. var key = _f[_e];
  1206. if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) {
  1207. instance[key] = responseBody[key];
  1208. }
  1209. }
  1210. }
  1211. return instance;
  1212. }
  1213. function deserializeDictionaryType(serializer, mapper, responseBody, objectName) {
  1214. /*jshint validthis: true */
  1215. var value = mapper.type.value;
  1216. if (!value || typeof value !== "object") {
  1217. throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
  1218. ("mapper and it must of type \"object\" in " + objectName));
  1219. }
  1220. if (responseBody) {
  1221. var tempDictionary = {};
  1222. for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) {
  1223. var key = _a[_i];
  1224. tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);
  1225. }
  1226. return tempDictionary;
  1227. }
  1228. return responseBody;
  1229. }
  1230. function deserializeSequenceType(serializer, mapper, responseBody, objectName) {
  1231. /*jshint validthis: true */
  1232. var element = mapper.type.element;
  1233. if (!element || typeof element !== "object") {
  1234. throw new Error("element\" metadata for an Array must be defined in the " +
  1235. ("mapper and it must of type \"object\" in " + objectName));
  1236. }
  1237. if (responseBody) {
  1238. if (!Array.isArray(responseBody)) {
  1239. // xml2js will interpret a single element array as just the element, so force it to be an array
  1240. responseBody = [responseBody];
  1241. }
  1242. var tempArray = [];
  1243. for (var i = 0; i < responseBody.length; i++) {
  1244. tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]");
  1245. }
  1246. return tempArray;
  1247. }
  1248. return responseBody;
  1249. }
  1250. function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
  1251. var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
  1252. if (polymorphicDiscriminator) {
  1253. var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
  1254. if (discriminatorName != undefined) {
  1255. var discriminatorValue = object[discriminatorName];
  1256. if (discriminatorValue != undefined) {
  1257. var typeName = mapper.type.uberParent || mapper.type.className;
  1258. var indexDiscriminator = discriminatorValue === typeName
  1259. ? discriminatorValue
  1260. : typeName + "." + discriminatorValue;
  1261. var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];
  1262. if (polymorphicMapper) {
  1263. mapper = polymorphicMapper;
  1264. }
  1265. }
  1266. }
  1267. }
  1268. return mapper;
  1269. }
  1270. function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
  1271. return mapper.type.polymorphicDiscriminator
  1272. || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent)
  1273. || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className);
  1274. }
  1275. function getPolymorphicDiscriminatorSafely(serializer, typeName) {
  1276. return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator);
  1277. }
  1278. // TODO: why is this here?
  1279. function serializeObject(toSerialize) {
  1280. if (toSerialize == undefined)
  1281. return undefined;
  1282. if (toSerialize instanceof Uint8Array) {
  1283. toSerialize = encodeByteArray(toSerialize);
  1284. return toSerialize;
  1285. }
  1286. else if (toSerialize instanceof Date) {
  1287. return toSerialize.toISOString();
  1288. }
  1289. else if (Array.isArray(toSerialize)) {
  1290. var array = [];
  1291. for (var i = 0; i < toSerialize.length; i++) {
  1292. array.push(serializeObject(toSerialize[i]));
  1293. }
  1294. return array;
  1295. }
  1296. else if (typeof toSerialize === "object") {
  1297. var dictionary = {};
  1298. for (var property in toSerialize) {
  1299. dictionary[property] = serializeObject(toSerialize[property]);
  1300. }
  1301. return dictionary;
  1302. }
  1303. return toSerialize;
  1304. }
  1305. /**
  1306. * Utility function to create a K:V from a list of strings
  1307. */
  1308. function strEnum(o) {
  1309. var result = {};
  1310. for (var _i = 0, o_1 = o; _i < o_1.length; _i++) {
  1311. var key = o_1[_i];
  1312. result[key] = key;
  1313. }
  1314. return result;
  1315. }
  1316. var MapperType = strEnum([
  1317. "Base64Url",
  1318. "Boolean",
  1319. "ByteArray",
  1320. "Composite",
  1321. "Date",
  1322. "DateTime",
  1323. "DateTimeRfc1123",
  1324. "Dictionary",
  1325. "Enum",
  1326. "Number",
  1327. "Object",
  1328. "Sequence",
  1329. "String",
  1330. "Stream",
  1331. "TimeSpan",
  1332. "UnixTime"
  1333. ]);
  1334. // Copyright (c) Microsoft Corporation. All rights reserved.
  1335. /**
  1336. * Creates a new WebResource object.
  1337. *
  1338. * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary
  1339. * properties to initiate a request.
  1340. *
  1341. * @constructor
  1342. */
  1343. var WebResource = /** @class */ (function () {
  1344. function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings) {
  1345. this.streamResponseBody = streamResponseBody;
  1346. this.url = url || "";
  1347. this.method = method || "GET";
  1348. this.headers = (headers instanceof HttpHeaders ? headers : new HttpHeaders(headers));
  1349. this.body = body;
  1350. this.query = query;
  1351. this.formData = undefined;
  1352. this.withCredentials = withCredentials || false;
  1353. this.abortSignal = abortSignal;
  1354. this.timeout = timeout || 0;
  1355. this.onUploadProgress = onUploadProgress;
  1356. this.onDownloadProgress = onDownloadProgress;
  1357. this.proxySettings = proxySettings;
  1358. this.keepAlive = keepAlive;
  1359. this.agentSettings = agentSettings;
  1360. }
  1361. /**
  1362. * Validates that the required properties such as method, url, headers["Content-Type"],
  1363. * headers["accept-language"] are defined. It will throw an error if one of the above
  1364. * mentioned properties are not defined.
  1365. */
  1366. WebResource.prototype.validateRequestProperties = function () {
  1367. if (!this.method) {
  1368. throw new Error("WebResource.method is required.");
  1369. }
  1370. if (!this.url) {
  1371. throw new Error("WebResource.url is required.");
  1372. }
  1373. };
  1374. /**
  1375. * Prepares the request.
  1376. * @param {RequestPrepareOptions} options Options to provide for preparing the request.
  1377. * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline.
  1378. */
  1379. WebResource.prototype.prepare = function (options) {
  1380. if (!options) {
  1381. throw new Error("options object is required");
  1382. }
  1383. if (options.method == undefined || typeof options.method.valueOf() !== "string") {
  1384. throw new Error("options.method must be a string.");
  1385. }
  1386. if (options.url && options.pathTemplate) {
  1387. throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them.");
  1388. }
  1389. if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") && (options.url == undefined || typeof options.url.valueOf() !== "string")) {
  1390. throw new Error("Please provide exactly one of options.pathTemplate or options.url.");
  1391. }
  1392. // set the url if it is provided.
  1393. if (options.url) {
  1394. if (typeof options.url !== "string") {
  1395. throw new Error("options.url must be of type \"string\".");
  1396. }
  1397. this.url = options.url;
  1398. }
  1399. // set the method
  1400. if (options.method) {
  1401. var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"];
  1402. if (validMethods.indexOf(options.method.toUpperCase()) === -1) {
  1403. throw new Error("The provided method \"" + options.method + "\" is invalid. Supported HTTP methods are: " + JSON.stringify(validMethods));
  1404. }
  1405. }
  1406. this.method = options.method.toUpperCase();
  1407. // construct the url if path template is provided
  1408. if (options.pathTemplate) {
  1409. var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters;
  1410. if (typeof pathTemplate_1 !== "string") {
  1411. throw new Error("options.pathTemplate must be of type \"string\".");
  1412. }
  1413. if (!options.baseUrl) {
  1414. options.baseUrl = "https://management.azure.com";
  1415. }
  1416. var baseUrl = options.baseUrl;
  1417. var url_1 = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1);
  1418. var segments = url_1.match(/({\w*\s*\w*})/ig);
  1419. if (segments && segments.length) {
  1420. if (!pathParameters_1) {
  1421. throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided.");
  1422. }
  1423. segments.forEach(function (item) {
  1424. var pathParamName = item.slice(1, -1);
  1425. var pathParam = pathParameters_1[pathParamName];
  1426. if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) {
  1427. throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName +
  1428. (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") +
  1429. ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") +
  1430. ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }."));
  1431. }
  1432. if (typeof pathParam.valueOf() === "string") {
  1433. url_1 = url_1.replace(item, encodeURIComponent(pathParam));
  1434. }
  1435. if (typeof pathParam.valueOf() === "object") {
  1436. if (!pathParam.value) {
  1437. throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
  1438. }
  1439. if (pathParam.skipUrlEncoding) {
  1440. url_1 = url_1.replace(item, pathParam.value);
  1441. }
  1442. else {
  1443. url_1 = url_1.replace(item, encodeURIComponent(pathParam.value));
  1444. }
  1445. }
  1446. });
  1447. }
  1448. this.url = url_1;
  1449. }
  1450. // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option.
  1451. if (options.queryParameters) {
  1452. var queryParameters = options.queryParameters;
  1453. if (typeof queryParameters !== "object") {
  1454. throw new Error("options.queryParameters must be of type object. It should be a JSON object " +
  1455. "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " +
  1456. "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }.");
  1457. }
  1458. // append question mark if it is not present in the url
  1459. if (this.url && this.url.indexOf("?") === -1) {
  1460. this.url += "?";
  1461. }
  1462. // construct queryString
  1463. var queryParams = [];
  1464. // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest().
  1465. this.query = {};
  1466. for (var queryParamName in queryParameters) {
  1467. var queryParam = queryParameters[queryParamName];
  1468. if (queryParam) {
  1469. if (typeof queryParam === "string") {
  1470. queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam));
  1471. this.query[queryParamName] = encodeURIComponent(queryParam);
  1472. }
  1473. else if (typeof queryParam === "object") {
  1474. if (!queryParam.value) {
  1475. throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
  1476. }
  1477. if (queryParam.skipUrlEncoding) {
  1478. queryParams.push(queryParamName + "=" + queryParam.value);
  1479. this.query[queryParamName] = queryParam.value;
  1480. }
  1481. else {
  1482. queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value));
  1483. this.query[queryParamName] = encodeURIComponent(queryParam.value);
  1484. }
  1485. }
  1486. }
  1487. } // end-of-for
  1488. // append the queryString
  1489. this.url += queryParams.join("&");
  1490. }
  1491. // add headers to the request if they are provided
  1492. if (options.headers) {
  1493. var headers = options.headers;
  1494. for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) {
  1495. var headerName = _a[_i];
  1496. this.headers.set(headerName, headers[headerName]);
  1497. }
  1498. }
  1499. // ensure accept-language is set correctly
  1500. if (!this.headers.get("accept-language")) {
  1501. this.headers.set("accept-language", "en-US");
  1502. }
  1503. // ensure the request-id is set correctly
  1504. if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) {
  1505. this.headers.set("x-ms-client-request-id", generateUuid());
  1506. }
  1507. // default
  1508. if (!this.headers.get("Content-Type")) {
  1509. this.headers.set("Content-Type", "application/json; charset=utf-8");
  1510. }
  1511. // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty
  1512. this.body = options.body;
  1513. if (options.body != undefined) {
  1514. // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream.
  1515. if (options.bodyIsStream) {
  1516. if (!this.headers.get("Transfer-Encoding")) {
  1517. this.headers.set("Transfer-Encoding", "chunked");
  1518. }
  1519. if (this.headers.get("Content-Type") !== "application/octet-stream") {
  1520. this.headers.set("Content-Type", "application/octet-stream");
  1521. }
  1522. }
  1523. else {
  1524. if (options.serializationMapper) {
  1525. this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody");
  1526. }
  1527. if (!options.disableJsonStringifyOnBody) {
  1528. this.body = JSON.stringify(options.body);
  1529. }
  1530. }
  1531. }
  1532. this.abortSignal = options.abortSignal;
  1533. this.onDownloadProgress = options.onDownloadProgress;
  1534. this.onUploadProgress = options.onUploadProgress;
  1535. return this;
  1536. };
  1537. /**
  1538. * Clone this WebResource HTTP request object.
  1539. * @returns {WebResource} The clone of this WebResource HTTP request object.
  1540. */
  1541. WebResource.prototype.clone = function () {
  1542. var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings);
  1543. if (this.formData) {
  1544. result.formData = this.formData;
  1545. }
  1546. if (this.operationSpec) {
  1547. result.operationSpec = this.operationSpec;
  1548. }
  1549. if (this.shouldDeserialize) {
  1550. result.shouldDeserialize = this.shouldDeserialize;
  1551. }
  1552. if (this.operationResponseGetter) {
  1553. result.operationResponseGetter = this.operationResponseGetter;
  1554. }
  1555. return result;
  1556. };
  1557. return WebResource;
  1558. }());
  1559. // Copyright (c) Microsoft Corporation. All rights reserved.
  1560. var RestError = /** @class */ (function (_super) {
  1561. tslib_1.__extends(RestError, _super);
  1562. function RestError(message, code, statusCode, request, response, body) {
  1563. var _this = _super.call(this, message) || this;
  1564. _this.code = code;
  1565. _this.statusCode = statusCode;
  1566. _this.request = request;
  1567. _this.response = response;
  1568. _this.body = body;
  1569. Object.setPrototypeOf(_this, RestError.prototype);
  1570. return _this;
  1571. }
  1572. RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
  1573. RestError.REQUEST_ABORTED_ERROR = "REQUEST_ABORTED_ERROR";
  1574. RestError.PARSE_ERROR = "PARSE_ERROR";
  1575. return RestError;
  1576. }(Error));
  1577. // Copyright (c) Microsoft Corporation. All rights reserved.
  1578. /**
  1579. * A class that handles the query portion of a URLBuilder.
  1580. */
  1581. var URLQuery = /** @class */ (function () {
  1582. function URLQuery() {
  1583. this._rawQuery = {};
  1584. }
  1585. /**
  1586. * Get whether or not there any query parameters in this URLQuery.
  1587. */
  1588. URLQuery.prototype.any = function () {
  1589. return Object.keys(this._rawQuery).length > 0;
  1590. };
  1591. /**
  1592. * Set a query parameter with the provided name and value. If the parameterValue is undefined or
  1593. * empty, then this will attempt to remove an existing query parameter with the provided
  1594. * parameterName.
  1595. */
  1596. URLQuery.prototype.set = function (parameterName, parameterValue) {
  1597. if (parameterName) {
  1598. if (parameterValue != undefined) {
  1599. var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();
  1600. this._rawQuery[parameterName] = newValue;
  1601. }
  1602. else {
  1603. delete this._rawQuery[parameterName];
  1604. }
  1605. }
  1606. };
  1607. /**
  1608. * Get the value of the query parameter with the provided name. If no parameter exists with the
  1609. * provided parameter name, then undefined will be returned.
  1610. */
  1611. URLQuery.prototype.get = function (parameterName) {
  1612. return parameterName ? this._rawQuery[parameterName] : undefined;
  1613. };
  1614. /**
  1615. * Get the string representation of this query. The return value will not start with a "?".
  1616. */
  1617. URLQuery.prototype.toString = function () {
  1618. var result = "";
  1619. for (var parameterName in this._rawQuery) {
  1620. if (result) {
  1621. result += "&";
  1622. }
  1623. var parameterValue = this._rawQuery[parameterName];
  1624. if (Array.isArray(parameterValue)) {
  1625. var parameterStrings = [];
  1626. for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {
  1627. var parameterValueElement = parameterValue_1[_i];
  1628. parameterStrings.push(parameterName + "=" + parameterValueElement);
  1629. }
  1630. result += parameterStrings.join("&");
  1631. }
  1632. else {
  1633. result += parameterName + "=" + parameterValue;
  1634. }
  1635. }
  1636. return result;
  1637. };
  1638. /**
  1639. * Parse a URLQuery from the provided text.
  1640. */
  1641. URLQuery.parse = function (text) {
  1642. var result = new URLQuery();
  1643. if (text) {
  1644. if (text.startsWith("?")) {
  1645. text = text.substring(1);
  1646. }
  1647. var currentState = "ParameterName";
  1648. var parameterName = "";
  1649. var parameterValue = "";
  1650. for (var i = 0; i < text.length; ++i) {
  1651. var currentCharacter = text[i];
  1652. switch (currentState) {
  1653. case "ParameterName":
  1654. switch (currentCharacter) {
  1655. case "=":
  1656. currentState = "ParameterValue";
  1657. break;
  1658. case "&":
  1659. parameterName = "";
  1660. parameterValue = "";
  1661. break;
  1662. default:
  1663. parameterName += currentCharacter;
  1664. break;
  1665. }
  1666. break;
  1667. case "ParameterValue":
  1668. switch (currentCharacter) {
  1669. case "=":
  1670. parameterName = "";
  1671. parameterValue = "";
  1672. currentState = "Invalid";
  1673. break;
  1674. case "&":
  1675. result.set(parameterName, parameterValue);
  1676. parameterName = "";
  1677. parameterValue = "";
  1678. currentState = "ParameterName";
  1679. break;
  1680. default:
  1681. parameterValue += currentCharacter;
  1682. break;
  1683. }
  1684. break;
  1685. case "Invalid":
  1686. if (currentCharacter === "&") {
  1687. currentState = "ParameterName";
  1688. }
  1689. break;
  1690. default:
  1691. throw new Error("Unrecognized URLQuery parse state: " + currentState);
  1692. }
  1693. }
  1694. if (currentState === "ParameterValue") {
  1695. result.set(parameterName, parameterValue);
  1696. }
  1697. }
  1698. return result;
  1699. };
  1700. return URLQuery;
  1701. }());
  1702. /**
  1703. * A class that handles creating, modifying, and parsing URLs.
  1704. */
  1705. var URLBuilder = /** @class */ (function () {
  1706. function URLBuilder() {
  1707. }
  1708. /**
  1709. * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL
  1710. * (such as a host, port, path, or query), those parts will be added to this URL as well.
  1711. */
  1712. URLBuilder.prototype.setScheme = function (scheme) {
  1713. if (!scheme) {
  1714. this._scheme = undefined;
  1715. }
  1716. else {
  1717. this.set(scheme, "SCHEME");
  1718. }
  1719. };
  1720. /**
  1721. * Get the scheme that has been set in this URL.
  1722. */
  1723. URLBuilder.prototype.getScheme = function () {
  1724. return this._scheme;
  1725. };
  1726. /**
  1727. * Set the host for this URL. If the provided host contains other parts of a URL (such as a
  1728. * port, path, or query), those parts will be added to this URL as well.
  1729. */
  1730. URLBuilder.prototype.setHost = function (host) {
  1731. if (!host) {
  1732. this._host = undefined;
  1733. }
  1734. else {
  1735. this.set(host, "SCHEME_OR_HOST");
  1736. }
  1737. };
  1738. /**
  1739. * Get the host that has been set in this URL.
  1740. */
  1741. URLBuilder.prototype.getHost = function () {
  1742. return this._host;
  1743. };
  1744. /**
  1745. * Set the port for this URL. If the provided port contains other parts of a URL (such as a
  1746. * path or query), those parts will be added to this URL as well.
  1747. */
  1748. URLBuilder.prototype.setPort = function (port) {
  1749. if (port == undefined || port === "") {
  1750. this._port = undefined;
  1751. }
  1752. else {
  1753. this.set(port.toString(), "PORT");
  1754. }
  1755. };
  1756. /**
  1757. * Get the port that has been set in this URL.
  1758. */
  1759. URLBuilder.prototype.getPort = function () {
  1760. return this._port;
  1761. };
  1762. /**
  1763. * Set the path for this URL. If the provided path contains a query, then it will be added to
  1764. * this URL as well.
  1765. */
  1766. URLBuilder.prototype.setPath = function (path) {
  1767. if (!path) {
  1768. this._path = undefined;
  1769. }
  1770. else {
  1771. if (path.indexOf("://") !== -1) {
  1772. this.set(path, "SCHEME");
  1773. }
  1774. else {
  1775. this.set(path, "PATH");
  1776. }
  1777. }
  1778. };
  1779. /**
  1780. * Append the provided path to this URL's existing path. If the provided path contains a query,
  1781. * then it will be added to this URL as well.
  1782. */
  1783. URLBuilder.prototype.appendPath = function (path) {
  1784. if (path) {
  1785. var currentPath = this.getPath();
  1786. if (currentPath) {
  1787. if (!currentPath.endsWith("/")) {
  1788. currentPath += "/";
  1789. }
  1790. if (path.startsWith("/")) {
  1791. path = path.substring(1);
  1792. }
  1793. path = currentPath + path;
  1794. }
  1795. this.set(path, "PATH");
  1796. }
  1797. };
  1798. /**
  1799. * Get the path that has been set in this URL.
  1800. */
  1801. URLBuilder.prototype.getPath = function () {
  1802. return this._path;
  1803. };
  1804. /**
  1805. * Set the query in this URL.
  1806. */
  1807. URLBuilder.prototype.setQuery = function (query) {
  1808. if (!query) {
  1809. this._query = undefined;
  1810. }
  1811. else {
  1812. this._query = URLQuery.parse(query);
  1813. }
  1814. };
  1815. /**
  1816. * Set a query parameter with the provided name and value in this URL's query. If the provided
  1817. * query parameter value is undefined or empty, then the query parameter will be removed if it
  1818. * existed.
  1819. */
  1820. URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {
  1821. if (queryParameterName) {
  1822. if (!this._query) {
  1823. this._query = new URLQuery();
  1824. }
  1825. this._query.set(queryParameterName, queryParameterValue);
  1826. }
  1827. };
  1828. /**
  1829. * Get the value of the query parameter with the provided query parameter name. If no query
  1830. * parameter exists with the provided name, then undefined will be returned.
  1831. */
  1832. URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {
  1833. return this._query ? this._query.get(queryParameterName) : undefined;
  1834. };
  1835. /**
  1836. * Get the query in this URL.
  1837. */
  1838. URLBuilder.prototype.getQuery = function () {
  1839. return this._query ? this._query.toString() : undefined;
  1840. };
  1841. /**
  1842. * Set the parts of this URL by parsing the provided text using the provided startState.
  1843. */
  1844. URLBuilder.prototype.set = function (text, startState) {
  1845. var tokenizer = new URLTokenizer(text, startState);
  1846. while (tokenizer.next()) {
  1847. var token = tokenizer.current();
  1848. if (token) {
  1849. switch (token.type) {
  1850. case "SCHEME":
  1851. this._scheme = token.text || undefined;
  1852. break;
  1853. case "HOST":
  1854. this._host = token.text || undefined;
  1855. break;
  1856. case "PORT":
  1857. this._port = token.text || undefined;
  1858. break;
  1859. case "PATH":
  1860. var tokenPath = token.text || undefined;
  1861. if (!this._path || this._path === "/" || tokenPath !== "/") {
  1862. this._path = tokenPath;
  1863. }
  1864. break;
  1865. case "QUERY":
  1866. this._query = URLQuery.parse(token.text);
  1867. break;
  1868. default:
  1869. throw new Error("Unrecognized URLTokenType: " + token.type);
  1870. }
  1871. }
  1872. }
  1873. };
  1874. URLBuilder.prototype.toString = function () {
  1875. var result = "";
  1876. if (this._scheme) {
  1877. result += this._scheme + "://";
  1878. }
  1879. if (this._host) {
  1880. result += this._host;
  1881. }
  1882. if (this._port) {
  1883. result += ":" + this._port;
  1884. }
  1885. if (this._path) {
  1886. if (!this._path.startsWith("/")) {
  1887. result += "/";
  1888. }
  1889. result += this._path;
  1890. }
  1891. if (this._query && this._query.any()) {
  1892. result += "?" + this._query.toString();
  1893. }
  1894. return result;
  1895. };
  1896. /**
  1897. * If the provided searchValue is found in this URLBuilder, then replace it with the provided
  1898. * replaceValue.
  1899. */
  1900. URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {
  1901. if (searchValue) {
  1902. this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));
  1903. this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));
  1904. this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));
  1905. this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));
  1906. this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));
  1907. }
  1908. };
  1909. URLBuilder.parse = function (text) {
  1910. var result = new URLBuilder();
  1911. result.set(text, "SCHEME_OR_HOST");
  1912. return result;
  1913. };
  1914. return URLBuilder;
  1915. }());
  1916. var URLToken = /** @class */ (function () {
  1917. function URLToken(text, type) {
  1918. this.text = text;
  1919. this.type = type;
  1920. }
  1921. URLToken.scheme = function (text) {
  1922. return new URLToken(text, "SCHEME");
  1923. };
  1924. URLToken.host = function (text) {
  1925. return new URLToken(text, "HOST");
  1926. };
  1927. URLToken.port = function (text) {
  1928. return new URLToken(text, "PORT");
  1929. };
  1930. URLToken.path = function (text) {
  1931. return new URLToken(text, "PATH");
  1932. };
  1933. URLToken.query = function (text) {
  1934. return new URLToken(text, "QUERY");
  1935. };
  1936. return URLToken;
  1937. }());
  1938. /**
  1939. * Get whether or not the provided character (single character string) is an alphanumeric (letter or
  1940. * digit) character.
  1941. */
  1942. function isAlphaNumericCharacter(character) {
  1943. var characterCode = character.charCodeAt(0);
  1944. return (48 /* '0' */ <= characterCode && characterCode <= 57 /* '9' */) ||
  1945. (65 /* 'A' */ <= characterCode && characterCode <= 90 /* 'Z' */) ||
  1946. (97 /* 'a' */ <= characterCode && characterCode <= 122 /* 'z' */);
  1947. }
  1948. /**
  1949. * A class that tokenizes URL strings.
  1950. */
  1951. var URLTokenizer = /** @class */ (function () {
  1952. function URLTokenizer(_text, state) {
  1953. this._text = _text;
  1954. this._textLength = _text ? _text.length : 0;
  1955. this._currentState = state != undefined ? state : "SCHEME_OR_HOST";
  1956. this._currentIndex = 0;
  1957. }
  1958. /**
  1959. * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer
  1960. * hasn't started or has finished tokenizing.
  1961. */
  1962. URLTokenizer.prototype.current = function () {
  1963. return this._currentToken;
  1964. };
  1965. /**
  1966. * Advance to the next URLToken and return whether or not a URLToken was found.
  1967. */
  1968. URLTokenizer.prototype.next = function () {
  1969. if (!hasCurrentCharacter(this)) {
  1970. this._currentToken = undefined;
  1971. }
  1972. else {
  1973. switch (this._currentState) {
  1974. case "SCHEME":
  1975. nextScheme(this);
  1976. break;
  1977. case "SCHEME_OR_HOST":
  1978. nextSchemeOrHost(this);
  1979. break;
  1980. case "HOST":
  1981. nextHost(this);
  1982. break;
  1983. case "PORT":
  1984. nextPort(this);
  1985. break;
  1986. case "PATH":
  1987. nextPath(this);
  1988. break;
  1989. case "QUERY":
  1990. nextQuery(this);
  1991. break;
  1992. default:
  1993. throw new Error("Unrecognized URLTokenizerState: " + this._currentState);
  1994. }
  1995. }
  1996. return !!this._currentToken;
  1997. };
  1998. return URLTokenizer;
  1999. }());
  2000. /**
  2001. * Read the remaining characters from this Tokenizer's character stream.
  2002. */
  2003. function readRemaining(tokenizer) {
  2004. var result = "";
  2005. if (tokenizer._currentIndex < tokenizer._textLength) {
  2006. result = tokenizer._text.substring(tokenizer._currentIndex);
  2007. tokenizer._currentIndex = tokenizer._textLength;
  2008. }
  2009. return result;
  2010. }
  2011. /**
  2012. * Whether or not this URLTokenizer has a current character.
  2013. */
  2014. function hasCurrentCharacter(tokenizer) {
  2015. return tokenizer._currentIndex < tokenizer._textLength;
  2016. }
  2017. /**
  2018. * Get the character in the text string at the current index.
  2019. */
  2020. function getCurrentCharacter(tokenizer) {
  2021. return tokenizer._text[tokenizer._currentIndex];
  2022. }
  2023. /**
  2024. * Advance to the character in text that is "step" characters ahead. If no step value is provided,
  2025. * then step will default to 1.
  2026. */
  2027. function nextCharacter(tokenizer, step) {
  2028. if (hasCurrentCharacter(tokenizer)) {
  2029. if (!step) {
  2030. step = 1;
  2031. }
  2032. tokenizer._currentIndex += step;
  2033. }
  2034. }
  2035. /**
  2036. * Starting with the current character, peek "charactersToPeek" number of characters ahead in this
  2037. * Tokenizer's stream of characters.
  2038. */
  2039. function peekCharacters(tokenizer, charactersToPeek) {
  2040. var endIndex = tokenizer._currentIndex + charactersToPeek;
  2041. if (tokenizer._textLength < endIndex) {
  2042. endIndex = tokenizer._textLength;
  2043. }
  2044. return tokenizer._text.substring(tokenizer._currentIndex, endIndex);
  2045. }
  2046. /**
  2047. * Read characters from this Tokenizer until the end of the stream or until the provided condition
  2048. * is false when provided the current character.
  2049. */
  2050. function readWhile(tokenizer, condition) {
  2051. var result = "";
  2052. while (hasCurrentCharacter(tokenizer)) {
  2053. var currentCharacter = getCurrentCharacter(tokenizer);
  2054. if (!condition(currentCharacter)) {
  2055. break;
  2056. }
  2057. else {
  2058. result += currentCharacter;
  2059. nextCharacter(tokenizer);
  2060. }
  2061. }
  2062. return result;
  2063. }
  2064. /**
  2065. * Read characters from this Tokenizer until a non-alphanumeric character or the end of the
  2066. * character stream is reached.
  2067. */
  2068. function readWhileLetterOrDigit(tokenizer) {
  2069. return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });
  2070. }
  2071. /**
  2072. * Read characters from this Tokenizer until one of the provided terminating characters is read or
  2073. * the end of the character stream is reached.
  2074. */
  2075. function readUntilCharacter(tokenizer) {
  2076. var terminatingCharacters = [];
  2077. for (var _i = 1; _i < arguments.length; _i++) {
  2078. terminatingCharacters[_i - 1] = arguments[_i];
  2079. }
  2080. return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });
  2081. }
  2082. function nextScheme(tokenizer) {
  2083. var scheme = readWhileLetterOrDigit(tokenizer);
  2084. tokenizer._currentToken = URLToken.scheme(scheme);
  2085. if (!hasCurrentCharacter(tokenizer)) {
  2086. tokenizer._currentState = "DONE";
  2087. }
  2088. else {
  2089. tokenizer._currentState = "HOST";
  2090. }
  2091. }
  2092. function nextSchemeOrHost(tokenizer) {
  2093. var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?");
  2094. if (!hasCurrentCharacter(tokenizer)) {
  2095. tokenizer._currentToken = URLToken.host(schemeOrHost);
  2096. tokenizer._currentState = "DONE";
  2097. }
  2098. else if (getCurrentCharacter(tokenizer) === ":") {
  2099. if (peekCharacters(tokenizer, 3) === "://") {
  2100. tokenizer._currentToken = URLToken.scheme(schemeOrHost);
  2101. tokenizer._currentState = "HOST";
  2102. }
  2103. else {
  2104. tokenizer._currentToken = URLToken.host(schemeOrHost);
  2105. tokenizer._currentState = "PORT";
  2106. }
  2107. }
  2108. else {
  2109. tokenizer._currentToken = URLToken.host(schemeOrHost);
  2110. if (getCurrentCharacter(tokenizer) === "/") {
  2111. tokenizer._currentState = "PATH";
  2112. }
  2113. else {
  2114. tokenizer._currentState = "QUERY";
  2115. }
  2116. }
  2117. }
  2118. function nextHost(tokenizer) {
  2119. if (peekCharacters(tokenizer, 3) === "://") {
  2120. nextCharacter(tokenizer, 3);
  2121. }
  2122. var host = readUntilCharacter(tokenizer, ":", "/", "?");
  2123. tokenizer._currentToken = URLToken.host(host);
  2124. if (!hasCurrentCharacter(tokenizer)) {
  2125. tokenizer._currentState = "DONE";
  2126. }
  2127. else if (getCurrentCharacter(tokenizer) === ":") {
  2128. tokenizer._currentState = "PORT";
  2129. }
  2130. else if (getCurrentCharacter(tokenizer) === "/") {
  2131. tokenizer._currentState = "PATH";
  2132. }
  2133. else {
  2134. tokenizer._currentState = "QUERY";
  2135. }
  2136. }
  2137. function nextPort(tokenizer) {
  2138. if (getCurrentCharacter(tokenizer) === ":") {
  2139. nextCharacter(tokenizer);
  2140. }
  2141. var port = readUntilCharacter(tokenizer, "/", "?");
  2142. tokenizer._currentToken = URLToken.port(port);
  2143. if (!hasCurrentCharacter(tokenizer)) {
  2144. tokenizer._currentState = "DONE";
  2145. }
  2146. else if (getCurrentCharacter(tokenizer) === "/") {
  2147. tokenizer._currentState = "PATH";
  2148. }
  2149. else {
  2150. tokenizer._currentState = "QUERY";
  2151. }
  2152. }
  2153. function nextPath(tokenizer) {
  2154. var path = readUntilCharacter(tokenizer, "?");
  2155. tokenizer._currentToken = URLToken.path(path);
  2156. if (!hasCurrentCharacter(tokenizer)) {
  2157. tokenizer._currentState = "DONE";
  2158. }
  2159. else {
  2160. tokenizer._currentState = "QUERY";
  2161. }
  2162. }
  2163. function nextQuery(tokenizer) {
  2164. if (getCurrentCharacter(tokenizer) === "?") {
  2165. nextCharacter(tokenizer);
  2166. }
  2167. var query = readRemaining(tokenizer);
  2168. tokenizer._currentToken = URLToken.query(query);
  2169. tokenizer._currentState = "DONE";
  2170. }
  2171. // Copyright (c) Microsoft Corporation. All rights reserved.
  2172. var axiosInstance = axios.create();
  2173. // This hack is still required with 0.19.0 version of axios since axios tries to merge the
  2174. // Content-Type header from it's config["<method name>"] where the method name is lower-case,
  2175. // into the request header. It could be possible that the Content-Type header is not present
  2176. // in the original request and this would create problems while creating the signature for
  2177. // storage data plane sdks.
  2178. axiosInstance.interceptors.request.use(function (config) { return (tslib_1.__assign({}, config, { method: config.method && config.method.toUpperCase() })); });
  2179. // keepalive agents are reused across instances to provide maximum socket reuse for
  2180. // outbound requests
  2181. var keepaliveAgents = {
  2182. http: new http.Agent({ keepAlive: true }),
  2183. https: new https.Agent({ keepAlive: true }),
  2184. };
  2185. /**
  2186. * A HttpClient implementation that uses axios to send HTTP requests.
  2187. */
  2188. var AxiosHttpClient = /** @class */ (function () {
  2189. function AxiosHttpClient() {
  2190. this.cookieJar = new tough.CookieJar();
  2191. }
  2192. AxiosHttpClient.prototype.sendRequest = function (httpRequest) {
  2193. return tslib_1.__awaiter(this, void 0, void 0, function () {
  2194. var formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, cookieString, abortSignal, abortListener, cancelToken, rawHeaders, httpRequestBody, axiosBody, onUploadProgress, loadedBytes_1, uploadReportStream, res, config, _b, httpAgent, httpsAgent, agent, err_1, axiosErr, headers, onDownloadProgress, responseBody, loadedBytes_2, downloadReportStream, length_1, operationResponse, setCookieHeader_1;
  2195. var _this = this;
  2196. return tslib_1.__generator(this, function (_c) {
  2197. switch (_c.label) {
  2198. case 0:
  2199. if (typeof httpRequest !== "object") {
  2200. throw new Error("httpRequest (WebResource) cannot be null or undefined and must be of type object.");
  2201. }
  2202. if (httpRequest.formData) {
  2203. formData = httpRequest.formData;
  2204. requestForm_1 = new FormData();
  2205. appendFormValue = function (key, value) {
  2206. // value function probably returns a stream so we can provide a fresh stream on each retry
  2207. if (typeof value === "function") {
  2208. value = value();
  2209. }
  2210. if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) {
  2211. requestForm_1.append(key, value.value, value.options);
  2212. }
  2213. else {
  2214. requestForm_1.append(key, value);
  2215. }
  2216. };
  2217. for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) {
  2218. formKey = _a[_i];
  2219. formValue = formData[formKey];
  2220. if (Array.isArray(formValue)) {
  2221. for (j = 0; j < formValue.length; j++) {
  2222. appendFormValue(formKey, formValue[j]);
  2223. }
  2224. }
  2225. else {
  2226. appendFormValue(formKey, formValue);
  2227. }
  2228. }
  2229. httpRequest.body = requestForm_1;
  2230. httpRequest.formData = undefined;
  2231. contentType = httpRequest.headers.get("Content-Type");
  2232. if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
  2233. if (typeof requestForm_1.getBoundary === "function") {
  2234. httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary());
  2235. }
  2236. else {
  2237. // browser will automatically apply a suitable content-type header
  2238. httpRequest.headers.remove("Content-Type");
  2239. }
  2240. }
  2241. }
  2242. if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2];
  2243. return [4 /*yield*/, new Promise(function (resolve, reject) {
  2244. _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) {
  2245. if (err) {
  2246. reject(err);
  2247. }
  2248. else {
  2249. resolve(cookie);
  2250. }
  2251. });
  2252. })];
  2253. case 1:
  2254. cookieString = _c.sent();
  2255. httpRequest.headers.set("Cookie", cookieString);
  2256. _c.label = 2;
  2257. case 2:
  2258. abortSignal = httpRequest.abortSignal;
  2259. if (abortSignal && abortSignal.aborted) {
  2260. throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);
  2261. }
  2262. cancelToken = abortSignal && new axios.CancelToken(function (canceler) {
  2263. abortListener = function () { return canceler(); };
  2264. abortSignal.addEventListener("abort", abortListener);
  2265. });
  2266. rawHeaders = httpRequest.headers.rawHeaders();
  2267. httpRequestBody = httpRequest.body;
  2268. axiosBody =
  2269. // Workaround for https://github.com/axios/axios/issues/755
  2270. // tslint:disable-next-line:no-null-keyword
  2271. typeof httpRequestBody === "undefined" ? null :
  2272. typeof httpRequestBody === "function" ? httpRequestBody() :
  2273. httpRequestBody;
  2274. onUploadProgress = httpRequest.onUploadProgress;
  2275. if (onUploadProgress && axiosBody) {
  2276. loadedBytes_1 = 0;
  2277. uploadReportStream = new stream.Transform({
  2278. transform: function (chunk, _encoding, callback) {
  2279. loadedBytes_1 += chunk.length;
  2280. onUploadProgress({ loadedBytes: loadedBytes_1 });
  2281. callback(undefined, chunk);
  2282. }
  2283. });
  2284. if (isReadableStream(axiosBody)) {
  2285. axiosBody.pipe(uploadReportStream);
  2286. }
  2287. else {
  2288. uploadReportStream.end(axiosBody);
  2289. }
  2290. axiosBody = uploadReportStream;
  2291. }
  2292. _c.label = 3;
  2293. case 3:
  2294. _c.trys.push([3, 5, 6, 7]);
  2295. config = {
  2296. method: httpRequest.method,
  2297. url: httpRequest.url,
  2298. headers: rawHeaders,
  2299. data: axiosBody,
  2300. transformResponse: function (data) { return data; },
  2301. validateStatus: function () { return true; },
  2302. // Workaround for https://github.com/axios/axios/issues/1362
  2303. maxContentLength: Infinity,
  2304. responseType: httpRequest.streamResponseBody ? "stream" : "text",
  2305. cancelToken: cancelToken,
  2306. timeout: httpRequest.timeout,
  2307. proxy: false
  2308. };
  2309. if (httpRequest.agentSettings) {
  2310. _b = httpRequest.agentSettings, httpAgent = _b.http, httpsAgent = _b.https;
  2311. if (httpsAgent) {
  2312. config.httpsAgent = httpsAgent;
  2313. }
  2314. if (httpAgent) {
  2315. config.httpAgent = httpAgent;
  2316. }
  2317. }
  2318. else if (httpRequest.proxySettings) {
  2319. agent = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers);
  2320. if (agent.isHttps) {
  2321. config.httpsAgent = agent.agent;
  2322. }
  2323. else {
  2324. config.httpAgent = agent.agent;
  2325. }
  2326. }
  2327. if (httpRequest.keepAlive === true) {
  2328. if (config.httpAgent) {
  2329. config.httpAgent.keepAlive = true;
  2330. }
  2331. else {
  2332. config.httpAgent = keepaliveAgents.http;
  2333. }
  2334. if (config.httpsAgent) {
  2335. config.httpsAgent.keepAlive = true;
  2336. }
  2337. else {
  2338. config.httpsAgent = keepaliveAgents.https;
  2339. }
  2340. }
  2341. return [4 /*yield*/, axiosInstance.request(config)];
  2342. case 4:
  2343. res = _c.sent();
  2344. return [3 /*break*/, 7];
  2345. case 5:
  2346. err_1 = _c.sent();
  2347. if (err_1 instanceof axios.Cancel) {
  2348. throw new RestError(err_1.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
  2349. }
  2350. else {
  2351. axiosErr = err_1;
  2352. throw new RestError(axiosErr.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
  2353. }
  2354. return [3 /*break*/, 7];
  2355. case 6:
  2356. if (abortSignal && abortListener) {
  2357. abortSignal.removeEventListener("abort", abortListener);
  2358. }
  2359. return [7 /*endfinally*/];
  2360. case 7:
  2361. headers = new HttpHeaders(res.headers);
  2362. onDownloadProgress = httpRequest.onDownloadProgress;
  2363. responseBody = res.data;
  2364. if (onDownloadProgress) {
  2365. if (isReadableStream(responseBody)) {
  2366. loadedBytes_2 = 0;
  2367. downloadReportStream = new stream.Transform({
  2368. transform: function (chunk, _encoding, callback) {
  2369. loadedBytes_2 += chunk.length;
  2370. onDownloadProgress({ loadedBytes: loadedBytes_2 });
  2371. callback(undefined, chunk);
  2372. }
  2373. });
  2374. responseBody.pipe(downloadReportStream);
  2375. responseBody = downloadReportStream;
  2376. }
  2377. else {
  2378. length_1 = parseInt(headers.get("Content-Length")) || responseBody.length || undefined;
  2379. if (length_1) {
  2380. // Calling callback for non-stream response for consistency with browser
  2381. onDownloadProgress({ loadedBytes: length_1 });
  2382. }
  2383. }
  2384. }
  2385. operationResponse = {
  2386. request: httpRequest,
  2387. status: res.status,
  2388. headers: headers,
  2389. readableStreamBody: httpRequest.streamResponseBody ? responseBody : undefined,
  2390. bodyAsText: httpRequest.streamResponseBody ? undefined : responseBody
  2391. };
  2392. if (!this.cookieJar) return [3 /*break*/, 9];
  2393. setCookieHeader_1 = operationResponse.headers.get("Set-Cookie");
  2394. if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 9];
  2395. return [4 /*yield*/, new Promise(function (resolve, reject) {
  2396. _this.cookieJar.setCookie(setCookieHeader_1, httpRequest.url, function (err) {
  2397. if (err) {
  2398. reject(err);
  2399. }
  2400. else {
  2401. resolve();
  2402. }
  2403. });
  2404. })];
  2405. case 8:
  2406. _c.sent();
  2407. _c.label = 9;
  2408. case 9: return [2 /*return*/, operationResponse];
  2409. }
  2410. });
  2411. });
  2412. };
  2413. return AxiosHttpClient;
  2414. }());
  2415. function isReadableStream(body) {
  2416. return typeof body.pipe === "function";
  2417. }
  2418. function createProxyAgent(requestUrl, proxySettings, headers) {
  2419. var tunnelOptions = {
  2420. proxy: {
  2421. host: URLBuilder.parse(proxySettings.host).getHost(),
  2422. port: proxySettings.port,
  2423. headers: (headers && headers.rawHeaders()) || {}
  2424. }
  2425. };
  2426. if ((proxySettings.username && proxySettings.password)) {
  2427. tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password;
  2428. }
  2429. var requestScheme = URLBuilder.parse(requestUrl).getScheme() || "";
  2430. var isRequestHttps = requestScheme.toLowerCase() === "https";
  2431. var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || "";
  2432. var isProxyHttps = proxyScheme.toLowerCase() === "https";
  2433. var proxyAgent = {
  2434. isHttps: isRequestHttps,
  2435. agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions)
  2436. };
  2437. return proxyAgent;
  2438. }
  2439. function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) {
  2440. if (isRequestHttps && isProxyHttps) {
  2441. return tunnel.httpsOverHttps(tunnelOptions);
  2442. }
  2443. else if (isRequestHttps && !isProxyHttps) {
  2444. return tunnel.httpsOverHttp(tunnelOptions);
  2445. }
  2446. else if (!isRequestHttps && isProxyHttps) {
  2447. return tunnel.httpOverHttps(tunnelOptions);
  2448. }
  2449. else {
  2450. return tunnel.httpOverHttp(tunnelOptions);
  2451. }
  2452. }
  2453. // Copyright (c) Microsoft Corporation. All rights reserved.
  2454. // Copyright (c) Microsoft Corporation. All rights reserved.
  2455. (function (HttpPipelineLogLevel) {
  2456. /**
  2457. * A log level that indicates that no logs will be logged.
  2458. */
  2459. HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
  2460. /**
  2461. * An error log.
  2462. */
  2463. HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
  2464. /**
  2465. * A warning log.
  2466. */
  2467. HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
  2468. /**
  2469. * An information log.
  2470. */
  2471. HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
  2472. })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {}));
  2473. // Copyright (c) Microsoft Corporation. All rights reserved.
  2474. // Licensed under the MIT License. See License.txt in the project root for license information.
  2475. /**
  2476. * Get the path to this parameter's value as a dotted string (a.b.c).
  2477. * @param parameter The parameter to get the path string for.
  2478. * @returns The path to this parameter's value as a dotted string.
  2479. */
  2480. function getPathStringFromParameter(parameter) {
  2481. return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);
  2482. }
  2483. function getPathStringFromParameterPath(parameterPath, mapper) {
  2484. var result;
  2485. if (typeof parameterPath === "string") {
  2486. result = parameterPath;
  2487. }
  2488. else if (Array.isArray(parameterPath)) {
  2489. result = parameterPath.join(".");
  2490. }
  2491. else {
  2492. result = mapper.serializedName;
  2493. }
  2494. return result;
  2495. }
  2496. // Copyright (c) Microsoft Corporation. All rights reserved.
  2497. function isStreamOperation(operationSpec) {
  2498. var result = false;
  2499. for (var statusCode in operationSpec.responses) {
  2500. var operationResponse = operationSpec.responses[statusCode];
  2501. if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) {
  2502. result = true;
  2503. break;
  2504. }
  2505. }
  2506. return result;
  2507. }
  2508. // Copyright (c) Microsoft Corporation. All rights reserved.
  2509. function stringifyXML(obj, opts) {
  2510. var builder = new xml2js.Builder({
  2511. explicitArray: false,
  2512. explicitCharkey: false,
  2513. rootName: (opts || {}).rootName,
  2514. renderOpts: {
  2515. pretty: false
  2516. }
  2517. });
  2518. return builder.buildObject(obj);
  2519. }
  2520. function parseXML(str) {
  2521. var xmlParser = new xml2js.Parser({
  2522. explicitArray: false,
  2523. explicitCharkey: false,
  2524. explicitRoot: false
  2525. });
  2526. return new Promise(function (resolve, reject) {
  2527. if (!str) {
  2528. reject(new Error("Document is empty"));
  2529. }
  2530. else {
  2531. xmlParser.parseString(str, function (err, res) {
  2532. if (err) {
  2533. reject(err);
  2534. }
  2535. else {
  2536. resolve(res);
  2537. }
  2538. });
  2539. }
  2540. });
  2541. }
  2542. // Copyright (c) Microsoft Corporation. All rights reserved.
  2543. var BaseRequestPolicy = /** @class */ (function () {
  2544. function BaseRequestPolicy(_nextPolicy, _options) {
  2545. this._nextPolicy = _nextPolicy;
  2546. this._options = _options;
  2547. }
  2548. /**
  2549. * Get whether or not a log with the provided log level should be logged.
  2550. * @param logLevel The log level of the log that will be logged.
  2551. * @returns Whether or not a log with the provided log level should be logged.
  2552. */
  2553. BaseRequestPolicy.prototype.shouldLog = function (logLevel) {
  2554. return this._options.shouldLog(logLevel);
  2555. };
  2556. /**
  2557. * Attempt to log the provided message to the provided logger. If no logger was provided or if
  2558. * the log level does not meat the logger's threshold, then nothing will be logged.
  2559. * @param logLevel The log level of this log.
  2560. * @param message The message of this log.
  2561. */
  2562. BaseRequestPolicy.prototype.log = function (logLevel, message) {
  2563. this._options.log(logLevel, message);
  2564. };
  2565. return BaseRequestPolicy;
  2566. }());
  2567. /**
  2568. * Optional properties that can be used when creating a RequestPolicy.
  2569. */
  2570. var RequestPolicyOptions = /** @class */ (function () {
  2571. function RequestPolicyOptions(_logger) {
  2572. this._logger = _logger;
  2573. }
  2574. /**
  2575. * Get whether or not a log with the provided log level should be logged.
  2576. * @param logLevel The log level of the log that will be logged.
  2577. * @returns Whether or not a log with the provided log level should be logged.
  2578. */
  2579. RequestPolicyOptions.prototype.shouldLog = function (logLevel) {
  2580. return !!this._logger &&
  2581. logLevel !== exports.HttpPipelineLogLevel.OFF &&
  2582. logLevel <= this._logger.minimumLogLevel;
  2583. };
  2584. /**
  2585. * Attempt to log the provided message to the provided logger. If no logger was provided or if
  2586. * the log level does not meat the logger's threshold, then nothing will be logged.
  2587. * @param logLevel The log level of this log.
  2588. * @param message The message of this log.
  2589. */
  2590. RequestPolicyOptions.prototype.log = function (logLevel, message) {
  2591. if (this._logger && this.shouldLog(logLevel)) {
  2592. this._logger.log(logLevel, message);
  2593. }
  2594. };
  2595. return RequestPolicyOptions;
  2596. }());
  2597. // Copyright (c) Microsoft Corporation. All rights reserved.
  2598. /**
  2599. * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they
  2600. * pass through the HTTP pipeline.
  2601. */
  2602. function deserializationPolicy(deserializationContentTypes) {
  2603. return {
  2604. create: function (nextPolicy, options) {
  2605. return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);
  2606. }
  2607. };
  2608. }
  2609. var defaultJsonContentTypes = ["application/json", "text/json"];
  2610. var defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
  2611. /**
  2612. * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the
  2613. * HTTP pipeline.
  2614. */
  2615. var DeserializationPolicy = /** @class */ (function (_super) {
  2616. tslib_1.__extends(DeserializationPolicy, _super);
  2617. function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {
  2618. var _this = _super.call(this, nextPolicy, options) || this;
  2619. _this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes;
  2620. _this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes;
  2621. return _this;
  2622. }
  2623. DeserializationPolicy.prototype.sendRequest = function (request) {
  2624. return tslib_1.__awaiter(this, void 0, void 0, function () {
  2625. var _this = this;
  2626. return tslib_1.__generator(this, function (_a) {
  2627. return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })];
  2628. });
  2629. });
  2630. };
  2631. return DeserializationPolicy;
  2632. }(BaseRequestPolicy));
  2633. function getOperationResponse(parsedResponse) {
  2634. var result;
  2635. var request = parsedResponse.request;
  2636. var operationSpec = request.operationSpec;
  2637. if (operationSpec) {
  2638. var operationResponseGetter = request.operationResponseGetter;
  2639. if (!operationResponseGetter) {
  2640. result = operationSpec.responses[parsedResponse.status];
  2641. }
  2642. else {
  2643. result = operationResponseGetter(operationSpec, parsedResponse);
  2644. }
  2645. }
  2646. return result;
  2647. }
  2648. function shouldDeserializeResponse(parsedResponse) {
  2649. var shouldDeserialize = parsedResponse.request.shouldDeserialize;
  2650. var result;
  2651. if (shouldDeserialize === undefined) {
  2652. result = true;
  2653. }
  2654. else if (typeof shouldDeserialize === "boolean") {
  2655. result = shouldDeserialize;
  2656. }
  2657. else {
  2658. result = shouldDeserialize(parsedResponse);
  2659. }
  2660. return result;
  2661. }
  2662. function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {
  2663. return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {
  2664. var shouldDeserialize = shouldDeserializeResponse(parsedResponse);
  2665. if (shouldDeserialize) {
  2666. var operationSpec = parsedResponse.request.operationSpec;
  2667. if (operationSpec && operationSpec.responses) {
  2668. var statusCode = parsedResponse.status;
  2669. var expectedStatusCodes = Object.keys(operationSpec.responses);
  2670. var hasNoExpectedStatusCodes = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
  2671. var responseSpec = getOperationResponse(parsedResponse);
  2672. var isExpectedStatusCode = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec;
  2673. if (!isExpectedStatusCode) {
  2674. var defaultResponseSpec = operationSpec.responses.default;
  2675. if (defaultResponseSpec) {
  2676. var initialErrorMessage = isStreamOperation(operationSpec)
  2677. ? "Unexpected status code: " + statusCode
  2678. : parsedResponse.bodyAsText;
  2679. var error = new RestError(initialErrorMessage);
  2680. error.statusCode = statusCode;
  2681. error.request = stripRequest(parsedResponse.request);
  2682. error.response = stripResponse(parsedResponse);
  2683. var parsedErrorResponse = parsedResponse.parsedBody;
  2684. try {
  2685. if (parsedErrorResponse) {
  2686. var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;
  2687. if (defaultResponseBodyMapper && defaultResponseBodyMapper.serializedName === "CloudError") {
  2688. if (parsedErrorResponse.error) {
  2689. parsedErrorResponse = parsedErrorResponse.error;
  2690. }
  2691. if (parsedErrorResponse.code) {
  2692. error.code = parsedErrorResponse.code;
  2693. }
  2694. if (parsedErrorResponse.message) {
  2695. error.message = parsedErrorResponse.message;
  2696. }
  2697. }
  2698. else {
  2699. var internalError = parsedErrorResponse;
  2700. if (parsedErrorResponse.error) {
  2701. internalError = parsedErrorResponse.error;
  2702. }
  2703. error.code = internalError.code;
  2704. if (internalError.message) {
  2705. error.message = internalError.message;
  2706. }
  2707. }
  2708. if (defaultResponseBodyMapper) {
  2709. var valueToDeserialize = parsedErrorResponse;
  2710. if (operationSpec.isXML && defaultResponseBodyMapper.type.name === MapperType.Sequence) {
  2711. valueToDeserialize = typeof parsedErrorResponse === "object"
  2712. ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]
  2713. : [];
  2714. }
  2715. error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body");
  2716. }
  2717. }
  2718. }
  2719. catch (defaultError) {
  2720. error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response.";
  2721. }
  2722. return Promise.reject(error);
  2723. }
  2724. }
  2725. else if (responseSpec) {
  2726. if (responseSpec.bodyMapper) {
  2727. var valueToDeserialize = parsedResponse.parsedBody;
  2728. if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {
  2729. valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : [];
  2730. }
  2731. try {
  2732. parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody");
  2733. }
  2734. catch (error) {
  2735. var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText);
  2736. restError.request = stripRequest(parsedResponse.request);
  2737. restError.response = stripResponse(parsedResponse);
  2738. return Promise.reject(restError);
  2739. }
  2740. }
  2741. else if (operationSpec.httpMethod === "HEAD") {
  2742. // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
  2743. parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
  2744. }
  2745. if (responseSpec.headersMapper) {
  2746. parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
  2747. }
  2748. }
  2749. }
  2750. }
  2751. return Promise.resolve(parsedResponse);
  2752. });
  2753. }
  2754. function parse(jsonContentTypes, xmlContentTypes, operationResponse) {
  2755. var errorHandler = function (err) {
  2756. var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + ".";
  2757. var errCode = err.code || RestError.PARSE_ERROR;
  2758. var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);
  2759. return Promise.reject(e);
  2760. };
  2761. if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {
  2762. var text_1 = operationResponse.bodyAsText;
  2763. var contentType = operationResponse.headers.get("Content-Type") || "";
  2764. var contentComponents = !contentType ? [] : contentType.split(";").map(function (component) { return component.toLowerCase(); });
  2765. if (contentComponents.length === 0 || contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {
  2766. return new Promise(function (resolve) {
  2767. operationResponse.parsedBody = JSON.parse(text_1);
  2768. resolve(operationResponse);
  2769. }).catch(errorHandler);
  2770. }
  2771. else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {
  2772. return parseXML(text_1)
  2773. .then(function (body) {
  2774. operationResponse.parsedBody = body;
  2775. return operationResponse;
  2776. })
  2777. .catch(errorHandler);
  2778. }
  2779. }
  2780. return Promise.resolve(operationResponse);
  2781. }
  2782. // Copyright (c) Microsoft Corporation. All rights reserved.
  2783. function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  2784. return {
  2785. create: function (nextPolicy, options) {
  2786. return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
  2787. }
  2788. };
  2789. }
  2790. var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
  2791. var DEFAULT_CLIENT_RETRY_COUNT = 3;
  2792. var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
  2793. var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
  2794. /**
  2795. * @class
  2796. * Instantiates a new "ExponentialRetryPolicyFilter" instance.
  2797. */
  2798. var ExponentialRetryPolicy = /** @class */ (function (_super) {
  2799. tslib_1.__extends(ExponentialRetryPolicy, _super);
  2800. /**
  2801. * @constructor
  2802. * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.
  2803. * @param {RequestPolicyOptions} options The options for this RequestPolicy.
  2804. * @param {number} [retryCount] The client retry count.
  2805. * @param {number} [retryInterval] The client retry interval, in milliseconds.
  2806. * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.
  2807. * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.
  2808. */
  2809. function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  2810. var _this = _super.call(this, nextPolicy, options) || this;
  2811. function isNumber(n) { return typeof n === "number"; }
  2812. _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;
  2813. _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;
  2814. _this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
  2815. _this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
  2816. return _this;
  2817. }
  2818. ExponentialRetryPolicy.prototype.sendRequest = function (request) {
  2819. var _this = this;
  2820. return this._nextPolicy.sendRequest(request.clone())
  2821. .then(function (response) { return retry(_this, request, response); })
  2822. .catch(function (error) { return retry(_this, request, error.response, undefined, error); });
  2823. };
  2824. return ExponentialRetryPolicy;
  2825. }(BaseRequestPolicy));
  2826. /**
  2827. * Determines if the operation should be retried and how long to wait until the next retry.
  2828. *
  2829. * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
  2830. * @param {number} statusCode The HTTP status code.
  2831. * @param {RetryData} retryData The retry data.
  2832. * @return {boolean} True if the operation qualifies for a retry; false otherwise.
  2833. */
  2834. function shouldRetry(policy, statusCode, retryData) {
  2835. if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) {
  2836. return false;
  2837. }
  2838. var currentCount;
  2839. if (!retryData) {
  2840. throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null.");
  2841. }
  2842. else {
  2843. currentCount = (retryData && retryData.retryCount);
  2844. }
  2845. return (currentCount < policy.retryCount);
  2846. }
  2847. /**
  2848. * Updates the retry data for the next attempt.
  2849. *
  2850. * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
  2851. * @param {RetryData} retryData The retry data.
  2852. * @param {RetryError} [err] The operation"s error, if any.
  2853. */
  2854. function updateRetryData(policy, retryData, err) {
  2855. if (!retryData) {
  2856. retryData = {
  2857. retryCount: 0,
  2858. retryInterval: 0
  2859. };
  2860. }
  2861. if (err) {
  2862. if (retryData.error) {
  2863. err.innerError = retryData.error;
  2864. }
  2865. retryData.error = err;
  2866. }
  2867. // Adjust retry count
  2868. retryData.retryCount++;
  2869. // Adjust retry interval
  2870. var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
  2871. var boundedRandDelta = policy.retryInterval * 0.8 +
  2872. Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
  2873. incrementDelta *= boundedRandDelta;
  2874. retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
  2875. return retryData;
  2876. }
  2877. function retry(policy, request, response, retryData, requestError) {
  2878. retryData = updateRetryData(policy, retryData, requestError);
  2879. var isAborted = request.abortSignal && request.abortSignal.aborted;
  2880. if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {
  2881. return delay(retryData.retryInterval)
  2882. .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
  2883. .then(function (res) { return retry(policy, request, res, retryData, undefined); })
  2884. .catch(function (err) { return retry(policy, request, response, retryData, err); });
  2885. }
  2886. else if (isAborted || requestError || !response) {
  2887. // If the operation failed in the end, return all errors instead of just the last one
  2888. var err = retryData.error ||
  2889. new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);
  2890. return Promise.reject(err);
  2891. }
  2892. else {
  2893. return Promise.resolve(response);
  2894. }
  2895. }
  2896. // Copyright (c) Microsoft Corporation. All rights reserved.
  2897. function generateClientRequestIdPolicy(requestIdHeaderName) {
  2898. if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; }
  2899. return {
  2900. create: function (nextPolicy, options) {
  2901. return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);
  2902. }
  2903. };
  2904. }
  2905. var GenerateClientRequestIdPolicy = /** @class */ (function (_super) {
  2906. tslib_1.__extends(GenerateClientRequestIdPolicy, _super);
  2907. function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {
  2908. var _this = _super.call(this, nextPolicy, options) || this;
  2909. _this._requestIdHeaderName = _requestIdHeaderName;
  2910. return _this;
  2911. }
  2912. GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {
  2913. if (!request.headers.contains(this._requestIdHeaderName)) {
  2914. request.headers.set(this._requestIdHeaderName, generateUuid());
  2915. }
  2916. return this._nextPolicy.sendRequest(request);
  2917. };
  2918. return GenerateClientRequestIdPolicy;
  2919. }(BaseRequestPolicy));
  2920. // Copyright (c) Microsoft Corporation. All rights reserved.
  2921. function getDefaultUserAgentKey() {
  2922. return Constants.HeaderConstants.USER_AGENT;
  2923. }
  2924. function getPlatformSpecificData() {
  2925. var runtimeInfo = {
  2926. key: "Node",
  2927. value: process.version
  2928. };
  2929. var osInfo = {
  2930. key: "OS",
  2931. value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")"
  2932. };
  2933. return [runtimeInfo, osInfo];
  2934. }
  2935. // Copyright (c) Microsoft Corporation. All rights reserved.
  2936. function getRuntimeInfo() {
  2937. var msRestRuntime = {
  2938. key: "ms-rest-js",
  2939. value: Constants.msRestVersion
  2940. };
  2941. return [msRestRuntime];
  2942. }
  2943. function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {
  2944. if (keySeparator === void 0) { keySeparator = " "; }
  2945. if (valueSeparator === void 0) { valueSeparator = "/"; }
  2946. return telemetryInfo.map(function (info) {
  2947. var value = info.value ? "" + valueSeparator + info.value : "";
  2948. return "" + info.key + value;
  2949. }).join(keySeparator);
  2950. }
  2951. var getDefaultUserAgentHeaderName = getDefaultUserAgentKey;
  2952. function getDefaultUserAgentValue() {
  2953. var runtimeInfo = getRuntimeInfo();
  2954. var platformSpecificData = getPlatformSpecificData();
  2955. var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));
  2956. return userAgent;
  2957. }
  2958. function userAgentPolicy(userAgentData) {
  2959. var key = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key;
  2960. var value = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value;
  2961. return {
  2962. create: function (nextPolicy, options) {
  2963. return new UserAgentPolicy(nextPolicy, options, key, value);
  2964. }
  2965. };
  2966. }
  2967. var UserAgentPolicy = /** @class */ (function (_super) {
  2968. tslib_1.__extends(UserAgentPolicy, _super);
  2969. function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {
  2970. var _this = _super.call(this, _nextPolicy, _options) || this;
  2971. _this._nextPolicy = _nextPolicy;
  2972. _this._options = _options;
  2973. _this.headerKey = headerKey;
  2974. _this.headerValue = headerValue;
  2975. return _this;
  2976. }
  2977. UserAgentPolicy.prototype.sendRequest = function (request) {
  2978. this.addUserAgentHeader(request);
  2979. return this._nextPolicy.sendRequest(request);
  2980. };
  2981. UserAgentPolicy.prototype.addUserAgentHeader = function (request) {
  2982. if (!request.headers) {
  2983. request.headers = new HttpHeaders();
  2984. }
  2985. if (!request.headers.get(this.headerKey) && this.headerValue) {
  2986. request.headers.set(this.headerKey, this.headerValue);
  2987. }
  2988. };
  2989. return UserAgentPolicy;
  2990. }(BaseRequestPolicy));
  2991. // Copyright (c) Microsoft Corporation. All rights reserved.
  2992. function redirectPolicy(maximumRetries) {
  2993. if (maximumRetries === void 0) { maximumRetries = 20; }
  2994. return {
  2995. create: function (nextPolicy, options) {
  2996. return new RedirectPolicy(nextPolicy, options, maximumRetries);
  2997. }
  2998. };
  2999. }
  3000. var RedirectPolicy = /** @class */ (function (_super) {
  3001. tslib_1.__extends(RedirectPolicy, _super);
  3002. function RedirectPolicy(nextPolicy, options, maxRetries) {
  3003. if (maxRetries === void 0) { maxRetries = 20; }
  3004. var _this = _super.call(this, nextPolicy, options) || this;
  3005. _this.maxRetries = maxRetries;
  3006. return _this;
  3007. }
  3008. RedirectPolicy.prototype.sendRequest = function (request) {
  3009. var _this = this;
  3010. return this._nextPolicy.sendRequest(request).then(function (response) { return handleRedirect(_this, response, 0); });
  3011. };
  3012. return RedirectPolicy;
  3013. }(BaseRequestPolicy));
  3014. function handleRedirect(policy, response, currentRetries) {
  3015. var request = response.request, status = response.status;
  3016. var locationHeader = response.headers.get("location");
  3017. if (locationHeader &&
  3018. (status === 300 || status === 307 || (status === 303 && request.method === "POST")) &&
  3019. (!policy.maxRetries || currentRetries < policy.maxRetries)) {
  3020. var builder = URLBuilder.parse(request.url);
  3021. builder.setPath(locationHeader);
  3022. request.url = builder.toString();
  3023. // POST request with Status code 303 should be converted into a
  3024. // redirected GET request if the redirect url is present in the location header
  3025. if (status === 303) {
  3026. request.method = "GET";
  3027. }
  3028. return policy._nextPolicy.sendRequest(request)
  3029. .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); });
  3030. }
  3031. return Promise.resolve(response);
  3032. }
  3033. function rpRegistrationPolicy(retryTimeout) {
  3034. if (retryTimeout === void 0) { retryTimeout = 30; }
  3035. return {
  3036. create: function (nextPolicy, options) {
  3037. return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);
  3038. }
  3039. };
  3040. }
  3041. var RPRegistrationPolicy = /** @class */ (function (_super) {
  3042. tslib_1.__extends(RPRegistrationPolicy, _super);
  3043. function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {
  3044. if (_retryTimeout === void 0) { _retryTimeout = 30; }
  3045. var _this = _super.call(this, nextPolicy, options) || this;
  3046. _this._retryTimeout = _retryTimeout;
  3047. return _this;
  3048. }
  3049. RPRegistrationPolicy.prototype.sendRequest = function (request) {
  3050. var _this = this;
  3051. return this._nextPolicy.sendRequest(request.clone())
  3052. .then(function (response) { return registerIfNeeded(_this, request, response); });
  3053. };
  3054. return RPRegistrationPolicy;
  3055. }(BaseRequestPolicy));
  3056. function registerIfNeeded(policy, request, response) {
  3057. if (response.status === 409) {
  3058. var rpName = checkRPNotRegisteredError(response.bodyAsText);
  3059. if (rpName) {
  3060. var urlPrefix = extractSubscriptionUrl(request.url);
  3061. return registerRP(policy, urlPrefix, rpName, request)
  3062. // Autoregistration of ${provider} failed for some reason. We will not return this error
  3063. // instead will return the initial response with 409 status code back to the user.
  3064. // do nothing here as we are returning the original response at the end of this method.
  3065. .catch(function () { return false; })
  3066. .then(function (registrationStatus) {
  3067. if (registrationStatus) {
  3068. // Retry the original request. We have to change the x-ms-client-request-id
  3069. // otherwise Azure endpoint will return the initial 409 (cached) response.
  3070. request.headers.set("x-ms-client-request-id", generateUuid());
  3071. return policy._nextPolicy.sendRequest(request.clone());
  3072. }
  3073. return response;
  3074. });
  3075. }
  3076. }
  3077. return Promise.resolve(response);
  3078. }
  3079. /**
  3080. * Reuses the headers of the original request and url (if specified).
  3081. * @param {WebResource} originalRequest The original request
  3082. * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.
  3083. * @returns {object} A new request object with desired headers.
  3084. */
  3085. function getRequestEssentials(originalRequest, reuseUrlToo) {
  3086. if (reuseUrlToo === void 0) { reuseUrlToo = false; }
  3087. var reqOptions = originalRequest.clone();
  3088. if (reuseUrlToo) {
  3089. reqOptions.url = originalRequest.url;
  3090. }
  3091. // We have to change the x-ms-client-request-id otherwise Azure endpoint
  3092. // will return the initial 409 (cached) response.
  3093. reqOptions.headers.set("x-ms-client-request-id", generateUuid());
  3094. // Set content-type to application/json
  3095. reqOptions.headers.set("Content-Type", "application/json; charset=utf-8");
  3096. return reqOptions;
  3097. }
  3098. /**
  3099. * Validates the error code and message associated with 409 response status code. If it matches to that of
  3100. * RP not registered then it returns the name of the RP else returns undefined.
  3101. * @param {string} body The response body received after making the original request.
  3102. * @returns {string} The name of the RP if condition is satisfied else undefined.
  3103. */
  3104. function checkRPNotRegisteredError(body) {
  3105. var result, responseBody;
  3106. if (body) {
  3107. try {
  3108. responseBody = JSON.parse(body);
  3109. }
  3110. catch (err) {
  3111. // do nothing;
  3112. }
  3113. if (responseBody && responseBody.error && responseBody.error.message &&
  3114. responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") {
  3115. var matchRes = responseBody.error.message.match(/.*'(.*)'/i);
  3116. if (matchRes) {
  3117. result = matchRes.pop();
  3118. }
  3119. }
  3120. }
  3121. return result;
  3122. }
  3123. /**
  3124. * Extracts the first part of the URL, just after subscription:
  3125. * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
  3126. * @param {string} url The original request url
  3127. * @returns {string} The url prefix as explained above.
  3128. */
  3129. function extractSubscriptionUrl(url) {
  3130. var result;
  3131. var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//ig);
  3132. if (matchRes && matchRes[0]) {
  3133. result = matchRes[0];
  3134. }
  3135. else {
  3136. throw new Error("Unable to extract subscriptionId from the given url - " + url + ".");
  3137. }
  3138. return result;
  3139. }
  3140. /**
  3141. * Registers the given provider.
  3142. * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
  3143. * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
  3144. * @param {string} provider The provider name to be registered.
  3145. * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response
  3146. * with a message that the provider is not registered.
  3147. * @param {registrationCallback} callback The callback that handles the RP registration
  3148. */
  3149. function registerRP(policy, urlPrefix, provider, originalRequest) {
  3150. var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01";
  3151. var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01";
  3152. var reqOptions = getRequestEssentials(originalRequest);
  3153. reqOptions.method = "POST";
  3154. reqOptions.url = postUrl;
  3155. return policy._nextPolicy.sendRequest(reqOptions)
  3156. .then(function (response) {
  3157. if (response.status !== 200) {
  3158. throw new Error("Autoregistration of " + provider + " failed. Please try registering manually.");
  3159. }
  3160. return getRegistrationStatus(policy, getUrl, originalRequest);
  3161. });
  3162. }
  3163. /**
  3164. * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.
  3165. * Polling will happen till the registrationState property of the response body is "Registered".
  3166. * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
  3167. * @param {string} url The request url for polling
  3168. * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response
  3169. * with a message that the provider is not registered.
  3170. * @returns {Promise<boolean>} True if RP Registration is successful.
  3171. */
  3172. function getRegistrationStatus(policy, url, originalRequest) {
  3173. var reqOptions = getRequestEssentials(originalRequest);
  3174. reqOptions.url = url;
  3175. reqOptions.method = "GET";
  3176. return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {
  3177. var obj = res.parsedBody;
  3178. if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") {
  3179. return true;
  3180. }
  3181. else {
  3182. return delay(policy._retryTimeout * 1000).then(function () { return getRegistrationStatus(policy, url, originalRequest); });
  3183. }
  3184. });
  3185. }
  3186. // Copyright (c) Microsoft Corporation. All rights reserved.
  3187. function signingPolicy(authenticationProvider) {
  3188. return {
  3189. create: function (nextPolicy, options) {
  3190. return new SigningPolicy(nextPolicy, options, authenticationProvider);
  3191. }
  3192. };
  3193. }
  3194. var SigningPolicy = /** @class */ (function (_super) {
  3195. tslib_1.__extends(SigningPolicy, _super);
  3196. function SigningPolicy(nextPolicy, options, authenticationProvider) {
  3197. var _this = _super.call(this, nextPolicy, options) || this;
  3198. _this.authenticationProvider = authenticationProvider;
  3199. return _this;
  3200. }
  3201. SigningPolicy.prototype.signRequest = function (request) {
  3202. return this.authenticationProvider.signRequest(request);
  3203. };
  3204. SigningPolicy.prototype.sendRequest = function (request) {
  3205. var _this = this;
  3206. return this.signRequest(request).then(function (nextRequest) { return _this._nextPolicy.sendRequest(nextRequest); });
  3207. };
  3208. return SigningPolicy;
  3209. }(BaseRequestPolicy));
  3210. // Copyright (c) Microsoft Corporation. All rights reserved.
  3211. function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  3212. return {
  3213. create: function (nextPolicy, options) {
  3214. return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
  3215. }
  3216. };
  3217. }
  3218. /**
  3219. * @class
  3220. * Instantiates a new "ExponentialRetryPolicyFilter" instance.
  3221. *
  3222. * @constructor
  3223. * @param {number} retryCount The client retry count.
  3224. * @param {number} retryInterval The client retry interval, in milliseconds.
  3225. * @param {number} minRetryInterval The minimum retry interval, in milliseconds.
  3226. * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.
  3227. */
  3228. var SystemErrorRetryPolicy = /** @class */ (function (_super) {
  3229. tslib_1.__extends(SystemErrorRetryPolicy, _super);
  3230. function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  3231. var _this = _super.call(this, nextPolicy, options) || this;
  3232. _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
  3233. _this.DEFAULT_CLIENT_RETRY_COUNT = 3;
  3234. _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
  3235. _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
  3236. _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;
  3237. _this.retryInterval = typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;
  3238. _this.minRetryInterval = typeof minRetryInterval === "number" ? minRetryInterval : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
  3239. _this.maxRetryInterval = typeof maxRetryInterval === "number" ? maxRetryInterval : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
  3240. return _this;
  3241. }
  3242. SystemErrorRetryPolicy.prototype.sendRequest = function (request) {
  3243. var _this = this;
  3244. return this._nextPolicy.sendRequest(request.clone()).then(function (response) { return retry$1(_this, request, response); });
  3245. };
  3246. return SystemErrorRetryPolicy;
  3247. }(BaseRequestPolicy));
  3248. /**
  3249. * Determines if the operation should be retried and how long to wait until the next retry.
  3250. *
  3251. * @param {number} statusCode The HTTP status code.
  3252. * @param {RetryData} retryData The retry data.
  3253. * @return {boolean} True if the operation qualifies for a retry; false otherwise.
  3254. */
  3255. function shouldRetry$1(policy, retryData) {
  3256. var currentCount;
  3257. if (!retryData) {
  3258. throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null.");
  3259. }
  3260. else {
  3261. currentCount = (retryData && retryData.retryCount);
  3262. }
  3263. return (currentCount < policy.retryCount);
  3264. }
  3265. /**
  3266. * Updates the retry data for the next attempt.
  3267. *
  3268. * @param {RetryData} retryData The retry data.
  3269. * @param {object} err The operation"s error, if any.
  3270. */
  3271. function updateRetryData$1(policy, retryData, err) {
  3272. if (!retryData) {
  3273. retryData = {
  3274. retryCount: 0,
  3275. retryInterval: 0
  3276. };
  3277. }
  3278. if (err) {
  3279. if (retryData.error) {
  3280. err.innerError = retryData.error;
  3281. }
  3282. retryData.error = err;
  3283. }
  3284. // Adjust retry count
  3285. retryData.retryCount++;
  3286. // Adjust retry interval
  3287. var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
  3288. var boundedRandDelta = policy.retryInterval * 0.8 +
  3289. Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
  3290. incrementDelta *= boundedRandDelta;
  3291. retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
  3292. return retryData;
  3293. }
  3294. function retry$1(policy, request, operationResponse, retryData, err) {
  3295. retryData = updateRetryData$1(policy, retryData, err);
  3296. if (err && err.code && shouldRetry$1(policy, retryData) &&
  3297. (err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" ||
  3298. err.code === "ECONNRESET" || err.code === "ENOENT")) {
  3299. // If previous operation ended with an error and the policy allows a retry, do that
  3300. return delay(retryData.retryInterval)
  3301. .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
  3302. .then(function (res) { return retry$1(policy, request, res, retryData, err); })
  3303. .catch(function (err) { return retry$1(policy, request, operationResponse, retryData, err); });
  3304. }
  3305. else {
  3306. if (err != undefined) {
  3307. // If the operation failed in the end, return all errors instead of just the last one
  3308. err = retryData.error;
  3309. return Promise.reject(err);
  3310. }
  3311. return Promise.resolve(operationResponse);
  3312. }
  3313. }
  3314. // Copyright (c) Microsoft Corporation. All rights reserved.
  3315. (function (QueryCollectionFormat) {
  3316. QueryCollectionFormat["Csv"] = ",";
  3317. QueryCollectionFormat["Ssv"] = " ";
  3318. QueryCollectionFormat["Tsv"] = "\t";
  3319. QueryCollectionFormat["Pipes"] = "|";
  3320. QueryCollectionFormat["Multi"] = "Multi";
  3321. })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));
  3322. // Copyright (c) Microsoft Corporation. All rights reserved.
  3323. function agentPolicy(agentSettings) {
  3324. return {
  3325. create: function (nextPolicy, options) {
  3326. return new AgentPolicy(nextPolicy, options, agentSettings);
  3327. }
  3328. };
  3329. }
  3330. var AgentPolicy = /** @class */ (function (_super) {
  3331. tslib_1.__extends(AgentPolicy, _super);
  3332. function AgentPolicy(nextPolicy, options, agentSettings) {
  3333. var _this = _super.call(this, nextPolicy, options) || this;
  3334. _this.agentSettings = agentSettings;
  3335. return _this;
  3336. }
  3337. AgentPolicy.prototype.sendRequest = function (request) {
  3338. if (!request.agentSettings) {
  3339. request.agentSettings = this.agentSettings;
  3340. }
  3341. return this._nextPolicy.sendRequest(request);
  3342. };
  3343. return AgentPolicy;
  3344. }(BaseRequestPolicy));
  3345. // Copyright (c) Microsoft Corporation. All rights reserved.
  3346. function loadEnvironmentProxyValue() {
  3347. if (!process) {
  3348. return undefined;
  3349. }
  3350. if (process.env[Constants.HTTPS_PROXY]) {
  3351. return process.env[Constants.HTTPS_PROXY];
  3352. }
  3353. else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) {
  3354. return process.env[Constants.HTTPS_PROXY.toLowerCase()];
  3355. }
  3356. else if (process.env[Constants.HTTP_PROXY]) {
  3357. return process.env[Constants.HTTP_PROXY];
  3358. }
  3359. else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) {
  3360. return process.env[Constants.HTTP_PROXY.toLowerCase()];
  3361. }
  3362. return undefined;
  3363. }
  3364. function getDefaultProxySettings(proxyUrl) {
  3365. if (!proxyUrl) {
  3366. proxyUrl = loadEnvironmentProxyValue();
  3367. if (!proxyUrl) {
  3368. return undefined;
  3369. }
  3370. }
  3371. var parsedUrl = URLBuilder.parse(proxyUrl);
  3372. return {
  3373. host: parsedUrl.getScheme() + "://" + parsedUrl.getHost(),
  3374. port: Number.parseInt(parsedUrl.getPort() || "80")
  3375. };
  3376. }
  3377. function proxyPolicy(proxySettings) {
  3378. return {
  3379. create: function (nextPolicy, options) {
  3380. return new ProxyPolicy(nextPolicy, options, proxySettings);
  3381. }
  3382. };
  3383. }
  3384. var ProxyPolicy = /** @class */ (function (_super) {
  3385. tslib_1.__extends(ProxyPolicy, _super);
  3386. function ProxyPolicy(nextPolicy, options, proxySettings) {
  3387. var _this = _super.call(this, nextPolicy, options) || this;
  3388. _this.proxySettings = proxySettings;
  3389. return _this;
  3390. }
  3391. ProxyPolicy.prototype.sendRequest = function (request) {
  3392. if (!request.proxySettings) {
  3393. request.proxySettings = this.proxySettings;
  3394. }
  3395. return this._nextPolicy.sendRequest(request);
  3396. };
  3397. return ProxyPolicy;
  3398. }(BaseRequestPolicy));
  3399. // Copyright (c) Microsoft Corporation. All rights reserved.
  3400. var StatusCodes = Constants.HttpConstants.StatusCodes;
  3401. function throttlingRetryPolicy() {
  3402. return {
  3403. create: function (nextPolicy, options) {
  3404. return new ThrottlingRetryPolicy(nextPolicy, options);
  3405. }
  3406. };
  3407. }
  3408. /**
  3409. * To learn more, please refer to
  3410. * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
  3411. * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
  3412. * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
  3413. */
  3414. var ThrottlingRetryPolicy = /** @class */ (function (_super) {
  3415. tslib_1.__extends(ThrottlingRetryPolicy, _super);
  3416. function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) {
  3417. var _this = _super.call(this, nextPolicy, options) || this;
  3418. _this._handleResponse = _handleResponse || _this._defaultResponseHandler;
  3419. return _this;
  3420. }
  3421. ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {
  3422. return tslib_1.__awaiter(this, void 0, void 0, function () {
  3423. var _this = this;
  3424. return tslib_1.__generator(this, function (_a) {
  3425. return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {
  3426. if (response.status !== StatusCodes.TooManyRequests) {
  3427. return response;
  3428. }
  3429. else {
  3430. return _this._handleResponse(httpRequest, response);
  3431. }
  3432. })];
  3433. });
  3434. });
  3435. };
  3436. ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) {
  3437. return tslib_1.__awaiter(this, void 0, void 0, function () {
  3438. var retryAfterHeader, delayInMs;
  3439. var _this = this;
  3440. return tslib_1.__generator(this, function (_a) {
  3441. retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);
  3442. if (retryAfterHeader) {
  3443. delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
  3444. if (delayInMs) {
  3445. return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })];
  3446. }
  3447. }
  3448. return [2 /*return*/, httpResponse];
  3449. });
  3450. });
  3451. };
  3452. ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {
  3453. var retryAfterInSeconds = Number(headerValue);
  3454. if (Number.isNaN(retryAfterInSeconds)) {
  3455. return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);
  3456. }
  3457. else {
  3458. return retryAfterInSeconds * 1000;
  3459. }
  3460. };
  3461. ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {
  3462. try {
  3463. var now = Date.now();
  3464. var date = Date.parse(headerValue);
  3465. var diff = date - now;
  3466. return Number.isNaN(diff) ? undefined : diff;
  3467. }
  3468. catch (error) {
  3469. return undefined;
  3470. }
  3471. };
  3472. return ThrottlingRetryPolicy;
  3473. }(BaseRequestPolicy));
  3474. // Copyright (c) Microsoft Corporation. All rights reserved.
  3475. /**
  3476. * @class
  3477. * Initializes a new instance of the ServiceClient.
  3478. */
  3479. var ServiceClient = /** @class */ (function () {
  3480. /**
  3481. * The ServiceClient constructor
  3482. * @constructor
  3483. * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
  3484. * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
  3485. */
  3486. function ServiceClient(credentials, options) {
  3487. if (!options) {
  3488. options = {};
  3489. }
  3490. if (credentials && !credentials.signRequest) {
  3491. throw new Error("credentials argument needs to implement signRequest method");
  3492. }
  3493. this._withCredentials = options.withCredentials || false;
  3494. this._httpClient = options.httpClient || new AxiosHttpClient();
  3495. this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
  3496. var requestPolicyFactories;
  3497. if (Array.isArray(options.requestPolicyFactories)) {
  3498. requestPolicyFactories = options.requestPolicyFactories;
  3499. }
  3500. else {
  3501. requestPolicyFactories = createDefaultRequestPolicyFactories(credentials, options);
  3502. if (options.requestPolicyFactories) {
  3503. var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
  3504. if (newRequestPolicyFactories) {
  3505. requestPolicyFactories = newRequestPolicyFactories;
  3506. }
  3507. }
  3508. }
  3509. this._requestPolicyFactories = requestPolicyFactories;
  3510. }
  3511. /**
  3512. * Send the provided httpRequest.
  3513. */
  3514. ServiceClient.prototype.sendRequest = function (options) {
  3515. if (options === null || options === undefined || typeof options !== "object") {
  3516. throw new Error("options cannot be null or undefined and it must be of type object.");
  3517. }
  3518. var httpRequest;
  3519. try {
  3520. if (options instanceof WebResource) {
  3521. options.validateRequestProperties();
  3522. httpRequest = options;
  3523. }
  3524. else {
  3525. httpRequest = new WebResource();
  3526. httpRequest = httpRequest.prepare(options);
  3527. }
  3528. }
  3529. catch (error) {
  3530. return Promise.reject(error);
  3531. }
  3532. var httpPipeline = this._httpClient;
  3533. if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
  3534. for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
  3535. httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
  3536. }
  3537. }
  3538. return httpPipeline.sendRequest(httpRequest);
  3539. };
  3540. /**
  3541. * Send an HTTP request that is populated using the provided OperationSpec.
  3542. * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
  3543. * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
  3544. * @param {ServiceCallback} callback The callback to call when the response is received.
  3545. */
  3546. ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
  3547. if (typeof operationArguments.options === "function") {
  3548. callback = operationArguments.options;
  3549. operationArguments.options = undefined;
  3550. }
  3551. var httpRequest = new WebResource();
  3552. var result;
  3553. try {
  3554. var baseUri = operationSpec.baseUrl || this.baseUri;
  3555. if (!baseUri) {
  3556. throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use.");
  3557. }
  3558. httpRequest.method = operationSpec.httpMethod;
  3559. httpRequest.operationSpec = operationSpec;
  3560. var requestUrl = URLBuilder.parse(baseUri);
  3561. if (operationSpec.path) {
  3562. requestUrl.appendPath(operationSpec.path);
  3563. }
  3564. if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
  3565. for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
  3566. var urlParameter = _a[_i];
  3567. var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
  3568. urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
  3569. if (!urlParameter.skipEncoding) {
  3570. urlParameterValue = encodeURIComponent(urlParameterValue);
  3571. }
  3572. requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
  3573. }
  3574. }
  3575. if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
  3576. for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
  3577. var queryParameter = _c[_b];
  3578. var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
  3579. if (queryParameterValue != undefined) {
  3580. queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
  3581. if (queryParameter.collectionFormat != undefined) {
  3582. if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {
  3583. if (queryParameterValue.length === 0) {
  3584. queryParameterValue = "";
  3585. }
  3586. else {
  3587. for (var index in queryParameterValue) {
  3588. var item = queryParameterValue[index];
  3589. queryParameterValue[index] = item == undefined ? "" : item.toString();
  3590. }
  3591. }
  3592. }
  3593. else {
  3594. queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
  3595. }
  3596. }
  3597. if (!queryParameter.skipEncoding) {
  3598. if (Array.isArray(queryParameterValue)) {
  3599. for (var index in queryParameterValue) {
  3600. queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
  3601. }
  3602. }
  3603. else {
  3604. queryParameterValue = encodeURIComponent(queryParameterValue);
  3605. }
  3606. }
  3607. requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
  3608. }
  3609. }
  3610. }
  3611. httpRequest.url = requestUrl.toString();
  3612. var contentType = operationSpec.contentType || this.requestContentType;
  3613. if (contentType) {
  3614. httpRequest.headers.set("Content-Type", contentType);
  3615. }
  3616. if (operationSpec.headerParameters) {
  3617. for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
  3618. var headerParameter = _e[_d];
  3619. var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
  3620. if (headerValue != undefined) {
  3621. headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
  3622. var headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix;
  3623. if (headerCollectionPrefix) {
  3624. for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
  3625. var key = _g[_f];
  3626. httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
  3627. }
  3628. }
  3629. else {
  3630. httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);
  3631. }
  3632. }
  3633. }
  3634. }
  3635. var options = operationArguments.options;
  3636. if (options) {
  3637. if (options.customHeaders) {
  3638. for (var customHeaderName in options.customHeaders) {
  3639. httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
  3640. }
  3641. }
  3642. if (options.abortSignal) {
  3643. httpRequest.abortSignal = options.abortSignal;
  3644. }
  3645. if (options.timeout) {
  3646. httpRequest.timeout = options.timeout;
  3647. }
  3648. if (options.onUploadProgress) {
  3649. httpRequest.onUploadProgress = options.onUploadProgress;
  3650. }
  3651. if (options.onDownloadProgress) {
  3652. httpRequest.onDownloadProgress = options.onDownloadProgress;
  3653. }
  3654. }
  3655. httpRequest.withCredentials = this._withCredentials;
  3656. serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
  3657. if (httpRequest.streamResponseBody == undefined) {
  3658. httpRequest.streamResponseBody = isStreamOperation(operationSpec);
  3659. }
  3660. result = this.sendRequest(httpRequest)
  3661. .then(function (res) { return flattenResponse(res, operationSpec.responses[res.status]); });
  3662. }
  3663. catch (error) {
  3664. result = Promise.reject(error);
  3665. }
  3666. var cb = callback;
  3667. if (cb) {
  3668. result
  3669. // tslint:disable-next-line:no-null-keyword
  3670. .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
  3671. .catch(function (err) { return cb(err); });
  3672. }
  3673. return result;
  3674. };
  3675. return ServiceClient;
  3676. }());
  3677. function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
  3678. if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
  3679. httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
  3680. var bodyMapper = operationSpec.requestBody.mapper;
  3681. var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
  3682. var typeName = bodyMapper.type.name;
  3683. try {
  3684. if (httpRequest.body != undefined || required) {
  3685. var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
  3686. httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
  3687. var isStream = typeName === MapperType.Stream;
  3688. if (operationSpec.isXML) {
  3689. if (typeName === MapperType.Sequence) {
  3690. httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
  3691. }
  3692. else if (!isStream) {
  3693. httpRequest.body = stringifyXML(httpRequest.body, { rootName: xmlName || serializedName });
  3694. }
  3695. }
  3696. else if (!isStream) {
  3697. httpRequest.body = JSON.stringify(httpRequest.body);
  3698. }
  3699. }
  3700. }
  3701. catch (error) {
  3702. throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
  3703. }
  3704. }
  3705. else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
  3706. httpRequest.formData = {};
  3707. for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
  3708. var formDataParameter = _a[_i];
  3709. var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
  3710. if (formDataParameterValue != undefined) {
  3711. var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
  3712. httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
  3713. }
  3714. }
  3715. }
  3716. }
  3717. function isRequestPolicyFactory(instance) {
  3718. return typeof instance.create === "function";
  3719. }
  3720. function getValueOrFunctionResult(value, defaultValueCreator) {
  3721. var result;
  3722. if (typeof value === "string") {
  3723. result = value;
  3724. }
  3725. else {
  3726. result = defaultValueCreator();
  3727. if (typeof value === "function") {
  3728. result = value(result);
  3729. }
  3730. }
  3731. return result;
  3732. }
  3733. function createDefaultRequestPolicyFactories(credentials, options) {
  3734. var factories = [];
  3735. if (options.generateClientRequestIdHeader) {
  3736. factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
  3737. }
  3738. if (credentials) {
  3739. if (isRequestPolicyFactory(credentials)) {
  3740. factories.push(credentials);
  3741. }
  3742. else {
  3743. factories.push(signingPolicy(credentials));
  3744. }
  3745. }
  3746. var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
  3747. var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
  3748. if (userAgentHeaderName && userAgentHeaderValue) {
  3749. factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
  3750. }
  3751. factories.push(redirectPolicy());
  3752. factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
  3753. if (!options.noRetryPolicy) {
  3754. factories.push(exponentialRetryPolicy());
  3755. factories.push(systemErrorRetryPolicy());
  3756. factories.push(throttlingRetryPolicy());
  3757. }
  3758. factories.push(deserializationPolicy(options.deserializationContentTypes));
  3759. var proxySettings = options.proxySettings || getDefaultProxySettings();
  3760. if (proxySettings) {
  3761. factories.push(proxyPolicy(proxySettings));
  3762. }
  3763. if (options.agentSettings) {
  3764. factories.push(agentPolicy(options.agentSettings));
  3765. }
  3766. return factories;
  3767. }
  3768. function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
  3769. return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
  3770. }
  3771. function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
  3772. var value;
  3773. if (typeof parameterPath === "string") {
  3774. parameterPath = [parameterPath];
  3775. }
  3776. if (Array.isArray(parameterPath)) {
  3777. if (parameterPath.length > 0) {
  3778. if (parameterMapper.isConstant) {
  3779. value = parameterMapper.defaultValue;
  3780. }
  3781. else {
  3782. var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
  3783. if (!propertySearchResult.propertyFound) {
  3784. propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
  3785. }
  3786. var useDefaultValue = false;
  3787. if (!propertySearchResult.propertyFound) {
  3788. useDefaultValue = parameterMapper.required || (parameterPath[0] === "options" && parameterPath.length === 2);
  3789. }
  3790. value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
  3791. }
  3792. // Serialize just for validation purposes.
  3793. var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
  3794. serializer.serialize(parameterMapper, value, parameterPathString);
  3795. }
  3796. }
  3797. else {
  3798. if (parameterMapper.required) {
  3799. value = {};
  3800. }
  3801. for (var propertyName in parameterPath) {
  3802. var propertyMapper = parameterMapper.type.modelProperties[propertyName];
  3803. var propertyPath = parameterPath[propertyName];
  3804. var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
  3805. // Serialize just for validation purposes.
  3806. var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
  3807. serializer.serialize(propertyMapper, propertyValue, propertyPathString);
  3808. if (propertyValue !== undefined) {
  3809. if (!value) {
  3810. value = {};
  3811. }
  3812. value[propertyName] = propertyValue;
  3813. }
  3814. }
  3815. }
  3816. return value;
  3817. }
  3818. function getPropertyFromParameterPath(parent, parameterPath) {
  3819. var result = { propertyFound: false };
  3820. var i = 0;
  3821. for (; i < parameterPath.length; ++i) {
  3822. var parameterPathPart = parameterPath[i];
  3823. // Make sure to check inherited properties too, so don't use hasOwnProperty().
  3824. if (parent != undefined && parameterPathPart in parent) {
  3825. parent = parent[parameterPathPart];
  3826. }
  3827. else {
  3828. break;
  3829. }
  3830. }
  3831. if (i === parameterPath.length) {
  3832. result.propertyValue = parent;
  3833. result.propertyFound = true;
  3834. }
  3835. return result;
  3836. }
  3837. function flattenResponse(_response, responseSpec) {
  3838. var parsedHeaders = _response.parsedHeaders;
  3839. var bodyMapper = responseSpec && responseSpec.bodyMapper;
  3840. var addOperationResponse = function (obj) {
  3841. return Object.defineProperty(obj, "_response", {
  3842. value: _response
  3843. });
  3844. };
  3845. if (bodyMapper) {
  3846. var typeName = bodyMapper.type.name;
  3847. if (typeName === "Stream") {
  3848. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
  3849. }
  3850. var modelProperties_1 = typeName === "Composite" && bodyMapper.type.modelProperties || {};
  3851. var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
  3852. if (typeName === "Sequence" || isPageableResponse) {
  3853. // We're expecting a sequence(array) make sure that the response body is in the
  3854. // correct format, if not make it an empty array []
  3855. var parsedBody = Array.isArray(_response.parsedBody)
  3856. ? _response.parsedBody
  3857. : [];
  3858. var arrayResponse = parsedBody.slice();
  3859. for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
  3860. var key = _a[_i];
  3861. if (modelProperties_1[key].serializedName) {
  3862. arrayResponse[key] = _response.parsedBody[key];
  3863. }
  3864. }
  3865. if (parsedHeaders) {
  3866. for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
  3867. var key = _c[_b];
  3868. arrayResponse[key] = parsedHeaders[key];
  3869. }
  3870. }
  3871. addOperationResponse(arrayResponse);
  3872. return arrayResponse;
  3873. }
  3874. if (typeName === "Composite" || typeName === "Dictionary") {
  3875. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, _response.parsedBody));
  3876. }
  3877. }
  3878. if (bodyMapper || _response.request.method === "HEAD") {
  3879. // primitive body types and HEAD booleans
  3880. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, { body: _response.parsedBody }));
  3881. }
  3882. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, _response.parsedBody));
  3883. }
  3884. // Copyright (c) Microsoft Corporation. All rights reserved.
  3885. function logPolicy(logger) {
  3886. if (logger === void 0) { logger = console.log; }
  3887. return {
  3888. create: function (nextPolicy, options) {
  3889. return new LogPolicy(nextPolicy, options, logger);
  3890. }
  3891. };
  3892. }
  3893. var LogPolicy = /** @class */ (function (_super) {
  3894. tslib_1.__extends(LogPolicy, _super);
  3895. function LogPolicy(nextPolicy, options, logger) {
  3896. if (logger === void 0) { logger = console.log; }
  3897. var _this = _super.call(this, nextPolicy, options) || this;
  3898. _this.logger = logger;
  3899. return _this;
  3900. }
  3901. LogPolicy.prototype.sendRequest = function (request) {
  3902. var _this = this;
  3903. return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });
  3904. };
  3905. return LogPolicy;
  3906. }(BaseRequestPolicy));
  3907. function logResponse(policy, response) {
  3908. policy.logger(">> Request: " + JSON.stringify(response.request, undefined, 2));
  3909. policy.logger(">> Response status code: " + response.status);
  3910. var responseBody = response.bodyAsText;
  3911. policy.logger(">> Body: " + responseBody);
  3912. return Promise.resolve(response);
  3913. }
  3914. // Copyright (c) Microsoft Corporation. All rights reserved.
  3915. var HeaderConstants = Constants.HeaderConstants;
  3916. var DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
  3917. /**
  3918. * A credentials object that uses a token string and a authorzation scheme to authenticate.
  3919. */
  3920. var TokenCredentials = /** @class */ (function () {
  3921. /**
  3922. * Creates a new TokenCredentials object.
  3923. *
  3924. * @constructor
  3925. * @param {string} token The token.
  3926. * @param {string} [authorizationScheme] The authorization scheme.
  3927. */
  3928. function TokenCredentials(token, authorizationScheme) {
  3929. if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; }
  3930. this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME;
  3931. if (!token) {
  3932. throw new Error("token cannot be null or undefined.");
  3933. }
  3934. this.token = token;
  3935. this.authorizationScheme = authorizationScheme;
  3936. }
  3937. /**
  3938. * Signs a request with the Authentication header.
  3939. *
  3940. * @param {WebResource} webResource The WebResource to be signed.
  3941. * @return {Promise<WebResource>} The signed request object.
  3942. */
  3943. TokenCredentials.prototype.signRequest = function (webResource) {
  3944. if (!webResource.headers)
  3945. webResource.headers = new HttpHeaders();
  3946. webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + " " + this.token);
  3947. return Promise.resolve(webResource);
  3948. };
  3949. return TokenCredentials;
  3950. }());
  3951. // Copyright (c) Microsoft Corporation. All rights reserved.
  3952. var HeaderConstants$1 = Constants.HeaderConstants;
  3953. var DEFAULT_AUTHORIZATION_SCHEME$1 = "Basic";
  3954. var BasicAuthenticationCredentials = /** @class */ (function () {
  3955. /**
  3956. * Creates a new BasicAuthenticationCredentials object.
  3957. *
  3958. * @constructor
  3959. * @param {string} userName User name.
  3960. * @param {string} password Password.
  3961. * @param {string} [authorizationScheme] The authorization scheme.
  3962. */
  3963. function BasicAuthenticationCredentials(userName, password, authorizationScheme) {
  3964. if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }
  3965. this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;
  3966. if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
  3967. throw new Error("userName cannot be null or undefined and must be of type string.");
  3968. }
  3969. if (password === null || password === undefined || typeof password.valueOf() !== "string") {
  3970. throw new Error("password cannot be null or undefined and must be of type string.");
  3971. }
  3972. this.userName = userName;
  3973. this.password = password;
  3974. this.authorizationScheme = authorizationScheme;
  3975. }
  3976. /**
  3977. * Signs a request with the Authentication header.
  3978. *
  3979. * @param {WebResource} webResource The WebResource to be signed.
  3980. * @returns {Promise<WebResource>} The signed request object.
  3981. */
  3982. BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {
  3983. var credentials = this.userName + ":" + this.password;
  3984. var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials);
  3985. if (!webResource.headers)
  3986. webResource.headers = new HttpHeaders();
  3987. webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);
  3988. return Promise.resolve(webResource);
  3989. };
  3990. return BasicAuthenticationCredentials;
  3991. }());
  3992. // Copyright (c) Microsoft Corporation. All rights reserved.
  3993. /**
  3994. * Authenticates to a service using an API key.
  3995. */
  3996. var ApiKeyCredentials = /** @class */ (function () {
  3997. /**
  3998. * @constructor
  3999. * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
  4000. */
  4001. function ApiKeyCredentials(options) {
  4002. if (!options || (options && !options.inHeader && !options.inQuery)) {
  4003. throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided.");
  4004. }
  4005. this.inHeader = options.inHeader;
  4006. this.inQuery = options.inQuery;
  4007. }
  4008. /**
  4009. * Signs a request with the values provided in the inHeader and inQuery parameter.
  4010. *
  4011. * @param {WebResource} webResource The WebResource to be signed.
  4012. * @returns {Promise<WebResource>} The signed request object.
  4013. */
  4014. ApiKeyCredentials.prototype.signRequest = function (webResource) {
  4015. if (!webResource) {
  4016. return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\"."));
  4017. }
  4018. if (this.inHeader) {
  4019. if (!webResource.headers) {
  4020. webResource.headers = new HttpHeaders();
  4021. }
  4022. for (var headerName in this.inHeader) {
  4023. webResource.headers.set(headerName, this.inHeader[headerName]);
  4024. }
  4025. }
  4026. if (this.inQuery) {
  4027. if (!webResource.url) {
  4028. return Promise.reject(new Error("url cannot be null in the request object."));
  4029. }
  4030. if (webResource.url.indexOf("?") < 0) {
  4031. webResource.url += "?";
  4032. }
  4033. for (var key in this.inQuery) {
  4034. if (!webResource.url.endsWith("?")) {
  4035. webResource.url += "&";
  4036. }
  4037. webResource.url += key + "=" + this.inQuery[key];
  4038. }
  4039. }
  4040. return Promise.resolve(webResource);
  4041. };
  4042. return ApiKeyCredentials;
  4043. }());
  4044. // Copyright (c) Microsoft Corporation. All rights reserved.
  4045. var TopicCredentials = /** @class */ (function (_super) {
  4046. tslib_1.__extends(TopicCredentials, _super);
  4047. /**
  4048. * Creates a new EventGrid TopicCredentials object.
  4049. *
  4050. * @constructor
  4051. * @param {string} topicKey The EventGrid topic key
  4052. */
  4053. function TopicCredentials(topicKey) {
  4054. var _this = this;
  4055. if (!topicKey || (topicKey && typeof topicKey !== "string")) {
  4056. throw new Error("topicKey cannot be null or undefined and must be of type string.");
  4057. }
  4058. var options = {
  4059. inHeader: {
  4060. "aeg-sas-key": topicKey
  4061. }
  4062. };
  4063. _this = _super.call(this, options) || this;
  4064. return _this;
  4065. }
  4066. return TopicCredentials;
  4067. }(ApiKeyCredentials));
  4068. // Copyright (c) Microsoft Corporation. All rights reserved.
  4069. var DomainCredentials = /** @class */ (function (_super) {
  4070. tslib_1.__extends(DomainCredentials, _super);
  4071. /**
  4072. * Creates a new EventGrid DomainCredentials object.
  4073. *
  4074. * @constructor
  4075. * @param {string} domainKey The EventGrid domain key
  4076. */
  4077. function DomainCredentials(domainKey) {
  4078. var _this = this;
  4079. if (!domainKey || (domainKey && typeof domainKey !== "string")) {
  4080. throw new Error("domainKey cannot be null or undefined and must be of type string.");
  4081. }
  4082. var options = {
  4083. inHeader: {
  4084. "aeg-sas-key": domainKey
  4085. }
  4086. };
  4087. _this = _super.call(this, options) || this;
  4088. return _this;
  4089. }
  4090. return DomainCredentials;
  4091. }(ApiKeyCredentials));
  4092. // Copyright (c) Microsoft Corporation. All rights reserved.
  4093. exports.WebResource = WebResource;
  4094. exports.DefaultHttpClient = AxiosHttpClient;
  4095. exports.HttpHeaders = HttpHeaders;
  4096. exports.RestError = RestError;
  4097. exports.ServiceClient = ServiceClient;
  4098. exports.flattenResponse = flattenResponse;
  4099. exports.Constants = Constants;
  4100. exports.logPolicy = logPolicy;
  4101. exports.BaseRequestPolicy = BaseRequestPolicy;
  4102. exports.RequestPolicyOptions = RequestPolicyOptions;
  4103. exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;
  4104. exports.exponentialRetryPolicy = exponentialRetryPolicy;
  4105. exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
  4106. exports.throttlingRetryPolicy = throttlingRetryPolicy;
  4107. exports.getDefaultProxySettings = getDefaultProxySettings;
  4108. exports.proxyPolicy = proxyPolicy;
  4109. exports.redirectPolicy = redirectPolicy;
  4110. exports.signingPolicy = signingPolicy;
  4111. exports.userAgentPolicy = userAgentPolicy;
  4112. exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
  4113. exports.deserializationPolicy = deserializationPolicy;
  4114. exports.deserializeResponseBody = deserializeResponseBody;
  4115. exports.MapperType = MapperType;
  4116. exports.Serializer = Serializer;
  4117. exports.serializeObject = serializeObject;
  4118. exports.stripRequest = stripRequest;
  4119. exports.stripResponse = stripResponse;
  4120. exports.delay = delay;
  4121. exports.executePromisesSequentially = executePromisesSequentially;
  4122. exports.generateUuid = generateUuid;
  4123. exports.encodeUri = encodeUri;
  4124. exports.promiseToCallback = promiseToCallback;
  4125. exports.promiseToServiceCallback = promiseToServiceCallback;
  4126. exports.isValidUuid = isValidUuid;
  4127. exports.applyMixins = applyMixins;
  4128. exports.isNode = isNode;
  4129. exports.isDuration = isDuration;
  4130. exports.URLBuilder = URLBuilder;
  4131. exports.URLQuery = URLQuery;
  4132. exports.TokenCredentials = TokenCredentials;
  4133. exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;
  4134. exports.ApiKeyCredentials = ApiKeyCredentials;
  4135. exports.TopicCredentials = TopicCredentials;
  4136. exports.DomainCredentials = DomainCredentials;
  4137. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  4138. },{"_process":525,"axios":114,"buffer":193,"form-data":255,"http":612,"https":318,"os":500,"stream":597,"tough-cookie":640,"tslib":3,"tunnel":648,"uuid/v4":663,"xml2js":671}],3:[function(require,module,exports){
  4139. (function (global){(function (){
  4140. /*! *****************************************************************************
  4141. Copyright (c) Microsoft Corporation.
  4142. Permission to use, copy, modify, and/or distribute this software for any
  4143. purpose with or without fee is hereby granted.
  4144. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  4145. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  4146. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  4147. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  4148. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  4149. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  4150. PERFORMANCE OF THIS SOFTWARE.
  4151. ***************************************************************************** */
  4152. /* global global, define, System, Reflect, Promise */
  4153. var __extends;
  4154. var __assign;
  4155. var __rest;
  4156. var __decorate;
  4157. var __param;
  4158. var __metadata;
  4159. var __awaiter;
  4160. var __generator;
  4161. var __exportStar;
  4162. var __values;
  4163. var __read;
  4164. var __spread;
  4165. var __spreadArrays;
  4166. var __await;
  4167. var __asyncGenerator;
  4168. var __asyncDelegator;
  4169. var __asyncValues;
  4170. var __makeTemplateObject;
  4171. var __importStar;
  4172. var __importDefault;
  4173. var __classPrivateFieldGet;
  4174. var __classPrivateFieldSet;
  4175. var __createBinding;
  4176. (function (factory) {
  4177. var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
  4178. if (typeof define === "function" && define.amd) {
  4179. define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
  4180. }
  4181. else if (typeof module === "object" && typeof module.exports === "object") {
  4182. factory(createExporter(root, createExporter(module.exports)));
  4183. }
  4184. else {
  4185. factory(createExporter(root));
  4186. }
  4187. function createExporter(exports, previous) {
  4188. if (exports !== root) {
  4189. if (typeof Object.create === "function") {
  4190. Object.defineProperty(exports, "__esModule", { value: true });
  4191. }
  4192. else {
  4193. exports.__esModule = true;
  4194. }
  4195. }
  4196. return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
  4197. }
  4198. })
  4199. (function (exporter) {
  4200. var extendStatics = Object.setPrototypeOf ||
  4201. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4202. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4203. __extends = function (d, b) {
  4204. extendStatics(d, b);
  4205. function __() { this.constructor = d; }
  4206. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4207. };
  4208. __assign = Object.assign || function (t) {
  4209. for (var s, i = 1, n = arguments.length; i < n; i++) {
  4210. s = arguments[i];
  4211. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  4212. }
  4213. return t;
  4214. };
  4215. __rest = function (s, e) {
  4216. var t = {};
  4217. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  4218. t[p] = s[p];
  4219. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  4220. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  4221. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  4222. t[p[i]] = s[p[i]];
  4223. }
  4224. return t;
  4225. };
  4226. __decorate = function (decorators, target, key, desc) {
  4227. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4228. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4229. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  4230. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4231. };
  4232. __param = function (paramIndex, decorator) {
  4233. return function (target, key) { decorator(target, key, paramIndex); }
  4234. };
  4235. __metadata = function (metadataKey, metadataValue) {
  4236. if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
  4237. };
  4238. __awaiter = function (thisArg, _arguments, P, generator) {
  4239. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4240. return new (P || (P = Promise))(function (resolve, reject) {
  4241. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4242. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4243. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  4244. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4245. });
  4246. };
  4247. __generator = function (thisArg, body) {
  4248. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  4249. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  4250. function verb(n) { return function (v) { return step([n, v]); }; }
  4251. function step(op) {
  4252. if (f) throw new TypeError("Generator is already executing.");
  4253. while (_) try {
  4254. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  4255. if (y = 0, t) op = [op[0] & 2, t.value];
  4256. switch (op[0]) {
  4257. case 0: case 1: t = op; break;
  4258. case 4: _.label++; return { value: op[1], done: false };
  4259. case 5: _.label++; y = op[1]; op = [0]; continue;
  4260. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  4261. default:
  4262. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  4263. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  4264. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  4265. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  4266. if (t[2]) _.ops.pop();
  4267. _.trys.pop(); continue;
  4268. }
  4269. op = body.call(thisArg, _);
  4270. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  4271. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  4272. }
  4273. };
  4274. __createBinding = function(o, m, k, k2) {
  4275. if (k2 === undefined) k2 = k;
  4276. o[k2] = m[k];
  4277. };
  4278. __exportStar = function (m, exports) {
  4279. for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
  4280. };
  4281. __values = function (o) {
  4282. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  4283. if (m) return m.call(o);
  4284. if (o && typeof o.length === "number") return {
  4285. next: function () {
  4286. if (o && i >= o.length) o = void 0;
  4287. return { value: o && o[i++], done: !o };
  4288. }
  4289. };
  4290. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  4291. };
  4292. __read = function (o, n) {
  4293. var m = typeof Symbol === "function" && o[Symbol.iterator];
  4294. if (!m) return o;
  4295. var i = m.call(o), r, ar = [], e;
  4296. try {
  4297. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  4298. }
  4299. catch (error) { e = { error: error }; }
  4300. finally {
  4301. try {
  4302. if (r && !r.done && (m = i["return"])) m.call(i);
  4303. }
  4304. finally { if (e) throw e.error; }
  4305. }
  4306. return ar;
  4307. };
  4308. __spread = function () {
  4309. for (var ar = [], i = 0; i < arguments.length; i++)
  4310. ar = ar.concat(__read(arguments[i]));
  4311. return ar;
  4312. };
  4313. __spreadArrays = function () {
  4314. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  4315. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  4316. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  4317. r[k] = a[j];
  4318. return r;
  4319. };
  4320. __await = function (v) {
  4321. return this instanceof __await ? (this.v = v, this) : new __await(v);
  4322. };
  4323. __asyncGenerator = function (thisArg, _arguments, generator) {
  4324. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  4325. var g = generator.apply(thisArg, _arguments || []), i, q = [];
  4326. return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
  4327. function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
  4328. function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
  4329. function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
  4330. function fulfill(value) { resume("next", value); }
  4331. function reject(value) { resume("throw", value); }
  4332. function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
  4333. };
  4334. __asyncDelegator = function (o) {
  4335. var i, p;
  4336. return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
  4337. function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
  4338. };
  4339. __asyncValues = function (o) {
  4340. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  4341. var m = o[Symbol.asyncIterator], i;
  4342. return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  4343. function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  4344. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
  4345. };
  4346. __makeTemplateObject = function (cooked, raw) {
  4347. if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
  4348. return cooked;
  4349. };
  4350. __importStar = function (mod) {
  4351. if (mod && mod.__esModule) return mod;
  4352. var result = {};
  4353. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  4354. result["default"] = mod;
  4355. return result;
  4356. };
  4357. __importDefault = function (mod) {
  4358. return (mod && mod.__esModule) ? mod : { "default": mod };
  4359. };
  4360. __classPrivateFieldGet = function (receiver, privateMap) {
  4361. if (!privateMap.has(receiver)) {
  4362. throw new TypeError("attempted to get private field on non-instance");
  4363. }
  4364. return privateMap.get(receiver);
  4365. };
  4366. __classPrivateFieldSet = function (receiver, privateMap, value) {
  4367. if (!privateMap.has(receiver)) {
  4368. throw new TypeError("attempted to set private field on non-instance");
  4369. }
  4370. privateMap.set(receiver, value);
  4371. return value;
  4372. };
  4373. exporter("__extends", __extends);
  4374. exporter("__assign", __assign);
  4375. exporter("__rest", __rest);
  4376. exporter("__decorate", __decorate);
  4377. exporter("__param", __param);
  4378. exporter("__metadata", __metadata);
  4379. exporter("__awaiter", __awaiter);
  4380. exporter("__generator", __generator);
  4381. exporter("__exportStar", __exportStar);
  4382. exporter("__createBinding", __createBinding);
  4383. exporter("__values", __values);
  4384. exporter("__read", __read);
  4385. exporter("__spread", __spread);
  4386. exporter("__spreadArrays", __spreadArrays);
  4387. exporter("__await", __await);
  4388. exporter("__asyncGenerator", __asyncGenerator);
  4389. exporter("__asyncDelegator", __asyncDelegator);
  4390. exporter("__asyncValues", __asyncValues);
  4391. exporter("__makeTemplateObject", __makeTemplateObject);
  4392. exporter("__importStar", __importStar);
  4393. exporter("__importDefault", __importDefault);
  4394. exporter("__classPrivateFieldGet", __classPrivateFieldGet);
  4395. exporter("__classPrivateFieldSet", __classPrivateFieldSet);
  4396. });
  4397. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4398. },{}],4:[function(require,module,exports){
  4399. (function (Buffer){(function (){
  4400. "use strict";
  4401. // Copyright (c) Microsoft Corporation. All rights reserved.
  4402. // Licensed under the MIT License. See License.txt in the project root for license information.
  4403. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  4404. return new (P || (P = Promise))(function (resolve, reject) {
  4405. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4406. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4407. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  4408. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4409. });
  4410. };
  4411. Object.defineProperty(exports, "__esModule", { value: true });
  4412. const fs_1 = require("fs");
  4413. const crypto_1 = require("crypto");
  4414. const applicationTokenCredentialsBase_1 = require("./applicationTokenCredentialsBase");
  4415. const authConstants_1 = require("../util/authConstants");
  4416. class ApplicationTokenCertificateCredentials extends applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase {
  4417. /**
  4418. * Creates a new ApplicationTokenCredentials object.
  4419. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  4420. * for detailed instructions on creating an Azure Active Directory application.
  4421. * @constructor
  4422. * @param {string} clientId The active directory application client id.
  4423. * @param {string} domain The domain or tenant id containing this application.
  4424. * @param {string} certificate A PEM encoded certificate private key.
  4425. * @param {string} thumbprint A hex encoded thumbprint of the certificate.
  4426. * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  4427. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  4428. * @param {Environment} [environment] The azure environment to authenticate with.
  4429. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  4430. */
  4431. constructor(clientId, domain, certificate, thumbprint, tokenAudience, environment, tokenCache) {
  4432. if (!certificate || typeof certificate.valueOf() !== "string") {
  4433. throw new Error("certificate must be a non empty string.");
  4434. }
  4435. if (!thumbprint || typeof thumbprint.valueOf() !== "string") {
  4436. throw new Error("thumbprint must be a non empty string.");
  4437. }
  4438. super(clientId, domain, tokenAudience, environment, tokenCache);
  4439. this.certificate = certificate;
  4440. this.thumbprint = thumbprint;
  4441. }
  4442. /**
  4443. * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
  4444. * @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
  4445. */
  4446. getToken() {
  4447. return __awaiter(this, void 0, void 0, function* () {
  4448. try {
  4449. const tokenResponse = yield this.getTokenFromCache();
  4450. return tokenResponse;
  4451. }
  4452. catch (error) {
  4453. if (error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) {
  4454. return Promise.reject(error);
  4455. }
  4456. return new Promise((resolve, reject) => {
  4457. const resource = this.getActiveDirectoryResourceId();
  4458. this.authContext.acquireTokenWithClientCertificate(resource, this.clientId, this.certificate, this.thumbprint, (error, tokenResponse) => {
  4459. if (error) {
  4460. return reject(error);
  4461. }
  4462. if (tokenResponse.error || tokenResponse.errorDescription) {
  4463. return reject(tokenResponse);
  4464. }
  4465. return resolve(tokenResponse);
  4466. });
  4467. });
  4468. }
  4469. });
  4470. }
  4471. /**
  4472. * Creates a new instance of ApplicationTokenCertificateCredentials.
  4473. *
  4474. * @param clientId The active directory application client id also known as the SPN (ServicePrincipal Name).
  4475. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  4476. * for an example.
  4477. * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example:
  4478. * - CertificateString: "-----BEGIN PRIVATE KEY-----\n<xxxxx>\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n<yyyyy>\n-----END CERTIFICATE-----\n"
  4479. * - CertificateFilePath: **Absolute** file path of the .pem file.
  4480. * @param domain The domain or tenant id containing this application.
  4481. * @param options AzureTokenCredentialsOptions - Object representing optional parameters.
  4482. *
  4483. * @returns ApplicationTokenCertificateCredentials
  4484. */
  4485. static create(clientId, certificateStringOrFilePath, domain, options) {
  4486. if (!certificateStringOrFilePath ||
  4487. typeof certificateStringOrFilePath.valueOf() !== "string") {
  4488. throw new Error("'certificateStringOrFilePath' must be a non empty string.");
  4489. }
  4490. if (!certificateStringOrFilePath.startsWith("-----BEGIN")) {
  4491. certificateStringOrFilePath = fs_1.readFileSync(certificateStringOrFilePath, "utf8");
  4492. }
  4493. const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9\+\/\n\r]+\=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/;
  4494. const matchCert = certificateStringOrFilePath.match(certificatePattern);
  4495. const rawCertificate = matchCert ? matchCert[3] : "";
  4496. if (!rawCertificate) {
  4497. throw new Error("Unable to correctly parse the certificate from the value provided in 'certificateStringOrFilePath' ");
  4498. }
  4499. const thumbprint = crypto_1.createHash("sha1")
  4500. .update(Buffer.from(rawCertificate, "base64"))
  4501. .digest("hex");
  4502. return new ApplicationTokenCertificateCredentials(clientId, domain, certificateStringOrFilePath, thumbprint, options.tokenAudience, options.environment, options.tokenCache);
  4503. }
  4504. }
  4505. exports.ApplicationTokenCertificateCredentials = ApplicationTokenCertificateCredentials;
  4506. }).call(this)}).call(this,require("buffer").Buffer)
  4507. },{"../util/authConstants":18,"./applicationTokenCredentialsBase":6,"buffer":193,"crypto":208,"fs":190}],5:[function(require,module,exports){
  4508. "use strict";
  4509. // Copyright (c) Microsoft Corporation. All rights reserved.
  4510. // Licensed under the MIT License. See License.txt in the project root for license information.
  4511. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  4512. return new (P || (P = Promise))(function (resolve, reject) {
  4513. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4514. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4515. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  4516. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4517. });
  4518. };
  4519. Object.defineProperty(exports, "__esModule", { value: true });
  4520. const applicationTokenCredentialsBase_1 = require("./applicationTokenCredentialsBase");
  4521. const authConstants_1 = require("../util/authConstants");
  4522. class ApplicationTokenCredentials extends applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase {
  4523. /**
  4524. * Creates a new ApplicationTokenCredentials object.
  4525. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  4526. * for detailed instructions on creating an Azure Active Directory application.
  4527. * @constructor
  4528. * @param {string} clientId The active directory application client id.
  4529. * @param {string} domain The domain or tenant id containing this application.
  4530. * @param {string} secret The authentication secret for the application.
  4531. * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  4532. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  4533. * @param {Environment} [environment] The azure environment to authenticate with.
  4534. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  4535. */
  4536. constructor(clientId, domain, secret, tokenAudience, environment, tokenCache) {
  4537. if (!secret || typeof secret.valueOf() !== "string") {
  4538. throw new Error("secret must be a non empty string.");
  4539. }
  4540. super(clientId, domain, tokenAudience, environment, tokenCache);
  4541. this.secret = secret;
  4542. }
  4543. /**
  4544. * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.
  4545. * @returns {Promise<TokenResponse>} A promise that resolves to TokenResponse and rejects with an Error.
  4546. */
  4547. getToken() {
  4548. return __awaiter(this, void 0, void 0, function* () {
  4549. try {
  4550. const tokenResponse = yield this.getTokenFromCache();
  4551. return tokenResponse;
  4552. }
  4553. catch (error) {
  4554. if (error.message &&
  4555. error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) {
  4556. return Promise.reject(error);
  4557. }
  4558. const resource = this.getActiveDirectoryResourceId();
  4559. return new Promise((resolve, reject) => {
  4560. this.authContext.acquireTokenWithClientCredentials(resource, this.clientId, this.secret, (error, tokenResponse) => {
  4561. if (error) {
  4562. return reject(error);
  4563. }
  4564. if (tokenResponse.error || tokenResponse.errorDescription) {
  4565. return reject(tokenResponse);
  4566. }
  4567. return resolve(tokenResponse);
  4568. });
  4569. });
  4570. }
  4571. });
  4572. }
  4573. }
  4574. exports.ApplicationTokenCredentials = ApplicationTokenCredentials;
  4575. },{"../util/authConstants":18,"./applicationTokenCredentialsBase":6}],6:[function(require,module,exports){
  4576. "use strict";
  4577. // Copyright (c) Microsoft Corporation. All rights reserved.
  4578. // Licensed under the MIT License. See License.txt in the project root for license information.
  4579. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  4580. return new (P || (P = Promise))(function (resolve, reject) {
  4581. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4582. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4583. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  4584. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4585. });
  4586. };
  4587. Object.defineProperty(exports, "__esModule", { value: true });
  4588. const tokenCredentialsBase_1 = require("./tokenCredentialsBase");
  4589. const authConstants_1 = require("../util/authConstants");
  4590. class ApplicationTokenCredentialsBase extends tokenCredentialsBase_1.TokenCredentialsBase {
  4591. /**
  4592. * Creates a new ApplicationTokenCredentials object.
  4593. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  4594. * for detailed instructions on creating an Azure Active Directory application.
  4595. * @constructor
  4596. * @param {string} clientId The active directory application client id.
  4597. * @param {string} domain The domain or tenant id containing this application.
  4598. * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  4599. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  4600. * @param {Environment} [environment] The azure environment to authenticate with.
  4601. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  4602. */
  4603. constructor(clientId, domain, tokenAudience, environment, tokenCache) {
  4604. super(clientId, domain, tokenAudience, environment, tokenCache);
  4605. }
  4606. getTokenFromCache() {
  4607. const _super = Object.create(null, {
  4608. getTokenFromCache: { get: () => super.getTokenFromCache }
  4609. });
  4610. return __awaiter(this, void 0, void 0, function* () {
  4611. const self = this;
  4612. // a thin wrapper over the base implementation. try get token from cache, additionaly clean up cache if required.
  4613. try {
  4614. const tokenResponse = yield _super.getTokenFromCache.call(this, undefined);
  4615. return Promise.resolve(tokenResponse);
  4616. }
  4617. catch (error) {
  4618. // Remove the stale token from the tokencache. ADAL gives the same error message "Entry not found in cache."
  4619. // for entry not being present in the cache and for accessToken being expired in the cache. We do not want the token cache
  4620. // to contain the expired token, we clean it up here.
  4621. const status = yield self.removeInvalidItemsFromCache({
  4622. _clientId: self.clientId
  4623. });
  4624. if (status.result) {
  4625. return Promise.reject(error);
  4626. }
  4627. const message = status && status.details && status.details.message
  4628. ? status.details.message
  4629. : status.details;
  4630. return Promise.reject(new Error(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR +
  4631. " : " +
  4632. "critical failure while removing expired token for service principal from token cache. " +
  4633. message));
  4634. }
  4635. });
  4636. }
  4637. /**
  4638. * Removes invalid items from token cache. This method is different. Here we never reject in case of error.
  4639. * Rather we resolve with an object that says the result is false and error information is provided in
  4640. * the details property of the resolved object. This is done to do better error handling in the above function
  4641. * where removeInvalidItemsFromCache() is called.
  4642. * @param {object} query The query to be used for finding the token for service principal from the cache
  4643. * @returns {result: boolean, details?: Error} resultObject with more info.
  4644. */
  4645. removeInvalidItemsFromCache(query) {
  4646. const self = this;
  4647. return new Promise(resolve => {
  4648. self.tokenCache.find(query, (error, entries) => {
  4649. if (error) {
  4650. return resolve({ result: false, details: error });
  4651. }
  4652. if (entries && entries.length > 0) {
  4653. return new Promise(resolve => {
  4654. return self.tokenCache.remove(entries, (err) => {
  4655. if (err) {
  4656. return resolve({ result: false, details: err });
  4657. }
  4658. return resolve({ result: true });
  4659. });
  4660. });
  4661. }
  4662. else {
  4663. return resolve({ result: true });
  4664. }
  4665. });
  4666. });
  4667. }
  4668. }
  4669. exports.ApplicationTokenCredentialsBase = ApplicationTokenCredentialsBase;
  4670. },{"../util/authConstants":18,"./tokenCredentialsBase":13}],7:[function(require,module,exports){
  4671. (function (Buffer){(function (){
  4672. "use strict";
  4673. // Copyright (c) Microsoft Corporation. All rights reserved.
  4674. // Licensed under the MIT License. See License.txt in the project root for license information.
  4675. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  4676. return new (P || (P = Promise))(function (resolve, reject) {
  4677. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  4678. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  4679. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  4680. step((generator = generator.apply(thisArg, _arguments || [])).next());
  4681. });
  4682. };
  4683. Object.defineProperty(exports, "__esModule", { value: true });
  4684. const ms_rest_js_1 = require("@azure/ms-rest-js");
  4685. const login_1 = require("../login");
  4686. /**
  4687. * Describes the credentials by retrieving token via Azure CLI.
  4688. */
  4689. class AzureCliCredentials {
  4690. constructor(subscriptionInfo, tokenInfo,
  4691. // tslint:disable-next-line: no-inferrable-types
  4692. resource = "https://management.azure.com") {
  4693. /**
  4694. * Azure resource endpoints.
  4695. * - Defaults to Azure Resource Manager from environment: AzureCloud. "https://management.azure.com"
  4696. * - For Azure KeyVault: "https://vault.azure.net"
  4697. * - For Azure Batch: "https://batch.core.windows.net"
  4698. * - For Azure Active Directory Graph: "https://graph.windows.net"
  4699. *
  4700. * To get the resource for other clouds:
  4701. * - `az cloud list`
  4702. */
  4703. // tslint:disable-next-line: no-inferrable-types
  4704. this.resource = "https://management.azure.com";
  4705. /**
  4706. * The number of seconds within which it is good to renew the token.
  4707. * A constant set to 270 seconds (4.5 minutes).
  4708. */
  4709. this._tokenRenewalMarginInSeconds = 270;
  4710. this.subscriptionInfo = subscriptionInfo;
  4711. this.tokenInfo = tokenInfo;
  4712. this.resource = resource;
  4713. }
  4714. /**
  4715. * Tries to get the new token from Azure CLI, if the token has expired or the subscription has
  4716. * changed else uses the cached accessToken.
  4717. * @return The tokenResponse (tokenType and accessToken are the two important properties).
  4718. */
  4719. getToken() {
  4720. return __awaiter(this, void 0, void 0, function* () {
  4721. if (this._hasTokenExpired() || this._hasSubscriptionChanged() || this._hasResourceChanged()) {
  4722. try {
  4723. // refresh the access token
  4724. this.tokenInfo = yield AzureCliCredentials.getAccessToken({
  4725. subscriptionIdOrName: this.subscriptionInfo.id,
  4726. resource: this.resource
  4727. });
  4728. }
  4729. catch (err) {
  4730. throw new Error(`An error occurred while refreshing the new access ` +
  4731. `token:${err.stderr ? err.stderr : err.message}`);
  4732. }
  4733. }
  4734. const result = {
  4735. accessToken: this.tokenInfo.accessToken,
  4736. tokenType: this.tokenInfo.tokenType,
  4737. expiresOn: this.tokenInfo.expiresOn,
  4738. tenantId: this.tokenInfo.tenant
  4739. };
  4740. return result;
  4741. });
  4742. }
  4743. /**
  4744. * Signs a request with the Authentication header.
  4745. * @param The request to be signed.
  4746. */
  4747. signRequest(webResource) {
  4748. return __awaiter(this, void 0, void 0, function* () {
  4749. const tokenResponse = yield this.getToken();
  4750. webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`);
  4751. return Promise.resolve(webResource);
  4752. });
  4753. }
  4754. _hasTokenExpired() {
  4755. let result = true;
  4756. const now = Math.floor(Date.now() / 1000);
  4757. if (this.tokenInfo.expiresOn &&
  4758. this.tokenInfo.expiresOn instanceof Date &&
  4759. Math.floor(this.tokenInfo.expiresOn.getTime() / 1000) - now > this._tokenRenewalMarginInSeconds) {
  4760. result = false;
  4761. }
  4762. return result;
  4763. }
  4764. _hasSubscriptionChanged() {
  4765. return this.subscriptionInfo.id !== this.tokenInfo.subscription;
  4766. }
  4767. _parseToken() {
  4768. try {
  4769. const base64Url = this.tokenInfo.accessToken.split(".")[1];
  4770. const base64 = decodeURIComponent(Buffer.from(base64Url, "base64").toString("binary").split("").map((c) => {
  4771. return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
  4772. }).join(""));
  4773. return JSON.parse(base64);
  4774. }
  4775. catch (err) {
  4776. const msg = `An error occurred while parsing the access token: ${err.stack}`;
  4777. throw new Error(msg);
  4778. }
  4779. }
  4780. _isAzureResourceManagerEndpoint(newResource, currentResource) {
  4781. if (newResource.endsWith("/"))
  4782. newResource = newResource.slice(0, -1);
  4783. if (currentResource.endsWith("/"))
  4784. currentResource = currentResource.slice(0, -1);
  4785. return (newResource === "https://management.core.windows.net" &&
  4786. currentResource === "https://management.azure.com") ||
  4787. (newResource === "https://management.azure.com" &&
  4788. currentResource === "https://management.core.windows.net");
  4789. }
  4790. _hasResourceChanged() {
  4791. const parsedToken = this._parseToken();
  4792. // normalize the resource string, since it is possible to
  4793. // provide a resource without a trailing slash
  4794. const currentResource = parsedToken.aud && parsedToken.aud.endsWith("/")
  4795. ? parsedToken.aud.slice(0, -1)
  4796. : parsedToken.aud;
  4797. const newResource = this.resource.endsWith("/")
  4798. ? this.resource.slice(0, -1)
  4799. : this.resource;
  4800. const result = this._isAzureResourceManagerEndpoint(newResource, currentResource)
  4801. ? false
  4802. : currentResource !== newResource;
  4803. return result;
  4804. }
  4805. /**
  4806. * Gets the access token for the default or specified subscription.
  4807. * @param options Optional parameters that can be provided to get the access token.
  4808. */
  4809. static getAccessToken(options = {}) {
  4810. return __awaiter(this, void 0, void 0, function* () {
  4811. try {
  4812. let cmd = "account get-access-token";
  4813. if (options.subscriptionIdOrName) {
  4814. cmd += ` -s "${options.subscriptionIdOrName}"`;
  4815. }
  4816. if (options.resource) {
  4817. cmd += ` --resource ${options.resource}`;
  4818. }
  4819. const result = yield login_1.execAz(cmd);
  4820. result.expiresOn = new Date(result.expiresOn);
  4821. return result;
  4822. }
  4823. catch (err) {
  4824. const message = `An error occurred while getting credentials from ` +
  4825. `Azure CLI: ${err.stack}`;
  4826. throw new Error(message);
  4827. }
  4828. });
  4829. }
  4830. /**
  4831. * Gets the subscription from Azure CLI.
  4832. * @param subscriptionIdOrName - The name or id of the subscription for which the information is
  4833. * required.
  4834. */
  4835. static getSubscription(subscriptionIdOrName) {
  4836. return __awaiter(this, void 0, void 0, function* () {
  4837. if (subscriptionIdOrName && (typeof subscriptionIdOrName !== "string" || !subscriptionIdOrName.length)) {
  4838. throw new Error("'subscriptionIdOrName' must be a non-empty string.");
  4839. }
  4840. try {
  4841. let cmd = "account show";
  4842. if (subscriptionIdOrName) {
  4843. cmd += ` -s "${subscriptionIdOrName}"`;
  4844. }
  4845. const result = yield login_1.execAz(cmd);
  4846. return result;
  4847. }
  4848. catch (err) {
  4849. const message = `An error occurred while getting information about the current subscription from ` +
  4850. `Azure CLI: ${err.stack}`;
  4851. throw new Error(message);
  4852. }
  4853. });
  4854. }
  4855. /**
  4856. * Sets the specified subscription as the default subscription for Azure CLI.
  4857. * @param subscriptionIdOrName The name or id of the subsciption that needs to be set as the
  4858. * default subscription.
  4859. */
  4860. static setDefaultSubscription(subscriptionIdOrName) {
  4861. return __awaiter(this, void 0, void 0, function* () {
  4862. try {
  4863. yield login_1.execAz(`account set -s ${subscriptionIdOrName}`);
  4864. }
  4865. catch (err) {
  4866. const message = `An error occurred while setting the current subscription from ` +
  4867. `Azure CLI: ${err.stack}`;
  4868. throw new Error(message);
  4869. }
  4870. });
  4871. }
  4872. /**
  4873. * Returns a list of all the subscriptions from Azure CLI.
  4874. * @param options Optional parameters that can be provided while listing all the subcriptions.
  4875. */
  4876. static listAllSubscriptions(options = {}) {
  4877. return __awaiter(this, void 0, void 0, function* () {
  4878. let subscriptionList = [];
  4879. try {
  4880. let cmd = "account list";
  4881. if (options.all) {
  4882. cmd += " --all";
  4883. }
  4884. if (options.refresh) {
  4885. cmd += "--refresh";
  4886. }
  4887. subscriptionList = yield login_1.execAz(cmd);
  4888. if (subscriptionList && subscriptionList.length) {
  4889. for (const sub of subscriptionList) {
  4890. if (sub.cloudName) {
  4891. sub.environmentName = sub.cloudName;
  4892. delete sub.cloudName;
  4893. }
  4894. }
  4895. }
  4896. return subscriptionList;
  4897. }
  4898. catch (err) {
  4899. const message = `An error occurred while getting a list of all the subscription from ` +
  4900. `Azure CLI: ${err.stack}`;
  4901. throw new Error(message);
  4902. }
  4903. });
  4904. }
  4905. /**
  4906. * Provides credentials that can be used by the JS SDK to interact with Azure via azure cli.
  4907. * **Pre-requisite**
  4908. * - **install azure-cli** . For more information see
  4909. * {@link https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest Install Azure CLI}
  4910. * - **login via `az login`**
  4911. * @param options - Optional parameters that can be provided while creating AzureCliCredentials.
  4912. */
  4913. static create(options = {}) {
  4914. return __awaiter(this, void 0, void 0, function* () {
  4915. const [subscriptinInfo, accessToken] = yield Promise.all([
  4916. AzureCliCredentials.getSubscription(options.subscriptionIdOrName),
  4917. AzureCliCredentials.getAccessToken(options)
  4918. ]);
  4919. return new AzureCliCredentials(subscriptinInfo, accessToken, options.resource);
  4920. });
  4921. }
  4922. }
  4923. exports.AzureCliCredentials = AzureCliCredentials;
  4924. }).call(this)}).call(this,require("buffer").Buffer)
  4925. },{"../login":15,"@azure/ms-rest-js":2,"buffer":193}],8:[function(require,module,exports){
  4926. "use strict";
  4927. // Copyright (c) Microsoft Corporation. All rights reserved.
  4928. // Licensed under the MIT License. See License.txt in the project root for license information.
  4929. Object.defineProperty(exports, "__esModule", { value: true });
  4930. const tokenCredentialsBase_1 = require("./tokenCredentialsBase");
  4931. const authConstants_1 = require("../util/authConstants");
  4932. class DeviceTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase {
  4933. /**
  4934. * Creates a new DeviceTokenCredentials object that gets a new access token using userCodeInfo (contains user_code, device_code)
  4935. * for authenticating user on device.
  4936. *
  4937. * When this credential is used, the script will provide a url and code. The user needs to copy the url and the code, paste it
  4938. * in a browser and authenticate over there. If successful, the script will get the access token.
  4939. *
  4940. * @constructor
  4941. * @param {string} [clientId] The active directory application client id.
  4942. * @param {string} [domain] The domain or tenant id containing this application. Default value is "common"
  4943. * @param {string} [username] The user name for account in the form: "user@example.com".
  4944. * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  4945. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  4946. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  4947. * for an example.
  4948. * @param {Environment} [environment] The azure environment to authenticate with. Default environment is "Azure" popularly known as "Public Azure Cloud".
  4949. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  4950. */
  4951. constructor(clientId, domain, username, tokenAudience, environment, tokenCache) {
  4952. if (!username) {
  4953. username = "user@example.com";
  4954. }
  4955. if (!domain) {
  4956. domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT;
  4957. }
  4958. if (!clientId) {
  4959. clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID;
  4960. }
  4961. super(clientId, domain, tokenAudience, environment, tokenCache);
  4962. this.username = username;
  4963. }
  4964. getToken() {
  4965. // For device auth, this is just getTokenFromCache.
  4966. return this.getTokenFromCache(this.username);
  4967. }
  4968. }
  4969. exports.DeviceTokenCredentials = DeviceTokenCredentials;
  4970. },{"../util/authConstants":18,"./tokenCredentialsBase":13}],9:[function(require,module,exports){
  4971. "use strict";
  4972. // Copyright (c) Microsoft Corporation. All rights reserved.
  4973. // Licensed under the MIT License. See License.txt in the project root for license information.
  4974. Object.defineProperty(exports, "__esModule", { value: true });
  4975. const applicationTokenCredentials_1 = require("./applicationTokenCredentials");
  4976. const applicationTokenCertificateCredentials_1 = require("./applicationTokenCertificateCredentials");
  4977. const deviceTokenCredentials_1 = require("./deviceTokenCredentials");
  4978. const msiAppServiceTokenCredentials_1 = require("./msiAppServiceTokenCredentials");
  4979. const msiTokenCredentials_1 = require("./msiTokenCredentials");
  4980. const msiVmTokenCredentials_1 = require("./msiVmTokenCredentials");
  4981. const tokenCredentialsBase_1 = require("./tokenCredentialsBase");
  4982. const userTokenCredentials_1 = require("./userTokenCredentials");
  4983. const adal_node_1 = require("adal-node");
  4984. function createAuthenticator(credentials) {
  4985. const convertedCredentials = _convert(credentials);
  4986. const authenticator = _createAuthenticatorMapper(convertedCredentials);
  4987. return authenticator;
  4988. }
  4989. exports.createAuthenticator = createAuthenticator;
  4990. function _convert(credentials) {
  4991. if (credentials instanceof msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials) {
  4992. return new msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials({
  4993. msiEndpoint: credentials.msiEndpoint,
  4994. msiSecret: credentials.msiSecret,
  4995. msiApiVersion: credentials.msiApiVersion,
  4996. resource: credentials.resource
  4997. });
  4998. }
  4999. else if (credentials instanceof msiVmTokenCredentials_1.MSIVmTokenCredentials) {
  5000. return new msiVmTokenCredentials_1.MSIVmTokenCredentials({
  5001. resource: credentials.resource,
  5002. msiEndpoint: credentials.msiEndpoint
  5003. });
  5004. }
  5005. else if (credentials instanceof msiTokenCredentials_1.MSITokenCredentials) {
  5006. throw new Error("MSI-credentials not one of: MSIVmTokenCredentials, MSIAppServiceTokenCredentials");
  5007. }
  5008. else {
  5009. return credentials;
  5010. }
  5011. }
  5012. function _createAuthenticatorMapper(credentials) {
  5013. return (challenge) => new Promise((resolve, reject) => {
  5014. // Function to take token Response and format a authorization value
  5015. const _formAuthorizationValue = (err, tokenResponse) => {
  5016. if (err) {
  5017. return reject(err);
  5018. }
  5019. if (tokenResponse.error) {
  5020. return reject(tokenResponse.error);
  5021. }
  5022. tokenResponse = tokenResponse;
  5023. // Calculate the value to be set in the request's Authorization header and resume the call.
  5024. const authorizationValue = tokenResponse.tokenType + " " + tokenResponse.accessToken;
  5025. return resolve(authorizationValue);
  5026. };
  5027. // Create a new authentication context.
  5028. if (credentials instanceof tokenCredentialsBase_1.TokenCredentialsBase) {
  5029. const context = new adal_node_1.AuthenticationContext(challenge.authorization, true, credentials.authContext && credentials.authContext.cache);
  5030. if (credentials instanceof applicationTokenCredentials_1.ApplicationTokenCredentials) {
  5031. return context.acquireTokenWithClientCredentials(challenge.resource, credentials.clientId, credentials.secret, _formAuthorizationValue);
  5032. }
  5033. else if (credentials instanceof applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials) {
  5034. return context.acquireTokenWithClientCertificate(challenge.resource, credentials.clientId, credentials.certificate, credentials.thumbprint, _formAuthorizationValue);
  5035. }
  5036. else if (credentials instanceof userTokenCredentials_1.UserTokenCredentials) {
  5037. return context.acquireTokenWithUsernamePassword(challenge.resource, credentials.username, credentials.password, credentials.clientId, _formAuthorizationValue);
  5038. }
  5039. else if (credentials instanceof deviceTokenCredentials_1.DeviceTokenCredentials) {
  5040. return context.acquireToken(challenge.resource, credentials.username, credentials.clientId, _formAuthorizationValue);
  5041. }
  5042. }
  5043. else if (credentials instanceof msiTokenCredentials_1.MSITokenCredentials) {
  5044. return credentials.getToken();
  5045. }
  5046. else {
  5047. return reject(new Error("credentials must be one of: ApplicationTokenCredentials, UserTokenCredentials, " +
  5048. "DeviceTokenCredentials, MSITokenCredentials"));
  5049. }
  5050. });
  5051. }
  5052. },{"./applicationTokenCertificateCredentials":4,"./applicationTokenCredentials":5,"./deviceTokenCredentials":8,"./msiAppServiceTokenCredentials":10,"./msiTokenCredentials":11,"./msiVmTokenCredentials":12,"./tokenCredentialsBase":13,"./userTokenCredentials":14,"adal-node":19}],10:[function(require,module,exports){
  5053. (function (process){(function (){
  5054. "use strict";
  5055. // Copyright (c) Microsoft Corporation. All rights reserved.
  5056. // Licensed under the MIT License. See License.txt in the project root for license information.
  5057. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5058. return new (P || (P = Promise))(function (resolve, reject) {
  5059. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5060. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5061. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  5062. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5063. });
  5064. };
  5065. Object.defineProperty(exports, "__esModule", { value: true });
  5066. const msiTokenCredentials_1 = require("./msiTokenCredentials");
  5067. const ms_rest_js_1 = require("@azure/ms-rest-js");
  5068. /**
  5069. * @class MSIAppServiceTokenCredentials
  5070. */
  5071. class MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials {
  5072. /**
  5073. * Creates an instance of MSIAppServiceTokenCredentials.
  5074. * @param {string} [options.msiEndpoint] - The local URL from which your app can request tokens.
  5075. * Either provide this parameter or set the environment variable `MSI_ENDPOINT`.
  5076. * For example: `MSI_ENDPOINT="http://127.0.0.1:41741/MSI/token/"`
  5077. * @param {string} [options.msiSecret] - The secret used in communication between your code and the local MSI agent.
  5078. * Either provide this parameter or set the environment variable `MSI_SECRET`.
  5079. * For example: `MSI_SECRET="69418689F1E342DD946CB82994CDA3CB"`
  5080. * @param {string} [options.resource] - The resource uri or token audience for which the token is needed.
  5081. * For e.g. it can be:
  5082. * - resource management endpoint "https://management.azure.com/" (default)
  5083. * - management endpoint "https://management.core.windows.net/"
  5084. * @param {string} [options.msiApiVersion] - The api-version of the local MSI agent. Default value is "2017-09-01".
  5085. */
  5086. constructor(options) {
  5087. if (!options)
  5088. options = {};
  5089. super(options);
  5090. options.msiEndpoint = options.msiEndpoint || process.env["MSI_ENDPOINT"];
  5091. options.msiSecret = options.msiSecret || process.env["MSI_SECRET"];
  5092. if (!options.msiEndpoint || (options.msiEndpoint && typeof options.msiEndpoint.valueOf() !== "string")) {
  5093. throw new Error('Either provide "msiEndpoint" as a property of the "options" object ' +
  5094. 'or set the environment variable "MSI_ENDPOINT" and it must be of type "string".');
  5095. }
  5096. if (!options.msiSecret || (options.msiSecret && typeof options.msiSecret.valueOf() !== "string")) {
  5097. throw new Error('Either provide "msiSecret" as a property of the "options" object ' +
  5098. 'or set the environment variable "MSI_SECRET" and it must be of type "string".');
  5099. }
  5100. if (!options.msiApiVersion) {
  5101. options.msiApiVersion = "2017-09-01";
  5102. }
  5103. else if (typeof options.msiApiVersion.valueOf() !== "string") {
  5104. throw new Error("msiApiVersion must be a uri.");
  5105. }
  5106. this.msiEndpoint = options.msiEndpoint;
  5107. this.msiSecret = options.msiSecret;
  5108. this.msiApiVersion = options.msiApiVersion;
  5109. }
  5110. /**
  5111. * Prepares and sends a GET request to a service endpoint indicated by the app service, which responds with the access token.
  5112. * @return {Promise<MSITokenResponse>} Promise with the tokenResponse (tokenType and accessToken are the two important properties).
  5113. */
  5114. getToken() {
  5115. return __awaiter(this, void 0, void 0, function* () {
  5116. const reqOptions = this.prepareRequestOptions();
  5117. let opRes;
  5118. let result;
  5119. opRes = yield this._httpClient.sendRequest(reqOptions);
  5120. if (opRes.bodyAsText === undefined || opRes.bodyAsText.indexOf("ExceptionMessage") !== -1) {
  5121. throw new Error(`MSI: Failed to retrieve a token from "${reqOptions.url}" with an error: ${opRes.bodyAsText}`);
  5122. }
  5123. result = this.parseTokenResponse(opRes.bodyAsText);
  5124. if (!result.tokenType) {
  5125. throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`);
  5126. }
  5127. else if (!result.accessToken) {
  5128. throw new Error(`Invalid token response, did not find accessToken. Response body is: ${opRes.bodyAsText}`);
  5129. }
  5130. return result;
  5131. });
  5132. }
  5133. prepareRequestOptions() {
  5134. const endpoint = this.msiEndpoint.endsWith("/") ? this.msiEndpoint : `${this.msiEndpoint}/`;
  5135. const resource = encodeURIComponent(this.resource);
  5136. const getUrl = `${endpoint}?resource=${resource}&api-version=${this.msiApiVersion}`;
  5137. const reqOptions = {
  5138. url: getUrl,
  5139. headers: {
  5140. "secret": this.msiSecret
  5141. },
  5142. method: "GET"
  5143. };
  5144. const webResource = new ms_rest_js_1.WebResource();
  5145. return webResource.prepare(reqOptions);
  5146. }
  5147. }
  5148. exports.MSIAppServiceTokenCredentials = MSIAppServiceTokenCredentials;
  5149. }).call(this)}).call(this,require('_process'))
  5150. },{"./msiTokenCredentials":11,"@azure/ms-rest-js":2,"_process":525}],11:[function(require,module,exports){
  5151. "use strict";
  5152. // Copyright (c) Microsoft Corporation. All rights reserved.
  5153. // Licensed under the MIT License. See License.txt in the project root for license information.
  5154. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5155. return new (P || (P = Promise))(function (resolve, reject) {
  5156. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5157. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5158. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  5159. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5160. });
  5161. };
  5162. Object.defineProperty(exports, "__esModule", { value: true });
  5163. const ms_rest_js_1 = require("@azure/ms-rest-js");
  5164. const authConstants_1 = require("../util/authConstants");
  5165. /**
  5166. * @class MSITokenCredentials - Provides information about managed service identity token credentials.
  5167. * This object can only be used to acquire token on a virtual machine provisioned in Azure with managed service identity.
  5168. */
  5169. class MSITokenCredentials {
  5170. /**
  5171. * Creates an instance of MSITokenCredentials.
  5172. * @param {object} [options] - Optional parameters
  5173. * @param {string} [options.resource] - The resource uri or token audience for which the token is needed.
  5174. * For e.g. it can be:
  5175. * - resource management endpoint "https://management.azure.com/"(default)
  5176. * - management endpoint "https://management.core.windows.net/"
  5177. */
  5178. constructor(options) {
  5179. if (!options)
  5180. options = {};
  5181. if (!options.resource) {
  5182. options.resource = authConstants_1.AuthConstants.RESOURCE_MANAGER_ENDPOINT;
  5183. }
  5184. else if (typeof options.resource.valueOf() !== "string") {
  5185. throw new Error("resource must be a uri.");
  5186. }
  5187. this.resource = options.resource;
  5188. this._httpClient = options.httpClient || new ms_rest_js_1.DefaultHttpClient();
  5189. }
  5190. /**
  5191. * Parses a tokenResponse json string into a object, and converts properties on the first level to camelCase.
  5192. * This method tries to standardize the tokenResponse
  5193. * @param {string} body A json string
  5194. * @return {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties).
  5195. */
  5196. parseTokenResponse(body) {
  5197. // Docs show different examples of possible MSI responses for different services. https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/overview
  5198. // expires_on - is a Date like string in this doc
  5199. // - https://docs.microsoft.com/en-us/azure/app-service/app-service-managed-service-identity#rest-protocol-examples
  5200. // In other doc it is stringified number.
  5201. // - https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/tutorial-linux-vm-access-arm#get-an-access-token-using-the-vms-identity-and-use-it-to-call-resource-manager
  5202. const parsedBody = JSON.parse(body);
  5203. parsedBody.accessToken = parsedBody["access_token"];
  5204. delete parsedBody["access_token"];
  5205. parsedBody.tokenType = parsedBody["token_type"];
  5206. delete parsedBody["token_type"];
  5207. if (parsedBody["refresh_token"]) {
  5208. parsedBody.refreshToken = parsedBody["refresh_token"];
  5209. delete parsedBody["refresh_token"];
  5210. }
  5211. if (parsedBody["expires_in"]) {
  5212. parsedBody.expiresIn = parsedBody["expires_in"];
  5213. if (typeof parsedBody["expires_in"] === "string") {
  5214. // normal number as a string '1504130527'
  5215. parsedBody.expiresIn = parseInt(parsedBody["expires_in"], 10);
  5216. }
  5217. delete parsedBody["expires_in"];
  5218. }
  5219. if (parsedBody["not_before"]) {
  5220. parsedBody.notBefore = parsedBody["not_before"];
  5221. if (typeof parsedBody["not_before"] === "string") {
  5222. // normal number as a string '1504130527'
  5223. parsedBody.notBefore = parseInt(parsedBody["not_before"], 10);
  5224. }
  5225. delete parsedBody["not_before"];
  5226. }
  5227. if (parsedBody["expires_on"]) {
  5228. parsedBody.expiresOn = parsedBody["expires_on"];
  5229. if (typeof parsedBody["expires_on"] === "string") {
  5230. // possibly a Date string '09/14/2017 00:00:00 PM +00:00'
  5231. if (parsedBody["expires_on"].includes(":") || parsedBody["expires_on"].includes("/")) {
  5232. parsedBody.expiresOn = new Date(parsedBody["expires_on"], 10);
  5233. }
  5234. else {
  5235. // normal number as a string '1504130527'
  5236. parsedBody.expiresOn = new Date(parseInt(parsedBody["expires_on"], 10));
  5237. }
  5238. }
  5239. delete parsedBody["expires_on"];
  5240. }
  5241. return parsedBody;
  5242. }
  5243. /**
  5244. * Signs a request with the Authentication header.
  5245. *
  5246. * @param {webResource} The WebResource to be signed.
  5247. * @return {Promise<WebResource>} Promise with signed WebResource.
  5248. */
  5249. signRequest(webResource) {
  5250. return __awaiter(this, void 0, void 0, function* () {
  5251. const tokenResponse = yield this.getToken();
  5252. webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`);
  5253. return Promise.resolve(webResource);
  5254. });
  5255. }
  5256. }
  5257. exports.MSITokenCredentials = MSITokenCredentials;
  5258. },{"../util/authConstants":18,"@azure/ms-rest-js":2}],12:[function(require,module,exports){
  5259. "use strict";
  5260. // Copyright (c) Microsoft Corporation. All rights reserved.
  5261. // Licensed under the MIT License. See License.txt in the project root for license information.
  5262. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5263. return new (P || (P = Promise))(function (resolve, reject) {
  5264. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5265. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5266. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  5267. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5268. });
  5269. };
  5270. Object.defineProperty(exports, "__esModule", { value: true });
  5271. const msiTokenCredentials_1 = require("./msiTokenCredentials");
  5272. const ms_rest_js_1 = require("@azure/ms-rest-js");
  5273. /**
  5274. * @class MSIVmTokenCredentials
  5275. */
  5276. class MSIVmTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials {
  5277. constructor(options) {
  5278. if (!options)
  5279. options = {};
  5280. super(options);
  5281. if (!options.msiEndpoint) {
  5282. options.msiEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token";
  5283. }
  5284. else if (typeof options.msiEndpoint !== "string") {
  5285. throw new Error("msiEndpoint must be a string.");
  5286. }
  5287. const urlBuilder = ms_rest_js_1.URLBuilder.parse(options.msiEndpoint);
  5288. if (!urlBuilder.getScheme()) {
  5289. options.msiEndpoint = `http://${options.msiEndpoint}`;
  5290. }
  5291. if (!options.apiVersion) {
  5292. options.apiVersion = "2018-02-01";
  5293. }
  5294. else if (typeof options.apiVersion !== "string") {
  5295. throw new Error("apiVersion must be a string.");
  5296. }
  5297. if (!options.httpMethod) {
  5298. options.httpMethod = "GET";
  5299. }
  5300. this.apiVersion = options.apiVersion;
  5301. this.msiEndpoint = options.msiEndpoint;
  5302. this.httpMethod = options.httpMethod;
  5303. this.objectId = options.objectId;
  5304. this.clientId = options.clientId;
  5305. this.identityId = options.identityId;
  5306. }
  5307. /**
  5308. * Prepares and sends a POST request to a service endpoint hosted on the Azure VM, which responds with the access token.
  5309. * @return {Promise<MSITokenResponse>} Promise with the tokenResponse (tokenType and accessToken are the two important properties).
  5310. */
  5311. getToken() {
  5312. return __awaiter(this, void 0, void 0, function* () {
  5313. const reqOptions = this.prepareRequestOptions();
  5314. let opRes;
  5315. let result;
  5316. opRes = yield this._httpClient.sendRequest(reqOptions);
  5317. result = this.parseTokenResponse(opRes.bodyAsText);
  5318. if (!result.tokenType) {
  5319. throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`);
  5320. }
  5321. else if (!result.accessToken) {
  5322. throw new Error(`Invalid token response, did not find accessToken. Response body is: ${opRes.bodyAsText}`);
  5323. }
  5324. return result;
  5325. });
  5326. }
  5327. prepareRequestOptions() {
  5328. const reqOptions = {
  5329. url: this.msiEndpoint,
  5330. headers: {
  5331. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
  5332. "Metadata": "true"
  5333. },
  5334. method: this.httpMethod,
  5335. queryParameters: {
  5336. "api-version": this.apiVersion,
  5337. "resource": this.resource,
  5338. "object_id": this.objectId,
  5339. "client_id": this.clientId,
  5340. "mi_res_id": this.identityId
  5341. }
  5342. };
  5343. const webResource = new ms_rest_js_1.WebResource();
  5344. return webResource.prepare(reqOptions);
  5345. }
  5346. }
  5347. exports.MSIVmTokenCredentials = MSIVmTokenCredentials;
  5348. },{"./msiTokenCredentials":11,"@azure/ms-rest-js":2}],13:[function(require,module,exports){
  5349. "use strict";
  5350. // Copyright (c) Microsoft Corporation. All rights reserved.
  5351. // Licensed under the MIT License. See License.txt in the project root for license information.
  5352. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5353. return new (P || (P = Promise))(function (resolve, reject) {
  5354. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5355. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5356. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  5357. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5358. });
  5359. };
  5360. Object.defineProperty(exports, "__esModule", { value: true });
  5361. const ms_rest_js_1 = require("@azure/ms-rest-js");
  5362. const ms_rest_azure_env_1 = require("@azure/ms-rest-azure-env");
  5363. const adal_node_1 = require("adal-node");
  5364. class TokenCredentialsBase {
  5365. constructor(clientId, domain, tokenAudience, environment = ms_rest_azure_env_1.Environment.AzureCloud, tokenCache = new adal_node_1.MemoryCache()) {
  5366. this.clientId = clientId;
  5367. this.domain = domain;
  5368. this.tokenAudience = tokenAudience;
  5369. this.environment = environment;
  5370. this.tokenCache = tokenCache;
  5371. if (!clientId || typeof clientId.valueOf() !== "string") {
  5372. throw new Error("clientId must be a non empty string.");
  5373. }
  5374. if (!domain || typeof domain.valueOf() !== "string") {
  5375. throw new Error("domain must be a non empty string.");
  5376. }
  5377. if (this.tokenAudience === "graph" && this.domain.toLowerCase() === "common") {
  5378. throw new Error(`${"If the tokenAudience is specified as \"graph\" then \"domain\" cannot be defaulted to \"commmon\" tenant.\
  5379. It must be the actual tenant (preferrably a string in a guid format)."}`);
  5380. }
  5381. const authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain;
  5382. this.authContext = new adal_node_1.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache);
  5383. }
  5384. getActiveDirectoryResourceId() {
  5385. let resource = this.environment.activeDirectoryResourceId;
  5386. if (this.tokenAudience) {
  5387. resource = this.tokenAudience;
  5388. if (this.tokenAudience.toLowerCase() === "graph") {
  5389. resource = this.environment.activeDirectoryGraphResourceId;
  5390. }
  5391. else if (this.tokenAudience.toLowerCase() === "batch") {
  5392. resource = this.environment.batchResourceId;
  5393. }
  5394. }
  5395. return resource;
  5396. }
  5397. getTokenFromCache(username) {
  5398. const self = this;
  5399. const resource = this.getActiveDirectoryResourceId();
  5400. return new Promise((resolve, reject) => {
  5401. self.authContext.acquireToken(resource, username, self.clientId, (error, tokenResponse) => {
  5402. if (error) {
  5403. return reject(error);
  5404. }
  5405. if (tokenResponse.error || tokenResponse.errorDescription) {
  5406. return reject(tokenResponse);
  5407. }
  5408. return resolve(tokenResponse);
  5409. });
  5410. });
  5411. }
  5412. /**
  5413. * Signs a request with the Authentication header.
  5414. *
  5415. * @param {webResource} The WebResource to be signed.
  5416. * @param {function(error)} callback The callback function.
  5417. * @return {undefined}
  5418. */
  5419. signRequest(webResource) {
  5420. return __awaiter(this, void 0, void 0, function* () {
  5421. const tokenResponse = yield this.getToken();
  5422. webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`);
  5423. return Promise.resolve(webResource);
  5424. });
  5425. }
  5426. }
  5427. exports.TokenCredentialsBase = TokenCredentialsBase;
  5428. },{"@azure/ms-rest-azure-env":1,"@azure/ms-rest-js":2,"adal-node":19}],14:[function(require,module,exports){
  5429. "use strict";
  5430. // Copyright (c) Microsoft Corporation. All rights reserved.
  5431. // Licensed under the MIT License. See License.txt in the project root for license information.
  5432. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5433. return new (P || (P = Promise))(function (resolve, reject) {
  5434. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5435. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5436. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  5437. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5438. });
  5439. };
  5440. Object.defineProperty(exports, "__esModule", { value: true });
  5441. const tokenCredentialsBase_1 = require("./tokenCredentialsBase");
  5442. class UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase {
  5443. /**
  5444. * Creates a new UserTokenCredentials object.
  5445. *
  5446. * @constructor
  5447. * @param {string} clientId The active directory application client id.
  5448. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  5449. * for an example.
  5450. * @param {string} domain The domain or tenant id containing this application.
  5451. * @param {string} username The user name for the Organization Id account.
  5452. * @param {string} password The password for the Organization Id account.
  5453. * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  5454. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  5455. * @param {Environment} [environment] The azure environment to authenticate with.
  5456. * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.
  5457. */
  5458. constructor(clientId, domain, username, password, tokenAudience, environment, tokenCache) {
  5459. if (!clientId || typeof clientId.valueOf() !== "string") {
  5460. throw new Error("clientId must be a non empty string.");
  5461. }
  5462. if (!domain || typeof domain.valueOf() !== "string") {
  5463. throw new Error("domain must be a non empty string.");
  5464. }
  5465. if (!username || typeof username.valueOf() !== "string") {
  5466. throw new Error("username must be a non empty string.");
  5467. }
  5468. if (!password || typeof password.valueOf() !== "string") {
  5469. throw new Error("password must be a non empty string.");
  5470. }
  5471. super(clientId, domain, tokenAudience, environment, tokenCache);
  5472. this.username = username;
  5473. this.password = password;
  5474. }
  5475. crossCheckUserNameWithToken(username, userIdFromToken) {
  5476. // to maintain the casing consistency between "azureprofile.json" and token cache. (RD 1996587)
  5477. // use the "userId" here, which should be the same with "username" except the casing.
  5478. return (username.toLowerCase() === userIdFromToken.toLowerCase());
  5479. }
  5480. /**
  5481. * Tries to get the token from cache initially. If that is unsuccessful then it tries to get the token from ADAL.
  5482. * @returns {Promise<TokenResponse>}
  5483. * {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties).
  5484. * @memberof UserTokenCredentials
  5485. */
  5486. getToken() {
  5487. return __awaiter(this, void 0, void 0, function* () {
  5488. try {
  5489. return yield this.getTokenFromCache(this.username);
  5490. }
  5491. catch (error) {
  5492. const self = this;
  5493. const resource = this.getActiveDirectoryResourceId();
  5494. return new Promise((resolve, reject) => {
  5495. self.authContext.acquireTokenWithUsernamePassword(resource, self.username, self.password, self.clientId, (error, tokenResponse) => {
  5496. if (error) {
  5497. return reject(error);
  5498. }
  5499. if (tokenResponse.error || tokenResponse.errorDescription) {
  5500. return reject(tokenResponse);
  5501. }
  5502. tokenResponse = tokenResponse;
  5503. if (self.crossCheckUserNameWithToken(self.username, tokenResponse.userId)) {
  5504. return resolve(tokenResponse);
  5505. }
  5506. else {
  5507. return reject(`The userId "${tokenResponse.userId}" in access token doesn"t match the username "${self.username}" provided during authentication.`);
  5508. }
  5509. });
  5510. });
  5511. }
  5512. });
  5513. }
  5514. }
  5515. exports.UserTokenCredentials = UserTokenCredentials;
  5516. },{"./tokenCredentialsBase":13}],15:[function(require,module,exports){
  5517. (function (process){(function (){
  5518. "use strict";
  5519. // Copyright (c) Microsoft Corporation. All rights reserved.
  5520. // Licensed under the MIT License. See License.txt in the project root for license information.
  5521. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  5522. return new (P || (P = Promise))(function (resolve, reject) {
  5523. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  5524. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  5525. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  5526. step((generator = generator.apply(thisArg, _arguments || [])).next());
  5527. });
  5528. };
  5529. Object.defineProperty(exports, "__esModule", { value: true });
  5530. const adal = require("adal-node");
  5531. const msRest = require("@azure/ms-rest-js");
  5532. const child_process_1 = require("child_process");
  5533. const fs_1 = require("fs");
  5534. const ms_rest_azure_env_1 = require("@azure/ms-rest-azure-env");
  5535. const applicationTokenCredentials_1 = require("./credentials/applicationTokenCredentials");
  5536. const applicationTokenCertificateCredentials_1 = require("./credentials/applicationTokenCertificateCredentials");
  5537. const deviceTokenCredentials_1 = require("./credentials/deviceTokenCredentials");
  5538. const userTokenCredentials_1 = require("./credentials/userTokenCredentials");
  5539. const authConstants_1 = require("./util/authConstants");
  5540. const subscriptionUtils_1 = require("./subscriptionManagement/subscriptionUtils");
  5541. const msiVmTokenCredentials_1 = require("./credentials/msiVmTokenCredentials");
  5542. const msiAppServiceTokenCredentials_1 = require("./credentials/msiAppServiceTokenCredentials");
  5543. /**
  5544. * @constant {Array<string>} managementPlaneTokenAudiences - Urls for management plane token
  5545. * audience across different azure environments.
  5546. */
  5547. const managementPlaneTokenAudiences = [
  5548. "https://management.core.windows.net/",
  5549. "https://management.core.chinacloudapi.cn/",
  5550. "https://management.core.usgovcloudapi.net/",
  5551. "https://management.core.cloudapi.de/",
  5552. "https://management.azure.com/",
  5553. "https://management.core.windows.net",
  5554. "https://management.core.chinacloudapi.cn",
  5555. "https://management.core.usgovcloudapi.net",
  5556. "https://management.core.cloudapi.de",
  5557. "https://management.azure.com"
  5558. ];
  5559. function turnOnLogging() {
  5560. const log = adal.Logging;
  5561. log.setLoggingOptions({
  5562. level: 3,
  5563. log: function (level, message, error) {
  5564. level;
  5565. console.info(message);
  5566. if (error) {
  5567. console.error(error);
  5568. }
  5569. }
  5570. });
  5571. }
  5572. if (process.env["AZURE_ADAL_LOGGING_ENABLED"]) {
  5573. turnOnLogging();
  5574. }
  5575. /**
  5576. * Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
  5577. * This method is applicable only for organizational ids that are not 2FA enabled otherwise please use interactive login.
  5578. *
  5579. * @param {string} username The user name for the Organization Id account.
  5580. * @param {string} password The password for the Organization Id account.
  5581. * @param {object} [options] Object representing optional parameters.
  5582. * @param {string} [options.clientId] The active directory application client id.
  5583. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  5584. * for an example.
  5585. * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  5586. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  5587. * @param {string} [options.domain] The domain or tenant id containing this application. Default value "common".
  5588. * @param {Environment} [options.environment] The azure environment to authenticate with.
  5589. * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
  5590. *
  5591. * @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
  5592. */
  5593. function withUsernamePasswordWithAuthResponse(username, password, options) {
  5594. return __awaiter(this, void 0, void 0, function* () {
  5595. if (!options) {
  5596. options = {};
  5597. }
  5598. if (!options.clientId) {
  5599. options.clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID;
  5600. }
  5601. if (!options.domain) {
  5602. options.domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT;
  5603. }
  5604. if (!options.environment) {
  5605. options.environment = ms_rest_azure_env_1.Environment.AzureCloud;
  5606. }
  5607. let creds;
  5608. let tenantList = [];
  5609. let subscriptionList = [];
  5610. try {
  5611. creds = new userTokenCredentials_1.UserTokenCredentials(options.clientId, options.domain, username, password, options.tokenAudience, options.environment);
  5612. yield creds.getToken();
  5613. // The token cache gets propulated for all the tenants as a part of building the tenantList.
  5614. tenantList = yield subscriptionUtils_1.buildTenantList(creds);
  5615. subscriptionList = yield _getSubscriptions(creds, tenantList, options.tokenAudience);
  5616. }
  5617. catch (err) {
  5618. return Promise.reject(err);
  5619. }
  5620. return Promise.resolve({ credentials: creds, subscriptions: subscriptionList });
  5621. });
  5622. }
  5623. exports.withUsernamePasswordWithAuthResponse = withUsernamePasswordWithAuthResponse;
  5624. /**
  5625. * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants.
  5626. *
  5627. * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name).
  5628. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  5629. * for an example.
  5630. * @param {string} secret The application secret for the service principal.
  5631. * @param {string} domain The domain or tenant id containing this application.
  5632. * @param {object} [options] Object representing optional parameters.
  5633. * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  5634. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  5635. * @param {Environment} [options.environment] The azure environment to authenticate with.
  5636. * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
  5637. *
  5638. * @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
  5639. */
  5640. function withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options) {
  5641. return __awaiter(this, void 0, void 0, function* () {
  5642. if (!options) {
  5643. options = {};
  5644. }
  5645. if (!options.environment) {
  5646. options.environment = ms_rest_azure_env_1.Environment.AzureCloud;
  5647. }
  5648. let creds;
  5649. let subscriptionList = [];
  5650. try {
  5651. creds = new applicationTokenCredentials_1.ApplicationTokenCredentials(clientId, domain, secret, options.tokenAudience, options.environment);
  5652. yield creds.getToken();
  5653. subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience);
  5654. }
  5655. catch (err) {
  5656. return Promise.reject(err);
  5657. }
  5658. return Promise.resolve({ credentials: creds, subscriptions: subscriptionList });
  5659. });
  5660. }
  5661. exports.withServicePrincipalSecretWithAuthResponse = withServicePrincipalSecretWithAuthResponse;
  5662. /**
  5663. * Provides an ApplicationTokenCertificateCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants.
  5664. *
  5665. * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name).
  5666. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  5667. * for an example.
  5668. * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example:
  5669. * - CertificateString: "-----BEGIN PRIVATE KEY-----\n<xxxxx>\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n<yyyyy>\n-----END CERTIFICATE-----\n"
  5670. * - CertificateFilePath: **Absolute** file path of the .pem file.
  5671. * @param {string} domain The domain or tenant id containing this application.
  5672. * @param {object} [options] Object representing optional parameters.
  5673. * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.
  5674. * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).
  5675. * @param {Environment} [options.environment] The azure environment to authenticate with.
  5676. * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
  5677. *
  5678. * @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
  5679. */
  5680. function withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options) {
  5681. return __awaiter(this, void 0, void 0, function* () {
  5682. if (!options) {
  5683. options = {};
  5684. }
  5685. if (!options.environment) {
  5686. options.environment = ms_rest_azure_env_1.Environment.AzureCloud;
  5687. }
  5688. let creds;
  5689. let subscriptionList = [];
  5690. try {
  5691. creds = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials.create(clientId, certificateStringOrFilePath, domain, options);
  5692. yield creds.getToken();
  5693. subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience);
  5694. }
  5695. catch (err) {
  5696. return Promise.reject(err);
  5697. }
  5698. return Promise.resolve({ credentials: creds, subscriptions: subscriptionList });
  5699. });
  5700. }
  5701. exports.withServicePrincipalCertificateWithAuthResponse = withServicePrincipalCertificateWithAuthResponse;
  5702. function validateAuthFileContent(credsObj, filePath) {
  5703. if (!credsObj) {
  5704. throw new Error("Please provide a credsObj to validate.");
  5705. }
  5706. if (!filePath) {
  5707. throw new Error("Please provide a filePath.");
  5708. }
  5709. if (!credsObj.clientId) {
  5710. throw new Error(`"clientId" is missing from the auth file: ${filePath}.`);
  5711. }
  5712. if (!credsObj.clientSecret && !credsObj.clientCertificate) {
  5713. throw new Error(`Either "clientSecret" or "clientCertificate" must be present in the auth file: ${filePath}.`);
  5714. }
  5715. if (!credsObj.subscriptionId) {
  5716. throw new Error(`"subscriptionId" is missing from the auth file: ${filePath}.`);
  5717. }
  5718. if (!credsObj.tenantId) {
  5719. throw new Error(`"tenantId" is missing from the auth file: ${filePath}.`);
  5720. }
  5721. if (!credsObj.activeDirectoryEndpointUrl) {
  5722. throw new Error(`"activeDirectoryEndpointUrl" is missing from the auth file: ${filePath}.`);
  5723. }
  5724. if (!credsObj.resourceManagerEndpointUrl) {
  5725. throw new Error(`"resourceManagerEndpointUrl" is missing from the auth file: ${filePath}.`);
  5726. }
  5727. if (!credsObj.activeDirectoryGraphResourceId) {
  5728. throw new Error(`"activeDirectoryGraphResourceId" is missing from the auth file: ${filePath}.`);
  5729. }
  5730. if (!credsObj.sqlManagementEndpointUrl) {
  5731. throw new Error(`"sqlManagementEndpointUrl" is missing from the auth file: ${filePath}.`);
  5732. }
  5733. }
  5734. function foundManagementEndpointUrl(authFileUrl, envUrl) {
  5735. if (!authFileUrl || (authFileUrl && typeof authFileUrl.valueOf() !== "string")) {
  5736. throw new Error("authFileUrl cannot be null or undefined and must be of type string.");
  5737. }
  5738. if (!envUrl || (envUrl && typeof envUrl.valueOf() !== "string")) {
  5739. throw new Error("envUrl cannot be null or undefined and must be of type string.");
  5740. }
  5741. authFileUrl = authFileUrl.endsWith("/") ? authFileUrl.slice(0, -1) : authFileUrl;
  5742. envUrl = envUrl.endsWith("/") ? envUrl.slice(0, -1) : envUrl;
  5743. return (authFileUrl.toLowerCase() === envUrl.toLowerCase());
  5744. }
  5745. /**
  5746. * Before using this method please install az cli from https://github.com/Azure/azure-cli/releases. Then execute `az ad sp create-for-rbac --sdk-auth > ${yourFilename.json}`.
  5747. * If you want to create the sp for a different cloud/environment then please execute:
  5748. * 1. az cloud list
  5749. * 2. az cloud set –n <name of the environment>
  5750. * 3. az ad sp create-for-rbac --sdk-auth > auth.json // create sp with secret
  5751. * **OR**
  5752. * 3. az ad sp create-for-rbac --create-cert --sdk-auth > auth.json // create sp with certificate
  5753. * If the service principal is already created then login with service principal info:
  5754. * 4. az login --service-principal -u <clientId> -p <clientSecret> -t <tenantId>
  5755. * 5. az account show --sdk-auth > auth.json
  5756. *
  5757. * Authenticates using the service principal information provided in the auth file. This method will set
  5758. * the subscriptionId from the auth file to the user provided environment variable in the options
  5759. * parameter or the default "AZURE_SUBSCRIPTION_ID".
  5760. *
  5761. * @param {object} [options] - Optional parameters
  5762. * @param {string} [options.filePath] - Absolute file path to the auth file. If not provided
  5763. * then please set the environment variable AZURE_AUTH_LOCATION.
  5764. * @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable
  5765. * name. Default is "AZURE_SUBSCRIPTION_ID".
  5766. * @param {function} [optionalCallback] The optional callback.
  5767. *
  5768. * @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
  5769. */
  5770. function withAuthFileWithAuthResponse(options) {
  5771. return __awaiter(this, void 0, void 0, function* () {
  5772. if (!options)
  5773. options = { filePath: "" };
  5774. const filePath = options.filePath || process.env[authConstants_1.AuthConstants.AZURE_AUTH_LOCATION];
  5775. const subscriptionEnvVariableName = options.subscriptionEnvVariableName || "AZURE_SUBSCRIPTION_ID";
  5776. if (!filePath) {
  5777. const msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${authConstants_1.AuthConstants.AZURE_AUTH_LOCATION}.`;
  5778. return Promise.reject(new Error(msg));
  5779. }
  5780. let content, credsObj = {};
  5781. const optionsForSp = {};
  5782. try {
  5783. content = fs_1.readFileSync(filePath, { encoding: "utf8" });
  5784. credsObj = JSON.parse(content);
  5785. validateAuthFileContent(credsObj, filePath);
  5786. }
  5787. catch (err) {
  5788. return Promise.reject(err);
  5789. }
  5790. if (!credsObj.managementEndpointUrl) {
  5791. credsObj.managementEndpointUrl = credsObj.resourceManagerEndpointUrl;
  5792. }
  5793. // setting the subscriptionId from auth file to the environment variable
  5794. process.env[subscriptionEnvVariableName] = credsObj.subscriptionId;
  5795. // get the AzureEnvironment or create a new AzureEnvironment based on the info provided in the auth file
  5796. const envFound = {
  5797. name: ""
  5798. };
  5799. const envNames = Object.keys(ms_rest_azure_env_1.Environment);
  5800. for (let i = 0; i < envNames.length; i++) {
  5801. const env = envNames[i];
  5802. const environmentObj = ms_rest_azure_env_1.Environment[env];
  5803. if (environmentObj &&
  5804. environmentObj.managementEndpointUrl &&
  5805. foundManagementEndpointUrl(credsObj.managementEndpointUrl, environmentObj.managementEndpointUrl)) {
  5806. envFound.name = environmentObj.name;
  5807. break;
  5808. }
  5809. }
  5810. if (envFound.name) {
  5811. optionsForSp.environment = ms_rest_azure_env_1.Environment[envFound.name];
  5812. }
  5813. else {
  5814. // create a new environment with provided info.
  5815. const envParams = {
  5816. // try to find a logical name or set the filepath as the env name.
  5817. name: credsObj.managementEndpointUrl.match(/.*management\.core\.(.*)\..*/i)[1] || filePath
  5818. };
  5819. const keys = Object.keys(credsObj);
  5820. for (let i = 0; i < keys.length; i++) {
  5821. const key = keys[i];
  5822. if (key.match(/^(clientId|clientSecret|clientCertificate|subscriptionId|tenantId)$/ig) === null) {
  5823. if (key === "activeDirectoryEndpointUrl" && !key.endsWith("/")) {
  5824. envParams[key] = credsObj[key] + "/";
  5825. }
  5826. else {
  5827. envParams[key] = credsObj[key];
  5828. }
  5829. }
  5830. }
  5831. if (!envParams.activeDirectoryResourceId) {
  5832. envParams.activeDirectoryResourceId = credsObj.managementEndpointUrl;
  5833. }
  5834. if (!envParams.portalUrl) {
  5835. envParams.portalUrl = "https://portal.azure.com";
  5836. }
  5837. optionsForSp.environment = ms_rest_azure_env_1.Environment.add(envParams);
  5838. }
  5839. if (credsObj.clientSecret) {
  5840. return withServicePrincipalSecretWithAuthResponse(credsObj.clientId, credsObj.clientSecret, credsObj.tenantId, optionsForSp);
  5841. }
  5842. return withServicePrincipalCertificateWithAuthResponse(credsObj.clientId, credsObj.clientCertificate, credsObj.tenantId, optionsForSp);
  5843. });
  5844. }
  5845. exports.withAuthFileWithAuthResponse = withAuthFileWithAuthResponse;
  5846. /**
  5847. * Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a
  5848. * DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.
  5849. *
  5850. * @param {object} [options] Object representing optional parameters.
  5851. *
  5852. * @param {string} [options.clientId] The active directory application client id.
  5853. * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}
  5854. * for an example.
  5855. *
  5856. * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is "graph".If tokenAudience is provided
  5857. * then domain should also be provided its value should not be the default "common" tenant. It must be a string (preferrably in a guid format).
  5858. *
  5859. * @param {string} [options.domain] The domain or tenant id containing this application. Default value is "common".
  5860. *
  5861. * @param {Environment} [options.environment] The azure environment to authenticate with. Default environment is "Public Azure".
  5862. *
  5863. * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.
  5864. *
  5865. * @param {object} [options.language] The language code specifying how the message should be localized to. Default value "en-us".
  5866. *
  5867. * @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When
  5868. * this option is specified the usercode response message will not be logged to console.
  5869. *
  5870. * @param {function} [optionalCallback] The optional callback.
  5871. *
  5872. * @returns {Promise<AuthResponse>} A Promise that resolves to AuthResponse that contains "credentials" and optional "subscriptions" array and rejects with an Error.
  5873. */
  5874. function withInteractiveWithAuthResponse(options) {
  5875. return __awaiter(this, void 0, void 0, function* () {
  5876. if (!options) {
  5877. options = {};
  5878. }
  5879. if (!options) {
  5880. options = {};
  5881. }
  5882. if (!options.environment) {
  5883. options.environment = ms_rest_azure_env_1.Environment.AzureCloud;
  5884. }
  5885. if (!options.domain) {
  5886. options.domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT;
  5887. }
  5888. if (!options.clientId) {
  5889. options.clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID;
  5890. }
  5891. if (!options.tokenCache) {
  5892. options.tokenCache = new adal.MemoryCache();
  5893. }
  5894. if (!options.language) {
  5895. options.language = authConstants_1.AuthConstants.DEFAULT_LANGUAGE;
  5896. }
  5897. if (!options.tokenAudience) {
  5898. options.tokenAudience = options.environment.activeDirectoryResourceId;
  5899. }
  5900. const interactiveOptions = {};
  5901. interactiveOptions.tokenAudience = options.tokenAudience;
  5902. interactiveOptions.environment = options.environment;
  5903. interactiveOptions.domain = options.domain;
  5904. interactiveOptions.clientId = options.clientId;
  5905. interactiveOptions.tokenCache = options.tokenCache;
  5906. interactiveOptions.language = options.language;
  5907. interactiveOptions.userCodeResponseLogger = options.userCodeResponseLogger;
  5908. const authorityUrl = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain;
  5909. const authContext = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache);
  5910. interactiveOptions.context = authContext;
  5911. let userCodeResponse;
  5912. let creds;
  5913. function tryAcquireToken(interactiveOptions, resolve, reject) {
  5914. authContext.acquireUserCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, interactiveOptions.language, (err, userCodeRes) => {
  5915. if (err) {
  5916. if (err.error === "authorization_pending") {
  5917. setTimeout(() => {
  5918. tryAcquireToken(interactiveOptions, resolve, reject);
  5919. }, 1000);
  5920. }
  5921. else {
  5922. return reject(err);
  5923. }
  5924. }
  5925. userCodeResponse = userCodeRes;
  5926. if (interactiveOptions.userCodeResponseLogger) {
  5927. interactiveOptions.userCodeResponseLogger(userCodeResponse.message);
  5928. }
  5929. else {
  5930. console.log(userCodeResponse.message);
  5931. }
  5932. return resolve(userCodeResponse);
  5933. });
  5934. }
  5935. const getUserCode = new Promise((resolve, reject) => {
  5936. return tryAcquireToken(interactiveOptions, resolve, reject);
  5937. });
  5938. return getUserCode.then(() => {
  5939. return new Promise((resolve, reject) => {
  5940. return authContext.acquireTokenWithDeviceCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, userCodeResponse, (error, tokenResponse) => {
  5941. if (error) {
  5942. return reject(error);
  5943. }
  5944. interactiveOptions.userName = tokenResponse.userId;
  5945. interactiveOptions.authorizationScheme = tokenResponse.tokenType;
  5946. try {
  5947. creds = new deviceTokenCredentials_1.DeviceTokenCredentials(interactiveOptions.clientId, interactiveOptions.domain, interactiveOptions.userName, interactiveOptions.tokenAudience, interactiveOptions.environment, interactiveOptions.tokenCache);
  5948. }
  5949. catch (err) {
  5950. return reject(err);
  5951. }
  5952. return resolve(creds);
  5953. });
  5954. });
  5955. }).then((creds) => {
  5956. return subscriptionUtils_1.buildTenantList(creds);
  5957. }).then((tenants) => {
  5958. return _getSubscriptions(creds, tenants, interactiveOptions.tokenAudience);
  5959. }).then((subscriptions) => {
  5960. return Promise.resolve({ credentials: creds, subscriptions: subscriptions });
  5961. });
  5962. });
  5963. }
  5964. exports.withInteractiveWithAuthResponse = withInteractiveWithAuthResponse;
  5965. function withAuthFile(options, callback) {
  5966. if (!callback && typeof options === "function") {
  5967. callback = options;
  5968. options = undefined;
  5969. }
  5970. const cb = callback;
  5971. if (!callback) {
  5972. return withAuthFileWithAuthResponse(options).then((authRes) => {
  5973. return Promise.resolve(authRes.credentials);
  5974. }).catch((err) => {
  5975. return Promise.reject(err);
  5976. });
  5977. }
  5978. else {
  5979. msRest.promiseToCallback(withAuthFileWithAuthResponse(options))((err, authRes) => {
  5980. if (err) {
  5981. return cb(err);
  5982. }
  5983. return cb(undefined, authRes.credentials, authRes.subscriptions);
  5984. });
  5985. }
  5986. }
  5987. exports.withAuthFile = withAuthFile;
  5988. function interactive(options, callback) {
  5989. if (!callback && typeof options === "function") {
  5990. callback = options;
  5991. options = undefined;
  5992. }
  5993. const cb = callback;
  5994. if (!callback) {
  5995. return withInteractiveWithAuthResponse(options).then((authRes) => {
  5996. return Promise.resolve(authRes.credentials);
  5997. }).catch((err) => {
  5998. return Promise.reject(err);
  5999. });
  6000. }
  6001. else {
  6002. msRest.promiseToCallback(withInteractiveWithAuthResponse(options))((err, authRes) => {
  6003. if (err) {
  6004. return cb(err);
  6005. }
  6006. return cb(undefined, authRes.credentials, authRes.subscriptions);
  6007. });
  6008. }
  6009. }
  6010. exports.interactive = interactive;
  6011. function withServicePrincipalSecret(clientId, secret, domain, options, callback) {
  6012. if (!callback && typeof options === "function") {
  6013. callback = options;
  6014. options = undefined;
  6015. }
  6016. const cb = callback;
  6017. if (!callback) {
  6018. return withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options).then((authRes) => {
  6019. return Promise.resolve(authRes.credentials);
  6020. }).catch((err) => {
  6021. return Promise.reject(err);
  6022. });
  6023. }
  6024. else {
  6025. msRest.promiseToCallback(withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options))((err, authRes) => {
  6026. if (err) {
  6027. return cb(err);
  6028. }
  6029. return cb(undefined, authRes.credentials, authRes.subscriptions);
  6030. });
  6031. }
  6032. }
  6033. exports.withServicePrincipalSecret = withServicePrincipalSecret;
  6034. function withServicePrincipalCertificate(clientId, certificateStringOrFilePath, domain, options, callback) {
  6035. if (!callback && typeof options === "function") {
  6036. callback = options;
  6037. options = undefined;
  6038. }
  6039. const cb = callback;
  6040. if (!callback) {
  6041. return withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options).then((authRes) => {
  6042. return Promise.resolve(authRes.credentials);
  6043. }).catch((err) => {
  6044. return Promise.reject(err);
  6045. });
  6046. }
  6047. else {
  6048. msRest.promiseToCallback(withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options))((err, authRes) => {
  6049. if (err) {
  6050. return cb(err);
  6051. }
  6052. return cb(undefined, authRes.credentials, authRes.subscriptions);
  6053. });
  6054. }
  6055. }
  6056. exports.withServicePrincipalCertificate = withServicePrincipalCertificate;
  6057. function withUsernamePassword(username, password, options, callback) {
  6058. if (!callback && typeof options === "function") {
  6059. callback = options;
  6060. options = undefined;
  6061. }
  6062. const cb = callback;
  6063. if (!callback) {
  6064. return withUsernamePasswordWithAuthResponse(username, password, options).then((authRes) => {
  6065. return Promise.resolve(authRes.credentials);
  6066. }).catch((err) => {
  6067. return Promise.reject(err);
  6068. });
  6069. }
  6070. else {
  6071. msRest.promiseToCallback(withUsernamePasswordWithAuthResponse(username, password, options))((err, authRes) => {
  6072. if (err) {
  6073. return cb(err);
  6074. }
  6075. return cb(undefined, authRes.credentials, authRes.subscriptions);
  6076. });
  6077. }
  6078. }
  6079. exports.withUsernamePassword = withUsernamePassword;
  6080. /**
  6081. * We only need to get the subscription list if the tokenAudience is for a management client.
  6082. */
  6083. function _getSubscriptions(creds, tenants, tokenAudience) {
  6084. if (tokenAudience &&
  6085. !managementPlaneTokenAudiences.some((item) => { return item === tokenAudience.toLowerCase(); })) {
  6086. return Promise.resolve(([]));
  6087. }
  6088. return subscriptionUtils_1.getSubscriptionsFromTenants(creds, tenants);
  6089. }
  6090. /**
  6091. * Initializes MSITokenCredentials class and calls getToken and returns a token response.
  6092. *
  6093. * @param {string} domain - required. The tenant id.
  6094. * @param {object} options - Optional parameters
  6095. * @param {string} [options.port] - port on which the MSI service is running on the host VM. Default port is 50342
  6096. * @param {string} [options.resource] - The resource uri or token audience for which the token is needed. Default - "https://management.azure.com/"
  6097. * @param {string} [options.aadEndpoint] - The add endpoint for authentication. default - "https://login.microsoftonline.com"
  6098. * @param {any} callback - the callback function.
  6099. */
  6100. function _withMSI(options) {
  6101. if (!options) {
  6102. options = {};
  6103. }
  6104. return new Promise((resolve, reject) => {
  6105. const creds = new msiVmTokenCredentials_1.MSIVmTokenCredentials(options);
  6106. creds.getToken().then((_tokenResponse) => {
  6107. // We ignore the token response, it's put in the cache.
  6108. return resolve(creds);
  6109. }).catch(error => {
  6110. reject(error);
  6111. });
  6112. });
  6113. }
  6114. function loginWithVmMSI(options, callback) {
  6115. if (!callback && typeof options === "function") {
  6116. callback = options;
  6117. options = {};
  6118. }
  6119. const cb = callback;
  6120. if (!callback) {
  6121. return _withMSI(options);
  6122. }
  6123. else {
  6124. msRest.promiseToCallback(_withMSI(options))((err, tokenRes) => {
  6125. if (err) {
  6126. return cb(err);
  6127. }
  6128. return cb(undefined, tokenRes);
  6129. });
  6130. }
  6131. }
  6132. exports.loginWithVmMSI = loginWithVmMSI;
  6133. /**
  6134. * Private method
  6135. */
  6136. function _withAppServiceMSI(options) {
  6137. if (!options) {
  6138. options = {};
  6139. }
  6140. return new Promise((resolve, reject) => {
  6141. const creds = new msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials(options);
  6142. creds.getToken().then((_tokenResponse) => {
  6143. // We ignore the token response, it's put in the cache.
  6144. return resolve(creds);
  6145. }).catch(error => {
  6146. reject(error);
  6147. });
  6148. });
  6149. }
  6150. function loginWithAppServiceMSI(options, callback) {
  6151. if (!callback && typeof options === "function") {
  6152. callback = options;
  6153. options = {};
  6154. }
  6155. const cb = callback;
  6156. if (!callback) {
  6157. return _withAppServiceMSI(options);
  6158. }
  6159. else {
  6160. msRest.promiseToCallback(_withAppServiceMSI(options))((err, tokenRes) => {
  6161. if (err) {
  6162. return cb(err);
  6163. }
  6164. return cb(undefined, tokenRes);
  6165. });
  6166. }
  6167. }
  6168. exports.loginWithAppServiceMSI = loginWithAppServiceMSI;
  6169. /**
  6170. * Executes the azure cli command and returns the result. It will be `undefined` if the command did
  6171. * not return anything or a `JSON object` if the command did return something.
  6172. * @param cmd The az cli command to execute.
  6173. */
  6174. function execAz(cmd) {
  6175. return __awaiter(this, void 0, void 0, function* () {
  6176. return new Promise((resolve, reject) => {
  6177. child_process_1.exec(`az ${cmd} --out json`, { encoding: "utf8" }, (error, stdout) => {
  6178. if (error) {
  6179. return reject(error);
  6180. }
  6181. if (stdout) {
  6182. try {
  6183. return resolve(JSON.parse(stdout));
  6184. }
  6185. catch (err) {
  6186. const msg = `An error occured while parsing the output "${stdout}", of ` +
  6187. `the cmd "${cmd}": ${err.stack}.`;
  6188. return reject(new Error(msg));
  6189. }
  6190. }
  6191. return resolve();
  6192. });
  6193. });
  6194. });
  6195. }
  6196. exports.execAz = execAz;
  6197. }).call(this)}).call(this,require('_process'))
  6198. },{"./credentials/applicationTokenCertificateCredentials":4,"./credentials/applicationTokenCredentials":5,"./credentials/deviceTokenCredentials":8,"./credentials/msiAppServiceTokenCredentials":10,"./credentials/msiVmTokenCredentials":12,"./credentials/userTokenCredentials":14,"./subscriptionManagement/subscriptionUtils":17,"./util/authConstants":18,"@azure/ms-rest-azure-env":1,"@azure/ms-rest-js":2,"_process":525,"adal-node":19,"child_process":190,"fs":190}],16:[function(require,module,exports){
  6199. "use strict";
  6200. // Copyright (c) Microsoft Corporation. All rights reserved.
  6201. // Licensed under the MIT License. See License.txt in the project root for license information.
  6202. Object.defineProperty(exports, "__esModule", { value: true });
  6203. var applicationTokenCredentials_1 = require("./credentials/applicationTokenCredentials");
  6204. exports.ApplicationTokenCredentials = applicationTokenCredentials_1.ApplicationTokenCredentials;
  6205. var applicationTokenCertificateCredentials_1 = require("./credentials/applicationTokenCertificateCredentials");
  6206. exports.ApplicationTokenCertificateCredentials = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials;
  6207. var deviceTokenCredentials_1 = require("./credentials/deviceTokenCredentials");
  6208. exports.DeviceTokenCredentials = deviceTokenCredentials_1.DeviceTokenCredentials;
  6209. var keyVaultFactory_1 = require("./credentials/keyVaultFactory");
  6210. exports.createAuthenticator = keyVaultFactory_1.createAuthenticator;
  6211. var msiAppServiceTokenCredentials_1 = require("./credentials/msiAppServiceTokenCredentials");
  6212. exports.MSIAppServiceTokenCredentials = msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials;
  6213. var msiTokenCredentials_1 = require("./credentials/msiTokenCredentials");
  6214. exports.MSITokenCredentials = msiTokenCredentials_1.MSITokenCredentials;
  6215. var msiVmTokenCredentials_1 = require("./credentials/msiVmTokenCredentials");
  6216. exports.MSIVmTokenCredentials = msiVmTokenCredentials_1.MSIVmTokenCredentials;
  6217. var tokenCredentialsBase_1 = require("./credentials/tokenCredentialsBase");
  6218. exports.TokenCredentialsBase = tokenCredentialsBase_1.TokenCredentialsBase;
  6219. var userTokenCredentials_1 = require("./credentials/userTokenCredentials");
  6220. exports.UserTokenCredentials = userTokenCredentials_1.UserTokenCredentials;
  6221. var authConstants_1 = require("./util/authConstants");
  6222. exports.AuthConstants = authConstants_1.AuthConstants;
  6223. var azureCliCredentials_1 = require("./credentials/azureCliCredentials");
  6224. exports.AzureCliCredentials = azureCliCredentials_1.AzureCliCredentials;
  6225. var login_1 = require("./login");
  6226. exports.interactiveLogin = login_1.interactive;
  6227. exports.interactiveLoginWithAuthResponse = login_1.withInteractiveWithAuthResponse;
  6228. exports.loginWithUsernamePassword = login_1.withUsernamePassword;
  6229. exports.loginWithUsernamePasswordWithAuthResponse = login_1.withUsernamePasswordWithAuthResponse;
  6230. exports.loginWithServicePrincipalSecret = login_1.withServicePrincipalSecret;
  6231. exports.loginWithServicePrincipalSecretWithAuthResponse = login_1.withServicePrincipalSecretWithAuthResponse;
  6232. exports.loginWithAuthFile = login_1.withAuthFile;
  6233. exports.loginWithAuthFileWithAuthResponse = login_1.withAuthFileWithAuthResponse;
  6234. exports.loginWithVmMSI = login_1.loginWithVmMSI;
  6235. exports.loginWithAppServiceMSI = login_1.loginWithAppServiceMSI;
  6236. exports.loginWithServicePrincipalCertificate = login_1.withServicePrincipalCertificate;
  6237. exports.loginWithServicePrincipalCertificateWithAuthResponse = login_1.withServicePrincipalCertificateWithAuthResponse;
  6238. },{"./credentials/applicationTokenCertificateCredentials":4,"./credentials/applicationTokenCredentials":5,"./credentials/azureCliCredentials":7,"./credentials/deviceTokenCredentials":8,"./credentials/keyVaultFactory":9,"./credentials/msiAppServiceTokenCredentials":10,"./credentials/msiTokenCredentials":11,"./credentials/msiVmTokenCredentials":12,"./credentials/tokenCredentialsBase":13,"./credentials/userTokenCredentials":14,"./login":15,"./util/authConstants":18}],17:[function(require,module,exports){
  6239. "use strict";
  6240. // Copyright (c) Microsoft Corporation. All rights reserved.
  6241. // Licensed under the MIT License. See License.txt in the project root for license information.
  6242. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  6243. return new (P || (P = Promise))(function (resolve, reject) {
  6244. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6245. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  6246. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  6247. step((generator = generator.apply(thisArg, _arguments || [])).next());
  6248. });
  6249. };
  6250. Object.defineProperty(exports, "__esModule", { value: true });
  6251. const msRest = require("@azure/ms-rest-js");
  6252. const applicationTokenCredentialsBase_1 = require("../credentials/applicationTokenCredentialsBase");
  6253. const authConstants_1 = require("../util/authConstants");
  6254. /**
  6255. * Builds an array of tenantIds.
  6256. * @param {TokenCredentialsBase} credentials The credentials.
  6257. * @param {string} apiVersion default value 2016-06-01
  6258. * @returns {Promise<string[]>} resolves to an array of tenantIds and rejects with an error.
  6259. */
  6260. function buildTenantList(credentials, apiVersion = "2016-06-01") {
  6261. return __awaiter(this, void 0, void 0, function* () {
  6262. if (credentials.domain && credentials.domain !== authConstants_1.AuthConstants.AAD_COMMON_TENANT) {
  6263. return Promise.resolve([credentials.domain]);
  6264. }
  6265. const client = new msRest.ServiceClient(credentials);
  6266. const baseUrl = credentials.environment.resourceManagerEndpointUrl;
  6267. const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}tenants?api-version=${apiVersion}`;
  6268. const req = {
  6269. url: reqUrl,
  6270. method: "GET",
  6271. };
  6272. let res;
  6273. try {
  6274. res = yield client.sendRequest(req);
  6275. }
  6276. catch (err) {
  6277. return Promise.reject(err);
  6278. }
  6279. const result = [];
  6280. const tenants = res.parsedBody;
  6281. for (const tenant in tenants.value) {
  6282. result.push(tenant.tenantId);
  6283. }
  6284. return Promise.resolve(result);
  6285. });
  6286. }
  6287. exports.buildTenantList = buildTenantList;
  6288. function getSubscriptionsFromTenants(credentials, tenantList, apiVersion = "2016-06-01") {
  6289. return __awaiter(this, void 0, void 0, function* () {
  6290. let subscriptions = [];
  6291. let userType = "user";
  6292. let username;
  6293. const originalDomain = credentials.domain;
  6294. if (credentials instanceof applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase) {
  6295. userType = "servicePrincipal";
  6296. username = credentials.clientId;
  6297. }
  6298. else {
  6299. username = credentials.username;
  6300. }
  6301. for (const tenant of tenantList) {
  6302. credentials.domain = tenant;
  6303. const client = new msRest.ServiceClient(credentials);
  6304. const baseUrl = credentials.environment.resourceManagerEndpointUrl;
  6305. const reqUrl = `${baseUrl}${baseUrl.endsWith("/") ? "" : "/"}subscriptions?api-version=${apiVersion}`;
  6306. const req = {
  6307. url: reqUrl,
  6308. method: "GET",
  6309. };
  6310. let res;
  6311. try {
  6312. res = yield client.sendRequest(req);
  6313. }
  6314. catch (err) {
  6315. return Promise.reject(err);
  6316. }
  6317. const subscriptionList = res.parsedBody.value;
  6318. subscriptions = subscriptions.concat(subscriptionList.map((s) => {
  6319. s.tenantId = tenant;
  6320. s.user = { name: username, type: userType };
  6321. s.environmentName = credentials.environment.name;
  6322. s.name = s.displayName;
  6323. s.id = s.subscriptionId;
  6324. delete s.displayName;
  6325. delete s.subscriptionId;
  6326. delete s.subscriptionPolicies;
  6327. return s;
  6328. }));
  6329. }
  6330. // Reset the original domain.
  6331. credentials.domain = originalDomain;
  6332. return Promise.resolve(subscriptions);
  6333. });
  6334. }
  6335. exports.getSubscriptionsFromTenants = getSubscriptionsFromTenants;
  6336. },{"../credentials/applicationTokenCredentialsBase":6,"../util/authConstants":18,"@azure/ms-rest-js":2}],18:[function(require,module,exports){
  6337. "use strict";
  6338. // Copyright (c) Microsoft Corporation. All rights reserved.
  6339. // Licensed under the MIT License. See License.txt in the project root for license information.
  6340. Object.defineProperty(exports, "__esModule", { value: true });
  6341. exports.AuthConstants = {
  6342. "AAD_COMMON_TENANT": "common",
  6343. "DEFAULT_ADAL_CLIENT_ID": "04b07795-8ddb-461a-bbee-02f9e1bf7b46",
  6344. "SDK_INTERNAL_ERROR": "SDK_INTERNAL_ERROR",
  6345. "DEFAULT_LANGUAGE": "en-us",
  6346. "AZURE_AUTH_LOCATION": "AZURE_AUTH_LOCATION",
  6347. "RESOURCE_MANAGER_ENDPOINT": "https://management.azure.com/"
  6348. };
  6349. },{}],19:[function(require,module,exports){
  6350. /*
  6351. * @copyright
  6352. * Copyright © Microsoft Open Technologies, Inc.
  6353. *
  6354. * All Rights Reserved
  6355. *
  6356. * Licensed under the Apache License, Version 2.0 (the "License");
  6357. * you may not use this file except in compliance with the License.
  6358. * You may obtain a copy of the License at
  6359. *
  6360. * http: *www.apache.org/licenses/LICENSE-2.0
  6361. *
  6362. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  6363. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  6364. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  6365. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  6366. *
  6367. * See the Apache License, Version 2.0 for the specific language
  6368. * governing permissions and limitations under the License.
  6369. */
  6370. 'use strict';
  6371. var _ = require('underscore');
  6372. var ac = require('./authentication-context');
  6373. var authParams = require('./authentication-parameters');
  6374. var logging = require('./log');
  6375. var MemoryCache = require('./memory-cache');
  6376. exports = {};
  6377. exports.Logging = logging.Logging;
  6378. exports.AuthenticationContext = ac.AuthenticationContext;
  6379. exports.setGlobalADALOptions = ac.setGlobalADALOptions;
  6380. exports.getGlobalADALOptions = ac.getGlobalADALOptions;
  6381. exports.MemoryCache = MemoryCache;
  6382. _.extend(exports, authParams);
  6383. /**
  6384. * Creates a new AuthenticationContext object. By default the authority will be checked against
  6385. * a list of known Azure Active Directory authorities. If the authority is not recognized as
  6386. * one of these well known authorities then token acquisition will fail. This behavior can be
  6387. * turned off via the validateAuthority parameter below.
  6388. * @function
  6389. * @param {string} authority A URL that identifies a token authority.
  6390. * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true.
  6391. * @returns {AuthenticationContext} A new authentication context.
  6392. */
  6393. exports.createAuthenticationContext = function(authority, validateAuthority) {
  6394. return new ac.AuthenticationContext(authority, validateAuthority);
  6395. };
  6396. module.exports = exports;
  6397. },{"./authentication-context":21,"./authentication-parameters":22,"./log":27,"./memory-cache":28,"underscore":651}],20:[function(require,module,exports){
  6398. /*
  6399. * @copyright
  6400. * Copyright © Microsoft Open Technologies, Inc.
  6401. *
  6402. * All Rights Reserved
  6403. *
  6404. * Licensed under the Apache License, Version 2.0 (the "License");
  6405. * you may not use this file except in compliance with the License.
  6406. * You may obtain a copy of the License at
  6407. *
  6408. * http: *www.apache.org/licenses/LICENSE-2.0
  6409. *
  6410. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  6411. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  6412. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  6413. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  6414. *
  6415. * See the Apache License, Version 2.0 for the specific language
  6416. * governing permissions and limitations under the License.
  6417. */
  6418. 'use strict';
  6419. var _ = require('underscore');
  6420. var constants = require('./constants');
  6421. var UserCodeResponseFields = constants.UserCodeResponseFields;
  6422. var argumentValidation = {
  6423. /**
  6424. * Throws if the passed in parameter is not a string.
  6425. * @param {string} param The parameter to validate.
  6426. * @param {string} name The name of the parameter being validated.
  6427. * @throws {Error} If the parameter is not a valid string.
  6428. */
  6429. validateStringParameter : function(param, name) {
  6430. if (!param) {
  6431. throw new Error('The ' + name + ' parameter is required.');
  6432. }
  6433. if (!_.isString(param)) {
  6434. throw new Error('The ' + name + ' parameter must be of type String.');
  6435. }
  6436. },
  6437. /**
  6438. * Validates that the callback passed in {@link AuthenticationContext.acquireToken} is a function
  6439. * @param {AcquireTokenCallback} callback
  6440. * @throws {Error} If the callback parameter is not a function
  6441. */
  6442. validateCallbackType : function(callback) {
  6443. if (!callback || !_.isFunction(callback)) {
  6444. throw new Error('acquireToken requires a function callback parameter.');
  6445. }
  6446. },
  6447. validateUserCodeInfo : function(userCodeInfo) {
  6448. if (!userCodeInfo){
  6449. throw new Error('The userCodeInfo parameter is required');
  6450. }
  6451. if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.DEVICE_CODE)){
  6452. throw new Error('The userCodeInfo is missing device_code');
  6453. }
  6454. if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.INTERVAL)){
  6455. throw new Error('The userCodeInfo is missing interval');
  6456. }
  6457. if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.EXPIRES_IN)){
  6458. throw new Error('The userCodeInfo is missing expires_in');
  6459. }
  6460. }
  6461. };
  6462. module.exports = argumentValidation;
  6463. },{"./constants":26,"underscore":651}],21:[function(require,module,exports){
  6464. /*
  6465. * @copyright
  6466. * Copyright © Microsoft Open Technologies, Inc.
  6467. *
  6468. * All Rights Reserved
  6469. *
  6470. * Licensed under the Apache License, Version 2.0 (the "License");
  6471. * you may not use this file except in compliance with the License.
  6472. * You may obtain a copy of the License at
  6473. *
  6474. * http: *www.apache.org/licenses/LICENSE-2.0
  6475. *
  6476. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  6477. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  6478. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  6479. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  6480. *
  6481. * See the Apache License, Version 2.0 for the specific language
  6482. * governing permissions and limitations under the License.
  6483. */
  6484. 'use strict';
  6485. var argument = require('./argument');
  6486. var Authority = require('./authority').Authority;
  6487. var TokenRequest = require('./token-request');
  6488. var CodeRequest = require('./code-request');
  6489. var createLogContext = require('./log').createLogContext;
  6490. var MemoryCache = require('./memory-cache');
  6491. var util = require('./util');
  6492. var constants = require('./constants');
  6493. var globalADALOptions = {};
  6494. var globalCache = new MemoryCache();
  6495. /**
  6496. * This function is used to add or remove entries from a TokenCache
  6497. * @typedef {function} ModifyCacheFunction
  6498. * @param {Array} entries An array of entries to either add or remove from the TokenCache
  6499. * @param {function} callback A callback function to call when the add or remove operation is complete.
  6500. * This function can take a single error argument.
  6501. */
  6502. /**
  6503. * This function is called by a TokenCache when a find operation completes.
  6504. * @callback TokenCacheFindCallback
  6505. * @param {Error} [err] If an error occurred during the find operation then it should be passed here.
  6506. * @param {Array} [entries] If the find operation was succesful then the matched entries should be returned here.
  6507. */
  6508. /**
  6509. * This function is called by ADAL to query a TokenCache. The query parameter is
  6510. * a flat object which must be compared against entries in the cache. An entry
  6511. * matches if it has all of the fields in the query and the values of those fields match
  6512. * the values in the query. A matched object may have more fields than the query object.
  6513. * @typedef {function} FindCacheFunction
  6514. * @param {object} query This object should be compared to cache entries and matches should be returned.
  6515. * @param {TokenCacheFindCallback} callback This callback should be called when the find operation is complete.
  6516. */
  6517. /**
  6518. * This is an interface that can be implemented to provide custom token cache persistence.
  6519. * @public
  6520. * @class TokenCache
  6521. * @property {ModifyCacheFunction} add Called by ADAL when entries should be added to the cache.
  6522. * @property {ModifyCacheFunction} remove Called by ADAL when entries should be removed from the cache.
  6523. * @property {FindCacheFunction} find Called when ADAL needs to find entries in the cache.
  6524. */
  6525. /**
  6526. * Creates a new AuthenticationContext object. By default the authority will be checked against
  6527. * a list of known Azure Active Directory authorities. If the authority is not recognized as
  6528. * one of these well known authorities then token acquisition will fail. This behavior can be
  6529. * turned off via the validateAuthority parameter below.
  6530. * @constructor
  6531. * @param {string} authority A URL that identifies a token authority.
  6532. * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true.
  6533. * @param {TokenCache} [cache] Sets the token cache used by this AuthenticationContext instance. If this parameter is not set
  6534. * then a default, in memory cache is used. The default in memory cache is global to the process and is
  6535. * shared by all AuthenticationContexts that are created with an empty cache parameter. To control the
  6536. * scope and lifetime of a cache you can either create a {@link MemoryCache} instance and pass it when
  6537. * constructing an AuthenticationContext or implement a custom {@link TokenCache} and pass that. Cache
  6538. * instances passed at AuthenticationContext construction time are only used by that instance of
  6539. * the AuthenticationContext and are not shared unless it has been manually passed during the
  6540. * construction of other AuthenticationContexts.
  6541. *
  6542. */
  6543. function AuthenticationContext(authority, validateAuthority, cache) {
  6544. var validate = (validateAuthority === undefined || validateAuthority === null || validateAuthority);
  6545. this._authority = new Authority(authority, validate);
  6546. this._oauth2client = null;
  6547. this._correlationId = null;
  6548. this._callContext = { options : globalADALOptions };
  6549. this._cache = cache || globalCache;
  6550. this._tokenRequestWithUserCode = {};
  6551. }
  6552. /**
  6553. * Gets the authority url this AuthenticationContext was constructed with.
  6554. * @instance
  6555. * @memberOf AuthenticationContext
  6556. * @type {string}
  6557. * @name authority
  6558. */
  6559. Object.defineProperty(AuthenticationContext.prototype, 'authority', {
  6560. get: function () {
  6561. return this._authority.url;
  6562. }
  6563. });
  6564. /**
  6565. * Gets/Sets the correlation id that will be used for the next acquireToken request.
  6566. * @instance
  6567. * @memberOf AuthenticationContext
  6568. * @type {string}
  6569. * @name correlationId
  6570. */
  6571. Object.defineProperty(AuthenticationContext.prototype, 'correlationId', {
  6572. get: function () {
  6573. return this._correlationId;
  6574. },
  6575. set: function (id) {
  6576. this._correlationId = id;
  6577. }
  6578. });
  6579. /**
  6580. * Get/Sets options that are applied to requests generated by this AuthenticationContext instance.
  6581. * @instance
  6582. * @memberOf AuthenticationContext
  6583. * @type {object}
  6584. * @name options
  6585. */
  6586. Object.defineProperty(AuthenticationContext.prototype, 'options', {
  6587. get: function() {
  6588. return this._callContext.options;
  6589. },
  6590. set: function (value) {
  6591. this._callContext.options = value;
  6592. }
  6593. });
  6594. /**
  6595. * Get the token cache used by this AuthenticationContext instance.
  6596. * @instance
  6597. * @memberOf AuthenticationContext
  6598. * @type {object}
  6599. * @name cache
  6600. */
  6601. Object.defineProperty(AuthenticationContext.prototype, 'cache', {
  6602. get: function() {
  6603. return this._cache;
  6604. },
  6605. });
  6606. /**
  6607. * This will be returned in case the OAuth 2 service returns an error.
  6608. * @typedef ErrorResponse
  6609. * @property {string} [error] A server error.
  6610. * @property {string} [errorDescription] A description of the error returned.
  6611. */
  6612. /**
  6613. * Contains tokens and metadata upon successful completion of an acquireToken call.
  6614. * @typedef TokenResponse
  6615. * @property {string} tokenType The type of token returned.
  6616. * @property {string} accessToken The returned access token.
  6617. * @property {string} [refreshToken] A refresh token.
  6618. * @property {Date} [createdOn] The date on which the access token was created.
  6619. * @property {Date} expiresOn The Date on which the access token expires.
  6620. * @property {int} expiresIn The amount of time, in seconds, for which the token is valid.
  6621. * @property {string} [userId] An id for the user. May be a displayable value if is_user_id_displayable is true.
  6622. * @property {bool} [isUserIdDisplayable] Indicates whether the user_id property will be meaningful if displayed to a user.
  6623. * @property {string} [tenantId] The identifier of the tenant under which the access token was issued.
  6624. * @property {string} [givenName] The given name of the principal represented by the access token.
  6625. * @property {string} [familyName] The family name of the principal represented by the access token.
  6626. * @property {string} [identityProvider] Identifies the identity provider that issued the access token.
  6627. */
  6628. /**
  6629. * This is the callback that is passed to all acquireToken variants below.
  6630. * @callback AcquireTokenCallback
  6631. * @param {Error} [error] If the request fails this parameter will contain an Error object.
  6632. * @param {TokenResponse|ErrorResponse} [response] On a succesful request returns a {@link TokenResposne}.
  6633. */
  6634. /**
  6635. * This function implements code that is common to all acquireToken flows.
  6636. * @private
  6637. * @param {AcquireTokenCallback} callback
  6638. * @param {Function} tokenFunction This is the function to call to actually acquire the token after common flow has completed.
  6639. */
  6640. AuthenticationContext.prototype._acquireToken = function(callback, tokenFunction) {
  6641. var self = this;
  6642. this._callContext._logContext = createLogContext(this.correlationId);
  6643. this._authority.validate(this._callContext, function(err) {
  6644. if (err) {
  6645. callback(err);
  6646. return;
  6647. }
  6648. tokenFunction.call(self);
  6649. });
  6650. };
  6651. AuthenticationContext.prototype._acquireUserCode = function (callback, codeFunction) {
  6652. var self = this;
  6653. this._callContext._logContext = createLogContext(this.correlationId);
  6654. this._authority.validate(this._callContext, function (err) {
  6655. if (err) {
  6656. callback(err);
  6657. return;
  6658. }
  6659. codeFunction.call(self);
  6660. });
  6661. };
  6662. /**
  6663. * Gets a token for a given resource.
  6664. * @param {string} resource A URI that identifies the resource for which the token is valid.
  6665. * @param {string} [userId] The username of the user on behalf this application is authenticating.
  6666. * @param {string} [clientId] The OAuth client id of the calling application.
  6667. * @param {AcquireTokenCallback} callback The callback function.
  6668. */
  6669. AuthenticationContext.prototype.acquireToken = function(resource, userId, clientId, callback) {
  6670. argument.validateCallbackType(callback);
  6671. try {
  6672. argument.validateStringParameter(resource, 'resource');
  6673. argument.validateStringParameter(clientId, 'clientId');
  6674. } catch(err) {
  6675. callback(err);
  6676. return;
  6677. }
  6678. this._acquireToken(callback, function() {
  6679. var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);
  6680. tokenRequest.getTokenFromCacheWithRefresh(userId, callback);
  6681. });
  6682. };
  6683. /**
  6684. * Gets a token for a given resource.
  6685. * @param {string} resource A URI that identifies the resource for which the token is valid.
  6686. * @param {string} username The username of the user on behalf this application is authenticating.
  6687. * @param {string} password The password of the user named in the username parameter.
  6688. * @param {string} clientId The OAuth client id of the calling application.
  6689. * @param {AcquireTokenCallback} callback The callback function.
  6690. */
  6691. AuthenticationContext.prototype.acquireTokenWithUsernamePassword = function(resource, username, password, clientId, callback) {
  6692. argument.validateCallbackType(callback);
  6693. try {
  6694. argument.validateStringParameter(resource, 'resource');
  6695. argument.validateStringParameter(username, 'username');
  6696. argument.validateStringParameter(password, 'password');
  6697. argument.validateStringParameter(clientId, 'clientId');
  6698. } catch(err) {
  6699. callback(err);
  6700. return;
  6701. }
  6702. this._acquireToken(callback, function() {
  6703. var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);
  6704. tokenRequest.getTokenWithUsernamePassword(username, password, callback);
  6705. });
  6706. };
  6707. /**
  6708. * Gets a token for a given resource.
  6709. * @param {string} resource A URI that identifies the resource for which the token is valid.
  6710. * @param {string} clientId The OAuth client id of the calling application.
  6711. * @param {string} clientSecret The OAuth client secret of the calling application.
  6712. * @param {AcquireTokenCallback} callback The callback function.
  6713. */
  6714. AuthenticationContext.prototype.acquireTokenWithClientCredentials = function(resource, clientId, clientSecret, callback) {
  6715. argument.validateCallbackType(callback);
  6716. try {
  6717. argument.validateStringParameter(resource, 'resource');
  6718. argument.validateStringParameter(clientId, 'clientId');
  6719. argument.validateStringParameter(clientSecret, 'clientSecret');
  6720. } catch (err) {
  6721. callback(err);
  6722. return;
  6723. }
  6724. this._acquireToken(callback, function() {
  6725. var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);
  6726. tokenRequest.getTokenWithClientCredentials(clientSecret, callback);
  6727. });
  6728. };
  6729. /**
  6730. * Gets a token for a given resource.
  6731. * @param {string} authorizationCode An authorization code returned from a client.
  6732. * @param {string} redirectUri The redirect uri that was used in the authorize call.
  6733. * @param {string} resource A URI that identifies the resource for which the token is valid.
  6734. * @param {string} clientId The OAuth client id of the calling application.
  6735. * @param {string} clientSecret The OAuth client secret of the calling application.
  6736. * @param {AcquireTokenCallback} callback The callback function.
  6737. */
  6738. AuthenticationContext.prototype.acquireTokenWithAuthorizationCode = function(authorizationCode, redirectUri, resource, clientId, clientSecret, callback) {
  6739. argument.validateCallbackType(callback);
  6740. try {
  6741. argument.validateStringParameter(resource, 'resource');
  6742. argument.validateStringParameter(authorizationCode, 'authorizationCode');
  6743. argument.validateStringParameter(redirectUri, 'redirectUri');
  6744. argument.validateStringParameter(clientId, 'clientId');
  6745. } catch(err) {
  6746. callback(err);
  6747. return;
  6748. }
  6749. this._acquireToken(callback, function() {
  6750. var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, redirectUri);
  6751. tokenRequest.getTokenWithAuthorizationCode(authorizationCode, clientSecret, callback);
  6752. });
  6753. };
  6754. /**
  6755. * Gets a new access token via a previously issued refresh token.
  6756. * @param {string} refreshToken A refresh token returned in a tokne response from a previous invocation of acquireToken.
  6757. * @param {string} clientId The OAuth client id of the calling application.
  6758. * @param {string} [clientSecret] The OAuth client secret of the calling application. (Note: this parameter is a late addition.
  6759. * This parameter may be ommitted entirely so that applications built before this change will continue
  6760. * to work unchanged.)
  6761. * @param {string} resource The OAuth resource for which a token is being request. This parameter is optional and can be set to null.
  6762. * @param {AcquireTokenCallback} callback The callback function.
  6763. */
  6764. AuthenticationContext.prototype.acquireTokenWithRefreshToken = function(refreshToken, clientId, clientSecret, resource, callback) {
  6765. // Fix up the arguments. Older clients may pass fewer arguments as the clientSecret paramter did not always exist.
  6766. // The code needs to make adjustments for those clients.
  6767. var clientSecretPresent = (5 === arguments.length);
  6768. var actualClientSecret = clientSecretPresent ? clientSecret : null;
  6769. var actualCallback = clientSecretPresent ? arguments[4] : arguments[3];
  6770. var actualResource = clientSecretPresent ? arguments[3] : arguments[2];
  6771. argument.validateCallbackType(actualCallback);
  6772. try {
  6773. argument.validateStringParameter(refreshToken, 'refreshToken');
  6774. argument.validateStringParameter(clientId, 'clientId');
  6775. } catch(err) {
  6776. callback(err);
  6777. return;
  6778. }
  6779. this._acquireToken(callback, function() {
  6780. var tokenRequest = new TokenRequest(this._callContext, this, clientId, actualResource);
  6781. tokenRequest.getTokenWithRefreshToken(refreshToken, actualClientSecret, actualCallback);
  6782. });
  6783. };
  6784. /**
  6785. * Gets a new access token using via a certificate credential.
  6786. * @param {string} resource A URI that identifies the resource for which the token is valid.
  6787. * @param {string} clientId The OAuth client id of the calling application.
  6788. * @param {string} certificate A PEM encoded certificate private key.
  6789. * @param {string} thumbprint A hex encoded thumbprint of the certificate.
  6790. * @param {AcquireTokenCallback} callback The callback function.
  6791. */
  6792. AuthenticationContext.prototype.acquireTokenWithClientCertificate = function(resource, clientId, certificate, thumbprint, callback) {
  6793. argument.validateCallbackType(callback);
  6794. try {
  6795. argument.validateStringParameter(resource, 'resource');
  6796. argument.validateStringParameter(certificate, 'certificate');
  6797. argument.validateStringParameter(thumbprint, 'thumbprint');
  6798. } catch(err) {
  6799. callback(err);
  6800. return;
  6801. }
  6802. this._acquireToken(callback, function() {
  6803. var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);
  6804. tokenRequest.getTokenWithCertificate(certificate, thumbprint, callback);
  6805. });
  6806. };
  6807. /**
  6808. * Gets the userCodeInfo which contains user_code, device_code for authenticating user on device.
  6809. * @param {string} resource A URI that identifies the resource for which the device_code and user_code is valid for.
  6810. * @param {string} clientId The OAuth client id of the calling application.
  6811. * @param {string} language The language code specifying how the message should be localized to.
  6812. * @param {AcquireTokenCallback} callback The callback function.
  6813. */
  6814. AuthenticationContext.prototype.acquireUserCode = function(resource, clientId, language, callback) {
  6815. argument.validateCallbackType(callback);
  6816. try {
  6817. argument.validateStringParameter(resource, 'resource');
  6818. argument.validateStringParameter(clientId, 'clientId');
  6819. } catch (err) {
  6820. callback(err);
  6821. return;
  6822. }
  6823. this._acquireUserCode(callback, function () {
  6824. var codeRequest = new CodeRequest(this._callContext, this, clientId, resource);
  6825. codeRequest.getUserCodeInfo(language, callback);
  6826. });
  6827. };
  6828. /**
  6829. * Gets a new access token using via a device code.
  6830. * @note This method doesn't look up the cache, it only stores the returned token into cache. To look up cache before making a new request,
  6831. * please use acquireToken.
  6832. * @param {string} clientId The OAuth client id of the calling application.
  6833. * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token.
  6834. * @param {AcquireTokenCallback} callback The callback function.
  6835. */
  6836. AuthenticationContext.prototype.acquireTokenWithDeviceCode = function(resource, clientId, userCodeInfo, callback){
  6837. argument.validateCallbackType(callback);
  6838. try{
  6839. argument.validateUserCodeInfo(userCodeInfo);
  6840. } catch (err) {
  6841. callback(err);
  6842. return;
  6843. }
  6844. var self = this;
  6845. this._acquireToken(callback, function() {
  6846. var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, null);
  6847. self._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]] = tokenRequest;
  6848. tokenRequest.getTokenWithDeviceCode(userCodeInfo, callback);
  6849. })
  6850. };
  6851. /**
  6852. * Cancels the polling request to get token with device code.
  6853. * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token.
  6854. * @param {AcquireTokenCallback} callback The callback function.
  6855. */
  6856. AuthenticationContext.prototype.cancelRequestToGetTokenWithDeviceCode = function (userCodeInfo, callback) {
  6857. argument.validateCallbackType(callback);
  6858. try {
  6859. argument.validateUserCodeInfo(userCodeInfo);
  6860. } catch (err) {
  6861. callback(err);
  6862. return;
  6863. }
  6864. if (!this._tokenRequestWithUserCode || !this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]) {
  6865. callback(new Error('No acquireTokenWithDeviceCodeRequest existed to be cancelled'));
  6866. return;
  6867. }
  6868. var tokenRequestToBeCancelled = this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]];
  6869. tokenRequestToBeCancelled.cancelTokenRequestWithDeviceCode();
  6870. delete this._tokenRequestWithUserCode[constants.UserCodeResponseFields.DEVICE_CODE];
  6871. };
  6872. var exports = {
  6873. AuthenticationContext : AuthenticationContext,
  6874. setGlobalADALOptions : function(options) {
  6875. globalADALOptions = options;
  6876. },
  6877. getGlobalADALOptions : function() {
  6878. return globalADALOptions;
  6879. }
  6880. };
  6881. util.adalInit();
  6882. module.exports = exports;
  6883. },{"./argument":20,"./authority":23,"./code-request":25,"./constants":26,"./log":27,"./memory-cache":28,"./token-request":32,"./util":34}],22:[function(require,module,exports){
  6884. /*
  6885. * @copyright
  6886. * Copyright © Microsoft Open Technologies, Inc.
  6887. *
  6888. * All Rights Reserved
  6889. *
  6890. * Licensed under the Apache License, Version 2.0 (the "License");
  6891. * you may not use this file except in compliance with the License.
  6892. * You may obtain a copy of the License at
  6893. *
  6894. * http: *www.apache.org/licenses/LICENSE-2.0
  6895. *
  6896. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  6897. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  6898. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  6899. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  6900. *
  6901. * See the Apache License, Version 2.0 for the specific language
  6902. * governing permissions and limitations under the License.
  6903. */
  6904. 'use strict';
  6905. var request = require('request');
  6906. var argument = require('./argument');
  6907. var log = require('./log');
  6908. var util = require('./util');
  6909. var HttpErrorCode = require('./constants').HttpError;
  6910. /*
  6911. * Constants
  6912. */
  6913. var consts = {
  6914. AUTHORIZATION_URI : 'authorization_uri',
  6915. RESOURCE : 'resource',
  6916. WWW_AUTHENTICATE_HEADER : 'www-authenticate'
  6917. };
  6918. /**
  6919. * The AuthenticationParameters class holds the parameters that are parsed from an OAuth challenge
  6920. * in the www-authenticate header.
  6921. * @constructor
  6922. * @param {string} authorizationUri The URI of an authority that can issues tokens for the
  6923. * resource that issued the challenge.
  6924. * @param {string} resource The resource for a which a token should be requested from the authority.
  6925. */
  6926. function AuthenticationParameters(authorizationUri, resource) {
  6927. this._authorizationUri = authorizationUri;
  6928. this._resource = resource;
  6929. }
  6930. /**
  6931. * The URI of an authority that can issues tokens for the resource that issued the challenge.
  6932. * @instance
  6933. * @memberOf AuthenticationParameters
  6934. * @type {string}
  6935. * @name authorizationUri
  6936. */
  6937. Object.defineProperty(AuthenticationParameters.prototype, 'authorizationUri', {
  6938. get : function() {
  6939. return this._authorizationUri;
  6940. }
  6941. });
  6942. /**
  6943. * The resource for a which a token should be requested from the authority.
  6944. * This property may be undefined if the resource was not returned in the challenge.
  6945. * @instance
  6946. * @memberOf AuthenticationParameters
  6947. * @type {string}
  6948. * @name authorizationUri
  6949. */
  6950. Object.defineProperty(AuthenticationParameters.prototype, 'resource', {
  6951. get : function() {
  6952. return this._resource;
  6953. }
  6954. });
  6955. var exports = {};
  6956. // The 401 challenge is a standard defined in RFC6750, which is based in part on RFC2617.
  6957. // The challenge has the following form.
  6958. // WWW-Authenticate : Bearer authorization_uri="https://login.windows.net/mytenant.com/oauth2/authorize",Resource_id="00000002-0000-0000-c000-000000000000"
  6959. // This regex is used to validate the structure of the challenge header.
  6960. // Match whole structure: ^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$
  6961. // ^ Start at the beginning of the string.
  6962. // \s*Bearer\s+ Match 'Bearer' surrounded by one or more amount of whitespace.
  6963. // ([^,\s="]+?) This cpatures the key which is composed of any characters except comma, whitespace or a quotes.
  6964. // = Match the = sign.
  6965. // "([^"]*?)" Captures the value can be any number of non quote characters. At this point only the first key value pair as been captured.
  6966. // \s* There can be any amount of white space after the first key value pair.
  6967. // ( Start a capture group to retrieve the rest of the key value pairs that are separated by commas.
  6968. // \s* There can be any amount of whitespace before the comma.
  6969. // , There must be a comma.
  6970. // \s* There can be any amount of whitespace after the comma.
  6971. // (([^,\s="]+?) This will capture the key that comes after the comma. It's made of a series of any character excpet comma, whitespace or quotes.
  6972. // = Match the equal sign between the key and value.
  6973. // " Match the opening quote of the value.
  6974. // ([^"]*?) This will capture the value which can be any number of non quote characters.
  6975. // " Match the values closing quote.
  6976. // \s* There can be any amount of whitespace before the next comma.
  6977. // )* Close the capture group for key value pairs. There can be any number of these.
  6978. // $ The rest of the string can be whitespace but nothing else up to the end of the string.
  6979. //
  6980. //
  6981. // In other some other languages the regex above would be all that was needed. However, in JavaScript the RegExp object does not
  6982. // return all of the captures in one go. So the regex above needs to be broken up so that captures can be retrieved
  6983. // iteratively.
  6984. //
  6985. function parseChallenge(challenge) {
  6986. // This regex checks the structure of the whole challenge header. The complete
  6987. // header needs to be checked for validity before we can be certain that
  6988. // we will succeed in pulling out the individual parts.
  6989. var bearerChallengeStructureValidation = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*(,\s*([^,\s="]+?)="([^"]*?)"\s*)*$/;
  6990. // This regex pulls out the key and value from the very first pair.
  6991. var firstKeyValuePairRegex = /^\s*Bearer\s+([^,\s="]+?)="([^"]*?)"\s*/;
  6992. // This regex is used to pull out all of the key value pairs after the first one.
  6993. // All of these begin with a comma.
  6994. var allOtherKeyValuePairRegex = /(?:,\s*([^,\s="]+?)="([^"]*?)"\s*)/g;
  6995. if (!bearerChallengeStructureValidation.test(challenge)) {
  6996. throw new Error('The challenge is not parseable as an RFC6750 OAuth2 challenge');
  6997. }
  6998. var challengeParameters = {};
  6999. for(var match = firstKeyValuePairRegex.exec(challenge);
  7000. match;
  7001. match = allOtherKeyValuePairRegex.exec(challenge)) {
  7002. challengeParameters[match[1]] = match[2];
  7003. }
  7004. return challengeParameters;
  7005. }
  7006. exports.AuthenticationParameters = AuthenticationParameters;
  7007. /**
  7008. * Creates an {@link AuthenticationParameters} object from the contents of a
  7009. * www-authenticate header received from a HTTP 401 response from a resource server.
  7010. * @param {string} challenge The content fo the www-authenticate header.
  7011. * @return {AuthenticationParameters} An AuthenticationParameters object containing the parsed values from the header.
  7012. */
  7013. exports.createAuthenticationParametersFromHeader = function(challenge) {
  7014. argument.validateStringParameter(challenge, 'challenge');
  7015. var challengeParameters = parseChallenge(challenge);
  7016. var authorizationUri = challengeParameters[consts.AUTHORIZATION_URI];
  7017. if (!authorizationUri) {
  7018. throw new Error('Could not find \'authorization_uri\' in challenge header.');
  7019. }
  7020. var resource = challengeParameters[consts.RESOURCE];
  7021. return new AuthenticationParameters(authorizationUri, resource);
  7022. };
  7023. /**
  7024. * Create an {@link AuthenticationParameters} object from a node http.IncomingMessage
  7025. * object that was created as a result of a request to a resource server. This function
  7026. * expects the response to contain a HTTP 401 error code with a www-authenticate
  7027. * header.
  7028. * @param {http.IncomingMessage} response A response from a http request to a resource server.
  7029. * @return {AuthenticationParameters}
  7030. */
  7031. exports.createAuthenticationParametersFromResponse = function(response) {
  7032. if (!response) {
  7033. throw new Error('Mising required parameter: response');
  7034. }
  7035. if (!response.statusCode) {
  7036. throw new Error('The response parameter does not have the expected HTTP statusCode field');
  7037. }
  7038. if (HttpErrorCode.UNAUTHORIZED !== response.statusCode) {
  7039. throw new Error('The response status code does not correspond to an OAuth challenge. ' +
  7040. 'The statusCode is expected to be 401 but is: ' + response.statusCode);
  7041. }
  7042. if (!response.headers) {
  7043. throw new Error('There were no headers found in the response.');
  7044. }
  7045. var challenge = response.headers[consts.WWW_AUTHENTICATE_HEADER];
  7046. if (!challenge) {
  7047. throw new Error('The response does not contain a WWW-Authenticate header that can be used to determine the authority_uri and resource.');
  7048. }
  7049. return exports.createAuthenticationParametersFromHeader(challenge);
  7050. };
  7051. function validateUrlObject(url) {
  7052. if (!url || !url.href) {
  7053. throw new Error('Parameter is of wrong type: url');
  7054. }
  7055. }
  7056. /**
  7057. * This is the callback that is passed to all acquireToken variants below.
  7058. * @callback CreateAuthenticationParametersCallback
  7059. * @memberOf AuthenticationContext
  7060. * @param {Error} [error] If the request fails this parameter will contain an Error object.
  7061. * @param {AuthenticationParameters} [parameters] On a succesful request returns a {@link AuthenticationParameters}.
  7062. */
  7063. /**
  7064. * Creates an {@link AuthenticationParameters} object by sending a get request
  7065. * to the url passed to this function, and parsing the resulting http 401
  7066. * response.
  7067. * @param {string|url} url The url of a resource server.
  7068. * @param {AuthenticationParameters} callback Called on error or request completion.
  7069. * @param {string} [correlationId] An optional correlationId to pass along with the request and to include in any logs.
  7070. */
  7071. exports.createAuthenticationParametersFromUrl = function(url, callback, correlationId) {
  7072. argument.validateCallbackType(callback);
  7073. try {
  7074. if (!url) {
  7075. callback(new Error('Missing required parameter: url'));
  7076. return;
  7077. }
  7078. var challengeUrl;
  7079. if ('string' === typeof(url)) {
  7080. challengeUrl = url;
  7081. } else {
  7082. validateUrlObject(url);
  7083. challengeUrl = url.href;
  7084. }
  7085. var logContext = log.createLogContext(correlationId);
  7086. var logger = new log.Logger('AuthenticationParameters', logContext);
  7087. logger.verbose('Attempting to retrieve authentication parameters');
  7088. logger.verbose('Attempting to retrieve authentication parameters from: ' + challengeUrl, true);
  7089. var options = util.createRequestOptions( { _callContext : { _logContext: logContext } } );
  7090. request.get(challengeUrl, options, function(err, response) {
  7091. if (err) {
  7092. logger.error('Authentication parameters http get failed.', err, true);
  7093. callback(err);
  7094. return;
  7095. }
  7096. var parameters;
  7097. try {
  7098. parameters = exports.createAuthenticationParametersFromResponse(response);
  7099. } catch(creationErr) {
  7100. logger.error('Unable to parse response in to authentication paramaters.', creationErr, true);
  7101. callback(creationErr);
  7102. return;
  7103. }
  7104. callback(null, parameters);
  7105. });
  7106. } catch(err) {
  7107. callback(err);
  7108. return;
  7109. }
  7110. };
  7111. module.exports = exports;
  7112. },{"./argument":20,"./constants":26,"./log":27,"./util":34,"request":546}],23:[function(require,module,exports){
  7113. /*
  7114. * @copyright
  7115. * Copyright © Microsoft Open Technologies, Inc.
  7116. *
  7117. * All Rights Reserved
  7118. *
  7119. * Licensed under the Apache License, Version 2.0 (the "License");
  7120. * you may not use this file except in compliance with the License.
  7121. * You may obtain a copy of the License at
  7122. *
  7123. * http: *www.apache.org/licenses/LICENSE-2.0
  7124. *
  7125. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  7126. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  7127. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  7128. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  7129. *
  7130. * See the Apache License, Version 2.0 for the specific language
  7131. * governing permissions and limitations under the License.
  7132. */
  7133. 'use strict';
  7134. var request = require('request');
  7135. var url = require('url');
  7136. var _ = require('underscore');
  7137. var AADConstants = require('./constants').AADConstants;
  7138. var Logger = require('./log').Logger;
  7139. var util = require('./util');
  7140. /**
  7141. * Constructs an Authority object with a specific authority URL.
  7142. * @private
  7143. * @constructor
  7144. * @param {string} authorityUrl A URL that identifies a token authority.
  7145. * @param {bool} validateAuthority Indicates whether the Authority url should be validated as an actual AAD
  7146. * authority. The default is true.
  7147. */
  7148. function Authority(authorityUrl, validateAuthority) {
  7149. this._log = null;
  7150. this._url = url.parse(authorityUrl);
  7151. this._validateAuthorityUrl();
  7152. this._validated = !validateAuthority;
  7153. this._host = null;
  7154. this._tenant = null;
  7155. this._parseAuthority();
  7156. this._authorizationEndpoint = null;
  7157. this._tokenEndpoint = null;
  7158. this._deviceCodeEndpoint = null;
  7159. this._isAdfsAuthority = (this._tenant.toLowerCase() === "adfs");
  7160. }
  7161. /**
  7162. * The URL of the authority
  7163. * @instance
  7164. * @type {string}
  7165. * @memberOf Authority
  7166. * @name url
  7167. */
  7168. Object.defineProperty(Authority.prototype, 'url', {
  7169. get: function() {
  7170. return url.format(this._url);
  7171. }
  7172. });
  7173. /**
  7174. * The token endpoint that the authority uses as discovered by instance discovery.
  7175. * @instance
  7176. * @type {string}
  7177. * @memberOf Authority
  7178. * @name tokenEndpoint
  7179. */
  7180. Object.defineProperty(Authority.prototype, 'tokenEndpoint', {
  7181. get: function() {
  7182. return this._tokenEndpoint;
  7183. }
  7184. });
  7185. Object.defineProperty(Authority.prototype, 'deviceCodeEndpoint', {
  7186. get: function() {
  7187. return this._deviceCodeEndpoint;
  7188. }
  7189. });
  7190. /**
  7191. * Checks the authority url to ensure that it meets basic requirements such as being over SSL. If it does not then
  7192. * this method will throw if any of the checks fail.
  7193. * @private
  7194. * @throws {Error} If the authority url fails to pass any validation checks.
  7195. */
  7196. Authority.prototype._validateAuthorityUrl = function() {
  7197. if (this._url.protocol !== 'https:') {
  7198. throw new Error('The authority url must be an https endpoint.');
  7199. }
  7200. if (this._url.query) {
  7201. throw new Error('The authority url must not have a query string.');
  7202. }
  7203. };
  7204. /**
  7205. * Parse the authority to get the tenant name. The rest of the
  7206. * URL is thrown away in favor of one of the endpoints from the validation doc.
  7207. * @private
  7208. */
  7209. Authority.prototype._parseAuthority = function() {
  7210. this._host = this._url.host;
  7211. var pathParts = this._url.pathname.split('/');
  7212. this._tenant = pathParts[1];
  7213. if (!this._tenant) {
  7214. throw new Error('Could not determine tenant.');
  7215. }
  7216. };
  7217. /**
  7218. * Performs instance discovery based on a simple match against well known authorities.
  7219. * @private
  7220. * @return {bool} Returns true if the authority is recognized.
  7221. */
  7222. Authority.prototype._performStaticInstanceDiscovery = function() {
  7223. this._log.verbose('Performing static instance discovery');
  7224. var hostIndex = _.indexOf(AADConstants.WELL_KNOWN_AUTHORITY_HOSTS, this._url.hostname);
  7225. var found = hostIndex > -1;
  7226. if (found) {
  7227. this._log.verbose('Authority validated via static instance discovery.');
  7228. }
  7229. return found;
  7230. };
  7231. Authority.prototype._createAuthorityUrl = function() {
  7232. return 'https://' + this._url.host + '/' + encodeURIComponent(this._tenant) + AADConstants.AUTHORIZE_ENDPOINT_PATH;
  7233. };
  7234. /**
  7235. * Creates an instance discovery endpoint url for the specific authority that this object represents.
  7236. * @private
  7237. * @param {string} authorityHost The host name of a well known authority.
  7238. * @return {URL} The constructed endpoint url.
  7239. */
  7240. Authority.prototype._createInstanceDiscoveryEndpointFromTemplate = function(authorityHost) {
  7241. var discoveryEndpoint = AADConstants.INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE;
  7242. discoveryEndpoint = discoveryEndpoint.replace('{authorize_host}', authorityHost);
  7243. discoveryEndpoint = discoveryEndpoint.replace('{authorize_endpoint}', encodeURIComponent(this._createAuthorityUrl()));
  7244. return url.parse(discoveryEndpoint);
  7245. };
  7246. /**
  7247. * Performs instance discovery via a network call to well known authorities.
  7248. * @private
  7249. * @param {Authority.InstanceDiscoveryCallback} callback The callback function. If succesful,
  7250. * this function calls the callback with the
  7251. * tenantDiscoveryEndpoint returned by the
  7252. * server.
  7253. */
  7254. Authority.prototype._performDynamicInstanceDiscovery = function(callback) {
  7255. try {
  7256. var self = this;
  7257. var discoveryEndpoint = this._createInstanceDiscoveryEndpointFromTemplate(AADConstants.WORLD_WIDE_AUTHORITY);
  7258. var getOptions = util.createRequestOptions(self);
  7259. this._log.verbose('Attempting instance discover');
  7260. this._log.verbose('Attempting instance discover at: ' + url.format(discoveryEndpoint), true);
  7261. request.get(discoveryEndpoint, getOptions, util.createRequestHandler('Instance Discovery', this._log, callback,
  7262. function(response, body) {
  7263. var discoveryResponse = JSON.parse(body);
  7264. if (discoveryResponse['tenant_discovery_endpoint']) {
  7265. callback(null, discoveryResponse['tenant_discovery_endpoint']);
  7266. } else {
  7267. callback(self._log.createError('Failed to parse instance discovery response'));
  7268. }
  7269. })
  7270. );
  7271. } catch(e) {
  7272. callback(e);
  7273. }
  7274. };
  7275. /**
  7276. * @callback InstanceDiscoveryCallback
  7277. * @private
  7278. * @memberOf Authority
  7279. * @param {Error} err If an error occurs during instance discovery then it will be returned here.
  7280. * @param {string} tenantDiscoveryEndpoint If instance discovery is successful then this will contain the
  7281. * tenantDiscoveryEndpoint associated with the authority.
  7282. */
  7283. /**
  7284. * Determines whether the authority is recognized as a trusted AAD authority.
  7285. * @private
  7286. * @param {Authority.InstanceDiscoveryCallback} callback The callback function.
  7287. */
  7288. Authority.prototype._validateViaInstanceDiscovery = function(callback) {
  7289. if (this._performStaticInstanceDiscovery()) {
  7290. callback();
  7291. } else {
  7292. this._performDynamicInstanceDiscovery(callback);
  7293. }
  7294. };
  7295. /**
  7296. * @callback GetOauthEndpointsCallback
  7297. * @private
  7298. * @memberOf Authority
  7299. * @param {Error} error An error if one occurred.
  7300. */
  7301. /**
  7302. * Given a tenant discovery endpoint this method will attempt to discover the token endpoint. If the
  7303. * tenant discovery endpoint is unreachable for some reason then it will fall back to a algorithmic generation of the
  7304. * token endpoint url.
  7305. * @private
  7306. * @param {string} tenantDiscoveryEndpoint The url of the tenant discovery endpoint for this authority.
  7307. * @param {Authority.GetOauthEndpointsCallback} callback The callback function.
  7308. */
  7309. Authority.prototype._getOAuthEndpoints = function(tenantDiscoveryEndpoint, callback) {
  7310. if (this._tokenEndpoint && this._deviceCodeEndpoint) {
  7311. callback();
  7312. return;
  7313. } else {
  7314. // fallback to the well known token endpoint path.
  7315. if (!this._tokenEndpoint){
  7316. this._tokenEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.TOKEN_ENDPOINT_PATH;
  7317. }
  7318. if (!this._deviceCodeEndpoint){
  7319. this._deviceCodeEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.DEVICE_ENDPOINT_PATH;
  7320. }
  7321. callback();
  7322. return;
  7323. }
  7324. };
  7325. /**
  7326. * @callback ValidateCallback
  7327. * @memberOf Authority
  7328. */
  7329. /**
  7330. * Perform validation on the authority represented by this object. In addition to simple validation
  7331. * the oauth token endpoint will be retrieved.
  7332. * @param {Authority.ValidateCallback} callback The callback function.
  7333. */
  7334. Authority.prototype.validate = function(callContext, callback) {
  7335. this._log = new Logger('Authority', callContext._logContext);
  7336. this._callContext = callContext;
  7337. var self = this;
  7338. if (!this._validated) {
  7339. this._log.verbose('Performing instance discovery');
  7340. this._log.verbose('Performing instance discovery: ' + url.format(this._url), true);
  7341. this._validateViaInstanceDiscovery(function(err, tenantDiscoveryEndpoint) {
  7342. if (err)
  7343. {
  7344. callback(err);
  7345. } else {
  7346. self._validated = true;
  7347. self._getOAuthEndpoints(tenantDiscoveryEndpoint, callback);
  7348. return;
  7349. }
  7350. });
  7351. } else {
  7352. this._log.verbose('Instance discovery/validation has either already been completed or is turned off');
  7353. this._log.verbose('Instance discovery/validation has either already been completed or is turned off: ' + url.format(this._url), true);
  7354. this._getOAuthEndpoints(null, callback);
  7355. return;
  7356. }
  7357. };
  7358. module.exports.Authority = Authority;
  7359. },{"./constants":26,"./log":27,"./util":34,"request":546,"underscore":651,"url":653}],24:[function(require,module,exports){
  7360. /*
  7361. * @copyright
  7362. * Copyright © Microsoft Open Technologies, Inc.
  7363. *
  7364. * All Rights Reserved
  7365. *
  7366. * Licensed under the Apache License, Version 2.0 (the "License");
  7367. * you may not use this file except in compliance with the License.
  7368. * You may obtain a copy of the License at
  7369. *
  7370. * http: *www.apache.org/licenses/LICENSE-2.0
  7371. *
  7372. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  7373. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  7374. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  7375. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  7376. *
  7377. * See the Apache License, Version 2.0 for the specific language
  7378. * governing permissions and limitations under the License.
  7379. */
  7380. 'use strict';
  7381. var _ = require('underscore');
  7382. var crypto = require('crypto');
  7383. require('date-utils'); // Adds a number of convenience methods to the builtin Date object.
  7384. var Logger = require('./log').Logger;
  7385. var constants = require('./constants');
  7386. var cacheConstants = constants.Cache;
  7387. var TokenResponseFields = constants.TokenResponseFields;
  7388. // TODO: remove this.
  7389. // There is a PM requirement that developers be able to look in to the cache and manipulate the cache based on
  7390. // the parameters (authority, resource, clientId, userId), in any combination. They must be able find, add, and remove
  7391. // tokens based on those parameters. Any default cache that the API supplies must allow for this query pattern.
  7392. // This has the following implications:
  7393. // The developer must not be required to calculate any special fields, such as hashes or unique keys.
  7394. //
  7395. // The default cache implementation can not include optimizations that break the previous requirement.
  7396. // This means that we can only do complete scans of the data and equality can only be calculated based on
  7397. // equality of all of the individual fields.
  7398. //
  7399. // The cache interface can not make any assumption about the query efficency of the cache nor can
  7400. // it help in optimizing those queries.
  7401. //
  7402. // There is no simple sorting optimization, rather a series of indexes, and index intersection would
  7403. // be necessary.
  7404. //
  7405. // If for some reason the developer tries to update the cache with a new entry that may be a refresh
  7406. // token, they will not know that they need to update all of the refresh tokens or they may get strange
  7407. // behavior.
  7408. //
  7409. // Related to the above, there is no definition of a coherent cache. And if there was there would be
  7410. // no way for our API to enforce it. What about duplicates?
  7411. //
  7412. // there be a single cache entry per (authority, resource, clientId)
  7413. // tuple, with no special tokens (i.e. MRRT tokens)
  7414. // Required cache operations
  7415. //
  7416. // Constants
  7417. var METADATA_CLIENTID = '_clientId';
  7418. var METADATA_AUTHORITY = '_authority';
  7419. function nop(placeHolder, callback) {
  7420. callback();
  7421. }
  7422. /*
  7423. * This is a place holder cache that does nothing.
  7424. */
  7425. var nopCache = {
  7426. add : nop,
  7427. addMany : nop,
  7428. remove : nop,
  7429. removeMany : nop,
  7430. find : nop
  7431. };
  7432. function createTokenHash(token) {
  7433. var hashAlg = crypto.createHash(cacheConstants.HASH_ALGORITHM);
  7434. hashAlg.update(token, 'utf8');
  7435. return hashAlg.digest('base64');
  7436. }
  7437. function createTokenIdMessage(entry) {
  7438. var accessTokenHash = createTokenHash(entry[TokenResponseFields.ACCESS_TOKEN]);
  7439. var message = 'AccessTokenId: ' + accessTokenHash;
  7440. if (entry[TokenResponseFields.REFRESH_TOKEN]) {
  7441. var refreshTokenHash = createTokenHash(entry[TokenResponseFields.REFRESH_TOKEN]);
  7442. message += ', RefreshTokenId: ' + refreshTokenHash;
  7443. }
  7444. return message;
  7445. }
  7446. /**
  7447. * This is the callback that is passed to all acquireToken variants below.
  7448. * @callback RefreshEntryFunction
  7449. * @memberOf CacheDriver
  7450. * @param {object} tokenResponse A token response to refresh.
  7451. * @param {string} [resource] The resource for which to obtain the token if it is different from the original token.
  7452. * @param {AcquireTokenCallback} callback Called on completion with an error or a new entry to add to the cache.
  7453. */
  7454. /**
  7455. * Constructs a new CacheDriver object.
  7456. * @constructor
  7457. * @private
  7458. * @param {object} callContext Contains any context information that applies to the request.
  7459. * @param {string} authority
  7460. * @param {TokenCache} [cache] A token cache to use. If none is passed then the CacheDriver instance
  7461. * will not cache.
  7462. * @param {RefreshEntryFunction} refreshFunction
  7463. */
  7464. function CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) {
  7465. this._callContext = callContext;
  7466. this._log = new Logger('CacheDriver', callContext._logContext);
  7467. this._authority = authority;
  7468. this._resource = resource;
  7469. this._clientId = clientId;
  7470. this._cache = cache || nopCache;
  7471. this._refreshFunction = refreshFunction;
  7472. }
  7473. /**
  7474. * This is the callback that is passed to all acquireToken variants below.
  7475. * @callback QueryCallback
  7476. * @memberOf CacheDriver
  7477. * @param {Error} [error] If the request fails this parameter will contain an Error object.
  7478. * @param {Array} [response] On a succesful request returns an array of matched entries.
  7479. */
  7480. /**
  7481. * The cache driver query function. Ensures that all queries are authority specific.
  7482. * @param {object} query A query object. Can contain a clientId or userId or both.
  7483. * @param {QueryCallback} callback
  7484. */
  7485. CacheDriver.prototype._find = function(query, callback) {
  7486. this._cache.find(query, callback);
  7487. };
  7488. /**
  7489. * Queries for all entries that might satisfy a request for a cached token.
  7490. * @param {object} query A query object. Can contain a clientId or userId or both.
  7491. * @param {QueryCallback} callback
  7492. */
  7493. CacheDriver.prototype._getPotentialEntries = function(query, callback) {
  7494. var self = this;
  7495. var potentialEntriesQuery = {};
  7496. if (query.clientId) {
  7497. potentialEntriesQuery[METADATA_CLIENTID] = query.clientId;
  7498. }
  7499. if (query.userId) {
  7500. potentialEntriesQuery[TokenResponseFields.USER_ID] = query.userId;
  7501. }
  7502. this._log.verbose('Looking for potential cache entries:');
  7503. this._log.verbose(JSON.stringify(potentialEntriesQuery), true);
  7504. this._find(potentialEntriesQuery, function(err, entries) {
  7505. self._log.verbose('Found ' + entries.length + ' potential entries.');
  7506. callback(err, entries);
  7507. return;
  7508. });
  7509. };
  7510. /**
  7511. * Finds all multi resource refresh tokens in the cache.
  7512. * Refresh token is bound to userId, clientId.
  7513. * @param {QueryCallback} callback
  7514. */
  7515. CacheDriver.prototype._findMRRTTokensForUser = function(user, callback) {
  7516. this._find({ isMRRT : true, userId : user, _clientId : this._clientId}, callback);
  7517. };
  7518. /**
  7519. * This is the callback that is passed to all acquireToken variants below.
  7520. * @callback SingleEntryCallback
  7521. * @memberOf CacheDriver
  7522. * @param {Error} [error] If the request fails this parameter will contain an Error object.
  7523. * @param {object} [response] On a succesful request returns a single cache entry.
  7524. */
  7525. /**
  7526. * Finds a single entry that matches the query. If multiple entries are found that satisfy the query
  7527. * then an error will be returned.
  7528. * @param {object} query A query object.
  7529. * @param {SingleEntryCallback} callback
  7530. */
  7531. CacheDriver.prototype._loadSingleEntryFromCache = function(query, callback) {
  7532. var self = this;
  7533. this._getPotentialEntries(query, function(err, potentialEntries) {
  7534. if (err) {
  7535. callback(err);
  7536. return;
  7537. }
  7538. var returnVal;
  7539. var isResourceTenantSpecific;
  7540. if (potentialEntries && 0 < potentialEntries.length) {
  7541. var resourceTenantSpecificEntries = _.where(potentialEntries, { resource : self._resource, _authority : self._authority });
  7542. if (!resourceTenantSpecificEntries || 0 === resourceTenantSpecificEntries.length) {
  7543. self._log.verbose('No resource specific cache entries found.');
  7544. // There are no resource specific entries. Find an MRRT token.
  7545. var mrrtTokens = _.where(potentialEntries, { isMRRT : true });
  7546. if (mrrtTokens && mrrtTokens.length > 0) {
  7547. self._log.verbose('Found an MRRT token.');
  7548. returnVal = mrrtTokens[0];
  7549. } else {
  7550. self._log.verbose('No MRRT tokens found.');
  7551. }
  7552. } else if (resourceTenantSpecificEntries.length === 1) {
  7553. self._log.verbose('Resource specific token found.');
  7554. returnVal = resourceTenantSpecificEntries[0];
  7555. isResourceTenantSpecific = true;
  7556. }else {
  7557. callback(self._log.createError('More than one token matches the criteria. The result is ambiguous.'));
  7558. return;
  7559. }
  7560. }
  7561. if (returnVal) {
  7562. self._log.verbose('Returning token from cache lookup');
  7563. self._log.verbose('Returning token from cache lookup, ' + createTokenIdMessage(returnVal), true);
  7564. }
  7565. callback(null, returnVal, isResourceTenantSpecific);
  7566. });
  7567. };
  7568. /**
  7569. * The response from a token refresh request never contains an id_token and therefore no
  7570. * userInfo can be created from the response. This function creates a new cache entry
  7571. * combining the id_token based info and cache metadata from the cache entry that was refreshed with the
  7572. * new tokens in the refresh response.
  7573. * @param {object} entry A cache entry corresponding to the resfreshResponse.
  7574. * @param {object} refreshResponse The response from a token refresh request for the entry parameter.
  7575. * @return {object} A new cache entry.
  7576. */
  7577. CacheDriver.prototype._createEntryFromRefresh = function(entry, refreshResponse) {
  7578. var newEntry = _.clone(entry);
  7579. newEntry = _.extend(newEntry, refreshResponse);
  7580. if (entry.isMRRT && this._authority !== entry[METADATA_AUTHORITY]) {
  7581. newEntry[METADATA_AUTHORITY] = this._authority;
  7582. }
  7583. this._log.verbose('Created new cache entry from refresh response.');
  7584. return newEntry;
  7585. };
  7586. CacheDriver.prototype._replaceEntry = function(entryToReplace, newEntry, callback) {
  7587. var self = this;
  7588. this.remove(entryToReplace, function(err) {
  7589. if (err) {
  7590. callback(err);
  7591. return;
  7592. }
  7593. self.add(newEntry, callback);
  7594. });
  7595. };
  7596. /**
  7597. * Given an expired cache entry refreshes it and updates the cache.
  7598. * @param {object} entry A cache entry with an MRRT to refresh for another resource.
  7599. * @param {SingleEntryCallback} callback
  7600. */
  7601. CacheDriver.prototype._refreshExpiredEntry = function(entry, callback) {
  7602. var self = this;
  7603. this._refreshFunction(entry, null, function(err, tokenResponse) {
  7604. if (err) {
  7605. callback(err);
  7606. return;
  7607. }
  7608. var newEntry = self._createEntryFromRefresh(entry, tokenResponse);
  7609. self._replaceEntry(entry, newEntry, function(err) {
  7610. if (err) {
  7611. self._log.error('error refreshing expired token', err, true);
  7612. } else {
  7613. self._log.info('Returning token refreshed after expiry.');
  7614. }
  7615. callback(err, newEntry);
  7616. });
  7617. });
  7618. };
  7619. /**
  7620. * Given a cache entry with an MRRT will acquire a new token for a new resource via the MRRT, and cache it.
  7621. * @param {object} entry A cache entry with an MRRT to refresh for another resource.
  7622. * @param {SingleEntryCallback} callback
  7623. */
  7624. CacheDriver.prototype._acquireNewTokenFromMrrt = function(entry, callback) {
  7625. var self = this;
  7626. this._refreshFunction(entry, this._resource, function(err, tokenResponse) {
  7627. if (err) {
  7628. callback(err);
  7629. return;
  7630. }
  7631. var newEntry = self._createEntryFromRefresh(entry, tokenResponse);
  7632. self.add(newEntry, function(err) {
  7633. if (err) {
  7634. self._log.error('error refreshing mrrt', err, true);
  7635. } else {
  7636. self._log.info('Returning token derived from mrrt refresh.');
  7637. }
  7638. callback(err, newEntry);
  7639. });
  7640. });
  7641. };
  7642. /**
  7643. * Given a token this function will refresh it if it is either expired, or an MRRT.
  7644. * @param {object} entry A cache entry to refresh if necessary.
  7645. * @param {Boolean} isResourceSpecific Indicates whether this token is appropriate for the resource for which
  7646. * it was requested or whether it is possibly an MRRT token for which
  7647. * a resource specific access token should be acquired.
  7648. * @param {SingleEntryCallback} callback
  7649. */
  7650. CacheDriver.prototype._refreshEntryIfNecessary = function(entry, isResourceSpecific, callback) {
  7651. var expiryDate = entry[TokenResponseFields.EXPIRES_ON];
  7652. // Add some buffer in to the time comparison to account for clock skew or latency.
  7653. var nowPlusBuffer = (new Date()).addMinutes(constants.Misc.CLOCK_BUFFER);
  7654. if (isResourceSpecific && nowPlusBuffer.isAfter(expiryDate)) {
  7655. this._log.info('Cached token is expired. Refreshing: ' + expiryDate);
  7656. this._refreshExpiredEntry(entry, callback);
  7657. return;
  7658. } else if (!isResourceSpecific && entry.isMRRT) {
  7659. this._log.info('Acquiring new access token from MRRT token.');
  7660. this._acquireNewTokenFromMrrt(entry, callback);
  7661. return;
  7662. } else {
  7663. callback(null, entry);
  7664. }
  7665. };
  7666. /**
  7667. * Finds a single entry in the cache that matches the query or fails if more than one match is found.
  7668. * @param {object} query A query object
  7669. * @param {SingleEntryCallback} callback
  7670. */
  7671. CacheDriver.prototype.find = function(query, callback) {
  7672. var self = this;
  7673. query = query || {};
  7674. this._log.verbose('finding using query');
  7675. this._log.verbose('finding with query:' + JSON.stringify(query), true);
  7676. this._loadSingleEntryFromCache(query, function(err, entry, isResourceTenantSpecific) {
  7677. if (err) {
  7678. callback(err);
  7679. return;
  7680. }
  7681. if (!entry) {
  7682. callback();
  7683. return;
  7684. }
  7685. self._refreshEntryIfNecessary(entry, isResourceTenantSpecific, function(err, newEntry) {
  7686. callback(err, newEntry);
  7687. return;
  7688. });
  7689. });
  7690. };
  7691. /**
  7692. * Removes a single entry from the cache.
  7693. * @param {object} entry The entry to remove.
  7694. * @param {Function} callback Called on completion. The first parameter may contain an error.
  7695. */
  7696. CacheDriver.prototype.remove = function(entry, callback) {
  7697. this._log.verbose('Removing entry.');
  7698. return this._cache.remove([entry], function(err) {
  7699. callback(err);
  7700. return;
  7701. });
  7702. };
  7703. /**
  7704. * Removes a collection of entries from the cache in a single batch operation.
  7705. * @param {Array} entries An array of cache entries to remove.
  7706. * @param {Function} callback This function is called when the operation is complete. Any error is provided as the
  7707. * first parameter.
  7708. */
  7709. CacheDriver.prototype._removeMany = function(entries, callback) {
  7710. this._log.verbose('Remove many: ' + entries.length);
  7711. this._cache.remove(entries, function(err) {
  7712. callback(err);
  7713. return;
  7714. });
  7715. };
  7716. /**
  7717. * Adds a collection of entries to the cache in a single batch operation.
  7718. * @param {Array} entries An array of entries to add to the cache.
  7719. * @param {Function} callback This function is called when the operation is complete. Any error is provided as the
  7720. * first parameter.
  7721. */
  7722. CacheDriver.prototype._addMany = function(entries, callback) {
  7723. this._log.verbose('Add many: ' + entries.length);
  7724. this._cache.add(entries, function(err) {
  7725. callback(err);
  7726. return;
  7727. });
  7728. };
  7729. /*
  7730. * Tests whether the passed entry is a multi resource refresh token.
  7731. * Somewhat mysteriously the presense of a resource field in a returned
  7732. * token response indicates that the response is an MRRT.
  7733. * @param {object} entry
  7734. * @return {Boolean} true if the entry is an MRRT.
  7735. */
  7736. function isMRRT(entry) {
  7737. return entry.resource ? true : false;
  7738. }
  7739. /**
  7740. * Given an cache entry this function finds all of the MRRT tokens already in the cache
  7741. * and updates them with the refresh_token of the passed in entry.
  7742. * @param {object} entry The entry from which to get an updated refresh_token
  7743. * @param {Function} callback Called back on completion. The first parameter may contain an error.
  7744. */
  7745. CacheDriver.prototype._updateRefreshTokens = function(entry, callback) {
  7746. var self = this;
  7747. if (isMRRT(entry)) {
  7748. this._findMRRTTokensForUser(entry.userId, function(err, mrrtTokens) {
  7749. if (err) {
  7750. callback(err);
  7751. return;
  7752. }
  7753. if (!mrrtTokens || 0 === mrrtTokens.length) {
  7754. callback();
  7755. return;
  7756. }
  7757. self._log.verbose('Updating ' + mrrtTokens.length + ' cached refresh tokens.');
  7758. self._removeMany(mrrtTokens, function(err) {
  7759. if (err) {
  7760. callback(err);
  7761. return;
  7762. }
  7763. for (var i = 0; i < mrrtTokens.length; i++) {
  7764. mrrtTokens[i][TokenResponseFields.REFRESH_TOKEN] = entry[TokenResponseFields.REFRESH_TOKEN];
  7765. }
  7766. self._addMany(mrrtTokens, function(err) {
  7767. callback(err);
  7768. return;
  7769. });
  7770. });
  7771. });
  7772. } else {
  7773. callback();
  7774. return;
  7775. }
  7776. };
  7777. /**
  7778. * Checks to see if the entry has cache metadata already. If it does
  7779. * then it probably came from a refresh operation and the metadata
  7780. * was copied from the originating entry.
  7781. * @param {object} entry The entry to check
  7782. * @return {bool} Returns true if the entry has already been augmented
  7783. * with cache metadata.
  7784. */
  7785. CacheDriver.prototype._entryHasMetadata = function(entry) {
  7786. return (_.has(entry, METADATA_CLIENTID) && _.has(entry, METADATA_AUTHORITY));
  7787. };
  7788. CacheDriver.prototype._augmentEntryWithCacheMetadata = function(entry) {
  7789. if (this._entryHasMetadata(entry)) {
  7790. return;
  7791. }
  7792. if (isMRRT(entry)) {
  7793. this._log.verbose('Added entry is MRRT');
  7794. entry.isMRRT = true;
  7795. } else {
  7796. entry.resource = this._resource;
  7797. }
  7798. entry[METADATA_CLIENTID] = this._clientId;
  7799. entry[METADATA_AUTHORITY] = this._authority;
  7800. };
  7801. /**
  7802. * Adds a single entry to the cache.
  7803. * @param {object} entry The entry to add.
  7804. * @param {string} clientId The id of this client app.
  7805. * @param {string} resource The id of the resource for which the cached token was obtained.
  7806. * @param {Function} callback Called back on completion. The first parameter may contain an error.
  7807. */
  7808. CacheDriver.prototype.add = function(entry, callback) {
  7809. var self = this;
  7810. this._log.verbose('Adding entry');
  7811. this._log.verbose('Adding entry, ' + createTokenIdMessage(entry));
  7812. this._augmentEntryWithCacheMetadata(entry);
  7813. this._updateRefreshTokens(entry, function(err) {
  7814. if (err) {
  7815. callback(err);
  7816. return;
  7817. }
  7818. self._cache.add([entry], function(err) {
  7819. callback(err);
  7820. return;
  7821. });
  7822. });
  7823. };
  7824. module.exports = CacheDriver;
  7825. },{"./constants":26,"./log":27,"crypto":208,"date-utils":209,"underscore":651}],25:[function(require,module,exports){
  7826. /*
  7827. * @copyright
  7828. * Copyright © Microsoft Open Technologies, Inc.
  7829. *
  7830. * All Rights Reserved
  7831. *
  7832. * Licensed under the Apache License, Version 2.0 (the "License");
  7833. * you may not use this file except in compliance with the License.
  7834. * You may obtain a copy of the License at
  7835. *
  7836. * http: *www.apache.org/licenses/LICENSE-2.0
  7837. *
  7838. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  7839. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  7840. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  7841. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  7842. *
  7843. * See the Apache License, Version 2.0 for the specific language
  7844. * governing permissions and limitations under the License.
  7845. */
  7846. 'use strict';
  7847. var constants = require('./constants');
  7848. var Logger = require('./log').Logger;
  7849. var Mex = require('./mex');
  7850. var OAuth2Client = require('./oauth2client');
  7851. var OAuth2Parameters = constants.OAuth2.Parameters;
  7852. var TokenResponseFields = constants.TokenResponseFields;
  7853. var OAuth2GrantType = constants.OAuth2.GrantType;
  7854. var OAuth2Scope = constants.OAuth2.Scope;
  7855. /**
  7856. * Constructs a new CodeRequest object.
  7857. * @constructor
  7858. * @private
  7859. * @param {object} callContext Contains any context information that applies to the request.
  7860. * @param {AuthenticationContext} authenticationContext
  7861. * @param {string} resource
  7862. * @param {string} clientId
  7863. */
  7864. // TODO: probably need to modify the parameter list.
  7865. function CodeRequest(callContext, authenticationContext, clientId, resource) {
  7866. this._log = new Logger('DeviceCodeRequest', callContext._logContext);
  7867. this._callContext = callContext;
  7868. this._authenticationContext = authenticationContext;
  7869. this._resource = resource;
  7870. this._clientId = clientId;
  7871. // This should be set at the beginning of getToken
  7872. // functions that have a userId.
  7873. this._userId = null;
  7874. };
  7875. /**
  7876. * Get user code info.
  7877. * @private
  7878. * @param {object} oauthParameters containing all the parameters needed to get the user code info.
  7879. * @param {callback} callback
  7880. */
  7881. CodeRequest.prototype._getUserCodeInfo = function (oauthParameters, callback) {
  7882. var oauth2Client = this._createOAuth2Client();
  7883. oauth2Client.getUserCodeInfo(oauthParameters, callback);
  7884. };
  7885. CodeRequest.prototype._createOAuth2Client = function () {
  7886. return new OAuth2Client(this._callContext, this._authenticationContext._authority);
  7887. };
  7888. /**
  7889. * Creates a set of basic, common, OAuthParameters based on values that the CodeRequest was created with.
  7890. * @private
  7891. * @return {object} containing all the basic parameters.
  7892. */
  7893. CodeRequest.prototype._createOAuthParameters = function () {
  7894. var oauthParameters = {};
  7895. oauthParameters[OAuth2Parameters.CLIENT_ID] = this._clientId;
  7896. oauthParameters[OAuth2Parameters.RESOURCE] = this._resource;
  7897. return oauthParameters;
  7898. };
  7899. /**
  7900. * Get the user code information.
  7901. * @param {string} language optional parameter used to get the user code info.
  7902. * @param {callback} callback
  7903. */
  7904. CodeRequest.prototype.getUserCodeInfo = function(language, callback) {
  7905. this._log.info('Getting user code info.');
  7906. var oauthParameters = this._createOAuthParameters();
  7907. if (language){
  7908. oauthParameters[OAuth2Parameters.LANGUAGE] = language;
  7909. }
  7910. this._getUserCodeInfo(oauthParameters, callback);
  7911. };
  7912. module.exports = CodeRequest;
  7913. },{"./constants":26,"./log":27,"./mex":29,"./oauth2client":30}],26:[function(require,module,exports){
  7914. /*
  7915. * @copyright
  7916. * Copyright © Microsoft Open Technologies, Inc.
  7917. *
  7918. * All Rights Reserved
  7919. *
  7920. * Licensed under the Apache License, Version 2.0 (the "License");
  7921. * you may not use this file except in compliance with the License.
  7922. * You may obtain a copy of the License at
  7923. *
  7924. * http: *www.apache.org/licenses/LICENSE-2.0
  7925. *
  7926. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  7927. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  7928. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  7929. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  7930. *
  7931. * See the Apache License, Version 2.0 for the specific language
  7932. * governing permissions and limitations under the License.
  7933. */
  7934. 'use strict';
  7935. var Constants = {
  7936. OAuth2 : {
  7937. Parameters : {
  7938. GRANT_TYPE : 'grant_type',
  7939. CLIENT_ASSERTION : 'client_assertion',
  7940. CLIENT_ASSERTION_TYPE : 'client_assertion_type',
  7941. CLIENT_ID : 'client_id',
  7942. CLIENT_SECRET : 'client_secret',
  7943. REDIRECT_URI : 'redirect_uri',
  7944. RESOURCE : 'resource',
  7945. CODE : 'code',
  7946. SCOPE : 'scope',
  7947. ASSERTION : 'assertion',
  7948. AAD_API_VERSION : 'api-version',
  7949. USERNAME : 'username',
  7950. PASSWORD : 'password',
  7951. REFRESH_TOKEN : 'refresh_token',
  7952. LANGUAGE : 'mkt',
  7953. DEVICE_CODE : 'device_code',
  7954. },
  7955. GrantType : {
  7956. AUTHORIZATION_CODE : 'authorization_code',
  7957. REFRESH_TOKEN : 'refresh_token',
  7958. CLIENT_CREDENTIALS : 'client_credentials',
  7959. JWT_BEARER : 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
  7960. PASSWORD : 'password',
  7961. SAML1 : 'urn:ietf:params:oauth:grant-type:saml1_1-bearer',
  7962. SAML2 : 'urn:ietf:params:oauth:grant-type:saml2-bearer',
  7963. DEVICE_CODE: 'device_code'
  7964. },
  7965. ResponseParameters : {
  7966. CODE : 'code',
  7967. TOKEN_TYPE : 'token_type',
  7968. ACCESS_TOKEN : 'access_token',
  7969. ID_TOKEN : 'id_token',
  7970. REFRESH_TOKEN : 'refresh_token',
  7971. CREATED_ON : 'created_on',
  7972. EXPIRES_ON : 'expires_on',
  7973. EXPIRES_IN : 'expires_in',
  7974. RESOURCE : 'resource',
  7975. ERROR : 'error',
  7976. ERROR_DESCRIPTION : 'error_description'
  7977. },
  7978. DeviceCodeResponseParameters : {
  7979. USER_CODE : 'user_code',
  7980. DEVICE_CODE : 'device_code',
  7981. VERIFICATION_URL : 'verification_url',
  7982. EXPIRES_IN : 'expires_in',
  7983. INTERVAL: 'interval',
  7984. MESSAGE: 'message',
  7985. ERROR: 'error',
  7986. ERROR_DESCRIPTION: 'error_description'
  7987. },
  7988. Scope : {
  7989. OPENID : 'openid'
  7990. },
  7991. IdTokenMap : {
  7992. 'tid' : 'tenantId',
  7993. 'given_name' : 'givenName',
  7994. 'family_name' : 'familyName',
  7995. 'idp' : 'identityProvider',
  7996. 'oid': 'oid'
  7997. }
  7998. },
  7999. TokenResponseFields : {
  8000. TOKEN_TYPE : 'tokenType',
  8001. ACCESS_TOKEN : 'accessToken',
  8002. REFRESH_TOKEN : 'refreshToken',
  8003. CREATED_ON : 'createdOn',
  8004. EXPIRES_ON : 'expiresOn',
  8005. EXPIRES_IN : 'expiresIn',
  8006. RESOURCE : 'resource',
  8007. USER_ID : 'userId',
  8008. ERROR : 'error',
  8009. ERROR_DESCRIPTION : 'errorDescription'
  8010. },
  8011. UserCodeResponseFields : {
  8012. USER_CODE : 'userCode',
  8013. DEVICE_CODE: 'deviceCode',
  8014. VERIFICATION_URL: 'verificationUrl',
  8015. EXPIRES_IN: 'expiresIn',
  8016. INTERVAL: 'interval',
  8017. MESSAGE: 'message',
  8018. ERROR: 'error',
  8019. ERROR_DESCRIPTION: 'errorDescription'
  8020. },
  8021. IdTokenFields : {
  8022. USER_ID : 'userId',
  8023. IS_USER_ID_DISPLAYABLE : 'isUserIdDisplayable',
  8024. TENANT_ID : 'tenantId',
  8025. GIVE_NAME : 'givenName',
  8026. FAMILY_NAME : 'familyName',
  8027. IDENTITY_PROVIDER : 'identityProvider'
  8028. },
  8029. Misc : {
  8030. MAX_DATE : 0xffffffff,
  8031. CLOCK_BUFFER : 5 // In minutes.
  8032. },
  8033. Jwt : {
  8034. SELF_SIGNED_JWT_LIFETIME : 10, // 10 mins in mins
  8035. AUDIENCE : 'aud',
  8036. ISSUER : 'iss',
  8037. SUBJECT : 'sub',
  8038. NOT_BEFORE : 'nbf',
  8039. EXPIRES_ON : 'exp',
  8040. JWT_ID : 'jti'
  8041. },
  8042. AADConstants : {
  8043. WORLD_WIDE_AUTHORITY : 'login.windows.net',
  8044. WELL_KNOWN_AUTHORITY_HOSTS : ['login.windows.net', 'login.microsoftonline.com', 'login.chinacloudapi.cn', 'login-us.microsoftonline.com', 'login.microsoftonline.de', 'login.microsoftonline.us'],
  8045. INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE : 'https://{authorize_host}/common/discovery/instance?authorization_endpoint={authorize_endpoint}&api-version=1.0',
  8046. AUTHORIZE_ENDPOINT_PATH : '/oauth2/authorize',
  8047. TOKEN_ENDPOINT_PATH : '/oauth2/token',
  8048. DEVICE_ENDPOINT_PATH : '/oauth2/devicecode'
  8049. },
  8050. UserRealm : {
  8051. FederationProtocolType : {
  8052. WSFederation : 'wstrust',
  8053. SAML2 : 'saml20',
  8054. Unknown : 'unknown'
  8055. },
  8056. AccountType : {
  8057. Federated : 'federated',
  8058. Managed : 'managed',
  8059. Unknown : 'unknown'
  8060. }
  8061. },
  8062. Saml : {
  8063. TokenTypeV1 : 'urn:oasis:names:tc:SAML:1.0:assertion',
  8064. TokenTypeV2 : 'urn:oasis:names:tc:SAML:2.0:assertion'
  8065. },
  8066. XmlNamespaces : {
  8067. wsdl : 'http://schemas.xmlsoap.org/wsdl/',
  8068. sp : 'http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702',
  8069. sp2005 : 'http://schemas.xmlsoap.org/ws/2005/07/securitypolicy',
  8070. wsu : 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd',
  8071. wsa10 : 'http://www.w3.org/2005/08/addressing',
  8072. http : 'http://schemas.microsoft.com/ws/06/2004/policy/http',
  8073. soap12 : 'http://schemas.xmlsoap.org/wsdl/soap12/',
  8074. wsp : 'http://schemas.xmlsoap.org/ws/2004/09/policy',
  8075. s : 'http://www.w3.org/2003/05/soap-envelope',
  8076. wsa : 'http://www.w3.org/2005/08/addressing',
  8077. wst : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512',
  8078. t : 'http://schemas.xmlsoap.org/ws/2005/02/trust'
  8079. },
  8080. Cache : {
  8081. HASH_ALGORITHM : 'sha256'
  8082. },
  8083. HttpError : {
  8084. UNAUTHORIZED : 401
  8085. },
  8086. AdalIdParameters : {
  8087. SKU : 'x-client-SKU',
  8088. VERSION : 'x-client-Ver',
  8089. OS : 'x-client-OS',
  8090. CPU : 'x-client-CPU',
  8091. NODE_SKU : 'Node'
  8092. },
  8093. WSTrustVersion : {
  8094. UNDEFINED : 'undefined',
  8095. WSTRUST13 : 'wstrust13',
  8096. WSTRUST2005 : 'wstrust2005'
  8097. }
  8098. };
  8099. module.exports = Constants;
  8100. },{}],27:[function(require,module,exports){
  8101. /*
  8102. * @copyright
  8103. * Copyright © Microsoft Open Technologies, Inc.
  8104. *
  8105. * All Rights Reserved
  8106. *
  8107. * Licensed under the Apache License, Version 2.0 (the "License");
  8108. * you may not use this file except in compliance with the License.
  8109. * You may obtain a copy of the License at
  8110. *
  8111. * http: *www.apache.org/licenses/LICENSE-2.0
  8112. *
  8113. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  8114. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  8115. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  8116. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  8117. *
  8118. * See the Apache License, Version 2.0 for the specific language
  8119. * governing permissions and limitations under the License.
  8120. */
  8121. 'use strict';
  8122. var _ = require('underscore');
  8123. var uuid = require('uuid'); // want to replace with this in the future: https://gist.github.com/jed/982883
  8124. var LEVEL_STRING_MAP = {
  8125. 0 : 'ERROR:',
  8126. 1 : 'WARNING:',
  8127. 2 : 'INFO:',
  8128. 3 : 'VERBOSE:'
  8129. };
  8130. /**
  8131. * Methods for controling global logging options for ADAL
  8132. * @namespace
  8133. */
  8134. var Logging = {
  8135. /**
  8136. * @callback LoggingCallback
  8137. * @memberOf Logging
  8138. * @param {Logging.LOGGING_LEVEL} level The level of this log entry.
  8139. * @param {string} message The text content of the log entry.
  8140. * @param {Error} [error] An Error object if this is an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry.
  8141. */
  8142. /**
  8143. * @typedef LoggingOptions
  8144. * @memberOf Logging
  8145. * @property {LoggingCallback} [log] The function to call when ADAL generates a log entry.
  8146. * @property {Logging.LOGGING_LEVEL} [level] The maximum level of log entries to generate.
  8147. */
  8148. /**
  8149. * Describes the available logging levels.
  8150. * @enum
  8151. * @type {Number}
  8152. */
  8153. LOGGING_LEVEL : {
  8154. ERROR : 0,
  8155. WARN : 1,
  8156. INFO : 2,
  8157. VERBOSE : 3
  8158. },
  8159. /**
  8160. * Sets global logging options for ADAL.
  8161. * @param {LoggingOptions} options
  8162. */
  8163. setLoggingOptions : function(options) {
  8164. if (!options) {
  8165. options = {};
  8166. }
  8167. if (options.log) {
  8168. if (!_.isFunction(options.log)) {
  8169. throw new Error('setLogOptions expects the log key in the options parameter to be a function');
  8170. }
  8171. } else {
  8172. // if no log function was passed set it to a default no op function.
  8173. options.log = function() {};
  8174. }
  8175. if (options.level) {
  8176. var level = options.level;
  8177. if (level < 0 || level > 3) {
  8178. throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive');
  8179. }
  8180. } else {
  8181. options.level = this.LOGGING_LEVEL.ERROR;
  8182. }
  8183. if (options.loggingWithPII != true) {
  8184. options.loggingWithPII = false;
  8185. }
  8186. this.LogOptions = options;
  8187. },
  8188. /**
  8189. * Get's the current global logging options.
  8190. * @return {LoggingOptions}
  8191. */
  8192. getLoggingOptions : function() {
  8193. return this.LogOptions;
  8194. },
  8195. /**
  8196. * Stores the current global logging options.
  8197. * @private
  8198. * @type {LoggingOptions}
  8199. */
  8200. LogOptions : {
  8201. log : function() {},
  8202. level : 0,
  8203. loggingWithPII: false
  8204. }
  8205. };
  8206. /**
  8207. * An internal logging object.
  8208. * @class
  8209. * @private
  8210. * @param {string} componentName The name of the component that created this instance. This name will be
  8211. * prepended to the beginning of all log entries generated by this instance.
  8212. */
  8213. function Logger(componentName, logContext) {
  8214. if (!logContext) {
  8215. throw new Error('Logger: logContext is a required parameter');
  8216. }
  8217. this._componentName = componentName;
  8218. this._logContext = logContext;
  8219. }
  8220. Object.defineProperty(Logger.prototype, 'context', {
  8221. get: function () {
  8222. return this._logContext;
  8223. }
  8224. });
  8225. /**
  8226. * Generates a log entry
  8227. * @param {Logging.LOGGING_LEVEL} level The level of this log entry
  8228. * @param {string|function} message A message string, or a function that returns a message string, to log.
  8229. * @param {Error} [error] If this is a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry then the caller
  8230. * should pass an error object in this parameter.
  8231. * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.
  8232. */
  8233. Logger.prototype.log = function (level, message, error, containsPII) {
  8234. if (containsPII == true && !Logging.LogOptions.loggingWithPII) {
  8235. return;
  8236. }
  8237. if (level <= Logging.LogOptions.level) {
  8238. if (_.isFunction(message)) {
  8239. message = message();
  8240. }
  8241. var correlationId = this._logContext.correlationId || '<no correlation id>';
  8242. var timeStamp = new Date().toUTCString();
  8243. var formattedMessage = timeStamp + ':' + correlationId + ' - ' + this._componentName + ': ' + LEVEL_STRING_MAP[level] + ' ' + message;
  8244. if (error) {
  8245. formattedMessage += '\nStack:\n' + error.stack;
  8246. }
  8247. Logging.LogOptions.log(level, formattedMessage, error);
  8248. }
  8249. };
  8250. /**
  8251. * Generate an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry.
  8252. * @param {string} message A message to log
  8253. * @param {Error} error The Error object associated with this log entry
  8254. * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.
  8255. */
  8256. Logger.prototype.error = function (message, error, containsPII) {
  8257. this.log(Logging.LOGGING_LEVEL.ERROR, message, error, containsPII);
  8258. };
  8259. /**
  8260. * Generate an {@link Logging.LOGGING_LEVEL.WARN|WARN} level log entry.
  8261. * @param {string} message A message to log
  8262. * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.
  8263. */
  8264. Logger.prototype.warn = function (message, containsPII) {
  8265. this.log(Logging.LOGGING_LEVEL.WARN, message, null, containsPII);
  8266. };
  8267. /**
  8268. * Generate an {@link Logging.LOGGING_LEVEL.INFO|INFO} level log entry.
  8269. * @param {string} message A message to log
  8270. * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.
  8271. */
  8272. Logger.prototype.info = function (message, containsPII) {
  8273. this.log(Logging.LOGGING_LEVEL.INFO, message, null, containsPII);
  8274. };
  8275. /**
  8276. * Generate an {@link Logging.LOGGING_LEVEL.VERBOSE|VERBOSE} level log entry.
  8277. * @param {string} message A message to log
  8278. * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.
  8279. */
  8280. Logger.prototype.verbose = function (message, containsPII) {
  8281. this.log(Logging.LOGGING_LEVEL.VERBOSE, message, null, containsPII);
  8282. };
  8283. /**
  8284. * Generate a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry, as well as an
  8285. * Error object to go with it. This is a convenience method for throwing logged errors.
  8286. * @param {string} message A message to log
  8287. * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.
  8288. */
  8289. Logger.prototype.createError = function(message, containsPII) {
  8290. var err = new Error(message);
  8291. this.error(message, err, containsPII);
  8292. return err;
  8293. };
  8294. /**
  8295. * Creates a new log context based on the correlationId passed in. If no correlationId is passed in
  8296. * then one is generated, by the function uuid.v4()
  8297. * @private
  8298. */
  8299. function createLogContext(correlationId) {
  8300. var id = correlationId || uuid.v4();
  8301. return { correlationId : id };
  8302. }
  8303. var exports = {
  8304. Logging : Logging,
  8305. Logger : Logger,
  8306. createLogContext : createLogContext
  8307. };
  8308. module.exports = exports;
  8309. },{"underscore":651,"uuid":659}],28:[function(require,module,exports){
  8310. /*
  8311. * @copyright
  8312. * Copyright © Microsoft Open Technologies, Inc.
  8313. *
  8314. * All Rights Reserved
  8315. *
  8316. * Licensed under the Apache License, Version 2.0 (the "License");
  8317. * you may not use this file except in compliance with the License.
  8318. * You may obtain a copy of the License at
  8319. *
  8320. * http: *www.apache.org/licenses/LICENSE-2.0
  8321. *
  8322. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  8323. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  8324. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  8325. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  8326. *
  8327. * See the Apache License, Version 2.0 for the specific language
  8328. * governing permissions and limitations under the License.
  8329. */
  8330. 'use strict';
  8331. var _ = require('underscore');
  8332. /**
  8333. * Constructs a new in memory token cache.
  8334. * @constructor
  8335. */
  8336. function MemoryCache() {
  8337. this._entries = [];
  8338. }
  8339. /**
  8340. * Removes a collection of entries from the cache in a single batch operation.
  8341. * @param {Array} entries An array of cache entries to remove.
  8342. * @param {Function} callback This function is called when the operation is complete. Any error is provided as the
  8343. * first parameter.
  8344. */
  8345. MemoryCache.prototype.remove = function(entries, callback) {
  8346. var updatedEntries = _.filter(this._entries, function(element) {
  8347. if (_.findWhere(entries, element)) {
  8348. return false;
  8349. }
  8350. return true;
  8351. });
  8352. this._entries = updatedEntries;
  8353. callback();
  8354. };
  8355. /**
  8356. * Adds a collection of entries to the cache in a single batch operation.
  8357. * @param {Array} entries An array of entries to add to the cache.
  8358. * @param {Function} callback This function is called when the operation is complete. Any error is provided as the
  8359. * first parameter.
  8360. */
  8361. MemoryCache.prototype.add = function(entries, callback) {
  8362. // Remove any entries that are duplicates of the existing
  8363. // cache elements.
  8364. _.each(this._entries, function(element) {
  8365. _.each(entries, function(addElement, index) {
  8366. if (_.isEqual(element, addElement)) {
  8367. entries[index] = null;
  8368. }
  8369. });
  8370. });
  8371. // Add the new entries to the end of the cache.
  8372. entries = _.compact(entries);
  8373. for (var i = 0; i < entries.length; i++) {
  8374. this._entries.push(entries[i]);
  8375. }
  8376. callback(null, true);
  8377. };
  8378. /**
  8379. * Finds all entries in the cache that match all of the passed in values.
  8380. * @param {object} query This object will be compared to each entry in the cache. Any entries that
  8381. * match all of the values in this object will be returned. All the values
  8382. * in the passed in object must match values in a potentialy returned object
  8383. * exactly. The returned object may have more values than the passed in query
  8384. * object.
  8385. * @param {TokenCacheFindCallback} callback
  8386. */
  8387. MemoryCache.prototype.find = function(query, callback) {
  8388. var results = _.where(this._entries, query);
  8389. callback(null, results);
  8390. };
  8391. module.exports = MemoryCache;
  8392. },{"underscore":651}],29:[function(require,module,exports){
  8393. /*
  8394. * @copyright
  8395. * Copyright © Microsoft Open Technologies, Inc.
  8396. *
  8397. * All Rights Reserved
  8398. *
  8399. * Licensed under the Apache License, Version 2.0 (the "License");
  8400. * you may not use this file except in compliance with the License.
  8401. * You may obtain a copy of the License at
  8402. *
  8403. * http: *www.apache.org/licenses/LICENSE-2.0
  8404. *
  8405. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  8406. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  8407. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  8408. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  8409. *
  8410. * See the Apache License, Version 2.0 for the specific language
  8411. * governing permissions and limitations under the License.
  8412. */
  8413. 'use strict';
  8414. var request = require('request');
  8415. var url = require('url');
  8416. var DOMParser = require('xmldom').DOMParser;
  8417. var _ = require('underscore');
  8418. var Logger = require('./log').Logger;
  8419. var util = require('./util');
  8420. var xmlutil = require('./xmlutil');
  8421. var select = xmlutil.xpathSelect;
  8422. var Namespaces = require('./constants').XmlNamespaces;
  8423. var WSTrustVersion = require('./constants').WSTrustVersion;
  8424. /**
  8425. * Create a new Mex object.
  8426. * @private
  8427. * @constructor
  8428. * @param {object} callContext Contains any context information that applies to the request.
  8429. * @param {string} url The url of the mex endpoint.
  8430. */
  8431. function Mex(callContext, url) {
  8432. this._log = new Logger('MEX', callContext._logContext);
  8433. this._callContext = callContext;
  8434. this._url = url;
  8435. this._dom = null;
  8436. this._mexDoc = null;
  8437. this._usernamePasswordPolicy = {};
  8438. this._log.verbose('Mex created');
  8439. this._log.verbose('Mex created with url: ' + url, true);
  8440. }
  8441. /**
  8442. * Returns the policy containing IDP url and wstrust version from which a username passwowrd can be exchanged for a token.
  8443. * @instance
  8444. * @memberOf Mex
  8445. * @name usernamePasswordPolicy
  8446. */
  8447. Object.defineProperty(Mex.prototype, 'usernamePasswordPolicy', {
  8448. get: function() {
  8449. return this._usernamePasswordPolicy;
  8450. }
  8451. });
  8452. /**
  8453. * @callback DiscoverCallback
  8454. * @memberOf Mex
  8455. * @param {object} error
  8456. */
  8457. /**
  8458. * Performs Mex discovery. This method will retrieve the mex document, parse it, and extract
  8459. * the username password ws-trust endpoint.
  8460. * @private
  8461. * @param {Mex.DiscoverCallback} callback Called when discover is complete.
  8462. */
  8463. Mex.prototype.discover = function (callback) {
  8464. this._log.verbose('Retrieving mex');
  8465. this._log.verbose('Retrieving mex at: ' + this._url);
  8466. var self = this;
  8467. var options = util.createRequestOptions(self, { headers : { 'Content-Type' : 'application/soap+xml'} });
  8468. request.get(this._url, options, util.createRequestHandler('Mex Get', this._log, callback,
  8469. function(response, body) {
  8470. try {
  8471. self._mexDoc = body;
  8472. var options = {
  8473. errorHandler : self._log.error
  8474. };
  8475. self._dom = new DOMParser(options).parseFromString(self._mexDoc);
  8476. self._parse(callback);
  8477. return;
  8478. } catch (err) {
  8479. self._log.error('Failed to parse mex response in to DOM', err, true);
  8480. callback(err);
  8481. }
  8482. })
  8483. );
  8484. };
  8485. var TRANSPORT_BINDING_XPATH = 'wsp:ExactlyOne/wsp:All/sp:TransportBinding';
  8486. var TRANSPORT_BINDING_2005_XPATH = 'wsp:ExactlyOne/wsp:All/sp2005:TransportBinding';
  8487. /**
  8488. * Checks a DOM policy node that is a potentialy appplicable username password policy
  8489. * to ensure that it has the correct transport.
  8490. * @private
  8491. * @param {object} policyNode The policy node to check.
  8492. * @returns {string} If the policy matches the desired transport then the id of the policy is returned.
  8493. * If not then null is returned.
  8494. */
  8495. Mex.prototype._checkPolicy = function(policyNode) {
  8496. var policyId = null;
  8497. var id = policyNode.getAttributeNS(Namespaces.wsu, 'Id');
  8498. var transportBindingNodes = select(policyNode, TRANSPORT_BINDING_XPATH);
  8499. if (0 === transportBindingNodes.length) {
  8500. transportBindingNodes = select(policyNode, TRANSPORT_BINDING_2005_XPATH);
  8501. }
  8502. if (0 !== transportBindingNodes.length) {
  8503. if (id) {
  8504. policyId = id;
  8505. }
  8506. }
  8507. if (policyId) {
  8508. this._log.verbose('found matching policy id');
  8509. this._log.verbose('found matching policy id: ' + policyId, true);
  8510. } else {
  8511. if (!id) {
  8512. id = '<no id>';
  8513. }
  8514. this._log.verbose('potential policy did not match required transport binding');
  8515. this._log.verbose('potential policy did not match required transport binding: ' + id, true);
  8516. }
  8517. return policyId;
  8518. };
  8519. /**
  8520. * Finds all username password policies within the mex document.
  8521. * @private
  8522. * @param xpath The xpath expression for selecting username token nodes.
  8523. * @returns {object} A map object that contains objects containing the id of username password polices.
  8524. */
  8525. Mex.prototype._selectUsernamePasswordPolicies = function(xpath) {
  8526. var policies = {};
  8527. var usernameTokenNodes = select(this._dom, xpath);
  8528. if (!usernameTokenNodes.length) {
  8529. this._log.warn('no username token policy nodes found');
  8530. return;
  8531. }
  8532. for (var i=0; i < usernameTokenNodes.length; i++) {
  8533. var policyNode = usernameTokenNodes[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
  8534. var id = this._checkPolicy(policyNode);
  8535. if (id) {
  8536. var idRef = '#' + id;
  8537. policies[idRef] = { id : idRef };
  8538. }
  8539. }
  8540. return _.isEmpty(policies) ? null : policies;
  8541. };
  8542. var SOAP_ACTION_XPATH = 'wsdl:operation/soap12:operation/@soapAction';
  8543. var RST_SOAP_ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue';
  8544. var RST_SOAP_ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue';
  8545. var SOAP_TRANSPORT_XPATH = 'soap12:binding/@transport';
  8546. var SOAP_HTTP_TRANSPORT_VALUE = 'http://schemas.xmlsoap.org/soap/http';
  8547. /**
  8548. * Given a DOM binding node determines whether it matches the correct soap action and transport.
  8549. * @private
  8550. * @param {object} bindingNode The DOM node to check.
  8551. * @returns {bool}
  8552. */
  8553. Mex.prototype._checkSoapActionAndTransport = function(bindingNode) {
  8554. var soapTransportAttributes;
  8555. var soapAction;
  8556. var soapTransport;
  8557. var bindingName = bindingNode.getAttribute('name');
  8558. var soapActionAttributes = select(bindingNode, SOAP_ACTION_XPATH);
  8559. if (soapActionAttributes.length) {
  8560. soapAction = soapActionAttributes[0].value;
  8561. soapTransportAttributes = select(bindingNode, SOAP_TRANSPORT_XPATH);
  8562. }
  8563. if (soapTransportAttributes.length) {
  8564. soapTransport = soapTransportAttributes[0].value;
  8565. }
  8566. if (soapTransport === SOAP_HTTP_TRANSPORT_VALUE) {
  8567. if (soapAction === RST_SOAP_ACTION_13) {
  8568. this._log.verbose('foud binding matching Action and Transport: ' + bindingName);
  8569. return WSTrustVersion.WSTRUST13;
  8570. }
  8571. else if (soapAction === RST_SOAP_ACTION_2005) {
  8572. this._log.verbose('found binding matching Action and Transport: ' + bindingName);
  8573. return WSTrustVersion.WSTRUST2005;
  8574. }
  8575. }
  8576. this._log.verbose('binding node did not match soap Action or Transport: ' + bindingName);
  8577. return WSTrustVersion.UNDEFINED;
  8578. };
  8579. /**
  8580. * Given a map with policy id keys, finds the bindings in the mex document that are linked to thos policies.
  8581. * @private
  8582. * @param {object} policies A map with policy id keys.
  8583. * @returns {object} a map of bindings id's to policy id's.
  8584. */
  8585. Mex.prototype._getMatchingBindings = function(policies) {
  8586. var bindings = {};
  8587. var bindingPolicyRefNodes = select(this._dom, '//wsdl:definitions/wsdl:binding/wsp:PolicyReference');
  8588. for (var i=0; i < bindingPolicyRefNodes.length; i++) {
  8589. var node = bindingPolicyRefNodes[i];
  8590. var uri = node.getAttribute('URI');
  8591. var policy = policies[uri];
  8592. if (policy) {
  8593. var bindingNode = node.parentNode;
  8594. var bindingName = bindingNode.getAttribute('name');
  8595. var version = this._checkSoapActionAndTransport(bindingNode);
  8596. if (version !== WSTrustVersion.UNDEFINED) {
  8597. var bindingPolicy = {};
  8598. bindingPolicy.url = uri;
  8599. bindingPolicy.version = version;
  8600. bindings[bindingName] = bindingPolicy;
  8601. }
  8602. }
  8603. }
  8604. return _.isEmpty(bindings) ? null : bindings;
  8605. };
  8606. /**
  8607. * Ensures that a url points to an SSL endpoint.
  8608. * @private
  8609. * @param {string} endpointUrl The url to check.
  8610. * @returns {bool}
  8611. */
  8612. Mex.prototype._urlIsSecure = function(endpointUrl) {
  8613. var parsedUrl = url.parse(endpointUrl);
  8614. return parsedUrl.protocol === 'https:';
  8615. };
  8616. var PORT_XPATH = '//wsdl:definitions/wsdl:service/wsdl:port';
  8617. var ADDRESS_XPATH = 'wsa10:EndpointReference/wsa10:Address';
  8618. /**
  8619. * Finds all of the wsdl ports in the mex document that are associated with username password policies. Augments
  8620. * the passed in bindings with the endpoint url of the correct port.
  8621. * @private
  8622. * @param {object} bindings A map of binding id's to policy id's.
  8623. */
  8624. Mex.prototype._getPortsForPolicyBindings = function(bindings, policies) {
  8625. var portNodes = select(this._dom, PORT_XPATH);
  8626. if (0 === portNodes.length) {
  8627. this._log.warning('no ports found');
  8628. }
  8629. for (var i=0; i < portNodes.length; i++) {
  8630. var portNode = portNodes[i];
  8631. var bindingId = portNode.getAttribute('binding');
  8632. // Clear any prefix
  8633. var bindingIdParts = bindingId.split(':');
  8634. bindingId = bindingIdParts[bindingIdParts.length - 1];
  8635. var trustPolicy = bindings[bindingId];
  8636. if (trustPolicy) {
  8637. var bindingPolicy = policies[trustPolicy.url];
  8638. if (bindingPolicy && !bindingPolicy.url) {
  8639. bindingPolicy.version = trustPolicy.version;
  8640. var addressNode = select(portNode, ADDRESS_XPATH);
  8641. if (0 === addressNode) {
  8642. throw this._log.createError('no address nodes on port.');
  8643. }
  8644. var address = xmlutil.findElementText(addressNode[0]);
  8645. if (this._urlIsSecure(address)) {
  8646. bindingPolicy.url = address;
  8647. } else {
  8648. this._log.warn('skipping insecure endpoint: ' + address);
  8649. }
  8650. }
  8651. }
  8652. }
  8653. };
  8654. /**
  8655. * Given a list of username password policies chooses one of them at random as the policy chosen by this Mex instance.
  8656. * @private
  8657. * @param {object} policies A map of policy id's to an object containing username password ws-trust endpoint addresses.
  8658. */
  8659. Mex.prototype._selectSingleMatchingPolicy = function(policies) {
  8660. // if both wstrust13 and wstrust2005 policy exists, then choose wstrust13, otherwise choose whatever exists.
  8661. var matchingPolicies = _.filter(policies, function(policy) { return policy.url ? true : false; });
  8662. if (!matchingPolicies) {
  8663. this._log.warn('no policies found with an url');
  8664. return;
  8665. }
  8666. var wstrust13Policy = null, wstrust2005Policy = null;
  8667. for(var i = 0; i < matchingPolicies.length; ++i) {
  8668. var matchingPolicy = matchingPolicies[i];
  8669. if (WSTrustVersion.WSTRUST13 === matchingPolicy.version) {
  8670. wstrust13Policy = matchingPolicy;
  8671. }
  8672. else if (WSTrustVersion.WSTRUST2005 === matchingPolicy.version) {
  8673. wstrust2005Policy = matchingPolicy;
  8674. }
  8675. }
  8676. if (!wstrust13Policy && !wstrust2005Policy) {
  8677. this._log.warn('no policies found with an url');
  8678. this._usernamePasswordPolicy = null;
  8679. return;
  8680. }
  8681. this._usernamePasswordPolicy = wstrust13Policy ? wstrust13Policy : wstrust2005Policy;
  8682. };
  8683. /**
  8684. * Parses the mex document previously retrieved.
  8685. * @private
  8686. * @param {Mex.DiscoverCallback} callback
  8687. */
  8688. Mex.prototype._parse = function(callback) {
  8689. var self = this;
  8690. var xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp:SignedEncryptedSupportingTokens/wsp:Policy/sp:UsernameToken/wsp:Policy/sp:WssUsernameToken10';
  8691. var policies = self._selectUsernamePasswordPolicies(xpathExpression);
  8692. xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10';
  8693. if (policies) {
  8694. _.extend(policies, self._selectUsernamePasswordPolicies(xpathExpression));
  8695. }
  8696. else {
  8697. policies = self._selectUsernamePasswordPolicies(xpathExpression);
  8698. }
  8699. if (!policies) {
  8700. callback(self._log.createError('No matching policies'));
  8701. return;
  8702. }
  8703. var bindings = self._getMatchingBindings(policies);
  8704. if (!bindings) {
  8705. callback(self._log.createError('No matching bindings'));
  8706. return;
  8707. }
  8708. self._getPortsForPolicyBindings(bindings, policies);
  8709. self._selectSingleMatchingPolicy(policies);
  8710. var err = this._url ? undefined : this._log.createError('No ws-trust endpoints match requirements.');
  8711. callback(err);
  8712. };
  8713. module.exports = Mex;
  8714. },{"./constants":26,"./log":27,"./util":34,"./xmlutil":37,"request":546,"underscore":651,"url":653,"xmldom":705}],30:[function(require,module,exports){
  8715. /*
  8716. * @copyright
  8717. * Copyright © Microsoft Open Technologies, Inc.
  8718. *
  8719. * All Rights Reserved
  8720. *
  8721. * Licensed under the Apache License, Version 2.0 (the "License");
  8722. * you may not use this file except in compliance with the License.
  8723. * You may obtain a copy of the License at
  8724. *
  8725. * http: *www.apache.org/licenses/LICENSE-2.0
  8726. *
  8727. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  8728. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  8729. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  8730. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  8731. *
  8732. * See the Apache License, Version 2.0 for the specific language
  8733. * governing permissions and limitations under the License.
  8734. */
  8735. 'use strict';
  8736. var _ = require('underscore');
  8737. require('date-utils'); // Adds a number of convenience methods to the builtin Date object.
  8738. var querystring = require('querystring');
  8739. var uuid = require('uuid');
  8740. var request = require('request');
  8741. var url = require('url');
  8742. var async = require('async');
  8743. var constants = require('./constants');
  8744. var Logger = require('./log').Logger;
  8745. var util = require('./util');
  8746. var OAuth2Parameters = constants.OAuth2.Parameters;
  8747. var OAuth2ResponseParameters = constants.OAuth2.ResponseParameters;
  8748. var DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters;
  8749. var IdTokenMap = constants.OAuth2.IdTokenMap;
  8750. var TokenResponseFields = constants.TokenResponseFields;
  8751. var UserCodeResponseFields = constants.UserCodeResponseFields;
  8752. var IdTokenFields = constants.IdTokenFields;
  8753. var TOKEN_RESPONSE_MAP = {};
  8754. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE;
  8755. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN;
  8756. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN;
  8757. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON;
  8758. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON;
  8759. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN;
  8760. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE;
  8761. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR;
  8762. TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION;
  8763. var DEVICE_CODE_RESPONSE_MAP = {};
  8764. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE;
  8765. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE;
  8766. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL;
  8767. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL;
  8768. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN;
  8769. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE;
  8770. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR;
  8771. DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION;
  8772. /**
  8773. * Constructs an instances of OAuth2Client
  8774. * @constructor
  8775. * @private
  8776. * @param {object} callContext Contains any context information that applies to the request.
  8777. * @param {string|url} authority An url that points to an authority.
  8778. */
  8779. function OAuth2Client(callContext, authority) {
  8780. this._tokenEndpoint = authority.tokenEndpoint;
  8781. this._deviceCodeEndpoint = authority.deviceCodeEndpoint;
  8782. this._log = new Logger('OAuth2Client', callContext._logContext);
  8783. this._callContext = callContext;
  8784. this._cancelPollingRequest = false;
  8785. }
  8786. /**
  8787. * Constructs an OAuth 2.0 token request url.
  8788. * @private
  8789. * @return {URL}
  8790. */
  8791. OAuth2Client.prototype._createTokenUrl = function () {
  8792. var tokenUrl = url.parse(this._tokenEndpoint);
  8793. var parameters = {};
  8794. parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0';
  8795. tokenUrl.search = querystring.stringify(parameters);
  8796. return tokenUrl;
  8797. };
  8798. /**
  8799. * Constructs the user code info request url.
  8800. * @private
  8801. * @return {URL}
  8802. */
  8803. OAuth2Client.prototype._createDeviceCodeUrl = function () {
  8804. var deviceCodeUrl = url.parse(this._deviceCodeEndpoint);
  8805. var parameters = {};
  8806. parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0';
  8807. deviceCodeUrl.search = querystring.stringify(parameters);
  8808. return deviceCodeUrl;
  8809. };
  8810. /**
  8811. * @private
  8812. * @param {object} obj An object in which integer values may reside.
  8813. * @param {array} keys An array of strings that specify keys in which integers may need parsing.
  8814. */
  8815. OAuth2Client.prototype._parseOptionalInts = function (obj, keys) {
  8816. var self = this;
  8817. keys.forEach(function(element) {
  8818. if (_.has(obj, element)) {
  8819. obj[element] = parseInt(obj[element], 10);
  8820. if (isNaN(obj[element])) {
  8821. throw self._log.createError(element + ' could not be parsed as an int.');
  8822. }
  8823. }
  8824. });
  8825. };
  8826. /**
  8827. * Parses a JWS encoded JWT into it's three parts.
  8828. * @param {string} jwtToken The token to parse.
  8829. * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined.
  8830. */
  8831. OAuth2Client.prototype._crackJwt = function(jwtToken) {
  8832. var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
  8833. var matches = idTokenPartsRegex.exec(jwtToken);
  8834. if (!matches || matches.length < 4) {
  8835. this._log.warn('The returned id_token is not parseable.');
  8836. return;
  8837. }
  8838. var crackedToken = {
  8839. header : matches[1],
  8840. JWSPayload : matches[2],
  8841. JWSSig : matches[3]
  8842. };
  8843. return crackedToken;
  8844. };
  8845. /**
  8846. * Finds the value that should be used as the userId value.
  8847. * @param {object} idToken The id token that parsed.
  8848. * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field.
  8849. */
  8850. OAuth2Client.prototype._getUserId = function(idToken) {
  8851. var userId;
  8852. var isDisplayable;
  8853. if (idToken.upn) {
  8854. userId = idToken.upn;
  8855. isDisplayable = true;
  8856. } else if (idToken.email) {
  8857. userId = idToken.email;
  8858. isDisplayable = true;
  8859. } else if (idToken.sub) {
  8860. userId = idToken.sub;
  8861. }
  8862. if (!userId) {
  8863. // generate a random GUID.
  8864. userId = uuid.v4();
  8865. }
  8866. var userIdVals = {};
  8867. userIdVals[IdTokenFields.USER_ID] = userId;
  8868. if (isDisplayable) {
  8869. userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true;
  8870. }
  8871. return userIdVals;
  8872. };
  8873. function mapFields(inObj, outObj, map) {
  8874. for (var key in inObj) {
  8875. if (map[key]) {
  8876. var mappedKey = map[key];
  8877. outObj[mappedKey] = inObj[key];
  8878. }
  8879. }
  8880. }
  8881. /**
  8882. * Given a decoded id token off the wire, this function extracts the values that
  8883. * ADAL commonly returns to callers and translates the names to more user
  8884. * friendly names.
  8885. * @param {Object} idToken A decoded id token.
  8886. * @return {Object} The set of extracted values with their new names.
  8887. */
  8888. OAuth2Client.prototype._extractIdTokenValues = function(idToken) {
  8889. var extractedValues = {};
  8890. _.extend(extractedValues, this._getUserId(idToken));
  8891. mapFields(idToken, extractedValues, IdTokenMap);
  8892. return extractedValues;
  8893. };
  8894. /**
  8895. * Parses the value of the id_token OAuth 2 Reponse.
  8896. * @param {string} encodedIdToken An unencrypted JWT token.
  8897. * @return {object} returns the decoded id_token or undefined.
  8898. */
  8899. OAuth2Client.prototype._parseIdToken = function(encodedIdToken) {
  8900. var crackedToken = this._crackJwt(encodedIdToken);
  8901. if (!crackedToken) {
  8902. return;
  8903. }
  8904. var idToken;
  8905. try {
  8906. var base64IdToken = crackedToken.JWSPayload;
  8907. var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken);
  8908. if (!base64Decoded) {
  8909. this._log.warn('The returned id_token could not be base64 url safe decoded.');
  8910. return;
  8911. }
  8912. idToken = JSON.parse(base64Decoded);
  8913. } catch (err) {
  8914. this._log.warn('the returned id_token could not be decoded');
  8915. this._log.warn('The returned id_token could not be decoded: ' + err.stack, true);
  8916. return;
  8917. }
  8918. return this._extractIdTokenValues(idToken);
  8919. };
  8920. /**
  8921. * Validates the response returned from an OAuth 2.0 token request.
  8922. * @private
  8923. * @param {string} body The response as a string encoded JSON object.
  8924. * @return {object} The parsed response.
  8925. */
  8926. OAuth2Client.prototype._validateTokenResponse = function(body) {
  8927. var wireResponse;
  8928. var tokenResponse = {};
  8929. try {
  8930. wireResponse = JSON.parse(body);
  8931. } catch(e) {
  8932. throw new Error('The token response returned from the server is unparseable as JSON');
  8933. }
  8934. var intKeys = [
  8935. OAuth2ResponseParameters.EXPIRES_ON,
  8936. OAuth2ResponseParameters.EXPIRES_IN,
  8937. OAuth2ResponseParameters.CREATED_ON
  8938. ];
  8939. this._parseOptionalInts(wireResponse, intKeys);
  8940. if (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) {
  8941. var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN];
  8942. var now = new Date();
  8943. wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn });
  8944. }
  8945. if (wireResponse[OAuth2ResponseParameters.CREATED_ON]) {
  8946. var tempDate = new Date();
  8947. var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON];
  8948. tempDate.setTime(createdOn);
  8949. wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate;
  8950. }
  8951. if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) {
  8952. throw this._log.createError('wireResponse is missing token_type');
  8953. }
  8954. if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) {
  8955. throw this._log.createError('wireResponse missing access_token');
  8956. }
  8957. mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP);
  8958. if (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) {
  8959. var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]);
  8960. if (idToken) {
  8961. _.extend(tokenResponse, idToken);
  8962. }
  8963. }
  8964. return tokenResponse;
  8965. };
  8966. /**
  8967. * Validates the response returned from an OAuth 2.0 device code request.
  8968. * @private
  8969. * @param {string} body The response as a string encoded JSON object.
  8970. * @return {object} The parsed response.
  8971. */
  8972. OAuth2Client.prototype._validateDeviceCodeResponse = function(body) {
  8973. var wireResponse;
  8974. var deviceCodeResponse = {};
  8975. try {
  8976. wireResponse = JSON.parse(body);
  8977. } catch(e) {
  8978. throw new Error('The device code response returned from the server is unparseable as JSON.');
  8979. }
  8980. var intKeys = [
  8981. DeviceCodeResponseParameters.EXPIRES_IN,
  8982. DeviceCodeResponseParameters.INTERVAL
  8983. ];
  8984. this._parseOptionalInts(wireResponse, intKeys);
  8985. if (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){
  8986. throw this._log.createError('wireResponse is missing expires_in');
  8987. }
  8988. if (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) {
  8989. throw this._log.createError('wireResponse is missing device code');
  8990. }
  8991. if (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) {
  8992. throw this._log.createError('wireResponse is missing user code');
  8993. }
  8994. mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP);
  8995. return deviceCodeResponse;
  8996. };
  8997. /**
  8998. * @private
  8999. * @param {string} body The body of a http token response.
  9000. */
  9001. OAuth2Client.prototype._handlePollingResponse = function(body) {
  9002. //handle token error response
  9003. var tokenResponse = this._handlePollingRequestErrorResponse(body);
  9004. if (_.isEmpty(tokenResponse)){
  9005. tokenResponse = this._validateTokenResponse(body);
  9006. }
  9007. return tokenResponse;
  9008. };
  9009. /**
  9010. * @private
  9011. * @param {string} body The body of a http token response.
  9012. */
  9013. OAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) {
  9014. var wireResponse;
  9015. var tokenResponse = {};
  9016. try {
  9017. wireResponse = JSON.parse(body);
  9018. } catch (e) {
  9019. throw new Error ('The token response returned from the server is unparsable as JSON');
  9020. }
  9021. if (wireResponse[OAuth2ResponseParameters.ERROR]) {
  9022. mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP);
  9023. }
  9024. return tokenResponse;
  9025. };
  9026. /**
  9027. * @private
  9028. * @param {object} response An http response object.
  9029. * @param {string} body The body of a http token response.
  9030. * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed
  9031. * into this function.
  9032. */
  9033. OAuth2Client.prototype._handleGetTokenResponse = function(response, body, callback) {
  9034. var tokenResponse;
  9035. try {
  9036. tokenResponse = this._validateTokenResponse(body);
  9037. } catch (e) {
  9038. this._log.error('Error validating get token response', e, true);
  9039. callback(e);
  9040. return;
  9041. }
  9042. callback(null, tokenResponse);
  9043. };
  9044. OAuth2Client.prototype._handleGetDeviceCodeResponse = function(response, body, callback) {
  9045. var deviceCodeResponse;
  9046. try {
  9047. deviceCodeResponse = this._validateDeviceCodeResponse(body);
  9048. } catch (e) {
  9049. this._log.error('Error validating get user code response', e, true);
  9050. callback(e);
  9051. return;
  9052. }
  9053. callback(null, deviceCodeResponse);
  9054. };
  9055. OAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) {
  9056. var self = this;
  9057. if (self._cancelPollingRequest === true) {
  9058. callback(null, new Error('Polling_Request_Cancelled'));
  9059. return;
  9060. }
  9061. request.post(postOptions, util.createRequestHandler('Get Token', this._log, function(response, body) {
  9062. //error response callback, for error response, it's already parsed as Json.
  9063. if (body && body.hasOwnProperty(TokenResponseFields.ERROR) && body[TokenResponseFields.ERROR] === 'authorization_pending') {
  9064. callback(new Error(body[TokenResponseFields.ERROR]), body);
  9065. }
  9066. else {
  9067. callback(null, body);
  9068. }
  9069. },
  9070. // success response callback
  9071. function (response, body) {
  9072. var tokenResponse;
  9073. try {
  9074. tokenResponse = self._handlePollingResponse(body);
  9075. } catch (e) {
  9076. self._log.error('Error validating get token response', e, true);
  9077. callback(null, e);
  9078. return;
  9079. }
  9080. callback(null, tokenResponse);
  9081. })
  9082. );
  9083. };
  9084. OAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) {
  9085. var postOptions = util.createRequestOptions(
  9086. this,
  9087. {
  9088. 'url' : url.format(postUrl),
  9089. body : urlEncodedRequestForm,
  9090. headers: {
  9091. 'Content-Type': 'application/x-www-form-urlencoded'
  9092. },
  9093. followRedirect : false,
  9094. encoding : 'utf8'
  9095. }
  9096. );
  9097. return postOptions;
  9098. };
  9099. /**
  9100. * @callback GetTokenCallback
  9101. * @memberOf OAuth2Client
  9102. * @param {Error} [error] In case of an error this will hold the associated Error object.
  9103. * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request.
  9104. */
  9105. /**
  9106. * @param {object} oauthParameters An object whose keys come from
  9107. * Constants.OAuth2.Parameters
  9108. * @param {OAuth2Client.GetTokenCallback} callback The callback function.
  9109. */
  9110. OAuth2Client.prototype.getToken = function(oauthParameters, callback) {
  9111. var self = this;
  9112. var tokenUrl = self._createTokenUrl();
  9113. var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters);
  9114. var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm);
  9115. request.post(postOptions, util.createRequestHandler('Get Token', this._log, callback,
  9116. function (response, body) {
  9117. self._handleGetTokenResponse(response, body, callback);
  9118. })
  9119. );
  9120. };
  9121. /**
  9122. * @param {object} oauthParameters An object whose keys come from
  9123. * Constants.OAuth2.Parameters
  9124. * @param {integer} refresh_interval The interval for polling request.
  9125. * @param {integer} exipres_in The timeout for polling request.
  9126. * @param {OAuth2Client.GetTokenCallback} callback The callback function.
  9127. */
  9128. OAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){
  9129. var self = this;
  9130. var maxTimesForRetry = Math.floor(expires_in / refresh_interval);
  9131. var tokenUrl = self._createTokenUrl();
  9132. var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters);
  9133. var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm);
  9134. var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000};
  9135. async.retry(optionsForRetry, function(retryCallback, response) {
  9136. self._getTokenWithPolling(postOptions, retryCallback);
  9137. }, function(err, response) {
  9138. if (response && response instanceof Error) {
  9139. callback(response);
  9140. return;
  9141. }
  9142. else if (response && response.hasOwnProperty(DeviceCodeResponseParameters.ERROR)) {
  9143. callback(response);
  9144. return;
  9145. }
  9146. callback(err, response);
  9147. });
  9148. };
  9149. OAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) {
  9150. // for now make it as a post request
  9151. var self = this;
  9152. var deviceCodeUrl = self._createDeviceCodeUrl();
  9153. var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters);
  9154. var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm);
  9155. request.post(postOptions, util.createRequestHandler('Get Device Code ', this._log, callback,
  9156. function (response, body) {
  9157. self._handleGetDeviceCodeResponse(response, body, callback);
  9158. })
  9159. );
  9160. };
  9161. /**
  9162. * Cancel the polling request made for acquiring token by device code.
  9163. */
  9164. OAuth2Client.prototype.cancelPollingRequest = function() {
  9165. this._cancelPollingRequest = true;
  9166. };
  9167. module.exports = OAuth2Client;
  9168. },{"./constants":26,"./log":27,"./util":34,"async":109,"date-utils":209,"querystring":543,"request":546,"underscore":651,"url":653,"uuid":659}],31:[function(require,module,exports){
  9169. (function (Buffer){(function (){
  9170. /*
  9171. * @copyright
  9172. * Copyright © Microsoft Open Technologies, Inc.
  9173. *
  9174. * All Rights Reserved
  9175. *
  9176. * Licensed under the Apache License, Version 2.0 (the "License");
  9177. * you may not use this file except in compliance with the License.
  9178. * You may obtain a copy of the License at
  9179. *
  9180. * http: *www.apache.org/licenses/LICENSE-2.0
  9181. *
  9182. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  9183. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  9184. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  9185. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  9186. *
  9187. * See the Apache License, Version 2.0 for the specific language
  9188. * governing permissions and limitations under the License.
  9189. */
  9190. 'use strict';
  9191. var jwtConstants = require('./constants').Jwt;
  9192. var Logger = require('./log').Logger;
  9193. var util = require('./util');
  9194. require('date-utils');
  9195. var jws = require('jws');
  9196. var uuid = require('uuid');
  9197. /**
  9198. * JavaScript dates are in milliseconds, but JWT dates are in seconds.
  9199. * This function does the conversion.
  9200. * @param {Date} date
  9201. * @return {string}
  9202. */
  9203. function dateGetTimeInSeconds(date) {
  9204. return Math.floor(date.getTime()/1000);
  9205. }
  9206. /**
  9207. * Constructs a new SelfSignedJwt object.
  9208. * @param {object} callContext Context specific to this token request.
  9209. * @param {Authority} authority The authority to be used as the JWT audience.
  9210. * @param {string} clientId The client id of the calling app.
  9211. */
  9212. function SelfSignedJwt(callContext, authority, clientId) {
  9213. this._log = new Logger('SelfSignedJwt', callContext._logContext);
  9214. this._callContext = callContext;
  9215. this._authority = authority;
  9216. this._tokenEndpoint = authority.tokenEndpoint;
  9217. this._clientId = clientId;
  9218. }
  9219. /**
  9220. * This wraps date creation in order to make unit testing easier.
  9221. * @return {Date}
  9222. */
  9223. SelfSignedJwt.prototype._getDateNow = function() {
  9224. return new Date();
  9225. };
  9226. SelfSignedJwt.prototype._getNewJwtId = function() {
  9227. return uuid.v4();
  9228. };
  9229. /**
  9230. * A regular certificate thumbprint is a hex encode string of the binary certificate
  9231. * hash. For some reason teh x5t value in a JWT is a url save base64 encoded string
  9232. * instead. This function does the conversion.
  9233. * @param {string} thumbprint A hex encoded certificate thumbprint.
  9234. * @return {string} A url safe base64 encoded certificate thumbprint.
  9235. */
  9236. SelfSignedJwt.prototype._createx5tValue = function(thumbprint) {
  9237. var hexString = thumbprint.replace(/:/g, '').replace(/ /g, '');
  9238. var base64 = (new Buffer(hexString, 'hex')).toString('base64');
  9239. return util.convertRegularToUrlSafeBase64EncodedString(base64);
  9240. };
  9241. /**
  9242. * Creates the JWT header.
  9243. * @param {string} thumbprint A hex encoded certificate thumbprint.
  9244. * @return {object}
  9245. */
  9246. SelfSignedJwt.prototype._createHeader = function(thumbprint) {
  9247. var x5t = this._createx5tValue(thumbprint);
  9248. var header = { typ: 'JWT', alg: 'RS256', x5t : x5t };
  9249. this._log.verbose('Creating self signed JWT header');
  9250. this._log.verbose('Creating self signed JWT header. x5t: ' + x5t, true);
  9251. return header;
  9252. };
  9253. /**
  9254. * Creates the JWT payload.
  9255. * @return {object}
  9256. */
  9257. SelfSignedJwt.prototype._createPayload = function() {
  9258. var now = this._getDateNow();
  9259. var expires = (new Date(now.getTime())).addMinutes(jwtConstants.SELF_SIGNED_JWT_LIFETIME);
  9260. this._log.verbose('Creating self signed JWT payload. Expires: ' + expires + ' NotBefore: ' + now);
  9261. var jwtPayload = {};
  9262. jwtPayload[jwtConstants.AUDIENCE] = this._tokenEndpoint;
  9263. jwtPayload[jwtConstants.ISSUER] = this._clientId;
  9264. jwtPayload[jwtConstants.SUBJECT] = this._clientId;
  9265. jwtPayload[jwtConstants.NOT_BEFORE] = dateGetTimeInSeconds(now);
  9266. jwtPayload[jwtConstants.EXPIRES_ON] = dateGetTimeInSeconds(expires);
  9267. jwtPayload[jwtConstants.JWT_ID] = this._getNewJwtId();
  9268. return jwtPayload;
  9269. };
  9270. SelfSignedJwt.prototype._throwOnInvalidJwtSignature = function(jwt) {
  9271. var jwtSegments = jwt.split('.');
  9272. if (3 > jwtSegments.length || !jwtSegments[2]) {
  9273. throw this._log.createError('Failed to sign JWT. This is most likely due to an invalid certificate.');
  9274. }
  9275. return;
  9276. };
  9277. SelfSignedJwt.prototype._signJwt = function(header, payload, certificate) {
  9278. var jwt;
  9279. try {
  9280. jwt = jws.sign({ header : header, payload : payload, secret : certificate });
  9281. }
  9282. catch (err) {
  9283. this._log.error(err, true);
  9284. throw this._log.createError('Failed to sign JWT.This is most likely due to an invalid certificate.');
  9285. }
  9286. this._throwOnInvalidJwtSignature(jwt);
  9287. return jwt;
  9288. };
  9289. SelfSignedJwt.prototype._reduceThumbprint = function(thumbprint) {
  9290. var canonical = thumbprint.toLowerCase().replace(/ /g, '').replace(/:/g, '');
  9291. this._throwOnInvalidThumbprint(canonical);
  9292. return canonical;
  9293. };
  9294. var numCharIn128BitHexString = 128/8*2;
  9295. var numCharIn160BitHexString = 160/8*2;
  9296. var thumbprintSizes = {};
  9297. thumbprintSizes[numCharIn128BitHexString] = true;
  9298. thumbprintSizes[numCharIn160BitHexString] = true;
  9299. var thumbprintRegExp = /^[a-f\d]*$/;
  9300. SelfSignedJwt.prototype._throwOnInvalidThumbprint = function(thumbprint) {
  9301. if (!thumbprintSizes[thumbprint.length] || !thumbprintRegExp.test(thumbprint)) {
  9302. throw this._log.createError('The thumbprint does not match a known format');
  9303. }
  9304. };
  9305. /**
  9306. * Creates a self signed JWT that can be used as a client_assertion.
  9307. * @param {string} certificate A PEM encoded certificate private key.
  9308. * @param {string} thumbprint A hex encoded thumbprint of the certificate.
  9309. * @return {string} A self signed JWT token.
  9310. */
  9311. SelfSignedJwt.prototype.create = function(certificate, thumbprint) {
  9312. thumbprint = this._reduceThumbprint(thumbprint);
  9313. var header = this._createHeader(thumbprint);
  9314. var payload = this._createPayload();
  9315. var jwt = this._signJwt(header, payload, certificate);
  9316. return jwt;
  9317. };
  9318. module.exports = SelfSignedJwt;
  9319. }).call(this)}).call(this,require("buffer").Buffer)
  9320. },{"./constants":26,"./log":27,"./util":34,"buffer":193,"date-utils":209,"jws":334,"uuid":659}],32:[function(require,module,exports){
  9321. (function (Buffer){(function (){
  9322. /*
  9323. * @copyright
  9324. * Copyright © Microsoft Open Technologies, Inc.
  9325. *
  9326. * All Rights Reserved
  9327. *
  9328. * Licensed under the Apache License, Version 2.0 (the "License");
  9329. * you may not use this file except in compliance with the License.
  9330. * You may obtain a copy of the License at
  9331. *
  9332. * http: *www.apache.org/licenses/LICENSE-2.0
  9333. *
  9334. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  9335. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  9336. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  9337. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  9338. *
  9339. * See the Apache License, Version 2.0 for the specific language
  9340. * governing permissions and limitations under the License.
  9341. */
  9342. 'use strict';
  9343. var constants = require('./constants');
  9344. var CacheDriver = require('./cache-driver');
  9345. var Logger = require('./log').Logger;
  9346. var Mex = require('./mex');
  9347. var OAuth2Client = require('./oauth2client');
  9348. var SelfSignedJwt = require('./self-signed-jwt');
  9349. var UserRealm = require('./user-realm');
  9350. var WSTrustRequest = require('./wstrust-request');
  9351. var OAuth2Parameters = constants.OAuth2.Parameters;
  9352. var TokenResponseFields = constants.TokenResponseFields;
  9353. var OAuth2GrantType = constants.OAuth2.GrantType;
  9354. var OAuth2Scope = constants.OAuth2.Scope;
  9355. var Saml = constants.Saml;
  9356. var AccountType = constants.UserRealm.AccountType;
  9357. var WSTrustVersion = constants.WSTrustVersion;
  9358. var DeviceCodeResponseParameters = constants.UserCodeResponseFields;
  9359. /**
  9360. * Constructs a new TokenRequest object.
  9361. * @constructor
  9362. * @private
  9363. * @param {object} callContext Contains any context information that applies to the request.
  9364. * @param {AuthenticationContext} authenticationContext
  9365. * @param {string} resource
  9366. * @param {string} clientId
  9367. * @param {string} redirectUri
  9368. */
  9369. function TokenRequest(callContext, authenticationContext, clientId, resource, redirectUri) {
  9370. this._log = new Logger('TokenRequest', callContext._logContext);
  9371. this._callContext = callContext;
  9372. this._authenticationContext = authenticationContext;
  9373. this._resource = resource;
  9374. this._clientId = clientId;
  9375. this._redirectUri = redirectUri;
  9376. // This should be set at the beginning of getToken
  9377. // functions that have a userId.
  9378. this._userId = null;
  9379. this._userRealm = null;
  9380. this._pollingClient = {};
  9381. }
  9382. TokenRequest.prototype._createUserRealmRequest = function(username) {
  9383. return new UserRealm(this._callContext, username, this._authenticationContext.authority);
  9384. };
  9385. TokenRequest.prototype._createMex = function(mexEndpoint) {
  9386. return new Mex(this._callContext, mexEndpoint);
  9387. };
  9388. TokenRequest.prototype._createWSTrustRequest = function(wstrustEndpoint, appliesTo, wstrustEndpointVersion) {
  9389. return new WSTrustRequest(this._callContext, wstrustEndpoint, appliesTo, wstrustEndpointVersion);
  9390. };
  9391. TokenRequest.prototype._createOAuth2Client = function() {
  9392. return new OAuth2Client(this._callContext, this._authenticationContext._authority);
  9393. };
  9394. TokenRequest.prototype._createSelfSignedJwt = function() {
  9395. return new SelfSignedJwt(this._callContext, this._authenticationContext._authority, this._clientId);
  9396. };
  9397. TokenRequest.prototype._oauthGetToken = function(oauthParameters, callback) {
  9398. var client = this._createOAuth2Client();
  9399. client.getToken(oauthParameters, callback);
  9400. };
  9401. TokenRequest.prototype._oauthGetTokenByPolling = function(oauthParameters, refresh_interval, expires_in, callback){
  9402. var client = this._createOAuth2Client();
  9403. client.getTokenWithPolling(oauthParameters, refresh_interval, expires_in, callback);
  9404. this._pollingClient = client;
  9405. }
  9406. TokenRequest.prototype._createCacheDriver = function() {
  9407. return new CacheDriver(
  9408. this._callContext,
  9409. this._authenticationContext.authority,
  9410. this._resource,
  9411. this._clientId,
  9412. this._authenticationContext.cache,
  9413. this._getTokenWithTokenResponse.bind(this)
  9414. );
  9415. };
  9416. /**
  9417. * Used by the cache driver to refresh tokens.
  9418. * @param {TokenResponse} entry A token response to refresh.
  9419. * @param {string} resource The resource for which to get the token.
  9420. * @param {AcquireTokenCallback} callback
  9421. */
  9422. TokenRequest.prototype._getTokenWithTokenResponse = function(entry, resource, callback) {
  9423. this._log.verbose('Called to refresh a token from the cache.');
  9424. var refreshToken = entry[TokenResponseFields.REFRESH_TOKEN];
  9425. this._getTokenWithRefreshToken(refreshToken, resource, null, callback);
  9426. };
  9427. TokenRequest.prototype._createCacheQuery = function() {
  9428. var query = {
  9429. clientId : this._clientId
  9430. };
  9431. if (this._userId) {
  9432. query.userId = this._userId;
  9433. } else {
  9434. this._log.verbose('No userId passed for cache query.');
  9435. }
  9436. return query;
  9437. };
  9438. TokenRequest.prototype._getTokenWithCacheWrapper = function(callback, getTokenFunc) {
  9439. var self = this;
  9440. this._cacheDriver = this._createCacheDriver();
  9441. var cacheQuery = this._createCacheQuery();
  9442. this._cacheDriver.find(cacheQuery, function(err, token) {
  9443. if (err) {
  9444. self._log.warn('Attempt to look for token in cahce resulted in Error');
  9445. self._log.warn('Attempt to look for token in cache resulted in Error: ' + err.stack, true);
  9446. }
  9447. if (!token) {
  9448. self._log.verbose('No appropriate cached token found.');
  9449. getTokenFunc.call(self, function(err, tokenResponse) {
  9450. if (err) {
  9451. self._log.verbose('getTokenFunc returned with err');
  9452. callback(err, tokenResponse);
  9453. return;
  9454. }
  9455. self._log.verbose('Successfully retrieved token from authority');
  9456. self._cacheDriver.add(tokenResponse, function() {
  9457. callback(null, tokenResponse);
  9458. });
  9459. });
  9460. } else {
  9461. self._log.info('Returning cached token.');
  9462. callback(err, token);
  9463. }
  9464. });
  9465. };
  9466. /**
  9467. * Store token into cache.
  9468. * @param {object} tokenResponse Token response to be added into the cache.
  9469. */
  9470. TokenRequest.prototype._addTokenIntoCache = function(tokenResponse, callback) {
  9471. this._cacheDriver = this._createCacheDriver();
  9472. this._log.verbose('Storing retrieved token into cache');
  9473. this._cacheDriver.add(tokenResponse, function(err) {
  9474. callback(err, tokenResponse);
  9475. });
  9476. };
  9477. /**
  9478. * Adds an OAuth parameter to the paramters object if the parameter is
  9479. * not null or undefined.
  9480. * @private
  9481. * @param {object} parameters OAuth parameters object.
  9482. * @param {string} key A member of the OAuth2Parameters constants.
  9483. * @param {object} value
  9484. */
  9485. function _addParameterIfAvailable(parameters, key, value) {
  9486. if (value) {
  9487. parameters[key] = value;
  9488. }
  9489. }
  9490. /**
  9491. * Creates a set of basic, common, OAuthParameters based on values that the TokenRequest
  9492. * was created with.
  9493. * @private
  9494. * @param {string} grantType A member of the OAuth2GrantType constants.
  9495. * @return {object}
  9496. */
  9497. TokenRequest.prototype._createOAuthParameters = function(grantType) {
  9498. var oauthParameters = {};
  9499. oauthParameters[OAuth2Parameters.GRANT_TYPE] = grantType;
  9500. if (OAuth2GrantType.AUTHORIZATION_CODE !== grantType &&
  9501. OAuth2GrantType.CLIENT_CREDENTIALS !== grantType &&
  9502. OAuth2GrantType.DEVICE_CODE != grantType) {
  9503. oauthParameters[OAuth2Parameters.SCOPE] = OAuth2Scope.OPENID;
  9504. }
  9505. _addParameterIfAvailable(oauthParameters, OAuth2Parameters.CLIENT_ID, this._clientId);
  9506. _addParameterIfAvailable(oauthParameters, OAuth2Parameters.RESOURCE, this._resource);
  9507. _addParameterIfAvailable(oauthParameters, OAuth2Parameters.REDIRECT_URI, this._redirectUri);
  9508. return oauthParameters;
  9509. };
  9510. /**
  9511. * Get's a token from AAD using a username and password
  9512. * @private
  9513. * @param {string} username
  9514. * @param {string} password
  9515. * @param {AcquireTokenCallback} callback
  9516. */
  9517. TokenRequest.prototype._getTokenUsernamePasswordManaged = function(username, password, callback) {
  9518. this._log.verbose('Acquiring token with username password for managed user');
  9519. var oauthParameters = this._createOAuthParameters(OAuth2GrantType.PASSWORD);
  9520. oauthParameters[OAuth2Parameters.PASSWORD] = password;
  9521. oauthParameters[OAuth2Parameters.USERNAME] = username;
  9522. this._oauthGetToken(oauthParameters, callback);
  9523. };
  9524. /**
  9525. * Determines the OAuth SAML grant type to use based on the passed in TokenType
  9526. * that was returned from a RSTR.
  9527. * @param {string} wstrustResponse RSTR token type.
  9528. * @return {string} An OAuth grant type.
  9529. */
  9530. TokenRequest.prototype._getSamlGrantType = function(wstrustResponse) {
  9531. var tokenType = wstrustResponse.tokenType;
  9532. switch (tokenType) {
  9533. case Saml.TokenTypeV1:
  9534. return OAuth2GrantType.SAML1;
  9535. case Saml.TokenTypeV2:
  9536. return OAuth2GrantType.SAML2;
  9537. default:
  9538. throw this._log.createError('RSTR returned unknown token type: ' + tokenType);
  9539. }
  9540. };
  9541. /**
  9542. * Performs an OAuth SAML Assertion grant type exchange. Uses a SAML token as the credential for getting
  9543. * an OAuth access token.
  9544. * @param {WSTrustResponse} wstrustResponse A response from a WSTrustRequest
  9545. * @param {AcquireTokenCallback} callback callback
  9546. */
  9547. TokenRequest.prototype._performWSTrustAssertionOAuthExchange = function(wstrustResponse, callback) {
  9548. this._log.verbose('Performing OAuth assertion grant type exchange.');
  9549. var oauthParameters;
  9550. try {
  9551. var grantType = this._getSamlGrantType(wstrustResponse);
  9552. var assertion = new Buffer(wstrustResponse.token).toString('base64');
  9553. oauthParameters = this._createOAuthParameters(grantType);
  9554. oauthParameters[OAuth2Parameters.ASSERTION] = assertion;
  9555. } catch (err) {
  9556. callback(err);
  9557. return;
  9558. }
  9559. this._oauthGetToken(oauthParameters, callback);
  9560. };
  9561. /**
  9562. * Exchange a username and password for a SAML token from an ADFS instance via WSTrust.
  9563. * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint.
  9564. * @param {string} wstrustEndpointVersion The version of the wstrust endpoint.
  9565. * @param {string} username username
  9566. * @param {string} password password
  9567. * @param {AcquireTokenCallback} callback callback
  9568. */
  9569. TokenRequest.prototype._performWSTrustExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) {
  9570. var self = this;
  9571. var wstrust = this._createWSTrustRequest(wstrustEndpoint, 'urn:federation:MicrosoftOnline', wstrustEndpointVersion);
  9572. wstrust.acquireToken(username, password, function(rstErr, response) {
  9573. if (rstErr) {
  9574. callback(rstErr);
  9575. return;
  9576. }
  9577. if (!response.token) {
  9578. var rstrErr = self._log.createError('Unsucessful RSTR.\n\terror code: ' + response.errorCode + '\n\tfaultMessage: ' + response.faultMessage, true);
  9579. callback(rstrErr);
  9580. return;
  9581. }
  9582. callback(null, response);
  9583. });
  9584. };
  9585. /**
  9586. * Given a username and password this method invokes a WSTrust and OAuth exchange to get an access token.
  9587. * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint.
  9588. * @param {string} username username
  9589. * @param {string} password password
  9590. * @param {AcquireTokenCallback} callback callback
  9591. */
  9592. TokenRequest.prototype._performUsernamePasswordForAccessTokenExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) {
  9593. var self = this;
  9594. this._performWSTrustExchange(wstrustEndpoint, wstrustEndpointVersion, username, password, function(err, wstrustResponse) {
  9595. if (err) {
  9596. callback(err);
  9597. return;
  9598. }
  9599. self._performWSTrustAssertionOAuthExchange(wstrustResponse, callback);
  9600. });
  9601. };
  9602. /**
  9603. * Returns an Error object indicating that AAD did not return a WSTrust endpoint.
  9604. * @return {Error}
  9605. */
  9606. TokenRequest.prototype._createADWSTrustEndpointError = function() {
  9607. return this._log.createError('AAD did not return a WSTrust endpoint. Unable to proceed.');
  9608. };
  9609. /**
  9610. * Gets an OAuth access token using a username and password via a federated ADFS instance.
  9611. * @param {string} username username
  9612. * @param {string} password password
  9613. * @param {AcquireTokenCallback} callback callback
  9614. */
  9615. TokenRequest.prototype._getTokenUsernamePasswordFederated = function(username, password, callback) {
  9616. this._log.verbose('Acquiring token with username password for federated user');
  9617. var self = this;
  9618. if (!this._userRealm.federationMetadataUrl) {
  9619. this._log.warn('Unable to retrieve federationMetadataUrl from AAD. Attempting fallback to AAD supplied endpoint.');
  9620. if (!this._userRealm.federationActiveAuthUrl) {
  9621. callback(this._createADWSTrustEndpointError());
  9622. return;
  9623. }
  9624. var wstrustVersion = this._parseWStrustVersionFromFederationActiveAuthUrl(this._userRealm.federationActiveAuthUrl);
  9625. this._log.verbose('Wstrust endpoint version is: ' + wstrustVersion);
  9626. this._performUsernamePasswordForAccessTokenExchange(this._userRealm.federationActiveAuthUrl, wstrustVersion, username, password, callback);
  9627. return;
  9628. } else {
  9629. var mexEndpoint = this._userRealm.federationMetadataUrl;
  9630. this._log.verbose('Attempting mex');
  9631. this._log.verbose('Attempting mex at: ' + mexEndpoint, true);
  9632. var mex = this._createMex(mexEndpoint);
  9633. mex.discover(function(mexErr) {
  9634. var wstrustEndpoint;
  9635. wstrustVersion = WSTrustVersion.UNDEFINED;
  9636. if (mexErr) {
  9637. self._log.warn('MEX exchange failed. Attempting fallback to AAD supplied endpoint.');
  9638. wstrustEndpoint = self._userRealm.federationActiveAuthUrl;
  9639. wstrustVersion = self._parseWStrustVersionFromFederationActiveAuthUrl(self._userRealm.federationActiveAuthUrl);
  9640. if (!wstrustEndpoint) {
  9641. callback(self._createADWSTrustEndpointError());
  9642. return;
  9643. }
  9644. } else {
  9645. wstrustEndpoint = mex.usernamePasswordPolicy.url;
  9646. wstrustVersion = mex.usernamePasswordPolicy.version;
  9647. }
  9648. self._performUsernamePasswordForAccessTokenExchange(wstrustEndpoint, wstrustVersion, username, password, callback);
  9649. return;
  9650. });
  9651. }
  9652. };
  9653. /**
  9654. * Gets wstrust endpoint version from the federation active auth url.
  9655. * @private
  9656. * @param {string} federationActiveAuthUrl federationActiveAuthUrl
  9657. * @return {object} The wstrust endpoint version.
  9658. */
  9659. TokenRequest.prototype._parseWStrustVersionFromFederationActiveAuthUrl = function(federationActiveAuthUrl) {
  9660. var wstrust2005Regex = /[/trust]?[2005][/usernamemixed]?/;
  9661. var wstrust13Regex = /[/trust]?[13][/usernamemixed]?/;
  9662. if (wstrust2005Regex.exec(federationActiveAuthUrl)) {
  9663. return WSTrustVersion.WSTRUST2005;
  9664. }
  9665. else if (wstrust13Regex.exec(federationActiveAuthUrl)) {
  9666. return WSTrustVersion.WSTRUST13;
  9667. }
  9668. return WSTrustVersion.UNDEFINED;
  9669. };
  9670. /**
  9671. * Decides whether the username represents a managed or a federated user and then
  9672. * obtains a token using the appropriate protocol flow.
  9673. * @private
  9674. * @param {string} username
  9675. * @param {string} password
  9676. * @param {AcquireTokenCallback} callback
  9677. */
  9678. TokenRequest.prototype.getTokenWithUsernamePassword = function(username, password, callback) {
  9679. this._log.info('Acquiring token with username password');
  9680. this._userId = username;
  9681. this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
  9682. var self = this;
  9683. if(this._authenticationContext._authority._isAdfsAuthority) {
  9684. this._log.info('Skipping user realm discovery for ADFS authority');
  9685. self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback);
  9686. return;
  9687. }
  9688. this._userRealm = this._createUserRealmRequest(username);
  9689. this._userRealm.discover(function(err) {
  9690. if (err) {
  9691. getTokenCompleteCallback(err);
  9692. return;
  9693. }
  9694. switch(self._userRealm.accountType) {
  9695. case AccountType.Managed:
  9696. self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback);
  9697. return;
  9698. case AccountType.Federated:
  9699. self._getTokenUsernamePasswordFederated(username, password, getTokenCompleteCallback);
  9700. return;
  9701. default:
  9702. getTokenCompleteCallback(self._log.createError('Server returned an unknown AccountType: ' + self._userRealm.AccountType));
  9703. }
  9704. });
  9705. });
  9706. };
  9707. /**
  9708. * Obtains a token using client credentials
  9709. * @private
  9710. * @param {string} clientSecret
  9711. * @param {AcquireTokenCallback} callback
  9712. */
  9713. TokenRequest.prototype.getTokenWithClientCredentials = function(clientSecret, callback) {
  9714. this._log.info('Getting token with client credentials.');
  9715. this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
  9716. var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS);
  9717. oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;
  9718. this._oauthGetToken(oauthParameters, getTokenCompleteCallback);
  9719. });
  9720. };
  9721. /**
  9722. * Obtains a token using an authorization code.
  9723. * @private
  9724. * @param {string} authorizationCode
  9725. * @param {string} clientSecret
  9726. * @param {AcquireTokenCallback} callback
  9727. */
  9728. TokenRequest.prototype.getTokenWithAuthorizationCode = function(authorizationCode, clientSecret, callback) {
  9729. this._log.info('Getting token with auth code.');
  9730. var oauthParameters = this._createOAuthParameters(OAuth2GrantType.AUTHORIZATION_CODE);
  9731. oauthParameters[OAuth2Parameters.CODE] = authorizationCode;
  9732. oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;
  9733. this._oauthGetToken(oauthParameters, callback);
  9734. };
  9735. /**
  9736. * Obtains a token using a refresh token.
  9737. * @param {string} refreshToken
  9738. * @param {string} resource
  9739. * @param {string} [clientSecret]
  9740. * @param {AcquireTokenCallback} callback
  9741. */
  9742. TokenRequest.prototype._getTokenWithRefreshToken = function(refreshToken, resource, clientSecret, callback) {
  9743. this._log.info('Getting a new token from a refresh token.');
  9744. var oauthParameters = this._createOAuthParameters(OAuth2GrantType.REFRESH_TOKEN);
  9745. if (resource) {
  9746. oauthParameters[OAuth2Parameters.RESOURCE] = resource;
  9747. }
  9748. if (clientSecret) {
  9749. oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;
  9750. }
  9751. oauthParameters[OAuth2Parameters.REFRESH_TOKEN] = refreshToken;
  9752. this._oauthGetToken(oauthParameters, callback);
  9753. };
  9754. /**
  9755. * Obtains a token using a refresh token.
  9756. * @param {string} refreshToken
  9757. * @param {string} [clientSecret]
  9758. * @param {AcquireTokenCallback} callback
  9759. */
  9760. TokenRequest.prototype.getTokenWithRefreshToken = function(refreshToken, clientSecret, callback) {
  9761. this._getTokenWithRefreshToken(refreshToken, null, clientSecret, callback);
  9762. };
  9763. /**
  9764. * Obtains a token from the cache, refreshing it or using a MRRT if necessary.
  9765. * @param {string} [userId] The user associated with the cached token.
  9766. * @param {AcquireTokenCallback} callback
  9767. */
  9768. TokenRequest.prototype.getTokenFromCacheWithRefresh = function(userId, callback) {
  9769. var self = this;
  9770. this._log.info('Getting token from cache with refresh if necessary.');
  9771. this._userId = userId;
  9772. this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
  9773. // If this method was called then no cached entry was found. Since
  9774. // this particular version of acquireToken can only retrieve tokens
  9775. // from the cache, return an error.
  9776. getTokenCompleteCallback(self._log.createError('Entry not found in cache.'));
  9777. });
  9778. };
  9779. /**
  9780. * Creates a self signed jwt.
  9781. * @param {string} authorityUrl
  9782. * @param {string} certificate A PEM encoded certificate private key.
  9783. * @param {string} thumbprint
  9784. * @return {string} A self signed JWT
  9785. */
  9786. TokenRequest.prototype._createJwt = function(authorityUrl, certificate, thumbprint) {
  9787. var jwt;
  9788. var ssj = this._createSelfSignedJwt();
  9789. jwt = ssj.create(certificate, thumbprint);
  9790. if (!jwt) {
  9791. throw this._log.createError('Failed to create JWT');
  9792. }
  9793. return jwt;
  9794. };
  9795. /**
  9796. * Obtains a token via a certificate. The certificate is used to generate a self signed
  9797. * JWT token that is passed as a client_assertion.
  9798. * @param {string} certificate A PEM encoded certificate private key.
  9799. * @param {string} thumbprint A hex encoded thumbprint of the certificate.
  9800. * @param {AcquireTokenCallback} callback
  9801. */
  9802. TokenRequest.prototype.getTokenWithCertificate = function(certificate, thumbprint, callback) {
  9803. this._log.info('Getting a token via certificate.');
  9804. var authorityUrl = this._authenticationContext._authority;
  9805. var jwt;
  9806. try {
  9807. jwt = this._createJwt(authorityUrl, certificate, thumbprint);
  9808. } catch (err) {
  9809. callback(err);
  9810. return;
  9811. }
  9812. var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS);
  9813. oauthParameters[OAuth2Parameters.CLIENT_ASSERTION_TYPE] = OAuth2GrantType.JWT_BEARER;
  9814. oauthParameters[OAuth2Parameters.CLIENT_ASSERTION] = jwt;
  9815. this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {
  9816. this._oauthGetToken(oauthParameters, getTokenCompleteCallback);
  9817. });
  9818. };
  9819. TokenRequest.prototype.getTokenWithDeviceCode = function(userCodeInfo, callback) {
  9820. this._log.info('Getting a token via device code');
  9821. var self = this;
  9822. var oauthParameters = this._createOAuthParameters(OAuth2GrantType.DEVICE_CODE);
  9823. oauthParameters[OAuth2Parameters.CODE] = userCodeInfo[DeviceCodeResponseParameters.DEVICE_CODE];
  9824. var interval = userCodeInfo[DeviceCodeResponseParameters.INTERVAL];
  9825. var expires_in = userCodeInfo[DeviceCodeResponseParameters.EXPIRES_IN];
  9826. if (interval <= 0) {
  9827. callback(new Error('invalid refresh interval'));
  9828. }
  9829. this._oauthGetTokenByPolling(oauthParameters, interval, expires_in, function(err, tokenResponse) {
  9830. if (err) {
  9831. self._log.verbose('Token polling request returend with err.');
  9832. callback(err, tokenResponse);
  9833. }
  9834. else {
  9835. self._addTokenIntoCache(tokenResponse, callback);
  9836. }
  9837. });
  9838. };
  9839. TokenRequest.prototype.cancelTokenRequestWithDeviceCode = function() {
  9840. this._pollingClient.cancelPollingRequest();
  9841. };
  9842. module.exports = TokenRequest;
  9843. }).call(this)}).call(this,require("buffer").Buffer)
  9844. },{"./cache-driver":24,"./constants":26,"./log":27,"./mex":29,"./oauth2client":30,"./self-signed-jwt":31,"./user-realm":33,"./wstrust-request":35,"buffer":193}],33:[function(require,module,exports){
  9845. /*
  9846. * @copyright
  9847. * Copyright © Microsoft Open Technologies, Inc.
  9848. *
  9849. * All Rights Reserved
  9850. *
  9851. * Licensed under the Apache License, Version 2.0 (the "License");
  9852. * you may not use this file except in compliance with the License.
  9853. * You may obtain a copy of the License at
  9854. *
  9855. * http: *www.apache.org/licenses/LICENSE-2.0
  9856. *
  9857. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  9858. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  9859. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  9860. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  9861. *
  9862. * See the Apache License, Version 2.0 for the specific language
  9863. * governing permissions and limitations under the License.
  9864. */
  9865. 'use strict';
  9866. var querystring = require('querystring');
  9867. var request = require('request');
  9868. var _ = require('underscore');
  9869. var url = require('url');
  9870. var constants = require('./constants');
  9871. var Logger = require('./log').Logger;
  9872. var util = require('./util');
  9873. var AccountType = constants.UserRealm.AccountType;
  9874. var FederationProtocolType = constants.UserRealm.FederationProtocolType;
  9875. var USER_REALM_PATH_TEMPLATE = 'common/UserRealm/<user>';
  9876. /**
  9877. * Create a new UserRealm object
  9878. * @private
  9879. * @constructor
  9880. * @param {object} callContext Contains any context information that applies to the request.
  9881. * @param {string} userPrinciple The username for which a realm needs to be discovered.
  9882. * @param {string} authority The string url of the authority that owns the userPrinciple.
  9883. */
  9884. function UserRealm(callContext, userPrinciple, authority) {
  9885. this._log = new Logger('UserRealm', callContext._logContext);
  9886. this._callContext = callContext;
  9887. this._apiVersion = '1.0';
  9888. this._federationProtocol = null;
  9889. this._accountType = null;
  9890. this._federationMetadataUrl = null;
  9891. this._federationActiveAuthUrl = null;
  9892. this._userPrinciple = userPrinciple;
  9893. this._authority = authority;
  9894. }
  9895. /**
  9896. * The API version requested by UserRealm.
  9897. * @type {string}
  9898. * @instance
  9899. * @memberOf UserRealm
  9900. * @name apiVersion
  9901. */
  9902. Object.defineProperty(UserRealm.prototype, 'apiVersion', {
  9903. get : function() {
  9904. return this._apiVersion;
  9905. }
  9906. });
  9907. /**
  9908. * The federation protocol used by the users realm.
  9909. * @type {string}
  9910. * @instance
  9911. * @memberOf UserRealm
  9912. * @name federationProtocol
  9913. */
  9914. Object.defineProperty(UserRealm.prototype, 'federationProtocol', {
  9915. get : function() {
  9916. return this._federationProtocol;
  9917. }
  9918. });
  9919. /**
  9920. * The Type of account. Either managed or federated.
  9921. * @type {string}
  9922. * @instance
  9923. * @memberOf UserRealm
  9924. * @name accountType
  9925. */
  9926. Object.defineProperty(UserRealm.prototype, 'accountType', {
  9927. get : function() {
  9928. return this._accountType;
  9929. }
  9930. });
  9931. /**
  9932. * If this is a federated account then this property will contain the mex url.
  9933. * @type {string}
  9934. * @instance
  9935. * @memberOf UserRealm
  9936. * @name federationsMetadataUrl
  9937. */
  9938. Object.defineProperty(UserRealm.prototype, 'federationMetadataUrl', {
  9939. get : function() {
  9940. return this._federationMetadataUrl;
  9941. }
  9942. });
  9943. /**
  9944. * If the account is federated this will contain the authentication endpoint.
  9945. * @type {string}
  9946. * @instance
  9947. * @memberOf UserRealm
  9948. * @name federationActiveAuthUrl
  9949. */
  9950. Object.defineProperty(UserRealm.prototype, 'federationActiveAuthUrl', {
  9951. get : function() {
  9952. return this._federationActiveAuthUrl;
  9953. }
  9954. });
  9955. /**
  9956. * Given the authority url this method constructs a full user realm discovery url.
  9957. * @private
  9958. * @returns A full user realm discovery url including path and query string.
  9959. */
  9960. UserRealm.prototype._getUserRealmUrl = function() {
  9961. var userRealmUrl = util.copyUrl(this._authority);
  9962. var urlEncodedUser = encodeURIComponent(this._userPrinciple);
  9963. userRealmUrl.pathname = USER_REALM_PATH_TEMPLATE.replace('<user>', urlEncodedUser);
  9964. var userRealmQuery = {
  9965. 'api-version' : this._apiVersion
  9966. };
  9967. userRealmUrl.search = querystring.stringify(userRealmQuery);
  9968. userRealmUrl = util.copyUrl(userRealmUrl);
  9969. return userRealmUrl;
  9970. };
  9971. /**
  9972. * Given a constants object and a value, validates that the value is a key in the constants object.
  9973. * @private
  9974. * @param {object} constants An object containing constant key value pairs.
  9975. * @param {string} value A value to check against the constants
  9976. * @param {bool} caseSensitive set to true if comparisons should be made as case sensitive. Defaults to false.
  9977. * @returns {bool|string} If value passed in matches one of the constants then the return value is the matched constant.
  9978. * If a non case sensitive match was done, then the value returned may be different than the value
  9979. * passed in. If there is no match then the method returns false.
  9980. */
  9981. UserRealm.prototype._validateConstantValue = function(constants, value, caseSensitive) {
  9982. if (!value) {
  9983. return false;
  9984. }
  9985. if (!caseSensitive) {
  9986. value = value.toLowerCase();
  9987. }
  9988. return _.contains(_.values(constants), value) ? value : false;
  9989. };
  9990. /**
  9991. * Checks whether an account type string is valid.
  9992. * @private
  9993. * @param {string} type An account type string.
  9994. * @returns {bool}
  9995. */
  9996. UserRealm.prototype._validateAccountType = function(type) {
  9997. return this._validateConstantValue(AccountType, type);
  9998. };
  9999. /**
  10000. * Checks whether a federation protocol string is valid.
  10001. * @private
  10002. * @param {string} protocol A federation protocol string.
  10003. * @returns {bool}
  10004. */
  10005. UserRealm.prototype._validateFederationProtocol = function(protocol) {
  10006. return this._validateConstantValue(FederationProtocolType, protocol);
  10007. };
  10008. /**
  10009. * Logs the values parsed as part of user realm discovery.
  10010. * @private
  10011. */
  10012. UserRealm.prototype._logParsedResponse = function() {
  10013. this._log.verbose('UserRealm response:');
  10014. this._log.verbose(' AccountType: ' + this.accountType);
  10015. this._log.verbose(' FederationProtocol: ' + this.federationProtocol);
  10016. this._log.verbose(' FederationMetatdataUrl: ' + this.federationMetadataUrl, true);
  10017. this._log.verbose(' FederationActiveAuthUrl: ' + this.federationActiveAuthUrl, true);
  10018. };
  10019. /**
  10020. * Parses the response from a user realm discovery request.
  10021. * @private
  10022. * @param {string} body The body returned as part of the http user realm discovery request.
  10023. * @param {UserRealm.DiscoverCallback} callback Called when parsing is complete.
  10024. */
  10025. UserRealm.prototype._parseDiscoveryResponse = function(body, callback) {
  10026. this._log.verbose('Discovery response:\n' + body, true);
  10027. var response;
  10028. try {
  10029. response = JSON.parse(body);
  10030. } catch (err) {
  10031. callback(this._log.createError('Parsing realm discovery respone JSON failed: ' + body, true));
  10032. return;
  10033. }
  10034. var accountType = this._validateAccountType(response['account_type']);
  10035. if (!accountType) {
  10036. callback(this._log.createError('Cannot parse account_type: ' + accountType));
  10037. return;
  10038. }
  10039. this._accountType = accountType;
  10040. if (this._accountType === AccountType.Federated) {
  10041. var protocol = this._validateFederationProtocol(response['federation_protocol']);
  10042. if (!protocol) {
  10043. callback(this._log.createError('Cannot parse federation protocol: ' + protocol));
  10044. return;
  10045. }
  10046. this._federationProtocol = protocol;
  10047. this._federationMetadataUrl = response['federation_metadata_url'];
  10048. this._federationActiveAuthUrl = response['federation_active_auth_url'];
  10049. }
  10050. this._logParsedResponse();
  10051. callback();
  10052. };
  10053. /**
  10054. * @callback DiscoverCallback
  10055. * @memberOf UserRealm
  10056. * @param {Error} error If an error occurs during discovery then this parameter will be used to return the error.
  10057. */
  10058. /**
  10059. * Performs user realm discovery and fills in the properties on this object.
  10060. * @private
  10061. * @param {UserRealm.DiscoverCallback} callback Called when discovery is complete.
  10062. */
  10063. UserRealm.prototype.discover = function(callback) {
  10064. var self = this;
  10065. var options = util.createRequestOptions(
  10066. this,
  10067. {
  10068. headers : {
  10069. Accept : 'application/json'
  10070. }
  10071. }
  10072. );
  10073. var userRealmUrl = this._getUserRealmUrl();
  10074. this._log.verbose('Performing user realm discovery at: ' + url.format(userRealmUrl), true);
  10075. request.get(userRealmUrl, options, util.createRequestHandler('User Realm Discovery', this._log, callback,
  10076. function(response, body) {
  10077. self._parseDiscoveryResponse(body, callback);
  10078. })
  10079. );
  10080. };
  10081. module.exports = UserRealm;
  10082. },{"./constants":26,"./log":27,"./util":34,"querystring":543,"request":546,"underscore":651,"url":653}],34:[function(require,module,exports){
  10083. (function (Buffer){(function (){
  10084. /*
  10085. * @copyright
  10086. * Copyright © Microsoft Open Technologies, Inc.
  10087. *
  10088. * All Rights Reserved
  10089. *
  10090. * Licensed under the Apache License, Version 2.0 (the "License");
  10091. * you may not use this file except in compliance with the License.
  10092. * You may obtain a copy of the License at
  10093. *
  10094. * http: *www.apache.org/licenses/LICENSE-2.0
  10095. *
  10096. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  10097. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  10098. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  10099. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  10100. *
  10101. * See the Apache License, Version 2.0 for the specific language
  10102. * governing permissions and limitations under the License.
  10103. */
  10104. 'use strict';
  10105. var _ = require('underscore');
  10106. var adalIdConstants = require('./constants').AdalIdParameters;
  10107. var os = require('os');
  10108. var url = require('url');
  10109. var ADAL_VERSION;
  10110. /**
  10111. * @namespace Util
  10112. * @private
  10113. */
  10114. function loadAdalVersion() {
  10115. ADAL_VERSION = require('../package.json').version;
  10116. }
  10117. function adalInit() {
  10118. loadAdalVersion();
  10119. }
  10120. /**
  10121. * @static
  10122. * @memberOf Util
  10123. * @param {string|int} statusCode An HTTP status code.
  10124. */
  10125. function isHttpSuccess(statusCode) {
  10126. return statusCode >= 200 && statusCode < 300;
  10127. }
  10128. function addDefaultRequestHeaders (self, options) {
  10129. if (!options.headers) {
  10130. options.headers = {};
  10131. }
  10132. var headers = options.headers;
  10133. if (!headers['Accept-Charset']) {
  10134. headers['Accept-Charset'] = 'utf-8';
  10135. }
  10136. headers['client-request-id'] = self._callContext._logContext.correlationId;
  10137. headers['return-client-request-id'] = 'true';
  10138. // ADAL Id headers
  10139. headers[adalIdConstants.SKU] = adalIdConstants.NODE_SKU;
  10140. headers[adalIdConstants.VERSION] = ADAL_VERSION;
  10141. headers[adalIdConstants.OS] = os.platform();
  10142. headers[adalIdConstants.CPU] = os.arch();
  10143. }
  10144. /**
  10145. * Central place for housing default request options. This is a place holder
  10146. * for when SSL validation is implemented an all requests are subject to that
  10147. * policy.
  10148. * @static
  10149. * @memberOf Util
  10150. * @param {object} options A set of options that will be merged with teh default options
  10151. * These will override any default options.
  10152. * @returns {object} Returns the merged options.
  10153. */
  10154. function createRequestOptions(self, options) {
  10155. var defaultOptions = {}; //{ strictSSL : true };
  10156. var mergedOptions = defaultOptions;
  10157. if (options) {
  10158. _.extend(mergedOptions, options);
  10159. }
  10160. if (self._callContext.options && self._callContext.options.http) {
  10161. _.extend(mergedOptions, self._callContext.options.http);
  10162. }
  10163. addDefaultRequestHeaders(self, mergedOptions);
  10164. return mergedOptions;
  10165. }
  10166. function logReturnCorrelationId(log, operationMessage, response) {
  10167. if (response && response.headers && response.headers['client-request-id']) {
  10168. log.info(operationMessage + 'Server returned this correlationId: ' + response.headers['client-request-id'], true);
  10169. }
  10170. }
  10171. /**
  10172. * Creates a function that can be used as the callback for http request operations. This is meant
  10173. * to centralize error handling in one place.
  10174. * @static
  10175. * @memberOf Util
  10176. * @param {string} operationMessage A message to be prepended to logged error strings. This should be something like 'Mex Request'
  10177. * and summarize the purpose of the http request.
  10178. * @param {object} log A Logger object being used by the calling component.
  10179. * @param {Util.CreateRequestHandlerErrorCallback} errorCallback Called in the event of an error.
  10180. * @param {Util.CreateRequestHandlerSuccessCallabck} successCallback Called on successfull completion of the request.
  10181. */
  10182. function createRequestHandler(operationMessage, log, errorCallback, successCallback) {
  10183. return function(err, response, body) {
  10184. logReturnCorrelationId(log, operationMessage, response);
  10185. if (err) {
  10186. log.error(operationMessage + ' request failed with', err, true);
  10187. errorCallback(err);
  10188. return;
  10189. }
  10190. if (!isHttpSuccess(response.statusCode)) {
  10191. var returnErrorString = operationMessage + ' request returned http error: ' + response.statusCode;
  10192. var errorResponse;
  10193. if (body) {
  10194. returnErrorString += ' and server response: ' + body;
  10195. try {
  10196. errorResponse = JSON.parse(body);
  10197. } catch (e) {
  10198. // No problem if it doesn't parse.
  10199. }
  10200. }
  10201. errorCallback(log.createError(returnErrorString, true), errorResponse);
  10202. return;
  10203. }
  10204. successCallback(response, body);
  10205. };
  10206. }
  10207. /**
  10208. * @callback CreateRequestHandlerErrorCallback
  10209. * @memberOf Util
  10210. * @param {Error} error An error object.
  10211. */
  10212. /**
  10213. * @callback CreateRequestHandlerSuccessCallabck
  10214. * @memberOf Util
  10215. * @param {object} response The response object returned from request.
  10216. * @param {string} body The body of the http response.
  10217. */
  10218. /**
  10219. * Deep copies a url object.
  10220. * @static
  10221. * @memberOf Util
  10222. * @param {URL} urlSource The source url object to copy.
  10223. * @returns {URL} A deep copy of sourceUrl.
  10224. */
  10225. function copyUrl(urlSource) {
  10226. return url.parse(url.format(urlSource));
  10227. }
  10228. function convertUrlSafeToRegularBase64EncodedString(str) {
  10229. return str.replace(/-/g, '+').replace(/_/g, '/');
  10230. }
  10231. function convertRegularToUrlSafeBase64EncodedString(str) {
  10232. return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
  10233. }
  10234. function base64DecodeStringUrlSafe(str) {
  10235. var base64 = convertUrlSafeToRegularBase64EncodedString(str);
  10236. return (new Buffer(base64, 'base64')).toString('utf8');
  10237. }
  10238. function base64EncodeStringUrlSafe(str) {
  10239. var base64 = (new Buffer(str, 'utf8').toString('base64'));
  10240. var converted = convertRegularToUrlSafeBase64EncodedString(base64);
  10241. return converted;
  10242. }
  10243. module.exports.adalInit = adalInit;
  10244. module.exports.isHttpSuccess = isHttpSuccess;
  10245. module.exports.createRequestHandler = createRequestHandler;
  10246. module.exports.createRequestOptions = createRequestOptions;
  10247. module.exports.copyUrl = copyUrl;
  10248. module.exports.base64DecodeStringUrlSafe = base64DecodeStringUrlSafe;
  10249. module.exports.base64EncodeStringUrlSafe = base64EncodeStringUrlSafe;
  10250. module.exports.convertRegularToUrlSafeBase64EncodedString = convertRegularToUrlSafeBase64EncodedString;
  10251. }).call(this)}).call(this,require("buffer").Buffer)
  10252. },{"../package.json":38,"./constants":26,"buffer":193,"os":500,"underscore":651,"url":653}],35:[function(require,module,exports){
  10253. /*
  10254. * @copyright
  10255. * Copyright © Microsoft Open Technologies, Inc.
  10256. *
  10257. * All Rights Reserved
  10258. *
  10259. * Licensed under the Apache License, Version 2.0 (the "License");
  10260. * you may not use this file except in compliance with the License.
  10261. * You may obtain a copy of the License at
  10262. *
  10263. * http: *www.apache.org/licenses/LICENSE-2.0
  10264. *
  10265. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  10266. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  10267. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  10268. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  10269. *
  10270. * See the Apache License, Version 2.0 for the specific language
  10271. * governing permissions and limitations under the License.
  10272. */
  10273. 'use strict';
  10274. var request = require('request');
  10275. var uuid = require('uuid');
  10276. var Logger = require('./log').Logger;
  10277. var util = require('./util');
  10278. var WSTrustResponse = require('./wstrust-response');
  10279. var WSTrustVersion = require('./constants').WSTrustVersion;
  10280. var USERNAME_PLACEHOLDER = '{UsernamePlaceHolder}';
  10281. var PASSWORD_PLACEHOLDER = '{PasswordPlaceHolder}';
  10282. /**
  10283. * Creates a new instance of WSTrustRequest
  10284. * @constructor
  10285. * @private
  10286. * @param {object} callContext Contains any context information that applies to the request.
  10287. * @param {string} wstrustEndpointUrl An STS WS-Trust soap endpoint.
  10288. * @param {string} appliesTo A URI that identifies a service for which the a token is to be obtained.
  10289. */
  10290. function WSTrustRequest(callContext, wstrustEndpointUrl, appliesTo, wstrustEndpointVersion) {
  10291. this._log = new Logger('WSTrustRequest', callContext._logContext);
  10292. this._callContext = callContext;
  10293. this._wstrustEndpointUrl = wstrustEndpointUrl;
  10294. this._appliesTo = appliesTo;
  10295. this._wstrustEndpointVersion = wstrustEndpointVersion;
  10296. }
  10297. /**
  10298. * Given a Date object adds the minutes parameter and returns a new Date object.
  10299. * @private
  10300. * @static
  10301. * @memberOf WSTrustRequest
  10302. * @param {Date} date A Date object.
  10303. * @param {Number} minutes The number of minutes to add to the date parameter.
  10304. * @returns {Date} Returns a Date object.
  10305. */
  10306. function _datePlusMinutes(date, minutes) {
  10307. var minutesInMilliSeconds = minutes * 60 * 1000;
  10308. var epochTime = date.getTime() + minutesInMilliSeconds;
  10309. return new Date(epochTime);
  10310. }
  10311. /**
  10312. * Builds the soap security header for the RST message.
  10313. * @private
  10314. * @param {string} username A username
  10315. * @param {string} password The passowrd that corresponds to the username parameter.
  10316. * @returns {string} A string that contains the soap security header.
  10317. */
  10318. WSTrustRequest.prototype._buildSecurityHeader = function() {
  10319. var timeNow = new Date();
  10320. var expireTime = _datePlusMinutes(timeNow, 10);
  10321. var timeNowString = timeNow.toISOString();
  10322. var expireTimeString = expireTime.toISOString();
  10323. var securityHeaderXml =
  10324. '<wsse:Security s:mustUnderstand=\'1\' xmlns:wsse=\'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\'>\
  10325. <wsu:Timestamp wsu:Id=\'_0\'>\
  10326. <wsu:Created>' + timeNowString + '</wsu:Created>\
  10327. <wsu:Expires>' + expireTimeString + '</wsu:Expires>\
  10328. </wsu:Timestamp>\
  10329. <wsse:UsernameToken wsu:Id=\'ADALUsernameToken\'>\
  10330. <wsse:Username>' + USERNAME_PLACEHOLDER + '</wsse:Username>\
  10331. <wsse:Password>' + PASSWORD_PLACEHOLDER + '</wsse:Password>\
  10332. </wsse:UsernameToken>\
  10333. </wsse:Security>';
  10334. return securityHeaderXml;
  10335. };
  10336. /**
  10337. * Replaces the placeholders in the RST template with the actual username and password values.
  10338. * @private
  10339. * @param {string} RSTTemplate An RST with placeholders for username and password.
  10340. * @param {string} username A username
  10341. * @param {string} password The passowrd that corresponds to the username parameter.
  10342. * @returns {string} A string containing a complete RST soap message.
  10343. */
  10344. WSTrustRequest.prototype._populateRSTUsernamePassword = function(RSTTemplate, username, password) {
  10345. var RST = RSTTemplate.replace(USERNAME_PLACEHOLDER, username).replace(PASSWORD_PLACEHOLDER, this._populatedEscapedPassword(password));
  10346. return RST;
  10347. };
  10348. /**
  10349. * Escape xml characters in password.
  10350. * @private
  10351. * @param {string} password The password to be excaped with xml charaters.
  10352. */
  10353. WSTrustRequest.prototype._populatedEscapedPassword = function (password) {
  10354. var escapedPassword = password;
  10355. return escapedPassword.replace(/&/g, '&amp;')
  10356. .replace(/"/g, '&quot;')
  10357. .replace(/'/g, '&apos;')
  10358. .replace(/</g, '&lt;')
  10359. .replace(/>/g, '&gt;');
  10360. }
  10361. /**
  10362. * Builds a WS-Trust RequestSecurityToken (RST) message using username password authentication.
  10363. * @private
  10364. * @param {string} username A username
  10365. * @param {string} password The passowrd that corresponds to the username parameter.
  10366. * @returns {string} A string containing a complete RST soap message.
  10367. */
  10368. WSTrustRequest.prototype._buildRST = function(username, password) {
  10369. var messageID = uuid.v4();
  10370. // Create a template RST with placeholders for the username and password so the
  10371. // the RST can be logged without the sensitive information.
  10372. var schemaLocation = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd';
  10373. var soapAction = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue';
  10374. var rstTrustNamespace = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512';
  10375. var keyType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer';
  10376. var requestType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue';
  10377. if (this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005) {
  10378. soapAction = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue';
  10379. rstTrustNamespace = 'http://schemas.xmlsoap.org/ws/2005/02/trust';
  10380. keyType = 'http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey';
  10381. requestType = 'http://schemas.xmlsoap.org/ws/2005/02/trust/Issue';
  10382. }
  10383. var RSTTemplate =
  10384. '<s:Envelope xmlns:s=\'http://www.w3.org/2003/05/soap-envelope\' xmlns:wsa=\'http://www.w3.org/2005/08/addressing\' xmlns:wsu=\'' + schemaLocation + '\'>\
  10385. <s:Header>\
  10386. <wsa:Action s:mustUnderstand=\'1\'>' + soapAction + '</wsa:Action>\
  10387. <wsa:messageID>urn:uuid:' + messageID + '</wsa:messageID>\
  10388. <wsa:ReplyTo>\
  10389. <wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address>\
  10390. </wsa:ReplyTo>\
  10391. <wsa:To s:mustUnderstand=\'1\'>' + this._wstrustEndpointUrl + '</wsa:To>\
  10392. ' + this._buildSecurityHeader() + '\
  10393. </s:Header>\
  10394. <s:Body>\
  10395. <wst:RequestSecurityToken xmlns:wst=\'' + rstTrustNamespace + '\'>\
  10396. <wsp:AppliesTo xmlns:wsp=\'http://schemas.xmlsoap.org/ws/2004/09/policy\'>\
  10397. <wsa:EndpointReference>\
  10398. <wsa:Address>' + this._appliesTo + '</wsa:Address>\
  10399. </wsa:EndpointReference>\
  10400. </wsp:AppliesTo>\
  10401. <wst:KeyType>' + keyType + '</wst:KeyType>\
  10402. <wst:RequestType>' + requestType + '</wst:RequestType>\
  10403. </wst:RequestSecurityToken>\
  10404. </s:Body>\
  10405. </s:Envelope>';
  10406. this._log.verbose('Created RST: \n' + RSTTemplate, true);
  10407. var RST = this._populateRSTUsernamePassword(RSTTemplate, username, password);
  10408. return RST;
  10409. };
  10410. /**
  10411. * Handles the processing of a RSTR
  10412. * @private
  10413. * @param {string} body
  10414. * @param {WSTrustRequest.AcquireTokenCallback} callback
  10415. */
  10416. WSTrustRequest.prototype._handleRSTR = function(body, callback) {
  10417. var err;
  10418. var wstrustResponse = new WSTrustResponse(this._callContext, body, this._wstrustEndpointVersion);
  10419. try {
  10420. wstrustResponse.parse();
  10421. } catch (error) {
  10422. err = error;
  10423. }
  10424. callback(err, wstrustResponse);
  10425. };
  10426. /**
  10427. * Performs a WS-Trust RequestSecurityToken request to obtain a federated token in exchange for a username password.
  10428. * @param {string} username A username
  10429. * @param {string} password The passowrd that corresponds to the username parameter.
  10430. * @param {WSTrustRequest.AcquireTokenCallback} callback Called once the federated token has been retrieved or on error.
  10431. */
  10432. WSTrustRequest.prototype.acquireToken = function(username, password, callback) {
  10433. if (this._wstrustEndpointVersion === WSTrustVersion.UNDEFINED) {
  10434. var err = this._log.createError('Unsupported wstrust endpoint version. Current support version is wstrust2005 or wstrust13.');
  10435. callback(err);
  10436. return;
  10437. }
  10438. var self = this;
  10439. var RST = this._buildRST(username, password);
  10440. var soapAction = this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005 ? 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue';
  10441. var options = util.createRequestOptions(
  10442. this,
  10443. {
  10444. headers : {
  10445. 'Content-Type' : 'application/soap+xml; charset=utf-8',
  10446. 'SOAPAction' : soapAction
  10447. },
  10448. body : RST
  10449. }
  10450. );
  10451. this._log.verbose('Sending RST to: ' + this._wstrustEndpointUrl, true);
  10452. request.post(this._wstrustEndpointUrl, options, util.createRequestHandler('WS-Trust RST', this._log, callback,
  10453. function(response, body) {
  10454. self._handleRSTR(body, callback);
  10455. }
  10456. ));
  10457. };
  10458. /**
  10459. * @callback AcquireTokenCallback
  10460. * @memberOf WSTrustRequest
  10461. * @param {Error} err Contains an error object if acquireToken fails.
  10462. * @param {WSTrustResponse} A successful response to the RST.
  10463. */
  10464. module.exports = WSTrustRequest;
  10465. },{"./constants":26,"./log":27,"./util":34,"./wstrust-response":36,"request":546,"uuid":659}],36:[function(require,module,exports){
  10466. /*
  10467. * @copyright
  10468. * Copyright © Microsoft Open Technologies, Inc.
  10469. *
  10470. * All Rights Reserved
  10471. *
  10472. * Licensed under the Apache License, Version 2.0 (the "License");
  10473. * you may not use this file except in compliance with the License.
  10474. * You may obtain a copy of the License at
  10475. *
  10476. * http: *www.apache.org/licenses/LICENSE-2.0
  10477. *
  10478. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  10479. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  10480. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  10481. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  10482. *
  10483. * See the Apache License, Version 2.0 for the specific language
  10484. * governing permissions and limitations under the License.
  10485. */
  10486. 'use strict';
  10487. var xmldom = require('xmldom');
  10488. var xmlutil = require('./xmlutil');
  10489. var Logger = require('./log').Logger;
  10490. var WSTrustVersion = require('./constants').WSTrustVersion;
  10491. var select = xmlutil.xpathSelect;
  10492. var DOMParser = xmldom.DOMParser;
  10493. // A regular expression for finding the SAML Assertion in an RSTR. Used to remove the SAML
  10494. // assertion when logging the RSTR.
  10495. var assertionRegEx = /RequestedSecurityToken.*?((<.*?:Assertion.*?>).*<\/.*?Assertion>).*?/;
  10496. /**
  10497. * Creates a log message that contains the RSTR scrubbed of the actual SAML assertion.
  10498. * @private
  10499. * @return {string} A log message.
  10500. */
  10501. function scrubRSTRLogMessage(RSTR) {
  10502. var scrubbedRSTR = null;
  10503. var singleLineRSTR = RSTR.replace(/(\r\n|\n|\r)/gm,'');
  10504. var matchResult = assertionRegEx.exec(singleLineRSTR);
  10505. if (null === matchResult) {
  10506. // No Assertion was matched so just return the RSTR as is.
  10507. scrubbedRSTR = singleLineRSTR;
  10508. } else {
  10509. var samlAssertion = matchResult[1];
  10510. var samlAssertionStartTag = matchResult[2];
  10511. scrubbedRSTR = singleLineRSTR.replace(samlAssertion, samlAssertionStartTag + 'ASSERTION CONTENTS REDACTED</saml:Assertion>');
  10512. }
  10513. return 'RSTR Response: ' + scrubbedRSTR;
  10514. }
  10515. /**
  10516. * Creates a new WSTrustResponse instance.
  10517. * @constructor
  10518. * @private
  10519. * @param {object} callContext Contains any context information that applies to the request.
  10520. * @param {string} response A soap response from a WS-Trust request.
  10521. * @param {sting} wstrustVersion The version for the WS-Trust request.
  10522. */
  10523. function WSTrustResponse(callContext, response, wstrustVersion) {
  10524. this._log = new Logger('WSTrustResponse', callContext._logContext);
  10525. this._callContext = callContext;
  10526. this._response = response;
  10527. this._dom = null;
  10528. this._errorCode = null;
  10529. this._faultMessage = null;
  10530. this._tokenType = null;
  10531. this._token = null;
  10532. this._wstrustVersion = wstrustVersion;
  10533. this._log.verbose(function(){return scrubRSTRLogMessage(response);});
  10534. }
  10535. /**
  10536. * If the soap response contained a soap fault then this property will contain the fault
  10537. * error code. Otherwise it will return null
  10538. * @instance
  10539. * @type {string}
  10540. * @memberOf WSTrustResponse
  10541. * @name errorCode
  10542. */
  10543. Object.defineProperty(WSTrustResponse.prototype, 'errorCode', {
  10544. get: function() {
  10545. return this._errorCode;
  10546. }
  10547. });
  10548. /**
  10549. * @property {string} FaultMessage If the soap resopnse contained a soap fault with a fault message then it will
  10550. * be returned by this property.
  10551. * @instance
  10552. * @type {string}
  10553. * @memberOf WSTrustResponse
  10554. * @name faultMessage
  10555. */
  10556. Object.defineProperty(WSTrustResponse.prototype, 'faultMessage', {
  10557. get: function() {
  10558. return this._faultMessage;
  10559. }
  10560. });
  10561. /**
  10562. * @property {string} TokenType If the soap resonse contained a token then this property will contain
  10563. * the token type uri
  10564. * @instance
  10565. * @type {string}
  10566. * @memberOf WSTrustResponse
  10567. * @name tokenType
  10568. */
  10569. Object.defineProperty(WSTrustResponse.prototype, 'tokenType', {
  10570. get: function() {
  10571. return this._tokenType;
  10572. }
  10573. });
  10574. /**
  10575. * @property {string} Token If the soap response contained a token then this property will hold that token.
  10576. * @instance
  10577. * @type {string}
  10578. * @memberOf WSTrustResponse
  10579. * @name token
  10580. */
  10581. Object.defineProperty(WSTrustResponse.prototype, 'token', {
  10582. get: function() {
  10583. return this._token;
  10584. }
  10585. });
  10586. // Sample error message
  10587. //<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  10588. // <s:Header>
  10589. // <a:Action s:mustUnderstand="1">http://www.w3.org/2005/08/addressing/soap/fault</a:Action>
  10590. // - <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  10591. // <u:Timestamp u:Id="_0">
  10592. // <u:Created>2013-07-30T00:32:21.989Z</u:Created>
  10593. // <u:Expires>2013-07-30T00:37:21.989Z</u:Expires>
  10594. // </u:Timestamp>
  10595. // </o:Security>
  10596. // </s:Header>
  10597. // <s:Body>
  10598. // <s:Fault>
  10599. // <s:Code>
  10600. // <s:Value>s:Sender</s:Value>
  10601. // <s:Subcode>
  10602. // <s:Value xmlns:a="http://docs.oasis-open.org/ws-sx/ws-trust/200512">a:RequestFailed</s:Value>
  10603. // </s:Subcode>
  10604. // </s:Code>
  10605. // <s:Reason>
  10606. // <s:Text xml:lang="en-US">MSIS3127: The specified request failed.</s:Text>
  10607. // </s:Reason>
  10608. // </s:Fault>
  10609. // </s:Body>
  10610. //</s:Envelope>
  10611. /**
  10612. * Attempts to parse an error from the soap response. If there is one then it
  10613. * will fill in the error related properties. Otherwsie it will do nothing.
  10614. * @private
  10615. * @returns {bool} true if an error was found and parsed in the response.
  10616. */
  10617. WSTrustResponse.prototype._parseError = function() {
  10618. var errorFound = false;
  10619. var faultNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Reason');
  10620. if (faultNode.length) {
  10621. this._faultMessage = xmlutil.serializeNodeChildren(faultNode[0]);
  10622. if (this._faultMessage) {
  10623. errorFound = true;
  10624. }
  10625. }
  10626. // Subcode has minoccurs=0 and maxoccurs=1(default) according to the http://www.w3.org/2003/05/soap-envelope
  10627. // Subcode may have another subcode as well. This is only targetting at top level subcode.
  10628. // Subcode value may have different messages not always uses http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd.
  10629. // text inside the value is not possible to select without prefix, so substring is necessary
  10630. var subcodeNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value');
  10631. if (1 < subcodeNode.length) {
  10632. throw this._log.createError('Found too many fault code values:' + subcodeNode.length);
  10633. }
  10634. if (subcodeNode.length) {
  10635. var errorCode = subcodeNode[0].firstChild.data;
  10636. this._errorCode = (errorCode.split(':'))[1];
  10637. errorFound = true;
  10638. }
  10639. return errorFound;
  10640. };
  10641. /**
  10642. * Attempts to parse a token from the soap response. If there is one then it will fill in the
  10643. * token related properties. Otherwise it does nothing.
  10644. * @private
  10645. * @throws {Error} If the response is not parseable, or too many tokens are found.
  10646. */
  10647. WSTrustResponse.prototype._parseToken = function() {
  10648. var xPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? '//s:Envelope/s:Body/t:RequestSecurityTokenResponse/t:TokenType' : '//s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/wst:RequestSecurityTokenResponse/wst:TokenType';
  10649. var tokenTypeNodes = select(this._dom, xPath);
  10650. if (!tokenTypeNodes.length) {
  10651. this._log.warn('No TokenType elements found in RSTR');
  10652. }
  10653. for (var i = 0, length = tokenTypeNodes.length; i < length; i++) {
  10654. if (this._token) {
  10655. this._log.warn('Found more than one returned token. Using the first.');
  10656. break;
  10657. }
  10658. var tokenTypeNode = tokenTypeNodes[i];
  10659. var tokenType = xmlutil.findElementText(tokenTypeNode);
  10660. if (!tokenType) {
  10661. this._log.warn('Could not find token type in RSTR token');
  10662. }
  10663. var securityTokenPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? 't:RequestedSecurityToken' : 'wst:RequestedSecurityToken';
  10664. var requestedTokenNode = select(tokenTypeNode.parentNode, securityTokenPath);
  10665. if (1 < requestedTokenNode) {
  10666. throw this._log.createError('Found too many RequestedSecurityToken nodes for token type: ' + tokenType);
  10667. }
  10668. if (!requestedTokenNode.length) {
  10669. this._log.warn('Unable to find RequestsSecurityToken element associated with TokenType element: ' + tokenType);
  10670. continue;
  10671. }
  10672. var token = xmlutil.serializeNodeChildren(requestedTokenNode[0]);
  10673. if (!token) {
  10674. this._log.warn('Unable to find token associated with TokenType element: ' + tokenType);
  10675. continue;
  10676. }
  10677. this._token = token;
  10678. this._tokenType = tokenType;
  10679. this._log.info('Found token of type: ' + this._tokenType);
  10680. }
  10681. if (!this._token) {
  10682. throw this._log.createError('Unable to find any tokens in RSTR.');
  10683. }
  10684. };
  10685. /**
  10686. * This method parses the soap response that was passed in at construction.
  10687. * @throws {Error} If the server returned an error, or there was any failure to parse the response.
  10688. */
  10689. WSTrustResponse.prototype.parse = function() {
  10690. if (!this._response) {
  10691. throw this._log.createError('Received empty RSTR response body.');
  10692. }
  10693. try {
  10694. try {
  10695. var options = {
  10696. errorHandler : this._log.error
  10697. };
  10698. this._dom = new DOMParser(options).parseFromString(this._response);
  10699. } catch (err) {
  10700. throw this._log.createError('Failed to parse RSTR in to DOM', err, true);
  10701. }
  10702. var errorFound = this._parseError();
  10703. if (errorFound) {
  10704. var stringErrorCode = this.ErrorCode || 'NONE';
  10705. var stringFaultMessage = this.FaultMessage || 'NONE';
  10706. throw this._log.createError('Server returned error in RSTR - ErrorCode: ' + stringErrorCode + ' : FaultMessage: ' + stringFaultMessage, true);
  10707. }
  10708. this._parseToken();
  10709. } catch (err) {
  10710. delete this._dom;
  10711. throw err;
  10712. }
  10713. };
  10714. module.exports = WSTrustResponse;
  10715. },{"./constants":26,"./log":27,"./xmlutil":37,"xmldom":705}],37:[function(require,module,exports){
  10716. /*
  10717. * @copyright
  10718. * Copyright © Microsoft Open Technologies, Inc.
  10719. *
  10720. * All Rights Reserved
  10721. *
  10722. * Licensed under the Apache License, Version 2.0 (the "License");
  10723. * you may not use this file except in compliance with the License.
  10724. * You may obtain a copy of the License at
  10725. *
  10726. * http: *www.apache.org/licenses/LICENSE-2.0
  10727. *
  10728. * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
  10729. * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  10730. * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
  10731. * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
  10732. *
  10733. * See the Apache License, Version 2.0 for the specific language
  10734. * governing permissions and limitations under the License.
  10735. */
  10736. 'use strict';
  10737. var _ = require('underscore');
  10738. var select = require('xpath.js');
  10739. var XMLSerializer = require('xmldom').XMLSerializer;
  10740. var constants = require('./constants');
  10741. /**
  10742. * @namespace XmlUtil
  10743. * @private
  10744. */
  10745. var XPATH_PATH_TEMPLATE = '*[local-name() = \'LOCAL_NAME\' and namespace-uri() = \'NAMESPACE\']';
  10746. /**
  10747. * The xpath implementation being used does not have a way of matching expanded namespace.
  10748. * This method takes an xpath query and expands all of the namespaces involved. It then
  10749. * re-writes the query in to a longer form that directory matches the correct namespaces.
  10750. * @private
  10751. * @static
  10752. * @memberOf XmlUtil
  10753. * @param {string} xpath The expath query string to expand.
  10754. * @returns {string} An expanded xpath query.
  10755. */
  10756. function expandQNames(xpath) {
  10757. var namespaces = constants.XmlNamespaces;
  10758. var pathParts = xpath.split('/');
  10759. for (var i=0; i < pathParts.length; i++) {
  10760. if (pathParts[i].indexOf(':') !== -1) {
  10761. var QNameParts = pathParts[i].split(':');
  10762. if (QNameParts.length !== 2) {
  10763. throw new Error('Unable to parse XPath string : ' + xpath + ' : with QName : ' + pathParts[i]);
  10764. }
  10765. var expandedPath = XPATH_PATH_TEMPLATE.replace('LOCAL_NAME', QNameParts[1]);
  10766. expandedPath = expandedPath.replace('NAMESPACE', namespaces[QNameParts[0]]);
  10767. pathParts[i] = expandedPath;
  10768. }
  10769. }
  10770. return pathParts.join('/');
  10771. }
  10772. var exports = {
  10773. /**
  10774. * Performs an xpath select that does appropriate namespace matching since the imported
  10775. * xpath module does not properly handle namespaces.
  10776. * @static
  10777. * @memberOf XmlUtil
  10778. * @param {object} dom A dom object created by the xmldom module
  10779. * @param {string} xpath An xpath expression
  10780. * @return {array} An array of matching dom nodes.
  10781. */
  10782. xpathSelect : function (dom, xpath) {
  10783. return select(dom, expandQNames(xpath));
  10784. },
  10785. /**
  10786. * Given a dom node serializes all immediate children that are xml elements.
  10787. * @static
  10788. * @memberOf XmlUtil
  10789. * @param {object} node An xml dom node.
  10790. * @return {string} Serialized xml.
  10791. */
  10792. serializeNodeChildren : function(node) {
  10793. var doc = '';
  10794. var sibling = node.firstChild;
  10795. var serializer = new XMLSerializer();
  10796. while (sibling) {
  10797. if (this.isElementNode(sibling)) {
  10798. doc += serializer.serializeToString(sibling);
  10799. }
  10800. sibling = sibling.nextSibling;
  10801. }
  10802. return doc !== '' ? doc : null;
  10803. },
  10804. /**
  10805. * Detects whether the passed in dom node represents an xml element.
  10806. * @static
  10807. * @memberOf XmlUtil
  10808. * @param {object} node An xml dom node.
  10809. * @return {Boolean} true if the node represents an element.
  10810. */
  10811. isElementNode : function(node) {
  10812. return _.has(node, 'tagName');
  10813. },
  10814. /**
  10815. * Given an xmldom node this function returns any text data contained within.
  10816. * @static
  10817. * @memberOf XmlUtil
  10818. * @param {object} node An xmldom node from which the data should be extracted.
  10819. * @return {string} Any data found within the element or null if none is found.
  10820. */
  10821. findElementText : function(node) {
  10822. var sibling = node.firstChild;
  10823. while (sibling && !sibling.data) {
  10824. sibling = sibling.nextSibling;
  10825. }
  10826. return sibling.data ? sibling.data : null;
  10827. }
  10828. };
  10829. module.exports = exports;
  10830. },{"./constants":26,"underscore":651,"xmldom":705,"xpath.js":709}],38:[function(require,module,exports){
  10831. module.exports={
  10832. "_from": "adal-node@^0.1.28",
  10833. "_id": "adal-node@0.1.28",
  10834. "_inBundle": false,
  10835. "_integrity": "sha1-RoxLs+u9lrEnBmn0ucuk4AZepIU=",
  10836. "_location": "/adal-node",
  10837. "_phantomChildren": {},
  10838. "_requested": {
  10839. "type": "range",
  10840. "registry": true,
  10841. "raw": "adal-node@^0.1.28",
  10842. "name": "adal-node",
  10843. "escapedName": "adal-node",
  10844. "rawSpec": "^0.1.28",
  10845. "saveSpec": null,
  10846. "fetchSpec": "^0.1.28"
  10847. },
  10848. "_requiredBy": [
  10849. "/@azure/ms-rest-nodeauth"
  10850. ],
  10851. "_resolved": "https://registry.npmjs.org/adal-node/-/adal-node-0.1.28.tgz",
  10852. "_shasum": "468c4bb3ebbd96b1270669f4b9cba4e0065ea485",
  10853. "_spec": "adal-node@^0.1.28",
  10854. "_where": "/home/dasimmet/repos/browserified/node_modules/@azure/ms-rest-nodeauth",
  10855. "author": {
  10856. "name": "Microsoft Open Technologies Inc",
  10857. "email": "msopentech@microsoft.com",
  10858. "url": "http://msopentech.com/"
  10859. },
  10860. "bugs": {
  10861. "url": "https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/issues"
  10862. },
  10863. "bundleDependencies": false,
  10864. "dependencies": {
  10865. "@types/node": "^8.0.47",
  10866. "async": ">=0.6.0",
  10867. "date-utils": "*",
  10868. "jws": "3.x.x",
  10869. "request": ">= 2.52.0",
  10870. "underscore": ">= 1.3.1",
  10871. "uuid": "^3.1.0",
  10872. "xmldom": ">= 0.1.x",
  10873. "xpath.js": "~1.1.0"
  10874. },
  10875. "deprecated": false,
  10876. "description": "Windows Azure Active Directory Client Library for node",
  10877. "devDependencies": {
  10878. "@types/mocha": "^2.2.44",
  10879. "@types/nock": "^8.2.1",
  10880. "@types/sinon": "^2.3.7",
  10881. "@types/underscore": "^1.8.4",
  10882. "jshint": "*",
  10883. "mocha": "*",
  10884. "nock": "*",
  10885. "sinon": "*",
  10886. "typescript": "^2.6.1"
  10887. },
  10888. "engines": {
  10889. "node": ">= 0.6.15"
  10890. },
  10891. "homepage": "https://github.com/AzureAD/azure-activedirectory-library-for-nodejs#readme",
  10892. "keywords": [
  10893. "node",
  10894. "azure",
  10895. "AAD",
  10896. "adal",
  10897. "adfs",
  10898. "oauth"
  10899. ],
  10900. "license": "Apache-2.0",
  10901. "main": "./lib/adal.js",
  10902. "name": "adal-node",
  10903. "repository": {
  10904. "type": "git",
  10905. "url": "git+https://github.com/AzureAD/azure-activedirectory-library-for-nodejs.git"
  10906. },
  10907. "scripts": {
  10908. "cover": "./test/util/cover",
  10909. "doc": "jsdoc lib",
  10910. "test": "npm run tsc && mocha -R spec --ui tdd test",
  10911. "tsc": "tsc -p tsconfig.json"
  10912. },
  10913. "types": "./lib/adal.d.ts",
  10914. "version": "0.1.28"
  10915. }
  10916. },{}],39:[function(require,module,exports){
  10917. 'use strict';
  10918. var compileSchema = require('./compile')
  10919. , resolve = require('./compile/resolve')
  10920. , Cache = require('./cache')
  10921. , SchemaObject = require('./compile/schema_obj')
  10922. , stableStringify = require('fast-json-stable-stringify')
  10923. , formats = require('./compile/formats')
  10924. , rules = require('./compile/rules')
  10925. , $dataMetaSchema = require('./data')
  10926. , util = require('./compile/util');
  10927. module.exports = Ajv;
  10928. Ajv.prototype.validate = validate;
  10929. Ajv.prototype.compile = compile;
  10930. Ajv.prototype.addSchema = addSchema;
  10931. Ajv.prototype.addMetaSchema = addMetaSchema;
  10932. Ajv.prototype.validateSchema = validateSchema;
  10933. Ajv.prototype.getSchema = getSchema;
  10934. Ajv.prototype.removeSchema = removeSchema;
  10935. Ajv.prototype.addFormat = addFormat;
  10936. Ajv.prototype.errorsText = errorsText;
  10937. Ajv.prototype._addSchema = _addSchema;
  10938. Ajv.prototype._compile = _compile;
  10939. Ajv.prototype.compileAsync = require('./compile/async');
  10940. var customKeyword = require('./keyword');
  10941. Ajv.prototype.addKeyword = customKeyword.add;
  10942. Ajv.prototype.getKeyword = customKeyword.get;
  10943. Ajv.prototype.removeKeyword = customKeyword.remove;
  10944. Ajv.prototype.validateKeyword = customKeyword.validate;
  10945. var errorClasses = require('./compile/error_classes');
  10946. Ajv.ValidationError = errorClasses.Validation;
  10947. Ajv.MissingRefError = errorClasses.MissingRef;
  10948. Ajv.$dataMetaSchema = $dataMetaSchema;
  10949. var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
  10950. var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
  10951. var META_SUPPORT_DATA = ['/properties'];
  10952. /**
  10953. * Creates validator instance.
  10954. * Usage: `Ajv(opts)`
  10955. * @param {Object} opts optional options
  10956. * @return {Object} ajv instance
  10957. */
  10958. function Ajv(opts) {
  10959. if (!(this instanceof Ajv)) return new Ajv(opts);
  10960. opts = this._opts = util.copy(opts) || {};
  10961. setLogger(this);
  10962. this._schemas = {};
  10963. this._refs = {};
  10964. this._fragments = {};
  10965. this._formats = formats(opts.format);
  10966. this._cache = opts.cache || new Cache;
  10967. this._loadingSchemas = {};
  10968. this._compilations = [];
  10969. this.RULES = rules();
  10970. this._getId = chooseGetId(opts);
  10971. opts.loopRequired = opts.loopRequired || Infinity;
  10972. if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
  10973. if (opts.serialize === undefined) opts.serialize = stableStringify;
  10974. this._metaOpts = getMetaSchemaOptions(this);
  10975. if (opts.formats) addInitialFormats(this);
  10976. if (opts.keywords) addInitialKeywords(this);
  10977. addDefaultMetaSchema(this);
  10978. if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
  10979. if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
  10980. addInitialSchemas(this);
  10981. }
  10982. /**
  10983. * Validate data using schema
  10984. * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
  10985. * @this Ajv
  10986. * @param {String|Object} schemaKeyRef key, ref or schema object
  10987. * @param {Any} data to be validated
  10988. * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
  10989. */
  10990. function validate(schemaKeyRef, data) {
  10991. var v;
  10992. if (typeof schemaKeyRef == 'string') {
  10993. v = this.getSchema(schemaKeyRef);
  10994. if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
  10995. } else {
  10996. var schemaObj = this._addSchema(schemaKeyRef);
  10997. v = schemaObj.validate || this._compile(schemaObj);
  10998. }
  10999. var valid = v(data);
  11000. if (v.$async !== true) this.errors = v.errors;
  11001. return valid;
  11002. }
  11003. /**
  11004. * Create validating function for passed schema.
  11005. * @this Ajv
  11006. * @param {Object} schema schema object
  11007. * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
  11008. * @return {Function} validating function
  11009. */
  11010. function compile(schema, _meta) {
  11011. var schemaObj = this._addSchema(schema, undefined, _meta);
  11012. return schemaObj.validate || this._compile(schemaObj);
  11013. }
  11014. /**
  11015. * Adds schema to the instance.
  11016. * @this Ajv
  11017. * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
  11018. * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
  11019. * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
  11020. * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
  11021. * @return {Ajv} this for method chaining
  11022. */
  11023. function addSchema(schema, key, _skipValidation, _meta) {
  11024. if (Array.isArray(schema)){
  11025. for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
  11026. return this;
  11027. }
  11028. var id = this._getId(schema);
  11029. if (id !== undefined && typeof id != 'string')
  11030. throw new Error('schema id must be string');
  11031. key = resolve.normalizeId(key || id);
  11032. checkUnique(this, key);
  11033. this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
  11034. return this;
  11035. }
  11036. /**
  11037. * Add schema that will be used to validate other schemas
  11038. * options in META_IGNORE_OPTIONS are alway set to false
  11039. * @this Ajv
  11040. * @param {Object} schema schema object
  11041. * @param {String} key optional schema key
  11042. * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
  11043. * @return {Ajv} this for method chaining
  11044. */
  11045. function addMetaSchema(schema, key, skipValidation) {
  11046. this.addSchema(schema, key, skipValidation, true);
  11047. return this;
  11048. }
  11049. /**
  11050. * Validate schema
  11051. * @this Ajv
  11052. * @param {Object} schema schema to validate
  11053. * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
  11054. * @return {Boolean} true if schema is valid
  11055. */
  11056. function validateSchema(schema, throwOrLogError) {
  11057. var $schema = schema.$schema;
  11058. if ($schema !== undefined && typeof $schema != 'string')
  11059. throw new Error('$schema must be a string');
  11060. $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  11061. if (!$schema) {
  11062. this.logger.warn('meta-schema not available');
  11063. this.errors = null;
  11064. return true;
  11065. }
  11066. var valid = this.validate($schema, schema);
  11067. if (!valid && throwOrLogError) {
  11068. var message = 'schema is invalid: ' + this.errorsText();
  11069. if (this._opts.validateSchema == 'log') this.logger.error(message);
  11070. else throw new Error(message);
  11071. }
  11072. return valid;
  11073. }
  11074. function defaultMeta(self) {
  11075. var meta = self._opts.meta;
  11076. self._opts.defaultMeta = typeof meta == 'object'
  11077. ? self._getId(meta) || meta
  11078. : self.getSchema(META_SCHEMA_ID)
  11079. ? META_SCHEMA_ID
  11080. : undefined;
  11081. return self._opts.defaultMeta;
  11082. }
  11083. /**
  11084. * Get compiled schema from the instance by `key` or `ref`.
  11085. * @this Ajv
  11086. * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
  11087. * @return {Function} schema validating function (with property `schema`).
  11088. */
  11089. function getSchema(keyRef) {
  11090. var schemaObj = _getSchemaObj(this, keyRef);
  11091. switch (typeof schemaObj) {
  11092. case 'object': return schemaObj.validate || this._compile(schemaObj);
  11093. case 'string': return this.getSchema(schemaObj);
  11094. case 'undefined': return _getSchemaFragment(this, keyRef);
  11095. }
  11096. }
  11097. function _getSchemaFragment(self, ref) {
  11098. var res = resolve.schema.call(self, { schema: {} }, ref);
  11099. if (res) {
  11100. var schema = res.schema
  11101. , root = res.root
  11102. , baseId = res.baseId;
  11103. var v = compileSchema.call(self, schema, root, undefined, baseId);
  11104. self._fragments[ref] = new SchemaObject({
  11105. ref: ref,
  11106. fragment: true,
  11107. schema: schema,
  11108. root: root,
  11109. baseId: baseId,
  11110. validate: v
  11111. });
  11112. return v;
  11113. }
  11114. }
  11115. function _getSchemaObj(self, keyRef) {
  11116. keyRef = resolve.normalizeId(keyRef);
  11117. return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
  11118. }
  11119. /**
  11120. * Remove cached schema(s).
  11121. * If no parameter is passed all schemas but meta-schemas are removed.
  11122. * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
  11123. * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
  11124. * @this Ajv
  11125. * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
  11126. * @return {Ajv} this for method chaining
  11127. */
  11128. function removeSchema(schemaKeyRef) {
  11129. if (schemaKeyRef instanceof RegExp) {
  11130. _removeAllSchemas(this, this._schemas, schemaKeyRef);
  11131. _removeAllSchemas(this, this._refs, schemaKeyRef);
  11132. return this;
  11133. }
  11134. switch (typeof schemaKeyRef) {
  11135. case 'undefined':
  11136. _removeAllSchemas(this, this._schemas);
  11137. _removeAllSchemas(this, this._refs);
  11138. this._cache.clear();
  11139. return this;
  11140. case 'string':
  11141. var schemaObj = _getSchemaObj(this, schemaKeyRef);
  11142. if (schemaObj) this._cache.del(schemaObj.cacheKey);
  11143. delete this._schemas[schemaKeyRef];
  11144. delete this._refs[schemaKeyRef];
  11145. return this;
  11146. case 'object':
  11147. var serialize = this._opts.serialize;
  11148. var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
  11149. this._cache.del(cacheKey);
  11150. var id = this._getId(schemaKeyRef);
  11151. if (id) {
  11152. id = resolve.normalizeId(id);
  11153. delete this._schemas[id];
  11154. delete this._refs[id];
  11155. }
  11156. }
  11157. return this;
  11158. }
  11159. function _removeAllSchemas(self, schemas, regex) {
  11160. for (var keyRef in schemas) {
  11161. var schemaObj = schemas[keyRef];
  11162. if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
  11163. self._cache.del(schemaObj.cacheKey);
  11164. delete schemas[keyRef];
  11165. }
  11166. }
  11167. }
  11168. /* @this Ajv */
  11169. function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
  11170. if (typeof schema != 'object' && typeof schema != 'boolean')
  11171. throw new Error('schema should be object or boolean');
  11172. var serialize = this._opts.serialize;
  11173. var cacheKey = serialize ? serialize(schema) : schema;
  11174. var cached = this._cache.get(cacheKey);
  11175. if (cached) return cached;
  11176. shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
  11177. var id = resolve.normalizeId(this._getId(schema));
  11178. if (id && shouldAddSchema) checkUnique(this, id);
  11179. var willValidate = this._opts.validateSchema !== false && !skipValidation;
  11180. var recursiveMeta;
  11181. if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
  11182. this.validateSchema(schema, true);
  11183. var localRefs = resolve.ids.call(this, schema);
  11184. var schemaObj = new SchemaObject({
  11185. id: id,
  11186. schema: schema,
  11187. localRefs: localRefs,
  11188. cacheKey: cacheKey,
  11189. meta: meta
  11190. });
  11191. if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
  11192. this._cache.put(cacheKey, schemaObj);
  11193. if (willValidate && recursiveMeta) this.validateSchema(schema, true);
  11194. return schemaObj;
  11195. }
  11196. /* @this Ajv */
  11197. function _compile(schemaObj, root) {
  11198. if (schemaObj.compiling) {
  11199. schemaObj.validate = callValidate;
  11200. callValidate.schema = schemaObj.schema;
  11201. callValidate.errors = null;
  11202. callValidate.root = root ? root : callValidate;
  11203. if (schemaObj.schema.$async === true)
  11204. callValidate.$async = true;
  11205. return callValidate;
  11206. }
  11207. schemaObj.compiling = true;
  11208. var currentOpts;
  11209. if (schemaObj.meta) {
  11210. currentOpts = this._opts;
  11211. this._opts = this._metaOpts;
  11212. }
  11213. var v;
  11214. try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
  11215. catch(e) {
  11216. delete schemaObj.validate;
  11217. throw e;
  11218. }
  11219. finally {
  11220. schemaObj.compiling = false;
  11221. if (schemaObj.meta) this._opts = currentOpts;
  11222. }
  11223. schemaObj.validate = v;
  11224. schemaObj.refs = v.refs;
  11225. schemaObj.refVal = v.refVal;
  11226. schemaObj.root = v.root;
  11227. return v;
  11228. /* @this {*} - custom context, see passContext option */
  11229. function callValidate() {
  11230. /* jshint validthis: true */
  11231. var _validate = schemaObj.validate;
  11232. var result = _validate.apply(this, arguments);
  11233. callValidate.errors = _validate.errors;
  11234. return result;
  11235. }
  11236. }
  11237. function chooseGetId(opts) {
  11238. switch (opts.schemaId) {
  11239. case 'auto': return _get$IdOrId;
  11240. case 'id': return _getId;
  11241. default: return _get$Id;
  11242. }
  11243. }
  11244. /* @this Ajv */
  11245. function _getId(schema) {
  11246. if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
  11247. return schema.id;
  11248. }
  11249. /* @this Ajv */
  11250. function _get$Id(schema) {
  11251. if (schema.id) this.logger.warn('schema id ignored', schema.id);
  11252. return schema.$id;
  11253. }
  11254. function _get$IdOrId(schema) {
  11255. if (schema.$id && schema.id && schema.$id != schema.id)
  11256. throw new Error('schema $id is different from id');
  11257. return schema.$id || schema.id;
  11258. }
  11259. /**
  11260. * Convert array of error message objects to string
  11261. * @this Ajv
  11262. * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
  11263. * @param {Object} options optional options with properties `separator` and `dataVar`.
  11264. * @return {String} human readable string with all errors descriptions
  11265. */
  11266. function errorsText(errors, options) {
  11267. errors = errors || this.errors;
  11268. if (!errors) return 'No errors';
  11269. options = options || {};
  11270. var separator = options.separator === undefined ? ', ' : options.separator;
  11271. var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
  11272. var text = '';
  11273. for (var i=0; i<errors.length; i++) {
  11274. var e = errors[i];
  11275. if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
  11276. }
  11277. return text.slice(0, -separator.length);
  11278. }
  11279. /**
  11280. * Add custom format
  11281. * @this Ajv
  11282. * @param {String} name format name
  11283. * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
  11284. * @return {Ajv} this for method chaining
  11285. */
  11286. function addFormat(name, format) {
  11287. if (typeof format == 'string') format = new RegExp(format);
  11288. this._formats[name] = format;
  11289. return this;
  11290. }
  11291. function addDefaultMetaSchema(self) {
  11292. var $dataSchema;
  11293. if (self._opts.$data) {
  11294. $dataSchema = require('./refs/data.json');
  11295. self.addMetaSchema($dataSchema, $dataSchema.$id, true);
  11296. }
  11297. if (self._opts.meta === false) return;
  11298. var metaSchema = require('./refs/json-schema-draft-07.json');
  11299. if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
  11300. self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
  11301. self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
  11302. }
  11303. function addInitialSchemas(self) {
  11304. var optsSchemas = self._opts.schemas;
  11305. if (!optsSchemas) return;
  11306. if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
  11307. else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
  11308. }
  11309. function addInitialFormats(self) {
  11310. for (var name in self._opts.formats) {
  11311. var format = self._opts.formats[name];
  11312. self.addFormat(name, format);
  11313. }
  11314. }
  11315. function addInitialKeywords(self) {
  11316. for (var name in self._opts.keywords) {
  11317. var keyword = self._opts.keywords[name];
  11318. self.addKeyword(name, keyword);
  11319. }
  11320. }
  11321. function checkUnique(self, id) {
  11322. if (self._schemas[id] || self._refs[id])
  11323. throw new Error('schema with key or id "' + id + '" already exists');
  11324. }
  11325. function getMetaSchemaOptions(self) {
  11326. var metaOpts = util.copy(self._opts);
  11327. for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
  11328. delete metaOpts[META_IGNORE_OPTIONS[i]];
  11329. return metaOpts;
  11330. }
  11331. function setLogger(self) {
  11332. var logger = self._opts.logger;
  11333. if (logger === false) {
  11334. self.logger = {log: noop, warn: noop, error: noop};
  11335. } else {
  11336. if (logger === undefined) logger = console;
  11337. if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
  11338. throw new Error('logger must implement log, warn and error methods');
  11339. self.logger = logger;
  11340. }
  11341. }
  11342. function noop() {}
  11343. },{"./cache":40,"./compile":44,"./compile/async":41,"./compile/error_classes":42,"./compile/formats":43,"./compile/resolve":45,"./compile/rules":46,"./compile/schema_obj":47,"./compile/util":49,"./data":50,"./keyword":78,"./refs/data.json":79,"./refs/json-schema-draft-07.json":81,"fast-json-stable-stringify":252}],40:[function(require,module,exports){
  11344. 'use strict';
  11345. var Cache = module.exports = function Cache() {
  11346. this._cache = {};
  11347. };
  11348. Cache.prototype.put = function Cache_put(key, value) {
  11349. this._cache[key] = value;
  11350. };
  11351. Cache.prototype.get = function Cache_get(key) {
  11352. return this._cache[key];
  11353. };
  11354. Cache.prototype.del = function Cache_del(key) {
  11355. delete this._cache[key];
  11356. };
  11357. Cache.prototype.clear = function Cache_clear() {
  11358. this._cache = {};
  11359. };
  11360. },{}],41:[function(require,module,exports){
  11361. 'use strict';
  11362. var MissingRefError = require('./error_classes').MissingRef;
  11363. module.exports = compileAsync;
  11364. /**
  11365. * Creates validating function for passed schema with asynchronous loading of missing schemas.
  11366. * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
  11367. * @this Ajv
  11368. * @param {Object} schema schema object
  11369. * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
  11370. * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
  11371. * @return {Promise} promise that resolves with a validating function.
  11372. */
  11373. function compileAsync(schema, meta, callback) {
  11374. /* eslint no-shadow: 0 */
  11375. /* global Promise */
  11376. /* jshint validthis: true */
  11377. var self = this;
  11378. if (typeof this._opts.loadSchema != 'function')
  11379. throw new Error('options.loadSchema should be a function');
  11380. if (typeof meta == 'function') {
  11381. callback = meta;
  11382. meta = undefined;
  11383. }
  11384. var p = loadMetaSchemaOf(schema).then(function () {
  11385. var schemaObj = self._addSchema(schema, undefined, meta);
  11386. return schemaObj.validate || _compileAsync(schemaObj);
  11387. });
  11388. if (callback) {
  11389. p.then(
  11390. function(v) { callback(null, v); },
  11391. callback
  11392. );
  11393. }
  11394. return p;
  11395. function loadMetaSchemaOf(sch) {
  11396. var $schema = sch.$schema;
  11397. return $schema && !self.getSchema($schema)
  11398. ? compileAsync.call(self, { $ref: $schema }, true)
  11399. : Promise.resolve();
  11400. }
  11401. function _compileAsync(schemaObj) {
  11402. try { return self._compile(schemaObj); }
  11403. catch(e) {
  11404. if (e instanceof MissingRefError) return loadMissingSchema(e);
  11405. throw e;
  11406. }
  11407. function loadMissingSchema(e) {
  11408. var ref = e.missingSchema;
  11409. if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
  11410. var schemaPromise = self._loadingSchemas[ref];
  11411. if (!schemaPromise) {
  11412. schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
  11413. schemaPromise.then(removePromise, removePromise);
  11414. }
  11415. return schemaPromise.then(function (sch) {
  11416. if (!added(ref)) {
  11417. return loadMetaSchemaOf(sch).then(function () {
  11418. if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
  11419. });
  11420. }
  11421. }).then(function() {
  11422. return _compileAsync(schemaObj);
  11423. });
  11424. function removePromise() {
  11425. delete self._loadingSchemas[ref];
  11426. }
  11427. function added(ref) {
  11428. return self._refs[ref] || self._schemas[ref];
  11429. }
  11430. }
  11431. }
  11432. }
  11433. },{"./error_classes":42}],42:[function(require,module,exports){
  11434. 'use strict';
  11435. var resolve = require('./resolve');
  11436. module.exports = {
  11437. Validation: errorSubclass(ValidationError),
  11438. MissingRef: errorSubclass(MissingRefError)
  11439. };
  11440. function ValidationError(errors) {
  11441. this.message = 'validation failed';
  11442. this.errors = errors;
  11443. this.ajv = this.validation = true;
  11444. }
  11445. MissingRefError.message = function (baseId, ref) {
  11446. return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
  11447. };
  11448. function MissingRefError(baseId, ref, message) {
  11449. this.message = message || MissingRefError.message(baseId, ref);
  11450. this.missingRef = resolve.url(baseId, ref);
  11451. this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
  11452. }
  11453. function errorSubclass(Subclass) {
  11454. Subclass.prototype = Object.create(Error.prototype);
  11455. Subclass.prototype.constructor = Subclass;
  11456. return Subclass;
  11457. }
  11458. },{"./resolve":45}],43:[function(require,module,exports){
  11459. 'use strict';
  11460. var util = require('./util');
  11461. var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
  11462. var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
  11463. var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
  11464. var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
  11465. var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
  11466. var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
  11467. // uri-template: https://tools.ietf.org/html/rfc6570
  11468. var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
  11469. // For the source: https://gist.github.com/dperini/729294
  11470. // For test cases: https://mathiasbynens.be/demo/url-regex
  11471. // @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
  11472. // var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
  11473. var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
  11474. var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
  11475. var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
  11476. var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
  11477. var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
  11478. module.exports = formats;
  11479. function formats(mode) {
  11480. mode = mode == 'full' ? 'full' : 'fast';
  11481. return util.copy(formats[mode]);
  11482. }
  11483. formats.fast = {
  11484. // date: http://tools.ietf.org/html/rfc3339#section-5.6
  11485. date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
  11486. // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
  11487. time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
  11488. 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
  11489. // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
  11490. uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
  11491. 'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
  11492. 'uri-template': URITEMPLATE,
  11493. url: URL,
  11494. // email (sources from jsen validator):
  11495. // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
  11496. // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
  11497. email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
  11498. hostname: HOSTNAME,
  11499. // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
  11500. ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  11501. // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  11502. ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  11503. regex: regex,
  11504. // uuid: http://tools.ietf.org/html/rfc4122
  11505. uuid: UUID,
  11506. // JSON-pointer: https://tools.ietf.org/html/rfc6901
  11507. // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
  11508. 'json-pointer': JSON_POINTER,
  11509. 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  11510. // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
  11511. 'relative-json-pointer': RELATIVE_JSON_POINTER
  11512. };
  11513. formats.full = {
  11514. date: date,
  11515. time: time,
  11516. 'date-time': date_time,
  11517. uri: uri,
  11518. 'uri-reference': URIREF,
  11519. 'uri-template': URITEMPLATE,
  11520. url: URL,
  11521. email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
  11522. hostname: HOSTNAME,
  11523. ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  11524. ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  11525. regex: regex,
  11526. uuid: UUID,
  11527. 'json-pointer': JSON_POINTER,
  11528. 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  11529. 'relative-json-pointer': RELATIVE_JSON_POINTER
  11530. };
  11531. function isLeapYear(year) {
  11532. // https://tools.ietf.org/html/rfc3339#appendix-C
  11533. return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  11534. }
  11535. function date(str) {
  11536. // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
  11537. var matches = str.match(DATE);
  11538. if (!matches) return false;
  11539. var year = +matches[1];
  11540. var month = +matches[2];
  11541. var day = +matches[3];
  11542. return month >= 1 && month <= 12 && day >= 1 &&
  11543. day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
  11544. }
  11545. function time(str, full) {
  11546. var matches = str.match(TIME);
  11547. if (!matches) return false;
  11548. var hour = matches[1];
  11549. var minute = matches[2];
  11550. var second = matches[3];
  11551. var timeZone = matches[5];
  11552. return ((hour <= 23 && minute <= 59 && second <= 59) ||
  11553. (hour == 23 && minute == 59 && second == 60)) &&
  11554. (!full || timeZone);
  11555. }
  11556. var DATE_TIME_SEPARATOR = /t|\s/i;
  11557. function date_time(str) {
  11558. // http://tools.ietf.org/html/rfc3339#section-5.6
  11559. var dateTime = str.split(DATE_TIME_SEPARATOR);
  11560. return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
  11561. }
  11562. var NOT_URI_FRAGMENT = /\/|:/;
  11563. function uri(str) {
  11564. // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
  11565. return NOT_URI_FRAGMENT.test(str) && URI.test(str);
  11566. }
  11567. var Z_ANCHOR = /[^\\]\\Z/;
  11568. function regex(str) {
  11569. if (Z_ANCHOR.test(str)) return false;
  11570. try {
  11571. new RegExp(str);
  11572. return true;
  11573. } catch(e) {
  11574. return false;
  11575. }
  11576. }
  11577. },{"./util":49}],44:[function(require,module,exports){
  11578. 'use strict';
  11579. var resolve = require('./resolve')
  11580. , util = require('./util')
  11581. , errorClasses = require('./error_classes')
  11582. , stableStringify = require('fast-json-stable-stringify');
  11583. var validateGenerator = require('../dotjs/validate');
  11584. /**
  11585. * Functions below are used inside compiled validations function
  11586. */
  11587. var ucs2length = util.ucs2length;
  11588. var equal = require('fast-deep-equal');
  11589. // this error is thrown by async schemas to return validation errors via exception
  11590. var ValidationError = errorClasses.Validation;
  11591. module.exports = compile;
  11592. /**
  11593. * Compiles schema to validation function
  11594. * @this Ajv
  11595. * @param {Object} schema schema object
  11596. * @param {Object} root object with information about the root schema for this schema
  11597. * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
  11598. * @param {String} baseId base ID for IDs in the schema
  11599. * @return {Function} validation function
  11600. */
  11601. function compile(schema, root, localRefs, baseId) {
  11602. /* jshint validthis: true, evil: true */
  11603. /* eslint no-shadow: 0 */
  11604. var self = this
  11605. , opts = this._opts
  11606. , refVal = [ undefined ]
  11607. , refs = {}
  11608. , patterns = []
  11609. , patternsHash = {}
  11610. , defaults = []
  11611. , defaultsHash = {}
  11612. , customRules = [];
  11613. root = root || { schema: schema, refVal: refVal, refs: refs };
  11614. var c = checkCompiling.call(this, schema, root, baseId);
  11615. var compilation = this._compilations[c.index];
  11616. if (c.compiling) return (compilation.callValidate = callValidate);
  11617. var formats = this._formats;
  11618. var RULES = this.RULES;
  11619. try {
  11620. var v = localCompile(schema, root, localRefs, baseId);
  11621. compilation.validate = v;
  11622. var cv = compilation.callValidate;
  11623. if (cv) {
  11624. cv.schema = v.schema;
  11625. cv.errors = null;
  11626. cv.refs = v.refs;
  11627. cv.refVal = v.refVal;
  11628. cv.root = v.root;
  11629. cv.$async = v.$async;
  11630. if (opts.sourceCode) cv.source = v.source;
  11631. }
  11632. return v;
  11633. } finally {
  11634. endCompiling.call(this, schema, root, baseId);
  11635. }
  11636. /* @this {*} - custom context, see passContext option */
  11637. function callValidate() {
  11638. /* jshint validthis: true */
  11639. var validate = compilation.validate;
  11640. var result = validate.apply(this, arguments);
  11641. callValidate.errors = validate.errors;
  11642. return result;
  11643. }
  11644. function localCompile(_schema, _root, localRefs, baseId) {
  11645. var isRoot = !_root || (_root && _root.schema == _schema);
  11646. if (_root.schema != root.schema)
  11647. return compile.call(self, _schema, _root, localRefs, baseId);
  11648. var $async = _schema.$async === true;
  11649. var sourceCode = validateGenerator({
  11650. isTop: true,
  11651. schema: _schema,
  11652. isRoot: isRoot,
  11653. baseId: baseId,
  11654. root: _root,
  11655. schemaPath: '',
  11656. errSchemaPath: '#',
  11657. errorPath: '""',
  11658. MissingRefError: errorClasses.MissingRef,
  11659. RULES: RULES,
  11660. validate: validateGenerator,
  11661. util: util,
  11662. resolve: resolve,
  11663. resolveRef: resolveRef,
  11664. usePattern: usePattern,
  11665. useDefault: useDefault,
  11666. useCustomRule: useCustomRule,
  11667. opts: opts,
  11668. formats: formats,
  11669. logger: self.logger,
  11670. self: self
  11671. });
  11672. sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
  11673. + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
  11674. + sourceCode;
  11675. if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
  11676. // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
  11677. var validate;
  11678. try {
  11679. var makeValidate = new Function(
  11680. 'self',
  11681. 'RULES',
  11682. 'formats',
  11683. 'root',
  11684. 'refVal',
  11685. 'defaults',
  11686. 'customRules',
  11687. 'equal',
  11688. 'ucs2length',
  11689. 'ValidationError',
  11690. sourceCode
  11691. );
  11692. validate = makeValidate(
  11693. self,
  11694. RULES,
  11695. formats,
  11696. root,
  11697. refVal,
  11698. defaults,
  11699. customRules,
  11700. equal,
  11701. ucs2length,
  11702. ValidationError
  11703. );
  11704. refVal[0] = validate;
  11705. } catch(e) {
  11706. self.logger.error('Error compiling schema, function code:', sourceCode);
  11707. throw e;
  11708. }
  11709. validate.schema = _schema;
  11710. validate.errors = null;
  11711. validate.refs = refs;
  11712. validate.refVal = refVal;
  11713. validate.root = isRoot ? validate : _root;
  11714. if ($async) validate.$async = true;
  11715. if (opts.sourceCode === true) {
  11716. validate.source = {
  11717. code: sourceCode,
  11718. patterns: patterns,
  11719. defaults: defaults
  11720. };
  11721. }
  11722. return validate;
  11723. }
  11724. function resolveRef(baseId, ref, isRoot) {
  11725. ref = resolve.url(baseId, ref);
  11726. var refIndex = refs[ref];
  11727. var _refVal, refCode;
  11728. if (refIndex !== undefined) {
  11729. _refVal = refVal[refIndex];
  11730. refCode = 'refVal[' + refIndex + ']';
  11731. return resolvedRef(_refVal, refCode);
  11732. }
  11733. if (!isRoot && root.refs) {
  11734. var rootRefId = root.refs[ref];
  11735. if (rootRefId !== undefined) {
  11736. _refVal = root.refVal[rootRefId];
  11737. refCode = addLocalRef(ref, _refVal);
  11738. return resolvedRef(_refVal, refCode);
  11739. }
  11740. }
  11741. refCode = addLocalRef(ref);
  11742. var v = resolve.call(self, localCompile, root, ref);
  11743. if (v === undefined) {
  11744. var localSchema = localRefs && localRefs[ref];
  11745. if (localSchema) {
  11746. v = resolve.inlineRef(localSchema, opts.inlineRefs)
  11747. ? localSchema
  11748. : compile.call(self, localSchema, root, localRefs, baseId);
  11749. }
  11750. }
  11751. if (v === undefined) {
  11752. removeLocalRef(ref);
  11753. } else {
  11754. replaceLocalRef(ref, v);
  11755. return resolvedRef(v, refCode);
  11756. }
  11757. }
  11758. function addLocalRef(ref, v) {
  11759. var refId = refVal.length;
  11760. refVal[refId] = v;
  11761. refs[ref] = refId;
  11762. return 'refVal' + refId;
  11763. }
  11764. function removeLocalRef(ref) {
  11765. delete refs[ref];
  11766. }
  11767. function replaceLocalRef(ref, v) {
  11768. var refId = refs[ref];
  11769. refVal[refId] = v;
  11770. }
  11771. function resolvedRef(refVal, code) {
  11772. return typeof refVal == 'object' || typeof refVal == 'boolean'
  11773. ? { code: code, schema: refVal, inline: true }
  11774. : { code: code, $async: refVal && !!refVal.$async };
  11775. }
  11776. function usePattern(regexStr) {
  11777. var index = patternsHash[regexStr];
  11778. if (index === undefined) {
  11779. index = patternsHash[regexStr] = patterns.length;
  11780. patterns[index] = regexStr;
  11781. }
  11782. return 'pattern' + index;
  11783. }
  11784. function useDefault(value) {
  11785. switch (typeof value) {
  11786. case 'boolean':
  11787. case 'number':
  11788. return '' + value;
  11789. case 'string':
  11790. return util.toQuotedString(value);
  11791. case 'object':
  11792. if (value === null) return 'null';
  11793. var valueStr = stableStringify(value);
  11794. var index = defaultsHash[valueStr];
  11795. if (index === undefined) {
  11796. index = defaultsHash[valueStr] = defaults.length;
  11797. defaults[index] = value;
  11798. }
  11799. return 'default' + index;
  11800. }
  11801. }
  11802. function useCustomRule(rule, schema, parentSchema, it) {
  11803. if (self._opts.validateSchema !== false) {
  11804. var deps = rule.definition.dependencies;
  11805. if (deps && !deps.every(function(keyword) {
  11806. return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
  11807. }))
  11808. throw new Error('parent schema must have all required keywords: ' + deps.join(','));
  11809. var validateSchema = rule.definition.validateSchema;
  11810. if (validateSchema) {
  11811. var valid = validateSchema(schema);
  11812. if (!valid) {
  11813. var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
  11814. if (self._opts.validateSchema == 'log') self.logger.error(message);
  11815. else throw new Error(message);
  11816. }
  11817. }
  11818. }
  11819. var compile = rule.definition.compile
  11820. , inline = rule.definition.inline
  11821. , macro = rule.definition.macro;
  11822. var validate;
  11823. if (compile) {
  11824. validate = compile.call(self, schema, parentSchema, it);
  11825. } else if (macro) {
  11826. validate = macro.call(self, schema, parentSchema, it);
  11827. if (opts.validateSchema !== false) self.validateSchema(validate, true);
  11828. } else if (inline) {
  11829. validate = inline.call(self, it, rule.keyword, schema, parentSchema);
  11830. } else {
  11831. validate = rule.definition.validate;
  11832. if (!validate) return;
  11833. }
  11834. if (validate === undefined)
  11835. throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
  11836. var index = customRules.length;
  11837. customRules[index] = validate;
  11838. return {
  11839. code: 'customRule' + index,
  11840. validate: validate
  11841. };
  11842. }
  11843. }
  11844. /**
  11845. * Checks if the schema is currently compiled
  11846. * @this Ajv
  11847. * @param {Object} schema schema to compile
  11848. * @param {Object} root root object
  11849. * @param {String} baseId base schema ID
  11850. * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
  11851. */
  11852. function checkCompiling(schema, root, baseId) {
  11853. /* jshint validthis: true */
  11854. var index = compIndex.call(this, schema, root, baseId);
  11855. if (index >= 0) return { index: index, compiling: true };
  11856. index = this._compilations.length;
  11857. this._compilations[index] = {
  11858. schema: schema,
  11859. root: root,
  11860. baseId: baseId
  11861. };
  11862. return { index: index, compiling: false };
  11863. }
  11864. /**
  11865. * Removes the schema from the currently compiled list
  11866. * @this Ajv
  11867. * @param {Object} schema schema to compile
  11868. * @param {Object} root root object
  11869. * @param {String} baseId base schema ID
  11870. */
  11871. function endCompiling(schema, root, baseId) {
  11872. /* jshint validthis: true */
  11873. var i = compIndex.call(this, schema, root, baseId);
  11874. if (i >= 0) this._compilations.splice(i, 1);
  11875. }
  11876. /**
  11877. * Index of schema compilation in the currently compiled list
  11878. * @this Ajv
  11879. * @param {Object} schema schema to compile
  11880. * @param {Object} root root object
  11881. * @param {String} baseId base schema ID
  11882. * @return {Integer} compilation index
  11883. */
  11884. function compIndex(schema, root, baseId) {
  11885. /* jshint validthis: true */
  11886. for (var i=0; i<this._compilations.length; i++) {
  11887. var c = this._compilations[i];
  11888. if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  11889. }
  11890. return -1;
  11891. }
  11892. function patternCode(i, patterns) {
  11893. return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
  11894. }
  11895. function defaultCode(i) {
  11896. return 'var default' + i + ' = defaults[' + i + '];';
  11897. }
  11898. function refValCode(i, refVal) {
  11899. return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
  11900. }
  11901. function customRuleCode(i) {
  11902. return 'var customRule' + i + ' = customRules[' + i + '];';
  11903. }
  11904. function vars(arr, statement) {
  11905. if (!arr.length) return '';
  11906. var code = '';
  11907. for (var i=0; i<arr.length; i++)
  11908. code += statement(i, arr);
  11909. return code;
  11910. }
  11911. },{"../dotjs/validate":77,"./error_classes":42,"./resolve":45,"./util":49,"fast-deep-equal":251,"fast-json-stable-stringify":252}],45:[function(require,module,exports){
  11912. 'use strict';
  11913. var URI = require('uri-js')
  11914. , equal = require('fast-deep-equal')
  11915. , util = require('./util')
  11916. , SchemaObject = require('./schema_obj')
  11917. , traverse = require('json-schema-traverse');
  11918. module.exports = resolve;
  11919. resolve.normalizeId = normalizeId;
  11920. resolve.fullPath = getFullPath;
  11921. resolve.url = resolveUrl;
  11922. resolve.ids = resolveIds;
  11923. resolve.inlineRef = inlineRef;
  11924. resolve.schema = resolveSchema;
  11925. /**
  11926. * [resolve and compile the references ($ref)]
  11927. * @this Ajv
  11928. * @param {Function} compile reference to schema compilation funciton (localCompile)
  11929. * @param {Object} root object with information about the root schema for the current schema
  11930. * @param {String} ref reference to resolve
  11931. * @return {Object|Function} schema object (if the schema can be inlined) or validation function
  11932. */
  11933. function resolve(compile, root, ref) {
  11934. /* jshint validthis: true */
  11935. var refVal = this._refs[ref];
  11936. if (typeof refVal == 'string') {
  11937. if (this._refs[refVal]) refVal = this._refs[refVal];
  11938. else return resolve.call(this, compile, root, refVal);
  11939. }
  11940. refVal = refVal || this._schemas[ref];
  11941. if (refVal instanceof SchemaObject) {
  11942. return inlineRef(refVal.schema, this._opts.inlineRefs)
  11943. ? refVal.schema
  11944. : refVal.validate || this._compile(refVal);
  11945. }
  11946. var res = resolveSchema.call(this, root, ref);
  11947. var schema, v, baseId;
  11948. if (res) {
  11949. schema = res.schema;
  11950. root = res.root;
  11951. baseId = res.baseId;
  11952. }
  11953. if (schema instanceof SchemaObject) {
  11954. v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
  11955. } else if (schema !== undefined) {
  11956. v = inlineRef(schema, this._opts.inlineRefs)
  11957. ? schema
  11958. : compile.call(this, schema, root, undefined, baseId);
  11959. }
  11960. return v;
  11961. }
  11962. /**
  11963. * Resolve schema, its root and baseId
  11964. * @this Ajv
  11965. * @param {Object} root root object with properties schema, refVal, refs
  11966. * @param {String} ref reference to resolve
  11967. * @return {Object} object with properties schema, root, baseId
  11968. */
  11969. function resolveSchema(root, ref) {
  11970. /* jshint validthis: true */
  11971. var p = URI.parse(ref)
  11972. , refPath = _getFullPath(p)
  11973. , baseId = getFullPath(this._getId(root.schema));
  11974. if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
  11975. var id = normalizeId(refPath);
  11976. var refVal = this._refs[id];
  11977. if (typeof refVal == 'string') {
  11978. return resolveRecursive.call(this, root, refVal, p);
  11979. } else if (refVal instanceof SchemaObject) {
  11980. if (!refVal.validate) this._compile(refVal);
  11981. root = refVal;
  11982. } else {
  11983. refVal = this._schemas[id];
  11984. if (refVal instanceof SchemaObject) {
  11985. if (!refVal.validate) this._compile(refVal);
  11986. if (id == normalizeId(ref))
  11987. return { schema: refVal, root: root, baseId: baseId };
  11988. root = refVal;
  11989. } else {
  11990. return;
  11991. }
  11992. }
  11993. if (!root.schema) return;
  11994. baseId = getFullPath(this._getId(root.schema));
  11995. }
  11996. return getJsonPointer.call(this, p, baseId, root.schema, root);
  11997. }
  11998. /* @this Ajv */
  11999. function resolveRecursive(root, ref, parsedRef) {
  12000. /* jshint validthis: true */
  12001. var res = resolveSchema.call(this, root, ref);
  12002. if (res) {
  12003. var schema = res.schema;
  12004. var baseId = res.baseId;
  12005. root = res.root;
  12006. var id = this._getId(schema);
  12007. if (id) baseId = resolveUrl(baseId, id);
  12008. return getJsonPointer.call(this, parsedRef, baseId, schema, root);
  12009. }
  12010. }
  12011. var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
  12012. /* @this Ajv */
  12013. function getJsonPointer(parsedRef, baseId, schema, root) {
  12014. /* jshint validthis: true */
  12015. parsedRef.fragment = parsedRef.fragment || '';
  12016. if (parsedRef.fragment.slice(0,1) != '/') return;
  12017. var parts = parsedRef.fragment.split('/');
  12018. for (var i = 1; i < parts.length; i++) {
  12019. var part = parts[i];
  12020. if (part) {
  12021. part = util.unescapeFragment(part);
  12022. schema = schema[part];
  12023. if (schema === undefined) break;
  12024. var id;
  12025. if (!PREVENT_SCOPE_CHANGE[part]) {
  12026. id = this._getId(schema);
  12027. if (id) baseId = resolveUrl(baseId, id);
  12028. if (schema.$ref) {
  12029. var $ref = resolveUrl(baseId, schema.$ref);
  12030. var res = resolveSchema.call(this, root, $ref);
  12031. if (res) {
  12032. schema = res.schema;
  12033. root = res.root;
  12034. baseId = res.baseId;
  12035. }
  12036. }
  12037. }
  12038. }
  12039. }
  12040. if (schema !== undefined && schema !== root.schema)
  12041. return { schema: schema, root: root, baseId: baseId };
  12042. }
  12043. var SIMPLE_INLINED = util.toHash([
  12044. 'type', 'format', 'pattern',
  12045. 'maxLength', 'minLength',
  12046. 'maxProperties', 'minProperties',
  12047. 'maxItems', 'minItems',
  12048. 'maximum', 'minimum',
  12049. 'uniqueItems', 'multipleOf',
  12050. 'required', 'enum'
  12051. ]);
  12052. function inlineRef(schema, limit) {
  12053. if (limit === false) return false;
  12054. if (limit === undefined || limit === true) return checkNoRef(schema);
  12055. else if (limit) return countKeys(schema) <= limit;
  12056. }
  12057. function checkNoRef(schema) {
  12058. var item;
  12059. if (Array.isArray(schema)) {
  12060. for (var i=0; i<schema.length; i++) {
  12061. item = schema[i];
  12062. if (typeof item == 'object' && !checkNoRef(item)) return false;
  12063. }
  12064. } else {
  12065. for (var key in schema) {
  12066. if (key == '$ref') return false;
  12067. item = schema[key];
  12068. if (typeof item == 'object' && !checkNoRef(item)) return false;
  12069. }
  12070. }
  12071. return true;
  12072. }
  12073. function countKeys(schema) {
  12074. var count = 0, item;
  12075. if (Array.isArray(schema)) {
  12076. for (var i=0; i<schema.length; i++) {
  12077. item = schema[i];
  12078. if (typeof item == 'object') count += countKeys(item);
  12079. if (count == Infinity) return Infinity;
  12080. }
  12081. } else {
  12082. for (var key in schema) {
  12083. if (key == '$ref') return Infinity;
  12084. if (SIMPLE_INLINED[key]) {
  12085. count++;
  12086. } else {
  12087. item = schema[key];
  12088. if (typeof item == 'object') count += countKeys(item) + 1;
  12089. if (count == Infinity) return Infinity;
  12090. }
  12091. }
  12092. }
  12093. return count;
  12094. }
  12095. function getFullPath(id, normalize) {
  12096. if (normalize !== false) id = normalizeId(id);
  12097. var p = URI.parse(id);
  12098. return _getFullPath(p);
  12099. }
  12100. function _getFullPath(p) {
  12101. return URI.serialize(p).split('#')[0] + '#';
  12102. }
  12103. var TRAILING_SLASH_HASH = /#\/?$/;
  12104. function normalizeId(id) {
  12105. return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
  12106. }
  12107. function resolveUrl(baseId, id) {
  12108. id = normalizeId(id);
  12109. return URI.resolve(baseId, id);
  12110. }
  12111. /* @this Ajv */
  12112. function resolveIds(schema) {
  12113. var schemaId = normalizeId(this._getId(schema));
  12114. var baseIds = {'': schemaId};
  12115. var fullPaths = {'': getFullPath(schemaId, false)};
  12116. var localRefs = {};
  12117. var self = this;
  12118. traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  12119. if (jsonPtr === '') return;
  12120. var id = self._getId(sch);
  12121. var baseId = baseIds[parentJsonPtr];
  12122. var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
  12123. if (keyIndex !== undefined)
  12124. fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
  12125. if (typeof id == 'string') {
  12126. id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
  12127. var refVal = self._refs[id];
  12128. if (typeof refVal == 'string') refVal = self._refs[refVal];
  12129. if (refVal && refVal.schema) {
  12130. if (!equal(sch, refVal.schema))
  12131. throw new Error('id "' + id + '" resolves to more than one schema');
  12132. } else if (id != normalizeId(fullPath)) {
  12133. if (id[0] == '#') {
  12134. if (localRefs[id] && !equal(sch, localRefs[id]))
  12135. throw new Error('id "' + id + '" resolves to more than one schema');
  12136. localRefs[id] = sch;
  12137. } else {
  12138. self._refs[id] = fullPath;
  12139. }
  12140. }
  12141. }
  12142. baseIds[jsonPtr] = baseId;
  12143. fullPaths[jsonPtr] = fullPath;
  12144. });
  12145. return localRefs;
  12146. }
  12147. },{"./schema_obj":47,"./util":49,"fast-deep-equal":251,"json-schema-traverse":329,"uri-js":652}],46:[function(require,module,exports){
  12148. 'use strict';
  12149. var ruleModules = require('../dotjs')
  12150. , toHash = require('./util').toHash;
  12151. module.exports = function rules() {
  12152. var RULES = [
  12153. { type: 'number',
  12154. rules: [ { 'maximum': ['exclusiveMaximum'] },
  12155. { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
  12156. { type: 'string',
  12157. rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
  12158. { type: 'array',
  12159. rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
  12160. { type: 'object',
  12161. rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
  12162. { 'properties': ['additionalProperties', 'patternProperties'] } ] },
  12163. { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
  12164. ];
  12165. var ALL = [ 'type', '$comment' ];
  12166. var KEYWORDS = [
  12167. '$schema', '$id', 'id', '$data', '$async', 'title',
  12168. 'description', 'default', 'definitions',
  12169. 'examples', 'readOnly', 'writeOnly',
  12170. 'contentMediaType', 'contentEncoding',
  12171. 'additionalItems', 'then', 'else'
  12172. ];
  12173. var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  12174. RULES.all = toHash(ALL);
  12175. RULES.types = toHash(TYPES);
  12176. RULES.forEach(function (group) {
  12177. group.rules = group.rules.map(function (keyword) {
  12178. var implKeywords;
  12179. if (typeof keyword == 'object') {
  12180. var key = Object.keys(keyword)[0];
  12181. implKeywords = keyword[key];
  12182. keyword = key;
  12183. implKeywords.forEach(function (k) {
  12184. ALL.push(k);
  12185. RULES.all[k] = true;
  12186. });
  12187. }
  12188. ALL.push(keyword);
  12189. var rule = RULES.all[keyword] = {
  12190. keyword: keyword,
  12191. code: ruleModules[keyword],
  12192. implements: implKeywords
  12193. };
  12194. return rule;
  12195. });
  12196. RULES.all.$comment = {
  12197. keyword: '$comment',
  12198. code: ruleModules.$comment
  12199. };
  12200. if (group.type) RULES.types[group.type] = group;
  12201. });
  12202. RULES.keywords = toHash(ALL.concat(KEYWORDS));
  12203. RULES.custom = {};
  12204. return RULES;
  12205. };
  12206. },{"../dotjs":66,"./util":49}],47:[function(require,module,exports){
  12207. 'use strict';
  12208. var util = require('./util');
  12209. module.exports = SchemaObject;
  12210. function SchemaObject(obj) {
  12211. util.copy(obj, this);
  12212. }
  12213. },{"./util":49}],48:[function(require,module,exports){
  12214. 'use strict';
  12215. // https://mathiasbynens.be/notes/javascript-encoding
  12216. // https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
  12217. module.exports = function ucs2length(str) {
  12218. var length = 0
  12219. , len = str.length
  12220. , pos = 0
  12221. , value;
  12222. while (pos < len) {
  12223. length++;
  12224. value = str.charCodeAt(pos++);
  12225. if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
  12226. // high surrogate, and there is a next character
  12227. value = str.charCodeAt(pos);
  12228. if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
  12229. }
  12230. }
  12231. return length;
  12232. };
  12233. },{}],49:[function(require,module,exports){
  12234. 'use strict';
  12235. module.exports = {
  12236. copy: copy,
  12237. checkDataType: checkDataType,
  12238. checkDataTypes: checkDataTypes,
  12239. coerceToTypes: coerceToTypes,
  12240. toHash: toHash,
  12241. getProperty: getProperty,
  12242. escapeQuotes: escapeQuotes,
  12243. equal: require('fast-deep-equal'),
  12244. ucs2length: require('./ucs2length'),
  12245. varOccurences: varOccurences,
  12246. varReplace: varReplace,
  12247. schemaHasRules: schemaHasRules,
  12248. schemaHasRulesExcept: schemaHasRulesExcept,
  12249. schemaUnknownRules: schemaUnknownRules,
  12250. toQuotedString: toQuotedString,
  12251. getPathExpr: getPathExpr,
  12252. getPath: getPath,
  12253. getData: getData,
  12254. unescapeFragment: unescapeFragment,
  12255. unescapeJsonPointer: unescapeJsonPointer,
  12256. escapeFragment: escapeFragment,
  12257. escapeJsonPointer: escapeJsonPointer
  12258. };
  12259. function copy(o, to) {
  12260. to = to || {};
  12261. for (var key in o) to[key] = o[key];
  12262. return to;
  12263. }
  12264. function checkDataType(dataType, data, strictNumbers, negate) {
  12265. var EQUAL = negate ? ' !== ' : ' === '
  12266. , AND = negate ? ' || ' : ' && '
  12267. , OK = negate ? '!' : ''
  12268. , NOT = negate ? '' : '!';
  12269. switch (dataType) {
  12270. case 'null': return data + EQUAL + 'null';
  12271. case 'array': return OK + 'Array.isArray(' + data + ')';
  12272. case 'object': return '(' + OK + data + AND +
  12273. 'typeof ' + data + EQUAL + '"object"' + AND +
  12274. NOT + 'Array.isArray(' + data + '))';
  12275. case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
  12276. NOT + '(' + data + ' % 1)' +
  12277. AND + data + EQUAL + data +
  12278. (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
  12279. case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
  12280. (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
  12281. default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
  12282. }
  12283. }
  12284. function checkDataTypes(dataTypes, data, strictNumbers) {
  12285. switch (dataTypes.length) {
  12286. case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
  12287. default:
  12288. var code = '';
  12289. var types = toHash(dataTypes);
  12290. if (types.array && types.object) {
  12291. code = types.null ? '(': '(!' + data + ' || ';
  12292. code += 'typeof ' + data + ' !== "object")';
  12293. delete types.null;
  12294. delete types.array;
  12295. delete types.object;
  12296. }
  12297. if (types.number) delete types.integer;
  12298. for (var t in types)
  12299. code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
  12300. return code;
  12301. }
  12302. }
  12303. var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
  12304. function coerceToTypes(optionCoerceTypes, dataTypes) {
  12305. if (Array.isArray(dataTypes)) {
  12306. var types = [];
  12307. for (var i=0; i<dataTypes.length; i++) {
  12308. var t = dataTypes[i];
  12309. if (COERCE_TO_TYPES[t]) types[types.length] = t;
  12310. else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
  12311. }
  12312. if (types.length) return types;
  12313. } else if (COERCE_TO_TYPES[dataTypes]) {
  12314. return [dataTypes];
  12315. } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
  12316. return ['array'];
  12317. }
  12318. }
  12319. function toHash(arr) {
  12320. var hash = {};
  12321. for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
  12322. return hash;
  12323. }
  12324. var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
  12325. var SINGLE_QUOTE = /'|\\/g;
  12326. function getProperty(key) {
  12327. return typeof key == 'number'
  12328. ? '[' + key + ']'
  12329. : IDENTIFIER.test(key)
  12330. ? '.' + key
  12331. : "['" + escapeQuotes(key) + "']";
  12332. }
  12333. function escapeQuotes(str) {
  12334. return str.replace(SINGLE_QUOTE, '\\$&')
  12335. .replace(/\n/g, '\\n')
  12336. .replace(/\r/g, '\\r')
  12337. .replace(/\f/g, '\\f')
  12338. .replace(/\t/g, '\\t');
  12339. }
  12340. function varOccurences(str, dataVar) {
  12341. dataVar += '[^0-9]';
  12342. var matches = str.match(new RegExp(dataVar, 'g'));
  12343. return matches ? matches.length : 0;
  12344. }
  12345. function varReplace(str, dataVar, expr) {
  12346. dataVar += '([^0-9])';
  12347. expr = expr.replace(/\$/g, '$$$$');
  12348. return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
  12349. }
  12350. function schemaHasRules(schema, rules) {
  12351. if (typeof schema == 'boolean') return !schema;
  12352. for (var key in schema) if (rules[key]) return true;
  12353. }
  12354. function schemaHasRulesExcept(schema, rules, exceptKeyword) {
  12355. if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
  12356. for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
  12357. }
  12358. function schemaUnknownRules(schema, rules) {
  12359. if (typeof schema == 'boolean') return;
  12360. for (var key in schema) if (!rules[key]) return key;
  12361. }
  12362. function toQuotedString(str) {
  12363. return '\'' + escapeQuotes(str) + '\'';
  12364. }
  12365. function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  12366. var path = jsonPointers // false by default
  12367. ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
  12368. : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
  12369. return joinPaths(currentPath, path);
  12370. }
  12371. function getPath(currentPath, prop, jsonPointers) {
  12372. var path = jsonPointers // false by default
  12373. ? toQuotedString('/' + escapeJsonPointer(prop))
  12374. : toQuotedString(getProperty(prop));
  12375. return joinPaths(currentPath, path);
  12376. }
  12377. var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
  12378. var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
  12379. function getData($data, lvl, paths) {
  12380. var up, jsonPointer, data, matches;
  12381. if ($data === '') return 'rootData';
  12382. if ($data[0] == '/') {
  12383. if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
  12384. jsonPointer = $data;
  12385. data = 'rootData';
  12386. } else {
  12387. matches = $data.match(RELATIVE_JSON_POINTER);
  12388. if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
  12389. up = +matches[1];
  12390. jsonPointer = matches[2];
  12391. if (jsonPointer == '#') {
  12392. if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
  12393. return paths[lvl - up];
  12394. }
  12395. if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
  12396. data = 'data' + ((lvl - up) || '');
  12397. if (!jsonPointer) return data;
  12398. }
  12399. var expr = data;
  12400. var segments = jsonPointer.split('/');
  12401. for (var i=0; i<segments.length; i++) {
  12402. var segment = segments[i];
  12403. if (segment) {
  12404. data += getProperty(unescapeJsonPointer(segment));
  12405. expr += ' && ' + data;
  12406. }
  12407. }
  12408. return expr;
  12409. }
  12410. function joinPaths (a, b) {
  12411. if (a == '""') return b;
  12412. return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
  12413. }
  12414. function unescapeFragment(str) {
  12415. return unescapeJsonPointer(decodeURIComponent(str));
  12416. }
  12417. function escapeFragment(str) {
  12418. return encodeURIComponent(escapeJsonPointer(str));
  12419. }
  12420. function escapeJsonPointer(str) {
  12421. return str.replace(/~/g, '~0').replace(/\//g, '~1');
  12422. }
  12423. function unescapeJsonPointer(str) {
  12424. return str.replace(/~1/g, '/').replace(/~0/g, '~');
  12425. }
  12426. },{"./ucs2length":48,"fast-deep-equal":251}],50:[function(require,module,exports){
  12427. 'use strict';
  12428. var KEYWORDS = [
  12429. 'multipleOf',
  12430. 'maximum',
  12431. 'exclusiveMaximum',
  12432. 'minimum',
  12433. 'exclusiveMinimum',
  12434. 'maxLength',
  12435. 'minLength',
  12436. 'pattern',
  12437. 'additionalItems',
  12438. 'maxItems',
  12439. 'minItems',
  12440. 'uniqueItems',
  12441. 'maxProperties',
  12442. 'minProperties',
  12443. 'required',
  12444. 'additionalProperties',
  12445. 'enum',
  12446. 'format',
  12447. 'const'
  12448. ];
  12449. module.exports = function (metaSchema, keywordsJsonPointers) {
  12450. for (var i=0; i<keywordsJsonPointers.length; i++) {
  12451. metaSchema = JSON.parse(JSON.stringify(metaSchema));
  12452. var segments = keywordsJsonPointers[i].split('/');
  12453. var keywords = metaSchema;
  12454. var j;
  12455. for (j=1; j<segments.length; j++)
  12456. keywords = keywords[segments[j]];
  12457. for (j=0; j<KEYWORDS.length; j++) {
  12458. var key = KEYWORDS[j];
  12459. var schema = keywords[key];
  12460. if (schema) {
  12461. keywords[key] = {
  12462. anyOf: [
  12463. schema,
  12464. { $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
  12465. ]
  12466. };
  12467. }
  12468. }
  12469. }
  12470. return metaSchema;
  12471. };
  12472. },{}],51:[function(require,module,exports){
  12473. 'use strict';
  12474. var metaSchema = require('./refs/json-schema-draft-07.json');
  12475. module.exports = {
  12476. $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
  12477. definitions: {
  12478. simpleTypes: metaSchema.definitions.simpleTypes
  12479. },
  12480. type: 'object',
  12481. dependencies: {
  12482. schema: ['validate'],
  12483. $data: ['validate'],
  12484. statements: ['inline'],
  12485. valid: {not: {required: ['macro']}}
  12486. },
  12487. properties: {
  12488. type: metaSchema.properties.type,
  12489. schema: {type: 'boolean'},
  12490. statements: {type: 'boolean'},
  12491. dependencies: {
  12492. type: 'array',
  12493. items: {type: 'string'}
  12494. },
  12495. metaSchema: {type: 'object'},
  12496. modifying: {type: 'boolean'},
  12497. valid: {type: 'boolean'},
  12498. $data: {type: 'boolean'},
  12499. async: {type: 'boolean'},
  12500. errors: {
  12501. anyOf: [
  12502. {type: 'boolean'},
  12503. {const: 'full'}
  12504. ]
  12505. }
  12506. }
  12507. };
  12508. },{"./refs/json-schema-draft-07.json":81}],52:[function(require,module,exports){
  12509. 'use strict';
  12510. module.exports = function generate__limit(it, $keyword, $ruleType) {
  12511. var out = ' ';
  12512. var $lvl = it.level;
  12513. var $dataLvl = it.dataLevel;
  12514. var $schema = it.schema[$keyword];
  12515. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  12516. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  12517. var $breakOnError = !it.opts.allErrors;
  12518. var $errorKeyword;
  12519. var $data = 'data' + ($dataLvl || '');
  12520. var $isData = it.opts.$data && $schema && $schema.$data,
  12521. $schemaValue;
  12522. if ($isData) {
  12523. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  12524. $schemaValue = 'schema' + $lvl;
  12525. } else {
  12526. $schemaValue = $schema;
  12527. }
  12528. var $isMax = $keyword == 'maximum',
  12529. $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
  12530. $schemaExcl = it.schema[$exclusiveKeyword],
  12531. $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
  12532. $op = $isMax ? '<' : '>',
  12533. $notOp = $isMax ? '>' : '<',
  12534. $errorKeyword = undefined;
  12535. if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
  12536. throw new Error($keyword + ' must be number');
  12537. }
  12538. if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {
  12539. throw new Error($exclusiveKeyword + ' must be number or boolean');
  12540. }
  12541. if ($isDataExcl) {
  12542. var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
  12543. $exclusive = 'exclusive' + $lvl,
  12544. $exclType = 'exclType' + $lvl,
  12545. $exclIsNumber = 'exclIsNumber' + $lvl,
  12546. $opExpr = 'op' + $lvl,
  12547. $opStr = '\' + ' + $opExpr + ' + \'';
  12548. out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
  12549. $schemaValueExcl = 'schemaExcl' + $lvl;
  12550. out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
  12551. var $errorKeyword = $exclusiveKeyword;
  12552. var $$outStack = $$outStack || [];
  12553. $$outStack.push(out);
  12554. out = ''; /* istanbul ignore else */
  12555. if (it.createErrors !== false) {
  12556. out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
  12557. if (it.opts.messages !== false) {
  12558. out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
  12559. }
  12560. if (it.opts.verbose) {
  12561. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  12562. }
  12563. out += ' } ';
  12564. } else {
  12565. out += ' {} ';
  12566. }
  12567. var __err = out;
  12568. out = $$outStack.pop();
  12569. if (!it.compositeRule && $breakOnError) {
  12570. /* istanbul ignore if */
  12571. if (it.async) {
  12572. out += ' throw new ValidationError([' + (__err) + ']); ';
  12573. } else {
  12574. out += ' validate.errors = [' + (__err) + ']; return false; ';
  12575. }
  12576. } else {
  12577. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  12578. }
  12579. out += ' } else if ( ';
  12580. if ($isData) {
  12581. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  12582. }
  12583. out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
  12584. if ($schema === undefined) {
  12585. $errorKeyword = $exclusiveKeyword;
  12586. $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
  12587. $schemaValue = $schemaValueExcl;
  12588. $isData = $isDataExcl;
  12589. }
  12590. } else {
  12591. var $exclIsNumber = typeof $schemaExcl == 'number',
  12592. $opStr = $op;
  12593. if ($exclIsNumber && $isData) {
  12594. var $opExpr = '\'' + $opStr + '\'';
  12595. out += ' if ( ';
  12596. if ($isData) {
  12597. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  12598. }
  12599. out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
  12600. } else {
  12601. if ($exclIsNumber && $schema === undefined) {
  12602. $exclusive = true;
  12603. $errorKeyword = $exclusiveKeyword;
  12604. $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
  12605. $schemaValue = $schemaExcl;
  12606. $notOp += '=';
  12607. } else {
  12608. if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
  12609. if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
  12610. $exclusive = true;
  12611. $errorKeyword = $exclusiveKeyword;
  12612. $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
  12613. $notOp += '=';
  12614. } else {
  12615. $exclusive = false;
  12616. $opStr += '=';
  12617. }
  12618. }
  12619. var $opExpr = '\'' + $opStr + '\'';
  12620. out += ' if ( ';
  12621. if ($isData) {
  12622. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  12623. }
  12624. out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
  12625. }
  12626. }
  12627. $errorKeyword = $errorKeyword || $keyword;
  12628. var $$outStack = $$outStack || [];
  12629. $$outStack.push(out);
  12630. out = ''; /* istanbul ignore else */
  12631. if (it.createErrors !== false) {
  12632. out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
  12633. if (it.opts.messages !== false) {
  12634. out += ' , message: \'should be ' + ($opStr) + ' ';
  12635. if ($isData) {
  12636. out += '\' + ' + ($schemaValue);
  12637. } else {
  12638. out += '' + ($schemaValue) + '\'';
  12639. }
  12640. }
  12641. if (it.opts.verbose) {
  12642. out += ' , schema: ';
  12643. if ($isData) {
  12644. out += 'validate.schema' + ($schemaPath);
  12645. } else {
  12646. out += '' + ($schema);
  12647. }
  12648. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  12649. }
  12650. out += ' } ';
  12651. } else {
  12652. out += ' {} ';
  12653. }
  12654. var __err = out;
  12655. out = $$outStack.pop();
  12656. if (!it.compositeRule && $breakOnError) {
  12657. /* istanbul ignore if */
  12658. if (it.async) {
  12659. out += ' throw new ValidationError([' + (__err) + ']); ';
  12660. } else {
  12661. out += ' validate.errors = [' + (__err) + ']; return false; ';
  12662. }
  12663. } else {
  12664. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  12665. }
  12666. out += ' } ';
  12667. if ($breakOnError) {
  12668. out += ' else { ';
  12669. }
  12670. return out;
  12671. }
  12672. },{}],53:[function(require,module,exports){
  12673. 'use strict';
  12674. module.exports = function generate__limitItems(it, $keyword, $ruleType) {
  12675. var out = ' ';
  12676. var $lvl = it.level;
  12677. var $dataLvl = it.dataLevel;
  12678. var $schema = it.schema[$keyword];
  12679. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  12680. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  12681. var $breakOnError = !it.opts.allErrors;
  12682. var $errorKeyword;
  12683. var $data = 'data' + ($dataLvl || '');
  12684. var $isData = it.opts.$data && $schema && $schema.$data,
  12685. $schemaValue;
  12686. if ($isData) {
  12687. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  12688. $schemaValue = 'schema' + $lvl;
  12689. } else {
  12690. $schemaValue = $schema;
  12691. }
  12692. if (!($isData || typeof $schema == 'number')) {
  12693. throw new Error($keyword + ' must be number');
  12694. }
  12695. var $op = $keyword == 'maxItems' ? '>' : '<';
  12696. out += 'if ( ';
  12697. if ($isData) {
  12698. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  12699. }
  12700. out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  12701. var $errorKeyword = $keyword;
  12702. var $$outStack = $$outStack || [];
  12703. $$outStack.push(out);
  12704. out = ''; /* istanbul ignore else */
  12705. if (it.createErrors !== false) {
  12706. out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
  12707. if (it.opts.messages !== false) {
  12708. out += ' , message: \'should NOT have ';
  12709. if ($keyword == 'maxItems') {
  12710. out += 'more';
  12711. } else {
  12712. out += 'fewer';
  12713. }
  12714. out += ' than ';
  12715. if ($isData) {
  12716. out += '\' + ' + ($schemaValue) + ' + \'';
  12717. } else {
  12718. out += '' + ($schema);
  12719. }
  12720. out += ' items\' ';
  12721. }
  12722. if (it.opts.verbose) {
  12723. out += ' , schema: ';
  12724. if ($isData) {
  12725. out += 'validate.schema' + ($schemaPath);
  12726. } else {
  12727. out += '' + ($schema);
  12728. }
  12729. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  12730. }
  12731. out += ' } ';
  12732. } else {
  12733. out += ' {} ';
  12734. }
  12735. var __err = out;
  12736. out = $$outStack.pop();
  12737. if (!it.compositeRule && $breakOnError) {
  12738. /* istanbul ignore if */
  12739. if (it.async) {
  12740. out += ' throw new ValidationError([' + (__err) + ']); ';
  12741. } else {
  12742. out += ' validate.errors = [' + (__err) + ']; return false; ';
  12743. }
  12744. } else {
  12745. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  12746. }
  12747. out += '} ';
  12748. if ($breakOnError) {
  12749. out += ' else { ';
  12750. }
  12751. return out;
  12752. }
  12753. },{}],54:[function(require,module,exports){
  12754. 'use strict';
  12755. module.exports = function generate__limitLength(it, $keyword, $ruleType) {
  12756. var out = ' ';
  12757. var $lvl = it.level;
  12758. var $dataLvl = it.dataLevel;
  12759. var $schema = it.schema[$keyword];
  12760. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  12761. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  12762. var $breakOnError = !it.opts.allErrors;
  12763. var $errorKeyword;
  12764. var $data = 'data' + ($dataLvl || '');
  12765. var $isData = it.opts.$data && $schema && $schema.$data,
  12766. $schemaValue;
  12767. if ($isData) {
  12768. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  12769. $schemaValue = 'schema' + $lvl;
  12770. } else {
  12771. $schemaValue = $schema;
  12772. }
  12773. if (!($isData || typeof $schema == 'number')) {
  12774. throw new Error($keyword + ' must be number');
  12775. }
  12776. var $op = $keyword == 'maxLength' ? '>' : '<';
  12777. out += 'if ( ';
  12778. if ($isData) {
  12779. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  12780. }
  12781. if (it.opts.unicode === false) {
  12782. out += ' ' + ($data) + '.length ';
  12783. } else {
  12784. out += ' ucs2length(' + ($data) + ') ';
  12785. }
  12786. out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
  12787. var $errorKeyword = $keyword;
  12788. var $$outStack = $$outStack || [];
  12789. $$outStack.push(out);
  12790. out = ''; /* istanbul ignore else */
  12791. if (it.createErrors !== false) {
  12792. out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
  12793. if (it.opts.messages !== false) {
  12794. out += ' , message: \'should NOT be ';
  12795. if ($keyword == 'maxLength') {
  12796. out += 'longer';
  12797. } else {
  12798. out += 'shorter';
  12799. }
  12800. out += ' than ';
  12801. if ($isData) {
  12802. out += '\' + ' + ($schemaValue) + ' + \'';
  12803. } else {
  12804. out += '' + ($schema);
  12805. }
  12806. out += ' characters\' ';
  12807. }
  12808. if (it.opts.verbose) {
  12809. out += ' , schema: ';
  12810. if ($isData) {
  12811. out += 'validate.schema' + ($schemaPath);
  12812. } else {
  12813. out += '' + ($schema);
  12814. }
  12815. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  12816. }
  12817. out += ' } ';
  12818. } else {
  12819. out += ' {} ';
  12820. }
  12821. var __err = out;
  12822. out = $$outStack.pop();
  12823. if (!it.compositeRule && $breakOnError) {
  12824. /* istanbul ignore if */
  12825. if (it.async) {
  12826. out += ' throw new ValidationError([' + (__err) + ']); ';
  12827. } else {
  12828. out += ' validate.errors = [' + (__err) + ']; return false; ';
  12829. }
  12830. } else {
  12831. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  12832. }
  12833. out += '} ';
  12834. if ($breakOnError) {
  12835. out += ' else { ';
  12836. }
  12837. return out;
  12838. }
  12839. },{}],55:[function(require,module,exports){
  12840. 'use strict';
  12841. module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
  12842. var out = ' ';
  12843. var $lvl = it.level;
  12844. var $dataLvl = it.dataLevel;
  12845. var $schema = it.schema[$keyword];
  12846. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  12847. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  12848. var $breakOnError = !it.opts.allErrors;
  12849. var $errorKeyword;
  12850. var $data = 'data' + ($dataLvl || '');
  12851. var $isData = it.opts.$data && $schema && $schema.$data,
  12852. $schemaValue;
  12853. if ($isData) {
  12854. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  12855. $schemaValue = 'schema' + $lvl;
  12856. } else {
  12857. $schemaValue = $schema;
  12858. }
  12859. if (!($isData || typeof $schema == 'number')) {
  12860. throw new Error($keyword + ' must be number');
  12861. }
  12862. var $op = $keyword == 'maxProperties' ? '>' : '<';
  12863. out += 'if ( ';
  12864. if ($isData) {
  12865. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  12866. }
  12867. out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  12868. var $errorKeyword = $keyword;
  12869. var $$outStack = $$outStack || [];
  12870. $$outStack.push(out);
  12871. out = ''; /* istanbul ignore else */
  12872. if (it.createErrors !== false) {
  12873. out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
  12874. if (it.opts.messages !== false) {
  12875. out += ' , message: \'should NOT have ';
  12876. if ($keyword == 'maxProperties') {
  12877. out += 'more';
  12878. } else {
  12879. out += 'fewer';
  12880. }
  12881. out += ' than ';
  12882. if ($isData) {
  12883. out += '\' + ' + ($schemaValue) + ' + \'';
  12884. } else {
  12885. out += '' + ($schema);
  12886. }
  12887. out += ' properties\' ';
  12888. }
  12889. if (it.opts.verbose) {
  12890. out += ' , schema: ';
  12891. if ($isData) {
  12892. out += 'validate.schema' + ($schemaPath);
  12893. } else {
  12894. out += '' + ($schema);
  12895. }
  12896. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  12897. }
  12898. out += ' } ';
  12899. } else {
  12900. out += ' {} ';
  12901. }
  12902. var __err = out;
  12903. out = $$outStack.pop();
  12904. if (!it.compositeRule && $breakOnError) {
  12905. /* istanbul ignore if */
  12906. if (it.async) {
  12907. out += ' throw new ValidationError([' + (__err) + ']); ';
  12908. } else {
  12909. out += ' validate.errors = [' + (__err) + ']; return false; ';
  12910. }
  12911. } else {
  12912. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  12913. }
  12914. out += '} ';
  12915. if ($breakOnError) {
  12916. out += ' else { ';
  12917. }
  12918. return out;
  12919. }
  12920. },{}],56:[function(require,module,exports){
  12921. 'use strict';
  12922. module.exports = function generate_allOf(it, $keyword, $ruleType) {
  12923. var out = ' ';
  12924. var $schema = it.schema[$keyword];
  12925. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  12926. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  12927. var $breakOnError = !it.opts.allErrors;
  12928. var $it = it.util.copy(it);
  12929. var $closingBraces = '';
  12930. $it.level++;
  12931. var $nextValid = 'valid' + $it.level;
  12932. var $currentBaseId = $it.baseId,
  12933. $allSchemasEmpty = true;
  12934. var arr1 = $schema;
  12935. if (arr1) {
  12936. var $sch, $i = -1,
  12937. l1 = arr1.length - 1;
  12938. while ($i < l1) {
  12939. $sch = arr1[$i += 1];
  12940. if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
  12941. $allSchemasEmpty = false;
  12942. $it.schema = $sch;
  12943. $it.schemaPath = $schemaPath + '[' + $i + ']';
  12944. $it.errSchemaPath = $errSchemaPath + '/' + $i;
  12945. out += ' ' + (it.validate($it)) + ' ';
  12946. $it.baseId = $currentBaseId;
  12947. if ($breakOnError) {
  12948. out += ' if (' + ($nextValid) + ') { ';
  12949. $closingBraces += '}';
  12950. }
  12951. }
  12952. }
  12953. }
  12954. if ($breakOnError) {
  12955. if ($allSchemasEmpty) {
  12956. out += ' if (true) { ';
  12957. } else {
  12958. out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
  12959. }
  12960. }
  12961. return out;
  12962. }
  12963. },{}],57:[function(require,module,exports){
  12964. 'use strict';
  12965. module.exports = function generate_anyOf(it, $keyword, $ruleType) {
  12966. var out = ' ';
  12967. var $lvl = it.level;
  12968. var $dataLvl = it.dataLevel;
  12969. var $schema = it.schema[$keyword];
  12970. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  12971. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  12972. var $breakOnError = !it.opts.allErrors;
  12973. var $data = 'data' + ($dataLvl || '');
  12974. var $valid = 'valid' + $lvl;
  12975. var $errs = 'errs__' + $lvl;
  12976. var $it = it.util.copy(it);
  12977. var $closingBraces = '';
  12978. $it.level++;
  12979. var $nextValid = 'valid' + $it.level;
  12980. var $noEmptySchema = $schema.every(function($sch) {
  12981. return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all));
  12982. });
  12983. if ($noEmptySchema) {
  12984. var $currentBaseId = $it.baseId;
  12985. out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; ';
  12986. var $wasComposite = it.compositeRule;
  12987. it.compositeRule = $it.compositeRule = true;
  12988. var arr1 = $schema;
  12989. if (arr1) {
  12990. var $sch, $i = -1,
  12991. l1 = arr1.length - 1;
  12992. while ($i < l1) {
  12993. $sch = arr1[$i += 1];
  12994. $it.schema = $sch;
  12995. $it.schemaPath = $schemaPath + '[' + $i + ']';
  12996. $it.errSchemaPath = $errSchemaPath + '/' + $i;
  12997. out += ' ' + (it.validate($it)) + ' ';
  12998. $it.baseId = $currentBaseId;
  12999. out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
  13000. $closingBraces += '}';
  13001. }
  13002. }
  13003. it.compositeRule = $it.compositeRule = $wasComposite;
  13004. out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
  13005. if (it.createErrors !== false) {
  13006. out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
  13007. if (it.opts.messages !== false) {
  13008. out += ' , message: \'should match some schema in anyOf\' ';
  13009. }
  13010. if (it.opts.verbose) {
  13011. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13012. }
  13013. out += ' } ';
  13014. } else {
  13015. out += ' {} ';
  13016. }
  13017. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13018. if (!it.compositeRule && $breakOnError) {
  13019. /* istanbul ignore if */
  13020. if (it.async) {
  13021. out += ' throw new ValidationError(vErrors); ';
  13022. } else {
  13023. out += ' validate.errors = vErrors; return false; ';
  13024. }
  13025. }
  13026. out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  13027. if (it.opts.allErrors) {
  13028. out += ' } ';
  13029. }
  13030. } else {
  13031. if ($breakOnError) {
  13032. out += ' if (true) { ';
  13033. }
  13034. }
  13035. return out;
  13036. }
  13037. },{}],58:[function(require,module,exports){
  13038. 'use strict';
  13039. module.exports = function generate_comment(it, $keyword, $ruleType) {
  13040. var out = ' ';
  13041. var $schema = it.schema[$keyword];
  13042. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13043. var $breakOnError = !it.opts.allErrors;
  13044. var $comment = it.util.toQuotedString($schema);
  13045. if (it.opts.$comment === true) {
  13046. out += ' console.log(' + ($comment) + ');';
  13047. } else if (typeof it.opts.$comment == 'function') {
  13048. out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
  13049. }
  13050. return out;
  13051. }
  13052. },{}],59:[function(require,module,exports){
  13053. 'use strict';
  13054. module.exports = function generate_const(it, $keyword, $ruleType) {
  13055. var out = ' ';
  13056. var $lvl = it.level;
  13057. var $dataLvl = it.dataLevel;
  13058. var $schema = it.schema[$keyword];
  13059. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13060. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13061. var $breakOnError = !it.opts.allErrors;
  13062. var $data = 'data' + ($dataLvl || '');
  13063. var $valid = 'valid' + $lvl;
  13064. var $isData = it.opts.$data && $schema && $schema.$data,
  13065. $schemaValue;
  13066. if ($isData) {
  13067. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  13068. $schemaValue = 'schema' + $lvl;
  13069. } else {
  13070. $schemaValue = $schema;
  13071. }
  13072. if (!$isData) {
  13073. out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
  13074. }
  13075. out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';
  13076. var $$outStack = $$outStack || [];
  13077. $$outStack.push(out);
  13078. out = ''; /* istanbul ignore else */
  13079. if (it.createErrors !== false) {
  13080. out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
  13081. if (it.opts.messages !== false) {
  13082. out += ' , message: \'should be equal to constant\' ';
  13083. }
  13084. if (it.opts.verbose) {
  13085. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13086. }
  13087. out += ' } ';
  13088. } else {
  13089. out += ' {} ';
  13090. }
  13091. var __err = out;
  13092. out = $$outStack.pop();
  13093. if (!it.compositeRule && $breakOnError) {
  13094. /* istanbul ignore if */
  13095. if (it.async) {
  13096. out += ' throw new ValidationError([' + (__err) + ']); ';
  13097. } else {
  13098. out += ' validate.errors = [' + (__err) + ']; return false; ';
  13099. }
  13100. } else {
  13101. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13102. }
  13103. out += ' }';
  13104. if ($breakOnError) {
  13105. out += ' else { ';
  13106. }
  13107. return out;
  13108. }
  13109. },{}],60:[function(require,module,exports){
  13110. 'use strict';
  13111. module.exports = function generate_contains(it, $keyword, $ruleType) {
  13112. var out = ' ';
  13113. var $lvl = it.level;
  13114. var $dataLvl = it.dataLevel;
  13115. var $schema = it.schema[$keyword];
  13116. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13117. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13118. var $breakOnError = !it.opts.allErrors;
  13119. var $data = 'data' + ($dataLvl || '');
  13120. var $valid = 'valid' + $lvl;
  13121. var $errs = 'errs__' + $lvl;
  13122. var $it = it.util.copy(it);
  13123. var $closingBraces = '';
  13124. $it.level++;
  13125. var $nextValid = 'valid' + $it.level;
  13126. var $idx = 'i' + $lvl,
  13127. $dataNxt = $it.dataLevel = it.dataLevel + 1,
  13128. $nextData = 'data' + $dataNxt,
  13129. $currentBaseId = it.baseId,
  13130. $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all));
  13131. out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  13132. if ($nonEmptySchema) {
  13133. var $wasComposite = it.compositeRule;
  13134. it.compositeRule = $it.compositeRule = true;
  13135. $it.schema = $schema;
  13136. $it.schemaPath = $schemaPath;
  13137. $it.errSchemaPath = $errSchemaPath;
  13138. out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
  13139. $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
  13140. var $passData = $data + '[' + $idx + ']';
  13141. $it.dataPathArr[$dataNxt] = $idx;
  13142. var $code = it.validate($it);
  13143. $it.baseId = $currentBaseId;
  13144. if (it.util.varOccurences($code, $nextData) < 2) {
  13145. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  13146. } else {
  13147. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  13148. }
  13149. out += ' if (' + ($nextValid) + ') break; } ';
  13150. it.compositeRule = $it.compositeRule = $wasComposite;
  13151. out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
  13152. } else {
  13153. out += ' if (' + ($data) + '.length == 0) {';
  13154. }
  13155. var $$outStack = $$outStack || [];
  13156. $$outStack.push(out);
  13157. out = ''; /* istanbul ignore else */
  13158. if (it.createErrors !== false) {
  13159. out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
  13160. if (it.opts.messages !== false) {
  13161. out += ' , message: \'should contain a valid item\' ';
  13162. }
  13163. if (it.opts.verbose) {
  13164. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13165. }
  13166. out += ' } ';
  13167. } else {
  13168. out += ' {} ';
  13169. }
  13170. var __err = out;
  13171. out = $$outStack.pop();
  13172. if (!it.compositeRule && $breakOnError) {
  13173. /* istanbul ignore if */
  13174. if (it.async) {
  13175. out += ' throw new ValidationError([' + (__err) + ']); ';
  13176. } else {
  13177. out += ' validate.errors = [' + (__err) + ']; return false; ';
  13178. }
  13179. } else {
  13180. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13181. }
  13182. out += ' } else { ';
  13183. if ($nonEmptySchema) {
  13184. out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  13185. }
  13186. if (it.opts.allErrors) {
  13187. out += ' } ';
  13188. }
  13189. return out;
  13190. }
  13191. },{}],61:[function(require,module,exports){
  13192. 'use strict';
  13193. module.exports = function generate_custom(it, $keyword, $ruleType) {
  13194. var out = ' ';
  13195. var $lvl = it.level;
  13196. var $dataLvl = it.dataLevel;
  13197. var $schema = it.schema[$keyword];
  13198. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13199. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13200. var $breakOnError = !it.opts.allErrors;
  13201. var $errorKeyword;
  13202. var $data = 'data' + ($dataLvl || '');
  13203. var $valid = 'valid' + $lvl;
  13204. var $errs = 'errs__' + $lvl;
  13205. var $isData = it.opts.$data && $schema && $schema.$data,
  13206. $schemaValue;
  13207. if ($isData) {
  13208. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  13209. $schemaValue = 'schema' + $lvl;
  13210. } else {
  13211. $schemaValue = $schema;
  13212. }
  13213. var $rule = this,
  13214. $definition = 'definition' + $lvl,
  13215. $rDef = $rule.definition,
  13216. $closingBraces = '';
  13217. var $compile, $inline, $macro, $ruleValidate, $validateCode;
  13218. if ($isData && $rDef.$data) {
  13219. $validateCode = 'keywordValidate' + $lvl;
  13220. var $validateSchema = $rDef.validateSchema;
  13221. out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
  13222. } else {
  13223. $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
  13224. if (!$ruleValidate) return;
  13225. $schemaValue = 'validate.schema' + $schemaPath;
  13226. $validateCode = $ruleValidate.code;
  13227. $compile = $rDef.compile;
  13228. $inline = $rDef.inline;
  13229. $macro = $rDef.macro;
  13230. }
  13231. var $ruleErrs = $validateCode + '.errors',
  13232. $i = 'i' + $lvl,
  13233. $ruleErr = 'ruleErr' + $lvl,
  13234. $asyncKeyword = $rDef.async;
  13235. if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
  13236. if (!($inline || $macro)) {
  13237. out += '' + ($ruleErrs) + ' = null;';
  13238. }
  13239. out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  13240. if ($isData && $rDef.$data) {
  13241. $closingBraces += '}';
  13242. out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
  13243. if ($validateSchema) {
  13244. $closingBraces += '}';
  13245. out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
  13246. }
  13247. }
  13248. if ($inline) {
  13249. if ($rDef.statements) {
  13250. out += ' ' + ($ruleValidate.validate) + ' ';
  13251. } else {
  13252. out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
  13253. }
  13254. } else if ($macro) {
  13255. var $it = it.util.copy(it);
  13256. var $closingBraces = '';
  13257. $it.level++;
  13258. var $nextValid = 'valid' + $it.level;
  13259. $it.schema = $ruleValidate.validate;
  13260. $it.schemaPath = '';
  13261. var $wasComposite = it.compositeRule;
  13262. it.compositeRule = $it.compositeRule = true;
  13263. var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
  13264. it.compositeRule = $it.compositeRule = $wasComposite;
  13265. out += ' ' + ($code);
  13266. } else {
  13267. var $$outStack = $$outStack || [];
  13268. $$outStack.push(out);
  13269. out = '';
  13270. out += ' ' + ($validateCode) + '.call( ';
  13271. if (it.opts.passContext) {
  13272. out += 'this';
  13273. } else {
  13274. out += 'self';
  13275. }
  13276. if ($compile || $rDef.schema === false) {
  13277. out += ' , ' + ($data) + ' ';
  13278. } else {
  13279. out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
  13280. }
  13281. out += ' , (dataPath || \'\')';
  13282. if (it.errorPath != '""') {
  13283. out += ' + ' + (it.errorPath);
  13284. }
  13285. var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
  13286. $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
  13287. out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) ';
  13288. var def_callRuleValidate = out;
  13289. out = $$outStack.pop();
  13290. if ($rDef.errors === false) {
  13291. out += ' ' + ($valid) + ' = ';
  13292. if ($asyncKeyword) {
  13293. out += 'await ';
  13294. }
  13295. out += '' + (def_callRuleValidate) + '; ';
  13296. } else {
  13297. if ($asyncKeyword) {
  13298. $ruleErrs = 'customErrors' + $lvl;
  13299. out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
  13300. } else {
  13301. out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
  13302. }
  13303. }
  13304. }
  13305. if ($rDef.modifying) {
  13306. out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
  13307. }
  13308. out += '' + ($closingBraces);
  13309. if ($rDef.valid) {
  13310. if ($breakOnError) {
  13311. out += ' if (true) { ';
  13312. }
  13313. } else {
  13314. out += ' if ( ';
  13315. if ($rDef.valid === undefined) {
  13316. out += ' !';
  13317. if ($macro) {
  13318. out += '' + ($nextValid);
  13319. } else {
  13320. out += '' + ($valid);
  13321. }
  13322. } else {
  13323. out += ' ' + (!$rDef.valid) + ' ';
  13324. }
  13325. out += ') { ';
  13326. $errorKeyword = $rule.keyword;
  13327. var $$outStack = $$outStack || [];
  13328. $$outStack.push(out);
  13329. out = '';
  13330. var $$outStack = $$outStack || [];
  13331. $$outStack.push(out);
  13332. out = ''; /* istanbul ignore else */
  13333. if (it.createErrors !== false) {
  13334. out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
  13335. if (it.opts.messages !== false) {
  13336. out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
  13337. }
  13338. if (it.opts.verbose) {
  13339. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13340. }
  13341. out += ' } ';
  13342. } else {
  13343. out += ' {} ';
  13344. }
  13345. var __err = out;
  13346. out = $$outStack.pop();
  13347. if (!it.compositeRule && $breakOnError) {
  13348. /* istanbul ignore if */
  13349. if (it.async) {
  13350. out += ' throw new ValidationError([' + (__err) + ']); ';
  13351. } else {
  13352. out += ' validate.errors = [' + (__err) + ']; return false; ';
  13353. }
  13354. } else {
  13355. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13356. }
  13357. var def_customError = out;
  13358. out = $$outStack.pop();
  13359. if ($inline) {
  13360. if ($rDef.errors) {
  13361. if ($rDef.errors != 'full') {
  13362. out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
  13363. if (it.opts.verbose) {
  13364. out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
  13365. }
  13366. out += ' } ';
  13367. }
  13368. } else {
  13369. if ($rDef.errors === false) {
  13370. out += ' ' + (def_customError) + ' ';
  13371. } else {
  13372. out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else { for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
  13373. if (it.opts.verbose) {
  13374. out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
  13375. }
  13376. out += ' } } ';
  13377. }
  13378. }
  13379. } else if ($macro) {
  13380. out += ' var err = '; /* istanbul ignore else */
  13381. if (it.createErrors !== false) {
  13382. out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
  13383. if (it.opts.messages !== false) {
  13384. out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
  13385. }
  13386. if (it.opts.verbose) {
  13387. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13388. }
  13389. out += ' } ';
  13390. } else {
  13391. out += ' {} ';
  13392. }
  13393. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13394. if (!it.compositeRule && $breakOnError) {
  13395. /* istanbul ignore if */
  13396. if (it.async) {
  13397. out += ' throw new ValidationError(vErrors); ';
  13398. } else {
  13399. out += ' validate.errors = vErrors; return false; ';
  13400. }
  13401. }
  13402. } else {
  13403. if ($rDef.errors === false) {
  13404. out += ' ' + (def_customError) + ' ';
  13405. } else {
  13406. out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; ';
  13407. if (it.opts.verbose) {
  13408. out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
  13409. }
  13410. out += ' } } else { ' + (def_customError) + ' } ';
  13411. }
  13412. }
  13413. out += ' } ';
  13414. if ($breakOnError) {
  13415. out += ' else { ';
  13416. }
  13417. }
  13418. return out;
  13419. }
  13420. },{}],62:[function(require,module,exports){
  13421. 'use strict';
  13422. module.exports = function generate_dependencies(it, $keyword, $ruleType) {
  13423. var out = ' ';
  13424. var $lvl = it.level;
  13425. var $dataLvl = it.dataLevel;
  13426. var $schema = it.schema[$keyword];
  13427. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13428. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13429. var $breakOnError = !it.opts.allErrors;
  13430. var $data = 'data' + ($dataLvl || '');
  13431. var $errs = 'errs__' + $lvl;
  13432. var $it = it.util.copy(it);
  13433. var $closingBraces = '';
  13434. $it.level++;
  13435. var $nextValid = 'valid' + $it.level;
  13436. var $schemaDeps = {},
  13437. $propertyDeps = {},
  13438. $ownProperties = it.opts.ownProperties;
  13439. for ($property in $schema) {
  13440. if ($property == '__proto__') continue;
  13441. var $sch = $schema[$property];
  13442. var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
  13443. $deps[$property] = $sch;
  13444. }
  13445. out += 'var ' + ($errs) + ' = errors;';
  13446. var $currentErrorPath = it.errorPath;
  13447. out += 'var missing' + ($lvl) + ';';
  13448. for (var $property in $propertyDeps) {
  13449. $deps = $propertyDeps[$property];
  13450. if ($deps.length) {
  13451. out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
  13452. if ($ownProperties) {
  13453. out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
  13454. }
  13455. if ($breakOnError) {
  13456. out += ' && ( ';
  13457. var arr1 = $deps;
  13458. if (arr1) {
  13459. var $propertyKey, $i = -1,
  13460. l1 = arr1.length - 1;
  13461. while ($i < l1) {
  13462. $propertyKey = arr1[$i += 1];
  13463. if ($i) {
  13464. out += ' || ';
  13465. }
  13466. var $prop = it.util.getProperty($propertyKey),
  13467. $useData = $data + $prop;
  13468. out += ' ( ( ' + ($useData) + ' === undefined ';
  13469. if ($ownProperties) {
  13470. out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
  13471. }
  13472. out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
  13473. }
  13474. }
  13475. out += ')) { ';
  13476. var $propertyPath = 'missing' + $lvl,
  13477. $missingProperty = '\' + ' + $propertyPath + ' + \'';
  13478. if (it.opts._errorDataPathProperty) {
  13479. it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
  13480. }
  13481. var $$outStack = $$outStack || [];
  13482. $$outStack.push(out);
  13483. out = ''; /* istanbul ignore else */
  13484. if (it.createErrors !== false) {
  13485. out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
  13486. if (it.opts.messages !== false) {
  13487. out += ' , message: \'should have ';
  13488. if ($deps.length == 1) {
  13489. out += 'property ' + (it.util.escapeQuotes($deps[0]));
  13490. } else {
  13491. out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
  13492. }
  13493. out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
  13494. }
  13495. if (it.opts.verbose) {
  13496. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13497. }
  13498. out += ' } ';
  13499. } else {
  13500. out += ' {} ';
  13501. }
  13502. var __err = out;
  13503. out = $$outStack.pop();
  13504. if (!it.compositeRule && $breakOnError) {
  13505. /* istanbul ignore if */
  13506. if (it.async) {
  13507. out += ' throw new ValidationError([' + (__err) + ']); ';
  13508. } else {
  13509. out += ' validate.errors = [' + (__err) + ']; return false; ';
  13510. }
  13511. } else {
  13512. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13513. }
  13514. } else {
  13515. out += ' ) { ';
  13516. var arr2 = $deps;
  13517. if (arr2) {
  13518. var $propertyKey, i2 = -1,
  13519. l2 = arr2.length - 1;
  13520. while (i2 < l2) {
  13521. $propertyKey = arr2[i2 += 1];
  13522. var $prop = it.util.getProperty($propertyKey),
  13523. $missingProperty = it.util.escapeQuotes($propertyKey),
  13524. $useData = $data + $prop;
  13525. if (it.opts._errorDataPathProperty) {
  13526. it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
  13527. }
  13528. out += ' if ( ' + ($useData) + ' === undefined ';
  13529. if ($ownProperties) {
  13530. out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
  13531. }
  13532. out += ') { var err = '; /* istanbul ignore else */
  13533. if (it.createErrors !== false) {
  13534. out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
  13535. if (it.opts.messages !== false) {
  13536. out += ' , message: \'should have ';
  13537. if ($deps.length == 1) {
  13538. out += 'property ' + (it.util.escapeQuotes($deps[0]));
  13539. } else {
  13540. out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
  13541. }
  13542. out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
  13543. }
  13544. if (it.opts.verbose) {
  13545. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13546. }
  13547. out += ' } ';
  13548. } else {
  13549. out += ' {} ';
  13550. }
  13551. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
  13552. }
  13553. }
  13554. }
  13555. out += ' } ';
  13556. if ($breakOnError) {
  13557. $closingBraces += '}';
  13558. out += ' else { ';
  13559. }
  13560. }
  13561. }
  13562. it.errorPath = $currentErrorPath;
  13563. var $currentBaseId = $it.baseId;
  13564. for (var $property in $schemaDeps) {
  13565. var $sch = $schemaDeps[$property];
  13566. if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
  13567. out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
  13568. if ($ownProperties) {
  13569. out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
  13570. }
  13571. out += ') { ';
  13572. $it.schema = $sch;
  13573. $it.schemaPath = $schemaPath + it.util.getProperty($property);
  13574. $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
  13575. out += ' ' + (it.validate($it)) + ' ';
  13576. $it.baseId = $currentBaseId;
  13577. out += ' } ';
  13578. if ($breakOnError) {
  13579. out += ' if (' + ($nextValid) + ') { ';
  13580. $closingBraces += '}';
  13581. }
  13582. }
  13583. }
  13584. if ($breakOnError) {
  13585. out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  13586. }
  13587. return out;
  13588. }
  13589. },{}],63:[function(require,module,exports){
  13590. 'use strict';
  13591. module.exports = function generate_enum(it, $keyword, $ruleType) {
  13592. var out = ' ';
  13593. var $lvl = it.level;
  13594. var $dataLvl = it.dataLevel;
  13595. var $schema = it.schema[$keyword];
  13596. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13597. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13598. var $breakOnError = !it.opts.allErrors;
  13599. var $data = 'data' + ($dataLvl || '');
  13600. var $valid = 'valid' + $lvl;
  13601. var $isData = it.opts.$data && $schema && $schema.$data,
  13602. $schemaValue;
  13603. if ($isData) {
  13604. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  13605. $schemaValue = 'schema' + $lvl;
  13606. } else {
  13607. $schemaValue = $schema;
  13608. }
  13609. var $i = 'i' + $lvl,
  13610. $vSchema = 'schema' + $lvl;
  13611. if (!$isData) {
  13612. out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
  13613. }
  13614. out += 'var ' + ($valid) + ';';
  13615. if ($isData) {
  13616. out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  13617. }
  13618. out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
  13619. if ($isData) {
  13620. out += ' } ';
  13621. }
  13622. out += ' if (!' + ($valid) + ') { ';
  13623. var $$outStack = $$outStack || [];
  13624. $$outStack.push(out);
  13625. out = ''; /* istanbul ignore else */
  13626. if (it.createErrors !== false) {
  13627. out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
  13628. if (it.opts.messages !== false) {
  13629. out += ' , message: \'should be equal to one of the allowed values\' ';
  13630. }
  13631. if (it.opts.verbose) {
  13632. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13633. }
  13634. out += ' } ';
  13635. } else {
  13636. out += ' {} ';
  13637. }
  13638. var __err = out;
  13639. out = $$outStack.pop();
  13640. if (!it.compositeRule && $breakOnError) {
  13641. /* istanbul ignore if */
  13642. if (it.async) {
  13643. out += ' throw new ValidationError([' + (__err) + ']); ';
  13644. } else {
  13645. out += ' validate.errors = [' + (__err) + ']; return false; ';
  13646. }
  13647. } else {
  13648. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13649. }
  13650. out += ' }';
  13651. if ($breakOnError) {
  13652. out += ' else { ';
  13653. }
  13654. return out;
  13655. }
  13656. },{}],64:[function(require,module,exports){
  13657. 'use strict';
  13658. module.exports = function generate_format(it, $keyword, $ruleType) {
  13659. var out = ' ';
  13660. var $lvl = it.level;
  13661. var $dataLvl = it.dataLevel;
  13662. var $schema = it.schema[$keyword];
  13663. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13664. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13665. var $breakOnError = !it.opts.allErrors;
  13666. var $data = 'data' + ($dataLvl || '');
  13667. if (it.opts.format === false) {
  13668. if ($breakOnError) {
  13669. out += ' if (true) { ';
  13670. }
  13671. return out;
  13672. }
  13673. var $isData = it.opts.$data && $schema && $schema.$data,
  13674. $schemaValue;
  13675. if ($isData) {
  13676. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  13677. $schemaValue = 'schema' + $lvl;
  13678. } else {
  13679. $schemaValue = $schema;
  13680. }
  13681. var $unknownFormats = it.opts.unknownFormats,
  13682. $allowUnknown = Array.isArray($unknownFormats);
  13683. if ($isData) {
  13684. var $format = 'format' + $lvl,
  13685. $isObject = 'isObject' + $lvl,
  13686. $formatType = 'formatType' + $lvl;
  13687. out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
  13688. if (it.async) {
  13689. out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
  13690. }
  13691. out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
  13692. if ($isData) {
  13693. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
  13694. }
  13695. out += ' (';
  13696. if ($unknownFormats != 'ignore') {
  13697. out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
  13698. if ($allowUnknown) {
  13699. out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
  13700. }
  13701. out += ') || ';
  13702. }
  13703. out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
  13704. if (it.async) {
  13705. out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
  13706. } else {
  13707. out += ' ' + ($format) + '(' + ($data) + ') ';
  13708. }
  13709. out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
  13710. } else {
  13711. var $format = it.formats[$schema];
  13712. if (!$format) {
  13713. if ($unknownFormats == 'ignore') {
  13714. it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
  13715. if ($breakOnError) {
  13716. out += ' if (true) { ';
  13717. }
  13718. return out;
  13719. } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
  13720. if ($breakOnError) {
  13721. out += ' if (true) { ';
  13722. }
  13723. return out;
  13724. } else {
  13725. throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
  13726. }
  13727. }
  13728. var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
  13729. var $formatType = $isObject && $format.type || 'string';
  13730. if ($isObject) {
  13731. var $async = $format.async === true;
  13732. $format = $format.validate;
  13733. }
  13734. if ($formatType != $ruleType) {
  13735. if ($breakOnError) {
  13736. out += ' if (true) { ';
  13737. }
  13738. return out;
  13739. }
  13740. if ($async) {
  13741. if (!it.async) throw new Error('async format in sync schema');
  13742. var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
  13743. out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
  13744. } else {
  13745. out += ' if (! ';
  13746. var $formatRef = 'formats' + it.util.getProperty($schema);
  13747. if ($isObject) $formatRef += '.validate';
  13748. if (typeof $format == 'function') {
  13749. out += ' ' + ($formatRef) + '(' + ($data) + ') ';
  13750. } else {
  13751. out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
  13752. }
  13753. out += ') { ';
  13754. }
  13755. }
  13756. var $$outStack = $$outStack || [];
  13757. $$outStack.push(out);
  13758. out = ''; /* istanbul ignore else */
  13759. if (it.createErrors !== false) {
  13760. out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
  13761. if ($isData) {
  13762. out += '' + ($schemaValue);
  13763. } else {
  13764. out += '' + (it.util.toQuotedString($schema));
  13765. }
  13766. out += ' } ';
  13767. if (it.opts.messages !== false) {
  13768. out += ' , message: \'should match format "';
  13769. if ($isData) {
  13770. out += '\' + ' + ($schemaValue) + ' + \'';
  13771. } else {
  13772. out += '' + (it.util.escapeQuotes($schema));
  13773. }
  13774. out += '"\' ';
  13775. }
  13776. if (it.opts.verbose) {
  13777. out += ' , schema: ';
  13778. if ($isData) {
  13779. out += 'validate.schema' + ($schemaPath);
  13780. } else {
  13781. out += '' + (it.util.toQuotedString($schema));
  13782. }
  13783. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13784. }
  13785. out += ' } ';
  13786. } else {
  13787. out += ' {} ';
  13788. }
  13789. var __err = out;
  13790. out = $$outStack.pop();
  13791. if (!it.compositeRule && $breakOnError) {
  13792. /* istanbul ignore if */
  13793. if (it.async) {
  13794. out += ' throw new ValidationError([' + (__err) + ']); ';
  13795. } else {
  13796. out += ' validate.errors = [' + (__err) + ']; return false; ';
  13797. }
  13798. } else {
  13799. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13800. }
  13801. out += ' } ';
  13802. if ($breakOnError) {
  13803. out += ' else { ';
  13804. }
  13805. return out;
  13806. }
  13807. },{}],65:[function(require,module,exports){
  13808. 'use strict';
  13809. module.exports = function generate_if(it, $keyword, $ruleType) {
  13810. var out = ' ';
  13811. var $lvl = it.level;
  13812. var $dataLvl = it.dataLevel;
  13813. var $schema = it.schema[$keyword];
  13814. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13815. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13816. var $breakOnError = !it.opts.allErrors;
  13817. var $data = 'data' + ($dataLvl || '');
  13818. var $valid = 'valid' + $lvl;
  13819. var $errs = 'errs__' + $lvl;
  13820. var $it = it.util.copy(it);
  13821. $it.level++;
  13822. var $nextValid = 'valid' + $it.level;
  13823. var $thenSch = it.schema['then'],
  13824. $elseSch = it.schema['else'],
  13825. $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)),
  13826. $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)),
  13827. $currentBaseId = $it.baseId;
  13828. if ($thenPresent || $elsePresent) {
  13829. var $ifClause;
  13830. $it.createErrors = false;
  13831. $it.schema = $schema;
  13832. $it.schemaPath = $schemaPath;
  13833. $it.errSchemaPath = $errSchemaPath;
  13834. out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; ';
  13835. var $wasComposite = it.compositeRule;
  13836. it.compositeRule = $it.compositeRule = true;
  13837. out += ' ' + (it.validate($it)) + ' ';
  13838. $it.baseId = $currentBaseId;
  13839. $it.createErrors = true;
  13840. out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  13841. it.compositeRule = $it.compositeRule = $wasComposite;
  13842. if ($thenPresent) {
  13843. out += ' if (' + ($nextValid) + ') { ';
  13844. $it.schema = it.schema['then'];
  13845. $it.schemaPath = it.schemaPath + '.then';
  13846. $it.errSchemaPath = it.errSchemaPath + '/then';
  13847. out += ' ' + (it.validate($it)) + ' ';
  13848. $it.baseId = $currentBaseId;
  13849. out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
  13850. if ($thenPresent && $elsePresent) {
  13851. $ifClause = 'ifClause' + $lvl;
  13852. out += ' var ' + ($ifClause) + ' = \'then\'; ';
  13853. } else {
  13854. $ifClause = '\'then\'';
  13855. }
  13856. out += ' } ';
  13857. if ($elsePresent) {
  13858. out += ' else { ';
  13859. }
  13860. } else {
  13861. out += ' if (!' + ($nextValid) + ') { ';
  13862. }
  13863. if ($elsePresent) {
  13864. $it.schema = it.schema['else'];
  13865. $it.schemaPath = it.schemaPath + '.else';
  13866. $it.errSchemaPath = it.errSchemaPath + '/else';
  13867. out += ' ' + (it.validate($it)) + ' ';
  13868. $it.baseId = $currentBaseId;
  13869. out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
  13870. if ($thenPresent && $elsePresent) {
  13871. $ifClause = 'ifClause' + $lvl;
  13872. out += ' var ' + ($ifClause) + ' = \'else\'; ';
  13873. } else {
  13874. $ifClause = '\'else\'';
  13875. }
  13876. out += ' } ';
  13877. }
  13878. out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
  13879. if (it.createErrors !== false) {
  13880. out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
  13881. if (it.opts.messages !== false) {
  13882. out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
  13883. }
  13884. if (it.opts.verbose) {
  13885. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13886. }
  13887. out += ' } ';
  13888. } else {
  13889. out += ' {} ';
  13890. }
  13891. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13892. if (!it.compositeRule && $breakOnError) {
  13893. /* istanbul ignore if */
  13894. if (it.async) {
  13895. out += ' throw new ValidationError(vErrors); ';
  13896. } else {
  13897. out += ' validate.errors = vErrors; return false; ';
  13898. }
  13899. }
  13900. out += ' } ';
  13901. if ($breakOnError) {
  13902. out += ' else { ';
  13903. }
  13904. } else {
  13905. if ($breakOnError) {
  13906. out += ' if (true) { ';
  13907. }
  13908. }
  13909. return out;
  13910. }
  13911. },{}],66:[function(require,module,exports){
  13912. 'use strict';
  13913. //all requires must be explicit because browserify won't work with dynamic requires
  13914. module.exports = {
  13915. '$ref': require('./ref'),
  13916. allOf: require('./allOf'),
  13917. anyOf: require('./anyOf'),
  13918. '$comment': require('./comment'),
  13919. const: require('./const'),
  13920. contains: require('./contains'),
  13921. dependencies: require('./dependencies'),
  13922. 'enum': require('./enum'),
  13923. format: require('./format'),
  13924. 'if': require('./if'),
  13925. items: require('./items'),
  13926. maximum: require('./_limit'),
  13927. minimum: require('./_limit'),
  13928. maxItems: require('./_limitItems'),
  13929. minItems: require('./_limitItems'),
  13930. maxLength: require('./_limitLength'),
  13931. minLength: require('./_limitLength'),
  13932. maxProperties: require('./_limitProperties'),
  13933. minProperties: require('./_limitProperties'),
  13934. multipleOf: require('./multipleOf'),
  13935. not: require('./not'),
  13936. oneOf: require('./oneOf'),
  13937. pattern: require('./pattern'),
  13938. properties: require('./properties'),
  13939. propertyNames: require('./propertyNames'),
  13940. required: require('./required'),
  13941. uniqueItems: require('./uniqueItems'),
  13942. validate: require('./validate')
  13943. };
  13944. },{"./_limit":52,"./_limitItems":53,"./_limitLength":54,"./_limitProperties":55,"./allOf":56,"./anyOf":57,"./comment":58,"./const":59,"./contains":60,"./dependencies":62,"./enum":63,"./format":64,"./if":65,"./items":67,"./multipleOf":68,"./not":69,"./oneOf":70,"./pattern":71,"./properties":72,"./propertyNames":73,"./ref":74,"./required":75,"./uniqueItems":76,"./validate":77}],67:[function(require,module,exports){
  13945. 'use strict';
  13946. module.exports = function generate_items(it, $keyword, $ruleType) {
  13947. var out = ' ';
  13948. var $lvl = it.level;
  13949. var $dataLvl = it.dataLevel;
  13950. var $schema = it.schema[$keyword];
  13951. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  13952. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  13953. var $breakOnError = !it.opts.allErrors;
  13954. var $data = 'data' + ($dataLvl || '');
  13955. var $valid = 'valid' + $lvl;
  13956. var $errs = 'errs__' + $lvl;
  13957. var $it = it.util.copy(it);
  13958. var $closingBraces = '';
  13959. $it.level++;
  13960. var $nextValid = 'valid' + $it.level;
  13961. var $idx = 'i' + $lvl,
  13962. $dataNxt = $it.dataLevel = it.dataLevel + 1,
  13963. $nextData = 'data' + $dataNxt,
  13964. $currentBaseId = it.baseId;
  13965. out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  13966. if (Array.isArray($schema)) {
  13967. var $additionalItems = it.schema.additionalItems;
  13968. if ($additionalItems === false) {
  13969. out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
  13970. var $currErrSchemaPath = $errSchemaPath;
  13971. $errSchemaPath = it.errSchemaPath + '/additionalItems';
  13972. out += ' if (!' + ($valid) + ') { ';
  13973. var $$outStack = $$outStack || [];
  13974. $$outStack.push(out);
  13975. out = ''; /* istanbul ignore else */
  13976. if (it.createErrors !== false) {
  13977. out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
  13978. if (it.opts.messages !== false) {
  13979. out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
  13980. }
  13981. if (it.opts.verbose) {
  13982. out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  13983. }
  13984. out += ' } ';
  13985. } else {
  13986. out += ' {} ';
  13987. }
  13988. var __err = out;
  13989. out = $$outStack.pop();
  13990. if (!it.compositeRule && $breakOnError) {
  13991. /* istanbul ignore if */
  13992. if (it.async) {
  13993. out += ' throw new ValidationError([' + (__err) + ']); ';
  13994. } else {
  13995. out += ' validate.errors = [' + (__err) + ']; return false; ';
  13996. }
  13997. } else {
  13998. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  13999. }
  14000. out += ' } ';
  14001. $errSchemaPath = $currErrSchemaPath;
  14002. if ($breakOnError) {
  14003. $closingBraces += '}';
  14004. out += ' else { ';
  14005. }
  14006. }
  14007. var arr1 = $schema;
  14008. if (arr1) {
  14009. var $sch, $i = -1,
  14010. l1 = arr1.length - 1;
  14011. while ($i < l1) {
  14012. $sch = arr1[$i += 1];
  14013. if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
  14014. out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
  14015. var $passData = $data + '[' + $i + ']';
  14016. $it.schema = $sch;
  14017. $it.schemaPath = $schemaPath + '[' + $i + ']';
  14018. $it.errSchemaPath = $errSchemaPath + '/' + $i;
  14019. $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
  14020. $it.dataPathArr[$dataNxt] = $i;
  14021. var $code = it.validate($it);
  14022. $it.baseId = $currentBaseId;
  14023. if (it.util.varOccurences($code, $nextData) < 2) {
  14024. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  14025. } else {
  14026. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  14027. }
  14028. out += ' } ';
  14029. if ($breakOnError) {
  14030. out += ' if (' + ($nextValid) + ') { ';
  14031. $closingBraces += '}';
  14032. }
  14033. }
  14034. }
  14035. }
  14036. if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
  14037. $it.schema = $additionalItems;
  14038. $it.schemaPath = it.schemaPath + '.additionalItems';
  14039. $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
  14040. out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
  14041. $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
  14042. var $passData = $data + '[' + $idx + ']';
  14043. $it.dataPathArr[$dataNxt] = $idx;
  14044. var $code = it.validate($it);
  14045. $it.baseId = $currentBaseId;
  14046. if (it.util.varOccurences($code, $nextData) < 2) {
  14047. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  14048. } else {
  14049. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  14050. }
  14051. if ($breakOnError) {
  14052. out += ' if (!' + ($nextValid) + ') break; ';
  14053. }
  14054. out += ' } } ';
  14055. if ($breakOnError) {
  14056. out += ' if (' + ($nextValid) + ') { ';
  14057. $closingBraces += '}';
  14058. }
  14059. }
  14060. } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
  14061. $it.schema = $schema;
  14062. $it.schemaPath = $schemaPath;
  14063. $it.errSchemaPath = $errSchemaPath;
  14064. out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
  14065. $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
  14066. var $passData = $data + '[' + $idx + ']';
  14067. $it.dataPathArr[$dataNxt] = $idx;
  14068. var $code = it.validate($it);
  14069. $it.baseId = $currentBaseId;
  14070. if (it.util.varOccurences($code, $nextData) < 2) {
  14071. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  14072. } else {
  14073. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  14074. }
  14075. if ($breakOnError) {
  14076. out += ' if (!' + ($nextValid) + ') break; ';
  14077. }
  14078. out += ' }';
  14079. }
  14080. if ($breakOnError) {
  14081. out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  14082. }
  14083. return out;
  14084. }
  14085. },{}],68:[function(require,module,exports){
  14086. 'use strict';
  14087. module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
  14088. var out = ' ';
  14089. var $lvl = it.level;
  14090. var $dataLvl = it.dataLevel;
  14091. var $schema = it.schema[$keyword];
  14092. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  14093. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14094. var $breakOnError = !it.opts.allErrors;
  14095. var $data = 'data' + ($dataLvl || '');
  14096. var $isData = it.opts.$data && $schema && $schema.$data,
  14097. $schemaValue;
  14098. if ($isData) {
  14099. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  14100. $schemaValue = 'schema' + $lvl;
  14101. } else {
  14102. $schemaValue = $schema;
  14103. }
  14104. if (!($isData || typeof $schema == 'number')) {
  14105. throw new Error($keyword + ' must be number');
  14106. }
  14107. out += 'var division' + ($lvl) + ';if (';
  14108. if ($isData) {
  14109. out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
  14110. }
  14111. out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
  14112. if (it.opts.multipleOfPrecision) {
  14113. out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
  14114. } else {
  14115. out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
  14116. }
  14117. out += ' ) ';
  14118. if ($isData) {
  14119. out += ' ) ';
  14120. }
  14121. out += ' ) { ';
  14122. var $$outStack = $$outStack || [];
  14123. $$outStack.push(out);
  14124. out = ''; /* istanbul ignore else */
  14125. if (it.createErrors !== false) {
  14126. out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
  14127. if (it.opts.messages !== false) {
  14128. out += ' , message: \'should be multiple of ';
  14129. if ($isData) {
  14130. out += '\' + ' + ($schemaValue);
  14131. } else {
  14132. out += '' + ($schemaValue) + '\'';
  14133. }
  14134. }
  14135. if (it.opts.verbose) {
  14136. out += ' , schema: ';
  14137. if ($isData) {
  14138. out += 'validate.schema' + ($schemaPath);
  14139. } else {
  14140. out += '' + ($schema);
  14141. }
  14142. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14143. }
  14144. out += ' } ';
  14145. } else {
  14146. out += ' {} ';
  14147. }
  14148. var __err = out;
  14149. out = $$outStack.pop();
  14150. if (!it.compositeRule && $breakOnError) {
  14151. /* istanbul ignore if */
  14152. if (it.async) {
  14153. out += ' throw new ValidationError([' + (__err) + ']); ';
  14154. } else {
  14155. out += ' validate.errors = [' + (__err) + ']; return false; ';
  14156. }
  14157. } else {
  14158. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14159. }
  14160. out += '} ';
  14161. if ($breakOnError) {
  14162. out += ' else { ';
  14163. }
  14164. return out;
  14165. }
  14166. },{}],69:[function(require,module,exports){
  14167. 'use strict';
  14168. module.exports = function generate_not(it, $keyword, $ruleType) {
  14169. var out = ' ';
  14170. var $lvl = it.level;
  14171. var $dataLvl = it.dataLevel;
  14172. var $schema = it.schema[$keyword];
  14173. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  14174. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14175. var $breakOnError = !it.opts.allErrors;
  14176. var $data = 'data' + ($dataLvl || '');
  14177. var $errs = 'errs__' + $lvl;
  14178. var $it = it.util.copy(it);
  14179. $it.level++;
  14180. var $nextValid = 'valid' + $it.level;
  14181. if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
  14182. $it.schema = $schema;
  14183. $it.schemaPath = $schemaPath;
  14184. $it.errSchemaPath = $errSchemaPath;
  14185. out += ' var ' + ($errs) + ' = errors; ';
  14186. var $wasComposite = it.compositeRule;
  14187. it.compositeRule = $it.compositeRule = true;
  14188. $it.createErrors = false;
  14189. var $allErrorsOption;
  14190. if ($it.opts.allErrors) {
  14191. $allErrorsOption = $it.opts.allErrors;
  14192. $it.opts.allErrors = false;
  14193. }
  14194. out += ' ' + (it.validate($it)) + ' ';
  14195. $it.createErrors = true;
  14196. if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
  14197. it.compositeRule = $it.compositeRule = $wasComposite;
  14198. out += ' if (' + ($nextValid) + ') { ';
  14199. var $$outStack = $$outStack || [];
  14200. $$outStack.push(out);
  14201. out = ''; /* istanbul ignore else */
  14202. if (it.createErrors !== false) {
  14203. out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
  14204. if (it.opts.messages !== false) {
  14205. out += ' , message: \'should NOT be valid\' ';
  14206. }
  14207. if (it.opts.verbose) {
  14208. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14209. }
  14210. out += ' } ';
  14211. } else {
  14212. out += ' {} ';
  14213. }
  14214. var __err = out;
  14215. out = $$outStack.pop();
  14216. if (!it.compositeRule && $breakOnError) {
  14217. /* istanbul ignore if */
  14218. if (it.async) {
  14219. out += ' throw new ValidationError([' + (__err) + ']); ';
  14220. } else {
  14221. out += ' validate.errors = [' + (__err) + ']; return false; ';
  14222. }
  14223. } else {
  14224. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14225. }
  14226. out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  14227. if (it.opts.allErrors) {
  14228. out += ' } ';
  14229. }
  14230. } else {
  14231. out += ' var err = '; /* istanbul ignore else */
  14232. if (it.createErrors !== false) {
  14233. out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
  14234. if (it.opts.messages !== false) {
  14235. out += ' , message: \'should NOT be valid\' ';
  14236. }
  14237. if (it.opts.verbose) {
  14238. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14239. }
  14240. out += ' } ';
  14241. } else {
  14242. out += ' {} ';
  14243. }
  14244. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14245. if ($breakOnError) {
  14246. out += ' if (false) { ';
  14247. }
  14248. }
  14249. return out;
  14250. }
  14251. },{}],70:[function(require,module,exports){
  14252. 'use strict';
  14253. module.exports = function generate_oneOf(it, $keyword, $ruleType) {
  14254. var out = ' ';
  14255. var $lvl = it.level;
  14256. var $dataLvl = it.dataLevel;
  14257. var $schema = it.schema[$keyword];
  14258. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  14259. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14260. var $breakOnError = !it.opts.allErrors;
  14261. var $data = 'data' + ($dataLvl || '');
  14262. var $valid = 'valid' + $lvl;
  14263. var $errs = 'errs__' + $lvl;
  14264. var $it = it.util.copy(it);
  14265. var $closingBraces = '';
  14266. $it.level++;
  14267. var $nextValid = 'valid' + $it.level;
  14268. var $currentBaseId = $it.baseId,
  14269. $prevValid = 'prevValid' + $lvl,
  14270. $passingSchemas = 'passingSchemas' + $lvl;
  14271. out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
  14272. var $wasComposite = it.compositeRule;
  14273. it.compositeRule = $it.compositeRule = true;
  14274. var arr1 = $schema;
  14275. if (arr1) {
  14276. var $sch, $i = -1,
  14277. l1 = arr1.length - 1;
  14278. while ($i < l1) {
  14279. $sch = arr1[$i += 1];
  14280. if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
  14281. $it.schema = $sch;
  14282. $it.schemaPath = $schemaPath + '[' + $i + ']';
  14283. $it.errSchemaPath = $errSchemaPath + '/' + $i;
  14284. out += ' ' + (it.validate($it)) + ' ';
  14285. $it.baseId = $currentBaseId;
  14286. } else {
  14287. out += ' var ' + ($nextValid) + ' = true; ';
  14288. }
  14289. if ($i) {
  14290. out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
  14291. $closingBraces += '}';
  14292. }
  14293. out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
  14294. }
  14295. }
  14296. it.compositeRule = $it.compositeRule = $wasComposite;
  14297. out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
  14298. if (it.createErrors !== false) {
  14299. out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
  14300. if (it.opts.messages !== false) {
  14301. out += ' , message: \'should match exactly one schema in oneOf\' ';
  14302. }
  14303. if (it.opts.verbose) {
  14304. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14305. }
  14306. out += ' } ';
  14307. } else {
  14308. out += ' {} ';
  14309. }
  14310. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14311. if (!it.compositeRule && $breakOnError) {
  14312. /* istanbul ignore if */
  14313. if (it.async) {
  14314. out += ' throw new ValidationError(vErrors); ';
  14315. } else {
  14316. out += ' validate.errors = vErrors; return false; ';
  14317. }
  14318. }
  14319. out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
  14320. if (it.opts.allErrors) {
  14321. out += ' } ';
  14322. }
  14323. return out;
  14324. }
  14325. },{}],71:[function(require,module,exports){
  14326. 'use strict';
  14327. module.exports = function generate_pattern(it, $keyword, $ruleType) {
  14328. var out = ' ';
  14329. var $lvl = it.level;
  14330. var $dataLvl = it.dataLevel;
  14331. var $schema = it.schema[$keyword];
  14332. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  14333. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14334. var $breakOnError = !it.opts.allErrors;
  14335. var $data = 'data' + ($dataLvl || '');
  14336. var $isData = it.opts.$data && $schema && $schema.$data,
  14337. $schemaValue;
  14338. if ($isData) {
  14339. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  14340. $schemaValue = 'schema' + $lvl;
  14341. } else {
  14342. $schemaValue = $schema;
  14343. }
  14344. var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
  14345. out += 'if ( ';
  14346. if ($isData) {
  14347. out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
  14348. }
  14349. out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { ';
  14350. var $$outStack = $$outStack || [];
  14351. $$outStack.push(out);
  14352. out = ''; /* istanbul ignore else */
  14353. if (it.createErrors !== false) {
  14354. out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';
  14355. if ($isData) {
  14356. out += '' + ($schemaValue);
  14357. } else {
  14358. out += '' + (it.util.toQuotedString($schema));
  14359. }
  14360. out += ' } ';
  14361. if (it.opts.messages !== false) {
  14362. out += ' , message: \'should match pattern "';
  14363. if ($isData) {
  14364. out += '\' + ' + ($schemaValue) + ' + \'';
  14365. } else {
  14366. out += '' + (it.util.escapeQuotes($schema));
  14367. }
  14368. out += '"\' ';
  14369. }
  14370. if (it.opts.verbose) {
  14371. out += ' , schema: ';
  14372. if ($isData) {
  14373. out += 'validate.schema' + ($schemaPath);
  14374. } else {
  14375. out += '' + (it.util.toQuotedString($schema));
  14376. }
  14377. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14378. }
  14379. out += ' } ';
  14380. } else {
  14381. out += ' {} ';
  14382. }
  14383. var __err = out;
  14384. out = $$outStack.pop();
  14385. if (!it.compositeRule && $breakOnError) {
  14386. /* istanbul ignore if */
  14387. if (it.async) {
  14388. out += ' throw new ValidationError([' + (__err) + ']); ';
  14389. } else {
  14390. out += ' validate.errors = [' + (__err) + ']; return false; ';
  14391. }
  14392. } else {
  14393. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14394. }
  14395. out += '} ';
  14396. if ($breakOnError) {
  14397. out += ' else { ';
  14398. }
  14399. return out;
  14400. }
  14401. },{}],72:[function(require,module,exports){
  14402. 'use strict';
  14403. module.exports = function generate_properties(it, $keyword, $ruleType) {
  14404. var out = ' ';
  14405. var $lvl = it.level;
  14406. var $dataLvl = it.dataLevel;
  14407. var $schema = it.schema[$keyword];
  14408. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  14409. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14410. var $breakOnError = !it.opts.allErrors;
  14411. var $data = 'data' + ($dataLvl || '');
  14412. var $errs = 'errs__' + $lvl;
  14413. var $it = it.util.copy(it);
  14414. var $closingBraces = '';
  14415. $it.level++;
  14416. var $nextValid = 'valid' + $it.level;
  14417. var $key = 'key' + $lvl,
  14418. $idx = 'idx' + $lvl,
  14419. $dataNxt = $it.dataLevel = it.dataLevel + 1,
  14420. $nextData = 'data' + $dataNxt,
  14421. $dataProperties = 'dataProperties' + $lvl;
  14422. var $schemaKeys = Object.keys($schema || {}).filter(notProto),
  14423. $pProperties = it.schema.patternProperties || {},
  14424. $pPropertyKeys = Object.keys($pProperties).filter(notProto),
  14425. $aProperties = it.schema.additionalProperties,
  14426. $someProperties = $schemaKeys.length || $pPropertyKeys.length,
  14427. $noAdditional = $aProperties === false,
  14428. $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
  14429. $removeAdditional = it.opts.removeAdditional,
  14430. $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
  14431. $ownProperties = it.opts.ownProperties,
  14432. $currentBaseId = it.baseId;
  14433. var $required = it.schema.required;
  14434. if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
  14435. var $requiredHash = it.util.toHash($required);
  14436. }
  14437. function notProto(p) {
  14438. return p !== '__proto__';
  14439. }
  14440. out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
  14441. if ($ownProperties) {
  14442. out += ' var ' + ($dataProperties) + ' = undefined;';
  14443. }
  14444. if ($checkAdditional) {
  14445. if ($ownProperties) {
  14446. out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
  14447. } else {
  14448. out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
  14449. }
  14450. if ($someProperties) {
  14451. out += ' var isAdditional' + ($lvl) + ' = !(false ';
  14452. if ($schemaKeys.length) {
  14453. if ($schemaKeys.length > 8) {
  14454. out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
  14455. } else {
  14456. var arr1 = $schemaKeys;
  14457. if (arr1) {
  14458. var $propertyKey, i1 = -1,
  14459. l1 = arr1.length - 1;
  14460. while (i1 < l1) {
  14461. $propertyKey = arr1[i1 += 1];
  14462. out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
  14463. }
  14464. }
  14465. }
  14466. }
  14467. if ($pPropertyKeys.length) {
  14468. var arr2 = $pPropertyKeys;
  14469. if (arr2) {
  14470. var $pProperty, $i = -1,
  14471. l2 = arr2.length - 1;
  14472. while ($i < l2) {
  14473. $pProperty = arr2[$i += 1];
  14474. out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
  14475. }
  14476. }
  14477. }
  14478. out += ' ); if (isAdditional' + ($lvl) + ') { ';
  14479. }
  14480. if ($removeAdditional == 'all') {
  14481. out += ' delete ' + ($data) + '[' + ($key) + ']; ';
  14482. } else {
  14483. var $currentErrorPath = it.errorPath;
  14484. var $additionalProperty = '\' + ' + $key + ' + \'';
  14485. if (it.opts._errorDataPathProperty) {
  14486. it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
  14487. }
  14488. if ($noAdditional) {
  14489. if ($removeAdditional) {
  14490. out += ' delete ' + ($data) + '[' + ($key) + ']; ';
  14491. } else {
  14492. out += ' ' + ($nextValid) + ' = false; ';
  14493. var $currErrSchemaPath = $errSchemaPath;
  14494. $errSchemaPath = it.errSchemaPath + '/additionalProperties';
  14495. var $$outStack = $$outStack || [];
  14496. $$outStack.push(out);
  14497. out = ''; /* istanbul ignore else */
  14498. if (it.createErrors !== false) {
  14499. out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
  14500. if (it.opts.messages !== false) {
  14501. out += ' , message: \'';
  14502. if (it.opts._errorDataPathProperty) {
  14503. out += 'is an invalid additional property';
  14504. } else {
  14505. out += 'should NOT have additional properties';
  14506. }
  14507. out += '\' ';
  14508. }
  14509. if (it.opts.verbose) {
  14510. out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14511. }
  14512. out += ' } ';
  14513. } else {
  14514. out += ' {} ';
  14515. }
  14516. var __err = out;
  14517. out = $$outStack.pop();
  14518. if (!it.compositeRule && $breakOnError) {
  14519. /* istanbul ignore if */
  14520. if (it.async) {
  14521. out += ' throw new ValidationError([' + (__err) + ']); ';
  14522. } else {
  14523. out += ' validate.errors = [' + (__err) + ']; return false; ';
  14524. }
  14525. } else {
  14526. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14527. }
  14528. $errSchemaPath = $currErrSchemaPath;
  14529. if ($breakOnError) {
  14530. out += ' break; ';
  14531. }
  14532. }
  14533. } else if ($additionalIsSchema) {
  14534. if ($removeAdditional == 'failing') {
  14535. out += ' var ' + ($errs) + ' = errors; ';
  14536. var $wasComposite = it.compositeRule;
  14537. it.compositeRule = $it.compositeRule = true;
  14538. $it.schema = $aProperties;
  14539. $it.schemaPath = it.schemaPath + '.additionalProperties';
  14540. $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
  14541. $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
  14542. var $passData = $data + '[' + $key + ']';
  14543. $it.dataPathArr[$dataNxt] = $key;
  14544. var $code = it.validate($it);
  14545. $it.baseId = $currentBaseId;
  14546. if (it.util.varOccurences($code, $nextData) < 2) {
  14547. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  14548. } else {
  14549. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  14550. }
  14551. out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } ';
  14552. it.compositeRule = $it.compositeRule = $wasComposite;
  14553. } else {
  14554. $it.schema = $aProperties;
  14555. $it.schemaPath = it.schemaPath + '.additionalProperties';
  14556. $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
  14557. $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
  14558. var $passData = $data + '[' + $key + ']';
  14559. $it.dataPathArr[$dataNxt] = $key;
  14560. var $code = it.validate($it);
  14561. $it.baseId = $currentBaseId;
  14562. if (it.util.varOccurences($code, $nextData) < 2) {
  14563. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  14564. } else {
  14565. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  14566. }
  14567. if ($breakOnError) {
  14568. out += ' if (!' + ($nextValid) + ') break; ';
  14569. }
  14570. }
  14571. }
  14572. it.errorPath = $currentErrorPath;
  14573. }
  14574. if ($someProperties) {
  14575. out += ' } ';
  14576. }
  14577. out += ' } ';
  14578. if ($breakOnError) {
  14579. out += ' if (' + ($nextValid) + ') { ';
  14580. $closingBraces += '}';
  14581. }
  14582. }
  14583. var $useDefaults = it.opts.useDefaults && !it.compositeRule;
  14584. if ($schemaKeys.length) {
  14585. var arr3 = $schemaKeys;
  14586. if (arr3) {
  14587. var $propertyKey, i3 = -1,
  14588. l3 = arr3.length - 1;
  14589. while (i3 < l3) {
  14590. $propertyKey = arr3[i3 += 1];
  14591. var $sch = $schema[$propertyKey];
  14592. if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
  14593. var $prop = it.util.getProperty($propertyKey),
  14594. $passData = $data + $prop,
  14595. $hasDefault = $useDefaults && $sch.default !== undefined;
  14596. $it.schema = $sch;
  14597. $it.schemaPath = $schemaPath + $prop;
  14598. $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
  14599. $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
  14600. $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
  14601. var $code = it.validate($it);
  14602. $it.baseId = $currentBaseId;
  14603. if (it.util.varOccurences($code, $nextData) < 2) {
  14604. $code = it.util.varReplace($code, $nextData, $passData);
  14605. var $useData = $passData;
  14606. } else {
  14607. var $useData = $nextData;
  14608. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
  14609. }
  14610. if ($hasDefault) {
  14611. out += ' ' + ($code) + ' ';
  14612. } else {
  14613. if ($requiredHash && $requiredHash[$propertyKey]) {
  14614. out += ' if ( ' + ($useData) + ' === undefined ';
  14615. if ($ownProperties) {
  14616. out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
  14617. }
  14618. out += ') { ' + ($nextValid) + ' = false; ';
  14619. var $currentErrorPath = it.errorPath,
  14620. $currErrSchemaPath = $errSchemaPath,
  14621. $missingProperty = it.util.escapeQuotes($propertyKey);
  14622. if (it.opts._errorDataPathProperty) {
  14623. it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
  14624. }
  14625. $errSchemaPath = it.errSchemaPath + '/required';
  14626. var $$outStack = $$outStack || [];
  14627. $$outStack.push(out);
  14628. out = ''; /* istanbul ignore else */
  14629. if (it.createErrors !== false) {
  14630. out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
  14631. if (it.opts.messages !== false) {
  14632. out += ' , message: \'';
  14633. if (it.opts._errorDataPathProperty) {
  14634. out += 'is a required property';
  14635. } else {
  14636. out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
  14637. }
  14638. out += '\' ';
  14639. }
  14640. if (it.opts.verbose) {
  14641. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14642. }
  14643. out += ' } ';
  14644. } else {
  14645. out += ' {} ';
  14646. }
  14647. var __err = out;
  14648. out = $$outStack.pop();
  14649. if (!it.compositeRule && $breakOnError) {
  14650. /* istanbul ignore if */
  14651. if (it.async) {
  14652. out += ' throw new ValidationError([' + (__err) + ']); ';
  14653. } else {
  14654. out += ' validate.errors = [' + (__err) + ']; return false; ';
  14655. }
  14656. } else {
  14657. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14658. }
  14659. $errSchemaPath = $currErrSchemaPath;
  14660. it.errorPath = $currentErrorPath;
  14661. out += ' } else { ';
  14662. } else {
  14663. if ($breakOnError) {
  14664. out += ' if ( ' + ($useData) + ' === undefined ';
  14665. if ($ownProperties) {
  14666. out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
  14667. }
  14668. out += ') { ' + ($nextValid) + ' = true; } else { ';
  14669. } else {
  14670. out += ' if (' + ($useData) + ' !== undefined ';
  14671. if ($ownProperties) {
  14672. out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
  14673. }
  14674. out += ' ) { ';
  14675. }
  14676. }
  14677. out += ' ' + ($code) + ' } ';
  14678. }
  14679. }
  14680. if ($breakOnError) {
  14681. out += ' if (' + ($nextValid) + ') { ';
  14682. $closingBraces += '}';
  14683. }
  14684. }
  14685. }
  14686. }
  14687. if ($pPropertyKeys.length) {
  14688. var arr4 = $pPropertyKeys;
  14689. if (arr4) {
  14690. var $pProperty, i4 = -1,
  14691. l4 = arr4.length - 1;
  14692. while (i4 < l4) {
  14693. $pProperty = arr4[i4 += 1];
  14694. var $sch = $pProperties[$pProperty];
  14695. if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
  14696. $it.schema = $sch;
  14697. $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
  14698. $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
  14699. if ($ownProperties) {
  14700. out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
  14701. } else {
  14702. out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
  14703. }
  14704. out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
  14705. $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
  14706. var $passData = $data + '[' + $key + ']';
  14707. $it.dataPathArr[$dataNxt] = $key;
  14708. var $code = it.validate($it);
  14709. $it.baseId = $currentBaseId;
  14710. if (it.util.varOccurences($code, $nextData) < 2) {
  14711. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  14712. } else {
  14713. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  14714. }
  14715. if ($breakOnError) {
  14716. out += ' if (!' + ($nextValid) + ') break; ';
  14717. }
  14718. out += ' } ';
  14719. if ($breakOnError) {
  14720. out += ' else ' + ($nextValid) + ' = true; ';
  14721. }
  14722. out += ' } ';
  14723. if ($breakOnError) {
  14724. out += ' if (' + ($nextValid) + ') { ';
  14725. $closingBraces += '}';
  14726. }
  14727. }
  14728. }
  14729. }
  14730. }
  14731. if ($breakOnError) {
  14732. out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  14733. }
  14734. return out;
  14735. }
  14736. },{}],73:[function(require,module,exports){
  14737. 'use strict';
  14738. module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
  14739. var out = ' ';
  14740. var $lvl = it.level;
  14741. var $dataLvl = it.dataLevel;
  14742. var $schema = it.schema[$keyword];
  14743. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  14744. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14745. var $breakOnError = !it.opts.allErrors;
  14746. var $data = 'data' + ($dataLvl || '');
  14747. var $errs = 'errs__' + $lvl;
  14748. var $it = it.util.copy(it);
  14749. var $closingBraces = '';
  14750. $it.level++;
  14751. var $nextValid = 'valid' + $it.level;
  14752. out += 'var ' + ($errs) + ' = errors;';
  14753. if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
  14754. $it.schema = $schema;
  14755. $it.schemaPath = $schemaPath;
  14756. $it.errSchemaPath = $errSchemaPath;
  14757. var $key = 'key' + $lvl,
  14758. $idx = 'idx' + $lvl,
  14759. $i = 'i' + $lvl,
  14760. $invalidName = '\' + ' + $key + ' + \'',
  14761. $dataNxt = $it.dataLevel = it.dataLevel + 1,
  14762. $nextData = 'data' + $dataNxt,
  14763. $dataProperties = 'dataProperties' + $lvl,
  14764. $ownProperties = it.opts.ownProperties,
  14765. $currentBaseId = it.baseId;
  14766. if ($ownProperties) {
  14767. out += ' var ' + ($dataProperties) + ' = undefined; ';
  14768. }
  14769. if ($ownProperties) {
  14770. out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
  14771. } else {
  14772. out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
  14773. }
  14774. out += ' var startErrs' + ($lvl) + ' = errors; ';
  14775. var $passData = $key;
  14776. var $wasComposite = it.compositeRule;
  14777. it.compositeRule = $it.compositeRule = true;
  14778. var $code = it.validate($it);
  14779. $it.baseId = $currentBaseId;
  14780. if (it.util.varOccurences($code, $nextData) < 2) {
  14781. out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
  14782. } else {
  14783. out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
  14784. }
  14785. it.compositeRule = $it.compositeRule = $wasComposite;
  14786. out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; } var err = '; /* istanbul ignore else */
  14787. if (it.createErrors !== false) {
  14788. out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
  14789. if (it.opts.messages !== false) {
  14790. out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
  14791. }
  14792. if (it.opts.verbose) {
  14793. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14794. }
  14795. out += ' } ';
  14796. } else {
  14797. out += ' {} ';
  14798. }
  14799. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14800. if (!it.compositeRule && $breakOnError) {
  14801. /* istanbul ignore if */
  14802. if (it.async) {
  14803. out += ' throw new ValidationError(vErrors); ';
  14804. } else {
  14805. out += ' validate.errors = vErrors; return false; ';
  14806. }
  14807. }
  14808. if ($breakOnError) {
  14809. out += ' break; ';
  14810. }
  14811. out += ' } }';
  14812. }
  14813. if ($breakOnError) {
  14814. out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  14815. }
  14816. return out;
  14817. }
  14818. },{}],74:[function(require,module,exports){
  14819. 'use strict';
  14820. module.exports = function generate_ref(it, $keyword, $ruleType) {
  14821. var out = ' ';
  14822. var $lvl = it.level;
  14823. var $dataLvl = it.dataLevel;
  14824. var $schema = it.schema[$keyword];
  14825. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14826. var $breakOnError = !it.opts.allErrors;
  14827. var $data = 'data' + ($dataLvl || '');
  14828. var $valid = 'valid' + $lvl;
  14829. var $async, $refCode;
  14830. if ($schema == '#' || $schema == '#/') {
  14831. if (it.isRoot) {
  14832. $async = it.async;
  14833. $refCode = 'validate';
  14834. } else {
  14835. $async = it.root.schema.$async === true;
  14836. $refCode = 'root.refVal[0]';
  14837. }
  14838. } else {
  14839. var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
  14840. if ($refVal === undefined) {
  14841. var $message = it.MissingRefError.message(it.baseId, $schema);
  14842. if (it.opts.missingRefs == 'fail') {
  14843. it.logger.error($message);
  14844. var $$outStack = $$outStack || [];
  14845. $$outStack.push(out);
  14846. out = ''; /* istanbul ignore else */
  14847. if (it.createErrors !== false) {
  14848. out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
  14849. if (it.opts.messages !== false) {
  14850. out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
  14851. }
  14852. if (it.opts.verbose) {
  14853. out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  14854. }
  14855. out += ' } ';
  14856. } else {
  14857. out += ' {} ';
  14858. }
  14859. var __err = out;
  14860. out = $$outStack.pop();
  14861. if (!it.compositeRule && $breakOnError) {
  14862. /* istanbul ignore if */
  14863. if (it.async) {
  14864. out += ' throw new ValidationError([' + (__err) + ']); ';
  14865. } else {
  14866. out += ' validate.errors = [' + (__err) + ']; return false; ';
  14867. }
  14868. } else {
  14869. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  14870. }
  14871. if ($breakOnError) {
  14872. out += ' if (false) { ';
  14873. }
  14874. } else if (it.opts.missingRefs == 'ignore') {
  14875. it.logger.warn($message);
  14876. if ($breakOnError) {
  14877. out += ' if (true) { ';
  14878. }
  14879. } else {
  14880. throw new it.MissingRefError(it.baseId, $schema, $message);
  14881. }
  14882. } else if ($refVal.inline) {
  14883. var $it = it.util.copy(it);
  14884. $it.level++;
  14885. var $nextValid = 'valid' + $it.level;
  14886. $it.schema = $refVal.schema;
  14887. $it.schemaPath = '';
  14888. $it.errSchemaPath = $schema;
  14889. var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
  14890. out += ' ' + ($code) + ' ';
  14891. if ($breakOnError) {
  14892. out += ' if (' + ($nextValid) + ') { ';
  14893. }
  14894. } else {
  14895. $async = $refVal.$async === true || (it.async && $refVal.$async !== false);
  14896. $refCode = $refVal.code;
  14897. }
  14898. }
  14899. if ($refCode) {
  14900. var $$outStack = $$outStack || [];
  14901. $$outStack.push(out);
  14902. out = '';
  14903. if (it.opts.passContext) {
  14904. out += ' ' + ($refCode) + '.call(this, ';
  14905. } else {
  14906. out += ' ' + ($refCode) + '( ';
  14907. }
  14908. out += ' ' + ($data) + ', (dataPath || \'\')';
  14909. if (it.errorPath != '""') {
  14910. out += ' + ' + (it.errorPath);
  14911. }
  14912. var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
  14913. $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
  14914. out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) ';
  14915. var __callValidate = out;
  14916. out = $$outStack.pop();
  14917. if ($async) {
  14918. if (!it.async) throw new Error('async schema referenced by sync schema');
  14919. if ($breakOnError) {
  14920. out += ' var ' + ($valid) + '; ';
  14921. }
  14922. out += ' try { await ' + (__callValidate) + '; ';
  14923. if ($breakOnError) {
  14924. out += ' ' + ($valid) + ' = true; ';
  14925. }
  14926. out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
  14927. if ($breakOnError) {
  14928. out += ' ' + ($valid) + ' = false; ';
  14929. }
  14930. out += ' } ';
  14931. if ($breakOnError) {
  14932. out += ' if (' + ($valid) + ') { ';
  14933. }
  14934. } else {
  14935. out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
  14936. if ($breakOnError) {
  14937. out += ' else { ';
  14938. }
  14939. }
  14940. }
  14941. return out;
  14942. }
  14943. },{}],75:[function(require,module,exports){
  14944. 'use strict';
  14945. module.exports = function generate_required(it, $keyword, $ruleType) {
  14946. var out = ' ';
  14947. var $lvl = it.level;
  14948. var $dataLvl = it.dataLevel;
  14949. var $schema = it.schema[$keyword];
  14950. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  14951. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  14952. var $breakOnError = !it.opts.allErrors;
  14953. var $data = 'data' + ($dataLvl || '');
  14954. var $valid = 'valid' + $lvl;
  14955. var $isData = it.opts.$data && $schema && $schema.$data,
  14956. $schemaValue;
  14957. if ($isData) {
  14958. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  14959. $schemaValue = 'schema' + $lvl;
  14960. } else {
  14961. $schemaValue = $schema;
  14962. }
  14963. var $vSchema = 'schema' + $lvl;
  14964. if (!$isData) {
  14965. if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
  14966. var $required = [];
  14967. var arr1 = $schema;
  14968. if (arr1) {
  14969. var $property, i1 = -1,
  14970. l1 = arr1.length - 1;
  14971. while (i1 < l1) {
  14972. $property = arr1[i1 += 1];
  14973. var $propertySch = it.schema.properties[$property];
  14974. if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
  14975. $required[$required.length] = $property;
  14976. }
  14977. }
  14978. }
  14979. } else {
  14980. var $required = $schema;
  14981. }
  14982. }
  14983. if ($isData || $required.length) {
  14984. var $currentErrorPath = it.errorPath,
  14985. $loopRequired = $isData || $required.length >= it.opts.loopRequired,
  14986. $ownProperties = it.opts.ownProperties;
  14987. if ($breakOnError) {
  14988. out += ' var missing' + ($lvl) + '; ';
  14989. if ($loopRequired) {
  14990. if (!$isData) {
  14991. out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
  14992. }
  14993. var $i = 'i' + $lvl,
  14994. $propertyPath = 'schema' + $lvl + '[' + $i + ']',
  14995. $missingProperty = '\' + ' + $propertyPath + ' + \'';
  14996. if (it.opts._errorDataPathProperty) {
  14997. it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
  14998. }
  14999. out += ' var ' + ($valid) + ' = true; ';
  15000. if ($isData) {
  15001. out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  15002. }
  15003. out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
  15004. if ($ownProperties) {
  15005. out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
  15006. }
  15007. out += '; if (!' + ($valid) + ') break; } ';
  15008. if ($isData) {
  15009. out += ' } ';
  15010. }
  15011. out += ' if (!' + ($valid) + ') { ';
  15012. var $$outStack = $$outStack || [];
  15013. $$outStack.push(out);
  15014. out = ''; /* istanbul ignore else */
  15015. if (it.createErrors !== false) {
  15016. out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
  15017. if (it.opts.messages !== false) {
  15018. out += ' , message: \'';
  15019. if (it.opts._errorDataPathProperty) {
  15020. out += 'is a required property';
  15021. } else {
  15022. out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
  15023. }
  15024. out += '\' ';
  15025. }
  15026. if (it.opts.verbose) {
  15027. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15028. }
  15029. out += ' } ';
  15030. } else {
  15031. out += ' {} ';
  15032. }
  15033. var __err = out;
  15034. out = $$outStack.pop();
  15035. if (!it.compositeRule && $breakOnError) {
  15036. /* istanbul ignore if */
  15037. if (it.async) {
  15038. out += ' throw new ValidationError([' + (__err) + ']); ';
  15039. } else {
  15040. out += ' validate.errors = [' + (__err) + ']; return false; ';
  15041. }
  15042. } else {
  15043. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  15044. }
  15045. out += ' } else { ';
  15046. } else {
  15047. out += ' if ( ';
  15048. var arr2 = $required;
  15049. if (arr2) {
  15050. var $propertyKey, $i = -1,
  15051. l2 = arr2.length - 1;
  15052. while ($i < l2) {
  15053. $propertyKey = arr2[$i += 1];
  15054. if ($i) {
  15055. out += ' || ';
  15056. }
  15057. var $prop = it.util.getProperty($propertyKey),
  15058. $useData = $data + $prop;
  15059. out += ' ( ( ' + ($useData) + ' === undefined ';
  15060. if ($ownProperties) {
  15061. out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
  15062. }
  15063. out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
  15064. }
  15065. }
  15066. out += ') { ';
  15067. var $propertyPath = 'missing' + $lvl,
  15068. $missingProperty = '\' + ' + $propertyPath + ' + \'';
  15069. if (it.opts._errorDataPathProperty) {
  15070. it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
  15071. }
  15072. var $$outStack = $$outStack || [];
  15073. $$outStack.push(out);
  15074. out = ''; /* istanbul ignore else */
  15075. if (it.createErrors !== false) {
  15076. out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
  15077. if (it.opts.messages !== false) {
  15078. out += ' , message: \'';
  15079. if (it.opts._errorDataPathProperty) {
  15080. out += 'is a required property';
  15081. } else {
  15082. out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
  15083. }
  15084. out += '\' ';
  15085. }
  15086. if (it.opts.verbose) {
  15087. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15088. }
  15089. out += ' } ';
  15090. } else {
  15091. out += ' {} ';
  15092. }
  15093. var __err = out;
  15094. out = $$outStack.pop();
  15095. if (!it.compositeRule && $breakOnError) {
  15096. /* istanbul ignore if */
  15097. if (it.async) {
  15098. out += ' throw new ValidationError([' + (__err) + ']); ';
  15099. } else {
  15100. out += ' validate.errors = [' + (__err) + ']; return false; ';
  15101. }
  15102. } else {
  15103. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  15104. }
  15105. out += ' } else { ';
  15106. }
  15107. } else {
  15108. if ($loopRequired) {
  15109. if (!$isData) {
  15110. out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
  15111. }
  15112. var $i = 'i' + $lvl,
  15113. $propertyPath = 'schema' + $lvl + '[' + $i + ']',
  15114. $missingProperty = '\' + ' + $propertyPath + ' + \'';
  15115. if (it.opts._errorDataPathProperty) {
  15116. it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
  15117. }
  15118. if ($isData) {
  15119. out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */
  15120. if (it.createErrors !== false) {
  15121. out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
  15122. if (it.opts.messages !== false) {
  15123. out += ' , message: \'';
  15124. if (it.opts._errorDataPathProperty) {
  15125. out += 'is a required property';
  15126. } else {
  15127. out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
  15128. }
  15129. out += '\' ';
  15130. }
  15131. if (it.opts.verbose) {
  15132. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15133. }
  15134. out += ' } ';
  15135. } else {
  15136. out += ' {} ';
  15137. }
  15138. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
  15139. }
  15140. out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
  15141. if ($ownProperties) {
  15142. out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
  15143. }
  15144. out += ') { var err = '; /* istanbul ignore else */
  15145. if (it.createErrors !== false) {
  15146. out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
  15147. if (it.opts.messages !== false) {
  15148. out += ' , message: \'';
  15149. if (it.opts._errorDataPathProperty) {
  15150. out += 'is a required property';
  15151. } else {
  15152. out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
  15153. }
  15154. out += '\' ';
  15155. }
  15156. if (it.opts.verbose) {
  15157. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15158. }
  15159. out += ' } ';
  15160. } else {
  15161. out += ' {} ';
  15162. }
  15163. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
  15164. if ($isData) {
  15165. out += ' } ';
  15166. }
  15167. } else {
  15168. var arr3 = $required;
  15169. if (arr3) {
  15170. var $propertyKey, i3 = -1,
  15171. l3 = arr3.length - 1;
  15172. while (i3 < l3) {
  15173. $propertyKey = arr3[i3 += 1];
  15174. var $prop = it.util.getProperty($propertyKey),
  15175. $missingProperty = it.util.escapeQuotes($propertyKey),
  15176. $useData = $data + $prop;
  15177. if (it.opts._errorDataPathProperty) {
  15178. it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
  15179. }
  15180. out += ' if ( ' + ($useData) + ' === undefined ';
  15181. if ($ownProperties) {
  15182. out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
  15183. }
  15184. out += ') { var err = '; /* istanbul ignore else */
  15185. if (it.createErrors !== false) {
  15186. out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
  15187. if (it.opts.messages !== false) {
  15188. out += ' , message: \'';
  15189. if (it.opts._errorDataPathProperty) {
  15190. out += 'is a required property';
  15191. } else {
  15192. out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
  15193. }
  15194. out += '\' ';
  15195. }
  15196. if (it.opts.verbose) {
  15197. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15198. }
  15199. out += ' } ';
  15200. } else {
  15201. out += ' {} ';
  15202. }
  15203. out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
  15204. }
  15205. }
  15206. }
  15207. }
  15208. it.errorPath = $currentErrorPath;
  15209. } else if ($breakOnError) {
  15210. out += ' if (true) {';
  15211. }
  15212. return out;
  15213. }
  15214. },{}],76:[function(require,module,exports){
  15215. 'use strict';
  15216. module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
  15217. var out = ' ';
  15218. var $lvl = it.level;
  15219. var $dataLvl = it.dataLevel;
  15220. var $schema = it.schema[$keyword];
  15221. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  15222. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  15223. var $breakOnError = !it.opts.allErrors;
  15224. var $data = 'data' + ($dataLvl || '');
  15225. var $valid = 'valid' + $lvl;
  15226. var $isData = it.opts.$data && $schema && $schema.$data,
  15227. $schemaValue;
  15228. if ($isData) {
  15229. out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
  15230. $schemaValue = 'schema' + $lvl;
  15231. } else {
  15232. $schemaValue = $schema;
  15233. }
  15234. if (($schema || $isData) && it.opts.uniqueItems !== false) {
  15235. if ($isData) {
  15236. out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
  15237. }
  15238. out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
  15239. var $itemType = it.schema.items && it.schema.items.type,
  15240. $typeIsArray = Array.isArray($itemType);
  15241. if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
  15242. out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
  15243. } else {
  15244. out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
  15245. var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
  15246. out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; ';
  15247. if ($typeIsArray) {
  15248. out += ' if (typeof item == \'string\') item = \'"\' + item; ';
  15249. }
  15250. out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
  15251. }
  15252. out += ' } ';
  15253. if ($isData) {
  15254. out += ' } ';
  15255. }
  15256. out += ' if (!' + ($valid) + ') { ';
  15257. var $$outStack = $$outStack || [];
  15258. $$outStack.push(out);
  15259. out = ''; /* istanbul ignore else */
  15260. if (it.createErrors !== false) {
  15261. out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
  15262. if (it.opts.messages !== false) {
  15263. out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
  15264. }
  15265. if (it.opts.verbose) {
  15266. out += ' , schema: ';
  15267. if ($isData) {
  15268. out += 'validate.schema' + ($schemaPath);
  15269. } else {
  15270. out += '' + ($schema);
  15271. }
  15272. out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15273. }
  15274. out += ' } ';
  15275. } else {
  15276. out += ' {} ';
  15277. }
  15278. var __err = out;
  15279. out = $$outStack.pop();
  15280. if (!it.compositeRule && $breakOnError) {
  15281. /* istanbul ignore if */
  15282. if (it.async) {
  15283. out += ' throw new ValidationError([' + (__err) + ']); ';
  15284. } else {
  15285. out += ' validate.errors = [' + (__err) + ']; return false; ';
  15286. }
  15287. } else {
  15288. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  15289. }
  15290. out += ' } ';
  15291. if ($breakOnError) {
  15292. out += ' else { ';
  15293. }
  15294. } else {
  15295. if ($breakOnError) {
  15296. out += ' if (true) { ';
  15297. }
  15298. }
  15299. return out;
  15300. }
  15301. },{}],77:[function(require,module,exports){
  15302. 'use strict';
  15303. module.exports = function generate_validate(it, $keyword, $ruleType) {
  15304. var out = '';
  15305. var $async = it.schema.$async === true,
  15306. $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
  15307. $id = it.self._getId(it.schema);
  15308. if (it.opts.strictKeywords) {
  15309. var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
  15310. if ($unknownKwd) {
  15311. var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
  15312. if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
  15313. else throw new Error($keywordsMsg);
  15314. }
  15315. }
  15316. if (it.isTop) {
  15317. out += ' var validate = ';
  15318. if ($async) {
  15319. it.async = true;
  15320. out += 'async ';
  15321. }
  15322. out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
  15323. if ($id && (it.opts.sourceCode || it.opts.processCode)) {
  15324. out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
  15325. }
  15326. }
  15327. if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
  15328. var $keyword = 'false schema';
  15329. var $lvl = it.level;
  15330. var $dataLvl = it.dataLevel;
  15331. var $schema = it.schema[$keyword];
  15332. var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  15333. var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  15334. var $breakOnError = !it.opts.allErrors;
  15335. var $errorKeyword;
  15336. var $data = 'data' + ($dataLvl || '');
  15337. var $valid = 'valid' + $lvl;
  15338. if (it.schema === false) {
  15339. if (it.isTop) {
  15340. $breakOnError = true;
  15341. } else {
  15342. out += ' var ' + ($valid) + ' = false; ';
  15343. }
  15344. var $$outStack = $$outStack || [];
  15345. $$outStack.push(out);
  15346. out = ''; /* istanbul ignore else */
  15347. if (it.createErrors !== false) {
  15348. out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
  15349. if (it.opts.messages !== false) {
  15350. out += ' , message: \'boolean schema is false\' ';
  15351. }
  15352. if (it.opts.verbose) {
  15353. out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15354. }
  15355. out += ' } ';
  15356. } else {
  15357. out += ' {} ';
  15358. }
  15359. var __err = out;
  15360. out = $$outStack.pop();
  15361. if (!it.compositeRule && $breakOnError) {
  15362. /* istanbul ignore if */
  15363. if (it.async) {
  15364. out += ' throw new ValidationError([' + (__err) + ']); ';
  15365. } else {
  15366. out += ' validate.errors = [' + (__err) + ']; return false; ';
  15367. }
  15368. } else {
  15369. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  15370. }
  15371. } else {
  15372. if (it.isTop) {
  15373. if ($async) {
  15374. out += ' return data; ';
  15375. } else {
  15376. out += ' validate.errors = null; return true; ';
  15377. }
  15378. } else {
  15379. out += ' var ' + ($valid) + ' = true; ';
  15380. }
  15381. }
  15382. if (it.isTop) {
  15383. out += ' }; return validate; ';
  15384. }
  15385. return out;
  15386. }
  15387. if (it.isTop) {
  15388. var $top = it.isTop,
  15389. $lvl = it.level = 0,
  15390. $dataLvl = it.dataLevel = 0,
  15391. $data = 'data';
  15392. it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
  15393. it.baseId = it.baseId || it.rootId;
  15394. delete it.isTop;
  15395. it.dataPathArr = [""];
  15396. if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
  15397. var $defaultMsg = 'default is ignored in the schema root';
  15398. if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
  15399. else throw new Error($defaultMsg);
  15400. }
  15401. out += ' var vErrors = null; ';
  15402. out += ' var errors = 0; ';
  15403. out += ' if (rootData === undefined) rootData = data; ';
  15404. } else {
  15405. var $lvl = it.level,
  15406. $dataLvl = it.dataLevel,
  15407. $data = 'data' + ($dataLvl || '');
  15408. if ($id) it.baseId = it.resolve.url(it.baseId, $id);
  15409. if ($async && !it.async) throw new Error('async schema in sync schema');
  15410. out += ' var errs_' + ($lvl) + ' = errors;';
  15411. }
  15412. var $valid = 'valid' + $lvl,
  15413. $breakOnError = !it.opts.allErrors,
  15414. $closingBraces1 = '',
  15415. $closingBraces2 = '';
  15416. var $errorKeyword;
  15417. var $typeSchema = it.schema.type,
  15418. $typeIsArray = Array.isArray($typeSchema);
  15419. if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
  15420. if ($typeIsArray) {
  15421. if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
  15422. } else if ($typeSchema != 'null') {
  15423. $typeSchema = [$typeSchema, 'null'];
  15424. $typeIsArray = true;
  15425. }
  15426. }
  15427. if ($typeIsArray && $typeSchema.length == 1) {
  15428. $typeSchema = $typeSchema[0];
  15429. $typeIsArray = false;
  15430. }
  15431. if (it.schema.$ref && $refKeywords) {
  15432. if (it.opts.extendRefs == 'fail') {
  15433. throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
  15434. } else if (it.opts.extendRefs !== true) {
  15435. $refKeywords = false;
  15436. it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
  15437. }
  15438. }
  15439. if (it.schema.$comment && it.opts.$comment) {
  15440. out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
  15441. }
  15442. if ($typeSchema) {
  15443. if (it.opts.coerceTypes) {
  15444. var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
  15445. }
  15446. var $rulesGroup = it.RULES.types[$typeSchema];
  15447. if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
  15448. var $schemaPath = it.schemaPath + '.type',
  15449. $errSchemaPath = it.errSchemaPath + '/type';
  15450. var $schemaPath = it.schemaPath + '.type',
  15451. $errSchemaPath = it.errSchemaPath + '/type',
  15452. $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
  15453. out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';
  15454. if ($coerceToTypes) {
  15455. var $dataType = 'dataType' + $lvl,
  15456. $coerced = 'coerced' + $lvl;
  15457. out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; ';
  15458. if (it.opts.coerceTypes == 'array') {
  15459. out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } ';
  15460. }
  15461. out += ' if (' + ($coerced) + ' !== undefined) ; ';
  15462. var arr1 = $coerceToTypes;
  15463. if (arr1) {
  15464. var $type, $i = -1,
  15465. l1 = arr1.length - 1;
  15466. while ($i < l1) {
  15467. $type = arr1[$i += 1];
  15468. if ($type == 'string') {
  15469. out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
  15470. } else if ($type == 'number' || $type == 'integer') {
  15471. out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
  15472. if ($type == 'integer') {
  15473. out += ' && !(' + ($data) + ' % 1)';
  15474. }
  15475. out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
  15476. } else if ($type == 'boolean') {
  15477. out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
  15478. } else if ($type == 'null') {
  15479. out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
  15480. } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
  15481. out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
  15482. }
  15483. }
  15484. }
  15485. out += ' else { ';
  15486. var $$outStack = $$outStack || [];
  15487. $$outStack.push(out);
  15488. out = ''; /* istanbul ignore else */
  15489. if (it.createErrors !== false) {
  15490. out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
  15491. if ($typeIsArray) {
  15492. out += '' + ($typeSchema.join(","));
  15493. } else {
  15494. out += '' + ($typeSchema);
  15495. }
  15496. out += '\' } ';
  15497. if (it.opts.messages !== false) {
  15498. out += ' , message: \'should be ';
  15499. if ($typeIsArray) {
  15500. out += '' + ($typeSchema.join(","));
  15501. } else {
  15502. out += '' + ($typeSchema);
  15503. }
  15504. out += '\' ';
  15505. }
  15506. if (it.opts.verbose) {
  15507. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15508. }
  15509. out += ' } ';
  15510. } else {
  15511. out += ' {} ';
  15512. }
  15513. var __err = out;
  15514. out = $$outStack.pop();
  15515. if (!it.compositeRule && $breakOnError) {
  15516. /* istanbul ignore if */
  15517. if (it.async) {
  15518. out += ' throw new ValidationError([' + (__err) + ']); ';
  15519. } else {
  15520. out += ' validate.errors = [' + (__err) + ']; return false; ';
  15521. }
  15522. } else {
  15523. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  15524. }
  15525. out += ' } if (' + ($coerced) + ' !== undefined) { ';
  15526. var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
  15527. $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
  15528. out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
  15529. if (!$dataLvl) {
  15530. out += 'if (' + ($parentData) + ' !== undefined)';
  15531. }
  15532. out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
  15533. } else {
  15534. var $$outStack = $$outStack || [];
  15535. $$outStack.push(out);
  15536. out = ''; /* istanbul ignore else */
  15537. if (it.createErrors !== false) {
  15538. out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
  15539. if ($typeIsArray) {
  15540. out += '' + ($typeSchema.join(","));
  15541. } else {
  15542. out += '' + ($typeSchema);
  15543. }
  15544. out += '\' } ';
  15545. if (it.opts.messages !== false) {
  15546. out += ' , message: \'should be ';
  15547. if ($typeIsArray) {
  15548. out += '' + ($typeSchema.join(","));
  15549. } else {
  15550. out += '' + ($typeSchema);
  15551. }
  15552. out += '\' ';
  15553. }
  15554. if (it.opts.verbose) {
  15555. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15556. }
  15557. out += ' } ';
  15558. } else {
  15559. out += ' {} ';
  15560. }
  15561. var __err = out;
  15562. out = $$outStack.pop();
  15563. if (!it.compositeRule && $breakOnError) {
  15564. /* istanbul ignore if */
  15565. if (it.async) {
  15566. out += ' throw new ValidationError([' + (__err) + ']); ';
  15567. } else {
  15568. out += ' validate.errors = [' + (__err) + ']; return false; ';
  15569. }
  15570. } else {
  15571. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  15572. }
  15573. }
  15574. out += ' } ';
  15575. }
  15576. }
  15577. if (it.schema.$ref && !$refKeywords) {
  15578. out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
  15579. if ($breakOnError) {
  15580. out += ' } if (errors === ';
  15581. if ($top) {
  15582. out += '0';
  15583. } else {
  15584. out += 'errs_' + ($lvl);
  15585. }
  15586. out += ') { ';
  15587. $closingBraces2 += '}';
  15588. }
  15589. } else {
  15590. var arr2 = it.RULES;
  15591. if (arr2) {
  15592. var $rulesGroup, i2 = -1,
  15593. l2 = arr2.length - 1;
  15594. while (i2 < l2) {
  15595. $rulesGroup = arr2[i2 += 1];
  15596. if ($shouldUseGroup($rulesGroup)) {
  15597. if ($rulesGroup.type) {
  15598. out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';
  15599. }
  15600. if (it.opts.useDefaults) {
  15601. if ($rulesGroup.type == 'object' && it.schema.properties) {
  15602. var $schema = it.schema.properties,
  15603. $schemaKeys = Object.keys($schema);
  15604. var arr3 = $schemaKeys;
  15605. if (arr3) {
  15606. var $propertyKey, i3 = -1,
  15607. l3 = arr3.length - 1;
  15608. while (i3 < l3) {
  15609. $propertyKey = arr3[i3 += 1];
  15610. var $sch = $schema[$propertyKey];
  15611. if ($sch.default !== undefined) {
  15612. var $passData = $data + it.util.getProperty($propertyKey);
  15613. if (it.compositeRule) {
  15614. if (it.opts.strictDefaults) {
  15615. var $defaultMsg = 'default is ignored for: ' + $passData;
  15616. if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
  15617. else throw new Error($defaultMsg);
  15618. }
  15619. } else {
  15620. out += ' if (' + ($passData) + ' === undefined ';
  15621. if (it.opts.useDefaults == 'empty') {
  15622. out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
  15623. }
  15624. out += ' ) ' + ($passData) + ' = ';
  15625. if (it.opts.useDefaults == 'shared') {
  15626. out += ' ' + (it.useDefault($sch.default)) + ' ';
  15627. } else {
  15628. out += ' ' + (JSON.stringify($sch.default)) + ' ';
  15629. }
  15630. out += '; ';
  15631. }
  15632. }
  15633. }
  15634. }
  15635. } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
  15636. var arr4 = it.schema.items;
  15637. if (arr4) {
  15638. var $sch, $i = -1,
  15639. l4 = arr4.length - 1;
  15640. while ($i < l4) {
  15641. $sch = arr4[$i += 1];
  15642. if ($sch.default !== undefined) {
  15643. var $passData = $data + '[' + $i + ']';
  15644. if (it.compositeRule) {
  15645. if (it.opts.strictDefaults) {
  15646. var $defaultMsg = 'default is ignored for: ' + $passData;
  15647. if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
  15648. else throw new Error($defaultMsg);
  15649. }
  15650. } else {
  15651. out += ' if (' + ($passData) + ' === undefined ';
  15652. if (it.opts.useDefaults == 'empty') {
  15653. out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
  15654. }
  15655. out += ' ) ' + ($passData) + ' = ';
  15656. if (it.opts.useDefaults == 'shared') {
  15657. out += ' ' + (it.useDefault($sch.default)) + ' ';
  15658. } else {
  15659. out += ' ' + (JSON.stringify($sch.default)) + ' ';
  15660. }
  15661. out += '; ';
  15662. }
  15663. }
  15664. }
  15665. }
  15666. }
  15667. }
  15668. var arr5 = $rulesGroup.rules;
  15669. if (arr5) {
  15670. var $rule, i5 = -1,
  15671. l5 = arr5.length - 1;
  15672. while (i5 < l5) {
  15673. $rule = arr5[i5 += 1];
  15674. if ($shouldUseRule($rule)) {
  15675. var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
  15676. if ($code) {
  15677. out += ' ' + ($code) + ' ';
  15678. if ($breakOnError) {
  15679. $closingBraces1 += '}';
  15680. }
  15681. }
  15682. }
  15683. }
  15684. }
  15685. if ($breakOnError) {
  15686. out += ' ' + ($closingBraces1) + ' ';
  15687. $closingBraces1 = '';
  15688. }
  15689. if ($rulesGroup.type) {
  15690. out += ' } ';
  15691. if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
  15692. out += ' else { ';
  15693. var $schemaPath = it.schemaPath + '.type',
  15694. $errSchemaPath = it.errSchemaPath + '/type';
  15695. var $$outStack = $$outStack || [];
  15696. $$outStack.push(out);
  15697. out = ''; /* istanbul ignore else */
  15698. if (it.createErrors !== false) {
  15699. out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
  15700. if ($typeIsArray) {
  15701. out += '' + ($typeSchema.join(","));
  15702. } else {
  15703. out += '' + ($typeSchema);
  15704. }
  15705. out += '\' } ';
  15706. if (it.opts.messages !== false) {
  15707. out += ' , message: \'should be ';
  15708. if ($typeIsArray) {
  15709. out += '' + ($typeSchema.join(","));
  15710. } else {
  15711. out += '' + ($typeSchema);
  15712. }
  15713. out += '\' ';
  15714. }
  15715. if (it.opts.verbose) {
  15716. out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
  15717. }
  15718. out += ' } ';
  15719. } else {
  15720. out += ' {} ';
  15721. }
  15722. var __err = out;
  15723. out = $$outStack.pop();
  15724. if (!it.compositeRule && $breakOnError) {
  15725. /* istanbul ignore if */
  15726. if (it.async) {
  15727. out += ' throw new ValidationError([' + (__err) + ']); ';
  15728. } else {
  15729. out += ' validate.errors = [' + (__err) + ']; return false; ';
  15730. }
  15731. } else {
  15732. out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  15733. }
  15734. out += ' } ';
  15735. }
  15736. }
  15737. if ($breakOnError) {
  15738. out += ' if (errors === ';
  15739. if ($top) {
  15740. out += '0';
  15741. } else {
  15742. out += 'errs_' + ($lvl);
  15743. }
  15744. out += ') { ';
  15745. $closingBraces2 += '}';
  15746. }
  15747. }
  15748. }
  15749. }
  15750. }
  15751. if ($breakOnError) {
  15752. out += ' ' + ($closingBraces2) + ' ';
  15753. }
  15754. if ($top) {
  15755. if ($async) {
  15756. out += ' if (errors === 0) return data; ';
  15757. out += ' else throw new ValidationError(vErrors); ';
  15758. } else {
  15759. out += ' validate.errors = vErrors; ';
  15760. out += ' return errors === 0; ';
  15761. }
  15762. out += ' }; return validate;';
  15763. } else {
  15764. out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
  15765. }
  15766. function $shouldUseGroup($rulesGroup) {
  15767. var rules = $rulesGroup.rules;
  15768. for (var i = 0; i < rules.length; i++)
  15769. if ($shouldUseRule(rules[i])) return true;
  15770. }
  15771. function $shouldUseRule($rule) {
  15772. return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
  15773. }
  15774. function $ruleImplementsSomeKeyword($rule) {
  15775. var impl = $rule.implements;
  15776. for (var i = 0; i < impl.length; i++)
  15777. if (it.schema[impl[i]] !== undefined) return true;
  15778. }
  15779. return out;
  15780. }
  15781. },{}],78:[function(require,module,exports){
  15782. 'use strict';
  15783. var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
  15784. var customRuleCode = require('./dotjs/custom');
  15785. var definitionSchema = require('./definition_schema');
  15786. module.exports = {
  15787. add: addKeyword,
  15788. get: getKeyword,
  15789. remove: removeKeyword,
  15790. validate: validateKeyword
  15791. };
  15792. /**
  15793. * Define custom keyword
  15794. * @this Ajv
  15795. * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
  15796. * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
  15797. * @return {Ajv} this for method chaining
  15798. */
  15799. function addKeyword(keyword, definition) {
  15800. /* jshint validthis: true */
  15801. /* eslint no-shadow: 0 */
  15802. var RULES = this.RULES;
  15803. if (RULES.keywords[keyword])
  15804. throw new Error('Keyword ' + keyword + ' is already defined');
  15805. if (!IDENTIFIER.test(keyword))
  15806. throw new Error('Keyword ' + keyword + ' is not a valid identifier');
  15807. if (definition) {
  15808. this.validateKeyword(definition, true);
  15809. var dataType = definition.type;
  15810. if (Array.isArray(dataType)) {
  15811. for (var i=0; i<dataType.length; i++)
  15812. _addRule(keyword, dataType[i], definition);
  15813. } else {
  15814. _addRule(keyword, dataType, definition);
  15815. }
  15816. var metaSchema = definition.metaSchema;
  15817. if (metaSchema) {
  15818. if (definition.$data && this._opts.$data) {
  15819. metaSchema = {
  15820. anyOf: [
  15821. metaSchema,
  15822. { '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
  15823. ]
  15824. };
  15825. }
  15826. definition.validateSchema = this.compile(metaSchema, true);
  15827. }
  15828. }
  15829. RULES.keywords[keyword] = RULES.all[keyword] = true;
  15830. function _addRule(keyword, dataType, definition) {
  15831. var ruleGroup;
  15832. for (var i=0; i<RULES.length; i++) {
  15833. var rg = RULES[i];
  15834. if (rg.type == dataType) {
  15835. ruleGroup = rg;
  15836. break;
  15837. }
  15838. }
  15839. if (!ruleGroup) {
  15840. ruleGroup = { type: dataType, rules: [] };
  15841. RULES.push(ruleGroup);
  15842. }
  15843. var rule = {
  15844. keyword: keyword,
  15845. definition: definition,
  15846. custom: true,
  15847. code: customRuleCode,
  15848. implements: definition.implements
  15849. };
  15850. ruleGroup.rules.push(rule);
  15851. RULES.custom[keyword] = rule;
  15852. }
  15853. return this;
  15854. }
  15855. /**
  15856. * Get keyword
  15857. * @this Ajv
  15858. * @param {String} keyword pre-defined or custom keyword.
  15859. * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
  15860. */
  15861. function getKeyword(keyword) {
  15862. /* jshint validthis: true */
  15863. var rule = this.RULES.custom[keyword];
  15864. return rule ? rule.definition : this.RULES.keywords[keyword] || false;
  15865. }
  15866. /**
  15867. * Remove keyword
  15868. * @this Ajv
  15869. * @param {String} keyword pre-defined or custom keyword.
  15870. * @return {Ajv} this for method chaining
  15871. */
  15872. function removeKeyword(keyword) {
  15873. /* jshint validthis: true */
  15874. var RULES = this.RULES;
  15875. delete RULES.keywords[keyword];
  15876. delete RULES.all[keyword];
  15877. delete RULES.custom[keyword];
  15878. for (var i=0; i<RULES.length; i++) {
  15879. var rules = RULES[i].rules;
  15880. for (var j=0; j<rules.length; j++) {
  15881. if (rules[j].keyword == keyword) {
  15882. rules.splice(j, 1);
  15883. break;
  15884. }
  15885. }
  15886. }
  15887. return this;
  15888. }
  15889. /**
  15890. * Validate keyword definition
  15891. * @this Ajv
  15892. * @param {Object} definition keyword definition object.
  15893. * @param {Boolean} throwError true to throw exception if definition is invalid
  15894. * @return {boolean} validation result
  15895. */
  15896. function validateKeyword(definition, throwError) {
  15897. validateKeyword.errors = null;
  15898. var v = this._validateKeyword = this._validateKeyword
  15899. || this.compile(definitionSchema, true);
  15900. if (v(definition)) return true;
  15901. validateKeyword.errors = v.errors;
  15902. if (throwError)
  15903. throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
  15904. else
  15905. return false;
  15906. }
  15907. },{"./definition_schema":51,"./dotjs/custom":61}],79:[function(require,module,exports){
  15908. module.exports={
  15909. "$schema": "http://json-schema.org/draft-07/schema#",
  15910. "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  15911. "description": "Meta-schema for $data reference (JSON Schema extension proposal)",
  15912. "type": "object",
  15913. "required": [ "$data" ],
  15914. "properties": {
  15915. "$data": {
  15916. "type": "string",
  15917. "anyOf": [
  15918. { "format": "relative-json-pointer" },
  15919. { "format": "json-pointer" }
  15920. ]
  15921. }
  15922. },
  15923. "additionalProperties": false
  15924. }
  15925. },{}],80:[function(require,module,exports){
  15926. module.exports={
  15927. "$schema": "http://json-schema.org/draft-06/schema#",
  15928. "$id": "http://json-schema.org/draft-06/schema#",
  15929. "title": "Core schema meta-schema",
  15930. "definitions": {
  15931. "schemaArray": {
  15932. "type": "array",
  15933. "minItems": 1,
  15934. "items": { "$ref": "#" }
  15935. },
  15936. "nonNegativeInteger": {
  15937. "type": "integer",
  15938. "minimum": 0
  15939. },
  15940. "nonNegativeIntegerDefault0": {
  15941. "allOf": [
  15942. { "$ref": "#/definitions/nonNegativeInteger" },
  15943. { "default": 0 }
  15944. ]
  15945. },
  15946. "simpleTypes": {
  15947. "enum": [
  15948. "array",
  15949. "boolean",
  15950. "integer",
  15951. "null",
  15952. "number",
  15953. "object",
  15954. "string"
  15955. ]
  15956. },
  15957. "stringArray": {
  15958. "type": "array",
  15959. "items": { "type": "string" },
  15960. "uniqueItems": true,
  15961. "default": []
  15962. }
  15963. },
  15964. "type": ["object", "boolean"],
  15965. "properties": {
  15966. "$id": {
  15967. "type": "string",
  15968. "format": "uri-reference"
  15969. },
  15970. "$schema": {
  15971. "type": "string",
  15972. "format": "uri"
  15973. },
  15974. "$ref": {
  15975. "type": "string",
  15976. "format": "uri-reference"
  15977. },
  15978. "title": {
  15979. "type": "string"
  15980. },
  15981. "description": {
  15982. "type": "string"
  15983. },
  15984. "default": {},
  15985. "examples": {
  15986. "type": "array",
  15987. "items": {}
  15988. },
  15989. "multipleOf": {
  15990. "type": "number",
  15991. "exclusiveMinimum": 0
  15992. },
  15993. "maximum": {
  15994. "type": "number"
  15995. },
  15996. "exclusiveMaximum": {
  15997. "type": "number"
  15998. },
  15999. "minimum": {
  16000. "type": "number"
  16001. },
  16002. "exclusiveMinimum": {
  16003. "type": "number"
  16004. },
  16005. "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
  16006. "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
  16007. "pattern": {
  16008. "type": "string",
  16009. "format": "regex"
  16010. },
  16011. "additionalItems": { "$ref": "#" },
  16012. "items": {
  16013. "anyOf": [
  16014. { "$ref": "#" },
  16015. { "$ref": "#/definitions/schemaArray" }
  16016. ],
  16017. "default": {}
  16018. },
  16019. "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
  16020. "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
  16021. "uniqueItems": {
  16022. "type": "boolean",
  16023. "default": false
  16024. },
  16025. "contains": { "$ref": "#" },
  16026. "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
  16027. "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
  16028. "required": { "$ref": "#/definitions/stringArray" },
  16029. "additionalProperties": { "$ref": "#" },
  16030. "definitions": {
  16031. "type": "object",
  16032. "additionalProperties": { "$ref": "#" },
  16033. "default": {}
  16034. },
  16035. "properties": {
  16036. "type": "object",
  16037. "additionalProperties": { "$ref": "#" },
  16038. "default": {}
  16039. },
  16040. "patternProperties": {
  16041. "type": "object",
  16042. "additionalProperties": { "$ref": "#" },
  16043. "default": {}
  16044. },
  16045. "dependencies": {
  16046. "type": "object",
  16047. "additionalProperties": {
  16048. "anyOf": [
  16049. { "$ref": "#" },
  16050. { "$ref": "#/definitions/stringArray" }
  16051. ]
  16052. }
  16053. },
  16054. "propertyNames": { "$ref": "#" },
  16055. "const": {},
  16056. "enum": {
  16057. "type": "array",
  16058. "minItems": 1,
  16059. "uniqueItems": true
  16060. },
  16061. "type": {
  16062. "anyOf": [
  16063. { "$ref": "#/definitions/simpleTypes" },
  16064. {
  16065. "type": "array",
  16066. "items": { "$ref": "#/definitions/simpleTypes" },
  16067. "minItems": 1,
  16068. "uniqueItems": true
  16069. }
  16070. ]
  16071. },
  16072. "format": { "type": "string" },
  16073. "allOf": { "$ref": "#/definitions/schemaArray" },
  16074. "anyOf": { "$ref": "#/definitions/schemaArray" },
  16075. "oneOf": { "$ref": "#/definitions/schemaArray" },
  16076. "not": { "$ref": "#" }
  16077. },
  16078. "default": {}
  16079. }
  16080. },{}],81:[function(require,module,exports){
  16081. module.exports={
  16082. "$schema": "http://json-schema.org/draft-07/schema#",
  16083. "$id": "http://json-schema.org/draft-07/schema#",
  16084. "title": "Core schema meta-schema",
  16085. "definitions": {
  16086. "schemaArray": {
  16087. "type": "array",
  16088. "minItems": 1,
  16089. "items": { "$ref": "#" }
  16090. },
  16091. "nonNegativeInteger": {
  16092. "type": "integer",
  16093. "minimum": 0
  16094. },
  16095. "nonNegativeIntegerDefault0": {
  16096. "allOf": [
  16097. { "$ref": "#/definitions/nonNegativeInteger" },
  16098. { "default": 0 }
  16099. ]
  16100. },
  16101. "simpleTypes": {
  16102. "enum": [
  16103. "array",
  16104. "boolean",
  16105. "integer",
  16106. "null",
  16107. "number",
  16108. "object",
  16109. "string"
  16110. ]
  16111. },
  16112. "stringArray": {
  16113. "type": "array",
  16114. "items": { "type": "string" },
  16115. "uniqueItems": true,
  16116. "default": []
  16117. }
  16118. },
  16119. "type": ["object", "boolean"],
  16120. "properties": {
  16121. "$id": {
  16122. "type": "string",
  16123. "format": "uri-reference"
  16124. },
  16125. "$schema": {
  16126. "type": "string",
  16127. "format": "uri"
  16128. },
  16129. "$ref": {
  16130. "type": "string",
  16131. "format": "uri-reference"
  16132. },
  16133. "$comment": {
  16134. "type": "string"
  16135. },
  16136. "title": {
  16137. "type": "string"
  16138. },
  16139. "description": {
  16140. "type": "string"
  16141. },
  16142. "default": true,
  16143. "readOnly": {
  16144. "type": "boolean",
  16145. "default": false
  16146. },
  16147. "examples": {
  16148. "type": "array",
  16149. "items": true
  16150. },
  16151. "multipleOf": {
  16152. "type": "number",
  16153. "exclusiveMinimum": 0
  16154. },
  16155. "maximum": {
  16156. "type": "number"
  16157. },
  16158. "exclusiveMaximum": {
  16159. "type": "number"
  16160. },
  16161. "minimum": {
  16162. "type": "number"
  16163. },
  16164. "exclusiveMinimum": {
  16165. "type": "number"
  16166. },
  16167. "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
  16168. "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
  16169. "pattern": {
  16170. "type": "string",
  16171. "format": "regex"
  16172. },
  16173. "additionalItems": { "$ref": "#" },
  16174. "items": {
  16175. "anyOf": [
  16176. { "$ref": "#" },
  16177. { "$ref": "#/definitions/schemaArray" }
  16178. ],
  16179. "default": true
  16180. },
  16181. "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
  16182. "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
  16183. "uniqueItems": {
  16184. "type": "boolean",
  16185. "default": false
  16186. },
  16187. "contains": { "$ref": "#" },
  16188. "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
  16189. "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
  16190. "required": { "$ref": "#/definitions/stringArray" },
  16191. "additionalProperties": { "$ref": "#" },
  16192. "definitions": {
  16193. "type": "object",
  16194. "additionalProperties": { "$ref": "#" },
  16195. "default": {}
  16196. },
  16197. "properties": {
  16198. "type": "object",
  16199. "additionalProperties": { "$ref": "#" },
  16200. "default": {}
  16201. },
  16202. "patternProperties": {
  16203. "type": "object",
  16204. "additionalProperties": { "$ref": "#" },
  16205. "propertyNames": { "format": "regex" },
  16206. "default": {}
  16207. },
  16208. "dependencies": {
  16209. "type": "object",
  16210. "additionalProperties": {
  16211. "anyOf": [
  16212. { "$ref": "#" },
  16213. { "$ref": "#/definitions/stringArray" }
  16214. ]
  16215. }
  16216. },
  16217. "propertyNames": { "$ref": "#" },
  16218. "const": true,
  16219. "enum": {
  16220. "type": "array",
  16221. "items": true,
  16222. "minItems": 1,
  16223. "uniqueItems": true
  16224. },
  16225. "type": {
  16226. "anyOf": [
  16227. { "$ref": "#/definitions/simpleTypes" },
  16228. {
  16229. "type": "array",
  16230. "items": { "$ref": "#/definitions/simpleTypes" },
  16231. "minItems": 1,
  16232. "uniqueItems": true
  16233. }
  16234. ]
  16235. },
  16236. "format": { "type": "string" },
  16237. "contentMediaType": { "type": "string" },
  16238. "contentEncoding": { "type": "string" },
  16239. "if": {"$ref": "#"},
  16240. "then": {"$ref": "#"},
  16241. "else": {"$ref": "#"},
  16242. "allOf": { "$ref": "#/definitions/schemaArray" },
  16243. "anyOf": { "$ref": "#/definitions/schemaArray" },
  16244. "oneOf": { "$ref": "#/definitions/schemaArray" },
  16245. "not": { "$ref": "#" }
  16246. },
  16247. "default": true
  16248. }
  16249. },{}],82:[function(require,module,exports){
  16250. /**
  16251. * Array#filter.
  16252. *
  16253. * @param {Array} arr
  16254. * @param {Function} fn
  16255. * @param {Object=} self
  16256. * @return {Array}
  16257. * @throw TypeError
  16258. */
  16259. module.exports = function (arr, fn, self) {
  16260. if (arr.filter) return arr.filter(fn, self);
  16261. if (void 0 === arr || null === arr) throw new TypeError;
  16262. if ('function' != typeof fn) throw new TypeError;
  16263. var ret = [];
  16264. for (var i = 0; i < arr.length; i++) {
  16265. if (!hasOwn.call(arr, i)) continue;
  16266. var val = arr[i];
  16267. if (fn.call(self, val, i, arr)) ret.push(val);
  16268. }
  16269. return ret;
  16270. };
  16271. var hasOwn = Object.prototype.hasOwnProperty;
  16272. },{}],83:[function(require,module,exports){
  16273. 'use strict';
  16274. const asn1 = exports;
  16275. asn1.bignum = require('bn.js');
  16276. asn1.define = require('./asn1/api').define;
  16277. asn1.base = require('./asn1/base');
  16278. asn1.constants = require('./asn1/constants');
  16279. asn1.decoders = require('./asn1/decoders');
  16280. asn1.encoders = require('./asn1/encoders');
  16281. },{"./asn1/api":84,"./asn1/base":86,"./asn1/constants":90,"./asn1/decoders":92,"./asn1/encoders":95,"bn.js":97}],84:[function(require,module,exports){
  16282. 'use strict';
  16283. const encoders = require('./encoders');
  16284. const decoders = require('./decoders');
  16285. const inherits = require('inherits');
  16286. const api = exports;
  16287. api.define = function define(name, body) {
  16288. return new Entity(name, body);
  16289. };
  16290. function Entity(name, body) {
  16291. this.name = name;
  16292. this.body = body;
  16293. this.decoders = {};
  16294. this.encoders = {};
  16295. }
  16296. Entity.prototype._createNamed = function createNamed(Base) {
  16297. const name = this.name;
  16298. function Generated(entity) {
  16299. this._initNamed(entity, name);
  16300. }
  16301. inherits(Generated, Base);
  16302. Generated.prototype._initNamed = function _initNamed(entity, name) {
  16303. Base.call(this, entity, name);
  16304. };
  16305. return new Generated(this);
  16306. };
  16307. Entity.prototype._getDecoder = function _getDecoder(enc) {
  16308. enc = enc || 'der';
  16309. // Lazily create decoder
  16310. if (!this.decoders.hasOwnProperty(enc))
  16311. this.decoders[enc] = this._createNamed(decoders[enc]);
  16312. return this.decoders[enc];
  16313. };
  16314. Entity.prototype.decode = function decode(data, enc, options) {
  16315. return this._getDecoder(enc).decode(data, options);
  16316. };
  16317. Entity.prototype._getEncoder = function _getEncoder(enc) {
  16318. enc = enc || 'der';
  16319. // Lazily create encoder
  16320. if (!this.encoders.hasOwnProperty(enc))
  16321. this.encoders[enc] = this._createNamed(encoders[enc]);
  16322. return this.encoders[enc];
  16323. };
  16324. Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
  16325. return this._getEncoder(enc).encode(data, reporter);
  16326. };
  16327. },{"./decoders":92,"./encoders":95,"inherits":320}],85:[function(require,module,exports){
  16328. 'use strict';
  16329. const inherits = require('inherits');
  16330. const Reporter = require('../base/reporter').Reporter;
  16331. const Buffer = require('safer-buffer').Buffer;
  16332. function DecoderBuffer(base, options) {
  16333. Reporter.call(this, options);
  16334. if (!Buffer.isBuffer(base)) {
  16335. this.error('Input not Buffer');
  16336. return;
  16337. }
  16338. this.base = base;
  16339. this.offset = 0;
  16340. this.length = base.length;
  16341. }
  16342. inherits(DecoderBuffer, Reporter);
  16343. exports.DecoderBuffer = DecoderBuffer;
  16344. DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) {
  16345. if (data instanceof DecoderBuffer) {
  16346. return true;
  16347. }
  16348. // Or accept compatible API
  16349. const isCompatible = typeof data === 'object' &&
  16350. Buffer.isBuffer(data.base) &&
  16351. data.constructor.name === 'DecoderBuffer' &&
  16352. typeof data.offset === 'number' &&
  16353. typeof data.length === 'number' &&
  16354. typeof data.save === 'function' &&
  16355. typeof data.restore === 'function' &&
  16356. typeof data.isEmpty === 'function' &&
  16357. typeof data.readUInt8 === 'function' &&
  16358. typeof data.skip === 'function' &&
  16359. typeof data.raw === 'function';
  16360. return isCompatible;
  16361. };
  16362. DecoderBuffer.prototype.save = function save() {
  16363. return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
  16364. };
  16365. DecoderBuffer.prototype.restore = function restore(save) {
  16366. // Return skipped data
  16367. const res = new DecoderBuffer(this.base);
  16368. res.offset = save.offset;
  16369. res.length = this.offset;
  16370. this.offset = save.offset;
  16371. Reporter.prototype.restore.call(this, save.reporter);
  16372. return res;
  16373. };
  16374. DecoderBuffer.prototype.isEmpty = function isEmpty() {
  16375. return this.offset === this.length;
  16376. };
  16377. DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
  16378. if (this.offset + 1 <= this.length)
  16379. return this.base.readUInt8(this.offset++, true);
  16380. else
  16381. return this.error(fail || 'DecoderBuffer overrun');
  16382. };
  16383. DecoderBuffer.prototype.skip = function skip(bytes, fail) {
  16384. if (!(this.offset + bytes <= this.length))
  16385. return this.error(fail || 'DecoderBuffer overrun');
  16386. const res = new DecoderBuffer(this.base);
  16387. // Share reporter state
  16388. res._reporterState = this._reporterState;
  16389. res.offset = this.offset;
  16390. res.length = this.offset + bytes;
  16391. this.offset += bytes;
  16392. return res;
  16393. };
  16394. DecoderBuffer.prototype.raw = function raw(save) {
  16395. return this.base.slice(save ? save.offset : this.offset, this.length);
  16396. };
  16397. function EncoderBuffer(value, reporter) {
  16398. if (Array.isArray(value)) {
  16399. this.length = 0;
  16400. this.value = value.map(function(item) {
  16401. if (!EncoderBuffer.isEncoderBuffer(item))
  16402. item = new EncoderBuffer(item, reporter);
  16403. this.length += item.length;
  16404. return item;
  16405. }, this);
  16406. } else if (typeof value === 'number') {
  16407. if (!(0 <= value && value <= 0xff))
  16408. return reporter.error('non-byte EncoderBuffer value');
  16409. this.value = value;
  16410. this.length = 1;
  16411. } else if (typeof value === 'string') {
  16412. this.value = value;
  16413. this.length = Buffer.byteLength(value);
  16414. } else if (Buffer.isBuffer(value)) {
  16415. this.value = value;
  16416. this.length = value.length;
  16417. } else {
  16418. return reporter.error('Unsupported type: ' + typeof value);
  16419. }
  16420. }
  16421. exports.EncoderBuffer = EncoderBuffer;
  16422. EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) {
  16423. if (data instanceof EncoderBuffer) {
  16424. return true;
  16425. }
  16426. // Or accept compatible API
  16427. const isCompatible = typeof data === 'object' &&
  16428. data.constructor.name === 'EncoderBuffer' &&
  16429. typeof data.length === 'number' &&
  16430. typeof data.join === 'function';
  16431. return isCompatible;
  16432. };
  16433. EncoderBuffer.prototype.join = function join(out, offset) {
  16434. if (!out)
  16435. out = Buffer.alloc(this.length);
  16436. if (!offset)
  16437. offset = 0;
  16438. if (this.length === 0)
  16439. return out;
  16440. if (Array.isArray(this.value)) {
  16441. this.value.forEach(function(item) {
  16442. item.join(out, offset);
  16443. offset += item.length;
  16444. });
  16445. } else {
  16446. if (typeof this.value === 'number')
  16447. out[offset] = this.value;
  16448. else if (typeof this.value === 'string')
  16449. out.write(this.value, offset);
  16450. else if (Buffer.isBuffer(this.value))
  16451. this.value.copy(out, offset);
  16452. offset += this.length;
  16453. }
  16454. return out;
  16455. };
  16456. },{"../base/reporter":88,"inherits":320,"safer-buffer":562}],86:[function(require,module,exports){
  16457. 'use strict';
  16458. const base = exports;
  16459. base.Reporter = require('./reporter').Reporter;
  16460. base.DecoderBuffer = require('./buffer').DecoderBuffer;
  16461. base.EncoderBuffer = require('./buffer').EncoderBuffer;
  16462. base.Node = require('./node');
  16463. },{"./buffer":85,"./node":87,"./reporter":88}],87:[function(require,module,exports){
  16464. 'use strict';
  16465. const Reporter = require('../base/reporter').Reporter;
  16466. const EncoderBuffer = require('../base/buffer').EncoderBuffer;
  16467. const DecoderBuffer = require('../base/buffer').DecoderBuffer;
  16468. const assert = require('minimalistic-assert');
  16469. // Supported tags
  16470. const tags = [
  16471. 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
  16472. 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
  16473. 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
  16474. 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
  16475. ];
  16476. // Public methods list
  16477. const methods = [
  16478. 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
  16479. 'any', 'contains'
  16480. ].concat(tags);
  16481. // Overrided methods list
  16482. const overrided = [
  16483. '_peekTag', '_decodeTag', '_use',
  16484. '_decodeStr', '_decodeObjid', '_decodeTime',
  16485. '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
  16486. '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
  16487. '_encodeNull', '_encodeInt', '_encodeBool'
  16488. ];
  16489. function Node(enc, parent, name) {
  16490. const state = {};
  16491. this._baseState = state;
  16492. state.name = name;
  16493. state.enc = enc;
  16494. state.parent = parent || null;
  16495. state.children = null;
  16496. // State
  16497. state.tag = null;
  16498. state.args = null;
  16499. state.reverseArgs = null;
  16500. state.choice = null;
  16501. state.optional = false;
  16502. state.any = false;
  16503. state.obj = false;
  16504. state.use = null;
  16505. state.useDecoder = null;
  16506. state.key = null;
  16507. state['default'] = null;
  16508. state.explicit = null;
  16509. state.implicit = null;
  16510. state.contains = null;
  16511. // Should create new instance on each method
  16512. if (!state.parent) {
  16513. state.children = [];
  16514. this._wrap();
  16515. }
  16516. }
  16517. module.exports = Node;
  16518. const stateProps = [
  16519. 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
  16520. 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
  16521. 'implicit', 'contains'
  16522. ];
  16523. Node.prototype.clone = function clone() {
  16524. const state = this._baseState;
  16525. const cstate = {};
  16526. stateProps.forEach(function(prop) {
  16527. cstate[prop] = state[prop];
  16528. });
  16529. const res = new this.constructor(cstate.parent);
  16530. res._baseState = cstate;
  16531. return res;
  16532. };
  16533. Node.prototype._wrap = function wrap() {
  16534. const state = this._baseState;
  16535. methods.forEach(function(method) {
  16536. this[method] = function _wrappedMethod() {
  16537. const clone = new this.constructor(this);
  16538. state.children.push(clone);
  16539. return clone[method].apply(clone, arguments);
  16540. };
  16541. }, this);
  16542. };
  16543. Node.prototype._init = function init(body) {
  16544. const state = this._baseState;
  16545. assert(state.parent === null);
  16546. body.call(this);
  16547. // Filter children
  16548. state.children = state.children.filter(function(child) {
  16549. return child._baseState.parent === this;
  16550. }, this);
  16551. assert.equal(state.children.length, 1, 'Root node can have only one child');
  16552. };
  16553. Node.prototype._useArgs = function useArgs(args) {
  16554. const state = this._baseState;
  16555. // Filter children and args
  16556. const children = args.filter(function(arg) {
  16557. return arg instanceof this.constructor;
  16558. }, this);
  16559. args = args.filter(function(arg) {
  16560. return !(arg instanceof this.constructor);
  16561. }, this);
  16562. if (children.length !== 0) {
  16563. assert(state.children === null);
  16564. state.children = children;
  16565. // Replace parent to maintain backward link
  16566. children.forEach(function(child) {
  16567. child._baseState.parent = this;
  16568. }, this);
  16569. }
  16570. if (args.length !== 0) {
  16571. assert(state.args === null);
  16572. state.args = args;
  16573. state.reverseArgs = args.map(function(arg) {
  16574. if (typeof arg !== 'object' || arg.constructor !== Object)
  16575. return arg;
  16576. const res = {};
  16577. Object.keys(arg).forEach(function(key) {
  16578. if (key == (key | 0))
  16579. key |= 0;
  16580. const value = arg[key];
  16581. res[value] = key;
  16582. });
  16583. return res;
  16584. });
  16585. }
  16586. };
  16587. //
  16588. // Overrided methods
  16589. //
  16590. overrided.forEach(function(method) {
  16591. Node.prototype[method] = function _overrided() {
  16592. const state = this._baseState;
  16593. throw new Error(method + ' not implemented for encoding: ' + state.enc);
  16594. };
  16595. });
  16596. //
  16597. // Public methods
  16598. //
  16599. tags.forEach(function(tag) {
  16600. Node.prototype[tag] = function _tagMethod() {
  16601. const state = this._baseState;
  16602. const args = Array.prototype.slice.call(arguments);
  16603. assert(state.tag === null);
  16604. state.tag = tag;
  16605. this._useArgs(args);
  16606. return this;
  16607. };
  16608. });
  16609. Node.prototype.use = function use(item) {
  16610. assert(item);
  16611. const state = this._baseState;
  16612. assert(state.use === null);
  16613. state.use = item;
  16614. return this;
  16615. };
  16616. Node.prototype.optional = function optional() {
  16617. const state = this._baseState;
  16618. state.optional = true;
  16619. return this;
  16620. };
  16621. Node.prototype.def = function def(val) {
  16622. const state = this._baseState;
  16623. assert(state['default'] === null);
  16624. state['default'] = val;
  16625. state.optional = true;
  16626. return this;
  16627. };
  16628. Node.prototype.explicit = function explicit(num) {
  16629. const state = this._baseState;
  16630. assert(state.explicit === null && state.implicit === null);
  16631. state.explicit = num;
  16632. return this;
  16633. };
  16634. Node.prototype.implicit = function implicit(num) {
  16635. const state = this._baseState;
  16636. assert(state.explicit === null && state.implicit === null);
  16637. state.implicit = num;
  16638. return this;
  16639. };
  16640. Node.prototype.obj = function obj() {
  16641. const state = this._baseState;
  16642. const args = Array.prototype.slice.call(arguments);
  16643. state.obj = true;
  16644. if (args.length !== 0)
  16645. this._useArgs(args);
  16646. return this;
  16647. };
  16648. Node.prototype.key = function key(newKey) {
  16649. const state = this._baseState;
  16650. assert(state.key === null);
  16651. state.key = newKey;
  16652. return this;
  16653. };
  16654. Node.prototype.any = function any() {
  16655. const state = this._baseState;
  16656. state.any = true;
  16657. return this;
  16658. };
  16659. Node.prototype.choice = function choice(obj) {
  16660. const state = this._baseState;
  16661. assert(state.choice === null);
  16662. state.choice = obj;
  16663. this._useArgs(Object.keys(obj).map(function(key) {
  16664. return obj[key];
  16665. }));
  16666. return this;
  16667. };
  16668. Node.prototype.contains = function contains(item) {
  16669. const state = this._baseState;
  16670. assert(state.use === null);
  16671. state.contains = item;
  16672. return this;
  16673. };
  16674. //
  16675. // Decoding
  16676. //
  16677. Node.prototype._decode = function decode(input, options) {
  16678. const state = this._baseState;
  16679. // Decode root node
  16680. if (state.parent === null)
  16681. return input.wrapResult(state.children[0]._decode(input, options));
  16682. let result = state['default'];
  16683. let present = true;
  16684. let prevKey = null;
  16685. if (state.key !== null)
  16686. prevKey = input.enterKey(state.key);
  16687. // Check if tag is there
  16688. if (state.optional) {
  16689. let tag = null;
  16690. if (state.explicit !== null)
  16691. tag = state.explicit;
  16692. else if (state.implicit !== null)
  16693. tag = state.implicit;
  16694. else if (state.tag !== null)
  16695. tag = state.tag;
  16696. if (tag === null && !state.any) {
  16697. // Trial and Error
  16698. const save = input.save();
  16699. try {
  16700. if (state.choice === null)
  16701. this._decodeGeneric(state.tag, input, options);
  16702. else
  16703. this._decodeChoice(input, options);
  16704. present = true;
  16705. } catch (e) {
  16706. present = false;
  16707. }
  16708. input.restore(save);
  16709. } else {
  16710. present = this._peekTag(input, tag, state.any);
  16711. if (input.isError(present))
  16712. return present;
  16713. }
  16714. }
  16715. // Push object on stack
  16716. let prevObj;
  16717. if (state.obj && present)
  16718. prevObj = input.enterObject();
  16719. if (present) {
  16720. // Unwrap explicit values
  16721. if (state.explicit !== null) {
  16722. const explicit = this._decodeTag(input, state.explicit);
  16723. if (input.isError(explicit))
  16724. return explicit;
  16725. input = explicit;
  16726. }
  16727. const start = input.offset;
  16728. // Unwrap implicit and normal values
  16729. if (state.use === null && state.choice === null) {
  16730. let save;
  16731. if (state.any)
  16732. save = input.save();
  16733. const body = this._decodeTag(
  16734. input,
  16735. state.implicit !== null ? state.implicit : state.tag,
  16736. state.any
  16737. );
  16738. if (input.isError(body))
  16739. return body;
  16740. if (state.any)
  16741. result = input.raw(save);
  16742. else
  16743. input = body;
  16744. }
  16745. if (options && options.track && state.tag !== null)
  16746. options.track(input.path(), start, input.length, 'tagged');
  16747. if (options && options.track && state.tag !== null)
  16748. options.track(input.path(), input.offset, input.length, 'content');
  16749. // Select proper method for tag
  16750. if (state.any) {
  16751. // no-op
  16752. } else if (state.choice === null) {
  16753. result = this._decodeGeneric(state.tag, input, options);
  16754. } else {
  16755. result = this._decodeChoice(input, options);
  16756. }
  16757. if (input.isError(result))
  16758. return result;
  16759. // Decode children
  16760. if (!state.any && state.choice === null && state.children !== null) {
  16761. state.children.forEach(function decodeChildren(child) {
  16762. // NOTE: We are ignoring errors here, to let parser continue with other
  16763. // parts of encoded data
  16764. child._decode(input, options);
  16765. });
  16766. }
  16767. // Decode contained/encoded by schema, only in bit or octet strings
  16768. if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
  16769. const data = new DecoderBuffer(result);
  16770. result = this._getUse(state.contains, input._reporterState.obj)
  16771. ._decode(data, options);
  16772. }
  16773. }
  16774. // Pop object
  16775. if (state.obj && present)
  16776. result = input.leaveObject(prevObj);
  16777. // Set key
  16778. if (state.key !== null && (result !== null || present === true))
  16779. input.leaveKey(prevKey, state.key, result);
  16780. else if (prevKey !== null)
  16781. input.exitKey(prevKey);
  16782. return result;
  16783. };
  16784. Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
  16785. const state = this._baseState;
  16786. if (tag === 'seq' || tag === 'set')
  16787. return null;
  16788. if (tag === 'seqof' || tag === 'setof')
  16789. return this._decodeList(input, tag, state.args[0], options);
  16790. else if (/str$/.test(tag))
  16791. return this._decodeStr(input, tag, options);
  16792. else if (tag === 'objid' && state.args)
  16793. return this._decodeObjid(input, state.args[0], state.args[1], options);
  16794. else if (tag === 'objid')
  16795. return this._decodeObjid(input, null, null, options);
  16796. else if (tag === 'gentime' || tag === 'utctime')
  16797. return this._decodeTime(input, tag, options);
  16798. else if (tag === 'null_')
  16799. return this._decodeNull(input, options);
  16800. else if (tag === 'bool')
  16801. return this._decodeBool(input, options);
  16802. else if (tag === 'objDesc')
  16803. return this._decodeStr(input, tag, options);
  16804. else if (tag === 'int' || tag === 'enum')
  16805. return this._decodeInt(input, state.args && state.args[0], options);
  16806. if (state.use !== null) {
  16807. return this._getUse(state.use, input._reporterState.obj)
  16808. ._decode(input, options);
  16809. } else {
  16810. return input.error('unknown tag: ' + tag);
  16811. }
  16812. };
  16813. Node.prototype._getUse = function _getUse(entity, obj) {
  16814. const state = this._baseState;
  16815. // Create altered use decoder if implicit is set
  16816. state.useDecoder = this._use(entity, obj);
  16817. assert(state.useDecoder._baseState.parent === null);
  16818. state.useDecoder = state.useDecoder._baseState.children[0];
  16819. if (state.implicit !== state.useDecoder._baseState.implicit) {
  16820. state.useDecoder = state.useDecoder.clone();
  16821. state.useDecoder._baseState.implicit = state.implicit;
  16822. }
  16823. return state.useDecoder;
  16824. };
  16825. Node.prototype._decodeChoice = function decodeChoice(input, options) {
  16826. const state = this._baseState;
  16827. let result = null;
  16828. let match = false;
  16829. Object.keys(state.choice).some(function(key) {
  16830. const save = input.save();
  16831. const node = state.choice[key];
  16832. try {
  16833. const value = node._decode(input, options);
  16834. if (input.isError(value))
  16835. return false;
  16836. result = { type: key, value: value };
  16837. match = true;
  16838. } catch (e) {
  16839. input.restore(save);
  16840. return false;
  16841. }
  16842. return true;
  16843. }, this);
  16844. if (!match)
  16845. return input.error('Choice not matched');
  16846. return result;
  16847. };
  16848. //
  16849. // Encoding
  16850. //
  16851. Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
  16852. return new EncoderBuffer(data, this.reporter);
  16853. };
  16854. Node.prototype._encode = function encode(data, reporter, parent) {
  16855. const state = this._baseState;
  16856. if (state['default'] !== null && state['default'] === data)
  16857. return;
  16858. const result = this._encodeValue(data, reporter, parent);
  16859. if (result === undefined)
  16860. return;
  16861. if (this._skipDefault(result, reporter, parent))
  16862. return;
  16863. return result;
  16864. };
  16865. Node.prototype._encodeValue = function encode(data, reporter, parent) {
  16866. const state = this._baseState;
  16867. // Decode root node
  16868. if (state.parent === null)
  16869. return state.children[0]._encode(data, reporter || new Reporter());
  16870. let result = null;
  16871. // Set reporter to share it with a child class
  16872. this.reporter = reporter;
  16873. // Check if data is there
  16874. if (state.optional && data === undefined) {
  16875. if (state['default'] !== null)
  16876. data = state['default'];
  16877. else
  16878. return;
  16879. }
  16880. // Encode children first
  16881. let content = null;
  16882. let primitive = false;
  16883. if (state.any) {
  16884. // Anything that was given is translated to buffer
  16885. result = this._createEncoderBuffer(data);
  16886. } else if (state.choice) {
  16887. result = this._encodeChoice(data, reporter);
  16888. } else if (state.contains) {
  16889. content = this._getUse(state.contains, parent)._encode(data, reporter);
  16890. primitive = true;
  16891. } else if (state.children) {
  16892. content = state.children.map(function(child) {
  16893. if (child._baseState.tag === 'null_')
  16894. return child._encode(null, reporter, data);
  16895. if (child._baseState.key === null)
  16896. return reporter.error('Child should have a key');
  16897. const prevKey = reporter.enterKey(child._baseState.key);
  16898. if (typeof data !== 'object')
  16899. return reporter.error('Child expected, but input is not object');
  16900. const res = child._encode(data[child._baseState.key], reporter, data);
  16901. reporter.leaveKey(prevKey);
  16902. return res;
  16903. }, this).filter(function(child) {
  16904. return child;
  16905. });
  16906. content = this._createEncoderBuffer(content);
  16907. } else {
  16908. if (state.tag === 'seqof' || state.tag === 'setof') {
  16909. // TODO(indutny): this should be thrown on DSL level
  16910. if (!(state.args && state.args.length === 1))
  16911. return reporter.error('Too many args for : ' + state.tag);
  16912. if (!Array.isArray(data))
  16913. return reporter.error('seqof/setof, but data is not Array');
  16914. const child = this.clone();
  16915. child._baseState.implicit = null;
  16916. content = this._createEncoderBuffer(data.map(function(item) {
  16917. const state = this._baseState;
  16918. return this._getUse(state.args[0], data)._encode(item, reporter);
  16919. }, child));
  16920. } else if (state.use !== null) {
  16921. result = this._getUse(state.use, parent)._encode(data, reporter);
  16922. } else {
  16923. content = this._encodePrimitive(state.tag, data);
  16924. primitive = true;
  16925. }
  16926. }
  16927. // Encode data itself
  16928. if (!state.any && state.choice === null) {
  16929. const tag = state.implicit !== null ? state.implicit : state.tag;
  16930. const cls = state.implicit === null ? 'universal' : 'context';
  16931. if (tag === null) {
  16932. if (state.use === null)
  16933. reporter.error('Tag could be omitted only for .use()');
  16934. } else {
  16935. if (state.use === null)
  16936. result = this._encodeComposite(tag, primitive, cls, content);
  16937. }
  16938. }
  16939. // Wrap in explicit
  16940. if (state.explicit !== null)
  16941. result = this._encodeComposite(state.explicit, false, 'context', result);
  16942. return result;
  16943. };
  16944. Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
  16945. const state = this._baseState;
  16946. const node = state.choice[data.type];
  16947. if (!node) {
  16948. assert(
  16949. false,
  16950. data.type + ' not found in ' +
  16951. JSON.stringify(Object.keys(state.choice)));
  16952. }
  16953. return node._encode(data.value, reporter);
  16954. };
  16955. Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
  16956. const state = this._baseState;
  16957. if (/str$/.test(tag))
  16958. return this._encodeStr(data, tag);
  16959. else if (tag === 'objid' && state.args)
  16960. return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
  16961. else if (tag === 'objid')
  16962. return this._encodeObjid(data, null, null);
  16963. else if (tag === 'gentime' || tag === 'utctime')
  16964. return this._encodeTime(data, tag);
  16965. else if (tag === 'null_')
  16966. return this._encodeNull();
  16967. else if (tag === 'int' || tag === 'enum')
  16968. return this._encodeInt(data, state.args && state.reverseArgs[0]);
  16969. else if (tag === 'bool')
  16970. return this._encodeBool(data);
  16971. else if (tag === 'objDesc')
  16972. return this._encodeStr(data, tag);
  16973. else
  16974. throw new Error('Unsupported tag: ' + tag);
  16975. };
  16976. Node.prototype._isNumstr = function isNumstr(str) {
  16977. return /^[0-9 ]*$/.test(str);
  16978. };
  16979. Node.prototype._isPrintstr = function isPrintstr(str) {
  16980. return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str);
  16981. };
  16982. },{"../base/buffer":85,"../base/reporter":88,"minimalistic-assert":345}],88:[function(require,module,exports){
  16983. 'use strict';
  16984. const inherits = require('inherits');
  16985. function Reporter(options) {
  16986. this._reporterState = {
  16987. obj: null,
  16988. path: [],
  16989. options: options || {},
  16990. errors: []
  16991. };
  16992. }
  16993. exports.Reporter = Reporter;
  16994. Reporter.prototype.isError = function isError(obj) {
  16995. return obj instanceof ReporterError;
  16996. };
  16997. Reporter.prototype.save = function save() {
  16998. const state = this._reporterState;
  16999. return { obj: state.obj, pathLen: state.path.length };
  17000. };
  17001. Reporter.prototype.restore = function restore(data) {
  17002. const state = this._reporterState;
  17003. state.obj = data.obj;
  17004. state.path = state.path.slice(0, data.pathLen);
  17005. };
  17006. Reporter.prototype.enterKey = function enterKey(key) {
  17007. return this._reporterState.path.push(key);
  17008. };
  17009. Reporter.prototype.exitKey = function exitKey(index) {
  17010. const state = this._reporterState;
  17011. state.path = state.path.slice(0, index - 1);
  17012. };
  17013. Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
  17014. const state = this._reporterState;
  17015. this.exitKey(index);
  17016. if (state.obj !== null)
  17017. state.obj[key] = value;
  17018. };
  17019. Reporter.prototype.path = function path() {
  17020. return this._reporterState.path.join('/');
  17021. };
  17022. Reporter.prototype.enterObject = function enterObject() {
  17023. const state = this._reporterState;
  17024. const prev = state.obj;
  17025. state.obj = {};
  17026. return prev;
  17027. };
  17028. Reporter.prototype.leaveObject = function leaveObject(prev) {
  17029. const state = this._reporterState;
  17030. const now = state.obj;
  17031. state.obj = prev;
  17032. return now;
  17033. };
  17034. Reporter.prototype.error = function error(msg) {
  17035. let err;
  17036. const state = this._reporterState;
  17037. const inherited = msg instanceof ReporterError;
  17038. if (inherited) {
  17039. err = msg;
  17040. } else {
  17041. err = new ReporterError(state.path.map(function(elem) {
  17042. return '[' + JSON.stringify(elem) + ']';
  17043. }).join(''), msg.message || msg, msg.stack);
  17044. }
  17045. if (!state.options.partial)
  17046. throw err;
  17047. if (!inherited)
  17048. state.errors.push(err);
  17049. return err;
  17050. };
  17051. Reporter.prototype.wrapResult = function wrapResult(result) {
  17052. const state = this._reporterState;
  17053. if (!state.options.partial)
  17054. return result;
  17055. return {
  17056. result: this.isError(result) ? null : result,
  17057. errors: state.errors
  17058. };
  17059. };
  17060. function ReporterError(path, msg) {
  17061. this.path = path;
  17062. this.rethrow(msg);
  17063. }
  17064. inherits(ReporterError, Error);
  17065. ReporterError.prototype.rethrow = function rethrow(msg) {
  17066. this.message = msg + ' at: ' + (this.path || '(shallow)');
  17067. if (Error.captureStackTrace)
  17068. Error.captureStackTrace(this, ReporterError);
  17069. if (!this.stack) {
  17070. try {
  17071. // IE only adds stack when thrown
  17072. throw new Error(this.message);
  17073. } catch (e) {
  17074. this.stack = e.stack;
  17075. }
  17076. }
  17077. return this;
  17078. };
  17079. },{"inherits":320}],89:[function(require,module,exports){
  17080. 'use strict';
  17081. // Helper
  17082. function reverse(map) {
  17083. const res = {};
  17084. Object.keys(map).forEach(function(key) {
  17085. // Convert key to integer if it is stringified
  17086. if ((key | 0) == key)
  17087. key = key | 0;
  17088. const value = map[key];
  17089. res[value] = key;
  17090. });
  17091. return res;
  17092. }
  17093. exports.tagClass = {
  17094. 0: 'universal',
  17095. 1: 'application',
  17096. 2: 'context',
  17097. 3: 'private'
  17098. };
  17099. exports.tagClassByName = reverse(exports.tagClass);
  17100. exports.tag = {
  17101. 0x00: 'end',
  17102. 0x01: 'bool',
  17103. 0x02: 'int',
  17104. 0x03: 'bitstr',
  17105. 0x04: 'octstr',
  17106. 0x05: 'null_',
  17107. 0x06: 'objid',
  17108. 0x07: 'objDesc',
  17109. 0x08: 'external',
  17110. 0x09: 'real',
  17111. 0x0a: 'enum',
  17112. 0x0b: 'embed',
  17113. 0x0c: 'utf8str',
  17114. 0x0d: 'relativeOid',
  17115. 0x10: 'seq',
  17116. 0x11: 'set',
  17117. 0x12: 'numstr',
  17118. 0x13: 'printstr',
  17119. 0x14: 't61str',
  17120. 0x15: 'videostr',
  17121. 0x16: 'ia5str',
  17122. 0x17: 'utctime',
  17123. 0x18: 'gentime',
  17124. 0x19: 'graphstr',
  17125. 0x1a: 'iso646str',
  17126. 0x1b: 'genstr',
  17127. 0x1c: 'unistr',
  17128. 0x1d: 'charstr',
  17129. 0x1e: 'bmpstr'
  17130. };
  17131. exports.tagByName = reverse(exports.tag);
  17132. },{}],90:[function(require,module,exports){
  17133. 'use strict';
  17134. const constants = exports;
  17135. // Helper
  17136. constants._reverse = function reverse(map) {
  17137. const res = {};
  17138. Object.keys(map).forEach(function(key) {
  17139. // Convert key to integer if it is stringified
  17140. if ((key | 0) == key)
  17141. key = key | 0;
  17142. const value = map[key];
  17143. res[value] = key;
  17144. });
  17145. return res;
  17146. };
  17147. constants.der = require('./der');
  17148. },{"./der":89}],91:[function(require,module,exports){
  17149. 'use strict';
  17150. const inherits = require('inherits');
  17151. const bignum = require('bn.js');
  17152. const DecoderBuffer = require('../base/buffer').DecoderBuffer;
  17153. const Node = require('../base/node');
  17154. // Import DER constants
  17155. const der = require('../constants/der');
  17156. function DERDecoder(entity) {
  17157. this.enc = 'der';
  17158. this.name = entity.name;
  17159. this.entity = entity;
  17160. // Construct base tree
  17161. this.tree = new DERNode();
  17162. this.tree._init(entity.body);
  17163. }
  17164. module.exports = DERDecoder;
  17165. DERDecoder.prototype.decode = function decode(data, options) {
  17166. if (!DecoderBuffer.isDecoderBuffer(data)) {
  17167. data = new DecoderBuffer(data, options);
  17168. }
  17169. return this.tree._decode(data, options);
  17170. };
  17171. // Tree methods
  17172. function DERNode(parent) {
  17173. Node.call(this, 'der', parent);
  17174. }
  17175. inherits(DERNode, Node);
  17176. DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
  17177. if (buffer.isEmpty())
  17178. return false;
  17179. const state = buffer.save();
  17180. const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
  17181. if (buffer.isError(decodedTag))
  17182. return decodedTag;
  17183. buffer.restore(state);
  17184. return decodedTag.tag === tag || decodedTag.tagStr === tag ||
  17185. (decodedTag.tagStr + 'of') === tag || any;
  17186. };
  17187. DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
  17188. const decodedTag = derDecodeTag(buffer,
  17189. 'Failed to decode tag of "' + tag + '"');
  17190. if (buffer.isError(decodedTag))
  17191. return decodedTag;
  17192. let len = derDecodeLen(buffer,
  17193. decodedTag.primitive,
  17194. 'Failed to get length of "' + tag + '"');
  17195. // Failure
  17196. if (buffer.isError(len))
  17197. return len;
  17198. if (!any &&
  17199. decodedTag.tag !== tag &&
  17200. decodedTag.tagStr !== tag &&
  17201. decodedTag.tagStr + 'of' !== tag) {
  17202. return buffer.error('Failed to match tag: "' + tag + '"');
  17203. }
  17204. if (decodedTag.primitive || len !== null)
  17205. return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
  17206. // Indefinite length... find END tag
  17207. const state = buffer.save();
  17208. const res = this._skipUntilEnd(
  17209. buffer,
  17210. 'Failed to skip indefinite length body: "' + this.tag + '"');
  17211. if (buffer.isError(res))
  17212. return res;
  17213. len = buffer.offset - state.offset;
  17214. buffer.restore(state);
  17215. return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
  17216. };
  17217. DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
  17218. for (;;) {
  17219. const tag = derDecodeTag(buffer, fail);
  17220. if (buffer.isError(tag))
  17221. return tag;
  17222. const len = derDecodeLen(buffer, tag.primitive, fail);
  17223. if (buffer.isError(len))
  17224. return len;
  17225. let res;
  17226. if (tag.primitive || len !== null)
  17227. res = buffer.skip(len);
  17228. else
  17229. res = this._skipUntilEnd(buffer, fail);
  17230. // Failure
  17231. if (buffer.isError(res))
  17232. return res;
  17233. if (tag.tagStr === 'end')
  17234. break;
  17235. }
  17236. };
  17237. DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
  17238. options) {
  17239. const result = [];
  17240. while (!buffer.isEmpty()) {
  17241. const possibleEnd = this._peekTag(buffer, 'end');
  17242. if (buffer.isError(possibleEnd))
  17243. return possibleEnd;
  17244. const res = decoder.decode(buffer, 'der', options);
  17245. if (buffer.isError(res) && possibleEnd)
  17246. break;
  17247. result.push(res);
  17248. }
  17249. return result;
  17250. };
  17251. DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
  17252. if (tag === 'bitstr') {
  17253. const unused = buffer.readUInt8();
  17254. if (buffer.isError(unused))
  17255. return unused;
  17256. return { unused: unused, data: buffer.raw() };
  17257. } else if (tag === 'bmpstr') {
  17258. const raw = buffer.raw();
  17259. if (raw.length % 2 === 1)
  17260. return buffer.error('Decoding of string type: bmpstr length mismatch');
  17261. let str = '';
  17262. for (let i = 0; i < raw.length / 2; i++) {
  17263. str += String.fromCharCode(raw.readUInt16BE(i * 2));
  17264. }
  17265. return str;
  17266. } else if (tag === 'numstr') {
  17267. const numstr = buffer.raw().toString('ascii');
  17268. if (!this._isNumstr(numstr)) {
  17269. return buffer.error('Decoding of string type: ' +
  17270. 'numstr unsupported characters');
  17271. }
  17272. return numstr;
  17273. } else if (tag === 'octstr') {
  17274. return buffer.raw();
  17275. } else if (tag === 'objDesc') {
  17276. return buffer.raw();
  17277. } else if (tag === 'printstr') {
  17278. const printstr = buffer.raw().toString('ascii');
  17279. if (!this._isPrintstr(printstr)) {
  17280. return buffer.error('Decoding of string type: ' +
  17281. 'printstr unsupported characters');
  17282. }
  17283. return printstr;
  17284. } else if (/str$/.test(tag)) {
  17285. return buffer.raw().toString();
  17286. } else {
  17287. return buffer.error('Decoding of string type: ' + tag + ' unsupported');
  17288. }
  17289. };
  17290. DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
  17291. let result;
  17292. const identifiers = [];
  17293. let ident = 0;
  17294. let subident = 0;
  17295. while (!buffer.isEmpty()) {
  17296. subident = buffer.readUInt8();
  17297. ident <<= 7;
  17298. ident |= subident & 0x7f;
  17299. if ((subident & 0x80) === 0) {
  17300. identifiers.push(ident);
  17301. ident = 0;
  17302. }
  17303. }
  17304. if (subident & 0x80)
  17305. identifiers.push(ident);
  17306. const first = (identifiers[0] / 40) | 0;
  17307. const second = identifiers[0] % 40;
  17308. if (relative)
  17309. result = identifiers;
  17310. else
  17311. result = [first, second].concat(identifiers.slice(1));
  17312. if (values) {
  17313. let tmp = values[result.join(' ')];
  17314. if (tmp === undefined)
  17315. tmp = values[result.join('.')];
  17316. if (tmp !== undefined)
  17317. result = tmp;
  17318. }
  17319. return result;
  17320. };
  17321. DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
  17322. const str = buffer.raw().toString();
  17323. let year;
  17324. let mon;
  17325. let day;
  17326. let hour;
  17327. let min;
  17328. let sec;
  17329. if (tag === 'gentime') {
  17330. year = str.slice(0, 4) | 0;
  17331. mon = str.slice(4, 6) | 0;
  17332. day = str.slice(6, 8) | 0;
  17333. hour = str.slice(8, 10) | 0;
  17334. min = str.slice(10, 12) | 0;
  17335. sec = str.slice(12, 14) | 0;
  17336. } else if (tag === 'utctime') {
  17337. year = str.slice(0, 2) | 0;
  17338. mon = str.slice(2, 4) | 0;
  17339. day = str.slice(4, 6) | 0;
  17340. hour = str.slice(6, 8) | 0;
  17341. min = str.slice(8, 10) | 0;
  17342. sec = str.slice(10, 12) | 0;
  17343. if (year < 70)
  17344. year = 2000 + year;
  17345. else
  17346. year = 1900 + year;
  17347. } else {
  17348. return buffer.error('Decoding ' + tag + ' time is not supported yet');
  17349. }
  17350. return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
  17351. };
  17352. DERNode.prototype._decodeNull = function decodeNull() {
  17353. return null;
  17354. };
  17355. DERNode.prototype._decodeBool = function decodeBool(buffer) {
  17356. const res = buffer.readUInt8();
  17357. if (buffer.isError(res))
  17358. return res;
  17359. else
  17360. return res !== 0;
  17361. };
  17362. DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
  17363. // Bigint, return as it is (assume big endian)
  17364. const raw = buffer.raw();
  17365. let res = new bignum(raw);
  17366. if (values)
  17367. res = values[res.toString(10)] || res;
  17368. return res;
  17369. };
  17370. DERNode.prototype._use = function use(entity, obj) {
  17371. if (typeof entity === 'function')
  17372. entity = entity(obj);
  17373. return entity._getDecoder('der').tree;
  17374. };
  17375. // Utility methods
  17376. function derDecodeTag(buf, fail) {
  17377. let tag = buf.readUInt8(fail);
  17378. if (buf.isError(tag))
  17379. return tag;
  17380. const cls = der.tagClass[tag >> 6];
  17381. const primitive = (tag & 0x20) === 0;
  17382. // Multi-octet tag - load
  17383. if ((tag & 0x1f) === 0x1f) {
  17384. let oct = tag;
  17385. tag = 0;
  17386. while ((oct & 0x80) === 0x80) {
  17387. oct = buf.readUInt8(fail);
  17388. if (buf.isError(oct))
  17389. return oct;
  17390. tag <<= 7;
  17391. tag |= oct & 0x7f;
  17392. }
  17393. } else {
  17394. tag &= 0x1f;
  17395. }
  17396. const tagStr = der.tag[tag];
  17397. return {
  17398. cls: cls,
  17399. primitive: primitive,
  17400. tag: tag,
  17401. tagStr: tagStr
  17402. };
  17403. }
  17404. function derDecodeLen(buf, primitive, fail) {
  17405. let len = buf.readUInt8(fail);
  17406. if (buf.isError(len))
  17407. return len;
  17408. // Indefinite form
  17409. if (!primitive && len === 0x80)
  17410. return null;
  17411. // Definite form
  17412. if ((len & 0x80) === 0) {
  17413. // Short form
  17414. return len;
  17415. }
  17416. // Long form
  17417. const num = len & 0x7f;
  17418. if (num > 4)
  17419. return buf.error('length octect is too long');
  17420. len = 0;
  17421. for (let i = 0; i < num; i++) {
  17422. len <<= 8;
  17423. const j = buf.readUInt8(fail);
  17424. if (buf.isError(j))
  17425. return j;
  17426. len |= j;
  17427. }
  17428. return len;
  17429. }
  17430. },{"../base/buffer":85,"../base/node":87,"../constants/der":89,"bn.js":97,"inherits":320}],92:[function(require,module,exports){
  17431. 'use strict';
  17432. const decoders = exports;
  17433. decoders.der = require('./der');
  17434. decoders.pem = require('./pem');
  17435. },{"./der":91,"./pem":93}],93:[function(require,module,exports){
  17436. 'use strict';
  17437. const inherits = require('inherits');
  17438. const Buffer = require('safer-buffer').Buffer;
  17439. const DERDecoder = require('./der');
  17440. function PEMDecoder(entity) {
  17441. DERDecoder.call(this, entity);
  17442. this.enc = 'pem';
  17443. }
  17444. inherits(PEMDecoder, DERDecoder);
  17445. module.exports = PEMDecoder;
  17446. PEMDecoder.prototype.decode = function decode(data, options) {
  17447. const lines = data.toString().split(/[\r\n]+/g);
  17448. const label = options.label.toUpperCase();
  17449. const re = /^-----(BEGIN|END) ([^-]+)-----$/;
  17450. let start = -1;
  17451. let end = -1;
  17452. for (let i = 0; i < lines.length; i++) {
  17453. const match = lines[i].match(re);
  17454. if (match === null)
  17455. continue;
  17456. if (match[2] !== label)
  17457. continue;
  17458. if (start === -1) {
  17459. if (match[1] !== 'BEGIN')
  17460. break;
  17461. start = i;
  17462. } else {
  17463. if (match[1] !== 'END')
  17464. break;
  17465. end = i;
  17466. break;
  17467. }
  17468. }
  17469. if (start === -1 || end === -1)
  17470. throw new Error('PEM section not found for: ' + label);
  17471. const base64 = lines.slice(start + 1, end).join('');
  17472. // Remove excessive symbols
  17473. base64.replace(/[^a-z0-9+/=]+/gi, '');
  17474. const input = Buffer.from(base64, 'base64');
  17475. return DERDecoder.prototype.decode.call(this, input, options);
  17476. };
  17477. },{"./der":91,"inherits":320,"safer-buffer":562}],94:[function(require,module,exports){
  17478. 'use strict';
  17479. const inherits = require('inherits');
  17480. const Buffer = require('safer-buffer').Buffer;
  17481. const Node = require('../base/node');
  17482. // Import DER constants
  17483. const der = require('../constants/der');
  17484. function DEREncoder(entity) {
  17485. this.enc = 'der';
  17486. this.name = entity.name;
  17487. this.entity = entity;
  17488. // Construct base tree
  17489. this.tree = new DERNode();
  17490. this.tree._init(entity.body);
  17491. }
  17492. module.exports = DEREncoder;
  17493. DEREncoder.prototype.encode = function encode(data, reporter) {
  17494. return this.tree._encode(data, reporter).join();
  17495. };
  17496. // Tree methods
  17497. function DERNode(parent) {
  17498. Node.call(this, 'der', parent);
  17499. }
  17500. inherits(DERNode, Node);
  17501. DERNode.prototype._encodeComposite = function encodeComposite(tag,
  17502. primitive,
  17503. cls,
  17504. content) {
  17505. const encodedTag = encodeTag(tag, primitive, cls, this.reporter);
  17506. // Short form
  17507. if (content.length < 0x80) {
  17508. const header = Buffer.alloc(2);
  17509. header[0] = encodedTag;
  17510. header[1] = content.length;
  17511. return this._createEncoderBuffer([ header, content ]);
  17512. }
  17513. // Long form
  17514. // Count octets required to store length
  17515. let lenOctets = 1;
  17516. for (let i = content.length; i >= 0x100; i >>= 8)
  17517. lenOctets++;
  17518. const header = Buffer.alloc(1 + 1 + lenOctets);
  17519. header[0] = encodedTag;
  17520. header[1] = 0x80 | lenOctets;
  17521. for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
  17522. header[i] = j & 0xff;
  17523. return this._createEncoderBuffer([ header, content ]);
  17524. };
  17525. DERNode.prototype._encodeStr = function encodeStr(str, tag) {
  17526. if (tag === 'bitstr') {
  17527. return this._createEncoderBuffer([ str.unused | 0, str.data ]);
  17528. } else if (tag === 'bmpstr') {
  17529. const buf = Buffer.alloc(str.length * 2);
  17530. for (let i = 0; i < str.length; i++) {
  17531. buf.writeUInt16BE(str.charCodeAt(i), i * 2);
  17532. }
  17533. return this._createEncoderBuffer(buf);
  17534. } else if (tag === 'numstr') {
  17535. if (!this._isNumstr(str)) {
  17536. return this.reporter.error('Encoding of string type: numstr supports ' +
  17537. 'only digits and space');
  17538. }
  17539. return this._createEncoderBuffer(str);
  17540. } else if (tag === 'printstr') {
  17541. if (!this._isPrintstr(str)) {
  17542. return this.reporter.error('Encoding of string type: printstr supports ' +
  17543. 'only latin upper and lower case letters, ' +
  17544. 'digits, space, apostrophe, left and rigth ' +
  17545. 'parenthesis, plus sign, comma, hyphen, ' +
  17546. 'dot, slash, colon, equal sign, ' +
  17547. 'question mark');
  17548. }
  17549. return this._createEncoderBuffer(str);
  17550. } else if (/str$/.test(tag)) {
  17551. return this._createEncoderBuffer(str);
  17552. } else if (tag === 'objDesc') {
  17553. return this._createEncoderBuffer(str);
  17554. } else {
  17555. return this.reporter.error('Encoding of string type: ' + tag +
  17556. ' unsupported');
  17557. }
  17558. };
  17559. DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
  17560. if (typeof id === 'string') {
  17561. if (!values)
  17562. return this.reporter.error('string objid given, but no values map found');
  17563. if (!values.hasOwnProperty(id))
  17564. return this.reporter.error('objid not found in values map');
  17565. id = values[id].split(/[\s.]+/g);
  17566. for (let i = 0; i < id.length; i++)
  17567. id[i] |= 0;
  17568. } else if (Array.isArray(id)) {
  17569. id = id.slice();
  17570. for (let i = 0; i < id.length; i++)
  17571. id[i] |= 0;
  17572. }
  17573. if (!Array.isArray(id)) {
  17574. return this.reporter.error('objid() should be either array or string, ' +
  17575. 'got: ' + JSON.stringify(id));
  17576. }
  17577. if (!relative) {
  17578. if (id[1] >= 40)
  17579. return this.reporter.error('Second objid identifier OOB');
  17580. id.splice(0, 2, id[0] * 40 + id[1]);
  17581. }
  17582. // Count number of octets
  17583. let size = 0;
  17584. for (let i = 0; i < id.length; i++) {
  17585. let ident = id[i];
  17586. for (size++; ident >= 0x80; ident >>= 7)
  17587. size++;
  17588. }
  17589. const objid = Buffer.alloc(size);
  17590. let offset = objid.length - 1;
  17591. for (let i = id.length - 1; i >= 0; i--) {
  17592. let ident = id[i];
  17593. objid[offset--] = ident & 0x7f;
  17594. while ((ident >>= 7) > 0)
  17595. objid[offset--] = 0x80 | (ident & 0x7f);
  17596. }
  17597. return this._createEncoderBuffer(objid);
  17598. };
  17599. function two(num) {
  17600. if (num < 10)
  17601. return '0' + num;
  17602. else
  17603. return num;
  17604. }
  17605. DERNode.prototype._encodeTime = function encodeTime(time, tag) {
  17606. let str;
  17607. const date = new Date(time);
  17608. if (tag === 'gentime') {
  17609. str = [
  17610. two(date.getUTCFullYear()),
  17611. two(date.getUTCMonth() + 1),
  17612. two(date.getUTCDate()),
  17613. two(date.getUTCHours()),
  17614. two(date.getUTCMinutes()),
  17615. two(date.getUTCSeconds()),
  17616. 'Z'
  17617. ].join('');
  17618. } else if (tag === 'utctime') {
  17619. str = [
  17620. two(date.getUTCFullYear() % 100),
  17621. two(date.getUTCMonth() + 1),
  17622. two(date.getUTCDate()),
  17623. two(date.getUTCHours()),
  17624. two(date.getUTCMinutes()),
  17625. two(date.getUTCSeconds()),
  17626. 'Z'
  17627. ].join('');
  17628. } else {
  17629. this.reporter.error('Encoding ' + tag + ' time is not supported yet');
  17630. }
  17631. return this._encodeStr(str, 'octstr');
  17632. };
  17633. DERNode.prototype._encodeNull = function encodeNull() {
  17634. return this._createEncoderBuffer('');
  17635. };
  17636. DERNode.prototype._encodeInt = function encodeInt(num, values) {
  17637. if (typeof num === 'string') {
  17638. if (!values)
  17639. return this.reporter.error('String int or enum given, but no values map');
  17640. if (!values.hasOwnProperty(num)) {
  17641. return this.reporter.error('Values map doesn\'t contain: ' +
  17642. JSON.stringify(num));
  17643. }
  17644. num = values[num];
  17645. }
  17646. // Bignum, assume big endian
  17647. if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
  17648. const numArray = num.toArray();
  17649. if (!num.sign && numArray[0] & 0x80) {
  17650. numArray.unshift(0);
  17651. }
  17652. num = Buffer.from(numArray);
  17653. }
  17654. if (Buffer.isBuffer(num)) {
  17655. let size = num.length;
  17656. if (num.length === 0)
  17657. size++;
  17658. const out = Buffer.alloc(size);
  17659. num.copy(out);
  17660. if (num.length === 0)
  17661. out[0] = 0;
  17662. return this._createEncoderBuffer(out);
  17663. }
  17664. if (num < 0x80)
  17665. return this._createEncoderBuffer(num);
  17666. if (num < 0x100)
  17667. return this._createEncoderBuffer([0, num]);
  17668. let size = 1;
  17669. for (let i = num; i >= 0x100; i >>= 8)
  17670. size++;
  17671. const out = new Array(size);
  17672. for (let i = out.length - 1; i >= 0; i--) {
  17673. out[i] = num & 0xff;
  17674. num >>= 8;
  17675. }
  17676. if(out[0] & 0x80) {
  17677. out.unshift(0);
  17678. }
  17679. return this._createEncoderBuffer(Buffer.from(out));
  17680. };
  17681. DERNode.prototype._encodeBool = function encodeBool(value) {
  17682. return this._createEncoderBuffer(value ? 0xff : 0);
  17683. };
  17684. DERNode.prototype._use = function use(entity, obj) {
  17685. if (typeof entity === 'function')
  17686. entity = entity(obj);
  17687. return entity._getEncoder('der').tree;
  17688. };
  17689. DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
  17690. const state = this._baseState;
  17691. let i;
  17692. if (state['default'] === null)
  17693. return false;
  17694. const data = dataBuffer.join();
  17695. if (state.defaultBuffer === undefined)
  17696. state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
  17697. if (data.length !== state.defaultBuffer.length)
  17698. return false;
  17699. for (i=0; i < data.length; i++)
  17700. if (data[i] !== state.defaultBuffer[i])
  17701. return false;
  17702. return true;
  17703. };
  17704. // Utility methods
  17705. function encodeTag(tag, primitive, cls, reporter) {
  17706. let res;
  17707. if (tag === 'seqof')
  17708. tag = 'seq';
  17709. else if (tag === 'setof')
  17710. tag = 'set';
  17711. if (der.tagByName.hasOwnProperty(tag))
  17712. res = der.tagByName[tag];
  17713. else if (typeof tag === 'number' && (tag | 0) === tag)
  17714. res = tag;
  17715. else
  17716. return reporter.error('Unknown tag: ' + tag);
  17717. if (res >= 0x1f)
  17718. return reporter.error('Multi-octet tag encoding unsupported');
  17719. if (!primitive)
  17720. res |= 0x20;
  17721. res |= (der.tagClassByName[cls || 'universal'] << 6);
  17722. return res;
  17723. }
  17724. },{"../base/node":87,"../constants/der":89,"inherits":320,"safer-buffer":562}],95:[function(require,module,exports){
  17725. 'use strict';
  17726. const encoders = exports;
  17727. encoders.der = require('./der');
  17728. encoders.pem = require('./pem');
  17729. },{"./der":94,"./pem":96}],96:[function(require,module,exports){
  17730. 'use strict';
  17731. const inherits = require('inherits');
  17732. const DEREncoder = require('./der');
  17733. function PEMEncoder(entity) {
  17734. DEREncoder.call(this, entity);
  17735. this.enc = 'pem';
  17736. }
  17737. inherits(PEMEncoder, DEREncoder);
  17738. module.exports = PEMEncoder;
  17739. PEMEncoder.prototype.encode = function encode(data, options) {
  17740. const buf = DEREncoder.prototype.encode.call(this, data);
  17741. const p = buf.toString('base64');
  17742. const out = [ '-----BEGIN ' + options.label + '-----' ];
  17743. for (let i = 0; i < p.length; i += 64)
  17744. out.push(p.slice(i, i + 64));
  17745. out.push('-----END ' + options.label + '-----');
  17746. return out.join('\n');
  17747. };
  17748. },{"./der":94,"inherits":320}],97:[function(require,module,exports){
  17749. (function (module, exports) {
  17750. 'use strict';
  17751. // Utils
  17752. function assert (val, msg) {
  17753. if (!val) throw new Error(msg || 'Assertion failed');
  17754. }
  17755. // Could use `inherits` module, but don't want to move from single file
  17756. // architecture yet.
  17757. function inherits (ctor, superCtor) {
  17758. ctor.super_ = superCtor;
  17759. var TempCtor = function () {};
  17760. TempCtor.prototype = superCtor.prototype;
  17761. ctor.prototype = new TempCtor();
  17762. ctor.prototype.constructor = ctor;
  17763. }
  17764. // BN
  17765. function BN (number, base, endian) {
  17766. if (BN.isBN(number)) {
  17767. return number;
  17768. }
  17769. this.negative = 0;
  17770. this.words = null;
  17771. this.length = 0;
  17772. // Reduction context
  17773. this.red = null;
  17774. if (number !== null) {
  17775. if (base === 'le' || base === 'be') {
  17776. endian = base;
  17777. base = 10;
  17778. }
  17779. this._init(number || 0, base || 10, endian || 'be');
  17780. }
  17781. }
  17782. if (typeof module === 'object') {
  17783. module.exports = BN;
  17784. } else {
  17785. exports.BN = BN;
  17786. }
  17787. BN.BN = BN;
  17788. BN.wordSize = 26;
  17789. var Buffer;
  17790. try {
  17791. Buffer = require('buffer').Buffer;
  17792. } catch (e) {
  17793. }
  17794. BN.isBN = function isBN (num) {
  17795. if (num instanceof BN) {
  17796. return true;
  17797. }
  17798. return num !== null && typeof num === 'object' &&
  17799. num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  17800. };
  17801. BN.max = function max (left, right) {
  17802. if (left.cmp(right) > 0) return left;
  17803. return right;
  17804. };
  17805. BN.min = function min (left, right) {
  17806. if (left.cmp(right) < 0) return left;
  17807. return right;
  17808. };
  17809. BN.prototype._init = function init (number, base, endian) {
  17810. if (typeof number === 'number') {
  17811. return this._initNumber(number, base, endian);
  17812. }
  17813. if (typeof number === 'object') {
  17814. return this._initArray(number, base, endian);
  17815. }
  17816. if (base === 'hex') {
  17817. base = 16;
  17818. }
  17819. assert(base === (base | 0) && base >= 2 && base <= 36);
  17820. number = number.toString().replace(/\s+/g, '');
  17821. var start = 0;
  17822. if (number[0] === '-') {
  17823. start++;
  17824. }
  17825. if (base === 16) {
  17826. this._parseHex(number, start);
  17827. } else {
  17828. this._parseBase(number, base, start);
  17829. }
  17830. if (number[0] === '-') {
  17831. this.negative = 1;
  17832. }
  17833. this.strip();
  17834. if (endian !== 'le') return;
  17835. this._initArray(this.toArray(), base, endian);
  17836. };
  17837. BN.prototype._initNumber = function _initNumber (number, base, endian) {
  17838. if (number < 0) {
  17839. this.negative = 1;
  17840. number = -number;
  17841. }
  17842. if (number < 0x4000000) {
  17843. this.words = [ number & 0x3ffffff ];
  17844. this.length = 1;
  17845. } else if (number < 0x10000000000000) {
  17846. this.words = [
  17847. number & 0x3ffffff,
  17848. (number / 0x4000000) & 0x3ffffff
  17849. ];
  17850. this.length = 2;
  17851. } else {
  17852. assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
  17853. this.words = [
  17854. number & 0x3ffffff,
  17855. (number / 0x4000000) & 0x3ffffff,
  17856. 1
  17857. ];
  17858. this.length = 3;
  17859. }
  17860. if (endian !== 'le') return;
  17861. // Reverse the bytes
  17862. this._initArray(this.toArray(), base, endian);
  17863. };
  17864. BN.prototype._initArray = function _initArray (number, base, endian) {
  17865. // Perhaps a Uint8Array
  17866. assert(typeof number.length === 'number');
  17867. if (number.length <= 0) {
  17868. this.words = [ 0 ];
  17869. this.length = 1;
  17870. return this;
  17871. }
  17872. this.length = Math.ceil(number.length / 3);
  17873. this.words = new Array(this.length);
  17874. for (var i = 0; i < this.length; i++) {
  17875. this.words[i] = 0;
  17876. }
  17877. var j, w;
  17878. var off = 0;
  17879. if (endian === 'be') {
  17880. for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
  17881. w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
  17882. this.words[j] |= (w << off) & 0x3ffffff;
  17883. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  17884. off += 24;
  17885. if (off >= 26) {
  17886. off -= 26;
  17887. j++;
  17888. }
  17889. }
  17890. } else if (endian === 'le') {
  17891. for (i = 0, j = 0; i < number.length; i += 3) {
  17892. w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
  17893. this.words[j] |= (w << off) & 0x3ffffff;
  17894. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  17895. off += 24;
  17896. if (off >= 26) {
  17897. off -= 26;
  17898. j++;
  17899. }
  17900. }
  17901. }
  17902. return this.strip();
  17903. };
  17904. function parseHex (str, start, end) {
  17905. var r = 0;
  17906. var len = Math.min(str.length, end);
  17907. for (var i = start; i < len; i++) {
  17908. var c = str.charCodeAt(i) - 48;
  17909. r <<= 4;
  17910. // 'a' - 'f'
  17911. if (c >= 49 && c <= 54) {
  17912. r |= c - 49 + 0xa;
  17913. // 'A' - 'F'
  17914. } else if (c >= 17 && c <= 22) {
  17915. r |= c - 17 + 0xa;
  17916. // '0' - '9'
  17917. } else {
  17918. r |= c & 0xf;
  17919. }
  17920. }
  17921. return r;
  17922. }
  17923. BN.prototype._parseHex = function _parseHex (number, start) {
  17924. // Create possibly bigger array to ensure that it fits the number
  17925. this.length = Math.ceil((number.length - start) / 6);
  17926. this.words = new Array(this.length);
  17927. for (var i = 0; i < this.length; i++) {
  17928. this.words[i] = 0;
  17929. }
  17930. var j, w;
  17931. // Scan 24-bit chunks and add them to the number
  17932. var off = 0;
  17933. for (i = number.length - 6, j = 0; i >= start; i -= 6) {
  17934. w = parseHex(number, i, i + 6);
  17935. this.words[j] |= (w << off) & 0x3ffffff;
  17936. // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
  17937. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  17938. off += 24;
  17939. if (off >= 26) {
  17940. off -= 26;
  17941. j++;
  17942. }
  17943. }
  17944. if (i + 6 !== start) {
  17945. w = parseHex(number, start, i + 6);
  17946. this.words[j] |= (w << off) & 0x3ffffff;
  17947. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  17948. }
  17949. this.strip();
  17950. };
  17951. function parseBase (str, start, end, mul) {
  17952. var r = 0;
  17953. var len = Math.min(str.length, end);
  17954. for (var i = start; i < len; i++) {
  17955. var c = str.charCodeAt(i) - 48;
  17956. r *= mul;
  17957. // 'a'
  17958. if (c >= 49) {
  17959. r += c - 49 + 0xa;
  17960. // 'A'
  17961. } else if (c >= 17) {
  17962. r += c - 17 + 0xa;
  17963. // '0' - '9'
  17964. } else {
  17965. r += c;
  17966. }
  17967. }
  17968. return r;
  17969. }
  17970. BN.prototype._parseBase = function _parseBase (number, base, start) {
  17971. // Initialize as zero
  17972. this.words = [ 0 ];
  17973. this.length = 1;
  17974. // Find length of limb in base
  17975. for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
  17976. limbLen++;
  17977. }
  17978. limbLen--;
  17979. limbPow = (limbPow / base) | 0;
  17980. var total = number.length - start;
  17981. var mod = total % limbLen;
  17982. var end = Math.min(total, total - mod) + start;
  17983. var word = 0;
  17984. for (var i = start; i < end; i += limbLen) {
  17985. word = parseBase(number, i, i + limbLen, base);
  17986. this.imuln(limbPow);
  17987. if (this.words[0] + word < 0x4000000) {
  17988. this.words[0] += word;
  17989. } else {
  17990. this._iaddn(word);
  17991. }
  17992. }
  17993. if (mod !== 0) {
  17994. var pow = 1;
  17995. word = parseBase(number, i, number.length, base);
  17996. for (i = 0; i < mod; i++) {
  17997. pow *= base;
  17998. }
  17999. this.imuln(pow);
  18000. if (this.words[0] + word < 0x4000000) {
  18001. this.words[0] += word;
  18002. } else {
  18003. this._iaddn(word);
  18004. }
  18005. }
  18006. };
  18007. BN.prototype.copy = function copy (dest) {
  18008. dest.words = new Array(this.length);
  18009. for (var i = 0; i < this.length; i++) {
  18010. dest.words[i] = this.words[i];
  18011. }
  18012. dest.length = this.length;
  18013. dest.negative = this.negative;
  18014. dest.red = this.red;
  18015. };
  18016. BN.prototype.clone = function clone () {
  18017. var r = new BN(null);
  18018. this.copy(r);
  18019. return r;
  18020. };
  18021. BN.prototype._expand = function _expand (size) {
  18022. while (this.length < size) {
  18023. this.words[this.length++] = 0;
  18024. }
  18025. return this;
  18026. };
  18027. // Remove leading `0` from `this`
  18028. BN.prototype.strip = function strip () {
  18029. while (this.length > 1 && this.words[this.length - 1] === 0) {
  18030. this.length--;
  18031. }
  18032. return this._normSign();
  18033. };
  18034. BN.prototype._normSign = function _normSign () {
  18035. // -0 = 0
  18036. if (this.length === 1 && this.words[0] === 0) {
  18037. this.negative = 0;
  18038. }
  18039. return this;
  18040. };
  18041. BN.prototype.inspect = function inspect () {
  18042. return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  18043. };
  18044. /*
  18045. var zeros = [];
  18046. var groupSizes = [];
  18047. var groupBases = [];
  18048. var s = '';
  18049. var i = -1;
  18050. while (++i < BN.wordSize) {
  18051. zeros[i] = s;
  18052. s += '0';
  18053. }
  18054. groupSizes[0] = 0;
  18055. groupSizes[1] = 0;
  18056. groupBases[0] = 0;
  18057. groupBases[1] = 0;
  18058. var base = 2 - 1;
  18059. while (++base < 36 + 1) {
  18060. var groupSize = 0;
  18061. var groupBase = 1;
  18062. while (groupBase < (1 << BN.wordSize) / base) {
  18063. groupBase *= base;
  18064. groupSize += 1;
  18065. }
  18066. groupSizes[base] = groupSize;
  18067. groupBases[base] = groupBase;
  18068. }
  18069. */
  18070. var zeros = [
  18071. '',
  18072. '0',
  18073. '00',
  18074. '000',
  18075. '0000',
  18076. '00000',
  18077. '000000',
  18078. '0000000',
  18079. '00000000',
  18080. '000000000',
  18081. '0000000000',
  18082. '00000000000',
  18083. '000000000000',
  18084. '0000000000000',
  18085. '00000000000000',
  18086. '000000000000000',
  18087. '0000000000000000',
  18088. '00000000000000000',
  18089. '000000000000000000',
  18090. '0000000000000000000',
  18091. '00000000000000000000',
  18092. '000000000000000000000',
  18093. '0000000000000000000000',
  18094. '00000000000000000000000',
  18095. '000000000000000000000000',
  18096. '0000000000000000000000000'
  18097. ];
  18098. var groupSizes = [
  18099. 0, 0,
  18100. 25, 16, 12, 11, 10, 9, 8,
  18101. 8, 7, 7, 7, 7, 6, 6,
  18102. 6, 6, 6, 6, 6, 5, 5,
  18103. 5, 5, 5, 5, 5, 5, 5,
  18104. 5, 5, 5, 5, 5, 5, 5
  18105. ];
  18106. var groupBases = [
  18107. 0, 0,
  18108. 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
  18109. 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
  18110. 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
  18111. 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
  18112. 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  18113. ];
  18114. BN.prototype.toString = function toString (base, padding) {
  18115. base = base || 10;
  18116. padding = padding | 0 || 1;
  18117. var out;
  18118. if (base === 16 || base === 'hex') {
  18119. out = '';
  18120. var off = 0;
  18121. var carry = 0;
  18122. for (var i = 0; i < this.length; i++) {
  18123. var w = this.words[i];
  18124. var word = (((w << off) | carry) & 0xffffff).toString(16);
  18125. carry = (w >>> (24 - off)) & 0xffffff;
  18126. if (carry !== 0 || i !== this.length - 1) {
  18127. out = zeros[6 - word.length] + word + out;
  18128. } else {
  18129. out = word + out;
  18130. }
  18131. off += 2;
  18132. if (off >= 26) {
  18133. off -= 26;
  18134. i--;
  18135. }
  18136. }
  18137. if (carry !== 0) {
  18138. out = carry.toString(16) + out;
  18139. }
  18140. while (out.length % padding !== 0) {
  18141. out = '0' + out;
  18142. }
  18143. if (this.negative !== 0) {
  18144. out = '-' + out;
  18145. }
  18146. return out;
  18147. }
  18148. if (base === (base | 0) && base >= 2 && base <= 36) {
  18149. // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
  18150. var groupSize = groupSizes[base];
  18151. // var groupBase = Math.pow(base, groupSize);
  18152. var groupBase = groupBases[base];
  18153. out = '';
  18154. var c = this.clone();
  18155. c.negative = 0;
  18156. while (!c.isZero()) {
  18157. var r = c.modn(groupBase).toString(base);
  18158. c = c.idivn(groupBase);
  18159. if (!c.isZero()) {
  18160. out = zeros[groupSize - r.length] + r + out;
  18161. } else {
  18162. out = r + out;
  18163. }
  18164. }
  18165. if (this.isZero()) {
  18166. out = '0' + out;
  18167. }
  18168. while (out.length % padding !== 0) {
  18169. out = '0' + out;
  18170. }
  18171. if (this.negative !== 0) {
  18172. out = '-' + out;
  18173. }
  18174. return out;
  18175. }
  18176. assert(false, 'Base should be between 2 and 36');
  18177. };
  18178. BN.prototype.toNumber = function toNumber () {
  18179. var ret = this.words[0];
  18180. if (this.length === 2) {
  18181. ret += this.words[1] * 0x4000000;
  18182. } else if (this.length === 3 && this.words[2] === 0x01) {
  18183. // NOTE: at this stage it is known that the top bit is set
  18184. ret += 0x10000000000000 + (this.words[1] * 0x4000000);
  18185. } else if (this.length > 2) {
  18186. assert(false, 'Number can only safely store up to 53 bits');
  18187. }
  18188. return (this.negative !== 0) ? -ret : ret;
  18189. };
  18190. BN.prototype.toJSON = function toJSON () {
  18191. return this.toString(16);
  18192. };
  18193. BN.prototype.toBuffer = function toBuffer (endian, length) {
  18194. assert(typeof Buffer !== 'undefined');
  18195. return this.toArrayLike(Buffer, endian, length);
  18196. };
  18197. BN.prototype.toArray = function toArray (endian, length) {
  18198. return this.toArrayLike(Array, endian, length);
  18199. };
  18200. BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
  18201. var byteLength = this.byteLength();
  18202. var reqLength = length || Math.max(1, byteLength);
  18203. assert(byteLength <= reqLength, 'byte array longer than desired length');
  18204. assert(reqLength > 0, 'Requested array length <= 0');
  18205. this.strip();
  18206. var littleEndian = endian === 'le';
  18207. var res = new ArrayType(reqLength);
  18208. var b, i;
  18209. var q = this.clone();
  18210. if (!littleEndian) {
  18211. // Assume big-endian
  18212. for (i = 0; i < reqLength - byteLength; i++) {
  18213. res[i] = 0;
  18214. }
  18215. for (i = 0; !q.isZero(); i++) {
  18216. b = q.andln(0xff);
  18217. q.iushrn(8);
  18218. res[reqLength - i - 1] = b;
  18219. }
  18220. } else {
  18221. for (i = 0; !q.isZero(); i++) {
  18222. b = q.andln(0xff);
  18223. q.iushrn(8);
  18224. res[i] = b;
  18225. }
  18226. for (; i < reqLength; i++) {
  18227. res[i] = 0;
  18228. }
  18229. }
  18230. return res;
  18231. };
  18232. if (Math.clz32) {
  18233. BN.prototype._countBits = function _countBits (w) {
  18234. return 32 - Math.clz32(w);
  18235. };
  18236. } else {
  18237. BN.prototype._countBits = function _countBits (w) {
  18238. var t = w;
  18239. var r = 0;
  18240. if (t >= 0x1000) {
  18241. r += 13;
  18242. t >>>= 13;
  18243. }
  18244. if (t >= 0x40) {
  18245. r += 7;
  18246. t >>>= 7;
  18247. }
  18248. if (t >= 0x8) {
  18249. r += 4;
  18250. t >>>= 4;
  18251. }
  18252. if (t >= 0x02) {
  18253. r += 2;
  18254. t >>>= 2;
  18255. }
  18256. return r + t;
  18257. };
  18258. }
  18259. BN.prototype._zeroBits = function _zeroBits (w) {
  18260. // Short-cut
  18261. if (w === 0) return 26;
  18262. var t = w;
  18263. var r = 0;
  18264. if ((t & 0x1fff) === 0) {
  18265. r += 13;
  18266. t >>>= 13;
  18267. }
  18268. if ((t & 0x7f) === 0) {
  18269. r += 7;
  18270. t >>>= 7;
  18271. }
  18272. if ((t & 0xf) === 0) {
  18273. r += 4;
  18274. t >>>= 4;
  18275. }
  18276. if ((t & 0x3) === 0) {
  18277. r += 2;
  18278. t >>>= 2;
  18279. }
  18280. if ((t & 0x1) === 0) {
  18281. r++;
  18282. }
  18283. return r;
  18284. };
  18285. // Return number of used bits in a BN
  18286. BN.prototype.bitLength = function bitLength () {
  18287. var w = this.words[this.length - 1];
  18288. var hi = this._countBits(w);
  18289. return (this.length - 1) * 26 + hi;
  18290. };
  18291. function toBitArray (num) {
  18292. var w = new Array(num.bitLength());
  18293. for (var bit = 0; bit < w.length; bit++) {
  18294. var off = (bit / 26) | 0;
  18295. var wbit = bit % 26;
  18296. w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
  18297. }
  18298. return w;
  18299. }
  18300. // Number of trailing zero bits
  18301. BN.prototype.zeroBits = function zeroBits () {
  18302. if (this.isZero()) return 0;
  18303. var r = 0;
  18304. for (var i = 0; i < this.length; i++) {
  18305. var b = this._zeroBits(this.words[i]);
  18306. r += b;
  18307. if (b !== 26) break;
  18308. }
  18309. return r;
  18310. };
  18311. BN.prototype.byteLength = function byteLength () {
  18312. return Math.ceil(this.bitLength() / 8);
  18313. };
  18314. BN.prototype.toTwos = function toTwos (width) {
  18315. if (this.negative !== 0) {
  18316. return this.abs().inotn(width).iaddn(1);
  18317. }
  18318. return this.clone();
  18319. };
  18320. BN.prototype.fromTwos = function fromTwos (width) {
  18321. if (this.testn(width - 1)) {
  18322. return this.notn(width).iaddn(1).ineg();
  18323. }
  18324. return this.clone();
  18325. };
  18326. BN.prototype.isNeg = function isNeg () {
  18327. return this.negative !== 0;
  18328. };
  18329. // Return negative clone of `this`
  18330. BN.prototype.neg = function neg () {
  18331. return this.clone().ineg();
  18332. };
  18333. BN.prototype.ineg = function ineg () {
  18334. if (!this.isZero()) {
  18335. this.negative ^= 1;
  18336. }
  18337. return this;
  18338. };
  18339. // Or `num` with `this` in-place
  18340. BN.prototype.iuor = function iuor (num) {
  18341. while (this.length < num.length) {
  18342. this.words[this.length++] = 0;
  18343. }
  18344. for (var i = 0; i < num.length; i++) {
  18345. this.words[i] = this.words[i] | num.words[i];
  18346. }
  18347. return this.strip();
  18348. };
  18349. BN.prototype.ior = function ior (num) {
  18350. assert((this.negative | num.negative) === 0);
  18351. return this.iuor(num);
  18352. };
  18353. // Or `num` with `this`
  18354. BN.prototype.or = function or (num) {
  18355. if (this.length > num.length) return this.clone().ior(num);
  18356. return num.clone().ior(this);
  18357. };
  18358. BN.prototype.uor = function uor (num) {
  18359. if (this.length > num.length) return this.clone().iuor(num);
  18360. return num.clone().iuor(this);
  18361. };
  18362. // And `num` with `this` in-place
  18363. BN.prototype.iuand = function iuand (num) {
  18364. // b = min-length(num, this)
  18365. var b;
  18366. if (this.length > num.length) {
  18367. b = num;
  18368. } else {
  18369. b = this;
  18370. }
  18371. for (var i = 0; i < b.length; i++) {
  18372. this.words[i] = this.words[i] & num.words[i];
  18373. }
  18374. this.length = b.length;
  18375. return this.strip();
  18376. };
  18377. BN.prototype.iand = function iand (num) {
  18378. assert((this.negative | num.negative) === 0);
  18379. return this.iuand(num);
  18380. };
  18381. // And `num` with `this`
  18382. BN.prototype.and = function and (num) {
  18383. if (this.length > num.length) return this.clone().iand(num);
  18384. return num.clone().iand(this);
  18385. };
  18386. BN.prototype.uand = function uand (num) {
  18387. if (this.length > num.length) return this.clone().iuand(num);
  18388. return num.clone().iuand(this);
  18389. };
  18390. // Xor `num` with `this` in-place
  18391. BN.prototype.iuxor = function iuxor (num) {
  18392. // a.length > b.length
  18393. var a;
  18394. var b;
  18395. if (this.length > num.length) {
  18396. a = this;
  18397. b = num;
  18398. } else {
  18399. a = num;
  18400. b = this;
  18401. }
  18402. for (var i = 0; i < b.length; i++) {
  18403. this.words[i] = a.words[i] ^ b.words[i];
  18404. }
  18405. if (this !== a) {
  18406. for (; i < a.length; i++) {
  18407. this.words[i] = a.words[i];
  18408. }
  18409. }
  18410. this.length = a.length;
  18411. return this.strip();
  18412. };
  18413. BN.prototype.ixor = function ixor (num) {
  18414. assert((this.negative | num.negative) === 0);
  18415. return this.iuxor(num);
  18416. };
  18417. // Xor `num` with `this`
  18418. BN.prototype.xor = function xor (num) {
  18419. if (this.length > num.length) return this.clone().ixor(num);
  18420. return num.clone().ixor(this);
  18421. };
  18422. BN.prototype.uxor = function uxor (num) {
  18423. if (this.length > num.length) return this.clone().iuxor(num);
  18424. return num.clone().iuxor(this);
  18425. };
  18426. // Not ``this`` with ``width`` bitwidth
  18427. BN.prototype.inotn = function inotn (width) {
  18428. assert(typeof width === 'number' && width >= 0);
  18429. var bytesNeeded = Math.ceil(width / 26) | 0;
  18430. var bitsLeft = width % 26;
  18431. // Extend the buffer with leading zeroes
  18432. this._expand(bytesNeeded);
  18433. if (bitsLeft > 0) {
  18434. bytesNeeded--;
  18435. }
  18436. // Handle complete words
  18437. for (var i = 0; i < bytesNeeded; i++) {
  18438. this.words[i] = ~this.words[i] & 0x3ffffff;
  18439. }
  18440. // Handle the residue
  18441. if (bitsLeft > 0) {
  18442. this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
  18443. }
  18444. // And remove leading zeroes
  18445. return this.strip();
  18446. };
  18447. BN.prototype.notn = function notn (width) {
  18448. return this.clone().inotn(width);
  18449. };
  18450. // Set `bit` of `this`
  18451. BN.prototype.setn = function setn (bit, val) {
  18452. assert(typeof bit === 'number' && bit >= 0);
  18453. var off = (bit / 26) | 0;
  18454. var wbit = bit % 26;
  18455. this._expand(off + 1);
  18456. if (val) {
  18457. this.words[off] = this.words[off] | (1 << wbit);
  18458. } else {
  18459. this.words[off] = this.words[off] & ~(1 << wbit);
  18460. }
  18461. return this.strip();
  18462. };
  18463. // Add `num` to `this` in-place
  18464. BN.prototype.iadd = function iadd (num) {
  18465. var r;
  18466. // negative + positive
  18467. if (this.negative !== 0 && num.negative === 0) {
  18468. this.negative = 0;
  18469. r = this.isub(num);
  18470. this.negative ^= 1;
  18471. return this._normSign();
  18472. // positive + negative
  18473. } else if (this.negative === 0 && num.negative !== 0) {
  18474. num.negative = 0;
  18475. r = this.isub(num);
  18476. num.negative = 1;
  18477. return r._normSign();
  18478. }
  18479. // a.length > b.length
  18480. var a, b;
  18481. if (this.length > num.length) {
  18482. a = this;
  18483. b = num;
  18484. } else {
  18485. a = num;
  18486. b = this;
  18487. }
  18488. var carry = 0;
  18489. for (var i = 0; i < b.length; i++) {
  18490. r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
  18491. this.words[i] = r & 0x3ffffff;
  18492. carry = r >>> 26;
  18493. }
  18494. for (; carry !== 0 && i < a.length; i++) {
  18495. r = (a.words[i] | 0) + carry;
  18496. this.words[i] = r & 0x3ffffff;
  18497. carry = r >>> 26;
  18498. }
  18499. this.length = a.length;
  18500. if (carry !== 0) {
  18501. this.words[this.length] = carry;
  18502. this.length++;
  18503. // Copy the rest of the words
  18504. } else if (a !== this) {
  18505. for (; i < a.length; i++) {
  18506. this.words[i] = a.words[i];
  18507. }
  18508. }
  18509. return this;
  18510. };
  18511. // Add `num` to `this`
  18512. BN.prototype.add = function add (num) {
  18513. var res;
  18514. if (num.negative !== 0 && this.negative === 0) {
  18515. num.negative = 0;
  18516. res = this.sub(num);
  18517. num.negative ^= 1;
  18518. return res;
  18519. } else if (num.negative === 0 && this.negative !== 0) {
  18520. this.negative = 0;
  18521. res = num.sub(this);
  18522. this.negative = 1;
  18523. return res;
  18524. }
  18525. if (this.length > num.length) return this.clone().iadd(num);
  18526. return num.clone().iadd(this);
  18527. };
  18528. // Subtract `num` from `this` in-place
  18529. BN.prototype.isub = function isub (num) {
  18530. // this - (-num) = this + num
  18531. if (num.negative !== 0) {
  18532. num.negative = 0;
  18533. var r = this.iadd(num);
  18534. num.negative = 1;
  18535. return r._normSign();
  18536. // -this - num = -(this + num)
  18537. } else if (this.negative !== 0) {
  18538. this.negative = 0;
  18539. this.iadd(num);
  18540. this.negative = 1;
  18541. return this._normSign();
  18542. }
  18543. // At this point both numbers are positive
  18544. var cmp = this.cmp(num);
  18545. // Optimization - zeroify
  18546. if (cmp === 0) {
  18547. this.negative = 0;
  18548. this.length = 1;
  18549. this.words[0] = 0;
  18550. return this;
  18551. }
  18552. // a > b
  18553. var a, b;
  18554. if (cmp > 0) {
  18555. a = this;
  18556. b = num;
  18557. } else {
  18558. a = num;
  18559. b = this;
  18560. }
  18561. var carry = 0;
  18562. for (var i = 0; i < b.length; i++) {
  18563. r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
  18564. carry = r >> 26;
  18565. this.words[i] = r & 0x3ffffff;
  18566. }
  18567. for (; carry !== 0 && i < a.length; i++) {
  18568. r = (a.words[i] | 0) + carry;
  18569. carry = r >> 26;
  18570. this.words[i] = r & 0x3ffffff;
  18571. }
  18572. // Copy rest of the words
  18573. if (carry === 0 && i < a.length && a !== this) {
  18574. for (; i < a.length; i++) {
  18575. this.words[i] = a.words[i];
  18576. }
  18577. }
  18578. this.length = Math.max(this.length, i);
  18579. if (a !== this) {
  18580. this.negative = 1;
  18581. }
  18582. return this.strip();
  18583. };
  18584. // Subtract `num` from `this`
  18585. BN.prototype.sub = function sub (num) {
  18586. return this.clone().isub(num);
  18587. };
  18588. function smallMulTo (self, num, out) {
  18589. out.negative = num.negative ^ self.negative;
  18590. var len = (self.length + num.length) | 0;
  18591. out.length = len;
  18592. len = (len - 1) | 0;
  18593. // Peel one iteration (compiler can't do it, because of code complexity)
  18594. var a = self.words[0] | 0;
  18595. var b = num.words[0] | 0;
  18596. var r = a * b;
  18597. var lo = r & 0x3ffffff;
  18598. var carry = (r / 0x4000000) | 0;
  18599. out.words[0] = lo;
  18600. for (var k = 1; k < len; k++) {
  18601. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  18602. // note that ncarry could be >= 0x3ffffff
  18603. var ncarry = carry >>> 26;
  18604. var rword = carry & 0x3ffffff;
  18605. var maxJ = Math.min(k, num.length - 1);
  18606. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  18607. var i = (k - j) | 0;
  18608. a = self.words[i] | 0;
  18609. b = num.words[j] | 0;
  18610. r = a * b + rword;
  18611. ncarry += (r / 0x4000000) | 0;
  18612. rword = r & 0x3ffffff;
  18613. }
  18614. out.words[k] = rword | 0;
  18615. carry = ncarry | 0;
  18616. }
  18617. if (carry !== 0) {
  18618. out.words[k] = carry | 0;
  18619. } else {
  18620. out.length--;
  18621. }
  18622. return out.strip();
  18623. }
  18624. // TODO(indutny): it may be reasonable to omit it for users who don't need
  18625. // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  18626. // multiplication (like elliptic secp256k1).
  18627. var comb10MulTo = function comb10MulTo (self, num, out) {
  18628. var a = self.words;
  18629. var b = num.words;
  18630. var o = out.words;
  18631. var c = 0;
  18632. var lo;
  18633. var mid;
  18634. var hi;
  18635. var a0 = a[0] | 0;
  18636. var al0 = a0 & 0x1fff;
  18637. var ah0 = a0 >>> 13;
  18638. var a1 = a[1] | 0;
  18639. var al1 = a1 & 0x1fff;
  18640. var ah1 = a1 >>> 13;
  18641. var a2 = a[2] | 0;
  18642. var al2 = a2 & 0x1fff;
  18643. var ah2 = a2 >>> 13;
  18644. var a3 = a[3] | 0;
  18645. var al3 = a3 & 0x1fff;
  18646. var ah3 = a3 >>> 13;
  18647. var a4 = a[4] | 0;
  18648. var al4 = a4 & 0x1fff;
  18649. var ah4 = a4 >>> 13;
  18650. var a5 = a[5] | 0;
  18651. var al5 = a5 & 0x1fff;
  18652. var ah5 = a5 >>> 13;
  18653. var a6 = a[6] | 0;
  18654. var al6 = a6 & 0x1fff;
  18655. var ah6 = a6 >>> 13;
  18656. var a7 = a[7] | 0;
  18657. var al7 = a7 & 0x1fff;
  18658. var ah7 = a7 >>> 13;
  18659. var a8 = a[8] | 0;
  18660. var al8 = a8 & 0x1fff;
  18661. var ah8 = a8 >>> 13;
  18662. var a9 = a[9] | 0;
  18663. var al9 = a9 & 0x1fff;
  18664. var ah9 = a9 >>> 13;
  18665. var b0 = b[0] | 0;
  18666. var bl0 = b0 & 0x1fff;
  18667. var bh0 = b0 >>> 13;
  18668. var b1 = b[1] | 0;
  18669. var bl1 = b1 & 0x1fff;
  18670. var bh1 = b1 >>> 13;
  18671. var b2 = b[2] | 0;
  18672. var bl2 = b2 & 0x1fff;
  18673. var bh2 = b2 >>> 13;
  18674. var b3 = b[3] | 0;
  18675. var bl3 = b3 & 0x1fff;
  18676. var bh3 = b3 >>> 13;
  18677. var b4 = b[4] | 0;
  18678. var bl4 = b4 & 0x1fff;
  18679. var bh4 = b4 >>> 13;
  18680. var b5 = b[5] | 0;
  18681. var bl5 = b5 & 0x1fff;
  18682. var bh5 = b5 >>> 13;
  18683. var b6 = b[6] | 0;
  18684. var bl6 = b6 & 0x1fff;
  18685. var bh6 = b6 >>> 13;
  18686. var b7 = b[7] | 0;
  18687. var bl7 = b7 & 0x1fff;
  18688. var bh7 = b7 >>> 13;
  18689. var b8 = b[8] | 0;
  18690. var bl8 = b8 & 0x1fff;
  18691. var bh8 = b8 >>> 13;
  18692. var b9 = b[9] | 0;
  18693. var bl9 = b9 & 0x1fff;
  18694. var bh9 = b9 >>> 13;
  18695. out.negative = self.negative ^ num.negative;
  18696. out.length = 19;
  18697. /* k = 0 */
  18698. lo = Math.imul(al0, bl0);
  18699. mid = Math.imul(al0, bh0);
  18700. mid = (mid + Math.imul(ah0, bl0)) | 0;
  18701. hi = Math.imul(ah0, bh0);
  18702. var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18703. c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
  18704. w0 &= 0x3ffffff;
  18705. /* k = 1 */
  18706. lo = Math.imul(al1, bl0);
  18707. mid = Math.imul(al1, bh0);
  18708. mid = (mid + Math.imul(ah1, bl0)) | 0;
  18709. hi = Math.imul(ah1, bh0);
  18710. lo = (lo + Math.imul(al0, bl1)) | 0;
  18711. mid = (mid + Math.imul(al0, bh1)) | 0;
  18712. mid = (mid + Math.imul(ah0, bl1)) | 0;
  18713. hi = (hi + Math.imul(ah0, bh1)) | 0;
  18714. var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18715. c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
  18716. w1 &= 0x3ffffff;
  18717. /* k = 2 */
  18718. lo = Math.imul(al2, bl0);
  18719. mid = Math.imul(al2, bh0);
  18720. mid = (mid + Math.imul(ah2, bl0)) | 0;
  18721. hi = Math.imul(ah2, bh0);
  18722. lo = (lo + Math.imul(al1, bl1)) | 0;
  18723. mid = (mid + Math.imul(al1, bh1)) | 0;
  18724. mid = (mid + Math.imul(ah1, bl1)) | 0;
  18725. hi = (hi + Math.imul(ah1, bh1)) | 0;
  18726. lo = (lo + Math.imul(al0, bl2)) | 0;
  18727. mid = (mid + Math.imul(al0, bh2)) | 0;
  18728. mid = (mid + Math.imul(ah0, bl2)) | 0;
  18729. hi = (hi + Math.imul(ah0, bh2)) | 0;
  18730. var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18731. c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
  18732. w2 &= 0x3ffffff;
  18733. /* k = 3 */
  18734. lo = Math.imul(al3, bl0);
  18735. mid = Math.imul(al3, bh0);
  18736. mid = (mid + Math.imul(ah3, bl0)) | 0;
  18737. hi = Math.imul(ah3, bh0);
  18738. lo = (lo + Math.imul(al2, bl1)) | 0;
  18739. mid = (mid + Math.imul(al2, bh1)) | 0;
  18740. mid = (mid + Math.imul(ah2, bl1)) | 0;
  18741. hi = (hi + Math.imul(ah2, bh1)) | 0;
  18742. lo = (lo + Math.imul(al1, bl2)) | 0;
  18743. mid = (mid + Math.imul(al1, bh2)) | 0;
  18744. mid = (mid + Math.imul(ah1, bl2)) | 0;
  18745. hi = (hi + Math.imul(ah1, bh2)) | 0;
  18746. lo = (lo + Math.imul(al0, bl3)) | 0;
  18747. mid = (mid + Math.imul(al0, bh3)) | 0;
  18748. mid = (mid + Math.imul(ah0, bl3)) | 0;
  18749. hi = (hi + Math.imul(ah0, bh3)) | 0;
  18750. var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18751. c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
  18752. w3 &= 0x3ffffff;
  18753. /* k = 4 */
  18754. lo = Math.imul(al4, bl0);
  18755. mid = Math.imul(al4, bh0);
  18756. mid = (mid + Math.imul(ah4, bl0)) | 0;
  18757. hi = Math.imul(ah4, bh0);
  18758. lo = (lo + Math.imul(al3, bl1)) | 0;
  18759. mid = (mid + Math.imul(al3, bh1)) | 0;
  18760. mid = (mid + Math.imul(ah3, bl1)) | 0;
  18761. hi = (hi + Math.imul(ah3, bh1)) | 0;
  18762. lo = (lo + Math.imul(al2, bl2)) | 0;
  18763. mid = (mid + Math.imul(al2, bh2)) | 0;
  18764. mid = (mid + Math.imul(ah2, bl2)) | 0;
  18765. hi = (hi + Math.imul(ah2, bh2)) | 0;
  18766. lo = (lo + Math.imul(al1, bl3)) | 0;
  18767. mid = (mid + Math.imul(al1, bh3)) | 0;
  18768. mid = (mid + Math.imul(ah1, bl3)) | 0;
  18769. hi = (hi + Math.imul(ah1, bh3)) | 0;
  18770. lo = (lo + Math.imul(al0, bl4)) | 0;
  18771. mid = (mid + Math.imul(al0, bh4)) | 0;
  18772. mid = (mid + Math.imul(ah0, bl4)) | 0;
  18773. hi = (hi + Math.imul(ah0, bh4)) | 0;
  18774. var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18775. c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
  18776. w4 &= 0x3ffffff;
  18777. /* k = 5 */
  18778. lo = Math.imul(al5, bl0);
  18779. mid = Math.imul(al5, bh0);
  18780. mid = (mid + Math.imul(ah5, bl0)) | 0;
  18781. hi = Math.imul(ah5, bh0);
  18782. lo = (lo + Math.imul(al4, bl1)) | 0;
  18783. mid = (mid + Math.imul(al4, bh1)) | 0;
  18784. mid = (mid + Math.imul(ah4, bl1)) | 0;
  18785. hi = (hi + Math.imul(ah4, bh1)) | 0;
  18786. lo = (lo + Math.imul(al3, bl2)) | 0;
  18787. mid = (mid + Math.imul(al3, bh2)) | 0;
  18788. mid = (mid + Math.imul(ah3, bl2)) | 0;
  18789. hi = (hi + Math.imul(ah3, bh2)) | 0;
  18790. lo = (lo + Math.imul(al2, bl3)) | 0;
  18791. mid = (mid + Math.imul(al2, bh3)) | 0;
  18792. mid = (mid + Math.imul(ah2, bl3)) | 0;
  18793. hi = (hi + Math.imul(ah2, bh3)) | 0;
  18794. lo = (lo + Math.imul(al1, bl4)) | 0;
  18795. mid = (mid + Math.imul(al1, bh4)) | 0;
  18796. mid = (mid + Math.imul(ah1, bl4)) | 0;
  18797. hi = (hi + Math.imul(ah1, bh4)) | 0;
  18798. lo = (lo + Math.imul(al0, bl5)) | 0;
  18799. mid = (mid + Math.imul(al0, bh5)) | 0;
  18800. mid = (mid + Math.imul(ah0, bl5)) | 0;
  18801. hi = (hi + Math.imul(ah0, bh5)) | 0;
  18802. var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18803. c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
  18804. w5 &= 0x3ffffff;
  18805. /* k = 6 */
  18806. lo = Math.imul(al6, bl0);
  18807. mid = Math.imul(al6, bh0);
  18808. mid = (mid + Math.imul(ah6, bl0)) | 0;
  18809. hi = Math.imul(ah6, bh0);
  18810. lo = (lo + Math.imul(al5, bl1)) | 0;
  18811. mid = (mid + Math.imul(al5, bh1)) | 0;
  18812. mid = (mid + Math.imul(ah5, bl1)) | 0;
  18813. hi = (hi + Math.imul(ah5, bh1)) | 0;
  18814. lo = (lo + Math.imul(al4, bl2)) | 0;
  18815. mid = (mid + Math.imul(al4, bh2)) | 0;
  18816. mid = (mid + Math.imul(ah4, bl2)) | 0;
  18817. hi = (hi + Math.imul(ah4, bh2)) | 0;
  18818. lo = (lo + Math.imul(al3, bl3)) | 0;
  18819. mid = (mid + Math.imul(al3, bh3)) | 0;
  18820. mid = (mid + Math.imul(ah3, bl3)) | 0;
  18821. hi = (hi + Math.imul(ah3, bh3)) | 0;
  18822. lo = (lo + Math.imul(al2, bl4)) | 0;
  18823. mid = (mid + Math.imul(al2, bh4)) | 0;
  18824. mid = (mid + Math.imul(ah2, bl4)) | 0;
  18825. hi = (hi + Math.imul(ah2, bh4)) | 0;
  18826. lo = (lo + Math.imul(al1, bl5)) | 0;
  18827. mid = (mid + Math.imul(al1, bh5)) | 0;
  18828. mid = (mid + Math.imul(ah1, bl5)) | 0;
  18829. hi = (hi + Math.imul(ah1, bh5)) | 0;
  18830. lo = (lo + Math.imul(al0, bl6)) | 0;
  18831. mid = (mid + Math.imul(al0, bh6)) | 0;
  18832. mid = (mid + Math.imul(ah0, bl6)) | 0;
  18833. hi = (hi + Math.imul(ah0, bh6)) | 0;
  18834. var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18835. c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
  18836. w6 &= 0x3ffffff;
  18837. /* k = 7 */
  18838. lo = Math.imul(al7, bl0);
  18839. mid = Math.imul(al7, bh0);
  18840. mid = (mid + Math.imul(ah7, bl0)) | 0;
  18841. hi = Math.imul(ah7, bh0);
  18842. lo = (lo + Math.imul(al6, bl1)) | 0;
  18843. mid = (mid + Math.imul(al6, bh1)) | 0;
  18844. mid = (mid + Math.imul(ah6, bl1)) | 0;
  18845. hi = (hi + Math.imul(ah6, bh1)) | 0;
  18846. lo = (lo + Math.imul(al5, bl2)) | 0;
  18847. mid = (mid + Math.imul(al5, bh2)) | 0;
  18848. mid = (mid + Math.imul(ah5, bl2)) | 0;
  18849. hi = (hi + Math.imul(ah5, bh2)) | 0;
  18850. lo = (lo + Math.imul(al4, bl3)) | 0;
  18851. mid = (mid + Math.imul(al4, bh3)) | 0;
  18852. mid = (mid + Math.imul(ah4, bl3)) | 0;
  18853. hi = (hi + Math.imul(ah4, bh3)) | 0;
  18854. lo = (lo + Math.imul(al3, bl4)) | 0;
  18855. mid = (mid + Math.imul(al3, bh4)) | 0;
  18856. mid = (mid + Math.imul(ah3, bl4)) | 0;
  18857. hi = (hi + Math.imul(ah3, bh4)) | 0;
  18858. lo = (lo + Math.imul(al2, bl5)) | 0;
  18859. mid = (mid + Math.imul(al2, bh5)) | 0;
  18860. mid = (mid + Math.imul(ah2, bl5)) | 0;
  18861. hi = (hi + Math.imul(ah2, bh5)) | 0;
  18862. lo = (lo + Math.imul(al1, bl6)) | 0;
  18863. mid = (mid + Math.imul(al1, bh6)) | 0;
  18864. mid = (mid + Math.imul(ah1, bl6)) | 0;
  18865. hi = (hi + Math.imul(ah1, bh6)) | 0;
  18866. lo = (lo + Math.imul(al0, bl7)) | 0;
  18867. mid = (mid + Math.imul(al0, bh7)) | 0;
  18868. mid = (mid + Math.imul(ah0, bl7)) | 0;
  18869. hi = (hi + Math.imul(ah0, bh7)) | 0;
  18870. var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18871. c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
  18872. w7 &= 0x3ffffff;
  18873. /* k = 8 */
  18874. lo = Math.imul(al8, bl0);
  18875. mid = Math.imul(al8, bh0);
  18876. mid = (mid + Math.imul(ah8, bl0)) | 0;
  18877. hi = Math.imul(ah8, bh0);
  18878. lo = (lo + Math.imul(al7, bl1)) | 0;
  18879. mid = (mid + Math.imul(al7, bh1)) | 0;
  18880. mid = (mid + Math.imul(ah7, bl1)) | 0;
  18881. hi = (hi + Math.imul(ah7, bh1)) | 0;
  18882. lo = (lo + Math.imul(al6, bl2)) | 0;
  18883. mid = (mid + Math.imul(al6, bh2)) | 0;
  18884. mid = (mid + Math.imul(ah6, bl2)) | 0;
  18885. hi = (hi + Math.imul(ah6, bh2)) | 0;
  18886. lo = (lo + Math.imul(al5, bl3)) | 0;
  18887. mid = (mid + Math.imul(al5, bh3)) | 0;
  18888. mid = (mid + Math.imul(ah5, bl3)) | 0;
  18889. hi = (hi + Math.imul(ah5, bh3)) | 0;
  18890. lo = (lo + Math.imul(al4, bl4)) | 0;
  18891. mid = (mid + Math.imul(al4, bh4)) | 0;
  18892. mid = (mid + Math.imul(ah4, bl4)) | 0;
  18893. hi = (hi + Math.imul(ah4, bh4)) | 0;
  18894. lo = (lo + Math.imul(al3, bl5)) | 0;
  18895. mid = (mid + Math.imul(al3, bh5)) | 0;
  18896. mid = (mid + Math.imul(ah3, bl5)) | 0;
  18897. hi = (hi + Math.imul(ah3, bh5)) | 0;
  18898. lo = (lo + Math.imul(al2, bl6)) | 0;
  18899. mid = (mid + Math.imul(al2, bh6)) | 0;
  18900. mid = (mid + Math.imul(ah2, bl6)) | 0;
  18901. hi = (hi + Math.imul(ah2, bh6)) | 0;
  18902. lo = (lo + Math.imul(al1, bl7)) | 0;
  18903. mid = (mid + Math.imul(al1, bh7)) | 0;
  18904. mid = (mid + Math.imul(ah1, bl7)) | 0;
  18905. hi = (hi + Math.imul(ah1, bh7)) | 0;
  18906. lo = (lo + Math.imul(al0, bl8)) | 0;
  18907. mid = (mid + Math.imul(al0, bh8)) | 0;
  18908. mid = (mid + Math.imul(ah0, bl8)) | 0;
  18909. hi = (hi + Math.imul(ah0, bh8)) | 0;
  18910. var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18911. c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
  18912. w8 &= 0x3ffffff;
  18913. /* k = 9 */
  18914. lo = Math.imul(al9, bl0);
  18915. mid = Math.imul(al9, bh0);
  18916. mid = (mid + Math.imul(ah9, bl0)) | 0;
  18917. hi = Math.imul(ah9, bh0);
  18918. lo = (lo + Math.imul(al8, bl1)) | 0;
  18919. mid = (mid + Math.imul(al8, bh1)) | 0;
  18920. mid = (mid + Math.imul(ah8, bl1)) | 0;
  18921. hi = (hi + Math.imul(ah8, bh1)) | 0;
  18922. lo = (lo + Math.imul(al7, bl2)) | 0;
  18923. mid = (mid + Math.imul(al7, bh2)) | 0;
  18924. mid = (mid + Math.imul(ah7, bl2)) | 0;
  18925. hi = (hi + Math.imul(ah7, bh2)) | 0;
  18926. lo = (lo + Math.imul(al6, bl3)) | 0;
  18927. mid = (mid + Math.imul(al6, bh3)) | 0;
  18928. mid = (mid + Math.imul(ah6, bl3)) | 0;
  18929. hi = (hi + Math.imul(ah6, bh3)) | 0;
  18930. lo = (lo + Math.imul(al5, bl4)) | 0;
  18931. mid = (mid + Math.imul(al5, bh4)) | 0;
  18932. mid = (mid + Math.imul(ah5, bl4)) | 0;
  18933. hi = (hi + Math.imul(ah5, bh4)) | 0;
  18934. lo = (lo + Math.imul(al4, bl5)) | 0;
  18935. mid = (mid + Math.imul(al4, bh5)) | 0;
  18936. mid = (mid + Math.imul(ah4, bl5)) | 0;
  18937. hi = (hi + Math.imul(ah4, bh5)) | 0;
  18938. lo = (lo + Math.imul(al3, bl6)) | 0;
  18939. mid = (mid + Math.imul(al3, bh6)) | 0;
  18940. mid = (mid + Math.imul(ah3, bl6)) | 0;
  18941. hi = (hi + Math.imul(ah3, bh6)) | 0;
  18942. lo = (lo + Math.imul(al2, bl7)) | 0;
  18943. mid = (mid + Math.imul(al2, bh7)) | 0;
  18944. mid = (mid + Math.imul(ah2, bl7)) | 0;
  18945. hi = (hi + Math.imul(ah2, bh7)) | 0;
  18946. lo = (lo + Math.imul(al1, bl8)) | 0;
  18947. mid = (mid + Math.imul(al1, bh8)) | 0;
  18948. mid = (mid + Math.imul(ah1, bl8)) | 0;
  18949. hi = (hi + Math.imul(ah1, bh8)) | 0;
  18950. lo = (lo + Math.imul(al0, bl9)) | 0;
  18951. mid = (mid + Math.imul(al0, bh9)) | 0;
  18952. mid = (mid + Math.imul(ah0, bl9)) | 0;
  18953. hi = (hi + Math.imul(ah0, bh9)) | 0;
  18954. var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18955. c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
  18956. w9 &= 0x3ffffff;
  18957. /* k = 10 */
  18958. lo = Math.imul(al9, bl1);
  18959. mid = Math.imul(al9, bh1);
  18960. mid = (mid + Math.imul(ah9, bl1)) | 0;
  18961. hi = Math.imul(ah9, bh1);
  18962. lo = (lo + Math.imul(al8, bl2)) | 0;
  18963. mid = (mid + Math.imul(al8, bh2)) | 0;
  18964. mid = (mid + Math.imul(ah8, bl2)) | 0;
  18965. hi = (hi + Math.imul(ah8, bh2)) | 0;
  18966. lo = (lo + Math.imul(al7, bl3)) | 0;
  18967. mid = (mid + Math.imul(al7, bh3)) | 0;
  18968. mid = (mid + Math.imul(ah7, bl3)) | 0;
  18969. hi = (hi + Math.imul(ah7, bh3)) | 0;
  18970. lo = (lo + Math.imul(al6, bl4)) | 0;
  18971. mid = (mid + Math.imul(al6, bh4)) | 0;
  18972. mid = (mid + Math.imul(ah6, bl4)) | 0;
  18973. hi = (hi + Math.imul(ah6, bh4)) | 0;
  18974. lo = (lo + Math.imul(al5, bl5)) | 0;
  18975. mid = (mid + Math.imul(al5, bh5)) | 0;
  18976. mid = (mid + Math.imul(ah5, bl5)) | 0;
  18977. hi = (hi + Math.imul(ah5, bh5)) | 0;
  18978. lo = (lo + Math.imul(al4, bl6)) | 0;
  18979. mid = (mid + Math.imul(al4, bh6)) | 0;
  18980. mid = (mid + Math.imul(ah4, bl6)) | 0;
  18981. hi = (hi + Math.imul(ah4, bh6)) | 0;
  18982. lo = (lo + Math.imul(al3, bl7)) | 0;
  18983. mid = (mid + Math.imul(al3, bh7)) | 0;
  18984. mid = (mid + Math.imul(ah3, bl7)) | 0;
  18985. hi = (hi + Math.imul(ah3, bh7)) | 0;
  18986. lo = (lo + Math.imul(al2, bl8)) | 0;
  18987. mid = (mid + Math.imul(al2, bh8)) | 0;
  18988. mid = (mid + Math.imul(ah2, bl8)) | 0;
  18989. hi = (hi + Math.imul(ah2, bh8)) | 0;
  18990. lo = (lo + Math.imul(al1, bl9)) | 0;
  18991. mid = (mid + Math.imul(al1, bh9)) | 0;
  18992. mid = (mid + Math.imul(ah1, bl9)) | 0;
  18993. hi = (hi + Math.imul(ah1, bh9)) | 0;
  18994. var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  18995. c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
  18996. w10 &= 0x3ffffff;
  18997. /* k = 11 */
  18998. lo = Math.imul(al9, bl2);
  18999. mid = Math.imul(al9, bh2);
  19000. mid = (mid + Math.imul(ah9, bl2)) | 0;
  19001. hi = Math.imul(ah9, bh2);
  19002. lo = (lo + Math.imul(al8, bl3)) | 0;
  19003. mid = (mid + Math.imul(al8, bh3)) | 0;
  19004. mid = (mid + Math.imul(ah8, bl3)) | 0;
  19005. hi = (hi + Math.imul(ah8, bh3)) | 0;
  19006. lo = (lo + Math.imul(al7, bl4)) | 0;
  19007. mid = (mid + Math.imul(al7, bh4)) | 0;
  19008. mid = (mid + Math.imul(ah7, bl4)) | 0;
  19009. hi = (hi + Math.imul(ah7, bh4)) | 0;
  19010. lo = (lo + Math.imul(al6, bl5)) | 0;
  19011. mid = (mid + Math.imul(al6, bh5)) | 0;
  19012. mid = (mid + Math.imul(ah6, bl5)) | 0;
  19013. hi = (hi + Math.imul(ah6, bh5)) | 0;
  19014. lo = (lo + Math.imul(al5, bl6)) | 0;
  19015. mid = (mid + Math.imul(al5, bh6)) | 0;
  19016. mid = (mid + Math.imul(ah5, bl6)) | 0;
  19017. hi = (hi + Math.imul(ah5, bh6)) | 0;
  19018. lo = (lo + Math.imul(al4, bl7)) | 0;
  19019. mid = (mid + Math.imul(al4, bh7)) | 0;
  19020. mid = (mid + Math.imul(ah4, bl7)) | 0;
  19021. hi = (hi + Math.imul(ah4, bh7)) | 0;
  19022. lo = (lo + Math.imul(al3, bl8)) | 0;
  19023. mid = (mid + Math.imul(al3, bh8)) | 0;
  19024. mid = (mid + Math.imul(ah3, bl8)) | 0;
  19025. hi = (hi + Math.imul(ah3, bh8)) | 0;
  19026. lo = (lo + Math.imul(al2, bl9)) | 0;
  19027. mid = (mid + Math.imul(al2, bh9)) | 0;
  19028. mid = (mid + Math.imul(ah2, bl9)) | 0;
  19029. hi = (hi + Math.imul(ah2, bh9)) | 0;
  19030. var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19031. c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
  19032. w11 &= 0x3ffffff;
  19033. /* k = 12 */
  19034. lo = Math.imul(al9, bl3);
  19035. mid = Math.imul(al9, bh3);
  19036. mid = (mid + Math.imul(ah9, bl3)) | 0;
  19037. hi = Math.imul(ah9, bh3);
  19038. lo = (lo + Math.imul(al8, bl4)) | 0;
  19039. mid = (mid + Math.imul(al8, bh4)) | 0;
  19040. mid = (mid + Math.imul(ah8, bl4)) | 0;
  19041. hi = (hi + Math.imul(ah8, bh4)) | 0;
  19042. lo = (lo + Math.imul(al7, bl5)) | 0;
  19043. mid = (mid + Math.imul(al7, bh5)) | 0;
  19044. mid = (mid + Math.imul(ah7, bl5)) | 0;
  19045. hi = (hi + Math.imul(ah7, bh5)) | 0;
  19046. lo = (lo + Math.imul(al6, bl6)) | 0;
  19047. mid = (mid + Math.imul(al6, bh6)) | 0;
  19048. mid = (mid + Math.imul(ah6, bl6)) | 0;
  19049. hi = (hi + Math.imul(ah6, bh6)) | 0;
  19050. lo = (lo + Math.imul(al5, bl7)) | 0;
  19051. mid = (mid + Math.imul(al5, bh7)) | 0;
  19052. mid = (mid + Math.imul(ah5, bl7)) | 0;
  19053. hi = (hi + Math.imul(ah5, bh7)) | 0;
  19054. lo = (lo + Math.imul(al4, bl8)) | 0;
  19055. mid = (mid + Math.imul(al4, bh8)) | 0;
  19056. mid = (mid + Math.imul(ah4, bl8)) | 0;
  19057. hi = (hi + Math.imul(ah4, bh8)) | 0;
  19058. lo = (lo + Math.imul(al3, bl9)) | 0;
  19059. mid = (mid + Math.imul(al3, bh9)) | 0;
  19060. mid = (mid + Math.imul(ah3, bl9)) | 0;
  19061. hi = (hi + Math.imul(ah3, bh9)) | 0;
  19062. var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19063. c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
  19064. w12 &= 0x3ffffff;
  19065. /* k = 13 */
  19066. lo = Math.imul(al9, bl4);
  19067. mid = Math.imul(al9, bh4);
  19068. mid = (mid + Math.imul(ah9, bl4)) | 0;
  19069. hi = Math.imul(ah9, bh4);
  19070. lo = (lo + Math.imul(al8, bl5)) | 0;
  19071. mid = (mid + Math.imul(al8, bh5)) | 0;
  19072. mid = (mid + Math.imul(ah8, bl5)) | 0;
  19073. hi = (hi + Math.imul(ah8, bh5)) | 0;
  19074. lo = (lo + Math.imul(al7, bl6)) | 0;
  19075. mid = (mid + Math.imul(al7, bh6)) | 0;
  19076. mid = (mid + Math.imul(ah7, bl6)) | 0;
  19077. hi = (hi + Math.imul(ah7, bh6)) | 0;
  19078. lo = (lo + Math.imul(al6, bl7)) | 0;
  19079. mid = (mid + Math.imul(al6, bh7)) | 0;
  19080. mid = (mid + Math.imul(ah6, bl7)) | 0;
  19081. hi = (hi + Math.imul(ah6, bh7)) | 0;
  19082. lo = (lo + Math.imul(al5, bl8)) | 0;
  19083. mid = (mid + Math.imul(al5, bh8)) | 0;
  19084. mid = (mid + Math.imul(ah5, bl8)) | 0;
  19085. hi = (hi + Math.imul(ah5, bh8)) | 0;
  19086. lo = (lo + Math.imul(al4, bl9)) | 0;
  19087. mid = (mid + Math.imul(al4, bh9)) | 0;
  19088. mid = (mid + Math.imul(ah4, bl9)) | 0;
  19089. hi = (hi + Math.imul(ah4, bh9)) | 0;
  19090. var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19091. c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
  19092. w13 &= 0x3ffffff;
  19093. /* k = 14 */
  19094. lo = Math.imul(al9, bl5);
  19095. mid = Math.imul(al9, bh5);
  19096. mid = (mid + Math.imul(ah9, bl5)) | 0;
  19097. hi = Math.imul(ah9, bh5);
  19098. lo = (lo + Math.imul(al8, bl6)) | 0;
  19099. mid = (mid + Math.imul(al8, bh6)) | 0;
  19100. mid = (mid + Math.imul(ah8, bl6)) | 0;
  19101. hi = (hi + Math.imul(ah8, bh6)) | 0;
  19102. lo = (lo + Math.imul(al7, bl7)) | 0;
  19103. mid = (mid + Math.imul(al7, bh7)) | 0;
  19104. mid = (mid + Math.imul(ah7, bl7)) | 0;
  19105. hi = (hi + Math.imul(ah7, bh7)) | 0;
  19106. lo = (lo + Math.imul(al6, bl8)) | 0;
  19107. mid = (mid + Math.imul(al6, bh8)) | 0;
  19108. mid = (mid + Math.imul(ah6, bl8)) | 0;
  19109. hi = (hi + Math.imul(ah6, bh8)) | 0;
  19110. lo = (lo + Math.imul(al5, bl9)) | 0;
  19111. mid = (mid + Math.imul(al5, bh9)) | 0;
  19112. mid = (mid + Math.imul(ah5, bl9)) | 0;
  19113. hi = (hi + Math.imul(ah5, bh9)) | 0;
  19114. var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19115. c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
  19116. w14 &= 0x3ffffff;
  19117. /* k = 15 */
  19118. lo = Math.imul(al9, bl6);
  19119. mid = Math.imul(al9, bh6);
  19120. mid = (mid + Math.imul(ah9, bl6)) | 0;
  19121. hi = Math.imul(ah9, bh6);
  19122. lo = (lo + Math.imul(al8, bl7)) | 0;
  19123. mid = (mid + Math.imul(al8, bh7)) | 0;
  19124. mid = (mid + Math.imul(ah8, bl7)) | 0;
  19125. hi = (hi + Math.imul(ah8, bh7)) | 0;
  19126. lo = (lo + Math.imul(al7, bl8)) | 0;
  19127. mid = (mid + Math.imul(al7, bh8)) | 0;
  19128. mid = (mid + Math.imul(ah7, bl8)) | 0;
  19129. hi = (hi + Math.imul(ah7, bh8)) | 0;
  19130. lo = (lo + Math.imul(al6, bl9)) | 0;
  19131. mid = (mid + Math.imul(al6, bh9)) | 0;
  19132. mid = (mid + Math.imul(ah6, bl9)) | 0;
  19133. hi = (hi + Math.imul(ah6, bh9)) | 0;
  19134. var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19135. c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
  19136. w15 &= 0x3ffffff;
  19137. /* k = 16 */
  19138. lo = Math.imul(al9, bl7);
  19139. mid = Math.imul(al9, bh7);
  19140. mid = (mid + Math.imul(ah9, bl7)) | 0;
  19141. hi = Math.imul(ah9, bh7);
  19142. lo = (lo + Math.imul(al8, bl8)) | 0;
  19143. mid = (mid + Math.imul(al8, bh8)) | 0;
  19144. mid = (mid + Math.imul(ah8, bl8)) | 0;
  19145. hi = (hi + Math.imul(ah8, bh8)) | 0;
  19146. lo = (lo + Math.imul(al7, bl9)) | 0;
  19147. mid = (mid + Math.imul(al7, bh9)) | 0;
  19148. mid = (mid + Math.imul(ah7, bl9)) | 0;
  19149. hi = (hi + Math.imul(ah7, bh9)) | 0;
  19150. var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19151. c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
  19152. w16 &= 0x3ffffff;
  19153. /* k = 17 */
  19154. lo = Math.imul(al9, bl8);
  19155. mid = Math.imul(al9, bh8);
  19156. mid = (mid + Math.imul(ah9, bl8)) | 0;
  19157. hi = Math.imul(ah9, bh8);
  19158. lo = (lo + Math.imul(al8, bl9)) | 0;
  19159. mid = (mid + Math.imul(al8, bh9)) | 0;
  19160. mid = (mid + Math.imul(ah8, bl9)) | 0;
  19161. hi = (hi + Math.imul(ah8, bh9)) | 0;
  19162. var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19163. c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
  19164. w17 &= 0x3ffffff;
  19165. /* k = 18 */
  19166. lo = Math.imul(al9, bl9);
  19167. mid = Math.imul(al9, bh9);
  19168. mid = (mid + Math.imul(ah9, bl9)) | 0;
  19169. hi = Math.imul(ah9, bh9);
  19170. var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  19171. c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
  19172. w18 &= 0x3ffffff;
  19173. o[0] = w0;
  19174. o[1] = w1;
  19175. o[2] = w2;
  19176. o[3] = w3;
  19177. o[4] = w4;
  19178. o[5] = w5;
  19179. o[6] = w6;
  19180. o[7] = w7;
  19181. o[8] = w8;
  19182. o[9] = w9;
  19183. o[10] = w10;
  19184. o[11] = w11;
  19185. o[12] = w12;
  19186. o[13] = w13;
  19187. o[14] = w14;
  19188. o[15] = w15;
  19189. o[16] = w16;
  19190. o[17] = w17;
  19191. o[18] = w18;
  19192. if (c !== 0) {
  19193. o[19] = c;
  19194. out.length++;
  19195. }
  19196. return out;
  19197. };
  19198. // Polyfill comb
  19199. if (!Math.imul) {
  19200. comb10MulTo = smallMulTo;
  19201. }
  19202. function bigMulTo (self, num, out) {
  19203. out.negative = num.negative ^ self.negative;
  19204. out.length = self.length + num.length;
  19205. var carry = 0;
  19206. var hncarry = 0;
  19207. for (var k = 0; k < out.length - 1; k++) {
  19208. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  19209. // note that ncarry could be >= 0x3ffffff
  19210. var ncarry = hncarry;
  19211. hncarry = 0;
  19212. var rword = carry & 0x3ffffff;
  19213. var maxJ = Math.min(k, num.length - 1);
  19214. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  19215. var i = k - j;
  19216. var a = self.words[i] | 0;
  19217. var b = num.words[j] | 0;
  19218. var r = a * b;
  19219. var lo = r & 0x3ffffff;
  19220. ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
  19221. lo = (lo + rword) | 0;
  19222. rword = lo & 0x3ffffff;
  19223. ncarry = (ncarry + (lo >>> 26)) | 0;
  19224. hncarry += ncarry >>> 26;
  19225. ncarry &= 0x3ffffff;
  19226. }
  19227. out.words[k] = rword;
  19228. carry = ncarry;
  19229. ncarry = hncarry;
  19230. }
  19231. if (carry !== 0) {
  19232. out.words[k] = carry;
  19233. } else {
  19234. out.length--;
  19235. }
  19236. return out.strip();
  19237. }
  19238. function jumboMulTo (self, num, out) {
  19239. var fftm = new FFTM();
  19240. return fftm.mulp(self, num, out);
  19241. }
  19242. BN.prototype.mulTo = function mulTo (num, out) {
  19243. var res;
  19244. var len = this.length + num.length;
  19245. if (this.length === 10 && num.length === 10) {
  19246. res = comb10MulTo(this, num, out);
  19247. } else if (len < 63) {
  19248. res = smallMulTo(this, num, out);
  19249. } else if (len < 1024) {
  19250. res = bigMulTo(this, num, out);
  19251. } else {
  19252. res = jumboMulTo(this, num, out);
  19253. }
  19254. return res;
  19255. };
  19256. // Cooley-Tukey algorithm for FFT
  19257. // slightly revisited to rely on looping instead of recursion
  19258. function FFTM (x, y) {
  19259. this.x = x;
  19260. this.y = y;
  19261. }
  19262. FFTM.prototype.makeRBT = function makeRBT (N) {
  19263. var t = new Array(N);
  19264. var l = BN.prototype._countBits(N) - 1;
  19265. for (var i = 0; i < N; i++) {
  19266. t[i] = this.revBin(i, l, N);
  19267. }
  19268. return t;
  19269. };
  19270. // Returns binary-reversed representation of `x`
  19271. FFTM.prototype.revBin = function revBin (x, l, N) {
  19272. if (x === 0 || x === N - 1) return x;
  19273. var rb = 0;
  19274. for (var i = 0; i < l; i++) {
  19275. rb |= (x & 1) << (l - i - 1);
  19276. x >>= 1;
  19277. }
  19278. return rb;
  19279. };
  19280. // Performs "tweedling" phase, therefore 'emulating'
  19281. // behaviour of the recursive algorithm
  19282. FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
  19283. for (var i = 0; i < N; i++) {
  19284. rtws[i] = rws[rbt[i]];
  19285. itws[i] = iws[rbt[i]];
  19286. }
  19287. };
  19288. FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
  19289. this.permute(rbt, rws, iws, rtws, itws, N);
  19290. for (var s = 1; s < N; s <<= 1) {
  19291. var l = s << 1;
  19292. var rtwdf = Math.cos(2 * Math.PI / l);
  19293. var itwdf = Math.sin(2 * Math.PI / l);
  19294. for (var p = 0; p < N; p += l) {
  19295. var rtwdf_ = rtwdf;
  19296. var itwdf_ = itwdf;
  19297. for (var j = 0; j < s; j++) {
  19298. var re = rtws[p + j];
  19299. var ie = itws[p + j];
  19300. var ro = rtws[p + j + s];
  19301. var io = itws[p + j + s];
  19302. var rx = rtwdf_ * ro - itwdf_ * io;
  19303. io = rtwdf_ * io + itwdf_ * ro;
  19304. ro = rx;
  19305. rtws[p + j] = re + ro;
  19306. itws[p + j] = ie + io;
  19307. rtws[p + j + s] = re - ro;
  19308. itws[p + j + s] = ie - io;
  19309. /* jshint maxdepth : false */
  19310. if (j !== l) {
  19311. rx = rtwdf * rtwdf_ - itwdf * itwdf_;
  19312. itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
  19313. rtwdf_ = rx;
  19314. }
  19315. }
  19316. }
  19317. }
  19318. };
  19319. FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
  19320. var N = Math.max(m, n) | 1;
  19321. var odd = N & 1;
  19322. var i = 0;
  19323. for (N = N / 2 | 0; N; N = N >>> 1) {
  19324. i++;
  19325. }
  19326. return 1 << i + 1 + odd;
  19327. };
  19328. FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
  19329. if (N <= 1) return;
  19330. for (var i = 0; i < N / 2; i++) {
  19331. var t = rws[i];
  19332. rws[i] = rws[N - i - 1];
  19333. rws[N - i - 1] = t;
  19334. t = iws[i];
  19335. iws[i] = -iws[N - i - 1];
  19336. iws[N - i - 1] = -t;
  19337. }
  19338. };
  19339. FFTM.prototype.normalize13b = function normalize13b (ws, N) {
  19340. var carry = 0;
  19341. for (var i = 0; i < N / 2; i++) {
  19342. var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
  19343. Math.round(ws[2 * i] / N) +
  19344. carry;
  19345. ws[i] = w & 0x3ffffff;
  19346. if (w < 0x4000000) {
  19347. carry = 0;
  19348. } else {
  19349. carry = w / 0x4000000 | 0;
  19350. }
  19351. }
  19352. return ws;
  19353. };
  19354. FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
  19355. var carry = 0;
  19356. for (var i = 0; i < len; i++) {
  19357. carry = carry + (ws[i] | 0);
  19358. rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
  19359. rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
  19360. }
  19361. // Pad with zeroes
  19362. for (i = 2 * len; i < N; ++i) {
  19363. rws[i] = 0;
  19364. }
  19365. assert(carry === 0);
  19366. assert((carry & ~0x1fff) === 0);
  19367. };
  19368. FFTM.prototype.stub = function stub (N) {
  19369. var ph = new Array(N);
  19370. for (var i = 0; i < N; i++) {
  19371. ph[i] = 0;
  19372. }
  19373. return ph;
  19374. };
  19375. FFTM.prototype.mulp = function mulp (x, y, out) {
  19376. var N = 2 * this.guessLen13b(x.length, y.length);
  19377. var rbt = this.makeRBT(N);
  19378. var _ = this.stub(N);
  19379. var rws = new Array(N);
  19380. var rwst = new Array(N);
  19381. var iwst = new Array(N);
  19382. var nrws = new Array(N);
  19383. var nrwst = new Array(N);
  19384. var niwst = new Array(N);
  19385. var rmws = out.words;
  19386. rmws.length = N;
  19387. this.convert13b(x.words, x.length, rws, N);
  19388. this.convert13b(y.words, y.length, nrws, N);
  19389. this.transform(rws, _, rwst, iwst, N, rbt);
  19390. this.transform(nrws, _, nrwst, niwst, N, rbt);
  19391. for (var i = 0; i < N; i++) {
  19392. var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
  19393. iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
  19394. rwst[i] = rx;
  19395. }
  19396. this.conjugate(rwst, iwst, N);
  19397. this.transform(rwst, iwst, rmws, _, N, rbt);
  19398. this.conjugate(rmws, _, N);
  19399. this.normalize13b(rmws, N);
  19400. out.negative = x.negative ^ y.negative;
  19401. out.length = x.length + y.length;
  19402. return out.strip();
  19403. };
  19404. // Multiply `this` by `num`
  19405. BN.prototype.mul = function mul (num) {
  19406. var out = new BN(null);
  19407. out.words = new Array(this.length + num.length);
  19408. return this.mulTo(num, out);
  19409. };
  19410. // Multiply employing FFT
  19411. BN.prototype.mulf = function mulf (num) {
  19412. var out = new BN(null);
  19413. out.words = new Array(this.length + num.length);
  19414. return jumboMulTo(this, num, out);
  19415. };
  19416. // In-place Multiplication
  19417. BN.prototype.imul = function imul (num) {
  19418. return this.clone().mulTo(num, this);
  19419. };
  19420. BN.prototype.imuln = function imuln (num) {
  19421. assert(typeof num === 'number');
  19422. assert(num < 0x4000000);
  19423. // Carry
  19424. var carry = 0;
  19425. for (var i = 0; i < this.length; i++) {
  19426. var w = (this.words[i] | 0) * num;
  19427. var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
  19428. carry >>= 26;
  19429. carry += (w / 0x4000000) | 0;
  19430. // NOTE: lo is 27bit maximum
  19431. carry += lo >>> 26;
  19432. this.words[i] = lo & 0x3ffffff;
  19433. }
  19434. if (carry !== 0) {
  19435. this.words[i] = carry;
  19436. this.length++;
  19437. }
  19438. return this;
  19439. };
  19440. BN.prototype.muln = function muln (num) {
  19441. return this.clone().imuln(num);
  19442. };
  19443. // `this` * `this`
  19444. BN.prototype.sqr = function sqr () {
  19445. return this.mul(this);
  19446. };
  19447. // `this` * `this` in-place
  19448. BN.prototype.isqr = function isqr () {
  19449. return this.imul(this.clone());
  19450. };
  19451. // Math.pow(`this`, `num`)
  19452. BN.prototype.pow = function pow (num) {
  19453. var w = toBitArray(num);
  19454. if (w.length === 0) return new BN(1);
  19455. // Skip leading zeroes
  19456. var res = this;
  19457. for (var i = 0; i < w.length; i++, res = res.sqr()) {
  19458. if (w[i] !== 0) break;
  19459. }
  19460. if (++i < w.length) {
  19461. for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
  19462. if (w[i] === 0) continue;
  19463. res = res.mul(q);
  19464. }
  19465. }
  19466. return res;
  19467. };
  19468. // Shift-left in-place
  19469. BN.prototype.iushln = function iushln (bits) {
  19470. assert(typeof bits === 'number' && bits >= 0);
  19471. var r = bits % 26;
  19472. var s = (bits - r) / 26;
  19473. var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
  19474. var i;
  19475. if (r !== 0) {
  19476. var carry = 0;
  19477. for (i = 0; i < this.length; i++) {
  19478. var newCarry = this.words[i] & carryMask;
  19479. var c = ((this.words[i] | 0) - newCarry) << r;
  19480. this.words[i] = c | carry;
  19481. carry = newCarry >>> (26 - r);
  19482. }
  19483. if (carry) {
  19484. this.words[i] = carry;
  19485. this.length++;
  19486. }
  19487. }
  19488. if (s !== 0) {
  19489. for (i = this.length - 1; i >= 0; i--) {
  19490. this.words[i + s] = this.words[i];
  19491. }
  19492. for (i = 0; i < s; i++) {
  19493. this.words[i] = 0;
  19494. }
  19495. this.length += s;
  19496. }
  19497. return this.strip();
  19498. };
  19499. BN.prototype.ishln = function ishln (bits) {
  19500. // TODO(indutny): implement me
  19501. assert(this.negative === 0);
  19502. return this.iushln(bits);
  19503. };
  19504. // Shift-right in-place
  19505. // NOTE: `hint` is a lowest bit before trailing zeroes
  19506. // NOTE: if `extended` is present - it will be filled with destroyed bits
  19507. BN.prototype.iushrn = function iushrn (bits, hint, extended) {
  19508. assert(typeof bits === 'number' && bits >= 0);
  19509. var h;
  19510. if (hint) {
  19511. h = (hint - (hint % 26)) / 26;
  19512. } else {
  19513. h = 0;
  19514. }
  19515. var r = bits % 26;
  19516. var s = Math.min((bits - r) / 26, this.length);
  19517. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  19518. var maskedWords = extended;
  19519. h -= s;
  19520. h = Math.max(0, h);
  19521. // Extended mode, copy masked part
  19522. if (maskedWords) {
  19523. for (var i = 0; i < s; i++) {
  19524. maskedWords.words[i] = this.words[i];
  19525. }
  19526. maskedWords.length = s;
  19527. }
  19528. if (s === 0) {
  19529. // No-op, we should not move anything at all
  19530. } else if (this.length > s) {
  19531. this.length -= s;
  19532. for (i = 0; i < this.length; i++) {
  19533. this.words[i] = this.words[i + s];
  19534. }
  19535. } else {
  19536. this.words[0] = 0;
  19537. this.length = 1;
  19538. }
  19539. var carry = 0;
  19540. for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
  19541. var word = this.words[i] | 0;
  19542. this.words[i] = (carry << (26 - r)) | (word >>> r);
  19543. carry = word & mask;
  19544. }
  19545. // Push carried bits as a mask
  19546. if (maskedWords && carry !== 0) {
  19547. maskedWords.words[maskedWords.length++] = carry;
  19548. }
  19549. if (this.length === 0) {
  19550. this.words[0] = 0;
  19551. this.length = 1;
  19552. }
  19553. return this.strip();
  19554. };
  19555. BN.prototype.ishrn = function ishrn (bits, hint, extended) {
  19556. // TODO(indutny): implement me
  19557. assert(this.negative === 0);
  19558. return this.iushrn(bits, hint, extended);
  19559. };
  19560. // Shift-left
  19561. BN.prototype.shln = function shln (bits) {
  19562. return this.clone().ishln(bits);
  19563. };
  19564. BN.prototype.ushln = function ushln (bits) {
  19565. return this.clone().iushln(bits);
  19566. };
  19567. // Shift-right
  19568. BN.prototype.shrn = function shrn (bits) {
  19569. return this.clone().ishrn(bits);
  19570. };
  19571. BN.prototype.ushrn = function ushrn (bits) {
  19572. return this.clone().iushrn(bits);
  19573. };
  19574. // Test if n bit is set
  19575. BN.prototype.testn = function testn (bit) {
  19576. assert(typeof bit === 'number' && bit >= 0);
  19577. var r = bit % 26;
  19578. var s = (bit - r) / 26;
  19579. var q = 1 << r;
  19580. // Fast case: bit is much higher than all existing words
  19581. if (this.length <= s) return false;
  19582. // Check bit and return
  19583. var w = this.words[s];
  19584. return !!(w & q);
  19585. };
  19586. // Return only lowers bits of number (in-place)
  19587. BN.prototype.imaskn = function imaskn (bits) {
  19588. assert(typeof bits === 'number' && bits >= 0);
  19589. var r = bits % 26;
  19590. var s = (bits - r) / 26;
  19591. assert(this.negative === 0, 'imaskn works only with positive numbers');
  19592. if (this.length <= s) {
  19593. return this;
  19594. }
  19595. if (r !== 0) {
  19596. s++;
  19597. }
  19598. this.length = Math.min(s, this.length);
  19599. if (r !== 0) {
  19600. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  19601. this.words[this.length - 1] &= mask;
  19602. }
  19603. return this.strip();
  19604. };
  19605. // Return only lowers bits of number
  19606. BN.prototype.maskn = function maskn (bits) {
  19607. return this.clone().imaskn(bits);
  19608. };
  19609. // Add plain number `num` to `this`
  19610. BN.prototype.iaddn = function iaddn (num) {
  19611. assert(typeof num === 'number');
  19612. assert(num < 0x4000000);
  19613. if (num < 0) return this.isubn(-num);
  19614. // Possible sign change
  19615. if (this.negative !== 0) {
  19616. if (this.length === 1 && (this.words[0] | 0) < num) {
  19617. this.words[0] = num - (this.words[0] | 0);
  19618. this.negative = 0;
  19619. return this;
  19620. }
  19621. this.negative = 0;
  19622. this.isubn(num);
  19623. this.negative = 1;
  19624. return this;
  19625. }
  19626. // Add without checks
  19627. return this._iaddn(num);
  19628. };
  19629. BN.prototype._iaddn = function _iaddn (num) {
  19630. this.words[0] += num;
  19631. // Carry
  19632. for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
  19633. this.words[i] -= 0x4000000;
  19634. if (i === this.length - 1) {
  19635. this.words[i + 1] = 1;
  19636. } else {
  19637. this.words[i + 1]++;
  19638. }
  19639. }
  19640. this.length = Math.max(this.length, i + 1);
  19641. return this;
  19642. };
  19643. // Subtract plain number `num` from `this`
  19644. BN.prototype.isubn = function isubn (num) {
  19645. assert(typeof num === 'number');
  19646. assert(num < 0x4000000);
  19647. if (num < 0) return this.iaddn(-num);
  19648. if (this.negative !== 0) {
  19649. this.negative = 0;
  19650. this.iaddn(num);
  19651. this.negative = 1;
  19652. return this;
  19653. }
  19654. this.words[0] -= num;
  19655. if (this.length === 1 && this.words[0] < 0) {
  19656. this.words[0] = -this.words[0];
  19657. this.negative = 1;
  19658. } else {
  19659. // Carry
  19660. for (var i = 0; i < this.length && this.words[i] < 0; i++) {
  19661. this.words[i] += 0x4000000;
  19662. this.words[i + 1] -= 1;
  19663. }
  19664. }
  19665. return this.strip();
  19666. };
  19667. BN.prototype.addn = function addn (num) {
  19668. return this.clone().iaddn(num);
  19669. };
  19670. BN.prototype.subn = function subn (num) {
  19671. return this.clone().isubn(num);
  19672. };
  19673. BN.prototype.iabs = function iabs () {
  19674. this.negative = 0;
  19675. return this;
  19676. };
  19677. BN.prototype.abs = function abs () {
  19678. return this.clone().iabs();
  19679. };
  19680. BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
  19681. var len = num.length + shift;
  19682. var i;
  19683. this._expand(len);
  19684. var w;
  19685. var carry = 0;
  19686. for (i = 0; i < num.length; i++) {
  19687. w = (this.words[i + shift] | 0) + carry;
  19688. var right = (num.words[i] | 0) * mul;
  19689. w -= right & 0x3ffffff;
  19690. carry = (w >> 26) - ((right / 0x4000000) | 0);
  19691. this.words[i + shift] = w & 0x3ffffff;
  19692. }
  19693. for (; i < this.length - shift; i++) {
  19694. w = (this.words[i + shift] | 0) + carry;
  19695. carry = w >> 26;
  19696. this.words[i + shift] = w & 0x3ffffff;
  19697. }
  19698. if (carry === 0) return this.strip();
  19699. // Subtraction overflow
  19700. assert(carry === -1);
  19701. carry = 0;
  19702. for (i = 0; i < this.length; i++) {
  19703. w = -(this.words[i] | 0) + carry;
  19704. carry = w >> 26;
  19705. this.words[i] = w & 0x3ffffff;
  19706. }
  19707. this.negative = 1;
  19708. return this.strip();
  19709. };
  19710. BN.prototype._wordDiv = function _wordDiv (num, mode) {
  19711. var shift = this.length - num.length;
  19712. var a = this.clone();
  19713. var b = num;
  19714. // Normalize
  19715. var bhi = b.words[b.length - 1] | 0;
  19716. var bhiBits = this._countBits(bhi);
  19717. shift = 26 - bhiBits;
  19718. if (shift !== 0) {
  19719. b = b.ushln(shift);
  19720. a.iushln(shift);
  19721. bhi = b.words[b.length - 1] | 0;
  19722. }
  19723. // Initialize quotient
  19724. var m = a.length - b.length;
  19725. var q;
  19726. if (mode !== 'mod') {
  19727. q = new BN(null);
  19728. q.length = m + 1;
  19729. q.words = new Array(q.length);
  19730. for (var i = 0; i < q.length; i++) {
  19731. q.words[i] = 0;
  19732. }
  19733. }
  19734. var diff = a.clone()._ishlnsubmul(b, 1, m);
  19735. if (diff.negative === 0) {
  19736. a = diff;
  19737. if (q) {
  19738. q.words[m] = 1;
  19739. }
  19740. }
  19741. for (var j = m - 1; j >= 0; j--) {
  19742. var qj = (a.words[b.length + j] | 0) * 0x4000000 +
  19743. (a.words[b.length + j - 1] | 0);
  19744. // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
  19745. // (0x7ffffff)
  19746. qj = Math.min((qj / bhi) | 0, 0x3ffffff);
  19747. a._ishlnsubmul(b, qj, j);
  19748. while (a.negative !== 0) {
  19749. qj--;
  19750. a.negative = 0;
  19751. a._ishlnsubmul(b, 1, j);
  19752. if (!a.isZero()) {
  19753. a.negative ^= 1;
  19754. }
  19755. }
  19756. if (q) {
  19757. q.words[j] = qj;
  19758. }
  19759. }
  19760. if (q) {
  19761. q.strip();
  19762. }
  19763. a.strip();
  19764. // Denormalize
  19765. if (mode !== 'div' && shift !== 0) {
  19766. a.iushrn(shift);
  19767. }
  19768. return {
  19769. div: q || null,
  19770. mod: a
  19771. };
  19772. };
  19773. // NOTE: 1) `mode` can be set to `mod` to request mod only,
  19774. // to `div` to request div only, or be absent to
  19775. // request both div & mod
  19776. // 2) `positive` is true if unsigned mod is requested
  19777. BN.prototype.divmod = function divmod (num, mode, positive) {
  19778. assert(!num.isZero());
  19779. if (this.isZero()) {
  19780. return {
  19781. div: new BN(0),
  19782. mod: new BN(0)
  19783. };
  19784. }
  19785. var div, mod, res;
  19786. if (this.negative !== 0 && num.negative === 0) {
  19787. res = this.neg().divmod(num, mode);
  19788. if (mode !== 'mod') {
  19789. div = res.div.neg();
  19790. }
  19791. if (mode !== 'div') {
  19792. mod = res.mod.neg();
  19793. if (positive && mod.negative !== 0) {
  19794. mod.iadd(num);
  19795. }
  19796. }
  19797. return {
  19798. div: div,
  19799. mod: mod
  19800. };
  19801. }
  19802. if (this.negative === 0 && num.negative !== 0) {
  19803. res = this.divmod(num.neg(), mode);
  19804. if (mode !== 'mod') {
  19805. div = res.div.neg();
  19806. }
  19807. return {
  19808. div: div,
  19809. mod: res.mod
  19810. };
  19811. }
  19812. if ((this.negative & num.negative) !== 0) {
  19813. res = this.neg().divmod(num.neg(), mode);
  19814. if (mode !== 'div') {
  19815. mod = res.mod.neg();
  19816. if (positive && mod.negative !== 0) {
  19817. mod.isub(num);
  19818. }
  19819. }
  19820. return {
  19821. div: res.div,
  19822. mod: mod
  19823. };
  19824. }
  19825. // Both numbers are positive at this point
  19826. // Strip both numbers to approximate shift value
  19827. if (num.length > this.length || this.cmp(num) < 0) {
  19828. return {
  19829. div: new BN(0),
  19830. mod: this
  19831. };
  19832. }
  19833. // Very short reduction
  19834. if (num.length === 1) {
  19835. if (mode === 'div') {
  19836. return {
  19837. div: this.divn(num.words[0]),
  19838. mod: null
  19839. };
  19840. }
  19841. if (mode === 'mod') {
  19842. return {
  19843. div: null,
  19844. mod: new BN(this.modn(num.words[0]))
  19845. };
  19846. }
  19847. return {
  19848. div: this.divn(num.words[0]),
  19849. mod: new BN(this.modn(num.words[0]))
  19850. };
  19851. }
  19852. return this._wordDiv(num, mode);
  19853. };
  19854. // Find `this` / `num`
  19855. BN.prototype.div = function div (num) {
  19856. return this.divmod(num, 'div', false).div;
  19857. };
  19858. // Find `this` % `num`
  19859. BN.prototype.mod = function mod (num) {
  19860. return this.divmod(num, 'mod', false).mod;
  19861. };
  19862. BN.prototype.umod = function umod (num) {
  19863. return this.divmod(num, 'mod', true).mod;
  19864. };
  19865. // Find Round(`this` / `num`)
  19866. BN.prototype.divRound = function divRound (num) {
  19867. var dm = this.divmod(num);
  19868. // Fast case - exact division
  19869. if (dm.mod.isZero()) return dm.div;
  19870. var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
  19871. var half = num.ushrn(1);
  19872. var r2 = num.andln(1);
  19873. var cmp = mod.cmp(half);
  19874. // Round down
  19875. if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
  19876. // Round up
  19877. return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  19878. };
  19879. BN.prototype.modn = function modn (num) {
  19880. assert(num <= 0x3ffffff);
  19881. var p = (1 << 26) % num;
  19882. var acc = 0;
  19883. for (var i = this.length - 1; i >= 0; i--) {
  19884. acc = (p * acc + (this.words[i] | 0)) % num;
  19885. }
  19886. return acc;
  19887. };
  19888. // In-place division by number
  19889. BN.prototype.idivn = function idivn (num) {
  19890. assert(num <= 0x3ffffff);
  19891. var carry = 0;
  19892. for (var i = this.length - 1; i >= 0; i--) {
  19893. var w = (this.words[i] | 0) + carry * 0x4000000;
  19894. this.words[i] = (w / num) | 0;
  19895. carry = w % num;
  19896. }
  19897. return this.strip();
  19898. };
  19899. BN.prototype.divn = function divn (num) {
  19900. return this.clone().idivn(num);
  19901. };
  19902. BN.prototype.egcd = function egcd (p) {
  19903. assert(p.negative === 0);
  19904. assert(!p.isZero());
  19905. var x = this;
  19906. var y = p.clone();
  19907. if (x.negative !== 0) {
  19908. x = x.umod(p);
  19909. } else {
  19910. x = x.clone();
  19911. }
  19912. // A * x + B * y = x
  19913. var A = new BN(1);
  19914. var B = new BN(0);
  19915. // C * x + D * y = y
  19916. var C = new BN(0);
  19917. var D = new BN(1);
  19918. var g = 0;
  19919. while (x.isEven() && y.isEven()) {
  19920. x.iushrn(1);
  19921. y.iushrn(1);
  19922. ++g;
  19923. }
  19924. var yp = y.clone();
  19925. var xp = x.clone();
  19926. while (!x.isZero()) {
  19927. for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  19928. if (i > 0) {
  19929. x.iushrn(i);
  19930. while (i-- > 0) {
  19931. if (A.isOdd() || B.isOdd()) {
  19932. A.iadd(yp);
  19933. B.isub(xp);
  19934. }
  19935. A.iushrn(1);
  19936. B.iushrn(1);
  19937. }
  19938. }
  19939. for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  19940. if (j > 0) {
  19941. y.iushrn(j);
  19942. while (j-- > 0) {
  19943. if (C.isOdd() || D.isOdd()) {
  19944. C.iadd(yp);
  19945. D.isub(xp);
  19946. }
  19947. C.iushrn(1);
  19948. D.iushrn(1);
  19949. }
  19950. }
  19951. if (x.cmp(y) >= 0) {
  19952. x.isub(y);
  19953. A.isub(C);
  19954. B.isub(D);
  19955. } else {
  19956. y.isub(x);
  19957. C.isub(A);
  19958. D.isub(B);
  19959. }
  19960. }
  19961. return {
  19962. a: C,
  19963. b: D,
  19964. gcd: y.iushln(g)
  19965. };
  19966. };
  19967. // This is reduced incarnation of the binary EEA
  19968. // above, designated to invert members of the
  19969. // _prime_ fields F(p) at a maximal speed
  19970. BN.prototype._invmp = function _invmp (p) {
  19971. assert(p.negative === 0);
  19972. assert(!p.isZero());
  19973. var a = this;
  19974. var b = p.clone();
  19975. if (a.negative !== 0) {
  19976. a = a.umod(p);
  19977. } else {
  19978. a = a.clone();
  19979. }
  19980. var x1 = new BN(1);
  19981. var x2 = new BN(0);
  19982. var delta = b.clone();
  19983. while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
  19984. for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  19985. if (i > 0) {
  19986. a.iushrn(i);
  19987. while (i-- > 0) {
  19988. if (x1.isOdd()) {
  19989. x1.iadd(delta);
  19990. }
  19991. x1.iushrn(1);
  19992. }
  19993. }
  19994. for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  19995. if (j > 0) {
  19996. b.iushrn(j);
  19997. while (j-- > 0) {
  19998. if (x2.isOdd()) {
  19999. x2.iadd(delta);
  20000. }
  20001. x2.iushrn(1);
  20002. }
  20003. }
  20004. if (a.cmp(b) >= 0) {
  20005. a.isub(b);
  20006. x1.isub(x2);
  20007. } else {
  20008. b.isub(a);
  20009. x2.isub(x1);
  20010. }
  20011. }
  20012. var res;
  20013. if (a.cmpn(1) === 0) {
  20014. res = x1;
  20015. } else {
  20016. res = x2;
  20017. }
  20018. if (res.cmpn(0) < 0) {
  20019. res.iadd(p);
  20020. }
  20021. return res;
  20022. };
  20023. BN.prototype.gcd = function gcd (num) {
  20024. if (this.isZero()) return num.abs();
  20025. if (num.isZero()) return this.abs();
  20026. var a = this.clone();
  20027. var b = num.clone();
  20028. a.negative = 0;
  20029. b.negative = 0;
  20030. // Remove common factor of two
  20031. for (var shift = 0; a.isEven() && b.isEven(); shift++) {
  20032. a.iushrn(1);
  20033. b.iushrn(1);
  20034. }
  20035. do {
  20036. while (a.isEven()) {
  20037. a.iushrn(1);
  20038. }
  20039. while (b.isEven()) {
  20040. b.iushrn(1);
  20041. }
  20042. var r = a.cmp(b);
  20043. if (r < 0) {
  20044. // Swap `a` and `b` to make `a` always bigger than `b`
  20045. var t = a;
  20046. a = b;
  20047. b = t;
  20048. } else if (r === 0 || b.cmpn(1) === 0) {
  20049. break;
  20050. }
  20051. a.isub(b);
  20052. } while (true);
  20053. return b.iushln(shift);
  20054. };
  20055. // Invert number in the field F(num)
  20056. BN.prototype.invm = function invm (num) {
  20057. return this.egcd(num).a.umod(num);
  20058. };
  20059. BN.prototype.isEven = function isEven () {
  20060. return (this.words[0] & 1) === 0;
  20061. };
  20062. BN.prototype.isOdd = function isOdd () {
  20063. return (this.words[0] & 1) === 1;
  20064. };
  20065. // And first word and num
  20066. BN.prototype.andln = function andln (num) {
  20067. return this.words[0] & num;
  20068. };
  20069. // Increment at the bit position in-line
  20070. BN.prototype.bincn = function bincn (bit) {
  20071. assert(typeof bit === 'number');
  20072. var r = bit % 26;
  20073. var s = (bit - r) / 26;
  20074. var q = 1 << r;
  20075. // Fast case: bit is much higher than all existing words
  20076. if (this.length <= s) {
  20077. this._expand(s + 1);
  20078. this.words[s] |= q;
  20079. return this;
  20080. }
  20081. // Add bit and propagate, if needed
  20082. var carry = q;
  20083. for (var i = s; carry !== 0 && i < this.length; i++) {
  20084. var w = this.words[i] | 0;
  20085. w += carry;
  20086. carry = w >>> 26;
  20087. w &= 0x3ffffff;
  20088. this.words[i] = w;
  20089. }
  20090. if (carry !== 0) {
  20091. this.words[i] = carry;
  20092. this.length++;
  20093. }
  20094. return this;
  20095. };
  20096. BN.prototype.isZero = function isZero () {
  20097. return this.length === 1 && this.words[0] === 0;
  20098. };
  20099. BN.prototype.cmpn = function cmpn (num) {
  20100. var negative = num < 0;
  20101. if (this.negative !== 0 && !negative) return -1;
  20102. if (this.negative === 0 && negative) return 1;
  20103. this.strip();
  20104. var res;
  20105. if (this.length > 1) {
  20106. res = 1;
  20107. } else {
  20108. if (negative) {
  20109. num = -num;
  20110. }
  20111. assert(num <= 0x3ffffff, 'Number is too big');
  20112. var w = this.words[0] | 0;
  20113. res = w === num ? 0 : w < num ? -1 : 1;
  20114. }
  20115. if (this.negative !== 0) return -res | 0;
  20116. return res;
  20117. };
  20118. // Compare two numbers and return:
  20119. // 1 - if `this` > `num`
  20120. // 0 - if `this` == `num`
  20121. // -1 - if `this` < `num`
  20122. BN.prototype.cmp = function cmp (num) {
  20123. if (this.negative !== 0 && num.negative === 0) return -1;
  20124. if (this.negative === 0 && num.negative !== 0) return 1;
  20125. var res = this.ucmp(num);
  20126. if (this.negative !== 0) return -res | 0;
  20127. return res;
  20128. };
  20129. // Unsigned comparison
  20130. BN.prototype.ucmp = function ucmp (num) {
  20131. // At this point both numbers have the same sign
  20132. if (this.length > num.length) return 1;
  20133. if (this.length < num.length) return -1;
  20134. var res = 0;
  20135. for (var i = this.length - 1; i >= 0; i--) {
  20136. var a = this.words[i] | 0;
  20137. var b = num.words[i] | 0;
  20138. if (a === b) continue;
  20139. if (a < b) {
  20140. res = -1;
  20141. } else if (a > b) {
  20142. res = 1;
  20143. }
  20144. break;
  20145. }
  20146. return res;
  20147. };
  20148. BN.prototype.gtn = function gtn (num) {
  20149. return this.cmpn(num) === 1;
  20150. };
  20151. BN.prototype.gt = function gt (num) {
  20152. return this.cmp(num) === 1;
  20153. };
  20154. BN.prototype.gten = function gten (num) {
  20155. return this.cmpn(num) >= 0;
  20156. };
  20157. BN.prototype.gte = function gte (num) {
  20158. return this.cmp(num) >= 0;
  20159. };
  20160. BN.prototype.ltn = function ltn (num) {
  20161. return this.cmpn(num) === -1;
  20162. };
  20163. BN.prototype.lt = function lt (num) {
  20164. return this.cmp(num) === -1;
  20165. };
  20166. BN.prototype.lten = function lten (num) {
  20167. return this.cmpn(num) <= 0;
  20168. };
  20169. BN.prototype.lte = function lte (num) {
  20170. return this.cmp(num) <= 0;
  20171. };
  20172. BN.prototype.eqn = function eqn (num) {
  20173. return this.cmpn(num) === 0;
  20174. };
  20175. BN.prototype.eq = function eq (num) {
  20176. return this.cmp(num) === 0;
  20177. };
  20178. //
  20179. // A reduce context, could be using montgomery or something better, depending
  20180. // on the `m` itself.
  20181. //
  20182. BN.red = function red (num) {
  20183. return new Red(num);
  20184. };
  20185. BN.prototype.toRed = function toRed (ctx) {
  20186. assert(!this.red, 'Already a number in reduction context');
  20187. assert(this.negative === 0, 'red works only with positives');
  20188. return ctx.convertTo(this)._forceRed(ctx);
  20189. };
  20190. BN.prototype.fromRed = function fromRed () {
  20191. assert(this.red, 'fromRed works only with numbers in reduction context');
  20192. return this.red.convertFrom(this);
  20193. };
  20194. BN.prototype._forceRed = function _forceRed (ctx) {
  20195. this.red = ctx;
  20196. return this;
  20197. };
  20198. BN.prototype.forceRed = function forceRed (ctx) {
  20199. assert(!this.red, 'Already a number in reduction context');
  20200. return this._forceRed(ctx);
  20201. };
  20202. BN.prototype.redAdd = function redAdd (num) {
  20203. assert(this.red, 'redAdd works only with red numbers');
  20204. return this.red.add(this, num);
  20205. };
  20206. BN.prototype.redIAdd = function redIAdd (num) {
  20207. assert(this.red, 'redIAdd works only with red numbers');
  20208. return this.red.iadd(this, num);
  20209. };
  20210. BN.prototype.redSub = function redSub (num) {
  20211. assert(this.red, 'redSub works only with red numbers');
  20212. return this.red.sub(this, num);
  20213. };
  20214. BN.prototype.redISub = function redISub (num) {
  20215. assert(this.red, 'redISub works only with red numbers');
  20216. return this.red.isub(this, num);
  20217. };
  20218. BN.prototype.redShl = function redShl (num) {
  20219. assert(this.red, 'redShl works only with red numbers');
  20220. return this.red.shl(this, num);
  20221. };
  20222. BN.prototype.redMul = function redMul (num) {
  20223. assert(this.red, 'redMul works only with red numbers');
  20224. this.red._verify2(this, num);
  20225. return this.red.mul(this, num);
  20226. };
  20227. BN.prototype.redIMul = function redIMul (num) {
  20228. assert(this.red, 'redMul works only with red numbers');
  20229. this.red._verify2(this, num);
  20230. return this.red.imul(this, num);
  20231. };
  20232. BN.prototype.redSqr = function redSqr () {
  20233. assert(this.red, 'redSqr works only with red numbers');
  20234. this.red._verify1(this);
  20235. return this.red.sqr(this);
  20236. };
  20237. BN.prototype.redISqr = function redISqr () {
  20238. assert(this.red, 'redISqr works only with red numbers');
  20239. this.red._verify1(this);
  20240. return this.red.isqr(this);
  20241. };
  20242. // Square root over p
  20243. BN.prototype.redSqrt = function redSqrt () {
  20244. assert(this.red, 'redSqrt works only with red numbers');
  20245. this.red._verify1(this);
  20246. return this.red.sqrt(this);
  20247. };
  20248. BN.prototype.redInvm = function redInvm () {
  20249. assert(this.red, 'redInvm works only with red numbers');
  20250. this.red._verify1(this);
  20251. return this.red.invm(this);
  20252. };
  20253. // Return negative clone of `this` % `red modulo`
  20254. BN.prototype.redNeg = function redNeg () {
  20255. assert(this.red, 'redNeg works only with red numbers');
  20256. this.red._verify1(this);
  20257. return this.red.neg(this);
  20258. };
  20259. BN.prototype.redPow = function redPow (num) {
  20260. assert(this.red && !num.red, 'redPow(normalNum)');
  20261. this.red._verify1(this);
  20262. return this.red.pow(this, num);
  20263. };
  20264. // Prime numbers with efficient reduction
  20265. var primes = {
  20266. k256: null,
  20267. p224: null,
  20268. p192: null,
  20269. p25519: null
  20270. };
  20271. // Pseudo-Mersenne prime
  20272. function MPrime (name, p) {
  20273. // P = 2 ^ N - K
  20274. this.name = name;
  20275. this.p = new BN(p, 16);
  20276. this.n = this.p.bitLength();
  20277. this.k = new BN(1).iushln(this.n).isub(this.p);
  20278. this.tmp = this._tmp();
  20279. }
  20280. MPrime.prototype._tmp = function _tmp () {
  20281. var tmp = new BN(null);
  20282. tmp.words = new Array(Math.ceil(this.n / 13));
  20283. return tmp;
  20284. };
  20285. MPrime.prototype.ireduce = function ireduce (num) {
  20286. // Assumes that `num` is less than `P^2`
  20287. // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
  20288. var r = num;
  20289. var rlen;
  20290. do {
  20291. this.split(r, this.tmp);
  20292. r = this.imulK(r);
  20293. r = r.iadd(this.tmp);
  20294. rlen = r.bitLength();
  20295. } while (rlen > this.n);
  20296. var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
  20297. if (cmp === 0) {
  20298. r.words[0] = 0;
  20299. r.length = 1;
  20300. } else if (cmp > 0) {
  20301. r.isub(this.p);
  20302. } else {
  20303. if (r.strip !== undefined) {
  20304. // r is BN v4 instance
  20305. r.strip();
  20306. } else {
  20307. // r is BN v5 instance
  20308. r._strip();
  20309. }
  20310. }
  20311. return r;
  20312. };
  20313. MPrime.prototype.split = function split (input, out) {
  20314. input.iushrn(this.n, 0, out);
  20315. };
  20316. MPrime.prototype.imulK = function imulK (num) {
  20317. return num.imul(this.k);
  20318. };
  20319. function K256 () {
  20320. MPrime.call(
  20321. this,
  20322. 'k256',
  20323. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  20324. }
  20325. inherits(K256, MPrime);
  20326. K256.prototype.split = function split (input, output) {
  20327. // 256 = 9 * 26 + 22
  20328. var mask = 0x3fffff;
  20329. var outLen = Math.min(input.length, 9);
  20330. for (var i = 0; i < outLen; i++) {
  20331. output.words[i] = input.words[i];
  20332. }
  20333. output.length = outLen;
  20334. if (input.length <= 9) {
  20335. input.words[0] = 0;
  20336. input.length = 1;
  20337. return;
  20338. }
  20339. // Shift by 9 limbs
  20340. var prev = input.words[9];
  20341. output.words[output.length++] = prev & mask;
  20342. for (i = 10; i < input.length; i++) {
  20343. var next = input.words[i] | 0;
  20344. input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
  20345. prev = next;
  20346. }
  20347. prev >>>= 22;
  20348. input.words[i - 10] = prev;
  20349. if (prev === 0 && input.length > 10) {
  20350. input.length -= 10;
  20351. } else {
  20352. input.length -= 9;
  20353. }
  20354. };
  20355. K256.prototype.imulK = function imulK (num) {
  20356. // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
  20357. num.words[num.length] = 0;
  20358. num.words[num.length + 1] = 0;
  20359. num.length += 2;
  20360. // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
  20361. var lo = 0;
  20362. for (var i = 0; i < num.length; i++) {
  20363. var w = num.words[i] | 0;
  20364. lo += w * 0x3d1;
  20365. num.words[i] = lo & 0x3ffffff;
  20366. lo = w * 0x40 + ((lo / 0x4000000) | 0);
  20367. }
  20368. // Fast length reduction
  20369. if (num.words[num.length - 1] === 0) {
  20370. num.length--;
  20371. if (num.words[num.length - 1] === 0) {
  20372. num.length--;
  20373. }
  20374. }
  20375. return num;
  20376. };
  20377. function P224 () {
  20378. MPrime.call(
  20379. this,
  20380. 'p224',
  20381. 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  20382. }
  20383. inherits(P224, MPrime);
  20384. function P192 () {
  20385. MPrime.call(
  20386. this,
  20387. 'p192',
  20388. 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  20389. }
  20390. inherits(P192, MPrime);
  20391. function P25519 () {
  20392. // 2 ^ 255 - 19
  20393. MPrime.call(
  20394. this,
  20395. '25519',
  20396. '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  20397. }
  20398. inherits(P25519, MPrime);
  20399. P25519.prototype.imulK = function imulK (num) {
  20400. // K = 0x13
  20401. var carry = 0;
  20402. for (var i = 0; i < num.length; i++) {
  20403. var hi = (num.words[i] | 0) * 0x13 + carry;
  20404. var lo = hi & 0x3ffffff;
  20405. hi >>>= 26;
  20406. num.words[i] = lo;
  20407. carry = hi;
  20408. }
  20409. if (carry !== 0) {
  20410. num.words[num.length++] = carry;
  20411. }
  20412. return num;
  20413. };
  20414. // Exported mostly for testing purposes, use plain name instead
  20415. BN._prime = function prime (name) {
  20416. // Cached version of prime
  20417. if (primes[name]) return primes[name];
  20418. var prime;
  20419. if (name === 'k256') {
  20420. prime = new K256();
  20421. } else if (name === 'p224') {
  20422. prime = new P224();
  20423. } else if (name === 'p192') {
  20424. prime = new P192();
  20425. } else if (name === 'p25519') {
  20426. prime = new P25519();
  20427. } else {
  20428. throw new Error('Unknown prime ' + name);
  20429. }
  20430. primes[name] = prime;
  20431. return prime;
  20432. };
  20433. //
  20434. // Base reduction engine
  20435. //
  20436. function Red (m) {
  20437. if (typeof m === 'string') {
  20438. var prime = BN._prime(m);
  20439. this.m = prime.p;
  20440. this.prime = prime;
  20441. } else {
  20442. assert(m.gtn(1), 'modulus must be greater than 1');
  20443. this.m = m;
  20444. this.prime = null;
  20445. }
  20446. }
  20447. Red.prototype._verify1 = function _verify1 (a) {
  20448. assert(a.negative === 0, 'red works only with positives');
  20449. assert(a.red, 'red works only with red numbers');
  20450. };
  20451. Red.prototype._verify2 = function _verify2 (a, b) {
  20452. assert((a.negative | b.negative) === 0, 'red works only with positives');
  20453. assert(a.red && a.red === b.red,
  20454. 'red works only with red numbers');
  20455. };
  20456. Red.prototype.imod = function imod (a) {
  20457. if (this.prime) return this.prime.ireduce(a)._forceRed(this);
  20458. return a.umod(this.m)._forceRed(this);
  20459. };
  20460. Red.prototype.neg = function neg (a) {
  20461. if (a.isZero()) {
  20462. return a.clone();
  20463. }
  20464. return this.m.sub(a)._forceRed(this);
  20465. };
  20466. Red.prototype.add = function add (a, b) {
  20467. this._verify2(a, b);
  20468. var res = a.add(b);
  20469. if (res.cmp(this.m) >= 0) {
  20470. res.isub(this.m);
  20471. }
  20472. return res._forceRed(this);
  20473. };
  20474. Red.prototype.iadd = function iadd (a, b) {
  20475. this._verify2(a, b);
  20476. var res = a.iadd(b);
  20477. if (res.cmp(this.m) >= 0) {
  20478. res.isub(this.m);
  20479. }
  20480. return res;
  20481. };
  20482. Red.prototype.sub = function sub (a, b) {
  20483. this._verify2(a, b);
  20484. var res = a.sub(b);
  20485. if (res.cmpn(0) < 0) {
  20486. res.iadd(this.m);
  20487. }
  20488. return res._forceRed(this);
  20489. };
  20490. Red.prototype.isub = function isub (a, b) {
  20491. this._verify2(a, b);
  20492. var res = a.isub(b);
  20493. if (res.cmpn(0) < 0) {
  20494. res.iadd(this.m);
  20495. }
  20496. return res;
  20497. };
  20498. Red.prototype.shl = function shl (a, num) {
  20499. this._verify1(a);
  20500. return this.imod(a.ushln(num));
  20501. };
  20502. Red.prototype.imul = function imul (a, b) {
  20503. this._verify2(a, b);
  20504. return this.imod(a.imul(b));
  20505. };
  20506. Red.prototype.mul = function mul (a, b) {
  20507. this._verify2(a, b);
  20508. return this.imod(a.mul(b));
  20509. };
  20510. Red.prototype.isqr = function isqr (a) {
  20511. return this.imul(a, a.clone());
  20512. };
  20513. Red.prototype.sqr = function sqr (a) {
  20514. return this.mul(a, a);
  20515. };
  20516. Red.prototype.sqrt = function sqrt (a) {
  20517. if (a.isZero()) return a.clone();
  20518. var mod3 = this.m.andln(3);
  20519. assert(mod3 % 2 === 1);
  20520. // Fast case
  20521. if (mod3 === 3) {
  20522. var pow = this.m.add(new BN(1)).iushrn(2);
  20523. return this.pow(a, pow);
  20524. }
  20525. // Tonelli-Shanks algorithm (Totally unoptimized and slow)
  20526. //
  20527. // Find Q and S, that Q * 2 ^ S = (P - 1)
  20528. var q = this.m.subn(1);
  20529. var s = 0;
  20530. while (!q.isZero() && q.andln(1) === 0) {
  20531. s++;
  20532. q.iushrn(1);
  20533. }
  20534. assert(!q.isZero());
  20535. var one = new BN(1).toRed(this);
  20536. var nOne = one.redNeg();
  20537. // Find quadratic non-residue
  20538. // NOTE: Max is such because of generalized Riemann hypothesis.
  20539. var lpow = this.m.subn(1).iushrn(1);
  20540. var z = this.m.bitLength();
  20541. z = new BN(2 * z * z).toRed(this);
  20542. while (this.pow(z, lpow).cmp(nOne) !== 0) {
  20543. z.redIAdd(nOne);
  20544. }
  20545. var c = this.pow(z, q);
  20546. var r = this.pow(a, q.addn(1).iushrn(1));
  20547. var t = this.pow(a, q);
  20548. var m = s;
  20549. while (t.cmp(one) !== 0) {
  20550. var tmp = t;
  20551. for (var i = 0; tmp.cmp(one) !== 0; i++) {
  20552. tmp = tmp.redSqr();
  20553. }
  20554. assert(i < m);
  20555. var b = this.pow(c, new BN(1).iushln(m - i - 1));
  20556. r = r.redMul(b);
  20557. c = b.redSqr();
  20558. t = t.redMul(c);
  20559. m = i;
  20560. }
  20561. return r;
  20562. };
  20563. Red.prototype.invm = function invm (a) {
  20564. var inv = a._invmp(this.m);
  20565. if (inv.negative !== 0) {
  20566. inv.negative = 0;
  20567. return this.imod(inv).redNeg();
  20568. } else {
  20569. return this.imod(inv);
  20570. }
  20571. };
  20572. Red.prototype.pow = function pow (a, num) {
  20573. if (num.isZero()) return new BN(1).toRed(this);
  20574. if (num.cmpn(1) === 0) return a.clone();
  20575. var windowSize = 4;
  20576. var wnd = new Array(1 << windowSize);
  20577. wnd[0] = new BN(1).toRed(this);
  20578. wnd[1] = a;
  20579. for (var i = 2; i < wnd.length; i++) {
  20580. wnd[i] = this.mul(wnd[i - 1], a);
  20581. }
  20582. var res = wnd[0];
  20583. var current = 0;
  20584. var currentLen = 0;
  20585. var start = num.bitLength() % 26;
  20586. if (start === 0) {
  20587. start = 26;
  20588. }
  20589. for (i = num.length - 1; i >= 0; i--) {
  20590. var word = num.words[i];
  20591. for (var j = start - 1; j >= 0; j--) {
  20592. var bit = (word >> j) & 1;
  20593. if (res !== wnd[0]) {
  20594. res = this.sqr(res);
  20595. }
  20596. if (bit === 0 && current === 0) {
  20597. currentLen = 0;
  20598. continue;
  20599. }
  20600. current <<= 1;
  20601. current |= bit;
  20602. currentLen++;
  20603. if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
  20604. res = this.mul(res, wnd[current]);
  20605. currentLen = 0;
  20606. current = 0;
  20607. }
  20608. start = 26;
  20609. }
  20610. return res;
  20611. };
  20612. Red.prototype.convertTo = function convertTo (num) {
  20613. var r = num.umod(this.m);
  20614. return r === num ? r.clone() : r;
  20615. };
  20616. Red.prototype.convertFrom = function convertFrom (num) {
  20617. var res = num.clone();
  20618. res.red = null;
  20619. return res;
  20620. };
  20621. //
  20622. // Montgomery method engine
  20623. //
  20624. BN.mont = function mont (num) {
  20625. return new Mont(num);
  20626. };
  20627. function Mont (m) {
  20628. Red.call(this, m);
  20629. this.shift = this.m.bitLength();
  20630. if (this.shift % 26 !== 0) {
  20631. this.shift += 26 - (this.shift % 26);
  20632. }
  20633. this.r = new BN(1).iushln(this.shift);
  20634. this.r2 = this.imod(this.r.sqr());
  20635. this.rinv = this.r._invmp(this.m);
  20636. this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
  20637. this.minv = this.minv.umod(this.r);
  20638. this.minv = this.r.sub(this.minv);
  20639. }
  20640. inherits(Mont, Red);
  20641. Mont.prototype.convertTo = function convertTo (num) {
  20642. return this.imod(num.ushln(this.shift));
  20643. };
  20644. Mont.prototype.convertFrom = function convertFrom (num) {
  20645. var r = this.imod(num.mul(this.rinv));
  20646. r.red = null;
  20647. return r;
  20648. };
  20649. Mont.prototype.imul = function imul (a, b) {
  20650. if (a.isZero() || b.isZero()) {
  20651. a.words[0] = 0;
  20652. a.length = 1;
  20653. return a;
  20654. }
  20655. var t = a.imul(b);
  20656. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  20657. var u = t.isub(c).iushrn(this.shift);
  20658. var res = u;
  20659. if (u.cmp(this.m) >= 0) {
  20660. res = u.isub(this.m);
  20661. } else if (u.cmpn(0) < 0) {
  20662. res = u.iadd(this.m);
  20663. }
  20664. return res._forceRed(this);
  20665. };
  20666. Mont.prototype.mul = function mul (a, b) {
  20667. if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
  20668. var t = a.mul(b);
  20669. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  20670. var u = t.isub(c).iushrn(this.shift);
  20671. var res = u;
  20672. if (u.cmp(this.m) >= 0) {
  20673. res = u.isub(this.m);
  20674. } else if (u.cmpn(0) < 0) {
  20675. res = u.iadd(this.m);
  20676. }
  20677. return res._forceRed(this);
  20678. };
  20679. Mont.prototype.invm = function invm (a) {
  20680. // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
  20681. var res = this.imod(a._invmp(this.m).mul(this.r2));
  20682. return res._forceRed(this);
  20683. };
  20684. })(typeof module === 'undefined' || module, this);
  20685. },{"buffer":144}],98:[function(require,module,exports){
  20686. // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
  20687. module.exports = {
  20688. newInvalidAsn1Error: function (msg) {
  20689. var e = new Error();
  20690. e.name = 'InvalidAsn1Error';
  20691. e.message = msg || '';
  20692. return e;
  20693. }
  20694. };
  20695. },{}],99:[function(require,module,exports){
  20696. // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
  20697. var errors = require('./errors');
  20698. var types = require('./types');
  20699. var Reader = require('./reader');
  20700. var Writer = require('./writer');
  20701. // --- Exports
  20702. module.exports = {
  20703. Reader: Reader,
  20704. Writer: Writer
  20705. };
  20706. for (var t in types) {
  20707. if (types.hasOwnProperty(t))
  20708. module.exports[t] = types[t];
  20709. }
  20710. for (var e in errors) {
  20711. if (errors.hasOwnProperty(e))
  20712. module.exports[e] = errors[e];
  20713. }
  20714. },{"./errors":98,"./reader":100,"./types":101,"./writer":102}],100:[function(require,module,exports){
  20715. // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
  20716. var assert = require('assert');
  20717. var Buffer = require('safer-buffer').Buffer;
  20718. var ASN1 = require('./types');
  20719. var errors = require('./errors');
  20720. // --- Globals
  20721. var newInvalidAsn1Error = errors.newInvalidAsn1Error;
  20722. // --- API
  20723. function Reader(data) {
  20724. if (!data || !Buffer.isBuffer(data))
  20725. throw new TypeError('data must be a node Buffer');
  20726. this._buf = data;
  20727. this._size = data.length;
  20728. // These hold the "current" state
  20729. this._len = 0;
  20730. this._offset = 0;
  20731. }
  20732. Object.defineProperty(Reader.prototype, 'length', {
  20733. enumerable: true,
  20734. get: function () { return (this._len); }
  20735. });
  20736. Object.defineProperty(Reader.prototype, 'offset', {
  20737. enumerable: true,
  20738. get: function () { return (this._offset); }
  20739. });
  20740. Object.defineProperty(Reader.prototype, 'remain', {
  20741. get: function () { return (this._size - this._offset); }
  20742. });
  20743. Object.defineProperty(Reader.prototype, 'buffer', {
  20744. get: function () { return (this._buf.slice(this._offset)); }
  20745. });
  20746. /**
  20747. * Reads a single byte and advances offset; you can pass in `true` to make this
  20748. * a "peek" operation (i.e., get the byte, but don't advance the offset).
  20749. *
  20750. * @param {Boolean} peek true means don't move offset.
  20751. * @return {Number} the next byte, null if not enough data.
  20752. */
  20753. Reader.prototype.readByte = function (peek) {
  20754. if (this._size - this._offset < 1)
  20755. return null;
  20756. var b = this._buf[this._offset] & 0xff;
  20757. if (!peek)
  20758. this._offset += 1;
  20759. return b;
  20760. };
  20761. Reader.prototype.peek = function () {
  20762. return this.readByte(true);
  20763. };
  20764. /**
  20765. * Reads a (potentially) variable length off the BER buffer. This call is
  20766. * not really meant to be called directly, as callers have to manipulate
  20767. * the internal buffer afterwards.
  20768. *
  20769. * As a result of this call, you can call `Reader.length`, until the
  20770. * next thing called that does a readLength.
  20771. *
  20772. * @return {Number} the amount of offset to advance the buffer.
  20773. * @throws {InvalidAsn1Error} on bad ASN.1
  20774. */
  20775. Reader.prototype.readLength = function (offset) {
  20776. if (offset === undefined)
  20777. offset = this._offset;
  20778. if (offset >= this._size)
  20779. return null;
  20780. var lenB = this._buf[offset++] & 0xff;
  20781. if (lenB === null)
  20782. return null;
  20783. if ((lenB & 0x80) === 0x80) {
  20784. lenB &= 0x7f;
  20785. if (lenB === 0)
  20786. throw newInvalidAsn1Error('Indefinite length not supported');
  20787. if (lenB > 4)
  20788. throw newInvalidAsn1Error('encoding too long');
  20789. if (this._size - offset < lenB)
  20790. return null;
  20791. this._len = 0;
  20792. for (var i = 0; i < lenB; i++)
  20793. this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
  20794. } else {
  20795. // Wasn't a variable length
  20796. this._len = lenB;
  20797. }
  20798. return offset;
  20799. };
  20800. /**
  20801. * Parses the next sequence in this BER buffer.
  20802. *
  20803. * To get the length of the sequence, call `Reader.length`.
  20804. *
  20805. * @return {Number} the sequence's tag.
  20806. */
  20807. Reader.prototype.readSequence = function (tag) {
  20808. var seq = this.peek();
  20809. if (seq === null)
  20810. return null;
  20811. if (tag !== undefined && tag !== seq)
  20812. throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
  20813. ': got 0x' + seq.toString(16));
  20814. var o = this.readLength(this._offset + 1); // stored in `length`
  20815. if (o === null)
  20816. return null;
  20817. this._offset = o;
  20818. return seq;
  20819. };
  20820. Reader.prototype.readInt = function () {
  20821. return this._readTag(ASN1.Integer);
  20822. };
  20823. Reader.prototype.readBoolean = function () {
  20824. return (this._readTag(ASN1.Boolean) === 0 ? false : true);
  20825. };
  20826. Reader.prototype.readEnumeration = function () {
  20827. return this._readTag(ASN1.Enumeration);
  20828. };
  20829. Reader.prototype.readString = function (tag, retbuf) {
  20830. if (!tag)
  20831. tag = ASN1.OctetString;
  20832. var b = this.peek();
  20833. if (b === null)
  20834. return null;
  20835. if (b !== tag)
  20836. throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
  20837. ': got 0x' + b.toString(16));
  20838. var o = this.readLength(this._offset + 1); // stored in `length`
  20839. if (o === null)
  20840. return null;
  20841. if (this.length > this._size - o)
  20842. return null;
  20843. this._offset = o;
  20844. if (this.length === 0)
  20845. return retbuf ? Buffer.alloc(0) : '';
  20846. var str = this._buf.slice(this._offset, this._offset + this.length);
  20847. this._offset += this.length;
  20848. return retbuf ? str : str.toString('utf8');
  20849. };
  20850. Reader.prototype.readOID = function (tag) {
  20851. if (!tag)
  20852. tag = ASN1.OID;
  20853. var b = this.readString(tag, true);
  20854. if (b === null)
  20855. return null;
  20856. var values = [];
  20857. var value = 0;
  20858. for (var i = 0; i < b.length; i++) {
  20859. var byte = b[i] & 0xff;
  20860. value <<= 7;
  20861. value += byte & 0x7f;
  20862. if ((byte & 0x80) === 0) {
  20863. values.push(value);
  20864. value = 0;
  20865. }
  20866. }
  20867. value = values.shift();
  20868. values.unshift(value % 40);
  20869. values.unshift((value / 40) >> 0);
  20870. return values.join('.');
  20871. };
  20872. Reader.prototype._readTag = function (tag) {
  20873. assert.ok(tag !== undefined);
  20874. var b = this.peek();
  20875. if (b === null)
  20876. return null;
  20877. if (b !== tag)
  20878. throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
  20879. ': got 0x' + b.toString(16));
  20880. var o = this.readLength(this._offset + 1); // stored in `length`
  20881. if (o === null)
  20882. return null;
  20883. if (this.length > 4)
  20884. throw newInvalidAsn1Error('Integer too long: ' + this.length);
  20885. if (this.length > this._size - o)
  20886. return null;
  20887. this._offset = o;
  20888. var fb = this._buf[this._offset];
  20889. var value = 0;
  20890. for (var i = 0; i < this.length; i++) {
  20891. value <<= 8;
  20892. value |= (this._buf[this._offset++] & 0xff);
  20893. }
  20894. if ((fb & 0x80) === 0x80 && i !== 4)
  20895. value -= (1 << (i * 8));
  20896. return value >> 0;
  20897. };
  20898. // --- Exported API
  20899. module.exports = Reader;
  20900. },{"./errors":98,"./types":101,"assert":105,"safer-buffer":562}],101:[function(require,module,exports){
  20901. // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
  20902. module.exports = {
  20903. EOC: 0,
  20904. Boolean: 1,
  20905. Integer: 2,
  20906. BitString: 3,
  20907. OctetString: 4,
  20908. Null: 5,
  20909. OID: 6,
  20910. ObjectDescriptor: 7,
  20911. External: 8,
  20912. Real: 9, // float
  20913. Enumeration: 10,
  20914. PDV: 11,
  20915. Utf8String: 12,
  20916. RelativeOID: 13,
  20917. Sequence: 16,
  20918. Set: 17,
  20919. NumericString: 18,
  20920. PrintableString: 19,
  20921. T61String: 20,
  20922. VideotexString: 21,
  20923. IA5String: 22,
  20924. UTCTime: 23,
  20925. GeneralizedTime: 24,
  20926. GraphicString: 25,
  20927. VisibleString: 26,
  20928. GeneralString: 28,
  20929. UniversalString: 29,
  20930. CharacterString: 30,
  20931. BMPString: 31,
  20932. Constructor: 32,
  20933. Context: 128
  20934. };
  20935. },{}],102:[function(require,module,exports){
  20936. // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
  20937. var assert = require('assert');
  20938. var Buffer = require('safer-buffer').Buffer;
  20939. var ASN1 = require('./types');
  20940. var errors = require('./errors');
  20941. // --- Globals
  20942. var newInvalidAsn1Error = errors.newInvalidAsn1Error;
  20943. var DEFAULT_OPTS = {
  20944. size: 1024,
  20945. growthFactor: 8
  20946. };
  20947. // --- Helpers
  20948. function merge(from, to) {
  20949. assert.ok(from);
  20950. assert.equal(typeof (from), 'object');
  20951. assert.ok(to);
  20952. assert.equal(typeof (to), 'object');
  20953. var keys = Object.getOwnPropertyNames(from);
  20954. keys.forEach(function (key) {
  20955. if (to[key])
  20956. return;
  20957. var value = Object.getOwnPropertyDescriptor(from, key);
  20958. Object.defineProperty(to, key, value);
  20959. });
  20960. return to;
  20961. }
  20962. // --- API
  20963. function Writer(options) {
  20964. options = merge(DEFAULT_OPTS, options || {});
  20965. this._buf = Buffer.alloc(options.size || 1024);
  20966. this._size = this._buf.length;
  20967. this._offset = 0;
  20968. this._options = options;
  20969. // A list of offsets in the buffer where we need to insert
  20970. // sequence tag/len pairs.
  20971. this._seq = [];
  20972. }
  20973. Object.defineProperty(Writer.prototype, 'buffer', {
  20974. get: function () {
  20975. if (this._seq.length)
  20976. throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');
  20977. return (this._buf.slice(0, this._offset));
  20978. }
  20979. });
  20980. Writer.prototype.writeByte = function (b) {
  20981. if (typeof (b) !== 'number')
  20982. throw new TypeError('argument must be a Number');
  20983. this._ensure(1);
  20984. this._buf[this._offset++] = b;
  20985. };
  20986. Writer.prototype.writeInt = function (i, tag) {
  20987. if (typeof (i) !== 'number')
  20988. throw new TypeError('argument must be a Number');
  20989. if (typeof (tag) !== 'number')
  20990. tag = ASN1.Integer;
  20991. var sz = 4;
  20992. while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
  20993. (sz > 1)) {
  20994. sz--;
  20995. i <<= 8;
  20996. }
  20997. if (sz > 4)
  20998. throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');
  20999. this._ensure(2 + sz);
  21000. this._buf[this._offset++] = tag;
  21001. this._buf[this._offset++] = sz;
  21002. while (sz-- > 0) {
  21003. this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
  21004. i <<= 8;
  21005. }
  21006. };
  21007. Writer.prototype.writeNull = function () {
  21008. this.writeByte(ASN1.Null);
  21009. this.writeByte(0x00);
  21010. };
  21011. Writer.prototype.writeEnumeration = function (i, tag) {
  21012. if (typeof (i) !== 'number')
  21013. throw new TypeError('argument must be a Number');
  21014. if (typeof (tag) !== 'number')
  21015. tag = ASN1.Enumeration;
  21016. return this.writeInt(i, tag);
  21017. };
  21018. Writer.prototype.writeBoolean = function (b, tag) {
  21019. if (typeof (b) !== 'boolean')
  21020. throw new TypeError('argument must be a Boolean');
  21021. if (typeof (tag) !== 'number')
  21022. tag = ASN1.Boolean;
  21023. this._ensure(3);
  21024. this._buf[this._offset++] = tag;
  21025. this._buf[this._offset++] = 0x01;
  21026. this._buf[this._offset++] = b ? 0xff : 0x00;
  21027. };
  21028. Writer.prototype.writeString = function (s, tag) {
  21029. if (typeof (s) !== 'string')
  21030. throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');
  21031. if (typeof (tag) !== 'number')
  21032. tag = ASN1.OctetString;
  21033. var len = Buffer.byteLength(s);
  21034. this.writeByte(tag);
  21035. this.writeLength(len);
  21036. if (len) {
  21037. this._ensure(len);
  21038. this._buf.write(s, this._offset);
  21039. this._offset += len;
  21040. }
  21041. };
  21042. Writer.prototype.writeBuffer = function (buf, tag) {
  21043. if (typeof (tag) !== 'number')
  21044. throw new TypeError('tag must be a number');
  21045. if (!Buffer.isBuffer(buf))
  21046. throw new TypeError('argument must be a buffer');
  21047. this.writeByte(tag);
  21048. this.writeLength(buf.length);
  21049. this._ensure(buf.length);
  21050. buf.copy(this._buf, this._offset, 0, buf.length);
  21051. this._offset += buf.length;
  21052. };
  21053. Writer.prototype.writeStringArray = function (strings) {
  21054. if ((!strings instanceof Array))
  21055. throw new TypeError('argument must be an Array[String]');
  21056. var self = this;
  21057. strings.forEach(function (s) {
  21058. self.writeString(s);
  21059. });
  21060. };
  21061. // This is really to solve DER cases, but whatever for now
  21062. Writer.prototype.writeOID = function (s, tag) {
  21063. if (typeof (s) !== 'string')
  21064. throw new TypeError('argument must be a string');
  21065. if (typeof (tag) !== 'number')
  21066. tag = ASN1.OID;
  21067. if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
  21068. throw new Error('argument is not a valid OID string');
  21069. function encodeOctet(bytes, octet) {
  21070. if (octet < 128) {
  21071. bytes.push(octet);
  21072. } else if (octet < 16384) {
  21073. bytes.push((octet >>> 7) | 0x80);
  21074. bytes.push(octet & 0x7F);
  21075. } else if (octet < 2097152) {
  21076. bytes.push((octet >>> 14) | 0x80);
  21077. bytes.push(((octet >>> 7) | 0x80) & 0xFF);
  21078. bytes.push(octet & 0x7F);
  21079. } else if (octet < 268435456) {
  21080. bytes.push((octet >>> 21) | 0x80);
  21081. bytes.push(((octet >>> 14) | 0x80) & 0xFF);
  21082. bytes.push(((octet >>> 7) | 0x80) & 0xFF);
  21083. bytes.push(octet & 0x7F);
  21084. } else {
  21085. bytes.push(((octet >>> 28) | 0x80) & 0xFF);
  21086. bytes.push(((octet >>> 21) | 0x80) & 0xFF);
  21087. bytes.push(((octet >>> 14) | 0x80) & 0xFF);
  21088. bytes.push(((octet >>> 7) | 0x80) & 0xFF);
  21089. bytes.push(octet & 0x7F);
  21090. }
  21091. }
  21092. var tmp = s.split('.');
  21093. var bytes = [];
  21094. bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
  21095. tmp.slice(2).forEach(function (b) {
  21096. encodeOctet(bytes, parseInt(b, 10));
  21097. });
  21098. var self = this;
  21099. this._ensure(2 + bytes.length);
  21100. this.writeByte(tag);
  21101. this.writeLength(bytes.length);
  21102. bytes.forEach(function (b) {
  21103. self.writeByte(b);
  21104. });
  21105. };
  21106. Writer.prototype.writeLength = function (len) {
  21107. if (typeof (len) !== 'number')
  21108. throw new TypeError('argument must be a Number');
  21109. this._ensure(4);
  21110. if (len <= 0x7f) {
  21111. this._buf[this._offset++] = len;
  21112. } else if (len <= 0xff) {
  21113. this._buf[this._offset++] = 0x81;
  21114. this._buf[this._offset++] = len;
  21115. } else if (len <= 0xffff) {
  21116. this._buf[this._offset++] = 0x82;
  21117. this._buf[this._offset++] = len >> 8;
  21118. this._buf[this._offset++] = len;
  21119. } else if (len <= 0xffffff) {
  21120. this._buf[this._offset++] = 0x83;
  21121. this._buf[this._offset++] = len >> 16;
  21122. this._buf[this._offset++] = len >> 8;
  21123. this._buf[this._offset++] = len;
  21124. } else {
  21125. throw newInvalidAsn1Error('Length too long (> 4 bytes)');
  21126. }
  21127. };
  21128. Writer.prototype.startSequence = function (tag) {
  21129. if (typeof (tag) !== 'number')
  21130. tag = ASN1.Sequence | ASN1.Constructor;
  21131. this.writeByte(tag);
  21132. this._seq.push(this._offset);
  21133. this._ensure(3);
  21134. this._offset += 3;
  21135. };
  21136. Writer.prototype.endSequence = function () {
  21137. var seq = this._seq.pop();
  21138. var start = seq + 3;
  21139. var len = this._offset - start;
  21140. if (len <= 0x7f) {
  21141. this._shift(start, len, -2);
  21142. this._buf[seq] = len;
  21143. } else if (len <= 0xff) {
  21144. this._shift(start, len, -1);
  21145. this._buf[seq] = 0x81;
  21146. this._buf[seq + 1] = len;
  21147. } else if (len <= 0xffff) {
  21148. this._buf[seq] = 0x82;
  21149. this._buf[seq + 1] = len >> 8;
  21150. this._buf[seq + 2] = len;
  21151. } else if (len <= 0xffffff) {
  21152. this._shift(start, len, 1);
  21153. this._buf[seq] = 0x83;
  21154. this._buf[seq + 1] = len >> 16;
  21155. this._buf[seq + 2] = len >> 8;
  21156. this._buf[seq + 3] = len;
  21157. } else {
  21158. throw newInvalidAsn1Error('Sequence too long');
  21159. }
  21160. };
  21161. Writer.prototype._shift = function (start, len, shift) {
  21162. assert.ok(start !== undefined);
  21163. assert.ok(len !== undefined);
  21164. assert.ok(shift);
  21165. this._buf.copy(this._buf, start + shift, start, start + len);
  21166. this._offset += shift;
  21167. };
  21168. Writer.prototype._ensure = function (len) {
  21169. assert.ok(len);
  21170. if (this._size - this._offset < len) {
  21171. var sz = this._size * this._options.growthFactor;
  21172. if (sz - this._offset < len)
  21173. sz += len;
  21174. var buf = Buffer.alloc(sz);
  21175. this._buf.copy(buf, 0, 0, this._offset);
  21176. this._buf = buf;
  21177. this._size = sz;
  21178. }
  21179. };
  21180. // --- Exported API
  21181. module.exports = Writer;
  21182. },{"./errors":98,"./types":101,"assert":105,"safer-buffer":562}],103:[function(require,module,exports){
  21183. // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
  21184. // If you have no idea what ASN.1 or BER is, see this:
  21185. // ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
  21186. var Ber = require('./ber/index');
  21187. // --- Exported API
  21188. module.exports = {
  21189. Ber: Ber,
  21190. BerReader: Ber.Reader,
  21191. BerWriter: Ber.Writer
  21192. };
  21193. },{"./ber/index":99}],104:[function(require,module,exports){
  21194. (function (Buffer,process){(function (){
  21195. // Copyright (c) 2012, Mark Cavage. All rights reserved.
  21196. // Copyright 2015 Joyent, Inc.
  21197. var assert = require('assert');
  21198. var Stream = require('stream').Stream;
  21199. var util = require('util');
  21200. ///--- Globals
  21201. /* JSSTYLED */
  21202. var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
  21203. ///--- Internal
  21204. function _capitalize(str) {
  21205. return (str.charAt(0).toUpperCase() + str.slice(1));
  21206. }
  21207. function _toss(name, expected, oper, arg, actual) {
  21208. throw new assert.AssertionError({
  21209. message: util.format('%s (%s) is required', name, expected),
  21210. actual: (actual === undefined) ? typeof (arg) : actual(arg),
  21211. expected: expected,
  21212. operator: oper || '===',
  21213. stackStartFunction: _toss.caller
  21214. });
  21215. }
  21216. function _getClass(arg) {
  21217. return (Object.prototype.toString.call(arg).slice(8, -1));
  21218. }
  21219. function noop() {
  21220. // Why even bother with asserts?
  21221. }
  21222. ///--- Exports
  21223. var types = {
  21224. bool: {
  21225. check: function (arg) { return typeof (arg) === 'boolean'; }
  21226. },
  21227. func: {
  21228. check: function (arg) { return typeof (arg) === 'function'; }
  21229. },
  21230. string: {
  21231. check: function (arg) { return typeof (arg) === 'string'; }
  21232. },
  21233. object: {
  21234. check: function (arg) {
  21235. return typeof (arg) === 'object' && arg !== null;
  21236. }
  21237. },
  21238. number: {
  21239. check: function (arg) {
  21240. return typeof (arg) === 'number' && !isNaN(arg);
  21241. }
  21242. },
  21243. finite: {
  21244. check: function (arg) {
  21245. return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
  21246. }
  21247. },
  21248. buffer: {
  21249. check: function (arg) { return Buffer.isBuffer(arg); },
  21250. operator: 'Buffer.isBuffer'
  21251. },
  21252. array: {
  21253. check: function (arg) { return Array.isArray(arg); },
  21254. operator: 'Array.isArray'
  21255. },
  21256. stream: {
  21257. check: function (arg) { return arg instanceof Stream; },
  21258. operator: 'instanceof',
  21259. actual: _getClass
  21260. },
  21261. date: {
  21262. check: function (arg) { return arg instanceof Date; },
  21263. operator: 'instanceof',
  21264. actual: _getClass
  21265. },
  21266. regexp: {
  21267. check: function (arg) { return arg instanceof RegExp; },
  21268. operator: 'instanceof',
  21269. actual: _getClass
  21270. },
  21271. uuid: {
  21272. check: function (arg) {
  21273. return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
  21274. },
  21275. operator: 'isUUID'
  21276. }
  21277. };
  21278. function _setExports(ndebug) {
  21279. var keys = Object.keys(types);
  21280. var out;
  21281. /* re-export standard assert */
  21282. if (process.env.NODE_NDEBUG) {
  21283. out = noop;
  21284. } else {
  21285. out = function (arg, msg) {
  21286. if (!arg) {
  21287. _toss(msg, 'true', arg);
  21288. }
  21289. };
  21290. }
  21291. /* standard checks */
  21292. keys.forEach(function (k) {
  21293. if (ndebug) {
  21294. out[k] = noop;
  21295. return;
  21296. }
  21297. var type = types[k];
  21298. out[k] = function (arg, msg) {
  21299. if (!type.check(arg)) {
  21300. _toss(msg, k, type.operator, arg, type.actual);
  21301. }
  21302. };
  21303. });
  21304. /* optional checks */
  21305. keys.forEach(function (k) {
  21306. var name = 'optional' + _capitalize(k);
  21307. if (ndebug) {
  21308. out[name] = noop;
  21309. return;
  21310. }
  21311. var type = types[k];
  21312. out[name] = function (arg, msg) {
  21313. if (arg === undefined || arg === null) {
  21314. return;
  21315. }
  21316. if (!type.check(arg)) {
  21317. _toss(msg, k, type.operator, arg, type.actual);
  21318. }
  21319. };
  21320. });
  21321. /* arrayOf checks */
  21322. keys.forEach(function (k) {
  21323. var name = 'arrayOf' + _capitalize(k);
  21324. if (ndebug) {
  21325. out[name] = noop;
  21326. return;
  21327. }
  21328. var type = types[k];
  21329. var expected = '[' + k + ']';
  21330. out[name] = function (arg, msg) {
  21331. if (!Array.isArray(arg)) {
  21332. _toss(msg, expected, type.operator, arg, type.actual);
  21333. }
  21334. var i;
  21335. for (i = 0; i < arg.length; i++) {
  21336. if (!type.check(arg[i])) {
  21337. _toss(msg, expected, type.operator, arg, type.actual);
  21338. }
  21339. }
  21340. };
  21341. });
  21342. /* optionalArrayOf checks */
  21343. keys.forEach(function (k) {
  21344. var name = 'optionalArrayOf' + _capitalize(k);
  21345. if (ndebug) {
  21346. out[name] = noop;
  21347. return;
  21348. }
  21349. var type = types[k];
  21350. var expected = '[' + k + ']';
  21351. out[name] = function (arg, msg) {
  21352. if (arg === undefined || arg === null) {
  21353. return;
  21354. }
  21355. if (!Array.isArray(arg)) {
  21356. _toss(msg, expected, type.operator, arg, type.actual);
  21357. }
  21358. var i;
  21359. for (i = 0; i < arg.length; i++) {
  21360. if (!type.check(arg[i])) {
  21361. _toss(msg, expected, type.operator, arg, type.actual);
  21362. }
  21363. }
  21364. };
  21365. });
  21366. /* re-export built-in assertions */
  21367. Object.keys(assert).forEach(function (k) {
  21368. if (k === 'AssertionError') {
  21369. out[k] = assert[k];
  21370. return;
  21371. }
  21372. if (ndebug) {
  21373. out[k] = noop;
  21374. return;
  21375. }
  21376. out[k] = assert[k];
  21377. });
  21378. /* export ourselves (for unit tests _only_) */
  21379. out._setExports = _setExports;
  21380. return out;
  21381. }
  21382. module.exports = _setExports(process.env.NODE_NDEBUG);
  21383. }).call(this)}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
  21384. },{"../is-buffer/index.js":322,"_process":525,"assert":105,"stream":597,"util":658}],105:[function(require,module,exports){
  21385. (function (global){(function (){
  21386. 'use strict';
  21387. var objectAssign = require('object-assign');
  21388. // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  21389. // original notice:
  21390. /*!
  21391. * The buffer module from node.js, for the browser.
  21392. *
  21393. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  21394. * @license MIT
  21395. */
  21396. function compare(a, b) {
  21397. if (a === b) {
  21398. return 0;
  21399. }
  21400. var x = a.length;
  21401. var y = b.length;
  21402. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  21403. if (a[i] !== b[i]) {
  21404. x = a[i];
  21405. y = b[i];
  21406. break;
  21407. }
  21408. }
  21409. if (x < y) {
  21410. return -1;
  21411. }
  21412. if (y < x) {
  21413. return 1;
  21414. }
  21415. return 0;
  21416. }
  21417. function isBuffer(b) {
  21418. if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
  21419. return global.Buffer.isBuffer(b);
  21420. }
  21421. return !!(b != null && b._isBuffer);
  21422. }
  21423. // based on node assert, original notice:
  21424. // NB: The URL to the CommonJS spec is kept just for tradition.
  21425. // node-assert has evolved a lot since then, both in API and behavior.
  21426. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  21427. //
  21428. // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  21429. //
  21430. // Originally from narwhal.js (http://narwhaljs.org)
  21431. // Copyright (c) 2009 Thomas Robinson <280north.com>
  21432. //
  21433. // Permission is hereby granted, free of charge, to any person obtaining a copy
  21434. // of this software and associated documentation files (the 'Software'), to
  21435. // deal in the Software without restriction, including without limitation the
  21436. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  21437. // sell copies of the Software, and to permit persons to whom the Software is
  21438. // furnished to do so, subject to the following conditions:
  21439. //
  21440. // The above copyright notice and this permission notice shall be included in
  21441. // all copies or substantial portions of the Software.
  21442. //
  21443. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21444. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21445. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21446. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  21447. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21448. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21449. var util = require('util/');
  21450. var hasOwn = Object.prototype.hasOwnProperty;
  21451. var pSlice = Array.prototype.slice;
  21452. var functionsHaveNames = (function () {
  21453. return function foo() {}.name === 'foo';
  21454. }());
  21455. function pToString (obj) {
  21456. return Object.prototype.toString.call(obj);
  21457. }
  21458. function isView(arrbuf) {
  21459. if (isBuffer(arrbuf)) {
  21460. return false;
  21461. }
  21462. if (typeof global.ArrayBuffer !== 'function') {
  21463. return false;
  21464. }
  21465. if (typeof ArrayBuffer.isView === 'function') {
  21466. return ArrayBuffer.isView(arrbuf);
  21467. }
  21468. if (!arrbuf) {
  21469. return false;
  21470. }
  21471. if (arrbuf instanceof DataView) {
  21472. return true;
  21473. }
  21474. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  21475. return true;
  21476. }
  21477. return false;
  21478. }
  21479. // 1. The assert module provides functions that throw
  21480. // AssertionError's when particular conditions are not met. The
  21481. // assert module must conform to the following interface.
  21482. var assert = module.exports = ok;
  21483. // 2. The AssertionError is defined in assert.
  21484. // new assert.AssertionError({ message: message,
  21485. // actual: actual,
  21486. // expected: expected })
  21487. var regex = /\s*function\s+([^\(\s]*)\s*/;
  21488. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  21489. function getName(func) {
  21490. if (!util.isFunction(func)) {
  21491. return;
  21492. }
  21493. if (functionsHaveNames) {
  21494. return func.name;
  21495. }
  21496. var str = func.toString();
  21497. var match = str.match(regex);
  21498. return match && match[1];
  21499. }
  21500. assert.AssertionError = function AssertionError(options) {
  21501. this.name = 'AssertionError';
  21502. this.actual = options.actual;
  21503. this.expected = options.expected;
  21504. this.operator = options.operator;
  21505. if (options.message) {
  21506. this.message = options.message;
  21507. this.generatedMessage = false;
  21508. } else {
  21509. this.message = getMessage(this);
  21510. this.generatedMessage = true;
  21511. }
  21512. var stackStartFunction = options.stackStartFunction || fail;
  21513. if (Error.captureStackTrace) {
  21514. Error.captureStackTrace(this, stackStartFunction);
  21515. } else {
  21516. // non v8 browsers so we can have a stacktrace
  21517. var err = new Error();
  21518. if (err.stack) {
  21519. var out = err.stack;
  21520. // try to strip useless frames
  21521. var fn_name = getName(stackStartFunction);
  21522. var idx = out.indexOf('\n' + fn_name);
  21523. if (idx >= 0) {
  21524. // once we have located the function frame
  21525. // we need to strip out everything before it (and its line)
  21526. var next_line = out.indexOf('\n', idx + 1);
  21527. out = out.substring(next_line + 1);
  21528. }
  21529. this.stack = out;
  21530. }
  21531. }
  21532. };
  21533. // assert.AssertionError instanceof Error
  21534. util.inherits(assert.AssertionError, Error);
  21535. function truncate(s, n) {
  21536. if (typeof s === 'string') {
  21537. return s.length < n ? s : s.slice(0, n);
  21538. } else {
  21539. return s;
  21540. }
  21541. }
  21542. function inspect(something) {
  21543. if (functionsHaveNames || !util.isFunction(something)) {
  21544. return util.inspect(something);
  21545. }
  21546. var rawname = getName(something);
  21547. var name = rawname ? ': ' + rawname : '';
  21548. return '[Function' + name + ']';
  21549. }
  21550. function getMessage(self) {
  21551. return truncate(inspect(self.actual), 128) + ' ' +
  21552. self.operator + ' ' +
  21553. truncate(inspect(self.expected), 128);
  21554. }
  21555. // At present only the three keys mentioned above are used and
  21556. // understood by the spec. Implementations or sub modules can pass
  21557. // other keys to the AssertionError's constructor - they will be
  21558. // ignored.
  21559. // 3. All of the following functions must throw an AssertionError
  21560. // when a corresponding condition is not met, with a message that
  21561. // may be undefined if not provided. All assertion methods provide
  21562. // both the actual and expected values to the assertion error for
  21563. // display purposes.
  21564. function fail(actual, expected, message, operator, stackStartFunction) {
  21565. throw new assert.AssertionError({
  21566. message: message,
  21567. actual: actual,
  21568. expected: expected,
  21569. operator: operator,
  21570. stackStartFunction: stackStartFunction
  21571. });
  21572. }
  21573. // EXTENSION! allows for well behaved errors defined elsewhere.
  21574. assert.fail = fail;
  21575. // 4. Pure assertion tests whether a value is truthy, as determined
  21576. // by !!guard.
  21577. // assert.ok(guard, message_opt);
  21578. // This statement is equivalent to assert.equal(true, !!guard,
  21579. // message_opt);. To test strictly for the value true, use
  21580. // assert.strictEqual(true, guard, message_opt);.
  21581. function ok(value, message) {
  21582. if (!value) fail(value, true, message, '==', assert.ok);
  21583. }
  21584. assert.ok = ok;
  21585. // 5. The equality assertion tests shallow, coercive equality with
  21586. // ==.
  21587. // assert.equal(actual, expected, message_opt);
  21588. assert.equal = function equal(actual, expected, message) {
  21589. if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  21590. };
  21591. // 6. The non-equality assertion tests for whether two objects are not equal
  21592. // with != assert.notEqual(actual, expected, message_opt);
  21593. assert.notEqual = function notEqual(actual, expected, message) {
  21594. if (actual == expected) {
  21595. fail(actual, expected, message, '!=', assert.notEqual);
  21596. }
  21597. };
  21598. // 7. The equivalence assertion tests a deep equality relation.
  21599. // assert.deepEqual(actual, expected, message_opt);
  21600. assert.deepEqual = function deepEqual(actual, expected, message) {
  21601. if (!_deepEqual(actual, expected, false)) {
  21602. fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  21603. }
  21604. };
  21605. assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  21606. if (!_deepEqual(actual, expected, true)) {
  21607. fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  21608. }
  21609. };
  21610. function _deepEqual(actual, expected, strict, memos) {
  21611. // 7.1. All identical values are equivalent, as determined by ===.
  21612. if (actual === expected) {
  21613. return true;
  21614. } else if (isBuffer(actual) && isBuffer(expected)) {
  21615. return compare(actual, expected) === 0;
  21616. // 7.2. If the expected value is a Date object, the actual value is
  21617. // equivalent if it is also a Date object that refers to the same time.
  21618. } else if (util.isDate(actual) && util.isDate(expected)) {
  21619. return actual.getTime() === expected.getTime();
  21620. // 7.3 If the expected value is a RegExp object, the actual value is
  21621. // equivalent if it is also a RegExp object with the same source and
  21622. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  21623. } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  21624. return actual.source === expected.source &&
  21625. actual.global === expected.global &&
  21626. actual.multiline === expected.multiline &&
  21627. actual.lastIndex === expected.lastIndex &&
  21628. actual.ignoreCase === expected.ignoreCase;
  21629. // 7.4. Other pairs that do not both pass typeof value == 'object',
  21630. // equivalence is determined by ==.
  21631. } else if ((actual === null || typeof actual !== 'object') &&
  21632. (expected === null || typeof expected !== 'object')) {
  21633. return strict ? actual === expected : actual == expected;
  21634. // If both values are instances of typed arrays, wrap their underlying
  21635. // ArrayBuffers in a Buffer each to increase performance
  21636. // This optimization requires the arrays to have the same type as checked by
  21637. // Object.prototype.toString (aka pToString). Never perform binary
  21638. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  21639. // bit patterns are not identical.
  21640. } else if (isView(actual) && isView(expected) &&
  21641. pToString(actual) === pToString(expected) &&
  21642. !(actual instanceof Float32Array ||
  21643. actual instanceof Float64Array)) {
  21644. return compare(new Uint8Array(actual.buffer),
  21645. new Uint8Array(expected.buffer)) === 0;
  21646. // 7.5 For all other Object pairs, including Array objects, equivalence is
  21647. // determined by having the same number of owned properties (as verified
  21648. // with Object.prototype.hasOwnProperty.call), the same set of keys
  21649. // (although not necessarily the same order), equivalent values for every
  21650. // corresponding key, and an identical 'prototype' property. Note: this
  21651. // accounts for both named and indexed properties on Arrays.
  21652. } else if (isBuffer(actual) !== isBuffer(expected)) {
  21653. return false;
  21654. } else {
  21655. memos = memos || {actual: [], expected: []};
  21656. var actualIndex = memos.actual.indexOf(actual);
  21657. if (actualIndex !== -1) {
  21658. if (actualIndex === memos.expected.indexOf(expected)) {
  21659. return true;
  21660. }
  21661. }
  21662. memos.actual.push(actual);
  21663. memos.expected.push(expected);
  21664. return objEquiv(actual, expected, strict, memos);
  21665. }
  21666. }
  21667. function isArguments(object) {
  21668. return Object.prototype.toString.call(object) == '[object Arguments]';
  21669. }
  21670. function objEquiv(a, b, strict, actualVisitedObjects) {
  21671. if (a === null || a === undefined || b === null || b === undefined)
  21672. return false;
  21673. // if one is a primitive, the other must be same
  21674. if (util.isPrimitive(a) || util.isPrimitive(b))
  21675. return a === b;
  21676. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  21677. return false;
  21678. var aIsArgs = isArguments(a);
  21679. var bIsArgs = isArguments(b);
  21680. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  21681. return false;
  21682. if (aIsArgs) {
  21683. a = pSlice.call(a);
  21684. b = pSlice.call(b);
  21685. return _deepEqual(a, b, strict);
  21686. }
  21687. var ka = objectKeys(a);
  21688. var kb = objectKeys(b);
  21689. var key, i;
  21690. // having the same number of owned properties (keys incorporates
  21691. // hasOwnProperty)
  21692. if (ka.length !== kb.length)
  21693. return false;
  21694. //the same set of keys (although not necessarily the same order),
  21695. ka.sort();
  21696. kb.sort();
  21697. //~~~cheap key test
  21698. for (i = ka.length - 1; i >= 0; i--) {
  21699. if (ka[i] !== kb[i])
  21700. return false;
  21701. }
  21702. //equivalent values for every corresponding key, and
  21703. //~~~possibly expensive deep test
  21704. for (i = ka.length - 1; i >= 0; i--) {
  21705. key = ka[i];
  21706. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  21707. return false;
  21708. }
  21709. return true;
  21710. }
  21711. // 8. The non-equivalence assertion tests for any deep inequality.
  21712. // assert.notDeepEqual(actual, expected, message_opt);
  21713. assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  21714. if (_deepEqual(actual, expected, false)) {
  21715. fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  21716. }
  21717. };
  21718. assert.notDeepStrictEqual = notDeepStrictEqual;
  21719. function notDeepStrictEqual(actual, expected, message) {
  21720. if (_deepEqual(actual, expected, true)) {
  21721. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  21722. }
  21723. }
  21724. // 9. The strict equality assertion tests strict equality, as determined by ===.
  21725. // assert.strictEqual(actual, expected, message_opt);
  21726. assert.strictEqual = function strictEqual(actual, expected, message) {
  21727. if (actual !== expected) {
  21728. fail(actual, expected, message, '===', assert.strictEqual);
  21729. }
  21730. };
  21731. // 10. The strict non-equality assertion tests for strict inequality, as
  21732. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  21733. assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  21734. if (actual === expected) {
  21735. fail(actual, expected, message, '!==', assert.notStrictEqual);
  21736. }
  21737. };
  21738. function expectedException(actual, expected) {
  21739. if (!actual || !expected) {
  21740. return false;
  21741. }
  21742. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  21743. return expected.test(actual);
  21744. }
  21745. try {
  21746. if (actual instanceof expected) {
  21747. return true;
  21748. }
  21749. } catch (e) {
  21750. // Ignore. The instanceof check doesn't work for arrow functions.
  21751. }
  21752. if (Error.isPrototypeOf(expected)) {
  21753. return false;
  21754. }
  21755. return expected.call({}, actual) === true;
  21756. }
  21757. function _tryBlock(block) {
  21758. var error;
  21759. try {
  21760. block();
  21761. } catch (e) {
  21762. error = e;
  21763. }
  21764. return error;
  21765. }
  21766. function _throws(shouldThrow, block, expected, message) {
  21767. var actual;
  21768. if (typeof block !== 'function') {
  21769. throw new TypeError('"block" argument must be a function');
  21770. }
  21771. if (typeof expected === 'string') {
  21772. message = expected;
  21773. expected = null;
  21774. }
  21775. actual = _tryBlock(block);
  21776. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  21777. (message ? ' ' + message : '.');
  21778. if (shouldThrow && !actual) {
  21779. fail(actual, expected, 'Missing expected exception' + message);
  21780. }
  21781. var userProvidedMessage = typeof message === 'string';
  21782. var isUnwantedException = !shouldThrow && util.isError(actual);
  21783. var isUnexpectedException = !shouldThrow && actual && !expected;
  21784. if ((isUnwantedException &&
  21785. userProvidedMessage &&
  21786. expectedException(actual, expected)) ||
  21787. isUnexpectedException) {
  21788. fail(actual, expected, 'Got unwanted exception' + message);
  21789. }
  21790. if ((shouldThrow && actual && expected &&
  21791. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  21792. throw actual;
  21793. }
  21794. }
  21795. // 11. Expected to throw an error:
  21796. // assert.throws(block, Error_opt, message_opt);
  21797. assert.throws = function(block, /*optional*/error, /*optional*/message) {
  21798. _throws(true, block, error, message);
  21799. };
  21800. // EXTENSION! This is annoying to write outside this module.
  21801. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  21802. _throws(false, block, error, message);
  21803. };
  21804. assert.ifError = function(err) { if (err) throw err; };
  21805. // Expose a strict only variant of assert
  21806. function strict(value, message) {
  21807. if (!value) fail(value, true, message, '==', strict);
  21808. }
  21809. assert.strict = objectAssign(strict, assert, {
  21810. equal: assert.strictEqual,
  21811. deepEqual: assert.deepStrictEqual,
  21812. notEqual: assert.notStrictEqual,
  21813. notDeepEqual: assert.notDeepStrictEqual
  21814. });
  21815. assert.strict.strict = assert.strict;
  21816. var objectKeys = Object.keys || function (obj) {
  21817. var keys = [];
  21818. for (var key in obj) {
  21819. if (hasOwn.call(obj, key)) keys.push(key);
  21820. }
  21821. return keys;
  21822. };
  21823. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  21824. },{"object-assign":499,"util/":108}],106:[function(require,module,exports){
  21825. if (typeof Object.create === 'function') {
  21826. // implementation from standard node.js 'util' module
  21827. module.exports = function inherits(ctor, superCtor) {
  21828. ctor.super_ = superCtor
  21829. ctor.prototype = Object.create(superCtor.prototype, {
  21830. constructor: {
  21831. value: ctor,
  21832. enumerable: false,
  21833. writable: true,
  21834. configurable: true
  21835. }
  21836. });
  21837. };
  21838. } else {
  21839. // old school shim for old browsers
  21840. module.exports = function inherits(ctor, superCtor) {
  21841. ctor.super_ = superCtor
  21842. var TempCtor = function () {}
  21843. TempCtor.prototype = superCtor.prototype
  21844. ctor.prototype = new TempCtor()
  21845. ctor.prototype.constructor = ctor
  21846. }
  21847. }
  21848. },{}],107:[function(require,module,exports){
  21849. module.exports = function isBuffer(arg) {
  21850. return arg && typeof arg === 'object'
  21851. && typeof arg.copy === 'function'
  21852. && typeof arg.fill === 'function'
  21853. && typeof arg.readUInt8 === 'function';
  21854. }
  21855. },{}],108:[function(require,module,exports){
  21856. (function (process,global){(function (){
  21857. // Copyright Joyent, Inc. and other Node contributors.
  21858. //
  21859. // Permission is hereby granted, free of charge, to any person obtaining a
  21860. // copy of this software and associated documentation files (the
  21861. // "Software"), to deal in the Software without restriction, including
  21862. // without limitation the rights to use, copy, modify, merge, publish,
  21863. // distribute, sublicense, and/or sell copies of the Software, and to permit
  21864. // persons to whom the Software is furnished to do so, subject to the
  21865. // following conditions:
  21866. //
  21867. // The above copyright notice and this permission notice shall be included
  21868. // in all copies or substantial portions of the Software.
  21869. //
  21870. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  21871. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21872. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  21873. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  21874. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  21875. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21876. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  21877. var formatRegExp = /%[sdj%]/g;
  21878. exports.format = function(f) {
  21879. if (!isString(f)) {
  21880. var objects = [];
  21881. for (var i = 0; i < arguments.length; i++) {
  21882. objects.push(inspect(arguments[i]));
  21883. }
  21884. return objects.join(' ');
  21885. }
  21886. var i = 1;
  21887. var args = arguments;
  21888. var len = args.length;
  21889. var str = String(f).replace(formatRegExp, function(x) {
  21890. if (x === '%%') return '%';
  21891. if (i >= len) return x;
  21892. switch (x) {
  21893. case '%s': return String(args[i++]);
  21894. case '%d': return Number(args[i++]);
  21895. case '%j':
  21896. try {
  21897. return JSON.stringify(args[i++]);
  21898. } catch (_) {
  21899. return '[Circular]';
  21900. }
  21901. default:
  21902. return x;
  21903. }
  21904. });
  21905. for (var x = args[i]; i < len; x = args[++i]) {
  21906. if (isNull(x) || !isObject(x)) {
  21907. str += ' ' + x;
  21908. } else {
  21909. str += ' ' + inspect(x);
  21910. }
  21911. }
  21912. return str;
  21913. };
  21914. // Mark that a method should not be used.
  21915. // Returns a modified function which warns once by default.
  21916. // If --no-deprecation is set, then it is a no-op.
  21917. exports.deprecate = function(fn, msg) {
  21918. // Allow for deprecating things in the process of starting up.
  21919. if (isUndefined(global.process)) {
  21920. return function() {
  21921. return exports.deprecate(fn, msg).apply(this, arguments);
  21922. };
  21923. }
  21924. if (process.noDeprecation === true) {
  21925. return fn;
  21926. }
  21927. var warned = false;
  21928. function deprecated() {
  21929. if (!warned) {
  21930. if (process.throwDeprecation) {
  21931. throw new Error(msg);
  21932. } else if (process.traceDeprecation) {
  21933. console.trace(msg);
  21934. } else {
  21935. console.error(msg);
  21936. }
  21937. warned = true;
  21938. }
  21939. return fn.apply(this, arguments);
  21940. }
  21941. return deprecated;
  21942. };
  21943. var debugs = {};
  21944. var debugEnviron;
  21945. exports.debuglog = function(set) {
  21946. if (isUndefined(debugEnviron))
  21947. debugEnviron = process.env.NODE_DEBUG || '';
  21948. set = set.toUpperCase();
  21949. if (!debugs[set]) {
  21950. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  21951. var pid = process.pid;
  21952. debugs[set] = function() {
  21953. var msg = exports.format.apply(exports, arguments);
  21954. console.error('%s %d: %s', set, pid, msg);
  21955. };
  21956. } else {
  21957. debugs[set] = function() {};
  21958. }
  21959. }
  21960. return debugs[set];
  21961. };
  21962. /**
  21963. * Echos the value of a value. Trys to print the value out
  21964. * in the best way possible given the different types.
  21965. *
  21966. * @param {Object} obj The object to print out.
  21967. * @param {Object} opts Optional options object that alters the output.
  21968. */
  21969. /* legacy: obj, showHidden, depth, colors*/
  21970. function inspect(obj, opts) {
  21971. // default options
  21972. var ctx = {
  21973. seen: [],
  21974. stylize: stylizeNoColor
  21975. };
  21976. // legacy...
  21977. if (arguments.length >= 3) ctx.depth = arguments[2];
  21978. if (arguments.length >= 4) ctx.colors = arguments[3];
  21979. if (isBoolean(opts)) {
  21980. // legacy...
  21981. ctx.showHidden = opts;
  21982. } else if (opts) {
  21983. // got an "options" object
  21984. exports._extend(ctx, opts);
  21985. }
  21986. // set default options
  21987. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  21988. if (isUndefined(ctx.depth)) ctx.depth = 2;
  21989. if (isUndefined(ctx.colors)) ctx.colors = false;
  21990. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  21991. if (ctx.colors) ctx.stylize = stylizeWithColor;
  21992. return formatValue(ctx, obj, ctx.depth);
  21993. }
  21994. exports.inspect = inspect;
  21995. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  21996. inspect.colors = {
  21997. 'bold' : [1, 22],
  21998. 'italic' : [3, 23],
  21999. 'underline' : [4, 24],
  22000. 'inverse' : [7, 27],
  22001. 'white' : [37, 39],
  22002. 'grey' : [90, 39],
  22003. 'black' : [30, 39],
  22004. 'blue' : [34, 39],
  22005. 'cyan' : [36, 39],
  22006. 'green' : [32, 39],
  22007. 'magenta' : [35, 39],
  22008. 'red' : [31, 39],
  22009. 'yellow' : [33, 39]
  22010. };
  22011. // Don't use 'blue' not visible on cmd.exe
  22012. inspect.styles = {
  22013. 'special': 'cyan',
  22014. 'number': 'yellow',
  22015. 'boolean': 'yellow',
  22016. 'undefined': 'grey',
  22017. 'null': 'bold',
  22018. 'string': 'green',
  22019. 'date': 'magenta',
  22020. // "name": intentionally not styling
  22021. 'regexp': 'red'
  22022. };
  22023. function stylizeWithColor(str, styleType) {
  22024. var style = inspect.styles[styleType];
  22025. if (style) {
  22026. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  22027. '\u001b[' + inspect.colors[style][1] + 'm';
  22028. } else {
  22029. return str;
  22030. }
  22031. }
  22032. function stylizeNoColor(str, styleType) {
  22033. return str;
  22034. }
  22035. function arrayToHash(array) {
  22036. var hash = {};
  22037. array.forEach(function(val, idx) {
  22038. hash[val] = true;
  22039. });
  22040. return hash;
  22041. }
  22042. function formatValue(ctx, value, recurseTimes) {
  22043. // Provide a hook for user-specified inspect functions.
  22044. // Check that value is an object with an inspect function on it
  22045. if (ctx.customInspect &&
  22046. value &&
  22047. isFunction(value.inspect) &&
  22048. // Filter out the util module, it's inspect function is special
  22049. value.inspect !== exports.inspect &&
  22050. // Also filter out any prototype objects using the circular check.
  22051. !(value.constructor && value.constructor.prototype === value)) {
  22052. var ret = value.inspect(recurseTimes, ctx);
  22053. if (!isString(ret)) {
  22054. ret = formatValue(ctx, ret, recurseTimes);
  22055. }
  22056. return ret;
  22057. }
  22058. // Primitive types cannot have properties
  22059. var primitive = formatPrimitive(ctx, value);
  22060. if (primitive) {
  22061. return primitive;
  22062. }
  22063. // Look up the keys of the object.
  22064. var keys = Object.keys(value);
  22065. var visibleKeys = arrayToHash(keys);
  22066. if (ctx.showHidden) {
  22067. keys = Object.getOwnPropertyNames(value);
  22068. }
  22069. // IE doesn't make error fields non-enumerable
  22070. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  22071. if (isError(value)
  22072. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  22073. return formatError(value);
  22074. }
  22075. // Some type of object without properties can be shortcutted.
  22076. if (keys.length === 0) {
  22077. if (isFunction(value)) {
  22078. var name = value.name ? ': ' + value.name : '';
  22079. return ctx.stylize('[Function' + name + ']', 'special');
  22080. }
  22081. if (isRegExp(value)) {
  22082. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  22083. }
  22084. if (isDate(value)) {
  22085. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  22086. }
  22087. if (isError(value)) {
  22088. return formatError(value);
  22089. }
  22090. }
  22091. var base = '', array = false, braces = ['{', '}'];
  22092. // Make Array say that they are Array
  22093. if (isArray(value)) {
  22094. array = true;
  22095. braces = ['[', ']'];
  22096. }
  22097. // Make functions say that they are functions
  22098. if (isFunction(value)) {
  22099. var n = value.name ? ': ' + value.name : '';
  22100. base = ' [Function' + n + ']';
  22101. }
  22102. // Make RegExps say that they are RegExps
  22103. if (isRegExp(value)) {
  22104. base = ' ' + RegExp.prototype.toString.call(value);
  22105. }
  22106. // Make dates with properties first say the date
  22107. if (isDate(value)) {
  22108. base = ' ' + Date.prototype.toUTCString.call(value);
  22109. }
  22110. // Make error with message first say the error
  22111. if (isError(value)) {
  22112. base = ' ' + formatError(value);
  22113. }
  22114. if (keys.length === 0 && (!array || value.length == 0)) {
  22115. return braces[0] + base + braces[1];
  22116. }
  22117. if (recurseTimes < 0) {
  22118. if (isRegExp(value)) {
  22119. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  22120. } else {
  22121. return ctx.stylize('[Object]', 'special');
  22122. }
  22123. }
  22124. ctx.seen.push(value);
  22125. var output;
  22126. if (array) {
  22127. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  22128. } else {
  22129. output = keys.map(function(key) {
  22130. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  22131. });
  22132. }
  22133. ctx.seen.pop();
  22134. return reduceToSingleString(output, base, braces);
  22135. }
  22136. function formatPrimitive(ctx, value) {
  22137. if (isUndefined(value))
  22138. return ctx.stylize('undefined', 'undefined');
  22139. if (isString(value)) {
  22140. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  22141. .replace(/'/g, "\\'")
  22142. .replace(/\\"/g, '"') + '\'';
  22143. return ctx.stylize(simple, 'string');
  22144. }
  22145. if (isNumber(value))
  22146. return ctx.stylize('' + value, 'number');
  22147. if (isBoolean(value))
  22148. return ctx.stylize('' + value, 'boolean');
  22149. // For some reason typeof null is "object", so special case here.
  22150. if (isNull(value))
  22151. return ctx.stylize('null', 'null');
  22152. }
  22153. function formatError(value) {
  22154. return '[' + Error.prototype.toString.call(value) + ']';
  22155. }
  22156. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  22157. var output = [];
  22158. for (var i = 0, l = value.length; i < l; ++i) {
  22159. if (hasOwnProperty(value, String(i))) {
  22160. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  22161. String(i), true));
  22162. } else {
  22163. output.push('');
  22164. }
  22165. }
  22166. keys.forEach(function(key) {
  22167. if (!key.match(/^\d+$/)) {
  22168. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  22169. key, true));
  22170. }
  22171. });
  22172. return output;
  22173. }
  22174. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  22175. var name, str, desc;
  22176. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  22177. if (desc.get) {
  22178. if (desc.set) {
  22179. str = ctx.stylize('[Getter/Setter]', 'special');
  22180. } else {
  22181. str = ctx.stylize('[Getter]', 'special');
  22182. }
  22183. } else {
  22184. if (desc.set) {
  22185. str = ctx.stylize('[Setter]', 'special');
  22186. }
  22187. }
  22188. if (!hasOwnProperty(visibleKeys, key)) {
  22189. name = '[' + key + ']';
  22190. }
  22191. if (!str) {
  22192. if (ctx.seen.indexOf(desc.value) < 0) {
  22193. if (isNull(recurseTimes)) {
  22194. str = formatValue(ctx, desc.value, null);
  22195. } else {
  22196. str = formatValue(ctx, desc.value, recurseTimes - 1);
  22197. }
  22198. if (str.indexOf('\n') > -1) {
  22199. if (array) {
  22200. str = str.split('\n').map(function(line) {
  22201. return ' ' + line;
  22202. }).join('\n').substr(2);
  22203. } else {
  22204. str = '\n' + str.split('\n').map(function(line) {
  22205. return ' ' + line;
  22206. }).join('\n');
  22207. }
  22208. }
  22209. } else {
  22210. str = ctx.stylize('[Circular]', 'special');
  22211. }
  22212. }
  22213. if (isUndefined(name)) {
  22214. if (array && key.match(/^\d+$/)) {
  22215. return str;
  22216. }
  22217. name = JSON.stringify('' + key);
  22218. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  22219. name = name.substr(1, name.length - 2);
  22220. name = ctx.stylize(name, 'name');
  22221. } else {
  22222. name = name.replace(/'/g, "\\'")
  22223. .replace(/\\"/g, '"')
  22224. .replace(/(^"|"$)/g, "'");
  22225. name = ctx.stylize(name, 'string');
  22226. }
  22227. }
  22228. return name + ': ' + str;
  22229. }
  22230. function reduceToSingleString(output, base, braces) {
  22231. var numLinesEst = 0;
  22232. var length = output.reduce(function(prev, cur) {
  22233. numLinesEst++;
  22234. if (cur.indexOf('\n') >= 0) numLinesEst++;
  22235. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  22236. }, 0);
  22237. if (length > 60) {
  22238. return braces[0] +
  22239. (base === '' ? '' : base + '\n ') +
  22240. ' ' +
  22241. output.join(',\n ') +
  22242. ' ' +
  22243. braces[1];
  22244. }
  22245. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  22246. }
  22247. // NOTE: These type checking functions intentionally don't use `instanceof`
  22248. // because it is fragile and can be easily faked with `Object.create()`.
  22249. function isArray(ar) {
  22250. return Array.isArray(ar);
  22251. }
  22252. exports.isArray = isArray;
  22253. function isBoolean(arg) {
  22254. return typeof arg === 'boolean';
  22255. }
  22256. exports.isBoolean = isBoolean;
  22257. function isNull(arg) {
  22258. return arg === null;
  22259. }
  22260. exports.isNull = isNull;
  22261. function isNullOrUndefined(arg) {
  22262. return arg == null;
  22263. }
  22264. exports.isNullOrUndefined = isNullOrUndefined;
  22265. function isNumber(arg) {
  22266. return typeof arg === 'number';
  22267. }
  22268. exports.isNumber = isNumber;
  22269. function isString(arg) {
  22270. return typeof arg === 'string';
  22271. }
  22272. exports.isString = isString;
  22273. function isSymbol(arg) {
  22274. return typeof arg === 'symbol';
  22275. }
  22276. exports.isSymbol = isSymbol;
  22277. function isUndefined(arg) {
  22278. return arg === void 0;
  22279. }
  22280. exports.isUndefined = isUndefined;
  22281. function isRegExp(re) {
  22282. return isObject(re) && objectToString(re) === '[object RegExp]';
  22283. }
  22284. exports.isRegExp = isRegExp;
  22285. function isObject(arg) {
  22286. return typeof arg === 'object' && arg !== null;
  22287. }
  22288. exports.isObject = isObject;
  22289. function isDate(d) {
  22290. return isObject(d) && objectToString(d) === '[object Date]';
  22291. }
  22292. exports.isDate = isDate;
  22293. function isError(e) {
  22294. return isObject(e) &&
  22295. (objectToString(e) === '[object Error]' || e instanceof Error);
  22296. }
  22297. exports.isError = isError;
  22298. function isFunction(arg) {
  22299. return typeof arg === 'function';
  22300. }
  22301. exports.isFunction = isFunction;
  22302. function isPrimitive(arg) {
  22303. return arg === null ||
  22304. typeof arg === 'boolean' ||
  22305. typeof arg === 'number' ||
  22306. typeof arg === 'string' ||
  22307. typeof arg === 'symbol' || // ES6 symbol
  22308. typeof arg === 'undefined';
  22309. }
  22310. exports.isPrimitive = isPrimitive;
  22311. exports.isBuffer = require('./support/isBuffer');
  22312. function objectToString(o) {
  22313. return Object.prototype.toString.call(o);
  22314. }
  22315. function pad(n) {
  22316. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  22317. }
  22318. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  22319. 'Oct', 'Nov', 'Dec'];
  22320. // 26 Feb 16:19:34
  22321. function timestamp() {
  22322. var d = new Date();
  22323. var time = [pad(d.getHours()),
  22324. pad(d.getMinutes()),
  22325. pad(d.getSeconds())].join(':');
  22326. return [d.getDate(), months[d.getMonth()], time].join(' ');
  22327. }
  22328. // log is just a thin wrapper to console.log that prepends a timestamp
  22329. exports.log = function() {
  22330. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  22331. };
  22332. /**
  22333. * Inherit the prototype methods from one constructor into another.
  22334. *
  22335. * The Function.prototype.inherits from lang.js rewritten as a standalone
  22336. * function (not on Function.prototype). NOTE: If this file is to be loaded
  22337. * during bootstrapping this function needs to be rewritten using some native
  22338. * functions as prototype setup using normal JavaScript does not work as
  22339. * expected during bootstrapping (see mirror.js in r114903).
  22340. *
  22341. * @param {function} ctor Constructor function which needs to inherit the
  22342. * prototype.
  22343. * @param {function} superCtor Constructor function to inherit prototype from.
  22344. */
  22345. exports.inherits = require('inherits');
  22346. exports._extend = function(origin, add) {
  22347. // Don't do anything if add isn't an object
  22348. if (!add || !isObject(add)) return origin;
  22349. var keys = Object.keys(add);
  22350. var i = keys.length;
  22351. while (i--) {
  22352. origin[keys[i]] = add[keys[i]];
  22353. }
  22354. return origin;
  22355. };
  22356. function hasOwnProperty(obj, prop) {
  22357. return Object.prototype.hasOwnProperty.call(obj, prop);
  22358. }
  22359. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22360. },{"./support/isBuffer":107,"_process":525,"inherits":106}],109:[function(require,module,exports){
  22361. (function (process,setImmediate){(function (){
  22362. (function (global, factory) {
  22363. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  22364. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  22365. (factory((global.async = {})));
  22366. }(this, (function (exports) { 'use strict';
  22367. /**
  22368. * Creates a continuation function with some arguments already applied.
  22369. *
  22370. * Useful as a shorthand when combined with other control flow functions. Any
  22371. * arguments passed to the returned function are added to the arguments
  22372. * originally passed to apply.
  22373. *
  22374. * @name apply
  22375. * @static
  22376. * @memberOf module:Utils
  22377. * @method
  22378. * @category Util
  22379. * @param {Function} fn - The function you want to eventually apply all
  22380. * arguments to. Invokes with (arguments...).
  22381. * @param {...*} arguments... - Any number of arguments to automatically apply
  22382. * when the continuation is called.
  22383. * @returns {Function} the partially-applied function
  22384. * @example
  22385. *
  22386. * // using apply
  22387. * async.parallel([
  22388. * async.apply(fs.writeFile, 'testfile1', 'test1'),
  22389. * async.apply(fs.writeFile, 'testfile2', 'test2')
  22390. * ]);
  22391. *
  22392. *
  22393. * // the same process without using apply
  22394. * async.parallel([
  22395. * function(callback) {
  22396. * fs.writeFile('testfile1', 'test1', callback);
  22397. * },
  22398. * function(callback) {
  22399. * fs.writeFile('testfile2', 'test2', callback);
  22400. * }
  22401. * ]);
  22402. *
  22403. * // It's possible to pass any number of additional arguments when calling the
  22404. * // continuation:
  22405. *
  22406. * node> var fn = async.apply(sys.puts, 'one');
  22407. * node> fn('two', 'three');
  22408. * one
  22409. * two
  22410. * three
  22411. */
  22412. function apply(fn, ...args) {
  22413. return (...callArgs) => fn(...args,...callArgs);
  22414. }
  22415. function initialParams (fn) {
  22416. return function (...args/*, callback*/) {
  22417. var callback = args.pop();
  22418. return fn.call(this, args, callback);
  22419. };
  22420. }
  22421. /* istanbul ignore file */
  22422. var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
  22423. var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
  22424. function fallback(fn) {
  22425. setTimeout(fn, 0);
  22426. }
  22427. function wrap(defer) {
  22428. return (fn, ...args) => defer(() => fn(...args));
  22429. }
  22430. var _defer;
  22431. if (hasSetImmediate) {
  22432. _defer = setImmediate;
  22433. } else if (hasNextTick) {
  22434. _defer = process.nextTick;
  22435. } else {
  22436. _defer = fallback;
  22437. }
  22438. var setImmediate$1 = wrap(_defer);
  22439. /**
  22440. * Take a sync function and make it async, passing its return value to a
  22441. * callback. This is useful for plugging sync functions into a waterfall,
  22442. * series, or other async functions. Any arguments passed to the generated
  22443. * function will be passed to the wrapped function (except for the final
  22444. * callback argument). Errors thrown will be passed to the callback.
  22445. *
  22446. * If the function passed to `asyncify` returns a Promise, that promises's
  22447. * resolved/rejected state will be used to call the callback, rather than simply
  22448. * the synchronous return value.
  22449. *
  22450. * This also means you can asyncify ES2017 `async` functions.
  22451. *
  22452. * @name asyncify
  22453. * @static
  22454. * @memberOf module:Utils
  22455. * @method
  22456. * @alias wrapSync
  22457. * @category Util
  22458. * @param {Function} func - The synchronous function, or Promise-returning
  22459. * function to convert to an {@link AsyncFunction}.
  22460. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
  22461. * invoked with `(args..., callback)`.
  22462. * @example
  22463. *
  22464. * // passing a regular synchronous function
  22465. * async.waterfall([
  22466. * async.apply(fs.readFile, filename, "utf8"),
  22467. * async.asyncify(JSON.parse),
  22468. * function (data, next) {
  22469. * // data is the result of parsing the text.
  22470. * // If there was a parsing error, it would have been caught.
  22471. * }
  22472. * ], callback);
  22473. *
  22474. * // passing a function returning a promise
  22475. * async.waterfall([
  22476. * async.apply(fs.readFile, filename, "utf8"),
  22477. * async.asyncify(function (contents) {
  22478. * return db.model.create(contents);
  22479. * }),
  22480. * function (model, next) {
  22481. * // `model` is the instantiated model object.
  22482. * // If there was an error, this function would be skipped.
  22483. * }
  22484. * ], callback);
  22485. *
  22486. * // es2017 example, though `asyncify` is not needed if your JS environment
  22487. * // supports async functions out of the box
  22488. * var q = async.queue(async.asyncify(async function(file) {
  22489. * var intermediateStep = await processFile(file);
  22490. * return await somePromise(intermediateStep)
  22491. * }));
  22492. *
  22493. * q.push(files);
  22494. */
  22495. function asyncify(func) {
  22496. if (isAsync(func)) {
  22497. return function (...args/*, callback*/) {
  22498. const callback = args.pop();
  22499. const promise = func.apply(this, args);
  22500. return handlePromise(promise, callback)
  22501. }
  22502. }
  22503. return initialParams(function (args, callback) {
  22504. var result;
  22505. try {
  22506. result = func.apply(this, args);
  22507. } catch (e) {
  22508. return callback(e);
  22509. }
  22510. // if result is Promise object
  22511. if (result && typeof result.then === 'function') {
  22512. return handlePromise(result, callback)
  22513. } else {
  22514. callback(null, result);
  22515. }
  22516. });
  22517. }
  22518. function handlePromise(promise, callback) {
  22519. return promise.then(value => {
  22520. invokeCallback(callback, null, value);
  22521. }, err => {
  22522. invokeCallback(callback, err && err.message ? err : new Error(err));
  22523. });
  22524. }
  22525. function invokeCallback(callback, error, value) {
  22526. try {
  22527. callback(error, value);
  22528. } catch (err) {
  22529. setImmediate$1(e => { throw e }, err);
  22530. }
  22531. }
  22532. function isAsync(fn) {
  22533. return fn[Symbol.toStringTag] === 'AsyncFunction';
  22534. }
  22535. function isAsyncGenerator(fn) {
  22536. return fn[Symbol.toStringTag] === 'AsyncGenerator';
  22537. }
  22538. function isAsyncIterable(obj) {
  22539. return typeof obj[Symbol.asyncIterator] === 'function';
  22540. }
  22541. function wrapAsync(asyncFn) {
  22542. if (typeof asyncFn !== 'function') throw new Error('expected a function')
  22543. return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
  22544. }
  22545. // conditionally promisify a function.
  22546. // only return a promise if a callback is omitted
  22547. function awaitify (asyncFn, arity = asyncFn.length) {
  22548. if (!arity) throw new Error('arity is undefined')
  22549. function awaitable (...args) {
  22550. if (typeof args[arity - 1] === 'function') {
  22551. return asyncFn.apply(this, args)
  22552. }
  22553. return new Promise((resolve, reject) => {
  22554. args[arity - 1] = (err, ...cbArgs) => {
  22555. if (err) return reject(err)
  22556. resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
  22557. };
  22558. asyncFn.apply(this, args);
  22559. })
  22560. }
  22561. return awaitable
  22562. }
  22563. function applyEach (eachfn) {
  22564. return function applyEach(fns, ...callArgs) {
  22565. const go = awaitify(function (callback) {
  22566. var that = this;
  22567. return eachfn(fns, (fn, cb) => {
  22568. wrapAsync(fn).apply(that, callArgs.concat(cb));
  22569. }, callback);
  22570. });
  22571. return go;
  22572. };
  22573. }
  22574. function _asyncMap(eachfn, arr, iteratee, callback) {
  22575. arr = arr || [];
  22576. var results = [];
  22577. var counter = 0;
  22578. var _iteratee = wrapAsync(iteratee);
  22579. return eachfn(arr, (value, _, iterCb) => {
  22580. var index = counter++;
  22581. _iteratee(value, (err, v) => {
  22582. results[index] = v;
  22583. iterCb(err);
  22584. });
  22585. }, err => {
  22586. callback(err, results);
  22587. });
  22588. }
  22589. function isArrayLike(value) {
  22590. return value &&
  22591. typeof value.length === 'number' &&
  22592. value.length >= 0 &&
  22593. value.length % 1 === 0;
  22594. }
  22595. // A temporary value used to identify if the loop should be broken.
  22596. // See #1064, #1293
  22597. const breakLoop = {};
  22598. function once(fn) {
  22599. function wrapper (...args) {
  22600. if (fn === null) return;
  22601. var callFn = fn;
  22602. fn = null;
  22603. callFn.apply(this, args);
  22604. }
  22605. Object.assign(wrapper, fn);
  22606. return wrapper
  22607. }
  22608. function getIterator (coll) {
  22609. return coll[Symbol.iterator] && coll[Symbol.iterator]();
  22610. }
  22611. function createArrayIterator(coll) {
  22612. var i = -1;
  22613. var len = coll.length;
  22614. return function next() {
  22615. return ++i < len ? {value: coll[i], key: i} : null;
  22616. }
  22617. }
  22618. function createES2015Iterator(iterator) {
  22619. var i = -1;
  22620. return function next() {
  22621. var item = iterator.next();
  22622. if (item.done)
  22623. return null;
  22624. i++;
  22625. return {value: item.value, key: i};
  22626. }
  22627. }
  22628. function createObjectIterator(obj) {
  22629. var okeys = obj ? Object.keys(obj) : [];
  22630. var i = -1;
  22631. var len = okeys.length;
  22632. return function next() {
  22633. var key = okeys[++i];
  22634. return i < len ? {value: obj[key], key} : null;
  22635. };
  22636. }
  22637. function createIterator(coll) {
  22638. if (isArrayLike(coll)) {
  22639. return createArrayIterator(coll);
  22640. }
  22641. var iterator = getIterator(coll);
  22642. return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
  22643. }
  22644. function onlyOnce(fn) {
  22645. return function (...args) {
  22646. if (fn === null) throw new Error("Callback was already called.");
  22647. var callFn = fn;
  22648. fn = null;
  22649. callFn.apply(this, args);
  22650. };
  22651. }
  22652. // for async generators
  22653. function asyncEachOfLimit(generator, limit, iteratee, callback) {
  22654. let done = false;
  22655. let canceled = false;
  22656. let awaiting = false;
  22657. let running = 0;
  22658. let idx = 0;
  22659. function replenish() {
  22660. //console.log('replenish')
  22661. if (running >= limit || awaiting || done) return
  22662. //console.log('replenish awaiting')
  22663. awaiting = true;
  22664. generator.next().then(({value, done: iterDone}) => {
  22665. //console.log('got value', value)
  22666. if (canceled || done) return
  22667. awaiting = false;
  22668. if (iterDone) {
  22669. done = true;
  22670. if (running <= 0) {
  22671. //console.log('done nextCb')
  22672. callback(null);
  22673. }
  22674. return;
  22675. }
  22676. running++;
  22677. iteratee(value, idx, iterateeCallback);
  22678. idx++;
  22679. replenish();
  22680. }).catch(handleError);
  22681. }
  22682. function iterateeCallback(err, result) {
  22683. //console.log('iterateeCallback')
  22684. running -= 1;
  22685. if (canceled) return
  22686. if (err) return handleError(err)
  22687. if (err === false) {
  22688. done = true;
  22689. canceled = true;
  22690. return
  22691. }
  22692. if (result === breakLoop || (done && running <= 0)) {
  22693. done = true;
  22694. //console.log('done iterCb')
  22695. return callback(null);
  22696. }
  22697. replenish();
  22698. }
  22699. function handleError(err) {
  22700. if (canceled) return
  22701. awaiting = false;
  22702. done = true;
  22703. callback(err);
  22704. }
  22705. replenish();
  22706. }
  22707. var eachOfLimit = (limit) => {
  22708. return (obj, iteratee, callback) => {
  22709. callback = once(callback);
  22710. if (limit <= 0) {
  22711. throw new RangeError('concurrency limit cannot be less than 1')
  22712. }
  22713. if (!obj) {
  22714. return callback(null);
  22715. }
  22716. if (isAsyncGenerator(obj)) {
  22717. return asyncEachOfLimit(obj, limit, iteratee, callback)
  22718. }
  22719. if (isAsyncIterable(obj)) {
  22720. return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)
  22721. }
  22722. var nextElem = createIterator(obj);
  22723. var done = false;
  22724. var canceled = false;
  22725. var running = 0;
  22726. var looping = false;
  22727. function iterateeCallback(err, value) {
  22728. if (canceled) return
  22729. running -= 1;
  22730. if (err) {
  22731. done = true;
  22732. callback(err);
  22733. }
  22734. else if (err === false) {
  22735. done = true;
  22736. canceled = true;
  22737. }
  22738. else if (value === breakLoop || (done && running <= 0)) {
  22739. done = true;
  22740. return callback(null);
  22741. }
  22742. else if (!looping) {
  22743. replenish();
  22744. }
  22745. }
  22746. function replenish () {
  22747. looping = true;
  22748. while (running < limit && !done) {
  22749. var elem = nextElem();
  22750. if (elem === null) {
  22751. done = true;
  22752. if (running <= 0) {
  22753. callback(null);
  22754. }
  22755. return;
  22756. }
  22757. running += 1;
  22758. iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
  22759. }
  22760. looping = false;
  22761. }
  22762. replenish();
  22763. };
  22764. };
  22765. /**
  22766. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
  22767. * time.
  22768. *
  22769. * @name eachOfLimit
  22770. * @static
  22771. * @memberOf module:Collections
  22772. * @method
  22773. * @see [async.eachOf]{@link module:Collections.eachOf}
  22774. * @alias forEachOfLimit
  22775. * @category Collection
  22776. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  22777. * @param {number} limit - The maximum number of async operations at a time.
  22778. * @param {AsyncFunction} iteratee - An async function to apply to each
  22779. * item in `coll`. The `key` is the item's key, or index in the case of an
  22780. * array.
  22781. * Invoked with (item, key, callback).
  22782. * @param {Function} [callback] - A callback which is called when all
  22783. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  22784. * @returns {Promise} a promise, if a callback is omitted
  22785. */
  22786. function eachOfLimit$1(coll, limit, iteratee, callback) {
  22787. return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
  22788. }
  22789. var eachOfLimit$2 = awaitify(eachOfLimit$1, 4);
  22790. // eachOf implementation optimized for array-likes
  22791. function eachOfArrayLike(coll, iteratee, callback) {
  22792. callback = once(callback);
  22793. var index = 0,
  22794. completed = 0,
  22795. {length} = coll,
  22796. canceled = false;
  22797. if (length === 0) {
  22798. callback(null);
  22799. }
  22800. function iteratorCallback(err, value) {
  22801. if (err === false) {
  22802. canceled = true;
  22803. }
  22804. if (canceled === true) return
  22805. if (err) {
  22806. callback(err);
  22807. } else if ((++completed === length) || value === breakLoop) {
  22808. callback(null);
  22809. }
  22810. }
  22811. for (; index < length; index++) {
  22812. iteratee(coll[index], index, onlyOnce(iteratorCallback));
  22813. }
  22814. }
  22815. // a generic version of eachOf which can handle array, object, and iterator cases.
  22816. function eachOfGeneric (coll, iteratee, callback) {
  22817. return eachOfLimit$2(coll, Infinity, iteratee, callback);
  22818. }
  22819. /**
  22820. * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
  22821. * to the iteratee.
  22822. *
  22823. * @name eachOf
  22824. * @static
  22825. * @memberOf module:Collections
  22826. * @method
  22827. * @alias forEachOf
  22828. * @category Collection
  22829. * @see [async.each]{@link module:Collections.each}
  22830. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  22831. * @param {AsyncFunction} iteratee - A function to apply to each
  22832. * item in `coll`.
  22833. * The `key` is the item's key, or index in the case of an array.
  22834. * Invoked with (item, key, callback).
  22835. * @param {Function} [callback] - A callback which is called when all
  22836. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  22837. * @returns {Promise} a promise, if a callback is omitted
  22838. * @example
  22839. *
  22840. * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
  22841. * var configs = {};
  22842. *
  22843. * async.forEachOf(obj, function (value, key, callback) {
  22844. * fs.readFile(__dirname + value, "utf8", function (err, data) {
  22845. * if (err) return callback(err);
  22846. * try {
  22847. * configs[key] = JSON.parse(data);
  22848. * } catch (e) {
  22849. * return callback(e);
  22850. * }
  22851. * callback();
  22852. * });
  22853. * }, function (err) {
  22854. * if (err) console.error(err.message);
  22855. * // configs is now a map of JSON data
  22856. * doSomethingWith(configs);
  22857. * });
  22858. */
  22859. function eachOf(coll, iteratee, callback) {
  22860. var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
  22861. return eachOfImplementation(coll, wrapAsync(iteratee), callback);
  22862. }
  22863. var eachOf$1 = awaitify(eachOf, 3);
  22864. /**
  22865. * Produces a new collection of values by mapping each value in `coll` through
  22866. * the `iteratee` function. The `iteratee` is called with an item from `coll`
  22867. * and a callback for when it has finished processing. Each of these callback
  22868. * takes 2 arguments: an `error`, and the transformed item from `coll`. If
  22869. * `iteratee` passes an error to its callback, the main `callback` (for the
  22870. * `map` function) is immediately called with the error.
  22871. *
  22872. * Note, that since this function applies the `iteratee` to each item in
  22873. * parallel, there is no guarantee that the `iteratee` functions will complete
  22874. * in order. However, the results array will be in the same order as the
  22875. * original `coll`.
  22876. *
  22877. * If `map` is passed an Object, the results will be an Array. The results
  22878. * will roughly be in the order of the original Objects' keys (but this can
  22879. * vary across JavaScript engines).
  22880. *
  22881. * @name map
  22882. * @static
  22883. * @memberOf module:Collections
  22884. * @method
  22885. * @category Collection
  22886. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  22887. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  22888. * `coll`.
  22889. * The iteratee should complete with the transformed item.
  22890. * Invoked with (item, callback).
  22891. * @param {Function} [callback] - A callback which is called when all `iteratee`
  22892. * functions have finished, or an error occurs. Results is an Array of the
  22893. * transformed items from the `coll`. Invoked with (err, results).
  22894. * @returns {Promise} a promise, if no callback is passed
  22895. * @example
  22896. *
  22897. * async.map(['file1','file2','file3'], fs.stat, function(err, results) {
  22898. * // results is now an array of stats for each file
  22899. * });
  22900. */
  22901. function map (coll, iteratee, callback) {
  22902. return _asyncMap(eachOf$1, coll, iteratee, callback)
  22903. }
  22904. var map$1 = awaitify(map, 3);
  22905. /**
  22906. * Applies the provided arguments to each function in the array, calling
  22907. * `callback` after all functions have completed. If you only provide the first
  22908. * argument, `fns`, then it will return a function which lets you pass in the
  22909. * arguments as if it were a single function call. If more arguments are
  22910. * provided, `callback` is required while `args` is still optional. The results
  22911. * for each of the applied async functions are passed to the final callback
  22912. * as an array.
  22913. *
  22914. * @name applyEach
  22915. * @static
  22916. * @memberOf module:ControlFlow
  22917. * @method
  22918. * @category Control Flow
  22919. * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s
  22920. * to all call with the same arguments
  22921. * @param {...*} [args] - any number of separate arguments to pass to the
  22922. * function.
  22923. * @param {Function} [callback] - the final argument should be the callback,
  22924. * called when all functions have completed processing.
  22925. * @returns {AsyncFunction} - Returns a function that takes no args other than
  22926. * an optional callback, that is the result of applying the `args` to each
  22927. * of the functions.
  22928. * @example
  22929. *
  22930. * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')
  22931. *
  22932. * appliedFn((err, results) => {
  22933. * // results[0] is the results for `enableSearch`
  22934. * // results[1] is the results for `updateSchema`
  22935. * });
  22936. *
  22937. * // partial application example:
  22938. * async.each(
  22939. * buckets,
  22940. * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),
  22941. * callback
  22942. * );
  22943. */
  22944. var applyEach$1 = applyEach(map$1);
  22945. /**
  22946. * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
  22947. *
  22948. * @name eachOfSeries
  22949. * @static
  22950. * @memberOf module:Collections
  22951. * @method
  22952. * @see [async.eachOf]{@link module:Collections.eachOf}
  22953. * @alias forEachOfSeries
  22954. * @category Collection
  22955. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  22956. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  22957. * `coll`.
  22958. * Invoked with (item, key, callback).
  22959. * @param {Function} [callback] - A callback which is called when all `iteratee`
  22960. * functions have finished, or an error occurs. Invoked with (err).
  22961. * @returns {Promise} a promise, if a callback is omitted
  22962. */
  22963. function eachOfSeries(coll, iteratee, callback) {
  22964. return eachOfLimit$2(coll, 1, iteratee, callback)
  22965. }
  22966. var eachOfSeries$1 = awaitify(eachOfSeries, 3);
  22967. /**
  22968. * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
  22969. *
  22970. * @name mapSeries
  22971. * @static
  22972. * @memberOf module:Collections
  22973. * @method
  22974. * @see [async.map]{@link module:Collections.map}
  22975. * @category Collection
  22976. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  22977. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  22978. * `coll`.
  22979. * The iteratee should complete with the transformed item.
  22980. * Invoked with (item, callback).
  22981. * @param {Function} [callback] - A callback which is called when all `iteratee`
  22982. * functions have finished, or an error occurs. Results is an array of the
  22983. * transformed items from the `coll`. Invoked with (err, results).
  22984. * @returns {Promise} a promise, if no callback is passed
  22985. */
  22986. function mapSeries (coll, iteratee, callback) {
  22987. return _asyncMap(eachOfSeries$1, coll, iteratee, callback)
  22988. }
  22989. var mapSeries$1 = awaitify(mapSeries, 3);
  22990. /**
  22991. * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
  22992. *
  22993. * @name applyEachSeries
  22994. * @static
  22995. * @memberOf module:ControlFlow
  22996. * @method
  22997. * @see [async.applyEach]{@link module:ControlFlow.applyEach}
  22998. * @category Control Flow
  22999. * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all
  23000. * call with the same arguments
  23001. * @param {...*} [args] - any number of separate arguments to pass to the
  23002. * function.
  23003. * @param {Function} [callback] - the final argument should be the callback,
  23004. * called when all functions have completed processing.
  23005. * @returns {AsyncFunction} - A function, that when called, is the result of
  23006. * appling the `args` to the list of functions. It takes no args, other than
  23007. * a callback.
  23008. */
  23009. var applyEachSeries = applyEach(mapSeries$1);
  23010. const PROMISE_SYMBOL = Symbol('promiseCallback');
  23011. function promiseCallback () {
  23012. let resolve, reject;
  23013. function callback (err, ...args) {
  23014. if (err) return reject(err)
  23015. resolve(args.length > 1 ? args : args[0]);
  23016. }
  23017. callback[PROMISE_SYMBOL] = new Promise((res, rej) => {
  23018. resolve = res,
  23019. reject = rej;
  23020. });
  23021. return callback
  23022. }
  23023. /**
  23024. * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
  23025. * their requirements. Each function can optionally depend on other functions
  23026. * being completed first, and each function is run as soon as its requirements
  23027. * are satisfied.
  23028. *
  23029. * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
  23030. * will stop. Further tasks will not execute (so any other functions depending
  23031. * on it will not run), and the main `callback` is immediately called with the
  23032. * error.
  23033. *
  23034. * {@link AsyncFunction}s also receive an object containing the results of functions which
  23035. * have completed so far as the first argument, if they have dependencies. If a
  23036. * task function has no dependencies, it will only be passed a callback.
  23037. *
  23038. * @name auto
  23039. * @static
  23040. * @memberOf module:ControlFlow
  23041. * @method
  23042. * @category Control Flow
  23043. * @param {Object} tasks - An object. Each of its properties is either a
  23044. * function or an array of requirements, with the {@link AsyncFunction} itself the last item
  23045. * in the array. The object's key of a property serves as the name of the task
  23046. * defined by that property, i.e. can be used when specifying requirements for
  23047. * other tasks. The function receives one or two arguments:
  23048. * * a `results` object, containing the results of the previously executed
  23049. * functions, only passed if the task has any dependencies,
  23050. * * a `callback(err, result)` function, which must be called when finished,
  23051. * passing an `error` (which can be `null`) and the result of the function's
  23052. * execution.
  23053. * @param {number} [concurrency=Infinity] - An optional `integer` for
  23054. * determining the maximum number of tasks that can be run in parallel. By
  23055. * default, as many as possible.
  23056. * @param {Function} [callback] - An optional callback which is called when all
  23057. * the tasks have been completed. It receives the `err` argument if any `tasks`
  23058. * pass an error to their callback. Results are always returned; however, if an
  23059. * error occurs, no further `tasks` will be performed, and the results object
  23060. * will only contain partial results. Invoked with (err, results).
  23061. * @returns {Promise} a promise, if a callback is not passed
  23062. * @example
  23063. *
  23064. * async.auto({
  23065. * // this function will just be passed a callback
  23066. * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
  23067. * showData: ['readData', function(results, cb) {
  23068. * // results.readData is the file's contents
  23069. * // ...
  23070. * }]
  23071. * }, callback);
  23072. *
  23073. * async.auto({
  23074. * get_data: function(callback) {
  23075. * console.log('in get_data');
  23076. * // async code to get some data
  23077. * callback(null, 'data', 'converted to array');
  23078. * },
  23079. * make_folder: function(callback) {
  23080. * console.log('in make_folder');
  23081. * // async code to create a directory to store a file in
  23082. * // this is run at the same time as getting the data
  23083. * callback(null, 'folder');
  23084. * },
  23085. * write_file: ['get_data', 'make_folder', function(results, callback) {
  23086. * console.log('in write_file', JSON.stringify(results));
  23087. * // once there is some data and the directory exists,
  23088. * // write the data to a file in the directory
  23089. * callback(null, 'filename');
  23090. * }],
  23091. * email_link: ['write_file', function(results, callback) {
  23092. * console.log('in email_link', JSON.stringify(results));
  23093. * // once the file is written let's email a link to it...
  23094. * // results.write_file contains the filename returned by write_file.
  23095. * callback(null, {'file':results.write_file, 'email':'user@example.com'});
  23096. * }]
  23097. * }, function(err, results) {
  23098. * console.log('err = ', err);
  23099. * console.log('results = ', results);
  23100. * });
  23101. */
  23102. function auto(tasks, concurrency, callback) {
  23103. if (typeof concurrency !== 'number') {
  23104. // concurrency is optional, shift the args.
  23105. callback = concurrency;
  23106. concurrency = null;
  23107. }
  23108. callback = once(callback || promiseCallback());
  23109. var numTasks = Object.keys(tasks).length;
  23110. if (!numTasks) {
  23111. return callback(null);
  23112. }
  23113. if (!concurrency) {
  23114. concurrency = numTasks;
  23115. }
  23116. var results = {};
  23117. var runningTasks = 0;
  23118. var canceled = false;
  23119. var hasError = false;
  23120. var listeners = Object.create(null);
  23121. var readyTasks = [];
  23122. // for cycle detection:
  23123. var readyToCheck = []; // tasks that have been identified as reachable
  23124. // without the possibility of returning to an ancestor task
  23125. var uncheckedDependencies = {};
  23126. Object.keys(tasks).forEach(key => {
  23127. var task = tasks[key];
  23128. if (!Array.isArray(task)) {
  23129. // no dependencies
  23130. enqueueTask(key, [task]);
  23131. readyToCheck.push(key);
  23132. return;
  23133. }
  23134. var dependencies = task.slice(0, task.length - 1);
  23135. var remainingDependencies = dependencies.length;
  23136. if (remainingDependencies === 0) {
  23137. enqueueTask(key, task);
  23138. readyToCheck.push(key);
  23139. return;
  23140. }
  23141. uncheckedDependencies[key] = remainingDependencies;
  23142. dependencies.forEach(dependencyName => {
  23143. if (!tasks[dependencyName]) {
  23144. throw new Error('async.auto task `' + key +
  23145. '` has a non-existent dependency `' +
  23146. dependencyName + '` in ' +
  23147. dependencies.join(', '));
  23148. }
  23149. addListener(dependencyName, () => {
  23150. remainingDependencies--;
  23151. if (remainingDependencies === 0) {
  23152. enqueueTask(key, task);
  23153. }
  23154. });
  23155. });
  23156. });
  23157. checkForDeadlocks();
  23158. processQueue();
  23159. function enqueueTask(key, task) {
  23160. readyTasks.push(() => runTask(key, task));
  23161. }
  23162. function processQueue() {
  23163. if (canceled) return
  23164. if (readyTasks.length === 0 && runningTasks === 0) {
  23165. return callback(null, results);
  23166. }
  23167. while(readyTasks.length && runningTasks < concurrency) {
  23168. var run = readyTasks.shift();
  23169. run();
  23170. }
  23171. }
  23172. function addListener(taskName, fn) {
  23173. var taskListeners = listeners[taskName];
  23174. if (!taskListeners) {
  23175. taskListeners = listeners[taskName] = [];
  23176. }
  23177. taskListeners.push(fn);
  23178. }
  23179. function taskComplete(taskName) {
  23180. var taskListeners = listeners[taskName] || [];
  23181. taskListeners.forEach(fn => fn());
  23182. processQueue();
  23183. }
  23184. function runTask(key, task) {
  23185. if (hasError) return;
  23186. var taskCallback = onlyOnce((err, ...result) => {
  23187. runningTasks--;
  23188. if (err === false) {
  23189. canceled = true;
  23190. return
  23191. }
  23192. if (result.length < 2) {
  23193. [result] = result;
  23194. }
  23195. if (err) {
  23196. var safeResults = {};
  23197. Object.keys(results).forEach(rkey => {
  23198. safeResults[rkey] = results[rkey];
  23199. });
  23200. safeResults[key] = result;
  23201. hasError = true;
  23202. listeners = Object.create(null);
  23203. if (canceled) return
  23204. callback(err, safeResults);
  23205. } else {
  23206. results[key] = result;
  23207. taskComplete(key);
  23208. }
  23209. });
  23210. runningTasks++;
  23211. var taskFn = wrapAsync(task[task.length - 1]);
  23212. if (task.length > 1) {
  23213. taskFn(results, taskCallback);
  23214. } else {
  23215. taskFn(taskCallback);
  23216. }
  23217. }
  23218. function checkForDeadlocks() {
  23219. // Kahn's algorithm
  23220. // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
  23221. // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
  23222. var currentTask;
  23223. var counter = 0;
  23224. while (readyToCheck.length) {
  23225. currentTask = readyToCheck.pop();
  23226. counter++;
  23227. getDependents(currentTask).forEach(dependent => {
  23228. if (--uncheckedDependencies[dependent] === 0) {
  23229. readyToCheck.push(dependent);
  23230. }
  23231. });
  23232. }
  23233. if (counter !== numTasks) {
  23234. throw new Error(
  23235. 'async.auto cannot execute tasks due to a recursive dependency'
  23236. );
  23237. }
  23238. }
  23239. function getDependents(taskName) {
  23240. var result = [];
  23241. Object.keys(tasks).forEach(key => {
  23242. const task = tasks[key];
  23243. if (Array.isArray(task) && task.indexOf(taskName) >= 0) {
  23244. result.push(key);
  23245. }
  23246. });
  23247. return result;
  23248. }
  23249. return callback[PROMISE_SYMBOL]
  23250. }
  23251. var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/;
  23252. var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/;
  23253. var FN_ARG_SPLIT = /,/;
  23254. var FN_ARG = /(=.+)?(\s*)$/;
  23255. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  23256. function parseParams(func) {
  23257. const src = func.toString().replace(STRIP_COMMENTS, '');
  23258. let match = src.match(FN_ARGS);
  23259. if (!match) {
  23260. match = src.match(ARROW_FN_ARGS);
  23261. }
  23262. if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src)
  23263. let [, args] = match;
  23264. return args
  23265. .replace(/\s/g, '')
  23266. .split(FN_ARG_SPLIT)
  23267. .map((arg) => arg.replace(FN_ARG, '').trim());
  23268. }
  23269. /**
  23270. * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
  23271. * tasks are specified as parameters to the function, after the usual callback
  23272. * parameter, with the parameter names matching the names of the tasks it
  23273. * depends on. This can provide even more readable task graphs which can be
  23274. * easier to maintain.
  23275. *
  23276. * If a final callback is specified, the task results are similarly injected,
  23277. * specified as named parameters after the initial error parameter.
  23278. *
  23279. * The autoInject function is purely syntactic sugar and its semantics are
  23280. * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
  23281. *
  23282. * @name autoInject
  23283. * @static
  23284. * @memberOf module:ControlFlow
  23285. * @method
  23286. * @see [async.auto]{@link module:ControlFlow.auto}
  23287. * @category Control Flow
  23288. * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
  23289. * the form 'func([dependencies...], callback). The object's key of a property
  23290. * serves as the name of the task defined by that property, i.e. can be used
  23291. * when specifying requirements for other tasks.
  23292. * * The `callback` parameter is a `callback(err, result)` which must be called
  23293. * when finished, passing an `error` (which can be `null`) and the result of
  23294. * the function's execution. The remaining parameters name other tasks on
  23295. * which the task is dependent, and the results from those tasks are the
  23296. * arguments of those parameters.
  23297. * @param {Function} [callback] - An optional callback which is called when all
  23298. * the tasks have been completed. It receives the `err` argument if any `tasks`
  23299. * pass an error to their callback, and a `results` object with any completed
  23300. * task results, similar to `auto`.
  23301. * @returns {Promise} a promise, if no callback is passed
  23302. * @example
  23303. *
  23304. * // The example from `auto` can be rewritten as follows:
  23305. * async.autoInject({
  23306. * get_data: function(callback) {
  23307. * // async code to get some data
  23308. * callback(null, 'data', 'converted to array');
  23309. * },
  23310. * make_folder: function(callback) {
  23311. * // async code to create a directory to store a file in
  23312. * // this is run at the same time as getting the data
  23313. * callback(null, 'folder');
  23314. * },
  23315. * write_file: function(get_data, make_folder, callback) {
  23316. * // once there is some data and the directory exists,
  23317. * // write the data to a file in the directory
  23318. * callback(null, 'filename');
  23319. * },
  23320. * email_link: function(write_file, callback) {
  23321. * // once the file is written let's email a link to it...
  23322. * // write_file contains the filename returned by write_file.
  23323. * callback(null, {'file':write_file, 'email':'user@example.com'});
  23324. * }
  23325. * }, function(err, results) {
  23326. * console.log('err = ', err);
  23327. * console.log('email_link = ', results.email_link);
  23328. * });
  23329. *
  23330. * // If you are using a JS minifier that mangles parameter names, `autoInject`
  23331. * // will not work with plain functions, since the parameter names will be
  23332. * // collapsed to a single letter identifier. To work around this, you can
  23333. * // explicitly specify the names of the parameters your task function needs
  23334. * // in an array, similar to Angular.js dependency injection.
  23335. *
  23336. * // This still has an advantage over plain `auto`, since the results a task
  23337. * // depends on are still spread into arguments.
  23338. * async.autoInject({
  23339. * //...
  23340. * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
  23341. * callback(null, 'filename');
  23342. * }],
  23343. * email_link: ['write_file', function(write_file, callback) {
  23344. * callback(null, {'file':write_file, 'email':'user@example.com'});
  23345. * }]
  23346. * //...
  23347. * }, function(err, results) {
  23348. * console.log('err = ', err);
  23349. * console.log('email_link = ', results.email_link);
  23350. * });
  23351. */
  23352. function autoInject(tasks, callback) {
  23353. var newTasks = {};
  23354. Object.keys(tasks).forEach(key => {
  23355. var taskFn = tasks[key];
  23356. var params;
  23357. var fnIsAsync = isAsync(taskFn);
  23358. var hasNoDeps =
  23359. (!fnIsAsync && taskFn.length === 1) ||
  23360. (fnIsAsync && taskFn.length === 0);
  23361. if (Array.isArray(taskFn)) {
  23362. params = [...taskFn];
  23363. taskFn = params.pop();
  23364. newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
  23365. } else if (hasNoDeps) {
  23366. // no dependencies, use the function as-is
  23367. newTasks[key] = taskFn;
  23368. } else {
  23369. params = parseParams(taskFn);
  23370. if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) {
  23371. throw new Error("autoInject task functions require explicit parameters.");
  23372. }
  23373. // remove callback param
  23374. if (!fnIsAsync) params.pop();
  23375. newTasks[key] = params.concat(newTask);
  23376. }
  23377. function newTask(results, taskCb) {
  23378. var newArgs = params.map(name => results[name]);
  23379. newArgs.push(taskCb);
  23380. wrapAsync(taskFn)(...newArgs);
  23381. }
  23382. });
  23383. return auto(newTasks, callback);
  23384. }
  23385. // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
  23386. // used for queues. This implementation assumes that the node provided by the user can be modified
  23387. // to adjust the next and last properties. We implement only the minimal functionality
  23388. // for queue support.
  23389. class DLL {
  23390. constructor() {
  23391. this.head = this.tail = null;
  23392. this.length = 0;
  23393. }
  23394. removeLink(node) {
  23395. if (node.prev) node.prev.next = node.next;
  23396. else this.head = node.next;
  23397. if (node.next) node.next.prev = node.prev;
  23398. else this.tail = node.prev;
  23399. node.prev = node.next = null;
  23400. this.length -= 1;
  23401. return node;
  23402. }
  23403. empty () {
  23404. while(this.head) this.shift();
  23405. return this;
  23406. }
  23407. insertAfter(node, newNode) {
  23408. newNode.prev = node;
  23409. newNode.next = node.next;
  23410. if (node.next) node.next.prev = newNode;
  23411. else this.tail = newNode;
  23412. node.next = newNode;
  23413. this.length += 1;
  23414. }
  23415. insertBefore(node, newNode) {
  23416. newNode.prev = node.prev;
  23417. newNode.next = node;
  23418. if (node.prev) node.prev.next = newNode;
  23419. else this.head = newNode;
  23420. node.prev = newNode;
  23421. this.length += 1;
  23422. }
  23423. unshift(node) {
  23424. if (this.head) this.insertBefore(this.head, node);
  23425. else setInitial(this, node);
  23426. }
  23427. push(node) {
  23428. if (this.tail) this.insertAfter(this.tail, node);
  23429. else setInitial(this, node);
  23430. }
  23431. shift() {
  23432. return this.head && this.removeLink(this.head);
  23433. }
  23434. pop() {
  23435. return this.tail && this.removeLink(this.tail);
  23436. }
  23437. toArray() {
  23438. return [...this]
  23439. }
  23440. *[Symbol.iterator] () {
  23441. var cur = this.head;
  23442. while (cur) {
  23443. yield cur.data;
  23444. cur = cur.next;
  23445. }
  23446. }
  23447. remove (testFn) {
  23448. var curr = this.head;
  23449. while(curr) {
  23450. var {next} = curr;
  23451. if (testFn(curr)) {
  23452. this.removeLink(curr);
  23453. }
  23454. curr = next;
  23455. }
  23456. return this;
  23457. }
  23458. }
  23459. function setInitial(dll, node) {
  23460. dll.length = 1;
  23461. dll.head = dll.tail = node;
  23462. }
  23463. function queue(worker, concurrency, payload) {
  23464. if (concurrency == null) {
  23465. concurrency = 1;
  23466. }
  23467. else if(concurrency === 0) {
  23468. throw new RangeError('Concurrency must not be zero');
  23469. }
  23470. var _worker = wrapAsync(worker);
  23471. var numRunning = 0;
  23472. var workersList = [];
  23473. const events = {
  23474. error: [],
  23475. drain: [],
  23476. saturated: [],
  23477. unsaturated: [],
  23478. empty: []
  23479. };
  23480. function on (event, handler) {
  23481. events[event].push(handler);
  23482. }
  23483. function once (event, handler) {
  23484. const handleAndRemove = (...args) => {
  23485. off(event, handleAndRemove);
  23486. handler(...args);
  23487. };
  23488. events[event].push(handleAndRemove);
  23489. }
  23490. function off (event, handler) {
  23491. if (!event) return Object.keys(events).forEach(ev => events[ev] = [])
  23492. if (!handler) return events[event] = []
  23493. events[event] = events[event].filter(ev => ev !== handler);
  23494. }
  23495. function trigger (event, ...args) {
  23496. events[event].forEach(handler => handler(...args));
  23497. }
  23498. var processingScheduled = false;
  23499. function _insert(data, insertAtFront, rejectOnError, callback) {
  23500. if (callback != null && typeof callback !== 'function') {
  23501. throw new Error('task callback must be a function');
  23502. }
  23503. q.started = true;
  23504. var res, rej;
  23505. function promiseCallback (err, ...args) {
  23506. // we don't care about the error, let the global error handler
  23507. // deal with it
  23508. if (err) return rejectOnError ? rej(err) : res()
  23509. if (args.length <= 1) return res(args[0])
  23510. res(args);
  23511. }
  23512. var item = {
  23513. data,
  23514. callback: rejectOnError ?
  23515. promiseCallback :
  23516. (callback || promiseCallback)
  23517. };
  23518. if (insertAtFront) {
  23519. q._tasks.unshift(item);
  23520. } else {
  23521. q._tasks.push(item);
  23522. }
  23523. if (!processingScheduled) {
  23524. processingScheduled = true;
  23525. setImmediate$1(() => {
  23526. processingScheduled = false;
  23527. q.process();
  23528. });
  23529. }
  23530. if (rejectOnError || !callback) {
  23531. return new Promise((resolve, reject) => {
  23532. res = resolve;
  23533. rej = reject;
  23534. })
  23535. }
  23536. }
  23537. function _createCB(tasks) {
  23538. return function (err, ...args) {
  23539. numRunning -= 1;
  23540. for (var i = 0, l = tasks.length; i < l; i++) {
  23541. var task = tasks[i];
  23542. var index = workersList.indexOf(task);
  23543. if (index === 0) {
  23544. workersList.shift();
  23545. } else if (index > 0) {
  23546. workersList.splice(index, 1);
  23547. }
  23548. task.callback(err, ...args);
  23549. if (err != null) {
  23550. trigger('error', err, task.data);
  23551. }
  23552. }
  23553. if (numRunning <= (q.concurrency - q.buffer) ) {
  23554. trigger('unsaturated');
  23555. }
  23556. if (q.idle()) {
  23557. trigger('drain');
  23558. }
  23559. q.process();
  23560. };
  23561. }
  23562. function _maybeDrain(data) {
  23563. if (data.length === 0 && q.idle()) {
  23564. // call drain immediately if there are no tasks
  23565. setImmediate$1(() => trigger('drain'));
  23566. return true
  23567. }
  23568. return false
  23569. }
  23570. const eventMethod = (name) => (handler) => {
  23571. if (!handler) {
  23572. return new Promise((resolve, reject) => {
  23573. once(name, (err, data) => {
  23574. if (err) return reject(err)
  23575. resolve(data);
  23576. });
  23577. })
  23578. }
  23579. off(name);
  23580. on(name, handler);
  23581. };
  23582. var isProcessing = false;
  23583. var q = {
  23584. _tasks: new DLL(),
  23585. *[Symbol.iterator] () {
  23586. yield* q._tasks[Symbol.iterator]();
  23587. },
  23588. concurrency,
  23589. payload,
  23590. buffer: concurrency / 4,
  23591. started: false,
  23592. paused: false,
  23593. push (data, callback) {
  23594. if (Array.isArray(data)) {
  23595. if (_maybeDrain(data)) return
  23596. return data.map(datum => _insert(datum, false, false, callback))
  23597. }
  23598. return _insert(data, false, false, callback);
  23599. },
  23600. pushAsync (data, callback) {
  23601. if (Array.isArray(data)) {
  23602. if (_maybeDrain(data)) return
  23603. return data.map(datum => _insert(datum, false, true, callback))
  23604. }
  23605. return _insert(data, false, true, callback);
  23606. },
  23607. kill () {
  23608. off();
  23609. q._tasks.empty();
  23610. },
  23611. unshift (data, callback) {
  23612. if (Array.isArray(data)) {
  23613. if (_maybeDrain(data)) return
  23614. return data.map(datum => _insert(datum, true, false, callback))
  23615. }
  23616. return _insert(data, true, false, callback);
  23617. },
  23618. unshiftAsync (data, callback) {
  23619. if (Array.isArray(data)) {
  23620. if (_maybeDrain(data)) return
  23621. return data.map(datum => _insert(datum, true, true, callback))
  23622. }
  23623. return _insert(data, true, true, callback);
  23624. },
  23625. remove (testFn) {
  23626. q._tasks.remove(testFn);
  23627. },
  23628. process () {
  23629. // Avoid trying to start too many processing operations. This can occur
  23630. // when callbacks resolve synchronously (#1267).
  23631. if (isProcessing) {
  23632. return;
  23633. }
  23634. isProcessing = true;
  23635. while(!q.paused && numRunning < q.concurrency && q._tasks.length){
  23636. var tasks = [], data = [];
  23637. var l = q._tasks.length;
  23638. if (q.payload) l = Math.min(l, q.payload);
  23639. for (var i = 0; i < l; i++) {
  23640. var node = q._tasks.shift();
  23641. tasks.push(node);
  23642. workersList.push(node);
  23643. data.push(node.data);
  23644. }
  23645. numRunning += 1;
  23646. if (q._tasks.length === 0) {
  23647. trigger('empty');
  23648. }
  23649. if (numRunning === q.concurrency) {
  23650. trigger('saturated');
  23651. }
  23652. var cb = onlyOnce(_createCB(tasks));
  23653. _worker(data, cb);
  23654. }
  23655. isProcessing = false;
  23656. },
  23657. length () {
  23658. return q._tasks.length;
  23659. },
  23660. running () {
  23661. return numRunning;
  23662. },
  23663. workersList () {
  23664. return workersList;
  23665. },
  23666. idle() {
  23667. return q._tasks.length + numRunning === 0;
  23668. },
  23669. pause () {
  23670. q.paused = true;
  23671. },
  23672. resume () {
  23673. if (q.paused === false) { return; }
  23674. q.paused = false;
  23675. setImmediate$1(q.process);
  23676. }
  23677. };
  23678. // define these as fixed properties, so people get useful errors when updating
  23679. Object.defineProperties(q, {
  23680. saturated: {
  23681. writable: false,
  23682. value: eventMethod('saturated')
  23683. },
  23684. unsaturated: {
  23685. writable: false,
  23686. value: eventMethod('unsaturated')
  23687. },
  23688. empty: {
  23689. writable: false,
  23690. value: eventMethod('empty')
  23691. },
  23692. drain: {
  23693. writable: false,
  23694. value: eventMethod('drain')
  23695. },
  23696. error: {
  23697. writable: false,
  23698. value: eventMethod('error')
  23699. },
  23700. });
  23701. return q;
  23702. }
  23703. /**
  23704. * Creates a `cargo` object with the specified payload. Tasks added to the
  23705. * cargo will be processed altogether (up to the `payload` limit). If the
  23706. * `worker` is in progress, the task is queued until it becomes available. Once
  23707. * the `worker` has completed some tasks, each callback of those tasks is
  23708. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  23709. * for how `cargo` and `queue` work.
  23710. *
  23711. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  23712. * at a time, cargo passes an array of tasks to a single worker, repeating
  23713. * when the worker is finished.
  23714. *
  23715. * @name cargo
  23716. * @static
  23717. * @memberOf module:ControlFlow
  23718. * @method
  23719. * @see [async.queue]{@link module:ControlFlow.queue}
  23720. * @category Control Flow
  23721. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  23722. * of queued tasks. Invoked with `(tasks, callback)`.
  23723. * @param {number} [payload=Infinity] - An optional `integer` for determining
  23724. * how many tasks should be processed per round; if omitted, the default is
  23725. * unlimited.
  23726. * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can
  23727. * attached as certain properties to listen for specific events during the
  23728. * lifecycle of the cargo and inner queue.
  23729. * @example
  23730. *
  23731. * // create a cargo object with payload 2
  23732. * var cargo = async.cargo(function(tasks, callback) {
  23733. * for (var i=0; i<tasks.length; i++) {
  23734. * console.log('hello ' + tasks[i].name);
  23735. * }
  23736. * callback();
  23737. * }, 2);
  23738. *
  23739. * // add some items
  23740. * cargo.push({name: 'foo'}, function(err) {
  23741. * console.log('finished processing foo');
  23742. * });
  23743. * cargo.push({name: 'bar'}, function(err) {
  23744. * console.log('finished processing bar');
  23745. * });
  23746. * await cargo.push({name: 'baz'});
  23747. * console.log('finished processing baz');
  23748. */
  23749. function cargo(worker, payload) {
  23750. return queue(worker, 1, payload);
  23751. }
  23752. /**
  23753. * Creates a `cargoQueue` object with the specified payload. Tasks added to the
  23754. * cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers.
  23755. * If the all `workers` are in progress, the task is queued until one becomes available. Once
  23756. * a `worker` has completed some tasks, each callback of those tasks is
  23757. * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
  23758. * for how `cargo` and `queue` work.
  23759. *
  23760. * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
  23761. * at a time, and [`cargo`]{@link module:ControlFlow.cargo} passes an array of tasks to a single worker,
  23762. * the cargoQueue passes an array of tasks to multiple parallel workers.
  23763. *
  23764. * @name cargoQueue
  23765. * @static
  23766. * @memberOf module:ControlFlow
  23767. * @method
  23768. * @see [async.queue]{@link module:ControlFlow.queue}
  23769. * @see [async.cargo]{@link module:ControlFLow.cargo}
  23770. * @category Control Flow
  23771. * @param {AsyncFunction} worker - An asynchronous function for processing an array
  23772. * of queued tasks. Invoked with `(tasks, callback)`.
  23773. * @param {number} [concurrency=1] - An `integer` for determining how many
  23774. * `worker` functions should be run in parallel. If omitted, the concurrency
  23775. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  23776. * @param {number} [payload=Infinity] - An optional `integer` for determining
  23777. * how many tasks should be processed per round; if omitted, the default is
  23778. * unlimited.
  23779. * @returns {module:ControlFlow.QueueObject} A cargoQueue object to manage the tasks. Callbacks can
  23780. * attached as certain properties to listen for specific events during the
  23781. * lifecycle of the cargoQueue and inner queue.
  23782. * @example
  23783. *
  23784. * // create a cargoQueue object with payload 2 and concurrency 2
  23785. * var cargoQueue = async.cargoQueue(function(tasks, callback) {
  23786. * for (var i=0; i<tasks.length; i++) {
  23787. * console.log('hello ' + tasks[i].name);
  23788. * }
  23789. * callback();
  23790. * }, 2, 2);
  23791. *
  23792. * // add some items
  23793. * cargoQueue.push({name: 'foo'}, function(err) {
  23794. * console.log('finished processing foo');
  23795. * });
  23796. * cargoQueue.push({name: 'bar'}, function(err) {
  23797. * console.log('finished processing bar');
  23798. * });
  23799. * cargoQueue.push({name: 'baz'}, function(err) {
  23800. * console.log('finished processing baz');
  23801. * });
  23802. * cargoQueue.push({name: 'boo'}, function(err) {
  23803. * console.log('finished processing boo');
  23804. * });
  23805. */
  23806. function cargo$1(worker, concurrency, payload) {
  23807. return queue(worker, concurrency, payload);
  23808. }
  23809. /**
  23810. * Reduces `coll` into a single value using an async `iteratee` to return each
  23811. * successive step. `memo` is the initial state of the reduction. This function
  23812. * only operates in series.
  23813. *
  23814. * For performance reasons, it may make sense to split a call to this function
  23815. * into a parallel map, and then use the normal `Array.prototype.reduce` on the
  23816. * results. This function is for situations where each step in the reduction
  23817. * needs to be async; if you can get the data before reducing it, then it's
  23818. * probably a good idea to do so.
  23819. *
  23820. * @name reduce
  23821. * @static
  23822. * @memberOf module:Collections
  23823. * @method
  23824. * @alias inject
  23825. * @alias foldl
  23826. * @category Collection
  23827. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  23828. * @param {*} memo - The initial state of the reduction.
  23829. * @param {AsyncFunction} iteratee - A function applied to each item in the
  23830. * array to produce the next step in the reduction.
  23831. * The `iteratee` should complete with the next state of the reduction.
  23832. * If the iteratee complete with an error, the reduction is stopped and the
  23833. * main `callback` is immediately called with the error.
  23834. * Invoked with (memo, item, callback).
  23835. * @param {Function} [callback] - A callback which is called after all the
  23836. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  23837. * (err, result).
  23838. * @returns {Promise} a promise, if no callback is passed
  23839. * @example
  23840. *
  23841. * async.reduce([1,2,3], 0, function(memo, item, callback) {
  23842. * // pointless async:
  23843. * process.nextTick(function() {
  23844. * callback(null, memo + item)
  23845. * });
  23846. * }, function(err, result) {
  23847. * // result is now equal to the last value of memo, which is 6
  23848. * });
  23849. */
  23850. function reduce(coll, memo, iteratee, callback) {
  23851. callback = once(callback);
  23852. var _iteratee = wrapAsync(iteratee);
  23853. return eachOfSeries$1(coll, (x, i, iterCb) => {
  23854. _iteratee(memo, x, (err, v) => {
  23855. memo = v;
  23856. iterCb(err);
  23857. });
  23858. }, err => callback(err, memo));
  23859. }
  23860. var reduce$1 = awaitify(reduce, 4);
  23861. /**
  23862. * Version of the compose function that is more natural to read. Each function
  23863. * consumes the return value of the previous function. It is the equivalent of
  23864. * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
  23865. *
  23866. * Each function is executed with the `this` binding of the composed function.
  23867. *
  23868. * @name seq
  23869. * @static
  23870. * @memberOf module:ControlFlow
  23871. * @method
  23872. * @see [async.compose]{@link module:ControlFlow.compose}
  23873. * @category Control Flow
  23874. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  23875. * @returns {Function} a function that composes the `functions` in order
  23876. * @example
  23877. *
  23878. * // Requires lodash (or underscore), express3 and dresende's orm2.
  23879. * // Part of an app, that fetches cats of the logged user.
  23880. * // This example uses `seq` function to avoid overnesting and error
  23881. * // handling clutter.
  23882. * app.get('/cats', function(request, response) {
  23883. * var User = request.models.User;
  23884. * async.seq(
  23885. * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
  23886. * function(user, fn) {
  23887. * user.getCats(fn); // 'getCats' has signature (callback(err, data))
  23888. * }
  23889. * )(req.session.user_id, function (err, cats) {
  23890. * if (err) {
  23891. * console.error(err);
  23892. * response.json({ status: 'error', message: err.message });
  23893. * } else {
  23894. * response.json({ status: 'ok', message: 'Cats found', data: cats });
  23895. * }
  23896. * });
  23897. * });
  23898. */
  23899. function seq(...functions) {
  23900. var _functions = functions.map(wrapAsync);
  23901. return function (...args) {
  23902. var that = this;
  23903. var cb = args[args.length - 1];
  23904. if (typeof cb == 'function') {
  23905. args.pop();
  23906. } else {
  23907. cb = promiseCallback();
  23908. }
  23909. reduce$1(_functions, args, (newargs, fn, iterCb) => {
  23910. fn.apply(that, newargs.concat((err, ...nextargs) => {
  23911. iterCb(err, nextargs);
  23912. }));
  23913. },
  23914. (err, results) => cb(err, ...results));
  23915. return cb[PROMISE_SYMBOL]
  23916. };
  23917. }
  23918. /**
  23919. * Creates a function which is a composition of the passed asynchronous
  23920. * functions. Each function consumes the return value of the function that
  23921. * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
  23922. * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
  23923. *
  23924. * If the last argument to the composed function is not a function, a promise
  23925. * is returned when you call it.
  23926. *
  23927. * Each function is executed with the `this` binding of the composed function.
  23928. *
  23929. * @name compose
  23930. * @static
  23931. * @memberOf module:ControlFlow
  23932. * @method
  23933. * @category Control Flow
  23934. * @param {...AsyncFunction} functions - the asynchronous functions to compose
  23935. * @returns {Function} an asynchronous function that is the composed
  23936. * asynchronous `functions`
  23937. * @example
  23938. *
  23939. * function add1(n, callback) {
  23940. * setTimeout(function () {
  23941. * callback(null, n + 1);
  23942. * }, 10);
  23943. * }
  23944. *
  23945. * function mul3(n, callback) {
  23946. * setTimeout(function () {
  23947. * callback(null, n * 3);
  23948. * }, 10);
  23949. * }
  23950. *
  23951. * var add1mul3 = async.compose(mul3, add1);
  23952. * add1mul3(4, function (err, result) {
  23953. * // result now equals 15
  23954. * });
  23955. */
  23956. function compose(...args) {
  23957. return seq(...args.reverse());
  23958. }
  23959. /**
  23960. * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
  23961. *
  23962. * @name mapLimit
  23963. * @static
  23964. * @memberOf module:Collections
  23965. * @method
  23966. * @see [async.map]{@link module:Collections.map}
  23967. * @category Collection
  23968. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  23969. * @param {number} limit - The maximum number of async operations at a time.
  23970. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  23971. * `coll`.
  23972. * The iteratee should complete with the transformed item.
  23973. * Invoked with (item, callback).
  23974. * @param {Function} [callback] - A callback which is called when all `iteratee`
  23975. * functions have finished, or an error occurs. Results is an array of the
  23976. * transformed items from the `coll`. Invoked with (err, results).
  23977. * @returns {Promise} a promise, if no callback is passed
  23978. */
  23979. function mapLimit (coll, limit, iteratee, callback) {
  23980. return _asyncMap(eachOfLimit(limit), coll, iteratee, callback)
  23981. }
  23982. var mapLimit$1 = awaitify(mapLimit, 4);
  23983. /**
  23984. * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
  23985. *
  23986. * @name concatLimit
  23987. * @static
  23988. * @memberOf module:Collections
  23989. * @method
  23990. * @see [async.concat]{@link module:Collections.concat}
  23991. * @category Collection
  23992. * @alias flatMapLimit
  23993. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  23994. * @param {number} limit - The maximum number of async operations at a time.
  23995. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  23996. * which should use an array as its result. Invoked with (item, callback).
  23997. * @param {Function} [callback] - A callback which is called after all the
  23998. * `iteratee` functions have finished, or an error occurs. Results is an array
  23999. * containing the concatenated results of the `iteratee` function. Invoked with
  24000. * (err, results).
  24001. * @returns A Promise, if no callback is passed
  24002. */
  24003. function concatLimit(coll, limit, iteratee, callback) {
  24004. var _iteratee = wrapAsync(iteratee);
  24005. return mapLimit$1(coll, limit, (val, iterCb) => {
  24006. _iteratee(val, (err, ...args) => {
  24007. if (err) return iterCb(err);
  24008. return iterCb(err, args);
  24009. });
  24010. }, (err, mapResults) => {
  24011. var result = [];
  24012. for (var i = 0; i < mapResults.length; i++) {
  24013. if (mapResults[i]) {
  24014. result = result.concat(...mapResults[i]);
  24015. }
  24016. }
  24017. return callback(err, result);
  24018. });
  24019. }
  24020. var concatLimit$1 = awaitify(concatLimit, 4);
  24021. /**
  24022. * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
  24023. * the concatenated list. The `iteratee`s are called in parallel, and the
  24024. * results are concatenated as they return. The results array will be returned in
  24025. * the original order of `coll` passed to the `iteratee` function.
  24026. *
  24027. * @name concat
  24028. * @static
  24029. * @memberOf module:Collections
  24030. * @method
  24031. * @category Collection
  24032. * @alias flatMap
  24033. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24034. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
  24035. * which should use an array as its result. Invoked with (item, callback).
  24036. * @param {Function} [callback] - A callback which is called after all the
  24037. * `iteratee` functions have finished, or an error occurs. Results is an array
  24038. * containing the concatenated results of the `iteratee` function. Invoked with
  24039. * (err, results).
  24040. * @returns A Promise, if no callback is passed
  24041. * @example
  24042. *
  24043. * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
  24044. * // files is now a list of filenames that exist in the 3 directories
  24045. * });
  24046. */
  24047. function concat(coll, iteratee, callback) {
  24048. return concatLimit$1(coll, Infinity, iteratee, callback)
  24049. }
  24050. var concat$1 = awaitify(concat, 3);
  24051. /**
  24052. * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
  24053. *
  24054. * @name concatSeries
  24055. * @static
  24056. * @memberOf module:Collections
  24057. * @method
  24058. * @see [async.concat]{@link module:Collections.concat}
  24059. * @category Collection
  24060. * @alias flatMapSeries
  24061. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24062. * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
  24063. * The iteratee should complete with an array an array of results.
  24064. * Invoked with (item, callback).
  24065. * @param {Function} [callback] - A callback which is called after all the
  24066. * `iteratee` functions have finished, or an error occurs. Results is an array
  24067. * containing the concatenated results of the `iteratee` function. Invoked with
  24068. * (err, results).
  24069. * @returns A Promise, if no callback is passed
  24070. */
  24071. function concatSeries(coll, iteratee, callback) {
  24072. return concatLimit$1(coll, 1, iteratee, callback)
  24073. }
  24074. var concatSeries$1 = awaitify(concatSeries, 3);
  24075. /**
  24076. * Returns a function that when called, calls-back with the values provided.
  24077. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
  24078. * [`auto`]{@link module:ControlFlow.auto}.
  24079. *
  24080. * @name constant
  24081. * @static
  24082. * @memberOf module:Utils
  24083. * @method
  24084. * @category Util
  24085. * @param {...*} arguments... - Any number of arguments to automatically invoke
  24086. * callback with.
  24087. * @returns {AsyncFunction} Returns a function that when invoked, automatically
  24088. * invokes the callback with the previous given arguments.
  24089. * @example
  24090. *
  24091. * async.waterfall([
  24092. * async.constant(42),
  24093. * function (value, next) {
  24094. * // value === 42
  24095. * },
  24096. * //...
  24097. * ], callback);
  24098. *
  24099. * async.waterfall([
  24100. * async.constant(filename, "utf8"),
  24101. * fs.readFile,
  24102. * function (fileData, next) {
  24103. * //...
  24104. * }
  24105. * //...
  24106. * ], callback);
  24107. *
  24108. * async.auto({
  24109. * hostname: async.constant("https://server.net/"),
  24110. * port: findFreePort,
  24111. * launchServer: ["hostname", "port", function (options, cb) {
  24112. * startServer(options, cb);
  24113. * }],
  24114. * //...
  24115. * }, callback);
  24116. */
  24117. function constant(...args) {
  24118. return function (...ignoredArgs/*, callback*/) {
  24119. var callback = ignoredArgs.pop();
  24120. return callback(null, ...args);
  24121. };
  24122. }
  24123. function _createTester(check, getResult) {
  24124. return (eachfn, arr, _iteratee, cb) => {
  24125. var testPassed = false;
  24126. var testResult;
  24127. const iteratee = wrapAsync(_iteratee);
  24128. eachfn(arr, (value, _, callback) => {
  24129. iteratee(value, (err, result) => {
  24130. if (err || err === false) return callback(err);
  24131. if (check(result) && !testResult) {
  24132. testPassed = true;
  24133. testResult = getResult(true, value);
  24134. return callback(null, breakLoop);
  24135. }
  24136. callback();
  24137. });
  24138. }, err => {
  24139. if (err) return cb(err);
  24140. cb(null, testPassed ? testResult : getResult(false));
  24141. });
  24142. };
  24143. }
  24144. /**
  24145. * Returns the first value in `coll` that passes an async truth test. The
  24146. * `iteratee` is applied in parallel, meaning the first iteratee to return
  24147. * `true` will fire the detect `callback` with that result. That means the
  24148. * result might not be the first item in the original `coll` (in terms of order)
  24149. * that passes the test.
  24150. * If order within the original `coll` is important, then look at
  24151. * [`detectSeries`]{@link module:Collections.detectSeries}.
  24152. *
  24153. * @name detect
  24154. * @static
  24155. * @memberOf module:Collections
  24156. * @method
  24157. * @alias find
  24158. * @category Collections
  24159. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24160. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  24161. * The iteratee must complete with a boolean value as its result.
  24162. * Invoked with (item, callback).
  24163. * @param {Function} [callback] - A callback which is called as soon as any
  24164. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  24165. * Result will be the first item in the array that passes the truth test
  24166. * (iteratee) or the value `undefined` if none passed. Invoked with
  24167. * (err, result).
  24168. * @returns A Promise, if no callback is passed
  24169. * @example
  24170. *
  24171. * async.detect(['file1','file2','file3'], function(filePath, callback) {
  24172. * fs.access(filePath, function(err) {
  24173. * callback(null, !err)
  24174. * });
  24175. * }, function(err, result) {
  24176. * // result now equals the first file in the list that exists
  24177. * });
  24178. */
  24179. function detect(coll, iteratee, callback) {
  24180. return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)
  24181. }
  24182. var detect$1 = awaitify(detect, 3);
  24183. /**
  24184. * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
  24185. * time.
  24186. *
  24187. * @name detectLimit
  24188. * @static
  24189. * @memberOf module:Collections
  24190. * @method
  24191. * @see [async.detect]{@link module:Collections.detect}
  24192. * @alias findLimit
  24193. * @category Collections
  24194. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24195. * @param {number} limit - The maximum number of async operations at a time.
  24196. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  24197. * The iteratee must complete with a boolean value as its result.
  24198. * Invoked with (item, callback).
  24199. * @param {Function} [callback] - A callback which is called as soon as any
  24200. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  24201. * Result will be the first item in the array that passes the truth test
  24202. * (iteratee) or the value `undefined` if none passed. Invoked with
  24203. * (err, result).
  24204. * @returns a Promise if no callback is passed
  24205. */
  24206. function detectLimit(coll, limit, iteratee, callback) {
  24207. return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback)
  24208. }
  24209. var detectLimit$1 = awaitify(detectLimit, 4);
  24210. /**
  24211. * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
  24212. *
  24213. * @name detectSeries
  24214. * @static
  24215. * @memberOf module:Collections
  24216. * @method
  24217. * @see [async.detect]{@link module:Collections.detect}
  24218. * @alias findSeries
  24219. * @category Collections
  24220. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24221. * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
  24222. * The iteratee must complete with a boolean value as its result.
  24223. * Invoked with (item, callback).
  24224. * @param {Function} [callback] - A callback which is called as soon as any
  24225. * iteratee returns `true`, or after all the `iteratee` functions have finished.
  24226. * Result will be the first item in the array that passes the truth test
  24227. * (iteratee) or the value `undefined` if none passed. Invoked with
  24228. * (err, result).
  24229. * @returns a Promise if no callback is passed
  24230. */
  24231. function detectSeries(coll, iteratee, callback) {
  24232. return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback)
  24233. }
  24234. var detectSeries$1 = awaitify(detectSeries, 3);
  24235. function consoleFunc(name) {
  24236. return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {
  24237. if (typeof console === 'object') {
  24238. if (err) {
  24239. if (console.error) {
  24240. console.error(err);
  24241. }
  24242. } else if (console[name]) {
  24243. resultArgs.forEach(x => console[name](x));
  24244. }
  24245. }
  24246. })
  24247. }
  24248. /**
  24249. * Logs the result of an [`async` function]{@link AsyncFunction} to the
  24250. * `console` using `console.dir` to display the properties of the resulting object.
  24251. * Only works in Node.js or in browsers that support `console.dir` and
  24252. * `console.error` (such as FF and Chrome).
  24253. * If multiple arguments are returned from the async function,
  24254. * `console.dir` is called on each argument in order.
  24255. *
  24256. * @name dir
  24257. * @static
  24258. * @memberOf module:Utils
  24259. * @method
  24260. * @category Util
  24261. * @param {AsyncFunction} function - The function you want to eventually apply
  24262. * all arguments to.
  24263. * @param {...*} arguments... - Any number of arguments to apply to the function.
  24264. * @example
  24265. *
  24266. * // in a module
  24267. * var hello = function(name, callback) {
  24268. * setTimeout(function() {
  24269. * callback(null, {hello: name});
  24270. * }, 1000);
  24271. * };
  24272. *
  24273. * // in the node repl
  24274. * node> async.dir(hello, 'world');
  24275. * {hello: 'world'}
  24276. */
  24277. var dir = consoleFunc('dir');
  24278. /**
  24279. * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
  24280. * the order of operations, the arguments `test` and `iteratee` are switched.
  24281. *
  24282. * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  24283. *
  24284. * @name doWhilst
  24285. * @static
  24286. * @memberOf module:ControlFlow
  24287. * @method
  24288. * @see [async.whilst]{@link module:ControlFlow.whilst}
  24289. * @category Control Flow
  24290. * @param {AsyncFunction} iteratee - A function which is called each time `test`
  24291. * passes. Invoked with (callback).
  24292. * @param {AsyncFunction} test - asynchronous truth test to perform after each
  24293. * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
  24294. * non-error args from the previous callback of `iteratee`.
  24295. * @param {Function} [callback] - A callback which is called after the test
  24296. * function has failed and repeated execution of `iteratee` has stopped.
  24297. * `callback` will be passed an error and any arguments passed to the final
  24298. * `iteratee`'s callback. Invoked with (err, [results]);
  24299. * @returns {Promise} a promise, if no callback is passed
  24300. */
  24301. function doWhilst(iteratee, test, callback) {
  24302. callback = onlyOnce(callback);
  24303. var _fn = wrapAsync(iteratee);
  24304. var _test = wrapAsync(test);
  24305. var results;
  24306. function next(err, ...args) {
  24307. if (err) return callback(err);
  24308. if (err === false) return;
  24309. results = args;
  24310. _test(...args, check);
  24311. }
  24312. function check(err, truth) {
  24313. if (err) return callback(err);
  24314. if (err === false) return;
  24315. if (!truth) return callback(null, ...results);
  24316. _fn(next);
  24317. }
  24318. return check(null, true);
  24319. }
  24320. var doWhilst$1 = awaitify(doWhilst, 3);
  24321. /**
  24322. * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
  24323. * argument ordering differs from `until`.
  24324. *
  24325. * @name doUntil
  24326. * @static
  24327. * @memberOf module:ControlFlow
  24328. * @method
  24329. * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
  24330. * @category Control Flow
  24331. * @param {AsyncFunction} iteratee - An async function which is called each time
  24332. * `test` fails. Invoked with (callback).
  24333. * @param {AsyncFunction} test - asynchronous truth test to perform after each
  24334. * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
  24335. * non-error args from the previous callback of `iteratee`
  24336. * @param {Function} [callback] - A callback which is called after the test
  24337. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  24338. * will be passed an error and any arguments passed to the final `iteratee`'s
  24339. * callback. Invoked with (err, [results]);
  24340. * @returns {Promise} a promise, if no callback is passed
  24341. */
  24342. function doUntil(iteratee, test, callback) {
  24343. const _test = wrapAsync(test);
  24344. return doWhilst$1(iteratee, (...args) => {
  24345. const cb = args.pop();
  24346. _test(...args, (err, truth) => cb (err, !truth));
  24347. }, callback);
  24348. }
  24349. function _withoutIndex(iteratee) {
  24350. return (value, index, callback) => iteratee(value, callback);
  24351. }
  24352. /**
  24353. * Applies the function `iteratee` to each item in `coll`, in parallel.
  24354. * The `iteratee` is called with an item from the list, and a callback for when
  24355. * it has finished. If the `iteratee` passes an error to its `callback`, the
  24356. * main `callback` (for the `each` function) is immediately called with the
  24357. * error.
  24358. *
  24359. * Note, that since this function applies `iteratee` to each item in parallel,
  24360. * there is no guarantee that the iteratee functions will complete in order.
  24361. *
  24362. * @name each
  24363. * @static
  24364. * @memberOf module:Collections
  24365. * @method
  24366. * @alias forEach
  24367. * @category Collection
  24368. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24369. * @param {AsyncFunction} iteratee - An async function to apply to
  24370. * each item in `coll`. Invoked with (item, callback).
  24371. * The array index is not passed to the iteratee.
  24372. * If you need the index, use `eachOf`.
  24373. * @param {Function} [callback] - A callback which is called when all
  24374. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  24375. * @returns {Promise} a promise, if a callback is omitted
  24376. * @example
  24377. *
  24378. * // assuming openFiles is an array of file names and saveFile is a function
  24379. * // to save the modified contents of that file:
  24380. *
  24381. * async.each(openFiles, saveFile, function(err){
  24382. * // if any of the saves produced an error, err would equal that error
  24383. * });
  24384. *
  24385. * // assuming openFiles is an array of file names
  24386. * async.each(openFiles, function(file, callback) {
  24387. *
  24388. * // Perform operation on file here.
  24389. * console.log('Processing file ' + file);
  24390. *
  24391. * if( file.length > 32 ) {
  24392. * console.log('This file name is too long');
  24393. * callback('File name too long');
  24394. * } else {
  24395. * // Do work to process file here
  24396. * console.log('File processed');
  24397. * callback();
  24398. * }
  24399. * }, function(err) {
  24400. * // if any of the file processing produced an error, err would equal that error
  24401. * if( err ) {
  24402. * // One of the iterations produced an error.
  24403. * // All processing will now stop.
  24404. * console.log('A file failed to process');
  24405. * } else {
  24406. * console.log('All files have been processed successfully');
  24407. * }
  24408. * });
  24409. */
  24410. function eachLimit(coll, iteratee, callback) {
  24411. return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  24412. }
  24413. var each = awaitify(eachLimit, 3);
  24414. /**
  24415. * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
  24416. *
  24417. * @name eachLimit
  24418. * @static
  24419. * @memberOf module:Collections
  24420. * @method
  24421. * @see [async.each]{@link module:Collections.each}
  24422. * @alias forEachLimit
  24423. * @category Collection
  24424. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24425. * @param {number} limit - The maximum number of async operations at a time.
  24426. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24427. * `coll`.
  24428. * The array index is not passed to the iteratee.
  24429. * If you need the index, use `eachOfLimit`.
  24430. * Invoked with (item, callback).
  24431. * @param {Function} [callback] - A callback which is called when all
  24432. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  24433. * @returns {Promise} a promise, if a callback is omitted
  24434. */
  24435. function eachLimit$1(coll, limit, iteratee, callback) {
  24436. return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
  24437. }
  24438. var eachLimit$2 = awaitify(eachLimit$1, 4);
  24439. /**
  24440. * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
  24441. *
  24442. * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item
  24443. * in series and therefore the iteratee functions will complete in order.
  24444. * @name eachSeries
  24445. * @static
  24446. * @memberOf module:Collections
  24447. * @method
  24448. * @see [async.each]{@link module:Collections.each}
  24449. * @alias forEachSeries
  24450. * @category Collection
  24451. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24452. * @param {AsyncFunction} iteratee - An async function to apply to each
  24453. * item in `coll`.
  24454. * The array index is not passed to the iteratee.
  24455. * If you need the index, use `eachOfSeries`.
  24456. * Invoked with (item, callback).
  24457. * @param {Function} [callback] - A callback which is called when all
  24458. * `iteratee` functions have finished, or an error occurs. Invoked with (err).
  24459. * @returns {Promise} a promise, if a callback is omitted
  24460. */
  24461. function eachSeries(coll, iteratee, callback) {
  24462. return eachLimit$2(coll, 1, iteratee, callback)
  24463. }
  24464. var eachSeries$1 = awaitify(eachSeries, 3);
  24465. /**
  24466. * Wrap an async function and ensure it calls its callback on a later tick of
  24467. * the event loop. If the function already calls its callback on a next tick,
  24468. * no extra deferral is added. This is useful for preventing stack overflows
  24469. * (`RangeError: Maximum call stack size exceeded`) and generally keeping
  24470. * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
  24471. * contained. ES2017 `async` functions are returned as-is -- they are immune
  24472. * to Zalgo's corrupting influences, as they always resolve on a later tick.
  24473. *
  24474. * @name ensureAsync
  24475. * @static
  24476. * @memberOf module:Utils
  24477. * @method
  24478. * @category Util
  24479. * @param {AsyncFunction} fn - an async function, one that expects a node-style
  24480. * callback as its last argument.
  24481. * @returns {AsyncFunction} Returns a wrapped function with the exact same call
  24482. * signature as the function passed in.
  24483. * @example
  24484. *
  24485. * function sometimesAsync(arg, callback) {
  24486. * if (cache[arg]) {
  24487. * return callback(null, cache[arg]); // this would be synchronous!!
  24488. * } else {
  24489. * doSomeIO(arg, callback); // this IO would be asynchronous
  24490. * }
  24491. * }
  24492. *
  24493. * // this has a risk of stack overflows if many results are cached in a row
  24494. * async.mapSeries(args, sometimesAsync, done);
  24495. *
  24496. * // this will defer sometimesAsync's callback if necessary,
  24497. * // preventing stack overflows
  24498. * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
  24499. */
  24500. function ensureAsync(fn) {
  24501. if (isAsync(fn)) return fn;
  24502. return function (...args/*, callback*/) {
  24503. var callback = args.pop();
  24504. var sync = true;
  24505. args.push((...innerArgs) => {
  24506. if (sync) {
  24507. setImmediate$1(() => callback(...innerArgs));
  24508. } else {
  24509. callback(...innerArgs);
  24510. }
  24511. });
  24512. fn.apply(this, args);
  24513. sync = false;
  24514. };
  24515. }
  24516. /**
  24517. * Returns `true` if every element in `coll` satisfies an async test. If any
  24518. * iteratee call returns `false`, the main `callback` is immediately called.
  24519. *
  24520. * @name every
  24521. * @static
  24522. * @memberOf module:Collections
  24523. * @method
  24524. * @alias all
  24525. * @category Collection
  24526. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24527. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  24528. * in the collection in parallel.
  24529. * The iteratee must complete with a boolean result value.
  24530. * Invoked with (item, callback).
  24531. * @param {Function} [callback] - A callback which is called after all the
  24532. * `iteratee` functions have finished. Result will be either `true` or `false`
  24533. * depending on the values of the async tests. Invoked with (err, result).
  24534. * @returns {Promise} a promise, if no callback provided
  24535. * @example
  24536. *
  24537. * async.every(['file1','file2','file3'], function(filePath, callback) {
  24538. * fs.access(filePath, function(err) {
  24539. * callback(null, !err)
  24540. * });
  24541. * }, function(err, result) {
  24542. * // if result is true then every file exists
  24543. * });
  24544. */
  24545. function every(coll, iteratee, callback) {
  24546. return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)
  24547. }
  24548. var every$1 = awaitify(every, 3);
  24549. /**
  24550. * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
  24551. *
  24552. * @name everyLimit
  24553. * @static
  24554. * @memberOf module:Collections
  24555. * @method
  24556. * @see [async.every]{@link module:Collections.every}
  24557. * @alias allLimit
  24558. * @category Collection
  24559. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24560. * @param {number} limit - The maximum number of async operations at a time.
  24561. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  24562. * in the collection in parallel.
  24563. * The iteratee must complete with a boolean result value.
  24564. * Invoked with (item, callback).
  24565. * @param {Function} [callback] - A callback which is called after all the
  24566. * `iteratee` functions have finished. Result will be either `true` or `false`
  24567. * depending on the values of the async tests. Invoked with (err, result).
  24568. * @returns {Promise} a promise, if no callback provided
  24569. */
  24570. function everyLimit(coll, limit, iteratee, callback) {
  24571. return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)
  24572. }
  24573. var everyLimit$1 = awaitify(everyLimit, 4);
  24574. /**
  24575. * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
  24576. *
  24577. * @name everySeries
  24578. * @static
  24579. * @memberOf module:Collections
  24580. * @method
  24581. * @see [async.every]{@link module:Collections.every}
  24582. * @alias allSeries
  24583. * @category Collection
  24584. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24585. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  24586. * in the collection in series.
  24587. * The iteratee must complete with a boolean result value.
  24588. * Invoked with (item, callback).
  24589. * @param {Function} [callback] - A callback which is called after all the
  24590. * `iteratee` functions have finished. Result will be either `true` or `false`
  24591. * depending on the values of the async tests. Invoked with (err, result).
  24592. * @returns {Promise} a promise, if no callback provided
  24593. */
  24594. function everySeries(coll, iteratee, callback) {
  24595. return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)
  24596. }
  24597. var everySeries$1 = awaitify(everySeries, 3);
  24598. function filterArray(eachfn, arr, iteratee, callback) {
  24599. var truthValues = new Array(arr.length);
  24600. eachfn(arr, (x, index, iterCb) => {
  24601. iteratee(x, (err, v) => {
  24602. truthValues[index] = !!v;
  24603. iterCb(err);
  24604. });
  24605. }, err => {
  24606. if (err) return callback(err);
  24607. var results = [];
  24608. for (var i = 0; i < arr.length; i++) {
  24609. if (truthValues[i]) results.push(arr[i]);
  24610. }
  24611. callback(null, results);
  24612. });
  24613. }
  24614. function filterGeneric(eachfn, coll, iteratee, callback) {
  24615. var results = [];
  24616. eachfn(coll, (x, index, iterCb) => {
  24617. iteratee(x, (err, v) => {
  24618. if (err) return iterCb(err);
  24619. if (v) {
  24620. results.push({index, value: x});
  24621. }
  24622. iterCb(err);
  24623. });
  24624. }, err => {
  24625. if (err) return callback(err);
  24626. callback(null, results
  24627. .sort((a, b) => a.index - b.index)
  24628. .map(v => v.value));
  24629. });
  24630. }
  24631. function _filter(eachfn, coll, iteratee, callback) {
  24632. var filter = isArrayLike(coll) ? filterArray : filterGeneric;
  24633. return filter(eachfn, coll, wrapAsync(iteratee), callback);
  24634. }
  24635. /**
  24636. * Returns a new array of all the values in `coll` which pass an async truth
  24637. * test. This operation is performed in parallel, but the results array will be
  24638. * in the same order as the original.
  24639. *
  24640. * @name filter
  24641. * @static
  24642. * @memberOf module:Collections
  24643. * @method
  24644. * @alias select
  24645. * @category Collection
  24646. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24647. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  24648. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  24649. * with a boolean argument once it has completed. Invoked with (item, callback).
  24650. * @param {Function} [callback] - A callback which is called after all the
  24651. * `iteratee` functions have finished. Invoked with (err, results).
  24652. * @returns {Promise} a promise, if no callback provided
  24653. * @example
  24654. *
  24655. * async.filter(['file1','file2','file3'], function(filePath, callback) {
  24656. * fs.access(filePath, function(err) {
  24657. * callback(null, !err)
  24658. * });
  24659. * }, function(err, results) {
  24660. * // results now equals an array of the existing files
  24661. * });
  24662. */
  24663. function filter (coll, iteratee, callback) {
  24664. return _filter(eachOf$1, coll, iteratee, callback)
  24665. }
  24666. var filter$1 = awaitify(filter, 3);
  24667. /**
  24668. * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
  24669. * time.
  24670. *
  24671. * @name filterLimit
  24672. * @static
  24673. * @memberOf module:Collections
  24674. * @method
  24675. * @see [async.filter]{@link module:Collections.filter}
  24676. * @alias selectLimit
  24677. * @category Collection
  24678. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24679. * @param {number} limit - The maximum number of async operations at a time.
  24680. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  24681. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  24682. * with a boolean argument once it has completed. Invoked with (item, callback).
  24683. * @param {Function} [callback] - A callback which is called after all the
  24684. * `iteratee` functions have finished. Invoked with (err, results).
  24685. * @returns {Promise} a promise, if no callback provided
  24686. */
  24687. function filterLimit (coll, limit, iteratee, callback) {
  24688. return _filter(eachOfLimit(limit), coll, iteratee, callback)
  24689. }
  24690. var filterLimit$1 = awaitify(filterLimit, 4);
  24691. /**
  24692. * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
  24693. *
  24694. * @name filterSeries
  24695. * @static
  24696. * @memberOf module:Collections
  24697. * @method
  24698. * @see [async.filter]{@link module:Collections.filter}
  24699. * @alias selectSeries
  24700. * @category Collection
  24701. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24702. * @param {Function} iteratee - A truth test to apply to each item in `coll`.
  24703. * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
  24704. * with a boolean argument once it has completed. Invoked with (item, callback).
  24705. * @param {Function} [callback] - A callback which is called after all the
  24706. * `iteratee` functions have finished. Invoked with (err, results)
  24707. * @returns {Promise} a promise, if no callback provided
  24708. */
  24709. function filterSeries (coll, iteratee, callback) {
  24710. return _filter(eachOfSeries$1, coll, iteratee, callback)
  24711. }
  24712. var filterSeries$1 = awaitify(filterSeries, 3);
  24713. /**
  24714. * Calls the asynchronous function `fn` with a callback parameter that allows it
  24715. * to call itself again, in series, indefinitely.
  24716. * If an error is passed to the callback then `errback` is called with the
  24717. * error, and execution stops, otherwise it will never be called.
  24718. *
  24719. * @name forever
  24720. * @static
  24721. * @memberOf module:ControlFlow
  24722. * @method
  24723. * @category Control Flow
  24724. * @param {AsyncFunction} fn - an async function to call repeatedly.
  24725. * Invoked with (next).
  24726. * @param {Function} [errback] - when `fn` passes an error to it's callback,
  24727. * this function will be called, and execution stops. Invoked with (err).
  24728. * @returns {Promise} a promise that rejects if an error occurs and an errback
  24729. * is not passed
  24730. * @example
  24731. *
  24732. * async.forever(
  24733. * function(next) {
  24734. * // next is suitable for passing to things that need a callback(err [, whatever]);
  24735. * // it will result in this function being called again.
  24736. * },
  24737. * function(err) {
  24738. * // if next is called with a value in its first parameter, it will appear
  24739. * // in here as 'err', and execution will stop.
  24740. * }
  24741. * );
  24742. */
  24743. function forever(fn, errback) {
  24744. var done = onlyOnce(errback);
  24745. var task = wrapAsync(ensureAsync(fn));
  24746. function next(err) {
  24747. if (err) return done(err);
  24748. if (err === false) return;
  24749. task(next);
  24750. }
  24751. return next();
  24752. }
  24753. var forever$1 = awaitify(forever, 2);
  24754. /**
  24755. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
  24756. *
  24757. * @name groupByLimit
  24758. * @static
  24759. * @memberOf module:Collections
  24760. * @method
  24761. * @see [async.groupBy]{@link module:Collections.groupBy}
  24762. * @category Collection
  24763. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24764. * @param {number} limit - The maximum number of async operations at a time.
  24765. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24766. * `coll`.
  24767. * The iteratee should complete with a `key` to group the value under.
  24768. * Invoked with (value, callback).
  24769. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24770. * functions have finished, or an error occurs. Result is an `Object` whoses
  24771. * properties are arrays of values which returned the corresponding key.
  24772. * @returns {Promise} a promise, if no callback is passed
  24773. */
  24774. function groupByLimit(coll, limit, iteratee, callback) {
  24775. var _iteratee = wrapAsync(iteratee);
  24776. return mapLimit$1(coll, limit, (val, iterCb) => {
  24777. _iteratee(val, (err, key) => {
  24778. if (err) return iterCb(err);
  24779. return iterCb(err, {key, val});
  24780. });
  24781. }, (err, mapResults) => {
  24782. var result = {};
  24783. // from MDN, handle object having an `hasOwnProperty` prop
  24784. var {hasOwnProperty} = Object.prototype;
  24785. for (var i = 0; i < mapResults.length; i++) {
  24786. if (mapResults[i]) {
  24787. var {key} = mapResults[i];
  24788. var {val} = mapResults[i];
  24789. if (hasOwnProperty.call(result, key)) {
  24790. result[key].push(val);
  24791. } else {
  24792. result[key] = [val];
  24793. }
  24794. }
  24795. }
  24796. return callback(err, result);
  24797. });
  24798. }
  24799. var groupByLimit$1 = awaitify(groupByLimit, 4);
  24800. /**
  24801. * Returns a new object, where each value corresponds to an array of items, from
  24802. * `coll`, that returned the corresponding key. That is, the keys of the object
  24803. * correspond to the values passed to the `iteratee` callback.
  24804. *
  24805. * Note: Since this function applies the `iteratee` to each item in parallel,
  24806. * there is no guarantee that the `iteratee` functions will complete in order.
  24807. * However, the values for each key in the `result` will be in the same order as
  24808. * the original `coll`. For Objects, the values will roughly be in the order of
  24809. * the original Objects' keys (but this can vary across JavaScript engines).
  24810. *
  24811. * @name groupBy
  24812. * @static
  24813. * @memberOf module:Collections
  24814. * @method
  24815. * @category Collection
  24816. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24817. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24818. * `coll`.
  24819. * The iteratee should complete with a `key` to group the value under.
  24820. * Invoked with (value, callback).
  24821. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24822. * functions have finished, or an error occurs. Result is an `Object` whoses
  24823. * properties are arrays of values which returned the corresponding key.
  24824. * @returns {Promise} a promise, if no callback is passed
  24825. * @example
  24826. *
  24827. * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {
  24828. * db.findById(userId, function(err, user) {
  24829. * if (err) return callback(err);
  24830. * return callback(null, user.age);
  24831. * });
  24832. * }, function(err, result) {
  24833. * // result is object containing the userIds grouped by age
  24834. * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};
  24835. * });
  24836. */
  24837. function groupBy (coll, iteratee, callback) {
  24838. return groupByLimit$1(coll, Infinity, iteratee, callback)
  24839. }
  24840. /**
  24841. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
  24842. *
  24843. * @name groupBySeries
  24844. * @static
  24845. * @memberOf module:Collections
  24846. * @method
  24847. * @see [async.groupBy]{@link module:Collections.groupBy}
  24848. * @category Collection
  24849. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  24850. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24851. * `coll`.
  24852. * The iteratee should complete with a `key` to group the value under.
  24853. * Invoked with (value, callback).
  24854. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24855. * functions have finished, or an error occurs. Result is an `Object` whoses
  24856. * properties are arrays of values which returned the corresponding key.
  24857. * @returns {Promise} a promise, if no callback is passed
  24858. */
  24859. function groupBySeries (coll, iteratee, callback) {
  24860. return groupByLimit$1(coll, 1, iteratee, callback)
  24861. }
  24862. /**
  24863. * Logs the result of an `async` function to the `console`. Only works in
  24864. * Node.js or in browsers that support `console.log` and `console.error` (such
  24865. * as FF and Chrome). If multiple arguments are returned from the async
  24866. * function, `console.log` is called on each argument in order.
  24867. *
  24868. * @name log
  24869. * @static
  24870. * @memberOf module:Utils
  24871. * @method
  24872. * @category Util
  24873. * @param {AsyncFunction} function - The function you want to eventually apply
  24874. * all arguments to.
  24875. * @param {...*} arguments... - Any number of arguments to apply to the function.
  24876. * @example
  24877. *
  24878. * // in a module
  24879. * var hello = function(name, callback) {
  24880. * setTimeout(function() {
  24881. * callback(null, 'hello ' + name);
  24882. * }, 1000);
  24883. * };
  24884. *
  24885. * // in the node repl
  24886. * node> async.log(hello, 'world');
  24887. * 'hello world'
  24888. */
  24889. var log = consoleFunc('log');
  24890. /**
  24891. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
  24892. * time.
  24893. *
  24894. * @name mapValuesLimit
  24895. * @static
  24896. * @memberOf module:Collections
  24897. * @method
  24898. * @see [async.mapValues]{@link module:Collections.mapValues}
  24899. * @category Collection
  24900. * @param {Object} obj - A collection to iterate over.
  24901. * @param {number} limit - The maximum number of async operations at a time.
  24902. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  24903. * in `coll`.
  24904. * The iteratee should complete with the transformed value as its result.
  24905. * Invoked with (value, key, callback).
  24906. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24907. * functions have finished, or an error occurs. `result` is a new object consisting
  24908. * of each key from `obj`, with each transformed value on the right-hand side.
  24909. * Invoked with (err, result).
  24910. * @returns {Promise} a promise, if no callback is passed
  24911. */
  24912. function mapValuesLimit(obj, limit, iteratee, callback) {
  24913. callback = once(callback);
  24914. var newObj = {};
  24915. var _iteratee = wrapAsync(iteratee);
  24916. return eachOfLimit(limit)(obj, (val, key, next) => {
  24917. _iteratee(val, key, (err, result) => {
  24918. if (err) return next(err);
  24919. newObj[key] = result;
  24920. next(err);
  24921. });
  24922. }, err => callback(err, newObj));
  24923. }
  24924. var mapValuesLimit$1 = awaitify(mapValuesLimit, 4);
  24925. /**
  24926. * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
  24927. *
  24928. * Produces a new Object by mapping each value of `obj` through the `iteratee`
  24929. * function. The `iteratee` is called each `value` and `key` from `obj` and a
  24930. * callback for when it has finished processing. Each of these callbacks takes
  24931. * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
  24932. * passes an error to its callback, the main `callback` (for the `mapValues`
  24933. * function) is immediately called with the error.
  24934. *
  24935. * Note, the order of the keys in the result is not guaranteed. The keys will
  24936. * be roughly in the order they complete, (but this is very engine-specific)
  24937. *
  24938. * @name mapValues
  24939. * @static
  24940. * @memberOf module:Collections
  24941. * @method
  24942. * @category Collection
  24943. * @param {Object} obj - A collection to iterate over.
  24944. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  24945. * in `coll`.
  24946. * The iteratee should complete with the transformed value as its result.
  24947. * Invoked with (value, key, callback).
  24948. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24949. * functions have finished, or an error occurs. `result` is a new object consisting
  24950. * of each key from `obj`, with each transformed value on the right-hand side.
  24951. * Invoked with (err, result).
  24952. * @returns {Promise} a promise, if no callback is passed
  24953. * @example
  24954. *
  24955. * async.mapValues({
  24956. * f1: 'file1',
  24957. * f2: 'file2',
  24958. * f3: 'file3'
  24959. * }, function (file, key, callback) {
  24960. * fs.stat(file, callback);
  24961. * }, function(err, result) {
  24962. * // result is now a map of stats for each file, e.g.
  24963. * // {
  24964. * // f1: [stats for file1],
  24965. * // f2: [stats for file2],
  24966. * // f3: [stats for file3]
  24967. * // }
  24968. * });
  24969. */
  24970. function mapValues(obj, iteratee, callback) {
  24971. return mapValuesLimit$1(obj, Infinity, iteratee, callback)
  24972. }
  24973. /**
  24974. * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
  24975. *
  24976. * @name mapValuesSeries
  24977. * @static
  24978. * @memberOf module:Collections
  24979. * @method
  24980. * @see [async.mapValues]{@link module:Collections.mapValues}
  24981. * @category Collection
  24982. * @param {Object} obj - A collection to iterate over.
  24983. * @param {AsyncFunction} iteratee - A function to apply to each value and key
  24984. * in `coll`.
  24985. * The iteratee should complete with the transformed value as its result.
  24986. * Invoked with (value, key, callback).
  24987. * @param {Function} [callback] - A callback which is called when all `iteratee`
  24988. * functions have finished, or an error occurs. `result` is a new object consisting
  24989. * of each key from `obj`, with each transformed value on the right-hand side.
  24990. * Invoked with (err, result).
  24991. * @returns {Promise} a promise, if no callback is passed
  24992. */
  24993. function mapValuesSeries(obj, iteratee, callback) {
  24994. return mapValuesLimit$1(obj, 1, iteratee, callback)
  24995. }
  24996. /**
  24997. * Caches the results of an async function. When creating a hash to store
  24998. * function results against, the callback is omitted from the hash and an
  24999. * optional hash function can be used.
  25000. *
  25001. * **Note: if the async function errs, the result will not be cached and
  25002. * subsequent calls will call the wrapped function.**
  25003. *
  25004. * If no hash function is specified, the first argument is used as a hash key,
  25005. * which may work reasonably if it is a string or a data type that converts to a
  25006. * distinct string. Note that objects and arrays will not behave reasonably.
  25007. * Neither will cases where the other arguments are significant. In such cases,
  25008. * specify your own hash function.
  25009. *
  25010. * The cache of results is exposed as the `memo` property of the function
  25011. * returned by `memoize`.
  25012. *
  25013. * @name memoize
  25014. * @static
  25015. * @memberOf module:Utils
  25016. * @method
  25017. * @category Util
  25018. * @param {AsyncFunction} fn - The async function to proxy and cache results from.
  25019. * @param {Function} hasher - An optional function for generating a custom hash
  25020. * for storing results. It has all the arguments applied to it apart from the
  25021. * callback, and must be synchronous.
  25022. * @returns {AsyncFunction} a memoized version of `fn`
  25023. * @example
  25024. *
  25025. * var slow_fn = function(name, callback) {
  25026. * // do something
  25027. * callback(null, result);
  25028. * };
  25029. * var fn = async.memoize(slow_fn);
  25030. *
  25031. * // fn can now be used as if it were slow_fn
  25032. * fn('some name', function() {
  25033. * // callback
  25034. * });
  25035. */
  25036. function memoize(fn, hasher = v => v) {
  25037. var memo = Object.create(null);
  25038. var queues = Object.create(null);
  25039. var _fn = wrapAsync(fn);
  25040. var memoized = initialParams((args, callback) => {
  25041. var key = hasher(...args);
  25042. if (key in memo) {
  25043. setImmediate$1(() => callback(null, ...memo[key]));
  25044. } else if (key in queues) {
  25045. queues[key].push(callback);
  25046. } else {
  25047. queues[key] = [callback];
  25048. _fn(...args, (err, ...resultArgs) => {
  25049. // #1465 don't memoize if an error occurred
  25050. if (!err) {
  25051. memo[key] = resultArgs;
  25052. }
  25053. var q = queues[key];
  25054. delete queues[key];
  25055. for (var i = 0, l = q.length; i < l; i++) {
  25056. q[i](err, ...resultArgs);
  25057. }
  25058. });
  25059. }
  25060. });
  25061. memoized.memo = memo;
  25062. memoized.unmemoized = fn;
  25063. return memoized;
  25064. }
  25065. /**
  25066. * Calls `callback` on a later loop around the event loop. In Node.js this just
  25067. * calls `process.nextTick`. In the browser it will use `setImmediate` if
  25068. * available, otherwise `setTimeout(callback, 0)`, which means other higher
  25069. * priority events may precede the execution of `callback`.
  25070. *
  25071. * This is used internally for browser-compatibility purposes.
  25072. *
  25073. * @name nextTick
  25074. * @static
  25075. * @memberOf module:Utils
  25076. * @method
  25077. * @see [async.setImmediate]{@link module:Utils.setImmediate}
  25078. * @category Util
  25079. * @param {Function} callback - The function to call on a later loop around
  25080. * the event loop. Invoked with (args...).
  25081. * @param {...*} args... - any number of additional arguments to pass to the
  25082. * callback on the next tick.
  25083. * @example
  25084. *
  25085. * var call_order = [];
  25086. * async.nextTick(function() {
  25087. * call_order.push('two');
  25088. * // call_order now equals ['one','two']
  25089. * });
  25090. * call_order.push('one');
  25091. *
  25092. * async.setImmediate(function (a, b, c) {
  25093. * // a, b, and c equal 1, 2, and 3
  25094. * }, 1, 2, 3);
  25095. */
  25096. var _defer$1;
  25097. if (hasNextTick) {
  25098. _defer$1 = process.nextTick;
  25099. } else if (hasSetImmediate) {
  25100. _defer$1 = setImmediate;
  25101. } else {
  25102. _defer$1 = fallback;
  25103. }
  25104. var nextTick = wrap(_defer$1);
  25105. var parallel = awaitify((eachfn, tasks, callback) => {
  25106. var results = isArrayLike(tasks) ? [] : {};
  25107. eachfn(tasks, (task, key, taskCb) => {
  25108. wrapAsync(task)((err, ...result) => {
  25109. if (result.length < 2) {
  25110. [result] = result;
  25111. }
  25112. results[key] = result;
  25113. taskCb(err);
  25114. });
  25115. }, err => callback(err, results));
  25116. }, 3);
  25117. /**
  25118. * Run the `tasks` collection of functions in parallel, without waiting until
  25119. * the previous function has completed. If any of the functions pass an error to
  25120. * its callback, the main `callback` is immediately called with the value of the
  25121. * error. Once the `tasks` have completed, the results are passed to the final
  25122. * `callback` as an array.
  25123. *
  25124. * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
  25125. * parallel execution of code. If your tasks do not use any timers or perform
  25126. * any I/O, they will actually be executed in series. Any synchronous setup
  25127. * sections for each task will happen one after the other. JavaScript remains
  25128. * single-threaded.
  25129. *
  25130. * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
  25131. * execution of other tasks when a task fails.
  25132. *
  25133. * It is also possible to use an object instead of an array. Each property will
  25134. * be run as a function and the results will be passed to the final `callback`
  25135. * as an object instead of an array. This can be a more readable way of handling
  25136. * results from {@link async.parallel}.
  25137. *
  25138. * @name parallel
  25139. * @static
  25140. * @memberOf module:ControlFlow
  25141. * @method
  25142. * @category Control Flow
  25143. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
  25144. * [async functions]{@link AsyncFunction} to run.
  25145. * Each async function can complete with any number of optional `result` values.
  25146. * @param {Function} [callback] - An optional callback to run once all the
  25147. * functions have completed successfully. This function gets a results array
  25148. * (or object) containing all the result arguments passed to the task callbacks.
  25149. * Invoked with (err, results).
  25150. * @returns {Promise} a promise, if a callback is not passed
  25151. *
  25152. * @example
  25153. * async.parallel([
  25154. * function(callback) {
  25155. * setTimeout(function() {
  25156. * callback(null, 'one');
  25157. * }, 200);
  25158. * },
  25159. * function(callback) {
  25160. * setTimeout(function() {
  25161. * callback(null, 'two');
  25162. * }, 100);
  25163. * }
  25164. * ],
  25165. * // optional callback
  25166. * function(err, results) {
  25167. * // the results array will equal ['one','two'] even though
  25168. * // the second function had a shorter timeout.
  25169. * });
  25170. *
  25171. * // an example using an object instead of an array
  25172. * async.parallel({
  25173. * one: function(callback) {
  25174. * setTimeout(function() {
  25175. * callback(null, 1);
  25176. * }, 200);
  25177. * },
  25178. * two: function(callback) {
  25179. * setTimeout(function() {
  25180. * callback(null, 2);
  25181. * }, 100);
  25182. * }
  25183. * }, function(err, results) {
  25184. * // results is now equals to: {one: 1, two: 2}
  25185. * });
  25186. */
  25187. function parallel$1(tasks, callback) {
  25188. return parallel(eachOf$1, tasks, callback);
  25189. }
  25190. /**
  25191. * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
  25192. * time.
  25193. *
  25194. * @name parallelLimit
  25195. * @static
  25196. * @memberOf module:ControlFlow
  25197. * @method
  25198. * @see [async.parallel]{@link module:ControlFlow.parallel}
  25199. * @category Control Flow
  25200. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
  25201. * [async functions]{@link AsyncFunction} to run.
  25202. * Each async function can complete with any number of optional `result` values.
  25203. * @param {number} limit - The maximum number of async operations at a time.
  25204. * @param {Function} [callback] - An optional callback to run once all the
  25205. * functions have completed successfully. This function gets a results array
  25206. * (or object) containing all the result arguments passed to the task callbacks.
  25207. * Invoked with (err, results).
  25208. * @returns {Promise} a promise, if a callback is not passed
  25209. */
  25210. function parallelLimit(tasks, limit, callback) {
  25211. return parallel(eachOfLimit(limit), tasks, callback);
  25212. }
  25213. /**
  25214. * A queue of tasks for the worker function to complete.
  25215. * @typedef {Iterable} QueueObject
  25216. * @memberOf module:ControlFlow
  25217. * @property {Function} length - a function returning the number of items
  25218. * waiting to be processed. Invoke with `queue.length()`.
  25219. * @property {boolean} started - a boolean indicating whether or not any
  25220. * items have been pushed and processed by the queue.
  25221. * @property {Function} running - a function returning the number of items
  25222. * currently being processed. Invoke with `queue.running()`.
  25223. * @property {Function} workersList - a function returning the array of items
  25224. * currently being processed. Invoke with `queue.workersList()`.
  25225. * @property {Function} idle - a function returning false if there are items
  25226. * waiting or being processed, or true if not. Invoke with `queue.idle()`.
  25227. * @property {number} concurrency - an integer for determining how many `worker`
  25228. * functions should be run in parallel. This property can be changed after a
  25229. * `queue` is created to alter the concurrency on-the-fly.
  25230. * @property {number} payload - an integer that specifies how many items are
  25231. * passed to the worker function at a time. only applies if this is a
  25232. * [cargo]{@link module:ControlFlow.cargo} object
  25233. * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`
  25234. * once the `worker` has finished processing the task. Instead of a single task,
  25235. * a `tasks` array can be submitted. The respective callback is used for every
  25236. * task in the list. Invoke with `queue.push(task, [callback])`,
  25237. * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.
  25238. * Invoke with `queue.unshift(task, [callback])`.
  25239. * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns
  25240. * a promise that rejects if an error occurs.
  25241. * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns
  25242. * a promise that rejects if an error occurs.
  25243. * @property {Function} remove - remove items from the queue that match a test
  25244. * function. The test function will be passed an object with a `data` property,
  25245. * and a `priority` property, if this is a
  25246. * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
  25247. * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
  25248. * `function ({data, priority}) {}` and returns a Boolean.
  25249. * @property {Function} saturated - a function that sets a callback that is
  25250. * called when the number of running workers hits the `concurrency` limit, and
  25251. * further tasks will be queued. If the callback is omitted, `q.saturated()`
  25252. * returns a promise for the next occurrence.
  25253. * @property {Function} unsaturated - a function that sets a callback that is
  25254. * called when the number of running workers is less than the `concurrency` &
  25255. * `buffer` limits, and further tasks will not be queued. If the callback is
  25256. * omitted, `q.unsaturated()` returns a promise for the next occurrence.
  25257. * @property {number} buffer - A minimum threshold buffer in order to say that
  25258. * the `queue` is `unsaturated`.
  25259. * @property {Function} empty - a function that sets a callback that is called
  25260. * when the last item from the `queue` is given to a `worker`. If the callback
  25261. * is omitted, `q.empty()` returns a promise for the next occurrence.
  25262. * @property {Function} drain - a function that sets a callback that is called
  25263. * when the last item from the `queue` has returned from the `worker`. If the
  25264. * callback is omitted, `q.drain()` returns a promise for the next occurrence.
  25265. * @property {Function} error - a function that sets a callback that is called
  25266. * when a task errors. Has the signature `function(error, task)`. If the
  25267. * callback is omitted, `error()` returns a promise that rejects on the next
  25268. * error.
  25269. * @property {boolean} paused - a boolean for determining whether the queue is
  25270. * in a paused state.
  25271. * @property {Function} pause - a function that pauses the processing of tasks
  25272. * until `resume()` is called. Invoke with `queue.pause()`.
  25273. * @property {Function} resume - a function that resumes the processing of
  25274. * queued tasks when the queue is paused. Invoke with `queue.resume()`.
  25275. * @property {Function} kill - a function that removes the `drain` callback and
  25276. * empties remaining tasks from the queue forcing it to go idle. No more tasks
  25277. * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
  25278. *
  25279. * @example
  25280. * const q = aync.queue(worker, 2)
  25281. * q.push(item1)
  25282. * q.push(item2)
  25283. * q.push(item3)
  25284. * // queues are iterable, spread into an array to inspect
  25285. * const items = [...q] // [item1, item2, item3]
  25286. * // or use for of
  25287. * for (let item of q) {
  25288. * console.log(item)
  25289. * }
  25290. *
  25291. * q.drain(() => {
  25292. * console.log('all done')
  25293. * })
  25294. * // or
  25295. * await q.drain()
  25296. */
  25297. /**
  25298. * Creates a `queue` object with the specified `concurrency`. Tasks added to the
  25299. * `queue` are processed in parallel (up to the `concurrency` limit). If all
  25300. * `worker`s are in progress, the task is queued until one becomes available.
  25301. * Once a `worker` completes a `task`, that `task`'s callback is called.
  25302. *
  25303. * @name queue
  25304. * @static
  25305. * @memberOf module:ControlFlow
  25306. * @method
  25307. * @category Control Flow
  25308. * @param {AsyncFunction} worker - An async function for processing a queued task.
  25309. * If you want to handle errors from an individual task, pass a callback to
  25310. * `q.push()`. Invoked with (task, callback).
  25311. * @param {number} [concurrency=1] - An `integer` for determining how many
  25312. * `worker` functions should be run in parallel. If omitted, the concurrency
  25313. * defaults to `1`. If the concurrency is `0`, an error is thrown.
  25314. * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be
  25315. * attached as certain properties to listen for specific events during the
  25316. * lifecycle of the queue.
  25317. * @example
  25318. *
  25319. * // create a queue object with concurrency 2
  25320. * var q = async.queue(function(task, callback) {
  25321. * console.log('hello ' + task.name);
  25322. * callback();
  25323. * }, 2);
  25324. *
  25325. * // assign a callback
  25326. * q.drain(function() {
  25327. * console.log('all items have been processed');
  25328. * });
  25329. * // or await the end
  25330. * await q.drain()
  25331. *
  25332. * // assign an error callback
  25333. * q.error(function(err, task) {
  25334. * console.error('task experienced an error');
  25335. * });
  25336. *
  25337. * // add some items to the queue
  25338. * q.push({name: 'foo'}, function(err) {
  25339. * console.log('finished processing foo');
  25340. * });
  25341. * // callback is optional
  25342. * q.push({name: 'bar'});
  25343. *
  25344. * // add some items to the queue (batch-wise)
  25345. * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
  25346. * console.log('finished processing item');
  25347. * });
  25348. *
  25349. * // add some items to the front of the queue
  25350. * q.unshift({name: 'bar'}, function (err) {
  25351. * console.log('finished processing bar');
  25352. * });
  25353. */
  25354. function queue$1 (worker, concurrency) {
  25355. var _worker = wrapAsync(worker);
  25356. return queue((items, cb) => {
  25357. _worker(items[0], cb);
  25358. }, concurrency, 1);
  25359. }
  25360. // Binary min-heap implementation used for priority queue.
  25361. // Implementation is stable, i.e. push time is considered for equal priorities
  25362. class Heap {
  25363. constructor() {
  25364. this.heap = [];
  25365. this.pushCount = Number.MIN_SAFE_INTEGER;
  25366. }
  25367. get length() {
  25368. return this.heap.length;
  25369. }
  25370. empty () {
  25371. this.heap = [];
  25372. return this;
  25373. }
  25374. percUp(index) {
  25375. let p;
  25376. while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) {
  25377. let t = this.heap[index];
  25378. this.heap[index] = this.heap[p];
  25379. this.heap[p] = t;
  25380. index = p;
  25381. }
  25382. }
  25383. percDown(index) {
  25384. let l;
  25385. while ((l=leftChi(index)) < this.heap.length) {
  25386. if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) {
  25387. l = l+1;
  25388. }
  25389. if (smaller(this.heap[index], this.heap[l])) {
  25390. break;
  25391. }
  25392. let t = this.heap[index];
  25393. this.heap[index] = this.heap[l];
  25394. this.heap[l] = t;
  25395. index = l;
  25396. }
  25397. }
  25398. push(node) {
  25399. node.pushCount = ++this.pushCount;
  25400. this.heap.push(node);
  25401. this.percUp(this.heap.length-1);
  25402. }
  25403. unshift(node) {
  25404. return this.heap.push(node);
  25405. }
  25406. shift() {
  25407. let [top] = this.heap;
  25408. this.heap[0] = this.heap[this.heap.length-1];
  25409. this.heap.pop();
  25410. this.percDown(0);
  25411. return top;
  25412. }
  25413. toArray() {
  25414. return [...this];
  25415. }
  25416. *[Symbol.iterator] () {
  25417. for (let i = 0; i < this.heap.length; i++) {
  25418. yield this.heap[i].data;
  25419. }
  25420. }
  25421. remove (testFn) {
  25422. let j = 0;
  25423. for (let i = 0; i < this.heap.length; i++) {
  25424. if (!testFn(this.heap[i])) {
  25425. this.heap[j] = this.heap[i];
  25426. j++;
  25427. }
  25428. }
  25429. this.heap.splice(j);
  25430. for (let i = parent(this.heap.length-1); i >= 0; i--) {
  25431. this.percDown(i);
  25432. }
  25433. return this;
  25434. }
  25435. }
  25436. function leftChi(i) {
  25437. return (i<<1)+1;
  25438. }
  25439. function parent(i) {
  25440. return ((i+1)>>1)-1;
  25441. }
  25442. function smaller(x, y) {
  25443. if (x.priority !== y.priority) {
  25444. return x.priority < y.priority;
  25445. }
  25446. else {
  25447. return x.pushCount < y.pushCount;
  25448. }
  25449. }
  25450. /**
  25451. * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
  25452. * completed in ascending priority order.
  25453. *
  25454. * @name priorityQueue
  25455. * @static
  25456. * @memberOf module:ControlFlow
  25457. * @method
  25458. * @see [async.queue]{@link module:ControlFlow.queue}
  25459. * @category Control Flow
  25460. * @param {AsyncFunction} worker - An async function for processing a queued task.
  25461. * If you want to handle errors from an individual task, pass a callback to
  25462. * `q.push()`.
  25463. * Invoked with (task, callback).
  25464. * @param {number} concurrency - An `integer` for determining how many `worker`
  25465. * functions should be run in parallel. If omitted, the concurrency defaults to
  25466. * `1`. If the concurrency is `0`, an error is thrown.
  25467. * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
  25468. * differences between `queue` and `priorityQueue` objects:
  25469. * * `push(task, priority, [callback])` - `priority` should be a number. If an
  25470. * array of `tasks` is given, all tasks will be assigned the same priority.
  25471. * * The `unshift` method was removed.
  25472. */
  25473. function priorityQueue(worker, concurrency) {
  25474. // Start with a normal queue
  25475. var q = queue$1(worker, concurrency);
  25476. q._tasks = new Heap();
  25477. // Override push to accept second parameter representing priority
  25478. q.push = function(data, priority = 0, callback = () => {}) {
  25479. if (typeof callback !== 'function') {
  25480. throw new Error('task callback must be a function');
  25481. }
  25482. q.started = true;
  25483. if (!Array.isArray(data)) {
  25484. data = [data];
  25485. }
  25486. if (data.length === 0 && q.idle()) {
  25487. // call drain immediately if there are no tasks
  25488. return setImmediate$1(() => q.drain());
  25489. }
  25490. for (var i = 0, l = data.length; i < l; i++) {
  25491. var item = {
  25492. data: data[i],
  25493. priority,
  25494. callback
  25495. };
  25496. q._tasks.push(item);
  25497. }
  25498. setImmediate$1(q.process);
  25499. };
  25500. // Remove unshift function
  25501. delete q.unshift;
  25502. return q;
  25503. }
  25504. /**
  25505. * Runs the `tasks` array of functions in parallel, without waiting until the
  25506. * previous function has completed. Once any of the `tasks` complete or pass an
  25507. * error to its callback, the main `callback` is immediately called. It's
  25508. * equivalent to `Promise.race()`.
  25509. *
  25510. * @name race
  25511. * @static
  25512. * @memberOf module:ControlFlow
  25513. * @method
  25514. * @category Control Flow
  25515. * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
  25516. * to run. Each function can complete with an optional `result` value.
  25517. * @param {Function} callback - A callback to run once any of the functions have
  25518. * completed. This function gets an error or result from the first function that
  25519. * completed. Invoked with (err, result).
  25520. * @returns undefined
  25521. * @example
  25522. *
  25523. * async.race([
  25524. * function(callback) {
  25525. * setTimeout(function() {
  25526. * callback(null, 'one');
  25527. * }, 200);
  25528. * },
  25529. * function(callback) {
  25530. * setTimeout(function() {
  25531. * callback(null, 'two');
  25532. * }, 100);
  25533. * }
  25534. * ],
  25535. * // main callback
  25536. * function(err, result) {
  25537. * // the result will be equal to 'two' as it finishes earlier
  25538. * });
  25539. */
  25540. function race(tasks, callback) {
  25541. callback = once(callback);
  25542. if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
  25543. if (!tasks.length) return callback();
  25544. for (var i = 0, l = tasks.length; i < l; i++) {
  25545. wrapAsync(tasks[i])(callback);
  25546. }
  25547. }
  25548. var race$1 = awaitify(race, 2);
  25549. /**
  25550. * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
  25551. *
  25552. * @name reduceRight
  25553. * @static
  25554. * @memberOf module:Collections
  25555. * @method
  25556. * @see [async.reduce]{@link module:Collections.reduce}
  25557. * @alias foldr
  25558. * @category Collection
  25559. * @param {Array} array - A collection to iterate over.
  25560. * @param {*} memo - The initial state of the reduction.
  25561. * @param {AsyncFunction} iteratee - A function applied to each item in the
  25562. * array to produce the next step in the reduction.
  25563. * The `iteratee` should complete with the next state of the reduction.
  25564. * If the iteratee complete with an error, the reduction is stopped and the
  25565. * main `callback` is immediately called with the error.
  25566. * Invoked with (memo, item, callback).
  25567. * @param {Function} [callback] - A callback which is called after all the
  25568. * `iteratee` functions have finished. Result is the reduced value. Invoked with
  25569. * (err, result).
  25570. * @returns {Promise} a promise, if no callback is passed
  25571. */
  25572. function reduceRight (array, memo, iteratee, callback) {
  25573. var reversed = [...array].reverse();
  25574. return reduce$1(reversed, memo, iteratee, callback);
  25575. }
  25576. /**
  25577. * Wraps the async function in another function that always completes with a
  25578. * result object, even when it errors.
  25579. *
  25580. * The result object has either the property `error` or `value`.
  25581. *
  25582. * @name reflect
  25583. * @static
  25584. * @memberOf module:Utils
  25585. * @method
  25586. * @category Util
  25587. * @param {AsyncFunction} fn - The async function you want to wrap
  25588. * @returns {Function} - A function that always passes null to it's callback as
  25589. * the error. The second argument to the callback will be an `object` with
  25590. * either an `error` or a `value` property.
  25591. * @example
  25592. *
  25593. * async.parallel([
  25594. * async.reflect(function(callback) {
  25595. * // do some stuff ...
  25596. * callback(null, 'one');
  25597. * }),
  25598. * async.reflect(function(callback) {
  25599. * // do some more stuff but error ...
  25600. * callback('bad stuff happened');
  25601. * }),
  25602. * async.reflect(function(callback) {
  25603. * // do some more stuff ...
  25604. * callback(null, 'two');
  25605. * })
  25606. * ],
  25607. * // optional callback
  25608. * function(err, results) {
  25609. * // values
  25610. * // results[0].value = 'one'
  25611. * // results[1].error = 'bad stuff happened'
  25612. * // results[2].value = 'two'
  25613. * });
  25614. */
  25615. function reflect(fn) {
  25616. var _fn = wrapAsync(fn);
  25617. return initialParams(function reflectOn(args, reflectCallback) {
  25618. args.push((error, ...cbArgs) => {
  25619. let retVal = {};
  25620. if (error) {
  25621. retVal.error = error;
  25622. }
  25623. if (cbArgs.length > 0){
  25624. var value = cbArgs;
  25625. if (cbArgs.length <= 1) {
  25626. [value] = cbArgs;
  25627. }
  25628. retVal.value = value;
  25629. }
  25630. reflectCallback(null, retVal);
  25631. });
  25632. return _fn.apply(this, args);
  25633. });
  25634. }
  25635. /**
  25636. * A helper function that wraps an array or an object of functions with `reflect`.
  25637. *
  25638. * @name reflectAll
  25639. * @static
  25640. * @memberOf module:Utils
  25641. * @method
  25642. * @see [async.reflect]{@link module:Utils.reflect}
  25643. * @category Util
  25644. * @param {Array|Object|Iterable} tasks - The collection of
  25645. * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
  25646. * @returns {Array} Returns an array of async functions, each wrapped in
  25647. * `async.reflect`
  25648. * @example
  25649. *
  25650. * let tasks = [
  25651. * function(callback) {
  25652. * setTimeout(function() {
  25653. * callback(null, 'one');
  25654. * }, 200);
  25655. * },
  25656. * function(callback) {
  25657. * // do some more stuff but error ...
  25658. * callback(new Error('bad stuff happened'));
  25659. * },
  25660. * function(callback) {
  25661. * setTimeout(function() {
  25662. * callback(null, 'two');
  25663. * }, 100);
  25664. * }
  25665. * ];
  25666. *
  25667. * async.parallel(async.reflectAll(tasks),
  25668. * // optional callback
  25669. * function(err, results) {
  25670. * // values
  25671. * // results[0].value = 'one'
  25672. * // results[1].error = Error('bad stuff happened')
  25673. * // results[2].value = 'two'
  25674. * });
  25675. *
  25676. * // an example using an object instead of an array
  25677. * let tasks = {
  25678. * one: function(callback) {
  25679. * setTimeout(function() {
  25680. * callback(null, 'one');
  25681. * }, 200);
  25682. * },
  25683. * two: function(callback) {
  25684. * callback('two');
  25685. * },
  25686. * three: function(callback) {
  25687. * setTimeout(function() {
  25688. * callback(null, 'three');
  25689. * }, 100);
  25690. * }
  25691. * };
  25692. *
  25693. * async.parallel(async.reflectAll(tasks),
  25694. * // optional callback
  25695. * function(err, results) {
  25696. * // values
  25697. * // results.one.value = 'one'
  25698. * // results.two.error = 'two'
  25699. * // results.three.value = 'three'
  25700. * });
  25701. */
  25702. function reflectAll(tasks) {
  25703. var results;
  25704. if (Array.isArray(tasks)) {
  25705. results = tasks.map(reflect);
  25706. } else {
  25707. results = {};
  25708. Object.keys(tasks).forEach(key => {
  25709. results[key] = reflect.call(this, tasks[key]);
  25710. });
  25711. }
  25712. return results;
  25713. }
  25714. function reject(eachfn, arr, _iteratee, callback) {
  25715. const iteratee = wrapAsync(_iteratee);
  25716. return _filter(eachfn, arr, (value, cb) => {
  25717. iteratee(value, (err, v) => {
  25718. cb(err, !v);
  25719. });
  25720. }, callback);
  25721. }
  25722. /**
  25723. * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
  25724. *
  25725. * @name reject
  25726. * @static
  25727. * @memberOf module:Collections
  25728. * @method
  25729. * @see [async.filter]{@link module:Collections.filter}
  25730. * @category Collection
  25731. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  25732. * @param {Function} iteratee - An async truth test to apply to each item in
  25733. * `coll`.
  25734. * The should complete with a boolean value as its `result`.
  25735. * Invoked with (item, callback).
  25736. * @param {Function} [callback] - A callback which is called after all the
  25737. * `iteratee` functions have finished. Invoked with (err, results).
  25738. * @returns {Promise} a promise, if no callback is passed
  25739. * @example
  25740. *
  25741. * async.reject(['file1','file2','file3'], function(filePath, callback) {
  25742. * fs.access(filePath, function(err) {
  25743. * callback(null, !err)
  25744. * });
  25745. * }, function(err, results) {
  25746. * // results now equals an array of missing files
  25747. * createFiles(results);
  25748. * });
  25749. */
  25750. function reject$1 (coll, iteratee, callback) {
  25751. return reject(eachOf$1, coll, iteratee, callback)
  25752. }
  25753. var reject$2 = awaitify(reject$1, 3);
  25754. /**
  25755. * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
  25756. * time.
  25757. *
  25758. * @name rejectLimit
  25759. * @static
  25760. * @memberOf module:Collections
  25761. * @method
  25762. * @see [async.reject]{@link module:Collections.reject}
  25763. * @category Collection
  25764. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  25765. * @param {number} limit - The maximum number of async operations at a time.
  25766. * @param {Function} iteratee - An async truth test to apply to each item in
  25767. * `coll`.
  25768. * The should complete with a boolean value as its `result`.
  25769. * Invoked with (item, callback).
  25770. * @param {Function} [callback] - A callback which is called after all the
  25771. * `iteratee` functions have finished. Invoked with (err, results).
  25772. * @returns {Promise} a promise, if no callback is passed
  25773. */
  25774. function rejectLimit (coll, limit, iteratee, callback) {
  25775. return reject(eachOfLimit(limit), coll, iteratee, callback)
  25776. }
  25777. var rejectLimit$1 = awaitify(rejectLimit, 4);
  25778. /**
  25779. * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
  25780. *
  25781. * @name rejectSeries
  25782. * @static
  25783. * @memberOf module:Collections
  25784. * @method
  25785. * @see [async.reject]{@link module:Collections.reject}
  25786. * @category Collection
  25787. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  25788. * @param {Function} iteratee - An async truth test to apply to each item in
  25789. * `coll`.
  25790. * The should complete with a boolean value as its `result`.
  25791. * Invoked with (item, callback).
  25792. * @param {Function} [callback] - A callback which is called after all the
  25793. * `iteratee` functions have finished. Invoked with (err, results).
  25794. * @returns {Promise} a promise, if no callback is passed
  25795. */
  25796. function rejectSeries (coll, iteratee, callback) {
  25797. return reject(eachOfSeries$1, coll, iteratee, callback)
  25798. }
  25799. var rejectSeries$1 = awaitify(rejectSeries, 3);
  25800. function constant$1(value) {
  25801. return function () {
  25802. return value;
  25803. }
  25804. }
  25805. /**
  25806. * Attempts to get a successful response from `task` no more than `times` times
  25807. * before returning an error. If the task is successful, the `callback` will be
  25808. * passed the result of the successful task. If all attempts fail, the callback
  25809. * will be passed the error and result (if any) of the final attempt.
  25810. *
  25811. * @name retry
  25812. * @static
  25813. * @memberOf module:ControlFlow
  25814. * @method
  25815. * @category Control Flow
  25816. * @see [async.retryable]{@link module:ControlFlow.retryable}
  25817. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
  25818. * object with `times` and `interval` or a number.
  25819. * * `times` - The number of attempts to make before giving up. The default
  25820. * is `5`.
  25821. * * `interval` - The time to wait between retries, in milliseconds. The
  25822. * default is `0`. The interval may also be specified as a function of the
  25823. * retry count (see example).
  25824. * * `errorFilter` - An optional synchronous function that is invoked on
  25825. * erroneous result. If it returns `true` the retry attempts will continue;
  25826. * if the function returns `false` the retry flow is aborted with the current
  25827. * attempt's error and result being returned to the final callback.
  25828. * Invoked with (err).
  25829. * * If `opts` is a number, the number specifies the number of times to retry,
  25830. * with the default interval of `0`.
  25831. * @param {AsyncFunction} task - An async function to retry.
  25832. * Invoked with (callback).
  25833. * @param {Function} [callback] - An optional callback which is called when the
  25834. * task has succeeded, or after the final failed attempt. It receives the `err`
  25835. * and `result` arguments of the last attempt at completing the `task`. Invoked
  25836. * with (err, results).
  25837. * @returns {Promise} a promise if no callback provided
  25838. *
  25839. * @example
  25840. *
  25841. * // The `retry` function can be used as a stand-alone control flow by passing
  25842. * // a callback, as shown below:
  25843. *
  25844. * // try calling apiMethod 3 times
  25845. * async.retry(3, apiMethod, function(err, result) {
  25846. * // do something with the result
  25847. * });
  25848. *
  25849. * // try calling apiMethod 3 times, waiting 200 ms between each retry
  25850. * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
  25851. * // do something with the result
  25852. * });
  25853. *
  25854. * // try calling apiMethod 10 times with exponential backoff
  25855. * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
  25856. * async.retry({
  25857. * times: 10,
  25858. * interval: function(retryCount) {
  25859. * return 50 * Math.pow(2, retryCount);
  25860. * }
  25861. * }, apiMethod, function(err, result) {
  25862. * // do something with the result
  25863. * });
  25864. *
  25865. * // try calling apiMethod the default 5 times no delay between each retry
  25866. * async.retry(apiMethod, function(err, result) {
  25867. * // do something with the result
  25868. * });
  25869. *
  25870. * // try calling apiMethod only when error condition satisfies, all other
  25871. * // errors will abort the retry control flow and return to final callback
  25872. * async.retry({
  25873. * errorFilter: function(err) {
  25874. * return err.message === 'Temporary error'; // only retry on a specific error
  25875. * }
  25876. * }, apiMethod, function(err, result) {
  25877. * // do something with the result
  25878. * });
  25879. *
  25880. * // to retry individual methods that are not as reliable within other
  25881. * // control flow functions, use the `retryable` wrapper:
  25882. * async.auto({
  25883. * users: api.getUsers.bind(api),
  25884. * payments: async.retryable(3, api.getPayments.bind(api))
  25885. * }, function(err, results) {
  25886. * // do something with the results
  25887. * });
  25888. *
  25889. */
  25890. const DEFAULT_TIMES = 5;
  25891. const DEFAULT_INTERVAL = 0;
  25892. function retry(opts, task, callback) {
  25893. var options = {
  25894. times: DEFAULT_TIMES,
  25895. intervalFunc: constant$1(DEFAULT_INTERVAL)
  25896. };
  25897. if (arguments.length < 3 && typeof opts === 'function') {
  25898. callback = task || promiseCallback();
  25899. task = opts;
  25900. } else {
  25901. parseTimes(options, opts);
  25902. callback = callback || promiseCallback();
  25903. }
  25904. if (typeof task !== 'function') {
  25905. throw new Error("Invalid arguments for async.retry");
  25906. }
  25907. var _task = wrapAsync(task);
  25908. var attempt = 1;
  25909. function retryAttempt() {
  25910. _task((err, ...args) => {
  25911. if (err === false) return
  25912. if (err && attempt++ < options.times &&
  25913. (typeof options.errorFilter != 'function' ||
  25914. options.errorFilter(err))) {
  25915. setTimeout(retryAttempt, options.intervalFunc(attempt - 1));
  25916. } else {
  25917. callback(err, ...args);
  25918. }
  25919. });
  25920. }
  25921. retryAttempt();
  25922. return callback[PROMISE_SYMBOL]
  25923. }
  25924. function parseTimes(acc, t) {
  25925. if (typeof t === 'object') {
  25926. acc.times = +t.times || DEFAULT_TIMES;
  25927. acc.intervalFunc = typeof t.interval === 'function' ?
  25928. t.interval :
  25929. constant$1(+t.interval || DEFAULT_INTERVAL);
  25930. acc.errorFilter = t.errorFilter;
  25931. } else if (typeof t === 'number' || typeof t === 'string') {
  25932. acc.times = +t || DEFAULT_TIMES;
  25933. } else {
  25934. throw new Error("Invalid arguments for async.retry");
  25935. }
  25936. }
  25937. /**
  25938. * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
  25939. * wraps a task and makes it retryable, rather than immediately calling it
  25940. * with retries.
  25941. *
  25942. * @name retryable
  25943. * @static
  25944. * @memberOf module:ControlFlow
  25945. * @method
  25946. * @see [async.retry]{@link module:ControlFlow.retry}
  25947. * @category Control Flow
  25948. * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
  25949. * options, exactly the same as from `retry`, except for a `opts.arity` that
  25950. * is the arity of the `task` function, defaulting to `task.length`
  25951. * @param {AsyncFunction} task - the asynchronous function to wrap.
  25952. * This function will be passed any arguments passed to the returned wrapper.
  25953. * Invoked with (...args, callback).
  25954. * @returns {AsyncFunction} The wrapped function, which when invoked, will
  25955. * retry on an error, based on the parameters specified in `opts`.
  25956. * This function will accept the same parameters as `task`.
  25957. * @example
  25958. *
  25959. * async.auto({
  25960. * dep1: async.retryable(3, getFromFlakyService),
  25961. * process: ["dep1", async.retryable(3, function (results, cb) {
  25962. * maybeProcessData(results.dep1, cb);
  25963. * })]
  25964. * }, callback);
  25965. */
  25966. function retryable (opts, task) {
  25967. if (!task) {
  25968. task = opts;
  25969. opts = null;
  25970. }
  25971. let arity = (opts && opts.arity) || task.length;
  25972. if (isAsync(task)) {
  25973. arity += 1;
  25974. }
  25975. var _task = wrapAsync(task);
  25976. return initialParams((args, callback) => {
  25977. if (args.length < arity - 1 || callback == null) {
  25978. args.push(callback);
  25979. callback = promiseCallback();
  25980. }
  25981. function taskFn(cb) {
  25982. _task(...args, cb);
  25983. }
  25984. if (opts) retry(opts, taskFn, callback);
  25985. else retry(taskFn, callback);
  25986. return callback[PROMISE_SYMBOL]
  25987. });
  25988. }
  25989. /**
  25990. * Run the functions in the `tasks` collection in series, each one running once
  25991. * the previous function has completed. If any functions in the series pass an
  25992. * error to its callback, no more functions are run, and `callback` is
  25993. * immediately called with the value of the error. Otherwise, `callback`
  25994. * receives an array of results when `tasks` have completed.
  25995. *
  25996. * It is also possible to use an object instead of an array. Each property will
  25997. * be run as a function, and the results will be passed to the final `callback`
  25998. * as an object instead of an array. This can be a more readable way of handling
  25999. * results from {@link async.series}.
  26000. *
  26001. * **Note** that while many implementations preserve the order of object
  26002. * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
  26003. * explicitly states that
  26004. *
  26005. * > The mechanics and order of enumerating the properties is not specified.
  26006. *
  26007. * So if you rely on the order in which your series of functions are executed,
  26008. * and want this to work on all platforms, consider using an array.
  26009. *
  26010. * @name series
  26011. * @static
  26012. * @memberOf module:ControlFlow
  26013. * @method
  26014. * @category Control Flow
  26015. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing
  26016. * [async functions]{@link AsyncFunction} to run in series.
  26017. * Each function can complete with any number of optional `result` values.
  26018. * @param {Function} [callback] - An optional callback to run once all the
  26019. * functions have completed. This function gets a results array (or object)
  26020. * containing all the result arguments passed to the `task` callbacks. Invoked
  26021. * with (err, result).
  26022. * @return {Promise} a promise, if no callback is passed
  26023. * @example
  26024. * async.series([
  26025. * function(callback) {
  26026. * // do some stuff ...
  26027. * callback(null, 'one');
  26028. * },
  26029. * function(callback) {
  26030. * // do some more stuff ...
  26031. * callback(null, 'two');
  26032. * }
  26033. * ],
  26034. * // optional callback
  26035. * function(err, results) {
  26036. * // results is now equal to ['one', 'two']
  26037. * });
  26038. *
  26039. * async.series({
  26040. * one: function(callback) {
  26041. * setTimeout(function() {
  26042. * callback(null, 1);
  26043. * }, 200);
  26044. * },
  26045. * two: function(callback){
  26046. * setTimeout(function() {
  26047. * callback(null, 2);
  26048. * }, 100);
  26049. * }
  26050. * }, function(err, results) {
  26051. * // results is now equal to: {one: 1, two: 2}
  26052. * });
  26053. */
  26054. function series(tasks, callback) {
  26055. return parallel(eachOfSeries$1, tasks, callback);
  26056. }
  26057. /**
  26058. * Returns `true` if at least one element in the `coll` satisfies an async test.
  26059. * If any iteratee call returns `true`, the main `callback` is immediately
  26060. * called.
  26061. *
  26062. * @name some
  26063. * @static
  26064. * @memberOf module:Collections
  26065. * @method
  26066. * @alias any
  26067. * @category Collection
  26068. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  26069. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  26070. * in the collections in parallel.
  26071. * The iteratee should complete with a boolean `result` value.
  26072. * Invoked with (item, callback).
  26073. * @param {Function} [callback] - A callback which is called as soon as any
  26074. * iteratee returns `true`, or after all the iteratee functions have finished.
  26075. * Result will be either `true` or `false` depending on the values of the async
  26076. * tests. Invoked with (err, result).
  26077. * @returns {Promise} a promise, if no callback provided
  26078. * @example
  26079. *
  26080. * async.some(['file1','file2','file3'], function(filePath, callback) {
  26081. * fs.access(filePath, function(err) {
  26082. * callback(null, !err)
  26083. * });
  26084. * }, function(err, result) {
  26085. * // if result is true then at least one of the files exists
  26086. * });
  26087. */
  26088. function some(coll, iteratee, callback) {
  26089. return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)
  26090. }
  26091. var some$1 = awaitify(some, 3);
  26092. /**
  26093. * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
  26094. *
  26095. * @name someLimit
  26096. * @static
  26097. * @memberOf module:Collections
  26098. * @method
  26099. * @see [async.some]{@link module:Collections.some}
  26100. * @alias anyLimit
  26101. * @category Collection
  26102. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  26103. * @param {number} limit - The maximum number of async operations at a time.
  26104. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  26105. * in the collections in parallel.
  26106. * The iteratee should complete with a boolean `result` value.
  26107. * Invoked with (item, callback).
  26108. * @param {Function} [callback] - A callback which is called as soon as any
  26109. * iteratee returns `true`, or after all the iteratee functions have finished.
  26110. * Result will be either `true` or `false` depending on the values of the async
  26111. * tests. Invoked with (err, result).
  26112. * @returns {Promise} a promise, if no callback provided
  26113. */
  26114. function someLimit(coll, limit, iteratee, callback) {
  26115. return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback)
  26116. }
  26117. var someLimit$1 = awaitify(someLimit, 4);
  26118. /**
  26119. * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
  26120. *
  26121. * @name someSeries
  26122. * @static
  26123. * @memberOf module:Collections
  26124. * @method
  26125. * @see [async.some]{@link module:Collections.some}
  26126. * @alias anySeries
  26127. * @category Collection
  26128. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  26129. * @param {AsyncFunction} iteratee - An async truth test to apply to each item
  26130. * in the collections in series.
  26131. * The iteratee should complete with a boolean `result` value.
  26132. * Invoked with (item, callback).
  26133. * @param {Function} [callback] - A callback which is called as soon as any
  26134. * iteratee returns `true`, or after all the iteratee functions have finished.
  26135. * Result will be either `true` or `false` depending on the values of the async
  26136. * tests. Invoked with (err, result).
  26137. * @returns {Promise} a promise, if no callback provided
  26138. */
  26139. function someSeries(coll, iteratee, callback) {
  26140. return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)
  26141. }
  26142. var someSeries$1 = awaitify(someSeries, 3);
  26143. /**
  26144. * Sorts a list by the results of running each `coll` value through an async
  26145. * `iteratee`.
  26146. *
  26147. * @name sortBy
  26148. * @static
  26149. * @memberOf module:Collections
  26150. * @method
  26151. * @category Collection
  26152. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  26153. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  26154. * `coll`.
  26155. * The iteratee should complete with a value to use as the sort criteria as
  26156. * its `result`.
  26157. * Invoked with (item, callback).
  26158. * @param {Function} callback - A callback which is called after all the
  26159. * `iteratee` functions have finished, or an error occurs. Results is the items
  26160. * from the original `coll` sorted by the values returned by the `iteratee`
  26161. * calls. Invoked with (err, results).
  26162. * @returns {Promise} a promise, if no callback passed
  26163. * @example
  26164. *
  26165. * async.sortBy(['file1','file2','file3'], function(file, callback) {
  26166. * fs.stat(file, function(err, stats) {
  26167. * callback(err, stats.mtime);
  26168. * });
  26169. * }, function(err, results) {
  26170. * // results is now the original array of files sorted by
  26171. * // modified date
  26172. * });
  26173. *
  26174. * // By modifying the callback parameter the
  26175. * // sorting order can be influenced:
  26176. *
  26177. * // ascending order
  26178. * async.sortBy([1,9,3,5], function(x, callback) {
  26179. * callback(null, x);
  26180. * }, function(err,result) {
  26181. * // result callback
  26182. * });
  26183. *
  26184. * // descending order
  26185. * async.sortBy([1,9,3,5], function(x, callback) {
  26186. * callback(null, x*-1); //<- x*-1 instead of x, turns the order around
  26187. * }, function(err,result) {
  26188. * // result callback
  26189. * });
  26190. */
  26191. function sortBy (coll, iteratee, callback) {
  26192. var _iteratee = wrapAsync(iteratee);
  26193. return map$1(coll, (x, iterCb) => {
  26194. _iteratee(x, (err, criteria) => {
  26195. if (err) return iterCb(err);
  26196. iterCb(err, {value: x, criteria});
  26197. });
  26198. }, (err, results) => {
  26199. if (err) return callback(err);
  26200. callback(null, results.sort(comparator).map(v => v.value));
  26201. });
  26202. function comparator(left, right) {
  26203. var a = left.criteria, b = right.criteria;
  26204. return a < b ? -1 : a > b ? 1 : 0;
  26205. }
  26206. }
  26207. var sortBy$1 = awaitify(sortBy, 3);
  26208. /**
  26209. * Sets a time limit on an asynchronous function. If the function does not call
  26210. * its callback within the specified milliseconds, it will be called with a
  26211. * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
  26212. *
  26213. * @name timeout
  26214. * @static
  26215. * @memberOf module:Utils
  26216. * @method
  26217. * @category Util
  26218. * @param {AsyncFunction} asyncFn - The async function to limit in time.
  26219. * @param {number} milliseconds - The specified time limit.
  26220. * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
  26221. * to timeout Error for more information..
  26222. * @returns {AsyncFunction} Returns a wrapped function that can be used with any
  26223. * of the control flow functions.
  26224. * Invoke this function with the same parameters as you would `asyncFunc`.
  26225. * @example
  26226. *
  26227. * function myFunction(foo, callback) {
  26228. * doAsyncTask(foo, function(err, data) {
  26229. * // handle errors
  26230. * if (err) return callback(err);
  26231. *
  26232. * // do some stuff ...
  26233. *
  26234. * // return processed data
  26235. * return callback(null, data);
  26236. * });
  26237. * }
  26238. *
  26239. * var wrapped = async.timeout(myFunction, 1000);
  26240. *
  26241. * // call `wrapped` as you would `myFunction`
  26242. * wrapped({ bar: 'bar' }, function(err, data) {
  26243. * // if `myFunction` takes < 1000 ms to execute, `err`
  26244. * // and `data` will have their expected values
  26245. *
  26246. * // else `err` will be an Error with the code 'ETIMEDOUT'
  26247. * });
  26248. */
  26249. function timeout(asyncFn, milliseconds, info) {
  26250. var fn = wrapAsync(asyncFn);
  26251. return initialParams((args, callback) => {
  26252. var timedOut = false;
  26253. var timer;
  26254. function timeoutCallback() {
  26255. var name = asyncFn.name || 'anonymous';
  26256. var error = new Error('Callback function "' + name + '" timed out.');
  26257. error.code = 'ETIMEDOUT';
  26258. if (info) {
  26259. error.info = info;
  26260. }
  26261. timedOut = true;
  26262. callback(error);
  26263. }
  26264. args.push((...cbArgs) => {
  26265. if (!timedOut) {
  26266. callback(...cbArgs);
  26267. clearTimeout(timer);
  26268. }
  26269. });
  26270. // setup timer and call original function
  26271. timer = setTimeout(timeoutCallback, milliseconds);
  26272. fn(...args);
  26273. });
  26274. }
  26275. function range(size) {
  26276. var result = Array(size);
  26277. while (size--) {
  26278. result[size] = size;
  26279. }
  26280. return result;
  26281. }
  26282. /**
  26283. * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
  26284. * time.
  26285. *
  26286. * @name timesLimit
  26287. * @static
  26288. * @memberOf module:ControlFlow
  26289. * @method
  26290. * @see [async.times]{@link module:ControlFlow.times}
  26291. * @category Control Flow
  26292. * @param {number} count - The number of times to run the function.
  26293. * @param {number} limit - The maximum number of async operations at a time.
  26294. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  26295. * Invoked with the iteration index and a callback: (n, next).
  26296. * @param {Function} callback - see [async.map]{@link module:Collections.map}.
  26297. * @returns {Promise} a promise, if no callback is provided
  26298. */
  26299. function timesLimit(count, limit, iteratee, callback) {
  26300. var _iteratee = wrapAsync(iteratee);
  26301. return mapLimit$1(range(count), limit, _iteratee, callback);
  26302. }
  26303. /**
  26304. * Calls the `iteratee` function `n` times, and accumulates results in the same
  26305. * manner you would use with [map]{@link module:Collections.map}.
  26306. *
  26307. * @name times
  26308. * @static
  26309. * @memberOf module:ControlFlow
  26310. * @method
  26311. * @see [async.map]{@link module:Collections.map}
  26312. * @category Control Flow
  26313. * @param {number} n - The number of times to run the function.
  26314. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  26315. * Invoked with the iteration index and a callback: (n, next).
  26316. * @param {Function} callback - see {@link module:Collections.map}.
  26317. * @returns {Promise} a promise, if no callback is provided
  26318. * @example
  26319. *
  26320. * // Pretend this is some complicated async factory
  26321. * var createUser = function(id, callback) {
  26322. * callback(null, {
  26323. * id: 'user' + id
  26324. * });
  26325. * };
  26326. *
  26327. * // generate 5 users
  26328. * async.times(5, function(n, next) {
  26329. * createUser(n, function(err, user) {
  26330. * next(err, user);
  26331. * });
  26332. * }, function(err, users) {
  26333. * // we should now have 5 users
  26334. * });
  26335. */
  26336. function times (n, iteratee, callback) {
  26337. return timesLimit(n, Infinity, iteratee, callback)
  26338. }
  26339. /**
  26340. * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
  26341. *
  26342. * @name timesSeries
  26343. * @static
  26344. * @memberOf module:ControlFlow
  26345. * @method
  26346. * @see [async.times]{@link module:ControlFlow.times}
  26347. * @category Control Flow
  26348. * @param {number} n - The number of times to run the function.
  26349. * @param {AsyncFunction} iteratee - The async function to call `n` times.
  26350. * Invoked with the iteration index and a callback: (n, next).
  26351. * @param {Function} callback - see {@link module:Collections.map}.
  26352. * @returns {Promise} a promise, if no callback is provided
  26353. */
  26354. function timesSeries (n, iteratee, callback) {
  26355. return timesLimit(n, 1, iteratee, callback)
  26356. }
  26357. /**
  26358. * A relative of `reduce`. Takes an Object or Array, and iterates over each
  26359. * element in parallel, each step potentially mutating an `accumulator` value.
  26360. * The type of the accumulator defaults to the type of collection passed in.
  26361. *
  26362. * @name transform
  26363. * @static
  26364. * @memberOf module:Collections
  26365. * @method
  26366. * @category Collection
  26367. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  26368. * @param {*} [accumulator] - The initial state of the transform. If omitted,
  26369. * it will default to an empty Object or Array, depending on the type of `coll`
  26370. * @param {AsyncFunction} iteratee - A function applied to each item in the
  26371. * collection that potentially modifies the accumulator.
  26372. * Invoked with (accumulator, item, key, callback).
  26373. * @param {Function} [callback] - A callback which is called after all the
  26374. * `iteratee` functions have finished. Result is the transformed accumulator.
  26375. * Invoked with (err, result).
  26376. * @returns {Promise} a promise, if no callback provided
  26377. * @example
  26378. *
  26379. * async.transform([1,2,3], function(acc, item, index, callback) {
  26380. * // pointless async:
  26381. * process.nextTick(function() {
  26382. * acc[index] = item * 2
  26383. * callback(null)
  26384. * });
  26385. * }, function(err, result) {
  26386. * // result is now equal to [2, 4, 6]
  26387. * });
  26388. *
  26389. * @example
  26390. *
  26391. * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
  26392. * setImmediate(function () {
  26393. * obj[key] = val * 2;
  26394. * callback();
  26395. * })
  26396. * }, function (err, result) {
  26397. * // result is equal to {a: 2, b: 4, c: 6}
  26398. * })
  26399. */
  26400. function transform (coll, accumulator, iteratee, callback) {
  26401. if (arguments.length <= 3 && typeof accumulator === 'function') {
  26402. callback = iteratee;
  26403. iteratee = accumulator;
  26404. accumulator = Array.isArray(coll) ? [] : {};
  26405. }
  26406. callback = once(callback || promiseCallback());
  26407. var _iteratee = wrapAsync(iteratee);
  26408. eachOf$1(coll, (v, k, cb) => {
  26409. _iteratee(accumulator, v, k, cb);
  26410. }, err => callback(err, accumulator));
  26411. return callback[PROMISE_SYMBOL]
  26412. }
  26413. /**
  26414. * It runs each task in series but stops whenever any of the functions were
  26415. * successful. If one of the tasks were successful, the `callback` will be
  26416. * passed the result of the successful task. If all tasks fail, the callback
  26417. * will be passed the error and result (if any) of the final attempt.
  26418. *
  26419. * @name tryEach
  26420. * @static
  26421. * @memberOf module:ControlFlow
  26422. * @method
  26423. * @category Control Flow
  26424. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to
  26425. * run, each function is passed a `callback(err, result)` it must call on
  26426. * completion with an error `err` (which can be `null`) and an optional `result`
  26427. * value.
  26428. * @param {Function} [callback] - An optional callback which is called when one
  26429. * of the tasks has succeeded, or all have failed. It receives the `err` and
  26430. * `result` arguments of the last attempt at completing the `task`. Invoked with
  26431. * (err, results).
  26432. * @returns {Promise} a promise, if no callback is passed
  26433. * @example
  26434. * async.tryEach([
  26435. * function getDataFromFirstWebsite(callback) {
  26436. * // Try getting the data from the first website
  26437. * callback(err, data);
  26438. * },
  26439. * function getDataFromSecondWebsite(callback) {
  26440. * // First website failed,
  26441. * // Try getting the data from the backup website
  26442. * callback(err, data);
  26443. * }
  26444. * ],
  26445. * // optional callback
  26446. * function(err, results) {
  26447. * Now do something with the data.
  26448. * });
  26449. *
  26450. */
  26451. function tryEach(tasks, callback) {
  26452. var error = null;
  26453. var result;
  26454. return eachSeries$1(tasks, (task, taskCb) => {
  26455. wrapAsync(task)((err, ...args) => {
  26456. if (err === false) return taskCb(err);
  26457. if (args.length < 2) {
  26458. [result] = args;
  26459. } else {
  26460. result = args;
  26461. }
  26462. error = err;
  26463. taskCb(err ? null : {});
  26464. });
  26465. }, () => callback(error, result));
  26466. }
  26467. var tryEach$1 = awaitify(tryEach);
  26468. /**
  26469. * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
  26470. * unmemoized form. Handy for testing.
  26471. *
  26472. * @name unmemoize
  26473. * @static
  26474. * @memberOf module:Utils
  26475. * @method
  26476. * @see [async.memoize]{@link module:Utils.memoize}
  26477. * @category Util
  26478. * @param {AsyncFunction} fn - the memoized function
  26479. * @returns {AsyncFunction} a function that calls the original unmemoized function
  26480. */
  26481. function unmemoize(fn) {
  26482. return (...args) => {
  26483. return (fn.unmemoized || fn)(...args);
  26484. };
  26485. }
  26486. /**
  26487. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  26488. * stopped, or an error occurs.
  26489. *
  26490. * @name whilst
  26491. * @static
  26492. * @memberOf module:ControlFlow
  26493. * @method
  26494. * @category Control Flow
  26495. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  26496. * execution of `iteratee`. Invoked with ().
  26497. * @param {AsyncFunction} iteratee - An async function which is called each time
  26498. * `test` passes. Invoked with (callback).
  26499. * @param {Function} [callback] - A callback which is called after the test
  26500. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  26501. * will be passed an error and any arguments passed to the final `iteratee`'s
  26502. * callback. Invoked with (err, [results]);
  26503. * @returns {Promise} a promise, if no callback is passed
  26504. * @example
  26505. *
  26506. * var count = 0;
  26507. * async.whilst(
  26508. * function test(cb) { cb(null, count < 5); },
  26509. * function iter(callback) {
  26510. * count++;
  26511. * setTimeout(function() {
  26512. * callback(null, count);
  26513. * }, 1000);
  26514. * },
  26515. * function (err, n) {
  26516. * // 5 seconds have passed, n = 5
  26517. * }
  26518. * );
  26519. */
  26520. function whilst(test, iteratee, callback) {
  26521. callback = onlyOnce(callback);
  26522. var _fn = wrapAsync(iteratee);
  26523. var _test = wrapAsync(test);
  26524. var results = [];
  26525. function next(err, ...rest) {
  26526. if (err) return callback(err);
  26527. results = rest;
  26528. if (err === false) return;
  26529. _test(check);
  26530. }
  26531. function check(err, truth) {
  26532. if (err) return callback(err);
  26533. if (err === false) return;
  26534. if (!truth) return callback(null, ...results);
  26535. _fn(next);
  26536. }
  26537. return _test(check);
  26538. }
  26539. var whilst$1 = awaitify(whilst, 3);
  26540. /**
  26541. * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
  26542. * stopped, or an error occurs. `callback` will be passed an error and any
  26543. * arguments passed to the final `iteratee`'s callback.
  26544. *
  26545. * The inverse of [whilst]{@link module:ControlFlow.whilst}.
  26546. *
  26547. * @name until
  26548. * @static
  26549. * @memberOf module:ControlFlow
  26550. * @method
  26551. * @see [async.whilst]{@link module:ControlFlow.whilst}
  26552. * @category Control Flow
  26553. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  26554. * execution of `iteratee`. Invoked with (callback).
  26555. * @param {AsyncFunction} iteratee - An async function which is called each time
  26556. * `test` fails. Invoked with (callback).
  26557. * @param {Function} [callback] - A callback which is called after the test
  26558. * function has passed and repeated execution of `iteratee` has stopped. `callback`
  26559. * will be passed an error and any arguments passed to the final `iteratee`'s
  26560. * callback. Invoked with (err, [results]);
  26561. * @returns {Promise} a promise, if a callback is not passed
  26562. *
  26563. * @example
  26564. * const results = []
  26565. * let finished = false
  26566. * async.until(function test(page, cb) {
  26567. * cb(null, finished)
  26568. * }, function iter(next) {
  26569. * fetchPage(url, (err, body) => {
  26570. * if (err) return next(err)
  26571. * results = results.concat(body.objects)
  26572. * finished = !!body.next
  26573. * next(err)
  26574. * })
  26575. * }, function done (err) {
  26576. * // all pages have been fetched
  26577. * })
  26578. */
  26579. function until(test, iteratee, callback) {
  26580. const _test = wrapAsync(test);
  26581. return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback);
  26582. }
  26583. /**
  26584. * Runs the `tasks` array of functions in series, each passing their results to
  26585. * the next in the array. However, if any of the `tasks` pass an error to their
  26586. * own callback, the next function is not executed, and the main `callback` is
  26587. * immediately called with the error.
  26588. *
  26589. * @name waterfall
  26590. * @static
  26591. * @memberOf module:ControlFlow
  26592. * @method
  26593. * @category Control Flow
  26594. * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
  26595. * to run.
  26596. * Each function should complete with any number of `result` values.
  26597. * The `result` values will be passed as arguments, in order, to the next task.
  26598. * @param {Function} [callback] - An optional callback to run once all the
  26599. * functions have completed. This will be passed the results of the last task's
  26600. * callback. Invoked with (err, [results]).
  26601. * @returns undefined
  26602. * @example
  26603. *
  26604. * async.waterfall([
  26605. * function(callback) {
  26606. * callback(null, 'one', 'two');
  26607. * },
  26608. * function(arg1, arg2, callback) {
  26609. * // arg1 now equals 'one' and arg2 now equals 'two'
  26610. * callback(null, 'three');
  26611. * },
  26612. * function(arg1, callback) {
  26613. * // arg1 now equals 'three'
  26614. * callback(null, 'done');
  26615. * }
  26616. * ], function (err, result) {
  26617. * // result now equals 'done'
  26618. * });
  26619. *
  26620. * // Or, with named functions:
  26621. * async.waterfall([
  26622. * myFirstFunction,
  26623. * mySecondFunction,
  26624. * myLastFunction,
  26625. * ], function (err, result) {
  26626. * // result now equals 'done'
  26627. * });
  26628. * function myFirstFunction(callback) {
  26629. * callback(null, 'one', 'two');
  26630. * }
  26631. * function mySecondFunction(arg1, arg2, callback) {
  26632. * // arg1 now equals 'one' and arg2 now equals 'two'
  26633. * callback(null, 'three');
  26634. * }
  26635. * function myLastFunction(arg1, callback) {
  26636. * // arg1 now equals 'three'
  26637. * callback(null, 'done');
  26638. * }
  26639. */
  26640. function waterfall (tasks, callback) {
  26641. callback = once(callback);
  26642. if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
  26643. if (!tasks.length) return callback();
  26644. var taskIndex = 0;
  26645. function nextTask(args) {
  26646. var task = wrapAsync(tasks[taskIndex++]);
  26647. task(...args, onlyOnce(next));
  26648. }
  26649. function next(err, ...args) {
  26650. if (err === false) return
  26651. if (err || taskIndex === tasks.length) {
  26652. return callback(err, ...args);
  26653. }
  26654. nextTask(args);
  26655. }
  26656. nextTask([]);
  26657. }
  26658. var waterfall$1 = awaitify(waterfall);
  26659. /**
  26660. * An "async function" in the context of Async is an asynchronous function with
  26661. * a variable number of parameters, with the final parameter being a callback.
  26662. * (`function (arg1, arg2, ..., callback) {}`)
  26663. * The final callback is of the form `callback(err, results...)`, which must be
  26664. * called once the function is completed. The callback should be called with a
  26665. * Error as its first argument to signal that an error occurred.
  26666. * Otherwise, if no error occurred, it should be called with `null` as the first
  26667. * argument, and any additional `result` arguments that may apply, to signal
  26668. * successful completion.
  26669. * The callback must be called exactly once, ideally on a later tick of the
  26670. * JavaScript event loop.
  26671. *
  26672. * This type of function is also referred to as a "Node-style async function",
  26673. * or a "continuation passing-style function" (CPS). Most of the methods of this
  26674. * library are themselves CPS/Node-style async functions, or functions that
  26675. * return CPS/Node-style async functions.
  26676. *
  26677. * Wherever we accept a Node-style async function, we also directly accept an
  26678. * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
  26679. * In this case, the `async` function will not be passed a final callback
  26680. * argument, and any thrown error will be used as the `err` argument of the
  26681. * implicit callback, and the return value will be used as the `result` value.
  26682. * (i.e. a `rejected` of the returned Promise becomes the `err` callback
  26683. * argument, and a `resolved` value becomes the `result`.)
  26684. *
  26685. * Note, due to JavaScript limitations, we can only detect native `async`
  26686. * functions and not transpilied implementations.
  26687. * Your environment must have `async`/`await` support for this to work.
  26688. * (e.g. Node > v7.6, or a recent version of a modern browser).
  26689. * If you are using `async` functions through a transpiler (e.g. Babel), you
  26690. * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
  26691. * because the `async function` will be compiled to an ordinary function that
  26692. * returns a promise.
  26693. *
  26694. * @typedef {Function} AsyncFunction
  26695. * @static
  26696. */
  26697. var index = {
  26698. apply,
  26699. applyEach: applyEach$1,
  26700. applyEachSeries,
  26701. asyncify,
  26702. auto,
  26703. autoInject,
  26704. cargo,
  26705. cargoQueue: cargo$1,
  26706. compose,
  26707. concat: concat$1,
  26708. concatLimit: concatLimit$1,
  26709. concatSeries: concatSeries$1,
  26710. constant,
  26711. detect: detect$1,
  26712. detectLimit: detectLimit$1,
  26713. detectSeries: detectSeries$1,
  26714. dir,
  26715. doUntil,
  26716. doWhilst: doWhilst$1,
  26717. each,
  26718. eachLimit: eachLimit$2,
  26719. eachOf: eachOf$1,
  26720. eachOfLimit: eachOfLimit$2,
  26721. eachOfSeries: eachOfSeries$1,
  26722. eachSeries: eachSeries$1,
  26723. ensureAsync,
  26724. every: every$1,
  26725. everyLimit: everyLimit$1,
  26726. everySeries: everySeries$1,
  26727. filter: filter$1,
  26728. filterLimit: filterLimit$1,
  26729. filterSeries: filterSeries$1,
  26730. forever: forever$1,
  26731. groupBy,
  26732. groupByLimit: groupByLimit$1,
  26733. groupBySeries,
  26734. log,
  26735. map: map$1,
  26736. mapLimit: mapLimit$1,
  26737. mapSeries: mapSeries$1,
  26738. mapValues,
  26739. mapValuesLimit: mapValuesLimit$1,
  26740. mapValuesSeries,
  26741. memoize,
  26742. nextTick,
  26743. parallel: parallel$1,
  26744. parallelLimit,
  26745. priorityQueue,
  26746. queue: queue$1,
  26747. race: race$1,
  26748. reduce: reduce$1,
  26749. reduceRight,
  26750. reflect,
  26751. reflectAll,
  26752. reject: reject$2,
  26753. rejectLimit: rejectLimit$1,
  26754. rejectSeries: rejectSeries$1,
  26755. retry,
  26756. retryable,
  26757. seq,
  26758. series,
  26759. setImmediate: setImmediate$1,
  26760. some: some$1,
  26761. someLimit: someLimit$1,
  26762. someSeries: someSeries$1,
  26763. sortBy: sortBy$1,
  26764. timeout,
  26765. times,
  26766. timesLimit,
  26767. timesSeries,
  26768. transform,
  26769. tryEach: tryEach$1,
  26770. unmemoize,
  26771. until,
  26772. waterfall: waterfall$1,
  26773. whilst: whilst$1,
  26774. // aliases
  26775. all: every$1,
  26776. allLimit: everyLimit$1,
  26777. allSeries: everySeries$1,
  26778. any: some$1,
  26779. anyLimit: someLimit$1,
  26780. anySeries: someSeries$1,
  26781. find: detect$1,
  26782. findLimit: detectLimit$1,
  26783. findSeries: detectSeries$1,
  26784. flatMap: concat$1,
  26785. flatMapLimit: concatLimit$1,
  26786. flatMapSeries: concatSeries$1,
  26787. forEach: each,
  26788. forEachSeries: eachSeries$1,
  26789. forEachLimit: eachLimit$2,
  26790. forEachOf: eachOf$1,
  26791. forEachOfSeries: eachOfSeries$1,
  26792. forEachOfLimit: eachOfLimit$2,
  26793. inject: reduce$1,
  26794. foldl: reduce$1,
  26795. foldr: reduceRight,
  26796. select: filter$1,
  26797. selectLimit: filterLimit$1,
  26798. selectSeries: filterSeries$1,
  26799. wrapSync: asyncify,
  26800. during: whilst$1,
  26801. doDuring: doWhilst$1
  26802. };
  26803. exports.default = index;
  26804. exports.apply = apply;
  26805. exports.applyEach = applyEach$1;
  26806. exports.applyEachSeries = applyEachSeries;
  26807. exports.asyncify = asyncify;
  26808. exports.auto = auto;
  26809. exports.autoInject = autoInject;
  26810. exports.cargo = cargo;
  26811. exports.cargoQueue = cargo$1;
  26812. exports.compose = compose;
  26813. exports.concat = concat$1;
  26814. exports.concatLimit = concatLimit$1;
  26815. exports.concatSeries = concatSeries$1;
  26816. exports.constant = constant;
  26817. exports.detect = detect$1;
  26818. exports.detectLimit = detectLimit$1;
  26819. exports.detectSeries = detectSeries$1;
  26820. exports.dir = dir;
  26821. exports.doUntil = doUntil;
  26822. exports.doWhilst = doWhilst$1;
  26823. exports.each = each;
  26824. exports.eachLimit = eachLimit$2;
  26825. exports.eachOf = eachOf$1;
  26826. exports.eachOfLimit = eachOfLimit$2;
  26827. exports.eachOfSeries = eachOfSeries$1;
  26828. exports.eachSeries = eachSeries$1;
  26829. exports.ensureAsync = ensureAsync;
  26830. exports.every = every$1;
  26831. exports.everyLimit = everyLimit$1;
  26832. exports.everySeries = everySeries$1;
  26833. exports.filter = filter$1;
  26834. exports.filterLimit = filterLimit$1;
  26835. exports.filterSeries = filterSeries$1;
  26836. exports.forever = forever$1;
  26837. exports.groupBy = groupBy;
  26838. exports.groupByLimit = groupByLimit$1;
  26839. exports.groupBySeries = groupBySeries;
  26840. exports.log = log;
  26841. exports.map = map$1;
  26842. exports.mapLimit = mapLimit$1;
  26843. exports.mapSeries = mapSeries$1;
  26844. exports.mapValues = mapValues;
  26845. exports.mapValuesLimit = mapValuesLimit$1;
  26846. exports.mapValuesSeries = mapValuesSeries;
  26847. exports.memoize = memoize;
  26848. exports.nextTick = nextTick;
  26849. exports.parallel = parallel$1;
  26850. exports.parallelLimit = parallelLimit;
  26851. exports.priorityQueue = priorityQueue;
  26852. exports.queue = queue$1;
  26853. exports.race = race$1;
  26854. exports.reduce = reduce$1;
  26855. exports.reduceRight = reduceRight;
  26856. exports.reflect = reflect;
  26857. exports.reflectAll = reflectAll;
  26858. exports.reject = reject$2;
  26859. exports.rejectLimit = rejectLimit$1;
  26860. exports.rejectSeries = rejectSeries$1;
  26861. exports.retry = retry;
  26862. exports.retryable = retryable;
  26863. exports.seq = seq;
  26864. exports.series = series;
  26865. exports.setImmediate = setImmediate$1;
  26866. exports.some = some$1;
  26867. exports.someLimit = someLimit$1;
  26868. exports.someSeries = someSeries$1;
  26869. exports.sortBy = sortBy$1;
  26870. exports.timeout = timeout;
  26871. exports.times = times;
  26872. exports.timesLimit = timesLimit;
  26873. exports.timesSeries = timesSeries;
  26874. exports.transform = transform;
  26875. exports.tryEach = tryEach$1;
  26876. exports.unmemoize = unmemoize;
  26877. exports.until = until;
  26878. exports.waterfall = waterfall$1;
  26879. exports.whilst = whilst$1;
  26880. exports.all = every$1;
  26881. exports.allLimit = everyLimit$1;
  26882. exports.allSeries = everySeries$1;
  26883. exports.any = some$1;
  26884. exports.anyLimit = someLimit$1;
  26885. exports.anySeries = someSeries$1;
  26886. exports.find = detect$1;
  26887. exports.findLimit = detectLimit$1;
  26888. exports.findSeries = detectSeries$1;
  26889. exports.flatMap = concat$1;
  26890. exports.flatMapLimit = concatLimit$1;
  26891. exports.flatMapSeries = concatSeries$1;
  26892. exports.forEach = each;
  26893. exports.forEachSeries = eachSeries$1;
  26894. exports.forEachLimit = eachLimit$2;
  26895. exports.forEachOf = eachOf$1;
  26896. exports.forEachOfSeries = eachOfSeries$1;
  26897. exports.forEachOfLimit = eachOfLimit$2;
  26898. exports.inject = reduce$1;
  26899. exports.foldl = reduce$1;
  26900. exports.foldr = reduceRight;
  26901. exports.select = filter$1;
  26902. exports.selectLimit = filterLimit$1;
  26903. exports.selectSeries = filterSeries$1;
  26904. exports.wrapSync = asyncify;
  26905. exports.during = whilst$1;
  26906. exports.doDuring = doWhilst$1;
  26907. Object.defineProperty(exports, '__esModule', { value: true });
  26908. })));
  26909. }).call(this)}).call(this,require('_process'),require("timers").setImmediate)
  26910. },{"_process":525,"timers":639}],110:[function(require,module,exports){
  26911. (function (global){(function (){
  26912. 'use strict';
  26913. var filter = require('array-filter');
  26914. module.exports = function availableTypedArrays() {
  26915. return filter([
  26916. 'BigInt64Array',
  26917. 'BigUint64Array',
  26918. 'Float32Array',
  26919. 'Float64Array',
  26920. 'Int16Array',
  26921. 'Int32Array',
  26922. 'Int8Array',
  26923. 'Uint16Array',
  26924. 'Uint32Array',
  26925. 'Uint8Array',
  26926. 'Uint8ClampedArray'
  26927. ], function (typedArray) {
  26928. return typeof global[typedArray] === 'function';
  26929. });
  26930. };
  26931. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26932. },{"array-filter":82}],111:[function(require,module,exports){
  26933. /*!
  26934. * Copyright 2010 LearnBoost <dev@learnboost.com>
  26935. *
  26936. * Licensed under the Apache License, Version 2.0 (the "License");
  26937. * you may not use this file except in compliance with the License.
  26938. * You may obtain a copy of the License at
  26939. *
  26940. * http://www.apache.org/licenses/LICENSE-2.0
  26941. *
  26942. * Unless required by applicable law or agreed to in writing, software
  26943. * distributed under the License is distributed on an "AS IS" BASIS,
  26944. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  26945. * See the License for the specific language governing permissions and
  26946. * limitations under the License.
  26947. */
  26948. /**
  26949. * Module dependencies.
  26950. */
  26951. var crypto = require('crypto')
  26952. , parse = require('url').parse
  26953. ;
  26954. /**
  26955. * Valid keys.
  26956. */
  26957. var keys =
  26958. [ 'acl'
  26959. , 'location'
  26960. , 'logging'
  26961. , 'notification'
  26962. , 'partNumber'
  26963. , 'policy'
  26964. , 'requestPayment'
  26965. , 'torrent'
  26966. , 'uploadId'
  26967. , 'uploads'
  26968. , 'versionId'
  26969. , 'versioning'
  26970. , 'versions'
  26971. , 'website'
  26972. ]
  26973. /**
  26974. * Return an "Authorization" header value with the given `options`
  26975. * in the form of "AWS <key>:<signature>"
  26976. *
  26977. * @param {Object} options
  26978. * @return {String}
  26979. * @api private
  26980. */
  26981. function authorization (options) {
  26982. return 'AWS ' + options.key + ':' + sign(options)
  26983. }
  26984. module.exports = authorization
  26985. module.exports.authorization = authorization
  26986. /**
  26987. * Simple HMAC-SHA1 Wrapper
  26988. *
  26989. * @param {Object} options
  26990. * @return {String}
  26991. * @api private
  26992. */
  26993. function hmacSha1 (options) {
  26994. return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
  26995. }
  26996. module.exports.hmacSha1 = hmacSha1
  26997. /**
  26998. * Create a base64 sha1 HMAC for `options`.
  26999. *
  27000. * @param {Object} options
  27001. * @return {String}
  27002. * @api private
  27003. */
  27004. function sign (options) {
  27005. options.message = stringToSign(options)
  27006. return hmacSha1(options)
  27007. }
  27008. module.exports.sign = sign
  27009. /**
  27010. * Create a base64 sha1 HMAC for `options`.
  27011. *
  27012. * Specifically to be used with S3 presigned URLs
  27013. *
  27014. * @param {Object} options
  27015. * @return {String}
  27016. * @api private
  27017. */
  27018. function signQuery (options) {
  27019. options.message = queryStringToSign(options)
  27020. return hmacSha1(options)
  27021. }
  27022. module.exports.signQuery= signQuery
  27023. /**
  27024. * Return a string for sign() with the given `options`.
  27025. *
  27026. * Spec:
  27027. *
  27028. * <verb>\n
  27029. * <md5>\n
  27030. * <content-type>\n
  27031. * <date>\n
  27032. * [headers\n]
  27033. * <resource>
  27034. *
  27035. * @param {Object} options
  27036. * @return {String}
  27037. * @api private
  27038. */
  27039. function stringToSign (options) {
  27040. var headers = options.amazonHeaders || ''
  27041. if (headers) headers += '\n'
  27042. var r =
  27043. [ options.verb
  27044. , options.md5
  27045. , options.contentType
  27046. , options.date ? options.date.toUTCString() : ''
  27047. , headers + options.resource
  27048. ]
  27049. return r.join('\n')
  27050. }
  27051. module.exports.stringToSign = stringToSign
  27052. /**
  27053. * Return a string for sign() with the given `options`, but is meant exclusively
  27054. * for S3 presigned URLs
  27055. *
  27056. * Spec:
  27057. *
  27058. * <date>\n
  27059. * <resource>
  27060. *
  27061. * @param {Object} options
  27062. * @return {String}
  27063. * @api private
  27064. */
  27065. function queryStringToSign (options){
  27066. return 'GET\n\n\n' + options.date + '\n' + options.resource
  27067. }
  27068. module.exports.queryStringToSign = queryStringToSign
  27069. /**
  27070. * Perform the following:
  27071. *
  27072. * - ignore non-amazon headers
  27073. * - lowercase fields
  27074. * - sort lexicographically
  27075. * - trim whitespace between ":"
  27076. * - join with newline
  27077. *
  27078. * @param {Object} headers
  27079. * @return {String}
  27080. * @api private
  27081. */
  27082. function canonicalizeHeaders (headers) {
  27083. var buf = []
  27084. , fields = Object.keys(headers)
  27085. ;
  27086. for (var i = 0, len = fields.length; i < len; ++i) {
  27087. var field = fields[i]
  27088. , val = headers[field]
  27089. , field = field.toLowerCase()
  27090. ;
  27091. if (0 !== field.indexOf('x-amz')) continue
  27092. buf.push(field + ':' + val)
  27093. }
  27094. return buf.sort().join('\n')
  27095. }
  27096. module.exports.canonicalizeHeaders = canonicalizeHeaders
  27097. /**
  27098. * Perform the following:
  27099. *
  27100. * - ignore non sub-resources
  27101. * - sort lexicographically
  27102. *
  27103. * @param {String} resource
  27104. * @return {String}
  27105. * @api private
  27106. */
  27107. function canonicalizeResource (resource) {
  27108. var url = parse(resource, true)
  27109. , path = url.pathname
  27110. , buf = []
  27111. ;
  27112. Object.keys(url.query).forEach(function(key){
  27113. if (!~keys.indexOf(key)) return
  27114. var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
  27115. buf.push(key + val)
  27116. })
  27117. return path + (buf.length ? '?' + buf.sort().join('&') : '')
  27118. }
  27119. module.exports.canonicalizeResource = canonicalizeResource
  27120. },{"crypto":208,"url":653}],112:[function(require,module,exports){
  27121. (function (process,Buffer){(function (){
  27122. var aws4 = exports,
  27123. url = require('url'),
  27124. querystring = require('querystring'),
  27125. crypto = require('crypto'),
  27126. lru = require('./lru'),
  27127. credentialsCache = lru(1000)
  27128. // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
  27129. function hmac(key, string, encoding) {
  27130. return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
  27131. }
  27132. function hash(string, encoding) {
  27133. return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
  27134. }
  27135. // This function assumes the string has already been percent encoded
  27136. function encodeRfc3986(urlEncodedString) {
  27137. return urlEncodedString.replace(/[!'()*]/g, function(c) {
  27138. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  27139. })
  27140. }
  27141. function encodeRfc3986Full(str) {
  27142. return encodeRfc3986(encodeURIComponent(str))
  27143. }
  27144. // A bit of a combination of:
  27145. // https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59
  27146. // https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199
  27147. // https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34
  27148. var HEADERS_TO_IGNORE = {
  27149. 'authorization': true,
  27150. 'connection': true,
  27151. 'x-amzn-trace-id': true,
  27152. 'user-agent': true,
  27153. 'expect': true,
  27154. 'presigned-expires': true,
  27155. 'range': true,
  27156. }
  27157. // request: { path | body, [host], [method], [headers], [service], [region] }
  27158. // credentials: { accessKeyId, secretAccessKey, [sessionToken] }
  27159. function RequestSigner(request, credentials) {
  27160. if (typeof request === 'string') request = url.parse(request)
  27161. var headers = request.headers = (request.headers || {}),
  27162. hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host)
  27163. this.request = request
  27164. this.credentials = credentials || this.defaultCredentials()
  27165. this.service = request.service || hostParts[0] || ''
  27166. this.region = request.region || hostParts[1] || 'us-east-1'
  27167. // SES uses a different domain from the service name
  27168. if (this.service === 'email') this.service = 'ses'
  27169. if (!request.method && request.body)
  27170. request.method = 'POST'
  27171. if (!headers.Host && !headers.host) {
  27172. headers.Host = request.hostname || request.host || this.createHost()
  27173. // If a port is specified explicitly, use it as is
  27174. if (request.port)
  27175. headers.Host += ':' + request.port
  27176. }
  27177. if (!request.hostname && !request.host)
  27178. request.hostname = headers.Host || headers.host
  27179. this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
  27180. }
  27181. RequestSigner.prototype.matchHost = function(host) {
  27182. var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
  27183. var hostParts = (match || []).slice(1, 3)
  27184. // ES's hostParts are sometimes the other way round, if the value that is expected
  27185. // to be region equals ‘es’ switch them back
  27186. // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
  27187. if (hostParts[1] === 'es')
  27188. hostParts = hostParts.reverse()
  27189. if (hostParts[1] == 's3') {
  27190. hostParts[0] = 's3'
  27191. hostParts[1] = 'us-east-1'
  27192. } else {
  27193. for (var i = 0; i < 2; i++) {
  27194. if (/^s3-/.test(hostParts[i])) {
  27195. hostParts[1] = hostParts[i].slice(3)
  27196. hostParts[0] = 's3'
  27197. break
  27198. }
  27199. }
  27200. }
  27201. return hostParts
  27202. }
  27203. // http://docs.aws.amazon.com/general/latest/gr/rande.html
  27204. RequestSigner.prototype.isSingleRegion = function() {
  27205. // Special case for S3 and SimpleDB in us-east-1
  27206. if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
  27207. return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
  27208. .indexOf(this.service) >= 0
  27209. }
  27210. RequestSigner.prototype.createHost = function() {
  27211. var region = this.isSingleRegion() ? '' : '.' + this.region,
  27212. subdomain = this.service === 'ses' ? 'email' : this.service
  27213. return subdomain + region + '.amazonaws.com'
  27214. }
  27215. RequestSigner.prototype.prepareRequest = function() {
  27216. this.parsePath()
  27217. var request = this.request, headers = request.headers, query
  27218. if (request.signQuery) {
  27219. this.parsedPath.query = query = this.parsedPath.query || {}
  27220. if (this.credentials.sessionToken)
  27221. query['X-Amz-Security-Token'] = this.credentials.sessionToken
  27222. if (this.service === 's3' && !query['X-Amz-Expires'])
  27223. query['X-Amz-Expires'] = 86400
  27224. if (query['X-Amz-Date'])
  27225. this.datetime = query['X-Amz-Date']
  27226. else
  27227. query['X-Amz-Date'] = this.getDateTime()
  27228. query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
  27229. query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
  27230. query['X-Amz-SignedHeaders'] = this.signedHeaders()
  27231. } else {
  27232. if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
  27233. if (request.body && !headers['Content-Type'] && !headers['content-type'])
  27234. headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
  27235. if (request.body && !headers['Content-Length'] && !headers['content-length'])
  27236. headers['Content-Length'] = Buffer.byteLength(request.body)
  27237. if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
  27238. headers['X-Amz-Security-Token'] = this.credentials.sessionToken
  27239. if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
  27240. headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
  27241. if (headers['X-Amz-Date'] || headers['x-amz-date'])
  27242. this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
  27243. else
  27244. headers['X-Amz-Date'] = this.getDateTime()
  27245. }
  27246. delete headers.Authorization
  27247. delete headers.authorization
  27248. }
  27249. }
  27250. RequestSigner.prototype.sign = function() {
  27251. if (!this.parsedPath) this.prepareRequest()
  27252. if (this.request.signQuery) {
  27253. this.parsedPath.query['X-Amz-Signature'] = this.signature()
  27254. } else {
  27255. this.request.headers.Authorization = this.authHeader()
  27256. }
  27257. this.request.path = this.formatPath()
  27258. return this.request
  27259. }
  27260. RequestSigner.prototype.getDateTime = function() {
  27261. if (!this.datetime) {
  27262. var headers = this.request.headers,
  27263. date = new Date(headers.Date || headers.date || new Date)
  27264. this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
  27265. // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
  27266. if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
  27267. }
  27268. return this.datetime
  27269. }
  27270. RequestSigner.prototype.getDate = function() {
  27271. return this.getDateTime().substr(0, 8)
  27272. }
  27273. RequestSigner.prototype.authHeader = function() {
  27274. return [
  27275. 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
  27276. 'SignedHeaders=' + this.signedHeaders(),
  27277. 'Signature=' + this.signature(),
  27278. ].join(', ')
  27279. }
  27280. RequestSigner.prototype.signature = function() {
  27281. var date = this.getDate(),
  27282. cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
  27283. kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
  27284. if (!kCredentials) {
  27285. kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
  27286. kRegion = hmac(kDate, this.region)
  27287. kService = hmac(kRegion, this.service)
  27288. kCredentials = hmac(kService, 'aws4_request')
  27289. credentialsCache.set(cacheKey, kCredentials)
  27290. }
  27291. return hmac(kCredentials, this.stringToSign(), 'hex')
  27292. }
  27293. RequestSigner.prototype.stringToSign = function() {
  27294. return [
  27295. 'AWS4-HMAC-SHA256',
  27296. this.getDateTime(),
  27297. this.credentialString(),
  27298. hash(this.canonicalString(), 'hex'),
  27299. ].join('\n')
  27300. }
  27301. RequestSigner.prototype.canonicalString = function() {
  27302. if (!this.parsedPath) this.prepareRequest()
  27303. var pathStr = this.parsedPath.path,
  27304. query = this.parsedPath.query,
  27305. headers = this.request.headers,
  27306. queryStr = '',
  27307. normalizePath = this.service !== 's3',
  27308. decodePath = this.service === 's3' || this.request.doNotEncodePath,
  27309. decodeSlashesInPath = this.service === 's3',
  27310. firstValOnly = this.service === 's3',
  27311. bodyHash
  27312. if (this.service === 's3' && this.request.signQuery) {
  27313. bodyHash = 'UNSIGNED-PAYLOAD'
  27314. } else if (this.isCodeCommitGit) {
  27315. bodyHash = ''
  27316. } else {
  27317. bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
  27318. hash(this.request.body || '', 'hex')
  27319. }
  27320. if (query) {
  27321. var reducedQuery = Object.keys(query).reduce(function(obj, key) {
  27322. if (!key) return obj
  27323. obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] :
  27324. (firstValOnly ? query[key][0] : query[key])
  27325. return obj
  27326. }, {})
  27327. var encodedQueryPieces = []
  27328. Object.keys(reducedQuery).sort().forEach(function(key) {
  27329. if (!Array.isArray(reducedQuery[key])) {
  27330. encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key]))
  27331. } else {
  27332. reducedQuery[key].map(encodeRfc3986Full).sort()
  27333. .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) })
  27334. }
  27335. })
  27336. queryStr = encodedQueryPieces.join('&')
  27337. }
  27338. if (pathStr !== '/') {
  27339. if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
  27340. pathStr = pathStr.split('/').reduce(function(path, piece) {
  27341. if (normalizePath && piece === '..') {
  27342. path.pop()
  27343. } else if (!normalizePath || piece !== '.') {
  27344. if (decodePath) piece = decodeURIComponent(piece.replace(/\+/g, ' '))
  27345. path.push(encodeRfc3986Full(piece))
  27346. }
  27347. return path
  27348. }, []).join('/')
  27349. if (pathStr[0] !== '/') pathStr = '/' + pathStr
  27350. if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
  27351. }
  27352. return [
  27353. this.request.method || 'GET',
  27354. pathStr,
  27355. queryStr,
  27356. this.canonicalHeaders() + '\n',
  27357. this.signedHeaders(),
  27358. bodyHash,
  27359. ].join('\n')
  27360. }
  27361. RequestSigner.prototype.canonicalHeaders = function() {
  27362. var headers = this.request.headers
  27363. function trimAll(header) {
  27364. return header.toString().trim().replace(/\s+/g, ' ')
  27365. }
  27366. return Object.keys(headers)
  27367. .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null })
  27368. .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
  27369. .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
  27370. .join('\n')
  27371. }
  27372. RequestSigner.prototype.signedHeaders = function() {
  27373. return Object.keys(this.request.headers)
  27374. .map(function(key) { return key.toLowerCase() })
  27375. .filter(function(key) { return HEADERS_TO_IGNORE[key] == null })
  27376. .sort()
  27377. .join(';')
  27378. }
  27379. RequestSigner.prototype.credentialString = function() {
  27380. return [
  27381. this.getDate(),
  27382. this.region,
  27383. this.service,
  27384. 'aws4_request',
  27385. ].join('/')
  27386. }
  27387. RequestSigner.prototype.defaultCredentials = function() {
  27388. var env = process.env
  27389. return {
  27390. accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
  27391. secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
  27392. sessionToken: env.AWS_SESSION_TOKEN,
  27393. }
  27394. }
  27395. RequestSigner.prototype.parsePath = function() {
  27396. var path = this.request.path || '/'
  27397. // S3 doesn't always encode characters > 127 correctly and
  27398. // all services don't encode characters > 255 correctly
  27399. // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
  27400. if (/[^0-9A-Za-z;,/?:@&=+$\-_.!~*'()#%]/.test(path)) {
  27401. path = encodeURI(decodeURI(path))
  27402. }
  27403. var queryIx = path.indexOf('?'),
  27404. query = null
  27405. if (queryIx >= 0) {
  27406. query = querystring.parse(path.slice(queryIx + 1))
  27407. path = path.slice(0, queryIx)
  27408. }
  27409. this.parsedPath = {
  27410. path: path,
  27411. query: query,
  27412. }
  27413. }
  27414. RequestSigner.prototype.formatPath = function() {
  27415. var path = this.parsedPath.path,
  27416. query = this.parsedPath.query
  27417. if (!query) return path
  27418. // Services don't support empty query string keys
  27419. if (query[''] != null) delete query['']
  27420. return path + '?' + encodeRfc3986(querystring.stringify(query))
  27421. }
  27422. aws4.RequestSigner = RequestSigner
  27423. aws4.sign = function(request, credentials) {
  27424. return new RequestSigner(request, credentials).sign()
  27425. }
  27426. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  27427. },{"./lru":113,"_process":525,"buffer":193,"crypto":208,"querystring":543,"url":653}],113:[function(require,module,exports){
  27428. module.exports = function(size) {
  27429. return new LruCache(size)
  27430. }
  27431. function LruCache(size) {
  27432. this.capacity = size | 0
  27433. this.map = Object.create(null)
  27434. this.list = new DoublyLinkedList()
  27435. }
  27436. LruCache.prototype.get = function(key) {
  27437. var node = this.map[key]
  27438. if (node == null) return undefined
  27439. this.used(node)
  27440. return node.val
  27441. }
  27442. LruCache.prototype.set = function(key, val) {
  27443. var node = this.map[key]
  27444. if (node != null) {
  27445. node.val = val
  27446. } else {
  27447. if (!this.capacity) this.prune()
  27448. if (!this.capacity) return false
  27449. node = new DoublyLinkedNode(key, val)
  27450. this.map[key] = node
  27451. this.capacity--
  27452. }
  27453. this.used(node)
  27454. return true
  27455. }
  27456. LruCache.prototype.used = function(node) {
  27457. this.list.moveToFront(node)
  27458. }
  27459. LruCache.prototype.prune = function() {
  27460. var node = this.list.pop()
  27461. if (node != null) {
  27462. delete this.map[node.key]
  27463. this.capacity++
  27464. }
  27465. }
  27466. function DoublyLinkedList() {
  27467. this.firstNode = null
  27468. this.lastNode = null
  27469. }
  27470. DoublyLinkedList.prototype.moveToFront = function(node) {
  27471. if (this.firstNode == node) return
  27472. this.remove(node)
  27473. if (this.firstNode == null) {
  27474. this.firstNode = node
  27475. this.lastNode = node
  27476. node.prev = null
  27477. node.next = null
  27478. } else {
  27479. node.prev = null
  27480. node.next = this.firstNode
  27481. node.next.prev = node
  27482. this.firstNode = node
  27483. }
  27484. }
  27485. DoublyLinkedList.prototype.pop = function() {
  27486. var lastNode = this.lastNode
  27487. if (lastNode != null) {
  27488. this.remove(lastNode)
  27489. }
  27490. return lastNode
  27491. }
  27492. DoublyLinkedList.prototype.remove = function(node) {
  27493. if (this.firstNode == node) {
  27494. this.firstNode = node.next
  27495. } else if (node.prev != null) {
  27496. node.prev.next = node.next
  27497. }
  27498. if (this.lastNode == node) {
  27499. this.lastNode = node.prev
  27500. } else if (node.next != null) {
  27501. node.next.prev = node.prev
  27502. }
  27503. }
  27504. function DoublyLinkedNode(key, val) {
  27505. this.key = key
  27506. this.val = val
  27507. this.prev = null
  27508. this.next = null
  27509. }
  27510. },{}],114:[function(require,module,exports){
  27511. module.exports = require('./lib/axios');
  27512. },{"./lib/axios":116}],115:[function(require,module,exports){
  27513. 'use strict';
  27514. var utils = require('./../utils');
  27515. var settle = require('./../core/settle');
  27516. var buildURL = require('./../helpers/buildURL');
  27517. var buildFullPath = require('../core/buildFullPath');
  27518. var parseHeaders = require('./../helpers/parseHeaders');
  27519. var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
  27520. var createError = require('../core/createError');
  27521. module.exports = function xhrAdapter(config) {
  27522. return new Promise(function dispatchXhrRequest(resolve, reject) {
  27523. var requestData = config.data;
  27524. var requestHeaders = config.headers;
  27525. if (utils.isFormData(requestData)) {
  27526. delete requestHeaders['Content-Type']; // Let the browser set it
  27527. }
  27528. var request = new XMLHttpRequest();
  27529. // HTTP basic authentication
  27530. if (config.auth) {
  27531. var username = config.auth.username || '';
  27532. var password = config.auth.password || '';
  27533. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  27534. }
  27535. var fullPath = buildFullPath(config.baseURL, config.url);
  27536. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
  27537. // Set the request timeout in MS
  27538. request.timeout = config.timeout;
  27539. // Listen for ready state
  27540. request.onreadystatechange = function handleLoad() {
  27541. if (!request || request.readyState !== 4) {
  27542. return;
  27543. }
  27544. // The request errored out and we didn't get a response, this will be
  27545. // handled by onerror instead
  27546. // With one exception: request that using file: protocol, most browsers
  27547. // will return status as 0 even though it's a successful request
  27548. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  27549. return;
  27550. }
  27551. // Prepare the response
  27552. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
  27553. var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
  27554. var response = {
  27555. data: responseData,
  27556. status: request.status,
  27557. statusText: request.statusText,
  27558. headers: responseHeaders,
  27559. config: config,
  27560. request: request
  27561. };
  27562. settle(resolve, reject, response);
  27563. // Clean up request
  27564. request = null;
  27565. };
  27566. // Handle browser request cancellation (as opposed to a manual cancellation)
  27567. request.onabort = function handleAbort() {
  27568. if (!request) {
  27569. return;
  27570. }
  27571. reject(createError('Request aborted', config, 'ECONNABORTED', request));
  27572. // Clean up request
  27573. request = null;
  27574. };
  27575. // Handle low level network errors
  27576. request.onerror = function handleError() {
  27577. // Real errors are hidden from us by the browser
  27578. // onerror should only fire if it's a network error
  27579. reject(createError('Network Error', config, null, request));
  27580. // Clean up request
  27581. request = null;
  27582. };
  27583. // Handle timeout
  27584. request.ontimeout = function handleTimeout() {
  27585. var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
  27586. if (config.timeoutErrorMessage) {
  27587. timeoutErrorMessage = config.timeoutErrorMessage;
  27588. }
  27589. reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
  27590. request));
  27591. // Clean up request
  27592. request = null;
  27593. };
  27594. // Add xsrf header
  27595. // This is only done if running in a standard browser environment.
  27596. // Specifically not if we're in a web worker, or react-native.
  27597. if (utils.isStandardBrowserEnv()) {
  27598. var cookies = require('./../helpers/cookies');
  27599. // Add xsrf header
  27600. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  27601. cookies.read(config.xsrfCookieName) :
  27602. undefined;
  27603. if (xsrfValue) {
  27604. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  27605. }
  27606. }
  27607. // Add headers to the request
  27608. if ('setRequestHeader' in request) {
  27609. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  27610. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  27611. // Remove Content-Type if data is undefined
  27612. delete requestHeaders[key];
  27613. } else {
  27614. // Otherwise add header to the request
  27615. request.setRequestHeader(key, val);
  27616. }
  27617. });
  27618. }
  27619. // Add withCredentials to request if needed
  27620. if (!utils.isUndefined(config.withCredentials)) {
  27621. request.withCredentials = !!config.withCredentials;
  27622. }
  27623. // Add responseType to request if needed
  27624. if (config.responseType) {
  27625. try {
  27626. request.responseType = config.responseType;
  27627. } catch (e) {
  27628. // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
  27629. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
  27630. if (config.responseType !== 'json') {
  27631. throw e;
  27632. }
  27633. }
  27634. }
  27635. // Handle progress if needed
  27636. if (typeof config.onDownloadProgress === 'function') {
  27637. request.addEventListener('progress', config.onDownloadProgress);
  27638. }
  27639. // Not all browsers support upload events
  27640. if (typeof config.onUploadProgress === 'function' && request.upload) {
  27641. request.upload.addEventListener('progress', config.onUploadProgress);
  27642. }
  27643. if (config.cancelToken) {
  27644. // Handle cancellation
  27645. config.cancelToken.promise.then(function onCanceled(cancel) {
  27646. if (!request) {
  27647. return;
  27648. }
  27649. request.abort();
  27650. reject(cancel);
  27651. // Clean up request
  27652. request = null;
  27653. });
  27654. }
  27655. if (requestData === undefined) {
  27656. requestData = null;
  27657. }
  27658. // Send the request
  27659. request.send(requestData);
  27660. });
  27661. };
  27662. },{"../core/buildFullPath":122,"../core/createError":123,"./../core/settle":127,"./../helpers/buildURL":131,"./../helpers/cookies":133,"./../helpers/isURLSameOrigin":135,"./../helpers/parseHeaders":137,"./../utils":139}],116:[function(require,module,exports){
  27663. 'use strict';
  27664. var utils = require('./utils');
  27665. var bind = require('./helpers/bind');
  27666. var Axios = require('./core/Axios');
  27667. var mergeConfig = require('./core/mergeConfig');
  27668. var defaults = require('./defaults');
  27669. /**
  27670. * Create an instance of Axios
  27671. *
  27672. * @param {Object} defaultConfig The default config for the instance
  27673. * @return {Axios} A new instance of Axios
  27674. */
  27675. function createInstance(defaultConfig) {
  27676. var context = new Axios(defaultConfig);
  27677. var instance = bind(Axios.prototype.request, context);
  27678. // Copy axios.prototype to instance
  27679. utils.extend(instance, Axios.prototype, context);
  27680. // Copy context to instance
  27681. utils.extend(instance, context);
  27682. return instance;
  27683. }
  27684. // Create the default instance to be exported
  27685. var axios = createInstance(defaults);
  27686. // Expose Axios class to allow class inheritance
  27687. axios.Axios = Axios;
  27688. // Factory for creating new instances
  27689. axios.create = function create(instanceConfig) {
  27690. return createInstance(mergeConfig(axios.defaults, instanceConfig));
  27691. };
  27692. // Expose Cancel & CancelToken
  27693. axios.Cancel = require('./cancel/Cancel');
  27694. axios.CancelToken = require('./cancel/CancelToken');
  27695. axios.isCancel = require('./cancel/isCancel');
  27696. // Expose all/spread
  27697. axios.all = function all(promises) {
  27698. return Promise.all(promises);
  27699. };
  27700. axios.spread = require('./helpers/spread');
  27701. module.exports = axios;
  27702. // Allow use of default import syntax in TypeScript
  27703. module.exports.default = axios;
  27704. },{"./cancel/Cancel":117,"./cancel/CancelToken":118,"./cancel/isCancel":119,"./core/Axios":120,"./core/mergeConfig":126,"./defaults":129,"./helpers/bind":130,"./helpers/spread":138,"./utils":139}],117:[function(require,module,exports){
  27705. 'use strict';
  27706. /**
  27707. * A `Cancel` is an object that is thrown when an operation is canceled.
  27708. *
  27709. * @class
  27710. * @param {string=} message The message.
  27711. */
  27712. function Cancel(message) {
  27713. this.message = message;
  27714. }
  27715. Cancel.prototype.toString = function toString() {
  27716. return 'Cancel' + (this.message ? ': ' + this.message : '');
  27717. };
  27718. Cancel.prototype.__CANCEL__ = true;
  27719. module.exports = Cancel;
  27720. },{}],118:[function(require,module,exports){
  27721. 'use strict';
  27722. var Cancel = require('./Cancel');
  27723. /**
  27724. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  27725. *
  27726. * @class
  27727. * @param {Function} executor The executor function.
  27728. */
  27729. function CancelToken(executor) {
  27730. if (typeof executor !== 'function') {
  27731. throw new TypeError('executor must be a function.');
  27732. }
  27733. var resolvePromise;
  27734. this.promise = new Promise(function promiseExecutor(resolve) {
  27735. resolvePromise = resolve;
  27736. });
  27737. var token = this;
  27738. executor(function cancel(message) {
  27739. if (token.reason) {
  27740. // Cancellation has already been requested
  27741. return;
  27742. }
  27743. token.reason = new Cancel(message);
  27744. resolvePromise(token.reason);
  27745. });
  27746. }
  27747. /**
  27748. * Throws a `Cancel` if cancellation has been requested.
  27749. */
  27750. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  27751. if (this.reason) {
  27752. throw this.reason;
  27753. }
  27754. };
  27755. /**
  27756. * Returns an object that contains a new `CancelToken` and a function that, when called,
  27757. * cancels the `CancelToken`.
  27758. */
  27759. CancelToken.source = function source() {
  27760. var cancel;
  27761. var token = new CancelToken(function executor(c) {
  27762. cancel = c;
  27763. });
  27764. return {
  27765. token: token,
  27766. cancel: cancel
  27767. };
  27768. };
  27769. module.exports = CancelToken;
  27770. },{"./Cancel":117}],119:[function(require,module,exports){
  27771. 'use strict';
  27772. module.exports = function isCancel(value) {
  27773. return !!(value && value.__CANCEL__);
  27774. };
  27775. },{}],120:[function(require,module,exports){
  27776. 'use strict';
  27777. var utils = require('./../utils');
  27778. var buildURL = require('../helpers/buildURL');
  27779. var InterceptorManager = require('./InterceptorManager');
  27780. var dispatchRequest = require('./dispatchRequest');
  27781. var mergeConfig = require('./mergeConfig');
  27782. /**
  27783. * Create a new instance of Axios
  27784. *
  27785. * @param {Object} instanceConfig The default config for the instance
  27786. */
  27787. function Axios(instanceConfig) {
  27788. this.defaults = instanceConfig;
  27789. this.interceptors = {
  27790. request: new InterceptorManager(),
  27791. response: new InterceptorManager()
  27792. };
  27793. }
  27794. /**
  27795. * Dispatch a request
  27796. *
  27797. * @param {Object} config The config specific for this request (merged with this.defaults)
  27798. */
  27799. Axios.prototype.request = function request(config) {
  27800. /*eslint no-param-reassign:0*/
  27801. // Allow for axios('example/url'[, config]) a la fetch API
  27802. if (typeof config === 'string') {
  27803. config = arguments[1] || {};
  27804. config.url = arguments[0];
  27805. } else {
  27806. config = config || {};
  27807. }
  27808. config = mergeConfig(this.defaults, config);
  27809. // Set config.method
  27810. if (config.method) {
  27811. config.method = config.method.toLowerCase();
  27812. } else if (this.defaults.method) {
  27813. config.method = this.defaults.method.toLowerCase();
  27814. } else {
  27815. config.method = 'get';
  27816. }
  27817. // Hook up interceptors middleware
  27818. var chain = [dispatchRequest, undefined];
  27819. var promise = Promise.resolve(config);
  27820. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  27821. chain.unshift(interceptor.fulfilled, interceptor.rejected);
  27822. });
  27823. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  27824. chain.push(interceptor.fulfilled, interceptor.rejected);
  27825. });
  27826. while (chain.length) {
  27827. promise = promise.then(chain.shift(), chain.shift());
  27828. }
  27829. return promise;
  27830. };
  27831. Axios.prototype.getUri = function getUri(config) {
  27832. config = mergeConfig(this.defaults, config);
  27833. return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
  27834. };
  27835. // Provide aliases for supported request methods
  27836. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  27837. /*eslint func-names:0*/
  27838. Axios.prototype[method] = function(url, config) {
  27839. return this.request(utils.merge(config || {}, {
  27840. method: method,
  27841. url: url
  27842. }));
  27843. };
  27844. });
  27845. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  27846. /*eslint func-names:0*/
  27847. Axios.prototype[method] = function(url, data, config) {
  27848. return this.request(utils.merge(config || {}, {
  27849. method: method,
  27850. url: url,
  27851. data: data
  27852. }));
  27853. };
  27854. });
  27855. module.exports = Axios;
  27856. },{"../helpers/buildURL":131,"./../utils":139,"./InterceptorManager":121,"./dispatchRequest":124,"./mergeConfig":126}],121:[function(require,module,exports){
  27857. 'use strict';
  27858. var utils = require('./../utils');
  27859. function InterceptorManager() {
  27860. this.handlers = [];
  27861. }
  27862. /**
  27863. * Add a new interceptor to the stack
  27864. *
  27865. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  27866. * @param {Function} rejected The function to handle `reject` for a `Promise`
  27867. *
  27868. * @return {Number} An ID used to remove interceptor later
  27869. */
  27870. InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  27871. this.handlers.push({
  27872. fulfilled: fulfilled,
  27873. rejected: rejected
  27874. });
  27875. return this.handlers.length - 1;
  27876. };
  27877. /**
  27878. * Remove an interceptor from the stack
  27879. *
  27880. * @param {Number} id The ID that was returned by `use`
  27881. */
  27882. InterceptorManager.prototype.eject = function eject(id) {
  27883. if (this.handlers[id]) {
  27884. this.handlers[id] = null;
  27885. }
  27886. };
  27887. /**
  27888. * Iterate over all the registered interceptors
  27889. *
  27890. * This method is particularly useful for skipping over any
  27891. * interceptors that may have become `null` calling `eject`.
  27892. *
  27893. * @param {Function} fn The function to call for each interceptor
  27894. */
  27895. InterceptorManager.prototype.forEach = function forEach(fn) {
  27896. utils.forEach(this.handlers, function forEachHandler(h) {
  27897. if (h !== null) {
  27898. fn(h);
  27899. }
  27900. });
  27901. };
  27902. module.exports = InterceptorManager;
  27903. },{"./../utils":139}],122:[function(require,module,exports){
  27904. 'use strict';
  27905. var isAbsoluteURL = require('../helpers/isAbsoluteURL');
  27906. var combineURLs = require('../helpers/combineURLs');
  27907. /**
  27908. * Creates a new URL by combining the baseURL with the requestedURL,
  27909. * only when the requestedURL is not already an absolute URL.
  27910. * If the requestURL is absolute, this function returns the requestedURL untouched.
  27911. *
  27912. * @param {string} baseURL The base URL
  27913. * @param {string} requestedURL Absolute or relative URL to combine
  27914. * @returns {string} The combined full path
  27915. */
  27916. module.exports = function buildFullPath(baseURL, requestedURL) {
  27917. if (baseURL && !isAbsoluteURL(requestedURL)) {
  27918. return combineURLs(baseURL, requestedURL);
  27919. }
  27920. return requestedURL;
  27921. };
  27922. },{"../helpers/combineURLs":132,"../helpers/isAbsoluteURL":134}],123:[function(require,module,exports){
  27923. 'use strict';
  27924. var enhanceError = require('./enhanceError');
  27925. /**
  27926. * Create an Error with the specified message, config, error code, request and response.
  27927. *
  27928. * @param {string} message The error message.
  27929. * @param {Object} config The config.
  27930. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  27931. * @param {Object} [request] The request.
  27932. * @param {Object} [response] The response.
  27933. * @returns {Error} The created error.
  27934. */
  27935. module.exports = function createError(message, config, code, request, response) {
  27936. var error = new Error(message);
  27937. return enhanceError(error, config, code, request, response);
  27938. };
  27939. },{"./enhanceError":125}],124:[function(require,module,exports){
  27940. 'use strict';
  27941. var utils = require('./../utils');
  27942. var transformData = require('./transformData');
  27943. var isCancel = require('../cancel/isCancel');
  27944. var defaults = require('../defaults');
  27945. /**
  27946. * Throws a `Cancel` if cancellation has been requested.
  27947. */
  27948. function throwIfCancellationRequested(config) {
  27949. if (config.cancelToken) {
  27950. config.cancelToken.throwIfRequested();
  27951. }
  27952. }
  27953. /**
  27954. * Dispatch a request to the server using the configured adapter.
  27955. *
  27956. * @param {object} config The config that is to be used for the request
  27957. * @returns {Promise} The Promise to be fulfilled
  27958. */
  27959. module.exports = function dispatchRequest(config) {
  27960. throwIfCancellationRequested(config);
  27961. // Ensure headers exist
  27962. config.headers = config.headers || {};
  27963. // Transform request data
  27964. config.data = transformData(
  27965. config.data,
  27966. config.headers,
  27967. config.transformRequest
  27968. );
  27969. // Flatten headers
  27970. config.headers = utils.merge(
  27971. config.headers.common || {},
  27972. config.headers[config.method] || {},
  27973. config.headers
  27974. );
  27975. utils.forEach(
  27976. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  27977. function cleanHeaderConfig(method) {
  27978. delete config.headers[method];
  27979. }
  27980. );
  27981. var adapter = config.adapter || defaults.adapter;
  27982. return adapter(config).then(function onAdapterResolution(response) {
  27983. throwIfCancellationRequested(config);
  27984. // Transform response data
  27985. response.data = transformData(
  27986. response.data,
  27987. response.headers,
  27988. config.transformResponse
  27989. );
  27990. return response;
  27991. }, function onAdapterRejection(reason) {
  27992. if (!isCancel(reason)) {
  27993. throwIfCancellationRequested(config);
  27994. // Transform response data
  27995. if (reason && reason.response) {
  27996. reason.response.data = transformData(
  27997. reason.response.data,
  27998. reason.response.headers,
  27999. config.transformResponse
  28000. );
  28001. }
  28002. }
  28003. return Promise.reject(reason);
  28004. });
  28005. };
  28006. },{"../cancel/isCancel":119,"../defaults":129,"./../utils":139,"./transformData":128}],125:[function(require,module,exports){
  28007. 'use strict';
  28008. /**
  28009. * Update an Error with the specified config, error code, and response.
  28010. *
  28011. * @param {Error} error The error to update.
  28012. * @param {Object} config The config.
  28013. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  28014. * @param {Object} [request] The request.
  28015. * @param {Object} [response] The response.
  28016. * @returns {Error} The error.
  28017. */
  28018. module.exports = function enhanceError(error, config, code, request, response) {
  28019. error.config = config;
  28020. if (code) {
  28021. error.code = code;
  28022. }
  28023. error.request = request;
  28024. error.response = response;
  28025. error.isAxiosError = true;
  28026. error.toJSON = function() {
  28027. return {
  28028. // Standard
  28029. message: this.message,
  28030. name: this.name,
  28031. // Microsoft
  28032. description: this.description,
  28033. number: this.number,
  28034. // Mozilla
  28035. fileName: this.fileName,
  28036. lineNumber: this.lineNumber,
  28037. columnNumber: this.columnNumber,
  28038. stack: this.stack,
  28039. // Axios
  28040. config: this.config,
  28041. code: this.code
  28042. };
  28043. };
  28044. return error;
  28045. };
  28046. },{}],126:[function(require,module,exports){
  28047. 'use strict';
  28048. var utils = require('../utils');
  28049. /**
  28050. * Config-specific merge-function which creates a new config-object
  28051. * by merging two configuration objects together.
  28052. *
  28053. * @param {Object} config1
  28054. * @param {Object} config2
  28055. * @returns {Object} New object resulting from merging config2 to config1
  28056. */
  28057. module.exports = function mergeConfig(config1, config2) {
  28058. // eslint-disable-next-line no-param-reassign
  28059. config2 = config2 || {};
  28060. var config = {};
  28061. var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
  28062. var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
  28063. var defaultToConfig2Keys = [
  28064. 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
  28065. 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
  28066. 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
  28067. 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
  28068. 'httpsAgent', 'cancelToken', 'socketPath'
  28069. ];
  28070. utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
  28071. if (typeof config2[prop] !== 'undefined') {
  28072. config[prop] = config2[prop];
  28073. }
  28074. });
  28075. utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
  28076. if (utils.isObject(config2[prop])) {
  28077. config[prop] = utils.deepMerge(config1[prop], config2[prop]);
  28078. } else if (typeof config2[prop] !== 'undefined') {
  28079. config[prop] = config2[prop];
  28080. } else if (utils.isObject(config1[prop])) {
  28081. config[prop] = utils.deepMerge(config1[prop]);
  28082. } else if (typeof config1[prop] !== 'undefined') {
  28083. config[prop] = config1[prop];
  28084. }
  28085. });
  28086. utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
  28087. if (typeof config2[prop] !== 'undefined') {
  28088. config[prop] = config2[prop];
  28089. } else if (typeof config1[prop] !== 'undefined') {
  28090. config[prop] = config1[prop];
  28091. }
  28092. });
  28093. var axiosKeys = valueFromConfig2Keys
  28094. .concat(mergeDeepPropertiesKeys)
  28095. .concat(defaultToConfig2Keys);
  28096. var otherKeys = Object
  28097. .keys(config2)
  28098. .filter(function filterAxiosKeys(key) {
  28099. return axiosKeys.indexOf(key) === -1;
  28100. });
  28101. utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
  28102. if (typeof config2[prop] !== 'undefined') {
  28103. config[prop] = config2[prop];
  28104. } else if (typeof config1[prop] !== 'undefined') {
  28105. config[prop] = config1[prop];
  28106. }
  28107. });
  28108. return config;
  28109. };
  28110. },{"../utils":139}],127:[function(require,module,exports){
  28111. 'use strict';
  28112. var createError = require('./createError');
  28113. /**
  28114. * Resolve or reject a Promise based on response status.
  28115. *
  28116. * @param {Function} resolve A function that resolves the promise.
  28117. * @param {Function} reject A function that rejects the promise.
  28118. * @param {object} response The response.
  28119. */
  28120. module.exports = function settle(resolve, reject, response) {
  28121. var validateStatus = response.config.validateStatus;
  28122. if (!validateStatus || validateStatus(response.status)) {
  28123. resolve(response);
  28124. } else {
  28125. reject(createError(
  28126. 'Request failed with status code ' + response.status,
  28127. response.config,
  28128. null,
  28129. response.request,
  28130. response
  28131. ));
  28132. }
  28133. };
  28134. },{"./createError":123}],128:[function(require,module,exports){
  28135. 'use strict';
  28136. var utils = require('./../utils');
  28137. /**
  28138. * Transform the data for a request or a response
  28139. *
  28140. * @param {Object|String} data The data to be transformed
  28141. * @param {Array} headers The headers for the request or response
  28142. * @param {Array|Function} fns A single function or Array of functions
  28143. * @returns {*} The resulting transformed data
  28144. */
  28145. module.exports = function transformData(data, headers, fns) {
  28146. /*eslint no-param-reassign:0*/
  28147. utils.forEach(fns, function transform(fn) {
  28148. data = fn(data, headers);
  28149. });
  28150. return data;
  28151. };
  28152. },{"./../utils":139}],129:[function(require,module,exports){
  28153. (function (process){(function (){
  28154. 'use strict';
  28155. var utils = require('./utils');
  28156. var normalizeHeaderName = require('./helpers/normalizeHeaderName');
  28157. var DEFAULT_CONTENT_TYPE = {
  28158. 'Content-Type': 'application/x-www-form-urlencoded'
  28159. };
  28160. function setContentTypeIfUnset(headers, value) {
  28161. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  28162. headers['Content-Type'] = value;
  28163. }
  28164. }
  28165. function getDefaultAdapter() {
  28166. var adapter;
  28167. if (typeof XMLHttpRequest !== 'undefined') {
  28168. // For browsers use XHR adapter
  28169. adapter = require('./adapters/xhr');
  28170. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  28171. // For node use HTTP adapter
  28172. adapter = require('./adapters/http');
  28173. }
  28174. return adapter;
  28175. }
  28176. var defaults = {
  28177. adapter: getDefaultAdapter(),
  28178. transformRequest: [function transformRequest(data, headers) {
  28179. normalizeHeaderName(headers, 'Accept');
  28180. normalizeHeaderName(headers, 'Content-Type');
  28181. if (utils.isFormData(data) ||
  28182. utils.isArrayBuffer(data) ||
  28183. utils.isBuffer(data) ||
  28184. utils.isStream(data) ||
  28185. utils.isFile(data) ||
  28186. utils.isBlob(data)
  28187. ) {
  28188. return data;
  28189. }
  28190. if (utils.isArrayBufferView(data)) {
  28191. return data.buffer;
  28192. }
  28193. if (utils.isURLSearchParams(data)) {
  28194. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  28195. return data.toString();
  28196. }
  28197. if (utils.isObject(data)) {
  28198. setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
  28199. return JSON.stringify(data);
  28200. }
  28201. return data;
  28202. }],
  28203. transformResponse: [function transformResponse(data) {
  28204. /*eslint no-param-reassign:0*/
  28205. if (typeof data === 'string') {
  28206. try {
  28207. data = JSON.parse(data);
  28208. } catch (e) { /* Ignore */ }
  28209. }
  28210. return data;
  28211. }],
  28212. /**
  28213. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  28214. * timeout is not created.
  28215. */
  28216. timeout: 0,
  28217. xsrfCookieName: 'XSRF-TOKEN',
  28218. xsrfHeaderName: 'X-XSRF-TOKEN',
  28219. maxContentLength: -1,
  28220. validateStatus: function validateStatus(status) {
  28221. return status >= 200 && status < 300;
  28222. }
  28223. };
  28224. defaults.headers = {
  28225. common: {
  28226. 'Accept': 'application/json, text/plain, */*'
  28227. }
  28228. };
  28229. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  28230. defaults.headers[method] = {};
  28231. });
  28232. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  28233. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  28234. });
  28235. module.exports = defaults;
  28236. }).call(this)}).call(this,require('_process'))
  28237. },{"./adapters/http":115,"./adapters/xhr":115,"./helpers/normalizeHeaderName":136,"./utils":139,"_process":525}],130:[function(require,module,exports){
  28238. 'use strict';
  28239. module.exports = function bind(fn, thisArg) {
  28240. return function wrap() {
  28241. var args = new Array(arguments.length);
  28242. for (var i = 0; i < args.length; i++) {
  28243. args[i] = arguments[i];
  28244. }
  28245. return fn.apply(thisArg, args);
  28246. };
  28247. };
  28248. },{}],131:[function(require,module,exports){
  28249. 'use strict';
  28250. var utils = require('./../utils');
  28251. function encode(val) {
  28252. return encodeURIComponent(val).
  28253. replace(/%40/gi, '@').
  28254. replace(/%3A/gi, ':').
  28255. replace(/%24/g, '$').
  28256. replace(/%2C/gi, ',').
  28257. replace(/%20/g, '+').
  28258. replace(/%5B/gi, '[').
  28259. replace(/%5D/gi, ']');
  28260. }
  28261. /**
  28262. * Build a URL by appending params to the end
  28263. *
  28264. * @param {string} url The base of the url (e.g., http://www.google.com)
  28265. * @param {object} [params] The params to be appended
  28266. * @returns {string} The formatted url
  28267. */
  28268. module.exports = function buildURL(url, params, paramsSerializer) {
  28269. /*eslint no-param-reassign:0*/
  28270. if (!params) {
  28271. return url;
  28272. }
  28273. var serializedParams;
  28274. if (paramsSerializer) {
  28275. serializedParams = paramsSerializer(params);
  28276. } else if (utils.isURLSearchParams(params)) {
  28277. serializedParams = params.toString();
  28278. } else {
  28279. var parts = [];
  28280. utils.forEach(params, function serialize(val, key) {
  28281. if (val === null || typeof val === 'undefined') {
  28282. return;
  28283. }
  28284. if (utils.isArray(val)) {
  28285. key = key + '[]';
  28286. } else {
  28287. val = [val];
  28288. }
  28289. utils.forEach(val, function parseValue(v) {
  28290. if (utils.isDate(v)) {
  28291. v = v.toISOString();
  28292. } else if (utils.isObject(v)) {
  28293. v = JSON.stringify(v);
  28294. }
  28295. parts.push(encode(key) + '=' + encode(v));
  28296. });
  28297. });
  28298. serializedParams = parts.join('&');
  28299. }
  28300. if (serializedParams) {
  28301. var hashmarkIndex = url.indexOf('#');
  28302. if (hashmarkIndex !== -1) {
  28303. url = url.slice(0, hashmarkIndex);
  28304. }
  28305. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  28306. }
  28307. return url;
  28308. };
  28309. },{"./../utils":139}],132:[function(require,module,exports){
  28310. 'use strict';
  28311. /**
  28312. * Creates a new URL by combining the specified URLs
  28313. *
  28314. * @param {string} baseURL The base URL
  28315. * @param {string} relativeURL The relative URL
  28316. * @returns {string} The combined URL
  28317. */
  28318. module.exports = function combineURLs(baseURL, relativeURL) {
  28319. return relativeURL
  28320. ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
  28321. : baseURL;
  28322. };
  28323. },{}],133:[function(require,module,exports){
  28324. 'use strict';
  28325. var utils = require('./../utils');
  28326. module.exports = (
  28327. utils.isStandardBrowserEnv() ?
  28328. // Standard browser envs support document.cookie
  28329. (function standardBrowserEnv() {
  28330. return {
  28331. write: function write(name, value, expires, path, domain, secure) {
  28332. var cookie = [];
  28333. cookie.push(name + '=' + encodeURIComponent(value));
  28334. if (utils.isNumber(expires)) {
  28335. cookie.push('expires=' + new Date(expires).toGMTString());
  28336. }
  28337. if (utils.isString(path)) {
  28338. cookie.push('path=' + path);
  28339. }
  28340. if (utils.isString(domain)) {
  28341. cookie.push('domain=' + domain);
  28342. }
  28343. if (secure === true) {
  28344. cookie.push('secure');
  28345. }
  28346. document.cookie = cookie.join('; ');
  28347. },
  28348. read: function read(name) {
  28349. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  28350. return (match ? decodeURIComponent(match[3]) : null);
  28351. },
  28352. remove: function remove(name) {
  28353. this.write(name, '', Date.now() - 86400000);
  28354. }
  28355. };
  28356. })() :
  28357. // Non standard browser env (web workers, react-native) lack needed support.
  28358. (function nonStandardBrowserEnv() {
  28359. return {
  28360. write: function write() {},
  28361. read: function read() { return null; },
  28362. remove: function remove() {}
  28363. };
  28364. })()
  28365. );
  28366. },{"./../utils":139}],134:[function(require,module,exports){
  28367. 'use strict';
  28368. /**
  28369. * Determines whether the specified URL is absolute
  28370. *
  28371. * @param {string} url The URL to test
  28372. * @returns {boolean} True if the specified URL is absolute, otherwise false
  28373. */
  28374. module.exports = function isAbsoluteURL(url) {
  28375. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  28376. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  28377. // by any combination of letters, digits, plus, period, or hyphen.
  28378. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  28379. };
  28380. },{}],135:[function(require,module,exports){
  28381. 'use strict';
  28382. var utils = require('./../utils');
  28383. module.exports = (
  28384. utils.isStandardBrowserEnv() ?
  28385. // Standard browser envs have full support of the APIs needed to test
  28386. // whether the request URL is of the same origin as current location.
  28387. (function standardBrowserEnv() {
  28388. var msie = /(msie|trident)/i.test(navigator.userAgent);
  28389. var urlParsingNode = document.createElement('a');
  28390. var originURL;
  28391. /**
  28392. * Parse a URL to discover it's components
  28393. *
  28394. * @param {String} url The URL to be parsed
  28395. * @returns {Object}
  28396. */
  28397. function resolveURL(url) {
  28398. var href = url;
  28399. if (msie) {
  28400. // IE needs attribute set twice to normalize properties
  28401. urlParsingNode.setAttribute('href', href);
  28402. href = urlParsingNode.href;
  28403. }
  28404. urlParsingNode.setAttribute('href', href);
  28405. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  28406. return {
  28407. href: urlParsingNode.href,
  28408. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  28409. host: urlParsingNode.host,
  28410. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  28411. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  28412. hostname: urlParsingNode.hostname,
  28413. port: urlParsingNode.port,
  28414. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  28415. urlParsingNode.pathname :
  28416. '/' + urlParsingNode.pathname
  28417. };
  28418. }
  28419. originURL = resolveURL(window.location.href);
  28420. /**
  28421. * Determine if a URL shares the same origin as the current location
  28422. *
  28423. * @param {String} requestURL The URL to test
  28424. * @returns {boolean} True if URL shares the same origin, otherwise false
  28425. */
  28426. return function isURLSameOrigin(requestURL) {
  28427. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  28428. return (parsed.protocol === originURL.protocol &&
  28429. parsed.host === originURL.host);
  28430. };
  28431. })() :
  28432. // Non standard browser envs (web workers, react-native) lack needed support.
  28433. (function nonStandardBrowserEnv() {
  28434. return function isURLSameOrigin() {
  28435. return true;
  28436. };
  28437. })()
  28438. );
  28439. },{"./../utils":139}],136:[function(require,module,exports){
  28440. 'use strict';
  28441. var utils = require('../utils');
  28442. module.exports = function normalizeHeaderName(headers, normalizedName) {
  28443. utils.forEach(headers, function processHeader(value, name) {
  28444. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  28445. headers[normalizedName] = value;
  28446. delete headers[name];
  28447. }
  28448. });
  28449. };
  28450. },{"../utils":139}],137:[function(require,module,exports){
  28451. 'use strict';
  28452. var utils = require('./../utils');
  28453. // Headers whose duplicates are ignored by node
  28454. // c.f. https://nodejs.org/api/http.html#http_message_headers
  28455. var ignoreDuplicateOf = [
  28456. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  28457. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  28458. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  28459. 'referer', 'retry-after', 'user-agent'
  28460. ];
  28461. /**
  28462. * Parse headers into an object
  28463. *
  28464. * ```
  28465. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  28466. * Content-Type: application/json
  28467. * Connection: keep-alive
  28468. * Transfer-Encoding: chunked
  28469. * ```
  28470. *
  28471. * @param {String} headers Headers needing to be parsed
  28472. * @returns {Object} Headers parsed into an object
  28473. */
  28474. module.exports = function parseHeaders(headers) {
  28475. var parsed = {};
  28476. var key;
  28477. var val;
  28478. var i;
  28479. if (!headers) { return parsed; }
  28480. utils.forEach(headers.split('\n'), function parser(line) {
  28481. i = line.indexOf(':');
  28482. key = utils.trim(line.substr(0, i)).toLowerCase();
  28483. val = utils.trim(line.substr(i + 1));
  28484. if (key) {
  28485. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  28486. return;
  28487. }
  28488. if (key === 'set-cookie') {
  28489. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  28490. } else {
  28491. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  28492. }
  28493. }
  28494. });
  28495. return parsed;
  28496. };
  28497. },{"./../utils":139}],138:[function(require,module,exports){
  28498. 'use strict';
  28499. /**
  28500. * Syntactic sugar for invoking a function and expanding an array for arguments.
  28501. *
  28502. * Common use case would be to use `Function.prototype.apply`.
  28503. *
  28504. * ```js
  28505. * function f(x, y, z) {}
  28506. * var args = [1, 2, 3];
  28507. * f.apply(null, args);
  28508. * ```
  28509. *
  28510. * With `spread` this example can be re-written.
  28511. *
  28512. * ```js
  28513. * spread(function(x, y, z) {})([1, 2, 3]);
  28514. * ```
  28515. *
  28516. * @param {Function} callback
  28517. * @returns {Function}
  28518. */
  28519. module.exports = function spread(callback) {
  28520. return function wrap(arr) {
  28521. return callback.apply(null, arr);
  28522. };
  28523. };
  28524. },{}],139:[function(require,module,exports){
  28525. 'use strict';
  28526. var bind = require('./helpers/bind');
  28527. /*global toString:true*/
  28528. // utils is a library of generic helper functions non-specific to axios
  28529. var toString = Object.prototype.toString;
  28530. /**
  28531. * Determine if a value is an Array
  28532. *
  28533. * @param {Object} val The value to test
  28534. * @returns {boolean} True if value is an Array, otherwise false
  28535. */
  28536. function isArray(val) {
  28537. return toString.call(val) === '[object Array]';
  28538. }
  28539. /**
  28540. * Determine if a value is undefined
  28541. *
  28542. * @param {Object} val The value to test
  28543. * @returns {boolean} True if the value is undefined, otherwise false
  28544. */
  28545. function isUndefined(val) {
  28546. return typeof val === 'undefined';
  28547. }
  28548. /**
  28549. * Determine if a value is a Buffer
  28550. *
  28551. * @param {Object} val The value to test
  28552. * @returns {boolean} True if value is a Buffer, otherwise false
  28553. */
  28554. function isBuffer(val) {
  28555. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
  28556. && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  28557. }
  28558. /**
  28559. * Determine if a value is an ArrayBuffer
  28560. *
  28561. * @param {Object} val The value to test
  28562. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  28563. */
  28564. function isArrayBuffer(val) {
  28565. return toString.call(val) === '[object ArrayBuffer]';
  28566. }
  28567. /**
  28568. * Determine if a value is a FormData
  28569. *
  28570. * @param {Object} val The value to test
  28571. * @returns {boolean} True if value is an FormData, otherwise false
  28572. */
  28573. function isFormData(val) {
  28574. return (typeof FormData !== 'undefined') && (val instanceof FormData);
  28575. }
  28576. /**
  28577. * Determine if a value is a view on an ArrayBuffer
  28578. *
  28579. * @param {Object} val The value to test
  28580. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  28581. */
  28582. function isArrayBufferView(val) {
  28583. var result;
  28584. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  28585. result = ArrayBuffer.isView(val);
  28586. } else {
  28587. result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
  28588. }
  28589. return result;
  28590. }
  28591. /**
  28592. * Determine if a value is a String
  28593. *
  28594. * @param {Object} val The value to test
  28595. * @returns {boolean} True if value is a String, otherwise false
  28596. */
  28597. function isString(val) {
  28598. return typeof val === 'string';
  28599. }
  28600. /**
  28601. * Determine if a value is a Number
  28602. *
  28603. * @param {Object} val The value to test
  28604. * @returns {boolean} True if value is a Number, otherwise false
  28605. */
  28606. function isNumber(val) {
  28607. return typeof val === 'number';
  28608. }
  28609. /**
  28610. * Determine if a value is an Object
  28611. *
  28612. * @param {Object} val The value to test
  28613. * @returns {boolean} True if value is an Object, otherwise false
  28614. */
  28615. function isObject(val) {
  28616. return val !== null && typeof val === 'object';
  28617. }
  28618. /**
  28619. * Determine if a value is a Date
  28620. *
  28621. * @param {Object} val The value to test
  28622. * @returns {boolean} True if value is a Date, otherwise false
  28623. */
  28624. function isDate(val) {
  28625. return toString.call(val) === '[object Date]';
  28626. }
  28627. /**
  28628. * Determine if a value is a File
  28629. *
  28630. * @param {Object} val The value to test
  28631. * @returns {boolean} True if value is a File, otherwise false
  28632. */
  28633. function isFile(val) {
  28634. return toString.call(val) === '[object File]';
  28635. }
  28636. /**
  28637. * Determine if a value is a Blob
  28638. *
  28639. * @param {Object} val The value to test
  28640. * @returns {boolean} True if value is a Blob, otherwise false
  28641. */
  28642. function isBlob(val) {
  28643. return toString.call(val) === '[object Blob]';
  28644. }
  28645. /**
  28646. * Determine if a value is a Function
  28647. *
  28648. * @param {Object} val The value to test
  28649. * @returns {boolean} True if value is a Function, otherwise false
  28650. */
  28651. function isFunction(val) {
  28652. return toString.call(val) === '[object Function]';
  28653. }
  28654. /**
  28655. * Determine if a value is a Stream
  28656. *
  28657. * @param {Object} val The value to test
  28658. * @returns {boolean} True if value is a Stream, otherwise false
  28659. */
  28660. function isStream(val) {
  28661. return isObject(val) && isFunction(val.pipe);
  28662. }
  28663. /**
  28664. * Determine if a value is a URLSearchParams object
  28665. *
  28666. * @param {Object} val The value to test
  28667. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  28668. */
  28669. function isURLSearchParams(val) {
  28670. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  28671. }
  28672. /**
  28673. * Trim excess whitespace off the beginning and end of a string
  28674. *
  28675. * @param {String} str The String to trim
  28676. * @returns {String} The String freed of excess whitespace
  28677. */
  28678. function trim(str) {
  28679. return str.replace(/^\s*/, '').replace(/\s*$/, '');
  28680. }
  28681. /**
  28682. * Determine if we're running in a standard browser environment
  28683. *
  28684. * This allows axios to run in a web worker, and react-native.
  28685. * Both environments support XMLHttpRequest, but not fully standard globals.
  28686. *
  28687. * web workers:
  28688. * typeof window -> undefined
  28689. * typeof document -> undefined
  28690. *
  28691. * react-native:
  28692. * navigator.product -> 'ReactNative'
  28693. * nativescript
  28694. * navigator.product -> 'NativeScript' or 'NS'
  28695. */
  28696. function isStandardBrowserEnv() {
  28697. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  28698. navigator.product === 'NativeScript' ||
  28699. navigator.product === 'NS')) {
  28700. return false;
  28701. }
  28702. return (
  28703. typeof window !== 'undefined' &&
  28704. typeof document !== 'undefined'
  28705. );
  28706. }
  28707. /**
  28708. * Iterate over an Array or an Object invoking a function for each item.
  28709. *
  28710. * If `obj` is an Array callback will be called passing
  28711. * the value, index, and complete array for each item.
  28712. *
  28713. * If 'obj' is an Object callback will be called passing
  28714. * the value, key, and complete object for each property.
  28715. *
  28716. * @param {Object|Array} obj The object to iterate
  28717. * @param {Function} fn The callback to invoke for each item
  28718. */
  28719. function forEach(obj, fn) {
  28720. // Don't bother if no value provided
  28721. if (obj === null || typeof obj === 'undefined') {
  28722. return;
  28723. }
  28724. // Force an array if not already something iterable
  28725. if (typeof obj !== 'object') {
  28726. /*eslint no-param-reassign:0*/
  28727. obj = [obj];
  28728. }
  28729. if (isArray(obj)) {
  28730. // Iterate over array values
  28731. for (var i = 0, l = obj.length; i < l; i++) {
  28732. fn.call(null, obj[i], i, obj);
  28733. }
  28734. } else {
  28735. // Iterate over object keys
  28736. for (var key in obj) {
  28737. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  28738. fn.call(null, obj[key], key, obj);
  28739. }
  28740. }
  28741. }
  28742. }
  28743. /**
  28744. * Accepts varargs expecting each argument to be an object, then
  28745. * immutably merges the properties of each object and returns result.
  28746. *
  28747. * When multiple objects contain the same key the later object in
  28748. * the arguments list will take precedence.
  28749. *
  28750. * Example:
  28751. *
  28752. * ```js
  28753. * var result = merge({foo: 123}, {foo: 456});
  28754. * console.log(result.foo); // outputs 456
  28755. * ```
  28756. *
  28757. * @param {Object} obj1 Object to merge
  28758. * @returns {Object} Result of all merge properties
  28759. */
  28760. function merge(/* obj1, obj2, obj3, ... */) {
  28761. var result = {};
  28762. function assignValue(val, key) {
  28763. if (typeof result[key] === 'object' && typeof val === 'object') {
  28764. result[key] = merge(result[key], val);
  28765. } else {
  28766. result[key] = val;
  28767. }
  28768. }
  28769. for (var i = 0, l = arguments.length; i < l; i++) {
  28770. forEach(arguments[i], assignValue);
  28771. }
  28772. return result;
  28773. }
  28774. /**
  28775. * Function equal to merge with the difference being that no reference
  28776. * to original objects is kept.
  28777. *
  28778. * @see merge
  28779. * @param {Object} obj1 Object to merge
  28780. * @returns {Object} Result of all merge properties
  28781. */
  28782. function deepMerge(/* obj1, obj2, obj3, ... */) {
  28783. var result = {};
  28784. function assignValue(val, key) {
  28785. if (typeof result[key] === 'object' && typeof val === 'object') {
  28786. result[key] = deepMerge(result[key], val);
  28787. } else if (typeof val === 'object') {
  28788. result[key] = deepMerge({}, val);
  28789. } else {
  28790. result[key] = val;
  28791. }
  28792. }
  28793. for (var i = 0, l = arguments.length; i < l; i++) {
  28794. forEach(arguments[i], assignValue);
  28795. }
  28796. return result;
  28797. }
  28798. /**
  28799. * Extends object a by mutably adding to it the properties of object b.
  28800. *
  28801. * @param {Object} a The object to be extended
  28802. * @param {Object} b The object to copy properties from
  28803. * @param {Object} thisArg The object to bind function to
  28804. * @return {Object} The resulting value of object a
  28805. */
  28806. function extend(a, b, thisArg) {
  28807. forEach(b, function assignValue(val, key) {
  28808. if (thisArg && typeof val === 'function') {
  28809. a[key] = bind(val, thisArg);
  28810. } else {
  28811. a[key] = val;
  28812. }
  28813. });
  28814. return a;
  28815. }
  28816. module.exports = {
  28817. isArray: isArray,
  28818. isArrayBuffer: isArrayBuffer,
  28819. isBuffer: isBuffer,
  28820. isFormData: isFormData,
  28821. isArrayBufferView: isArrayBufferView,
  28822. isString: isString,
  28823. isNumber: isNumber,
  28824. isObject: isObject,
  28825. isUndefined: isUndefined,
  28826. isDate: isDate,
  28827. isFile: isFile,
  28828. isBlob: isBlob,
  28829. isFunction: isFunction,
  28830. isStream: isStream,
  28831. isURLSearchParams: isURLSearchParams,
  28832. isStandardBrowserEnv: isStandardBrowserEnv,
  28833. forEach: forEach,
  28834. merge: merge,
  28835. deepMerge: deepMerge,
  28836. extend: extend,
  28837. trim: trim
  28838. };
  28839. },{"./helpers/bind":130}],140:[function(require,module,exports){
  28840. 'use strict'
  28841. exports.byteLength = byteLength
  28842. exports.toByteArray = toByteArray
  28843. exports.fromByteArray = fromByteArray
  28844. var lookup = []
  28845. var revLookup = []
  28846. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  28847. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  28848. for (var i = 0, len = code.length; i < len; ++i) {
  28849. lookup[i] = code[i]
  28850. revLookup[code.charCodeAt(i)] = i
  28851. }
  28852. // Support decoding URL-safe base64 strings, as Node.js does.
  28853. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  28854. revLookup['-'.charCodeAt(0)] = 62
  28855. revLookup['_'.charCodeAt(0)] = 63
  28856. function getLens (b64) {
  28857. var len = b64.length
  28858. if (len % 4 > 0) {
  28859. throw new Error('Invalid string. Length must be a multiple of 4')
  28860. }
  28861. // Trim off extra bytes after placeholder bytes are found
  28862. // See: https://github.com/beatgammit/base64-js/issues/42
  28863. var validLen = b64.indexOf('=')
  28864. if (validLen === -1) validLen = len
  28865. var placeHoldersLen = validLen === len
  28866. ? 0
  28867. : 4 - (validLen % 4)
  28868. return [validLen, placeHoldersLen]
  28869. }
  28870. // base64 is 4/3 + up to two characters of the original data
  28871. function byteLength (b64) {
  28872. var lens = getLens(b64)
  28873. var validLen = lens[0]
  28874. var placeHoldersLen = lens[1]
  28875. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  28876. }
  28877. function _byteLength (b64, validLen, placeHoldersLen) {
  28878. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  28879. }
  28880. function toByteArray (b64) {
  28881. var tmp
  28882. var lens = getLens(b64)
  28883. var validLen = lens[0]
  28884. var placeHoldersLen = lens[1]
  28885. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  28886. var curByte = 0
  28887. // if there are placeholders, only get up to the last complete 4 chars
  28888. var len = placeHoldersLen > 0
  28889. ? validLen - 4
  28890. : validLen
  28891. var i
  28892. for (i = 0; i < len; i += 4) {
  28893. tmp =
  28894. (revLookup[b64.charCodeAt(i)] << 18) |
  28895. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  28896. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  28897. revLookup[b64.charCodeAt(i + 3)]
  28898. arr[curByte++] = (tmp >> 16) & 0xFF
  28899. arr[curByte++] = (tmp >> 8) & 0xFF
  28900. arr[curByte++] = tmp & 0xFF
  28901. }
  28902. if (placeHoldersLen === 2) {
  28903. tmp =
  28904. (revLookup[b64.charCodeAt(i)] << 2) |
  28905. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  28906. arr[curByte++] = tmp & 0xFF
  28907. }
  28908. if (placeHoldersLen === 1) {
  28909. tmp =
  28910. (revLookup[b64.charCodeAt(i)] << 10) |
  28911. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  28912. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  28913. arr[curByte++] = (tmp >> 8) & 0xFF
  28914. arr[curByte++] = tmp & 0xFF
  28915. }
  28916. return arr
  28917. }
  28918. function tripletToBase64 (num) {
  28919. return lookup[num >> 18 & 0x3F] +
  28920. lookup[num >> 12 & 0x3F] +
  28921. lookup[num >> 6 & 0x3F] +
  28922. lookup[num & 0x3F]
  28923. }
  28924. function encodeChunk (uint8, start, end) {
  28925. var tmp
  28926. var output = []
  28927. for (var i = start; i < end; i += 3) {
  28928. tmp =
  28929. ((uint8[i] << 16) & 0xFF0000) +
  28930. ((uint8[i + 1] << 8) & 0xFF00) +
  28931. (uint8[i + 2] & 0xFF)
  28932. output.push(tripletToBase64(tmp))
  28933. }
  28934. return output.join('')
  28935. }
  28936. function fromByteArray (uint8) {
  28937. var tmp
  28938. var len = uint8.length
  28939. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  28940. var parts = []
  28941. var maxChunkLength = 16383 // must be multiple of 3
  28942. // go through the array every three bytes, we'll deal with trailing stuff later
  28943. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  28944. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  28945. }
  28946. // pad the end with zeros, but make sure to not forget the extra bytes
  28947. if (extraBytes === 1) {
  28948. tmp = uint8[len - 1]
  28949. parts.push(
  28950. lookup[tmp >> 2] +
  28951. lookup[(tmp << 4) & 0x3F] +
  28952. '=='
  28953. )
  28954. } else if (extraBytes === 2) {
  28955. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  28956. parts.push(
  28957. lookup[tmp >> 10] +
  28958. lookup[(tmp >> 4) & 0x3F] +
  28959. lookup[(tmp << 2) & 0x3F] +
  28960. '='
  28961. )
  28962. }
  28963. return parts.join('')
  28964. }
  28965. },{}],141:[function(require,module,exports){
  28966. 'use strict';
  28967. var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;
  28968. /*
  28969. * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a
  28970. * result, it retains the original copyright and license. The two files are
  28971. * under slightly different (but compatible) licenses, and are here combined in
  28972. * one file.
  28973. *
  28974. * Credit for the actual porting work goes to:
  28975. * Devi Mandiri <me@devi.web.id>
  28976. */
  28977. /*
  28978. * The Blowfish portions are under the following license:
  28979. *
  28980. * Blowfish block cipher for OpenBSD
  28981. * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
  28982. * All rights reserved.
  28983. *
  28984. * Implementation advice by David Mazieres <dm@lcs.mit.edu>.
  28985. *
  28986. * Redistribution and use in source and binary forms, with or without
  28987. * modification, are permitted provided that the following conditions
  28988. * are met:
  28989. * 1. Redistributions of source code must retain the above copyright
  28990. * notice, this list of conditions and the following disclaimer.
  28991. * 2. Redistributions in binary form must reproduce the above copyright
  28992. * notice, this list of conditions and the following disclaimer in the
  28993. * documentation and/or other materials provided with the distribution.
  28994. * 3. The name of the author may not be used to endorse or promote products
  28995. * derived from this software without specific prior written permission.
  28996. *
  28997. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  28998. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  28999. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  29000. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  29001. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  29002. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29003. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29004. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29005. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  29006. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29007. */
  29008. /*
  29009. * The bcrypt_pbkdf portions are under the following license:
  29010. *
  29011. * Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
  29012. *
  29013. * Permission to use, copy, modify, and distribute this software for any
  29014. * purpose with or without fee is hereby granted, provided that the above
  29015. * copyright notice and this permission notice appear in all copies.
  29016. *
  29017. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  29018. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  29019. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  29020. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  29021. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  29022. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  29023. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  29024. */
  29025. /*
  29026. * Performance improvements (Javascript-specific):
  29027. *
  29028. * Copyright 2016, Joyent Inc
  29029. * Author: Alex Wilson <alex.wilson@joyent.com>
  29030. *
  29031. * Permission to use, copy, modify, and distribute this software for any
  29032. * purpose with or without fee is hereby granted, provided that the above
  29033. * copyright notice and this permission notice appear in all copies.
  29034. *
  29035. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  29036. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  29037. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  29038. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  29039. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  29040. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  29041. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  29042. */
  29043. // Ported from OpenBSD bcrypt_pbkdf.c v1.9
  29044. var BLF_J = 0;
  29045. var Blowfish = function() {
  29046. this.S = [
  29047. new Uint32Array([
  29048. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  29049. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  29050. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  29051. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  29052. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  29053. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  29054. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  29055. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  29056. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  29057. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  29058. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  29059. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  29060. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  29061. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  29062. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  29063. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  29064. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  29065. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  29066. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  29067. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  29068. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  29069. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  29070. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  29071. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  29072. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  29073. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  29074. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  29075. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  29076. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  29077. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  29078. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  29079. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  29080. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  29081. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  29082. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  29083. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  29084. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  29085. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  29086. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  29087. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  29088. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  29089. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  29090. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  29091. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  29092. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  29093. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  29094. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  29095. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  29096. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  29097. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  29098. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  29099. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  29100. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  29101. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  29102. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  29103. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  29104. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  29105. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  29106. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  29107. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  29108. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  29109. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  29110. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  29111. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),
  29112. new Uint32Array([
  29113. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  29114. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  29115. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  29116. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  29117. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  29118. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  29119. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  29120. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  29121. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  29122. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  29123. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  29124. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  29125. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  29126. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  29127. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  29128. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  29129. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  29130. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  29131. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  29132. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  29133. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  29134. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  29135. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  29136. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  29137. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  29138. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  29139. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  29140. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  29141. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  29142. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  29143. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  29144. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  29145. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  29146. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  29147. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  29148. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  29149. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  29150. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  29151. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  29152. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  29153. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  29154. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  29155. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  29156. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  29157. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  29158. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  29159. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  29160. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  29161. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  29162. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  29163. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  29164. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  29165. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  29166. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  29167. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  29168. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  29169. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  29170. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  29171. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  29172. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  29173. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  29174. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  29175. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  29176. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),
  29177. new Uint32Array([
  29178. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  29179. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  29180. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  29181. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  29182. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  29183. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  29184. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  29185. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  29186. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  29187. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  29188. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  29189. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  29190. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  29191. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  29192. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  29193. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  29194. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  29195. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  29196. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  29197. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  29198. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  29199. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  29200. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  29201. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  29202. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  29203. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  29204. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  29205. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  29206. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  29207. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  29208. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  29209. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  29210. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  29211. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  29212. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  29213. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  29214. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  29215. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  29216. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  29217. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  29218. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  29219. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  29220. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  29221. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  29222. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  29223. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  29224. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  29225. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  29226. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  29227. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  29228. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  29229. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  29230. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  29231. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  29232. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  29233. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  29234. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  29235. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  29236. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  29237. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  29238. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  29239. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  29240. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  29241. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),
  29242. new Uint32Array([
  29243. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  29244. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  29245. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  29246. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  29247. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  29248. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  29249. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  29250. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  29251. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  29252. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  29253. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  29254. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  29255. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  29256. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  29257. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  29258. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  29259. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  29260. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  29261. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  29262. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  29263. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  29264. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  29265. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  29266. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  29267. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  29268. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  29269. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  29270. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  29271. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  29272. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  29273. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  29274. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  29275. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  29276. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  29277. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  29278. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  29279. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  29280. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  29281. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  29282. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  29283. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  29284. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  29285. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  29286. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  29287. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  29288. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  29289. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  29290. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  29291. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  29292. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  29293. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  29294. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  29295. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  29296. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  29297. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  29298. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  29299. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  29300. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  29301. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  29302. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  29303. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  29304. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  29305. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  29306. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])
  29307. ];
  29308. this.P = new Uint32Array([
  29309. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  29310. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  29311. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  29312. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  29313. 0x9216d5d9, 0x8979fb1b]);
  29314. };
  29315. function F(S, x8, i) {
  29316. return (((S[0][x8[i+3]] +
  29317. S[1][x8[i+2]]) ^
  29318. S[2][x8[i+1]]) +
  29319. S[3][x8[i]]);
  29320. };
  29321. Blowfish.prototype.encipher = function(x, x8) {
  29322. if (x8 === undefined) {
  29323. x8 = new Uint8Array(x.buffer);
  29324. if (x.byteOffset !== 0)
  29325. x8 = x8.subarray(x.byteOffset);
  29326. }
  29327. x[0] ^= this.P[0];
  29328. for (var i = 1; i < 16; i += 2) {
  29329. x[1] ^= F(this.S, x8, 0) ^ this.P[i];
  29330. x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];
  29331. }
  29332. var t = x[0];
  29333. x[0] = x[1] ^ this.P[17];
  29334. x[1] = t;
  29335. };
  29336. Blowfish.prototype.decipher = function(x) {
  29337. var x8 = new Uint8Array(x.buffer);
  29338. if (x.byteOffset !== 0)
  29339. x8 = x8.subarray(x.byteOffset);
  29340. x[0] ^= this.P[17];
  29341. for (var i = 16; i > 0; i -= 2) {
  29342. x[1] ^= F(this.S, x8, 0) ^ this.P[i];
  29343. x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];
  29344. }
  29345. var t = x[0];
  29346. x[0] = x[1] ^ this.P[0];
  29347. x[1] = t;
  29348. };
  29349. function stream2word(data, databytes){
  29350. var i, temp = 0;
  29351. for (i = 0; i < 4; i++, BLF_J++) {
  29352. if (BLF_J >= databytes) BLF_J = 0;
  29353. temp = (temp << 8) | data[BLF_J];
  29354. }
  29355. return temp;
  29356. };
  29357. Blowfish.prototype.expand0state = function(key, keybytes) {
  29358. var d = new Uint32Array(2), i, k;
  29359. var d8 = new Uint8Array(d.buffer);
  29360. for (i = 0, BLF_J = 0; i < 18; i++) {
  29361. this.P[i] ^= stream2word(key, keybytes);
  29362. }
  29363. BLF_J = 0;
  29364. for (i = 0; i < 18; i += 2) {
  29365. this.encipher(d, d8);
  29366. this.P[i] = d[0];
  29367. this.P[i+1] = d[1];
  29368. }
  29369. for (i = 0; i < 4; i++) {
  29370. for (k = 0; k < 256; k += 2) {
  29371. this.encipher(d, d8);
  29372. this.S[i][k] = d[0];
  29373. this.S[i][k+1] = d[1];
  29374. }
  29375. }
  29376. };
  29377. Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) {
  29378. var d = new Uint32Array(2), i, k;
  29379. for (i = 0, BLF_J = 0; i < 18; i++) {
  29380. this.P[i] ^= stream2word(key, keybytes);
  29381. }
  29382. for (i = 0, BLF_J = 0; i < 18; i += 2) {
  29383. d[0] ^= stream2word(data, databytes);
  29384. d[1] ^= stream2word(data, databytes);
  29385. this.encipher(d);
  29386. this.P[i] = d[0];
  29387. this.P[i+1] = d[1];
  29388. }
  29389. for (i = 0; i < 4; i++) {
  29390. for (k = 0; k < 256; k += 2) {
  29391. d[0] ^= stream2word(data, databytes);
  29392. d[1] ^= stream2word(data, databytes);
  29393. this.encipher(d);
  29394. this.S[i][k] = d[0];
  29395. this.S[i][k+1] = d[1];
  29396. }
  29397. }
  29398. BLF_J = 0;
  29399. };
  29400. Blowfish.prototype.enc = function(data, blocks) {
  29401. for (var i = 0; i < blocks; i++) {
  29402. this.encipher(data.subarray(i*2));
  29403. }
  29404. };
  29405. Blowfish.prototype.dec = function(data, blocks) {
  29406. for (var i = 0; i < blocks; i++) {
  29407. this.decipher(data.subarray(i*2));
  29408. }
  29409. };
  29410. var BCRYPT_BLOCKS = 8,
  29411. BCRYPT_HASHSIZE = 32;
  29412. function bcrypt_hash(sha2pass, sha2salt, out) {
  29413. var state = new Blowfish(),
  29414. cdata = new Uint32Array(BCRYPT_BLOCKS), i,
  29415. ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,
  29416. 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,
  29417. 105,116,101]); //"OxychromaticBlowfishSwatDynamite"
  29418. state.expandstate(sha2salt, 64, sha2pass, 64);
  29419. for (i = 0; i < 64; i++) {
  29420. state.expand0state(sha2salt, 64);
  29421. state.expand0state(sha2pass, 64);
  29422. }
  29423. for (i = 0; i < BCRYPT_BLOCKS; i++)
  29424. cdata[i] = stream2word(ciphertext, ciphertext.byteLength);
  29425. for (i = 0; i < 64; i++)
  29426. state.enc(cdata, cdata.byteLength / 8);
  29427. for (i = 0; i < BCRYPT_BLOCKS; i++) {
  29428. out[4*i+3] = cdata[i] >>> 24;
  29429. out[4*i+2] = cdata[i] >>> 16;
  29430. out[4*i+1] = cdata[i] >>> 8;
  29431. out[4*i+0] = cdata[i];
  29432. }
  29433. };
  29434. function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {
  29435. var sha2pass = new Uint8Array(64),
  29436. sha2salt = new Uint8Array(64),
  29437. out = new Uint8Array(BCRYPT_HASHSIZE),
  29438. tmpout = new Uint8Array(BCRYPT_HASHSIZE),
  29439. countsalt = new Uint8Array(saltlen+4),
  29440. i, j, amt, stride, dest, count,
  29441. origkeylen = keylen;
  29442. if (rounds < 1)
  29443. return -1;
  29444. if (passlen === 0 || saltlen === 0 || keylen === 0 ||
  29445. keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))
  29446. return -1;
  29447. stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);
  29448. amt = Math.floor((keylen + stride - 1) / stride);
  29449. for (i = 0; i < saltlen; i++)
  29450. countsalt[i] = salt[i];
  29451. crypto_hash_sha512(sha2pass, pass, passlen);
  29452. for (count = 1; keylen > 0; count++) {
  29453. countsalt[saltlen+0] = count >>> 24;
  29454. countsalt[saltlen+1] = count >>> 16;
  29455. countsalt[saltlen+2] = count >>> 8;
  29456. countsalt[saltlen+3] = count;
  29457. crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);
  29458. bcrypt_hash(sha2pass, sha2salt, tmpout);
  29459. for (i = out.byteLength; i--;)
  29460. out[i] = tmpout[i];
  29461. for (i = 1; i < rounds; i++) {
  29462. crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);
  29463. bcrypt_hash(sha2pass, sha2salt, tmpout);
  29464. for (j = 0; j < out.byteLength; j++)
  29465. out[j] ^= tmpout[j];
  29466. }
  29467. amt = Math.min(amt, keylen);
  29468. for (i = 0; i < amt; i++) {
  29469. dest = i * stride + (count - 1);
  29470. if (dest >= origkeylen)
  29471. break;
  29472. key[dest] = out[i];
  29473. }
  29474. keylen -= i;
  29475. }
  29476. return 0;
  29477. };
  29478. module.exports = {
  29479. BLOCKS: BCRYPT_BLOCKS,
  29480. HASHSIZE: BCRYPT_HASHSIZE,
  29481. hash: bcrypt_hash,
  29482. pbkdf: bcrypt_pbkdf
  29483. };
  29484. },{"tweetnacl":650}],142:[function(require,module,exports){
  29485. (function (module, exports) {
  29486. 'use strict';
  29487. // Utils
  29488. function assert (val, msg) {
  29489. if (!val) throw new Error(msg || 'Assertion failed');
  29490. }
  29491. // Could use `inherits` module, but don't want to move from single file
  29492. // architecture yet.
  29493. function inherits (ctor, superCtor) {
  29494. ctor.super_ = superCtor;
  29495. var TempCtor = function () {};
  29496. TempCtor.prototype = superCtor.prototype;
  29497. ctor.prototype = new TempCtor();
  29498. ctor.prototype.constructor = ctor;
  29499. }
  29500. // BN
  29501. function BN (number, base, endian) {
  29502. if (BN.isBN(number)) {
  29503. return number;
  29504. }
  29505. this.negative = 0;
  29506. this.words = null;
  29507. this.length = 0;
  29508. // Reduction context
  29509. this.red = null;
  29510. if (number !== null) {
  29511. if (base === 'le' || base === 'be') {
  29512. endian = base;
  29513. base = 10;
  29514. }
  29515. this._init(number || 0, base || 10, endian || 'be');
  29516. }
  29517. }
  29518. if (typeof module === 'object') {
  29519. module.exports = BN;
  29520. } else {
  29521. exports.BN = BN;
  29522. }
  29523. BN.BN = BN;
  29524. BN.wordSize = 26;
  29525. var Buffer;
  29526. try {
  29527. Buffer = require('buffer').Buffer;
  29528. } catch (e) {
  29529. }
  29530. BN.isBN = function isBN (num) {
  29531. if (num instanceof BN) {
  29532. return true;
  29533. }
  29534. return num !== null && typeof num === 'object' &&
  29535. num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  29536. };
  29537. BN.max = function max (left, right) {
  29538. if (left.cmp(right) > 0) return left;
  29539. return right;
  29540. };
  29541. BN.min = function min (left, right) {
  29542. if (left.cmp(right) < 0) return left;
  29543. return right;
  29544. };
  29545. BN.prototype._init = function init (number, base, endian) {
  29546. if (typeof number === 'number') {
  29547. return this._initNumber(number, base, endian);
  29548. }
  29549. if (typeof number === 'object') {
  29550. return this._initArray(number, base, endian);
  29551. }
  29552. if (base === 'hex') {
  29553. base = 16;
  29554. }
  29555. assert(base === (base | 0) && base >= 2 && base <= 36);
  29556. number = number.toString().replace(/\s+/g, '');
  29557. var start = 0;
  29558. if (number[0] === '-') {
  29559. start++;
  29560. }
  29561. if (base === 16) {
  29562. this._parseHex(number, start);
  29563. } else {
  29564. this._parseBase(number, base, start);
  29565. }
  29566. if (number[0] === '-') {
  29567. this.negative = 1;
  29568. }
  29569. this._strip();
  29570. if (endian !== 'le') return;
  29571. this._initArray(this.toArray(), base, endian);
  29572. };
  29573. BN.prototype._initNumber = function _initNumber (number, base, endian) {
  29574. if (number < 0) {
  29575. this.negative = 1;
  29576. number = -number;
  29577. }
  29578. if (number < 0x4000000) {
  29579. this.words = [number & 0x3ffffff];
  29580. this.length = 1;
  29581. } else if (number < 0x10000000000000) {
  29582. this.words = [
  29583. number & 0x3ffffff,
  29584. (number / 0x4000000) & 0x3ffffff
  29585. ];
  29586. this.length = 2;
  29587. } else {
  29588. assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
  29589. this.words = [
  29590. number & 0x3ffffff,
  29591. (number / 0x4000000) & 0x3ffffff,
  29592. 1
  29593. ];
  29594. this.length = 3;
  29595. }
  29596. if (endian !== 'le') return;
  29597. // Reverse the bytes
  29598. this._initArray(this.toArray(), base, endian);
  29599. };
  29600. BN.prototype._initArray = function _initArray (number, base, endian) {
  29601. // Perhaps a Uint8Array
  29602. assert(typeof number.length === 'number');
  29603. if (number.length <= 0) {
  29604. this.words = [0];
  29605. this.length = 1;
  29606. return this;
  29607. }
  29608. this.length = Math.ceil(number.length / 3);
  29609. this.words = new Array(this.length);
  29610. for (var i = 0; i < this.length; i++) {
  29611. this.words[i] = 0;
  29612. }
  29613. var j, w;
  29614. var off = 0;
  29615. if (endian === 'be') {
  29616. for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
  29617. w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
  29618. this.words[j] |= (w << off) & 0x3ffffff;
  29619. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  29620. off += 24;
  29621. if (off >= 26) {
  29622. off -= 26;
  29623. j++;
  29624. }
  29625. }
  29626. } else if (endian === 'le') {
  29627. for (i = 0, j = 0; i < number.length; i += 3) {
  29628. w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
  29629. this.words[j] |= (w << off) & 0x3ffffff;
  29630. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  29631. off += 24;
  29632. if (off >= 26) {
  29633. off -= 26;
  29634. j++;
  29635. }
  29636. }
  29637. }
  29638. return this._strip();
  29639. };
  29640. function parseHex (str, start, end) {
  29641. var r = 0;
  29642. var len = Math.min(str.length, end);
  29643. var z = 0;
  29644. for (var i = start; i < len; i++) {
  29645. var c = str.charCodeAt(i) - 48;
  29646. r <<= 4;
  29647. var b;
  29648. // 'a' - 'f'
  29649. if (c >= 49 && c <= 54) {
  29650. b = c - 49 + 0xa;
  29651. // 'A' - 'F'
  29652. } else if (c >= 17 && c <= 22) {
  29653. b = c - 17 + 0xa;
  29654. // '0' - '9'
  29655. } else {
  29656. b = c;
  29657. }
  29658. r |= b;
  29659. z |= b;
  29660. }
  29661. assert(!(z & 0xf0), 'Invalid character in ' + str);
  29662. return r;
  29663. }
  29664. BN.prototype._parseHex = function _parseHex (number, start) {
  29665. // Create possibly bigger array to ensure that it fits the number
  29666. this.length = Math.ceil((number.length - start) / 6);
  29667. this.words = new Array(this.length);
  29668. for (var i = 0; i < this.length; i++) {
  29669. this.words[i] = 0;
  29670. }
  29671. var j, w;
  29672. // Scan 24-bit chunks and add them to the number
  29673. var off = 0;
  29674. for (i = number.length - 6, j = 0; i >= start; i -= 6) {
  29675. w = parseHex(number, i, i + 6);
  29676. this.words[j] |= (w << off) & 0x3ffffff;
  29677. // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
  29678. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  29679. off += 24;
  29680. if (off >= 26) {
  29681. off -= 26;
  29682. j++;
  29683. }
  29684. }
  29685. if (i + 6 !== start) {
  29686. w = parseHex(number, start, i + 6);
  29687. this.words[j] |= (w << off) & 0x3ffffff;
  29688. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  29689. }
  29690. this._strip();
  29691. };
  29692. function parseBase (str, start, end, mul) {
  29693. var r = 0;
  29694. var b = 0;
  29695. var len = Math.min(str.length, end);
  29696. for (var i = start; i < len; i++) {
  29697. var c = str.charCodeAt(i) - 48;
  29698. r *= mul;
  29699. // 'a'
  29700. if (c >= 49) {
  29701. b = c - 49 + 0xa;
  29702. // 'A'
  29703. } else if (c >= 17) {
  29704. b = c - 17 + 0xa;
  29705. // '0' - '9'
  29706. } else {
  29707. b = c;
  29708. }
  29709. assert(c >= 0 && b < mul, 'Invalid character');
  29710. r += b;
  29711. }
  29712. return r;
  29713. }
  29714. BN.prototype._parseBase = function _parseBase (number, base, start) {
  29715. // Initialize as zero
  29716. this.words = [0];
  29717. this.length = 1;
  29718. // Find length of limb in base
  29719. for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
  29720. limbLen++;
  29721. }
  29722. limbLen--;
  29723. limbPow = (limbPow / base) | 0;
  29724. var total = number.length - start;
  29725. var mod = total % limbLen;
  29726. var end = Math.min(total, total - mod) + start;
  29727. var word = 0;
  29728. for (var i = start; i < end; i += limbLen) {
  29729. word = parseBase(number, i, i + limbLen, base);
  29730. this.imuln(limbPow);
  29731. if (this.words[0] + word < 0x4000000) {
  29732. this.words[0] += word;
  29733. } else {
  29734. this._iaddn(word);
  29735. }
  29736. }
  29737. if (mod !== 0) {
  29738. var pow = 1;
  29739. word = parseBase(number, i, number.length, base);
  29740. for (i = 0; i < mod; i++) {
  29741. pow *= base;
  29742. }
  29743. this.imuln(pow);
  29744. if (this.words[0] + word < 0x4000000) {
  29745. this.words[0] += word;
  29746. } else {
  29747. this._iaddn(word);
  29748. }
  29749. }
  29750. };
  29751. BN.prototype.copy = function copy (dest) {
  29752. dest.words = new Array(this.length);
  29753. for (var i = 0; i < this.length; i++) {
  29754. dest.words[i] = this.words[i];
  29755. }
  29756. dest.length = this.length;
  29757. dest.negative = this.negative;
  29758. dest.red = this.red;
  29759. };
  29760. function move (dest, src) {
  29761. dest.words = src.words;
  29762. dest.length = src.length;
  29763. dest.negative = src.negative;
  29764. dest.red = src.red;
  29765. }
  29766. BN.prototype._move = function _move (dest) {
  29767. move(dest, this);
  29768. };
  29769. BN.prototype.clone = function clone () {
  29770. var r = new BN(null);
  29771. this.copy(r);
  29772. return r;
  29773. };
  29774. BN.prototype._expand = function _expand (size) {
  29775. while (this.length < size) {
  29776. this.words[this.length++] = 0;
  29777. }
  29778. return this;
  29779. };
  29780. // Remove leading `0` from `this`
  29781. BN.prototype._strip = function strip () {
  29782. while (this.length > 1 && this.words[this.length - 1] === 0) {
  29783. this.length--;
  29784. }
  29785. return this._normSign();
  29786. };
  29787. BN.prototype._normSign = function _normSign () {
  29788. // -0 = 0
  29789. if (this.length === 1 && this.words[0] === 0) {
  29790. this.negative = 0;
  29791. }
  29792. return this;
  29793. };
  29794. // Check Symbol.for because not everywhere where Symbol defined
  29795. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
  29796. if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
  29797. try {
  29798. BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
  29799. } catch (e) {
  29800. BN.prototype.inspect = inspect;
  29801. }
  29802. } else {
  29803. BN.prototype.inspect = inspect;
  29804. }
  29805. function inspect () {
  29806. return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  29807. }
  29808. /*
  29809. var zeros = [];
  29810. var groupSizes = [];
  29811. var groupBases = [];
  29812. var s = '';
  29813. var i = -1;
  29814. while (++i < BN.wordSize) {
  29815. zeros[i] = s;
  29816. s += '0';
  29817. }
  29818. groupSizes[0] = 0;
  29819. groupSizes[1] = 0;
  29820. groupBases[0] = 0;
  29821. groupBases[1] = 0;
  29822. var base = 2 - 1;
  29823. while (++base < 36 + 1) {
  29824. var groupSize = 0;
  29825. var groupBase = 1;
  29826. while (groupBase < (1 << BN.wordSize) / base) {
  29827. groupBase *= base;
  29828. groupSize += 1;
  29829. }
  29830. groupSizes[base] = groupSize;
  29831. groupBases[base] = groupBase;
  29832. }
  29833. */
  29834. var zeros = [
  29835. '',
  29836. '0',
  29837. '00',
  29838. '000',
  29839. '0000',
  29840. '00000',
  29841. '000000',
  29842. '0000000',
  29843. '00000000',
  29844. '000000000',
  29845. '0000000000',
  29846. '00000000000',
  29847. '000000000000',
  29848. '0000000000000',
  29849. '00000000000000',
  29850. '000000000000000',
  29851. '0000000000000000',
  29852. '00000000000000000',
  29853. '000000000000000000',
  29854. '0000000000000000000',
  29855. '00000000000000000000',
  29856. '000000000000000000000',
  29857. '0000000000000000000000',
  29858. '00000000000000000000000',
  29859. '000000000000000000000000',
  29860. '0000000000000000000000000'
  29861. ];
  29862. var groupSizes = [
  29863. 0, 0,
  29864. 25, 16, 12, 11, 10, 9, 8,
  29865. 8, 7, 7, 7, 7, 6, 6,
  29866. 6, 6, 6, 6, 6, 5, 5,
  29867. 5, 5, 5, 5, 5, 5, 5,
  29868. 5, 5, 5, 5, 5, 5, 5
  29869. ];
  29870. var groupBases = [
  29871. 0, 0,
  29872. 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
  29873. 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
  29874. 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
  29875. 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
  29876. 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  29877. ];
  29878. BN.prototype.toString = function toString (base, padding) {
  29879. base = base || 10;
  29880. padding = padding | 0 || 1;
  29881. var out;
  29882. if (base === 16 || base === 'hex') {
  29883. out = '';
  29884. var off = 0;
  29885. var carry = 0;
  29886. for (var i = 0; i < this.length; i++) {
  29887. var w = this.words[i];
  29888. var word = (((w << off) | carry) & 0xffffff).toString(16);
  29889. carry = (w >>> (24 - off)) & 0xffffff;
  29890. if (carry !== 0 || i !== this.length - 1) {
  29891. out = zeros[6 - word.length] + word + out;
  29892. } else {
  29893. out = word + out;
  29894. }
  29895. off += 2;
  29896. if (off >= 26) {
  29897. off -= 26;
  29898. i--;
  29899. }
  29900. }
  29901. if (carry !== 0) {
  29902. out = carry.toString(16) + out;
  29903. }
  29904. while (out.length % padding !== 0) {
  29905. out = '0' + out;
  29906. }
  29907. if (this.negative !== 0) {
  29908. out = '-' + out;
  29909. }
  29910. return out;
  29911. }
  29912. if (base === (base | 0) && base >= 2 && base <= 36) {
  29913. // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
  29914. var groupSize = groupSizes[base];
  29915. // var groupBase = Math.pow(base, groupSize);
  29916. var groupBase = groupBases[base];
  29917. out = '';
  29918. var c = this.clone();
  29919. c.negative = 0;
  29920. while (!c.isZero()) {
  29921. var r = c.modrn(groupBase).toString(base);
  29922. c = c.idivn(groupBase);
  29923. if (!c.isZero()) {
  29924. out = zeros[groupSize - r.length] + r + out;
  29925. } else {
  29926. out = r + out;
  29927. }
  29928. }
  29929. if (this.isZero()) {
  29930. out = '0' + out;
  29931. }
  29932. while (out.length % padding !== 0) {
  29933. out = '0' + out;
  29934. }
  29935. if (this.negative !== 0) {
  29936. out = '-' + out;
  29937. }
  29938. return out;
  29939. }
  29940. assert(false, 'Base should be between 2 and 36');
  29941. };
  29942. BN.prototype.toNumber = function toNumber () {
  29943. var ret = this.words[0];
  29944. if (this.length === 2) {
  29945. ret += this.words[1] * 0x4000000;
  29946. } else if (this.length === 3 && this.words[2] === 0x01) {
  29947. // NOTE: at this stage it is known that the top bit is set
  29948. ret += 0x10000000000000 + (this.words[1] * 0x4000000);
  29949. } else if (this.length > 2) {
  29950. assert(false, 'Number can only safely store up to 53 bits');
  29951. }
  29952. return (this.negative !== 0) ? -ret : ret;
  29953. };
  29954. BN.prototype.toJSON = function toJSON () {
  29955. return this.toString(16, 2);
  29956. };
  29957. if (Buffer) {
  29958. BN.prototype.toBuffer = function toBuffer (endian, length) {
  29959. return this.toArrayLike(Buffer, endian, length);
  29960. };
  29961. }
  29962. BN.prototype.toArray = function toArray (endian, length) {
  29963. return this.toArrayLike(Array, endian, length);
  29964. };
  29965. var allocate = function allocate (ArrayType, size) {
  29966. if (ArrayType.allocUnsafe) {
  29967. return ArrayType.allocUnsafe(size);
  29968. }
  29969. return new ArrayType(size);
  29970. };
  29971. BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
  29972. this._strip();
  29973. var byteLength = this.byteLength();
  29974. var reqLength = length || Math.max(1, byteLength);
  29975. assert(byteLength <= reqLength, 'byte array longer than desired length');
  29976. assert(reqLength > 0, 'Requested array length <= 0');
  29977. var res = allocate(ArrayType, reqLength);
  29978. var postfix = endian === 'le' ? 'LE' : 'BE';
  29979. this['_toArrayLike' + postfix](res, byteLength);
  29980. return res;
  29981. };
  29982. BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {
  29983. var position = 0;
  29984. var carry = 0;
  29985. for (var i = 0, shift = 0; i < this.length; i++) {
  29986. var word = (this.words[i] << shift) | carry;
  29987. res[position++] = word & 0xff;
  29988. if (position < res.length) {
  29989. res[position++] = (word >> 8) & 0xff;
  29990. }
  29991. if (position < res.length) {
  29992. res[position++] = (word >> 16) & 0xff;
  29993. }
  29994. if (shift === 6) {
  29995. if (position < res.length) {
  29996. res[position++] = (word >> 24) & 0xff;
  29997. }
  29998. carry = 0;
  29999. shift = 0;
  30000. } else {
  30001. carry = word >>> 24;
  30002. shift += 2;
  30003. }
  30004. }
  30005. if (position < res.length) {
  30006. res[position++] = carry;
  30007. while (position < res.length) {
  30008. res[position++] = 0;
  30009. }
  30010. }
  30011. };
  30012. BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {
  30013. var position = res.length - 1;
  30014. var carry = 0;
  30015. for (var i = 0, shift = 0; i < this.length; i++) {
  30016. var word = (this.words[i] << shift) | carry;
  30017. res[position--] = word & 0xff;
  30018. if (position >= 0) {
  30019. res[position--] = (word >> 8) & 0xff;
  30020. }
  30021. if (position >= 0) {
  30022. res[position--] = (word >> 16) & 0xff;
  30023. }
  30024. if (shift === 6) {
  30025. if (position >= 0) {
  30026. res[position--] = (word >> 24) & 0xff;
  30027. }
  30028. carry = 0;
  30029. shift = 0;
  30030. } else {
  30031. carry = word >>> 24;
  30032. shift += 2;
  30033. }
  30034. }
  30035. if (position >= 0) {
  30036. res[position--] = carry;
  30037. while (position >= 0) {
  30038. res[position--] = 0;
  30039. }
  30040. }
  30041. };
  30042. if (Math.clz32) {
  30043. BN.prototype._countBits = function _countBits (w) {
  30044. return 32 - Math.clz32(w);
  30045. };
  30046. } else {
  30047. BN.prototype._countBits = function _countBits (w) {
  30048. var t = w;
  30049. var r = 0;
  30050. if (t >= 0x1000) {
  30051. r += 13;
  30052. t >>>= 13;
  30053. }
  30054. if (t >= 0x40) {
  30055. r += 7;
  30056. t >>>= 7;
  30057. }
  30058. if (t >= 0x8) {
  30059. r += 4;
  30060. t >>>= 4;
  30061. }
  30062. if (t >= 0x02) {
  30063. r += 2;
  30064. t >>>= 2;
  30065. }
  30066. return r + t;
  30067. };
  30068. }
  30069. BN.prototype._zeroBits = function _zeroBits (w) {
  30070. // Short-cut
  30071. if (w === 0) return 26;
  30072. var t = w;
  30073. var r = 0;
  30074. if ((t & 0x1fff) === 0) {
  30075. r += 13;
  30076. t >>>= 13;
  30077. }
  30078. if ((t & 0x7f) === 0) {
  30079. r += 7;
  30080. t >>>= 7;
  30081. }
  30082. if ((t & 0xf) === 0) {
  30083. r += 4;
  30084. t >>>= 4;
  30085. }
  30086. if ((t & 0x3) === 0) {
  30087. r += 2;
  30088. t >>>= 2;
  30089. }
  30090. if ((t & 0x1) === 0) {
  30091. r++;
  30092. }
  30093. return r;
  30094. };
  30095. // Return number of used bits in a BN
  30096. BN.prototype.bitLength = function bitLength () {
  30097. var w = this.words[this.length - 1];
  30098. var hi = this._countBits(w);
  30099. return (this.length - 1) * 26 + hi;
  30100. };
  30101. function toBitArray (num) {
  30102. var w = new Array(num.bitLength());
  30103. for (var bit = 0; bit < w.length; bit++) {
  30104. var off = (bit / 26) | 0;
  30105. var wbit = bit % 26;
  30106. w[bit] = (num.words[off] >>> wbit) & 0x01;
  30107. }
  30108. return w;
  30109. }
  30110. // Number of trailing zero bits
  30111. BN.prototype.zeroBits = function zeroBits () {
  30112. if (this.isZero()) return 0;
  30113. var r = 0;
  30114. for (var i = 0; i < this.length; i++) {
  30115. var b = this._zeroBits(this.words[i]);
  30116. r += b;
  30117. if (b !== 26) break;
  30118. }
  30119. return r;
  30120. };
  30121. BN.prototype.byteLength = function byteLength () {
  30122. return Math.ceil(this.bitLength() / 8);
  30123. };
  30124. BN.prototype.toTwos = function toTwos (width) {
  30125. if (this.negative !== 0) {
  30126. return this.abs().inotn(width).iaddn(1);
  30127. }
  30128. return this.clone();
  30129. };
  30130. BN.prototype.fromTwos = function fromTwos (width) {
  30131. if (this.testn(width - 1)) {
  30132. return this.notn(width).iaddn(1).ineg();
  30133. }
  30134. return this.clone();
  30135. };
  30136. BN.prototype.isNeg = function isNeg () {
  30137. return this.negative !== 0;
  30138. };
  30139. // Return negative clone of `this`
  30140. BN.prototype.neg = function neg () {
  30141. return this.clone().ineg();
  30142. };
  30143. BN.prototype.ineg = function ineg () {
  30144. if (!this.isZero()) {
  30145. this.negative ^= 1;
  30146. }
  30147. return this;
  30148. };
  30149. // Or `num` with `this` in-place
  30150. BN.prototype.iuor = function iuor (num) {
  30151. while (this.length < num.length) {
  30152. this.words[this.length++] = 0;
  30153. }
  30154. for (var i = 0; i < num.length; i++) {
  30155. this.words[i] = this.words[i] | num.words[i];
  30156. }
  30157. return this._strip();
  30158. };
  30159. BN.prototype.ior = function ior (num) {
  30160. assert((this.negative | num.negative) === 0);
  30161. return this.iuor(num);
  30162. };
  30163. // Or `num` with `this`
  30164. BN.prototype.or = function or (num) {
  30165. if (this.length > num.length) return this.clone().ior(num);
  30166. return num.clone().ior(this);
  30167. };
  30168. BN.prototype.uor = function uor (num) {
  30169. if (this.length > num.length) return this.clone().iuor(num);
  30170. return num.clone().iuor(this);
  30171. };
  30172. // And `num` with `this` in-place
  30173. BN.prototype.iuand = function iuand (num) {
  30174. // b = min-length(num, this)
  30175. var b;
  30176. if (this.length > num.length) {
  30177. b = num;
  30178. } else {
  30179. b = this;
  30180. }
  30181. for (var i = 0; i < b.length; i++) {
  30182. this.words[i] = this.words[i] & num.words[i];
  30183. }
  30184. this.length = b.length;
  30185. return this._strip();
  30186. };
  30187. BN.prototype.iand = function iand (num) {
  30188. assert((this.negative | num.negative) === 0);
  30189. return this.iuand(num);
  30190. };
  30191. // And `num` with `this`
  30192. BN.prototype.and = function and (num) {
  30193. if (this.length > num.length) return this.clone().iand(num);
  30194. return num.clone().iand(this);
  30195. };
  30196. BN.prototype.uand = function uand (num) {
  30197. if (this.length > num.length) return this.clone().iuand(num);
  30198. return num.clone().iuand(this);
  30199. };
  30200. // Xor `num` with `this` in-place
  30201. BN.prototype.iuxor = function iuxor (num) {
  30202. // a.length > b.length
  30203. var a;
  30204. var b;
  30205. if (this.length > num.length) {
  30206. a = this;
  30207. b = num;
  30208. } else {
  30209. a = num;
  30210. b = this;
  30211. }
  30212. for (var i = 0; i < b.length; i++) {
  30213. this.words[i] = a.words[i] ^ b.words[i];
  30214. }
  30215. if (this !== a) {
  30216. for (; i < a.length; i++) {
  30217. this.words[i] = a.words[i];
  30218. }
  30219. }
  30220. this.length = a.length;
  30221. return this._strip();
  30222. };
  30223. BN.prototype.ixor = function ixor (num) {
  30224. assert((this.negative | num.negative) === 0);
  30225. return this.iuxor(num);
  30226. };
  30227. // Xor `num` with `this`
  30228. BN.prototype.xor = function xor (num) {
  30229. if (this.length > num.length) return this.clone().ixor(num);
  30230. return num.clone().ixor(this);
  30231. };
  30232. BN.prototype.uxor = function uxor (num) {
  30233. if (this.length > num.length) return this.clone().iuxor(num);
  30234. return num.clone().iuxor(this);
  30235. };
  30236. // Not ``this`` with ``width`` bitwidth
  30237. BN.prototype.inotn = function inotn (width) {
  30238. assert(typeof width === 'number' && width >= 0);
  30239. var bytesNeeded = Math.ceil(width / 26) | 0;
  30240. var bitsLeft = width % 26;
  30241. // Extend the buffer with leading zeroes
  30242. this._expand(bytesNeeded);
  30243. if (bitsLeft > 0) {
  30244. bytesNeeded--;
  30245. }
  30246. // Handle complete words
  30247. for (var i = 0; i < bytesNeeded; i++) {
  30248. this.words[i] = ~this.words[i] & 0x3ffffff;
  30249. }
  30250. // Handle the residue
  30251. if (bitsLeft > 0) {
  30252. this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
  30253. }
  30254. // And remove leading zeroes
  30255. return this._strip();
  30256. };
  30257. BN.prototype.notn = function notn (width) {
  30258. return this.clone().inotn(width);
  30259. };
  30260. // Set `bit` of `this`
  30261. BN.prototype.setn = function setn (bit, val) {
  30262. assert(typeof bit === 'number' && bit >= 0);
  30263. var off = (bit / 26) | 0;
  30264. var wbit = bit % 26;
  30265. this._expand(off + 1);
  30266. if (val) {
  30267. this.words[off] = this.words[off] | (1 << wbit);
  30268. } else {
  30269. this.words[off] = this.words[off] & ~(1 << wbit);
  30270. }
  30271. return this._strip();
  30272. };
  30273. // Add `num` to `this` in-place
  30274. BN.prototype.iadd = function iadd (num) {
  30275. var r;
  30276. // negative + positive
  30277. if (this.negative !== 0 && num.negative === 0) {
  30278. this.negative = 0;
  30279. r = this.isub(num);
  30280. this.negative ^= 1;
  30281. return this._normSign();
  30282. // positive + negative
  30283. } else if (this.negative === 0 && num.negative !== 0) {
  30284. num.negative = 0;
  30285. r = this.isub(num);
  30286. num.negative = 1;
  30287. return r._normSign();
  30288. }
  30289. // a.length > b.length
  30290. var a, b;
  30291. if (this.length > num.length) {
  30292. a = this;
  30293. b = num;
  30294. } else {
  30295. a = num;
  30296. b = this;
  30297. }
  30298. var carry = 0;
  30299. for (var i = 0; i < b.length; i++) {
  30300. r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
  30301. this.words[i] = r & 0x3ffffff;
  30302. carry = r >>> 26;
  30303. }
  30304. for (; carry !== 0 && i < a.length; i++) {
  30305. r = (a.words[i] | 0) + carry;
  30306. this.words[i] = r & 0x3ffffff;
  30307. carry = r >>> 26;
  30308. }
  30309. this.length = a.length;
  30310. if (carry !== 0) {
  30311. this.words[this.length] = carry;
  30312. this.length++;
  30313. // Copy the rest of the words
  30314. } else if (a !== this) {
  30315. for (; i < a.length; i++) {
  30316. this.words[i] = a.words[i];
  30317. }
  30318. }
  30319. return this;
  30320. };
  30321. // Add `num` to `this`
  30322. BN.prototype.add = function add (num) {
  30323. var res;
  30324. if (num.negative !== 0 && this.negative === 0) {
  30325. num.negative = 0;
  30326. res = this.sub(num);
  30327. num.negative ^= 1;
  30328. return res;
  30329. } else if (num.negative === 0 && this.negative !== 0) {
  30330. this.negative = 0;
  30331. res = num.sub(this);
  30332. this.negative = 1;
  30333. return res;
  30334. }
  30335. if (this.length > num.length) return this.clone().iadd(num);
  30336. return num.clone().iadd(this);
  30337. };
  30338. // Subtract `num` from `this` in-place
  30339. BN.prototype.isub = function isub (num) {
  30340. // this - (-num) = this + num
  30341. if (num.negative !== 0) {
  30342. num.negative = 0;
  30343. var r = this.iadd(num);
  30344. num.negative = 1;
  30345. return r._normSign();
  30346. // -this - num = -(this + num)
  30347. } else if (this.negative !== 0) {
  30348. this.negative = 0;
  30349. this.iadd(num);
  30350. this.negative = 1;
  30351. return this._normSign();
  30352. }
  30353. // At this point both numbers are positive
  30354. var cmp = this.cmp(num);
  30355. // Optimization - zeroify
  30356. if (cmp === 0) {
  30357. this.negative = 0;
  30358. this.length = 1;
  30359. this.words[0] = 0;
  30360. return this;
  30361. }
  30362. // a > b
  30363. var a, b;
  30364. if (cmp > 0) {
  30365. a = this;
  30366. b = num;
  30367. } else {
  30368. a = num;
  30369. b = this;
  30370. }
  30371. var carry = 0;
  30372. for (var i = 0; i < b.length; i++) {
  30373. r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
  30374. carry = r >> 26;
  30375. this.words[i] = r & 0x3ffffff;
  30376. }
  30377. for (; carry !== 0 && i < a.length; i++) {
  30378. r = (a.words[i] | 0) + carry;
  30379. carry = r >> 26;
  30380. this.words[i] = r & 0x3ffffff;
  30381. }
  30382. // Copy rest of the words
  30383. if (carry === 0 && i < a.length && a !== this) {
  30384. for (; i < a.length; i++) {
  30385. this.words[i] = a.words[i];
  30386. }
  30387. }
  30388. this.length = Math.max(this.length, i);
  30389. if (a !== this) {
  30390. this.negative = 1;
  30391. }
  30392. return this._strip();
  30393. };
  30394. // Subtract `num` from `this`
  30395. BN.prototype.sub = function sub (num) {
  30396. return this.clone().isub(num);
  30397. };
  30398. function smallMulTo (self, num, out) {
  30399. out.negative = num.negative ^ self.negative;
  30400. var len = (self.length + num.length) | 0;
  30401. out.length = len;
  30402. len = (len - 1) | 0;
  30403. // Peel one iteration (compiler can't do it, because of code complexity)
  30404. var a = self.words[0] | 0;
  30405. var b = num.words[0] | 0;
  30406. var r = a * b;
  30407. var lo = r & 0x3ffffff;
  30408. var carry = (r / 0x4000000) | 0;
  30409. out.words[0] = lo;
  30410. for (var k = 1; k < len; k++) {
  30411. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  30412. // note that ncarry could be >= 0x3ffffff
  30413. var ncarry = carry >>> 26;
  30414. var rword = carry & 0x3ffffff;
  30415. var maxJ = Math.min(k, num.length - 1);
  30416. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  30417. var i = (k - j) | 0;
  30418. a = self.words[i] | 0;
  30419. b = num.words[j] | 0;
  30420. r = a * b + rword;
  30421. ncarry += (r / 0x4000000) | 0;
  30422. rword = r & 0x3ffffff;
  30423. }
  30424. out.words[k] = rword | 0;
  30425. carry = ncarry | 0;
  30426. }
  30427. if (carry !== 0) {
  30428. out.words[k] = carry | 0;
  30429. } else {
  30430. out.length--;
  30431. }
  30432. return out._strip();
  30433. }
  30434. // TODO(indutny): it may be reasonable to omit it for users who don't need
  30435. // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  30436. // multiplication (like elliptic secp256k1).
  30437. var comb10MulTo = function comb10MulTo (self, num, out) {
  30438. var a = self.words;
  30439. var b = num.words;
  30440. var o = out.words;
  30441. var c = 0;
  30442. var lo;
  30443. var mid;
  30444. var hi;
  30445. var a0 = a[0] | 0;
  30446. var al0 = a0 & 0x1fff;
  30447. var ah0 = a0 >>> 13;
  30448. var a1 = a[1] | 0;
  30449. var al1 = a1 & 0x1fff;
  30450. var ah1 = a1 >>> 13;
  30451. var a2 = a[2] | 0;
  30452. var al2 = a2 & 0x1fff;
  30453. var ah2 = a2 >>> 13;
  30454. var a3 = a[3] | 0;
  30455. var al3 = a3 & 0x1fff;
  30456. var ah3 = a3 >>> 13;
  30457. var a4 = a[4] | 0;
  30458. var al4 = a4 & 0x1fff;
  30459. var ah4 = a4 >>> 13;
  30460. var a5 = a[5] | 0;
  30461. var al5 = a5 & 0x1fff;
  30462. var ah5 = a5 >>> 13;
  30463. var a6 = a[6] | 0;
  30464. var al6 = a6 & 0x1fff;
  30465. var ah6 = a6 >>> 13;
  30466. var a7 = a[7] | 0;
  30467. var al7 = a7 & 0x1fff;
  30468. var ah7 = a7 >>> 13;
  30469. var a8 = a[8] | 0;
  30470. var al8 = a8 & 0x1fff;
  30471. var ah8 = a8 >>> 13;
  30472. var a9 = a[9] | 0;
  30473. var al9 = a9 & 0x1fff;
  30474. var ah9 = a9 >>> 13;
  30475. var b0 = b[0] | 0;
  30476. var bl0 = b0 & 0x1fff;
  30477. var bh0 = b0 >>> 13;
  30478. var b1 = b[1] | 0;
  30479. var bl1 = b1 & 0x1fff;
  30480. var bh1 = b1 >>> 13;
  30481. var b2 = b[2] | 0;
  30482. var bl2 = b2 & 0x1fff;
  30483. var bh2 = b2 >>> 13;
  30484. var b3 = b[3] | 0;
  30485. var bl3 = b3 & 0x1fff;
  30486. var bh3 = b3 >>> 13;
  30487. var b4 = b[4] | 0;
  30488. var bl4 = b4 & 0x1fff;
  30489. var bh4 = b4 >>> 13;
  30490. var b5 = b[5] | 0;
  30491. var bl5 = b5 & 0x1fff;
  30492. var bh5 = b5 >>> 13;
  30493. var b6 = b[6] | 0;
  30494. var bl6 = b6 & 0x1fff;
  30495. var bh6 = b6 >>> 13;
  30496. var b7 = b[7] | 0;
  30497. var bl7 = b7 & 0x1fff;
  30498. var bh7 = b7 >>> 13;
  30499. var b8 = b[8] | 0;
  30500. var bl8 = b8 & 0x1fff;
  30501. var bh8 = b8 >>> 13;
  30502. var b9 = b[9] | 0;
  30503. var bl9 = b9 & 0x1fff;
  30504. var bh9 = b9 >>> 13;
  30505. out.negative = self.negative ^ num.negative;
  30506. out.length = 19;
  30507. /* k = 0 */
  30508. lo = Math.imul(al0, bl0);
  30509. mid = Math.imul(al0, bh0);
  30510. mid = (mid + Math.imul(ah0, bl0)) | 0;
  30511. hi = Math.imul(ah0, bh0);
  30512. var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30513. c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
  30514. w0 &= 0x3ffffff;
  30515. /* k = 1 */
  30516. lo = Math.imul(al1, bl0);
  30517. mid = Math.imul(al1, bh0);
  30518. mid = (mid + Math.imul(ah1, bl0)) | 0;
  30519. hi = Math.imul(ah1, bh0);
  30520. lo = (lo + Math.imul(al0, bl1)) | 0;
  30521. mid = (mid + Math.imul(al0, bh1)) | 0;
  30522. mid = (mid + Math.imul(ah0, bl1)) | 0;
  30523. hi = (hi + Math.imul(ah0, bh1)) | 0;
  30524. var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30525. c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
  30526. w1 &= 0x3ffffff;
  30527. /* k = 2 */
  30528. lo = Math.imul(al2, bl0);
  30529. mid = Math.imul(al2, bh0);
  30530. mid = (mid + Math.imul(ah2, bl0)) | 0;
  30531. hi = Math.imul(ah2, bh0);
  30532. lo = (lo + Math.imul(al1, bl1)) | 0;
  30533. mid = (mid + Math.imul(al1, bh1)) | 0;
  30534. mid = (mid + Math.imul(ah1, bl1)) | 0;
  30535. hi = (hi + Math.imul(ah1, bh1)) | 0;
  30536. lo = (lo + Math.imul(al0, bl2)) | 0;
  30537. mid = (mid + Math.imul(al0, bh2)) | 0;
  30538. mid = (mid + Math.imul(ah0, bl2)) | 0;
  30539. hi = (hi + Math.imul(ah0, bh2)) | 0;
  30540. var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30541. c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
  30542. w2 &= 0x3ffffff;
  30543. /* k = 3 */
  30544. lo = Math.imul(al3, bl0);
  30545. mid = Math.imul(al3, bh0);
  30546. mid = (mid + Math.imul(ah3, bl0)) | 0;
  30547. hi = Math.imul(ah3, bh0);
  30548. lo = (lo + Math.imul(al2, bl1)) | 0;
  30549. mid = (mid + Math.imul(al2, bh1)) | 0;
  30550. mid = (mid + Math.imul(ah2, bl1)) | 0;
  30551. hi = (hi + Math.imul(ah2, bh1)) | 0;
  30552. lo = (lo + Math.imul(al1, bl2)) | 0;
  30553. mid = (mid + Math.imul(al1, bh2)) | 0;
  30554. mid = (mid + Math.imul(ah1, bl2)) | 0;
  30555. hi = (hi + Math.imul(ah1, bh2)) | 0;
  30556. lo = (lo + Math.imul(al0, bl3)) | 0;
  30557. mid = (mid + Math.imul(al0, bh3)) | 0;
  30558. mid = (mid + Math.imul(ah0, bl3)) | 0;
  30559. hi = (hi + Math.imul(ah0, bh3)) | 0;
  30560. var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30561. c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
  30562. w3 &= 0x3ffffff;
  30563. /* k = 4 */
  30564. lo = Math.imul(al4, bl0);
  30565. mid = Math.imul(al4, bh0);
  30566. mid = (mid + Math.imul(ah4, bl0)) | 0;
  30567. hi = Math.imul(ah4, bh0);
  30568. lo = (lo + Math.imul(al3, bl1)) | 0;
  30569. mid = (mid + Math.imul(al3, bh1)) | 0;
  30570. mid = (mid + Math.imul(ah3, bl1)) | 0;
  30571. hi = (hi + Math.imul(ah3, bh1)) | 0;
  30572. lo = (lo + Math.imul(al2, bl2)) | 0;
  30573. mid = (mid + Math.imul(al2, bh2)) | 0;
  30574. mid = (mid + Math.imul(ah2, bl2)) | 0;
  30575. hi = (hi + Math.imul(ah2, bh2)) | 0;
  30576. lo = (lo + Math.imul(al1, bl3)) | 0;
  30577. mid = (mid + Math.imul(al1, bh3)) | 0;
  30578. mid = (mid + Math.imul(ah1, bl3)) | 0;
  30579. hi = (hi + Math.imul(ah1, bh3)) | 0;
  30580. lo = (lo + Math.imul(al0, bl4)) | 0;
  30581. mid = (mid + Math.imul(al0, bh4)) | 0;
  30582. mid = (mid + Math.imul(ah0, bl4)) | 0;
  30583. hi = (hi + Math.imul(ah0, bh4)) | 0;
  30584. var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30585. c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
  30586. w4 &= 0x3ffffff;
  30587. /* k = 5 */
  30588. lo = Math.imul(al5, bl0);
  30589. mid = Math.imul(al5, bh0);
  30590. mid = (mid + Math.imul(ah5, bl0)) | 0;
  30591. hi = Math.imul(ah5, bh0);
  30592. lo = (lo + Math.imul(al4, bl1)) | 0;
  30593. mid = (mid + Math.imul(al4, bh1)) | 0;
  30594. mid = (mid + Math.imul(ah4, bl1)) | 0;
  30595. hi = (hi + Math.imul(ah4, bh1)) | 0;
  30596. lo = (lo + Math.imul(al3, bl2)) | 0;
  30597. mid = (mid + Math.imul(al3, bh2)) | 0;
  30598. mid = (mid + Math.imul(ah3, bl2)) | 0;
  30599. hi = (hi + Math.imul(ah3, bh2)) | 0;
  30600. lo = (lo + Math.imul(al2, bl3)) | 0;
  30601. mid = (mid + Math.imul(al2, bh3)) | 0;
  30602. mid = (mid + Math.imul(ah2, bl3)) | 0;
  30603. hi = (hi + Math.imul(ah2, bh3)) | 0;
  30604. lo = (lo + Math.imul(al1, bl4)) | 0;
  30605. mid = (mid + Math.imul(al1, bh4)) | 0;
  30606. mid = (mid + Math.imul(ah1, bl4)) | 0;
  30607. hi = (hi + Math.imul(ah1, bh4)) | 0;
  30608. lo = (lo + Math.imul(al0, bl5)) | 0;
  30609. mid = (mid + Math.imul(al0, bh5)) | 0;
  30610. mid = (mid + Math.imul(ah0, bl5)) | 0;
  30611. hi = (hi + Math.imul(ah0, bh5)) | 0;
  30612. var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30613. c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
  30614. w5 &= 0x3ffffff;
  30615. /* k = 6 */
  30616. lo = Math.imul(al6, bl0);
  30617. mid = Math.imul(al6, bh0);
  30618. mid = (mid + Math.imul(ah6, bl0)) | 0;
  30619. hi = Math.imul(ah6, bh0);
  30620. lo = (lo + Math.imul(al5, bl1)) | 0;
  30621. mid = (mid + Math.imul(al5, bh1)) | 0;
  30622. mid = (mid + Math.imul(ah5, bl1)) | 0;
  30623. hi = (hi + Math.imul(ah5, bh1)) | 0;
  30624. lo = (lo + Math.imul(al4, bl2)) | 0;
  30625. mid = (mid + Math.imul(al4, bh2)) | 0;
  30626. mid = (mid + Math.imul(ah4, bl2)) | 0;
  30627. hi = (hi + Math.imul(ah4, bh2)) | 0;
  30628. lo = (lo + Math.imul(al3, bl3)) | 0;
  30629. mid = (mid + Math.imul(al3, bh3)) | 0;
  30630. mid = (mid + Math.imul(ah3, bl3)) | 0;
  30631. hi = (hi + Math.imul(ah3, bh3)) | 0;
  30632. lo = (lo + Math.imul(al2, bl4)) | 0;
  30633. mid = (mid + Math.imul(al2, bh4)) | 0;
  30634. mid = (mid + Math.imul(ah2, bl4)) | 0;
  30635. hi = (hi + Math.imul(ah2, bh4)) | 0;
  30636. lo = (lo + Math.imul(al1, bl5)) | 0;
  30637. mid = (mid + Math.imul(al1, bh5)) | 0;
  30638. mid = (mid + Math.imul(ah1, bl5)) | 0;
  30639. hi = (hi + Math.imul(ah1, bh5)) | 0;
  30640. lo = (lo + Math.imul(al0, bl6)) | 0;
  30641. mid = (mid + Math.imul(al0, bh6)) | 0;
  30642. mid = (mid + Math.imul(ah0, bl6)) | 0;
  30643. hi = (hi + Math.imul(ah0, bh6)) | 0;
  30644. var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30645. c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
  30646. w6 &= 0x3ffffff;
  30647. /* k = 7 */
  30648. lo = Math.imul(al7, bl0);
  30649. mid = Math.imul(al7, bh0);
  30650. mid = (mid + Math.imul(ah7, bl0)) | 0;
  30651. hi = Math.imul(ah7, bh0);
  30652. lo = (lo + Math.imul(al6, bl1)) | 0;
  30653. mid = (mid + Math.imul(al6, bh1)) | 0;
  30654. mid = (mid + Math.imul(ah6, bl1)) | 0;
  30655. hi = (hi + Math.imul(ah6, bh1)) | 0;
  30656. lo = (lo + Math.imul(al5, bl2)) | 0;
  30657. mid = (mid + Math.imul(al5, bh2)) | 0;
  30658. mid = (mid + Math.imul(ah5, bl2)) | 0;
  30659. hi = (hi + Math.imul(ah5, bh2)) | 0;
  30660. lo = (lo + Math.imul(al4, bl3)) | 0;
  30661. mid = (mid + Math.imul(al4, bh3)) | 0;
  30662. mid = (mid + Math.imul(ah4, bl3)) | 0;
  30663. hi = (hi + Math.imul(ah4, bh3)) | 0;
  30664. lo = (lo + Math.imul(al3, bl4)) | 0;
  30665. mid = (mid + Math.imul(al3, bh4)) | 0;
  30666. mid = (mid + Math.imul(ah3, bl4)) | 0;
  30667. hi = (hi + Math.imul(ah3, bh4)) | 0;
  30668. lo = (lo + Math.imul(al2, bl5)) | 0;
  30669. mid = (mid + Math.imul(al2, bh5)) | 0;
  30670. mid = (mid + Math.imul(ah2, bl5)) | 0;
  30671. hi = (hi + Math.imul(ah2, bh5)) | 0;
  30672. lo = (lo + Math.imul(al1, bl6)) | 0;
  30673. mid = (mid + Math.imul(al1, bh6)) | 0;
  30674. mid = (mid + Math.imul(ah1, bl6)) | 0;
  30675. hi = (hi + Math.imul(ah1, bh6)) | 0;
  30676. lo = (lo + Math.imul(al0, bl7)) | 0;
  30677. mid = (mid + Math.imul(al0, bh7)) | 0;
  30678. mid = (mid + Math.imul(ah0, bl7)) | 0;
  30679. hi = (hi + Math.imul(ah0, bh7)) | 0;
  30680. var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30681. c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
  30682. w7 &= 0x3ffffff;
  30683. /* k = 8 */
  30684. lo = Math.imul(al8, bl0);
  30685. mid = Math.imul(al8, bh0);
  30686. mid = (mid + Math.imul(ah8, bl0)) | 0;
  30687. hi = Math.imul(ah8, bh0);
  30688. lo = (lo + Math.imul(al7, bl1)) | 0;
  30689. mid = (mid + Math.imul(al7, bh1)) | 0;
  30690. mid = (mid + Math.imul(ah7, bl1)) | 0;
  30691. hi = (hi + Math.imul(ah7, bh1)) | 0;
  30692. lo = (lo + Math.imul(al6, bl2)) | 0;
  30693. mid = (mid + Math.imul(al6, bh2)) | 0;
  30694. mid = (mid + Math.imul(ah6, bl2)) | 0;
  30695. hi = (hi + Math.imul(ah6, bh2)) | 0;
  30696. lo = (lo + Math.imul(al5, bl3)) | 0;
  30697. mid = (mid + Math.imul(al5, bh3)) | 0;
  30698. mid = (mid + Math.imul(ah5, bl3)) | 0;
  30699. hi = (hi + Math.imul(ah5, bh3)) | 0;
  30700. lo = (lo + Math.imul(al4, bl4)) | 0;
  30701. mid = (mid + Math.imul(al4, bh4)) | 0;
  30702. mid = (mid + Math.imul(ah4, bl4)) | 0;
  30703. hi = (hi + Math.imul(ah4, bh4)) | 0;
  30704. lo = (lo + Math.imul(al3, bl5)) | 0;
  30705. mid = (mid + Math.imul(al3, bh5)) | 0;
  30706. mid = (mid + Math.imul(ah3, bl5)) | 0;
  30707. hi = (hi + Math.imul(ah3, bh5)) | 0;
  30708. lo = (lo + Math.imul(al2, bl6)) | 0;
  30709. mid = (mid + Math.imul(al2, bh6)) | 0;
  30710. mid = (mid + Math.imul(ah2, bl6)) | 0;
  30711. hi = (hi + Math.imul(ah2, bh6)) | 0;
  30712. lo = (lo + Math.imul(al1, bl7)) | 0;
  30713. mid = (mid + Math.imul(al1, bh7)) | 0;
  30714. mid = (mid + Math.imul(ah1, bl7)) | 0;
  30715. hi = (hi + Math.imul(ah1, bh7)) | 0;
  30716. lo = (lo + Math.imul(al0, bl8)) | 0;
  30717. mid = (mid + Math.imul(al0, bh8)) | 0;
  30718. mid = (mid + Math.imul(ah0, bl8)) | 0;
  30719. hi = (hi + Math.imul(ah0, bh8)) | 0;
  30720. var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30721. c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
  30722. w8 &= 0x3ffffff;
  30723. /* k = 9 */
  30724. lo = Math.imul(al9, bl0);
  30725. mid = Math.imul(al9, bh0);
  30726. mid = (mid + Math.imul(ah9, bl0)) | 0;
  30727. hi = Math.imul(ah9, bh0);
  30728. lo = (lo + Math.imul(al8, bl1)) | 0;
  30729. mid = (mid + Math.imul(al8, bh1)) | 0;
  30730. mid = (mid + Math.imul(ah8, bl1)) | 0;
  30731. hi = (hi + Math.imul(ah8, bh1)) | 0;
  30732. lo = (lo + Math.imul(al7, bl2)) | 0;
  30733. mid = (mid + Math.imul(al7, bh2)) | 0;
  30734. mid = (mid + Math.imul(ah7, bl2)) | 0;
  30735. hi = (hi + Math.imul(ah7, bh2)) | 0;
  30736. lo = (lo + Math.imul(al6, bl3)) | 0;
  30737. mid = (mid + Math.imul(al6, bh3)) | 0;
  30738. mid = (mid + Math.imul(ah6, bl3)) | 0;
  30739. hi = (hi + Math.imul(ah6, bh3)) | 0;
  30740. lo = (lo + Math.imul(al5, bl4)) | 0;
  30741. mid = (mid + Math.imul(al5, bh4)) | 0;
  30742. mid = (mid + Math.imul(ah5, bl4)) | 0;
  30743. hi = (hi + Math.imul(ah5, bh4)) | 0;
  30744. lo = (lo + Math.imul(al4, bl5)) | 0;
  30745. mid = (mid + Math.imul(al4, bh5)) | 0;
  30746. mid = (mid + Math.imul(ah4, bl5)) | 0;
  30747. hi = (hi + Math.imul(ah4, bh5)) | 0;
  30748. lo = (lo + Math.imul(al3, bl6)) | 0;
  30749. mid = (mid + Math.imul(al3, bh6)) | 0;
  30750. mid = (mid + Math.imul(ah3, bl6)) | 0;
  30751. hi = (hi + Math.imul(ah3, bh6)) | 0;
  30752. lo = (lo + Math.imul(al2, bl7)) | 0;
  30753. mid = (mid + Math.imul(al2, bh7)) | 0;
  30754. mid = (mid + Math.imul(ah2, bl7)) | 0;
  30755. hi = (hi + Math.imul(ah2, bh7)) | 0;
  30756. lo = (lo + Math.imul(al1, bl8)) | 0;
  30757. mid = (mid + Math.imul(al1, bh8)) | 0;
  30758. mid = (mid + Math.imul(ah1, bl8)) | 0;
  30759. hi = (hi + Math.imul(ah1, bh8)) | 0;
  30760. lo = (lo + Math.imul(al0, bl9)) | 0;
  30761. mid = (mid + Math.imul(al0, bh9)) | 0;
  30762. mid = (mid + Math.imul(ah0, bl9)) | 0;
  30763. hi = (hi + Math.imul(ah0, bh9)) | 0;
  30764. var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30765. c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
  30766. w9 &= 0x3ffffff;
  30767. /* k = 10 */
  30768. lo = Math.imul(al9, bl1);
  30769. mid = Math.imul(al9, bh1);
  30770. mid = (mid + Math.imul(ah9, bl1)) | 0;
  30771. hi = Math.imul(ah9, bh1);
  30772. lo = (lo + Math.imul(al8, bl2)) | 0;
  30773. mid = (mid + Math.imul(al8, bh2)) | 0;
  30774. mid = (mid + Math.imul(ah8, bl2)) | 0;
  30775. hi = (hi + Math.imul(ah8, bh2)) | 0;
  30776. lo = (lo + Math.imul(al7, bl3)) | 0;
  30777. mid = (mid + Math.imul(al7, bh3)) | 0;
  30778. mid = (mid + Math.imul(ah7, bl3)) | 0;
  30779. hi = (hi + Math.imul(ah7, bh3)) | 0;
  30780. lo = (lo + Math.imul(al6, bl4)) | 0;
  30781. mid = (mid + Math.imul(al6, bh4)) | 0;
  30782. mid = (mid + Math.imul(ah6, bl4)) | 0;
  30783. hi = (hi + Math.imul(ah6, bh4)) | 0;
  30784. lo = (lo + Math.imul(al5, bl5)) | 0;
  30785. mid = (mid + Math.imul(al5, bh5)) | 0;
  30786. mid = (mid + Math.imul(ah5, bl5)) | 0;
  30787. hi = (hi + Math.imul(ah5, bh5)) | 0;
  30788. lo = (lo + Math.imul(al4, bl6)) | 0;
  30789. mid = (mid + Math.imul(al4, bh6)) | 0;
  30790. mid = (mid + Math.imul(ah4, bl6)) | 0;
  30791. hi = (hi + Math.imul(ah4, bh6)) | 0;
  30792. lo = (lo + Math.imul(al3, bl7)) | 0;
  30793. mid = (mid + Math.imul(al3, bh7)) | 0;
  30794. mid = (mid + Math.imul(ah3, bl7)) | 0;
  30795. hi = (hi + Math.imul(ah3, bh7)) | 0;
  30796. lo = (lo + Math.imul(al2, bl8)) | 0;
  30797. mid = (mid + Math.imul(al2, bh8)) | 0;
  30798. mid = (mid + Math.imul(ah2, bl8)) | 0;
  30799. hi = (hi + Math.imul(ah2, bh8)) | 0;
  30800. lo = (lo + Math.imul(al1, bl9)) | 0;
  30801. mid = (mid + Math.imul(al1, bh9)) | 0;
  30802. mid = (mid + Math.imul(ah1, bl9)) | 0;
  30803. hi = (hi + Math.imul(ah1, bh9)) | 0;
  30804. var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30805. c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
  30806. w10 &= 0x3ffffff;
  30807. /* k = 11 */
  30808. lo = Math.imul(al9, bl2);
  30809. mid = Math.imul(al9, bh2);
  30810. mid = (mid + Math.imul(ah9, bl2)) | 0;
  30811. hi = Math.imul(ah9, bh2);
  30812. lo = (lo + Math.imul(al8, bl3)) | 0;
  30813. mid = (mid + Math.imul(al8, bh3)) | 0;
  30814. mid = (mid + Math.imul(ah8, bl3)) | 0;
  30815. hi = (hi + Math.imul(ah8, bh3)) | 0;
  30816. lo = (lo + Math.imul(al7, bl4)) | 0;
  30817. mid = (mid + Math.imul(al7, bh4)) | 0;
  30818. mid = (mid + Math.imul(ah7, bl4)) | 0;
  30819. hi = (hi + Math.imul(ah7, bh4)) | 0;
  30820. lo = (lo + Math.imul(al6, bl5)) | 0;
  30821. mid = (mid + Math.imul(al6, bh5)) | 0;
  30822. mid = (mid + Math.imul(ah6, bl5)) | 0;
  30823. hi = (hi + Math.imul(ah6, bh5)) | 0;
  30824. lo = (lo + Math.imul(al5, bl6)) | 0;
  30825. mid = (mid + Math.imul(al5, bh6)) | 0;
  30826. mid = (mid + Math.imul(ah5, bl6)) | 0;
  30827. hi = (hi + Math.imul(ah5, bh6)) | 0;
  30828. lo = (lo + Math.imul(al4, bl7)) | 0;
  30829. mid = (mid + Math.imul(al4, bh7)) | 0;
  30830. mid = (mid + Math.imul(ah4, bl7)) | 0;
  30831. hi = (hi + Math.imul(ah4, bh7)) | 0;
  30832. lo = (lo + Math.imul(al3, bl8)) | 0;
  30833. mid = (mid + Math.imul(al3, bh8)) | 0;
  30834. mid = (mid + Math.imul(ah3, bl8)) | 0;
  30835. hi = (hi + Math.imul(ah3, bh8)) | 0;
  30836. lo = (lo + Math.imul(al2, bl9)) | 0;
  30837. mid = (mid + Math.imul(al2, bh9)) | 0;
  30838. mid = (mid + Math.imul(ah2, bl9)) | 0;
  30839. hi = (hi + Math.imul(ah2, bh9)) | 0;
  30840. var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30841. c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
  30842. w11 &= 0x3ffffff;
  30843. /* k = 12 */
  30844. lo = Math.imul(al9, bl3);
  30845. mid = Math.imul(al9, bh3);
  30846. mid = (mid + Math.imul(ah9, bl3)) | 0;
  30847. hi = Math.imul(ah9, bh3);
  30848. lo = (lo + Math.imul(al8, bl4)) | 0;
  30849. mid = (mid + Math.imul(al8, bh4)) | 0;
  30850. mid = (mid + Math.imul(ah8, bl4)) | 0;
  30851. hi = (hi + Math.imul(ah8, bh4)) | 0;
  30852. lo = (lo + Math.imul(al7, bl5)) | 0;
  30853. mid = (mid + Math.imul(al7, bh5)) | 0;
  30854. mid = (mid + Math.imul(ah7, bl5)) | 0;
  30855. hi = (hi + Math.imul(ah7, bh5)) | 0;
  30856. lo = (lo + Math.imul(al6, bl6)) | 0;
  30857. mid = (mid + Math.imul(al6, bh6)) | 0;
  30858. mid = (mid + Math.imul(ah6, bl6)) | 0;
  30859. hi = (hi + Math.imul(ah6, bh6)) | 0;
  30860. lo = (lo + Math.imul(al5, bl7)) | 0;
  30861. mid = (mid + Math.imul(al5, bh7)) | 0;
  30862. mid = (mid + Math.imul(ah5, bl7)) | 0;
  30863. hi = (hi + Math.imul(ah5, bh7)) | 0;
  30864. lo = (lo + Math.imul(al4, bl8)) | 0;
  30865. mid = (mid + Math.imul(al4, bh8)) | 0;
  30866. mid = (mid + Math.imul(ah4, bl8)) | 0;
  30867. hi = (hi + Math.imul(ah4, bh8)) | 0;
  30868. lo = (lo + Math.imul(al3, bl9)) | 0;
  30869. mid = (mid + Math.imul(al3, bh9)) | 0;
  30870. mid = (mid + Math.imul(ah3, bl9)) | 0;
  30871. hi = (hi + Math.imul(ah3, bh9)) | 0;
  30872. var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30873. c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
  30874. w12 &= 0x3ffffff;
  30875. /* k = 13 */
  30876. lo = Math.imul(al9, bl4);
  30877. mid = Math.imul(al9, bh4);
  30878. mid = (mid + Math.imul(ah9, bl4)) | 0;
  30879. hi = Math.imul(ah9, bh4);
  30880. lo = (lo + Math.imul(al8, bl5)) | 0;
  30881. mid = (mid + Math.imul(al8, bh5)) | 0;
  30882. mid = (mid + Math.imul(ah8, bl5)) | 0;
  30883. hi = (hi + Math.imul(ah8, bh5)) | 0;
  30884. lo = (lo + Math.imul(al7, bl6)) | 0;
  30885. mid = (mid + Math.imul(al7, bh6)) | 0;
  30886. mid = (mid + Math.imul(ah7, bl6)) | 0;
  30887. hi = (hi + Math.imul(ah7, bh6)) | 0;
  30888. lo = (lo + Math.imul(al6, bl7)) | 0;
  30889. mid = (mid + Math.imul(al6, bh7)) | 0;
  30890. mid = (mid + Math.imul(ah6, bl7)) | 0;
  30891. hi = (hi + Math.imul(ah6, bh7)) | 0;
  30892. lo = (lo + Math.imul(al5, bl8)) | 0;
  30893. mid = (mid + Math.imul(al5, bh8)) | 0;
  30894. mid = (mid + Math.imul(ah5, bl8)) | 0;
  30895. hi = (hi + Math.imul(ah5, bh8)) | 0;
  30896. lo = (lo + Math.imul(al4, bl9)) | 0;
  30897. mid = (mid + Math.imul(al4, bh9)) | 0;
  30898. mid = (mid + Math.imul(ah4, bl9)) | 0;
  30899. hi = (hi + Math.imul(ah4, bh9)) | 0;
  30900. var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30901. c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
  30902. w13 &= 0x3ffffff;
  30903. /* k = 14 */
  30904. lo = Math.imul(al9, bl5);
  30905. mid = Math.imul(al9, bh5);
  30906. mid = (mid + Math.imul(ah9, bl5)) | 0;
  30907. hi = Math.imul(ah9, bh5);
  30908. lo = (lo + Math.imul(al8, bl6)) | 0;
  30909. mid = (mid + Math.imul(al8, bh6)) | 0;
  30910. mid = (mid + Math.imul(ah8, bl6)) | 0;
  30911. hi = (hi + Math.imul(ah8, bh6)) | 0;
  30912. lo = (lo + Math.imul(al7, bl7)) | 0;
  30913. mid = (mid + Math.imul(al7, bh7)) | 0;
  30914. mid = (mid + Math.imul(ah7, bl7)) | 0;
  30915. hi = (hi + Math.imul(ah7, bh7)) | 0;
  30916. lo = (lo + Math.imul(al6, bl8)) | 0;
  30917. mid = (mid + Math.imul(al6, bh8)) | 0;
  30918. mid = (mid + Math.imul(ah6, bl8)) | 0;
  30919. hi = (hi + Math.imul(ah6, bh8)) | 0;
  30920. lo = (lo + Math.imul(al5, bl9)) | 0;
  30921. mid = (mid + Math.imul(al5, bh9)) | 0;
  30922. mid = (mid + Math.imul(ah5, bl9)) | 0;
  30923. hi = (hi + Math.imul(ah5, bh9)) | 0;
  30924. var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30925. c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
  30926. w14 &= 0x3ffffff;
  30927. /* k = 15 */
  30928. lo = Math.imul(al9, bl6);
  30929. mid = Math.imul(al9, bh6);
  30930. mid = (mid + Math.imul(ah9, bl6)) | 0;
  30931. hi = Math.imul(ah9, bh6);
  30932. lo = (lo + Math.imul(al8, bl7)) | 0;
  30933. mid = (mid + Math.imul(al8, bh7)) | 0;
  30934. mid = (mid + Math.imul(ah8, bl7)) | 0;
  30935. hi = (hi + Math.imul(ah8, bh7)) | 0;
  30936. lo = (lo + Math.imul(al7, bl8)) | 0;
  30937. mid = (mid + Math.imul(al7, bh8)) | 0;
  30938. mid = (mid + Math.imul(ah7, bl8)) | 0;
  30939. hi = (hi + Math.imul(ah7, bh8)) | 0;
  30940. lo = (lo + Math.imul(al6, bl9)) | 0;
  30941. mid = (mid + Math.imul(al6, bh9)) | 0;
  30942. mid = (mid + Math.imul(ah6, bl9)) | 0;
  30943. hi = (hi + Math.imul(ah6, bh9)) | 0;
  30944. var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30945. c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
  30946. w15 &= 0x3ffffff;
  30947. /* k = 16 */
  30948. lo = Math.imul(al9, bl7);
  30949. mid = Math.imul(al9, bh7);
  30950. mid = (mid + Math.imul(ah9, bl7)) | 0;
  30951. hi = Math.imul(ah9, bh7);
  30952. lo = (lo + Math.imul(al8, bl8)) | 0;
  30953. mid = (mid + Math.imul(al8, bh8)) | 0;
  30954. mid = (mid + Math.imul(ah8, bl8)) | 0;
  30955. hi = (hi + Math.imul(ah8, bh8)) | 0;
  30956. lo = (lo + Math.imul(al7, bl9)) | 0;
  30957. mid = (mid + Math.imul(al7, bh9)) | 0;
  30958. mid = (mid + Math.imul(ah7, bl9)) | 0;
  30959. hi = (hi + Math.imul(ah7, bh9)) | 0;
  30960. var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30961. c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
  30962. w16 &= 0x3ffffff;
  30963. /* k = 17 */
  30964. lo = Math.imul(al9, bl8);
  30965. mid = Math.imul(al9, bh8);
  30966. mid = (mid + Math.imul(ah9, bl8)) | 0;
  30967. hi = Math.imul(ah9, bh8);
  30968. lo = (lo + Math.imul(al8, bl9)) | 0;
  30969. mid = (mid + Math.imul(al8, bh9)) | 0;
  30970. mid = (mid + Math.imul(ah8, bl9)) | 0;
  30971. hi = (hi + Math.imul(ah8, bh9)) | 0;
  30972. var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30973. c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
  30974. w17 &= 0x3ffffff;
  30975. /* k = 18 */
  30976. lo = Math.imul(al9, bl9);
  30977. mid = Math.imul(al9, bh9);
  30978. mid = (mid + Math.imul(ah9, bl9)) | 0;
  30979. hi = Math.imul(ah9, bh9);
  30980. var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  30981. c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
  30982. w18 &= 0x3ffffff;
  30983. o[0] = w0;
  30984. o[1] = w1;
  30985. o[2] = w2;
  30986. o[3] = w3;
  30987. o[4] = w4;
  30988. o[5] = w5;
  30989. o[6] = w6;
  30990. o[7] = w7;
  30991. o[8] = w8;
  30992. o[9] = w9;
  30993. o[10] = w10;
  30994. o[11] = w11;
  30995. o[12] = w12;
  30996. o[13] = w13;
  30997. o[14] = w14;
  30998. o[15] = w15;
  30999. o[16] = w16;
  31000. o[17] = w17;
  31001. o[18] = w18;
  31002. if (c !== 0) {
  31003. o[19] = c;
  31004. out.length++;
  31005. }
  31006. return out;
  31007. };
  31008. // Polyfill comb
  31009. if (!Math.imul) {
  31010. comb10MulTo = smallMulTo;
  31011. }
  31012. function bigMulTo (self, num, out) {
  31013. out.negative = num.negative ^ self.negative;
  31014. out.length = self.length + num.length;
  31015. var carry = 0;
  31016. var hncarry = 0;
  31017. for (var k = 0; k < out.length - 1; k++) {
  31018. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  31019. // note that ncarry could be >= 0x3ffffff
  31020. var ncarry = hncarry;
  31021. hncarry = 0;
  31022. var rword = carry & 0x3ffffff;
  31023. var maxJ = Math.min(k, num.length - 1);
  31024. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  31025. var i = k - j;
  31026. var a = self.words[i] | 0;
  31027. var b = num.words[j] | 0;
  31028. var r = a * b;
  31029. var lo = r & 0x3ffffff;
  31030. ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
  31031. lo = (lo + rword) | 0;
  31032. rword = lo & 0x3ffffff;
  31033. ncarry = (ncarry + (lo >>> 26)) | 0;
  31034. hncarry += ncarry >>> 26;
  31035. ncarry &= 0x3ffffff;
  31036. }
  31037. out.words[k] = rword;
  31038. carry = ncarry;
  31039. ncarry = hncarry;
  31040. }
  31041. if (carry !== 0) {
  31042. out.words[k] = carry;
  31043. } else {
  31044. out.length--;
  31045. }
  31046. return out._strip();
  31047. }
  31048. function jumboMulTo (self, num, out) {
  31049. // Temporary disable, see https://github.com/indutny/bn.js/issues/211
  31050. // var fftm = new FFTM();
  31051. // return fftm.mulp(self, num, out);
  31052. return bigMulTo(self, num, out);
  31053. }
  31054. BN.prototype.mulTo = function mulTo (num, out) {
  31055. var res;
  31056. var len = this.length + num.length;
  31057. if (this.length === 10 && num.length === 10) {
  31058. res = comb10MulTo(this, num, out);
  31059. } else if (len < 63) {
  31060. res = smallMulTo(this, num, out);
  31061. } else if (len < 1024) {
  31062. res = bigMulTo(this, num, out);
  31063. } else {
  31064. res = jumboMulTo(this, num, out);
  31065. }
  31066. return res;
  31067. };
  31068. // Cooley-Tukey algorithm for FFT
  31069. // slightly revisited to rely on looping instead of recursion
  31070. function FFTM (x, y) {
  31071. this.x = x;
  31072. this.y = y;
  31073. }
  31074. FFTM.prototype.makeRBT = function makeRBT (N) {
  31075. var t = new Array(N);
  31076. var l = BN.prototype._countBits(N) - 1;
  31077. for (var i = 0; i < N; i++) {
  31078. t[i] = this.revBin(i, l, N);
  31079. }
  31080. return t;
  31081. };
  31082. // Returns binary-reversed representation of `x`
  31083. FFTM.prototype.revBin = function revBin (x, l, N) {
  31084. if (x === 0 || x === N - 1) return x;
  31085. var rb = 0;
  31086. for (var i = 0; i < l; i++) {
  31087. rb |= (x & 1) << (l - i - 1);
  31088. x >>= 1;
  31089. }
  31090. return rb;
  31091. };
  31092. // Performs "tweedling" phase, therefore 'emulating'
  31093. // behaviour of the recursive algorithm
  31094. FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
  31095. for (var i = 0; i < N; i++) {
  31096. rtws[i] = rws[rbt[i]];
  31097. itws[i] = iws[rbt[i]];
  31098. }
  31099. };
  31100. FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
  31101. this.permute(rbt, rws, iws, rtws, itws, N);
  31102. for (var s = 1; s < N; s <<= 1) {
  31103. var l = s << 1;
  31104. var rtwdf = Math.cos(2 * Math.PI / l);
  31105. var itwdf = Math.sin(2 * Math.PI / l);
  31106. for (var p = 0; p < N; p += l) {
  31107. var rtwdf_ = rtwdf;
  31108. var itwdf_ = itwdf;
  31109. for (var j = 0; j < s; j++) {
  31110. var re = rtws[p + j];
  31111. var ie = itws[p + j];
  31112. var ro = rtws[p + j + s];
  31113. var io = itws[p + j + s];
  31114. var rx = rtwdf_ * ro - itwdf_ * io;
  31115. io = rtwdf_ * io + itwdf_ * ro;
  31116. ro = rx;
  31117. rtws[p + j] = re + ro;
  31118. itws[p + j] = ie + io;
  31119. rtws[p + j + s] = re - ro;
  31120. itws[p + j + s] = ie - io;
  31121. /* jshint maxdepth : false */
  31122. if (j !== l) {
  31123. rx = rtwdf * rtwdf_ - itwdf * itwdf_;
  31124. itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
  31125. rtwdf_ = rx;
  31126. }
  31127. }
  31128. }
  31129. }
  31130. };
  31131. FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
  31132. var N = Math.max(m, n) | 1;
  31133. var odd = N & 1;
  31134. var i = 0;
  31135. for (N = N / 2 | 0; N; N = N >>> 1) {
  31136. i++;
  31137. }
  31138. return 1 << i + 1 + odd;
  31139. };
  31140. FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
  31141. if (N <= 1) return;
  31142. for (var i = 0; i < N / 2; i++) {
  31143. var t = rws[i];
  31144. rws[i] = rws[N - i - 1];
  31145. rws[N - i - 1] = t;
  31146. t = iws[i];
  31147. iws[i] = -iws[N - i - 1];
  31148. iws[N - i - 1] = -t;
  31149. }
  31150. };
  31151. FFTM.prototype.normalize13b = function normalize13b (ws, N) {
  31152. var carry = 0;
  31153. for (var i = 0; i < N / 2; i++) {
  31154. var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
  31155. Math.round(ws[2 * i] / N) +
  31156. carry;
  31157. ws[i] = w & 0x3ffffff;
  31158. if (w < 0x4000000) {
  31159. carry = 0;
  31160. } else {
  31161. carry = w / 0x4000000 | 0;
  31162. }
  31163. }
  31164. return ws;
  31165. };
  31166. FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
  31167. var carry = 0;
  31168. for (var i = 0; i < len; i++) {
  31169. carry = carry + (ws[i] | 0);
  31170. rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
  31171. rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
  31172. }
  31173. // Pad with zeroes
  31174. for (i = 2 * len; i < N; ++i) {
  31175. rws[i] = 0;
  31176. }
  31177. assert(carry === 0);
  31178. assert((carry & ~0x1fff) === 0);
  31179. };
  31180. FFTM.prototype.stub = function stub (N) {
  31181. var ph = new Array(N);
  31182. for (var i = 0; i < N; i++) {
  31183. ph[i] = 0;
  31184. }
  31185. return ph;
  31186. };
  31187. FFTM.prototype.mulp = function mulp (x, y, out) {
  31188. var N = 2 * this.guessLen13b(x.length, y.length);
  31189. var rbt = this.makeRBT(N);
  31190. var _ = this.stub(N);
  31191. var rws = new Array(N);
  31192. var rwst = new Array(N);
  31193. var iwst = new Array(N);
  31194. var nrws = new Array(N);
  31195. var nrwst = new Array(N);
  31196. var niwst = new Array(N);
  31197. var rmws = out.words;
  31198. rmws.length = N;
  31199. this.convert13b(x.words, x.length, rws, N);
  31200. this.convert13b(y.words, y.length, nrws, N);
  31201. this.transform(rws, _, rwst, iwst, N, rbt);
  31202. this.transform(nrws, _, nrwst, niwst, N, rbt);
  31203. for (var i = 0; i < N; i++) {
  31204. var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
  31205. iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
  31206. rwst[i] = rx;
  31207. }
  31208. this.conjugate(rwst, iwst, N);
  31209. this.transform(rwst, iwst, rmws, _, N, rbt);
  31210. this.conjugate(rmws, _, N);
  31211. this.normalize13b(rmws, N);
  31212. out.negative = x.negative ^ y.negative;
  31213. out.length = x.length + y.length;
  31214. return out._strip();
  31215. };
  31216. // Multiply `this` by `num`
  31217. BN.prototype.mul = function mul (num) {
  31218. var out = new BN(null);
  31219. out.words = new Array(this.length + num.length);
  31220. return this.mulTo(num, out);
  31221. };
  31222. // Multiply employing FFT
  31223. BN.prototype.mulf = function mulf (num) {
  31224. var out = new BN(null);
  31225. out.words = new Array(this.length + num.length);
  31226. return jumboMulTo(this, num, out);
  31227. };
  31228. // In-place Multiplication
  31229. BN.prototype.imul = function imul (num) {
  31230. return this.clone().mulTo(num, this);
  31231. };
  31232. BN.prototype.imuln = function imuln (num) {
  31233. var isNegNum = num < 0;
  31234. if (isNegNum) num = -num;
  31235. assert(typeof num === 'number');
  31236. assert(num < 0x4000000);
  31237. // Carry
  31238. var carry = 0;
  31239. for (var i = 0; i < this.length; i++) {
  31240. var w = (this.words[i] | 0) * num;
  31241. var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
  31242. carry >>= 26;
  31243. carry += (w / 0x4000000) | 0;
  31244. // NOTE: lo is 27bit maximum
  31245. carry += lo >>> 26;
  31246. this.words[i] = lo & 0x3ffffff;
  31247. }
  31248. if (carry !== 0) {
  31249. this.words[i] = carry;
  31250. this.length++;
  31251. }
  31252. return isNegNum ? this.ineg() : this;
  31253. };
  31254. BN.prototype.muln = function muln (num) {
  31255. return this.clone().imuln(num);
  31256. };
  31257. // `this` * `this`
  31258. BN.prototype.sqr = function sqr () {
  31259. return this.mul(this);
  31260. };
  31261. // `this` * `this` in-place
  31262. BN.prototype.isqr = function isqr () {
  31263. return this.imul(this.clone());
  31264. };
  31265. // Math.pow(`this`, `num`)
  31266. BN.prototype.pow = function pow (num) {
  31267. var w = toBitArray(num);
  31268. if (w.length === 0) return new BN(1);
  31269. // Skip leading zeroes
  31270. var res = this;
  31271. for (var i = 0; i < w.length; i++, res = res.sqr()) {
  31272. if (w[i] !== 0) break;
  31273. }
  31274. if (++i < w.length) {
  31275. for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
  31276. if (w[i] === 0) continue;
  31277. res = res.mul(q);
  31278. }
  31279. }
  31280. return res;
  31281. };
  31282. // Shift-left in-place
  31283. BN.prototype.iushln = function iushln (bits) {
  31284. assert(typeof bits === 'number' && bits >= 0);
  31285. var r = bits % 26;
  31286. var s = (bits - r) / 26;
  31287. var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
  31288. var i;
  31289. if (r !== 0) {
  31290. var carry = 0;
  31291. for (i = 0; i < this.length; i++) {
  31292. var newCarry = this.words[i] & carryMask;
  31293. var c = ((this.words[i] | 0) - newCarry) << r;
  31294. this.words[i] = c | carry;
  31295. carry = newCarry >>> (26 - r);
  31296. }
  31297. if (carry) {
  31298. this.words[i] = carry;
  31299. this.length++;
  31300. }
  31301. }
  31302. if (s !== 0) {
  31303. for (i = this.length - 1; i >= 0; i--) {
  31304. this.words[i + s] = this.words[i];
  31305. }
  31306. for (i = 0; i < s; i++) {
  31307. this.words[i] = 0;
  31308. }
  31309. this.length += s;
  31310. }
  31311. return this._strip();
  31312. };
  31313. BN.prototype.ishln = function ishln (bits) {
  31314. // TODO(indutny): implement me
  31315. assert(this.negative === 0);
  31316. return this.iushln(bits);
  31317. };
  31318. // Shift-right in-place
  31319. // NOTE: `hint` is a lowest bit before trailing zeroes
  31320. // NOTE: if `extended` is present - it will be filled with destroyed bits
  31321. BN.prototype.iushrn = function iushrn (bits, hint, extended) {
  31322. assert(typeof bits === 'number' && bits >= 0);
  31323. var h;
  31324. if (hint) {
  31325. h = (hint - (hint % 26)) / 26;
  31326. } else {
  31327. h = 0;
  31328. }
  31329. var r = bits % 26;
  31330. var s = Math.min((bits - r) / 26, this.length);
  31331. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  31332. var maskedWords = extended;
  31333. h -= s;
  31334. h = Math.max(0, h);
  31335. // Extended mode, copy masked part
  31336. if (maskedWords) {
  31337. for (var i = 0; i < s; i++) {
  31338. maskedWords.words[i] = this.words[i];
  31339. }
  31340. maskedWords.length = s;
  31341. }
  31342. if (s === 0) {
  31343. // No-op, we should not move anything at all
  31344. } else if (this.length > s) {
  31345. this.length -= s;
  31346. for (i = 0; i < this.length; i++) {
  31347. this.words[i] = this.words[i + s];
  31348. }
  31349. } else {
  31350. this.words[0] = 0;
  31351. this.length = 1;
  31352. }
  31353. var carry = 0;
  31354. for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
  31355. var word = this.words[i] | 0;
  31356. this.words[i] = (carry << (26 - r)) | (word >>> r);
  31357. carry = word & mask;
  31358. }
  31359. // Push carried bits as a mask
  31360. if (maskedWords && carry !== 0) {
  31361. maskedWords.words[maskedWords.length++] = carry;
  31362. }
  31363. if (this.length === 0) {
  31364. this.words[0] = 0;
  31365. this.length = 1;
  31366. }
  31367. return this._strip();
  31368. };
  31369. BN.prototype.ishrn = function ishrn (bits, hint, extended) {
  31370. // TODO(indutny): implement me
  31371. assert(this.negative === 0);
  31372. return this.iushrn(bits, hint, extended);
  31373. };
  31374. // Shift-left
  31375. BN.prototype.shln = function shln (bits) {
  31376. return this.clone().ishln(bits);
  31377. };
  31378. BN.prototype.ushln = function ushln (bits) {
  31379. return this.clone().iushln(bits);
  31380. };
  31381. // Shift-right
  31382. BN.prototype.shrn = function shrn (bits) {
  31383. return this.clone().ishrn(bits);
  31384. };
  31385. BN.prototype.ushrn = function ushrn (bits) {
  31386. return this.clone().iushrn(bits);
  31387. };
  31388. // Test if n bit is set
  31389. BN.prototype.testn = function testn (bit) {
  31390. assert(typeof bit === 'number' && bit >= 0);
  31391. var r = bit % 26;
  31392. var s = (bit - r) / 26;
  31393. var q = 1 << r;
  31394. // Fast case: bit is much higher than all existing words
  31395. if (this.length <= s) return false;
  31396. // Check bit and return
  31397. var w = this.words[s];
  31398. return !!(w & q);
  31399. };
  31400. // Return only lowers bits of number (in-place)
  31401. BN.prototype.imaskn = function imaskn (bits) {
  31402. assert(typeof bits === 'number' && bits >= 0);
  31403. var r = bits % 26;
  31404. var s = (bits - r) / 26;
  31405. assert(this.negative === 0, 'imaskn works only with positive numbers');
  31406. if (this.length <= s) {
  31407. return this;
  31408. }
  31409. if (r !== 0) {
  31410. s++;
  31411. }
  31412. this.length = Math.min(s, this.length);
  31413. if (r !== 0) {
  31414. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  31415. this.words[this.length - 1] &= mask;
  31416. }
  31417. return this._strip();
  31418. };
  31419. // Return only lowers bits of number
  31420. BN.prototype.maskn = function maskn (bits) {
  31421. return this.clone().imaskn(bits);
  31422. };
  31423. // Add plain number `num` to `this`
  31424. BN.prototype.iaddn = function iaddn (num) {
  31425. assert(typeof num === 'number');
  31426. assert(num < 0x4000000);
  31427. if (num < 0) return this.isubn(-num);
  31428. // Possible sign change
  31429. if (this.negative !== 0) {
  31430. if (this.length === 1 && (this.words[0] | 0) <= num) {
  31431. this.words[0] = num - (this.words[0] | 0);
  31432. this.negative = 0;
  31433. return this;
  31434. }
  31435. this.negative = 0;
  31436. this.isubn(num);
  31437. this.negative = 1;
  31438. return this;
  31439. }
  31440. // Add without checks
  31441. return this._iaddn(num);
  31442. };
  31443. BN.prototype._iaddn = function _iaddn (num) {
  31444. this.words[0] += num;
  31445. // Carry
  31446. for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
  31447. this.words[i] -= 0x4000000;
  31448. if (i === this.length - 1) {
  31449. this.words[i + 1] = 1;
  31450. } else {
  31451. this.words[i + 1]++;
  31452. }
  31453. }
  31454. this.length = Math.max(this.length, i + 1);
  31455. return this;
  31456. };
  31457. // Subtract plain number `num` from `this`
  31458. BN.prototype.isubn = function isubn (num) {
  31459. assert(typeof num === 'number');
  31460. assert(num < 0x4000000);
  31461. if (num < 0) return this.iaddn(-num);
  31462. if (this.negative !== 0) {
  31463. this.negative = 0;
  31464. this.iaddn(num);
  31465. this.negative = 1;
  31466. return this;
  31467. }
  31468. this.words[0] -= num;
  31469. if (this.length === 1 && this.words[0] < 0) {
  31470. this.words[0] = -this.words[0];
  31471. this.negative = 1;
  31472. } else {
  31473. // Carry
  31474. for (var i = 0; i < this.length && this.words[i] < 0; i++) {
  31475. this.words[i] += 0x4000000;
  31476. this.words[i + 1] -= 1;
  31477. }
  31478. }
  31479. return this._strip();
  31480. };
  31481. BN.prototype.addn = function addn (num) {
  31482. return this.clone().iaddn(num);
  31483. };
  31484. BN.prototype.subn = function subn (num) {
  31485. return this.clone().isubn(num);
  31486. };
  31487. BN.prototype.iabs = function iabs () {
  31488. this.negative = 0;
  31489. return this;
  31490. };
  31491. BN.prototype.abs = function abs () {
  31492. return this.clone().iabs();
  31493. };
  31494. BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
  31495. var len = num.length + shift;
  31496. var i;
  31497. this._expand(len);
  31498. var w;
  31499. var carry = 0;
  31500. for (i = 0; i < num.length; i++) {
  31501. w = (this.words[i + shift] | 0) + carry;
  31502. var right = (num.words[i] | 0) * mul;
  31503. w -= right & 0x3ffffff;
  31504. carry = (w >> 26) - ((right / 0x4000000) | 0);
  31505. this.words[i + shift] = w & 0x3ffffff;
  31506. }
  31507. for (; i < this.length - shift; i++) {
  31508. w = (this.words[i + shift] | 0) + carry;
  31509. carry = w >> 26;
  31510. this.words[i + shift] = w & 0x3ffffff;
  31511. }
  31512. if (carry === 0) return this._strip();
  31513. // Subtraction overflow
  31514. assert(carry === -1);
  31515. carry = 0;
  31516. for (i = 0; i < this.length; i++) {
  31517. w = -(this.words[i] | 0) + carry;
  31518. carry = w >> 26;
  31519. this.words[i] = w & 0x3ffffff;
  31520. }
  31521. this.negative = 1;
  31522. return this._strip();
  31523. };
  31524. BN.prototype._wordDiv = function _wordDiv (num, mode) {
  31525. var shift = this.length - num.length;
  31526. var a = this.clone();
  31527. var b = num;
  31528. // Normalize
  31529. var bhi = b.words[b.length - 1] | 0;
  31530. var bhiBits = this._countBits(bhi);
  31531. shift = 26 - bhiBits;
  31532. if (shift !== 0) {
  31533. b = b.ushln(shift);
  31534. a.iushln(shift);
  31535. bhi = b.words[b.length - 1] | 0;
  31536. }
  31537. // Initialize quotient
  31538. var m = a.length - b.length;
  31539. var q;
  31540. if (mode !== 'mod') {
  31541. q = new BN(null);
  31542. q.length = m + 1;
  31543. q.words = new Array(q.length);
  31544. for (var i = 0; i < q.length; i++) {
  31545. q.words[i] = 0;
  31546. }
  31547. }
  31548. var diff = a.clone()._ishlnsubmul(b, 1, m);
  31549. if (diff.negative === 0) {
  31550. a = diff;
  31551. if (q) {
  31552. q.words[m] = 1;
  31553. }
  31554. }
  31555. for (var j = m - 1; j >= 0; j--) {
  31556. var qj = (a.words[b.length + j] | 0) * 0x4000000 +
  31557. (a.words[b.length + j - 1] | 0);
  31558. // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
  31559. // (0x7ffffff)
  31560. qj = Math.min((qj / bhi) | 0, 0x3ffffff);
  31561. a._ishlnsubmul(b, qj, j);
  31562. while (a.negative !== 0) {
  31563. qj--;
  31564. a.negative = 0;
  31565. a._ishlnsubmul(b, 1, j);
  31566. if (!a.isZero()) {
  31567. a.negative ^= 1;
  31568. }
  31569. }
  31570. if (q) {
  31571. q.words[j] = qj;
  31572. }
  31573. }
  31574. if (q) {
  31575. q._strip();
  31576. }
  31577. a._strip();
  31578. // Denormalize
  31579. if (mode !== 'div' && shift !== 0) {
  31580. a.iushrn(shift);
  31581. }
  31582. return {
  31583. div: q || null,
  31584. mod: a
  31585. };
  31586. };
  31587. // NOTE: 1) `mode` can be set to `mod` to request mod only,
  31588. // to `div` to request div only, or be absent to
  31589. // request both div & mod
  31590. // 2) `positive` is true if unsigned mod is requested
  31591. BN.prototype.divmod = function divmod (num, mode, positive) {
  31592. assert(!num.isZero());
  31593. if (this.isZero()) {
  31594. return {
  31595. div: new BN(0),
  31596. mod: new BN(0)
  31597. };
  31598. }
  31599. var div, mod, res;
  31600. if (this.negative !== 0 && num.negative === 0) {
  31601. res = this.neg().divmod(num, mode);
  31602. if (mode !== 'mod') {
  31603. div = res.div.neg();
  31604. }
  31605. if (mode !== 'div') {
  31606. mod = res.mod.neg();
  31607. if (positive && mod.negative !== 0) {
  31608. mod.iadd(num);
  31609. }
  31610. }
  31611. return {
  31612. div: div,
  31613. mod: mod
  31614. };
  31615. }
  31616. if (this.negative === 0 && num.negative !== 0) {
  31617. res = this.divmod(num.neg(), mode);
  31618. if (mode !== 'mod') {
  31619. div = res.div.neg();
  31620. }
  31621. return {
  31622. div: div,
  31623. mod: res.mod
  31624. };
  31625. }
  31626. if ((this.negative & num.negative) !== 0) {
  31627. res = this.neg().divmod(num.neg(), mode);
  31628. if (mode !== 'div') {
  31629. mod = res.mod.neg();
  31630. if (positive && mod.negative !== 0) {
  31631. mod.isub(num);
  31632. }
  31633. }
  31634. return {
  31635. div: res.div,
  31636. mod: mod
  31637. };
  31638. }
  31639. // Both numbers are positive at this point
  31640. // Strip both numbers to approximate shift value
  31641. if (num.length > this.length || this.cmp(num) < 0) {
  31642. return {
  31643. div: new BN(0),
  31644. mod: this
  31645. };
  31646. }
  31647. // Very short reduction
  31648. if (num.length === 1) {
  31649. if (mode === 'div') {
  31650. return {
  31651. div: this.divn(num.words[0]),
  31652. mod: null
  31653. };
  31654. }
  31655. if (mode === 'mod') {
  31656. return {
  31657. div: null,
  31658. mod: new BN(this.modrn(num.words[0]))
  31659. };
  31660. }
  31661. return {
  31662. div: this.divn(num.words[0]),
  31663. mod: new BN(this.modrn(num.words[0]))
  31664. };
  31665. }
  31666. return this._wordDiv(num, mode);
  31667. };
  31668. // Find `this` / `num`
  31669. BN.prototype.div = function div (num) {
  31670. return this.divmod(num, 'div', false).div;
  31671. };
  31672. // Find `this` % `num`
  31673. BN.prototype.mod = function mod (num) {
  31674. return this.divmod(num, 'mod', false).mod;
  31675. };
  31676. BN.prototype.umod = function umod (num) {
  31677. return this.divmod(num, 'mod', true).mod;
  31678. };
  31679. // Find Round(`this` / `num`)
  31680. BN.prototype.divRound = function divRound (num) {
  31681. var dm = this.divmod(num);
  31682. // Fast case - exact division
  31683. if (dm.mod.isZero()) return dm.div;
  31684. var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
  31685. var half = num.ushrn(1);
  31686. var r2 = num.andln(1);
  31687. var cmp = mod.cmp(half);
  31688. // Round down
  31689. if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;
  31690. // Round up
  31691. return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  31692. };
  31693. BN.prototype.modrn = function modrn (num) {
  31694. var isNegNum = num < 0;
  31695. if (isNegNum) num = -num;
  31696. assert(num <= 0x3ffffff);
  31697. var p = (1 << 26) % num;
  31698. var acc = 0;
  31699. for (var i = this.length - 1; i >= 0; i--) {
  31700. acc = (p * acc + (this.words[i] | 0)) % num;
  31701. }
  31702. return isNegNum ? -acc : acc;
  31703. };
  31704. // WARNING: DEPRECATED
  31705. BN.prototype.modn = function modn (num) {
  31706. return this.modrn(num);
  31707. };
  31708. // In-place division by number
  31709. BN.prototype.idivn = function idivn (num) {
  31710. var isNegNum = num < 0;
  31711. if (isNegNum) num = -num;
  31712. assert(num <= 0x3ffffff);
  31713. var carry = 0;
  31714. for (var i = this.length - 1; i >= 0; i--) {
  31715. var w = (this.words[i] | 0) + carry * 0x4000000;
  31716. this.words[i] = (w / num) | 0;
  31717. carry = w % num;
  31718. }
  31719. this._strip();
  31720. return isNegNum ? this.ineg() : this;
  31721. };
  31722. BN.prototype.divn = function divn (num) {
  31723. return this.clone().idivn(num);
  31724. };
  31725. BN.prototype.egcd = function egcd (p) {
  31726. assert(p.negative === 0);
  31727. assert(!p.isZero());
  31728. var x = this;
  31729. var y = p.clone();
  31730. if (x.negative !== 0) {
  31731. x = x.umod(p);
  31732. } else {
  31733. x = x.clone();
  31734. }
  31735. // A * x + B * y = x
  31736. var A = new BN(1);
  31737. var B = new BN(0);
  31738. // C * x + D * y = y
  31739. var C = new BN(0);
  31740. var D = new BN(1);
  31741. var g = 0;
  31742. while (x.isEven() && y.isEven()) {
  31743. x.iushrn(1);
  31744. y.iushrn(1);
  31745. ++g;
  31746. }
  31747. var yp = y.clone();
  31748. var xp = x.clone();
  31749. while (!x.isZero()) {
  31750. for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  31751. if (i > 0) {
  31752. x.iushrn(i);
  31753. while (i-- > 0) {
  31754. if (A.isOdd() || B.isOdd()) {
  31755. A.iadd(yp);
  31756. B.isub(xp);
  31757. }
  31758. A.iushrn(1);
  31759. B.iushrn(1);
  31760. }
  31761. }
  31762. for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  31763. if (j > 0) {
  31764. y.iushrn(j);
  31765. while (j-- > 0) {
  31766. if (C.isOdd() || D.isOdd()) {
  31767. C.iadd(yp);
  31768. D.isub(xp);
  31769. }
  31770. C.iushrn(1);
  31771. D.iushrn(1);
  31772. }
  31773. }
  31774. if (x.cmp(y) >= 0) {
  31775. x.isub(y);
  31776. A.isub(C);
  31777. B.isub(D);
  31778. } else {
  31779. y.isub(x);
  31780. C.isub(A);
  31781. D.isub(B);
  31782. }
  31783. }
  31784. return {
  31785. a: C,
  31786. b: D,
  31787. gcd: y.iushln(g)
  31788. };
  31789. };
  31790. // This is reduced incarnation of the binary EEA
  31791. // above, designated to invert members of the
  31792. // _prime_ fields F(p) at a maximal speed
  31793. BN.prototype._invmp = function _invmp (p) {
  31794. assert(p.negative === 0);
  31795. assert(!p.isZero());
  31796. var a = this;
  31797. var b = p.clone();
  31798. if (a.negative !== 0) {
  31799. a = a.umod(p);
  31800. } else {
  31801. a = a.clone();
  31802. }
  31803. var x1 = new BN(1);
  31804. var x2 = new BN(0);
  31805. var delta = b.clone();
  31806. while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
  31807. for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  31808. if (i > 0) {
  31809. a.iushrn(i);
  31810. while (i-- > 0) {
  31811. if (x1.isOdd()) {
  31812. x1.iadd(delta);
  31813. }
  31814. x1.iushrn(1);
  31815. }
  31816. }
  31817. for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  31818. if (j > 0) {
  31819. b.iushrn(j);
  31820. while (j-- > 0) {
  31821. if (x2.isOdd()) {
  31822. x2.iadd(delta);
  31823. }
  31824. x2.iushrn(1);
  31825. }
  31826. }
  31827. if (a.cmp(b) >= 0) {
  31828. a.isub(b);
  31829. x1.isub(x2);
  31830. } else {
  31831. b.isub(a);
  31832. x2.isub(x1);
  31833. }
  31834. }
  31835. var res;
  31836. if (a.cmpn(1) === 0) {
  31837. res = x1;
  31838. } else {
  31839. res = x2;
  31840. }
  31841. if (res.cmpn(0) < 0) {
  31842. res.iadd(p);
  31843. }
  31844. return res;
  31845. };
  31846. BN.prototype.gcd = function gcd (num) {
  31847. if (this.isZero()) return num.abs();
  31848. if (num.isZero()) return this.abs();
  31849. var a = this.clone();
  31850. var b = num.clone();
  31851. a.negative = 0;
  31852. b.negative = 0;
  31853. // Remove common factor of two
  31854. for (var shift = 0; a.isEven() && b.isEven(); shift++) {
  31855. a.iushrn(1);
  31856. b.iushrn(1);
  31857. }
  31858. do {
  31859. while (a.isEven()) {
  31860. a.iushrn(1);
  31861. }
  31862. while (b.isEven()) {
  31863. b.iushrn(1);
  31864. }
  31865. var r = a.cmp(b);
  31866. if (r < 0) {
  31867. // Swap `a` and `b` to make `a` always bigger than `b`
  31868. var t = a;
  31869. a = b;
  31870. b = t;
  31871. } else if (r === 0 || b.cmpn(1) === 0) {
  31872. break;
  31873. }
  31874. a.isub(b);
  31875. } while (true);
  31876. return b.iushln(shift);
  31877. };
  31878. // Invert number in the field F(num)
  31879. BN.prototype.invm = function invm (num) {
  31880. return this.egcd(num).a.umod(num);
  31881. };
  31882. BN.prototype.isEven = function isEven () {
  31883. return (this.words[0] & 1) === 0;
  31884. };
  31885. BN.prototype.isOdd = function isOdd () {
  31886. return (this.words[0] & 1) === 1;
  31887. };
  31888. // And first word and num
  31889. BN.prototype.andln = function andln (num) {
  31890. return this.words[0] & num;
  31891. };
  31892. // Increment at the bit position in-line
  31893. BN.prototype.bincn = function bincn (bit) {
  31894. assert(typeof bit === 'number');
  31895. var r = bit % 26;
  31896. var s = (bit - r) / 26;
  31897. var q = 1 << r;
  31898. // Fast case: bit is much higher than all existing words
  31899. if (this.length <= s) {
  31900. this._expand(s + 1);
  31901. this.words[s] |= q;
  31902. return this;
  31903. }
  31904. // Add bit and propagate, if needed
  31905. var carry = q;
  31906. for (var i = s; carry !== 0 && i < this.length; i++) {
  31907. var w = this.words[i] | 0;
  31908. w += carry;
  31909. carry = w >>> 26;
  31910. w &= 0x3ffffff;
  31911. this.words[i] = w;
  31912. }
  31913. if (carry !== 0) {
  31914. this.words[i] = carry;
  31915. this.length++;
  31916. }
  31917. return this;
  31918. };
  31919. BN.prototype.isZero = function isZero () {
  31920. return this.length === 1 && this.words[0] === 0;
  31921. };
  31922. BN.prototype.cmpn = function cmpn (num) {
  31923. var negative = num < 0;
  31924. if (this.negative !== 0 && !negative) return -1;
  31925. if (this.negative === 0 && negative) return 1;
  31926. this._strip();
  31927. var res;
  31928. if (this.length > 1) {
  31929. res = 1;
  31930. } else {
  31931. if (negative) {
  31932. num = -num;
  31933. }
  31934. assert(num <= 0x3ffffff, 'Number is too big');
  31935. var w = this.words[0] | 0;
  31936. res = w === num ? 0 : w < num ? -1 : 1;
  31937. }
  31938. if (this.negative !== 0) return -res | 0;
  31939. return res;
  31940. };
  31941. // Compare two numbers and return:
  31942. // 1 - if `this` > `num`
  31943. // 0 - if `this` == `num`
  31944. // -1 - if `this` < `num`
  31945. BN.prototype.cmp = function cmp (num) {
  31946. if (this.negative !== 0 && num.negative === 0) return -1;
  31947. if (this.negative === 0 && num.negative !== 0) return 1;
  31948. var res = this.ucmp(num);
  31949. if (this.negative !== 0) return -res | 0;
  31950. return res;
  31951. };
  31952. // Unsigned comparison
  31953. BN.prototype.ucmp = function ucmp (num) {
  31954. // At this point both numbers have the same sign
  31955. if (this.length > num.length) return 1;
  31956. if (this.length < num.length) return -1;
  31957. var res = 0;
  31958. for (var i = this.length - 1; i >= 0; i--) {
  31959. var a = this.words[i] | 0;
  31960. var b = num.words[i] | 0;
  31961. if (a === b) continue;
  31962. if (a < b) {
  31963. res = -1;
  31964. } else if (a > b) {
  31965. res = 1;
  31966. }
  31967. break;
  31968. }
  31969. return res;
  31970. };
  31971. BN.prototype.gtn = function gtn (num) {
  31972. return this.cmpn(num) === 1;
  31973. };
  31974. BN.prototype.gt = function gt (num) {
  31975. return this.cmp(num) === 1;
  31976. };
  31977. BN.prototype.gten = function gten (num) {
  31978. return this.cmpn(num) >= 0;
  31979. };
  31980. BN.prototype.gte = function gte (num) {
  31981. return this.cmp(num) >= 0;
  31982. };
  31983. BN.prototype.ltn = function ltn (num) {
  31984. return this.cmpn(num) === -1;
  31985. };
  31986. BN.prototype.lt = function lt (num) {
  31987. return this.cmp(num) === -1;
  31988. };
  31989. BN.prototype.lten = function lten (num) {
  31990. return this.cmpn(num) <= 0;
  31991. };
  31992. BN.prototype.lte = function lte (num) {
  31993. return this.cmp(num) <= 0;
  31994. };
  31995. BN.prototype.eqn = function eqn (num) {
  31996. return this.cmpn(num) === 0;
  31997. };
  31998. BN.prototype.eq = function eq (num) {
  31999. return this.cmp(num) === 0;
  32000. };
  32001. //
  32002. // A reduce context, could be using montgomery or something better, depending
  32003. // on the `m` itself.
  32004. //
  32005. BN.red = function red (num) {
  32006. return new Red(num);
  32007. };
  32008. BN.prototype.toRed = function toRed (ctx) {
  32009. assert(!this.red, 'Already a number in reduction context');
  32010. assert(this.negative === 0, 'red works only with positives');
  32011. return ctx.convertTo(this)._forceRed(ctx);
  32012. };
  32013. BN.prototype.fromRed = function fromRed () {
  32014. assert(this.red, 'fromRed works only with numbers in reduction context');
  32015. return this.red.convertFrom(this);
  32016. };
  32017. BN.prototype._forceRed = function _forceRed (ctx) {
  32018. this.red = ctx;
  32019. return this;
  32020. };
  32021. BN.prototype.forceRed = function forceRed (ctx) {
  32022. assert(!this.red, 'Already a number in reduction context');
  32023. return this._forceRed(ctx);
  32024. };
  32025. BN.prototype.redAdd = function redAdd (num) {
  32026. assert(this.red, 'redAdd works only with red numbers');
  32027. return this.red.add(this, num);
  32028. };
  32029. BN.prototype.redIAdd = function redIAdd (num) {
  32030. assert(this.red, 'redIAdd works only with red numbers');
  32031. return this.red.iadd(this, num);
  32032. };
  32033. BN.prototype.redSub = function redSub (num) {
  32034. assert(this.red, 'redSub works only with red numbers');
  32035. return this.red.sub(this, num);
  32036. };
  32037. BN.prototype.redISub = function redISub (num) {
  32038. assert(this.red, 'redISub works only with red numbers');
  32039. return this.red.isub(this, num);
  32040. };
  32041. BN.prototype.redShl = function redShl (num) {
  32042. assert(this.red, 'redShl works only with red numbers');
  32043. return this.red.shl(this, num);
  32044. };
  32045. BN.prototype.redMul = function redMul (num) {
  32046. assert(this.red, 'redMul works only with red numbers');
  32047. this.red._verify2(this, num);
  32048. return this.red.mul(this, num);
  32049. };
  32050. BN.prototype.redIMul = function redIMul (num) {
  32051. assert(this.red, 'redMul works only with red numbers');
  32052. this.red._verify2(this, num);
  32053. return this.red.imul(this, num);
  32054. };
  32055. BN.prototype.redSqr = function redSqr () {
  32056. assert(this.red, 'redSqr works only with red numbers');
  32057. this.red._verify1(this);
  32058. return this.red.sqr(this);
  32059. };
  32060. BN.prototype.redISqr = function redISqr () {
  32061. assert(this.red, 'redISqr works only with red numbers');
  32062. this.red._verify1(this);
  32063. return this.red.isqr(this);
  32064. };
  32065. // Square root over p
  32066. BN.prototype.redSqrt = function redSqrt () {
  32067. assert(this.red, 'redSqrt works only with red numbers');
  32068. this.red._verify1(this);
  32069. return this.red.sqrt(this);
  32070. };
  32071. BN.prototype.redInvm = function redInvm () {
  32072. assert(this.red, 'redInvm works only with red numbers');
  32073. this.red._verify1(this);
  32074. return this.red.invm(this);
  32075. };
  32076. // Return negative clone of `this` % `red modulo`
  32077. BN.prototype.redNeg = function redNeg () {
  32078. assert(this.red, 'redNeg works only with red numbers');
  32079. this.red._verify1(this);
  32080. return this.red.neg(this);
  32081. };
  32082. BN.prototype.redPow = function redPow (num) {
  32083. assert(this.red && !num.red, 'redPow(normalNum)');
  32084. this.red._verify1(this);
  32085. return this.red.pow(this, num);
  32086. };
  32087. // Prime numbers with efficient reduction
  32088. var primes = {
  32089. k256: null,
  32090. p224: null,
  32091. p192: null,
  32092. p25519: null
  32093. };
  32094. // Pseudo-Mersenne prime
  32095. function MPrime (name, p) {
  32096. // P = 2 ^ N - K
  32097. this.name = name;
  32098. this.p = new BN(p, 16);
  32099. this.n = this.p.bitLength();
  32100. this.k = new BN(1).iushln(this.n).isub(this.p);
  32101. this.tmp = this._tmp();
  32102. }
  32103. MPrime.prototype._tmp = function _tmp () {
  32104. var tmp = new BN(null);
  32105. tmp.words = new Array(Math.ceil(this.n / 13));
  32106. return tmp;
  32107. };
  32108. MPrime.prototype.ireduce = function ireduce (num) {
  32109. // Assumes that `num` is less than `P^2`
  32110. // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
  32111. var r = num;
  32112. var rlen;
  32113. do {
  32114. this.split(r, this.tmp);
  32115. r = this.imulK(r);
  32116. r = r.iadd(this.tmp);
  32117. rlen = r.bitLength();
  32118. } while (rlen > this.n);
  32119. var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
  32120. if (cmp === 0) {
  32121. r.words[0] = 0;
  32122. r.length = 1;
  32123. } else if (cmp > 0) {
  32124. r.isub(this.p);
  32125. } else {
  32126. if (r.strip !== undefined) {
  32127. // r is a BN v4 instance
  32128. r.strip();
  32129. } else {
  32130. // r is a BN v5 instance
  32131. r._strip();
  32132. }
  32133. }
  32134. return r;
  32135. };
  32136. MPrime.prototype.split = function split (input, out) {
  32137. input.iushrn(this.n, 0, out);
  32138. };
  32139. MPrime.prototype.imulK = function imulK (num) {
  32140. return num.imul(this.k);
  32141. };
  32142. function K256 () {
  32143. MPrime.call(
  32144. this,
  32145. 'k256',
  32146. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  32147. }
  32148. inherits(K256, MPrime);
  32149. K256.prototype.split = function split (input, output) {
  32150. // 256 = 9 * 26 + 22
  32151. var mask = 0x3fffff;
  32152. var outLen = Math.min(input.length, 9);
  32153. for (var i = 0; i < outLen; i++) {
  32154. output.words[i] = input.words[i];
  32155. }
  32156. output.length = outLen;
  32157. if (input.length <= 9) {
  32158. input.words[0] = 0;
  32159. input.length = 1;
  32160. return;
  32161. }
  32162. // Shift by 9 limbs
  32163. var prev = input.words[9];
  32164. output.words[output.length++] = prev & mask;
  32165. for (i = 10; i < input.length; i++) {
  32166. var next = input.words[i] | 0;
  32167. input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
  32168. prev = next;
  32169. }
  32170. prev >>>= 22;
  32171. input.words[i - 10] = prev;
  32172. if (prev === 0 && input.length > 10) {
  32173. input.length -= 10;
  32174. } else {
  32175. input.length -= 9;
  32176. }
  32177. };
  32178. K256.prototype.imulK = function imulK (num) {
  32179. // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
  32180. num.words[num.length] = 0;
  32181. num.words[num.length + 1] = 0;
  32182. num.length += 2;
  32183. // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
  32184. var lo = 0;
  32185. for (var i = 0; i < num.length; i++) {
  32186. var w = num.words[i] | 0;
  32187. lo += w * 0x3d1;
  32188. num.words[i] = lo & 0x3ffffff;
  32189. lo = w * 0x40 + ((lo / 0x4000000) | 0);
  32190. }
  32191. // Fast length reduction
  32192. if (num.words[num.length - 1] === 0) {
  32193. num.length--;
  32194. if (num.words[num.length - 1] === 0) {
  32195. num.length--;
  32196. }
  32197. }
  32198. return num;
  32199. };
  32200. function P224 () {
  32201. MPrime.call(
  32202. this,
  32203. 'p224',
  32204. 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  32205. }
  32206. inherits(P224, MPrime);
  32207. function P192 () {
  32208. MPrime.call(
  32209. this,
  32210. 'p192',
  32211. 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  32212. }
  32213. inherits(P192, MPrime);
  32214. function P25519 () {
  32215. // 2 ^ 255 - 19
  32216. MPrime.call(
  32217. this,
  32218. '25519',
  32219. '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  32220. }
  32221. inherits(P25519, MPrime);
  32222. P25519.prototype.imulK = function imulK (num) {
  32223. // K = 0x13
  32224. var carry = 0;
  32225. for (var i = 0; i < num.length; i++) {
  32226. var hi = (num.words[i] | 0) * 0x13 + carry;
  32227. var lo = hi & 0x3ffffff;
  32228. hi >>>= 26;
  32229. num.words[i] = lo;
  32230. carry = hi;
  32231. }
  32232. if (carry !== 0) {
  32233. num.words[num.length++] = carry;
  32234. }
  32235. return num;
  32236. };
  32237. // Exported mostly for testing purposes, use plain name instead
  32238. BN._prime = function prime (name) {
  32239. // Cached version of prime
  32240. if (primes[name]) return primes[name];
  32241. var prime;
  32242. if (name === 'k256') {
  32243. prime = new K256();
  32244. } else if (name === 'p224') {
  32245. prime = new P224();
  32246. } else if (name === 'p192') {
  32247. prime = new P192();
  32248. } else if (name === 'p25519') {
  32249. prime = new P25519();
  32250. } else {
  32251. throw new Error('Unknown prime ' + name);
  32252. }
  32253. primes[name] = prime;
  32254. return prime;
  32255. };
  32256. //
  32257. // Base reduction engine
  32258. //
  32259. function Red (m) {
  32260. if (typeof m === 'string') {
  32261. var prime = BN._prime(m);
  32262. this.m = prime.p;
  32263. this.prime = prime;
  32264. } else {
  32265. assert(m.gtn(1), 'modulus must be greater than 1');
  32266. this.m = m;
  32267. this.prime = null;
  32268. }
  32269. }
  32270. Red.prototype._verify1 = function _verify1 (a) {
  32271. assert(a.negative === 0, 'red works only with positives');
  32272. assert(a.red, 'red works only with red numbers');
  32273. };
  32274. Red.prototype._verify2 = function _verify2 (a, b) {
  32275. assert((a.negative | b.negative) === 0, 'red works only with positives');
  32276. assert(a.red && a.red === b.red,
  32277. 'red works only with red numbers');
  32278. };
  32279. Red.prototype.imod = function imod (a) {
  32280. if (this.prime) return this.prime.ireduce(a)._forceRed(this);
  32281. move(a, a.umod(this.m)._forceRed(this));
  32282. return a;
  32283. };
  32284. Red.prototype.neg = function neg (a) {
  32285. if (a.isZero()) {
  32286. return a.clone();
  32287. }
  32288. return this.m.sub(a)._forceRed(this);
  32289. };
  32290. Red.prototype.add = function add (a, b) {
  32291. this._verify2(a, b);
  32292. var res = a.add(b);
  32293. if (res.cmp(this.m) >= 0) {
  32294. res.isub(this.m);
  32295. }
  32296. return res._forceRed(this);
  32297. };
  32298. Red.prototype.iadd = function iadd (a, b) {
  32299. this._verify2(a, b);
  32300. var res = a.iadd(b);
  32301. if (res.cmp(this.m) >= 0) {
  32302. res.isub(this.m);
  32303. }
  32304. return res;
  32305. };
  32306. Red.prototype.sub = function sub (a, b) {
  32307. this._verify2(a, b);
  32308. var res = a.sub(b);
  32309. if (res.cmpn(0) < 0) {
  32310. res.iadd(this.m);
  32311. }
  32312. return res._forceRed(this);
  32313. };
  32314. Red.prototype.isub = function isub (a, b) {
  32315. this._verify2(a, b);
  32316. var res = a.isub(b);
  32317. if (res.cmpn(0) < 0) {
  32318. res.iadd(this.m);
  32319. }
  32320. return res;
  32321. };
  32322. Red.prototype.shl = function shl (a, num) {
  32323. this._verify1(a);
  32324. return this.imod(a.ushln(num));
  32325. };
  32326. Red.prototype.imul = function imul (a, b) {
  32327. this._verify2(a, b);
  32328. return this.imod(a.imul(b));
  32329. };
  32330. Red.prototype.mul = function mul (a, b) {
  32331. this._verify2(a, b);
  32332. return this.imod(a.mul(b));
  32333. };
  32334. Red.prototype.isqr = function isqr (a) {
  32335. return this.imul(a, a.clone());
  32336. };
  32337. Red.prototype.sqr = function sqr (a) {
  32338. return this.mul(a, a);
  32339. };
  32340. Red.prototype.sqrt = function sqrt (a) {
  32341. if (a.isZero()) return a.clone();
  32342. var mod3 = this.m.andln(3);
  32343. assert(mod3 % 2 === 1);
  32344. // Fast case
  32345. if (mod3 === 3) {
  32346. var pow = this.m.add(new BN(1)).iushrn(2);
  32347. return this.pow(a, pow);
  32348. }
  32349. // Tonelli-Shanks algorithm (Totally unoptimized and slow)
  32350. //
  32351. // Find Q and S, that Q * 2 ^ S = (P - 1)
  32352. var q = this.m.subn(1);
  32353. var s = 0;
  32354. while (!q.isZero() && q.andln(1) === 0) {
  32355. s++;
  32356. q.iushrn(1);
  32357. }
  32358. assert(!q.isZero());
  32359. var one = new BN(1).toRed(this);
  32360. var nOne = one.redNeg();
  32361. // Find quadratic non-residue
  32362. // NOTE: Max is such because of generalized Riemann hypothesis.
  32363. var lpow = this.m.subn(1).iushrn(1);
  32364. var z = this.m.bitLength();
  32365. z = new BN(2 * z * z).toRed(this);
  32366. while (this.pow(z, lpow).cmp(nOne) !== 0) {
  32367. z.redIAdd(nOne);
  32368. }
  32369. var c = this.pow(z, q);
  32370. var r = this.pow(a, q.addn(1).iushrn(1));
  32371. var t = this.pow(a, q);
  32372. var m = s;
  32373. while (t.cmp(one) !== 0) {
  32374. var tmp = t;
  32375. for (var i = 0; tmp.cmp(one) !== 0; i++) {
  32376. tmp = tmp.redSqr();
  32377. }
  32378. assert(i < m);
  32379. var b = this.pow(c, new BN(1).iushln(m - i - 1));
  32380. r = r.redMul(b);
  32381. c = b.redSqr();
  32382. t = t.redMul(c);
  32383. m = i;
  32384. }
  32385. return r;
  32386. };
  32387. Red.prototype.invm = function invm (a) {
  32388. var inv = a._invmp(this.m);
  32389. if (inv.negative !== 0) {
  32390. inv.negative = 0;
  32391. return this.imod(inv).redNeg();
  32392. } else {
  32393. return this.imod(inv);
  32394. }
  32395. };
  32396. Red.prototype.pow = function pow (a, num) {
  32397. if (num.isZero()) return new BN(1).toRed(this);
  32398. if (num.cmpn(1) === 0) return a.clone();
  32399. var windowSize = 4;
  32400. var wnd = new Array(1 << windowSize);
  32401. wnd[0] = new BN(1).toRed(this);
  32402. wnd[1] = a;
  32403. for (var i = 2; i < wnd.length; i++) {
  32404. wnd[i] = this.mul(wnd[i - 1], a);
  32405. }
  32406. var res = wnd[0];
  32407. var current = 0;
  32408. var currentLen = 0;
  32409. var start = num.bitLength() % 26;
  32410. if (start === 0) {
  32411. start = 26;
  32412. }
  32413. for (i = num.length - 1; i >= 0; i--) {
  32414. var word = num.words[i];
  32415. for (var j = start - 1; j >= 0; j--) {
  32416. var bit = (word >> j) & 1;
  32417. if (res !== wnd[0]) {
  32418. res = this.sqr(res);
  32419. }
  32420. if (bit === 0 && current === 0) {
  32421. currentLen = 0;
  32422. continue;
  32423. }
  32424. current <<= 1;
  32425. current |= bit;
  32426. currentLen++;
  32427. if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
  32428. res = this.mul(res, wnd[current]);
  32429. currentLen = 0;
  32430. current = 0;
  32431. }
  32432. start = 26;
  32433. }
  32434. return res;
  32435. };
  32436. Red.prototype.convertTo = function convertTo (num) {
  32437. var r = num.umod(this.m);
  32438. return r === num ? r.clone() : r;
  32439. };
  32440. Red.prototype.convertFrom = function convertFrom (num) {
  32441. var res = num.clone();
  32442. res.red = null;
  32443. return res;
  32444. };
  32445. //
  32446. // Montgomery method engine
  32447. //
  32448. BN.mont = function mont (num) {
  32449. return new Mont(num);
  32450. };
  32451. function Mont (m) {
  32452. Red.call(this, m);
  32453. this.shift = this.m.bitLength();
  32454. if (this.shift % 26 !== 0) {
  32455. this.shift += 26 - (this.shift % 26);
  32456. }
  32457. this.r = new BN(1).iushln(this.shift);
  32458. this.r2 = this.imod(this.r.sqr());
  32459. this.rinv = this.r._invmp(this.m);
  32460. this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
  32461. this.minv = this.minv.umod(this.r);
  32462. this.minv = this.r.sub(this.minv);
  32463. }
  32464. inherits(Mont, Red);
  32465. Mont.prototype.convertTo = function convertTo (num) {
  32466. return this.imod(num.ushln(this.shift));
  32467. };
  32468. Mont.prototype.convertFrom = function convertFrom (num) {
  32469. var r = this.imod(num.mul(this.rinv));
  32470. r.red = null;
  32471. return r;
  32472. };
  32473. Mont.prototype.imul = function imul (a, b) {
  32474. if (a.isZero() || b.isZero()) {
  32475. a.words[0] = 0;
  32476. a.length = 1;
  32477. return a;
  32478. }
  32479. var t = a.imul(b);
  32480. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  32481. var u = t.isub(c).iushrn(this.shift);
  32482. var res = u;
  32483. if (u.cmp(this.m) >= 0) {
  32484. res = u.isub(this.m);
  32485. } else if (u.cmpn(0) < 0) {
  32486. res = u.iadd(this.m);
  32487. }
  32488. return res._forceRed(this);
  32489. };
  32490. Mont.prototype.mul = function mul (a, b) {
  32491. if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
  32492. var t = a.mul(b);
  32493. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  32494. var u = t.isub(c).iushrn(this.shift);
  32495. var res = u;
  32496. if (u.cmp(this.m) >= 0) {
  32497. res = u.isub(this.m);
  32498. } else if (u.cmpn(0) < 0) {
  32499. res = u.iadd(this.m);
  32500. }
  32501. return res._forceRed(this);
  32502. };
  32503. Mont.prototype.invm = function invm (a) {
  32504. // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
  32505. var res = this.imod(a._invmp(this.m).mul(this.r2));
  32506. return res._forceRed(this);
  32507. };
  32508. })(typeof module === 'undefined' || module, this);
  32509. },{"buffer":144}],143:[function(require,module,exports){
  32510. var r;
  32511. module.exports = function rand(len) {
  32512. if (!r)
  32513. r = new Rand(null);
  32514. return r.generate(len);
  32515. };
  32516. function Rand(rand) {
  32517. this.rand = rand;
  32518. }
  32519. module.exports.Rand = Rand;
  32520. Rand.prototype.generate = function generate(len) {
  32521. return this._rand(len);
  32522. };
  32523. // Emulate crypto API using randy
  32524. Rand.prototype._rand = function _rand(n) {
  32525. if (this.rand.getBytes)
  32526. return this.rand.getBytes(n);
  32527. var res = new Uint8Array(n);
  32528. for (var i = 0; i < res.length; i++)
  32529. res[i] = this.rand.getByte();
  32530. return res;
  32531. };
  32532. if (typeof self === 'object') {
  32533. if (self.crypto && self.crypto.getRandomValues) {
  32534. // Modern browsers
  32535. Rand.prototype._rand = function _rand(n) {
  32536. var arr = new Uint8Array(n);
  32537. self.crypto.getRandomValues(arr);
  32538. return arr;
  32539. };
  32540. } else if (self.msCrypto && self.msCrypto.getRandomValues) {
  32541. // IE
  32542. Rand.prototype._rand = function _rand(n) {
  32543. var arr = new Uint8Array(n);
  32544. self.msCrypto.getRandomValues(arr);
  32545. return arr;
  32546. };
  32547. // Safari's WebWorkers do not have `crypto`
  32548. } else if (typeof window === 'object') {
  32549. // Old junk
  32550. Rand.prototype._rand = function() {
  32551. throw new Error('Not implemented yet');
  32552. };
  32553. }
  32554. } else {
  32555. // Node.js or Web worker with no crypto support
  32556. try {
  32557. var crypto = require('crypto');
  32558. if (typeof crypto.randomBytes !== 'function')
  32559. throw new Error('Not supported');
  32560. Rand.prototype._rand = function _rand(n) {
  32561. return crypto.randomBytes(n);
  32562. };
  32563. } catch (e) {
  32564. }
  32565. }
  32566. },{"crypto":144}],144:[function(require,module,exports){
  32567. },{}],145:[function(require,module,exports){
  32568. // based on the aes implimentation in triple sec
  32569. // https://github.com/keybase/triplesec
  32570. // which is in turn based on the one from crypto-js
  32571. // https://code.google.com/p/crypto-js/
  32572. var Buffer = require('safe-buffer').Buffer
  32573. function asUInt32Array (buf) {
  32574. if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
  32575. var len = (buf.length / 4) | 0
  32576. var out = new Array(len)
  32577. for (var i = 0; i < len; i++) {
  32578. out[i] = buf.readUInt32BE(i * 4)
  32579. }
  32580. return out
  32581. }
  32582. function scrubVec (v) {
  32583. for (var i = 0; i < v.length; v++) {
  32584. v[i] = 0
  32585. }
  32586. }
  32587. function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
  32588. var SUB_MIX0 = SUB_MIX[0]
  32589. var SUB_MIX1 = SUB_MIX[1]
  32590. var SUB_MIX2 = SUB_MIX[2]
  32591. var SUB_MIX3 = SUB_MIX[3]
  32592. var s0 = M[0] ^ keySchedule[0]
  32593. var s1 = M[1] ^ keySchedule[1]
  32594. var s2 = M[2] ^ keySchedule[2]
  32595. var s3 = M[3] ^ keySchedule[3]
  32596. var t0, t1, t2, t3
  32597. var ksRow = 4
  32598. for (var round = 1; round < nRounds; round++) {
  32599. t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
  32600. t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
  32601. t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
  32602. t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
  32603. s0 = t0
  32604. s1 = t1
  32605. s2 = t2
  32606. s3 = t3
  32607. }
  32608. t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
  32609. t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
  32610. t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
  32611. t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
  32612. t0 = t0 >>> 0
  32613. t1 = t1 >>> 0
  32614. t2 = t2 >>> 0
  32615. t3 = t3 >>> 0
  32616. return [t0, t1, t2, t3]
  32617. }
  32618. // AES constants
  32619. var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
  32620. var G = (function () {
  32621. // Compute double table
  32622. var d = new Array(256)
  32623. for (var j = 0; j < 256; j++) {
  32624. if (j < 128) {
  32625. d[j] = j << 1
  32626. } else {
  32627. d[j] = (j << 1) ^ 0x11b
  32628. }
  32629. }
  32630. var SBOX = []
  32631. var INV_SBOX = []
  32632. var SUB_MIX = [[], [], [], []]
  32633. var INV_SUB_MIX = [[], [], [], []]
  32634. // Walk GF(2^8)
  32635. var x = 0
  32636. var xi = 0
  32637. for (var i = 0; i < 256; ++i) {
  32638. // Compute sbox
  32639. var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
  32640. sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
  32641. SBOX[x] = sx
  32642. INV_SBOX[sx] = x
  32643. // Compute multiplication
  32644. var x2 = d[x]
  32645. var x4 = d[x2]
  32646. var x8 = d[x4]
  32647. // Compute sub bytes, mix columns tables
  32648. var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
  32649. SUB_MIX[0][x] = (t << 24) | (t >>> 8)
  32650. SUB_MIX[1][x] = (t << 16) | (t >>> 16)
  32651. SUB_MIX[2][x] = (t << 8) | (t >>> 24)
  32652. SUB_MIX[3][x] = t
  32653. // Compute inv sub bytes, inv mix columns tables
  32654. t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
  32655. INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
  32656. INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
  32657. INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
  32658. INV_SUB_MIX[3][sx] = t
  32659. if (x === 0) {
  32660. x = xi = 1
  32661. } else {
  32662. x = x2 ^ d[d[d[x8 ^ x2]]]
  32663. xi ^= d[d[xi]]
  32664. }
  32665. }
  32666. return {
  32667. SBOX: SBOX,
  32668. INV_SBOX: INV_SBOX,
  32669. SUB_MIX: SUB_MIX,
  32670. INV_SUB_MIX: INV_SUB_MIX
  32671. }
  32672. })()
  32673. function AES (key) {
  32674. this._key = asUInt32Array(key)
  32675. this._reset()
  32676. }
  32677. AES.blockSize = 4 * 4
  32678. AES.keySize = 256 / 8
  32679. AES.prototype.blockSize = AES.blockSize
  32680. AES.prototype.keySize = AES.keySize
  32681. AES.prototype._reset = function () {
  32682. var keyWords = this._key
  32683. var keySize = keyWords.length
  32684. var nRounds = keySize + 6
  32685. var ksRows = (nRounds + 1) * 4
  32686. var keySchedule = []
  32687. for (var k = 0; k < keySize; k++) {
  32688. keySchedule[k] = keyWords[k]
  32689. }
  32690. for (k = keySize; k < ksRows; k++) {
  32691. var t = keySchedule[k - 1]
  32692. if (k % keySize === 0) {
  32693. t = (t << 8) | (t >>> 24)
  32694. t =
  32695. (G.SBOX[t >>> 24] << 24) |
  32696. (G.SBOX[(t >>> 16) & 0xff] << 16) |
  32697. (G.SBOX[(t >>> 8) & 0xff] << 8) |
  32698. (G.SBOX[t & 0xff])
  32699. t ^= RCON[(k / keySize) | 0] << 24
  32700. } else if (keySize > 6 && k % keySize === 4) {
  32701. t =
  32702. (G.SBOX[t >>> 24] << 24) |
  32703. (G.SBOX[(t >>> 16) & 0xff] << 16) |
  32704. (G.SBOX[(t >>> 8) & 0xff] << 8) |
  32705. (G.SBOX[t & 0xff])
  32706. }
  32707. keySchedule[k] = keySchedule[k - keySize] ^ t
  32708. }
  32709. var invKeySchedule = []
  32710. for (var ik = 0; ik < ksRows; ik++) {
  32711. var ksR = ksRows - ik
  32712. var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
  32713. if (ik < 4 || ksR <= 4) {
  32714. invKeySchedule[ik] = tt
  32715. } else {
  32716. invKeySchedule[ik] =
  32717. G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
  32718. G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
  32719. G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
  32720. G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
  32721. }
  32722. }
  32723. this._nRounds = nRounds
  32724. this._keySchedule = keySchedule
  32725. this._invKeySchedule = invKeySchedule
  32726. }
  32727. AES.prototype.encryptBlockRaw = function (M) {
  32728. M = asUInt32Array(M)
  32729. return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
  32730. }
  32731. AES.prototype.encryptBlock = function (M) {
  32732. var out = this.encryptBlockRaw(M)
  32733. var buf = Buffer.allocUnsafe(16)
  32734. buf.writeUInt32BE(out[0], 0)
  32735. buf.writeUInt32BE(out[1], 4)
  32736. buf.writeUInt32BE(out[2], 8)
  32737. buf.writeUInt32BE(out[3], 12)
  32738. return buf
  32739. }
  32740. AES.prototype.decryptBlock = function (M) {
  32741. M = asUInt32Array(M)
  32742. // swap
  32743. var m1 = M[1]
  32744. M[1] = M[3]
  32745. M[3] = m1
  32746. var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
  32747. var buf = Buffer.allocUnsafe(16)
  32748. buf.writeUInt32BE(out[0], 0)
  32749. buf.writeUInt32BE(out[3], 4)
  32750. buf.writeUInt32BE(out[2], 8)
  32751. buf.writeUInt32BE(out[1], 12)
  32752. return buf
  32753. }
  32754. AES.prototype.scrub = function () {
  32755. scrubVec(this._keySchedule)
  32756. scrubVec(this._invKeySchedule)
  32757. scrubVec(this._key)
  32758. }
  32759. module.exports.AES = AES
  32760. },{"safe-buffer":561}],146:[function(require,module,exports){
  32761. var aes = require('./aes')
  32762. var Buffer = require('safe-buffer').Buffer
  32763. var Transform = require('cipher-base')
  32764. var inherits = require('inherits')
  32765. var GHASH = require('./ghash')
  32766. var xor = require('buffer-xor')
  32767. var incr32 = require('./incr32')
  32768. function xorTest (a, b) {
  32769. var out = 0
  32770. if (a.length !== b.length) out++
  32771. var len = Math.min(a.length, b.length)
  32772. for (var i = 0; i < len; ++i) {
  32773. out += (a[i] ^ b[i])
  32774. }
  32775. return out
  32776. }
  32777. function calcIv (self, iv, ck) {
  32778. if (iv.length === 12) {
  32779. self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
  32780. return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
  32781. }
  32782. var ghash = new GHASH(ck)
  32783. var len = iv.length
  32784. var toPad = len % 16
  32785. ghash.update(iv)
  32786. if (toPad) {
  32787. toPad = 16 - toPad
  32788. ghash.update(Buffer.alloc(toPad, 0))
  32789. }
  32790. ghash.update(Buffer.alloc(8, 0))
  32791. var ivBits = len * 8
  32792. var tail = Buffer.alloc(8)
  32793. tail.writeUIntBE(ivBits, 0, 8)
  32794. ghash.update(tail)
  32795. self._finID = ghash.state
  32796. var out = Buffer.from(self._finID)
  32797. incr32(out)
  32798. return out
  32799. }
  32800. function StreamCipher (mode, key, iv, decrypt) {
  32801. Transform.call(this)
  32802. var h = Buffer.alloc(4, 0)
  32803. this._cipher = new aes.AES(key)
  32804. var ck = this._cipher.encryptBlock(h)
  32805. this._ghash = new GHASH(ck)
  32806. iv = calcIv(this, iv, ck)
  32807. this._prev = Buffer.from(iv)
  32808. this._cache = Buffer.allocUnsafe(0)
  32809. this._secCache = Buffer.allocUnsafe(0)
  32810. this._decrypt = decrypt
  32811. this._alen = 0
  32812. this._len = 0
  32813. this._mode = mode
  32814. this._authTag = null
  32815. this._called = false
  32816. }
  32817. inherits(StreamCipher, Transform)
  32818. StreamCipher.prototype._update = function (chunk) {
  32819. if (!this._called && this._alen) {
  32820. var rump = 16 - (this._alen % 16)
  32821. if (rump < 16) {
  32822. rump = Buffer.alloc(rump, 0)
  32823. this._ghash.update(rump)
  32824. }
  32825. }
  32826. this._called = true
  32827. var out = this._mode.encrypt(this, chunk)
  32828. if (this._decrypt) {
  32829. this._ghash.update(chunk)
  32830. } else {
  32831. this._ghash.update(out)
  32832. }
  32833. this._len += chunk.length
  32834. return out
  32835. }
  32836. StreamCipher.prototype._final = function () {
  32837. if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
  32838. var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
  32839. if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
  32840. this._authTag = tag
  32841. this._cipher.scrub()
  32842. }
  32843. StreamCipher.prototype.getAuthTag = function getAuthTag () {
  32844. if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
  32845. return this._authTag
  32846. }
  32847. StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
  32848. if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
  32849. this._authTag = tag
  32850. }
  32851. StreamCipher.prototype.setAAD = function setAAD (buf) {
  32852. if (this._called) throw new Error('Attempting to set AAD in unsupported state')
  32853. this._ghash.update(buf)
  32854. this._alen += buf.length
  32855. }
  32856. module.exports = StreamCipher
  32857. },{"./aes":145,"./ghash":150,"./incr32":151,"buffer-xor":192,"cipher-base":198,"inherits":320,"safe-buffer":561}],147:[function(require,module,exports){
  32858. var ciphers = require('./encrypter')
  32859. var deciphers = require('./decrypter')
  32860. var modes = require('./modes/list.json')
  32861. function getCiphers () {
  32862. return Object.keys(modes)
  32863. }
  32864. exports.createCipher = exports.Cipher = ciphers.createCipher
  32865. exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
  32866. exports.createDecipher = exports.Decipher = deciphers.createDecipher
  32867. exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
  32868. exports.listCiphers = exports.getCiphers = getCiphers
  32869. },{"./decrypter":148,"./encrypter":149,"./modes/list.json":159}],148:[function(require,module,exports){
  32870. var AuthCipher = require('./authCipher')
  32871. var Buffer = require('safe-buffer').Buffer
  32872. var MODES = require('./modes')
  32873. var StreamCipher = require('./streamCipher')
  32874. var Transform = require('cipher-base')
  32875. var aes = require('./aes')
  32876. var ebtk = require('evp_bytestokey')
  32877. var inherits = require('inherits')
  32878. function Decipher (mode, key, iv) {
  32879. Transform.call(this)
  32880. this._cache = new Splitter()
  32881. this._last = void 0
  32882. this._cipher = new aes.AES(key)
  32883. this._prev = Buffer.from(iv)
  32884. this._mode = mode
  32885. this._autopadding = true
  32886. }
  32887. inherits(Decipher, Transform)
  32888. Decipher.prototype._update = function (data) {
  32889. this._cache.add(data)
  32890. var chunk
  32891. var thing
  32892. var out = []
  32893. while ((chunk = this._cache.get(this._autopadding))) {
  32894. thing = this._mode.decrypt(this, chunk)
  32895. out.push(thing)
  32896. }
  32897. return Buffer.concat(out)
  32898. }
  32899. Decipher.prototype._final = function () {
  32900. var chunk = this._cache.flush()
  32901. if (this._autopadding) {
  32902. return unpad(this._mode.decrypt(this, chunk))
  32903. } else if (chunk) {
  32904. throw new Error('data not multiple of block length')
  32905. }
  32906. }
  32907. Decipher.prototype.setAutoPadding = function (setTo) {
  32908. this._autopadding = !!setTo
  32909. return this
  32910. }
  32911. function Splitter () {
  32912. this.cache = Buffer.allocUnsafe(0)
  32913. }
  32914. Splitter.prototype.add = function (data) {
  32915. this.cache = Buffer.concat([this.cache, data])
  32916. }
  32917. Splitter.prototype.get = function (autoPadding) {
  32918. var out
  32919. if (autoPadding) {
  32920. if (this.cache.length > 16) {
  32921. out = this.cache.slice(0, 16)
  32922. this.cache = this.cache.slice(16)
  32923. return out
  32924. }
  32925. } else {
  32926. if (this.cache.length >= 16) {
  32927. out = this.cache.slice(0, 16)
  32928. this.cache = this.cache.slice(16)
  32929. return out
  32930. }
  32931. }
  32932. return null
  32933. }
  32934. Splitter.prototype.flush = function () {
  32935. if (this.cache.length) return this.cache
  32936. }
  32937. function unpad (last) {
  32938. var padded = last[15]
  32939. if (padded < 1 || padded > 16) {
  32940. throw new Error('unable to decrypt data')
  32941. }
  32942. var i = -1
  32943. while (++i < padded) {
  32944. if (last[(i + (16 - padded))] !== padded) {
  32945. throw new Error('unable to decrypt data')
  32946. }
  32947. }
  32948. if (padded === 16) return
  32949. return last.slice(0, 16 - padded)
  32950. }
  32951. function createDecipheriv (suite, password, iv) {
  32952. var config = MODES[suite.toLowerCase()]
  32953. if (!config) throw new TypeError('invalid suite type')
  32954. if (typeof iv === 'string') iv = Buffer.from(iv)
  32955. if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
  32956. if (typeof password === 'string') password = Buffer.from(password)
  32957. if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
  32958. if (config.type === 'stream') {
  32959. return new StreamCipher(config.module, password, iv, true)
  32960. } else if (config.type === 'auth') {
  32961. return new AuthCipher(config.module, password, iv, true)
  32962. }
  32963. return new Decipher(config.module, password, iv)
  32964. }
  32965. function createDecipher (suite, password) {
  32966. var config = MODES[suite.toLowerCase()]
  32967. if (!config) throw new TypeError('invalid suite type')
  32968. var keys = ebtk(password, false, config.key, config.iv)
  32969. return createDecipheriv(suite, keys.key, keys.iv)
  32970. }
  32971. exports.createDecipher = createDecipher
  32972. exports.createDecipheriv = createDecipheriv
  32973. },{"./aes":145,"./authCipher":146,"./modes":158,"./streamCipher":161,"cipher-base":198,"evp_bytestokey":248,"inherits":320,"safe-buffer":561}],149:[function(require,module,exports){
  32974. var MODES = require('./modes')
  32975. var AuthCipher = require('./authCipher')
  32976. var Buffer = require('safe-buffer').Buffer
  32977. var StreamCipher = require('./streamCipher')
  32978. var Transform = require('cipher-base')
  32979. var aes = require('./aes')
  32980. var ebtk = require('evp_bytestokey')
  32981. var inherits = require('inherits')
  32982. function Cipher (mode, key, iv) {
  32983. Transform.call(this)
  32984. this._cache = new Splitter()
  32985. this._cipher = new aes.AES(key)
  32986. this._prev = Buffer.from(iv)
  32987. this._mode = mode
  32988. this._autopadding = true
  32989. }
  32990. inherits(Cipher, Transform)
  32991. Cipher.prototype._update = function (data) {
  32992. this._cache.add(data)
  32993. var chunk
  32994. var thing
  32995. var out = []
  32996. while ((chunk = this._cache.get())) {
  32997. thing = this._mode.encrypt(this, chunk)
  32998. out.push(thing)
  32999. }
  33000. return Buffer.concat(out)
  33001. }
  33002. var PADDING = Buffer.alloc(16, 0x10)
  33003. Cipher.prototype._final = function () {
  33004. var chunk = this._cache.flush()
  33005. if (this._autopadding) {
  33006. chunk = this._mode.encrypt(this, chunk)
  33007. this._cipher.scrub()
  33008. return chunk
  33009. }
  33010. if (!chunk.equals(PADDING)) {
  33011. this._cipher.scrub()
  33012. throw new Error('data not multiple of block length')
  33013. }
  33014. }
  33015. Cipher.prototype.setAutoPadding = function (setTo) {
  33016. this._autopadding = !!setTo
  33017. return this
  33018. }
  33019. function Splitter () {
  33020. this.cache = Buffer.allocUnsafe(0)
  33021. }
  33022. Splitter.prototype.add = function (data) {
  33023. this.cache = Buffer.concat([this.cache, data])
  33024. }
  33025. Splitter.prototype.get = function () {
  33026. if (this.cache.length > 15) {
  33027. var out = this.cache.slice(0, 16)
  33028. this.cache = this.cache.slice(16)
  33029. return out
  33030. }
  33031. return null
  33032. }
  33033. Splitter.prototype.flush = function () {
  33034. var len = 16 - this.cache.length
  33035. var padBuff = Buffer.allocUnsafe(len)
  33036. var i = -1
  33037. while (++i < len) {
  33038. padBuff.writeUInt8(len, i)
  33039. }
  33040. return Buffer.concat([this.cache, padBuff])
  33041. }
  33042. function createCipheriv (suite, password, iv) {
  33043. var config = MODES[suite.toLowerCase()]
  33044. if (!config) throw new TypeError('invalid suite type')
  33045. if (typeof password === 'string') password = Buffer.from(password)
  33046. if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
  33047. if (typeof iv === 'string') iv = Buffer.from(iv)
  33048. if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
  33049. if (config.type === 'stream') {
  33050. return new StreamCipher(config.module, password, iv)
  33051. } else if (config.type === 'auth') {
  33052. return new AuthCipher(config.module, password, iv)
  33053. }
  33054. return new Cipher(config.module, password, iv)
  33055. }
  33056. function createCipher (suite, password) {
  33057. var config = MODES[suite.toLowerCase()]
  33058. if (!config) throw new TypeError('invalid suite type')
  33059. var keys = ebtk(password, false, config.key, config.iv)
  33060. return createCipheriv(suite, keys.key, keys.iv)
  33061. }
  33062. exports.createCipheriv = createCipheriv
  33063. exports.createCipher = createCipher
  33064. },{"./aes":145,"./authCipher":146,"./modes":158,"./streamCipher":161,"cipher-base":198,"evp_bytestokey":248,"inherits":320,"safe-buffer":561}],150:[function(require,module,exports){
  33065. var Buffer = require('safe-buffer').Buffer
  33066. var ZEROES = Buffer.alloc(16, 0)
  33067. function toArray (buf) {
  33068. return [
  33069. buf.readUInt32BE(0),
  33070. buf.readUInt32BE(4),
  33071. buf.readUInt32BE(8),
  33072. buf.readUInt32BE(12)
  33073. ]
  33074. }
  33075. function fromArray (out) {
  33076. var buf = Buffer.allocUnsafe(16)
  33077. buf.writeUInt32BE(out[0] >>> 0, 0)
  33078. buf.writeUInt32BE(out[1] >>> 0, 4)
  33079. buf.writeUInt32BE(out[2] >>> 0, 8)
  33080. buf.writeUInt32BE(out[3] >>> 0, 12)
  33081. return buf
  33082. }
  33083. function GHASH (key) {
  33084. this.h = key
  33085. this.state = Buffer.alloc(16, 0)
  33086. this.cache = Buffer.allocUnsafe(0)
  33087. }
  33088. // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
  33089. // by Juho Vähä-Herttua
  33090. GHASH.prototype.ghash = function (block) {
  33091. var i = -1
  33092. while (++i < block.length) {
  33093. this.state[i] ^= block[i]
  33094. }
  33095. this._multiply()
  33096. }
  33097. GHASH.prototype._multiply = function () {
  33098. var Vi = toArray(this.h)
  33099. var Zi = [0, 0, 0, 0]
  33100. var j, xi, lsbVi
  33101. var i = -1
  33102. while (++i < 128) {
  33103. xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
  33104. if (xi) {
  33105. // Z_i+1 = Z_i ^ V_i
  33106. Zi[0] ^= Vi[0]
  33107. Zi[1] ^= Vi[1]
  33108. Zi[2] ^= Vi[2]
  33109. Zi[3] ^= Vi[3]
  33110. }
  33111. // Store the value of LSB(V_i)
  33112. lsbVi = (Vi[3] & 1) !== 0
  33113. // V_i+1 = V_i >> 1
  33114. for (j = 3; j > 0; j--) {
  33115. Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
  33116. }
  33117. Vi[0] = Vi[0] >>> 1
  33118. // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
  33119. if (lsbVi) {
  33120. Vi[0] = Vi[0] ^ (0xe1 << 24)
  33121. }
  33122. }
  33123. this.state = fromArray(Zi)
  33124. }
  33125. GHASH.prototype.update = function (buf) {
  33126. this.cache = Buffer.concat([this.cache, buf])
  33127. var chunk
  33128. while (this.cache.length >= 16) {
  33129. chunk = this.cache.slice(0, 16)
  33130. this.cache = this.cache.slice(16)
  33131. this.ghash(chunk)
  33132. }
  33133. }
  33134. GHASH.prototype.final = function (abl, bl) {
  33135. if (this.cache.length) {
  33136. this.ghash(Buffer.concat([this.cache, ZEROES], 16))
  33137. }
  33138. this.ghash(fromArray([0, abl, 0, bl]))
  33139. return this.state
  33140. }
  33141. module.exports = GHASH
  33142. },{"safe-buffer":561}],151:[function(require,module,exports){
  33143. function incr32 (iv) {
  33144. var len = iv.length
  33145. var item
  33146. while (len--) {
  33147. item = iv.readUInt8(len)
  33148. if (item === 255) {
  33149. iv.writeUInt8(0, len)
  33150. } else {
  33151. item++
  33152. iv.writeUInt8(item, len)
  33153. break
  33154. }
  33155. }
  33156. }
  33157. module.exports = incr32
  33158. },{}],152:[function(require,module,exports){
  33159. var xor = require('buffer-xor')
  33160. exports.encrypt = function (self, block) {
  33161. var data = xor(block, self._prev)
  33162. self._prev = self._cipher.encryptBlock(data)
  33163. return self._prev
  33164. }
  33165. exports.decrypt = function (self, block) {
  33166. var pad = self._prev
  33167. self._prev = block
  33168. var out = self._cipher.decryptBlock(block)
  33169. return xor(out, pad)
  33170. }
  33171. },{"buffer-xor":192}],153:[function(require,module,exports){
  33172. var Buffer = require('safe-buffer').Buffer
  33173. var xor = require('buffer-xor')
  33174. function encryptStart (self, data, decrypt) {
  33175. var len = data.length
  33176. var out = xor(data, self._cache)
  33177. self._cache = self._cache.slice(len)
  33178. self._prev = Buffer.concat([self._prev, decrypt ? data : out])
  33179. return out
  33180. }
  33181. exports.encrypt = function (self, data, decrypt) {
  33182. var out = Buffer.allocUnsafe(0)
  33183. var len
  33184. while (data.length) {
  33185. if (self._cache.length === 0) {
  33186. self._cache = self._cipher.encryptBlock(self._prev)
  33187. self._prev = Buffer.allocUnsafe(0)
  33188. }
  33189. if (self._cache.length <= data.length) {
  33190. len = self._cache.length
  33191. out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
  33192. data = data.slice(len)
  33193. } else {
  33194. out = Buffer.concat([out, encryptStart(self, data, decrypt)])
  33195. break
  33196. }
  33197. }
  33198. return out
  33199. }
  33200. },{"buffer-xor":192,"safe-buffer":561}],154:[function(require,module,exports){
  33201. var Buffer = require('safe-buffer').Buffer
  33202. function encryptByte (self, byteParam, decrypt) {
  33203. var pad
  33204. var i = -1
  33205. var len = 8
  33206. var out = 0
  33207. var bit, value
  33208. while (++i < len) {
  33209. pad = self._cipher.encryptBlock(self._prev)
  33210. bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
  33211. value = pad[0] ^ bit
  33212. out += ((value & 0x80) >> (i % 8))
  33213. self._prev = shiftIn(self._prev, decrypt ? bit : value)
  33214. }
  33215. return out
  33216. }
  33217. function shiftIn (buffer, value) {
  33218. var len = buffer.length
  33219. var i = -1
  33220. var out = Buffer.allocUnsafe(buffer.length)
  33221. buffer = Buffer.concat([buffer, Buffer.from([value])])
  33222. while (++i < len) {
  33223. out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
  33224. }
  33225. return out
  33226. }
  33227. exports.encrypt = function (self, chunk, decrypt) {
  33228. var len = chunk.length
  33229. var out = Buffer.allocUnsafe(len)
  33230. var i = -1
  33231. while (++i < len) {
  33232. out[i] = encryptByte(self, chunk[i], decrypt)
  33233. }
  33234. return out
  33235. }
  33236. },{"safe-buffer":561}],155:[function(require,module,exports){
  33237. var Buffer = require('safe-buffer').Buffer
  33238. function encryptByte (self, byteParam, decrypt) {
  33239. var pad = self._cipher.encryptBlock(self._prev)
  33240. var out = pad[0] ^ byteParam
  33241. self._prev = Buffer.concat([
  33242. self._prev.slice(1),
  33243. Buffer.from([decrypt ? byteParam : out])
  33244. ])
  33245. return out
  33246. }
  33247. exports.encrypt = function (self, chunk, decrypt) {
  33248. var len = chunk.length
  33249. var out = Buffer.allocUnsafe(len)
  33250. var i = -1
  33251. while (++i < len) {
  33252. out[i] = encryptByte(self, chunk[i], decrypt)
  33253. }
  33254. return out
  33255. }
  33256. },{"safe-buffer":561}],156:[function(require,module,exports){
  33257. var xor = require('buffer-xor')
  33258. var Buffer = require('safe-buffer').Buffer
  33259. var incr32 = require('../incr32')
  33260. function getBlock (self) {
  33261. var out = self._cipher.encryptBlockRaw(self._prev)
  33262. incr32(self._prev)
  33263. return out
  33264. }
  33265. var blockSize = 16
  33266. exports.encrypt = function (self, chunk) {
  33267. var chunkNum = Math.ceil(chunk.length / blockSize)
  33268. var start = self._cache.length
  33269. self._cache = Buffer.concat([
  33270. self._cache,
  33271. Buffer.allocUnsafe(chunkNum * blockSize)
  33272. ])
  33273. for (var i = 0; i < chunkNum; i++) {
  33274. var out = getBlock(self)
  33275. var offset = start + i * blockSize
  33276. self._cache.writeUInt32BE(out[0], offset + 0)
  33277. self._cache.writeUInt32BE(out[1], offset + 4)
  33278. self._cache.writeUInt32BE(out[2], offset + 8)
  33279. self._cache.writeUInt32BE(out[3], offset + 12)
  33280. }
  33281. var pad = self._cache.slice(0, chunk.length)
  33282. self._cache = self._cache.slice(chunk.length)
  33283. return xor(chunk, pad)
  33284. }
  33285. },{"../incr32":151,"buffer-xor":192,"safe-buffer":561}],157:[function(require,module,exports){
  33286. exports.encrypt = function (self, block) {
  33287. return self._cipher.encryptBlock(block)
  33288. }
  33289. exports.decrypt = function (self, block) {
  33290. return self._cipher.decryptBlock(block)
  33291. }
  33292. },{}],158:[function(require,module,exports){
  33293. var modeModules = {
  33294. ECB: require('./ecb'),
  33295. CBC: require('./cbc'),
  33296. CFB: require('./cfb'),
  33297. CFB8: require('./cfb8'),
  33298. CFB1: require('./cfb1'),
  33299. OFB: require('./ofb'),
  33300. CTR: require('./ctr'),
  33301. GCM: require('./ctr')
  33302. }
  33303. var modes = require('./list.json')
  33304. for (var key in modes) {
  33305. modes[key].module = modeModules[modes[key].mode]
  33306. }
  33307. module.exports = modes
  33308. },{"./cbc":152,"./cfb":153,"./cfb1":154,"./cfb8":155,"./ctr":156,"./ecb":157,"./list.json":159,"./ofb":160}],159:[function(require,module,exports){
  33309. module.exports={
  33310. "aes-128-ecb": {
  33311. "cipher": "AES",
  33312. "key": 128,
  33313. "iv": 0,
  33314. "mode": "ECB",
  33315. "type": "block"
  33316. },
  33317. "aes-192-ecb": {
  33318. "cipher": "AES",
  33319. "key": 192,
  33320. "iv": 0,
  33321. "mode": "ECB",
  33322. "type": "block"
  33323. },
  33324. "aes-256-ecb": {
  33325. "cipher": "AES",
  33326. "key": 256,
  33327. "iv": 0,
  33328. "mode": "ECB",
  33329. "type": "block"
  33330. },
  33331. "aes-128-cbc": {
  33332. "cipher": "AES",
  33333. "key": 128,
  33334. "iv": 16,
  33335. "mode": "CBC",
  33336. "type": "block"
  33337. },
  33338. "aes-192-cbc": {
  33339. "cipher": "AES",
  33340. "key": 192,
  33341. "iv": 16,
  33342. "mode": "CBC",
  33343. "type": "block"
  33344. },
  33345. "aes-256-cbc": {
  33346. "cipher": "AES",
  33347. "key": 256,
  33348. "iv": 16,
  33349. "mode": "CBC",
  33350. "type": "block"
  33351. },
  33352. "aes128": {
  33353. "cipher": "AES",
  33354. "key": 128,
  33355. "iv": 16,
  33356. "mode": "CBC",
  33357. "type": "block"
  33358. },
  33359. "aes192": {
  33360. "cipher": "AES",
  33361. "key": 192,
  33362. "iv": 16,
  33363. "mode": "CBC",
  33364. "type": "block"
  33365. },
  33366. "aes256": {
  33367. "cipher": "AES",
  33368. "key": 256,
  33369. "iv": 16,
  33370. "mode": "CBC",
  33371. "type": "block"
  33372. },
  33373. "aes-128-cfb": {
  33374. "cipher": "AES",
  33375. "key": 128,
  33376. "iv": 16,
  33377. "mode": "CFB",
  33378. "type": "stream"
  33379. },
  33380. "aes-192-cfb": {
  33381. "cipher": "AES",
  33382. "key": 192,
  33383. "iv": 16,
  33384. "mode": "CFB",
  33385. "type": "stream"
  33386. },
  33387. "aes-256-cfb": {
  33388. "cipher": "AES",
  33389. "key": 256,
  33390. "iv": 16,
  33391. "mode": "CFB",
  33392. "type": "stream"
  33393. },
  33394. "aes-128-cfb8": {
  33395. "cipher": "AES",
  33396. "key": 128,
  33397. "iv": 16,
  33398. "mode": "CFB8",
  33399. "type": "stream"
  33400. },
  33401. "aes-192-cfb8": {
  33402. "cipher": "AES",
  33403. "key": 192,
  33404. "iv": 16,
  33405. "mode": "CFB8",
  33406. "type": "stream"
  33407. },
  33408. "aes-256-cfb8": {
  33409. "cipher": "AES",
  33410. "key": 256,
  33411. "iv": 16,
  33412. "mode": "CFB8",
  33413. "type": "stream"
  33414. },
  33415. "aes-128-cfb1": {
  33416. "cipher": "AES",
  33417. "key": 128,
  33418. "iv": 16,
  33419. "mode": "CFB1",
  33420. "type": "stream"
  33421. },
  33422. "aes-192-cfb1": {
  33423. "cipher": "AES",
  33424. "key": 192,
  33425. "iv": 16,
  33426. "mode": "CFB1",
  33427. "type": "stream"
  33428. },
  33429. "aes-256-cfb1": {
  33430. "cipher": "AES",
  33431. "key": 256,
  33432. "iv": 16,
  33433. "mode": "CFB1",
  33434. "type": "stream"
  33435. },
  33436. "aes-128-ofb": {
  33437. "cipher": "AES",
  33438. "key": 128,
  33439. "iv": 16,
  33440. "mode": "OFB",
  33441. "type": "stream"
  33442. },
  33443. "aes-192-ofb": {
  33444. "cipher": "AES",
  33445. "key": 192,
  33446. "iv": 16,
  33447. "mode": "OFB",
  33448. "type": "stream"
  33449. },
  33450. "aes-256-ofb": {
  33451. "cipher": "AES",
  33452. "key": 256,
  33453. "iv": 16,
  33454. "mode": "OFB",
  33455. "type": "stream"
  33456. },
  33457. "aes-128-ctr": {
  33458. "cipher": "AES",
  33459. "key": 128,
  33460. "iv": 16,
  33461. "mode": "CTR",
  33462. "type": "stream"
  33463. },
  33464. "aes-192-ctr": {
  33465. "cipher": "AES",
  33466. "key": 192,
  33467. "iv": 16,
  33468. "mode": "CTR",
  33469. "type": "stream"
  33470. },
  33471. "aes-256-ctr": {
  33472. "cipher": "AES",
  33473. "key": 256,
  33474. "iv": 16,
  33475. "mode": "CTR",
  33476. "type": "stream"
  33477. },
  33478. "aes-128-gcm": {
  33479. "cipher": "AES",
  33480. "key": 128,
  33481. "iv": 12,
  33482. "mode": "GCM",
  33483. "type": "auth"
  33484. },
  33485. "aes-192-gcm": {
  33486. "cipher": "AES",
  33487. "key": 192,
  33488. "iv": 12,
  33489. "mode": "GCM",
  33490. "type": "auth"
  33491. },
  33492. "aes-256-gcm": {
  33493. "cipher": "AES",
  33494. "key": 256,
  33495. "iv": 12,
  33496. "mode": "GCM",
  33497. "type": "auth"
  33498. }
  33499. }
  33500. },{}],160:[function(require,module,exports){
  33501. (function (Buffer){(function (){
  33502. var xor = require('buffer-xor')
  33503. function getBlock (self) {
  33504. self._prev = self._cipher.encryptBlock(self._prev)
  33505. return self._prev
  33506. }
  33507. exports.encrypt = function (self, chunk) {
  33508. while (self._cache.length < chunk.length) {
  33509. self._cache = Buffer.concat([self._cache, getBlock(self)])
  33510. }
  33511. var pad = self._cache.slice(0, chunk.length)
  33512. self._cache = self._cache.slice(chunk.length)
  33513. return xor(chunk, pad)
  33514. }
  33515. }).call(this)}).call(this,require("buffer").Buffer)
  33516. },{"buffer":193,"buffer-xor":192}],161:[function(require,module,exports){
  33517. var aes = require('./aes')
  33518. var Buffer = require('safe-buffer').Buffer
  33519. var Transform = require('cipher-base')
  33520. var inherits = require('inherits')
  33521. function StreamCipher (mode, key, iv, decrypt) {
  33522. Transform.call(this)
  33523. this._cipher = new aes.AES(key)
  33524. this._prev = Buffer.from(iv)
  33525. this._cache = Buffer.allocUnsafe(0)
  33526. this._secCache = Buffer.allocUnsafe(0)
  33527. this._decrypt = decrypt
  33528. this._mode = mode
  33529. }
  33530. inherits(StreamCipher, Transform)
  33531. StreamCipher.prototype._update = function (chunk) {
  33532. return this._mode.encrypt(this, chunk, this._decrypt)
  33533. }
  33534. StreamCipher.prototype._final = function () {
  33535. this._cipher.scrub()
  33536. }
  33537. module.exports = StreamCipher
  33538. },{"./aes":145,"cipher-base":198,"inherits":320,"safe-buffer":561}],162:[function(require,module,exports){
  33539. var DES = require('browserify-des')
  33540. var aes = require('browserify-aes/browser')
  33541. var aesModes = require('browserify-aes/modes')
  33542. var desModes = require('browserify-des/modes')
  33543. var ebtk = require('evp_bytestokey')
  33544. function createCipher (suite, password) {
  33545. suite = suite.toLowerCase()
  33546. var keyLen, ivLen
  33547. if (aesModes[suite]) {
  33548. keyLen = aesModes[suite].key
  33549. ivLen = aesModes[suite].iv
  33550. } else if (desModes[suite]) {
  33551. keyLen = desModes[suite].key * 8
  33552. ivLen = desModes[suite].iv
  33553. } else {
  33554. throw new TypeError('invalid suite type')
  33555. }
  33556. var keys = ebtk(password, false, keyLen, ivLen)
  33557. return createCipheriv(suite, keys.key, keys.iv)
  33558. }
  33559. function createDecipher (suite, password) {
  33560. suite = suite.toLowerCase()
  33561. var keyLen, ivLen
  33562. if (aesModes[suite]) {
  33563. keyLen = aesModes[suite].key
  33564. ivLen = aesModes[suite].iv
  33565. } else if (desModes[suite]) {
  33566. keyLen = desModes[suite].key * 8
  33567. ivLen = desModes[suite].iv
  33568. } else {
  33569. throw new TypeError('invalid suite type')
  33570. }
  33571. var keys = ebtk(password, false, keyLen, ivLen)
  33572. return createDecipheriv(suite, keys.key, keys.iv)
  33573. }
  33574. function createCipheriv (suite, key, iv) {
  33575. suite = suite.toLowerCase()
  33576. if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
  33577. if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })
  33578. throw new TypeError('invalid suite type')
  33579. }
  33580. function createDecipheriv (suite, key, iv) {
  33581. suite = suite.toLowerCase()
  33582. if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
  33583. if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })
  33584. throw new TypeError('invalid suite type')
  33585. }
  33586. function getCiphers () {
  33587. return Object.keys(desModes).concat(aes.getCiphers())
  33588. }
  33589. exports.createCipher = exports.Cipher = createCipher
  33590. exports.createCipheriv = exports.Cipheriv = createCipheriv
  33591. exports.createDecipher = exports.Decipher = createDecipher
  33592. exports.createDecipheriv = exports.Decipheriv = createDecipheriv
  33593. exports.listCiphers = exports.getCiphers = getCiphers
  33594. },{"browserify-aes/browser":147,"browserify-aes/modes":158,"browserify-des":163,"browserify-des/modes":164,"evp_bytestokey":248}],163:[function(require,module,exports){
  33595. var CipherBase = require('cipher-base')
  33596. var des = require('des.js')
  33597. var inherits = require('inherits')
  33598. var Buffer = require('safe-buffer').Buffer
  33599. var modes = {
  33600. 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
  33601. 'des-ede3': des.EDE,
  33602. 'des-ede-cbc': des.CBC.instantiate(des.EDE),
  33603. 'des-ede': des.EDE,
  33604. 'des-cbc': des.CBC.instantiate(des.DES),
  33605. 'des-ecb': des.DES
  33606. }
  33607. modes.des = modes['des-cbc']
  33608. modes.des3 = modes['des-ede3-cbc']
  33609. module.exports = DES
  33610. inherits(DES, CipherBase)
  33611. function DES (opts) {
  33612. CipherBase.call(this)
  33613. var modeName = opts.mode.toLowerCase()
  33614. var mode = modes[modeName]
  33615. var type
  33616. if (opts.decrypt) {
  33617. type = 'decrypt'
  33618. } else {
  33619. type = 'encrypt'
  33620. }
  33621. var key = opts.key
  33622. if (!Buffer.isBuffer(key)) {
  33623. key = Buffer.from(key)
  33624. }
  33625. if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
  33626. key = Buffer.concat([key, key.slice(0, 8)])
  33627. }
  33628. var iv = opts.iv
  33629. if (!Buffer.isBuffer(iv)) {
  33630. iv = Buffer.from(iv)
  33631. }
  33632. this._des = mode.create({
  33633. key: key,
  33634. iv: iv,
  33635. type: type
  33636. })
  33637. }
  33638. DES.prototype._update = function (data) {
  33639. return Buffer.from(this._des.update(data))
  33640. }
  33641. DES.prototype._final = function () {
  33642. return Buffer.from(this._des.final())
  33643. }
  33644. },{"cipher-base":198,"des.js":212,"inherits":320,"safe-buffer":561}],164:[function(require,module,exports){
  33645. exports['des-ecb'] = {
  33646. key: 8,
  33647. iv: 0
  33648. }
  33649. exports['des-cbc'] = exports.des = {
  33650. key: 8,
  33651. iv: 8
  33652. }
  33653. exports['des-ede3-cbc'] = exports.des3 = {
  33654. key: 24,
  33655. iv: 8
  33656. }
  33657. exports['des-ede3'] = {
  33658. key: 24,
  33659. iv: 0
  33660. }
  33661. exports['des-ede-cbc'] = {
  33662. key: 16,
  33663. iv: 8
  33664. }
  33665. exports['des-ede'] = {
  33666. key: 16,
  33667. iv: 0
  33668. }
  33669. },{}],165:[function(require,module,exports){
  33670. (function (Buffer){(function (){
  33671. var BN = require('bn.js')
  33672. var randomBytes = require('randombytes')
  33673. function blind (priv) {
  33674. var r = getr(priv)
  33675. var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed()
  33676. return { blinder: blinder, unblinder: r.invm(priv.modulus) }
  33677. }
  33678. function getr (priv) {
  33679. var len = priv.modulus.byteLength()
  33680. var r
  33681. do {
  33682. r = new BN(randomBytes(len))
  33683. } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2))
  33684. return r
  33685. }
  33686. function crt (msg, priv) {
  33687. var blinds = blind(priv)
  33688. var len = priv.modulus.byteLength()
  33689. var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus)
  33690. var c1 = blinded.toRed(BN.mont(priv.prime1))
  33691. var c2 = blinded.toRed(BN.mont(priv.prime2))
  33692. var qinv = priv.coefficient
  33693. var p = priv.prime1
  33694. var q = priv.prime2
  33695. var m1 = c1.redPow(priv.exponent1).fromRed()
  33696. var m2 = c2.redPow(priv.exponent2).fromRed()
  33697. var h = m1.isub(m2).imul(qinv).umod(p).imul(q)
  33698. return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len)
  33699. }
  33700. crt.getr = getr
  33701. module.exports = crt
  33702. }).call(this)}).call(this,require("buffer").Buffer)
  33703. },{"bn.js":142,"buffer":193,"randombytes":544}],166:[function(require,module,exports){
  33704. module.exports = require('./browser/algorithms.json')
  33705. },{"./browser/algorithms.json":167}],167:[function(require,module,exports){
  33706. module.exports={
  33707. "sha224WithRSAEncryption": {
  33708. "sign": "rsa",
  33709. "hash": "sha224",
  33710. "id": "302d300d06096086480165030402040500041c"
  33711. },
  33712. "RSA-SHA224": {
  33713. "sign": "ecdsa/rsa",
  33714. "hash": "sha224",
  33715. "id": "302d300d06096086480165030402040500041c"
  33716. },
  33717. "sha256WithRSAEncryption": {
  33718. "sign": "rsa",
  33719. "hash": "sha256",
  33720. "id": "3031300d060960864801650304020105000420"
  33721. },
  33722. "RSA-SHA256": {
  33723. "sign": "ecdsa/rsa",
  33724. "hash": "sha256",
  33725. "id": "3031300d060960864801650304020105000420"
  33726. },
  33727. "sha384WithRSAEncryption": {
  33728. "sign": "rsa",
  33729. "hash": "sha384",
  33730. "id": "3041300d060960864801650304020205000430"
  33731. },
  33732. "RSA-SHA384": {
  33733. "sign": "ecdsa/rsa",
  33734. "hash": "sha384",
  33735. "id": "3041300d060960864801650304020205000430"
  33736. },
  33737. "sha512WithRSAEncryption": {
  33738. "sign": "rsa",
  33739. "hash": "sha512",
  33740. "id": "3051300d060960864801650304020305000440"
  33741. },
  33742. "RSA-SHA512": {
  33743. "sign": "ecdsa/rsa",
  33744. "hash": "sha512",
  33745. "id": "3051300d060960864801650304020305000440"
  33746. },
  33747. "RSA-SHA1": {
  33748. "sign": "rsa",
  33749. "hash": "sha1",
  33750. "id": "3021300906052b0e03021a05000414"
  33751. },
  33752. "ecdsa-with-SHA1": {
  33753. "sign": "ecdsa",
  33754. "hash": "sha1",
  33755. "id": ""
  33756. },
  33757. "sha256": {
  33758. "sign": "ecdsa",
  33759. "hash": "sha256",
  33760. "id": ""
  33761. },
  33762. "sha224": {
  33763. "sign": "ecdsa",
  33764. "hash": "sha224",
  33765. "id": ""
  33766. },
  33767. "sha384": {
  33768. "sign": "ecdsa",
  33769. "hash": "sha384",
  33770. "id": ""
  33771. },
  33772. "sha512": {
  33773. "sign": "ecdsa",
  33774. "hash": "sha512",
  33775. "id": ""
  33776. },
  33777. "DSA-SHA": {
  33778. "sign": "dsa",
  33779. "hash": "sha1",
  33780. "id": ""
  33781. },
  33782. "DSA-SHA1": {
  33783. "sign": "dsa",
  33784. "hash": "sha1",
  33785. "id": ""
  33786. },
  33787. "DSA": {
  33788. "sign": "dsa",
  33789. "hash": "sha1",
  33790. "id": ""
  33791. },
  33792. "DSA-WITH-SHA224": {
  33793. "sign": "dsa",
  33794. "hash": "sha224",
  33795. "id": ""
  33796. },
  33797. "DSA-SHA224": {
  33798. "sign": "dsa",
  33799. "hash": "sha224",
  33800. "id": ""
  33801. },
  33802. "DSA-WITH-SHA256": {
  33803. "sign": "dsa",
  33804. "hash": "sha256",
  33805. "id": ""
  33806. },
  33807. "DSA-SHA256": {
  33808. "sign": "dsa",
  33809. "hash": "sha256",
  33810. "id": ""
  33811. },
  33812. "DSA-WITH-SHA384": {
  33813. "sign": "dsa",
  33814. "hash": "sha384",
  33815. "id": ""
  33816. },
  33817. "DSA-SHA384": {
  33818. "sign": "dsa",
  33819. "hash": "sha384",
  33820. "id": ""
  33821. },
  33822. "DSA-WITH-SHA512": {
  33823. "sign": "dsa",
  33824. "hash": "sha512",
  33825. "id": ""
  33826. },
  33827. "DSA-SHA512": {
  33828. "sign": "dsa",
  33829. "hash": "sha512",
  33830. "id": ""
  33831. },
  33832. "DSA-RIPEMD160": {
  33833. "sign": "dsa",
  33834. "hash": "rmd160",
  33835. "id": ""
  33836. },
  33837. "ripemd160WithRSA": {
  33838. "sign": "rsa",
  33839. "hash": "rmd160",
  33840. "id": "3021300906052b2403020105000414"
  33841. },
  33842. "RSA-RIPEMD160": {
  33843. "sign": "rsa",
  33844. "hash": "rmd160",
  33845. "id": "3021300906052b2403020105000414"
  33846. },
  33847. "md5WithRSAEncryption": {
  33848. "sign": "rsa",
  33849. "hash": "md5",
  33850. "id": "3020300c06082a864886f70d020505000410"
  33851. },
  33852. "RSA-MD5": {
  33853. "sign": "rsa",
  33854. "hash": "md5",
  33855. "id": "3020300c06082a864886f70d020505000410"
  33856. }
  33857. }
  33858. },{}],168:[function(require,module,exports){
  33859. module.exports={
  33860. "1.3.132.0.10": "secp256k1",
  33861. "1.3.132.0.33": "p224",
  33862. "1.2.840.10045.3.1.1": "p192",
  33863. "1.2.840.10045.3.1.7": "p256",
  33864. "1.3.132.0.34": "p384",
  33865. "1.3.132.0.35": "p521"
  33866. }
  33867. },{}],169:[function(require,module,exports){
  33868. var Buffer = require('safe-buffer').Buffer
  33869. var createHash = require('create-hash')
  33870. var stream = require('readable-stream')
  33871. var inherits = require('inherits')
  33872. var sign = require('./sign')
  33873. var verify = require('./verify')
  33874. var algorithms = require('./algorithms.json')
  33875. Object.keys(algorithms).forEach(function (key) {
  33876. algorithms[key].id = Buffer.from(algorithms[key].id, 'hex')
  33877. algorithms[key.toLowerCase()] = algorithms[key]
  33878. })
  33879. function Sign (algorithm) {
  33880. stream.Writable.call(this)
  33881. var data = algorithms[algorithm]
  33882. if (!data) throw new Error('Unknown message digest')
  33883. this._hashType = data.hash
  33884. this._hash = createHash(data.hash)
  33885. this._tag = data.id
  33886. this._signType = data.sign
  33887. }
  33888. inherits(Sign, stream.Writable)
  33889. Sign.prototype._write = function _write (data, _, done) {
  33890. this._hash.update(data)
  33891. done()
  33892. }
  33893. Sign.prototype.update = function update (data, enc) {
  33894. if (typeof data === 'string') data = Buffer.from(data, enc)
  33895. this._hash.update(data)
  33896. return this
  33897. }
  33898. Sign.prototype.sign = function signMethod (key, enc) {
  33899. this.end()
  33900. var hash = this._hash.digest()
  33901. var sig = sign(hash, key, this._hashType, this._signType, this._tag)
  33902. return enc ? sig.toString(enc) : sig
  33903. }
  33904. function Verify (algorithm) {
  33905. stream.Writable.call(this)
  33906. var data = algorithms[algorithm]
  33907. if (!data) throw new Error('Unknown message digest')
  33908. this._hash = createHash(data.hash)
  33909. this._tag = data.id
  33910. this._signType = data.sign
  33911. }
  33912. inherits(Verify, stream.Writable)
  33913. Verify.prototype._write = function _write (data, _, done) {
  33914. this._hash.update(data)
  33915. done()
  33916. }
  33917. Verify.prototype.update = function update (data, enc) {
  33918. if (typeof data === 'string') data = Buffer.from(data, enc)
  33919. this._hash.update(data)
  33920. return this
  33921. }
  33922. Verify.prototype.verify = function verifyMethod (key, sig, enc) {
  33923. if (typeof sig === 'string') sig = Buffer.from(sig, enc)
  33924. this.end()
  33925. var hash = this._hash.digest()
  33926. return verify(sig, hash, key, this._signType, this._tag)
  33927. }
  33928. function createSign (algorithm) {
  33929. return new Sign(algorithm)
  33930. }
  33931. function createVerify (algorithm) {
  33932. return new Verify(algorithm)
  33933. }
  33934. module.exports = {
  33935. Sign: createSign,
  33936. Verify: createVerify,
  33937. createSign: createSign,
  33938. createVerify: createVerify
  33939. }
  33940. },{"./algorithms.json":167,"./sign":170,"./verify":171,"create-hash":204,"inherits":320,"readable-stream":186,"safe-buffer":187}],170:[function(require,module,exports){
  33941. // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
  33942. var Buffer = require('safe-buffer').Buffer
  33943. var createHmac = require('create-hmac')
  33944. var crt = require('browserify-rsa')
  33945. var EC = require('elliptic').ec
  33946. var BN = require('bn.js')
  33947. var parseKeys = require('parse-asn1')
  33948. var curves = require('./curves.json')
  33949. function sign (hash, key, hashType, signType, tag) {
  33950. var priv = parseKeys(key)
  33951. if (priv.curve) {
  33952. // rsa keys can be interpreted as ecdsa ones in openssl
  33953. if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
  33954. return ecSign(hash, priv)
  33955. } else if (priv.type === 'dsa') {
  33956. if (signType !== 'dsa') throw new Error('wrong private key type')
  33957. return dsaSign(hash, priv, hashType)
  33958. } else {
  33959. if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
  33960. }
  33961. hash = Buffer.concat([tag, hash])
  33962. var len = priv.modulus.byteLength()
  33963. var pad = [0, 1]
  33964. while (hash.length + pad.length + 1 < len) pad.push(0xff)
  33965. pad.push(0x00)
  33966. var i = -1
  33967. while (++i < hash.length) pad.push(hash[i])
  33968. var out = crt(pad, priv)
  33969. return out
  33970. }
  33971. function ecSign (hash, priv) {
  33972. var curveId = curves[priv.curve.join('.')]
  33973. if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
  33974. var curve = new EC(curveId)
  33975. var key = curve.keyFromPrivate(priv.privateKey)
  33976. var out = key.sign(hash)
  33977. return Buffer.from(out.toDER())
  33978. }
  33979. function dsaSign (hash, priv, algo) {
  33980. var x = priv.params.priv_key
  33981. var p = priv.params.p
  33982. var q = priv.params.q
  33983. var g = priv.params.g
  33984. var r = new BN(0)
  33985. var k
  33986. var H = bits2int(hash, q).mod(q)
  33987. var s = false
  33988. var kv = getKey(x, q, hash, algo)
  33989. while (s === false) {
  33990. k = makeKey(q, kv, algo)
  33991. r = makeR(g, k, p, q)
  33992. s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
  33993. if (s.cmpn(0) === 0) {
  33994. s = false
  33995. r = new BN(0)
  33996. }
  33997. }
  33998. return toDER(r, s)
  33999. }
  34000. function toDER (r, s) {
  34001. r = r.toArray()
  34002. s = s.toArray()
  34003. // Pad values
  34004. if (r[0] & 0x80) r = [0].concat(r)
  34005. if (s[0] & 0x80) s = [0].concat(s)
  34006. var total = r.length + s.length + 4
  34007. var res = [0x30, total, 0x02, r.length]
  34008. res = res.concat(r, [0x02, s.length], s)
  34009. return Buffer.from(res)
  34010. }
  34011. function getKey (x, q, hash, algo) {
  34012. x = Buffer.from(x.toArray())
  34013. if (x.length < q.byteLength()) {
  34014. var zeros = Buffer.alloc(q.byteLength() - x.length)
  34015. x = Buffer.concat([zeros, x])
  34016. }
  34017. var hlen = hash.length
  34018. var hbits = bits2octets(hash, q)
  34019. var v = Buffer.alloc(hlen)
  34020. v.fill(1)
  34021. var k = Buffer.alloc(hlen)
  34022. k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest()
  34023. v = createHmac(algo, k).update(v).digest()
  34024. k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest()
  34025. v = createHmac(algo, k).update(v).digest()
  34026. return { k: k, v: v }
  34027. }
  34028. function bits2int (obits, q) {
  34029. var bits = new BN(obits)
  34030. var shift = (obits.length << 3) - q.bitLength()
  34031. if (shift > 0) bits.ishrn(shift)
  34032. return bits
  34033. }
  34034. function bits2octets (bits, q) {
  34035. bits = bits2int(bits, q)
  34036. bits = bits.mod(q)
  34037. var out = Buffer.from(bits.toArray())
  34038. if (out.length < q.byteLength()) {
  34039. var zeros = Buffer.alloc(q.byteLength() - out.length)
  34040. out = Buffer.concat([zeros, out])
  34041. }
  34042. return out
  34043. }
  34044. function makeKey (q, kv, algo) {
  34045. var t
  34046. var k
  34047. do {
  34048. t = Buffer.alloc(0)
  34049. while (t.length * 8 < q.bitLength()) {
  34050. kv.v = createHmac(algo, kv.k).update(kv.v).digest()
  34051. t = Buffer.concat([t, kv.v])
  34052. }
  34053. k = bits2int(t, q)
  34054. kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest()
  34055. kv.v = createHmac(algo, kv.k).update(kv.v).digest()
  34056. } while (k.cmp(q) !== -1)
  34057. return k
  34058. }
  34059. function makeR (g, k, p, q) {
  34060. return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
  34061. }
  34062. module.exports = sign
  34063. module.exports.getKey = getKey
  34064. module.exports.makeKey = makeKey
  34065. },{"./curves.json":168,"bn.js":142,"browserify-rsa":165,"create-hmac":206,"elliptic":228,"parse-asn1":516,"safe-buffer":187}],171:[function(require,module,exports){
  34066. // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
  34067. var Buffer = require('safe-buffer').Buffer
  34068. var BN = require('bn.js')
  34069. var EC = require('elliptic').ec
  34070. var parseKeys = require('parse-asn1')
  34071. var curves = require('./curves.json')
  34072. function verify (sig, hash, key, signType, tag) {
  34073. var pub = parseKeys(key)
  34074. if (pub.type === 'ec') {
  34075. // rsa keys can be interpreted as ecdsa ones in openssl
  34076. if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
  34077. return ecVerify(sig, hash, pub)
  34078. } else if (pub.type === 'dsa') {
  34079. if (signType !== 'dsa') throw new Error('wrong public key type')
  34080. return dsaVerify(sig, hash, pub)
  34081. } else {
  34082. if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
  34083. }
  34084. hash = Buffer.concat([tag, hash])
  34085. var len = pub.modulus.byteLength()
  34086. var pad = [1]
  34087. var padNum = 0
  34088. while (hash.length + pad.length + 2 < len) {
  34089. pad.push(0xff)
  34090. padNum++
  34091. }
  34092. pad.push(0x00)
  34093. var i = -1
  34094. while (++i < hash.length) {
  34095. pad.push(hash[i])
  34096. }
  34097. pad = Buffer.from(pad)
  34098. var red = BN.mont(pub.modulus)
  34099. sig = new BN(sig).toRed(red)
  34100. sig = sig.redPow(new BN(pub.publicExponent))
  34101. sig = Buffer.from(sig.fromRed().toArray())
  34102. var out = padNum < 8 ? 1 : 0
  34103. len = Math.min(sig.length, pad.length)
  34104. if (sig.length !== pad.length) out = 1
  34105. i = -1
  34106. while (++i < len) out |= sig[i] ^ pad[i]
  34107. return out === 0
  34108. }
  34109. function ecVerify (sig, hash, pub) {
  34110. var curveId = curves[pub.data.algorithm.curve.join('.')]
  34111. if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
  34112. var curve = new EC(curveId)
  34113. var pubkey = pub.data.subjectPrivateKey.data
  34114. return curve.verify(hash, sig, pubkey)
  34115. }
  34116. function dsaVerify (sig, hash, pub) {
  34117. var p = pub.data.p
  34118. var q = pub.data.q
  34119. var g = pub.data.g
  34120. var y = pub.data.pub_key
  34121. var unpacked = parseKeys.signature.decode(sig, 'der')
  34122. var s = unpacked.s
  34123. var r = unpacked.r
  34124. checkValue(s, q)
  34125. checkValue(r, q)
  34126. var montp = BN.mont(p)
  34127. var w = s.invm(q)
  34128. var v = g.toRed(montp)
  34129. .redPow(new BN(hash).mul(w).mod(q))
  34130. .fromRed()
  34131. .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
  34132. .mod(p)
  34133. .mod(q)
  34134. return v.cmp(r) === 0
  34135. }
  34136. function checkValue (b, q) {
  34137. if (b.cmpn(0) <= 0) throw new Error('invalid sig')
  34138. if (b.cmp(q) >= q) throw new Error('invalid sig')
  34139. }
  34140. module.exports = verify
  34141. },{"./curves.json":168,"bn.js":142,"elliptic":228,"parse-asn1":516,"safe-buffer":187}],172:[function(require,module,exports){
  34142. 'use strict';
  34143. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  34144. var codes = {};
  34145. function createErrorType(code, message, Base) {
  34146. if (!Base) {
  34147. Base = Error;
  34148. }
  34149. function getMessage(arg1, arg2, arg3) {
  34150. if (typeof message === 'string') {
  34151. return message;
  34152. } else {
  34153. return message(arg1, arg2, arg3);
  34154. }
  34155. }
  34156. var NodeError =
  34157. /*#__PURE__*/
  34158. function (_Base) {
  34159. _inheritsLoose(NodeError, _Base);
  34160. function NodeError(arg1, arg2, arg3) {
  34161. return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
  34162. }
  34163. return NodeError;
  34164. }(Base);
  34165. NodeError.prototype.name = Base.name;
  34166. NodeError.prototype.code = code;
  34167. codes[code] = NodeError;
  34168. } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
  34169. function oneOf(expected, thing) {
  34170. if (Array.isArray(expected)) {
  34171. var len = expected.length;
  34172. expected = expected.map(function (i) {
  34173. return String(i);
  34174. });
  34175. if (len > 2) {
  34176. return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
  34177. } else if (len === 2) {
  34178. return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
  34179. } else {
  34180. return "of ".concat(thing, " ").concat(expected[0]);
  34181. }
  34182. } else {
  34183. return "of ".concat(thing, " ").concat(String(expected));
  34184. }
  34185. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
  34186. function startsWith(str, search, pos) {
  34187. return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  34188. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
  34189. function endsWith(str, search, this_len) {
  34190. if (this_len === undefined || this_len > str.length) {
  34191. this_len = str.length;
  34192. }
  34193. return str.substring(this_len - search.length, this_len) === search;
  34194. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
  34195. function includes(str, search, start) {
  34196. if (typeof start !== 'number') {
  34197. start = 0;
  34198. }
  34199. if (start + search.length > str.length) {
  34200. return false;
  34201. } else {
  34202. return str.indexOf(search, start) !== -1;
  34203. }
  34204. }
  34205. createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  34206. return 'The value "' + value + '" is invalid for option "' + name + '"';
  34207. }, TypeError);
  34208. createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  34209. // determiner: 'must be' or 'must not be'
  34210. var determiner;
  34211. if (typeof expected === 'string' && startsWith(expected, 'not ')) {
  34212. determiner = 'must not be';
  34213. expected = expected.replace(/^not /, '');
  34214. } else {
  34215. determiner = 'must be';
  34216. }
  34217. var msg;
  34218. if (endsWith(name, ' argument')) {
  34219. // For cases like 'first argument'
  34220. msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  34221. } else {
  34222. var type = includes(name, '.') ? 'property' : 'argument';
  34223. msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  34224. }
  34225. msg += ". Received type ".concat(typeof actual);
  34226. return msg;
  34227. }, TypeError);
  34228. createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
  34229. createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  34230. return 'The ' + name + ' method is not implemented';
  34231. });
  34232. createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
  34233. createErrorType('ERR_STREAM_DESTROYED', function (name) {
  34234. return 'Cannot call ' + name + ' after a stream was destroyed';
  34235. });
  34236. createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  34237. createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
  34238. createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
  34239. createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
  34240. createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  34241. return 'Unknown encoding: ' + arg;
  34242. }, TypeError);
  34243. createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
  34244. module.exports.codes = codes;
  34245. },{}],173:[function(require,module,exports){
  34246. (function (process){(function (){
  34247. // Copyright Joyent, Inc. and other Node contributors.
  34248. //
  34249. // Permission is hereby granted, free of charge, to any person obtaining a
  34250. // copy of this software and associated documentation files (the
  34251. // "Software"), to deal in the Software without restriction, including
  34252. // without limitation the rights to use, copy, modify, merge, publish,
  34253. // distribute, sublicense, and/or sell copies of the Software, and to permit
  34254. // persons to whom the Software is furnished to do so, subject to the
  34255. // following conditions:
  34256. //
  34257. // The above copyright notice and this permission notice shall be included
  34258. // in all copies or substantial portions of the Software.
  34259. //
  34260. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  34261. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  34262. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  34263. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  34264. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  34265. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  34266. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  34267. // a duplex stream is just a stream that is both readable and writable.
  34268. // Since JS doesn't have multiple prototypal inheritance, this class
  34269. // prototypally inherits from Readable, and then parasitically from
  34270. // Writable.
  34271. 'use strict';
  34272. /*<replacement>*/
  34273. var objectKeys = Object.keys || function (obj) {
  34274. var keys = [];
  34275. for (var key in obj) {
  34276. keys.push(key);
  34277. }
  34278. return keys;
  34279. };
  34280. /*</replacement>*/
  34281. module.exports = Duplex;
  34282. var Readable = require('./_stream_readable');
  34283. var Writable = require('./_stream_writable');
  34284. require('inherits')(Duplex, Readable);
  34285. {
  34286. // Allow the keys array to be GC'ed.
  34287. var keys = objectKeys(Writable.prototype);
  34288. for (var v = 0; v < keys.length; v++) {
  34289. var method = keys[v];
  34290. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  34291. }
  34292. }
  34293. function Duplex(options) {
  34294. if (!(this instanceof Duplex)) return new Duplex(options);
  34295. Readable.call(this, options);
  34296. Writable.call(this, options);
  34297. this.allowHalfOpen = true;
  34298. if (options) {
  34299. if (options.readable === false) this.readable = false;
  34300. if (options.writable === false) this.writable = false;
  34301. if (options.allowHalfOpen === false) {
  34302. this.allowHalfOpen = false;
  34303. this.once('end', onend);
  34304. }
  34305. }
  34306. }
  34307. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  34308. // making it explicit this property is not enumerable
  34309. // because otherwise some prototype manipulation in
  34310. // userland will fail
  34311. enumerable: false,
  34312. get: function get() {
  34313. return this._writableState.highWaterMark;
  34314. }
  34315. });
  34316. Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  34317. // making it explicit this property is not enumerable
  34318. // because otherwise some prototype manipulation in
  34319. // userland will fail
  34320. enumerable: false,
  34321. get: function get() {
  34322. return this._writableState && this._writableState.getBuffer();
  34323. }
  34324. });
  34325. Object.defineProperty(Duplex.prototype, 'writableLength', {
  34326. // making it explicit this property is not enumerable
  34327. // because otherwise some prototype manipulation in
  34328. // userland will fail
  34329. enumerable: false,
  34330. get: function get() {
  34331. return this._writableState.length;
  34332. }
  34333. }); // the no-half-open enforcer
  34334. function onend() {
  34335. // If the writable side ended, then we're ok.
  34336. if (this._writableState.ended) return; // no more data can be written.
  34337. // But allow more writes to happen in this tick.
  34338. process.nextTick(onEndNT, this);
  34339. }
  34340. function onEndNT(self) {
  34341. self.end();
  34342. }
  34343. Object.defineProperty(Duplex.prototype, 'destroyed', {
  34344. // making it explicit this property is not enumerable
  34345. // because otherwise some prototype manipulation in
  34346. // userland will fail
  34347. enumerable: false,
  34348. get: function get() {
  34349. if (this._readableState === undefined || this._writableState === undefined) {
  34350. return false;
  34351. }
  34352. return this._readableState.destroyed && this._writableState.destroyed;
  34353. },
  34354. set: function set(value) {
  34355. // we ignore the value if the stream
  34356. // has not been initialized yet
  34357. if (this._readableState === undefined || this._writableState === undefined) {
  34358. return;
  34359. } // backward compatibility, the user is explicitly
  34360. // managing destroyed
  34361. this._readableState.destroyed = value;
  34362. this._writableState.destroyed = value;
  34363. }
  34364. });
  34365. }).call(this)}).call(this,require('_process'))
  34366. },{"./_stream_readable":175,"./_stream_writable":177,"_process":525,"inherits":320}],174:[function(require,module,exports){
  34367. // Copyright Joyent, Inc. and other Node contributors.
  34368. //
  34369. // Permission is hereby granted, free of charge, to any person obtaining a
  34370. // copy of this software and associated documentation files (the
  34371. // "Software"), to deal in the Software without restriction, including
  34372. // without limitation the rights to use, copy, modify, merge, publish,
  34373. // distribute, sublicense, and/or sell copies of the Software, and to permit
  34374. // persons to whom the Software is furnished to do so, subject to the
  34375. // following conditions:
  34376. //
  34377. // The above copyright notice and this permission notice shall be included
  34378. // in all copies or substantial portions of the Software.
  34379. //
  34380. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  34381. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  34382. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  34383. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  34384. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  34385. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  34386. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  34387. // a passthrough stream.
  34388. // basically just the most minimal sort of Transform stream.
  34389. // Every written chunk gets output as-is.
  34390. 'use strict';
  34391. module.exports = PassThrough;
  34392. var Transform = require('./_stream_transform');
  34393. require('inherits')(PassThrough, Transform);
  34394. function PassThrough(options) {
  34395. if (!(this instanceof PassThrough)) return new PassThrough(options);
  34396. Transform.call(this, options);
  34397. }
  34398. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  34399. cb(null, chunk);
  34400. };
  34401. },{"./_stream_transform":176,"inherits":320}],175:[function(require,module,exports){
  34402. (function (process,global){(function (){
  34403. // Copyright Joyent, Inc. and other Node contributors.
  34404. //
  34405. // Permission is hereby granted, free of charge, to any person obtaining a
  34406. // copy of this software and associated documentation files (the
  34407. // "Software"), to deal in the Software without restriction, including
  34408. // without limitation the rights to use, copy, modify, merge, publish,
  34409. // distribute, sublicense, and/or sell copies of the Software, and to permit
  34410. // persons to whom the Software is furnished to do so, subject to the
  34411. // following conditions:
  34412. //
  34413. // The above copyright notice and this permission notice shall be included
  34414. // in all copies or substantial portions of the Software.
  34415. //
  34416. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  34417. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  34418. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  34419. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  34420. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  34421. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  34422. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  34423. 'use strict';
  34424. module.exports = Readable;
  34425. /*<replacement>*/
  34426. var Duplex;
  34427. /*</replacement>*/
  34428. Readable.ReadableState = ReadableState;
  34429. /*<replacement>*/
  34430. var EE = require('events').EventEmitter;
  34431. var EElistenerCount = function EElistenerCount(emitter, type) {
  34432. return emitter.listeners(type).length;
  34433. };
  34434. /*</replacement>*/
  34435. /*<replacement>*/
  34436. var Stream = require('./internal/streams/stream');
  34437. /*</replacement>*/
  34438. var Buffer = require('buffer').Buffer;
  34439. var OurUint8Array = global.Uint8Array || function () {};
  34440. function _uint8ArrayToBuffer(chunk) {
  34441. return Buffer.from(chunk);
  34442. }
  34443. function _isUint8Array(obj) {
  34444. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  34445. }
  34446. /*<replacement>*/
  34447. var debugUtil = require('util');
  34448. var debug;
  34449. if (debugUtil && debugUtil.debuglog) {
  34450. debug = debugUtil.debuglog('stream');
  34451. } else {
  34452. debug = function debug() {};
  34453. }
  34454. /*</replacement>*/
  34455. var BufferList = require('./internal/streams/buffer_list');
  34456. var destroyImpl = require('./internal/streams/destroy');
  34457. var _require = require('./internal/streams/state'),
  34458. getHighWaterMark = _require.getHighWaterMark;
  34459. var _require$codes = require('../errors').codes,
  34460. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  34461. ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  34462. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  34463. ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
  34464. var StringDecoder;
  34465. var createReadableStreamAsyncIterator;
  34466. var from;
  34467. require('inherits')(Readable, Stream);
  34468. var errorOrDestroy = destroyImpl.errorOrDestroy;
  34469. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  34470. function prependListener(emitter, event, fn) {
  34471. // Sadly this is not cacheable as some libraries bundle their own
  34472. // event emitter implementation with them.
  34473. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
  34474. // userland ones. NEVER DO THIS. This is here only because this code needs
  34475. // to continue to work with older versions of Node.js that do not include
  34476. // the prependListener() method. The goal is to eventually remove this hack.
  34477. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  34478. }
  34479. function ReadableState(options, stream, isDuplex) {
  34480. Duplex = Duplex || require('./_stream_duplex');
  34481. options = options || {}; // Duplex streams are both readable and writable, but share
  34482. // the same options object.
  34483. // However, some cases require setting options to different
  34484. // values for the readable and the writable sides of the duplex stream.
  34485. // These options can be provided separately as readableXXX and writableXXX.
  34486. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
  34487. // make all the buffer merging and length checks go away
  34488. this.objectMode = !!options.objectMode;
  34489. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
  34490. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  34491. this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
  34492. // linked list can remove elements from the beginning faster than
  34493. // array.shift()
  34494. this.buffer = new BufferList();
  34495. this.length = 0;
  34496. this.pipes = null;
  34497. this.pipesCount = 0;
  34498. this.flowing = null;
  34499. this.ended = false;
  34500. this.endEmitted = false;
  34501. this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
  34502. // immediately, or on a later tick. We set this to true at first, because
  34503. // any actions that shouldn't happen until "later" should generally also
  34504. // not happen before the first read call.
  34505. this.sync = true; // whenever we return null, then we set a flag to say
  34506. // that we're awaiting a 'readable' event emission.
  34507. this.needReadable = false;
  34508. this.emittedReadable = false;
  34509. this.readableListening = false;
  34510. this.resumeScheduled = false;
  34511. this.paused = true; // Should close be emitted on destroy. Defaults to true.
  34512. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
  34513. this.autoDestroy = !!options.autoDestroy; // has it been destroyed
  34514. this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
  34515. // encoding is 'binary' so we have to make this configurable.
  34516. // Everything else in the universe uses 'utf8', though.
  34517. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
  34518. this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
  34519. this.readingMore = false;
  34520. this.decoder = null;
  34521. this.encoding = null;
  34522. if (options.encoding) {
  34523. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  34524. this.decoder = new StringDecoder(options.encoding);
  34525. this.encoding = options.encoding;
  34526. }
  34527. }
  34528. function Readable(options) {
  34529. Duplex = Duplex || require('./_stream_duplex');
  34530. if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
  34531. // the ReadableState constructor, at least with V8 6.5
  34532. var isDuplex = this instanceof Duplex;
  34533. this._readableState = new ReadableState(options, this, isDuplex); // legacy
  34534. this.readable = true;
  34535. if (options) {
  34536. if (typeof options.read === 'function') this._read = options.read;
  34537. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  34538. }
  34539. Stream.call(this);
  34540. }
  34541. Object.defineProperty(Readable.prototype, 'destroyed', {
  34542. // making it explicit this property is not enumerable
  34543. // because otherwise some prototype manipulation in
  34544. // userland will fail
  34545. enumerable: false,
  34546. get: function get() {
  34547. if (this._readableState === undefined) {
  34548. return false;
  34549. }
  34550. return this._readableState.destroyed;
  34551. },
  34552. set: function set(value) {
  34553. // we ignore the value if the stream
  34554. // has not been initialized yet
  34555. if (!this._readableState) {
  34556. return;
  34557. } // backward compatibility, the user is explicitly
  34558. // managing destroyed
  34559. this._readableState.destroyed = value;
  34560. }
  34561. });
  34562. Readable.prototype.destroy = destroyImpl.destroy;
  34563. Readable.prototype._undestroy = destroyImpl.undestroy;
  34564. Readable.prototype._destroy = function (err, cb) {
  34565. cb(err);
  34566. }; // Manually shove something into the read() buffer.
  34567. // This returns true if the highWaterMark has not been hit yet,
  34568. // similar to how Writable.write() returns true if you should
  34569. // write() some more.
  34570. Readable.prototype.push = function (chunk, encoding) {
  34571. var state = this._readableState;
  34572. var skipChunkCheck;
  34573. if (!state.objectMode) {
  34574. if (typeof chunk === 'string') {
  34575. encoding = encoding || state.defaultEncoding;
  34576. if (encoding !== state.encoding) {
  34577. chunk = Buffer.from(chunk, encoding);
  34578. encoding = '';
  34579. }
  34580. skipChunkCheck = true;
  34581. }
  34582. } else {
  34583. skipChunkCheck = true;
  34584. }
  34585. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  34586. }; // Unshift should *always* be something directly out of read()
  34587. Readable.prototype.unshift = function (chunk) {
  34588. return readableAddChunk(this, chunk, null, true, false);
  34589. };
  34590. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  34591. debug('readableAddChunk', chunk);
  34592. var state = stream._readableState;
  34593. if (chunk === null) {
  34594. state.reading = false;
  34595. onEofChunk(stream, state);
  34596. } else {
  34597. var er;
  34598. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  34599. if (er) {
  34600. errorOrDestroy(stream, er);
  34601. } else if (state.objectMode || chunk && chunk.length > 0) {
  34602. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  34603. chunk = _uint8ArrayToBuffer(chunk);
  34604. }
  34605. if (addToFront) {
  34606. if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
  34607. } else if (state.ended) {
  34608. errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
  34609. } else if (state.destroyed) {
  34610. return false;
  34611. } else {
  34612. state.reading = false;
  34613. if (state.decoder && !encoding) {
  34614. chunk = state.decoder.write(chunk);
  34615. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  34616. } else {
  34617. addChunk(stream, state, chunk, false);
  34618. }
  34619. }
  34620. } else if (!addToFront) {
  34621. state.reading = false;
  34622. maybeReadMore(stream, state);
  34623. }
  34624. } // We can push more data if we are below the highWaterMark.
  34625. // Also, if we have no data yet, we can stand some more bytes.
  34626. // This is to work around cases where hwm=0, such as the repl.
  34627. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  34628. }
  34629. function addChunk(stream, state, chunk, addToFront) {
  34630. if (state.flowing && state.length === 0 && !state.sync) {
  34631. state.awaitDrain = 0;
  34632. stream.emit('data', chunk);
  34633. } else {
  34634. // update the buffer info.
  34635. state.length += state.objectMode ? 1 : chunk.length;
  34636. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  34637. if (state.needReadable) emitReadable(stream);
  34638. }
  34639. maybeReadMore(stream, state);
  34640. }
  34641. function chunkInvalid(state, chunk) {
  34642. var er;
  34643. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  34644. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  34645. }
  34646. return er;
  34647. }
  34648. Readable.prototype.isPaused = function () {
  34649. return this._readableState.flowing === false;
  34650. }; // backwards compatibility.
  34651. Readable.prototype.setEncoding = function (enc) {
  34652. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  34653. var decoder = new StringDecoder(enc);
  34654. this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
  34655. this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
  34656. var p = this._readableState.buffer.head;
  34657. var content = '';
  34658. while (p !== null) {
  34659. content += decoder.write(p.data);
  34660. p = p.next;
  34661. }
  34662. this._readableState.buffer.clear();
  34663. if (content !== '') this._readableState.buffer.push(content);
  34664. this._readableState.length = content.length;
  34665. return this;
  34666. }; // Don't raise the hwm > 1GB
  34667. var MAX_HWM = 0x40000000;
  34668. function computeNewHighWaterMark(n) {
  34669. if (n >= MAX_HWM) {
  34670. // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
  34671. n = MAX_HWM;
  34672. } else {
  34673. // Get the next highest power of 2 to prevent increasing hwm excessively in
  34674. // tiny amounts
  34675. n--;
  34676. n |= n >>> 1;
  34677. n |= n >>> 2;
  34678. n |= n >>> 4;
  34679. n |= n >>> 8;
  34680. n |= n >>> 16;
  34681. n++;
  34682. }
  34683. return n;
  34684. } // This function is designed to be inlinable, so please take care when making
  34685. // changes to the function body.
  34686. function howMuchToRead(n, state) {
  34687. if (n <= 0 || state.length === 0 && state.ended) return 0;
  34688. if (state.objectMode) return 1;
  34689. if (n !== n) {
  34690. // Only flow one buffer at a time
  34691. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  34692. } // If we're asking for more than the current hwm, then raise the hwm.
  34693. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  34694. if (n <= state.length) return n; // Don't have enough
  34695. if (!state.ended) {
  34696. state.needReadable = true;
  34697. return 0;
  34698. }
  34699. return state.length;
  34700. } // you can override either this method, or the async _read(n) below.
  34701. Readable.prototype.read = function (n) {
  34702. debug('read', n);
  34703. n = parseInt(n, 10);
  34704. var state = this._readableState;
  34705. var nOrig = n;
  34706. if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
  34707. // already have a bunch of data in the buffer, then just trigger
  34708. // the 'readable' event and move on.
  34709. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  34710. debug('read: emitReadable', state.length, state.ended);
  34711. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  34712. return null;
  34713. }
  34714. n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
  34715. if (n === 0 && state.ended) {
  34716. if (state.length === 0) endReadable(this);
  34717. return null;
  34718. } // All the actual chunk generation logic needs to be
  34719. // *below* the call to _read. The reason is that in certain
  34720. // synthetic stream cases, such as passthrough streams, _read
  34721. // may be a completely synchronous operation which may change
  34722. // the state of the read buffer, providing enough data when
  34723. // before there was *not* enough.
  34724. //
  34725. // So, the steps are:
  34726. // 1. Figure out what the state of things will be after we do
  34727. // a read from the buffer.
  34728. //
  34729. // 2. If that resulting state will trigger a _read, then call _read.
  34730. // Note that this may be asynchronous, or synchronous. Yes, it is
  34731. // deeply ugly to write APIs this way, but that still doesn't mean
  34732. // that the Readable class should behave improperly, as streams are
  34733. // designed to be sync/async agnostic.
  34734. // Take note if the _read call is sync or async (ie, if the read call
  34735. // has returned yet), so that we know whether or not it's safe to emit
  34736. // 'readable' etc.
  34737. //
  34738. // 3. Actually pull the requested chunks out of the buffer and return.
  34739. // if we need a readable event, then we need to do some reading.
  34740. var doRead = state.needReadable;
  34741. debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
  34742. if (state.length === 0 || state.length - n < state.highWaterMark) {
  34743. doRead = true;
  34744. debug('length less than watermark', doRead);
  34745. } // however, if we've ended, then there's no point, and if we're already
  34746. // reading, then it's unnecessary.
  34747. if (state.ended || state.reading) {
  34748. doRead = false;
  34749. debug('reading or ended', doRead);
  34750. } else if (doRead) {
  34751. debug('do read');
  34752. state.reading = true;
  34753. state.sync = true; // if the length is currently zero, then we *need* a readable event.
  34754. if (state.length === 0) state.needReadable = true; // call internal read method
  34755. this._read(state.highWaterMark);
  34756. state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
  34757. // and we need to re-evaluate how much data we can return to the user.
  34758. if (!state.reading) n = howMuchToRead(nOrig, state);
  34759. }
  34760. var ret;
  34761. if (n > 0) ret = fromList(n, state);else ret = null;
  34762. if (ret === null) {
  34763. state.needReadable = state.length <= state.highWaterMark;
  34764. n = 0;
  34765. } else {
  34766. state.length -= n;
  34767. state.awaitDrain = 0;
  34768. }
  34769. if (state.length === 0) {
  34770. // If we have nothing in the buffer, then we want to know
  34771. // as soon as we *do* get something into the buffer.
  34772. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
  34773. if (nOrig !== n && state.ended) endReadable(this);
  34774. }
  34775. if (ret !== null) this.emit('data', ret);
  34776. return ret;
  34777. };
  34778. function onEofChunk(stream, state) {
  34779. debug('onEofChunk');
  34780. if (state.ended) return;
  34781. if (state.decoder) {
  34782. var chunk = state.decoder.end();
  34783. if (chunk && chunk.length) {
  34784. state.buffer.push(chunk);
  34785. state.length += state.objectMode ? 1 : chunk.length;
  34786. }
  34787. }
  34788. state.ended = true;
  34789. if (state.sync) {
  34790. // if we are sync, wait until next tick to emit the data.
  34791. // Otherwise we risk emitting data in the flow()
  34792. // the readable code triggers during a read() call
  34793. emitReadable(stream);
  34794. } else {
  34795. // emit 'readable' now to make sure it gets picked up.
  34796. state.needReadable = false;
  34797. if (!state.emittedReadable) {
  34798. state.emittedReadable = true;
  34799. emitReadable_(stream);
  34800. }
  34801. }
  34802. } // Don't emit readable right away in sync mode, because this can trigger
  34803. // another read() call => stack overflow. This way, it might trigger
  34804. // a nextTick recursion warning, but that's not so bad.
  34805. function emitReadable(stream) {
  34806. var state = stream._readableState;
  34807. debug('emitReadable', state.needReadable, state.emittedReadable);
  34808. state.needReadable = false;
  34809. if (!state.emittedReadable) {
  34810. debug('emitReadable', state.flowing);
  34811. state.emittedReadable = true;
  34812. process.nextTick(emitReadable_, stream);
  34813. }
  34814. }
  34815. function emitReadable_(stream) {
  34816. var state = stream._readableState;
  34817. debug('emitReadable_', state.destroyed, state.length, state.ended);
  34818. if (!state.destroyed && (state.length || state.ended)) {
  34819. stream.emit('readable');
  34820. state.emittedReadable = false;
  34821. } // The stream needs another readable event if
  34822. // 1. It is not flowing, as the flow mechanism will take
  34823. // care of it.
  34824. // 2. It is not ended.
  34825. // 3. It is below the highWaterMark, so we can schedule
  34826. // another readable later.
  34827. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  34828. flow(stream);
  34829. } // at this point, the user has presumably seen the 'readable' event,
  34830. // and called read() to consume some data. that may have triggered
  34831. // in turn another _read(n) call, in which case reading = true if
  34832. // it's in progress.
  34833. // However, if we're not ended, or reading, and the length < hwm,
  34834. // then go ahead and try to read some more preemptively.
  34835. function maybeReadMore(stream, state) {
  34836. if (!state.readingMore) {
  34837. state.readingMore = true;
  34838. process.nextTick(maybeReadMore_, stream, state);
  34839. }
  34840. }
  34841. function maybeReadMore_(stream, state) {
  34842. // Attempt to read more data if we should.
  34843. //
  34844. // The conditions for reading more data are (one of):
  34845. // - Not enough data buffered (state.length < state.highWaterMark). The loop
  34846. // is responsible for filling the buffer with enough data if such data
  34847. // is available. If highWaterMark is 0 and we are not in the flowing mode
  34848. // we should _not_ attempt to buffer any extra data. We'll get more data
  34849. // when the stream consumer calls read() instead.
  34850. // - No data in the buffer, and the stream is in flowing mode. In this mode
  34851. // the loop below is responsible for ensuring read() is called. Failing to
  34852. // call read here would abort the flow and there's no other mechanism for
  34853. // continuing the flow if the stream consumer has just subscribed to the
  34854. // 'data' event.
  34855. //
  34856. // In addition to the above conditions to keep reading data, the following
  34857. // conditions prevent the data from being read:
  34858. // - The stream has ended (state.ended).
  34859. // - There is already a pending 'read' operation (state.reading). This is a
  34860. // case where the the stream has called the implementation defined _read()
  34861. // method, but they are processing the call asynchronously and have _not_
  34862. // called push() with new data. In this case we skip performing more
  34863. // read()s. The execution ends in this method again after the _read() ends
  34864. // up calling push() with more data.
  34865. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  34866. var len = state.length;
  34867. debug('maybeReadMore read 0');
  34868. stream.read(0);
  34869. if (len === state.length) // didn't get any data, stop spinning.
  34870. break;
  34871. }
  34872. state.readingMore = false;
  34873. } // abstract method. to be overridden in specific implementation classes.
  34874. // call cb(er, data) where data is <= n in length.
  34875. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  34876. // arbitrary, and perhaps not very meaningful.
  34877. Readable.prototype._read = function (n) {
  34878. errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
  34879. };
  34880. Readable.prototype.pipe = function (dest, pipeOpts) {
  34881. var src = this;
  34882. var state = this._readableState;
  34883. switch (state.pipesCount) {
  34884. case 0:
  34885. state.pipes = dest;
  34886. break;
  34887. case 1:
  34888. state.pipes = [state.pipes, dest];
  34889. break;
  34890. default:
  34891. state.pipes.push(dest);
  34892. break;
  34893. }
  34894. state.pipesCount += 1;
  34895. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  34896. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  34897. var endFn = doEnd ? onend : unpipe;
  34898. if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  34899. dest.on('unpipe', onunpipe);
  34900. function onunpipe(readable, unpipeInfo) {
  34901. debug('onunpipe');
  34902. if (readable === src) {
  34903. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  34904. unpipeInfo.hasUnpiped = true;
  34905. cleanup();
  34906. }
  34907. }
  34908. }
  34909. function onend() {
  34910. debug('onend');
  34911. dest.end();
  34912. } // when the dest drains, it reduces the awaitDrain counter
  34913. // on the source. This would be more elegant with a .once()
  34914. // handler in flow(), but adding and removing repeatedly is
  34915. // too slow.
  34916. var ondrain = pipeOnDrain(src);
  34917. dest.on('drain', ondrain);
  34918. var cleanedUp = false;
  34919. function cleanup() {
  34920. debug('cleanup'); // cleanup event handlers once the pipe is broken
  34921. dest.removeListener('close', onclose);
  34922. dest.removeListener('finish', onfinish);
  34923. dest.removeListener('drain', ondrain);
  34924. dest.removeListener('error', onerror);
  34925. dest.removeListener('unpipe', onunpipe);
  34926. src.removeListener('end', onend);
  34927. src.removeListener('end', unpipe);
  34928. src.removeListener('data', ondata);
  34929. cleanedUp = true; // if the reader is waiting for a drain event from this
  34930. // specific writer, then it would cause it to never start
  34931. // flowing again.
  34932. // So, if this is awaiting a drain, then we just call it now.
  34933. // If we don't know, then assume that we are waiting for one.
  34934. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  34935. }
  34936. src.on('data', ondata);
  34937. function ondata(chunk) {
  34938. debug('ondata');
  34939. var ret = dest.write(chunk);
  34940. debug('dest.write', ret);
  34941. if (ret === false) {
  34942. // If the user unpiped during `dest.write()`, it is possible
  34943. // to get stuck in a permanently paused state if that write
  34944. // also returned false.
  34945. // => Check whether `dest` is still a piping destination.
  34946. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  34947. debug('false write response, pause', state.awaitDrain);
  34948. state.awaitDrain++;
  34949. }
  34950. src.pause();
  34951. }
  34952. } // if the dest has an error, then stop piping into it.
  34953. // however, don't suppress the throwing behavior for this.
  34954. function onerror(er) {
  34955. debug('onerror', er);
  34956. unpipe();
  34957. dest.removeListener('error', onerror);
  34958. if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  34959. } // Make sure our error handler is attached before userland ones.
  34960. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
  34961. function onclose() {
  34962. dest.removeListener('finish', onfinish);
  34963. unpipe();
  34964. }
  34965. dest.once('close', onclose);
  34966. function onfinish() {
  34967. debug('onfinish');
  34968. dest.removeListener('close', onclose);
  34969. unpipe();
  34970. }
  34971. dest.once('finish', onfinish);
  34972. function unpipe() {
  34973. debug('unpipe');
  34974. src.unpipe(dest);
  34975. } // tell the dest that it's being piped to
  34976. dest.emit('pipe', src); // start the flow if it hasn't been started already.
  34977. if (!state.flowing) {
  34978. debug('pipe resume');
  34979. src.resume();
  34980. }
  34981. return dest;
  34982. };
  34983. function pipeOnDrain(src) {
  34984. return function pipeOnDrainFunctionResult() {
  34985. var state = src._readableState;
  34986. debug('pipeOnDrain', state.awaitDrain);
  34987. if (state.awaitDrain) state.awaitDrain--;
  34988. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  34989. state.flowing = true;
  34990. flow(src);
  34991. }
  34992. };
  34993. }
  34994. Readable.prototype.unpipe = function (dest) {
  34995. var state = this._readableState;
  34996. var unpipeInfo = {
  34997. hasUnpiped: false
  34998. }; // if we're not piping anywhere, then do nothing.
  34999. if (state.pipesCount === 0) return this; // just one destination. most common case.
  35000. if (state.pipesCount === 1) {
  35001. // passed in one, but it's not the right one.
  35002. if (dest && dest !== state.pipes) return this;
  35003. if (!dest) dest = state.pipes; // got a match.
  35004. state.pipes = null;
  35005. state.pipesCount = 0;
  35006. state.flowing = false;
  35007. if (dest) dest.emit('unpipe', this, unpipeInfo);
  35008. return this;
  35009. } // slow case. multiple pipe destinations.
  35010. if (!dest) {
  35011. // remove all.
  35012. var dests = state.pipes;
  35013. var len = state.pipesCount;
  35014. state.pipes = null;
  35015. state.pipesCount = 0;
  35016. state.flowing = false;
  35017. for (var i = 0; i < len; i++) {
  35018. dests[i].emit('unpipe', this, {
  35019. hasUnpiped: false
  35020. });
  35021. }
  35022. return this;
  35023. } // try to find the right one.
  35024. var index = indexOf(state.pipes, dest);
  35025. if (index === -1) return this;
  35026. state.pipes.splice(index, 1);
  35027. state.pipesCount -= 1;
  35028. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  35029. dest.emit('unpipe', this, unpipeInfo);
  35030. return this;
  35031. }; // set up data events if they are asked for
  35032. // Ensure readable listeners eventually get something
  35033. Readable.prototype.on = function (ev, fn) {
  35034. var res = Stream.prototype.on.call(this, ev, fn);
  35035. var state = this._readableState;
  35036. if (ev === 'data') {
  35037. // update readableListening so that resume() may be a no-op
  35038. // a few lines down. This is needed to support once('readable').
  35039. state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
  35040. if (state.flowing !== false) this.resume();
  35041. } else if (ev === 'readable') {
  35042. if (!state.endEmitted && !state.readableListening) {
  35043. state.readableListening = state.needReadable = true;
  35044. state.flowing = false;
  35045. state.emittedReadable = false;
  35046. debug('on readable', state.length, state.reading);
  35047. if (state.length) {
  35048. emitReadable(this);
  35049. } else if (!state.reading) {
  35050. process.nextTick(nReadingNextTick, this);
  35051. }
  35052. }
  35053. }
  35054. return res;
  35055. };
  35056. Readable.prototype.addListener = Readable.prototype.on;
  35057. Readable.prototype.removeListener = function (ev, fn) {
  35058. var res = Stream.prototype.removeListener.call(this, ev, fn);
  35059. if (ev === 'readable') {
  35060. // We need to check if there is someone still listening to
  35061. // readable and reset the state. However this needs to happen
  35062. // after readable has been emitted but before I/O (nextTick) to
  35063. // support once('readable', fn) cycles. This means that calling
  35064. // resume within the same tick will have no
  35065. // effect.
  35066. process.nextTick(updateReadableListening, this);
  35067. }
  35068. return res;
  35069. };
  35070. Readable.prototype.removeAllListeners = function (ev) {
  35071. var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  35072. if (ev === 'readable' || ev === undefined) {
  35073. // We need to check if there is someone still listening to
  35074. // readable and reset the state. However this needs to happen
  35075. // after readable has been emitted but before I/O (nextTick) to
  35076. // support once('readable', fn) cycles. This means that calling
  35077. // resume within the same tick will have no
  35078. // effect.
  35079. process.nextTick(updateReadableListening, this);
  35080. }
  35081. return res;
  35082. };
  35083. function updateReadableListening(self) {
  35084. var state = self._readableState;
  35085. state.readableListening = self.listenerCount('readable') > 0;
  35086. if (state.resumeScheduled && !state.paused) {
  35087. // flowing needs to be set to true now, otherwise
  35088. // the upcoming resume will not flow.
  35089. state.flowing = true; // crude way to check if we should resume
  35090. } else if (self.listenerCount('data') > 0) {
  35091. self.resume();
  35092. }
  35093. }
  35094. function nReadingNextTick(self) {
  35095. debug('readable nexttick read 0');
  35096. self.read(0);
  35097. } // pause() and resume() are remnants of the legacy readable stream API
  35098. // If the user uses them, then switch into old mode.
  35099. Readable.prototype.resume = function () {
  35100. var state = this._readableState;
  35101. if (!state.flowing) {
  35102. debug('resume'); // we flow only if there is no one listening
  35103. // for readable, but we still have to call
  35104. // resume()
  35105. state.flowing = !state.readableListening;
  35106. resume(this, state);
  35107. }
  35108. state.paused = false;
  35109. return this;
  35110. };
  35111. function resume(stream, state) {
  35112. if (!state.resumeScheduled) {
  35113. state.resumeScheduled = true;
  35114. process.nextTick(resume_, stream, state);
  35115. }
  35116. }
  35117. function resume_(stream, state) {
  35118. debug('resume', state.reading);
  35119. if (!state.reading) {
  35120. stream.read(0);
  35121. }
  35122. state.resumeScheduled = false;
  35123. stream.emit('resume');
  35124. flow(stream);
  35125. if (state.flowing && !state.reading) stream.read(0);
  35126. }
  35127. Readable.prototype.pause = function () {
  35128. debug('call pause flowing=%j', this._readableState.flowing);
  35129. if (this._readableState.flowing !== false) {
  35130. debug('pause');
  35131. this._readableState.flowing = false;
  35132. this.emit('pause');
  35133. }
  35134. this._readableState.paused = true;
  35135. return this;
  35136. };
  35137. function flow(stream) {
  35138. var state = stream._readableState;
  35139. debug('flow', state.flowing);
  35140. while (state.flowing && stream.read() !== null) {
  35141. ;
  35142. }
  35143. } // wrap an old-style stream as the async data source.
  35144. // This is *not* part of the readable stream interface.
  35145. // It is an ugly unfortunate mess of history.
  35146. Readable.prototype.wrap = function (stream) {
  35147. var _this = this;
  35148. var state = this._readableState;
  35149. var paused = false;
  35150. stream.on('end', function () {
  35151. debug('wrapped end');
  35152. if (state.decoder && !state.ended) {
  35153. var chunk = state.decoder.end();
  35154. if (chunk && chunk.length) _this.push(chunk);
  35155. }
  35156. _this.push(null);
  35157. });
  35158. stream.on('data', function (chunk) {
  35159. debug('wrapped data');
  35160. if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
  35161. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  35162. var ret = _this.push(chunk);
  35163. if (!ret) {
  35164. paused = true;
  35165. stream.pause();
  35166. }
  35167. }); // proxy all the other methods.
  35168. // important when wrapping filters and duplexes.
  35169. for (var i in stream) {
  35170. if (this[i] === undefined && typeof stream[i] === 'function') {
  35171. this[i] = function methodWrap(method) {
  35172. return function methodWrapReturnFunction() {
  35173. return stream[method].apply(stream, arguments);
  35174. };
  35175. }(i);
  35176. }
  35177. } // proxy certain important events.
  35178. for (var n = 0; n < kProxyEvents.length; n++) {
  35179. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  35180. } // when we try to consume some more bytes, simply unpause the
  35181. // underlying stream.
  35182. this._read = function (n) {
  35183. debug('wrapped _read', n);
  35184. if (paused) {
  35185. paused = false;
  35186. stream.resume();
  35187. }
  35188. };
  35189. return this;
  35190. };
  35191. if (typeof Symbol === 'function') {
  35192. Readable.prototype[Symbol.asyncIterator] = function () {
  35193. if (createReadableStreamAsyncIterator === undefined) {
  35194. createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
  35195. }
  35196. return createReadableStreamAsyncIterator(this);
  35197. };
  35198. }
  35199. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  35200. // making it explicit this property is not enumerable
  35201. // because otherwise some prototype manipulation in
  35202. // userland will fail
  35203. enumerable: false,
  35204. get: function get() {
  35205. return this._readableState.highWaterMark;
  35206. }
  35207. });
  35208. Object.defineProperty(Readable.prototype, 'readableBuffer', {
  35209. // making it explicit this property is not enumerable
  35210. // because otherwise some prototype manipulation in
  35211. // userland will fail
  35212. enumerable: false,
  35213. get: function get() {
  35214. return this._readableState && this._readableState.buffer;
  35215. }
  35216. });
  35217. Object.defineProperty(Readable.prototype, 'readableFlowing', {
  35218. // making it explicit this property is not enumerable
  35219. // because otherwise some prototype manipulation in
  35220. // userland will fail
  35221. enumerable: false,
  35222. get: function get() {
  35223. return this._readableState.flowing;
  35224. },
  35225. set: function set(state) {
  35226. if (this._readableState) {
  35227. this._readableState.flowing = state;
  35228. }
  35229. }
  35230. }); // exposed for testing purposes only.
  35231. Readable._fromList = fromList;
  35232. Object.defineProperty(Readable.prototype, 'readableLength', {
  35233. // making it explicit this property is not enumerable
  35234. // because otherwise some prototype manipulation in
  35235. // userland will fail
  35236. enumerable: false,
  35237. get: function get() {
  35238. return this._readableState.length;
  35239. }
  35240. }); // Pluck off n bytes from an array of buffers.
  35241. // Length is the combined lengths of all the buffers in the list.
  35242. // This function is designed to be inlinable, so please take care when making
  35243. // changes to the function body.
  35244. function fromList(n, state) {
  35245. // nothing buffered
  35246. if (state.length === 0) return null;
  35247. var ret;
  35248. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  35249. // read it all, truncate the list
  35250. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
  35251. state.buffer.clear();
  35252. } else {
  35253. // read part of list
  35254. ret = state.buffer.consume(n, state.decoder);
  35255. }
  35256. return ret;
  35257. }
  35258. function endReadable(stream) {
  35259. var state = stream._readableState;
  35260. debug('endReadable', state.endEmitted);
  35261. if (!state.endEmitted) {
  35262. state.ended = true;
  35263. process.nextTick(endReadableNT, state, stream);
  35264. }
  35265. }
  35266. function endReadableNT(state, stream) {
  35267. debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
  35268. if (!state.endEmitted && state.length === 0) {
  35269. state.endEmitted = true;
  35270. stream.readable = false;
  35271. stream.emit('end');
  35272. if (state.autoDestroy) {
  35273. // In case of duplex streams we need a way to detect
  35274. // if the writable side is ready for autoDestroy as well
  35275. var wState = stream._writableState;
  35276. if (!wState || wState.autoDestroy && wState.finished) {
  35277. stream.destroy();
  35278. }
  35279. }
  35280. }
  35281. }
  35282. if (typeof Symbol === 'function') {
  35283. Readable.from = function (iterable, opts) {
  35284. if (from === undefined) {
  35285. from = require('./internal/streams/from');
  35286. }
  35287. return from(Readable, iterable, opts);
  35288. };
  35289. }
  35290. function indexOf(xs, x) {
  35291. for (var i = 0, l = xs.length; i < l; i++) {
  35292. if (xs[i] === x) return i;
  35293. }
  35294. return -1;
  35295. }
  35296. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  35297. },{"../errors":172,"./_stream_duplex":173,"./internal/streams/async_iterator":178,"./internal/streams/buffer_list":179,"./internal/streams/destroy":180,"./internal/streams/from":182,"./internal/streams/state":184,"./internal/streams/stream":185,"_process":525,"buffer":193,"events":247,"inherits":320,"string_decoder/":631,"util":144}],176:[function(require,module,exports){
  35298. // Copyright Joyent, Inc. and other Node contributors.
  35299. //
  35300. // Permission is hereby granted, free of charge, to any person obtaining a
  35301. // copy of this software and associated documentation files (the
  35302. // "Software"), to deal in the Software without restriction, including
  35303. // without limitation the rights to use, copy, modify, merge, publish,
  35304. // distribute, sublicense, and/or sell copies of the Software, and to permit
  35305. // persons to whom the Software is furnished to do so, subject to the
  35306. // following conditions:
  35307. //
  35308. // The above copyright notice and this permission notice shall be included
  35309. // in all copies or substantial portions of the Software.
  35310. //
  35311. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  35312. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  35313. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  35314. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  35315. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  35316. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  35317. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  35318. // a transform stream is a readable/writable stream where you do
  35319. // something with the data. Sometimes it's called a "filter",
  35320. // but that's not a great name for it, since that implies a thing where
  35321. // some bits pass through, and others are simply ignored. (That would
  35322. // be a valid example of a transform, of course.)
  35323. //
  35324. // While the output is causally related to the input, it's not a
  35325. // necessarily symmetric or synchronous transformation. For example,
  35326. // a zlib stream might take multiple plain-text writes(), and then
  35327. // emit a single compressed chunk some time in the future.
  35328. //
  35329. // Here's how this works:
  35330. //
  35331. // The Transform stream has all the aspects of the readable and writable
  35332. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  35333. // internally, and returns false if there's a lot of pending writes
  35334. // buffered up. When you call read(), that calls _read(n) until
  35335. // there's enough pending readable data buffered up.
  35336. //
  35337. // In a transform stream, the written data is placed in a buffer. When
  35338. // _read(n) is called, it transforms the queued up data, calling the
  35339. // buffered _write cb's as it consumes chunks. If consuming a single
  35340. // written chunk would result in multiple output chunks, then the first
  35341. // outputted bit calls the readcb, and subsequent chunks just go into
  35342. // the read buffer, and will cause it to emit 'readable' if necessary.
  35343. //
  35344. // This way, back-pressure is actually determined by the reading side,
  35345. // since _read has to be called to start processing a new chunk. However,
  35346. // a pathological inflate type of transform can cause excessive buffering
  35347. // here. For example, imagine a stream where every byte of input is
  35348. // interpreted as an integer from 0-255, and then results in that many
  35349. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  35350. // 1kb of data being output. In this case, you could write a very small
  35351. // amount of input, and end up with a very large amount of output. In
  35352. // such a pathological inflating mechanism, there'd be no way to tell
  35353. // the system to stop doing the transform. A single 4MB write could
  35354. // cause the system to run out of memory.
  35355. //
  35356. // However, even in such a pathological case, only a single written chunk
  35357. // would be consumed, and then the rest would wait (un-transformed) until
  35358. // the results of the previous transformed chunk were consumed.
  35359. 'use strict';
  35360. module.exports = Transform;
  35361. var _require$codes = require('../errors').codes,
  35362. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  35363. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  35364. ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  35365. ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  35366. var Duplex = require('./_stream_duplex');
  35367. require('inherits')(Transform, Duplex);
  35368. function afterTransform(er, data) {
  35369. var ts = this._transformState;
  35370. ts.transforming = false;
  35371. var cb = ts.writecb;
  35372. if (cb === null) {
  35373. return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  35374. }
  35375. ts.writechunk = null;
  35376. ts.writecb = null;
  35377. if (data != null) // single equals check for both `null` and `undefined`
  35378. this.push(data);
  35379. cb(er);
  35380. var rs = this._readableState;
  35381. rs.reading = false;
  35382. if (rs.needReadable || rs.length < rs.highWaterMark) {
  35383. this._read(rs.highWaterMark);
  35384. }
  35385. }
  35386. function Transform(options) {
  35387. if (!(this instanceof Transform)) return new Transform(options);
  35388. Duplex.call(this, options);
  35389. this._transformState = {
  35390. afterTransform: afterTransform.bind(this),
  35391. needTransform: false,
  35392. transforming: false,
  35393. writecb: null,
  35394. writechunk: null,
  35395. writeencoding: null
  35396. }; // start out asking for a readable event once data is transformed.
  35397. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
  35398. // that Readable wants before the first _read call, so unset the
  35399. // sync guard flag.
  35400. this._readableState.sync = false;
  35401. if (options) {
  35402. if (typeof options.transform === 'function') this._transform = options.transform;
  35403. if (typeof options.flush === 'function') this._flush = options.flush;
  35404. } // When the writable side finishes, then flush out anything remaining.
  35405. this.on('prefinish', prefinish);
  35406. }
  35407. function prefinish() {
  35408. var _this = this;
  35409. if (typeof this._flush === 'function' && !this._readableState.destroyed) {
  35410. this._flush(function (er, data) {
  35411. done(_this, er, data);
  35412. });
  35413. } else {
  35414. done(this, null, null);
  35415. }
  35416. }
  35417. Transform.prototype.push = function (chunk, encoding) {
  35418. this._transformState.needTransform = false;
  35419. return Duplex.prototype.push.call(this, chunk, encoding);
  35420. }; // This is the part where you do stuff!
  35421. // override this function in implementation classes.
  35422. // 'chunk' is an input chunk.
  35423. //
  35424. // Call `push(newChunk)` to pass along transformed output
  35425. // to the readable side. You may call 'push' zero or more times.
  35426. //
  35427. // Call `cb(err)` when you are done with this chunk. If you pass
  35428. // an error, then that'll put the hurt on the whole operation. If you
  35429. // never call cb(), then you'll never get another chunk.
  35430. Transform.prototype._transform = function (chunk, encoding, cb) {
  35431. cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
  35432. };
  35433. Transform.prototype._write = function (chunk, encoding, cb) {
  35434. var ts = this._transformState;
  35435. ts.writecb = cb;
  35436. ts.writechunk = chunk;
  35437. ts.writeencoding = encoding;
  35438. if (!ts.transforming) {
  35439. var rs = this._readableState;
  35440. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  35441. }
  35442. }; // Doesn't matter what the args are here.
  35443. // _transform does all the work.
  35444. // That we got here means that the readable side wants more data.
  35445. Transform.prototype._read = function (n) {
  35446. var ts = this._transformState;
  35447. if (ts.writechunk !== null && !ts.transforming) {
  35448. ts.transforming = true;
  35449. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  35450. } else {
  35451. // mark that we need a transform, so that any data that comes in
  35452. // will get processed, now that we've asked for it.
  35453. ts.needTransform = true;
  35454. }
  35455. };
  35456. Transform.prototype._destroy = function (err, cb) {
  35457. Duplex.prototype._destroy.call(this, err, function (err2) {
  35458. cb(err2);
  35459. });
  35460. };
  35461. function done(stream, er, data) {
  35462. if (er) return stream.emit('error', er);
  35463. if (data != null) // single equals check for both `null` and `undefined`
  35464. stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
  35465. // if there's nothing in the write buffer, then that means
  35466. // that nothing more will ever be provided
  35467. if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  35468. if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  35469. return stream.push(null);
  35470. }
  35471. },{"../errors":172,"./_stream_duplex":173,"inherits":320}],177:[function(require,module,exports){
  35472. (function (process,global){(function (){
  35473. // Copyright Joyent, Inc. and other Node contributors.
  35474. //
  35475. // Permission is hereby granted, free of charge, to any person obtaining a
  35476. // copy of this software and associated documentation files (the
  35477. // "Software"), to deal in the Software without restriction, including
  35478. // without limitation the rights to use, copy, modify, merge, publish,
  35479. // distribute, sublicense, and/or sell copies of the Software, and to permit
  35480. // persons to whom the Software is furnished to do so, subject to the
  35481. // following conditions:
  35482. //
  35483. // The above copyright notice and this permission notice shall be included
  35484. // in all copies or substantial portions of the Software.
  35485. //
  35486. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  35487. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  35488. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  35489. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  35490. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  35491. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  35492. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  35493. // A bit simpler than readable streams.
  35494. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  35495. // the drain event emission and buffering.
  35496. 'use strict';
  35497. module.exports = Writable;
  35498. /* <replacement> */
  35499. function WriteReq(chunk, encoding, cb) {
  35500. this.chunk = chunk;
  35501. this.encoding = encoding;
  35502. this.callback = cb;
  35503. this.next = null;
  35504. } // It seems a linked list but it is not
  35505. // there will be only 2 of these for each stream
  35506. function CorkedRequest(state) {
  35507. var _this = this;
  35508. this.next = null;
  35509. this.entry = null;
  35510. this.finish = function () {
  35511. onCorkedFinish(_this, state);
  35512. };
  35513. }
  35514. /* </replacement> */
  35515. /*<replacement>*/
  35516. var Duplex;
  35517. /*</replacement>*/
  35518. Writable.WritableState = WritableState;
  35519. /*<replacement>*/
  35520. var internalUtil = {
  35521. deprecate: require('util-deprecate')
  35522. };
  35523. /*</replacement>*/
  35524. /*<replacement>*/
  35525. var Stream = require('./internal/streams/stream');
  35526. /*</replacement>*/
  35527. var Buffer = require('buffer').Buffer;
  35528. var OurUint8Array = global.Uint8Array || function () {};
  35529. function _uint8ArrayToBuffer(chunk) {
  35530. return Buffer.from(chunk);
  35531. }
  35532. function _isUint8Array(obj) {
  35533. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  35534. }
  35535. var destroyImpl = require('./internal/streams/destroy');
  35536. var _require = require('./internal/streams/state'),
  35537. getHighWaterMark = _require.getHighWaterMark;
  35538. var _require$codes = require('../errors').codes,
  35539. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  35540. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  35541. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  35542. ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  35543. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  35544. ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  35545. ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  35546. ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  35547. var errorOrDestroy = destroyImpl.errorOrDestroy;
  35548. require('inherits')(Writable, Stream);
  35549. function nop() {}
  35550. function WritableState(options, stream, isDuplex) {
  35551. Duplex = Duplex || require('./_stream_duplex');
  35552. options = options || {}; // Duplex streams are both readable and writable, but share
  35553. // the same options object.
  35554. // However, some cases require setting options to different
  35555. // values for the readable and the writable sides of the duplex stream,
  35556. // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  35557. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
  35558. // contains buffers or objects.
  35559. this.objectMode = !!options.objectMode;
  35560. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
  35561. // Note: 0 is a valid value, means that we always return false if
  35562. // the entire buffer is not flushed immediately on write()
  35563. this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
  35564. this.finalCalled = false; // drain event flag.
  35565. this.needDrain = false; // at the start of calling end()
  35566. this.ending = false; // when end() has been called, and returned
  35567. this.ended = false; // when 'finish' is emitted
  35568. this.finished = false; // has it been destroyed
  35569. this.destroyed = false; // should we decode strings into buffers before passing to _write?
  35570. // this is here so that some node-core streams can optimize string
  35571. // handling at a lower level.
  35572. var noDecode = options.decodeStrings === false;
  35573. this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
  35574. // encoding is 'binary' so we have to make this configurable.
  35575. // Everything else in the universe uses 'utf8', though.
  35576. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
  35577. // of how much we're waiting to get pushed to some underlying
  35578. // socket or file.
  35579. this.length = 0; // a flag to see when we're in the middle of a write.
  35580. this.writing = false; // when true all writes will be buffered until .uncork() call
  35581. this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
  35582. // or on a later tick. We set this to true at first, because any
  35583. // actions that shouldn't happen until "later" should generally also
  35584. // not happen before the first write call.
  35585. this.sync = true; // a flag to know if we're processing previously buffered items, which
  35586. // may call the _write() callback in the same tick, so that we don't
  35587. // end up in an overlapped onwrite situation.
  35588. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
  35589. this.onwrite = function (er) {
  35590. onwrite(stream, er);
  35591. }; // the callback that the user supplies to write(chunk,encoding,cb)
  35592. this.writecb = null; // the amount that is being written when _write is called.
  35593. this.writelen = 0;
  35594. this.bufferedRequest = null;
  35595. this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
  35596. // this must be 0 before 'finish' can be emitted
  35597. this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
  35598. // This is relevant for synchronous Transform streams
  35599. this.prefinished = false; // True if the error was already emitted and should not be thrown again
  35600. this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
  35601. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
  35602. this.autoDestroy = !!options.autoDestroy; // count buffered requests
  35603. this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
  35604. // one allocated and free to use, and we maintain at most two
  35605. this.corkedRequestsFree = new CorkedRequest(this);
  35606. }
  35607. WritableState.prototype.getBuffer = function getBuffer() {
  35608. var current = this.bufferedRequest;
  35609. var out = [];
  35610. while (current) {
  35611. out.push(current);
  35612. current = current.next;
  35613. }
  35614. return out;
  35615. };
  35616. (function () {
  35617. try {
  35618. Object.defineProperty(WritableState.prototype, 'buffer', {
  35619. get: internalUtil.deprecate(function writableStateBufferGetter() {
  35620. return this.getBuffer();
  35621. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  35622. });
  35623. } catch (_) {}
  35624. })(); // Test _writableState for inheritance to account for Duplex streams,
  35625. // whose prototype chain only points to Readable.
  35626. var realHasInstance;
  35627. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  35628. realHasInstance = Function.prototype[Symbol.hasInstance];
  35629. Object.defineProperty(Writable, Symbol.hasInstance, {
  35630. value: function value(object) {
  35631. if (realHasInstance.call(this, object)) return true;
  35632. if (this !== Writable) return false;
  35633. return object && object._writableState instanceof WritableState;
  35634. }
  35635. });
  35636. } else {
  35637. realHasInstance = function realHasInstance(object) {
  35638. return object instanceof this;
  35639. };
  35640. }
  35641. function Writable(options) {
  35642. Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
  35643. // `realHasInstance` is necessary because using plain `instanceof`
  35644. // would return false, as no `_writableState` property is attached.
  35645. // Trying to use the custom `instanceof` for Writable here will also break the
  35646. // Node.js LazyTransform implementation, which has a non-trivial getter for
  35647. // `_writableState` that would lead to infinite recursion.
  35648. // Checking for a Stream.Duplex instance is faster here instead of inside
  35649. // the WritableState constructor, at least with V8 6.5
  35650. var isDuplex = this instanceof Duplex;
  35651. if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  35652. this._writableState = new WritableState(options, this, isDuplex); // legacy.
  35653. this.writable = true;
  35654. if (options) {
  35655. if (typeof options.write === 'function') this._write = options.write;
  35656. if (typeof options.writev === 'function') this._writev = options.writev;
  35657. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  35658. if (typeof options.final === 'function') this._final = options.final;
  35659. }
  35660. Stream.call(this);
  35661. } // Otherwise people can pipe Writable streams, which is just wrong.
  35662. Writable.prototype.pipe = function () {
  35663. errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  35664. };
  35665. function writeAfterEnd(stream, cb) {
  35666. var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
  35667. errorOrDestroy(stream, er);
  35668. process.nextTick(cb, er);
  35669. } // Checks that a user-supplied chunk is valid, especially for the particular
  35670. // mode the stream is in. Currently this means that `null` is never accepted
  35671. // and undefined/non-string values are only allowed in object mode.
  35672. function validChunk(stream, state, chunk, cb) {
  35673. var er;
  35674. if (chunk === null) {
  35675. er = new ERR_STREAM_NULL_VALUES();
  35676. } else if (typeof chunk !== 'string' && !state.objectMode) {
  35677. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  35678. }
  35679. if (er) {
  35680. errorOrDestroy(stream, er);
  35681. process.nextTick(cb, er);
  35682. return false;
  35683. }
  35684. return true;
  35685. }
  35686. Writable.prototype.write = function (chunk, encoding, cb) {
  35687. var state = this._writableState;
  35688. var ret = false;
  35689. var isBuf = !state.objectMode && _isUint8Array(chunk);
  35690. if (isBuf && !Buffer.isBuffer(chunk)) {
  35691. chunk = _uint8ArrayToBuffer(chunk);
  35692. }
  35693. if (typeof encoding === 'function') {
  35694. cb = encoding;
  35695. encoding = null;
  35696. }
  35697. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  35698. if (typeof cb !== 'function') cb = nop;
  35699. if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  35700. state.pendingcb++;
  35701. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  35702. }
  35703. return ret;
  35704. };
  35705. Writable.prototype.cork = function () {
  35706. this._writableState.corked++;
  35707. };
  35708. Writable.prototype.uncork = function () {
  35709. var state = this._writableState;
  35710. if (state.corked) {
  35711. state.corked--;
  35712. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  35713. }
  35714. };
  35715. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  35716. // node::ParseEncoding() requires lower case.
  35717. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  35718. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  35719. this._writableState.defaultEncoding = encoding;
  35720. return this;
  35721. };
  35722. Object.defineProperty(Writable.prototype, 'writableBuffer', {
  35723. // making it explicit this property is not enumerable
  35724. // because otherwise some prototype manipulation in
  35725. // userland will fail
  35726. enumerable: false,
  35727. get: function get() {
  35728. return this._writableState && this._writableState.getBuffer();
  35729. }
  35730. });
  35731. function decodeChunk(state, chunk, encoding) {
  35732. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  35733. chunk = Buffer.from(chunk, encoding);
  35734. }
  35735. return chunk;
  35736. }
  35737. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  35738. // making it explicit this property is not enumerable
  35739. // because otherwise some prototype manipulation in
  35740. // userland will fail
  35741. enumerable: false,
  35742. get: function get() {
  35743. return this._writableState.highWaterMark;
  35744. }
  35745. }); // if we're already writing something, then just put this
  35746. // in the queue, and wait our turn. Otherwise, call _write
  35747. // If we return false, then we need a drain event, so set that flag.
  35748. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  35749. if (!isBuf) {
  35750. var newChunk = decodeChunk(state, chunk, encoding);
  35751. if (chunk !== newChunk) {
  35752. isBuf = true;
  35753. encoding = 'buffer';
  35754. chunk = newChunk;
  35755. }
  35756. }
  35757. var len = state.objectMode ? 1 : chunk.length;
  35758. state.length += len;
  35759. var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
  35760. if (!ret) state.needDrain = true;
  35761. if (state.writing || state.corked) {
  35762. var last = state.lastBufferedRequest;
  35763. state.lastBufferedRequest = {
  35764. chunk: chunk,
  35765. encoding: encoding,
  35766. isBuf: isBuf,
  35767. callback: cb,
  35768. next: null
  35769. };
  35770. if (last) {
  35771. last.next = state.lastBufferedRequest;
  35772. } else {
  35773. state.bufferedRequest = state.lastBufferedRequest;
  35774. }
  35775. state.bufferedRequestCount += 1;
  35776. } else {
  35777. doWrite(stream, state, false, len, chunk, encoding, cb);
  35778. }
  35779. return ret;
  35780. }
  35781. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  35782. state.writelen = len;
  35783. state.writecb = cb;
  35784. state.writing = true;
  35785. state.sync = true;
  35786. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  35787. state.sync = false;
  35788. }
  35789. function onwriteError(stream, state, sync, er, cb) {
  35790. --state.pendingcb;
  35791. if (sync) {
  35792. // defer the callback if we are being called synchronously
  35793. // to avoid piling up things on the stack
  35794. process.nextTick(cb, er); // this can emit finish, and it will always happen
  35795. // after error
  35796. process.nextTick(finishMaybe, stream, state);
  35797. stream._writableState.errorEmitted = true;
  35798. errorOrDestroy(stream, er);
  35799. } else {
  35800. // the caller expect this to happen before if
  35801. // it is async
  35802. cb(er);
  35803. stream._writableState.errorEmitted = true;
  35804. errorOrDestroy(stream, er); // this can emit finish, but finish must
  35805. // always follow error
  35806. finishMaybe(stream, state);
  35807. }
  35808. }
  35809. function onwriteStateUpdate(state) {
  35810. state.writing = false;
  35811. state.writecb = null;
  35812. state.length -= state.writelen;
  35813. state.writelen = 0;
  35814. }
  35815. function onwrite(stream, er) {
  35816. var state = stream._writableState;
  35817. var sync = state.sync;
  35818. var cb = state.writecb;
  35819. if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  35820. onwriteStateUpdate(state);
  35821. if (er) onwriteError(stream, state, sync, er, cb);else {
  35822. // Check if we're actually ready to finish, but don't emit yet
  35823. var finished = needFinish(state) || stream.destroyed;
  35824. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  35825. clearBuffer(stream, state);
  35826. }
  35827. if (sync) {
  35828. process.nextTick(afterWrite, stream, state, finished, cb);
  35829. } else {
  35830. afterWrite(stream, state, finished, cb);
  35831. }
  35832. }
  35833. }
  35834. function afterWrite(stream, state, finished, cb) {
  35835. if (!finished) onwriteDrain(stream, state);
  35836. state.pendingcb--;
  35837. cb();
  35838. finishMaybe(stream, state);
  35839. } // Must force callback to be called on nextTick, so that we don't
  35840. // emit 'drain' before the write() consumer gets the 'false' return
  35841. // value, and has a chance to attach a 'drain' listener.
  35842. function onwriteDrain(stream, state) {
  35843. if (state.length === 0 && state.needDrain) {
  35844. state.needDrain = false;
  35845. stream.emit('drain');
  35846. }
  35847. } // if there's something in the buffer waiting, then process it
  35848. function clearBuffer(stream, state) {
  35849. state.bufferProcessing = true;
  35850. var entry = state.bufferedRequest;
  35851. if (stream._writev && entry && entry.next) {
  35852. // Fast case, write everything using _writev()
  35853. var l = state.bufferedRequestCount;
  35854. var buffer = new Array(l);
  35855. var holder = state.corkedRequestsFree;
  35856. holder.entry = entry;
  35857. var count = 0;
  35858. var allBuffers = true;
  35859. while (entry) {
  35860. buffer[count] = entry;
  35861. if (!entry.isBuf) allBuffers = false;
  35862. entry = entry.next;
  35863. count += 1;
  35864. }
  35865. buffer.allBuffers = allBuffers;
  35866. doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
  35867. // as the hot path ends with doWrite
  35868. state.pendingcb++;
  35869. state.lastBufferedRequest = null;
  35870. if (holder.next) {
  35871. state.corkedRequestsFree = holder.next;
  35872. holder.next = null;
  35873. } else {
  35874. state.corkedRequestsFree = new CorkedRequest(state);
  35875. }
  35876. state.bufferedRequestCount = 0;
  35877. } else {
  35878. // Slow case, write chunks one-by-one
  35879. while (entry) {
  35880. var chunk = entry.chunk;
  35881. var encoding = entry.encoding;
  35882. var cb = entry.callback;
  35883. var len = state.objectMode ? 1 : chunk.length;
  35884. doWrite(stream, state, false, len, chunk, encoding, cb);
  35885. entry = entry.next;
  35886. state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
  35887. // it means that we need to wait until it does.
  35888. // also, that means that the chunk and cb are currently
  35889. // being processed, so move the buffer counter past them.
  35890. if (state.writing) {
  35891. break;
  35892. }
  35893. }
  35894. if (entry === null) state.lastBufferedRequest = null;
  35895. }
  35896. state.bufferedRequest = entry;
  35897. state.bufferProcessing = false;
  35898. }
  35899. Writable.prototype._write = function (chunk, encoding, cb) {
  35900. cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
  35901. };
  35902. Writable.prototype._writev = null;
  35903. Writable.prototype.end = function (chunk, encoding, cb) {
  35904. var state = this._writableState;
  35905. if (typeof chunk === 'function') {
  35906. cb = chunk;
  35907. chunk = null;
  35908. encoding = null;
  35909. } else if (typeof encoding === 'function') {
  35910. cb = encoding;
  35911. encoding = null;
  35912. }
  35913. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
  35914. if (state.corked) {
  35915. state.corked = 1;
  35916. this.uncork();
  35917. } // ignore unnecessary end() calls.
  35918. if (!state.ending) endWritable(this, state, cb);
  35919. return this;
  35920. };
  35921. Object.defineProperty(Writable.prototype, 'writableLength', {
  35922. // making it explicit this property is not enumerable
  35923. // because otherwise some prototype manipulation in
  35924. // userland will fail
  35925. enumerable: false,
  35926. get: function get() {
  35927. return this._writableState.length;
  35928. }
  35929. });
  35930. function needFinish(state) {
  35931. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  35932. }
  35933. function callFinal(stream, state) {
  35934. stream._final(function (err) {
  35935. state.pendingcb--;
  35936. if (err) {
  35937. errorOrDestroy(stream, err);
  35938. }
  35939. state.prefinished = true;
  35940. stream.emit('prefinish');
  35941. finishMaybe(stream, state);
  35942. });
  35943. }
  35944. function prefinish(stream, state) {
  35945. if (!state.prefinished && !state.finalCalled) {
  35946. if (typeof stream._final === 'function' && !state.destroyed) {
  35947. state.pendingcb++;
  35948. state.finalCalled = true;
  35949. process.nextTick(callFinal, stream, state);
  35950. } else {
  35951. state.prefinished = true;
  35952. stream.emit('prefinish');
  35953. }
  35954. }
  35955. }
  35956. function finishMaybe(stream, state) {
  35957. var need = needFinish(state);
  35958. if (need) {
  35959. prefinish(stream, state);
  35960. if (state.pendingcb === 0) {
  35961. state.finished = true;
  35962. stream.emit('finish');
  35963. if (state.autoDestroy) {
  35964. // In case of duplex streams we need a way to detect
  35965. // if the readable side is ready for autoDestroy as well
  35966. var rState = stream._readableState;
  35967. if (!rState || rState.autoDestroy && rState.endEmitted) {
  35968. stream.destroy();
  35969. }
  35970. }
  35971. }
  35972. }
  35973. return need;
  35974. }
  35975. function endWritable(stream, state, cb) {
  35976. state.ending = true;
  35977. finishMaybe(stream, state);
  35978. if (cb) {
  35979. if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  35980. }
  35981. state.ended = true;
  35982. stream.writable = false;
  35983. }
  35984. function onCorkedFinish(corkReq, state, err) {
  35985. var entry = corkReq.entry;
  35986. corkReq.entry = null;
  35987. while (entry) {
  35988. var cb = entry.callback;
  35989. state.pendingcb--;
  35990. cb(err);
  35991. entry = entry.next;
  35992. } // reuse the free corkReq.
  35993. state.corkedRequestsFree.next = corkReq;
  35994. }
  35995. Object.defineProperty(Writable.prototype, 'destroyed', {
  35996. // making it explicit this property is not enumerable
  35997. // because otherwise some prototype manipulation in
  35998. // userland will fail
  35999. enumerable: false,
  36000. get: function get() {
  36001. if (this._writableState === undefined) {
  36002. return false;
  36003. }
  36004. return this._writableState.destroyed;
  36005. },
  36006. set: function set(value) {
  36007. // we ignore the value if the stream
  36008. // has not been initialized yet
  36009. if (!this._writableState) {
  36010. return;
  36011. } // backward compatibility, the user is explicitly
  36012. // managing destroyed
  36013. this._writableState.destroyed = value;
  36014. }
  36015. });
  36016. Writable.prototype.destroy = destroyImpl.destroy;
  36017. Writable.prototype._undestroy = destroyImpl.undestroy;
  36018. Writable.prototype._destroy = function (err, cb) {
  36019. cb(err);
  36020. };
  36021. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  36022. },{"../errors":172,"./_stream_duplex":173,"./internal/streams/destroy":180,"./internal/streams/state":184,"./internal/streams/stream":185,"_process":525,"buffer":193,"inherits":320,"util-deprecate":655}],178:[function(require,module,exports){
  36023. (function (process){(function (){
  36024. 'use strict';
  36025. var _Object$setPrototypeO;
  36026. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  36027. var finished = require('./end-of-stream');
  36028. var kLastResolve = Symbol('lastResolve');
  36029. var kLastReject = Symbol('lastReject');
  36030. var kError = Symbol('error');
  36031. var kEnded = Symbol('ended');
  36032. var kLastPromise = Symbol('lastPromise');
  36033. var kHandlePromise = Symbol('handlePromise');
  36034. var kStream = Symbol('stream');
  36035. function createIterResult(value, done) {
  36036. return {
  36037. value: value,
  36038. done: done
  36039. };
  36040. }
  36041. function readAndResolve(iter) {
  36042. var resolve = iter[kLastResolve];
  36043. if (resolve !== null) {
  36044. var data = iter[kStream].read(); // we defer if data is null
  36045. // we can be expecting either 'end' or
  36046. // 'error'
  36047. if (data !== null) {
  36048. iter[kLastPromise] = null;
  36049. iter[kLastResolve] = null;
  36050. iter[kLastReject] = null;
  36051. resolve(createIterResult(data, false));
  36052. }
  36053. }
  36054. }
  36055. function onReadable(iter) {
  36056. // we wait for the next tick, because it might
  36057. // emit an error with process.nextTick
  36058. process.nextTick(readAndResolve, iter);
  36059. }
  36060. function wrapForNext(lastPromise, iter) {
  36061. return function (resolve, reject) {
  36062. lastPromise.then(function () {
  36063. if (iter[kEnded]) {
  36064. resolve(createIterResult(undefined, true));
  36065. return;
  36066. }
  36067. iter[kHandlePromise](resolve, reject);
  36068. }, reject);
  36069. };
  36070. }
  36071. var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
  36072. var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  36073. get stream() {
  36074. return this[kStream];
  36075. },
  36076. next: function next() {
  36077. var _this = this;
  36078. // if we have detected an error in the meanwhile
  36079. // reject straight away
  36080. var error = this[kError];
  36081. if (error !== null) {
  36082. return Promise.reject(error);
  36083. }
  36084. if (this[kEnded]) {
  36085. return Promise.resolve(createIterResult(undefined, true));
  36086. }
  36087. if (this[kStream].destroyed) {
  36088. // We need to defer via nextTick because if .destroy(err) is
  36089. // called, the error will be emitted via nextTick, and
  36090. // we cannot guarantee that there is no error lingering around
  36091. // waiting to be emitted.
  36092. return new Promise(function (resolve, reject) {
  36093. process.nextTick(function () {
  36094. if (_this[kError]) {
  36095. reject(_this[kError]);
  36096. } else {
  36097. resolve(createIterResult(undefined, true));
  36098. }
  36099. });
  36100. });
  36101. } // if we have multiple next() calls
  36102. // we will wait for the previous Promise to finish
  36103. // this logic is optimized to support for await loops,
  36104. // where next() is only called once at a time
  36105. var lastPromise = this[kLastPromise];
  36106. var promise;
  36107. if (lastPromise) {
  36108. promise = new Promise(wrapForNext(lastPromise, this));
  36109. } else {
  36110. // fast path needed to support multiple this.push()
  36111. // without triggering the next() queue
  36112. var data = this[kStream].read();
  36113. if (data !== null) {
  36114. return Promise.resolve(createIterResult(data, false));
  36115. }
  36116. promise = new Promise(this[kHandlePromise]);
  36117. }
  36118. this[kLastPromise] = promise;
  36119. return promise;
  36120. }
  36121. }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  36122. return this;
  36123. }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  36124. var _this2 = this;
  36125. // destroy(err, cb) is a private API
  36126. // we can guarantee we have that here, because we control the
  36127. // Readable class this is attached to
  36128. return new Promise(function (resolve, reject) {
  36129. _this2[kStream].destroy(null, function (err) {
  36130. if (err) {
  36131. reject(err);
  36132. return;
  36133. }
  36134. resolve(createIterResult(undefined, true));
  36135. });
  36136. });
  36137. }), _Object$setPrototypeO), AsyncIteratorPrototype);
  36138. var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  36139. var _Object$create;
  36140. var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
  36141. value: stream,
  36142. writable: true
  36143. }), _defineProperty(_Object$create, kLastResolve, {
  36144. value: null,
  36145. writable: true
  36146. }), _defineProperty(_Object$create, kLastReject, {
  36147. value: null,
  36148. writable: true
  36149. }), _defineProperty(_Object$create, kError, {
  36150. value: null,
  36151. writable: true
  36152. }), _defineProperty(_Object$create, kEnded, {
  36153. value: stream._readableState.endEmitted,
  36154. writable: true
  36155. }), _defineProperty(_Object$create, kHandlePromise, {
  36156. value: function value(resolve, reject) {
  36157. var data = iterator[kStream].read();
  36158. if (data) {
  36159. iterator[kLastPromise] = null;
  36160. iterator[kLastResolve] = null;
  36161. iterator[kLastReject] = null;
  36162. resolve(createIterResult(data, false));
  36163. } else {
  36164. iterator[kLastResolve] = resolve;
  36165. iterator[kLastReject] = reject;
  36166. }
  36167. },
  36168. writable: true
  36169. }), _Object$create));
  36170. iterator[kLastPromise] = null;
  36171. finished(stream, function (err) {
  36172. if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  36173. var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
  36174. // returned by next() and store the error
  36175. if (reject !== null) {
  36176. iterator[kLastPromise] = null;
  36177. iterator[kLastResolve] = null;
  36178. iterator[kLastReject] = null;
  36179. reject(err);
  36180. }
  36181. iterator[kError] = err;
  36182. return;
  36183. }
  36184. var resolve = iterator[kLastResolve];
  36185. if (resolve !== null) {
  36186. iterator[kLastPromise] = null;
  36187. iterator[kLastResolve] = null;
  36188. iterator[kLastReject] = null;
  36189. resolve(createIterResult(undefined, true));
  36190. }
  36191. iterator[kEnded] = true;
  36192. });
  36193. stream.on('readable', onReadable.bind(null, iterator));
  36194. return iterator;
  36195. };
  36196. module.exports = createReadableStreamAsyncIterator;
  36197. }).call(this)}).call(this,require('_process'))
  36198. },{"./end-of-stream":181,"_process":525}],179:[function(require,module,exports){
  36199. 'use strict';
  36200. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  36201. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  36202. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  36203. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  36204. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  36205. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  36206. var _require = require('buffer'),
  36207. Buffer = _require.Buffer;
  36208. var _require2 = require('util'),
  36209. inspect = _require2.inspect;
  36210. var custom = inspect && inspect.custom || 'inspect';
  36211. function copyBuffer(src, target, offset) {
  36212. Buffer.prototype.copy.call(src, target, offset);
  36213. }
  36214. module.exports =
  36215. /*#__PURE__*/
  36216. function () {
  36217. function BufferList() {
  36218. _classCallCheck(this, BufferList);
  36219. this.head = null;
  36220. this.tail = null;
  36221. this.length = 0;
  36222. }
  36223. _createClass(BufferList, [{
  36224. key: "push",
  36225. value: function push(v) {
  36226. var entry = {
  36227. data: v,
  36228. next: null
  36229. };
  36230. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  36231. this.tail = entry;
  36232. ++this.length;
  36233. }
  36234. }, {
  36235. key: "unshift",
  36236. value: function unshift(v) {
  36237. var entry = {
  36238. data: v,
  36239. next: this.head
  36240. };
  36241. if (this.length === 0) this.tail = entry;
  36242. this.head = entry;
  36243. ++this.length;
  36244. }
  36245. }, {
  36246. key: "shift",
  36247. value: function shift() {
  36248. if (this.length === 0) return;
  36249. var ret = this.head.data;
  36250. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  36251. --this.length;
  36252. return ret;
  36253. }
  36254. }, {
  36255. key: "clear",
  36256. value: function clear() {
  36257. this.head = this.tail = null;
  36258. this.length = 0;
  36259. }
  36260. }, {
  36261. key: "join",
  36262. value: function join(s) {
  36263. if (this.length === 0) return '';
  36264. var p = this.head;
  36265. var ret = '' + p.data;
  36266. while (p = p.next) {
  36267. ret += s + p.data;
  36268. }
  36269. return ret;
  36270. }
  36271. }, {
  36272. key: "concat",
  36273. value: function concat(n) {
  36274. if (this.length === 0) return Buffer.alloc(0);
  36275. var ret = Buffer.allocUnsafe(n >>> 0);
  36276. var p = this.head;
  36277. var i = 0;
  36278. while (p) {
  36279. copyBuffer(p.data, ret, i);
  36280. i += p.data.length;
  36281. p = p.next;
  36282. }
  36283. return ret;
  36284. } // Consumes a specified amount of bytes or characters from the buffered data.
  36285. }, {
  36286. key: "consume",
  36287. value: function consume(n, hasStrings) {
  36288. var ret;
  36289. if (n < this.head.data.length) {
  36290. // `slice` is the same for buffers and strings.
  36291. ret = this.head.data.slice(0, n);
  36292. this.head.data = this.head.data.slice(n);
  36293. } else if (n === this.head.data.length) {
  36294. // First chunk is a perfect match.
  36295. ret = this.shift();
  36296. } else {
  36297. // Result spans more than one buffer.
  36298. ret = hasStrings ? this._getString(n) : this._getBuffer(n);
  36299. }
  36300. return ret;
  36301. }
  36302. }, {
  36303. key: "first",
  36304. value: function first() {
  36305. return this.head.data;
  36306. } // Consumes a specified amount of characters from the buffered data.
  36307. }, {
  36308. key: "_getString",
  36309. value: function _getString(n) {
  36310. var p = this.head;
  36311. var c = 1;
  36312. var ret = p.data;
  36313. n -= ret.length;
  36314. while (p = p.next) {
  36315. var str = p.data;
  36316. var nb = n > str.length ? str.length : n;
  36317. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  36318. n -= nb;
  36319. if (n === 0) {
  36320. if (nb === str.length) {
  36321. ++c;
  36322. if (p.next) this.head = p.next;else this.head = this.tail = null;
  36323. } else {
  36324. this.head = p;
  36325. p.data = str.slice(nb);
  36326. }
  36327. break;
  36328. }
  36329. ++c;
  36330. }
  36331. this.length -= c;
  36332. return ret;
  36333. } // Consumes a specified amount of bytes from the buffered data.
  36334. }, {
  36335. key: "_getBuffer",
  36336. value: function _getBuffer(n) {
  36337. var ret = Buffer.allocUnsafe(n);
  36338. var p = this.head;
  36339. var c = 1;
  36340. p.data.copy(ret);
  36341. n -= p.data.length;
  36342. while (p = p.next) {
  36343. var buf = p.data;
  36344. var nb = n > buf.length ? buf.length : n;
  36345. buf.copy(ret, ret.length - n, 0, nb);
  36346. n -= nb;
  36347. if (n === 0) {
  36348. if (nb === buf.length) {
  36349. ++c;
  36350. if (p.next) this.head = p.next;else this.head = this.tail = null;
  36351. } else {
  36352. this.head = p;
  36353. p.data = buf.slice(nb);
  36354. }
  36355. break;
  36356. }
  36357. ++c;
  36358. }
  36359. this.length -= c;
  36360. return ret;
  36361. } // Make sure the linked list only shows the minimal necessary information.
  36362. }, {
  36363. key: custom,
  36364. value: function value(_, options) {
  36365. return inspect(this, _objectSpread({}, options, {
  36366. // Only inspect one level.
  36367. depth: 0,
  36368. // It should not recurse.
  36369. customInspect: false
  36370. }));
  36371. }
  36372. }]);
  36373. return BufferList;
  36374. }();
  36375. },{"buffer":193,"util":144}],180:[function(require,module,exports){
  36376. (function (process){(function (){
  36377. 'use strict'; // undocumented cb() API, needed for core, not for public API
  36378. function destroy(err, cb) {
  36379. var _this = this;
  36380. var readableDestroyed = this._readableState && this._readableState.destroyed;
  36381. var writableDestroyed = this._writableState && this._writableState.destroyed;
  36382. if (readableDestroyed || writableDestroyed) {
  36383. if (cb) {
  36384. cb(err);
  36385. } else if (err) {
  36386. if (!this._writableState) {
  36387. process.nextTick(emitErrorNT, this, err);
  36388. } else if (!this._writableState.errorEmitted) {
  36389. this._writableState.errorEmitted = true;
  36390. process.nextTick(emitErrorNT, this, err);
  36391. }
  36392. }
  36393. return this;
  36394. } // we set destroyed to true before firing error callbacks in order
  36395. // to make it re-entrance safe in case destroy() is called within callbacks
  36396. if (this._readableState) {
  36397. this._readableState.destroyed = true;
  36398. } // if this is a duplex stream mark the writable part as destroyed as well
  36399. if (this._writableState) {
  36400. this._writableState.destroyed = true;
  36401. }
  36402. this._destroy(err || null, function (err) {
  36403. if (!cb && err) {
  36404. if (!_this._writableState) {
  36405. process.nextTick(emitErrorAndCloseNT, _this, err);
  36406. } else if (!_this._writableState.errorEmitted) {
  36407. _this._writableState.errorEmitted = true;
  36408. process.nextTick(emitErrorAndCloseNT, _this, err);
  36409. } else {
  36410. process.nextTick(emitCloseNT, _this);
  36411. }
  36412. } else if (cb) {
  36413. process.nextTick(emitCloseNT, _this);
  36414. cb(err);
  36415. } else {
  36416. process.nextTick(emitCloseNT, _this);
  36417. }
  36418. });
  36419. return this;
  36420. }
  36421. function emitErrorAndCloseNT(self, err) {
  36422. emitErrorNT(self, err);
  36423. emitCloseNT(self);
  36424. }
  36425. function emitCloseNT(self) {
  36426. if (self._writableState && !self._writableState.emitClose) return;
  36427. if (self._readableState && !self._readableState.emitClose) return;
  36428. self.emit('close');
  36429. }
  36430. function undestroy() {
  36431. if (this._readableState) {
  36432. this._readableState.destroyed = false;
  36433. this._readableState.reading = false;
  36434. this._readableState.ended = false;
  36435. this._readableState.endEmitted = false;
  36436. }
  36437. if (this._writableState) {
  36438. this._writableState.destroyed = false;
  36439. this._writableState.ended = false;
  36440. this._writableState.ending = false;
  36441. this._writableState.finalCalled = false;
  36442. this._writableState.prefinished = false;
  36443. this._writableState.finished = false;
  36444. this._writableState.errorEmitted = false;
  36445. }
  36446. }
  36447. function emitErrorNT(self, err) {
  36448. self.emit('error', err);
  36449. }
  36450. function errorOrDestroy(stream, err) {
  36451. // We have tests that rely on errors being emitted
  36452. // in the same tick, so changing this is semver major.
  36453. // For now when you opt-in to autoDestroy we allow
  36454. // the error to be emitted nextTick. In a future
  36455. // semver major update we should change the default to this.
  36456. var rState = stream._readableState;
  36457. var wState = stream._writableState;
  36458. if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
  36459. }
  36460. module.exports = {
  36461. destroy: destroy,
  36462. undestroy: undestroy,
  36463. errorOrDestroy: errorOrDestroy
  36464. };
  36465. }).call(this)}).call(this,require('_process'))
  36466. },{"_process":525}],181:[function(require,module,exports){
  36467. // Ported from https://github.com/mafintosh/end-of-stream with
  36468. // permission from the author, Mathias Buus (@mafintosh).
  36469. 'use strict';
  36470. var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
  36471. function once(callback) {
  36472. var called = false;
  36473. return function () {
  36474. if (called) return;
  36475. called = true;
  36476. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36477. args[_key] = arguments[_key];
  36478. }
  36479. callback.apply(this, args);
  36480. };
  36481. }
  36482. function noop() {}
  36483. function isRequest(stream) {
  36484. return stream.setHeader && typeof stream.abort === 'function';
  36485. }
  36486. function eos(stream, opts, callback) {
  36487. if (typeof opts === 'function') return eos(stream, null, opts);
  36488. if (!opts) opts = {};
  36489. callback = once(callback || noop);
  36490. var readable = opts.readable || opts.readable !== false && stream.readable;
  36491. var writable = opts.writable || opts.writable !== false && stream.writable;
  36492. var onlegacyfinish = function onlegacyfinish() {
  36493. if (!stream.writable) onfinish();
  36494. };
  36495. var writableEnded = stream._writableState && stream._writableState.finished;
  36496. var onfinish = function onfinish() {
  36497. writable = false;
  36498. writableEnded = true;
  36499. if (!readable) callback.call(stream);
  36500. };
  36501. var readableEnded = stream._readableState && stream._readableState.endEmitted;
  36502. var onend = function onend() {
  36503. readable = false;
  36504. readableEnded = true;
  36505. if (!writable) callback.call(stream);
  36506. };
  36507. var onerror = function onerror(err) {
  36508. callback.call(stream, err);
  36509. };
  36510. var onclose = function onclose() {
  36511. var err;
  36512. if (readable && !readableEnded) {
  36513. if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  36514. return callback.call(stream, err);
  36515. }
  36516. if (writable && !writableEnded) {
  36517. if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  36518. return callback.call(stream, err);
  36519. }
  36520. };
  36521. var onrequest = function onrequest() {
  36522. stream.req.on('finish', onfinish);
  36523. };
  36524. if (isRequest(stream)) {
  36525. stream.on('complete', onfinish);
  36526. stream.on('abort', onclose);
  36527. if (stream.req) onrequest();else stream.on('request', onrequest);
  36528. } else if (writable && !stream._writableState) {
  36529. // legacy streams
  36530. stream.on('end', onlegacyfinish);
  36531. stream.on('close', onlegacyfinish);
  36532. }
  36533. stream.on('end', onend);
  36534. stream.on('finish', onfinish);
  36535. if (opts.error !== false) stream.on('error', onerror);
  36536. stream.on('close', onclose);
  36537. return function () {
  36538. stream.removeListener('complete', onfinish);
  36539. stream.removeListener('abort', onclose);
  36540. stream.removeListener('request', onrequest);
  36541. if (stream.req) stream.req.removeListener('finish', onfinish);
  36542. stream.removeListener('end', onlegacyfinish);
  36543. stream.removeListener('close', onlegacyfinish);
  36544. stream.removeListener('finish', onfinish);
  36545. stream.removeListener('end', onend);
  36546. stream.removeListener('error', onerror);
  36547. stream.removeListener('close', onclose);
  36548. };
  36549. }
  36550. module.exports = eos;
  36551. },{"../../../errors":172}],182:[function(require,module,exports){
  36552. module.exports = function () {
  36553. throw new Error('Readable.from is not available in the browser')
  36554. };
  36555. },{}],183:[function(require,module,exports){
  36556. // Ported from https://github.com/mafintosh/pump with
  36557. // permission from the author, Mathias Buus (@mafintosh).
  36558. 'use strict';
  36559. var eos;
  36560. function once(callback) {
  36561. var called = false;
  36562. return function () {
  36563. if (called) return;
  36564. called = true;
  36565. callback.apply(void 0, arguments);
  36566. };
  36567. }
  36568. var _require$codes = require('../../../errors').codes,
  36569. ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  36570. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  36571. function noop(err) {
  36572. // Rethrow the error if it exists to avoid swallowing it
  36573. if (err) throw err;
  36574. }
  36575. function isRequest(stream) {
  36576. return stream.setHeader && typeof stream.abort === 'function';
  36577. }
  36578. function destroyer(stream, reading, writing, callback) {
  36579. callback = once(callback);
  36580. var closed = false;
  36581. stream.on('close', function () {
  36582. closed = true;
  36583. });
  36584. if (eos === undefined) eos = require('./end-of-stream');
  36585. eos(stream, {
  36586. readable: reading,
  36587. writable: writing
  36588. }, function (err) {
  36589. if (err) return callback(err);
  36590. closed = true;
  36591. callback();
  36592. });
  36593. var destroyed = false;
  36594. return function (err) {
  36595. if (closed) return;
  36596. if (destroyed) return;
  36597. destroyed = true; // request.destroy just do .end - .abort is what we want
  36598. if (isRequest(stream)) return stream.abort();
  36599. if (typeof stream.destroy === 'function') return stream.destroy();
  36600. callback(err || new ERR_STREAM_DESTROYED('pipe'));
  36601. };
  36602. }
  36603. function call(fn) {
  36604. fn();
  36605. }
  36606. function pipe(from, to) {
  36607. return from.pipe(to);
  36608. }
  36609. function popCallback(streams) {
  36610. if (!streams.length) return noop;
  36611. if (typeof streams[streams.length - 1] !== 'function') return noop;
  36612. return streams.pop();
  36613. }
  36614. function pipeline() {
  36615. for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
  36616. streams[_key] = arguments[_key];
  36617. }
  36618. var callback = popCallback(streams);
  36619. if (Array.isArray(streams[0])) streams = streams[0];
  36620. if (streams.length < 2) {
  36621. throw new ERR_MISSING_ARGS('streams');
  36622. }
  36623. var error;
  36624. var destroys = streams.map(function (stream, i) {
  36625. var reading = i < streams.length - 1;
  36626. var writing = i > 0;
  36627. return destroyer(stream, reading, writing, function (err) {
  36628. if (!error) error = err;
  36629. if (err) destroys.forEach(call);
  36630. if (reading) return;
  36631. destroys.forEach(call);
  36632. callback(error);
  36633. });
  36634. });
  36635. return streams.reduce(pipe);
  36636. }
  36637. module.exports = pipeline;
  36638. },{"../../../errors":172,"./end-of-stream":181}],184:[function(require,module,exports){
  36639. 'use strict';
  36640. var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
  36641. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  36642. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  36643. }
  36644. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  36645. var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  36646. if (hwm != null) {
  36647. if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
  36648. var name = isDuplex ? duplexKey : 'highWaterMark';
  36649. throw new ERR_INVALID_OPT_VALUE(name, hwm);
  36650. }
  36651. return Math.floor(hwm);
  36652. } // Default value
  36653. return state.objectMode ? 16 : 16 * 1024;
  36654. }
  36655. module.exports = {
  36656. getHighWaterMark: getHighWaterMark
  36657. };
  36658. },{"../../../errors":172}],185:[function(require,module,exports){
  36659. module.exports = require('events').EventEmitter;
  36660. },{"events":247}],186:[function(require,module,exports){
  36661. exports = module.exports = require('./lib/_stream_readable.js');
  36662. exports.Stream = exports;
  36663. exports.Readable = exports;
  36664. exports.Writable = require('./lib/_stream_writable.js');
  36665. exports.Duplex = require('./lib/_stream_duplex.js');
  36666. exports.Transform = require('./lib/_stream_transform.js');
  36667. exports.PassThrough = require('./lib/_stream_passthrough.js');
  36668. exports.finished = require('./lib/internal/streams/end-of-stream.js');
  36669. exports.pipeline = require('./lib/internal/streams/pipeline.js');
  36670. },{"./lib/_stream_duplex.js":173,"./lib/_stream_passthrough.js":174,"./lib/_stream_readable.js":175,"./lib/_stream_transform.js":176,"./lib/_stream_writable.js":177,"./lib/internal/streams/end-of-stream.js":181,"./lib/internal/streams/pipeline.js":183}],187:[function(require,module,exports){
  36671. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  36672. /* eslint-disable node/no-deprecated-api */
  36673. var buffer = require('buffer')
  36674. var Buffer = buffer.Buffer
  36675. // alternative to using Object.keys for old browsers
  36676. function copyProps (src, dst) {
  36677. for (var key in src) {
  36678. dst[key] = src[key]
  36679. }
  36680. }
  36681. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  36682. module.exports = buffer
  36683. } else {
  36684. // Copy properties from require('buffer')
  36685. copyProps(buffer, exports)
  36686. exports.Buffer = SafeBuffer
  36687. }
  36688. function SafeBuffer (arg, encodingOrOffset, length) {
  36689. return Buffer(arg, encodingOrOffset, length)
  36690. }
  36691. SafeBuffer.prototype = Object.create(Buffer.prototype)
  36692. // Copy static methods from Buffer
  36693. copyProps(Buffer, SafeBuffer)
  36694. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  36695. if (typeof arg === 'number') {
  36696. throw new TypeError('Argument must not be a number')
  36697. }
  36698. return Buffer(arg, encodingOrOffset, length)
  36699. }
  36700. SafeBuffer.alloc = function (size, fill, encoding) {
  36701. if (typeof size !== 'number') {
  36702. throw new TypeError('Argument must be a number')
  36703. }
  36704. var buf = Buffer(size)
  36705. if (fill !== undefined) {
  36706. if (typeof encoding === 'string') {
  36707. buf.fill(fill, encoding)
  36708. } else {
  36709. buf.fill(fill)
  36710. }
  36711. } else {
  36712. buf.fill(0)
  36713. }
  36714. return buf
  36715. }
  36716. SafeBuffer.allocUnsafe = function (size) {
  36717. if (typeof size !== 'number') {
  36718. throw new TypeError('Argument must be a number')
  36719. }
  36720. return Buffer(size)
  36721. }
  36722. SafeBuffer.allocUnsafeSlow = function (size) {
  36723. if (typeof size !== 'number') {
  36724. throw new TypeError('Argument must be a number')
  36725. }
  36726. return buffer.SlowBuffer(size)
  36727. }
  36728. },{"buffer":193}],188:[function(require,module,exports){
  36729. (function (process,Buffer){(function (){
  36730. 'use strict';
  36731. /* eslint camelcase: "off" */
  36732. var assert = require('assert');
  36733. var Zstream = require('pako/lib/zlib/zstream');
  36734. var zlib_deflate = require('pako/lib/zlib/deflate.js');
  36735. var zlib_inflate = require('pako/lib/zlib/inflate.js');
  36736. var constants = require('pako/lib/zlib/constants');
  36737. for (var key in constants) {
  36738. exports[key] = constants[key];
  36739. }
  36740. // zlib modes
  36741. exports.NONE = 0;
  36742. exports.DEFLATE = 1;
  36743. exports.INFLATE = 2;
  36744. exports.GZIP = 3;
  36745. exports.GUNZIP = 4;
  36746. exports.DEFLATERAW = 5;
  36747. exports.INFLATERAW = 6;
  36748. exports.UNZIP = 7;
  36749. var GZIP_HEADER_ID1 = 0x1f;
  36750. var GZIP_HEADER_ID2 = 0x8b;
  36751. /**
  36752. * Emulate Node's zlib C++ layer for use by the JS layer in index.js
  36753. */
  36754. function Zlib(mode) {
  36755. if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
  36756. throw new TypeError('Bad argument');
  36757. }
  36758. this.dictionary = null;
  36759. this.err = 0;
  36760. this.flush = 0;
  36761. this.init_done = false;
  36762. this.level = 0;
  36763. this.memLevel = 0;
  36764. this.mode = mode;
  36765. this.strategy = 0;
  36766. this.windowBits = 0;
  36767. this.write_in_progress = false;
  36768. this.pending_close = false;
  36769. this.gzip_id_bytes_read = 0;
  36770. }
  36771. Zlib.prototype.close = function () {
  36772. if (this.write_in_progress) {
  36773. this.pending_close = true;
  36774. return;
  36775. }
  36776. this.pending_close = false;
  36777. assert(this.init_done, 'close before init');
  36778. assert(this.mode <= exports.UNZIP);
  36779. if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
  36780. zlib_deflate.deflateEnd(this.strm);
  36781. } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
  36782. zlib_inflate.inflateEnd(this.strm);
  36783. }
  36784. this.mode = exports.NONE;
  36785. this.dictionary = null;
  36786. };
  36787. Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
  36788. return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
  36789. };
  36790. Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
  36791. return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
  36792. };
  36793. Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
  36794. assert.equal(arguments.length, 8);
  36795. assert(this.init_done, 'write before init');
  36796. assert(this.mode !== exports.NONE, 'already finalized');
  36797. assert.equal(false, this.write_in_progress, 'write already in progress');
  36798. assert.equal(false, this.pending_close, 'close is pending');
  36799. this.write_in_progress = true;
  36800. assert.equal(false, flush === undefined, 'must provide flush value');
  36801. this.write_in_progress = true;
  36802. if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
  36803. throw new Error('Invalid flush value');
  36804. }
  36805. if (input == null) {
  36806. input = Buffer.alloc(0);
  36807. in_len = 0;
  36808. in_off = 0;
  36809. }
  36810. this.strm.avail_in = in_len;
  36811. this.strm.input = input;
  36812. this.strm.next_in = in_off;
  36813. this.strm.avail_out = out_len;
  36814. this.strm.output = out;
  36815. this.strm.next_out = out_off;
  36816. this.flush = flush;
  36817. if (!async) {
  36818. // sync version
  36819. this._process();
  36820. if (this._checkError()) {
  36821. return this._afterSync();
  36822. }
  36823. return;
  36824. }
  36825. // async version
  36826. var self = this;
  36827. process.nextTick(function () {
  36828. self._process();
  36829. self._after();
  36830. });
  36831. return this;
  36832. };
  36833. Zlib.prototype._afterSync = function () {
  36834. var avail_out = this.strm.avail_out;
  36835. var avail_in = this.strm.avail_in;
  36836. this.write_in_progress = false;
  36837. return [avail_in, avail_out];
  36838. };
  36839. Zlib.prototype._process = function () {
  36840. var next_expected_header_byte = null;
  36841. // If the avail_out is left at 0, then it means that it ran out
  36842. // of room. If there was avail_out left over, then it means
  36843. // that all of the input was consumed.
  36844. switch (this.mode) {
  36845. case exports.DEFLATE:
  36846. case exports.GZIP:
  36847. case exports.DEFLATERAW:
  36848. this.err = zlib_deflate.deflate(this.strm, this.flush);
  36849. break;
  36850. case exports.UNZIP:
  36851. if (this.strm.avail_in > 0) {
  36852. next_expected_header_byte = this.strm.next_in;
  36853. }
  36854. switch (this.gzip_id_bytes_read) {
  36855. case 0:
  36856. if (next_expected_header_byte === null) {
  36857. break;
  36858. }
  36859. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
  36860. this.gzip_id_bytes_read = 1;
  36861. next_expected_header_byte++;
  36862. if (this.strm.avail_in === 1) {
  36863. // The only available byte was already read.
  36864. break;
  36865. }
  36866. } else {
  36867. this.mode = exports.INFLATE;
  36868. break;
  36869. }
  36870. // fallthrough
  36871. case 1:
  36872. if (next_expected_header_byte === null) {
  36873. break;
  36874. }
  36875. if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
  36876. this.gzip_id_bytes_read = 2;
  36877. this.mode = exports.GUNZIP;
  36878. } else {
  36879. // There is no actual difference between INFLATE and INFLATERAW
  36880. // (after initialization).
  36881. this.mode = exports.INFLATE;
  36882. }
  36883. break;
  36884. default:
  36885. throw new Error('invalid number of gzip magic number bytes read');
  36886. }
  36887. // fallthrough
  36888. case exports.INFLATE:
  36889. case exports.GUNZIP:
  36890. case exports.INFLATERAW:
  36891. this.err = zlib_inflate.inflate(this.strm, this.flush
  36892. // If data was encoded with dictionary
  36893. );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
  36894. // Load it
  36895. this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
  36896. if (this.err === exports.Z_OK) {
  36897. // And try to decode again
  36898. this.err = zlib_inflate.inflate(this.strm, this.flush);
  36899. } else if (this.err === exports.Z_DATA_ERROR) {
  36900. // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
  36901. // Make it possible for After() to tell a bad dictionary from bad
  36902. // input.
  36903. this.err = exports.Z_NEED_DICT;
  36904. }
  36905. }
  36906. while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
  36907. // Bytes remain in input buffer. Perhaps this is another compressed
  36908. // member in the same archive, or just trailing garbage.
  36909. // Trailing zero bytes are okay, though, since they are frequently
  36910. // used for padding.
  36911. this.reset();
  36912. this.err = zlib_inflate.inflate(this.strm, this.flush);
  36913. }
  36914. break;
  36915. default:
  36916. throw new Error('Unknown mode ' + this.mode);
  36917. }
  36918. };
  36919. Zlib.prototype._checkError = function () {
  36920. // Acceptable error states depend on the type of zlib stream.
  36921. switch (this.err) {
  36922. case exports.Z_OK:
  36923. case exports.Z_BUF_ERROR:
  36924. if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
  36925. this._error('unexpected end of file');
  36926. return false;
  36927. }
  36928. break;
  36929. case exports.Z_STREAM_END:
  36930. // normal statuses, not fatal
  36931. break;
  36932. case exports.Z_NEED_DICT:
  36933. if (this.dictionary == null) {
  36934. this._error('Missing dictionary');
  36935. } else {
  36936. this._error('Bad dictionary');
  36937. }
  36938. return false;
  36939. default:
  36940. // something else.
  36941. this._error('Zlib error');
  36942. return false;
  36943. }
  36944. return true;
  36945. };
  36946. Zlib.prototype._after = function () {
  36947. if (!this._checkError()) {
  36948. return;
  36949. }
  36950. var avail_out = this.strm.avail_out;
  36951. var avail_in = this.strm.avail_in;
  36952. this.write_in_progress = false;
  36953. // call the write() cb
  36954. this.callback(avail_in, avail_out);
  36955. if (this.pending_close) {
  36956. this.close();
  36957. }
  36958. };
  36959. Zlib.prototype._error = function (message) {
  36960. if (this.strm.msg) {
  36961. message = this.strm.msg;
  36962. }
  36963. this.onerror(message, this.err
  36964. // no hope of rescue.
  36965. );this.write_in_progress = false;
  36966. if (this.pending_close) {
  36967. this.close();
  36968. }
  36969. };
  36970. Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
  36971. assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
  36972. assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
  36973. assert(level >= -1 && level <= 9, 'invalid compression level');
  36974. assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
  36975. assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
  36976. this._init(level, windowBits, memLevel, strategy, dictionary);
  36977. this._setDictionary();
  36978. };
  36979. Zlib.prototype.params = function () {
  36980. throw new Error('deflateParams Not supported');
  36981. };
  36982. Zlib.prototype.reset = function () {
  36983. this._reset();
  36984. this._setDictionary();
  36985. };
  36986. Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
  36987. this.level = level;
  36988. this.windowBits = windowBits;
  36989. this.memLevel = memLevel;
  36990. this.strategy = strategy;
  36991. this.flush = exports.Z_NO_FLUSH;
  36992. this.err = exports.Z_OK;
  36993. if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
  36994. this.windowBits += 16;
  36995. }
  36996. if (this.mode === exports.UNZIP) {
  36997. this.windowBits += 32;
  36998. }
  36999. if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
  37000. this.windowBits = -1 * this.windowBits;
  37001. }
  37002. this.strm = new Zstream();
  37003. switch (this.mode) {
  37004. case exports.DEFLATE:
  37005. case exports.GZIP:
  37006. case exports.DEFLATERAW:
  37007. this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
  37008. break;
  37009. case exports.INFLATE:
  37010. case exports.GUNZIP:
  37011. case exports.INFLATERAW:
  37012. case exports.UNZIP:
  37013. this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
  37014. break;
  37015. default:
  37016. throw new Error('Unknown mode ' + this.mode);
  37017. }
  37018. if (this.err !== exports.Z_OK) {
  37019. this._error('Init error');
  37020. }
  37021. this.dictionary = dictionary;
  37022. this.write_in_progress = false;
  37023. this.init_done = true;
  37024. };
  37025. Zlib.prototype._setDictionary = function () {
  37026. if (this.dictionary == null) {
  37027. return;
  37028. }
  37029. this.err = exports.Z_OK;
  37030. switch (this.mode) {
  37031. case exports.DEFLATE:
  37032. case exports.DEFLATERAW:
  37033. this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
  37034. break;
  37035. default:
  37036. break;
  37037. }
  37038. if (this.err !== exports.Z_OK) {
  37039. this._error('Failed to set dictionary');
  37040. }
  37041. };
  37042. Zlib.prototype._reset = function () {
  37043. this.err = exports.Z_OK;
  37044. switch (this.mode) {
  37045. case exports.DEFLATE:
  37046. case exports.DEFLATERAW:
  37047. case exports.GZIP:
  37048. this.err = zlib_deflate.deflateReset(this.strm);
  37049. break;
  37050. case exports.INFLATE:
  37051. case exports.INFLATERAW:
  37052. case exports.GUNZIP:
  37053. this.err = zlib_inflate.inflateReset(this.strm);
  37054. break;
  37055. default:
  37056. break;
  37057. }
  37058. if (this.err !== exports.Z_OK) {
  37059. this._error('Failed to reset stream');
  37060. }
  37061. };
  37062. exports.Zlib = Zlib;
  37063. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  37064. },{"_process":525,"assert":105,"buffer":193,"pako/lib/zlib/constants":503,"pako/lib/zlib/deflate.js":505,"pako/lib/zlib/inflate.js":507,"pako/lib/zlib/zstream":511}],189:[function(require,module,exports){
  37065. (function (process){(function (){
  37066. 'use strict';
  37067. var Buffer = require('buffer').Buffer;
  37068. var Transform = require('stream').Transform;
  37069. var binding = require('./binding');
  37070. var util = require('util');
  37071. var assert = require('assert').ok;
  37072. var kMaxLength = require('buffer').kMaxLength;
  37073. var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
  37074. // zlib doesn't provide these, so kludge them in following the same
  37075. // const naming scheme zlib uses.
  37076. binding.Z_MIN_WINDOWBITS = 8;
  37077. binding.Z_MAX_WINDOWBITS = 15;
  37078. binding.Z_DEFAULT_WINDOWBITS = 15;
  37079. // fewer than 64 bytes per chunk is stupid.
  37080. // technically it could work with as few as 8, but even 64 bytes
  37081. // is absurdly low. Usually a MB or more is best.
  37082. binding.Z_MIN_CHUNK = 64;
  37083. binding.Z_MAX_CHUNK = Infinity;
  37084. binding.Z_DEFAULT_CHUNK = 16 * 1024;
  37085. binding.Z_MIN_MEMLEVEL = 1;
  37086. binding.Z_MAX_MEMLEVEL = 9;
  37087. binding.Z_DEFAULT_MEMLEVEL = 8;
  37088. binding.Z_MIN_LEVEL = -1;
  37089. binding.Z_MAX_LEVEL = 9;
  37090. binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
  37091. // expose all the zlib constants
  37092. var bkeys = Object.keys(binding);
  37093. for (var bk = 0; bk < bkeys.length; bk++) {
  37094. var bkey = bkeys[bk];
  37095. if (bkey.match(/^Z/)) {
  37096. Object.defineProperty(exports, bkey, {
  37097. enumerable: true, value: binding[bkey], writable: false
  37098. });
  37099. }
  37100. }
  37101. // translation table for return codes.
  37102. var codes = {
  37103. Z_OK: binding.Z_OK,
  37104. Z_STREAM_END: binding.Z_STREAM_END,
  37105. Z_NEED_DICT: binding.Z_NEED_DICT,
  37106. Z_ERRNO: binding.Z_ERRNO,
  37107. Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
  37108. Z_DATA_ERROR: binding.Z_DATA_ERROR,
  37109. Z_MEM_ERROR: binding.Z_MEM_ERROR,
  37110. Z_BUF_ERROR: binding.Z_BUF_ERROR,
  37111. Z_VERSION_ERROR: binding.Z_VERSION_ERROR
  37112. };
  37113. var ckeys = Object.keys(codes);
  37114. for (var ck = 0; ck < ckeys.length; ck++) {
  37115. var ckey = ckeys[ck];
  37116. codes[codes[ckey]] = ckey;
  37117. }
  37118. Object.defineProperty(exports, 'codes', {
  37119. enumerable: true, value: Object.freeze(codes), writable: false
  37120. });
  37121. exports.Deflate = Deflate;
  37122. exports.Inflate = Inflate;
  37123. exports.Gzip = Gzip;
  37124. exports.Gunzip = Gunzip;
  37125. exports.DeflateRaw = DeflateRaw;
  37126. exports.InflateRaw = InflateRaw;
  37127. exports.Unzip = Unzip;
  37128. exports.createDeflate = function (o) {
  37129. return new Deflate(o);
  37130. };
  37131. exports.createInflate = function (o) {
  37132. return new Inflate(o);
  37133. };
  37134. exports.createDeflateRaw = function (o) {
  37135. return new DeflateRaw(o);
  37136. };
  37137. exports.createInflateRaw = function (o) {
  37138. return new InflateRaw(o);
  37139. };
  37140. exports.createGzip = function (o) {
  37141. return new Gzip(o);
  37142. };
  37143. exports.createGunzip = function (o) {
  37144. return new Gunzip(o);
  37145. };
  37146. exports.createUnzip = function (o) {
  37147. return new Unzip(o);
  37148. };
  37149. // Convenience methods.
  37150. // compress/decompress a string or buffer in one step.
  37151. exports.deflate = function (buffer, opts, callback) {
  37152. if (typeof opts === 'function') {
  37153. callback = opts;
  37154. opts = {};
  37155. }
  37156. return zlibBuffer(new Deflate(opts), buffer, callback);
  37157. };
  37158. exports.deflateSync = function (buffer, opts) {
  37159. return zlibBufferSync(new Deflate(opts), buffer);
  37160. };
  37161. exports.gzip = function (buffer, opts, callback) {
  37162. if (typeof opts === 'function') {
  37163. callback = opts;
  37164. opts = {};
  37165. }
  37166. return zlibBuffer(new Gzip(opts), buffer, callback);
  37167. };
  37168. exports.gzipSync = function (buffer, opts) {
  37169. return zlibBufferSync(new Gzip(opts), buffer);
  37170. };
  37171. exports.deflateRaw = function (buffer, opts, callback) {
  37172. if (typeof opts === 'function') {
  37173. callback = opts;
  37174. opts = {};
  37175. }
  37176. return zlibBuffer(new DeflateRaw(opts), buffer, callback);
  37177. };
  37178. exports.deflateRawSync = function (buffer, opts) {
  37179. return zlibBufferSync(new DeflateRaw(opts), buffer);
  37180. };
  37181. exports.unzip = function (buffer, opts, callback) {
  37182. if (typeof opts === 'function') {
  37183. callback = opts;
  37184. opts = {};
  37185. }
  37186. return zlibBuffer(new Unzip(opts), buffer, callback);
  37187. };
  37188. exports.unzipSync = function (buffer, opts) {
  37189. return zlibBufferSync(new Unzip(opts), buffer);
  37190. };
  37191. exports.inflate = function (buffer, opts, callback) {
  37192. if (typeof opts === 'function') {
  37193. callback = opts;
  37194. opts = {};
  37195. }
  37196. return zlibBuffer(new Inflate(opts), buffer, callback);
  37197. };
  37198. exports.inflateSync = function (buffer, opts) {
  37199. return zlibBufferSync(new Inflate(opts), buffer);
  37200. };
  37201. exports.gunzip = function (buffer, opts, callback) {
  37202. if (typeof opts === 'function') {
  37203. callback = opts;
  37204. opts = {};
  37205. }
  37206. return zlibBuffer(new Gunzip(opts), buffer, callback);
  37207. };
  37208. exports.gunzipSync = function (buffer, opts) {
  37209. return zlibBufferSync(new Gunzip(opts), buffer);
  37210. };
  37211. exports.inflateRaw = function (buffer, opts, callback) {
  37212. if (typeof opts === 'function') {
  37213. callback = opts;
  37214. opts = {};
  37215. }
  37216. return zlibBuffer(new InflateRaw(opts), buffer, callback);
  37217. };
  37218. exports.inflateRawSync = function (buffer, opts) {
  37219. return zlibBufferSync(new InflateRaw(opts), buffer);
  37220. };
  37221. function zlibBuffer(engine, buffer, callback) {
  37222. var buffers = [];
  37223. var nread = 0;
  37224. engine.on('error', onError);
  37225. engine.on('end', onEnd);
  37226. engine.end(buffer);
  37227. flow();
  37228. function flow() {
  37229. var chunk;
  37230. while (null !== (chunk = engine.read())) {
  37231. buffers.push(chunk);
  37232. nread += chunk.length;
  37233. }
  37234. engine.once('readable', flow);
  37235. }
  37236. function onError(err) {
  37237. engine.removeListener('end', onEnd);
  37238. engine.removeListener('readable', flow);
  37239. callback(err);
  37240. }
  37241. function onEnd() {
  37242. var buf;
  37243. var err = null;
  37244. if (nread >= kMaxLength) {
  37245. err = new RangeError(kRangeErrorMessage);
  37246. } else {
  37247. buf = Buffer.concat(buffers, nread);
  37248. }
  37249. buffers = [];
  37250. engine.close();
  37251. callback(err, buf);
  37252. }
  37253. }
  37254. function zlibBufferSync(engine, buffer) {
  37255. if (typeof buffer === 'string') buffer = Buffer.from(buffer);
  37256. if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
  37257. var flushFlag = engine._finishFlushFlag;
  37258. return engine._processChunk(buffer, flushFlag);
  37259. }
  37260. // generic zlib
  37261. // minimal 2-byte header
  37262. function Deflate(opts) {
  37263. if (!(this instanceof Deflate)) return new Deflate(opts);
  37264. Zlib.call(this, opts, binding.DEFLATE);
  37265. }
  37266. function Inflate(opts) {
  37267. if (!(this instanceof Inflate)) return new Inflate(opts);
  37268. Zlib.call(this, opts, binding.INFLATE);
  37269. }
  37270. // gzip - bigger header, same deflate compression
  37271. function Gzip(opts) {
  37272. if (!(this instanceof Gzip)) return new Gzip(opts);
  37273. Zlib.call(this, opts, binding.GZIP);
  37274. }
  37275. function Gunzip(opts) {
  37276. if (!(this instanceof Gunzip)) return new Gunzip(opts);
  37277. Zlib.call(this, opts, binding.GUNZIP);
  37278. }
  37279. // raw - no header
  37280. function DeflateRaw(opts) {
  37281. if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
  37282. Zlib.call(this, opts, binding.DEFLATERAW);
  37283. }
  37284. function InflateRaw(opts) {
  37285. if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
  37286. Zlib.call(this, opts, binding.INFLATERAW);
  37287. }
  37288. // auto-detect header.
  37289. function Unzip(opts) {
  37290. if (!(this instanceof Unzip)) return new Unzip(opts);
  37291. Zlib.call(this, opts, binding.UNZIP);
  37292. }
  37293. function isValidFlushFlag(flag) {
  37294. return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
  37295. }
  37296. // the Zlib class they all inherit from
  37297. // This thing manages the queue of requests, and returns
  37298. // true or false if there is anything in the queue when
  37299. // you call the .write() method.
  37300. function Zlib(opts, mode) {
  37301. var _this = this;
  37302. this._opts = opts = opts || {};
  37303. this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
  37304. Transform.call(this, opts);
  37305. if (opts.flush && !isValidFlushFlag(opts.flush)) {
  37306. throw new Error('Invalid flush flag: ' + opts.flush);
  37307. }
  37308. if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
  37309. throw new Error('Invalid flush flag: ' + opts.finishFlush);
  37310. }
  37311. this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
  37312. this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
  37313. if (opts.chunkSize) {
  37314. if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
  37315. throw new Error('Invalid chunk size: ' + opts.chunkSize);
  37316. }
  37317. }
  37318. if (opts.windowBits) {
  37319. if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
  37320. throw new Error('Invalid windowBits: ' + opts.windowBits);
  37321. }
  37322. }
  37323. if (opts.level) {
  37324. if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
  37325. throw new Error('Invalid compression level: ' + opts.level);
  37326. }
  37327. }
  37328. if (opts.memLevel) {
  37329. if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
  37330. throw new Error('Invalid memLevel: ' + opts.memLevel);
  37331. }
  37332. }
  37333. if (opts.strategy) {
  37334. if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
  37335. throw new Error('Invalid strategy: ' + opts.strategy);
  37336. }
  37337. }
  37338. if (opts.dictionary) {
  37339. if (!Buffer.isBuffer(opts.dictionary)) {
  37340. throw new Error('Invalid dictionary: it should be a Buffer instance');
  37341. }
  37342. }
  37343. this._handle = new binding.Zlib(mode);
  37344. var self = this;
  37345. this._hadError = false;
  37346. this._handle.onerror = function (message, errno) {
  37347. // there is no way to cleanly recover.
  37348. // continuing only obscures problems.
  37349. _close(self);
  37350. self._hadError = true;
  37351. var error = new Error(message);
  37352. error.errno = errno;
  37353. error.code = exports.codes[errno];
  37354. self.emit('error', error);
  37355. };
  37356. var level = exports.Z_DEFAULT_COMPRESSION;
  37357. if (typeof opts.level === 'number') level = opts.level;
  37358. var strategy = exports.Z_DEFAULT_STRATEGY;
  37359. if (typeof opts.strategy === 'number') strategy = opts.strategy;
  37360. this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
  37361. this._buffer = Buffer.allocUnsafe(this._chunkSize);
  37362. this._offset = 0;
  37363. this._level = level;
  37364. this._strategy = strategy;
  37365. this.once('end', this.close);
  37366. Object.defineProperty(this, '_closed', {
  37367. get: function () {
  37368. return !_this._handle;
  37369. },
  37370. configurable: true,
  37371. enumerable: true
  37372. });
  37373. }
  37374. util.inherits(Zlib, Transform);
  37375. Zlib.prototype.params = function (level, strategy, callback) {
  37376. if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
  37377. throw new RangeError('Invalid compression level: ' + level);
  37378. }
  37379. if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
  37380. throw new TypeError('Invalid strategy: ' + strategy);
  37381. }
  37382. if (this._level !== level || this._strategy !== strategy) {
  37383. var self = this;
  37384. this.flush(binding.Z_SYNC_FLUSH, function () {
  37385. assert(self._handle, 'zlib binding closed');
  37386. self._handle.params(level, strategy);
  37387. if (!self._hadError) {
  37388. self._level = level;
  37389. self._strategy = strategy;
  37390. if (callback) callback();
  37391. }
  37392. });
  37393. } else {
  37394. process.nextTick(callback);
  37395. }
  37396. };
  37397. Zlib.prototype.reset = function () {
  37398. assert(this._handle, 'zlib binding closed');
  37399. return this._handle.reset();
  37400. };
  37401. // This is the _flush function called by the transform class,
  37402. // internally, when the last chunk has been written.
  37403. Zlib.prototype._flush = function (callback) {
  37404. this._transform(Buffer.alloc(0), '', callback);
  37405. };
  37406. Zlib.prototype.flush = function (kind, callback) {
  37407. var _this2 = this;
  37408. var ws = this._writableState;
  37409. if (typeof kind === 'function' || kind === undefined && !callback) {
  37410. callback = kind;
  37411. kind = binding.Z_FULL_FLUSH;
  37412. }
  37413. if (ws.ended) {
  37414. if (callback) process.nextTick(callback);
  37415. } else if (ws.ending) {
  37416. if (callback) this.once('end', callback);
  37417. } else if (ws.needDrain) {
  37418. if (callback) {
  37419. this.once('drain', function () {
  37420. return _this2.flush(kind, callback);
  37421. });
  37422. }
  37423. } else {
  37424. this._flushFlag = kind;
  37425. this.write(Buffer.alloc(0), '', callback);
  37426. }
  37427. };
  37428. Zlib.prototype.close = function (callback) {
  37429. _close(this, callback);
  37430. process.nextTick(emitCloseNT, this);
  37431. };
  37432. function _close(engine, callback) {
  37433. if (callback) process.nextTick(callback);
  37434. // Caller may invoke .close after a zlib error (which will null _handle).
  37435. if (!engine._handle) return;
  37436. engine._handle.close();
  37437. engine._handle = null;
  37438. }
  37439. function emitCloseNT(self) {
  37440. self.emit('close');
  37441. }
  37442. Zlib.prototype._transform = function (chunk, encoding, cb) {
  37443. var flushFlag;
  37444. var ws = this._writableState;
  37445. var ending = ws.ending || ws.ended;
  37446. var last = ending && (!chunk || ws.length === chunk.length);
  37447. if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
  37448. if (!this._handle) return cb(new Error('zlib binding closed'));
  37449. // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
  37450. // (or whatever flag was provided using opts.finishFlush).
  37451. // If it's explicitly flushing at some other time, then we use
  37452. // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
  37453. // goodness.
  37454. if (last) flushFlag = this._finishFlushFlag;else {
  37455. flushFlag = this._flushFlag;
  37456. // once we've flushed the last of the queue, stop flushing and
  37457. // go back to the normal behavior.
  37458. if (chunk.length >= ws.length) {
  37459. this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
  37460. }
  37461. }
  37462. this._processChunk(chunk, flushFlag, cb);
  37463. };
  37464. Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
  37465. var availInBefore = chunk && chunk.length;
  37466. var availOutBefore = this._chunkSize - this._offset;
  37467. var inOff = 0;
  37468. var self = this;
  37469. var async = typeof cb === 'function';
  37470. if (!async) {
  37471. var buffers = [];
  37472. var nread = 0;
  37473. var error;
  37474. this.on('error', function (er) {
  37475. error = er;
  37476. });
  37477. assert(this._handle, 'zlib binding closed');
  37478. do {
  37479. var res = this._handle.writeSync(flushFlag, chunk, // in
  37480. inOff, // in_off
  37481. availInBefore, // in_len
  37482. this._buffer, // out
  37483. this._offset, //out_off
  37484. availOutBefore); // out_len
  37485. } while (!this._hadError && callback(res[0], res[1]));
  37486. if (this._hadError) {
  37487. throw error;
  37488. }
  37489. if (nread >= kMaxLength) {
  37490. _close(this);
  37491. throw new RangeError(kRangeErrorMessage);
  37492. }
  37493. var buf = Buffer.concat(buffers, nread);
  37494. _close(this);
  37495. return buf;
  37496. }
  37497. assert(this._handle, 'zlib binding closed');
  37498. var req = this._handle.write(flushFlag, chunk, // in
  37499. inOff, // in_off
  37500. availInBefore, // in_len
  37501. this._buffer, // out
  37502. this._offset, //out_off
  37503. availOutBefore); // out_len
  37504. req.buffer = chunk;
  37505. req.callback = callback;
  37506. function callback(availInAfter, availOutAfter) {
  37507. // When the callback is used in an async write, the callback's
  37508. // context is the `req` object that was created. The req object
  37509. // is === this._handle, and that's why it's important to null
  37510. // out the values after they are done being used. `this._handle`
  37511. // can stay in memory longer than the callback and buffer are needed.
  37512. if (this) {
  37513. this.buffer = null;
  37514. this.callback = null;
  37515. }
  37516. if (self._hadError) return;
  37517. var have = availOutBefore - availOutAfter;
  37518. assert(have >= 0, 'have should not go down');
  37519. if (have > 0) {
  37520. var out = self._buffer.slice(self._offset, self._offset + have);
  37521. self._offset += have;
  37522. // serve some output to the consumer.
  37523. if (async) {
  37524. self.push(out);
  37525. } else {
  37526. buffers.push(out);
  37527. nread += out.length;
  37528. }
  37529. }
  37530. // exhausted the output buffer, or used all the input create a new one.
  37531. if (availOutAfter === 0 || self._offset >= self._chunkSize) {
  37532. availOutBefore = self._chunkSize;
  37533. self._offset = 0;
  37534. self._buffer = Buffer.allocUnsafe(self._chunkSize);
  37535. }
  37536. if (availOutAfter === 0) {
  37537. // Not actually done. Need to reprocess.
  37538. // Also, update the availInBefore to the availInAfter value,
  37539. // so that if we have to hit it a third (fourth, etc.) time,
  37540. // it'll have the correct byte counts.
  37541. inOff += availInBefore - availInAfter;
  37542. availInBefore = availInAfter;
  37543. if (!async) return true;
  37544. var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
  37545. newReq.callback = callback; // this same function
  37546. newReq.buffer = chunk;
  37547. return;
  37548. }
  37549. if (!async) return false;
  37550. // finished with the chunk.
  37551. cb();
  37552. }
  37553. };
  37554. util.inherits(Deflate, Zlib);
  37555. util.inherits(Inflate, Zlib);
  37556. util.inherits(Gzip, Zlib);
  37557. util.inherits(Gunzip, Zlib);
  37558. util.inherits(DeflateRaw, Zlib);
  37559. util.inherits(InflateRaw, Zlib);
  37560. util.inherits(Unzip, Zlib);
  37561. }).call(this)}).call(this,require('_process'))
  37562. },{"./binding":188,"_process":525,"assert":105,"buffer":193,"stream":597,"util":658}],190:[function(require,module,exports){
  37563. arguments[4][144][0].apply(exports,arguments)
  37564. },{"dup":144}],191:[function(require,module,exports){
  37565. /*jshint node:true */
  37566. 'use strict';
  37567. var Buffer = require('buffer').Buffer; // browserify
  37568. var SlowBuffer = require('buffer').SlowBuffer;
  37569. module.exports = bufferEq;
  37570. function bufferEq(a, b) {
  37571. // shortcutting on type is necessary for correctness
  37572. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  37573. return false;
  37574. }
  37575. // buffer sizes should be well-known information, so despite this
  37576. // shortcutting, it doesn't leak any information about the *contents* of the
  37577. // buffers.
  37578. if (a.length !== b.length) {
  37579. return false;
  37580. }
  37581. var c = 0;
  37582. for (var i = 0; i < a.length; i++) {
  37583. /*jshint bitwise:false */
  37584. c |= a[i] ^ b[i]; // XOR
  37585. }
  37586. return c === 0;
  37587. }
  37588. bufferEq.install = function() {
  37589. Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {
  37590. return bufferEq(this, that);
  37591. };
  37592. };
  37593. var origBufEqual = Buffer.prototype.equal;
  37594. var origSlowBufEqual = SlowBuffer.prototype.equal;
  37595. bufferEq.restore = function() {
  37596. Buffer.prototype.equal = origBufEqual;
  37597. SlowBuffer.prototype.equal = origSlowBufEqual;
  37598. };
  37599. },{"buffer":193}],192:[function(require,module,exports){
  37600. (function (Buffer){(function (){
  37601. module.exports = function xor (a, b) {
  37602. var length = Math.min(a.length, b.length)
  37603. var buffer = new Buffer(length)
  37604. for (var i = 0; i < length; ++i) {
  37605. buffer[i] = a[i] ^ b[i]
  37606. }
  37607. return buffer
  37608. }
  37609. }).call(this)}).call(this,require("buffer").Buffer)
  37610. },{"buffer":193}],193:[function(require,module,exports){
  37611. (function (Buffer){(function (){
  37612. /*!
  37613. * The buffer module from node.js, for the browser.
  37614. *
  37615. * @author Feross Aboukhadijeh <https://feross.org>
  37616. * @license MIT
  37617. */
  37618. /* eslint-disable no-proto */
  37619. 'use strict'
  37620. var base64 = require('base64-js')
  37621. var ieee754 = require('ieee754')
  37622. exports.Buffer = Buffer
  37623. exports.SlowBuffer = SlowBuffer
  37624. exports.INSPECT_MAX_BYTES = 50
  37625. var K_MAX_LENGTH = 0x7fffffff
  37626. exports.kMaxLength = K_MAX_LENGTH
  37627. /**
  37628. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  37629. * === true Use Uint8Array implementation (fastest)
  37630. * === false Print warning and recommend using `buffer` v4.x which has an Object
  37631. * implementation (most compatible, even IE6)
  37632. *
  37633. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  37634. * Opera 11.6+, iOS 4.2+.
  37635. *
  37636. * We report that the browser does not support typed arrays if the are not subclassable
  37637. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  37638. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  37639. * for __proto__ and has a buggy typed array implementation.
  37640. */
  37641. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  37642. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  37643. typeof console.error === 'function') {
  37644. console.error(
  37645. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  37646. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  37647. )
  37648. }
  37649. function typedArraySupport () {
  37650. // Can typed array instances can be augmented?
  37651. try {
  37652. var arr = new Uint8Array(1)
  37653. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  37654. return arr.foo() === 42
  37655. } catch (e) {
  37656. return false
  37657. }
  37658. }
  37659. Object.defineProperty(Buffer.prototype, 'parent', {
  37660. enumerable: true,
  37661. get: function () {
  37662. if (!Buffer.isBuffer(this)) return undefined
  37663. return this.buffer
  37664. }
  37665. })
  37666. Object.defineProperty(Buffer.prototype, 'offset', {
  37667. enumerable: true,
  37668. get: function () {
  37669. if (!Buffer.isBuffer(this)) return undefined
  37670. return this.byteOffset
  37671. }
  37672. })
  37673. function createBuffer (length) {
  37674. if (length > K_MAX_LENGTH) {
  37675. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  37676. }
  37677. // Return an augmented `Uint8Array` instance
  37678. var buf = new Uint8Array(length)
  37679. buf.__proto__ = Buffer.prototype
  37680. return buf
  37681. }
  37682. /**
  37683. * The Buffer constructor returns instances of `Uint8Array` that have their
  37684. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  37685. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  37686. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  37687. * returns a single octet.
  37688. *
  37689. * The `Uint8Array` prototype remains unmodified.
  37690. */
  37691. function Buffer (arg, encodingOrOffset, length) {
  37692. // Common case.
  37693. if (typeof arg === 'number') {
  37694. if (typeof encodingOrOffset === 'string') {
  37695. throw new TypeError(
  37696. 'The "string" argument must be of type string. Received type number'
  37697. )
  37698. }
  37699. return allocUnsafe(arg)
  37700. }
  37701. return from(arg, encodingOrOffset, length)
  37702. }
  37703. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  37704. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  37705. Buffer[Symbol.species] === Buffer) {
  37706. Object.defineProperty(Buffer, Symbol.species, {
  37707. value: null,
  37708. configurable: true,
  37709. enumerable: false,
  37710. writable: false
  37711. })
  37712. }
  37713. Buffer.poolSize = 8192 // not used by this implementation
  37714. function from (value, encodingOrOffset, length) {
  37715. if (typeof value === 'string') {
  37716. return fromString(value, encodingOrOffset)
  37717. }
  37718. if (ArrayBuffer.isView(value)) {
  37719. return fromArrayLike(value)
  37720. }
  37721. if (value == null) {
  37722. throw TypeError(
  37723. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  37724. 'or Array-like Object. Received type ' + (typeof value)
  37725. )
  37726. }
  37727. if (isInstance(value, ArrayBuffer) ||
  37728. (value && isInstance(value.buffer, ArrayBuffer))) {
  37729. return fromArrayBuffer(value, encodingOrOffset, length)
  37730. }
  37731. if (typeof value === 'number') {
  37732. throw new TypeError(
  37733. 'The "value" argument must not be of type number. Received type number'
  37734. )
  37735. }
  37736. var valueOf = value.valueOf && value.valueOf()
  37737. if (valueOf != null && valueOf !== value) {
  37738. return Buffer.from(valueOf, encodingOrOffset, length)
  37739. }
  37740. var b = fromObject(value)
  37741. if (b) return b
  37742. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  37743. typeof value[Symbol.toPrimitive] === 'function') {
  37744. return Buffer.from(
  37745. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  37746. )
  37747. }
  37748. throw new TypeError(
  37749. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  37750. 'or Array-like Object. Received type ' + (typeof value)
  37751. )
  37752. }
  37753. /**
  37754. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  37755. * if value is a number.
  37756. * Buffer.from(str[, encoding])
  37757. * Buffer.from(array)
  37758. * Buffer.from(buffer)
  37759. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  37760. **/
  37761. Buffer.from = function (value, encodingOrOffset, length) {
  37762. return from(value, encodingOrOffset, length)
  37763. }
  37764. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  37765. // https://github.com/feross/buffer/pull/148
  37766. Buffer.prototype.__proto__ = Uint8Array.prototype
  37767. Buffer.__proto__ = Uint8Array
  37768. function assertSize (size) {
  37769. if (typeof size !== 'number') {
  37770. throw new TypeError('"size" argument must be of type number')
  37771. } else if (size < 0) {
  37772. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  37773. }
  37774. }
  37775. function alloc (size, fill, encoding) {
  37776. assertSize(size)
  37777. if (size <= 0) {
  37778. return createBuffer(size)
  37779. }
  37780. if (fill !== undefined) {
  37781. // Only pay attention to encoding if it's a string. This
  37782. // prevents accidentally sending in a number that would
  37783. // be interpretted as a start offset.
  37784. return typeof encoding === 'string'
  37785. ? createBuffer(size).fill(fill, encoding)
  37786. : createBuffer(size).fill(fill)
  37787. }
  37788. return createBuffer(size)
  37789. }
  37790. /**
  37791. * Creates a new filled Buffer instance.
  37792. * alloc(size[, fill[, encoding]])
  37793. **/
  37794. Buffer.alloc = function (size, fill, encoding) {
  37795. return alloc(size, fill, encoding)
  37796. }
  37797. function allocUnsafe (size) {
  37798. assertSize(size)
  37799. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  37800. }
  37801. /**
  37802. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  37803. * */
  37804. Buffer.allocUnsafe = function (size) {
  37805. return allocUnsafe(size)
  37806. }
  37807. /**
  37808. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  37809. */
  37810. Buffer.allocUnsafeSlow = function (size) {
  37811. return allocUnsafe(size)
  37812. }
  37813. function fromString (string, encoding) {
  37814. if (typeof encoding !== 'string' || encoding === '') {
  37815. encoding = 'utf8'
  37816. }
  37817. if (!Buffer.isEncoding(encoding)) {
  37818. throw new TypeError('Unknown encoding: ' + encoding)
  37819. }
  37820. var length = byteLength(string, encoding) | 0
  37821. var buf = createBuffer(length)
  37822. var actual = buf.write(string, encoding)
  37823. if (actual !== length) {
  37824. // Writing a hex string, for example, that contains invalid characters will
  37825. // cause everything after the first invalid character to be ignored. (e.g.
  37826. // 'abxxcd' will be treated as 'ab')
  37827. buf = buf.slice(0, actual)
  37828. }
  37829. return buf
  37830. }
  37831. function fromArrayLike (array) {
  37832. var length = array.length < 0 ? 0 : checked(array.length) | 0
  37833. var buf = createBuffer(length)
  37834. for (var i = 0; i < length; i += 1) {
  37835. buf[i] = array[i] & 255
  37836. }
  37837. return buf
  37838. }
  37839. function fromArrayBuffer (array, byteOffset, length) {
  37840. if (byteOffset < 0 || array.byteLength < byteOffset) {
  37841. throw new RangeError('"offset" is outside of buffer bounds')
  37842. }
  37843. if (array.byteLength < byteOffset + (length || 0)) {
  37844. throw new RangeError('"length" is outside of buffer bounds')
  37845. }
  37846. var buf
  37847. if (byteOffset === undefined && length === undefined) {
  37848. buf = new Uint8Array(array)
  37849. } else if (length === undefined) {
  37850. buf = new Uint8Array(array, byteOffset)
  37851. } else {
  37852. buf = new Uint8Array(array, byteOffset, length)
  37853. }
  37854. // Return an augmented `Uint8Array` instance
  37855. buf.__proto__ = Buffer.prototype
  37856. return buf
  37857. }
  37858. function fromObject (obj) {
  37859. if (Buffer.isBuffer(obj)) {
  37860. var len = checked(obj.length) | 0
  37861. var buf = createBuffer(len)
  37862. if (buf.length === 0) {
  37863. return buf
  37864. }
  37865. obj.copy(buf, 0, 0, len)
  37866. return buf
  37867. }
  37868. if (obj.length !== undefined) {
  37869. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  37870. return createBuffer(0)
  37871. }
  37872. return fromArrayLike(obj)
  37873. }
  37874. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  37875. return fromArrayLike(obj.data)
  37876. }
  37877. }
  37878. function checked (length) {
  37879. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  37880. // length is NaN (which is otherwise coerced to zero.)
  37881. if (length >= K_MAX_LENGTH) {
  37882. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  37883. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  37884. }
  37885. return length | 0
  37886. }
  37887. function SlowBuffer (length) {
  37888. if (+length != length) { // eslint-disable-line eqeqeq
  37889. length = 0
  37890. }
  37891. return Buffer.alloc(+length)
  37892. }
  37893. Buffer.isBuffer = function isBuffer (b) {
  37894. return b != null && b._isBuffer === true &&
  37895. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  37896. }
  37897. Buffer.compare = function compare (a, b) {
  37898. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  37899. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  37900. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  37901. throw new TypeError(
  37902. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  37903. )
  37904. }
  37905. if (a === b) return 0
  37906. var x = a.length
  37907. var y = b.length
  37908. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  37909. if (a[i] !== b[i]) {
  37910. x = a[i]
  37911. y = b[i]
  37912. break
  37913. }
  37914. }
  37915. if (x < y) return -1
  37916. if (y < x) return 1
  37917. return 0
  37918. }
  37919. Buffer.isEncoding = function isEncoding (encoding) {
  37920. switch (String(encoding).toLowerCase()) {
  37921. case 'hex':
  37922. case 'utf8':
  37923. case 'utf-8':
  37924. case 'ascii':
  37925. case 'latin1':
  37926. case 'binary':
  37927. case 'base64':
  37928. case 'ucs2':
  37929. case 'ucs-2':
  37930. case 'utf16le':
  37931. case 'utf-16le':
  37932. return true
  37933. default:
  37934. return false
  37935. }
  37936. }
  37937. Buffer.concat = function concat (list, length) {
  37938. if (!Array.isArray(list)) {
  37939. throw new TypeError('"list" argument must be an Array of Buffers')
  37940. }
  37941. if (list.length === 0) {
  37942. return Buffer.alloc(0)
  37943. }
  37944. var i
  37945. if (length === undefined) {
  37946. length = 0
  37947. for (i = 0; i < list.length; ++i) {
  37948. length += list[i].length
  37949. }
  37950. }
  37951. var buffer = Buffer.allocUnsafe(length)
  37952. var pos = 0
  37953. for (i = 0; i < list.length; ++i) {
  37954. var buf = list[i]
  37955. if (isInstance(buf, Uint8Array)) {
  37956. buf = Buffer.from(buf)
  37957. }
  37958. if (!Buffer.isBuffer(buf)) {
  37959. throw new TypeError('"list" argument must be an Array of Buffers')
  37960. }
  37961. buf.copy(buffer, pos)
  37962. pos += buf.length
  37963. }
  37964. return buffer
  37965. }
  37966. function byteLength (string, encoding) {
  37967. if (Buffer.isBuffer(string)) {
  37968. return string.length
  37969. }
  37970. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  37971. return string.byteLength
  37972. }
  37973. if (typeof string !== 'string') {
  37974. throw new TypeError(
  37975. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  37976. 'Received type ' + typeof string
  37977. )
  37978. }
  37979. var len = string.length
  37980. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  37981. if (!mustMatch && len === 0) return 0
  37982. // Use a for loop to avoid recursion
  37983. var loweredCase = false
  37984. for (;;) {
  37985. switch (encoding) {
  37986. case 'ascii':
  37987. case 'latin1':
  37988. case 'binary':
  37989. return len
  37990. case 'utf8':
  37991. case 'utf-8':
  37992. return utf8ToBytes(string).length
  37993. case 'ucs2':
  37994. case 'ucs-2':
  37995. case 'utf16le':
  37996. case 'utf-16le':
  37997. return len * 2
  37998. case 'hex':
  37999. return len >>> 1
  38000. case 'base64':
  38001. return base64ToBytes(string).length
  38002. default:
  38003. if (loweredCase) {
  38004. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  38005. }
  38006. encoding = ('' + encoding).toLowerCase()
  38007. loweredCase = true
  38008. }
  38009. }
  38010. }
  38011. Buffer.byteLength = byteLength
  38012. function slowToString (encoding, start, end) {
  38013. var loweredCase = false
  38014. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  38015. // property of a typed array.
  38016. // This behaves neither like String nor Uint8Array in that we set start/end
  38017. // to their upper/lower bounds if the value passed is out of range.
  38018. // undefined is handled specially as per ECMA-262 6th Edition,
  38019. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  38020. if (start === undefined || start < 0) {
  38021. start = 0
  38022. }
  38023. // Return early if start > this.length. Done here to prevent potential uint32
  38024. // coercion fail below.
  38025. if (start > this.length) {
  38026. return ''
  38027. }
  38028. if (end === undefined || end > this.length) {
  38029. end = this.length
  38030. }
  38031. if (end <= 0) {
  38032. return ''
  38033. }
  38034. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  38035. end >>>= 0
  38036. start >>>= 0
  38037. if (end <= start) {
  38038. return ''
  38039. }
  38040. if (!encoding) encoding = 'utf8'
  38041. while (true) {
  38042. switch (encoding) {
  38043. case 'hex':
  38044. return hexSlice(this, start, end)
  38045. case 'utf8':
  38046. case 'utf-8':
  38047. return utf8Slice(this, start, end)
  38048. case 'ascii':
  38049. return asciiSlice(this, start, end)
  38050. case 'latin1':
  38051. case 'binary':
  38052. return latin1Slice(this, start, end)
  38053. case 'base64':
  38054. return base64Slice(this, start, end)
  38055. case 'ucs2':
  38056. case 'ucs-2':
  38057. case 'utf16le':
  38058. case 'utf-16le':
  38059. return utf16leSlice(this, start, end)
  38060. default:
  38061. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  38062. encoding = (encoding + '').toLowerCase()
  38063. loweredCase = true
  38064. }
  38065. }
  38066. }
  38067. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  38068. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  38069. // reliably in a browserify context because there could be multiple different
  38070. // copies of the 'buffer' package in use. This method works even for Buffer
  38071. // instances that were created from another copy of the `buffer` package.
  38072. // See: https://github.com/feross/buffer/issues/154
  38073. Buffer.prototype._isBuffer = true
  38074. function swap (b, n, m) {
  38075. var i = b[n]
  38076. b[n] = b[m]
  38077. b[m] = i
  38078. }
  38079. Buffer.prototype.swap16 = function swap16 () {
  38080. var len = this.length
  38081. if (len % 2 !== 0) {
  38082. throw new RangeError('Buffer size must be a multiple of 16-bits')
  38083. }
  38084. for (var i = 0; i < len; i += 2) {
  38085. swap(this, i, i + 1)
  38086. }
  38087. return this
  38088. }
  38089. Buffer.prototype.swap32 = function swap32 () {
  38090. var len = this.length
  38091. if (len % 4 !== 0) {
  38092. throw new RangeError('Buffer size must be a multiple of 32-bits')
  38093. }
  38094. for (var i = 0; i < len; i += 4) {
  38095. swap(this, i, i + 3)
  38096. swap(this, i + 1, i + 2)
  38097. }
  38098. return this
  38099. }
  38100. Buffer.prototype.swap64 = function swap64 () {
  38101. var len = this.length
  38102. if (len % 8 !== 0) {
  38103. throw new RangeError('Buffer size must be a multiple of 64-bits')
  38104. }
  38105. for (var i = 0; i < len; i += 8) {
  38106. swap(this, i, i + 7)
  38107. swap(this, i + 1, i + 6)
  38108. swap(this, i + 2, i + 5)
  38109. swap(this, i + 3, i + 4)
  38110. }
  38111. return this
  38112. }
  38113. Buffer.prototype.toString = function toString () {
  38114. var length = this.length
  38115. if (length === 0) return ''
  38116. if (arguments.length === 0) return utf8Slice(this, 0, length)
  38117. return slowToString.apply(this, arguments)
  38118. }
  38119. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  38120. Buffer.prototype.equals = function equals (b) {
  38121. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  38122. if (this === b) return true
  38123. return Buffer.compare(this, b) === 0
  38124. }
  38125. Buffer.prototype.inspect = function inspect () {
  38126. var str = ''
  38127. var max = exports.INSPECT_MAX_BYTES
  38128. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  38129. if (this.length > max) str += ' ... '
  38130. return '<Buffer ' + str + '>'
  38131. }
  38132. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  38133. if (isInstance(target, Uint8Array)) {
  38134. target = Buffer.from(target, target.offset, target.byteLength)
  38135. }
  38136. if (!Buffer.isBuffer(target)) {
  38137. throw new TypeError(
  38138. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  38139. 'Received type ' + (typeof target)
  38140. )
  38141. }
  38142. if (start === undefined) {
  38143. start = 0
  38144. }
  38145. if (end === undefined) {
  38146. end = target ? target.length : 0
  38147. }
  38148. if (thisStart === undefined) {
  38149. thisStart = 0
  38150. }
  38151. if (thisEnd === undefined) {
  38152. thisEnd = this.length
  38153. }
  38154. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  38155. throw new RangeError('out of range index')
  38156. }
  38157. if (thisStart >= thisEnd && start >= end) {
  38158. return 0
  38159. }
  38160. if (thisStart >= thisEnd) {
  38161. return -1
  38162. }
  38163. if (start >= end) {
  38164. return 1
  38165. }
  38166. start >>>= 0
  38167. end >>>= 0
  38168. thisStart >>>= 0
  38169. thisEnd >>>= 0
  38170. if (this === target) return 0
  38171. var x = thisEnd - thisStart
  38172. var y = end - start
  38173. var len = Math.min(x, y)
  38174. var thisCopy = this.slice(thisStart, thisEnd)
  38175. var targetCopy = target.slice(start, end)
  38176. for (var i = 0; i < len; ++i) {
  38177. if (thisCopy[i] !== targetCopy[i]) {
  38178. x = thisCopy[i]
  38179. y = targetCopy[i]
  38180. break
  38181. }
  38182. }
  38183. if (x < y) return -1
  38184. if (y < x) return 1
  38185. return 0
  38186. }
  38187. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  38188. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  38189. //
  38190. // Arguments:
  38191. // - buffer - a Buffer to search
  38192. // - val - a string, Buffer, or number
  38193. // - byteOffset - an index into `buffer`; will be clamped to an int32
  38194. // - encoding - an optional encoding, relevant is val is a string
  38195. // - dir - true for indexOf, false for lastIndexOf
  38196. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  38197. // Empty buffer means no match
  38198. if (buffer.length === 0) return -1
  38199. // Normalize byteOffset
  38200. if (typeof byteOffset === 'string') {
  38201. encoding = byteOffset
  38202. byteOffset = 0
  38203. } else if (byteOffset > 0x7fffffff) {
  38204. byteOffset = 0x7fffffff
  38205. } else if (byteOffset < -0x80000000) {
  38206. byteOffset = -0x80000000
  38207. }
  38208. byteOffset = +byteOffset // Coerce to Number.
  38209. if (numberIsNaN(byteOffset)) {
  38210. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  38211. byteOffset = dir ? 0 : (buffer.length - 1)
  38212. }
  38213. // Normalize byteOffset: negative offsets start from the end of the buffer
  38214. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  38215. if (byteOffset >= buffer.length) {
  38216. if (dir) return -1
  38217. else byteOffset = buffer.length - 1
  38218. } else if (byteOffset < 0) {
  38219. if (dir) byteOffset = 0
  38220. else return -1
  38221. }
  38222. // Normalize val
  38223. if (typeof val === 'string') {
  38224. val = Buffer.from(val, encoding)
  38225. }
  38226. // Finally, search either indexOf (if dir is true) or lastIndexOf
  38227. if (Buffer.isBuffer(val)) {
  38228. // Special case: looking for empty string/buffer always fails
  38229. if (val.length === 0) {
  38230. return -1
  38231. }
  38232. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  38233. } else if (typeof val === 'number') {
  38234. val = val & 0xFF // Search for a byte value [0-255]
  38235. if (typeof Uint8Array.prototype.indexOf === 'function') {
  38236. if (dir) {
  38237. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  38238. } else {
  38239. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  38240. }
  38241. }
  38242. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  38243. }
  38244. throw new TypeError('val must be string, number or Buffer')
  38245. }
  38246. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  38247. var indexSize = 1
  38248. var arrLength = arr.length
  38249. var valLength = val.length
  38250. if (encoding !== undefined) {
  38251. encoding = String(encoding).toLowerCase()
  38252. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  38253. encoding === 'utf16le' || encoding === 'utf-16le') {
  38254. if (arr.length < 2 || val.length < 2) {
  38255. return -1
  38256. }
  38257. indexSize = 2
  38258. arrLength /= 2
  38259. valLength /= 2
  38260. byteOffset /= 2
  38261. }
  38262. }
  38263. function read (buf, i) {
  38264. if (indexSize === 1) {
  38265. return buf[i]
  38266. } else {
  38267. return buf.readUInt16BE(i * indexSize)
  38268. }
  38269. }
  38270. var i
  38271. if (dir) {
  38272. var foundIndex = -1
  38273. for (i = byteOffset; i < arrLength; i++) {
  38274. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  38275. if (foundIndex === -1) foundIndex = i
  38276. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  38277. } else {
  38278. if (foundIndex !== -1) i -= i - foundIndex
  38279. foundIndex = -1
  38280. }
  38281. }
  38282. } else {
  38283. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  38284. for (i = byteOffset; i >= 0; i--) {
  38285. var found = true
  38286. for (var j = 0; j < valLength; j++) {
  38287. if (read(arr, i + j) !== read(val, j)) {
  38288. found = false
  38289. break
  38290. }
  38291. }
  38292. if (found) return i
  38293. }
  38294. }
  38295. return -1
  38296. }
  38297. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  38298. return this.indexOf(val, byteOffset, encoding) !== -1
  38299. }
  38300. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  38301. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  38302. }
  38303. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  38304. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  38305. }
  38306. function hexWrite (buf, string, offset, length) {
  38307. offset = Number(offset) || 0
  38308. var remaining = buf.length - offset
  38309. if (!length) {
  38310. length = remaining
  38311. } else {
  38312. length = Number(length)
  38313. if (length > remaining) {
  38314. length = remaining
  38315. }
  38316. }
  38317. var strLen = string.length
  38318. if (length > strLen / 2) {
  38319. length = strLen / 2
  38320. }
  38321. for (var i = 0; i < length; ++i) {
  38322. var parsed = parseInt(string.substr(i * 2, 2), 16)
  38323. if (numberIsNaN(parsed)) return i
  38324. buf[offset + i] = parsed
  38325. }
  38326. return i
  38327. }
  38328. function utf8Write (buf, string, offset, length) {
  38329. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  38330. }
  38331. function asciiWrite (buf, string, offset, length) {
  38332. return blitBuffer(asciiToBytes(string), buf, offset, length)
  38333. }
  38334. function latin1Write (buf, string, offset, length) {
  38335. return asciiWrite(buf, string, offset, length)
  38336. }
  38337. function base64Write (buf, string, offset, length) {
  38338. return blitBuffer(base64ToBytes(string), buf, offset, length)
  38339. }
  38340. function ucs2Write (buf, string, offset, length) {
  38341. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  38342. }
  38343. Buffer.prototype.write = function write (string, offset, length, encoding) {
  38344. // Buffer#write(string)
  38345. if (offset === undefined) {
  38346. encoding = 'utf8'
  38347. length = this.length
  38348. offset = 0
  38349. // Buffer#write(string, encoding)
  38350. } else if (length === undefined && typeof offset === 'string') {
  38351. encoding = offset
  38352. length = this.length
  38353. offset = 0
  38354. // Buffer#write(string, offset[, length][, encoding])
  38355. } else if (isFinite(offset)) {
  38356. offset = offset >>> 0
  38357. if (isFinite(length)) {
  38358. length = length >>> 0
  38359. if (encoding === undefined) encoding = 'utf8'
  38360. } else {
  38361. encoding = length
  38362. length = undefined
  38363. }
  38364. } else {
  38365. throw new Error(
  38366. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  38367. )
  38368. }
  38369. var remaining = this.length - offset
  38370. if (length === undefined || length > remaining) length = remaining
  38371. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  38372. throw new RangeError('Attempt to write outside buffer bounds')
  38373. }
  38374. if (!encoding) encoding = 'utf8'
  38375. var loweredCase = false
  38376. for (;;) {
  38377. switch (encoding) {
  38378. case 'hex':
  38379. return hexWrite(this, string, offset, length)
  38380. case 'utf8':
  38381. case 'utf-8':
  38382. return utf8Write(this, string, offset, length)
  38383. case 'ascii':
  38384. return asciiWrite(this, string, offset, length)
  38385. case 'latin1':
  38386. case 'binary':
  38387. return latin1Write(this, string, offset, length)
  38388. case 'base64':
  38389. // Warning: maxLength not taken into account in base64Write
  38390. return base64Write(this, string, offset, length)
  38391. case 'ucs2':
  38392. case 'ucs-2':
  38393. case 'utf16le':
  38394. case 'utf-16le':
  38395. return ucs2Write(this, string, offset, length)
  38396. default:
  38397. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  38398. encoding = ('' + encoding).toLowerCase()
  38399. loweredCase = true
  38400. }
  38401. }
  38402. }
  38403. Buffer.prototype.toJSON = function toJSON () {
  38404. return {
  38405. type: 'Buffer',
  38406. data: Array.prototype.slice.call(this._arr || this, 0)
  38407. }
  38408. }
  38409. function base64Slice (buf, start, end) {
  38410. if (start === 0 && end === buf.length) {
  38411. return base64.fromByteArray(buf)
  38412. } else {
  38413. return base64.fromByteArray(buf.slice(start, end))
  38414. }
  38415. }
  38416. function utf8Slice (buf, start, end) {
  38417. end = Math.min(buf.length, end)
  38418. var res = []
  38419. var i = start
  38420. while (i < end) {
  38421. var firstByte = buf[i]
  38422. var codePoint = null
  38423. var bytesPerSequence = (firstByte > 0xEF) ? 4
  38424. : (firstByte > 0xDF) ? 3
  38425. : (firstByte > 0xBF) ? 2
  38426. : 1
  38427. if (i + bytesPerSequence <= end) {
  38428. var secondByte, thirdByte, fourthByte, tempCodePoint
  38429. switch (bytesPerSequence) {
  38430. case 1:
  38431. if (firstByte < 0x80) {
  38432. codePoint = firstByte
  38433. }
  38434. break
  38435. case 2:
  38436. secondByte = buf[i + 1]
  38437. if ((secondByte & 0xC0) === 0x80) {
  38438. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  38439. if (tempCodePoint > 0x7F) {
  38440. codePoint = tempCodePoint
  38441. }
  38442. }
  38443. break
  38444. case 3:
  38445. secondByte = buf[i + 1]
  38446. thirdByte = buf[i + 2]
  38447. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  38448. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  38449. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  38450. codePoint = tempCodePoint
  38451. }
  38452. }
  38453. break
  38454. case 4:
  38455. secondByte = buf[i + 1]
  38456. thirdByte = buf[i + 2]
  38457. fourthByte = buf[i + 3]
  38458. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  38459. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  38460. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  38461. codePoint = tempCodePoint
  38462. }
  38463. }
  38464. }
  38465. }
  38466. if (codePoint === null) {
  38467. // we did not generate a valid codePoint so insert a
  38468. // replacement char (U+FFFD) and advance only 1 byte
  38469. codePoint = 0xFFFD
  38470. bytesPerSequence = 1
  38471. } else if (codePoint > 0xFFFF) {
  38472. // encode to utf16 (surrogate pair dance)
  38473. codePoint -= 0x10000
  38474. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  38475. codePoint = 0xDC00 | codePoint & 0x3FF
  38476. }
  38477. res.push(codePoint)
  38478. i += bytesPerSequence
  38479. }
  38480. return decodeCodePointsArray(res)
  38481. }
  38482. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  38483. // the lowest limit is Chrome, with 0x10000 args.
  38484. // We go 1 magnitude less, for safety
  38485. var MAX_ARGUMENTS_LENGTH = 0x1000
  38486. function decodeCodePointsArray (codePoints) {
  38487. var len = codePoints.length
  38488. if (len <= MAX_ARGUMENTS_LENGTH) {
  38489. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  38490. }
  38491. // Decode in chunks to avoid "call stack size exceeded".
  38492. var res = ''
  38493. var i = 0
  38494. while (i < len) {
  38495. res += String.fromCharCode.apply(
  38496. String,
  38497. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  38498. )
  38499. }
  38500. return res
  38501. }
  38502. function asciiSlice (buf, start, end) {
  38503. var ret = ''
  38504. end = Math.min(buf.length, end)
  38505. for (var i = start; i < end; ++i) {
  38506. ret += String.fromCharCode(buf[i] & 0x7F)
  38507. }
  38508. return ret
  38509. }
  38510. function latin1Slice (buf, start, end) {
  38511. var ret = ''
  38512. end = Math.min(buf.length, end)
  38513. for (var i = start; i < end; ++i) {
  38514. ret += String.fromCharCode(buf[i])
  38515. }
  38516. return ret
  38517. }
  38518. function hexSlice (buf, start, end) {
  38519. var len = buf.length
  38520. if (!start || start < 0) start = 0
  38521. if (!end || end < 0 || end > len) end = len
  38522. var out = ''
  38523. for (var i = start; i < end; ++i) {
  38524. out += toHex(buf[i])
  38525. }
  38526. return out
  38527. }
  38528. function utf16leSlice (buf, start, end) {
  38529. var bytes = buf.slice(start, end)
  38530. var res = ''
  38531. for (var i = 0; i < bytes.length; i += 2) {
  38532. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  38533. }
  38534. return res
  38535. }
  38536. Buffer.prototype.slice = function slice (start, end) {
  38537. var len = this.length
  38538. start = ~~start
  38539. end = end === undefined ? len : ~~end
  38540. if (start < 0) {
  38541. start += len
  38542. if (start < 0) start = 0
  38543. } else if (start > len) {
  38544. start = len
  38545. }
  38546. if (end < 0) {
  38547. end += len
  38548. if (end < 0) end = 0
  38549. } else if (end > len) {
  38550. end = len
  38551. }
  38552. if (end < start) end = start
  38553. var newBuf = this.subarray(start, end)
  38554. // Return an augmented `Uint8Array` instance
  38555. newBuf.__proto__ = Buffer.prototype
  38556. return newBuf
  38557. }
  38558. /*
  38559. * Need to make sure that buffer isn't trying to write out of bounds.
  38560. */
  38561. function checkOffset (offset, ext, length) {
  38562. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  38563. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  38564. }
  38565. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  38566. offset = offset >>> 0
  38567. byteLength = byteLength >>> 0
  38568. if (!noAssert) checkOffset(offset, byteLength, this.length)
  38569. var val = this[offset]
  38570. var mul = 1
  38571. var i = 0
  38572. while (++i < byteLength && (mul *= 0x100)) {
  38573. val += this[offset + i] * mul
  38574. }
  38575. return val
  38576. }
  38577. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  38578. offset = offset >>> 0
  38579. byteLength = byteLength >>> 0
  38580. if (!noAssert) {
  38581. checkOffset(offset, byteLength, this.length)
  38582. }
  38583. var val = this[offset + --byteLength]
  38584. var mul = 1
  38585. while (byteLength > 0 && (mul *= 0x100)) {
  38586. val += this[offset + --byteLength] * mul
  38587. }
  38588. return val
  38589. }
  38590. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  38591. offset = offset >>> 0
  38592. if (!noAssert) checkOffset(offset, 1, this.length)
  38593. return this[offset]
  38594. }
  38595. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  38596. offset = offset >>> 0
  38597. if (!noAssert) checkOffset(offset, 2, this.length)
  38598. return this[offset] | (this[offset + 1] << 8)
  38599. }
  38600. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  38601. offset = offset >>> 0
  38602. if (!noAssert) checkOffset(offset, 2, this.length)
  38603. return (this[offset] << 8) | this[offset + 1]
  38604. }
  38605. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  38606. offset = offset >>> 0
  38607. if (!noAssert) checkOffset(offset, 4, this.length)
  38608. return ((this[offset]) |
  38609. (this[offset + 1] << 8) |
  38610. (this[offset + 2] << 16)) +
  38611. (this[offset + 3] * 0x1000000)
  38612. }
  38613. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  38614. offset = offset >>> 0
  38615. if (!noAssert) checkOffset(offset, 4, this.length)
  38616. return (this[offset] * 0x1000000) +
  38617. ((this[offset + 1] << 16) |
  38618. (this[offset + 2] << 8) |
  38619. this[offset + 3])
  38620. }
  38621. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  38622. offset = offset >>> 0
  38623. byteLength = byteLength >>> 0
  38624. if (!noAssert) checkOffset(offset, byteLength, this.length)
  38625. var val = this[offset]
  38626. var mul = 1
  38627. var i = 0
  38628. while (++i < byteLength && (mul *= 0x100)) {
  38629. val += this[offset + i] * mul
  38630. }
  38631. mul *= 0x80
  38632. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  38633. return val
  38634. }
  38635. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  38636. offset = offset >>> 0
  38637. byteLength = byteLength >>> 0
  38638. if (!noAssert) checkOffset(offset, byteLength, this.length)
  38639. var i = byteLength
  38640. var mul = 1
  38641. var val = this[offset + --i]
  38642. while (i > 0 && (mul *= 0x100)) {
  38643. val += this[offset + --i] * mul
  38644. }
  38645. mul *= 0x80
  38646. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  38647. return val
  38648. }
  38649. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  38650. offset = offset >>> 0
  38651. if (!noAssert) checkOffset(offset, 1, this.length)
  38652. if (!(this[offset] & 0x80)) return (this[offset])
  38653. return ((0xff - this[offset] + 1) * -1)
  38654. }
  38655. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  38656. offset = offset >>> 0
  38657. if (!noAssert) checkOffset(offset, 2, this.length)
  38658. var val = this[offset] | (this[offset + 1] << 8)
  38659. return (val & 0x8000) ? val | 0xFFFF0000 : val
  38660. }
  38661. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  38662. offset = offset >>> 0
  38663. if (!noAssert) checkOffset(offset, 2, this.length)
  38664. var val = this[offset + 1] | (this[offset] << 8)
  38665. return (val & 0x8000) ? val | 0xFFFF0000 : val
  38666. }
  38667. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  38668. offset = offset >>> 0
  38669. if (!noAssert) checkOffset(offset, 4, this.length)
  38670. return (this[offset]) |
  38671. (this[offset + 1] << 8) |
  38672. (this[offset + 2] << 16) |
  38673. (this[offset + 3] << 24)
  38674. }
  38675. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  38676. offset = offset >>> 0
  38677. if (!noAssert) checkOffset(offset, 4, this.length)
  38678. return (this[offset] << 24) |
  38679. (this[offset + 1] << 16) |
  38680. (this[offset + 2] << 8) |
  38681. (this[offset + 3])
  38682. }
  38683. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  38684. offset = offset >>> 0
  38685. if (!noAssert) checkOffset(offset, 4, this.length)
  38686. return ieee754.read(this, offset, true, 23, 4)
  38687. }
  38688. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  38689. offset = offset >>> 0
  38690. if (!noAssert) checkOffset(offset, 4, this.length)
  38691. return ieee754.read(this, offset, false, 23, 4)
  38692. }
  38693. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  38694. offset = offset >>> 0
  38695. if (!noAssert) checkOffset(offset, 8, this.length)
  38696. return ieee754.read(this, offset, true, 52, 8)
  38697. }
  38698. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  38699. offset = offset >>> 0
  38700. if (!noAssert) checkOffset(offset, 8, this.length)
  38701. return ieee754.read(this, offset, false, 52, 8)
  38702. }
  38703. function checkInt (buf, value, offset, ext, max, min) {
  38704. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  38705. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  38706. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  38707. }
  38708. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  38709. value = +value
  38710. offset = offset >>> 0
  38711. byteLength = byteLength >>> 0
  38712. if (!noAssert) {
  38713. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  38714. checkInt(this, value, offset, byteLength, maxBytes, 0)
  38715. }
  38716. var mul = 1
  38717. var i = 0
  38718. this[offset] = value & 0xFF
  38719. while (++i < byteLength && (mul *= 0x100)) {
  38720. this[offset + i] = (value / mul) & 0xFF
  38721. }
  38722. return offset + byteLength
  38723. }
  38724. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  38725. value = +value
  38726. offset = offset >>> 0
  38727. byteLength = byteLength >>> 0
  38728. if (!noAssert) {
  38729. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  38730. checkInt(this, value, offset, byteLength, maxBytes, 0)
  38731. }
  38732. var i = byteLength - 1
  38733. var mul = 1
  38734. this[offset + i] = value & 0xFF
  38735. while (--i >= 0 && (mul *= 0x100)) {
  38736. this[offset + i] = (value / mul) & 0xFF
  38737. }
  38738. return offset + byteLength
  38739. }
  38740. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  38741. value = +value
  38742. offset = offset >>> 0
  38743. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  38744. this[offset] = (value & 0xff)
  38745. return offset + 1
  38746. }
  38747. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  38748. value = +value
  38749. offset = offset >>> 0
  38750. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  38751. this[offset] = (value & 0xff)
  38752. this[offset + 1] = (value >>> 8)
  38753. return offset + 2
  38754. }
  38755. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  38756. value = +value
  38757. offset = offset >>> 0
  38758. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  38759. this[offset] = (value >>> 8)
  38760. this[offset + 1] = (value & 0xff)
  38761. return offset + 2
  38762. }
  38763. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  38764. value = +value
  38765. offset = offset >>> 0
  38766. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  38767. this[offset + 3] = (value >>> 24)
  38768. this[offset + 2] = (value >>> 16)
  38769. this[offset + 1] = (value >>> 8)
  38770. this[offset] = (value & 0xff)
  38771. return offset + 4
  38772. }
  38773. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  38774. value = +value
  38775. offset = offset >>> 0
  38776. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  38777. this[offset] = (value >>> 24)
  38778. this[offset + 1] = (value >>> 16)
  38779. this[offset + 2] = (value >>> 8)
  38780. this[offset + 3] = (value & 0xff)
  38781. return offset + 4
  38782. }
  38783. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  38784. value = +value
  38785. offset = offset >>> 0
  38786. if (!noAssert) {
  38787. var limit = Math.pow(2, (8 * byteLength) - 1)
  38788. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  38789. }
  38790. var i = 0
  38791. var mul = 1
  38792. var sub = 0
  38793. this[offset] = value & 0xFF
  38794. while (++i < byteLength && (mul *= 0x100)) {
  38795. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  38796. sub = 1
  38797. }
  38798. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  38799. }
  38800. return offset + byteLength
  38801. }
  38802. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  38803. value = +value
  38804. offset = offset >>> 0
  38805. if (!noAssert) {
  38806. var limit = Math.pow(2, (8 * byteLength) - 1)
  38807. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  38808. }
  38809. var i = byteLength - 1
  38810. var mul = 1
  38811. var sub = 0
  38812. this[offset + i] = value & 0xFF
  38813. while (--i >= 0 && (mul *= 0x100)) {
  38814. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  38815. sub = 1
  38816. }
  38817. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  38818. }
  38819. return offset + byteLength
  38820. }
  38821. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  38822. value = +value
  38823. offset = offset >>> 0
  38824. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  38825. if (value < 0) value = 0xff + value + 1
  38826. this[offset] = (value & 0xff)
  38827. return offset + 1
  38828. }
  38829. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  38830. value = +value
  38831. offset = offset >>> 0
  38832. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  38833. this[offset] = (value & 0xff)
  38834. this[offset + 1] = (value >>> 8)
  38835. return offset + 2
  38836. }
  38837. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  38838. value = +value
  38839. offset = offset >>> 0
  38840. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  38841. this[offset] = (value >>> 8)
  38842. this[offset + 1] = (value & 0xff)
  38843. return offset + 2
  38844. }
  38845. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  38846. value = +value
  38847. offset = offset >>> 0
  38848. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  38849. this[offset] = (value & 0xff)
  38850. this[offset + 1] = (value >>> 8)
  38851. this[offset + 2] = (value >>> 16)
  38852. this[offset + 3] = (value >>> 24)
  38853. return offset + 4
  38854. }
  38855. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  38856. value = +value
  38857. offset = offset >>> 0
  38858. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  38859. if (value < 0) value = 0xffffffff + value + 1
  38860. this[offset] = (value >>> 24)
  38861. this[offset + 1] = (value >>> 16)
  38862. this[offset + 2] = (value >>> 8)
  38863. this[offset + 3] = (value & 0xff)
  38864. return offset + 4
  38865. }
  38866. function checkIEEE754 (buf, value, offset, ext, max, min) {
  38867. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  38868. if (offset < 0) throw new RangeError('Index out of range')
  38869. }
  38870. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  38871. value = +value
  38872. offset = offset >>> 0
  38873. if (!noAssert) {
  38874. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  38875. }
  38876. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  38877. return offset + 4
  38878. }
  38879. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  38880. return writeFloat(this, value, offset, true, noAssert)
  38881. }
  38882. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  38883. return writeFloat(this, value, offset, false, noAssert)
  38884. }
  38885. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  38886. value = +value
  38887. offset = offset >>> 0
  38888. if (!noAssert) {
  38889. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  38890. }
  38891. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  38892. return offset + 8
  38893. }
  38894. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  38895. return writeDouble(this, value, offset, true, noAssert)
  38896. }
  38897. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  38898. return writeDouble(this, value, offset, false, noAssert)
  38899. }
  38900. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  38901. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  38902. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  38903. if (!start) start = 0
  38904. if (!end && end !== 0) end = this.length
  38905. if (targetStart >= target.length) targetStart = target.length
  38906. if (!targetStart) targetStart = 0
  38907. if (end > 0 && end < start) end = start
  38908. // Copy 0 bytes; we're done
  38909. if (end === start) return 0
  38910. if (target.length === 0 || this.length === 0) return 0
  38911. // Fatal error conditions
  38912. if (targetStart < 0) {
  38913. throw new RangeError('targetStart out of bounds')
  38914. }
  38915. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  38916. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  38917. // Are we oob?
  38918. if (end > this.length) end = this.length
  38919. if (target.length - targetStart < end - start) {
  38920. end = target.length - targetStart + start
  38921. }
  38922. var len = end - start
  38923. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  38924. // Use built-in when available, missing from IE11
  38925. this.copyWithin(targetStart, start, end)
  38926. } else if (this === target && start < targetStart && targetStart < end) {
  38927. // descending copy from end
  38928. for (var i = len - 1; i >= 0; --i) {
  38929. target[i + targetStart] = this[i + start]
  38930. }
  38931. } else {
  38932. Uint8Array.prototype.set.call(
  38933. target,
  38934. this.subarray(start, end),
  38935. targetStart
  38936. )
  38937. }
  38938. return len
  38939. }
  38940. // Usage:
  38941. // buffer.fill(number[, offset[, end]])
  38942. // buffer.fill(buffer[, offset[, end]])
  38943. // buffer.fill(string[, offset[, end]][, encoding])
  38944. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  38945. // Handle string cases:
  38946. if (typeof val === 'string') {
  38947. if (typeof start === 'string') {
  38948. encoding = start
  38949. start = 0
  38950. end = this.length
  38951. } else if (typeof end === 'string') {
  38952. encoding = end
  38953. end = this.length
  38954. }
  38955. if (encoding !== undefined && typeof encoding !== 'string') {
  38956. throw new TypeError('encoding must be a string')
  38957. }
  38958. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  38959. throw new TypeError('Unknown encoding: ' + encoding)
  38960. }
  38961. if (val.length === 1) {
  38962. var code = val.charCodeAt(0)
  38963. if ((encoding === 'utf8' && code < 128) ||
  38964. encoding === 'latin1') {
  38965. // Fast path: If `val` fits into a single byte, use that numeric value.
  38966. val = code
  38967. }
  38968. }
  38969. } else if (typeof val === 'number') {
  38970. val = val & 255
  38971. }
  38972. // Invalid ranges are not set to a default, so can range check early.
  38973. if (start < 0 || this.length < start || this.length < end) {
  38974. throw new RangeError('Out of range index')
  38975. }
  38976. if (end <= start) {
  38977. return this
  38978. }
  38979. start = start >>> 0
  38980. end = end === undefined ? this.length : end >>> 0
  38981. if (!val) val = 0
  38982. var i
  38983. if (typeof val === 'number') {
  38984. for (i = start; i < end; ++i) {
  38985. this[i] = val
  38986. }
  38987. } else {
  38988. var bytes = Buffer.isBuffer(val)
  38989. ? val
  38990. : Buffer.from(val, encoding)
  38991. var len = bytes.length
  38992. if (len === 0) {
  38993. throw new TypeError('The value "' + val +
  38994. '" is invalid for argument "value"')
  38995. }
  38996. for (i = 0; i < end - start; ++i) {
  38997. this[i + start] = bytes[i % len]
  38998. }
  38999. }
  39000. return this
  39001. }
  39002. // HELPER FUNCTIONS
  39003. // ================
  39004. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  39005. function base64clean (str) {
  39006. // Node takes equal signs as end of the Base64 encoding
  39007. str = str.split('=')[0]
  39008. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  39009. str = str.trim().replace(INVALID_BASE64_RE, '')
  39010. // Node converts strings with length < 2 to ''
  39011. if (str.length < 2) return ''
  39012. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  39013. while (str.length % 4 !== 0) {
  39014. str = str + '='
  39015. }
  39016. return str
  39017. }
  39018. function toHex (n) {
  39019. if (n < 16) return '0' + n.toString(16)
  39020. return n.toString(16)
  39021. }
  39022. function utf8ToBytes (string, units) {
  39023. units = units || Infinity
  39024. var codePoint
  39025. var length = string.length
  39026. var leadSurrogate = null
  39027. var bytes = []
  39028. for (var i = 0; i < length; ++i) {
  39029. codePoint = string.charCodeAt(i)
  39030. // is surrogate component
  39031. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  39032. // last char was a lead
  39033. if (!leadSurrogate) {
  39034. // no lead yet
  39035. if (codePoint > 0xDBFF) {
  39036. // unexpected trail
  39037. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  39038. continue
  39039. } else if (i + 1 === length) {
  39040. // unpaired lead
  39041. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  39042. continue
  39043. }
  39044. // valid lead
  39045. leadSurrogate = codePoint
  39046. continue
  39047. }
  39048. // 2 leads in a row
  39049. if (codePoint < 0xDC00) {
  39050. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  39051. leadSurrogate = codePoint
  39052. continue
  39053. }
  39054. // valid surrogate pair
  39055. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  39056. } else if (leadSurrogate) {
  39057. // valid bmp char, but last char was a lead
  39058. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  39059. }
  39060. leadSurrogate = null
  39061. // encode utf8
  39062. if (codePoint < 0x80) {
  39063. if ((units -= 1) < 0) break
  39064. bytes.push(codePoint)
  39065. } else if (codePoint < 0x800) {
  39066. if ((units -= 2) < 0) break
  39067. bytes.push(
  39068. codePoint >> 0x6 | 0xC0,
  39069. codePoint & 0x3F | 0x80
  39070. )
  39071. } else if (codePoint < 0x10000) {
  39072. if ((units -= 3) < 0) break
  39073. bytes.push(
  39074. codePoint >> 0xC | 0xE0,
  39075. codePoint >> 0x6 & 0x3F | 0x80,
  39076. codePoint & 0x3F | 0x80
  39077. )
  39078. } else if (codePoint < 0x110000) {
  39079. if ((units -= 4) < 0) break
  39080. bytes.push(
  39081. codePoint >> 0x12 | 0xF0,
  39082. codePoint >> 0xC & 0x3F | 0x80,
  39083. codePoint >> 0x6 & 0x3F | 0x80,
  39084. codePoint & 0x3F | 0x80
  39085. )
  39086. } else {
  39087. throw new Error('Invalid code point')
  39088. }
  39089. }
  39090. return bytes
  39091. }
  39092. function asciiToBytes (str) {
  39093. var byteArray = []
  39094. for (var i = 0; i < str.length; ++i) {
  39095. // Node's code seems to be doing this and not & 0x7F..
  39096. byteArray.push(str.charCodeAt(i) & 0xFF)
  39097. }
  39098. return byteArray
  39099. }
  39100. function utf16leToBytes (str, units) {
  39101. var c, hi, lo
  39102. var byteArray = []
  39103. for (var i = 0; i < str.length; ++i) {
  39104. if ((units -= 2) < 0) break
  39105. c = str.charCodeAt(i)
  39106. hi = c >> 8
  39107. lo = c % 256
  39108. byteArray.push(lo)
  39109. byteArray.push(hi)
  39110. }
  39111. return byteArray
  39112. }
  39113. function base64ToBytes (str) {
  39114. return base64.toByteArray(base64clean(str))
  39115. }
  39116. function blitBuffer (src, dst, offset, length) {
  39117. for (var i = 0; i < length; ++i) {
  39118. if ((i + offset >= dst.length) || (i >= src.length)) break
  39119. dst[i + offset] = src[i]
  39120. }
  39121. return i
  39122. }
  39123. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  39124. // the `instanceof` check but they should be treated as of that type.
  39125. // See: https://github.com/feross/buffer/issues/166
  39126. function isInstance (obj, type) {
  39127. return obj instanceof type ||
  39128. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  39129. obj.constructor.name === type.name)
  39130. }
  39131. function numberIsNaN (obj) {
  39132. // For IE11 support
  39133. return obj !== obj // eslint-disable-line no-self-compare
  39134. }
  39135. }).call(this)}).call(this,require("buffer").Buffer)
  39136. },{"base64-js":140,"buffer":193,"ieee754":319}],194:[function(require,module,exports){
  39137. module.exports = {
  39138. "100": "Continue",
  39139. "101": "Switching Protocols",
  39140. "102": "Processing",
  39141. "200": "OK",
  39142. "201": "Created",
  39143. "202": "Accepted",
  39144. "203": "Non-Authoritative Information",
  39145. "204": "No Content",
  39146. "205": "Reset Content",
  39147. "206": "Partial Content",
  39148. "207": "Multi-Status",
  39149. "208": "Already Reported",
  39150. "226": "IM Used",
  39151. "300": "Multiple Choices",
  39152. "301": "Moved Permanently",
  39153. "302": "Found",
  39154. "303": "See Other",
  39155. "304": "Not Modified",
  39156. "305": "Use Proxy",
  39157. "307": "Temporary Redirect",
  39158. "308": "Permanent Redirect",
  39159. "400": "Bad Request",
  39160. "401": "Unauthorized",
  39161. "402": "Payment Required",
  39162. "403": "Forbidden",
  39163. "404": "Not Found",
  39164. "405": "Method Not Allowed",
  39165. "406": "Not Acceptable",
  39166. "407": "Proxy Authentication Required",
  39167. "408": "Request Timeout",
  39168. "409": "Conflict",
  39169. "410": "Gone",
  39170. "411": "Length Required",
  39171. "412": "Precondition Failed",
  39172. "413": "Payload Too Large",
  39173. "414": "URI Too Long",
  39174. "415": "Unsupported Media Type",
  39175. "416": "Range Not Satisfiable",
  39176. "417": "Expectation Failed",
  39177. "418": "I'm a teapot",
  39178. "421": "Misdirected Request",
  39179. "422": "Unprocessable Entity",
  39180. "423": "Locked",
  39181. "424": "Failed Dependency",
  39182. "425": "Unordered Collection",
  39183. "426": "Upgrade Required",
  39184. "428": "Precondition Required",
  39185. "429": "Too Many Requests",
  39186. "431": "Request Header Fields Too Large",
  39187. "451": "Unavailable For Legal Reasons",
  39188. "500": "Internal Server Error",
  39189. "501": "Not Implemented",
  39190. "502": "Bad Gateway",
  39191. "503": "Service Unavailable",
  39192. "504": "Gateway Timeout",
  39193. "505": "HTTP Version Not Supported",
  39194. "506": "Variant Also Negotiates",
  39195. "507": "Insufficient Storage",
  39196. "508": "Loop Detected",
  39197. "509": "Bandwidth Limit Exceeded",
  39198. "510": "Not Extended",
  39199. "511": "Network Authentication Required"
  39200. }
  39201. },{}],195:[function(require,module,exports){
  39202. 'use strict';
  39203. var GetIntrinsic = require('get-intrinsic');
  39204. var callBind = require('./');
  39205. var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
  39206. module.exports = function callBoundIntrinsic(name, allowMissing) {
  39207. var intrinsic = GetIntrinsic(name, !!allowMissing);
  39208. if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
  39209. return callBind(intrinsic);
  39210. }
  39211. return intrinsic;
  39212. };
  39213. },{"./":196,"get-intrinsic":258}],196:[function(require,module,exports){
  39214. 'use strict';
  39215. var bind = require('function-bind');
  39216. var GetIntrinsic = require('get-intrinsic');
  39217. var $apply = GetIntrinsic('%Function.prototype.apply%');
  39218. var $call = GetIntrinsic('%Function.prototype.call%');
  39219. var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
  39220. var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
  39221. if ($defineProperty) {
  39222. try {
  39223. $defineProperty({}, 'a', { value: 1 });
  39224. } catch (e) {
  39225. // IE 8 has a broken defineProperty
  39226. $defineProperty = null;
  39227. }
  39228. }
  39229. module.exports = function callBind() {
  39230. return $reflectApply(bind, $call, arguments);
  39231. };
  39232. var applyBind = function applyBind() {
  39233. return $reflectApply(bind, $apply, arguments);
  39234. };
  39235. if ($defineProperty) {
  39236. $defineProperty(module.exports, 'apply', { value: applyBind });
  39237. } else {
  39238. module.exports.apply = applyBind;
  39239. }
  39240. },{"function-bind":257,"get-intrinsic":258}],197:[function(require,module,exports){
  39241. function Caseless (dict) {
  39242. this.dict = dict || {}
  39243. }
  39244. Caseless.prototype.set = function (name, value, clobber) {
  39245. if (typeof name === 'object') {
  39246. for (var i in name) {
  39247. this.set(i, name[i], value)
  39248. }
  39249. } else {
  39250. if (typeof clobber === 'undefined') clobber = true
  39251. var has = this.has(name)
  39252. if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
  39253. else this.dict[has || name] = value
  39254. return has
  39255. }
  39256. }
  39257. Caseless.prototype.has = function (name) {
  39258. var keys = Object.keys(this.dict)
  39259. , name = name.toLowerCase()
  39260. ;
  39261. for (var i=0;i<keys.length;i++) {
  39262. if (keys[i].toLowerCase() === name) return keys[i]
  39263. }
  39264. return false
  39265. }
  39266. Caseless.prototype.get = function (name) {
  39267. name = name.toLowerCase()
  39268. var result, _key
  39269. var headers = this.dict
  39270. Object.keys(headers).forEach(function (key) {
  39271. _key = key.toLowerCase()
  39272. if (name === _key) result = headers[key]
  39273. })
  39274. return result
  39275. }
  39276. Caseless.prototype.swap = function (name) {
  39277. var has = this.has(name)
  39278. if (has === name) return
  39279. if (!has) throw new Error('There is no header than matches "'+name+'"')
  39280. this.dict[name] = this.dict[has]
  39281. delete this.dict[has]
  39282. }
  39283. Caseless.prototype.del = function (name) {
  39284. var has = this.has(name)
  39285. return delete this.dict[has || name]
  39286. }
  39287. module.exports = function (dict) {return new Caseless(dict)}
  39288. module.exports.httpify = function (resp, headers) {
  39289. var c = new Caseless(headers)
  39290. resp.setHeader = function (key, value, clobber) {
  39291. if (typeof value === 'undefined') return
  39292. return c.set(key, value, clobber)
  39293. }
  39294. resp.hasHeader = function (key) {
  39295. return c.has(key)
  39296. }
  39297. resp.getHeader = function (key) {
  39298. return c.get(key)
  39299. }
  39300. resp.removeHeader = function (key) {
  39301. return c.del(key)
  39302. }
  39303. resp.headers = c.dict
  39304. return c
  39305. }
  39306. },{}],198:[function(require,module,exports){
  39307. var Buffer = require('safe-buffer').Buffer
  39308. var Transform = require('stream').Transform
  39309. var StringDecoder = require('string_decoder').StringDecoder
  39310. var inherits = require('inherits')
  39311. function CipherBase (hashMode) {
  39312. Transform.call(this)
  39313. this.hashMode = typeof hashMode === 'string'
  39314. if (this.hashMode) {
  39315. this[hashMode] = this._finalOrDigest
  39316. } else {
  39317. this.final = this._finalOrDigest
  39318. }
  39319. if (this._final) {
  39320. this.__final = this._final
  39321. this._final = null
  39322. }
  39323. this._decoder = null
  39324. this._encoding = null
  39325. }
  39326. inherits(CipherBase, Transform)
  39327. CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
  39328. if (typeof data === 'string') {
  39329. data = Buffer.from(data, inputEnc)
  39330. }
  39331. var outData = this._update(data)
  39332. if (this.hashMode) return this
  39333. if (outputEnc) {
  39334. outData = this._toString(outData, outputEnc)
  39335. }
  39336. return outData
  39337. }
  39338. CipherBase.prototype.setAutoPadding = function () {}
  39339. CipherBase.prototype.getAuthTag = function () {
  39340. throw new Error('trying to get auth tag in unsupported state')
  39341. }
  39342. CipherBase.prototype.setAuthTag = function () {
  39343. throw new Error('trying to set auth tag in unsupported state')
  39344. }
  39345. CipherBase.prototype.setAAD = function () {
  39346. throw new Error('trying to set aad in unsupported state')
  39347. }
  39348. CipherBase.prototype._transform = function (data, _, next) {
  39349. var err
  39350. try {
  39351. if (this.hashMode) {
  39352. this._update(data)
  39353. } else {
  39354. this.push(this._update(data))
  39355. }
  39356. } catch (e) {
  39357. err = e
  39358. } finally {
  39359. next(err)
  39360. }
  39361. }
  39362. CipherBase.prototype._flush = function (done) {
  39363. var err
  39364. try {
  39365. this.push(this.__final())
  39366. } catch (e) {
  39367. err = e
  39368. }
  39369. done(err)
  39370. }
  39371. CipherBase.prototype._finalOrDigest = function (outputEnc) {
  39372. var outData = this.__final() || Buffer.alloc(0)
  39373. if (outputEnc) {
  39374. outData = this._toString(outData, outputEnc, true)
  39375. }
  39376. return outData
  39377. }
  39378. CipherBase.prototype._toString = function (value, enc, fin) {
  39379. if (!this._decoder) {
  39380. this._decoder = new StringDecoder(enc)
  39381. this._encoding = enc
  39382. }
  39383. if (this._encoding !== enc) throw new Error('can\'t switch encodings')
  39384. var out = this._decoder.write(value)
  39385. if (fin) {
  39386. out += this._decoder.end()
  39387. }
  39388. return out
  39389. }
  39390. module.exports = CipherBase
  39391. },{"inherits":320,"safe-buffer":561,"stream":597,"string_decoder":631}],199:[function(require,module,exports){
  39392. (function (Buffer){(function (){
  39393. var util = require('util');
  39394. var Stream = require('stream').Stream;
  39395. var DelayedStream = require('delayed-stream');
  39396. module.exports = CombinedStream;
  39397. function CombinedStream() {
  39398. this.writable = false;
  39399. this.readable = true;
  39400. this.dataSize = 0;
  39401. this.maxDataSize = 2 * 1024 * 1024;
  39402. this.pauseStreams = true;
  39403. this._released = false;
  39404. this._streams = [];
  39405. this._currentStream = null;
  39406. this._insideLoop = false;
  39407. this._pendingNext = false;
  39408. }
  39409. util.inherits(CombinedStream, Stream);
  39410. CombinedStream.create = function(options) {
  39411. var combinedStream = new this();
  39412. options = options || {};
  39413. for (var option in options) {
  39414. combinedStream[option] = options[option];
  39415. }
  39416. return combinedStream;
  39417. };
  39418. CombinedStream.isStreamLike = function(stream) {
  39419. return (typeof stream !== 'function')
  39420. && (typeof stream !== 'string')
  39421. && (typeof stream !== 'boolean')
  39422. && (typeof stream !== 'number')
  39423. && (!Buffer.isBuffer(stream));
  39424. };
  39425. CombinedStream.prototype.append = function(stream) {
  39426. var isStreamLike = CombinedStream.isStreamLike(stream);
  39427. if (isStreamLike) {
  39428. if (!(stream instanceof DelayedStream)) {
  39429. var newStream = DelayedStream.create(stream, {
  39430. maxDataSize: Infinity,
  39431. pauseStream: this.pauseStreams,
  39432. });
  39433. stream.on('data', this._checkDataSize.bind(this));
  39434. stream = newStream;
  39435. }
  39436. this._handleErrors(stream);
  39437. if (this.pauseStreams) {
  39438. stream.pause();
  39439. }
  39440. }
  39441. this._streams.push(stream);
  39442. return this;
  39443. };
  39444. CombinedStream.prototype.pipe = function(dest, options) {
  39445. Stream.prototype.pipe.call(this, dest, options);
  39446. this.resume();
  39447. return dest;
  39448. };
  39449. CombinedStream.prototype._getNext = function() {
  39450. this._currentStream = null;
  39451. if (this._insideLoop) {
  39452. this._pendingNext = true;
  39453. return; // defer call
  39454. }
  39455. this._insideLoop = true;
  39456. try {
  39457. do {
  39458. this._pendingNext = false;
  39459. this._realGetNext();
  39460. } while (this._pendingNext);
  39461. } finally {
  39462. this._insideLoop = false;
  39463. }
  39464. };
  39465. CombinedStream.prototype._realGetNext = function() {
  39466. var stream = this._streams.shift();
  39467. if (typeof stream == 'undefined') {
  39468. this.end();
  39469. return;
  39470. }
  39471. if (typeof stream !== 'function') {
  39472. this._pipeNext(stream);
  39473. return;
  39474. }
  39475. var getStream = stream;
  39476. getStream(function(stream) {
  39477. var isStreamLike = CombinedStream.isStreamLike(stream);
  39478. if (isStreamLike) {
  39479. stream.on('data', this._checkDataSize.bind(this));
  39480. this._handleErrors(stream);
  39481. }
  39482. this._pipeNext(stream);
  39483. }.bind(this));
  39484. };
  39485. CombinedStream.prototype._pipeNext = function(stream) {
  39486. this._currentStream = stream;
  39487. var isStreamLike = CombinedStream.isStreamLike(stream);
  39488. if (isStreamLike) {
  39489. stream.on('end', this._getNext.bind(this));
  39490. stream.pipe(this, {end: false});
  39491. return;
  39492. }
  39493. var value = stream;
  39494. this.write(value);
  39495. this._getNext();
  39496. };
  39497. CombinedStream.prototype._handleErrors = function(stream) {
  39498. var self = this;
  39499. stream.on('error', function(err) {
  39500. self._emitError(err);
  39501. });
  39502. };
  39503. CombinedStream.prototype.write = function(data) {
  39504. this.emit('data', data);
  39505. };
  39506. CombinedStream.prototype.pause = function() {
  39507. if (!this.pauseStreams) {
  39508. return;
  39509. }
  39510. if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
  39511. this.emit('pause');
  39512. };
  39513. CombinedStream.prototype.resume = function() {
  39514. if (!this._released) {
  39515. this._released = true;
  39516. this.writable = true;
  39517. this._getNext();
  39518. }
  39519. if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
  39520. this.emit('resume');
  39521. };
  39522. CombinedStream.prototype.end = function() {
  39523. this._reset();
  39524. this.emit('end');
  39525. };
  39526. CombinedStream.prototype.destroy = function() {
  39527. this._reset();
  39528. this.emit('close');
  39529. };
  39530. CombinedStream.prototype._reset = function() {
  39531. this.writable = false;
  39532. this._streams = [];
  39533. this._currentStream = null;
  39534. };
  39535. CombinedStream.prototype._checkDataSize = function() {
  39536. this._updateDataSize();
  39537. if (this.dataSize <= this.maxDataSize) {
  39538. return;
  39539. }
  39540. var message =
  39541. 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
  39542. this._emitError(new Error(message));
  39543. };
  39544. CombinedStream.prototype._updateDataSize = function() {
  39545. this.dataSize = 0;
  39546. var self = this;
  39547. this._streams.forEach(function(stream) {
  39548. if (!stream.dataSize) {
  39549. return;
  39550. }
  39551. self.dataSize += stream.dataSize;
  39552. });
  39553. if (this._currentStream && this._currentStream.dataSize) {
  39554. this.dataSize += this._currentStream.dataSize;
  39555. }
  39556. };
  39557. CombinedStream.prototype._emitError = function(err) {
  39558. this._reset();
  39559. this.emit('error', err);
  39560. };
  39561. }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  39562. },{"../../is-buffer/index.js":322,"delayed-stream":210,"stream":597,"util":658}],200:[function(require,module,exports){
  39563. module.exports={
  39564. "O_RDONLY": 0,
  39565. "O_WRONLY": 1,
  39566. "O_RDWR": 2,
  39567. "S_IFMT": 61440,
  39568. "S_IFREG": 32768,
  39569. "S_IFDIR": 16384,
  39570. "S_IFCHR": 8192,
  39571. "S_IFBLK": 24576,
  39572. "S_IFIFO": 4096,
  39573. "S_IFLNK": 40960,
  39574. "S_IFSOCK": 49152,
  39575. "O_CREAT": 512,
  39576. "O_EXCL": 2048,
  39577. "O_NOCTTY": 131072,
  39578. "O_TRUNC": 1024,
  39579. "O_APPEND": 8,
  39580. "O_DIRECTORY": 1048576,
  39581. "O_NOFOLLOW": 256,
  39582. "O_SYNC": 128,
  39583. "O_SYMLINK": 2097152,
  39584. "O_NONBLOCK": 4,
  39585. "S_IRWXU": 448,
  39586. "S_IRUSR": 256,
  39587. "S_IWUSR": 128,
  39588. "S_IXUSR": 64,
  39589. "S_IRWXG": 56,
  39590. "S_IRGRP": 32,
  39591. "S_IWGRP": 16,
  39592. "S_IXGRP": 8,
  39593. "S_IRWXO": 7,
  39594. "S_IROTH": 4,
  39595. "S_IWOTH": 2,
  39596. "S_IXOTH": 1,
  39597. "E2BIG": 7,
  39598. "EACCES": 13,
  39599. "EADDRINUSE": 48,
  39600. "EADDRNOTAVAIL": 49,
  39601. "EAFNOSUPPORT": 47,
  39602. "EAGAIN": 35,
  39603. "EALREADY": 37,
  39604. "EBADF": 9,
  39605. "EBADMSG": 94,
  39606. "EBUSY": 16,
  39607. "ECANCELED": 89,
  39608. "ECHILD": 10,
  39609. "ECONNABORTED": 53,
  39610. "ECONNREFUSED": 61,
  39611. "ECONNRESET": 54,
  39612. "EDEADLK": 11,
  39613. "EDESTADDRREQ": 39,
  39614. "EDOM": 33,
  39615. "EDQUOT": 69,
  39616. "EEXIST": 17,
  39617. "EFAULT": 14,
  39618. "EFBIG": 27,
  39619. "EHOSTUNREACH": 65,
  39620. "EIDRM": 90,
  39621. "EILSEQ": 92,
  39622. "EINPROGRESS": 36,
  39623. "EINTR": 4,
  39624. "EINVAL": 22,
  39625. "EIO": 5,
  39626. "EISCONN": 56,
  39627. "EISDIR": 21,
  39628. "ELOOP": 62,
  39629. "EMFILE": 24,
  39630. "EMLINK": 31,
  39631. "EMSGSIZE": 40,
  39632. "EMULTIHOP": 95,
  39633. "ENAMETOOLONG": 63,
  39634. "ENETDOWN": 50,
  39635. "ENETRESET": 52,
  39636. "ENETUNREACH": 51,
  39637. "ENFILE": 23,
  39638. "ENOBUFS": 55,
  39639. "ENODATA": 96,
  39640. "ENODEV": 19,
  39641. "ENOENT": 2,
  39642. "ENOEXEC": 8,
  39643. "ENOLCK": 77,
  39644. "ENOLINK": 97,
  39645. "ENOMEM": 12,
  39646. "ENOMSG": 91,
  39647. "ENOPROTOOPT": 42,
  39648. "ENOSPC": 28,
  39649. "ENOSR": 98,
  39650. "ENOSTR": 99,
  39651. "ENOSYS": 78,
  39652. "ENOTCONN": 57,
  39653. "ENOTDIR": 20,
  39654. "ENOTEMPTY": 66,
  39655. "ENOTSOCK": 38,
  39656. "ENOTSUP": 45,
  39657. "ENOTTY": 25,
  39658. "ENXIO": 6,
  39659. "EOPNOTSUPP": 102,
  39660. "EOVERFLOW": 84,
  39661. "EPERM": 1,
  39662. "EPIPE": 32,
  39663. "EPROTO": 100,
  39664. "EPROTONOSUPPORT": 43,
  39665. "EPROTOTYPE": 41,
  39666. "ERANGE": 34,
  39667. "EROFS": 30,
  39668. "ESPIPE": 29,
  39669. "ESRCH": 3,
  39670. "ESTALE": 70,
  39671. "ETIME": 101,
  39672. "ETIMEDOUT": 60,
  39673. "ETXTBSY": 26,
  39674. "EWOULDBLOCK": 35,
  39675. "EXDEV": 18,
  39676. "SIGHUP": 1,
  39677. "SIGINT": 2,
  39678. "SIGQUIT": 3,
  39679. "SIGILL": 4,
  39680. "SIGTRAP": 5,
  39681. "SIGABRT": 6,
  39682. "SIGIOT": 6,
  39683. "SIGBUS": 10,
  39684. "SIGFPE": 8,
  39685. "SIGKILL": 9,
  39686. "SIGUSR1": 30,
  39687. "SIGSEGV": 11,
  39688. "SIGUSR2": 31,
  39689. "SIGPIPE": 13,
  39690. "SIGALRM": 14,
  39691. "SIGTERM": 15,
  39692. "SIGCHLD": 20,
  39693. "SIGCONT": 19,
  39694. "SIGSTOP": 17,
  39695. "SIGTSTP": 18,
  39696. "SIGTTIN": 21,
  39697. "SIGTTOU": 22,
  39698. "SIGURG": 16,
  39699. "SIGXCPU": 24,
  39700. "SIGXFSZ": 25,
  39701. "SIGVTALRM": 26,
  39702. "SIGPROF": 27,
  39703. "SIGWINCH": 28,
  39704. "SIGIO": 23,
  39705. "SIGSYS": 12,
  39706. "SSL_OP_ALL": 2147486719,
  39707. "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION": 262144,
  39708. "SSL_OP_CIPHER_SERVER_PREFERENCE": 4194304,
  39709. "SSL_OP_CISCO_ANYCONNECT": 32768,
  39710. "SSL_OP_COOKIE_EXCHANGE": 8192,
  39711. "SSL_OP_CRYPTOPRO_TLSEXT_BUG": 2147483648,
  39712. "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS": 2048,
  39713. "SSL_OP_EPHEMERAL_RSA": 0,
  39714. "SSL_OP_LEGACY_SERVER_CONNECT": 4,
  39715. "SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER": 32,
  39716. "SSL_OP_MICROSOFT_SESS_ID_BUG": 1,
  39717. "SSL_OP_MSIE_SSLV2_RSA_PADDING": 0,
  39718. "SSL_OP_NETSCAPE_CA_DN_BUG": 536870912,
  39719. "SSL_OP_NETSCAPE_CHALLENGE_BUG": 2,
  39720. "SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG": 1073741824,
  39721. "SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG": 8,
  39722. "SSL_OP_NO_COMPRESSION": 131072,
  39723. "SSL_OP_NO_QUERY_MTU": 4096,
  39724. "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION": 65536,
  39725. "SSL_OP_NO_SSLv2": 16777216,
  39726. "SSL_OP_NO_SSLv3": 33554432,
  39727. "SSL_OP_NO_TICKET": 16384,
  39728. "SSL_OP_NO_TLSv1": 67108864,
  39729. "SSL_OP_NO_TLSv1_1": 268435456,
  39730. "SSL_OP_NO_TLSv1_2": 134217728,
  39731. "SSL_OP_PKCS1_CHECK_1": 0,
  39732. "SSL_OP_PKCS1_CHECK_2": 0,
  39733. "SSL_OP_SINGLE_DH_USE": 1048576,
  39734. "SSL_OP_SINGLE_ECDH_USE": 524288,
  39735. "SSL_OP_SSLEAY_080_CLIENT_DH_BUG": 128,
  39736. "SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG": 0,
  39737. "SSL_OP_TLS_BLOCK_PADDING_BUG": 512,
  39738. "SSL_OP_TLS_D5_BUG": 256,
  39739. "SSL_OP_TLS_ROLLBACK_BUG": 8388608,
  39740. "ENGINE_METHOD_DSA": 2,
  39741. "ENGINE_METHOD_DH": 4,
  39742. "ENGINE_METHOD_RAND": 8,
  39743. "ENGINE_METHOD_ECDH": 16,
  39744. "ENGINE_METHOD_ECDSA": 32,
  39745. "ENGINE_METHOD_CIPHERS": 64,
  39746. "ENGINE_METHOD_DIGESTS": 128,
  39747. "ENGINE_METHOD_STORE": 256,
  39748. "ENGINE_METHOD_PKEY_METHS": 512,
  39749. "ENGINE_METHOD_PKEY_ASN1_METHS": 1024,
  39750. "ENGINE_METHOD_ALL": 65535,
  39751. "ENGINE_METHOD_NONE": 0,
  39752. "DH_CHECK_P_NOT_SAFE_PRIME": 2,
  39753. "DH_CHECK_P_NOT_PRIME": 1,
  39754. "DH_UNABLE_TO_CHECK_GENERATOR": 4,
  39755. "DH_NOT_SUITABLE_GENERATOR": 8,
  39756. "NPN_ENABLED": 1,
  39757. "RSA_PKCS1_PADDING": 1,
  39758. "RSA_SSLV23_PADDING": 2,
  39759. "RSA_NO_PADDING": 3,
  39760. "RSA_PKCS1_OAEP_PADDING": 4,
  39761. "RSA_X931_PADDING": 5,
  39762. "RSA_PKCS1_PSS_PADDING": 6,
  39763. "POINT_CONVERSION_COMPRESSED": 2,
  39764. "POINT_CONVERSION_UNCOMPRESSED": 4,
  39765. "POINT_CONVERSION_HYBRID": 6,
  39766. "F_OK": 0,
  39767. "R_OK": 4,
  39768. "W_OK": 2,
  39769. "X_OK": 1,
  39770. "UV_UDP_REUSEADDR": 4
  39771. }
  39772. },{}],201:[function(require,module,exports){
  39773. (function (Buffer){(function (){
  39774. // Copyright Joyent, Inc. and other Node contributors.
  39775. //
  39776. // Permission is hereby granted, free of charge, to any person obtaining a
  39777. // copy of this software and associated documentation files (the
  39778. // "Software"), to deal in the Software without restriction, including
  39779. // without limitation the rights to use, copy, modify, merge, publish,
  39780. // distribute, sublicense, and/or sell copies of the Software, and to permit
  39781. // persons to whom the Software is furnished to do so, subject to the
  39782. // following conditions:
  39783. //
  39784. // The above copyright notice and this permission notice shall be included
  39785. // in all copies or substantial portions of the Software.
  39786. //
  39787. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  39788. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  39789. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  39790. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  39791. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  39792. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  39793. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  39794. // NOTE: These type checking functions intentionally don't use `instanceof`
  39795. // because it is fragile and can be easily faked with `Object.create()`.
  39796. function isArray(arg) {
  39797. if (Array.isArray) {
  39798. return Array.isArray(arg);
  39799. }
  39800. return objectToString(arg) === '[object Array]';
  39801. }
  39802. exports.isArray = isArray;
  39803. function isBoolean(arg) {
  39804. return typeof arg === 'boolean';
  39805. }
  39806. exports.isBoolean = isBoolean;
  39807. function isNull(arg) {
  39808. return arg === null;
  39809. }
  39810. exports.isNull = isNull;
  39811. function isNullOrUndefined(arg) {
  39812. return arg == null;
  39813. }
  39814. exports.isNullOrUndefined = isNullOrUndefined;
  39815. function isNumber(arg) {
  39816. return typeof arg === 'number';
  39817. }
  39818. exports.isNumber = isNumber;
  39819. function isString(arg) {
  39820. return typeof arg === 'string';
  39821. }
  39822. exports.isString = isString;
  39823. function isSymbol(arg) {
  39824. return typeof arg === 'symbol';
  39825. }
  39826. exports.isSymbol = isSymbol;
  39827. function isUndefined(arg) {
  39828. return arg === void 0;
  39829. }
  39830. exports.isUndefined = isUndefined;
  39831. function isRegExp(re) {
  39832. return objectToString(re) === '[object RegExp]';
  39833. }
  39834. exports.isRegExp = isRegExp;
  39835. function isObject(arg) {
  39836. return typeof arg === 'object' && arg !== null;
  39837. }
  39838. exports.isObject = isObject;
  39839. function isDate(d) {
  39840. return objectToString(d) === '[object Date]';
  39841. }
  39842. exports.isDate = isDate;
  39843. function isError(e) {
  39844. return (objectToString(e) === '[object Error]' || e instanceof Error);
  39845. }
  39846. exports.isError = isError;
  39847. function isFunction(arg) {
  39848. return typeof arg === 'function';
  39849. }
  39850. exports.isFunction = isFunction;
  39851. function isPrimitive(arg) {
  39852. return arg === null ||
  39853. typeof arg === 'boolean' ||
  39854. typeof arg === 'number' ||
  39855. typeof arg === 'string' ||
  39856. typeof arg === 'symbol' || // ES6 symbol
  39857. typeof arg === 'undefined';
  39858. }
  39859. exports.isPrimitive = isPrimitive;
  39860. exports.isBuffer = Buffer.isBuffer;
  39861. function objectToString(o) {
  39862. return Object.prototype.toString.call(o);
  39863. }
  39864. }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  39865. },{"../../is-buffer/index.js":322}],202:[function(require,module,exports){
  39866. (function (Buffer){(function (){
  39867. var elliptic = require('elliptic')
  39868. var BN = require('bn.js')
  39869. module.exports = function createECDH (curve) {
  39870. return new ECDH(curve)
  39871. }
  39872. var aliases = {
  39873. secp256k1: {
  39874. name: 'secp256k1',
  39875. byteLength: 32
  39876. },
  39877. secp224r1: {
  39878. name: 'p224',
  39879. byteLength: 28
  39880. },
  39881. prime256v1: {
  39882. name: 'p256',
  39883. byteLength: 32
  39884. },
  39885. prime192v1: {
  39886. name: 'p192',
  39887. byteLength: 24
  39888. },
  39889. ed25519: {
  39890. name: 'ed25519',
  39891. byteLength: 32
  39892. },
  39893. secp384r1: {
  39894. name: 'p384',
  39895. byteLength: 48
  39896. },
  39897. secp521r1: {
  39898. name: 'p521',
  39899. byteLength: 66
  39900. }
  39901. }
  39902. aliases.p224 = aliases.secp224r1
  39903. aliases.p256 = aliases.secp256r1 = aliases.prime256v1
  39904. aliases.p192 = aliases.secp192r1 = aliases.prime192v1
  39905. aliases.p384 = aliases.secp384r1
  39906. aliases.p521 = aliases.secp521r1
  39907. function ECDH (curve) {
  39908. this.curveType = aliases[curve]
  39909. if (!this.curveType) {
  39910. this.curveType = {
  39911. name: curve
  39912. }
  39913. }
  39914. this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
  39915. this.keys = void 0
  39916. }
  39917. ECDH.prototype.generateKeys = function (enc, format) {
  39918. this.keys = this.curve.genKeyPair()
  39919. return this.getPublicKey(enc, format)
  39920. }
  39921. ECDH.prototype.computeSecret = function (other, inenc, enc) {
  39922. inenc = inenc || 'utf8'
  39923. if (!Buffer.isBuffer(other)) {
  39924. other = new Buffer(other, inenc)
  39925. }
  39926. var otherPub = this.curve.keyFromPublic(other).getPublic()
  39927. var out = otherPub.mul(this.keys.getPrivate()).getX()
  39928. return formatReturnValue(out, enc, this.curveType.byteLength)
  39929. }
  39930. ECDH.prototype.getPublicKey = function (enc, format) {
  39931. var key = this.keys.getPublic(format === 'compressed', true)
  39932. if (format === 'hybrid') {
  39933. if (key[key.length - 1] % 2) {
  39934. key[0] = 7
  39935. } else {
  39936. key[0] = 6
  39937. }
  39938. }
  39939. return formatReturnValue(key, enc)
  39940. }
  39941. ECDH.prototype.getPrivateKey = function (enc) {
  39942. return formatReturnValue(this.keys.getPrivate(), enc)
  39943. }
  39944. ECDH.prototype.setPublicKey = function (pub, enc) {
  39945. enc = enc || 'utf8'
  39946. if (!Buffer.isBuffer(pub)) {
  39947. pub = new Buffer(pub, enc)
  39948. }
  39949. this.keys._importPublic(pub)
  39950. return this
  39951. }
  39952. ECDH.prototype.setPrivateKey = function (priv, enc) {
  39953. enc = enc || 'utf8'
  39954. if (!Buffer.isBuffer(priv)) {
  39955. priv = new Buffer(priv, enc)
  39956. }
  39957. var _priv = new BN(priv)
  39958. _priv = _priv.toString(16)
  39959. this.keys = this.curve.genKeyPair()
  39960. this.keys._importPrivate(_priv)
  39961. return this
  39962. }
  39963. function formatReturnValue (bn, enc, len) {
  39964. if (!Array.isArray(bn)) {
  39965. bn = bn.toArray()
  39966. }
  39967. var buf = new Buffer(bn)
  39968. if (len && buf.length < len) {
  39969. var zeros = new Buffer(len - buf.length)
  39970. zeros.fill(0)
  39971. buf = Buffer.concat([zeros, buf])
  39972. }
  39973. if (!enc) {
  39974. return buf
  39975. } else {
  39976. return buf.toString(enc)
  39977. }
  39978. }
  39979. }).call(this)}).call(this,require("buffer").Buffer)
  39980. },{"bn.js":203,"buffer":193,"elliptic":228}],203:[function(require,module,exports){
  39981. arguments[4][97][0].apply(exports,arguments)
  39982. },{"buffer":144,"dup":97}],204:[function(require,module,exports){
  39983. 'use strict'
  39984. var inherits = require('inherits')
  39985. var MD5 = require('md5.js')
  39986. var RIPEMD160 = require('ripemd160')
  39987. var sha = require('sha.js')
  39988. var Base = require('cipher-base')
  39989. function Hash (hash) {
  39990. Base.call(this, 'digest')
  39991. this._hash = hash
  39992. }
  39993. inherits(Hash, Base)
  39994. Hash.prototype._update = function (data) {
  39995. this._hash.update(data)
  39996. }
  39997. Hash.prototype._final = function () {
  39998. return this._hash.digest()
  39999. }
  40000. module.exports = function createHash (alg) {
  40001. alg = alg.toLowerCase()
  40002. if (alg === 'md5') return new MD5()
  40003. if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()
  40004. return new Hash(sha(alg))
  40005. }
  40006. },{"cipher-base":198,"inherits":320,"md5.js":339,"ripemd160":560,"sha.js":565}],205:[function(require,module,exports){
  40007. var MD5 = require('md5.js')
  40008. module.exports = function (buffer) {
  40009. return new MD5().update(buffer).digest()
  40010. }
  40011. },{"md5.js":339}],206:[function(require,module,exports){
  40012. 'use strict'
  40013. var inherits = require('inherits')
  40014. var Legacy = require('./legacy')
  40015. var Base = require('cipher-base')
  40016. var Buffer = require('safe-buffer').Buffer
  40017. var md5 = require('create-hash/md5')
  40018. var RIPEMD160 = require('ripemd160')
  40019. var sha = require('sha.js')
  40020. var ZEROS = Buffer.alloc(128)
  40021. function Hmac (alg, key) {
  40022. Base.call(this, 'digest')
  40023. if (typeof key === 'string') {
  40024. key = Buffer.from(key)
  40025. }
  40026. var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
  40027. this._alg = alg
  40028. this._key = key
  40029. if (key.length > blocksize) {
  40030. var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
  40031. key = hash.update(key).digest()
  40032. } else if (key.length < blocksize) {
  40033. key = Buffer.concat([key, ZEROS], blocksize)
  40034. }
  40035. var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  40036. var opad = this._opad = Buffer.allocUnsafe(blocksize)
  40037. for (var i = 0; i < blocksize; i++) {
  40038. ipad[i] = key[i] ^ 0x36
  40039. opad[i] = key[i] ^ 0x5C
  40040. }
  40041. this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
  40042. this._hash.update(ipad)
  40043. }
  40044. inherits(Hmac, Base)
  40045. Hmac.prototype._update = function (data) {
  40046. this._hash.update(data)
  40047. }
  40048. Hmac.prototype._final = function () {
  40049. var h = this._hash.digest()
  40050. var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
  40051. return hash.update(this._opad).update(h).digest()
  40052. }
  40053. module.exports = function createHmac (alg, key) {
  40054. alg = alg.toLowerCase()
  40055. if (alg === 'rmd160' || alg === 'ripemd160') {
  40056. return new Hmac('rmd160', key)
  40057. }
  40058. if (alg === 'md5') {
  40059. return new Legacy(md5, key)
  40060. }
  40061. return new Hmac(alg, key)
  40062. }
  40063. },{"./legacy":207,"cipher-base":198,"create-hash/md5":205,"inherits":320,"ripemd160":560,"safe-buffer":561,"sha.js":565}],207:[function(require,module,exports){
  40064. 'use strict'
  40065. var inherits = require('inherits')
  40066. var Buffer = require('safe-buffer').Buffer
  40067. var Base = require('cipher-base')
  40068. var ZEROS = Buffer.alloc(128)
  40069. var blocksize = 64
  40070. function Hmac (alg, key) {
  40071. Base.call(this, 'digest')
  40072. if (typeof key === 'string') {
  40073. key = Buffer.from(key)
  40074. }
  40075. this._alg = alg
  40076. this._key = key
  40077. if (key.length > blocksize) {
  40078. key = alg(key)
  40079. } else if (key.length < blocksize) {
  40080. key = Buffer.concat([key, ZEROS], blocksize)
  40081. }
  40082. var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
  40083. var opad = this._opad = Buffer.allocUnsafe(blocksize)
  40084. for (var i = 0; i < blocksize; i++) {
  40085. ipad[i] = key[i] ^ 0x36
  40086. opad[i] = key[i] ^ 0x5C
  40087. }
  40088. this._hash = [ipad]
  40089. }
  40090. inherits(Hmac, Base)
  40091. Hmac.prototype._update = function (data) {
  40092. this._hash.push(data)
  40093. }
  40094. Hmac.prototype._final = function () {
  40095. var h = this._alg(Buffer.concat(this._hash))
  40096. return this._alg(Buffer.concat([this._opad, h]))
  40097. }
  40098. module.exports = Hmac
  40099. },{"cipher-base":198,"inherits":320,"safe-buffer":561}],208:[function(require,module,exports){
  40100. 'use strict'
  40101. exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
  40102. exports.createHash = exports.Hash = require('create-hash')
  40103. exports.createHmac = exports.Hmac = require('create-hmac')
  40104. var algos = require('browserify-sign/algos')
  40105. var algoKeys = Object.keys(algos)
  40106. var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
  40107. exports.getHashes = function () {
  40108. return hashes
  40109. }
  40110. var p = require('pbkdf2')
  40111. exports.pbkdf2 = p.pbkdf2
  40112. exports.pbkdf2Sync = p.pbkdf2Sync
  40113. var aes = require('browserify-cipher')
  40114. exports.Cipher = aes.Cipher
  40115. exports.createCipher = aes.createCipher
  40116. exports.Cipheriv = aes.Cipheriv
  40117. exports.createCipheriv = aes.createCipheriv
  40118. exports.Decipher = aes.Decipher
  40119. exports.createDecipher = aes.createDecipher
  40120. exports.Decipheriv = aes.Decipheriv
  40121. exports.createDecipheriv = aes.createDecipheriv
  40122. exports.getCiphers = aes.getCiphers
  40123. exports.listCiphers = aes.listCiphers
  40124. var dh = require('diffie-hellman')
  40125. exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
  40126. exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
  40127. exports.getDiffieHellman = dh.getDiffieHellman
  40128. exports.createDiffieHellman = dh.createDiffieHellman
  40129. exports.DiffieHellman = dh.DiffieHellman
  40130. var sign = require('browserify-sign')
  40131. exports.createSign = sign.createSign
  40132. exports.Sign = sign.Sign
  40133. exports.createVerify = sign.createVerify
  40134. exports.Verify = sign.Verify
  40135. exports.createECDH = require('create-ecdh')
  40136. var publicEncrypt = require('public-encrypt')
  40137. exports.publicEncrypt = publicEncrypt.publicEncrypt
  40138. exports.privateEncrypt = publicEncrypt.privateEncrypt
  40139. exports.publicDecrypt = publicEncrypt.publicDecrypt
  40140. exports.privateDecrypt = publicEncrypt.privateDecrypt
  40141. // the least I can do is make error messages for the rest of the node.js/crypto api.
  40142. // ;[
  40143. // 'createCredentials'
  40144. // ].forEach(function (name) {
  40145. // exports[name] = function () {
  40146. // throw new Error([
  40147. // 'sorry, ' + name + ' is not implemented yet',
  40148. // 'we accept pull requests',
  40149. // 'https://github.com/crypto-browserify/crypto-browserify'
  40150. // ].join('\n'))
  40151. // }
  40152. // })
  40153. var rf = require('randomfill')
  40154. exports.randomFill = rf.randomFill
  40155. exports.randomFillSync = rf.randomFillSync
  40156. exports.createCredentials = function () {
  40157. throw new Error([
  40158. 'sorry, createCredentials is not implemented yet',
  40159. 'we accept pull requests',
  40160. 'https://github.com/crypto-browserify/crypto-browserify'
  40161. ].join('\n'))
  40162. }
  40163. exports.constants = {
  40164. 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
  40165. 'DH_CHECK_P_NOT_PRIME': 1,
  40166. 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
  40167. 'DH_NOT_SUITABLE_GENERATOR': 8,
  40168. 'NPN_ENABLED': 1,
  40169. 'ALPN_ENABLED': 1,
  40170. 'RSA_PKCS1_PADDING': 1,
  40171. 'RSA_SSLV23_PADDING': 2,
  40172. 'RSA_NO_PADDING': 3,
  40173. 'RSA_PKCS1_OAEP_PADDING': 4,
  40174. 'RSA_X931_PADDING': 5,
  40175. 'RSA_PKCS1_PSS_PADDING': 6,
  40176. 'POINT_CONVERSION_COMPRESSED': 2,
  40177. 'POINT_CONVERSION_UNCOMPRESSED': 4,
  40178. 'POINT_CONVERSION_HYBRID': 6
  40179. }
  40180. },{"browserify-cipher":162,"browserify-sign":169,"browserify-sign/algos":166,"create-ecdh":202,"create-hash":204,"create-hmac":206,"diffie-hellman":218,"pbkdf2":518,"public-encrypt":528,"randombytes":544,"randomfill":545}],209:[function(require,module,exports){
  40181. /*
  40182. © 2011 by Jerry Sievert
  40183. Permission is hereby granted, free of charge, to any person obtaining a copy
  40184. of this software and associated documentation files (the "Software"), to deal
  40185. in the Software without restriction, including without limitation the rights
  40186. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40187. copies of the Software, and to permit persons to whom the Software is
  40188. furnished to do so, subject to the following conditions:
  40189. The above copyright notice and this permission notice shall be included in
  40190. all copies or substantial portions of the Software.
  40191. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40192. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40193. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40194. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40195. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40196. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40197. THE SOFTWARE.
  40198. */
  40199. (function () {
  40200. /** @class Date */
  40201. // constants
  40202. var monthsAbbr = [], monthsFull = [], daysAbbr = [], daysFull = [], dayNames = {}, monthsAll, daysAll = [], monthNames = [];
  40203. monthsAbbr = [
  40204. 'Jan',
  40205. 'Feb',
  40206. 'Mar',
  40207. 'Apr',
  40208. 'May',
  40209. 'Jun',
  40210. 'Jul',
  40211. 'Aug',
  40212. 'Sep',
  40213. 'Oct',
  40214. 'Nov',
  40215. 'Dec'
  40216. ];
  40217. monthsFull = [
  40218. 'January',
  40219. 'February',
  40220. 'March',
  40221. 'April',
  40222. 'May',
  40223. 'June',
  40224. 'July',
  40225. 'August',
  40226. 'September',
  40227. 'October',
  40228. 'November',
  40229. 'December'
  40230. ];
  40231. daysAbbr = [
  40232. 'Sun',
  40233. 'Mon',
  40234. 'Tue',
  40235. 'Wed',
  40236. 'Thu',
  40237. 'Fri',
  40238. 'Sat'
  40239. ];
  40240. daysFull = [
  40241. 'Sunday',
  40242. 'Monday',
  40243. 'Tuesday',
  40244. 'Wednesday',
  40245. 'Thursday',
  40246. 'Friday',
  40247. 'Saturday'
  40248. ];
  40249. dayNames = {
  40250. 'su': 0,
  40251. 'sun': 0,
  40252. 'sunday': 0,
  40253. 'mo': 1,
  40254. 'mon': 1,
  40255. 'monday': 1,
  40256. 'tu': 2,
  40257. 'tue': 2,
  40258. 'tuesday': 2,
  40259. 'we': 3,
  40260. 'wed': 3,
  40261. 'wednesday': 3,
  40262. 'th': 4,
  40263. 'thu': 4,
  40264. 'thursday': 4,
  40265. 'fr': 5,
  40266. 'fri': 5,
  40267. 'friday': 5,
  40268. 'sa': 6,
  40269. 'sat': 6,
  40270. 'saturday': 6
  40271. };
  40272. monthsAll = monthsFull.concat(monthsAbbr);
  40273. daysAll = [
  40274. 'su',
  40275. 'sun',
  40276. 'sunday',
  40277. 'mo',
  40278. 'mon',
  40279. 'monday',
  40280. 'tu',
  40281. 'tue',
  40282. 'tuesday',
  40283. 'we',
  40284. 'wed',
  40285. 'wednesday',
  40286. 'th',
  40287. 'thu',
  40288. 'thursday',
  40289. 'fr',
  40290. 'fri',
  40291. 'friday',
  40292. 'sa',
  40293. 'sat',
  40294. 'saturday'
  40295. ];
  40296. monthNames = {
  40297. 'jan': 0,
  40298. 'january': 0,
  40299. 'feb': 1,
  40300. 'february': 1,
  40301. 'mar': 2,
  40302. 'march': 2,
  40303. 'apr': 3,
  40304. 'april': 3,
  40305. 'may': 4,
  40306. 'jun': 5,
  40307. 'june': 5,
  40308. 'jul': 6,
  40309. 'july': 6,
  40310. 'aug': 7,
  40311. 'august': 7,
  40312. 'sep': 8,
  40313. 'september': 8,
  40314. 'oct': 9,
  40315. 'october': 9,
  40316. 'nov': 10,
  40317. 'november': 10,
  40318. 'dec': 11,
  40319. 'december': 11
  40320. };
  40321. var daysInMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
  40322. // private helper functions
  40323. /** @ignore */
  40324. function pad(str, length) {
  40325. str = String(str);
  40326. while (str.length < length) {
  40327. str = '0' + str;
  40328. }
  40329. return str;
  40330. }
  40331. var isInteger = function (str) {
  40332. if (str.match(/^(\d+)$/)) {
  40333. return true;
  40334. }
  40335. return false;
  40336. };
  40337. var getInt = function (str, i, minlength, maxlength) {
  40338. for (var x = maxlength; x >= minlength; x--) {
  40339. var token = str.substring(i, i + x);
  40340. if (token.length < minlength) {
  40341. return null;
  40342. }
  40343. if (isInteger(token)) {
  40344. return token;
  40345. }
  40346. }
  40347. return null;
  40348. };
  40349. // static class methods
  40350. var origParse = Date.parse;
  40351. // ------------------------------------------------------------------
  40352. // getDateFromFormat( date_string , format_string )
  40353. //
  40354. // This function takes a date string and a format string. It matches
  40355. // If the date string matches the format string, it returns the
  40356. // getTime() of the date. If it does not match, it returns NaN.
  40357. // Original Author: Matt Kruse <matt@mattkruse.com>
  40358. // WWW: http://www.mattkruse.com/
  40359. // Adapted from: http://www.mattkruse.com/javascript/date/source.html
  40360. // ------------------------------------------------------------------
  40361. var getDateFromFormat = function (val, format) {
  40362. val = val + "";
  40363. format = format + "";
  40364. var iVal = 0;
  40365. var iFormat = 0;
  40366. var c = "";
  40367. var token = "";
  40368. var token2 = "";
  40369. var x, y;
  40370. var now = new Date();
  40371. var year = now.getYear();
  40372. var month = now.getMonth() + 1;
  40373. var date = 1;
  40374. var hh = 0;
  40375. var mm = 0;
  40376. var ss = 0;
  40377. var ampm = "";
  40378. while (iFormat < format.length) {
  40379. // Get next token from format string
  40380. c = format.charAt(iFormat);
  40381. token = "";
  40382. while ((format.charAt(iFormat) === c) && (iFormat < format.length)) {
  40383. token += format.charAt(iFormat++);
  40384. }
  40385. // Extract contents of value based on format token
  40386. if (token === "yyyy" || token === "yy" || token === "y") {
  40387. if (token === "yyyy") {
  40388. x = 4;
  40389. y = 4;
  40390. }
  40391. if (token === "yy") {
  40392. x = 2;
  40393. y = 2;
  40394. }
  40395. if (token === "y") {
  40396. x = 2;
  40397. y = 4;
  40398. }
  40399. year = getInt(val, iVal, x, y);
  40400. if (year === null) {
  40401. return NaN;
  40402. }
  40403. iVal += year.length;
  40404. if (year.length === 2) {
  40405. if (year > 70) {
  40406. year = 1900 + (year - 0);
  40407. } else {
  40408. year = 2000 + (year - 0);
  40409. }
  40410. }
  40411. } else if (token === "MMM" || token === "NNN") {
  40412. month = 0;
  40413. for (var i = 0; i < monthsAll.length; i++) {
  40414. var monthName = monthsAll[i];
  40415. if (val.substring(iVal, iVal + monthName.length).toLowerCase() === monthName.toLowerCase()) {
  40416. if (token === "MMM" || (token === "NNN" && i > 11)) {
  40417. month = i + 1;
  40418. if (month > 12) {
  40419. month -= 12;
  40420. }
  40421. iVal += monthName.length;
  40422. break;
  40423. }
  40424. }
  40425. }
  40426. if ((month < 1) || (month > 12)) {
  40427. return NaN;
  40428. }
  40429. } else if (token === "EE" || token === "E") {
  40430. for (var n = 0; n < daysAll.length; n++) {
  40431. var dayName = daysAll[n];
  40432. if (val.substring(iVal, iVal + dayName.length).toLowerCase() === dayName.toLowerCase()) {
  40433. iVal += dayName.length;
  40434. break;
  40435. }
  40436. }
  40437. } else if (token === "MM" || token === "M") {
  40438. month = getInt(val, iVal, token.length, 2);
  40439. if (month === null || (month < 1) || (month > 12)) {
  40440. return NaN;
  40441. }
  40442. iVal += month.length;
  40443. } else if (token === "dd" || token === "d") {
  40444. date = getInt(val, iVal, token.length, 2);
  40445. if (date === null || (date < 1) || (date > 31)) {
  40446. return NaN;
  40447. }
  40448. iVal += date.length;
  40449. } else if (token === "hh" || token === "h") {
  40450. hh = getInt(val, iVal, token.length, 2);
  40451. if (hh === null || (hh < 1) || (hh > 12)) {
  40452. return NaN;
  40453. }
  40454. iVal += hh.length;
  40455. } else if (token === "HH" || token === "H") {
  40456. hh = getInt(val, iVal, token.length, 2);
  40457. if (hh === null || (hh < 0) || (hh > 23)) {
  40458. return NaN;
  40459. }
  40460. iVal += hh.length;
  40461. } else if (token === "KK" || token === "K") {
  40462. hh = getInt(val, iVal, token.length, 2);
  40463. if (hh === null || (hh < 0) || (hh > 11)) {
  40464. return NaN;
  40465. }
  40466. iVal += hh.length;
  40467. } else if (token === "kk" || token === "k") {
  40468. hh = getInt(val, iVal, token.length, 2);
  40469. if (hh === null || (hh < 1) || (hh > 24)) {
  40470. return NaN;
  40471. }
  40472. iVal += hh.length;
  40473. hh--;
  40474. } else if (token === "mm" || token === "m") {
  40475. mm = getInt(val, iVal, token.length, 2);
  40476. if (mm === null || (mm < 0) || (mm > 59)) {
  40477. return NaN;
  40478. }
  40479. iVal += mm.length;
  40480. } else if (token === "ss" || token === "s") {
  40481. ss = getInt(val, iVal, token.length, 2);
  40482. if (ss === null || (ss < 0) || (ss > 59)) {
  40483. return NaN;
  40484. }
  40485. iVal += ss.length;
  40486. } else if (token === "a") {
  40487. if (val.substring(iVal, iVal + 2).toLowerCase() === "am") {
  40488. ampm = "AM";
  40489. } else if (val.substring(iVal, iVal + 2).toLowerCase() === "pm") {
  40490. ampm = "PM";
  40491. } else {
  40492. return NaN;
  40493. }
  40494. iVal += 2;
  40495. } else {
  40496. if (val.substring(iVal, iVal + token.length) !== token) {
  40497. return NaN;
  40498. } else {
  40499. iVal += token.length;
  40500. }
  40501. }
  40502. }
  40503. // If there are any trailing characters left in the value, it doesn't match
  40504. if (iVal !== val.length) {
  40505. return NaN;
  40506. }
  40507. // Is date valid for month?
  40508. if (month === 2) {
  40509. // Check for leap year
  40510. if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) { // leap year
  40511. if (date > 29) {
  40512. return NaN;
  40513. }
  40514. } else {
  40515. if (date > 28) {
  40516. return NaN;
  40517. }
  40518. }
  40519. }
  40520. if ((month === 4) || (month === 6) || (month === 9) || (month === 11)) {
  40521. if (date > 30) {
  40522. return NaN;
  40523. }
  40524. }
  40525. // Correct hours value
  40526. if (hh < 12 && ampm === "PM") {
  40527. hh = hh - 0 + 12;
  40528. } else if (hh > 11 && ampm === "AM") {
  40529. hh -= 12;
  40530. }
  40531. var newdate = new Date(year, month - 1, date, hh, mm, ss);
  40532. return newdate.getTime();
  40533. };
  40534. /** @ignore */
  40535. Date.parse = function (date, format) {
  40536. if (format) {
  40537. return getDateFromFormat(date, format);
  40538. }
  40539. var timestamp = origParse(date), minutesOffset = 0, match;
  40540. if (isNaN(timestamp) && (match = /^(\d{4}|[+\-]\d{6})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?))?/.exec(date))) {
  40541. if (match[8] !== 'Z') {
  40542. minutesOffset = +match[10] * 60 + (+match[11]);
  40543. if (match[9] === '+') {
  40544. minutesOffset = 0 - minutesOffset;
  40545. }
  40546. }
  40547. match[7] = match[7] || '000';
  40548. timestamp = Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5] + minutesOffset, +match[6], +match[7].substr(0, 3));
  40549. }
  40550. return timestamp;
  40551. };
  40552. function polyfill(name, func) {
  40553. if (Date.prototype[name] === undefined) {
  40554. Date.prototype[name] = func;
  40555. }
  40556. }
  40557. /**
  40558. Returns new instance of Date object with the date set to today and
  40559. the time set to midnight
  40560. @static
  40561. @returns {Date} Today's Date
  40562. @function today
  40563. @memberof Date
  40564. */
  40565. Date.today = function () {
  40566. return new Date().clearTime();
  40567. };
  40568. /**
  40569. Returns new instance of Date object with the date set to today and
  40570. the time set to midnight in UTC
  40571. @static
  40572. @returns {Date} Today's Date in UTC
  40573. @function UTCtoday
  40574. @memberof Date
  40575. */
  40576. Date.UTCtoday = function () {
  40577. return new Date().clearUTCTime();
  40578. };
  40579. /**
  40580. Returns new instance of Date object with the date set to tomorrow and
  40581. the time set to midnight
  40582. @static
  40583. @returns {Date} Tomorrow's Date
  40584. @function tomorrow
  40585. @memberof Date
  40586. */
  40587. Date.tomorrow = function () {
  40588. return Date.today().add({days: 1});
  40589. };
  40590. /**
  40591. Returns new instance of Date object with the date set to tomorrow and
  40592. the time set to midnight in UTC
  40593. @static
  40594. @returns {Date} Tomorrow's Date in UTC
  40595. @function UTCtomorrow
  40596. @memberof Date
  40597. */
  40598. Date.UTCtomorrow = function () {
  40599. return Date.UTCtoday().add({days: 1});
  40600. };
  40601. /**
  40602. Returns new instance of Date object with the date set to yesterday and
  40603. the time set to midnight
  40604. @static
  40605. @returns {Date} Yesterday's Date
  40606. @function yesterday
  40607. @memberof Date
  40608. */
  40609. Date.yesterday = function () {
  40610. return Date.today().add({days: -1});
  40611. };
  40612. /**
  40613. Returns new instance of Date object with the date set to yesterday and
  40614. the time set to midnight in UTC
  40615. @static
  40616. @returns {Date} Yesterday's Date in UTC
  40617. @function UTCyesterday
  40618. @memberof Date
  40619. */
  40620. Date.UTCyesterday = function () {
  40621. return Date.UTCtoday().add({days: -1});
  40622. };
  40623. /**
  40624. Returns whether the day is valid
  40625. @static
  40626. @param day {Number} day of the month
  40627. @param year {Number} year
  40628. @param month {Number} month of the year [0-11]
  40629. @returns {Boolean}
  40630. @function validateDay
  40631. @memberof Date
  40632. */
  40633. Date.validateDay = function (day, year, month) {
  40634. var date = new Date(year, month, day);
  40635. return (date.getFullYear() === year &&
  40636. date.getMonth() === month &&
  40637. date.getDate() === day);
  40638. };
  40639. /**
  40640. Returns whether the year is valid
  40641. @static
  40642. @param year {Number} year
  40643. @returns {Boolean}
  40644. @function validateYear
  40645. @memberof Date
  40646. */
  40647. Date.validateYear = function (year) {
  40648. return (year >= 0 && year <= 9999);
  40649. };
  40650. /**
  40651. Returns whether the second is valid
  40652. @static
  40653. @param second {Number} second
  40654. @returns {Boolean}
  40655. @function validateSecond
  40656. @memberof Date
  40657. */
  40658. Date.validateSecond = function (second) {
  40659. return (second >= 0 && second < 60);
  40660. };
  40661. /**
  40662. Returns whether the month is valid [0-11]
  40663. @static
  40664. @param month {Number} month
  40665. @returns {Boolean}
  40666. @function validateMonth
  40667. @memberof Date
  40668. */
  40669. Date.validateMonth = function (month) {
  40670. return (month >= 0 && month < 12);
  40671. };
  40672. /**
  40673. Returns whether the minute is valid
  40674. @static
  40675. @param minute {Number} minute
  40676. @returns {Boolean}
  40677. @function validateMinute
  40678. @memberof Date
  40679. */
  40680. Date.validateMinute = function (minute) {
  40681. return (minute >= 0 && minute < 60);
  40682. };
  40683. /**
  40684. Returns whether the millisecond is valid
  40685. @static
  40686. @param millisecond {Number} millisecond
  40687. @returns {Boolean}
  40688. @function validateMillisecond
  40689. @memberof Date
  40690. */
  40691. Date.validateMillisecond = function (milli) {
  40692. return (milli >= 0 && milli < 1000);
  40693. };
  40694. /**
  40695. Returns whether the hour is valid [0-23]
  40696. @static
  40697. @param hour {Number} hour
  40698. @returns {Boolean}
  40699. @function validateHour
  40700. @memberof Date
  40701. */
  40702. Date.validateHour = function (hour) {
  40703. return (hour >= 0 && hour < 24);
  40704. };
  40705. /**
  40706. Compares two dates
  40707. @static
  40708. @param date1 {Date} first date
  40709. @param date2 {Date} second date
  40710. @returns {Number} -1 if date1 is less than date2, 0 if they are equal, 1 if date1 is more than date2
  40711. @function compare
  40712. @memberof Date
  40713. */
  40714. Date.compare = function (date1, date2) {
  40715. if (date1.valueOf() < date2.valueOf()) {
  40716. return -1;
  40717. } else if (date1.valueOf() > date2.valueOf()) {
  40718. return 1;
  40719. }
  40720. return 0;
  40721. };
  40722. /**
  40723. Compares two dates to the millisecond
  40724. @static
  40725. @param date1 {Date} first date
  40726. @param date2 {Date} second date
  40727. @returns {Boolean}
  40728. @function equals
  40729. @memberof Date
  40730. */
  40731. Date.equals = function (date1, date2) {
  40732. return date1.valueOf() === date2.valueOf();
  40733. };
  40734. /**
  40735. Compares two dates by day
  40736. @static
  40737. @param date1 {Date} first date
  40738. @param date2 {Date} second date
  40739. @returns {Boolean}
  40740. @function equalsDay
  40741. @memberof Date
  40742. */
  40743. Date.equalsDay = function (date1, date2) {
  40744. return date1.toYMD() === date2.toYMD();
  40745. };
  40746. /**
  40747. Returns the day number for a day [0-6]
  40748. @static
  40749. @param day {String} day name
  40750. @returns {Number}
  40751. @function getDayNumberFromName
  40752. @memberof Date
  40753. */
  40754. Date.getDayNumberFromName = function (name) {
  40755. return dayNames[name.toLowerCase()];
  40756. };
  40757. /**
  40758. Returns the day number for a month [0-11]
  40759. @static
  40760. @param month {String} month name
  40761. @returns {Number}
  40762. @function getMonthNumberFromName
  40763. @memberof Date
  40764. */
  40765. Date.getMonthNumberFromName = function (name) {
  40766. return monthNames[name.toLowerCase()];
  40767. };
  40768. /**
  40769. Returns the month name for a month [0-11]
  40770. @static
  40771. @param month {Number} month
  40772. @returns {String}
  40773. @function getMonthNameFromNumber
  40774. @memberof Date
  40775. */
  40776. Date.getMonthNameFromNumber = function (number) {
  40777. return monthsFull[number];
  40778. };
  40779. /**
  40780. Returns the month name abbreviated for a month [0-11]
  40781. @static
  40782. @param month {Number} month
  40783. @returns {String}
  40784. @function getMonthAbbrFromNumber
  40785. @memberof Date
  40786. */
  40787. Date.getMonthAbbrFromNumber = function (number) {
  40788. return monthsAbbr[number];
  40789. };
  40790. /**
  40791. Returns whether or not the year is a leap year
  40792. @static
  40793. @param year {Number} year
  40794. @returns {Boolean}
  40795. @function isLeapYear
  40796. @memberof Date
  40797. */
  40798. Date.isLeapYear = function (year) {
  40799. return (new Date(year, 1, 29).getDate() === 29);
  40800. };
  40801. /**
  40802. Returns the number of days in a month
  40803. @static
  40804. @param year {Number} year
  40805. @param month {Number} month
  40806. @returns {Number}
  40807. @function getDaysInMonth
  40808. @memberof Date
  40809. */
  40810. Date.getDaysInMonth = function (year, month) {
  40811. if (month === 1) {
  40812. return Date.isLeapYear(year) ? 29 : 28;
  40813. }
  40814. return daysInMonth[month];
  40815. };
  40816. /**
  40817. Returns the abbreviated month name
  40818. @returns {String}
  40819. @function getMonthAbbr
  40820. @instance
  40821. @memberof Date
  40822. */
  40823. polyfill('getMonthAbbr', function () {
  40824. return monthsAbbr[this.getMonth()];
  40825. });
  40826. /**
  40827. Returns the month name
  40828. @returns {String}
  40829. @function getMonthName
  40830. @instance
  40831. @memberof Date
  40832. */
  40833. polyfill('getMonthName', function () {
  40834. return monthsFull[this.getMonth()];
  40835. });
  40836. /**
  40837. Returns the name of last month
  40838. @returns {String}
  40839. @function getLastMonthName
  40840. @instance
  40841. @memberof Date
  40842. */
  40843. polyfill('getLastMonthName', function () {
  40844. var i = this.getMonth();
  40845. i = (i === 0 ? 11 : i - 1);
  40846. return monthsFull[i];
  40847. });
  40848. /**
  40849. Returns the current UTC office
  40850. @returns {String}
  40851. @function getUTCOffset
  40852. @instance
  40853. @memberof Date
  40854. */
  40855. polyfill('getUTCOffset', function () {
  40856. var tz = pad(Math.abs(this.getTimezoneOffset() / 0.6), 4);
  40857. if (this.getTimezoneOffset() > 0) {
  40858. tz = '-' + tz;
  40859. }
  40860. return tz;
  40861. });
  40862. /**
  40863. Returns a padded Common Log Format
  40864. @returns {String}
  40865. @function toCLFString
  40866. @deprecated Will be deprecated in version 2.0 in favor of toFormat
  40867. @instance
  40868. @memberof Date
  40869. */
  40870. polyfill('toCLFString', function () {
  40871. return pad(this.getDate(), 2) + '/' + this.getMonthAbbr() + '/' +
  40872. this.getFullYear() + ':' + pad(this.getHours(), 2) + ':' +
  40873. pad(this.getMinutes(), 2) + ':' + pad(this.getSeconds(), 2) +
  40874. ' ' + this.getUTCOffset();
  40875. });
  40876. /**
  40877. Returns a padded Year/Month/Day
  40878. @returns {String}
  40879. @param separator {String} optional, defaults to "-"
  40880. @function toYMD
  40881. @deprecated Will be deprecated in version 2.0 in favor of toFormat
  40882. @instance
  40883. @memberof Date
  40884. */
  40885. polyfill('toYMD', function (separator) {
  40886. separator = typeof separator === 'undefined' ? '-' : separator;
  40887. return this.getFullYear() + separator + pad(this.getMonth() + 1, 2) +
  40888. separator + pad(this.getDate(), 2);
  40889. });
  40890. /**
  40891. Returns a formatted String for database insertion
  40892. @returns {String}
  40893. @function toDBString
  40894. @deprecated Will be deprecated in version 2.0 in favor of toFormat
  40895. @instance
  40896. @memberof Date
  40897. */
  40898. polyfill('toDBString', function () {
  40899. return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1, 2) +
  40900. '-' + pad(this.getUTCDate(), 2) + ' ' + pad(this.getUTCHours(), 2) +
  40901. ':' + pad(this.getUTCMinutes(), 2) + ':' + pad(this.getUTCSeconds(), 2);
  40902. });
  40903. /**
  40904. Sets the time to 00:00:00.0000 and returns a new Date object
  40905. @returns {Date}
  40906. @function clearTime
  40907. @instance
  40908. @memberof Date
  40909. */
  40910. polyfill('clearTime', function () {
  40911. this.setHours(0);
  40912. this.setMinutes(0);
  40913. this.setSeconds(0);
  40914. this.setMilliseconds(0);
  40915. return this;
  40916. });
  40917. /**
  40918. Sets the time to 00:00:00.0000 and returns a new Date object with set to UTC
  40919. @returns {Date}
  40920. @function clearUTCTime
  40921. @instance
  40922. @memberof Date
  40923. */
  40924. polyfill('clearUTCTime', function () {
  40925. this.setUTCHours(0);
  40926. this.setUTCMinutes(0);
  40927. this.setUTCSeconds(0);
  40928. this.setUTCMilliseconds(0);
  40929. return this;
  40930. });
  40931. /**
  40932. Adds `milliseconds`, `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, and `years` and returns a new Date.
  40933. Usage: `data.add({ "seconds": 10, "days": 1 })`
  40934. @param additions {Object}
  40935. @returns {Date}
  40936. @function add
  40937. @instance
  40938. @memberof Date
  40939. */
  40940. polyfill('add', function (obj) {
  40941. if (obj.milliseconds !== undefined) {
  40942. this.setMilliseconds(this.getMilliseconds() + obj.milliseconds);
  40943. }
  40944. if (obj.seconds !== undefined) {
  40945. this.setSeconds(this.getSeconds() + obj.seconds);
  40946. }
  40947. if (obj.minutes !== undefined) {
  40948. this.setMinutes(this.getMinutes() + obj.minutes);
  40949. }
  40950. if (obj.hours !== undefined) {
  40951. this.setHours(this.getHours() + obj.hours);
  40952. }
  40953. if (obj.days !== undefined) {
  40954. this.setDate(this.getDate() + obj.days);
  40955. }
  40956. if (obj.weeks !== undefined) {
  40957. this.setDate(this.getDate() + (obj.weeks * 7));
  40958. }
  40959. if (obj.months !== undefined) {
  40960. this.setMonth(this.getMonth() + obj.months);
  40961. }
  40962. if (obj.years !== undefined) {
  40963. this.setFullYear(this.getFullYear() + obj.years);
  40964. }
  40965. return this;
  40966. });
  40967. /**
  40968. Adds milliseconds to the Date and returns it
  40969. @returns {Date}
  40970. @param milliseconds {Number} Number of milliseconds to add
  40971. @function addMilliseconds
  40972. @deprecated Will be deprecated in version 2.0 in favor of add
  40973. @instance
  40974. @memberof Date
  40975. */
  40976. polyfill('addMilliseconds', function (milliseconds) {
  40977. return this.add({ milliseconds: milliseconds });
  40978. });
  40979. /**
  40980. Adds seconds to the Date and returns it
  40981. @returns {Date}
  40982. @param seconds {Number} Number of seconds to add
  40983. @function addSeconds
  40984. @deprecated Will be deprecated in version 2.0 in favor of add
  40985. @instance
  40986. @memberof Date
  40987. */
  40988. polyfill('addSeconds', function (seconds) {
  40989. return this.add({ seconds: seconds });
  40990. });
  40991. /**
  40992. Adds minutes to the Date and returns it
  40993. @returns {Date}
  40994. @param minutes {Number} Number of minutes to add
  40995. @function addMinutes
  40996. @deprecated Will be deprecated in version 2.0 in favor of add
  40997. @instance
  40998. @memberof Date
  40999. */
  41000. polyfill('addMinutes', function (minutes) {
  41001. return this.add({ minutes: minutes });
  41002. });
  41003. /**
  41004. Adds hours to the Date and returns it
  41005. @returns {Date}
  41006. @param hours {Number} Number of hours to add
  41007. @function addHours
  41008. @deprecated Will be deprecated in version 2.0 in favor of add
  41009. @instance
  41010. @memberof Date
  41011. */
  41012. polyfill('addHours', function (hours) {
  41013. return this.add({ hours: hours });
  41014. });
  41015. /**
  41016. Adds days to the Date and returns it
  41017. @returns {Date}
  41018. @param days {Number} Number of days to add
  41019. @function addSeconds
  41020. @deprecated Will be deprecated in version 2.0 in favor of add
  41021. @instance
  41022. @memberof Date
  41023. */
  41024. polyfill('addDays', function (days) {
  41025. return this.add({ days: days });
  41026. });
  41027. /**
  41028. Adds weeks to the Date and returns it
  41029. @returns {Date}
  41030. @param weeks {Number} Number of weeks to add
  41031. @function addWeeks
  41032. @deprecated Will be deprecated in version 2.0 in favor of add
  41033. @instance
  41034. @memberof Date
  41035. */
  41036. polyfill('addWeeks', function (weeks) {
  41037. return this.add({ days: (weeks * 7) });
  41038. });
  41039. /**
  41040. Adds months to the Date and returns it
  41041. @returns {Date}
  41042. @param months {Number} Number of months to add
  41043. @function addMonths
  41044. @deprecated Will be deprecated in version 2.0 in favor of add
  41045. @instance
  41046. @memberof Date
  41047. */
  41048. polyfill('addMonths', function (months) {
  41049. return this.add({ months: months });
  41050. });
  41051. /**
  41052. Adds years to the Date and returns it
  41053. @returns {Date}
  41054. @param years {Number} Number of years to add
  41055. @function addYears
  41056. @deprecated Will be deprecated in version 2.0 in favor of add
  41057. @instance
  41058. @memberof Date
  41059. */
  41060. polyfill('addYears', function (years) {
  41061. return this.add({ years: years });
  41062. });
  41063. /**
  41064. Removes `milliseconds`, `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, and `years` and returns a new Date.
  41065. Usage: `data.remove({ "seconds": 10, "days": 1 })`
  41066. @param removals {Object}
  41067. @returns {Date}
  41068. @function remove
  41069. @instance
  41070. @memberof Date
  41071. */
  41072. polyfill('remove', function (obj) {
  41073. if (obj.seconds !== undefined) {
  41074. this.setSeconds(this.getSeconds() - obj.seconds);
  41075. }
  41076. if (obj.minutes !== undefined) {
  41077. this.setMinutes(this.getMinutes() - obj.minutes);
  41078. }
  41079. if (obj.hours !== undefined) {
  41080. this.setHours(this.getHours() - obj.hours);
  41081. }
  41082. if (obj.days !== undefined) {
  41083. this.setDate(this.getDate() - obj.days);
  41084. }
  41085. if (obj.weeks !== undefined) {
  41086. this.setDate(this.getDate() - (obj.weeks * 7));
  41087. }
  41088. if (obj.months !== undefined) {
  41089. this.setMonth(this.getMonth() - obj.months);
  41090. }
  41091. if (obj.years !== undefined) {
  41092. this.setFullYear(this.getFullYear() - obj.years);
  41093. }
  41094. return this;
  41095. });
  41096. /**
  41097. Removes milliseconds from the Date and returns it
  41098. @returns {Date}
  41099. @param milliseconds {Number} Number of millseconds to remove
  41100. @function removeMilliseconds
  41101. @deprecated Will be deprecated in version 2.0 in favor of remove
  41102. @instance
  41103. @memberof Date
  41104. */
  41105. polyfill('removeMilliseconds', function (milliseconds) {
  41106. throw new Error('Not implemented');
  41107. });
  41108. /**
  41109. Removes seconds from the Date and returns it
  41110. @returns {Date}
  41111. @param seconds {Number} Number of seconds to remove
  41112. @function removeSeconds
  41113. @deprecated Will be deprecated in version 2.0 in favor of remove
  41114. @instance
  41115. @memberof Date
  41116. */
  41117. polyfill('removeSeconds', function (seconds) {
  41118. return this.remove({ seconds: seconds });
  41119. });
  41120. /**
  41121. Removes minutes from the Date and returns it
  41122. @returns {Date}
  41123. @param seconds {Number} Number of minutes to remove
  41124. @function removeMinutes
  41125. @deprecated Will be deprecated in version 2.0 in favor of remove
  41126. @instance
  41127. @memberof Date
  41128. */
  41129. polyfill('removeMinutes', function (minutes) {
  41130. return this.remove({ minutes: minutes });
  41131. });
  41132. /**
  41133. Removes hours from the Date and returns it
  41134. @returns {Date}
  41135. @param hours {Number} Number of hours to remove
  41136. @function removeHours
  41137. @deprecated Will be deprecated in version 2.0 in favor of remove
  41138. @instance
  41139. @memberof Date
  41140. */
  41141. polyfill('removeHours', function (hours) {
  41142. return this.remove({ hours: hours });
  41143. });
  41144. /**
  41145. Removes days from the Date and returns it
  41146. @returns {Date}
  41147. @param days {Number} Number of days to remove
  41148. @function removeDays
  41149. @deprecated Will be deprecated in version 2.0 in favor of remove
  41150. @instance
  41151. @memberof Date
  41152. */
  41153. polyfill('removeDays', function (days) {
  41154. return this.remove({ days: days });
  41155. });
  41156. /**
  41157. Removes weeks from the Date and returns it
  41158. @returns {Date}
  41159. @param weeks {Number} Number of weeks to remove
  41160. @function removeWeeks
  41161. @deprecated Will be deprecated in version 2.0 in favor of remove
  41162. @instance
  41163. @memberof Date
  41164. */
  41165. polyfill('removeWeeks', function (weeks) {
  41166. return this.remove({ days: (weeks * 7) });
  41167. });
  41168. /**
  41169. Removes months from the Date and returns it
  41170. @returns {Date}
  41171. @param months {Number} Number of months to remove
  41172. @function removeMonths
  41173. @deprecated Will be deprecated in version 2.0 in favor of remove
  41174. @instance
  41175. @memberof Date
  41176. */
  41177. polyfill('removeMonths', function (months) {
  41178. return this.remove({ months: months });
  41179. });
  41180. /**
  41181. Removes years from the Date and returns it
  41182. @returns {Date}
  41183. @param years {Number} Number of years to remove
  41184. @function removeYears
  41185. @deprecated Will be deprecated in version 2.0 in favor of remove
  41186. @instance
  41187. @memberof Date
  41188. */
  41189. polyfill('removeYears', function (years) {
  41190. return this.remove({ years: years });
  41191. });
  41192. /**
  41193. Adds weekdays based on a Mon-Fri work schedule and returns it
  41194. @returns {Date}
  41195. @param weekdays {Number} Number of weekdays to add
  41196. @function addWeekdays
  41197. @instance
  41198. @memberof Date
  41199. */
  41200. polyfill('addWeekdays', function (weekdays) {
  41201. var day = this.getDay();
  41202. if (day === 0) { day = 7; }
  41203. var daysOffset = weekdays;
  41204. var weekspan = Math.floor(( weekdays + day - 1 ) / 5.0);
  41205. if (weekdays > 0){
  41206. daysOffset += weekspan * 2;
  41207. if ( day > 5 ) { daysOffset -= day - 5; }
  41208. } else {
  41209. daysOffset += Math.min( weekspan * 2, 0);
  41210. if ( day > 6 ) { daysOffset -= 1; }
  41211. }
  41212. return this.addDays( daysOffset );
  41213. });
  41214. /**
  41215. Sets the time and date to now
  41216. @function setTimeToNow
  41217. @instance
  41218. @memberof Date
  41219. */
  41220. polyfill('setTimeToNow', function () {
  41221. var n = new Date();
  41222. this.setMilliseconds(n.getMilliseconds());
  41223. this.setSeconds(n.getSeconds());
  41224. this.setMinutes(n.getMinutes());
  41225. this.setHours(n.getHours());
  41226. });
  41227. /**
  41228. Returns a cloned copy of the current Date
  41229. @function clone
  41230. @instance
  41231. @memberof Date
  41232. */
  41233. polyfill('clone', function () {
  41234. return new Date(this.valueOf());
  41235. });
  41236. /**
  41237. Returns whether this Date is between a start and end date
  41238. @function between
  41239. @returns {Boolean}
  41240. @instance
  41241. @memberof Date
  41242. */
  41243. polyfill('between', function (start, end) {
  41244. return (this.valueOf() >= start.valueOf() &&
  41245. this.valueOf() <= end.valueOf());
  41246. });
  41247. /**
  41248. Compares a Date to this Date
  41249. @param {Date} Date to compare to
  41250. @function compareTo
  41251. @returns {Number} -1 if less than date, 0 if they are equal, 1 if more than date
  41252. @instance
  41253. @memberof Date
  41254. */
  41255. polyfill('compareTo', function (date) {
  41256. return Date.compare(this, date);
  41257. });
  41258. /**
  41259. Compares a Date and time to this Date and time for equality
  41260. @param {Date} Date to compare to
  41261. @function equals
  41262. @returns {Boolean}
  41263. @instance
  41264. @memberof Date
  41265. */
  41266. polyfill('equals', function (date) {
  41267. return Date.equals(this, date);
  41268. });
  41269. /**
  41270. Compares a Date to this Date for equality
  41271. @param {Date} Date to compare to
  41272. @function equalsDay
  41273. @returns {Boolean}
  41274. @instance
  41275. @memberof Date
  41276. */
  41277. polyfill('equalsDay', function (date) {
  41278. return Date.equalsDay(this, date);
  41279. });
  41280. /**
  41281. Checks to see if the Date is today
  41282. @function isToday
  41283. @returns {Boolean}
  41284. @instance
  41285. @memberof Date
  41286. */
  41287. polyfill('isToday', function () {
  41288. return Date.equalsDay(this, Date.today());
  41289. });
  41290. /**
  41291. Compares a Date to this Date for to see if it is after the Date passed
  41292. @param {Date} Date to compare to
  41293. @function isAfter
  41294. @returns {Boolean}
  41295. @instance
  41296. @memberof Date
  41297. */
  41298. polyfill('isAfter', function (date) {
  41299. date = date ? date : new Date();
  41300. return (this.compareTo(date) > 0);
  41301. });
  41302. /**
  41303. Compares a Date to this Date for to see if it is before the Date passed
  41304. @param {Date} Date to compare to
  41305. @function isBefore
  41306. @returns {Boolean}
  41307. @instance
  41308. @memberof Date
  41309. */
  41310. polyfill('isBefore', function (date) {
  41311. date = date ? date : new Date();
  41312. return (this.compareTo(date) < 0);
  41313. });
  41314. /**
  41315. Returns `true` if the Date is a weekend using standard Saturday/Sunday definition of a weekend
  41316. @function isWeekend
  41317. @returns {Boolean}
  41318. @instance
  41319. @memberof Date
  41320. */
  41321. polyfill('isWeekend', function (date) {
  41322. return (this.getDay() % 6 === 0);
  41323. });
  41324. /**
  41325. Returns the number of days between this Date and the Date passed in
  41326. @function getDaysBetween
  41327. @param {Date} Date to compare to
  41328. @returns {Number}
  41329. @instance
  41330. @memberof Date
  41331. */
  41332. polyfill('getDaysBetween', function (date) {
  41333. return ((date.clone().valueOf() - this.valueOf()) / 86400000) | 0;
  41334. });
  41335. /**
  41336. Returns the number of hours between this Date and the Date passed in
  41337. @function getHoursBetween
  41338. @param {Date} Date to compare to
  41339. @returns {Number}
  41340. @instance
  41341. @memberof Date
  41342. */
  41343. polyfill('getHoursBetween', function (date) {
  41344. return ((date.clone().valueOf() - this.valueOf()) / 3600000) | 0;
  41345. });
  41346. /**
  41347. Returns the number of minutes between this Date and the Date passed in
  41348. @function getMinutesBetween
  41349. @param {Date} Date to compare to
  41350. @returns {Number}
  41351. @instance
  41352. @memberof Date
  41353. */
  41354. polyfill('getMinutesBetween', function (date) {
  41355. return ((date.clone().valueOf() - this.valueOf()) / 60000) | 0;
  41356. });
  41357. /**
  41358. Returns the number of seconds between this Date and the Date passed in
  41359. @function getSecondsBetween
  41360. @param {Date} Date to compare to
  41361. @returns {Number}
  41362. @instance
  41363. @memberof Date
  41364. */
  41365. polyfill('getSecondsBetween', function (date) {
  41366. return ((date.clone().valueOf() - this.valueOf()) / 1000) | 0;
  41367. });
  41368. /**
  41369. Returns the number of milliseconds between this Date and the Date passed in
  41370. @function getMillisecondsBetween
  41371. @param {Date} Date to compare to
  41372. @returns {Number}
  41373. @instance
  41374. @memberof Date
  41375. */
  41376. polyfill('getMillisecondsBetween', function (date) {
  41377. return ((date.clone().valueOf() - this.valueOf())) | 0;
  41378. });
  41379. /**
  41380. Returns the number of months between this Date and the Date passed in
  41381. @function getMonthsBetween
  41382. @param {Date} Date to compare to
  41383. @returns {Number}
  41384. @instance
  41385. @memberof Date
  41386. */
  41387. polyfill('getMonthsBetween', function (date) {
  41388. var daysDiff = Math.abs(((+this) / (86400 * 1000)) - ((+date) / (86400 * 1000)));
  41389. var start = new Date((+date) < (+this) ? (+date) : (+this));
  41390. var end = new Date((date) > (+this) ? (+date) : (+this));
  41391. var months = 0;
  41392. while (+start < +end) {
  41393. months++;
  41394. start = start.addMonths(1);
  41395. }
  41396. var days = Math.abs(((+start) / (86400 * 1000)) - ((+end) / (86400 * 1000)));
  41397. return months - (days / 31);
  41398. });
  41399. /**
  41400. Returns the ordinal number of this Date
  41401. @function getOrdinalNumber
  41402. @returns {Number}
  41403. @instance
  41404. @memberof Date
  41405. */
  41406. polyfill('getOrdinalNumber', function () {
  41407. return Math.ceil((this.clone().clearTime() - new Date(this.getFullYear(), 0, 1)) / 86400000) + 1;
  41408. });
  41409. /**
  41410. Returns the a formatted version of this Date
  41411. @function toFormat
  41412. @param format {String} Format of the Date, using `YYYY`, `YY`, `MM`, `DD`, `HH`, `HH24`, `MI`, `SS`, etc
  41413. @returns {String}
  41414. @instance
  41415. @memberof Date
  41416. */
  41417. polyfill('toFormat', function (format) {
  41418. return toFormat(format, getReplaceMap(this));
  41419. });
  41420. /**
  41421. Returns the a formatted version of the UTC version of this Date
  41422. @function toUTCFormat
  41423. @param format {String} Format of the Date, using `YYYY`, `YY`, `MM`, `DD`, `HH`, `HH24`, `MI`, `SS`, etc
  41424. @returns {String}
  41425. @instance
  41426. @memberof Date
  41427. */
  41428. polyfill('toUTCFormat', function (format) {
  41429. return toFormat(format, getUTCReplaceMap(this));
  41430. });
  41431. /**
  41432. Returns the week number of this Date
  41433. @function getWeekNumber
  41434. @returns {Number}
  41435. @instance
  41436. @memberof Date
  41437. */
  41438. polyfill('getWeekNumber', function() {
  41439. var onejan = new Date(this.getFullYear(),0,1);
  41440. return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
  41441. });
  41442. /**
  41443. Returns the week number of this Date, zero padded
  41444. @function getFullWeekNumber
  41445. @returns {Number}
  41446. @instance
  41447. @memberof Date
  41448. */
  41449. polyfill('getFullWeekNumber', function() {
  41450. var weekNumber = '' + this.getWeekNumber();
  41451. if (weekNumber.length === 1) {
  41452. weekNumber = "0" + weekNumber;
  41453. }
  41454. return weekNumber;
  41455. });
  41456. var toFormat = function(format, replaceMap) {
  41457. var f = [ format ], i, l, s;
  41458. var replace = function (str, rep) {
  41459. var i = 0, l = f.length, j, ll, t, n = [];
  41460. for (; i < l; i++) {
  41461. if (typeof f[i] == 'string') {
  41462. t = f[i].split(str);
  41463. for (j = 0, ll = t.length - 1; j < ll; j++) {
  41464. n.push(t[j]);
  41465. n.push([rep]); // replacement pushed as non-string
  41466. }
  41467. n.push(t[ll]);
  41468. } else {
  41469. // must be a replacement, don't process, just push
  41470. n.push(f[i]);
  41471. }
  41472. }
  41473. f = n;
  41474. };
  41475. for (i in replaceMap) {
  41476. replace(i, replaceMap[i]);
  41477. }
  41478. s = '';
  41479. for (i = 0, l = f.length; i < l; i++)
  41480. s += typeof f[i] == 'string' ? f[i] : f[i][0];
  41481. return f.join('');
  41482. };
  41483. var getReplaceMap = function(date) {
  41484. var hours = (date.getHours() % 12) ? date.getHours() % 12 : 12;
  41485. return {
  41486. 'YYYY': date.getFullYear(),
  41487. 'YY': String(date.getFullYear()).slice(-2),
  41488. 'MMMM': monthsFull[date.getMonth()],
  41489. 'MMM': monthsAbbr[date.getMonth()],
  41490. 'MM': pad(date.getMonth() + 1, 2),
  41491. 'MI': pad(date.getMinutes(), 2),
  41492. 'M': date.getMonth() + 1,
  41493. 'DDDD': daysFull[date.getDay()],
  41494. 'DDD': daysAbbr[date.getDay()],
  41495. 'DD': pad(date.getDate(), 2),
  41496. 'D': date.getDate(),
  41497. 'HH24': pad(date.getHours(), 2),
  41498. 'HH': pad(hours, 2),
  41499. 'H': hours,
  41500. 'SS': pad(date.getSeconds(), 2),
  41501. 'PP': (date.getHours() >= 12) ? 'PM' : 'AM',
  41502. 'P': (date.getHours() >= 12) ? 'pm' : 'am',
  41503. 'LL': pad(date.getMilliseconds(), 3)
  41504. };
  41505. };
  41506. var getUTCReplaceMap = function(date) {
  41507. var hours = (date.getUTCHours() % 12) ? date.getUTCHours() % 12 : 12;
  41508. return {
  41509. 'YYYY': date.getUTCFullYear(),
  41510. 'YY': String(date.getUTCFullYear()).slice(-2),
  41511. 'MMMM': monthsFull[date.getUTCMonth()],
  41512. 'MMM': monthsAbbr[date.getUTCMonth()],
  41513. 'MM': pad(date.getUTCMonth() + 1, 2),
  41514. 'MI': pad(date.getUTCMinutes(), 2),
  41515. 'M': date.getUTCMonth() + 1,
  41516. 'DDDD': daysFull[date.getUTCDay()],
  41517. 'DDD': daysAbbr[date.getUTCDay()],
  41518. 'DD': pad(date.getUTCDate(), 2),
  41519. 'D': date.getUTCDate(),
  41520. 'HH24': pad(date.getUTCHours(), 2),
  41521. 'HH': pad(hours, 2),
  41522. 'H': hours,
  41523. 'SS': pad(date.getUTCSeconds(), 2),
  41524. 'PP': (date.getUTCHours() >= 12) ? 'PM' : 'AM',
  41525. 'P': (date.getUTCHours() >= 12) ? 'pm' : 'am',
  41526. 'LL': pad(date.getUTCMilliseconds(), 3)
  41527. };
  41528. };
  41529. /*
  41530. * change the language
  41531. * @param lang => support "es" Spanish, "fr" french, "pt-BR" Portuguese Brazil
  41532. * translate => diego
  41533. */
  41534. var language = function (lang) {
  41535. if (lang == "es") {
  41536. monthsAbbr = [
  41537. 'Ene',
  41538. 'Feb',
  41539. 'Mar',
  41540. 'Abr',
  41541. 'May',
  41542. 'Jun',
  41543. 'Jul',
  41544. 'Ago',
  41545. 'Sep',
  41546. 'Oct',
  41547. 'Nov',
  41548. 'Dic'
  41549. ];
  41550. monthsFull = [
  41551. 'Enero',
  41552. 'Febrero',
  41553. 'Marzo',
  41554. 'Abril',
  41555. 'Mayo',
  41556. 'Junio',
  41557. 'Julio',
  41558. 'Agosto',
  41559. 'Septiembre',
  41560. 'Octubre',
  41561. 'Noviembre',
  41562. 'Diciembre'
  41563. ];
  41564. daysAbbr = [
  41565. 'Dom',
  41566. 'Lun',
  41567. 'Mar',
  41568. 'Mie',
  41569. 'Jue',
  41570. 'Vie',
  41571. 'Sab'
  41572. ];
  41573. daysFull = [
  41574. 'Domingo',
  41575. 'Lunes',
  41576. 'Martes',
  41577. 'Miércoles',
  41578. 'Jueves',
  41579. 'Viernes',
  41580. 'Sábado'
  41581. ];
  41582. dayNames = {
  41583. 'do': 0,
  41584. 'dom': 0,
  41585. 'domingo': 0,
  41586. 'lu': 1,
  41587. 'lun': 1,
  41588. 'lunes': 1,
  41589. 'ma': 2,
  41590. 'mar': 2,
  41591. 'martes': 2,
  41592. 'mi': 3,
  41593. 'mie': 3,
  41594. 'miercoles': 3,
  41595. 'ju': 4,
  41596. 'jue': 4,
  41597. 'jueves': 4,
  41598. 'vi': 5,
  41599. 'vie': 5,
  41600. 'viernes': 5,
  41601. 'sa': 6,
  41602. 'sab': 6,
  41603. 'sabado': 6
  41604. };
  41605. monthsAll = monthsFull.concat(monthsAbbr);
  41606. daysAll = [
  41607. 'do',
  41608. 'dom',
  41609. 'domingo',
  41610. 'lu',
  41611. 'lun',
  41612. 'lunes',
  41613. 'ma',
  41614. 'mar',
  41615. 'martes',
  41616. 'mi',
  41617. 'mie',
  41618. 'miércoles',
  41619. 'ju',
  41620. 'jue',
  41621. 'jueves',
  41622. 'vi',
  41623. 'vie',
  41624. 'viernes',
  41625. 'sa',
  41626. 'sab',
  41627. 'sábado'
  41628. ];
  41629. monthNames = {
  41630. 'ene': 0,
  41631. 'enero': 0,
  41632. 'feb': 1,
  41633. 'febrero': 1,
  41634. 'mar': 2,
  41635. 'marzo': 2,
  41636. 'abr': 3,
  41637. 'abril': 3,
  41638. 'may': 4,
  41639. 'mayo':4,
  41640. 'jun': 5,
  41641. 'junio': 5,
  41642. 'jul': 6,
  41643. 'julio': 6,
  41644. 'ago': 7,
  41645. 'agosto': 7,
  41646. 'sep': 8,
  41647. 'septiembre': 8,
  41648. 'oct': 9,
  41649. 'octubre': 9,
  41650. 'nov': 10,
  41651. 'noviembre': 10,
  41652. 'dic': 11,
  41653. 'diciembre': 11
  41654. };
  41655. } else if (lang == "fr") {
  41656. monthsAbbr = [
  41657. 'Jan',
  41658. 'Fév',
  41659. 'Mar',
  41660. 'Avr',
  41661. 'Mai',
  41662. 'Jui',
  41663. 'Jul',
  41664. 'Aoû',
  41665. 'Sep',
  41666. 'Oct',
  41667. 'Nov',
  41668. 'Déc'
  41669. ];
  41670. monthsFull = [
  41671. 'Janvier',
  41672. 'Février',
  41673. 'Mars',
  41674. 'Avril',
  41675. 'Mai',
  41676. 'Juin',
  41677. 'Juillet',
  41678. 'Août',
  41679. 'Septembre',
  41680. 'Octobre',
  41681. 'Novembre',
  41682. 'Décembre'
  41683. ];
  41684. daysAbbr = [
  41685. 'Dim',
  41686. 'Lun',
  41687. 'Mar',
  41688. 'Mer',
  41689. 'Jeu',
  41690. 'Ven',
  41691. 'Sam'
  41692. ];
  41693. daysFull = [
  41694. 'Dimanchi',
  41695. 'Lundi',
  41696. 'Mardi',
  41697. 'Mercredi',
  41698. 'Jeudi',
  41699. 'Vendredi',
  41700. 'Samedi'
  41701. ];
  41702. dayNames = {
  41703. 'di': 0,
  41704. 'dim': 0,
  41705. 'dimanchi': 0,
  41706. 'lu': 1,
  41707. 'lun': 1,
  41708. 'lundi': 1,
  41709. 'ma': 2,
  41710. 'mar': 2,
  41711. 'mardi': 2,
  41712. 'me': 3,
  41713. 'mer': 3,
  41714. 'mercredi': 3,
  41715. 'je': 4,
  41716. 'jeu': 4,
  41717. 'jeudi': 4,
  41718. 've': 5,
  41719. 'ven': 5,
  41720. 'vendredi': 5,
  41721. 'sa': 6,
  41722. 'sam': 6,
  41723. 'samedi': 6
  41724. };
  41725. monthsAll = monthsFull.concat(monthsAbbr);
  41726. daysAll = [
  41727. 'di',
  41728. 'dim',
  41729. 'dimanchi',
  41730. 'lu',
  41731. 'lun',
  41732. 'lundi',
  41733. 'ma',
  41734. 'mar',
  41735. 'mardi',
  41736. 'me',
  41737. 'mer',
  41738. 'mercredi',
  41739. 'je',
  41740. 'jeu',
  41741. 'jeudi',
  41742. 've',
  41743. 'ven',
  41744. 'vendredi',
  41745. 'sa',
  41746. 'sam',
  41747. 'samedi'
  41748. ];
  41749. monthNames = {
  41750. 'jan': 0,
  41751. 'janvier': 0,
  41752. 'fév': 1,
  41753. 'février': 1,
  41754. 'mar': 2,
  41755. 'mars': 2,
  41756. 'avr': 3,
  41757. 'avril': 3,
  41758. 'mai': 4,
  41759. 'jui': 5,
  41760. 'juin': 5,
  41761. 'jul': 6,
  41762. 'juillet': 6,
  41763. 'aoû': 7,
  41764. 'août': 7,
  41765. 'sep': 8,
  41766. 'septembre': 8,
  41767. 'oct': 9,
  41768. 'octobre': 9,
  41769. 'nov': 10,
  41770. 'novembre': 10,
  41771. 'déc': 11,
  41772. 'décembre': 11
  41773. };
  41774. } else if (lang == "pt-BR") {
  41775. monthsAbbr = [
  41776. 'Jan',
  41777. 'Fev',
  41778. 'Mar',
  41779. 'Abr',
  41780. 'Mai',
  41781. 'Jun',
  41782. 'Jul',
  41783. 'Ago',
  41784. 'Set',
  41785. 'Out',
  41786. 'Nov',
  41787. 'Dez'
  41788. ];
  41789. monthsFull = [
  41790. 'Janeiro',
  41791. 'Fevereiro',
  41792. 'Março',
  41793. 'Abril',
  41794. 'Maio',
  41795. 'Junho',
  41796. 'Julho',
  41797. 'Agosto',
  41798. 'Setembro',
  41799. 'Outubro',
  41800. 'Novembro',
  41801. 'Dezembro'
  41802. ];
  41803. daysAbbr = [
  41804. 'Dom',
  41805. 'Seg',
  41806. 'Ter',
  41807. 'Qua',
  41808. 'Qui',
  41809. 'Sex',
  41810. 'Sab'
  41811. ];
  41812. daysFull = [
  41813. 'Domingo',
  41814. 'Segunda',
  41815. 'Terça',
  41816. 'Quarta',
  41817. 'Quinta',
  41818. 'Sexta',
  41819. 'Sábado'
  41820. ];
  41821. dayNames = {
  41822. 'do': 0,
  41823. 'dom': 0,
  41824. 'domingo': 0,
  41825. 'se': 1,
  41826. 'seg': 1,
  41827. 'segunda': 1,
  41828. 'te': 2,
  41829. 'ter': 2,
  41830. 'terca': 2,
  41831. 'qa': 3,
  41832. 'qua': 3,
  41833. 'quarta': 3,
  41834. 'qi': 4,
  41835. 'qui': 4,
  41836. 'quinta': 4,
  41837. 'se': 5,
  41838. 'sex': 5,
  41839. 'sexta': 5,
  41840. 'sa': 6,
  41841. 'sab': 6,
  41842. 'sabado': 6
  41843. };
  41844. monthsAll = monthsFull.concat(monthsAbbr);
  41845. daysAll = [
  41846. 'do',
  41847. 'dom',
  41848. 'domingo',
  41849. 'se',
  41850. 'seg',
  41851. 'segunda',
  41852. 'te',
  41853. 'ter',
  41854. 'terça',
  41855. 'qa',
  41856. 'qua',
  41857. 'quarta',
  41858. 'qi',
  41859. 'qui',
  41860. 'quinta',
  41861. 'se',
  41862. 'sex',
  41863. 'sexta',
  41864. 'sa',
  41865. 'sab',
  41866. 'sábado'
  41867. ];
  41868. monthNames = {
  41869. 'jan': 0,
  41870. 'janeiro': 0,
  41871. 'fev': 1,
  41872. 'fevereiro': 1,
  41873. 'mar': 2,
  41874. 'março': 2,
  41875. 'abr': 3,
  41876. 'abril': 3,
  41877. 'mai': 4,
  41878. 'jun': 5,
  41879. 'junho': 5,
  41880. 'jul': 6,
  41881. 'julho': 6,
  41882. 'ago': 7,
  41883. 'agosto': 7,
  41884. 'set': 8,
  41885. 'setembro': 8,
  41886. 'out': 9,
  41887. 'outubro': 9,
  41888. 'nov': 10,
  41889. 'novembro': 10,
  41890. 'dez': 11,
  41891. 'dezembro': 11
  41892. };
  41893. }
  41894. };
  41895. // Are we being imported?..
  41896. if (typeof module !== "undefined" && typeof module.exports === "object") {
  41897. module.exports.language = language;
  41898. } else if (typeof exports === "object") {
  41899. exports.language = language;
  41900. } else if (typeof Date.language === "undefined"){
  41901. // ...if not and if no language, then add statically to Date (for browsers.)
  41902. Date.language = language;
  41903. }
  41904. }());
  41905. },{}],210:[function(require,module,exports){
  41906. var Stream = require('stream').Stream;
  41907. var util = require('util');
  41908. module.exports = DelayedStream;
  41909. function DelayedStream() {
  41910. this.source = null;
  41911. this.dataSize = 0;
  41912. this.maxDataSize = 1024 * 1024;
  41913. this.pauseStream = true;
  41914. this._maxDataSizeExceeded = false;
  41915. this._released = false;
  41916. this._bufferedEvents = [];
  41917. }
  41918. util.inherits(DelayedStream, Stream);
  41919. DelayedStream.create = function(source, options) {
  41920. var delayedStream = new this();
  41921. options = options || {};
  41922. for (var option in options) {
  41923. delayedStream[option] = options[option];
  41924. }
  41925. delayedStream.source = source;
  41926. var realEmit = source.emit;
  41927. source.emit = function() {
  41928. delayedStream._handleEmit(arguments);
  41929. return realEmit.apply(source, arguments);
  41930. };
  41931. source.on('error', function() {});
  41932. if (delayedStream.pauseStream) {
  41933. source.pause();
  41934. }
  41935. return delayedStream;
  41936. };
  41937. Object.defineProperty(DelayedStream.prototype, 'readable', {
  41938. configurable: true,
  41939. enumerable: true,
  41940. get: function() {
  41941. return this.source.readable;
  41942. }
  41943. });
  41944. DelayedStream.prototype.setEncoding = function() {
  41945. return this.source.setEncoding.apply(this.source, arguments);
  41946. };
  41947. DelayedStream.prototype.resume = function() {
  41948. if (!this._released) {
  41949. this.release();
  41950. }
  41951. this.source.resume();
  41952. };
  41953. DelayedStream.prototype.pause = function() {
  41954. this.source.pause();
  41955. };
  41956. DelayedStream.prototype.release = function() {
  41957. this._released = true;
  41958. this._bufferedEvents.forEach(function(args) {
  41959. this.emit.apply(this, args);
  41960. }.bind(this));
  41961. this._bufferedEvents = [];
  41962. };
  41963. DelayedStream.prototype.pipe = function() {
  41964. var r = Stream.prototype.pipe.apply(this, arguments);
  41965. this.resume();
  41966. return r;
  41967. };
  41968. DelayedStream.prototype._handleEmit = function(args) {
  41969. if (this._released) {
  41970. this.emit.apply(this, args);
  41971. return;
  41972. }
  41973. if (args[0] === 'data') {
  41974. this.dataSize += args[1].length;
  41975. this._checkIfMaxDataSizeExceeded();
  41976. }
  41977. this._bufferedEvents.push(args);
  41978. };
  41979. DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
  41980. if (this._maxDataSizeExceeded) {
  41981. return;
  41982. }
  41983. if (this.dataSize <= this.maxDataSize) {
  41984. return;
  41985. }
  41986. this._maxDataSizeExceeded = true;
  41987. var message =
  41988. 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
  41989. this.emit('error', new Error(message));
  41990. };
  41991. },{"stream":597,"util":658}],211:[function(require,module,exports){
  41992. /*!
  41993. * depd
  41994. * Copyright(c) 2015 Douglas Christopher Wilson
  41995. * MIT Licensed
  41996. */
  41997. 'use strict'
  41998. /**
  41999. * Module exports.
  42000. * @public
  42001. */
  42002. module.exports = depd
  42003. /**
  42004. * Create deprecate for namespace in caller.
  42005. */
  42006. function depd (namespace) {
  42007. if (!namespace) {
  42008. throw new TypeError('argument namespace is required')
  42009. }
  42010. function deprecate (message) {
  42011. // no-op in browser
  42012. }
  42013. deprecate._file = undefined
  42014. deprecate._ignored = true
  42015. deprecate._namespace = namespace
  42016. deprecate._traced = false
  42017. deprecate._warned = Object.create(null)
  42018. deprecate.function = wrapfunction
  42019. deprecate.property = wrapproperty
  42020. return deprecate
  42021. }
  42022. /**
  42023. * Return a wrapped function in a deprecation message.
  42024. *
  42025. * This is a no-op version of the wrapper, which does nothing but call
  42026. * validation.
  42027. */
  42028. function wrapfunction (fn, message) {
  42029. if (typeof fn !== 'function') {
  42030. throw new TypeError('argument fn must be a function')
  42031. }
  42032. return fn
  42033. }
  42034. /**
  42035. * Wrap property in a deprecation message.
  42036. *
  42037. * This is a no-op version of the wrapper, which does nothing but call
  42038. * validation.
  42039. */
  42040. function wrapproperty (obj, prop, message) {
  42041. if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
  42042. throw new TypeError('argument obj must be object')
  42043. }
  42044. var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
  42045. if (!descriptor) {
  42046. throw new TypeError('must call property on owner object')
  42047. }
  42048. if (!descriptor.configurable) {
  42049. throw new TypeError('property must be configurable')
  42050. }
  42051. }
  42052. },{}],212:[function(require,module,exports){
  42053. 'use strict';
  42054. exports.utils = require('./des/utils');
  42055. exports.Cipher = require('./des/cipher');
  42056. exports.DES = require('./des/des');
  42057. exports.CBC = require('./des/cbc');
  42058. exports.EDE = require('./des/ede');
  42059. },{"./des/cbc":213,"./des/cipher":214,"./des/des":215,"./des/ede":216,"./des/utils":217}],213:[function(require,module,exports){
  42060. 'use strict';
  42061. var assert = require('minimalistic-assert');
  42062. var inherits = require('inherits');
  42063. var proto = {};
  42064. function CBCState(iv) {
  42065. assert.equal(iv.length, 8, 'Invalid IV length');
  42066. this.iv = new Array(8);
  42067. for (var i = 0; i < this.iv.length; i++)
  42068. this.iv[i] = iv[i];
  42069. }
  42070. function instantiate(Base) {
  42071. function CBC(options) {
  42072. Base.call(this, options);
  42073. this._cbcInit();
  42074. }
  42075. inherits(CBC, Base);
  42076. var keys = Object.keys(proto);
  42077. for (var i = 0; i < keys.length; i++) {
  42078. var key = keys[i];
  42079. CBC.prototype[key] = proto[key];
  42080. }
  42081. CBC.create = function create(options) {
  42082. return new CBC(options);
  42083. };
  42084. return CBC;
  42085. }
  42086. exports.instantiate = instantiate;
  42087. proto._cbcInit = function _cbcInit() {
  42088. var state = new CBCState(this.options.iv);
  42089. this._cbcState = state;
  42090. };
  42091. proto._update = function _update(inp, inOff, out, outOff) {
  42092. var state = this._cbcState;
  42093. var superProto = this.constructor.super_.prototype;
  42094. var iv = state.iv;
  42095. if (this.type === 'encrypt') {
  42096. for (var i = 0; i < this.blockSize; i++)
  42097. iv[i] ^= inp[inOff + i];
  42098. superProto._update.call(this, iv, 0, out, outOff);
  42099. for (var i = 0; i < this.blockSize; i++)
  42100. iv[i] = out[outOff + i];
  42101. } else {
  42102. superProto._update.call(this, inp, inOff, out, outOff);
  42103. for (var i = 0; i < this.blockSize; i++)
  42104. out[outOff + i] ^= iv[i];
  42105. for (var i = 0; i < this.blockSize; i++)
  42106. iv[i] = inp[inOff + i];
  42107. }
  42108. };
  42109. },{"inherits":320,"minimalistic-assert":345}],214:[function(require,module,exports){
  42110. 'use strict';
  42111. var assert = require('minimalistic-assert');
  42112. function Cipher(options) {
  42113. this.options = options;
  42114. this.type = this.options.type;
  42115. this.blockSize = 8;
  42116. this._init();
  42117. this.buffer = new Array(this.blockSize);
  42118. this.bufferOff = 0;
  42119. }
  42120. module.exports = Cipher;
  42121. Cipher.prototype._init = function _init() {
  42122. // Might be overrided
  42123. };
  42124. Cipher.prototype.update = function update(data) {
  42125. if (data.length === 0)
  42126. return [];
  42127. if (this.type === 'decrypt')
  42128. return this._updateDecrypt(data);
  42129. else
  42130. return this._updateEncrypt(data);
  42131. };
  42132. Cipher.prototype._buffer = function _buffer(data, off) {
  42133. // Append data to buffer
  42134. var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
  42135. for (var i = 0; i < min; i++)
  42136. this.buffer[this.bufferOff + i] = data[off + i];
  42137. this.bufferOff += min;
  42138. // Shift next
  42139. return min;
  42140. };
  42141. Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
  42142. this._update(this.buffer, 0, out, off);
  42143. this.bufferOff = 0;
  42144. return this.blockSize;
  42145. };
  42146. Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
  42147. var inputOff = 0;
  42148. var outputOff = 0;
  42149. var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
  42150. var out = new Array(count * this.blockSize);
  42151. if (this.bufferOff !== 0) {
  42152. inputOff += this._buffer(data, inputOff);
  42153. if (this.bufferOff === this.buffer.length)
  42154. outputOff += this._flushBuffer(out, outputOff);
  42155. }
  42156. // Write blocks
  42157. var max = data.length - ((data.length - inputOff) % this.blockSize);
  42158. for (; inputOff < max; inputOff += this.blockSize) {
  42159. this._update(data, inputOff, out, outputOff);
  42160. outputOff += this.blockSize;
  42161. }
  42162. // Queue rest
  42163. for (; inputOff < data.length; inputOff++, this.bufferOff++)
  42164. this.buffer[this.bufferOff] = data[inputOff];
  42165. return out;
  42166. };
  42167. Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
  42168. var inputOff = 0;
  42169. var outputOff = 0;
  42170. var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
  42171. var out = new Array(count * this.blockSize);
  42172. // TODO(indutny): optimize it, this is far from optimal
  42173. for (; count > 0; count--) {
  42174. inputOff += this._buffer(data, inputOff);
  42175. outputOff += this._flushBuffer(out, outputOff);
  42176. }
  42177. // Buffer rest of the input
  42178. inputOff += this._buffer(data, inputOff);
  42179. return out;
  42180. };
  42181. Cipher.prototype.final = function final(buffer) {
  42182. var first;
  42183. if (buffer)
  42184. first = this.update(buffer);
  42185. var last;
  42186. if (this.type === 'encrypt')
  42187. last = this._finalEncrypt();
  42188. else
  42189. last = this._finalDecrypt();
  42190. if (first)
  42191. return first.concat(last);
  42192. else
  42193. return last;
  42194. };
  42195. Cipher.prototype._pad = function _pad(buffer, off) {
  42196. if (off === 0)
  42197. return false;
  42198. while (off < buffer.length)
  42199. buffer[off++] = 0;
  42200. return true;
  42201. };
  42202. Cipher.prototype._finalEncrypt = function _finalEncrypt() {
  42203. if (!this._pad(this.buffer, this.bufferOff))
  42204. return [];
  42205. var out = new Array(this.blockSize);
  42206. this._update(this.buffer, 0, out, 0);
  42207. return out;
  42208. };
  42209. Cipher.prototype._unpad = function _unpad(buffer) {
  42210. return buffer;
  42211. };
  42212. Cipher.prototype._finalDecrypt = function _finalDecrypt() {
  42213. assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
  42214. var out = new Array(this.blockSize);
  42215. this._flushBuffer(out, 0);
  42216. return this._unpad(out);
  42217. };
  42218. },{"minimalistic-assert":345}],215:[function(require,module,exports){
  42219. 'use strict';
  42220. var assert = require('minimalistic-assert');
  42221. var inherits = require('inherits');
  42222. var utils = require('./utils');
  42223. var Cipher = require('./cipher');
  42224. function DESState() {
  42225. this.tmp = new Array(2);
  42226. this.keys = null;
  42227. }
  42228. function DES(options) {
  42229. Cipher.call(this, options);
  42230. var state = new DESState();
  42231. this._desState = state;
  42232. this.deriveKeys(state, options.key);
  42233. }
  42234. inherits(DES, Cipher);
  42235. module.exports = DES;
  42236. DES.create = function create(options) {
  42237. return new DES(options);
  42238. };
  42239. var shiftTable = [
  42240. 1, 1, 2, 2, 2, 2, 2, 2,
  42241. 1, 2, 2, 2, 2, 2, 2, 1
  42242. ];
  42243. DES.prototype.deriveKeys = function deriveKeys(state, key) {
  42244. state.keys = new Array(16 * 2);
  42245. assert.equal(key.length, this.blockSize, 'Invalid key length');
  42246. var kL = utils.readUInt32BE(key, 0);
  42247. var kR = utils.readUInt32BE(key, 4);
  42248. utils.pc1(kL, kR, state.tmp, 0);
  42249. kL = state.tmp[0];
  42250. kR = state.tmp[1];
  42251. for (var i = 0; i < state.keys.length; i += 2) {
  42252. var shift = shiftTable[i >>> 1];
  42253. kL = utils.r28shl(kL, shift);
  42254. kR = utils.r28shl(kR, shift);
  42255. utils.pc2(kL, kR, state.keys, i);
  42256. }
  42257. };
  42258. DES.prototype._update = function _update(inp, inOff, out, outOff) {
  42259. var state = this._desState;
  42260. var l = utils.readUInt32BE(inp, inOff);
  42261. var r = utils.readUInt32BE(inp, inOff + 4);
  42262. // Initial Permutation
  42263. utils.ip(l, r, state.tmp, 0);
  42264. l = state.tmp[0];
  42265. r = state.tmp[1];
  42266. if (this.type === 'encrypt')
  42267. this._encrypt(state, l, r, state.tmp, 0);
  42268. else
  42269. this._decrypt(state, l, r, state.tmp, 0);
  42270. l = state.tmp[0];
  42271. r = state.tmp[1];
  42272. utils.writeUInt32BE(out, l, outOff);
  42273. utils.writeUInt32BE(out, r, outOff + 4);
  42274. };
  42275. DES.prototype._pad = function _pad(buffer, off) {
  42276. var value = buffer.length - off;
  42277. for (var i = off; i < buffer.length; i++)
  42278. buffer[i] = value;
  42279. return true;
  42280. };
  42281. DES.prototype._unpad = function _unpad(buffer) {
  42282. var pad = buffer[buffer.length - 1];
  42283. for (var i = buffer.length - pad; i < buffer.length; i++)
  42284. assert.equal(buffer[i], pad);
  42285. return buffer.slice(0, buffer.length - pad);
  42286. };
  42287. DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
  42288. var l = lStart;
  42289. var r = rStart;
  42290. // Apply f() x16 times
  42291. for (var i = 0; i < state.keys.length; i += 2) {
  42292. var keyL = state.keys[i];
  42293. var keyR = state.keys[i + 1];
  42294. // f(r, k)
  42295. utils.expand(r, state.tmp, 0);
  42296. keyL ^= state.tmp[0];
  42297. keyR ^= state.tmp[1];
  42298. var s = utils.substitute(keyL, keyR);
  42299. var f = utils.permute(s);
  42300. var t = r;
  42301. r = (l ^ f) >>> 0;
  42302. l = t;
  42303. }
  42304. // Reverse Initial Permutation
  42305. utils.rip(r, l, out, off);
  42306. };
  42307. DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
  42308. var l = rStart;
  42309. var r = lStart;
  42310. // Apply f() x16 times
  42311. for (var i = state.keys.length - 2; i >= 0; i -= 2) {
  42312. var keyL = state.keys[i];
  42313. var keyR = state.keys[i + 1];
  42314. // f(r, k)
  42315. utils.expand(l, state.tmp, 0);
  42316. keyL ^= state.tmp[0];
  42317. keyR ^= state.tmp[1];
  42318. var s = utils.substitute(keyL, keyR);
  42319. var f = utils.permute(s);
  42320. var t = l;
  42321. l = (r ^ f) >>> 0;
  42322. r = t;
  42323. }
  42324. // Reverse Initial Permutation
  42325. utils.rip(l, r, out, off);
  42326. };
  42327. },{"./cipher":214,"./utils":217,"inherits":320,"minimalistic-assert":345}],216:[function(require,module,exports){
  42328. 'use strict';
  42329. var assert = require('minimalistic-assert');
  42330. var inherits = require('inherits');
  42331. var Cipher = require('./cipher');
  42332. var DES = require('./des');
  42333. function EDEState(type, key) {
  42334. assert.equal(key.length, 24, 'Invalid key length');
  42335. var k1 = key.slice(0, 8);
  42336. var k2 = key.slice(8, 16);
  42337. var k3 = key.slice(16, 24);
  42338. if (type === 'encrypt') {
  42339. this.ciphers = [
  42340. DES.create({ type: 'encrypt', key: k1 }),
  42341. DES.create({ type: 'decrypt', key: k2 }),
  42342. DES.create({ type: 'encrypt', key: k3 })
  42343. ];
  42344. } else {
  42345. this.ciphers = [
  42346. DES.create({ type: 'decrypt', key: k3 }),
  42347. DES.create({ type: 'encrypt', key: k2 }),
  42348. DES.create({ type: 'decrypt', key: k1 })
  42349. ];
  42350. }
  42351. }
  42352. function EDE(options) {
  42353. Cipher.call(this, options);
  42354. var state = new EDEState(this.type, this.options.key);
  42355. this._edeState = state;
  42356. }
  42357. inherits(EDE, Cipher);
  42358. module.exports = EDE;
  42359. EDE.create = function create(options) {
  42360. return new EDE(options);
  42361. };
  42362. EDE.prototype._update = function _update(inp, inOff, out, outOff) {
  42363. var state = this._edeState;
  42364. state.ciphers[0]._update(inp, inOff, out, outOff);
  42365. state.ciphers[1]._update(out, outOff, out, outOff);
  42366. state.ciphers[2]._update(out, outOff, out, outOff);
  42367. };
  42368. EDE.prototype._pad = DES.prototype._pad;
  42369. EDE.prototype._unpad = DES.prototype._unpad;
  42370. },{"./cipher":214,"./des":215,"inherits":320,"minimalistic-assert":345}],217:[function(require,module,exports){
  42371. 'use strict';
  42372. exports.readUInt32BE = function readUInt32BE(bytes, off) {
  42373. var res = (bytes[0 + off] << 24) |
  42374. (bytes[1 + off] << 16) |
  42375. (bytes[2 + off] << 8) |
  42376. bytes[3 + off];
  42377. return res >>> 0;
  42378. };
  42379. exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
  42380. bytes[0 + off] = value >>> 24;
  42381. bytes[1 + off] = (value >>> 16) & 0xff;
  42382. bytes[2 + off] = (value >>> 8) & 0xff;
  42383. bytes[3 + off] = value & 0xff;
  42384. };
  42385. exports.ip = function ip(inL, inR, out, off) {
  42386. var outL = 0;
  42387. var outR = 0;
  42388. for (var i = 6; i >= 0; i -= 2) {
  42389. for (var j = 0; j <= 24; j += 8) {
  42390. outL <<= 1;
  42391. outL |= (inR >>> (j + i)) & 1;
  42392. }
  42393. for (var j = 0; j <= 24; j += 8) {
  42394. outL <<= 1;
  42395. outL |= (inL >>> (j + i)) & 1;
  42396. }
  42397. }
  42398. for (var i = 6; i >= 0; i -= 2) {
  42399. for (var j = 1; j <= 25; j += 8) {
  42400. outR <<= 1;
  42401. outR |= (inR >>> (j + i)) & 1;
  42402. }
  42403. for (var j = 1; j <= 25; j += 8) {
  42404. outR <<= 1;
  42405. outR |= (inL >>> (j + i)) & 1;
  42406. }
  42407. }
  42408. out[off + 0] = outL >>> 0;
  42409. out[off + 1] = outR >>> 0;
  42410. };
  42411. exports.rip = function rip(inL, inR, out, off) {
  42412. var outL = 0;
  42413. var outR = 0;
  42414. for (var i = 0; i < 4; i++) {
  42415. for (var j = 24; j >= 0; j -= 8) {
  42416. outL <<= 1;
  42417. outL |= (inR >>> (j + i)) & 1;
  42418. outL <<= 1;
  42419. outL |= (inL >>> (j + i)) & 1;
  42420. }
  42421. }
  42422. for (var i = 4; i < 8; i++) {
  42423. for (var j = 24; j >= 0; j -= 8) {
  42424. outR <<= 1;
  42425. outR |= (inR >>> (j + i)) & 1;
  42426. outR <<= 1;
  42427. outR |= (inL >>> (j + i)) & 1;
  42428. }
  42429. }
  42430. out[off + 0] = outL >>> 0;
  42431. out[off + 1] = outR >>> 0;
  42432. };
  42433. exports.pc1 = function pc1(inL, inR, out, off) {
  42434. var outL = 0;
  42435. var outR = 0;
  42436. // 7, 15, 23, 31, 39, 47, 55, 63
  42437. // 6, 14, 22, 30, 39, 47, 55, 63
  42438. // 5, 13, 21, 29, 39, 47, 55, 63
  42439. // 4, 12, 20, 28
  42440. for (var i = 7; i >= 5; i--) {
  42441. for (var j = 0; j <= 24; j += 8) {
  42442. outL <<= 1;
  42443. outL |= (inR >> (j + i)) & 1;
  42444. }
  42445. for (var j = 0; j <= 24; j += 8) {
  42446. outL <<= 1;
  42447. outL |= (inL >> (j + i)) & 1;
  42448. }
  42449. }
  42450. for (var j = 0; j <= 24; j += 8) {
  42451. outL <<= 1;
  42452. outL |= (inR >> (j + i)) & 1;
  42453. }
  42454. // 1, 9, 17, 25, 33, 41, 49, 57
  42455. // 2, 10, 18, 26, 34, 42, 50, 58
  42456. // 3, 11, 19, 27, 35, 43, 51, 59
  42457. // 36, 44, 52, 60
  42458. for (var i = 1; i <= 3; i++) {
  42459. for (var j = 0; j <= 24; j += 8) {
  42460. outR <<= 1;
  42461. outR |= (inR >> (j + i)) & 1;
  42462. }
  42463. for (var j = 0; j <= 24; j += 8) {
  42464. outR <<= 1;
  42465. outR |= (inL >> (j + i)) & 1;
  42466. }
  42467. }
  42468. for (var j = 0; j <= 24; j += 8) {
  42469. outR <<= 1;
  42470. outR |= (inL >> (j + i)) & 1;
  42471. }
  42472. out[off + 0] = outL >>> 0;
  42473. out[off + 1] = outR >>> 0;
  42474. };
  42475. exports.r28shl = function r28shl(num, shift) {
  42476. return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
  42477. };
  42478. var pc2table = [
  42479. // inL => outL
  42480. 14, 11, 17, 4, 27, 23, 25, 0,
  42481. 13, 22, 7, 18, 5, 9, 16, 24,
  42482. 2, 20, 12, 21, 1, 8, 15, 26,
  42483. // inR => outR
  42484. 15, 4, 25, 19, 9, 1, 26, 16,
  42485. 5, 11, 23, 8, 12, 7, 17, 0,
  42486. 22, 3, 10, 14, 6, 20, 27, 24
  42487. ];
  42488. exports.pc2 = function pc2(inL, inR, out, off) {
  42489. var outL = 0;
  42490. var outR = 0;
  42491. var len = pc2table.length >>> 1;
  42492. for (var i = 0; i < len; i++) {
  42493. outL <<= 1;
  42494. outL |= (inL >>> pc2table[i]) & 0x1;
  42495. }
  42496. for (var i = len; i < pc2table.length; i++) {
  42497. outR <<= 1;
  42498. outR |= (inR >>> pc2table[i]) & 0x1;
  42499. }
  42500. out[off + 0] = outL >>> 0;
  42501. out[off + 1] = outR >>> 0;
  42502. };
  42503. exports.expand = function expand(r, out, off) {
  42504. var outL = 0;
  42505. var outR = 0;
  42506. outL = ((r & 1) << 5) | (r >>> 27);
  42507. for (var i = 23; i >= 15; i -= 4) {
  42508. outL <<= 6;
  42509. outL |= (r >>> i) & 0x3f;
  42510. }
  42511. for (var i = 11; i >= 3; i -= 4) {
  42512. outR |= (r >>> i) & 0x3f;
  42513. outR <<= 6;
  42514. }
  42515. outR |= ((r & 0x1f) << 1) | (r >>> 31);
  42516. out[off + 0] = outL >>> 0;
  42517. out[off + 1] = outR >>> 0;
  42518. };
  42519. var sTable = [
  42520. 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
  42521. 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
  42522. 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
  42523. 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
  42524. 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
  42525. 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
  42526. 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
  42527. 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
  42528. 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
  42529. 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
  42530. 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
  42531. 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
  42532. 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
  42533. 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
  42534. 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
  42535. 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
  42536. 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
  42537. 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
  42538. 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
  42539. 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
  42540. 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
  42541. 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
  42542. 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
  42543. 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
  42544. 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
  42545. 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
  42546. 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
  42547. 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
  42548. 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
  42549. 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
  42550. 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
  42551. 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
  42552. ];
  42553. exports.substitute = function substitute(inL, inR) {
  42554. var out = 0;
  42555. for (var i = 0; i < 4; i++) {
  42556. var b = (inL >>> (18 - i * 6)) & 0x3f;
  42557. var sb = sTable[i * 0x40 + b];
  42558. out <<= 4;
  42559. out |= sb;
  42560. }
  42561. for (var i = 0; i < 4; i++) {
  42562. var b = (inR >>> (18 - i * 6)) & 0x3f;
  42563. var sb = sTable[4 * 0x40 + i * 0x40 + b];
  42564. out <<= 4;
  42565. out |= sb;
  42566. }
  42567. return out >>> 0;
  42568. };
  42569. var permuteTable = [
  42570. 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
  42571. 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
  42572. ];
  42573. exports.permute = function permute(num) {
  42574. var out = 0;
  42575. for (var i = 0; i < permuteTable.length; i++) {
  42576. out <<= 1;
  42577. out |= (num >>> permuteTable[i]) & 0x1;
  42578. }
  42579. return out >>> 0;
  42580. };
  42581. exports.padSplit = function padSplit(num, size, group) {
  42582. var str = num.toString(2);
  42583. while (str.length < size)
  42584. str = '0' + str;
  42585. var out = [];
  42586. for (var i = 0; i < size; i += group)
  42587. out.push(str.slice(i, i + group));
  42588. return out.join(' ');
  42589. };
  42590. },{}],218:[function(require,module,exports){
  42591. (function (Buffer){(function (){
  42592. var generatePrime = require('./lib/generatePrime')
  42593. var primes = require('./lib/primes.json')
  42594. var DH = require('./lib/dh')
  42595. function getDiffieHellman (mod) {
  42596. var prime = new Buffer(primes[mod].prime, 'hex')
  42597. var gen = new Buffer(primes[mod].gen, 'hex')
  42598. return new DH(prime, gen)
  42599. }
  42600. var ENCODINGS = {
  42601. 'binary': true, 'hex': true, 'base64': true
  42602. }
  42603. function createDiffieHellman (prime, enc, generator, genc) {
  42604. if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
  42605. return createDiffieHellman(prime, 'binary', enc, generator)
  42606. }
  42607. enc = enc || 'binary'
  42608. genc = genc || 'binary'
  42609. generator = generator || new Buffer([2])
  42610. if (!Buffer.isBuffer(generator)) {
  42611. generator = new Buffer(generator, genc)
  42612. }
  42613. if (typeof prime === 'number') {
  42614. return new DH(generatePrime(prime, generator), generator, true)
  42615. }
  42616. if (!Buffer.isBuffer(prime)) {
  42617. prime = new Buffer(prime, enc)
  42618. }
  42619. return new DH(prime, generator, true)
  42620. }
  42621. exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
  42622. exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
  42623. }).call(this)}).call(this,require("buffer").Buffer)
  42624. },{"./lib/dh":219,"./lib/generatePrime":220,"./lib/primes.json":221,"buffer":193}],219:[function(require,module,exports){
  42625. (function (Buffer){(function (){
  42626. var BN = require('bn.js');
  42627. var MillerRabin = require('miller-rabin');
  42628. var millerRabin = new MillerRabin();
  42629. var TWENTYFOUR = new BN(24);
  42630. var ELEVEN = new BN(11);
  42631. var TEN = new BN(10);
  42632. var THREE = new BN(3);
  42633. var SEVEN = new BN(7);
  42634. var primes = require('./generatePrime');
  42635. var randomBytes = require('randombytes');
  42636. module.exports = DH;
  42637. function setPublicKey(pub, enc) {
  42638. enc = enc || 'utf8';
  42639. if (!Buffer.isBuffer(pub)) {
  42640. pub = new Buffer(pub, enc);
  42641. }
  42642. this._pub = new BN(pub);
  42643. return this;
  42644. }
  42645. function setPrivateKey(priv, enc) {
  42646. enc = enc || 'utf8';
  42647. if (!Buffer.isBuffer(priv)) {
  42648. priv = new Buffer(priv, enc);
  42649. }
  42650. this._priv = new BN(priv);
  42651. return this;
  42652. }
  42653. var primeCache = {};
  42654. function checkPrime(prime, generator) {
  42655. var gen = generator.toString('hex');
  42656. var hex = [gen, prime.toString(16)].join('_');
  42657. if (hex in primeCache) {
  42658. return primeCache[hex];
  42659. }
  42660. var error = 0;
  42661. if (prime.isEven() ||
  42662. !primes.simpleSieve ||
  42663. !primes.fermatTest(prime) ||
  42664. !millerRabin.test(prime)) {
  42665. //not a prime so +1
  42666. error += 1;
  42667. if (gen === '02' || gen === '05') {
  42668. // we'd be able to check the generator
  42669. // it would fail so +8
  42670. error += 8;
  42671. } else {
  42672. //we wouldn't be able to test the generator
  42673. // so +4
  42674. error += 4;
  42675. }
  42676. primeCache[hex] = error;
  42677. return error;
  42678. }
  42679. if (!millerRabin.test(prime.shrn(1))) {
  42680. //not a safe prime
  42681. error += 2;
  42682. }
  42683. var rem;
  42684. switch (gen) {
  42685. case '02':
  42686. if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
  42687. // unsuidable generator
  42688. error += 8;
  42689. }
  42690. break;
  42691. case '05':
  42692. rem = prime.mod(TEN);
  42693. if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
  42694. // prime mod 10 needs to equal 3 or 7
  42695. error += 8;
  42696. }
  42697. break;
  42698. default:
  42699. error += 4;
  42700. }
  42701. primeCache[hex] = error;
  42702. return error;
  42703. }
  42704. function DH(prime, generator, malleable) {
  42705. this.setGenerator(generator);
  42706. this.__prime = new BN(prime);
  42707. this._prime = BN.mont(this.__prime);
  42708. this._primeLen = prime.length;
  42709. this._pub = undefined;
  42710. this._priv = undefined;
  42711. this._primeCode = undefined;
  42712. if (malleable) {
  42713. this.setPublicKey = setPublicKey;
  42714. this.setPrivateKey = setPrivateKey;
  42715. } else {
  42716. this._primeCode = 8;
  42717. }
  42718. }
  42719. Object.defineProperty(DH.prototype, 'verifyError', {
  42720. enumerable: true,
  42721. get: function () {
  42722. if (typeof this._primeCode !== 'number') {
  42723. this._primeCode = checkPrime(this.__prime, this.__gen);
  42724. }
  42725. return this._primeCode;
  42726. }
  42727. });
  42728. DH.prototype.generateKeys = function () {
  42729. if (!this._priv) {
  42730. this._priv = new BN(randomBytes(this._primeLen));
  42731. }
  42732. this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
  42733. return this.getPublicKey();
  42734. };
  42735. DH.prototype.computeSecret = function (other) {
  42736. other = new BN(other);
  42737. other = other.toRed(this._prime);
  42738. var secret = other.redPow(this._priv).fromRed();
  42739. var out = new Buffer(secret.toArray());
  42740. var prime = this.getPrime();
  42741. if (out.length < prime.length) {
  42742. var front = new Buffer(prime.length - out.length);
  42743. front.fill(0);
  42744. out = Buffer.concat([front, out]);
  42745. }
  42746. return out;
  42747. };
  42748. DH.prototype.getPublicKey = function getPublicKey(enc) {
  42749. return formatReturnValue(this._pub, enc);
  42750. };
  42751. DH.prototype.getPrivateKey = function getPrivateKey(enc) {
  42752. return formatReturnValue(this._priv, enc);
  42753. };
  42754. DH.prototype.getPrime = function (enc) {
  42755. return formatReturnValue(this.__prime, enc);
  42756. };
  42757. DH.prototype.getGenerator = function (enc) {
  42758. return formatReturnValue(this._gen, enc);
  42759. };
  42760. DH.prototype.setGenerator = function (gen, enc) {
  42761. enc = enc || 'utf8';
  42762. if (!Buffer.isBuffer(gen)) {
  42763. gen = new Buffer(gen, enc);
  42764. }
  42765. this.__gen = gen;
  42766. this._gen = new BN(gen);
  42767. return this;
  42768. };
  42769. function formatReturnValue(bn, enc) {
  42770. var buf = new Buffer(bn.toArray());
  42771. if (!enc) {
  42772. return buf;
  42773. } else {
  42774. return buf.toString(enc);
  42775. }
  42776. }
  42777. }).call(this)}).call(this,require("buffer").Buffer)
  42778. },{"./generatePrime":220,"bn.js":222,"buffer":193,"miller-rabin":340,"randombytes":544}],220:[function(require,module,exports){
  42779. var randomBytes = require('randombytes');
  42780. module.exports = findPrime;
  42781. findPrime.simpleSieve = simpleSieve;
  42782. findPrime.fermatTest = fermatTest;
  42783. var BN = require('bn.js');
  42784. var TWENTYFOUR = new BN(24);
  42785. var MillerRabin = require('miller-rabin');
  42786. var millerRabin = new MillerRabin();
  42787. var ONE = new BN(1);
  42788. var TWO = new BN(2);
  42789. var FIVE = new BN(5);
  42790. var SIXTEEN = new BN(16);
  42791. var EIGHT = new BN(8);
  42792. var TEN = new BN(10);
  42793. var THREE = new BN(3);
  42794. var SEVEN = new BN(7);
  42795. var ELEVEN = new BN(11);
  42796. var FOUR = new BN(4);
  42797. var TWELVE = new BN(12);
  42798. var primes = null;
  42799. function _getPrimes() {
  42800. if (primes !== null)
  42801. return primes;
  42802. var limit = 0x100000;
  42803. var res = [];
  42804. res[0] = 2;
  42805. for (var i = 1, k = 3; k < limit; k += 2) {
  42806. var sqrt = Math.ceil(Math.sqrt(k));
  42807. for (var j = 0; j < i && res[j] <= sqrt; j++)
  42808. if (k % res[j] === 0)
  42809. break;
  42810. if (i !== j && res[j] <= sqrt)
  42811. continue;
  42812. res[i++] = k;
  42813. }
  42814. primes = res;
  42815. return res;
  42816. }
  42817. function simpleSieve(p) {
  42818. var primes = _getPrimes();
  42819. for (var i = 0; i < primes.length; i++)
  42820. if (p.modn(primes[i]) === 0) {
  42821. if (p.cmpn(primes[i]) === 0) {
  42822. return true;
  42823. } else {
  42824. return false;
  42825. }
  42826. }
  42827. return true;
  42828. }
  42829. function fermatTest(p) {
  42830. var red = BN.mont(p);
  42831. return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
  42832. }
  42833. function findPrime(bits, gen) {
  42834. if (bits < 16) {
  42835. // this is what openssl does
  42836. if (gen === 2 || gen === 5) {
  42837. return new BN([0x8c, 0x7b]);
  42838. } else {
  42839. return new BN([0x8c, 0x27]);
  42840. }
  42841. }
  42842. gen = new BN(gen);
  42843. var num, n2;
  42844. while (true) {
  42845. num = new BN(randomBytes(Math.ceil(bits / 8)));
  42846. while (num.bitLength() > bits) {
  42847. num.ishrn(1);
  42848. }
  42849. if (num.isEven()) {
  42850. num.iadd(ONE);
  42851. }
  42852. if (!num.testn(1)) {
  42853. num.iadd(TWO);
  42854. }
  42855. if (!gen.cmp(TWO)) {
  42856. while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
  42857. num.iadd(FOUR);
  42858. }
  42859. } else if (!gen.cmp(FIVE)) {
  42860. while (num.mod(TEN).cmp(THREE)) {
  42861. num.iadd(FOUR);
  42862. }
  42863. }
  42864. n2 = num.shrn(1);
  42865. if (simpleSieve(n2) && simpleSieve(num) &&
  42866. fermatTest(n2) && fermatTest(num) &&
  42867. millerRabin.test(n2) && millerRabin.test(num)) {
  42868. return num;
  42869. }
  42870. }
  42871. }
  42872. },{"bn.js":222,"miller-rabin":340,"randombytes":544}],221:[function(require,module,exports){
  42873. module.exports={
  42874. "modp1": {
  42875. "gen": "02",
  42876. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
  42877. },
  42878. "modp2": {
  42879. "gen": "02",
  42880. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
  42881. },
  42882. "modp5": {
  42883. "gen": "02",
  42884. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
  42885. },
  42886. "modp14": {
  42887. "gen": "02",
  42888. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
  42889. },
  42890. "modp15": {
  42891. "gen": "02",
  42892. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
  42893. },
  42894. "modp16": {
  42895. "gen": "02",
  42896. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
  42897. },
  42898. "modp17": {
  42899. "gen": "02",
  42900. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
  42901. },
  42902. "modp18": {
  42903. "gen": "02",
  42904. "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
  42905. }
  42906. }
  42907. },{}],222:[function(require,module,exports){
  42908. arguments[4][97][0].apply(exports,arguments)
  42909. },{"buffer":144,"dup":97}],223:[function(require,module,exports){
  42910. var crypto = require("crypto");
  42911. var BigInteger = require("jsbn").BigInteger;
  42912. var ECPointFp = require("./lib/ec.js").ECPointFp;
  42913. var Buffer = require("safer-buffer").Buffer;
  42914. exports.ECCurves = require("./lib/sec.js");
  42915. // zero prepad
  42916. function unstupid(hex,len)
  42917. {
  42918. return (hex.length >= len) ? hex : unstupid("0"+hex,len);
  42919. }
  42920. exports.ECKey = function(curve, key, isPublic)
  42921. {
  42922. var priv;
  42923. var c = curve();
  42924. var n = c.getN();
  42925. var bytes = Math.floor(n.bitLength()/8);
  42926. if(key)
  42927. {
  42928. if(isPublic)
  42929. {
  42930. var curve = c.getCurve();
  42931. // var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format
  42932. // var y = key.slice(bytes+1);
  42933. // this.P = new ECPointFp(curve,
  42934. // curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)),
  42935. // curve.fromBigInteger(new BigInteger(y.toString("hex"), 16)));
  42936. this.P = curve.decodePointHex(key.toString("hex"));
  42937. }else{
  42938. if(key.length != bytes) return false;
  42939. priv = new BigInteger(key.toString("hex"), 16);
  42940. }
  42941. }else{
  42942. var n1 = n.subtract(BigInteger.ONE);
  42943. var r = new BigInteger(crypto.randomBytes(n.bitLength()));
  42944. priv = r.mod(n1).add(BigInteger.ONE);
  42945. this.P = c.getG().multiply(priv);
  42946. }
  42947. if(this.P)
  42948. {
  42949. // var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2);
  42950. // this.PublicKey = Buffer.from("04"+pubhex,"hex");
  42951. this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex");
  42952. }
  42953. if(priv)
  42954. {
  42955. this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex");
  42956. this.deriveSharedSecret = function(key)
  42957. {
  42958. if(!key || !key.P) return false;
  42959. var S = key.P.multiply(priv);
  42960. return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex");
  42961. }
  42962. }
  42963. }
  42964. },{"./lib/ec.js":224,"./lib/sec.js":225,"crypto":208,"jsbn":328,"safer-buffer":562}],224:[function(require,module,exports){
  42965. // Basic Javascript Elliptic Curve implementation
  42966. // Ported loosely from BouncyCastle's Java EC code
  42967. // Only Fp curves implemented for now
  42968. // Requires jsbn.js and jsbn2.js
  42969. var BigInteger = require('jsbn').BigInteger
  42970. var Barrett = BigInteger.prototype.Barrett
  42971. // ----------------
  42972. // ECFieldElementFp
  42973. // constructor
  42974. function ECFieldElementFp(q,x) {
  42975. this.x = x;
  42976. // TODO if(x.compareTo(q) >= 0) error
  42977. this.q = q;
  42978. }
  42979. function feFpEquals(other) {
  42980. if(other == this) return true;
  42981. return (this.q.equals(other.q) && this.x.equals(other.x));
  42982. }
  42983. function feFpToBigInteger() {
  42984. return this.x;
  42985. }
  42986. function feFpNegate() {
  42987. return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
  42988. }
  42989. function feFpAdd(b) {
  42990. return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
  42991. }
  42992. function feFpSubtract(b) {
  42993. return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
  42994. }
  42995. function feFpMultiply(b) {
  42996. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
  42997. }
  42998. function feFpSquare() {
  42999. return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
  43000. }
  43001. function feFpDivide(b) {
  43002. return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
  43003. }
  43004. ECFieldElementFp.prototype.equals = feFpEquals;
  43005. ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger;
  43006. ECFieldElementFp.prototype.negate = feFpNegate;
  43007. ECFieldElementFp.prototype.add = feFpAdd;
  43008. ECFieldElementFp.prototype.subtract = feFpSubtract;
  43009. ECFieldElementFp.prototype.multiply = feFpMultiply;
  43010. ECFieldElementFp.prototype.square = feFpSquare;
  43011. ECFieldElementFp.prototype.divide = feFpDivide;
  43012. // ----------------
  43013. // ECPointFp
  43014. // constructor
  43015. function ECPointFp(curve,x,y,z) {
  43016. this.curve = curve;
  43017. this.x = x;
  43018. this.y = y;
  43019. // Projective coordinates: either zinv == null or z * zinv == 1
  43020. // z and zinv are just BigIntegers, not fieldElements
  43021. if(z == null) {
  43022. this.z = BigInteger.ONE;
  43023. }
  43024. else {
  43025. this.z = z;
  43026. }
  43027. this.zinv = null;
  43028. //TODO: compression flag
  43029. }
  43030. function pointFpGetX() {
  43031. if(this.zinv == null) {
  43032. this.zinv = this.z.modInverse(this.curve.q);
  43033. }
  43034. var r = this.x.toBigInteger().multiply(this.zinv);
  43035. this.curve.reduce(r);
  43036. return this.curve.fromBigInteger(r);
  43037. }
  43038. function pointFpGetY() {
  43039. if(this.zinv == null) {
  43040. this.zinv = this.z.modInverse(this.curve.q);
  43041. }
  43042. var r = this.y.toBigInteger().multiply(this.zinv);
  43043. this.curve.reduce(r);
  43044. return this.curve.fromBigInteger(r);
  43045. }
  43046. function pointFpEquals(other) {
  43047. if(other == this) return true;
  43048. if(this.isInfinity()) return other.isInfinity();
  43049. if(other.isInfinity()) return this.isInfinity();
  43050. var u, v;
  43051. // u = Y2 * Z1 - Y1 * Z2
  43052. u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
  43053. if(!u.equals(BigInteger.ZERO)) return false;
  43054. // v = X2 * Z1 - X1 * Z2
  43055. v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
  43056. return v.equals(BigInteger.ZERO);
  43057. }
  43058. function pointFpIsInfinity() {
  43059. if((this.x == null) && (this.y == null)) return true;
  43060. return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
  43061. }
  43062. function pointFpNegate() {
  43063. return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
  43064. }
  43065. function pointFpAdd(b) {
  43066. if(this.isInfinity()) return b;
  43067. if(b.isInfinity()) return this;
  43068. // u = Y2 * Z1 - Y1 * Z2
  43069. var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q);
  43070. // v = X2 * Z1 - X1 * Z2
  43071. var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q);
  43072. if(BigInteger.ZERO.equals(v)) {
  43073. if(BigInteger.ZERO.equals(u)) {
  43074. return this.twice(); // this == b, so double
  43075. }
  43076. return this.curve.getInfinity(); // this = -b, so infinity
  43077. }
  43078. var THREE = new BigInteger("3");
  43079. var x1 = this.x.toBigInteger();
  43080. var y1 = this.y.toBigInteger();
  43081. var x2 = b.x.toBigInteger();
  43082. var y2 = b.y.toBigInteger();
  43083. var v2 = v.square();
  43084. var v3 = v2.multiply(v);
  43085. var x1v2 = x1.multiply(v2);
  43086. var zu2 = u.square().multiply(this.z);
  43087. // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
  43088. var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q);
  43089. // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
  43090. var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q);
  43091. // z3 = v^3 * z1 * z2
  43092. var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q);
  43093. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  43094. }
  43095. function pointFpTwice() {
  43096. if(this.isInfinity()) return this;
  43097. if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity();
  43098. // TODO: optimized handling of constants
  43099. var THREE = new BigInteger("3");
  43100. var x1 = this.x.toBigInteger();
  43101. var y1 = this.y.toBigInteger();
  43102. var y1z1 = y1.multiply(this.z);
  43103. var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q);
  43104. var a = this.curve.a.toBigInteger();
  43105. // w = 3 * x1^2 + a * z1^2
  43106. var w = x1.square().multiply(THREE);
  43107. if(!BigInteger.ZERO.equals(a)) {
  43108. w = w.add(this.z.square().multiply(a));
  43109. }
  43110. w = w.mod(this.curve.q);
  43111. //this.curve.reduce(w);
  43112. // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
  43113. var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q);
  43114. // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
  43115. var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q);
  43116. // z3 = 8 * (y1 * z1)^3
  43117. var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q);
  43118. return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
  43119. }
  43120. // Simple NAF (Non-Adjacent Form) multiplication algorithm
  43121. // TODO: modularize the multiplication algorithm
  43122. function pointFpMultiply(k) {
  43123. if(this.isInfinity()) return this;
  43124. if(k.signum() == 0) return this.curve.getInfinity();
  43125. var e = k;
  43126. var h = e.multiply(new BigInteger("3"));
  43127. var neg = this.negate();
  43128. var R = this;
  43129. var i;
  43130. for(i = h.bitLength() - 2; i > 0; --i) {
  43131. R = R.twice();
  43132. var hBit = h.testBit(i);
  43133. var eBit = e.testBit(i);
  43134. if (hBit != eBit) {
  43135. R = R.add(hBit ? this : neg);
  43136. }
  43137. }
  43138. return R;
  43139. }
  43140. // Compute this*j + x*k (simultaneous multiplication)
  43141. function pointFpMultiplyTwo(j,x,k) {
  43142. var i;
  43143. if(j.bitLength() > k.bitLength())
  43144. i = j.bitLength() - 1;
  43145. else
  43146. i = k.bitLength() - 1;
  43147. var R = this.curve.getInfinity();
  43148. var both = this.add(x);
  43149. while(i >= 0) {
  43150. R = R.twice();
  43151. if(j.testBit(i)) {
  43152. if(k.testBit(i)) {
  43153. R = R.add(both);
  43154. }
  43155. else {
  43156. R = R.add(this);
  43157. }
  43158. }
  43159. else {
  43160. if(k.testBit(i)) {
  43161. R = R.add(x);
  43162. }
  43163. }
  43164. --i;
  43165. }
  43166. return R;
  43167. }
  43168. ECPointFp.prototype.getX = pointFpGetX;
  43169. ECPointFp.prototype.getY = pointFpGetY;
  43170. ECPointFp.prototype.equals = pointFpEquals;
  43171. ECPointFp.prototype.isInfinity = pointFpIsInfinity;
  43172. ECPointFp.prototype.negate = pointFpNegate;
  43173. ECPointFp.prototype.add = pointFpAdd;
  43174. ECPointFp.prototype.twice = pointFpTwice;
  43175. ECPointFp.prototype.multiply = pointFpMultiply;
  43176. ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo;
  43177. // ----------------
  43178. // ECCurveFp
  43179. // constructor
  43180. function ECCurveFp(q,a,b) {
  43181. this.q = q;
  43182. this.a = this.fromBigInteger(a);
  43183. this.b = this.fromBigInteger(b);
  43184. this.infinity = new ECPointFp(this, null, null);
  43185. this.reducer = new Barrett(this.q);
  43186. }
  43187. function curveFpGetQ() {
  43188. return this.q;
  43189. }
  43190. function curveFpGetA() {
  43191. return this.a;
  43192. }
  43193. function curveFpGetB() {
  43194. return this.b;
  43195. }
  43196. function curveFpEquals(other) {
  43197. if(other == this) return true;
  43198. return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b));
  43199. }
  43200. function curveFpGetInfinity() {
  43201. return this.infinity;
  43202. }
  43203. function curveFpFromBigInteger(x) {
  43204. return new ECFieldElementFp(this.q, x);
  43205. }
  43206. function curveReduce(x) {
  43207. this.reducer.reduce(x);
  43208. }
  43209. // for now, work with hex strings because they're easier in JS
  43210. function curveFpDecodePointHex(s) {
  43211. switch(parseInt(s.substr(0,2), 16)) { // first byte
  43212. case 0:
  43213. return this.infinity;
  43214. case 2:
  43215. case 3:
  43216. // point compression not supported yet
  43217. return null;
  43218. case 4:
  43219. case 6:
  43220. case 7:
  43221. var len = (s.length - 2) / 2;
  43222. var xHex = s.substr(2, len);
  43223. var yHex = s.substr(len+2, len);
  43224. return new ECPointFp(this,
  43225. this.fromBigInteger(new BigInteger(xHex, 16)),
  43226. this.fromBigInteger(new BigInteger(yHex, 16)));
  43227. default: // unsupported
  43228. return null;
  43229. }
  43230. }
  43231. function curveFpEncodePointHex(p) {
  43232. if (p.isInfinity()) return "00";
  43233. var xHex = p.getX().toBigInteger().toString(16);
  43234. var yHex = p.getY().toBigInteger().toString(16);
  43235. var oLen = this.getQ().toString(16).length;
  43236. if ((oLen % 2) != 0) oLen++;
  43237. while (xHex.length < oLen) {
  43238. xHex = "0" + xHex;
  43239. }
  43240. while (yHex.length < oLen) {
  43241. yHex = "0" + yHex;
  43242. }
  43243. return "04" + xHex + yHex;
  43244. }
  43245. ECCurveFp.prototype.getQ = curveFpGetQ;
  43246. ECCurveFp.prototype.getA = curveFpGetA;
  43247. ECCurveFp.prototype.getB = curveFpGetB;
  43248. ECCurveFp.prototype.equals = curveFpEquals;
  43249. ECCurveFp.prototype.getInfinity = curveFpGetInfinity;
  43250. ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger;
  43251. ECCurveFp.prototype.reduce = curveReduce;
  43252. //ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex;
  43253. ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex;
  43254. // from: https://github.com/kaielvin/jsbn-ec-point-compression
  43255. ECCurveFp.prototype.decodePointHex = function(s)
  43256. {
  43257. var yIsEven;
  43258. switch(parseInt(s.substr(0,2), 16)) { // first byte
  43259. case 0:
  43260. return this.infinity;
  43261. case 2:
  43262. yIsEven = false;
  43263. case 3:
  43264. if(yIsEven == undefined) yIsEven = true;
  43265. var len = s.length - 2;
  43266. var xHex = s.substr(2, len);
  43267. var x = this.fromBigInteger(new BigInteger(xHex,16));
  43268. var alpha = x.multiply(x.square().add(this.getA())).add(this.getB());
  43269. var beta = alpha.sqrt();
  43270. if (beta == null) throw "Invalid point compression";
  43271. var betaValue = beta.toBigInteger();
  43272. if (betaValue.testBit(0) != yIsEven)
  43273. {
  43274. // Use the other root
  43275. beta = this.fromBigInteger(this.getQ().subtract(betaValue));
  43276. }
  43277. return new ECPointFp(this,x,beta);
  43278. case 4:
  43279. case 6:
  43280. case 7:
  43281. var len = (s.length - 2) / 2;
  43282. var xHex = s.substr(2, len);
  43283. var yHex = s.substr(len+2, len);
  43284. return new ECPointFp(this,
  43285. this.fromBigInteger(new BigInteger(xHex, 16)),
  43286. this.fromBigInteger(new BigInteger(yHex, 16)));
  43287. default: // unsupported
  43288. return null;
  43289. }
  43290. }
  43291. ECCurveFp.prototype.encodeCompressedPointHex = function(p)
  43292. {
  43293. if (p.isInfinity()) return "00";
  43294. var xHex = p.getX().toBigInteger().toString(16);
  43295. var oLen = this.getQ().toString(16).length;
  43296. if ((oLen % 2) != 0) oLen++;
  43297. while (xHex.length < oLen)
  43298. xHex = "0" + xHex;
  43299. var yPrefix;
  43300. if(p.getY().toBigInteger().isEven()) yPrefix = "02";
  43301. else yPrefix = "03";
  43302. return yPrefix + xHex;
  43303. }
  43304. ECFieldElementFp.prototype.getR = function()
  43305. {
  43306. if(this.r != undefined) return this.r;
  43307. this.r = null;
  43308. var bitLength = this.q.bitLength();
  43309. if (bitLength > 128)
  43310. {
  43311. var firstWord = this.q.shiftRight(bitLength - 64);
  43312. if (firstWord.intValue() == -1)
  43313. {
  43314. this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q);
  43315. }
  43316. }
  43317. return this.r;
  43318. }
  43319. ECFieldElementFp.prototype.modMult = function(x1,x2)
  43320. {
  43321. return this.modReduce(x1.multiply(x2));
  43322. }
  43323. ECFieldElementFp.prototype.modReduce = function(x)
  43324. {
  43325. if (this.getR() != null)
  43326. {
  43327. var qLen = q.bitLength();
  43328. while (x.bitLength() > (qLen + 1))
  43329. {
  43330. var u = x.shiftRight(qLen);
  43331. var v = x.subtract(u.shiftLeft(qLen));
  43332. if (!this.getR().equals(BigInteger.ONE))
  43333. {
  43334. u = u.multiply(this.getR());
  43335. }
  43336. x = u.add(v);
  43337. }
  43338. while (x.compareTo(q) >= 0)
  43339. {
  43340. x = x.subtract(q);
  43341. }
  43342. }
  43343. else
  43344. {
  43345. x = x.mod(q);
  43346. }
  43347. return x;
  43348. }
  43349. ECFieldElementFp.prototype.sqrt = function()
  43350. {
  43351. if (!this.q.testBit(0)) throw "unsupported";
  43352. // p mod 4 == 3
  43353. if (this.q.testBit(1))
  43354. {
  43355. var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q));
  43356. return z.square().equals(this) ? z : null;
  43357. }
  43358. // p mod 4 == 1
  43359. var qMinusOne = this.q.subtract(BigInteger.ONE);
  43360. var legendreExponent = qMinusOne.shiftRight(1);
  43361. if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE)))
  43362. {
  43363. return null;
  43364. }
  43365. var u = qMinusOne.shiftRight(2);
  43366. var k = u.shiftLeft(1).add(BigInteger.ONE);
  43367. var Q = this.x;
  43368. var fourQ = modDouble(modDouble(Q));
  43369. var U, V;
  43370. do
  43371. {
  43372. var P;
  43373. do
  43374. {
  43375. P = new BigInteger(this.q.bitLength(), new SecureRandom());
  43376. }
  43377. while (P.compareTo(this.q) >= 0
  43378. || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne)));
  43379. var result = this.lucasSequence(P, Q, k);
  43380. U = result[0];
  43381. V = result[1];
  43382. if (this.modMult(V, V).equals(fourQ))
  43383. {
  43384. // Integer division by 2, mod q
  43385. if (V.testBit(0))
  43386. {
  43387. V = V.add(q);
  43388. }
  43389. V = V.shiftRight(1);
  43390. return new ECFieldElementFp(q,V);
  43391. }
  43392. }
  43393. while (U.equals(BigInteger.ONE) || U.equals(qMinusOne));
  43394. return null;
  43395. }
  43396. ECFieldElementFp.prototype.lucasSequence = function(P,Q,k)
  43397. {
  43398. var n = k.bitLength();
  43399. var s = k.getLowestSetBit();
  43400. var Uh = BigInteger.ONE;
  43401. var Vl = BigInteger.TWO;
  43402. var Vh = P;
  43403. var Ql = BigInteger.ONE;
  43404. var Qh = BigInteger.ONE;
  43405. for (var j = n - 1; j >= s + 1; --j)
  43406. {
  43407. Ql = this.modMult(Ql, Qh);
  43408. if (k.testBit(j))
  43409. {
  43410. Qh = this.modMult(Ql, Q);
  43411. Uh = this.modMult(Uh, Vh);
  43412. Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
  43413. Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
  43414. }
  43415. else
  43416. {
  43417. Qh = Ql;
  43418. Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
  43419. Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
  43420. Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
  43421. }
  43422. }
  43423. Ql = this.modMult(Ql, Qh);
  43424. Qh = this.modMult(Ql, Q);
  43425. Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
  43426. Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
  43427. Ql = this.modMult(Ql, Qh);
  43428. for (var j = 1; j <= s; ++j)
  43429. {
  43430. Uh = this.modMult(Uh, Vl);
  43431. Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
  43432. Ql = this.modMult(Ql, Ql);
  43433. }
  43434. return [ Uh, Vl ];
  43435. }
  43436. var exports = {
  43437. ECCurveFp: ECCurveFp,
  43438. ECPointFp: ECPointFp,
  43439. ECFieldElementFp: ECFieldElementFp
  43440. }
  43441. module.exports = exports
  43442. },{"jsbn":328}],225:[function(require,module,exports){
  43443. // Named EC curves
  43444. // Requires ec.js, jsbn.js, and jsbn2.js
  43445. var BigInteger = require('jsbn').BigInteger
  43446. var ECCurveFp = require('./ec.js').ECCurveFp
  43447. // ----------------
  43448. // X9ECParameters
  43449. // constructor
  43450. function X9ECParameters(curve,g,n,h) {
  43451. this.curve = curve;
  43452. this.g = g;
  43453. this.n = n;
  43454. this.h = h;
  43455. }
  43456. function x9getCurve() {
  43457. return this.curve;
  43458. }
  43459. function x9getG() {
  43460. return this.g;
  43461. }
  43462. function x9getN() {
  43463. return this.n;
  43464. }
  43465. function x9getH() {
  43466. return this.h;
  43467. }
  43468. X9ECParameters.prototype.getCurve = x9getCurve;
  43469. X9ECParameters.prototype.getG = x9getG;
  43470. X9ECParameters.prototype.getN = x9getN;
  43471. X9ECParameters.prototype.getH = x9getH;
  43472. // ----------------
  43473. // SECNamedCurves
  43474. function fromHex(s) { return new BigInteger(s, 16); }
  43475. function secp128r1() {
  43476. // p = 2^128 - 2^97 - 1
  43477. var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
  43478. var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
  43479. var b = fromHex("E87579C11079F43DD824993C2CEE5ED3");
  43480. //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679");
  43481. var n = fromHex("FFFFFFFE0000000075A30D1B9038A115");
  43482. var h = BigInteger.ONE;
  43483. var curve = new ECCurveFp(p, a, b);
  43484. var G = curve.decodePointHex("04"
  43485. + "161FF7528B899B2D0C28607CA52C5B86"
  43486. + "CF5AC8395BAFEB13C02DA292DDED7A83");
  43487. return new X9ECParameters(curve, G, n, h);
  43488. }
  43489. function secp160k1() {
  43490. // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
  43491. var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
  43492. var a = BigInteger.ZERO;
  43493. var b = fromHex("7");
  43494. //byte[] S = null;
  43495. var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
  43496. var h = BigInteger.ONE;
  43497. var curve = new ECCurveFp(p, a, b);
  43498. var G = curve.decodePointHex("04"
  43499. + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
  43500. + "938CF935318FDCED6BC28286531733C3F03C4FEE");
  43501. return new X9ECParameters(curve, G, n, h);
  43502. }
  43503. function secp160r1() {
  43504. // p = 2^160 - 2^31 - 1
  43505. var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
  43506. var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
  43507. var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
  43508. //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345");
  43509. var n = fromHex("0100000000000000000001F4C8F927AED3CA752257");
  43510. var h = BigInteger.ONE;
  43511. var curve = new ECCurveFp(p, a, b);
  43512. var G = curve.decodePointHex("04"
  43513. + "4A96B5688EF573284664698968C38BB913CBFC82"
  43514. + "23A628553168947D59DCC912042351377AC5FB32");
  43515. return new X9ECParameters(curve, G, n, h);
  43516. }
  43517. function secp192k1() {
  43518. // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
  43519. var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
  43520. var a = BigInteger.ZERO;
  43521. var b = fromHex("3");
  43522. //byte[] S = null;
  43523. var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
  43524. var h = BigInteger.ONE;
  43525. var curve = new ECCurveFp(p, a, b);
  43526. var G = curve.decodePointHex("04"
  43527. + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
  43528. + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
  43529. return new X9ECParameters(curve, G, n, h);
  43530. }
  43531. function secp192r1() {
  43532. // p = 2^192 - 2^64 - 1
  43533. var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
  43534. var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
  43535. var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
  43536. //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
  43537. var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
  43538. var h = BigInteger.ONE;
  43539. var curve = new ECCurveFp(p, a, b);
  43540. var G = curve.decodePointHex("04"
  43541. + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
  43542. + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
  43543. return new X9ECParameters(curve, G, n, h);
  43544. }
  43545. function secp224r1() {
  43546. // p = 2^224 - 2^96 + 1
  43547. var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
  43548. var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
  43549. var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
  43550. //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
  43551. var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
  43552. var h = BigInteger.ONE;
  43553. var curve = new ECCurveFp(p, a, b);
  43554. var G = curve.decodePointHex("04"
  43555. + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
  43556. + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
  43557. return new X9ECParameters(curve, G, n, h);
  43558. }
  43559. function secp256r1() {
  43560. // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
  43561. var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
  43562. var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
  43563. var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
  43564. //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90");
  43565. var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
  43566. var h = BigInteger.ONE;
  43567. var curve = new ECCurveFp(p, a, b);
  43568. var G = curve.decodePointHex("04"
  43569. + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
  43570. + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
  43571. return new X9ECParameters(curve, G, n, h);
  43572. }
  43573. // TODO: make this into a proper hashtable
  43574. function getSECCurveByName(name) {
  43575. if(name == "secp128r1") return secp128r1();
  43576. if(name == "secp160k1") return secp160k1();
  43577. if(name == "secp160r1") return secp160r1();
  43578. if(name == "secp192k1") return secp192k1();
  43579. if(name == "secp192r1") return secp192r1();
  43580. if(name == "secp224r1") return secp224r1();
  43581. if(name == "secp256r1") return secp256r1();
  43582. return null;
  43583. }
  43584. module.exports = {
  43585. "secp128r1":secp128r1,
  43586. "secp160k1":secp160k1,
  43587. "secp160r1":secp160r1,
  43588. "secp192k1":secp192k1,
  43589. "secp192r1":secp192r1,
  43590. "secp224r1":secp224r1,
  43591. "secp256r1":secp256r1
  43592. }
  43593. },{"./ec.js":224,"jsbn":328}],226:[function(require,module,exports){
  43594. 'use strict';
  43595. var Buffer = require('safe-buffer').Buffer;
  43596. var getParamBytesForAlg = require('./param-bytes-for-alg');
  43597. var MAX_OCTET = 0x80,
  43598. CLASS_UNIVERSAL = 0,
  43599. PRIMITIVE_BIT = 0x20,
  43600. TAG_SEQ = 0x10,
  43601. TAG_INT = 0x02,
  43602. ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),
  43603. ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);
  43604. function base64Url(base64) {
  43605. return base64
  43606. .replace(/=/g, '')
  43607. .replace(/\+/g, '-')
  43608. .replace(/\//g, '_');
  43609. }
  43610. function signatureAsBuffer(signature) {
  43611. if (Buffer.isBuffer(signature)) {
  43612. return signature;
  43613. } else if ('string' === typeof signature) {
  43614. return Buffer.from(signature, 'base64');
  43615. }
  43616. throw new TypeError('ECDSA signature must be a Base64 string or a Buffer');
  43617. }
  43618. function derToJose(signature, alg) {
  43619. signature = signatureAsBuffer(signature);
  43620. var paramBytes = getParamBytesForAlg(alg);
  43621. // the DER encoded param should at most be the param size, plus a padding
  43622. // zero, since due to being a signed integer
  43623. var maxEncodedParamLength = paramBytes + 1;
  43624. var inputLength = signature.length;
  43625. var offset = 0;
  43626. if (signature[offset++] !== ENCODED_TAG_SEQ) {
  43627. throw new Error('Could not find expected "seq"');
  43628. }
  43629. var seqLength = signature[offset++];
  43630. if (seqLength === (MAX_OCTET | 1)) {
  43631. seqLength = signature[offset++];
  43632. }
  43633. if (inputLength - offset < seqLength) {
  43634. throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');
  43635. }
  43636. if (signature[offset++] !== ENCODED_TAG_INT) {
  43637. throw new Error('Could not find expected "int" for "r"');
  43638. }
  43639. var rLength = signature[offset++];
  43640. if (inputLength - offset - 2 < rLength) {
  43641. throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');
  43642. }
  43643. if (maxEncodedParamLength < rLength) {
  43644. throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
  43645. }
  43646. var rOffset = offset;
  43647. offset += rLength;
  43648. if (signature[offset++] !== ENCODED_TAG_INT) {
  43649. throw new Error('Could not find expected "int" for "s"');
  43650. }
  43651. var sLength = signature[offset++];
  43652. if (inputLength - offset !== sLength) {
  43653. throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');
  43654. }
  43655. if (maxEncodedParamLength < sLength) {
  43656. throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');
  43657. }
  43658. var sOffset = offset;
  43659. offset += sLength;
  43660. if (offset !== inputLength) {
  43661. throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');
  43662. }
  43663. var rPadding = paramBytes - rLength,
  43664. sPadding = paramBytes - sLength;
  43665. var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);
  43666. for (offset = 0; offset < rPadding; ++offset) {
  43667. dst[offset] = 0;
  43668. }
  43669. signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);
  43670. offset = paramBytes;
  43671. for (var o = offset; offset < o + sPadding; ++offset) {
  43672. dst[offset] = 0;
  43673. }
  43674. signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);
  43675. dst = dst.toString('base64');
  43676. dst = base64Url(dst);
  43677. return dst;
  43678. }
  43679. function countPadding(buf, start, stop) {
  43680. var padding = 0;
  43681. while (start + padding < stop && buf[start + padding] === 0) {
  43682. ++padding;
  43683. }
  43684. var needsSign = buf[start + padding] >= MAX_OCTET;
  43685. if (needsSign) {
  43686. --padding;
  43687. }
  43688. return padding;
  43689. }
  43690. function joseToDer(signature, alg) {
  43691. signature = signatureAsBuffer(signature);
  43692. var paramBytes = getParamBytesForAlg(alg);
  43693. var signatureBytes = signature.length;
  43694. if (signatureBytes !== paramBytes * 2) {
  43695. throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');
  43696. }
  43697. var rPadding = countPadding(signature, 0, paramBytes);
  43698. var sPadding = countPadding(signature, paramBytes, signature.length);
  43699. var rLength = paramBytes - rPadding;
  43700. var sLength = paramBytes - sPadding;
  43701. var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;
  43702. var shortLength = rsBytes < MAX_OCTET;
  43703. var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);
  43704. var offset = 0;
  43705. dst[offset++] = ENCODED_TAG_SEQ;
  43706. if (shortLength) {
  43707. // Bit 8 has value "0"
  43708. // bits 7-1 give the length.
  43709. dst[offset++] = rsBytes;
  43710. } else {
  43711. // Bit 8 of first octet has value "1"
  43712. // bits 7-1 give the number of additional length octets.
  43713. dst[offset++] = MAX_OCTET | 1;
  43714. // length, base 256
  43715. dst[offset++] = rsBytes & 0xff;
  43716. }
  43717. dst[offset++] = ENCODED_TAG_INT;
  43718. dst[offset++] = rLength;
  43719. if (rPadding < 0) {
  43720. dst[offset++] = 0;
  43721. offset += signature.copy(dst, offset, 0, paramBytes);
  43722. } else {
  43723. offset += signature.copy(dst, offset, rPadding, paramBytes);
  43724. }
  43725. dst[offset++] = ENCODED_TAG_INT;
  43726. dst[offset++] = sLength;
  43727. if (sPadding < 0) {
  43728. dst[offset++] = 0;
  43729. signature.copy(dst, offset, paramBytes);
  43730. } else {
  43731. signature.copy(dst, offset, paramBytes + sPadding);
  43732. }
  43733. return dst;
  43734. }
  43735. module.exports = {
  43736. derToJose: derToJose,
  43737. joseToDer: joseToDer
  43738. };
  43739. },{"./param-bytes-for-alg":227,"safe-buffer":561}],227:[function(require,module,exports){
  43740. 'use strict';
  43741. function getParamSize(keySize) {
  43742. var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);
  43743. return result;
  43744. }
  43745. var paramBytesForAlg = {
  43746. ES256: getParamSize(256),
  43747. ES384: getParamSize(384),
  43748. ES512: getParamSize(521)
  43749. };
  43750. function getParamBytesForAlg(alg) {
  43751. var paramBytes = paramBytesForAlg[alg];
  43752. if (paramBytes) {
  43753. return paramBytes;
  43754. }
  43755. throw new Error('Unknown algorithm "' + alg + '"');
  43756. }
  43757. module.exports = getParamBytesForAlg;
  43758. },{}],228:[function(require,module,exports){
  43759. 'use strict';
  43760. var elliptic = exports;
  43761. elliptic.version = require('../package.json').version;
  43762. elliptic.utils = require('./elliptic/utils');
  43763. elliptic.rand = require('brorand');
  43764. elliptic.curve = require('./elliptic/curve');
  43765. elliptic.curves = require('./elliptic/curves');
  43766. // Protocols
  43767. elliptic.ec = require('./elliptic/ec');
  43768. elliptic.eddsa = require('./elliptic/eddsa');
  43769. },{"../package.json":244,"./elliptic/curve":231,"./elliptic/curves":234,"./elliptic/ec":235,"./elliptic/eddsa":238,"./elliptic/utils":242,"brorand":143}],229:[function(require,module,exports){
  43770. 'use strict';
  43771. var BN = require('bn.js');
  43772. var utils = require('../utils');
  43773. var getNAF = utils.getNAF;
  43774. var getJSF = utils.getJSF;
  43775. var assert = utils.assert;
  43776. function BaseCurve(type, conf) {
  43777. this.type = type;
  43778. this.p = new BN(conf.p, 16);
  43779. // Use Montgomery, when there is no fast reduction for the prime
  43780. this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
  43781. // Useful for many curves
  43782. this.zero = new BN(0).toRed(this.red);
  43783. this.one = new BN(1).toRed(this.red);
  43784. this.two = new BN(2).toRed(this.red);
  43785. // Curve configuration, optional
  43786. this.n = conf.n && new BN(conf.n, 16);
  43787. this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
  43788. // Temporary arrays
  43789. this._wnafT1 = new Array(4);
  43790. this._wnafT2 = new Array(4);
  43791. this._wnafT3 = new Array(4);
  43792. this._wnafT4 = new Array(4);
  43793. this._bitLength = this.n ? this.n.bitLength() : 0;
  43794. // Generalized Greg Maxwell's trick
  43795. var adjustCount = this.n && this.p.div(this.n);
  43796. if (!adjustCount || adjustCount.cmpn(100) > 0) {
  43797. this.redN = null;
  43798. } else {
  43799. this._maxwellTrick = true;
  43800. this.redN = this.n.toRed(this.red);
  43801. }
  43802. }
  43803. module.exports = BaseCurve;
  43804. BaseCurve.prototype.point = function point() {
  43805. throw new Error('Not implemented');
  43806. };
  43807. BaseCurve.prototype.validate = function validate() {
  43808. throw new Error('Not implemented');
  43809. };
  43810. BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
  43811. assert(p.precomputed);
  43812. var doubles = p._getDoubles();
  43813. var naf = getNAF(k, 1, this._bitLength);
  43814. var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
  43815. I /= 3;
  43816. // Translate into more windowed form
  43817. var repr = [];
  43818. for (var j = 0; j < naf.length; j += doubles.step) {
  43819. var nafW = 0;
  43820. for (var k = j + doubles.step - 1; k >= j; k--)
  43821. nafW = (nafW << 1) + naf[k];
  43822. repr.push(nafW);
  43823. }
  43824. var a = this.jpoint(null, null, null);
  43825. var b = this.jpoint(null, null, null);
  43826. for (var i = I; i > 0; i--) {
  43827. for (var j = 0; j < repr.length; j++) {
  43828. var nafW = repr[j];
  43829. if (nafW === i)
  43830. b = b.mixedAdd(doubles.points[j]);
  43831. else if (nafW === -i)
  43832. b = b.mixedAdd(doubles.points[j].neg());
  43833. }
  43834. a = a.add(b);
  43835. }
  43836. return a.toP();
  43837. };
  43838. BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
  43839. var w = 4;
  43840. // Precompute window
  43841. var nafPoints = p._getNAFPoints(w);
  43842. w = nafPoints.wnd;
  43843. var wnd = nafPoints.points;
  43844. // Get NAF form
  43845. var naf = getNAF(k, w, this._bitLength);
  43846. // Add `this`*(N+1) for every w-NAF index
  43847. var acc = this.jpoint(null, null, null);
  43848. for (var i = naf.length - 1; i >= 0; i--) {
  43849. // Count zeroes
  43850. for (var k = 0; i >= 0 && naf[i] === 0; i--)
  43851. k++;
  43852. if (i >= 0)
  43853. k++;
  43854. acc = acc.dblp(k);
  43855. if (i < 0)
  43856. break;
  43857. var z = naf[i];
  43858. assert(z !== 0);
  43859. if (p.type === 'affine') {
  43860. // J +- P
  43861. if (z > 0)
  43862. acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
  43863. else
  43864. acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
  43865. } else {
  43866. // J +- J
  43867. if (z > 0)
  43868. acc = acc.add(wnd[(z - 1) >> 1]);
  43869. else
  43870. acc = acc.add(wnd[(-z - 1) >> 1].neg());
  43871. }
  43872. }
  43873. return p.type === 'affine' ? acc.toP() : acc;
  43874. };
  43875. BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
  43876. points,
  43877. coeffs,
  43878. len,
  43879. jacobianResult) {
  43880. var wndWidth = this._wnafT1;
  43881. var wnd = this._wnafT2;
  43882. var naf = this._wnafT3;
  43883. // Fill all arrays
  43884. var max = 0;
  43885. for (var i = 0; i < len; i++) {
  43886. var p = points[i];
  43887. var nafPoints = p._getNAFPoints(defW);
  43888. wndWidth[i] = nafPoints.wnd;
  43889. wnd[i] = nafPoints.points;
  43890. }
  43891. // Comb small window NAFs
  43892. for (var i = len - 1; i >= 1; i -= 2) {
  43893. var a = i - 1;
  43894. var b = i;
  43895. if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
  43896. naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
  43897. naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
  43898. max = Math.max(naf[a].length, max);
  43899. max = Math.max(naf[b].length, max);
  43900. continue;
  43901. }
  43902. var comb = [
  43903. points[a], /* 1 */
  43904. null, /* 3 */
  43905. null, /* 5 */
  43906. points[b] /* 7 */
  43907. ];
  43908. // Try to avoid Projective points, if possible
  43909. if (points[a].y.cmp(points[b].y) === 0) {
  43910. comb[1] = points[a].add(points[b]);
  43911. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  43912. } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
  43913. comb[1] = points[a].toJ().mixedAdd(points[b]);
  43914. comb[2] = points[a].add(points[b].neg());
  43915. } else {
  43916. comb[1] = points[a].toJ().mixedAdd(points[b]);
  43917. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  43918. }
  43919. var index = [
  43920. -3, /* -1 -1 */
  43921. -1, /* -1 0 */
  43922. -5, /* -1 1 */
  43923. -7, /* 0 -1 */
  43924. 0, /* 0 0 */
  43925. 7, /* 0 1 */
  43926. 5, /* 1 -1 */
  43927. 1, /* 1 0 */
  43928. 3 /* 1 1 */
  43929. ];
  43930. var jsf = getJSF(coeffs[a], coeffs[b]);
  43931. max = Math.max(jsf[0].length, max);
  43932. naf[a] = new Array(max);
  43933. naf[b] = new Array(max);
  43934. for (var j = 0; j < max; j++) {
  43935. var ja = jsf[0][j] | 0;
  43936. var jb = jsf[1][j] | 0;
  43937. naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
  43938. naf[b][j] = 0;
  43939. wnd[a] = comb;
  43940. }
  43941. }
  43942. var acc = this.jpoint(null, null, null);
  43943. var tmp = this._wnafT4;
  43944. for (var i = max; i >= 0; i--) {
  43945. var k = 0;
  43946. while (i >= 0) {
  43947. var zero = true;
  43948. for (var j = 0; j < len; j++) {
  43949. tmp[j] = naf[j][i] | 0;
  43950. if (tmp[j] !== 0)
  43951. zero = false;
  43952. }
  43953. if (!zero)
  43954. break;
  43955. k++;
  43956. i--;
  43957. }
  43958. if (i >= 0)
  43959. k++;
  43960. acc = acc.dblp(k);
  43961. if (i < 0)
  43962. break;
  43963. for (var j = 0; j < len; j++) {
  43964. var z = tmp[j];
  43965. var p;
  43966. if (z === 0)
  43967. continue;
  43968. else if (z > 0)
  43969. p = wnd[j][(z - 1) >> 1];
  43970. else if (z < 0)
  43971. p = wnd[j][(-z - 1) >> 1].neg();
  43972. if (p.type === 'affine')
  43973. acc = acc.mixedAdd(p);
  43974. else
  43975. acc = acc.add(p);
  43976. }
  43977. }
  43978. // Zeroify references
  43979. for (var i = 0; i < len; i++)
  43980. wnd[i] = null;
  43981. if (jacobianResult)
  43982. return acc;
  43983. else
  43984. return acc.toP();
  43985. };
  43986. function BasePoint(curve, type) {
  43987. this.curve = curve;
  43988. this.type = type;
  43989. this.precomputed = null;
  43990. }
  43991. BaseCurve.BasePoint = BasePoint;
  43992. BasePoint.prototype.eq = function eq(/*other*/) {
  43993. throw new Error('Not implemented');
  43994. };
  43995. BasePoint.prototype.validate = function validate() {
  43996. return this.curve.validate(this);
  43997. };
  43998. BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  43999. bytes = utils.toArray(bytes, enc);
  44000. var len = this.p.byteLength();
  44001. // uncompressed, hybrid-odd, hybrid-even
  44002. if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
  44003. bytes.length - 1 === 2 * len) {
  44004. if (bytes[0] === 0x06)
  44005. assert(bytes[bytes.length - 1] % 2 === 0);
  44006. else if (bytes[0] === 0x07)
  44007. assert(bytes[bytes.length - 1] % 2 === 1);
  44008. var res = this.point(bytes.slice(1, 1 + len),
  44009. bytes.slice(1 + len, 1 + 2 * len));
  44010. return res;
  44011. } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
  44012. bytes.length - 1 === len) {
  44013. return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
  44014. }
  44015. throw new Error('Unknown point format');
  44016. };
  44017. BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
  44018. return this.encode(enc, true);
  44019. };
  44020. BasePoint.prototype._encode = function _encode(compact) {
  44021. var len = this.curve.p.byteLength();
  44022. var x = this.getX().toArray('be', len);
  44023. if (compact)
  44024. return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
  44025. return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
  44026. };
  44027. BasePoint.prototype.encode = function encode(enc, compact) {
  44028. return utils.encode(this._encode(compact), enc);
  44029. };
  44030. BasePoint.prototype.precompute = function precompute(power) {
  44031. if (this.precomputed)
  44032. return this;
  44033. var precomputed = {
  44034. doubles: null,
  44035. naf: null,
  44036. beta: null
  44037. };
  44038. precomputed.naf = this._getNAFPoints(8);
  44039. precomputed.doubles = this._getDoubles(4, power);
  44040. precomputed.beta = this._getBeta();
  44041. this.precomputed = precomputed;
  44042. return this;
  44043. };
  44044. BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
  44045. if (!this.precomputed)
  44046. return false;
  44047. var doubles = this.precomputed.doubles;
  44048. if (!doubles)
  44049. return false;
  44050. return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
  44051. };
  44052. BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
  44053. if (this.precomputed && this.precomputed.doubles)
  44054. return this.precomputed.doubles;
  44055. var doubles = [ this ];
  44056. var acc = this;
  44057. for (var i = 0; i < power; i += step) {
  44058. for (var j = 0; j < step; j++)
  44059. acc = acc.dbl();
  44060. doubles.push(acc);
  44061. }
  44062. return {
  44063. step: step,
  44064. points: doubles
  44065. };
  44066. };
  44067. BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
  44068. if (this.precomputed && this.precomputed.naf)
  44069. return this.precomputed.naf;
  44070. var res = [ this ];
  44071. var max = (1 << wnd) - 1;
  44072. var dbl = max === 1 ? null : this.dbl();
  44073. for (var i = 1; i < max; i++)
  44074. res[i] = res[i - 1].add(dbl);
  44075. return {
  44076. wnd: wnd,
  44077. points: res
  44078. };
  44079. };
  44080. BasePoint.prototype._getBeta = function _getBeta() {
  44081. return null;
  44082. };
  44083. BasePoint.prototype.dblp = function dblp(k) {
  44084. var r = this;
  44085. for (var i = 0; i < k; i++)
  44086. r = r.dbl();
  44087. return r;
  44088. };
  44089. },{"../utils":242,"bn.js":243}],230:[function(require,module,exports){
  44090. 'use strict';
  44091. var utils = require('../utils');
  44092. var BN = require('bn.js');
  44093. var inherits = require('inherits');
  44094. var Base = require('./base');
  44095. var assert = utils.assert;
  44096. function EdwardsCurve(conf) {
  44097. // NOTE: Important as we are creating point in Base.call()
  44098. this.twisted = (conf.a | 0) !== 1;
  44099. this.mOneA = this.twisted && (conf.a | 0) === -1;
  44100. this.extended = this.mOneA;
  44101. Base.call(this, 'edwards', conf);
  44102. this.a = new BN(conf.a, 16).umod(this.red.m);
  44103. this.a = this.a.toRed(this.red);
  44104. this.c = new BN(conf.c, 16).toRed(this.red);
  44105. this.c2 = this.c.redSqr();
  44106. this.d = new BN(conf.d, 16).toRed(this.red);
  44107. this.dd = this.d.redAdd(this.d);
  44108. assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
  44109. this.oneC = (conf.c | 0) === 1;
  44110. }
  44111. inherits(EdwardsCurve, Base);
  44112. module.exports = EdwardsCurve;
  44113. EdwardsCurve.prototype._mulA = function _mulA(num) {
  44114. if (this.mOneA)
  44115. return num.redNeg();
  44116. else
  44117. return this.a.redMul(num);
  44118. };
  44119. EdwardsCurve.prototype._mulC = function _mulC(num) {
  44120. if (this.oneC)
  44121. return num;
  44122. else
  44123. return this.c.redMul(num);
  44124. };
  44125. // Just for compatibility with Short curve
  44126. EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
  44127. return this.point(x, y, z, t);
  44128. };
  44129. EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
  44130. x = new BN(x, 16);
  44131. if (!x.red)
  44132. x = x.toRed(this.red);
  44133. var x2 = x.redSqr();
  44134. var rhs = this.c2.redSub(this.a.redMul(x2));
  44135. var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
  44136. var y2 = rhs.redMul(lhs.redInvm());
  44137. var y = y2.redSqrt();
  44138. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
  44139. throw new Error('invalid point');
  44140. var isOdd = y.fromRed().isOdd();
  44141. if (odd && !isOdd || !odd && isOdd)
  44142. y = y.redNeg();
  44143. return this.point(x, y);
  44144. };
  44145. EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
  44146. y = new BN(y, 16);
  44147. if (!y.red)
  44148. y = y.toRed(this.red);
  44149. // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
  44150. var y2 = y.redSqr();
  44151. var lhs = y2.redSub(this.c2);
  44152. var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
  44153. var x2 = lhs.redMul(rhs.redInvm());
  44154. if (x2.cmp(this.zero) === 0) {
  44155. if (odd)
  44156. throw new Error('invalid point');
  44157. else
  44158. return this.point(this.zero, y);
  44159. }
  44160. var x = x2.redSqrt();
  44161. if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
  44162. throw new Error('invalid point');
  44163. if (x.fromRed().isOdd() !== odd)
  44164. x = x.redNeg();
  44165. return this.point(x, y);
  44166. };
  44167. EdwardsCurve.prototype.validate = function validate(point) {
  44168. if (point.isInfinity())
  44169. return true;
  44170. // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
  44171. point.normalize();
  44172. var x2 = point.x.redSqr();
  44173. var y2 = point.y.redSqr();
  44174. var lhs = x2.redMul(this.a).redAdd(y2);
  44175. var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
  44176. return lhs.cmp(rhs) === 0;
  44177. };
  44178. function Point(curve, x, y, z, t) {
  44179. Base.BasePoint.call(this, curve, 'projective');
  44180. if (x === null && y === null && z === null) {
  44181. this.x = this.curve.zero;
  44182. this.y = this.curve.one;
  44183. this.z = this.curve.one;
  44184. this.t = this.curve.zero;
  44185. this.zOne = true;
  44186. } else {
  44187. this.x = new BN(x, 16);
  44188. this.y = new BN(y, 16);
  44189. this.z = z ? new BN(z, 16) : this.curve.one;
  44190. this.t = t && new BN(t, 16);
  44191. if (!this.x.red)
  44192. this.x = this.x.toRed(this.curve.red);
  44193. if (!this.y.red)
  44194. this.y = this.y.toRed(this.curve.red);
  44195. if (!this.z.red)
  44196. this.z = this.z.toRed(this.curve.red);
  44197. if (this.t && !this.t.red)
  44198. this.t = this.t.toRed(this.curve.red);
  44199. this.zOne = this.z === this.curve.one;
  44200. // Use extended coordinates
  44201. if (this.curve.extended && !this.t) {
  44202. this.t = this.x.redMul(this.y);
  44203. if (!this.zOne)
  44204. this.t = this.t.redMul(this.z.redInvm());
  44205. }
  44206. }
  44207. }
  44208. inherits(Point, Base.BasePoint);
  44209. EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  44210. return Point.fromJSON(this, obj);
  44211. };
  44212. EdwardsCurve.prototype.point = function point(x, y, z, t) {
  44213. return new Point(this, x, y, z, t);
  44214. };
  44215. Point.fromJSON = function fromJSON(curve, obj) {
  44216. return new Point(curve, obj[0], obj[1], obj[2]);
  44217. };
  44218. Point.prototype.inspect = function inspect() {
  44219. if (this.isInfinity())
  44220. return '<EC Point Infinity>';
  44221. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  44222. ' y: ' + this.y.fromRed().toString(16, 2) +
  44223. ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  44224. };
  44225. Point.prototype.isInfinity = function isInfinity() {
  44226. // XXX This code assumes that zero is always zero in red
  44227. return this.x.cmpn(0) === 0 &&
  44228. (this.y.cmp(this.z) === 0 ||
  44229. (this.zOne && this.y.cmp(this.curve.c) === 0));
  44230. };
  44231. Point.prototype._extDbl = function _extDbl() {
  44232. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  44233. // #doubling-dbl-2008-hwcd
  44234. // 4M + 4S
  44235. // A = X1^2
  44236. var a = this.x.redSqr();
  44237. // B = Y1^2
  44238. var b = this.y.redSqr();
  44239. // C = 2 * Z1^2
  44240. var c = this.z.redSqr();
  44241. c = c.redIAdd(c);
  44242. // D = a * A
  44243. var d = this.curve._mulA(a);
  44244. // E = (X1 + Y1)^2 - A - B
  44245. var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
  44246. // G = D + B
  44247. var g = d.redAdd(b);
  44248. // F = G - C
  44249. var f = g.redSub(c);
  44250. // H = D - B
  44251. var h = d.redSub(b);
  44252. // X3 = E * F
  44253. var nx = e.redMul(f);
  44254. // Y3 = G * H
  44255. var ny = g.redMul(h);
  44256. // T3 = E * H
  44257. var nt = e.redMul(h);
  44258. // Z3 = F * G
  44259. var nz = f.redMul(g);
  44260. return this.curve.point(nx, ny, nz, nt);
  44261. };
  44262. Point.prototype._projDbl = function _projDbl() {
  44263. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  44264. // #doubling-dbl-2008-bbjlp
  44265. // #doubling-dbl-2007-bl
  44266. // and others
  44267. // Generally 3M + 4S or 2M + 4S
  44268. // B = (X1 + Y1)^2
  44269. var b = this.x.redAdd(this.y).redSqr();
  44270. // C = X1^2
  44271. var c = this.x.redSqr();
  44272. // D = Y1^2
  44273. var d = this.y.redSqr();
  44274. var nx;
  44275. var ny;
  44276. var nz;
  44277. if (this.curve.twisted) {
  44278. // E = a * C
  44279. var e = this.curve._mulA(c);
  44280. // F = E + D
  44281. var f = e.redAdd(d);
  44282. if (this.zOne) {
  44283. // X3 = (B - C - D) * (F - 2)
  44284. nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
  44285. // Y3 = F * (E - D)
  44286. ny = f.redMul(e.redSub(d));
  44287. // Z3 = F^2 - 2 * F
  44288. nz = f.redSqr().redSub(f).redSub(f);
  44289. } else {
  44290. // H = Z1^2
  44291. var h = this.z.redSqr();
  44292. // J = F - 2 * H
  44293. var j = f.redSub(h).redISub(h);
  44294. // X3 = (B-C-D)*J
  44295. nx = b.redSub(c).redISub(d).redMul(j);
  44296. // Y3 = F * (E - D)
  44297. ny = f.redMul(e.redSub(d));
  44298. // Z3 = F * J
  44299. nz = f.redMul(j);
  44300. }
  44301. } else {
  44302. // E = C + D
  44303. var e = c.redAdd(d);
  44304. // H = (c * Z1)^2
  44305. var h = this.curve._mulC(this.z).redSqr();
  44306. // J = E - 2 * H
  44307. var j = e.redSub(h).redSub(h);
  44308. // X3 = c * (B - E) * J
  44309. nx = this.curve._mulC(b.redISub(e)).redMul(j);
  44310. // Y3 = c * E * (C - D)
  44311. ny = this.curve._mulC(e).redMul(c.redISub(d));
  44312. // Z3 = E * J
  44313. nz = e.redMul(j);
  44314. }
  44315. return this.curve.point(nx, ny, nz);
  44316. };
  44317. Point.prototype.dbl = function dbl() {
  44318. if (this.isInfinity())
  44319. return this;
  44320. // Double in extended coordinates
  44321. if (this.curve.extended)
  44322. return this._extDbl();
  44323. else
  44324. return this._projDbl();
  44325. };
  44326. Point.prototype._extAdd = function _extAdd(p) {
  44327. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  44328. // #addition-add-2008-hwcd-3
  44329. // 8M
  44330. // A = (Y1 - X1) * (Y2 - X2)
  44331. var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
  44332. // B = (Y1 + X1) * (Y2 + X2)
  44333. var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
  44334. // C = T1 * k * T2
  44335. var c = this.t.redMul(this.curve.dd).redMul(p.t);
  44336. // D = Z1 * 2 * Z2
  44337. var d = this.z.redMul(p.z.redAdd(p.z));
  44338. // E = B - A
  44339. var e = b.redSub(a);
  44340. // F = D - C
  44341. var f = d.redSub(c);
  44342. // G = D + C
  44343. var g = d.redAdd(c);
  44344. // H = B + A
  44345. var h = b.redAdd(a);
  44346. // X3 = E * F
  44347. var nx = e.redMul(f);
  44348. // Y3 = G * H
  44349. var ny = g.redMul(h);
  44350. // T3 = E * H
  44351. var nt = e.redMul(h);
  44352. // Z3 = F * G
  44353. var nz = f.redMul(g);
  44354. return this.curve.point(nx, ny, nz, nt);
  44355. };
  44356. Point.prototype._projAdd = function _projAdd(p) {
  44357. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  44358. // #addition-add-2008-bbjlp
  44359. // #addition-add-2007-bl
  44360. // 10M + 1S
  44361. // A = Z1 * Z2
  44362. var a = this.z.redMul(p.z);
  44363. // B = A^2
  44364. var b = a.redSqr();
  44365. // C = X1 * X2
  44366. var c = this.x.redMul(p.x);
  44367. // D = Y1 * Y2
  44368. var d = this.y.redMul(p.y);
  44369. // E = d * C * D
  44370. var e = this.curve.d.redMul(c).redMul(d);
  44371. // F = B - E
  44372. var f = b.redSub(e);
  44373. // G = B + E
  44374. var g = b.redAdd(e);
  44375. // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
  44376. var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
  44377. var nx = a.redMul(f).redMul(tmp);
  44378. var ny;
  44379. var nz;
  44380. if (this.curve.twisted) {
  44381. // Y3 = A * G * (D - a * C)
  44382. ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
  44383. // Z3 = F * G
  44384. nz = f.redMul(g);
  44385. } else {
  44386. // Y3 = A * G * (D - C)
  44387. ny = a.redMul(g).redMul(d.redSub(c));
  44388. // Z3 = c * F * G
  44389. nz = this.curve._mulC(f).redMul(g);
  44390. }
  44391. return this.curve.point(nx, ny, nz);
  44392. };
  44393. Point.prototype.add = function add(p) {
  44394. if (this.isInfinity())
  44395. return p;
  44396. if (p.isInfinity())
  44397. return this;
  44398. if (this.curve.extended)
  44399. return this._extAdd(p);
  44400. else
  44401. return this._projAdd(p);
  44402. };
  44403. Point.prototype.mul = function mul(k) {
  44404. if (this._hasDoubles(k))
  44405. return this.curve._fixedNafMul(this, k);
  44406. else
  44407. return this.curve._wnafMul(this, k);
  44408. };
  44409. Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
  44410. return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
  44411. };
  44412. Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
  44413. return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
  44414. };
  44415. Point.prototype.normalize = function normalize() {
  44416. if (this.zOne)
  44417. return this;
  44418. // Normalize coordinates
  44419. var zi = this.z.redInvm();
  44420. this.x = this.x.redMul(zi);
  44421. this.y = this.y.redMul(zi);
  44422. if (this.t)
  44423. this.t = this.t.redMul(zi);
  44424. this.z = this.curve.one;
  44425. this.zOne = true;
  44426. return this;
  44427. };
  44428. Point.prototype.neg = function neg() {
  44429. return this.curve.point(this.x.redNeg(),
  44430. this.y,
  44431. this.z,
  44432. this.t && this.t.redNeg());
  44433. };
  44434. Point.prototype.getX = function getX() {
  44435. this.normalize();
  44436. return this.x.fromRed();
  44437. };
  44438. Point.prototype.getY = function getY() {
  44439. this.normalize();
  44440. return this.y.fromRed();
  44441. };
  44442. Point.prototype.eq = function eq(other) {
  44443. return this === other ||
  44444. this.getX().cmp(other.getX()) === 0 &&
  44445. this.getY().cmp(other.getY()) === 0;
  44446. };
  44447. Point.prototype.eqXToP = function eqXToP(x) {
  44448. var rx = x.toRed(this.curve.red).redMul(this.z);
  44449. if (this.x.cmp(rx) === 0)
  44450. return true;
  44451. var xc = x.clone();
  44452. var t = this.curve.redN.redMul(this.z);
  44453. for (;;) {
  44454. xc.iadd(this.curve.n);
  44455. if (xc.cmp(this.curve.p) >= 0)
  44456. return false;
  44457. rx.redIAdd(t);
  44458. if (this.x.cmp(rx) === 0)
  44459. return true;
  44460. }
  44461. };
  44462. // Compatibility with BaseCurve
  44463. Point.prototype.toP = Point.prototype.normalize;
  44464. Point.prototype.mixedAdd = Point.prototype.add;
  44465. },{"../utils":242,"./base":229,"bn.js":243,"inherits":320}],231:[function(require,module,exports){
  44466. 'use strict';
  44467. var curve = exports;
  44468. curve.base = require('./base');
  44469. curve.short = require('./short');
  44470. curve.mont = require('./mont');
  44471. curve.edwards = require('./edwards');
  44472. },{"./base":229,"./edwards":230,"./mont":232,"./short":233}],232:[function(require,module,exports){
  44473. 'use strict';
  44474. var BN = require('bn.js');
  44475. var inherits = require('inherits');
  44476. var Base = require('./base');
  44477. var utils = require('../utils');
  44478. function MontCurve(conf) {
  44479. Base.call(this, 'mont', conf);
  44480. this.a = new BN(conf.a, 16).toRed(this.red);
  44481. this.b = new BN(conf.b, 16).toRed(this.red);
  44482. this.i4 = new BN(4).toRed(this.red).redInvm();
  44483. this.two = new BN(2).toRed(this.red);
  44484. this.a24 = this.i4.redMul(this.a.redAdd(this.two));
  44485. }
  44486. inherits(MontCurve, Base);
  44487. module.exports = MontCurve;
  44488. MontCurve.prototype.validate = function validate(point) {
  44489. var x = point.normalize().x;
  44490. var x2 = x.redSqr();
  44491. var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
  44492. var y = rhs.redSqrt();
  44493. return y.redSqr().cmp(rhs) === 0;
  44494. };
  44495. function Point(curve, x, z) {
  44496. Base.BasePoint.call(this, curve, 'projective');
  44497. if (x === null && z === null) {
  44498. this.x = this.curve.one;
  44499. this.z = this.curve.zero;
  44500. } else {
  44501. this.x = new BN(x, 16);
  44502. this.z = new BN(z, 16);
  44503. if (!this.x.red)
  44504. this.x = this.x.toRed(this.curve.red);
  44505. if (!this.z.red)
  44506. this.z = this.z.toRed(this.curve.red);
  44507. }
  44508. }
  44509. inherits(Point, Base.BasePoint);
  44510. MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  44511. return this.point(utils.toArray(bytes, enc), 1);
  44512. };
  44513. MontCurve.prototype.point = function point(x, z) {
  44514. return new Point(this, x, z);
  44515. };
  44516. MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  44517. return Point.fromJSON(this, obj);
  44518. };
  44519. Point.prototype.precompute = function precompute() {
  44520. // No-op
  44521. };
  44522. Point.prototype._encode = function _encode() {
  44523. return this.getX().toArray('be', this.curve.p.byteLength());
  44524. };
  44525. Point.fromJSON = function fromJSON(curve, obj) {
  44526. return new Point(curve, obj[0], obj[1] || curve.one);
  44527. };
  44528. Point.prototype.inspect = function inspect() {
  44529. if (this.isInfinity())
  44530. return '<EC Point Infinity>';
  44531. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  44532. ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  44533. };
  44534. Point.prototype.isInfinity = function isInfinity() {
  44535. // XXX This code assumes that zero is always zero in red
  44536. return this.z.cmpn(0) === 0;
  44537. };
  44538. Point.prototype.dbl = function dbl() {
  44539. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
  44540. // 2M + 2S + 4A
  44541. // A = X1 + Z1
  44542. var a = this.x.redAdd(this.z);
  44543. // AA = A^2
  44544. var aa = a.redSqr();
  44545. // B = X1 - Z1
  44546. var b = this.x.redSub(this.z);
  44547. // BB = B^2
  44548. var bb = b.redSqr();
  44549. // C = AA - BB
  44550. var c = aa.redSub(bb);
  44551. // X3 = AA * BB
  44552. var nx = aa.redMul(bb);
  44553. // Z3 = C * (BB + A24 * C)
  44554. var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
  44555. return this.curve.point(nx, nz);
  44556. };
  44557. Point.prototype.add = function add() {
  44558. throw new Error('Not supported on Montgomery curve');
  44559. };
  44560. Point.prototype.diffAdd = function diffAdd(p, diff) {
  44561. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
  44562. // 4M + 2S + 6A
  44563. // A = X2 + Z2
  44564. var a = this.x.redAdd(this.z);
  44565. // B = X2 - Z2
  44566. var b = this.x.redSub(this.z);
  44567. // C = X3 + Z3
  44568. var c = p.x.redAdd(p.z);
  44569. // D = X3 - Z3
  44570. var d = p.x.redSub(p.z);
  44571. // DA = D * A
  44572. var da = d.redMul(a);
  44573. // CB = C * B
  44574. var cb = c.redMul(b);
  44575. // X5 = Z1 * (DA + CB)^2
  44576. var nx = diff.z.redMul(da.redAdd(cb).redSqr());
  44577. // Z5 = X1 * (DA - CB)^2
  44578. var nz = diff.x.redMul(da.redISub(cb).redSqr());
  44579. return this.curve.point(nx, nz);
  44580. };
  44581. Point.prototype.mul = function mul(k) {
  44582. var t = k.clone();
  44583. var a = this; // (N / 2) * Q + Q
  44584. var b = this.curve.point(null, null); // (N / 2) * Q
  44585. var c = this; // Q
  44586. for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
  44587. bits.push(t.andln(1));
  44588. for (var i = bits.length - 1; i >= 0; i--) {
  44589. if (bits[i] === 0) {
  44590. // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
  44591. a = a.diffAdd(b, c);
  44592. // N * Q = 2 * ((N / 2) * Q + Q))
  44593. b = b.dbl();
  44594. } else {
  44595. // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
  44596. b = a.diffAdd(b, c);
  44597. // N * Q + Q = 2 * ((N / 2) * Q + Q)
  44598. a = a.dbl();
  44599. }
  44600. }
  44601. return b;
  44602. };
  44603. Point.prototype.mulAdd = function mulAdd() {
  44604. throw new Error('Not supported on Montgomery curve');
  44605. };
  44606. Point.prototype.jumlAdd = function jumlAdd() {
  44607. throw new Error('Not supported on Montgomery curve');
  44608. };
  44609. Point.prototype.eq = function eq(other) {
  44610. return this.getX().cmp(other.getX()) === 0;
  44611. };
  44612. Point.prototype.normalize = function normalize() {
  44613. this.x = this.x.redMul(this.z.redInvm());
  44614. this.z = this.curve.one;
  44615. return this;
  44616. };
  44617. Point.prototype.getX = function getX() {
  44618. // Normalize coordinates
  44619. this.normalize();
  44620. return this.x.fromRed();
  44621. };
  44622. },{"../utils":242,"./base":229,"bn.js":243,"inherits":320}],233:[function(require,module,exports){
  44623. 'use strict';
  44624. var utils = require('../utils');
  44625. var BN = require('bn.js');
  44626. var inherits = require('inherits');
  44627. var Base = require('./base');
  44628. var assert = utils.assert;
  44629. function ShortCurve(conf) {
  44630. Base.call(this, 'short', conf);
  44631. this.a = new BN(conf.a, 16).toRed(this.red);
  44632. this.b = new BN(conf.b, 16).toRed(this.red);
  44633. this.tinv = this.two.redInvm();
  44634. this.zeroA = this.a.fromRed().cmpn(0) === 0;
  44635. this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
  44636. // If the curve is endomorphic, precalculate beta and lambda
  44637. this.endo = this._getEndomorphism(conf);
  44638. this._endoWnafT1 = new Array(4);
  44639. this._endoWnafT2 = new Array(4);
  44640. }
  44641. inherits(ShortCurve, Base);
  44642. module.exports = ShortCurve;
  44643. ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
  44644. // No efficient endomorphism
  44645. if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
  44646. return;
  44647. // Compute beta and lambda, that lambda * P = (beta * Px; Py)
  44648. var beta;
  44649. var lambda;
  44650. if (conf.beta) {
  44651. beta = new BN(conf.beta, 16).toRed(this.red);
  44652. } else {
  44653. var betas = this._getEndoRoots(this.p);
  44654. // Choose the smallest beta
  44655. beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
  44656. beta = beta.toRed(this.red);
  44657. }
  44658. if (conf.lambda) {
  44659. lambda = new BN(conf.lambda, 16);
  44660. } else {
  44661. // Choose the lambda that is matching selected beta
  44662. var lambdas = this._getEndoRoots(this.n);
  44663. if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
  44664. lambda = lambdas[0];
  44665. } else {
  44666. lambda = lambdas[1];
  44667. assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
  44668. }
  44669. }
  44670. // Get basis vectors, used for balanced length-two representation
  44671. var basis;
  44672. if (conf.basis) {
  44673. basis = conf.basis.map(function(vec) {
  44674. return {
  44675. a: new BN(vec.a, 16),
  44676. b: new BN(vec.b, 16)
  44677. };
  44678. });
  44679. } else {
  44680. basis = this._getEndoBasis(lambda);
  44681. }
  44682. return {
  44683. beta: beta,
  44684. lambda: lambda,
  44685. basis: basis
  44686. };
  44687. };
  44688. ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
  44689. // Find roots of for x^2 + x + 1 in F
  44690. // Root = (-1 +- Sqrt(-3)) / 2
  44691. //
  44692. var red = num === this.p ? this.red : BN.mont(num);
  44693. var tinv = new BN(2).toRed(red).redInvm();
  44694. var ntinv = tinv.redNeg();
  44695. var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
  44696. var l1 = ntinv.redAdd(s).fromRed();
  44697. var l2 = ntinv.redSub(s).fromRed();
  44698. return [ l1, l2 ];
  44699. };
  44700. ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
  44701. // aprxSqrt >= sqrt(this.n)
  44702. var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
  44703. // 3.74
  44704. // Run EGCD, until r(L + 1) < aprxSqrt
  44705. var u = lambda;
  44706. var v = this.n.clone();
  44707. var x1 = new BN(1);
  44708. var y1 = new BN(0);
  44709. var x2 = new BN(0);
  44710. var y2 = new BN(1);
  44711. // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
  44712. var a0;
  44713. var b0;
  44714. // First vector
  44715. var a1;
  44716. var b1;
  44717. // Second vector
  44718. var a2;
  44719. var b2;
  44720. var prevR;
  44721. var i = 0;
  44722. var r;
  44723. var x;
  44724. while (u.cmpn(0) !== 0) {
  44725. var q = v.div(u);
  44726. r = v.sub(q.mul(u));
  44727. x = x2.sub(q.mul(x1));
  44728. var y = y2.sub(q.mul(y1));
  44729. if (!a1 && r.cmp(aprxSqrt) < 0) {
  44730. a0 = prevR.neg();
  44731. b0 = x1;
  44732. a1 = r.neg();
  44733. b1 = x;
  44734. } else if (a1 && ++i === 2) {
  44735. break;
  44736. }
  44737. prevR = r;
  44738. v = u;
  44739. u = r;
  44740. x2 = x1;
  44741. x1 = x;
  44742. y2 = y1;
  44743. y1 = y;
  44744. }
  44745. a2 = r.neg();
  44746. b2 = x;
  44747. var len1 = a1.sqr().add(b1.sqr());
  44748. var len2 = a2.sqr().add(b2.sqr());
  44749. if (len2.cmp(len1) >= 0) {
  44750. a2 = a0;
  44751. b2 = b0;
  44752. }
  44753. // Normalize signs
  44754. if (a1.negative) {
  44755. a1 = a1.neg();
  44756. b1 = b1.neg();
  44757. }
  44758. if (a2.negative) {
  44759. a2 = a2.neg();
  44760. b2 = b2.neg();
  44761. }
  44762. return [
  44763. { a: a1, b: b1 },
  44764. { a: a2, b: b2 }
  44765. ];
  44766. };
  44767. ShortCurve.prototype._endoSplit = function _endoSplit(k) {
  44768. var basis = this.endo.basis;
  44769. var v1 = basis[0];
  44770. var v2 = basis[1];
  44771. var c1 = v2.b.mul(k).divRound(this.n);
  44772. var c2 = v1.b.neg().mul(k).divRound(this.n);
  44773. var p1 = c1.mul(v1.a);
  44774. var p2 = c2.mul(v2.a);
  44775. var q1 = c1.mul(v1.b);
  44776. var q2 = c2.mul(v2.b);
  44777. // Calculate answer
  44778. var k1 = k.sub(p1).sub(p2);
  44779. var k2 = q1.add(q2).neg();
  44780. return { k1: k1, k2: k2 };
  44781. };
  44782. ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
  44783. x = new BN(x, 16);
  44784. if (!x.red)
  44785. x = x.toRed(this.red);
  44786. var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
  44787. var y = y2.redSqrt();
  44788. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
  44789. throw new Error('invalid point');
  44790. // XXX Is there any way to tell if the number is odd without converting it
  44791. // to non-red form?
  44792. var isOdd = y.fromRed().isOdd();
  44793. if (odd && !isOdd || !odd && isOdd)
  44794. y = y.redNeg();
  44795. return this.point(x, y);
  44796. };
  44797. ShortCurve.prototype.validate = function validate(point) {
  44798. if (point.inf)
  44799. return true;
  44800. var x = point.x;
  44801. var y = point.y;
  44802. var ax = this.a.redMul(x);
  44803. var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
  44804. return y.redSqr().redISub(rhs).cmpn(0) === 0;
  44805. };
  44806. ShortCurve.prototype._endoWnafMulAdd =
  44807. function _endoWnafMulAdd(points, coeffs, jacobianResult) {
  44808. var npoints = this._endoWnafT1;
  44809. var ncoeffs = this._endoWnafT2;
  44810. for (var i = 0; i < points.length; i++) {
  44811. var split = this._endoSplit(coeffs[i]);
  44812. var p = points[i];
  44813. var beta = p._getBeta();
  44814. if (split.k1.negative) {
  44815. split.k1.ineg();
  44816. p = p.neg(true);
  44817. }
  44818. if (split.k2.negative) {
  44819. split.k2.ineg();
  44820. beta = beta.neg(true);
  44821. }
  44822. npoints[i * 2] = p;
  44823. npoints[i * 2 + 1] = beta;
  44824. ncoeffs[i * 2] = split.k1;
  44825. ncoeffs[i * 2 + 1] = split.k2;
  44826. }
  44827. var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
  44828. // Clean-up references to points and coefficients
  44829. for (var j = 0; j < i * 2; j++) {
  44830. npoints[j] = null;
  44831. ncoeffs[j] = null;
  44832. }
  44833. return res;
  44834. };
  44835. function Point(curve, x, y, isRed) {
  44836. Base.BasePoint.call(this, curve, 'affine');
  44837. if (x === null && y === null) {
  44838. this.x = null;
  44839. this.y = null;
  44840. this.inf = true;
  44841. } else {
  44842. this.x = new BN(x, 16);
  44843. this.y = new BN(y, 16);
  44844. // Force redgomery representation when loading from JSON
  44845. if (isRed) {
  44846. this.x.forceRed(this.curve.red);
  44847. this.y.forceRed(this.curve.red);
  44848. }
  44849. if (!this.x.red)
  44850. this.x = this.x.toRed(this.curve.red);
  44851. if (!this.y.red)
  44852. this.y = this.y.toRed(this.curve.red);
  44853. this.inf = false;
  44854. }
  44855. }
  44856. inherits(Point, Base.BasePoint);
  44857. ShortCurve.prototype.point = function point(x, y, isRed) {
  44858. return new Point(this, x, y, isRed);
  44859. };
  44860. ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
  44861. return Point.fromJSON(this, obj, red);
  44862. };
  44863. Point.prototype._getBeta = function _getBeta() {
  44864. if (!this.curve.endo)
  44865. return;
  44866. var pre = this.precomputed;
  44867. if (pre && pre.beta)
  44868. return pre.beta;
  44869. var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
  44870. if (pre) {
  44871. var curve = this.curve;
  44872. var endoMul = function(p) {
  44873. return curve.point(p.x.redMul(curve.endo.beta), p.y);
  44874. };
  44875. pre.beta = beta;
  44876. beta.precomputed = {
  44877. beta: null,
  44878. naf: pre.naf && {
  44879. wnd: pre.naf.wnd,
  44880. points: pre.naf.points.map(endoMul)
  44881. },
  44882. doubles: pre.doubles && {
  44883. step: pre.doubles.step,
  44884. points: pre.doubles.points.map(endoMul)
  44885. }
  44886. };
  44887. }
  44888. return beta;
  44889. };
  44890. Point.prototype.toJSON = function toJSON() {
  44891. if (!this.precomputed)
  44892. return [ this.x, this.y ];
  44893. return [ this.x, this.y, this.precomputed && {
  44894. doubles: this.precomputed.doubles && {
  44895. step: this.precomputed.doubles.step,
  44896. points: this.precomputed.doubles.points.slice(1)
  44897. },
  44898. naf: this.precomputed.naf && {
  44899. wnd: this.precomputed.naf.wnd,
  44900. points: this.precomputed.naf.points.slice(1)
  44901. }
  44902. } ];
  44903. };
  44904. Point.fromJSON = function fromJSON(curve, obj, red) {
  44905. if (typeof obj === 'string')
  44906. obj = JSON.parse(obj);
  44907. var res = curve.point(obj[0], obj[1], red);
  44908. if (!obj[2])
  44909. return res;
  44910. function obj2point(obj) {
  44911. return curve.point(obj[0], obj[1], red);
  44912. }
  44913. var pre = obj[2];
  44914. res.precomputed = {
  44915. beta: null,
  44916. doubles: pre.doubles && {
  44917. step: pre.doubles.step,
  44918. points: [ res ].concat(pre.doubles.points.map(obj2point))
  44919. },
  44920. naf: pre.naf && {
  44921. wnd: pre.naf.wnd,
  44922. points: [ res ].concat(pre.naf.points.map(obj2point))
  44923. }
  44924. };
  44925. return res;
  44926. };
  44927. Point.prototype.inspect = function inspect() {
  44928. if (this.isInfinity())
  44929. return '<EC Point Infinity>';
  44930. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  44931. ' y: ' + this.y.fromRed().toString(16, 2) + '>';
  44932. };
  44933. Point.prototype.isInfinity = function isInfinity() {
  44934. return this.inf;
  44935. };
  44936. Point.prototype.add = function add(p) {
  44937. // O + P = P
  44938. if (this.inf)
  44939. return p;
  44940. // P + O = P
  44941. if (p.inf)
  44942. return this;
  44943. // P + P = 2P
  44944. if (this.eq(p))
  44945. return this.dbl();
  44946. // P + (-P) = O
  44947. if (this.neg().eq(p))
  44948. return this.curve.point(null, null);
  44949. // P + Q = O
  44950. if (this.x.cmp(p.x) === 0)
  44951. return this.curve.point(null, null);
  44952. var c = this.y.redSub(p.y);
  44953. if (c.cmpn(0) !== 0)
  44954. c = c.redMul(this.x.redSub(p.x).redInvm());
  44955. var nx = c.redSqr().redISub(this.x).redISub(p.x);
  44956. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  44957. return this.curve.point(nx, ny);
  44958. };
  44959. Point.prototype.dbl = function dbl() {
  44960. if (this.inf)
  44961. return this;
  44962. // 2P = O
  44963. var ys1 = this.y.redAdd(this.y);
  44964. if (ys1.cmpn(0) === 0)
  44965. return this.curve.point(null, null);
  44966. var a = this.curve.a;
  44967. var x2 = this.x.redSqr();
  44968. var dyinv = ys1.redInvm();
  44969. var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
  44970. var nx = c.redSqr().redISub(this.x.redAdd(this.x));
  44971. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  44972. return this.curve.point(nx, ny);
  44973. };
  44974. Point.prototype.getX = function getX() {
  44975. return this.x.fromRed();
  44976. };
  44977. Point.prototype.getY = function getY() {
  44978. return this.y.fromRed();
  44979. };
  44980. Point.prototype.mul = function mul(k) {
  44981. k = new BN(k, 16);
  44982. if (this.isInfinity())
  44983. return this;
  44984. else if (this._hasDoubles(k))
  44985. return this.curve._fixedNafMul(this, k);
  44986. else if (this.curve.endo)
  44987. return this.curve._endoWnafMulAdd([ this ], [ k ]);
  44988. else
  44989. return this.curve._wnafMul(this, k);
  44990. };
  44991. Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
  44992. var points = [ this, p2 ];
  44993. var coeffs = [ k1, k2 ];
  44994. if (this.curve.endo)
  44995. return this.curve._endoWnafMulAdd(points, coeffs);
  44996. else
  44997. return this.curve._wnafMulAdd(1, points, coeffs, 2);
  44998. };
  44999. Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
  45000. var points = [ this, p2 ];
  45001. var coeffs = [ k1, k2 ];
  45002. if (this.curve.endo)
  45003. return this.curve._endoWnafMulAdd(points, coeffs, true);
  45004. else
  45005. return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
  45006. };
  45007. Point.prototype.eq = function eq(p) {
  45008. return this === p ||
  45009. this.inf === p.inf &&
  45010. (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
  45011. };
  45012. Point.prototype.neg = function neg(_precompute) {
  45013. if (this.inf)
  45014. return this;
  45015. var res = this.curve.point(this.x, this.y.redNeg());
  45016. if (_precompute && this.precomputed) {
  45017. var pre = this.precomputed;
  45018. var negate = function(p) {
  45019. return p.neg();
  45020. };
  45021. res.precomputed = {
  45022. naf: pre.naf && {
  45023. wnd: pre.naf.wnd,
  45024. points: pre.naf.points.map(negate)
  45025. },
  45026. doubles: pre.doubles && {
  45027. step: pre.doubles.step,
  45028. points: pre.doubles.points.map(negate)
  45029. }
  45030. };
  45031. }
  45032. return res;
  45033. };
  45034. Point.prototype.toJ = function toJ() {
  45035. if (this.inf)
  45036. return this.curve.jpoint(null, null, null);
  45037. var res = this.curve.jpoint(this.x, this.y, this.curve.one);
  45038. return res;
  45039. };
  45040. function JPoint(curve, x, y, z) {
  45041. Base.BasePoint.call(this, curve, 'jacobian');
  45042. if (x === null && y === null && z === null) {
  45043. this.x = this.curve.one;
  45044. this.y = this.curve.one;
  45045. this.z = new BN(0);
  45046. } else {
  45047. this.x = new BN(x, 16);
  45048. this.y = new BN(y, 16);
  45049. this.z = new BN(z, 16);
  45050. }
  45051. if (!this.x.red)
  45052. this.x = this.x.toRed(this.curve.red);
  45053. if (!this.y.red)
  45054. this.y = this.y.toRed(this.curve.red);
  45055. if (!this.z.red)
  45056. this.z = this.z.toRed(this.curve.red);
  45057. this.zOne = this.z === this.curve.one;
  45058. }
  45059. inherits(JPoint, Base.BasePoint);
  45060. ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
  45061. return new JPoint(this, x, y, z);
  45062. };
  45063. JPoint.prototype.toP = function toP() {
  45064. if (this.isInfinity())
  45065. return this.curve.point(null, null);
  45066. var zinv = this.z.redInvm();
  45067. var zinv2 = zinv.redSqr();
  45068. var ax = this.x.redMul(zinv2);
  45069. var ay = this.y.redMul(zinv2).redMul(zinv);
  45070. return this.curve.point(ax, ay);
  45071. };
  45072. JPoint.prototype.neg = function neg() {
  45073. return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
  45074. };
  45075. JPoint.prototype.add = function add(p) {
  45076. // O + P = P
  45077. if (this.isInfinity())
  45078. return p;
  45079. // P + O = P
  45080. if (p.isInfinity())
  45081. return this;
  45082. // 12M + 4S + 7A
  45083. var pz2 = p.z.redSqr();
  45084. var z2 = this.z.redSqr();
  45085. var u1 = this.x.redMul(pz2);
  45086. var u2 = p.x.redMul(z2);
  45087. var s1 = this.y.redMul(pz2.redMul(p.z));
  45088. var s2 = p.y.redMul(z2.redMul(this.z));
  45089. var h = u1.redSub(u2);
  45090. var r = s1.redSub(s2);
  45091. if (h.cmpn(0) === 0) {
  45092. if (r.cmpn(0) !== 0)
  45093. return this.curve.jpoint(null, null, null);
  45094. else
  45095. return this.dbl();
  45096. }
  45097. var h2 = h.redSqr();
  45098. var h3 = h2.redMul(h);
  45099. var v = u1.redMul(h2);
  45100. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  45101. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  45102. var nz = this.z.redMul(p.z).redMul(h);
  45103. return this.curve.jpoint(nx, ny, nz);
  45104. };
  45105. JPoint.prototype.mixedAdd = function mixedAdd(p) {
  45106. // O + P = P
  45107. if (this.isInfinity())
  45108. return p.toJ();
  45109. // P + O = P
  45110. if (p.isInfinity())
  45111. return this;
  45112. // 8M + 3S + 7A
  45113. var z2 = this.z.redSqr();
  45114. var u1 = this.x;
  45115. var u2 = p.x.redMul(z2);
  45116. var s1 = this.y;
  45117. var s2 = p.y.redMul(z2).redMul(this.z);
  45118. var h = u1.redSub(u2);
  45119. var r = s1.redSub(s2);
  45120. if (h.cmpn(0) === 0) {
  45121. if (r.cmpn(0) !== 0)
  45122. return this.curve.jpoint(null, null, null);
  45123. else
  45124. return this.dbl();
  45125. }
  45126. var h2 = h.redSqr();
  45127. var h3 = h2.redMul(h);
  45128. var v = u1.redMul(h2);
  45129. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  45130. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  45131. var nz = this.z.redMul(h);
  45132. return this.curve.jpoint(nx, ny, nz);
  45133. };
  45134. JPoint.prototype.dblp = function dblp(pow) {
  45135. if (pow === 0)
  45136. return this;
  45137. if (this.isInfinity())
  45138. return this;
  45139. if (!pow)
  45140. return this.dbl();
  45141. if (this.curve.zeroA || this.curve.threeA) {
  45142. var r = this;
  45143. for (var i = 0; i < pow; i++)
  45144. r = r.dbl();
  45145. return r;
  45146. }
  45147. // 1M + 2S + 1A + N * (4S + 5M + 8A)
  45148. // N = 1 => 6M + 6S + 9A
  45149. var a = this.curve.a;
  45150. var tinv = this.curve.tinv;
  45151. var jx = this.x;
  45152. var jy = this.y;
  45153. var jz = this.z;
  45154. var jz4 = jz.redSqr().redSqr();
  45155. // Reuse results
  45156. var jyd = jy.redAdd(jy);
  45157. for (var i = 0; i < pow; i++) {
  45158. var jx2 = jx.redSqr();
  45159. var jyd2 = jyd.redSqr();
  45160. var jyd4 = jyd2.redSqr();
  45161. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  45162. var t1 = jx.redMul(jyd2);
  45163. var nx = c.redSqr().redISub(t1.redAdd(t1));
  45164. var t2 = t1.redISub(nx);
  45165. var dny = c.redMul(t2);
  45166. dny = dny.redIAdd(dny).redISub(jyd4);
  45167. var nz = jyd.redMul(jz);
  45168. if (i + 1 < pow)
  45169. jz4 = jz4.redMul(jyd4);
  45170. jx = nx;
  45171. jz = nz;
  45172. jyd = dny;
  45173. }
  45174. return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
  45175. };
  45176. JPoint.prototype.dbl = function dbl() {
  45177. if (this.isInfinity())
  45178. return this;
  45179. if (this.curve.zeroA)
  45180. return this._zeroDbl();
  45181. else if (this.curve.threeA)
  45182. return this._threeDbl();
  45183. else
  45184. return this._dbl();
  45185. };
  45186. JPoint.prototype._zeroDbl = function _zeroDbl() {
  45187. var nx;
  45188. var ny;
  45189. var nz;
  45190. // Z = 1
  45191. if (this.zOne) {
  45192. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  45193. // #doubling-mdbl-2007-bl
  45194. // 1M + 5S + 14A
  45195. // XX = X1^2
  45196. var xx = this.x.redSqr();
  45197. // YY = Y1^2
  45198. var yy = this.y.redSqr();
  45199. // YYYY = YY^2
  45200. var yyyy = yy.redSqr();
  45201. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  45202. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  45203. s = s.redIAdd(s);
  45204. // M = 3 * XX + a; a = 0
  45205. var m = xx.redAdd(xx).redIAdd(xx);
  45206. // T = M ^ 2 - 2*S
  45207. var t = m.redSqr().redISub(s).redISub(s);
  45208. // 8 * YYYY
  45209. var yyyy8 = yyyy.redIAdd(yyyy);
  45210. yyyy8 = yyyy8.redIAdd(yyyy8);
  45211. yyyy8 = yyyy8.redIAdd(yyyy8);
  45212. // X3 = T
  45213. nx = t;
  45214. // Y3 = M * (S - T) - 8 * YYYY
  45215. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  45216. // Z3 = 2*Y1
  45217. nz = this.y.redAdd(this.y);
  45218. } else {
  45219. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  45220. // #doubling-dbl-2009-l
  45221. // 2M + 5S + 13A
  45222. // A = X1^2
  45223. var a = this.x.redSqr();
  45224. // B = Y1^2
  45225. var b = this.y.redSqr();
  45226. // C = B^2
  45227. var c = b.redSqr();
  45228. // D = 2 * ((X1 + B)^2 - A - C)
  45229. var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
  45230. d = d.redIAdd(d);
  45231. // E = 3 * A
  45232. var e = a.redAdd(a).redIAdd(a);
  45233. // F = E^2
  45234. var f = e.redSqr();
  45235. // 8 * C
  45236. var c8 = c.redIAdd(c);
  45237. c8 = c8.redIAdd(c8);
  45238. c8 = c8.redIAdd(c8);
  45239. // X3 = F - 2 * D
  45240. nx = f.redISub(d).redISub(d);
  45241. // Y3 = E * (D - X3) - 8 * C
  45242. ny = e.redMul(d.redISub(nx)).redISub(c8);
  45243. // Z3 = 2 * Y1 * Z1
  45244. nz = this.y.redMul(this.z);
  45245. nz = nz.redIAdd(nz);
  45246. }
  45247. return this.curve.jpoint(nx, ny, nz);
  45248. };
  45249. JPoint.prototype._threeDbl = function _threeDbl() {
  45250. var nx;
  45251. var ny;
  45252. var nz;
  45253. // Z = 1
  45254. if (this.zOne) {
  45255. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
  45256. // #doubling-mdbl-2007-bl
  45257. // 1M + 5S + 15A
  45258. // XX = X1^2
  45259. var xx = this.x.redSqr();
  45260. // YY = Y1^2
  45261. var yy = this.y.redSqr();
  45262. // YYYY = YY^2
  45263. var yyyy = yy.redSqr();
  45264. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  45265. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  45266. s = s.redIAdd(s);
  45267. // M = 3 * XX + a
  45268. var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
  45269. // T = M^2 - 2 * S
  45270. var t = m.redSqr().redISub(s).redISub(s);
  45271. // X3 = T
  45272. nx = t;
  45273. // Y3 = M * (S - T) - 8 * YYYY
  45274. var yyyy8 = yyyy.redIAdd(yyyy);
  45275. yyyy8 = yyyy8.redIAdd(yyyy8);
  45276. yyyy8 = yyyy8.redIAdd(yyyy8);
  45277. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  45278. // Z3 = 2 * Y1
  45279. nz = this.y.redAdd(this.y);
  45280. } else {
  45281. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
  45282. // 3M + 5S
  45283. // delta = Z1^2
  45284. var delta = this.z.redSqr();
  45285. // gamma = Y1^2
  45286. var gamma = this.y.redSqr();
  45287. // beta = X1 * gamma
  45288. var beta = this.x.redMul(gamma);
  45289. // alpha = 3 * (X1 - delta) * (X1 + delta)
  45290. var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
  45291. alpha = alpha.redAdd(alpha).redIAdd(alpha);
  45292. // X3 = alpha^2 - 8 * beta
  45293. var beta4 = beta.redIAdd(beta);
  45294. beta4 = beta4.redIAdd(beta4);
  45295. var beta8 = beta4.redAdd(beta4);
  45296. nx = alpha.redSqr().redISub(beta8);
  45297. // Z3 = (Y1 + Z1)^2 - gamma - delta
  45298. nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
  45299. // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
  45300. var ggamma8 = gamma.redSqr();
  45301. ggamma8 = ggamma8.redIAdd(ggamma8);
  45302. ggamma8 = ggamma8.redIAdd(ggamma8);
  45303. ggamma8 = ggamma8.redIAdd(ggamma8);
  45304. ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
  45305. }
  45306. return this.curve.jpoint(nx, ny, nz);
  45307. };
  45308. JPoint.prototype._dbl = function _dbl() {
  45309. var a = this.curve.a;
  45310. // 4M + 6S + 10A
  45311. var jx = this.x;
  45312. var jy = this.y;
  45313. var jz = this.z;
  45314. var jz4 = jz.redSqr().redSqr();
  45315. var jx2 = jx.redSqr();
  45316. var jy2 = jy.redSqr();
  45317. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  45318. var jxd4 = jx.redAdd(jx);
  45319. jxd4 = jxd4.redIAdd(jxd4);
  45320. var t1 = jxd4.redMul(jy2);
  45321. var nx = c.redSqr().redISub(t1.redAdd(t1));
  45322. var t2 = t1.redISub(nx);
  45323. var jyd8 = jy2.redSqr();
  45324. jyd8 = jyd8.redIAdd(jyd8);
  45325. jyd8 = jyd8.redIAdd(jyd8);
  45326. jyd8 = jyd8.redIAdd(jyd8);
  45327. var ny = c.redMul(t2).redISub(jyd8);
  45328. var nz = jy.redAdd(jy).redMul(jz);
  45329. return this.curve.jpoint(nx, ny, nz);
  45330. };
  45331. JPoint.prototype.trpl = function trpl() {
  45332. if (!this.curve.zeroA)
  45333. return this.dbl().add(this);
  45334. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
  45335. // 5M + 10S + ...
  45336. // XX = X1^2
  45337. var xx = this.x.redSqr();
  45338. // YY = Y1^2
  45339. var yy = this.y.redSqr();
  45340. // ZZ = Z1^2
  45341. var zz = this.z.redSqr();
  45342. // YYYY = YY^2
  45343. var yyyy = yy.redSqr();
  45344. // M = 3 * XX + a * ZZ2; a = 0
  45345. var m = xx.redAdd(xx).redIAdd(xx);
  45346. // MM = M^2
  45347. var mm = m.redSqr();
  45348. // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
  45349. var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  45350. e = e.redIAdd(e);
  45351. e = e.redAdd(e).redIAdd(e);
  45352. e = e.redISub(mm);
  45353. // EE = E^2
  45354. var ee = e.redSqr();
  45355. // T = 16*YYYY
  45356. var t = yyyy.redIAdd(yyyy);
  45357. t = t.redIAdd(t);
  45358. t = t.redIAdd(t);
  45359. t = t.redIAdd(t);
  45360. // U = (M + E)^2 - MM - EE - T
  45361. var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
  45362. // X3 = 4 * (X1 * EE - 4 * YY * U)
  45363. var yyu4 = yy.redMul(u);
  45364. yyu4 = yyu4.redIAdd(yyu4);
  45365. yyu4 = yyu4.redIAdd(yyu4);
  45366. var nx = this.x.redMul(ee).redISub(yyu4);
  45367. nx = nx.redIAdd(nx);
  45368. nx = nx.redIAdd(nx);
  45369. // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
  45370. var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
  45371. ny = ny.redIAdd(ny);
  45372. ny = ny.redIAdd(ny);
  45373. ny = ny.redIAdd(ny);
  45374. // Z3 = (Z1 + E)^2 - ZZ - EE
  45375. var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
  45376. return this.curve.jpoint(nx, ny, nz);
  45377. };
  45378. JPoint.prototype.mul = function mul(k, kbase) {
  45379. k = new BN(k, kbase);
  45380. return this.curve._wnafMul(this, k);
  45381. };
  45382. JPoint.prototype.eq = function eq(p) {
  45383. if (p.type === 'affine')
  45384. return this.eq(p.toJ());
  45385. if (this === p)
  45386. return true;
  45387. // x1 * z2^2 == x2 * z1^2
  45388. var z2 = this.z.redSqr();
  45389. var pz2 = p.z.redSqr();
  45390. if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
  45391. return false;
  45392. // y1 * z2^3 == y2 * z1^3
  45393. var z3 = z2.redMul(this.z);
  45394. var pz3 = pz2.redMul(p.z);
  45395. return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
  45396. };
  45397. JPoint.prototype.eqXToP = function eqXToP(x) {
  45398. var zs = this.z.redSqr();
  45399. var rx = x.toRed(this.curve.red).redMul(zs);
  45400. if (this.x.cmp(rx) === 0)
  45401. return true;
  45402. var xc = x.clone();
  45403. var t = this.curve.redN.redMul(zs);
  45404. for (;;) {
  45405. xc.iadd(this.curve.n);
  45406. if (xc.cmp(this.curve.p) >= 0)
  45407. return false;
  45408. rx.redIAdd(t);
  45409. if (this.x.cmp(rx) === 0)
  45410. return true;
  45411. }
  45412. };
  45413. JPoint.prototype.inspect = function inspect() {
  45414. if (this.isInfinity())
  45415. return '<EC JPoint Infinity>';
  45416. return '<EC JPoint x: ' + this.x.toString(16, 2) +
  45417. ' y: ' + this.y.toString(16, 2) +
  45418. ' z: ' + this.z.toString(16, 2) + '>';
  45419. };
  45420. JPoint.prototype.isInfinity = function isInfinity() {
  45421. // XXX This code assumes that zero is always zero in red
  45422. return this.z.cmpn(0) === 0;
  45423. };
  45424. },{"../utils":242,"./base":229,"bn.js":243,"inherits":320}],234:[function(require,module,exports){
  45425. 'use strict';
  45426. var curves = exports;
  45427. var hash = require('hash.js');
  45428. var curve = require('./curve');
  45429. var utils = require('./utils');
  45430. var assert = utils.assert;
  45431. function PresetCurve(options) {
  45432. if (options.type === 'short')
  45433. this.curve = new curve.short(options);
  45434. else if (options.type === 'edwards')
  45435. this.curve = new curve.edwards(options);
  45436. else
  45437. this.curve = new curve.mont(options);
  45438. this.g = this.curve.g;
  45439. this.n = this.curve.n;
  45440. this.hash = options.hash;
  45441. assert(this.g.validate(), 'Invalid curve');
  45442. assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
  45443. }
  45444. curves.PresetCurve = PresetCurve;
  45445. function defineCurve(name, options) {
  45446. Object.defineProperty(curves, name, {
  45447. configurable: true,
  45448. enumerable: true,
  45449. get: function() {
  45450. var curve = new PresetCurve(options);
  45451. Object.defineProperty(curves, name, {
  45452. configurable: true,
  45453. enumerable: true,
  45454. value: curve
  45455. });
  45456. return curve;
  45457. }
  45458. });
  45459. }
  45460. defineCurve('p192', {
  45461. type: 'short',
  45462. prime: 'p192',
  45463. p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
  45464. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
  45465. b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
  45466. n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
  45467. hash: hash.sha256,
  45468. gRed: false,
  45469. g: [
  45470. '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
  45471. '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
  45472. ]
  45473. });
  45474. defineCurve('p224', {
  45475. type: 'short',
  45476. prime: 'p224',
  45477. p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
  45478. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
  45479. b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
  45480. n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
  45481. hash: hash.sha256,
  45482. gRed: false,
  45483. g: [
  45484. 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
  45485. 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
  45486. ]
  45487. });
  45488. defineCurve('p256', {
  45489. type: 'short',
  45490. prime: null,
  45491. p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
  45492. a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
  45493. b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
  45494. n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
  45495. hash: hash.sha256,
  45496. gRed: false,
  45497. g: [
  45498. '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
  45499. '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
  45500. ]
  45501. });
  45502. defineCurve('p384', {
  45503. type: 'short',
  45504. prime: null,
  45505. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  45506. 'fffffffe ffffffff 00000000 00000000 ffffffff',
  45507. a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  45508. 'fffffffe ffffffff 00000000 00000000 fffffffc',
  45509. b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
  45510. '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
  45511. n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
  45512. 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
  45513. hash: hash.sha384,
  45514. gRed: false,
  45515. g: [
  45516. 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
  45517. '5502f25d bf55296c 3a545e38 72760ab7',
  45518. '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
  45519. '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
  45520. ]
  45521. });
  45522. defineCurve('p521', {
  45523. type: 'short',
  45524. prime: null,
  45525. p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  45526. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  45527. 'ffffffff ffffffff ffffffff ffffffff ffffffff',
  45528. a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  45529. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  45530. 'ffffffff ffffffff ffffffff ffffffff fffffffc',
  45531. b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
  45532. '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
  45533. '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
  45534. n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  45535. 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
  45536. 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
  45537. hash: hash.sha512,
  45538. gRed: false,
  45539. g: [
  45540. '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
  45541. '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
  45542. 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
  45543. '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
  45544. '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
  45545. '3fad0761 353c7086 a272c240 88be9476 9fd16650'
  45546. ]
  45547. });
  45548. defineCurve('curve25519', {
  45549. type: 'mont',
  45550. prime: 'p25519',
  45551. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  45552. a: '76d06',
  45553. b: '1',
  45554. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  45555. hash: hash.sha256,
  45556. gRed: false,
  45557. g: [
  45558. '9'
  45559. ]
  45560. });
  45561. defineCurve('ed25519', {
  45562. type: 'edwards',
  45563. prime: 'p25519',
  45564. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  45565. a: '-1',
  45566. c: '1',
  45567. // -121665 * (121666^(-1)) (mod P)
  45568. d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
  45569. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  45570. hash: hash.sha256,
  45571. gRed: false,
  45572. g: [
  45573. '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
  45574. // 4/5
  45575. '6666666666666666666666666666666666666666666666666666666666666658'
  45576. ]
  45577. });
  45578. var pre;
  45579. try {
  45580. pre = require('./precomputed/secp256k1');
  45581. } catch (e) {
  45582. pre = undefined;
  45583. }
  45584. defineCurve('secp256k1', {
  45585. type: 'short',
  45586. prime: 'k256',
  45587. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
  45588. a: '0',
  45589. b: '7',
  45590. n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
  45591. h: '1',
  45592. hash: hash.sha256,
  45593. // Precomputed endomorphism
  45594. beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
  45595. lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
  45596. basis: [
  45597. {
  45598. a: '3086d221a7d46bcde86c90e49284eb15',
  45599. b: '-e4437ed6010e88286f547fa90abfe4c3'
  45600. },
  45601. {
  45602. a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
  45603. b: '3086d221a7d46bcde86c90e49284eb15'
  45604. }
  45605. ],
  45606. gRed: false,
  45607. g: [
  45608. '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
  45609. '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
  45610. pre
  45611. ]
  45612. });
  45613. },{"./curve":231,"./precomputed/secp256k1":241,"./utils":242,"hash.js":300}],235:[function(require,module,exports){
  45614. 'use strict';
  45615. var BN = require('bn.js');
  45616. var HmacDRBG = require('hmac-drbg');
  45617. var utils = require('../utils');
  45618. var curves = require('../curves');
  45619. var rand = require('brorand');
  45620. var assert = utils.assert;
  45621. var KeyPair = require('./key');
  45622. var Signature = require('./signature');
  45623. function EC(options) {
  45624. if (!(this instanceof EC))
  45625. return new EC(options);
  45626. // Shortcut `elliptic.ec(curve-name)`
  45627. if (typeof options === 'string') {
  45628. assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);
  45629. options = curves[options];
  45630. }
  45631. // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
  45632. if (options instanceof curves.PresetCurve)
  45633. options = { curve: options };
  45634. this.curve = options.curve.curve;
  45635. this.n = this.curve.n;
  45636. this.nh = this.n.ushrn(1);
  45637. this.g = this.curve.g;
  45638. // Point on curve
  45639. this.g = options.curve.g;
  45640. this.g.precompute(options.curve.n.bitLength() + 1);
  45641. // Hash for function for DRBG
  45642. this.hash = options.hash || options.curve.hash;
  45643. }
  45644. module.exports = EC;
  45645. EC.prototype.keyPair = function keyPair(options) {
  45646. return new KeyPair(this, options);
  45647. };
  45648. EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
  45649. return KeyPair.fromPrivate(this, priv, enc);
  45650. };
  45651. EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
  45652. return KeyPair.fromPublic(this, pub, enc);
  45653. };
  45654. EC.prototype.genKeyPair = function genKeyPair(options) {
  45655. if (!options)
  45656. options = {};
  45657. // Instantiate Hmac_DRBG
  45658. var drbg = new HmacDRBG({
  45659. hash: this.hash,
  45660. pers: options.pers,
  45661. persEnc: options.persEnc || 'utf8',
  45662. entropy: options.entropy || rand(this.hash.hmacStrength),
  45663. entropyEnc: options.entropy && options.entropyEnc || 'utf8',
  45664. nonce: this.n.toArray()
  45665. });
  45666. var bytes = this.n.byteLength();
  45667. var ns2 = this.n.sub(new BN(2));
  45668. do {
  45669. var priv = new BN(drbg.generate(bytes));
  45670. if (priv.cmp(ns2) > 0)
  45671. continue;
  45672. priv.iaddn(1);
  45673. return this.keyFromPrivate(priv);
  45674. } while (true);
  45675. };
  45676. EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
  45677. var delta = msg.byteLength() * 8 - this.n.bitLength();
  45678. if (delta > 0)
  45679. msg = msg.ushrn(delta);
  45680. if (!truncOnly && msg.cmp(this.n) >= 0)
  45681. return msg.sub(this.n);
  45682. else
  45683. return msg;
  45684. };
  45685. EC.prototype.sign = function sign(msg, key, enc, options) {
  45686. if (typeof enc === 'object') {
  45687. options = enc;
  45688. enc = null;
  45689. }
  45690. if (!options)
  45691. options = {};
  45692. key = this.keyFromPrivate(key, enc);
  45693. msg = this._truncateToN(new BN(msg, 16));
  45694. // Zero-extend key to provide enough entropy
  45695. var bytes = this.n.byteLength();
  45696. var bkey = key.getPrivate().toArray('be', bytes);
  45697. // Zero-extend nonce to have the same byte size as N
  45698. var nonce = msg.toArray('be', bytes);
  45699. // Instantiate Hmac_DRBG
  45700. var drbg = new HmacDRBG({
  45701. hash: this.hash,
  45702. entropy: bkey,
  45703. nonce: nonce,
  45704. pers: options.pers,
  45705. persEnc: options.persEnc || 'utf8'
  45706. });
  45707. // Number of bytes to generate
  45708. var ns1 = this.n.sub(new BN(1));
  45709. for (var iter = 0; true; iter++) {
  45710. var k = options.k ?
  45711. options.k(iter) :
  45712. new BN(drbg.generate(this.n.byteLength()));
  45713. k = this._truncateToN(k, true);
  45714. if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
  45715. continue;
  45716. var kp = this.g.mul(k);
  45717. if (kp.isInfinity())
  45718. continue;
  45719. var kpX = kp.getX();
  45720. var r = kpX.umod(this.n);
  45721. if (r.cmpn(0) === 0)
  45722. continue;
  45723. var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
  45724. s = s.umod(this.n);
  45725. if (s.cmpn(0) === 0)
  45726. continue;
  45727. var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
  45728. (kpX.cmp(r) !== 0 ? 2 : 0);
  45729. // Use complement of `s`, if it is > `n / 2`
  45730. if (options.canonical && s.cmp(this.nh) > 0) {
  45731. s = this.n.sub(s);
  45732. recoveryParam ^= 1;
  45733. }
  45734. return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
  45735. }
  45736. };
  45737. EC.prototype.verify = function verify(msg, signature, key, enc) {
  45738. msg = this._truncateToN(new BN(msg, 16));
  45739. key = this.keyFromPublic(key, enc);
  45740. signature = new Signature(signature, 'hex');
  45741. // Perform primitive values validation
  45742. var r = signature.r;
  45743. var s = signature.s;
  45744. if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
  45745. return false;
  45746. if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
  45747. return false;
  45748. // Validate signature
  45749. var sinv = s.invm(this.n);
  45750. var u1 = sinv.mul(msg).umod(this.n);
  45751. var u2 = sinv.mul(r).umod(this.n);
  45752. if (!this.curve._maxwellTrick) {
  45753. var p = this.g.mulAdd(u1, key.getPublic(), u2);
  45754. if (p.isInfinity())
  45755. return false;
  45756. return p.getX().umod(this.n).cmp(r) === 0;
  45757. }
  45758. // NOTE: Greg Maxwell's trick, inspired by:
  45759. // https://git.io/vad3K
  45760. var p = this.g.jmulAdd(u1, key.getPublic(), u2);
  45761. if (p.isInfinity())
  45762. return false;
  45763. // Compare `p.x` of Jacobian point with `r`,
  45764. // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
  45765. // inverse of `p.z^2`
  45766. return p.eqXToP(r);
  45767. };
  45768. EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
  45769. assert((3 & j) === j, 'The recovery param is more than two bits');
  45770. signature = new Signature(signature, enc);
  45771. var n = this.n;
  45772. var e = new BN(msg);
  45773. var r = signature.r;
  45774. var s = signature.s;
  45775. // A set LSB signifies that the y-coordinate is odd
  45776. var isYOdd = j & 1;
  45777. var isSecondKey = j >> 1;
  45778. if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
  45779. throw new Error('Unable to find sencond key candinate');
  45780. // 1.1. Let x = r + jn.
  45781. if (isSecondKey)
  45782. r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
  45783. else
  45784. r = this.curve.pointFromX(r, isYOdd);
  45785. var rInv = signature.r.invm(n);
  45786. var s1 = n.sub(e).mul(rInv).umod(n);
  45787. var s2 = s.mul(rInv).umod(n);
  45788. // 1.6.1 Compute Q = r^-1 (sR - eG)
  45789. // Q = r^-1 (sR + -eG)
  45790. return this.g.mulAdd(s1, r, s2);
  45791. };
  45792. EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
  45793. signature = new Signature(signature, enc);
  45794. if (signature.recoveryParam !== null)
  45795. return signature.recoveryParam;
  45796. for (var i = 0; i < 4; i++) {
  45797. var Qprime;
  45798. try {
  45799. Qprime = this.recoverPubKey(e, signature, i);
  45800. } catch (e) {
  45801. continue;
  45802. }
  45803. if (Qprime.eq(Q))
  45804. return i;
  45805. }
  45806. throw new Error('Unable to find valid recovery factor');
  45807. };
  45808. },{"../curves":234,"../utils":242,"./key":236,"./signature":237,"bn.js":243,"brorand":143,"hmac-drbg":312}],236:[function(require,module,exports){
  45809. 'use strict';
  45810. var BN = require('bn.js');
  45811. var utils = require('../utils');
  45812. var assert = utils.assert;
  45813. function KeyPair(ec, options) {
  45814. this.ec = ec;
  45815. this.priv = null;
  45816. this.pub = null;
  45817. // KeyPair(ec, { priv: ..., pub: ... })
  45818. if (options.priv)
  45819. this._importPrivate(options.priv, options.privEnc);
  45820. if (options.pub)
  45821. this._importPublic(options.pub, options.pubEnc);
  45822. }
  45823. module.exports = KeyPair;
  45824. KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
  45825. if (pub instanceof KeyPair)
  45826. return pub;
  45827. return new KeyPair(ec, {
  45828. pub: pub,
  45829. pubEnc: enc
  45830. });
  45831. };
  45832. KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
  45833. if (priv instanceof KeyPair)
  45834. return priv;
  45835. return new KeyPair(ec, {
  45836. priv: priv,
  45837. privEnc: enc
  45838. });
  45839. };
  45840. KeyPair.prototype.validate = function validate() {
  45841. var pub = this.getPublic();
  45842. if (pub.isInfinity())
  45843. return { result: false, reason: 'Invalid public key' };
  45844. if (!pub.validate())
  45845. return { result: false, reason: 'Public key is not a point' };
  45846. if (!pub.mul(this.ec.curve.n).isInfinity())
  45847. return { result: false, reason: 'Public key * N != O' };
  45848. return { result: true, reason: null };
  45849. };
  45850. KeyPair.prototype.getPublic = function getPublic(compact, enc) {
  45851. // compact is optional argument
  45852. if (typeof compact === 'string') {
  45853. enc = compact;
  45854. compact = null;
  45855. }
  45856. if (!this.pub)
  45857. this.pub = this.ec.g.mul(this.priv);
  45858. if (!enc)
  45859. return this.pub;
  45860. return this.pub.encode(enc, compact);
  45861. };
  45862. KeyPair.prototype.getPrivate = function getPrivate(enc) {
  45863. if (enc === 'hex')
  45864. return this.priv.toString(16, 2);
  45865. else
  45866. return this.priv;
  45867. };
  45868. KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
  45869. this.priv = new BN(key, enc || 16);
  45870. // Ensure that the priv won't be bigger than n, otherwise we may fail
  45871. // in fixed multiplication method
  45872. this.priv = this.priv.umod(this.ec.curve.n);
  45873. };
  45874. KeyPair.prototype._importPublic = function _importPublic(key, enc) {
  45875. if (key.x || key.y) {
  45876. // Montgomery points only have an `x` coordinate.
  45877. // Weierstrass/Edwards points on the other hand have both `x` and
  45878. // `y` coordinates.
  45879. if (this.ec.curve.type === 'mont') {
  45880. assert(key.x, 'Need x coordinate');
  45881. } else if (this.ec.curve.type === 'short' ||
  45882. this.ec.curve.type === 'edwards') {
  45883. assert(key.x && key.y, 'Need both x and y coordinate');
  45884. }
  45885. this.pub = this.ec.curve.point(key.x, key.y);
  45886. return;
  45887. }
  45888. this.pub = this.ec.curve.decodePoint(key, enc);
  45889. };
  45890. // ECDH
  45891. KeyPair.prototype.derive = function derive(pub) {
  45892. return pub.mul(this.priv).getX();
  45893. };
  45894. // ECDSA
  45895. KeyPair.prototype.sign = function sign(msg, enc, options) {
  45896. return this.ec.sign(msg, this, enc, options);
  45897. };
  45898. KeyPair.prototype.verify = function verify(msg, signature) {
  45899. return this.ec.verify(msg, signature, this);
  45900. };
  45901. KeyPair.prototype.inspect = function inspect() {
  45902. return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
  45903. ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
  45904. };
  45905. },{"../utils":242,"bn.js":243}],237:[function(require,module,exports){
  45906. 'use strict';
  45907. var BN = require('bn.js');
  45908. var utils = require('../utils');
  45909. var assert = utils.assert;
  45910. function Signature(options, enc) {
  45911. if (options instanceof Signature)
  45912. return options;
  45913. if (this._importDER(options, enc))
  45914. return;
  45915. assert(options.r && options.s, 'Signature without r or s');
  45916. this.r = new BN(options.r, 16);
  45917. this.s = new BN(options.s, 16);
  45918. if (options.recoveryParam === undefined)
  45919. this.recoveryParam = null;
  45920. else
  45921. this.recoveryParam = options.recoveryParam;
  45922. }
  45923. module.exports = Signature;
  45924. function Position() {
  45925. this.place = 0;
  45926. }
  45927. function getLength(buf, p) {
  45928. var initial = buf[p.place++];
  45929. if (!(initial & 0x80)) {
  45930. return initial;
  45931. }
  45932. var octetLen = initial & 0xf;
  45933. // Indefinite length or overflow
  45934. if (octetLen === 0 || octetLen > 4) {
  45935. return false;
  45936. }
  45937. var val = 0;
  45938. for (var i = 0, off = p.place; i < octetLen; i++, off++) {
  45939. val <<= 8;
  45940. val |= buf[off];
  45941. val >>>= 0;
  45942. }
  45943. // Leading zeroes
  45944. if (val <= 0x7f) {
  45945. return false;
  45946. }
  45947. p.place = off;
  45948. return val;
  45949. }
  45950. function rmPadding(buf) {
  45951. var i = 0;
  45952. var len = buf.length - 1;
  45953. while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
  45954. i++;
  45955. }
  45956. if (i === 0) {
  45957. return buf;
  45958. }
  45959. return buf.slice(i);
  45960. }
  45961. Signature.prototype._importDER = function _importDER(data, enc) {
  45962. data = utils.toArray(data, enc);
  45963. var p = new Position();
  45964. if (data[p.place++] !== 0x30) {
  45965. return false;
  45966. }
  45967. var len = getLength(data, p);
  45968. if (len === false) {
  45969. return false;
  45970. }
  45971. if ((len + p.place) !== data.length) {
  45972. return false;
  45973. }
  45974. if (data[p.place++] !== 0x02) {
  45975. return false;
  45976. }
  45977. var rlen = getLength(data, p);
  45978. if (rlen === false) {
  45979. return false;
  45980. }
  45981. var r = data.slice(p.place, rlen + p.place);
  45982. p.place += rlen;
  45983. if (data[p.place++] !== 0x02) {
  45984. return false;
  45985. }
  45986. var slen = getLength(data, p);
  45987. if (slen === false) {
  45988. return false;
  45989. }
  45990. if (data.length !== slen + p.place) {
  45991. return false;
  45992. }
  45993. var s = data.slice(p.place, slen + p.place);
  45994. if (r[0] === 0) {
  45995. if (r[1] & 0x80) {
  45996. r = r.slice(1);
  45997. } else {
  45998. // Leading zeroes
  45999. return false;
  46000. }
  46001. }
  46002. if (s[0] === 0) {
  46003. if (s[1] & 0x80) {
  46004. s = s.slice(1);
  46005. } else {
  46006. // Leading zeroes
  46007. return false;
  46008. }
  46009. }
  46010. this.r = new BN(r);
  46011. this.s = new BN(s);
  46012. this.recoveryParam = null;
  46013. return true;
  46014. };
  46015. function constructLength(arr, len) {
  46016. if (len < 0x80) {
  46017. arr.push(len);
  46018. return;
  46019. }
  46020. var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
  46021. arr.push(octets | 0x80);
  46022. while (--octets) {
  46023. arr.push((len >>> (octets << 3)) & 0xff);
  46024. }
  46025. arr.push(len);
  46026. }
  46027. Signature.prototype.toDER = function toDER(enc) {
  46028. var r = this.r.toArray();
  46029. var s = this.s.toArray();
  46030. // Pad values
  46031. if (r[0] & 0x80)
  46032. r = [ 0 ].concat(r);
  46033. // Pad values
  46034. if (s[0] & 0x80)
  46035. s = [ 0 ].concat(s);
  46036. r = rmPadding(r);
  46037. s = rmPadding(s);
  46038. while (!s[0] && !(s[1] & 0x80)) {
  46039. s = s.slice(1);
  46040. }
  46041. var arr = [ 0x02 ];
  46042. constructLength(arr, r.length);
  46043. arr = arr.concat(r);
  46044. arr.push(0x02);
  46045. constructLength(arr, s.length);
  46046. var backHalf = arr.concat(s);
  46047. var res = [ 0x30 ];
  46048. constructLength(res, backHalf.length);
  46049. res = res.concat(backHalf);
  46050. return utils.encode(res, enc);
  46051. };
  46052. },{"../utils":242,"bn.js":243}],238:[function(require,module,exports){
  46053. 'use strict';
  46054. var hash = require('hash.js');
  46055. var curves = require('../curves');
  46056. var utils = require('../utils');
  46057. var assert = utils.assert;
  46058. var parseBytes = utils.parseBytes;
  46059. var KeyPair = require('./key');
  46060. var Signature = require('./signature');
  46061. function EDDSA(curve) {
  46062. assert(curve === 'ed25519', 'only tested with ed25519 so far');
  46063. if (!(this instanceof EDDSA))
  46064. return new EDDSA(curve);
  46065. var curve = curves[curve].curve;
  46066. this.curve = curve;
  46067. this.g = curve.g;
  46068. this.g.precompute(curve.n.bitLength() + 1);
  46069. this.pointClass = curve.point().constructor;
  46070. this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
  46071. this.hash = hash.sha512;
  46072. }
  46073. module.exports = EDDSA;
  46074. /**
  46075. * @param {Array|String} message - message bytes
  46076. * @param {Array|String|KeyPair} secret - secret bytes or a keypair
  46077. * @returns {Signature} - signature
  46078. */
  46079. EDDSA.prototype.sign = function sign(message, secret) {
  46080. message = parseBytes(message);
  46081. var key = this.keyFromSecret(secret);
  46082. var r = this.hashInt(key.messagePrefix(), message);
  46083. var R = this.g.mul(r);
  46084. var Rencoded = this.encodePoint(R);
  46085. var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
  46086. .mul(key.priv());
  46087. var S = r.add(s_).umod(this.curve.n);
  46088. return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
  46089. };
  46090. /**
  46091. * @param {Array} message - message bytes
  46092. * @param {Array|String|Signature} sig - sig bytes
  46093. * @param {Array|String|Point|KeyPair} pub - public key
  46094. * @returns {Boolean} - true if public key matches sig of message
  46095. */
  46096. EDDSA.prototype.verify = function verify(message, sig, pub) {
  46097. message = parseBytes(message);
  46098. sig = this.makeSignature(sig);
  46099. var key = this.keyFromPublic(pub);
  46100. var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
  46101. var SG = this.g.mul(sig.S());
  46102. var RplusAh = sig.R().add(key.pub().mul(h));
  46103. return RplusAh.eq(SG);
  46104. };
  46105. EDDSA.prototype.hashInt = function hashInt() {
  46106. var hash = this.hash();
  46107. for (var i = 0; i < arguments.length; i++)
  46108. hash.update(arguments[i]);
  46109. return utils.intFromLE(hash.digest()).umod(this.curve.n);
  46110. };
  46111. EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
  46112. return KeyPair.fromPublic(this, pub);
  46113. };
  46114. EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
  46115. return KeyPair.fromSecret(this, secret);
  46116. };
  46117. EDDSA.prototype.makeSignature = function makeSignature(sig) {
  46118. if (sig instanceof Signature)
  46119. return sig;
  46120. return new Signature(this, sig);
  46121. };
  46122. /**
  46123. * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
  46124. *
  46125. * EDDSA defines methods for encoding and decoding points and integers. These are
  46126. * helper convenience methods, that pass along to utility functions implied
  46127. * parameters.
  46128. *
  46129. */
  46130. EDDSA.prototype.encodePoint = function encodePoint(point) {
  46131. var enc = point.getY().toArray('le', this.encodingLength);
  46132. enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
  46133. return enc;
  46134. };
  46135. EDDSA.prototype.decodePoint = function decodePoint(bytes) {
  46136. bytes = utils.parseBytes(bytes);
  46137. var lastIx = bytes.length - 1;
  46138. var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
  46139. var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
  46140. var y = utils.intFromLE(normed);
  46141. return this.curve.pointFromY(y, xIsOdd);
  46142. };
  46143. EDDSA.prototype.encodeInt = function encodeInt(num) {
  46144. return num.toArray('le', this.encodingLength);
  46145. };
  46146. EDDSA.prototype.decodeInt = function decodeInt(bytes) {
  46147. return utils.intFromLE(bytes);
  46148. };
  46149. EDDSA.prototype.isPoint = function isPoint(val) {
  46150. return val instanceof this.pointClass;
  46151. };
  46152. },{"../curves":234,"../utils":242,"./key":239,"./signature":240,"hash.js":300}],239:[function(require,module,exports){
  46153. 'use strict';
  46154. var utils = require('../utils');
  46155. var assert = utils.assert;
  46156. var parseBytes = utils.parseBytes;
  46157. var cachedProperty = utils.cachedProperty;
  46158. /**
  46159. * @param {EDDSA} eddsa - instance
  46160. * @param {Object} params - public/private key parameters
  46161. *
  46162. * @param {Array<Byte>} [params.secret] - secret seed bytes
  46163. * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
  46164. * @param {Array<Byte>} [params.pub] - public key point encoded as bytes
  46165. *
  46166. */
  46167. function KeyPair(eddsa, params) {
  46168. this.eddsa = eddsa;
  46169. this._secret = parseBytes(params.secret);
  46170. if (eddsa.isPoint(params.pub))
  46171. this._pub = params.pub;
  46172. else
  46173. this._pubBytes = parseBytes(params.pub);
  46174. }
  46175. KeyPair.fromPublic = function fromPublic(eddsa, pub) {
  46176. if (pub instanceof KeyPair)
  46177. return pub;
  46178. return new KeyPair(eddsa, { pub: pub });
  46179. };
  46180. KeyPair.fromSecret = function fromSecret(eddsa, secret) {
  46181. if (secret instanceof KeyPair)
  46182. return secret;
  46183. return new KeyPair(eddsa, { secret: secret });
  46184. };
  46185. KeyPair.prototype.secret = function secret() {
  46186. return this._secret;
  46187. };
  46188. cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
  46189. return this.eddsa.encodePoint(this.pub());
  46190. });
  46191. cachedProperty(KeyPair, 'pub', function pub() {
  46192. if (this._pubBytes)
  46193. return this.eddsa.decodePoint(this._pubBytes);
  46194. return this.eddsa.g.mul(this.priv());
  46195. });
  46196. cachedProperty(KeyPair, 'privBytes', function privBytes() {
  46197. var eddsa = this.eddsa;
  46198. var hash = this.hash();
  46199. var lastIx = eddsa.encodingLength - 1;
  46200. var a = hash.slice(0, eddsa.encodingLength);
  46201. a[0] &= 248;
  46202. a[lastIx] &= 127;
  46203. a[lastIx] |= 64;
  46204. return a;
  46205. });
  46206. cachedProperty(KeyPair, 'priv', function priv() {
  46207. return this.eddsa.decodeInt(this.privBytes());
  46208. });
  46209. cachedProperty(KeyPair, 'hash', function hash() {
  46210. return this.eddsa.hash().update(this.secret()).digest();
  46211. });
  46212. cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
  46213. return this.hash().slice(this.eddsa.encodingLength);
  46214. });
  46215. KeyPair.prototype.sign = function sign(message) {
  46216. assert(this._secret, 'KeyPair can only verify');
  46217. return this.eddsa.sign(message, this);
  46218. };
  46219. KeyPair.prototype.verify = function verify(message, sig) {
  46220. return this.eddsa.verify(message, sig, this);
  46221. };
  46222. KeyPair.prototype.getSecret = function getSecret(enc) {
  46223. assert(this._secret, 'KeyPair is public only');
  46224. return utils.encode(this.secret(), enc);
  46225. };
  46226. KeyPair.prototype.getPublic = function getPublic(enc) {
  46227. return utils.encode(this.pubBytes(), enc);
  46228. };
  46229. module.exports = KeyPair;
  46230. },{"../utils":242}],240:[function(require,module,exports){
  46231. 'use strict';
  46232. var BN = require('bn.js');
  46233. var utils = require('../utils');
  46234. var assert = utils.assert;
  46235. var cachedProperty = utils.cachedProperty;
  46236. var parseBytes = utils.parseBytes;
  46237. /**
  46238. * @param {EDDSA} eddsa - eddsa instance
  46239. * @param {Array<Bytes>|Object} sig -
  46240. * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
  46241. * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
  46242. * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
  46243. * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
  46244. */
  46245. function Signature(eddsa, sig) {
  46246. this.eddsa = eddsa;
  46247. if (typeof sig !== 'object')
  46248. sig = parseBytes(sig);
  46249. if (Array.isArray(sig)) {
  46250. sig = {
  46251. R: sig.slice(0, eddsa.encodingLength),
  46252. S: sig.slice(eddsa.encodingLength)
  46253. };
  46254. }
  46255. assert(sig.R && sig.S, 'Signature without R or S');
  46256. if (eddsa.isPoint(sig.R))
  46257. this._R = sig.R;
  46258. if (sig.S instanceof BN)
  46259. this._S = sig.S;
  46260. this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  46261. this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  46262. }
  46263. cachedProperty(Signature, 'S', function S() {
  46264. return this.eddsa.decodeInt(this.Sencoded());
  46265. });
  46266. cachedProperty(Signature, 'R', function R() {
  46267. return this.eddsa.decodePoint(this.Rencoded());
  46268. });
  46269. cachedProperty(Signature, 'Rencoded', function Rencoded() {
  46270. return this.eddsa.encodePoint(this.R());
  46271. });
  46272. cachedProperty(Signature, 'Sencoded', function Sencoded() {
  46273. return this.eddsa.encodeInt(this.S());
  46274. });
  46275. Signature.prototype.toBytes = function toBytes() {
  46276. return this.Rencoded().concat(this.Sencoded());
  46277. };
  46278. Signature.prototype.toHex = function toHex() {
  46279. return utils.encode(this.toBytes(), 'hex').toUpperCase();
  46280. };
  46281. module.exports = Signature;
  46282. },{"../utils":242,"bn.js":243}],241:[function(require,module,exports){
  46283. module.exports = {
  46284. doubles: {
  46285. step: 4,
  46286. points: [
  46287. [
  46288. 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
  46289. 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
  46290. ],
  46291. [
  46292. '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
  46293. '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
  46294. ],
  46295. [
  46296. '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
  46297. 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
  46298. ],
  46299. [
  46300. '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
  46301. '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
  46302. ],
  46303. [
  46304. '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
  46305. '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
  46306. ],
  46307. [
  46308. '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
  46309. '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
  46310. ],
  46311. [
  46312. 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
  46313. '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
  46314. ],
  46315. [
  46316. '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
  46317. 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
  46318. ],
  46319. [
  46320. 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
  46321. '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
  46322. ],
  46323. [
  46324. 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
  46325. 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
  46326. ],
  46327. [
  46328. 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
  46329. '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
  46330. ],
  46331. [
  46332. '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
  46333. '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
  46334. ],
  46335. [
  46336. '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
  46337. '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
  46338. ],
  46339. [
  46340. '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
  46341. '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
  46342. ],
  46343. [
  46344. '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
  46345. '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
  46346. ],
  46347. [
  46348. '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
  46349. '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
  46350. ],
  46351. [
  46352. '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
  46353. '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
  46354. ],
  46355. [
  46356. '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
  46357. '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
  46358. ],
  46359. [
  46360. '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
  46361. 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
  46362. ],
  46363. [
  46364. 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
  46365. '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
  46366. ],
  46367. [
  46368. 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
  46369. '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
  46370. ],
  46371. [
  46372. '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
  46373. '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
  46374. ],
  46375. [
  46376. '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
  46377. '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
  46378. ],
  46379. [
  46380. 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
  46381. '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
  46382. ],
  46383. [
  46384. '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
  46385. 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
  46386. ],
  46387. [
  46388. 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
  46389. '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
  46390. ],
  46391. [
  46392. 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
  46393. 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
  46394. ],
  46395. [
  46396. 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
  46397. '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
  46398. ],
  46399. [
  46400. 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
  46401. 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
  46402. ],
  46403. [
  46404. 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
  46405. '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
  46406. ],
  46407. [
  46408. '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
  46409. 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
  46410. ],
  46411. [
  46412. '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
  46413. '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
  46414. ],
  46415. [
  46416. 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
  46417. '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
  46418. ],
  46419. [
  46420. '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
  46421. 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
  46422. ],
  46423. [
  46424. 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
  46425. '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
  46426. ],
  46427. [
  46428. 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
  46429. '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
  46430. ],
  46431. [
  46432. 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
  46433. 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
  46434. ],
  46435. [
  46436. '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
  46437. '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
  46438. ],
  46439. [
  46440. '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
  46441. '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
  46442. ],
  46443. [
  46444. '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
  46445. 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
  46446. ],
  46447. [
  46448. '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
  46449. '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
  46450. ],
  46451. [
  46452. 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
  46453. '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
  46454. ],
  46455. [
  46456. '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
  46457. '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
  46458. ],
  46459. [
  46460. '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
  46461. 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
  46462. ],
  46463. [
  46464. '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
  46465. '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
  46466. ],
  46467. [
  46468. 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
  46469. '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
  46470. ],
  46471. [
  46472. '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
  46473. 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
  46474. ],
  46475. [
  46476. 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
  46477. 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
  46478. ],
  46479. [
  46480. 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
  46481. '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
  46482. ],
  46483. [
  46484. '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
  46485. 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
  46486. ],
  46487. [
  46488. '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
  46489. 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
  46490. ],
  46491. [
  46492. 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
  46493. '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
  46494. ],
  46495. [
  46496. 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
  46497. '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
  46498. ],
  46499. [
  46500. 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
  46501. '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
  46502. ],
  46503. [
  46504. '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
  46505. 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
  46506. ],
  46507. [
  46508. '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
  46509. '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
  46510. ],
  46511. [
  46512. 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
  46513. 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
  46514. ],
  46515. [
  46516. '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
  46517. 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
  46518. ],
  46519. [
  46520. '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
  46521. '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
  46522. ],
  46523. [
  46524. '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
  46525. '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
  46526. ],
  46527. [
  46528. 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
  46529. 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
  46530. ],
  46531. [
  46532. '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
  46533. '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
  46534. ],
  46535. [
  46536. '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
  46537. '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
  46538. ],
  46539. [
  46540. 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
  46541. '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
  46542. ],
  46543. [
  46544. 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
  46545. 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
  46546. ]
  46547. ]
  46548. },
  46549. naf: {
  46550. wnd: 7,
  46551. points: [
  46552. [
  46553. 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
  46554. '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
  46555. ],
  46556. [
  46557. '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
  46558. 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
  46559. ],
  46560. [
  46561. '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
  46562. '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
  46563. ],
  46564. [
  46565. 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
  46566. 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
  46567. ],
  46568. [
  46569. '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
  46570. 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
  46571. ],
  46572. [
  46573. 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
  46574. 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
  46575. ],
  46576. [
  46577. 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
  46578. '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
  46579. ],
  46580. [
  46581. 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
  46582. '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
  46583. ],
  46584. [
  46585. '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
  46586. '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
  46587. ],
  46588. [
  46589. '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
  46590. '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
  46591. ],
  46592. [
  46593. '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
  46594. '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
  46595. ],
  46596. [
  46597. '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
  46598. '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
  46599. ],
  46600. [
  46601. 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
  46602. 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
  46603. ],
  46604. [
  46605. 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
  46606. '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
  46607. ],
  46608. [
  46609. '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
  46610. 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
  46611. ],
  46612. [
  46613. '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
  46614. 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
  46615. ],
  46616. [
  46617. '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
  46618. '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
  46619. ],
  46620. [
  46621. '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
  46622. '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
  46623. ],
  46624. [
  46625. '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
  46626. '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
  46627. ],
  46628. [
  46629. '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
  46630. 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
  46631. ],
  46632. [
  46633. 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
  46634. 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
  46635. ],
  46636. [
  46637. '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
  46638. '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
  46639. ],
  46640. [
  46641. '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
  46642. '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
  46643. ],
  46644. [
  46645. 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
  46646. 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
  46647. ],
  46648. [
  46649. '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
  46650. '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
  46651. ],
  46652. [
  46653. 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
  46654. 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
  46655. ],
  46656. [
  46657. 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
  46658. 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
  46659. ],
  46660. [
  46661. '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
  46662. '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
  46663. ],
  46664. [
  46665. '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
  46666. '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
  46667. ],
  46668. [
  46669. '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
  46670. '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
  46671. ],
  46672. [
  46673. 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
  46674. '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
  46675. ],
  46676. [
  46677. '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
  46678. '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
  46679. ],
  46680. [
  46681. 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
  46682. '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
  46683. ],
  46684. [
  46685. '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
  46686. 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
  46687. ],
  46688. [
  46689. '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
  46690. 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
  46691. ],
  46692. [
  46693. 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
  46694. 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
  46695. ],
  46696. [
  46697. '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
  46698. '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
  46699. ],
  46700. [
  46701. '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
  46702. 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
  46703. ],
  46704. [
  46705. 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
  46706. 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
  46707. ],
  46708. [
  46709. '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
  46710. '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
  46711. ],
  46712. [
  46713. '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
  46714. 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
  46715. ],
  46716. [
  46717. '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
  46718. '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
  46719. ],
  46720. [
  46721. '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
  46722. 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
  46723. ],
  46724. [
  46725. 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
  46726. '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
  46727. ],
  46728. [
  46729. '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
  46730. '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
  46731. ],
  46732. [
  46733. '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
  46734. 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
  46735. ],
  46736. [
  46737. '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
  46738. 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
  46739. ],
  46740. [
  46741. 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
  46742. 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
  46743. ],
  46744. [
  46745. 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
  46746. 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
  46747. ],
  46748. [
  46749. '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
  46750. '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
  46751. ],
  46752. [
  46753. '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
  46754. '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
  46755. ],
  46756. [
  46757. 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
  46758. '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
  46759. ],
  46760. [
  46761. 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
  46762. 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
  46763. ],
  46764. [
  46765. '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
  46766. '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
  46767. ],
  46768. [
  46769. '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
  46770. '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
  46771. ],
  46772. [
  46773. 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
  46774. '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
  46775. ],
  46776. [
  46777. '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
  46778. '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
  46779. ],
  46780. [
  46781. 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
  46782. 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
  46783. ],
  46784. [
  46785. '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
  46786. 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
  46787. ],
  46788. [
  46789. '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
  46790. '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
  46791. ],
  46792. [
  46793. 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
  46794. '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
  46795. ],
  46796. [
  46797. 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
  46798. '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
  46799. ],
  46800. [
  46801. '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
  46802. '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
  46803. ],
  46804. [
  46805. '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
  46806. '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
  46807. ],
  46808. [
  46809. '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
  46810. 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
  46811. ],
  46812. [
  46813. '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
  46814. 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
  46815. ],
  46816. [
  46817. '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
  46818. '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
  46819. ],
  46820. [
  46821. '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
  46822. '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
  46823. ],
  46824. [
  46825. '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
  46826. '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
  46827. ],
  46828. [
  46829. '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
  46830. 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
  46831. ],
  46832. [
  46833. 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
  46834. 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
  46835. ],
  46836. [
  46837. '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
  46838. 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
  46839. ],
  46840. [
  46841. 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
  46842. '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
  46843. ],
  46844. [
  46845. 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
  46846. '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
  46847. ],
  46848. [
  46849. 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
  46850. '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
  46851. ],
  46852. [
  46853. 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
  46854. '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
  46855. ],
  46856. [
  46857. '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
  46858. 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
  46859. ],
  46860. [
  46861. '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
  46862. '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
  46863. ],
  46864. [
  46865. '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
  46866. 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
  46867. ],
  46868. [
  46869. 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
  46870. 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
  46871. ],
  46872. [
  46873. 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
  46874. '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
  46875. ],
  46876. [
  46877. 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
  46878. 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
  46879. ],
  46880. [
  46881. 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
  46882. '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
  46883. ],
  46884. [
  46885. '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
  46886. '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
  46887. ],
  46888. [
  46889. 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
  46890. '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
  46891. ],
  46892. [
  46893. 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
  46894. '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
  46895. ],
  46896. [
  46897. '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
  46898. '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
  46899. ],
  46900. [
  46901. '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
  46902. 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
  46903. ],
  46904. [
  46905. 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
  46906. '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
  46907. ],
  46908. [
  46909. 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
  46910. '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
  46911. ],
  46912. [
  46913. 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
  46914. '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
  46915. ],
  46916. [
  46917. '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
  46918. '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
  46919. ],
  46920. [
  46921. 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
  46922. 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
  46923. ],
  46924. [
  46925. '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
  46926. 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
  46927. ],
  46928. [
  46929. 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
  46930. 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
  46931. ],
  46932. [
  46933. 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
  46934. '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
  46935. ],
  46936. [
  46937. '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
  46938. 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
  46939. ],
  46940. [
  46941. 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
  46942. '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
  46943. ],
  46944. [
  46945. 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
  46946. '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
  46947. ],
  46948. [
  46949. 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
  46950. '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
  46951. ],
  46952. [
  46953. '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
  46954. 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
  46955. ],
  46956. [
  46957. '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
  46958. 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
  46959. ],
  46960. [
  46961. 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
  46962. '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
  46963. ],
  46964. [
  46965. '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
  46966. 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
  46967. ],
  46968. [
  46969. '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
  46970. '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
  46971. ],
  46972. [
  46973. '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
  46974. 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
  46975. ],
  46976. [
  46977. 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
  46978. 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
  46979. ],
  46980. [
  46981. '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
  46982. 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
  46983. ],
  46984. [
  46985. '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
  46986. '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
  46987. ],
  46988. [
  46989. '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
  46990. 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
  46991. ],
  46992. [
  46993. '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
  46994. '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
  46995. ],
  46996. [
  46997. 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
  46998. 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
  46999. ],
  47000. [
  47001. '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
  47002. '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
  47003. ],
  47004. [
  47005. 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
  47006. '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
  47007. ],
  47008. [
  47009. '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
  47010. '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
  47011. ],
  47012. [
  47013. 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
  47014. 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
  47015. ],
  47016. [
  47017. 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
  47018. '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
  47019. ],
  47020. [
  47021. 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
  47022. 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
  47023. ],
  47024. [
  47025. '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
  47026. 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
  47027. ],
  47028. [
  47029. '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
  47030. '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
  47031. ],
  47032. [
  47033. '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
  47034. 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
  47035. ],
  47036. [
  47037. '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
  47038. '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
  47039. ],
  47040. [
  47041. '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
  47042. '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
  47043. ],
  47044. [
  47045. '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
  47046. 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
  47047. ],
  47048. [
  47049. '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
  47050. '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
  47051. ],
  47052. [
  47053. '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
  47054. '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
  47055. ],
  47056. [
  47057. '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
  47058. '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
  47059. ]
  47060. ]
  47061. }
  47062. };
  47063. },{}],242:[function(require,module,exports){
  47064. 'use strict';
  47065. var utils = exports;
  47066. var BN = require('bn.js');
  47067. var minAssert = require('minimalistic-assert');
  47068. var minUtils = require('minimalistic-crypto-utils');
  47069. utils.assert = minAssert;
  47070. utils.toArray = minUtils.toArray;
  47071. utils.zero2 = minUtils.zero2;
  47072. utils.toHex = minUtils.toHex;
  47073. utils.encode = minUtils.encode;
  47074. // Represent num in a w-NAF form
  47075. function getNAF(num, w, bits) {
  47076. var naf = new Array(Math.max(num.bitLength(), bits) + 1);
  47077. naf.fill(0);
  47078. var ws = 1 << (w + 1);
  47079. var k = num.clone();
  47080. for (var i = 0; i < naf.length; i++) {
  47081. var z;
  47082. var mod = k.andln(ws - 1);
  47083. if (k.isOdd()) {
  47084. if (mod > (ws >> 1) - 1)
  47085. z = (ws >> 1) - mod;
  47086. else
  47087. z = mod;
  47088. k.isubn(z);
  47089. } else {
  47090. z = 0;
  47091. }
  47092. naf[i] = z;
  47093. k.iushrn(1);
  47094. }
  47095. return naf;
  47096. }
  47097. utils.getNAF = getNAF;
  47098. // Represent k1, k2 in a Joint Sparse Form
  47099. function getJSF(k1, k2) {
  47100. var jsf = [
  47101. [],
  47102. []
  47103. ];
  47104. k1 = k1.clone();
  47105. k2 = k2.clone();
  47106. var d1 = 0;
  47107. var d2 = 0;
  47108. while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
  47109. // First phase
  47110. var m14 = (k1.andln(3) + d1) & 3;
  47111. var m24 = (k2.andln(3) + d2) & 3;
  47112. if (m14 === 3)
  47113. m14 = -1;
  47114. if (m24 === 3)
  47115. m24 = -1;
  47116. var u1;
  47117. if ((m14 & 1) === 0) {
  47118. u1 = 0;
  47119. } else {
  47120. var m8 = (k1.andln(7) + d1) & 7;
  47121. if ((m8 === 3 || m8 === 5) && m24 === 2)
  47122. u1 = -m14;
  47123. else
  47124. u1 = m14;
  47125. }
  47126. jsf[0].push(u1);
  47127. var u2;
  47128. if ((m24 & 1) === 0) {
  47129. u2 = 0;
  47130. } else {
  47131. var m8 = (k2.andln(7) + d2) & 7;
  47132. if ((m8 === 3 || m8 === 5) && m14 === 2)
  47133. u2 = -m24;
  47134. else
  47135. u2 = m24;
  47136. }
  47137. jsf[1].push(u2);
  47138. // Second phase
  47139. if (2 * d1 === u1 + 1)
  47140. d1 = 1 - d1;
  47141. if (2 * d2 === u2 + 1)
  47142. d2 = 1 - d2;
  47143. k1.iushrn(1);
  47144. k2.iushrn(1);
  47145. }
  47146. return jsf;
  47147. }
  47148. utils.getJSF = getJSF;
  47149. function cachedProperty(obj, name, computer) {
  47150. var key = '_' + name;
  47151. obj.prototype[name] = function cachedProperty() {
  47152. return this[key] !== undefined ? this[key] :
  47153. this[key] = computer.call(this);
  47154. };
  47155. }
  47156. utils.cachedProperty = cachedProperty;
  47157. function parseBytes(bytes) {
  47158. return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
  47159. bytes;
  47160. }
  47161. utils.parseBytes = parseBytes;
  47162. function intFromLE(bytes) {
  47163. return new BN(bytes, 'hex', 'le');
  47164. }
  47165. utils.intFromLE = intFromLE;
  47166. },{"bn.js":243,"minimalistic-assert":345,"minimalistic-crypto-utils":346}],243:[function(require,module,exports){
  47167. arguments[4][97][0].apply(exports,arguments)
  47168. },{"buffer":144,"dup":97}],244:[function(require,module,exports){
  47169. module.exports={
  47170. "_from": "elliptic@^6.5.3",
  47171. "_id": "elliptic@6.5.3",
  47172. "_inBundle": false,
  47173. "_integrity": "sha512-IMqzv5wNQf+E6aHeIqATs0tOLeOTwj1QKbRcS3jBbYkl5oLAserA8yJTT7/VyHUYG91PRmPyeQDObKLPpeS4dw==",
  47174. "_location": "/elliptic",
  47175. "_phantomChildren": {},
  47176. "_requested": {
  47177. "type": "range",
  47178. "registry": true,
  47179. "raw": "elliptic@^6.5.3",
  47180. "name": "elliptic",
  47181. "escapedName": "elliptic",
  47182. "rawSpec": "^6.5.3",
  47183. "saveSpec": null,
  47184. "fetchSpec": "^6.5.3"
  47185. },
  47186. "_requiredBy": [
  47187. "/browserify-sign",
  47188. "/create-ecdh"
  47189. ],
  47190. "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.3.tgz",
  47191. "_shasum": "cb59eb2efdaf73a0bd78ccd7015a62ad6e0f93d6",
  47192. "_spec": "elliptic@^6.5.3",
  47193. "_where": "/home/dasimmet/repos/browserified/node_modules/browserify-sign",
  47194. "author": {
  47195. "name": "Fedor Indutny",
  47196. "email": "fedor@indutny.com"
  47197. },
  47198. "bugs": {
  47199. "url": "https://github.com/indutny/elliptic/issues"
  47200. },
  47201. "bundleDependencies": false,
  47202. "dependencies": {
  47203. "bn.js": "^4.4.0",
  47204. "brorand": "^1.0.1",
  47205. "hash.js": "^1.0.0",
  47206. "hmac-drbg": "^1.0.0",
  47207. "inherits": "^2.0.1",
  47208. "minimalistic-assert": "^1.0.0",
  47209. "minimalistic-crypto-utils": "^1.0.0"
  47210. },
  47211. "deprecated": false,
  47212. "description": "EC cryptography",
  47213. "devDependencies": {
  47214. "brfs": "^1.4.3",
  47215. "coveralls": "^3.0.8",
  47216. "grunt": "^1.0.4",
  47217. "grunt-browserify": "^5.0.0",
  47218. "grunt-cli": "^1.2.0",
  47219. "grunt-contrib-connect": "^1.0.0",
  47220. "grunt-contrib-copy": "^1.0.0",
  47221. "grunt-contrib-uglify": "^1.0.1",
  47222. "grunt-mocha-istanbul": "^3.0.1",
  47223. "grunt-saucelabs": "^9.0.1",
  47224. "istanbul": "^0.4.2",
  47225. "jscs": "^3.0.7",
  47226. "jshint": "^2.10.3",
  47227. "mocha": "^6.2.2"
  47228. },
  47229. "files": [
  47230. "lib"
  47231. ],
  47232. "homepage": "https://github.com/indutny/elliptic",
  47233. "keywords": [
  47234. "EC",
  47235. "Elliptic",
  47236. "curve",
  47237. "Cryptography"
  47238. ],
  47239. "license": "MIT",
  47240. "main": "lib/elliptic.js",
  47241. "name": "elliptic",
  47242. "repository": {
  47243. "type": "git",
  47244. "url": "git+ssh://git@github.com/indutny/elliptic.git"
  47245. },
  47246. "scripts": {
  47247. "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
  47248. "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
  47249. "lint": "npm run jscs && npm run jshint",
  47250. "test": "npm run lint && npm run unit",
  47251. "unit": "istanbul test _mocha --reporter=spec test/index.js",
  47252. "version": "grunt dist && git add dist/"
  47253. },
  47254. "version": "6.5.3"
  47255. }
  47256. },{}],245:[function(require,module,exports){
  47257. 'use strict';
  47258. /* globals
  47259. AggregateError,
  47260. Atomics,
  47261. FinalizationRegistry,
  47262. SharedArrayBuffer,
  47263. WeakRef,
  47264. */
  47265. var undefined;
  47266. var $SyntaxError = SyntaxError;
  47267. var $Function = Function;
  47268. var $TypeError = TypeError;
  47269. // eslint-disable-next-line consistent-return
  47270. var getEvalledConstructor = function (expressionSyntax) {
  47271. try {
  47272. // eslint-disable-next-line no-new-func
  47273. return Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
  47274. } catch (e) {}
  47275. };
  47276. var $gOPD = Object.getOwnPropertyDescriptor;
  47277. if ($gOPD) {
  47278. try {
  47279. $gOPD({}, '');
  47280. } catch (e) {
  47281. $gOPD = null; // this is IE 8, which has a broken gOPD
  47282. }
  47283. }
  47284. var throwTypeError = function () { throw new $TypeError(); };
  47285. var ThrowTypeError = $gOPD
  47286. ? (function () {
  47287. try {
  47288. // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
  47289. arguments.callee; // IE 8 does not throw here
  47290. return throwTypeError;
  47291. } catch (calleeThrows) {
  47292. try {
  47293. // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
  47294. return $gOPD(arguments, 'callee').get;
  47295. } catch (gOPDthrows) {
  47296. return throwTypeError;
  47297. }
  47298. }
  47299. }())
  47300. : throwTypeError;
  47301. var hasSymbols = require('has-symbols')();
  47302. var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
  47303. var asyncGenFunction = getEvalledConstructor('async function* () {}');
  47304. var asyncGenFunctionPrototype = asyncGenFunction ? asyncGenFunction.prototype : undefined;
  47305. var asyncGenPrototype = asyncGenFunctionPrototype ? asyncGenFunctionPrototype.prototype : undefined;
  47306. var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
  47307. var INTRINSICS = {
  47308. '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
  47309. '%Array%': Array,
  47310. '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
  47311. '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
  47312. '%AsyncFromSyncIteratorPrototype%': undefined,
  47313. '%AsyncFunction%': getEvalledConstructor('async function () {}'),
  47314. '%AsyncGenerator%': asyncGenFunctionPrototype,
  47315. '%AsyncGeneratorFunction%': asyncGenFunction,
  47316. '%AsyncIteratorPrototype%': asyncGenPrototype ? getProto(asyncGenPrototype) : undefined,
  47317. '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
  47318. '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
  47319. '%Boolean%': Boolean,
  47320. '%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
  47321. '%Date%': Date,
  47322. '%decodeURI%': decodeURI,
  47323. '%decodeURIComponent%': decodeURIComponent,
  47324. '%encodeURI%': encodeURI,
  47325. '%encodeURIComponent%': encodeURIComponent,
  47326. '%Error%': Error,
  47327. '%eval%': eval, // eslint-disable-line no-eval
  47328. '%EvalError%': EvalError,
  47329. '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
  47330. '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
  47331. '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
  47332. '%Function%': $Function,
  47333. '%GeneratorFunction%': getEvalledConstructor('function* () {}'),
  47334. '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
  47335. '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
  47336. '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
  47337. '%isFinite%': isFinite,
  47338. '%isNaN%': isNaN,
  47339. '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
  47340. '%JSON%': typeof JSON === 'object' ? JSON : undefined,
  47341. '%Map%': typeof Map === 'undefined' ? undefined : Map,
  47342. '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
  47343. '%Math%': Math,
  47344. '%Number%': Number,
  47345. '%Object%': Object,
  47346. '%parseFloat%': parseFloat,
  47347. '%parseInt%': parseInt,
  47348. '%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
  47349. '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
  47350. '%RangeError%': RangeError,
  47351. '%ReferenceError%': ReferenceError,
  47352. '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
  47353. '%RegExp%': RegExp,
  47354. '%Set%': typeof Set === 'undefined' ? undefined : Set,
  47355. '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
  47356. '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
  47357. '%String%': String,
  47358. '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
  47359. '%Symbol%': hasSymbols ? Symbol : undefined,
  47360. '%SyntaxError%': $SyntaxError,
  47361. '%ThrowTypeError%': ThrowTypeError,
  47362. '%TypedArray%': TypedArray,
  47363. '%TypeError%': $TypeError,
  47364. '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
  47365. '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
  47366. '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
  47367. '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
  47368. '%URIError%': URIError,
  47369. '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
  47370. '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
  47371. '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
  47372. };
  47373. var LEGACY_ALIASES = {
  47374. '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
  47375. '%ArrayPrototype%': ['Array', 'prototype'],
  47376. '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
  47377. '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
  47378. '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
  47379. '%ArrayProto_values%': ['Array', 'prototype', 'values'],
  47380. '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
  47381. '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
  47382. '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
  47383. '%BooleanPrototype%': ['Boolean', 'prototype'],
  47384. '%DataViewPrototype%': ['DataView', 'prototype'],
  47385. '%DatePrototype%': ['Date', 'prototype'],
  47386. '%ErrorPrototype%': ['Error', 'prototype'],
  47387. '%EvalErrorPrototype%': ['EvalError', 'prototype'],
  47388. '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
  47389. '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
  47390. '%FunctionPrototype%': ['Function', 'prototype'],
  47391. '%Generator%': ['GeneratorFunction', 'prototype'],
  47392. '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
  47393. '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
  47394. '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
  47395. '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
  47396. '%JSONParse%': ['JSON', 'parse'],
  47397. '%JSONStringify%': ['JSON', 'stringify'],
  47398. '%MapPrototype%': ['Map', 'prototype'],
  47399. '%NumberPrototype%': ['Number', 'prototype'],
  47400. '%ObjectPrototype%': ['Object', 'prototype'],
  47401. '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
  47402. '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
  47403. '%PromisePrototype%': ['Promise', 'prototype'],
  47404. '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
  47405. '%Promise_all%': ['Promise', 'all'],
  47406. '%Promise_reject%': ['Promise', 'reject'],
  47407. '%Promise_resolve%': ['Promise', 'resolve'],
  47408. '%RangeErrorPrototype%': ['RangeError', 'prototype'],
  47409. '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
  47410. '%RegExpPrototype%': ['RegExp', 'prototype'],
  47411. '%SetPrototype%': ['Set', 'prototype'],
  47412. '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
  47413. '%StringPrototype%': ['String', 'prototype'],
  47414. '%SymbolPrototype%': ['Symbol', 'prototype'],
  47415. '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
  47416. '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
  47417. '%TypeErrorPrototype%': ['TypeError', 'prototype'],
  47418. '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
  47419. '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
  47420. '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
  47421. '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
  47422. '%URIErrorPrototype%': ['URIError', 'prototype'],
  47423. '%WeakMapPrototype%': ['WeakMap', 'prototype'],
  47424. '%WeakSetPrototype%': ['WeakSet', 'prototype']
  47425. };
  47426. var bind = require('function-bind');
  47427. var hasOwn = require('has');
  47428. var $concat = bind.call(Function.call, Array.prototype.concat);
  47429. var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
  47430. var $replace = bind.call(Function.call, String.prototype.replace);
  47431. /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
  47432. var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
  47433. var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
  47434. var stringToPath = function stringToPath(string) {
  47435. var result = [];
  47436. $replace(string, rePropName, function (match, number, quote, subString) {
  47437. result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
  47438. });
  47439. return result;
  47440. };
  47441. /* end adaptation */
  47442. var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
  47443. var intrinsicName = name;
  47444. var alias;
  47445. if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
  47446. alias = LEGACY_ALIASES[intrinsicName];
  47447. intrinsicName = '%' + alias[0] + '%';
  47448. }
  47449. if (hasOwn(INTRINSICS, intrinsicName)) {
  47450. var value = INTRINSICS[intrinsicName];
  47451. if (typeof value === 'undefined' && !allowMissing) {
  47452. throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
  47453. }
  47454. return {
  47455. alias: alias,
  47456. name: intrinsicName,
  47457. value: value
  47458. };
  47459. }
  47460. throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
  47461. };
  47462. module.exports = function GetIntrinsic(name, allowMissing) {
  47463. if (typeof name !== 'string' || name.length === 0) {
  47464. throw new $TypeError('intrinsic name must be a non-empty string');
  47465. }
  47466. if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
  47467. throw new $TypeError('"allowMissing" argument must be a boolean');
  47468. }
  47469. var parts = stringToPath(name);
  47470. var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
  47471. var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
  47472. var intrinsicRealName = intrinsic.name;
  47473. var value = intrinsic.value;
  47474. var skipFurtherCaching = false;
  47475. var alias = intrinsic.alias;
  47476. if (alias) {
  47477. intrinsicBaseName = alias[0];
  47478. $spliceApply(parts, $concat([0, 1], alias));
  47479. }
  47480. for (var i = 1, isOwn = true; i < parts.length; i += 1) {
  47481. var part = parts[i];
  47482. if (part === 'constructor' || !isOwn) {
  47483. skipFurtherCaching = true;
  47484. }
  47485. intrinsicBaseName += '.' + part;
  47486. intrinsicRealName = '%' + intrinsicBaseName + '%';
  47487. if (hasOwn(INTRINSICS, intrinsicRealName)) {
  47488. value = INTRINSICS[intrinsicRealName];
  47489. } else if (value != null) {
  47490. if ($gOPD && (i + 1) >= parts.length) {
  47491. var desc = $gOPD(value, part);
  47492. isOwn = !!desc;
  47493. if (!allowMissing && !(part in value)) {
  47494. throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
  47495. }
  47496. // By convention, when a data property is converted to an accessor
  47497. // property to emulate a data property that does not suffer from
  47498. // the override mistake, that accessor's getter is marked with
  47499. // an `originalValue` property. Here, when we detect this, we
  47500. // uphold the illusion by pretending to see that original data
  47501. // property, i.e., returning the value rather than the getter
  47502. // itself.
  47503. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
  47504. value = desc.get;
  47505. } else {
  47506. value = value[part];
  47507. }
  47508. } else {
  47509. isOwn = hasOwn(value, part);
  47510. value = value[part];
  47511. }
  47512. if (isOwn && !skipFurtherCaching) {
  47513. INTRINSICS[intrinsicRealName] = value;
  47514. }
  47515. }
  47516. }
  47517. return value;
  47518. };
  47519. },{"function-bind":257,"has":282,"has-symbols":280}],246:[function(require,module,exports){
  47520. 'use strict';
  47521. var GetIntrinsic = require('../GetIntrinsic');
  47522. var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%');
  47523. if ($gOPD) {
  47524. try {
  47525. $gOPD([], 'length');
  47526. } catch (e) {
  47527. // IE 8 has a broken gOPD
  47528. $gOPD = null;
  47529. }
  47530. }
  47531. module.exports = $gOPD;
  47532. },{"../GetIntrinsic":245}],247:[function(require,module,exports){
  47533. // Copyright Joyent, Inc. and other Node contributors.
  47534. //
  47535. // Permission is hereby granted, free of charge, to any person obtaining a
  47536. // copy of this software and associated documentation files (the
  47537. // "Software"), to deal in the Software without restriction, including
  47538. // without limitation the rights to use, copy, modify, merge, publish,
  47539. // distribute, sublicense, and/or sell copies of the Software, and to permit
  47540. // persons to whom the Software is furnished to do so, subject to the
  47541. // following conditions:
  47542. //
  47543. // The above copyright notice and this permission notice shall be included
  47544. // in all copies or substantial portions of the Software.
  47545. //
  47546. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  47547. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  47548. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  47549. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  47550. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  47551. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  47552. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  47553. 'use strict';
  47554. var R = typeof Reflect === 'object' ? Reflect : null
  47555. var ReflectApply = R && typeof R.apply === 'function'
  47556. ? R.apply
  47557. : function ReflectApply(target, receiver, args) {
  47558. return Function.prototype.apply.call(target, receiver, args);
  47559. }
  47560. var ReflectOwnKeys
  47561. if (R && typeof R.ownKeys === 'function') {
  47562. ReflectOwnKeys = R.ownKeys
  47563. } else if (Object.getOwnPropertySymbols) {
  47564. ReflectOwnKeys = function ReflectOwnKeys(target) {
  47565. return Object.getOwnPropertyNames(target)
  47566. .concat(Object.getOwnPropertySymbols(target));
  47567. };
  47568. } else {
  47569. ReflectOwnKeys = function ReflectOwnKeys(target) {
  47570. return Object.getOwnPropertyNames(target);
  47571. };
  47572. }
  47573. function ProcessEmitWarning(warning) {
  47574. if (console && console.warn) console.warn(warning);
  47575. }
  47576. var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  47577. return value !== value;
  47578. }
  47579. function EventEmitter() {
  47580. EventEmitter.init.call(this);
  47581. }
  47582. module.exports = EventEmitter;
  47583. module.exports.once = once;
  47584. // Backwards-compat with node 0.10.x
  47585. EventEmitter.EventEmitter = EventEmitter;
  47586. EventEmitter.prototype._events = undefined;
  47587. EventEmitter.prototype._eventsCount = 0;
  47588. EventEmitter.prototype._maxListeners = undefined;
  47589. // By default EventEmitters will print a warning if more than 10 listeners are
  47590. // added to it. This is a useful default which helps finding memory leaks.
  47591. var defaultMaxListeners = 10;
  47592. function checkListener(listener) {
  47593. if (typeof listener !== 'function') {
  47594. throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  47595. }
  47596. }
  47597. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  47598. enumerable: true,
  47599. get: function() {
  47600. return defaultMaxListeners;
  47601. },
  47602. set: function(arg) {
  47603. if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
  47604. throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
  47605. }
  47606. defaultMaxListeners = arg;
  47607. }
  47608. });
  47609. EventEmitter.init = function() {
  47610. if (this._events === undefined ||
  47611. this._events === Object.getPrototypeOf(this)._events) {
  47612. this._events = Object.create(null);
  47613. this._eventsCount = 0;
  47614. }
  47615. this._maxListeners = this._maxListeners || undefined;
  47616. };
  47617. // Obviously not all Emitters should be limited to 10. This function allows
  47618. // that to be increased. Set to zero for unlimited.
  47619. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  47620. if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
  47621. throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  47622. }
  47623. this._maxListeners = n;
  47624. return this;
  47625. };
  47626. function _getMaxListeners(that) {
  47627. if (that._maxListeners === undefined)
  47628. return EventEmitter.defaultMaxListeners;
  47629. return that._maxListeners;
  47630. }
  47631. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  47632. return _getMaxListeners(this);
  47633. };
  47634. EventEmitter.prototype.emit = function emit(type) {
  47635. var args = [];
  47636. for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  47637. var doError = (type === 'error');
  47638. var events = this._events;
  47639. if (events !== undefined)
  47640. doError = (doError && events.error === undefined);
  47641. else if (!doError)
  47642. return false;
  47643. // If there is no 'error' event listener then throw.
  47644. if (doError) {
  47645. var er;
  47646. if (args.length > 0)
  47647. er = args[0];
  47648. if (er instanceof Error) {
  47649. // Note: The comments on the `throw` lines are intentional, they show
  47650. // up in Node's output if this results in an unhandled exception.
  47651. throw er; // Unhandled 'error' event
  47652. }
  47653. // At least give some kind of context to the user
  47654. var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
  47655. err.context = er;
  47656. throw err; // Unhandled 'error' event
  47657. }
  47658. var handler = events[type];
  47659. if (handler === undefined)
  47660. return false;
  47661. if (typeof handler === 'function') {
  47662. ReflectApply(handler, this, args);
  47663. } else {
  47664. var len = handler.length;
  47665. var listeners = arrayClone(handler, len);
  47666. for (var i = 0; i < len; ++i)
  47667. ReflectApply(listeners[i], this, args);
  47668. }
  47669. return true;
  47670. };
  47671. function _addListener(target, type, listener, prepend) {
  47672. var m;
  47673. var events;
  47674. var existing;
  47675. checkListener(listener);
  47676. events = target._events;
  47677. if (events === undefined) {
  47678. events = target._events = Object.create(null);
  47679. target._eventsCount = 0;
  47680. } else {
  47681. // To avoid recursion in the case that type === "newListener"! Before
  47682. // adding it to the listeners, first emit "newListener".
  47683. if (events.newListener !== undefined) {
  47684. target.emit('newListener', type,
  47685. listener.listener ? listener.listener : listener);
  47686. // Re-assign `events` because a newListener handler could have caused the
  47687. // this._events to be assigned to a new object
  47688. events = target._events;
  47689. }
  47690. existing = events[type];
  47691. }
  47692. if (existing === undefined) {
  47693. // Optimize the case of one listener. Don't need the extra array object.
  47694. existing = events[type] = listener;
  47695. ++target._eventsCount;
  47696. } else {
  47697. if (typeof existing === 'function') {
  47698. // Adding the second element, need to change to array.
  47699. existing = events[type] =
  47700. prepend ? [listener, existing] : [existing, listener];
  47701. // If we've already got an array, just append.
  47702. } else if (prepend) {
  47703. existing.unshift(listener);
  47704. } else {
  47705. existing.push(listener);
  47706. }
  47707. // Check for listener leak
  47708. m = _getMaxListeners(target);
  47709. if (m > 0 && existing.length > m && !existing.warned) {
  47710. existing.warned = true;
  47711. // No error code for this since it is a Warning
  47712. // eslint-disable-next-line no-restricted-syntax
  47713. var w = new Error('Possible EventEmitter memory leak detected. ' +
  47714. existing.length + ' ' + String(type) + ' listeners ' +
  47715. 'added. Use emitter.setMaxListeners() to ' +
  47716. 'increase limit');
  47717. w.name = 'MaxListenersExceededWarning';
  47718. w.emitter = target;
  47719. w.type = type;
  47720. w.count = existing.length;
  47721. ProcessEmitWarning(w);
  47722. }
  47723. }
  47724. return target;
  47725. }
  47726. EventEmitter.prototype.addListener = function addListener(type, listener) {
  47727. return _addListener(this, type, listener, false);
  47728. };
  47729. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  47730. EventEmitter.prototype.prependListener =
  47731. function prependListener(type, listener) {
  47732. return _addListener(this, type, listener, true);
  47733. };
  47734. function onceWrapper() {
  47735. if (!this.fired) {
  47736. this.target.removeListener(this.type, this.wrapFn);
  47737. this.fired = true;
  47738. if (arguments.length === 0)
  47739. return this.listener.call(this.target);
  47740. return this.listener.apply(this.target, arguments);
  47741. }
  47742. }
  47743. function _onceWrap(target, type, listener) {
  47744. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  47745. var wrapped = onceWrapper.bind(state);
  47746. wrapped.listener = listener;
  47747. state.wrapFn = wrapped;
  47748. return wrapped;
  47749. }
  47750. EventEmitter.prototype.once = function once(type, listener) {
  47751. checkListener(listener);
  47752. this.on(type, _onceWrap(this, type, listener));
  47753. return this;
  47754. };
  47755. EventEmitter.prototype.prependOnceListener =
  47756. function prependOnceListener(type, listener) {
  47757. checkListener(listener);
  47758. this.prependListener(type, _onceWrap(this, type, listener));
  47759. return this;
  47760. };
  47761. // Emits a 'removeListener' event if and only if the listener was removed.
  47762. EventEmitter.prototype.removeListener =
  47763. function removeListener(type, listener) {
  47764. var list, events, position, i, originalListener;
  47765. checkListener(listener);
  47766. events = this._events;
  47767. if (events === undefined)
  47768. return this;
  47769. list = events[type];
  47770. if (list === undefined)
  47771. return this;
  47772. if (list === listener || list.listener === listener) {
  47773. if (--this._eventsCount === 0)
  47774. this._events = Object.create(null);
  47775. else {
  47776. delete events[type];
  47777. if (events.removeListener)
  47778. this.emit('removeListener', type, list.listener || listener);
  47779. }
  47780. } else if (typeof list !== 'function') {
  47781. position = -1;
  47782. for (i = list.length - 1; i >= 0; i--) {
  47783. if (list[i] === listener || list[i].listener === listener) {
  47784. originalListener = list[i].listener;
  47785. position = i;
  47786. break;
  47787. }
  47788. }
  47789. if (position < 0)
  47790. return this;
  47791. if (position === 0)
  47792. list.shift();
  47793. else {
  47794. spliceOne(list, position);
  47795. }
  47796. if (list.length === 1)
  47797. events[type] = list[0];
  47798. if (events.removeListener !== undefined)
  47799. this.emit('removeListener', type, originalListener || listener);
  47800. }
  47801. return this;
  47802. };
  47803. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  47804. EventEmitter.prototype.removeAllListeners =
  47805. function removeAllListeners(type) {
  47806. var listeners, events, i;
  47807. events = this._events;
  47808. if (events === undefined)
  47809. return this;
  47810. // not listening for removeListener, no need to emit
  47811. if (events.removeListener === undefined) {
  47812. if (arguments.length === 0) {
  47813. this._events = Object.create(null);
  47814. this._eventsCount = 0;
  47815. } else if (events[type] !== undefined) {
  47816. if (--this._eventsCount === 0)
  47817. this._events = Object.create(null);
  47818. else
  47819. delete events[type];
  47820. }
  47821. return this;
  47822. }
  47823. // emit removeListener for all listeners on all events
  47824. if (arguments.length === 0) {
  47825. var keys = Object.keys(events);
  47826. var key;
  47827. for (i = 0; i < keys.length; ++i) {
  47828. key = keys[i];
  47829. if (key === 'removeListener') continue;
  47830. this.removeAllListeners(key);
  47831. }
  47832. this.removeAllListeners('removeListener');
  47833. this._events = Object.create(null);
  47834. this._eventsCount = 0;
  47835. return this;
  47836. }
  47837. listeners = events[type];
  47838. if (typeof listeners === 'function') {
  47839. this.removeListener(type, listeners);
  47840. } else if (listeners !== undefined) {
  47841. // LIFO order
  47842. for (i = listeners.length - 1; i >= 0; i--) {
  47843. this.removeListener(type, listeners[i]);
  47844. }
  47845. }
  47846. return this;
  47847. };
  47848. function _listeners(target, type, unwrap) {
  47849. var events = target._events;
  47850. if (events === undefined)
  47851. return [];
  47852. var evlistener = events[type];
  47853. if (evlistener === undefined)
  47854. return [];
  47855. if (typeof evlistener === 'function')
  47856. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  47857. return unwrap ?
  47858. unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  47859. }
  47860. EventEmitter.prototype.listeners = function listeners(type) {
  47861. return _listeners(this, type, true);
  47862. };
  47863. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  47864. return _listeners(this, type, false);
  47865. };
  47866. EventEmitter.listenerCount = function(emitter, type) {
  47867. if (typeof emitter.listenerCount === 'function') {
  47868. return emitter.listenerCount(type);
  47869. } else {
  47870. return listenerCount.call(emitter, type);
  47871. }
  47872. };
  47873. EventEmitter.prototype.listenerCount = listenerCount;
  47874. function listenerCount(type) {
  47875. var events = this._events;
  47876. if (events !== undefined) {
  47877. var evlistener = events[type];
  47878. if (typeof evlistener === 'function') {
  47879. return 1;
  47880. } else if (evlistener !== undefined) {
  47881. return evlistener.length;
  47882. }
  47883. }
  47884. return 0;
  47885. }
  47886. EventEmitter.prototype.eventNames = function eventNames() {
  47887. return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
  47888. };
  47889. function arrayClone(arr, n) {
  47890. var copy = new Array(n);
  47891. for (var i = 0; i < n; ++i)
  47892. copy[i] = arr[i];
  47893. return copy;
  47894. }
  47895. function spliceOne(list, index) {
  47896. for (; index + 1 < list.length; index++)
  47897. list[index] = list[index + 1];
  47898. list.pop();
  47899. }
  47900. function unwrapListeners(arr) {
  47901. var ret = new Array(arr.length);
  47902. for (var i = 0; i < ret.length; ++i) {
  47903. ret[i] = arr[i].listener || arr[i];
  47904. }
  47905. return ret;
  47906. }
  47907. function once(emitter, name) {
  47908. return new Promise(function (resolve, reject) {
  47909. function eventListener() {
  47910. if (errorListener !== undefined) {
  47911. emitter.removeListener('error', errorListener);
  47912. }
  47913. resolve([].slice.call(arguments));
  47914. };
  47915. var errorListener;
  47916. // Adding an error listener is not optional because
  47917. // if an error is thrown on an event emitter we cannot
  47918. // guarantee that the actual event we are waiting will
  47919. // be fired. The result could be a silent way to create
  47920. // memory or file descriptor leaks, which is something
  47921. // we should avoid.
  47922. if (name !== 'error') {
  47923. errorListener = function errorListener(err) {
  47924. emitter.removeListener(name, eventListener);
  47925. reject(err);
  47926. };
  47927. emitter.once('error', errorListener);
  47928. }
  47929. emitter.once(name, eventListener);
  47930. });
  47931. }
  47932. },{}],248:[function(require,module,exports){
  47933. var Buffer = require('safe-buffer').Buffer
  47934. var MD5 = require('md5.js')
  47935. /* eslint-disable camelcase */
  47936. function EVP_BytesToKey (password, salt, keyBits, ivLen) {
  47937. if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
  47938. if (salt) {
  47939. if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
  47940. if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
  47941. }
  47942. var keyLen = keyBits / 8
  47943. var key = Buffer.alloc(keyLen)
  47944. var iv = Buffer.alloc(ivLen || 0)
  47945. var tmp = Buffer.alloc(0)
  47946. while (keyLen > 0 || ivLen > 0) {
  47947. var hash = new MD5()
  47948. hash.update(tmp)
  47949. hash.update(password)
  47950. if (salt) hash.update(salt)
  47951. tmp = hash.digest()
  47952. var used = 0
  47953. if (keyLen > 0) {
  47954. var keyStart = key.length - keyLen
  47955. used = Math.min(keyLen, tmp.length)
  47956. tmp.copy(key, keyStart, 0, used)
  47957. keyLen -= used
  47958. }
  47959. if (used < tmp.length && ivLen > 0) {
  47960. var ivStart = iv.length - ivLen
  47961. var length = Math.min(ivLen, tmp.length - used)
  47962. tmp.copy(iv, ivStart, used, used + length)
  47963. ivLen -= length
  47964. }
  47965. }
  47966. tmp.fill(0)
  47967. return { key: key, iv: iv }
  47968. }
  47969. module.exports = EVP_BytesToKey
  47970. },{"md5.js":339,"safe-buffer":561}],249:[function(require,module,exports){
  47971. 'use strict';
  47972. var hasOwn = Object.prototype.hasOwnProperty;
  47973. var toStr = Object.prototype.toString;
  47974. var defineProperty = Object.defineProperty;
  47975. var gOPD = Object.getOwnPropertyDescriptor;
  47976. var isArray = function isArray(arr) {
  47977. if (typeof Array.isArray === 'function') {
  47978. return Array.isArray(arr);
  47979. }
  47980. return toStr.call(arr) === '[object Array]';
  47981. };
  47982. var isPlainObject = function isPlainObject(obj) {
  47983. if (!obj || toStr.call(obj) !== '[object Object]') {
  47984. return false;
  47985. }
  47986. var hasOwnConstructor = hasOwn.call(obj, 'constructor');
  47987. var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
  47988. // Not own constructor property must be Object
  47989. if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
  47990. return false;
  47991. }
  47992. // Own properties are enumerated firstly, so to speed up,
  47993. // if last one is own, then all properties are own.
  47994. var key;
  47995. for (key in obj) { /**/ }
  47996. return typeof key === 'undefined' || hasOwn.call(obj, key);
  47997. };
  47998. // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
  47999. var setProperty = function setProperty(target, options) {
  48000. if (defineProperty && options.name === '__proto__') {
  48001. defineProperty(target, options.name, {
  48002. enumerable: true,
  48003. configurable: true,
  48004. value: options.newValue,
  48005. writable: true
  48006. });
  48007. } else {
  48008. target[options.name] = options.newValue;
  48009. }
  48010. };
  48011. // Return undefined instead of __proto__ if '__proto__' is not an own property
  48012. var getProperty = function getProperty(obj, name) {
  48013. if (name === '__proto__') {
  48014. if (!hasOwn.call(obj, name)) {
  48015. return void 0;
  48016. } else if (gOPD) {
  48017. // In early versions of node, obj['__proto__'] is buggy when obj has
  48018. // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
  48019. return gOPD(obj, name).value;
  48020. }
  48021. }
  48022. return obj[name];
  48023. };
  48024. module.exports = function extend() {
  48025. var options, name, src, copy, copyIsArray, clone;
  48026. var target = arguments[0];
  48027. var i = 1;
  48028. var length = arguments.length;
  48029. var deep = false;
  48030. // Handle a deep copy situation
  48031. if (typeof target === 'boolean') {
  48032. deep = target;
  48033. target = arguments[1] || {};
  48034. // skip the boolean and the target
  48035. i = 2;
  48036. }
  48037. if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
  48038. target = {};
  48039. }
  48040. for (; i < length; ++i) {
  48041. options = arguments[i];
  48042. // Only deal with non-null/undefined values
  48043. if (options != null) {
  48044. // Extend the base object
  48045. for (name in options) {
  48046. src = getProperty(target, name);
  48047. copy = getProperty(options, name);
  48048. // Prevent never-ending loop
  48049. if (target !== copy) {
  48050. // Recurse if we're merging plain objects or arrays
  48051. if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
  48052. if (copyIsArray) {
  48053. copyIsArray = false;
  48054. clone = src && isArray(src) ? src : [];
  48055. } else {
  48056. clone = src && isPlainObject(src) ? src : {};
  48057. }
  48058. // Never move original objects, clone them
  48059. setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
  48060. // Don't bring in undefined values
  48061. } else if (typeof copy !== 'undefined') {
  48062. setProperty(target, { name: name, newValue: copy });
  48063. }
  48064. }
  48065. }
  48066. }
  48067. }
  48068. // Return the modified object
  48069. return target;
  48070. };
  48071. },{}],250:[function(require,module,exports){
  48072. (function (process){(function (){
  48073. /*
  48074. * extsprintf.js: extended POSIX-style sprintf
  48075. */
  48076. var mod_assert = require('assert');
  48077. var mod_util = require('util');
  48078. /*
  48079. * Public interface
  48080. */
  48081. exports.sprintf = jsSprintf;
  48082. exports.printf = jsPrintf;
  48083. exports.fprintf = jsFprintf;
  48084. /*
  48085. * Stripped down version of s[n]printf(3c). We make a best effort to throw an
  48086. * exception when given a format string we don't understand, rather than
  48087. * ignoring it, so that we won't break existing programs if/when we go implement
  48088. * the rest of this.
  48089. *
  48090. * This implementation currently supports specifying
  48091. * - field alignment ('-' flag),
  48092. * - zero-pad ('0' flag)
  48093. * - always show numeric sign ('+' flag),
  48094. * - field width
  48095. * - conversions for strings, decimal integers, and floats (numbers).
  48096. * - argument size specifiers. These are all accepted but ignored, since
  48097. * Javascript has no notion of the physical size of an argument.
  48098. *
  48099. * Everything else is currently unsupported, most notably precision, unsigned
  48100. * numbers, non-decimal numbers, and characters.
  48101. */
  48102. function jsSprintf(fmt)
  48103. {
  48104. var regex = [
  48105. '([^%]*)', /* normal text */
  48106. '%', /* start of format */
  48107. '([\'\\-+ #0]*?)', /* flags (optional) */
  48108. '([1-9]\\d*)?', /* width (optional) */
  48109. '(\\.([1-9]\\d*))?', /* precision (optional) */
  48110. '[lhjztL]*?', /* length mods (ignored) */
  48111. '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
  48112. ].join('');
  48113. var re = new RegExp(regex);
  48114. var args = Array.prototype.slice.call(arguments, 1);
  48115. var flags, width, precision, conversion;
  48116. var left, pad, sign, arg, match;
  48117. var ret = '';
  48118. var argn = 1;
  48119. mod_assert.equal('string', typeof (fmt));
  48120. while ((match = re.exec(fmt)) !== null) {
  48121. ret += match[1];
  48122. fmt = fmt.substring(match[0].length);
  48123. flags = match[2] || '';
  48124. width = match[3] || 0;
  48125. precision = match[4] || '';
  48126. conversion = match[6];
  48127. left = false;
  48128. sign = false;
  48129. pad = ' ';
  48130. if (conversion == '%') {
  48131. ret += '%';
  48132. continue;
  48133. }
  48134. if (args.length === 0)
  48135. throw (new Error('too few args to sprintf'));
  48136. arg = args.shift();
  48137. argn++;
  48138. if (flags.match(/[\' #]/))
  48139. throw (new Error(
  48140. 'unsupported flags: ' + flags));
  48141. if (precision.length > 0)
  48142. throw (new Error(
  48143. 'non-zero precision not supported'));
  48144. if (flags.match(/-/))
  48145. left = true;
  48146. if (flags.match(/0/))
  48147. pad = '0';
  48148. if (flags.match(/\+/))
  48149. sign = true;
  48150. switch (conversion) {
  48151. case 's':
  48152. if (arg === undefined || arg === null)
  48153. throw (new Error('argument ' + argn +
  48154. ': attempted to print undefined or null ' +
  48155. 'as a string'));
  48156. ret += doPad(pad, width, left, arg.toString());
  48157. break;
  48158. case 'd':
  48159. arg = Math.floor(arg);
  48160. /*jsl:fallthru*/
  48161. case 'f':
  48162. sign = sign && arg > 0 ? '+' : '';
  48163. ret += sign + doPad(pad, width, left,
  48164. arg.toString());
  48165. break;
  48166. case 'x':
  48167. ret += doPad(pad, width, left, arg.toString(16));
  48168. break;
  48169. case 'j': /* non-standard */
  48170. if (width === 0)
  48171. width = 10;
  48172. ret += mod_util.inspect(arg, false, width);
  48173. break;
  48174. case 'r': /* non-standard */
  48175. ret += dumpException(arg);
  48176. break;
  48177. default:
  48178. throw (new Error('unsupported conversion: ' +
  48179. conversion));
  48180. }
  48181. }
  48182. ret += fmt;
  48183. return (ret);
  48184. }
  48185. function jsPrintf() {
  48186. var args = Array.prototype.slice.call(arguments);
  48187. args.unshift(process.stdout);
  48188. jsFprintf.apply(null, args);
  48189. }
  48190. function jsFprintf(stream) {
  48191. var args = Array.prototype.slice.call(arguments, 1);
  48192. return (stream.write(jsSprintf.apply(this, args)));
  48193. }
  48194. function doPad(chr, width, left, str)
  48195. {
  48196. var ret = str;
  48197. while (ret.length < width) {
  48198. if (left)
  48199. ret += chr;
  48200. else
  48201. ret = chr + ret;
  48202. }
  48203. return (ret);
  48204. }
  48205. /*
  48206. * This function dumps long stack traces for exceptions having a cause() method.
  48207. * See node-verror for an example.
  48208. */
  48209. function dumpException(ex)
  48210. {
  48211. var ret;
  48212. if (!(ex instanceof Error))
  48213. throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
  48214. /* Note that V8 prepends "ex.stack" with ex.toString(). */
  48215. ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
  48216. if (ex.cause && typeof (ex.cause) === 'function') {
  48217. var cex = ex.cause();
  48218. if (cex) {
  48219. ret += '\nCaused by: ' + dumpException(cex);
  48220. }
  48221. }
  48222. return (ret);
  48223. }
  48224. }).call(this)}).call(this,require('_process'))
  48225. },{"_process":525,"assert":105,"util":658}],251:[function(require,module,exports){
  48226. 'use strict';
  48227. // do not edit .js files directly - edit src/index.jst
  48228. module.exports = function equal(a, b) {
  48229. if (a === b) return true;
  48230. if (a && b && typeof a == 'object' && typeof b == 'object') {
  48231. if (a.constructor !== b.constructor) return false;
  48232. var length, i, keys;
  48233. if (Array.isArray(a)) {
  48234. length = a.length;
  48235. if (length != b.length) return false;
  48236. for (i = length; i-- !== 0;)
  48237. if (!equal(a[i], b[i])) return false;
  48238. return true;
  48239. }
  48240. if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
  48241. if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
  48242. if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
  48243. keys = Object.keys(a);
  48244. length = keys.length;
  48245. if (length !== Object.keys(b).length) return false;
  48246. for (i = length; i-- !== 0;)
  48247. if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
  48248. for (i = length; i-- !== 0;) {
  48249. var key = keys[i];
  48250. if (!equal(a[key], b[key])) return false;
  48251. }
  48252. return true;
  48253. }
  48254. // true if both NaN, false otherwise
  48255. return a!==a && b!==b;
  48256. };
  48257. },{}],252:[function(require,module,exports){
  48258. 'use strict';
  48259. module.exports = function (data, opts) {
  48260. if (!opts) opts = {};
  48261. if (typeof opts === 'function') opts = { cmp: opts };
  48262. var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
  48263. var cmp = opts.cmp && (function (f) {
  48264. return function (node) {
  48265. return function (a, b) {
  48266. var aobj = { key: a, value: node[a] };
  48267. var bobj = { key: b, value: node[b] };
  48268. return f(aobj, bobj);
  48269. };
  48270. };
  48271. })(opts.cmp);
  48272. var seen = [];
  48273. return (function stringify (node) {
  48274. if (node && node.toJSON && typeof node.toJSON === 'function') {
  48275. node = node.toJSON();
  48276. }
  48277. if (node === undefined) return;
  48278. if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
  48279. if (typeof node !== 'object') return JSON.stringify(node);
  48280. var i, out;
  48281. if (Array.isArray(node)) {
  48282. out = '[';
  48283. for (i = 0; i < node.length; i++) {
  48284. if (i) out += ',';
  48285. out += stringify(node[i]) || 'null';
  48286. }
  48287. return out + ']';
  48288. }
  48289. if (node === null) return 'null';
  48290. if (seen.indexOf(node) !== -1) {
  48291. if (cycles) return JSON.stringify('__cycle__');
  48292. throw new TypeError('Converting circular structure to JSON');
  48293. }
  48294. var seenIndex = seen.push(node) - 1;
  48295. var keys = Object.keys(node).sort(cmp && cmp(node));
  48296. out = '';
  48297. for (i = 0; i < keys.length; i++) {
  48298. var key = keys[i];
  48299. var value = stringify(node[key]);
  48300. if (!value) continue;
  48301. if (out) out += ',';
  48302. out += JSON.stringify(key) + ':' + value;
  48303. }
  48304. seen.splice(seenIndex, 1);
  48305. return '{' + out + '}';
  48306. })(data);
  48307. };
  48308. },{}],253:[function(require,module,exports){
  48309. var hasOwn = Object.prototype.hasOwnProperty;
  48310. var toString = Object.prototype.toString;
  48311. module.exports = function forEach (obj, fn, ctx) {
  48312. if (toString.call(fn) !== '[object Function]') {
  48313. throw new TypeError('iterator must be a function');
  48314. }
  48315. var l = obj.length;
  48316. if (l === +l) {
  48317. for (var i = 0; i < l; i++) {
  48318. fn.call(ctx, obj[i], i, obj);
  48319. }
  48320. } else {
  48321. for (var k in obj) {
  48322. if (hasOwn.call(obj, k)) {
  48323. fn.call(ctx, obj[k], k, obj);
  48324. }
  48325. }
  48326. }
  48327. };
  48328. },{}],254:[function(require,module,exports){
  48329. module.exports = ForeverAgent
  48330. ForeverAgent.SSL = ForeverAgentSSL
  48331. var util = require('util')
  48332. , Agent = require('http').Agent
  48333. , net = require('net')
  48334. , tls = require('tls')
  48335. , AgentSSL = require('https').Agent
  48336. function getConnectionName(host, port) {
  48337. var name = ''
  48338. if (typeof host === 'string') {
  48339. name = host + ':' + port
  48340. } else {
  48341. // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name.
  48342. name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':')
  48343. }
  48344. return name
  48345. }
  48346. function ForeverAgent(options) {
  48347. var self = this
  48348. self.options = options || {}
  48349. self.requests = {}
  48350. self.sockets = {}
  48351. self.freeSockets = {}
  48352. self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
  48353. self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
  48354. self.on('free', function(socket, host, port) {
  48355. var name = getConnectionName(host, port)
  48356. if (self.requests[name] && self.requests[name].length) {
  48357. self.requests[name].shift().onSocket(socket)
  48358. } else if (self.sockets[name].length < self.minSockets) {
  48359. if (!self.freeSockets[name]) self.freeSockets[name] = []
  48360. self.freeSockets[name].push(socket)
  48361. // if an error happens while we don't use the socket anyway, meh, throw the socket away
  48362. var onIdleError = function() {
  48363. socket.destroy()
  48364. }
  48365. socket._onIdleError = onIdleError
  48366. socket.on('error', onIdleError)
  48367. } else {
  48368. // If there are no pending requests just destroy the
  48369. // socket and it will get removed from the pool. This
  48370. // gets us out of timeout issues and allows us to
  48371. // default to Connection:keep-alive.
  48372. socket.destroy()
  48373. }
  48374. })
  48375. }
  48376. util.inherits(ForeverAgent, Agent)
  48377. ForeverAgent.defaultMinSockets = 5
  48378. ForeverAgent.prototype.createConnection = net.createConnection
  48379. ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
  48380. ForeverAgent.prototype.addRequest = function(req, host, port) {
  48381. var name = getConnectionName(host, port)
  48382. if (typeof host !== 'string') {
  48383. var options = host
  48384. port = options.port
  48385. host = options.host
  48386. }
  48387. if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
  48388. var idleSocket = this.freeSockets[name].pop()
  48389. idleSocket.removeListener('error', idleSocket._onIdleError)
  48390. delete idleSocket._onIdleError
  48391. req._reusedSocket = true
  48392. req.onSocket(idleSocket)
  48393. } else {
  48394. this.addRequestNoreuse(req, host, port)
  48395. }
  48396. }
  48397. ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
  48398. if (this.sockets[name]) {
  48399. var index = this.sockets[name].indexOf(s)
  48400. if (index !== -1) {
  48401. this.sockets[name].splice(index, 1)
  48402. }
  48403. } else if (this.sockets[name] && this.sockets[name].length === 0) {
  48404. // don't leak
  48405. delete this.sockets[name]
  48406. delete this.requests[name]
  48407. }
  48408. if (this.freeSockets[name]) {
  48409. var index = this.freeSockets[name].indexOf(s)
  48410. if (index !== -1) {
  48411. this.freeSockets[name].splice(index, 1)
  48412. if (this.freeSockets[name].length === 0) {
  48413. delete this.freeSockets[name]
  48414. }
  48415. }
  48416. }
  48417. if (this.requests[name] && this.requests[name].length) {
  48418. // If we have pending requests and a socket gets closed a new one
  48419. // needs to be created to take over in the pool for the one that closed.
  48420. this.createSocket(name, host, port).emit('free')
  48421. }
  48422. }
  48423. function ForeverAgentSSL (options) {
  48424. ForeverAgent.call(this, options)
  48425. }
  48426. util.inherits(ForeverAgentSSL, ForeverAgent)
  48427. ForeverAgentSSL.prototype.createConnection = createConnectionSSL
  48428. ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
  48429. function createConnectionSSL (port, host, options) {
  48430. if (typeof port === 'object') {
  48431. options = port;
  48432. } else if (typeof host === 'object') {
  48433. options = host;
  48434. } else if (typeof options === 'object') {
  48435. options = options;
  48436. } else {
  48437. options = {};
  48438. }
  48439. if (typeof port === 'number') {
  48440. options.port = port;
  48441. }
  48442. if (typeof host === 'string') {
  48443. options.host = host;
  48444. }
  48445. return tls.connect(options);
  48446. }
  48447. },{"http":612,"https":318,"net":190,"tls":190,"util":658}],255:[function(require,module,exports){
  48448. /* eslint-env browser */
  48449. module.exports = typeof self == 'object' ? self.FormData : window.FormData;
  48450. },{}],256:[function(require,module,exports){
  48451. 'use strict';
  48452. /* eslint no-invalid-this: 1 */
  48453. var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
  48454. var slice = Array.prototype.slice;
  48455. var toStr = Object.prototype.toString;
  48456. var funcType = '[object Function]';
  48457. module.exports = function bind(that) {
  48458. var target = this;
  48459. if (typeof target !== 'function' || toStr.call(target) !== funcType) {
  48460. throw new TypeError(ERROR_MESSAGE + target);
  48461. }
  48462. var args = slice.call(arguments, 1);
  48463. var bound;
  48464. var binder = function () {
  48465. if (this instanceof bound) {
  48466. var result = target.apply(
  48467. this,
  48468. args.concat(slice.call(arguments))
  48469. );
  48470. if (Object(result) === result) {
  48471. return result;
  48472. }
  48473. return this;
  48474. } else {
  48475. return target.apply(
  48476. that,
  48477. args.concat(slice.call(arguments))
  48478. );
  48479. }
  48480. };
  48481. var boundLength = Math.max(0, target.length - args.length);
  48482. var boundArgs = [];
  48483. for (var i = 0; i < boundLength; i++) {
  48484. boundArgs.push('$' + i);
  48485. }
  48486. bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
  48487. if (target.prototype) {
  48488. var Empty = function Empty() {};
  48489. Empty.prototype = target.prototype;
  48490. bound.prototype = new Empty();
  48491. Empty.prototype = null;
  48492. }
  48493. return bound;
  48494. };
  48495. },{}],257:[function(require,module,exports){
  48496. 'use strict';
  48497. var implementation = require('./implementation');
  48498. module.exports = Function.prototype.bind || implementation;
  48499. },{"./implementation":256}],258:[function(require,module,exports){
  48500. 'use strict';
  48501. /* globals
  48502. AggregateError,
  48503. Atomics,
  48504. FinalizationRegistry,
  48505. SharedArrayBuffer,
  48506. WeakRef,
  48507. */
  48508. var undefined;
  48509. var $SyntaxError = SyntaxError;
  48510. var $Function = Function;
  48511. var $TypeError = TypeError;
  48512. // eslint-disable-next-line consistent-return
  48513. var getEvalledConstructor = function (expressionSyntax) {
  48514. try {
  48515. // eslint-disable-next-line no-new-func
  48516. return Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
  48517. } catch (e) {}
  48518. };
  48519. var $gOPD = Object.getOwnPropertyDescriptor;
  48520. if ($gOPD) {
  48521. try {
  48522. $gOPD({}, '');
  48523. } catch (e) {
  48524. $gOPD = null; // this is IE 8, which has a broken gOPD
  48525. }
  48526. }
  48527. var throwTypeError = function () {
  48528. throw new $TypeError();
  48529. };
  48530. var ThrowTypeError = $gOPD
  48531. ? (function () {
  48532. try {
  48533. // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
  48534. arguments.callee; // IE 8 does not throw here
  48535. return throwTypeError;
  48536. } catch (calleeThrows) {
  48537. try {
  48538. // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
  48539. return $gOPD(arguments, 'callee').get;
  48540. } catch (gOPDthrows) {
  48541. return throwTypeError;
  48542. }
  48543. }
  48544. }())
  48545. : throwTypeError;
  48546. var hasSymbols = require('has-symbols')();
  48547. var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
  48548. var asyncGenFunction = getEvalledConstructor('async function* () {}');
  48549. var asyncGenFunctionPrototype = asyncGenFunction ? asyncGenFunction.prototype : undefined;
  48550. var asyncGenPrototype = asyncGenFunctionPrototype ? asyncGenFunctionPrototype.prototype : undefined;
  48551. var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
  48552. var INTRINSICS = {
  48553. '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
  48554. '%Array%': Array,
  48555. '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
  48556. '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
  48557. '%AsyncFromSyncIteratorPrototype%': undefined,
  48558. '%AsyncFunction%': getEvalledConstructor('async function () {}'),
  48559. '%AsyncGenerator%': asyncGenFunctionPrototype,
  48560. '%AsyncGeneratorFunction%': asyncGenFunction,
  48561. '%AsyncIteratorPrototype%': asyncGenPrototype ? getProto(asyncGenPrototype) : undefined,
  48562. '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
  48563. '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
  48564. '%Boolean%': Boolean,
  48565. '%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
  48566. '%Date%': Date,
  48567. '%decodeURI%': decodeURI,
  48568. '%decodeURIComponent%': decodeURIComponent,
  48569. '%encodeURI%': encodeURI,
  48570. '%encodeURIComponent%': encodeURIComponent,
  48571. '%Error%': Error,
  48572. '%eval%': eval, // eslint-disable-line no-eval
  48573. '%EvalError%': EvalError,
  48574. '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
  48575. '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
  48576. '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
  48577. '%Function%': $Function,
  48578. '%GeneratorFunction%': getEvalledConstructor('function* () {}'),
  48579. '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
  48580. '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
  48581. '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
  48582. '%isFinite%': isFinite,
  48583. '%isNaN%': isNaN,
  48584. '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
  48585. '%JSON%': typeof JSON === 'object' ? JSON : undefined,
  48586. '%Map%': typeof Map === 'undefined' ? undefined : Map,
  48587. '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
  48588. '%Math%': Math,
  48589. '%Number%': Number,
  48590. '%Object%': Object,
  48591. '%parseFloat%': parseFloat,
  48592. '%parseInt%': parseInt,
  48593. '%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
  48594. '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
  48595. '%RangeError%': RangeError,
  48596. '%ReferenceError%': ReferenceError,
  48597. '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
  48598. '%RegExp%': RegExp,
  48599. '%Set%': typeof Set === 'undefined' ? undefined : Set,
  48600. '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
  48601. '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
  48602. '%String%': String,
  48603. '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
  48604. '%Symbol%': hasSymbols ? Symbol : undefined,
  48605. '%SyntaxError%': $SyntaxError,
  48606. '%ThrowTypeError%': ThrowTypeError,
  48607. '%TypedArray%': TypedArray,
  48608. '%TypeError%': $TypeError,
  48609. '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
  48610. '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
  48611. '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
  48612. '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
  48613. '%URIError%': URIError,
  48614. '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
  48615. '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
  48616. '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
  48617. };
  48618. var LEGACY_ALIASES = {
  48619. '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
  48620. '%ArrayPrototype%': ['Array', 'prototype'],
  48621. '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
  48622. '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
  48623. '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
  48624. '%ArrayProto_values%': ['Array', 'prototype', 'values'],
  48625. '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
  48626. '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
  48627. '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
  48628. '%BooleanPrototype%': ['Boolean', 'prototype'],
  48629. '%DataViewPrototype%': ['DataView', 'prototype'],
  48630. '%DatePrototype%': ['Date', 'prototype'],
  48631. '%ErrorPrototype%': ['Error', 'prototype'],
  48632. '%EvalErrorPrototype%': ['EvalError', 'prototype'],
  48633. '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
  48634. '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
  48635. '%FunctionPrototype%': ['Function', 'prototype'],
  48636. '%Generator%': ['GeneratorFunction', 'prototype'],
  48637. '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
  48638. '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
  48639. '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
  48640. '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
  48641. '%JSONParse%': ['JSON', 'parse'],
  48642. '%JSONStringify%': ['JSON', 'stringify'],
  48643. '%MapPrototype%': ['Map', 'prototype'],
  48644. '%NumberPrototype%': ['Number', 'prototype'],
  48645. '%ObjectPrototype%': ['Object', 'prototype'],
  48646. '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
  48647. '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
  48648. '%PromisePrototype%': ['Promise', 'prototype'],
  48649. '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
  48650. '%Promise_all%': ['Promise', 'all'],
  48651. '%Promise_reject%': ['Promise', 'reject'],
  48652. '%Promise_resolve%': ['Promise', 'resolve'],
  48653. '%RangeErrorPrototype%': ['RangeError', 'prototype'],
  48654. '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
  48655. '%RegExpPrototype%': ['RegExp', 'prototype'],
  48656. '%SetPrototype%': ['Set', 'prototype'],
  48657. '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
  48658. '%StringPrototype%': ['String', 'prototype'],
  48659. '%SymbolPrototype%': ['Symbol', 'prototype'],
  48660. '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
  48661. '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
  48662. '%TypeErrorPrototype%': ['TypeError', 'prototype'],
  48663. '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
  48664. '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
  48665. '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
  48666. '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
  48667. '%URIErrorPrototype%': ['URIError', 'prototype'],
  48668. '%WeakMapPrototype%': ['WeakMap', 'prototype'],
  48669. '%WeakSetPrototype%': ['WeakSet', 'prototype']
  48670. };
  48671. var bind = require('function-bind');
  48672. var hasOwn = require('has');
  48673. var $concat = bind.call(Function.call, Array.prototype.concat);
  48674. var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
  48675. var $replace = bind.call(Function.call, String.prototype.replace);
  48676. /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
  48677. var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
  48678. var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
  48679. var stringToPath = function stringToPath(string) {
  48680. var result = [];
  48681. $replace(string, rePropName, function (match, number, quote, subString) {
  48682. result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
  48683. });
  48684. return result;
  48685. };
  48686. /* end adaptation */
  48687. var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
  48688. var intrinsicName = name;
  48689. var alias;
  48690. if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
  48691. alias = LEGACY_ALIASES[intrinsicName];
  48692. intrinsicName = '%' + alias[0] + '%';
  48693. }
  48694. if (hasOwn(INTRINSICS, intrinsicName)) {
  48695. var value = INTRINSICS[intrinsicName];
  48696. if (typeof value === 'undefined' && !allowMissing) {
  48697. throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
  48698. }
  48699. return {
  48700. alias: alias,
  48701. name: intrinsicName,
  48702. value: value
  48703. };
  48704. }
  48705. throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
  48706. };
  48707. module.exports = function GetIntrinsic(name, allowMissing) {
  48708. if (typeof name !== 'string' || name.length === 0) {
  48709. throw new $TypeError('intrinsic name must be a non-empty string');
  48710. }
  48711. if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
  48712. throw new $TypeError('"allowMissing" argument must be a boolean');
  48713. }
  48714. var parts = stringToPath(name);
  48715. var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
  48716. var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
  48717. var intrinsicRealName = intrinsic.name;
  48718. var value = intrinsic.value;
  48719. var skipFurtherCaching = false;
  48720. var alias = intrinsic.alias;
  48721. if (alias) {
  48722. intrinsicBaseName = alias[0];
  48723. $spliceApply(parts, $concat([0, 1], alias));
  48724. }
  48725. for (var i = 1, isOwn = true; i < parts.length; i += 1) {
  48726. var part = parts[i];
  48727. if (part === 'constructor' || !isOwn) {
  48728. skipFurtherCaching = true;
  48729. }
  48730. intrinsicBaseName += '.' + part;
  48731. intrinsicRealName = '%' + intrinsicBaseName + '%';
  48732. if (hasOwn(INTRINSICS, intrinsicRealName)) {
  48733. value = INTRINSICS[intrinsicRealName];
  48734. } else if (value != null) {
  48735. if ($gOPD && (i + 1) >= parts.length) {
  48736. var desc = $gOPD(value, part);
  48737. isOwn = !!desc;
  48738. if (!allowMissing && !(part in value)) {
  48739. throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
  48740. }
  48741. // By convention, when a data property is converted to an accessor
  48742. // property to emulate a data property that does not suffer from
  48743. // the override mistake, that accessor's getter is marked with
  48744. // an `originalValue` property. Here, when we detect this, we
  48745. // uphold the illusion by pretending to see that original data
  48746. // property, i.e., returning the value rather than the getter
  48747. // itself.
  48748. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
  48749. value = desc.get;
  48750. } else {
  48751. value = value[part];
  48752. }
  48753. } else {
  48754. isOwn = hasOwn(value, part);
  48755. value = value[part];
  48756. }
  48757. if (isOwn && !skipFurtherCaching) {
  48758. INTRINSICS[intrinsicRealName] = value;
  48759. }
  48760. }
  48761. }
  48762. return value;
  48763. };
  48764. },{"function-bind":257,"has":282,"has-symbols":280}],259:[function(require,module,exports){
  48765. module.exports={
  48766. "$id": "afterRequest.json#",
  48767. "$schema": "http://json-schema.org/draft-06/schema#",
  48768. "type": "object",
  48769. "optional": true,
  48770. "required": [
  48771. "lastAccess",
  48772. "eTag",
  48773. "hitCount"
  48774. ],
  48775. "properties": {
  48776. "expires": {
  48777. "type": "string",
  48778. "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
  48779. },
  48780. "lastAccess": {
  48781. "type": "string",
  48782. "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
  48783. },
  48784. "eTag": {
  48785. "type": "string"
  48786. },
  48787. "hitCount": {
  48788. "type": "integer"
  48789. },
  48790. "comment": {
  48791. "type": "string"
  48792. }
  48793. }
  48794. }
  48795. },{}],260:[function(require,module,exports){
  48796. module.exports={
  48797. "$id": "beforeRequest.json#",
  48798. "$schema": "http://json-schema.org/draft-06/schema#",
  48799. "type": "object",
  48800. "optional": true,
  48801. "required": [
  48802. "lastAccess",
  48803. "eTag",
  48804. "hitCount"
  48805. ],
  48806. "properties": {
  48807. "expires": {
  48808. "type": "string",
  48809. "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
  48810. },
  48811. "lastAccess": {
  48812. "type": "string",
  48813. "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
  48814. },
  48815. "eTag": {
  48816. "type": "string"
  48817. },
  48818. "hitCount": {
  48819. "type": "integer"
  48820. },
  48821. "comment": {
  48822. "type": "string"
  48823. }
  48824. }
  48825. }
  48826. },{}],261:[function(require,module,exports){
  48827. module.exports={
  48828. "$id": "browser.json#",
  48829. "$schema": "http://json-schema.org/draft-06/schema#",
  48830. "type": "object",
  48831. "required": [
  48832. "name",
  48833. "version"
  48834. ],
  48835. "properties": {
  48836. "name": {
  48837. "type": "string"
  48838. },
  48839. "version": {
  48840. "type": "string"
  48841. },
  48842. "comment": {
  48843. "type": "string"
  48844. }
  48845. }
  48846. }
  48847. },{}],262:[function(require,module,exports){
  48848. module.exports={
  48849. "$id": "cache.json#",
  48850. "$schema": "http://json-schema.org/draft-06/schema#",
  48851. "properties": {
  48852. "beforeRequest": {
  48853. "oneOf": [
  48854. { "type": "null" },
  48855. { "$ref": "beforeRequest.json#" }
  48856. ]
  48857. },
  48858. "afterRequest": {
  48859. "oneOf": [
  48860. { "type": "null" },
  48861. { "$ref": "afterRequest.json#" }
  48862. ]
  48863. },
  48864. "comment": {
  48865. "type": "string"
  48866. }
  48867. }
  48868. }
  48869. },{}],263:[function(require,module,exports){
  48870. module.exports={
  48871. "$id": "content.json#",
  48872. "$schema": "http://json-schema.org/draft-06/schema#",
  48873. "type": "object",
  48874. "required": [
  48875. "size",
  48876. "mimeType"
  48877. ],
  48878. "properties": {
  48879. "size": {
  48880. "type": "integer"
  48881. },
  48882. "compression": {
  48883. "type": "integer"
  48884. },
  48885. "mimeType": {
  48886. "type": "string"
  48887. },
  48888. "text": {
  48889. "type": "string"
  48890. },
  48891. "encoding": {
  48892. "type": "string"
  48893. },
  48894. "comment": {
  48895. "type": "string"
  48896. }
  48897. }
  48898. }
  48899. },{}],264:[function(require,module,exports){
  48900. module.exports={
  48901. "$id": "cookie.json#",
  48902. "$schema": "http://json-schema.org/draft-06/schema#",
  48903. "type": "object",
  48904. "required": [
  48905. "name",
  48906. "value"
  48907. ],
  48908. "properties": {
  48909. "name": {
  48910. "type": "string"
  48911. },
  48912. "value": {
  48913. "type": "string"
  48914. },
  48915. "path": {
  48916. "type": "string"
  48917. },
  48918. "domain": {
  48919. "type": "string"
  48920. },
  48921. "expires": {
  48922. "type": ["string", "null"],
  48923. "format": "date-time"
  48924. },
  48925. "httpOnly": {
  48926. "type": "boolean"
  48927. },
  48928. "secure": {
  48929. "type": "boolean"
  48930. },
  48931. "comment": {
  48932. "type": "string"
  48933. }
  48934. }
  48935. }
  48936. },{}],265:[function(require,module,exports){
  48937. module.exports={
  48938. "$id": "creator.json#",
  48939. "$schema": "http://json-schema.org/draft-06/schema#",
  48940. "type": "object",
  48941. "required": [
  48942. "name",
  48943. "version"
  48944. ],
  48945. "properties": {
  48946. "name": {
  48947. "type": "string"
  48948. },
  48949. "version": {
  48950. "type": "string"
  48951. },
  48952. "comment": {
  48953. "type": "string"
  48954. }
  48955. }
  48956. }
  48957. },{}],266:[function(require,module,exports){
  48958. module.exports={
  48959. "$id": "entry.json#",
  48960. "$schema": "http://json-schema.org/draft-06/schema#",
  48961. "type": "object",
  48962. "optional": true,
  48963. "required": [
  48964. "startedDateTime",
  48965. "time",
  48966. "request",
  48967. "response",
  48968. "cache",
  48969. "timings"
  48970. ],
  48971. "properties": {
  48972. "pageref": {
  48973. "type": "string"
  48974. },
  48975. "startedDateTime": {
  48976. "type": "string",
  48977. "format": "date-time",
  48978. "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
  48979. },
  48980. "time": {
  48981. "type": "number",
  48982. "min": 0
  48983. },
  48984. "request": {
  48985. "$ref": "request.json#"
  48986. },
  48987. "response": {
  48988. "$ref": "response.json#"
  48989. },
  48990. "cache": {
  48991. "$ref": "cache.json#"
  48992. },
  48993. "timings": {
  48994. "$ref": "timings.json#"
  48995. },
  48996. "serverIPAddress": {
  48997. "type": "string",
  48998. "oneOf": [
  48999. { "format": "ipv4" },
  49000. { "format": "ipv6" }
  49001. ]
  49002. },
  49003. "connection": {
  49004. "type": "string"
  49005. },
  49006. "comment": {
  49007. "type": "string"
  49008. }
  49009. }
  49010. }
  49011. },{}],267:[function(require,module,exports){
  49012. module.exports={
  49013. "$id": "har.json#",
  49014. "$schema": "http://json-schema.org/draft-06/schema#",
  49015. "type": "object",
  49016. "required": [
  49017. "log"
  49018. ],
  49019. "properties": {
  49020. "log": {
  49021. "$ref": "log.json#"
  49022. }
  49023. }
  49024. }
  49025. },{}],268:[function(require,module,exports){
  49026. module.exports={
  49027. "$id": "header.json#",
  49028. "$schema": "http://json-schema.org/draft-06/schema#",
  49029. "type": "object",
  49030. "required": [
  49031. "name",
  49032. "value"
  49033. ],
  49034. "properties": {
  49035. "name": {
  49036. "type": "string"
  49037. },
  49038. "value": {
  49039. "type": "string"
  49040. },
  49041. "comment": {
  49042. "type": "string"
  49043. }
  49044. }
  49045. }
  49046. },{}],269:[function(require,module,exports){
  49047. 'use strict'
  49048. module.exports = {
  49049. afterRequest: require('./afterRequest.json'),
  49050. beforeRequest: require('./beforeRequest.json'),
  49051. browser: require('./browser.json'),
  49052. cache: require('./cache.json'),
  49053. content: require('./content.json'),
  49054. cookie: require('./cookie.json'),
  49055. creator: require('./creator.json'),
  49056. entry: require('./entry.json'),
  49057. har: require('./har.json'),
  49058. header: require('./header.json'),
  49059. log: require('./log.json'),
  49060. page: require('./page.json'),
  49061. pageTimings: require('./pageTimings.json'),
  49062. postData: require('./postData.json'),
  49063. query: require('./query.json'),
  49064. request: require('./request.json'),
  49065. response: require('./response.json'),
  49066. timings: require('./timings.json')
  49067. }
  49068. },{"./afterRequest.json":259,"./beforeRequest.json":260,"./browser.json":261,"./cache.json":262,"./content.json":263,"./cookie.json":264,"./creator.json":265,"./entry.json":266,"./har.json":267,"./header.json":268,"./log.json":270,"./page.json":271,"./pageTimings.json":272,"./postData.json":273,"./query.json":274,"./request.json":275,"./response.json":276,"./timings.json":277}],270:[function(require,module,exports){
  49069. module.exports={
  49070. "$id": "log.json#",
  49071. "$schema": "http://json-schema.org/draft-06/schema#",
  49072. "type": "object",
  49073. "required": [
  49074. "version",
  49075. "creator",
  49076. "entries"
  49077. ],
  49078. "properties": {
  49079. "version": {
  49080. "type": "string"
  49081. },
  49082. "creator": {
  49083. "$ref": "creator.json#"
  49084. },
  49085. "browser": {
  49086. "$ref": "browser.json#"
  49087. },
  49088. "pages": {
  49089. "type": "array",
  49090. "items": {
  49091. "$ref": "page.json#"
  49092. }
  49093. },
  49094. "entries": {
  49095. "type": "array",
  49096. "items": {
  49097. "$ref": "entry.json#"
  49098. }
  49099. },
  49100. "comment": {
  49101. "type": "string"
  49102. }
  49103. }
  49104. }
  49105. },{}],271:[function(require,module,exports){
  49106. module.exports={
  49107. "$id": "page.json#",
  49108. "$schema": "http://json-schema.org/draft-06/schema#",
  49109. "type": "object",
  49110. "optional": true,
  49111. "required": [
  49112. "startedDateTime",
  49113. "id",
  49114. "title",
  49115. "pageTimings"
  49116. ],
  49117. "properties": {
  49118. "startedDateTime": {
  49119. "type": "string",
  49120. "format": "date-time",
  49121. "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
  49122. },
  49123. "id": {
  49124. "type": "string",
  49125. "unique": true
  49126. },
  49127. "title": {
  49128. "type": "string"
  49129. },
  49130. "pageTimings": {
  49131. "$ref": "pageTimings.json#"
  49132. },
  49133. "comment": {
  49134. "type": "string"
  49135. }
  49136. }
  49137. }
  49138. },{}],272:[function(require,module,exports){
  49139. module.exports={
  49140. "$id": "pageTimings.json#",
  49141. "$schema": "http://json-schema.org/draft-06/schema#",
  49142. "type": "object",
  49143. "properties": {
  49144. "onContentLoad": {
  49145. "type": "number",
  49146. "min": -1
  49147. },
  49148. "onLoad": {
  49149. "type": "number",
  49150. "min": -1
  49151. },
  49152. "comment": {
  49153. "type": "string"
  49154. }
  49155. }
  49156. }
  49157. },{}],273:[function(require,module,exports){
  49158. module.exports={
  49159. "$id": "postData.json#",
  49160. "$schema": "http://json-schema.org/draft-06/schema#",
  49161. "type": "object",
  49162. "optional": true,
  49163. "required": [
  49164. "mimeType"
  49165. ],
  49166. "properties": {
  49167. "mimeType": {
  49168. "type": "string"
  49169. },
  49170. "text": {
  49171. "type": "string"
  49172. },
  49173. "params": {
  49174. "type": "array",
  49175. "required": [
  49176. "name"
  49177. ],
  49178. "properties": {
  49179. "name": {
  49180. "type": "string"
  49181. },
  49182. "value": {
  49183. "type": "string"
  49184. },
  49185. "fileName": {
  49186. "type": "string"
  49187. },
  49188. "contentType": {
  49189. "type": "string"
  49190. },
  49191. "comment": {
  49192. "type": "string"
  49193. }
  49194. }
  49195. },
  49196. "comment": {
  49197. "type": "string"
  49198. }
  49199. }
  49200. }
  49201. },{}],274:[function(require,module,exports){
  49202. module.exports={
  49203. "$id": "query.json#",
  49204. "$schema": "http://json-schema.org/draft-06/schema#",
  49205. "type": "object",
  49206. "required": [
  49207. "name",
  49208. "value"
  49209. ],
  49210. "properties": {
  49211. "name": {
  49212. "type": "string"
  49213. },
  49214. "value": {
  49215. "type": "string"
  49216. },
  49217. "comment": {
  49218. "type": "string"
  49219. }
  49220. }
  49221. }
  49222. },{}],275:[function(require,module,exports){
  49223. module.exports={
  49224. "$id": "request.json#",
  49225. "$schema": "http://json-schema.org/draft-06/schema#",
  49226. "type": "object",
  49227. "required": [
  49228. "method",
  49229. "url",
  49230. "httpVersion",
  49231. "cookies",
  49232. "headers",
  49233. "queryString",
  49234. "headersSize",
  49235. "bodySize"
  49236. ],
  49237. "properties": {
  49238. "method": {
  49239. "type": "string"
  49240. },
  49241. "url": {
  49242. "type": "string",
  49243. "format": "uri"
  49244. },
  49245. "httpVersion": {
  49246. "type": "string"
  49247. },
  49248. "cookies": {
  49249. "type": "array",
  49250. "items": {
  49251. "$ref": "cookie.json#"
  49252. }
  49253. },
  49254. "headers": {
  49255. "type": "array",
  49256. "items": {
  49257. "$ref": "header.json#"
  49258. }
  49259. },
  49260. "queryString": {
  49261. "type": "array",
  49262. "items": {
  49263. "$ref": "query.json#"
  49264. }
  49265. },
  49266. "postData": {
  49267. "$ref": "postData.json#"
  49268. },
  49269. "headersSize": {
  49270. "type": "integer"
  49271. },
  49272. "bodySize": {
  49273. "type": "integer"
  49274. },
  49275. "comment": {
  49276. "type": "string"
  49277. }
  49278. }
  49279. }
  49280. },{}],276:[function(require,module,exports){
  49281. module.exports={
  49282. "$id": "response.json#",
  49283. "$schema": "http://json-schema.org/draft-06/schema#",
  49284. "type": "object",
  49285. "required": [
  49286. "status",
  49287. "statusText",
  49288. "httpVersion",
  49289. "cookies",
  49290. "headers",
  49291. "content",
  49292. "redirectURL",
  49293. "headersSize",
  49294. "bodySize"
  49295. ],
  49296. "properties": {
  49297. "status": {
  49298. "type": "integer"
  49299. },
  49300. "statusText": {
  49301. "type": "string"
  49302. },
  49303. "httpVersion": {
  49304. "type": "string"
  49305. },
  49306. "cookies": {
  49307. "type": "array",
  49308. "items": {
  49309. "$ref": "cookie.json#"
  49310. }
  49311. },
  49312. "headers": {
  49313. "type": "array",
  49314. "items": {
  49315. "$ref": "header.json#"
  49316. }
  49317. },
  49318. "content": {
  49319. "$ref": "content.json#"
  49320. },
  49321. "redirectURL": {
  49322. "type": "string"
  49323. },
  49324. "headersSize": {
  49325. "type": "integer"
  49326. },
  49327. "bodySize": {
  49328. "type": "integer"
  49329. },
  49330. "comment": {
  49331. "type": "string"
  49332. }
  49333. }
  49334. }
  49335. },{}],277:[function(require,module,exports){
  49336. module.exports={
  49337. "$id": "timings.json#",
  49338. "$schema": "http://json-schema.org/draft-06/schema#",
  49339. "required": [
  49340. "send",
  49341. "wait",
  49342. "receive"
  49343. ],
  49344. "properties": {
  49345. "dns": {
  49346. "type": "number",
  49347. "min": -1
  49348. },
  49349. "connect": {
  49350. "type": "number",
  49351. "min": -1
  49352. },
  49353. "blocked": {
  49354. "type": "number",
  49355. "min": -1
  49356. },
  49357. "send": {
  49358. "type": "number",
  49359. "min": -1
  49360. },
  49361. "wait": {
  49362. "type": "number",
  49363. "min": -1
  49364. },
  49365. "receive": {
  49366. "type": "number",
  49367. "min": -1
  49368. },
  49369. "ssl": {
  49370. "type": "number",
  49371. "min": -1
  49372. },
  49373. "comment": {
  49374. "type": "string"
  49375. }
  49376. }
  49377. }
  49378. },{}],278:[function(require,module,exports){
  49379. function HARError (errors) {
  49380. var message = 'validation failed'
  49381. this.name = 'HARError'
  49382. this.message = message
  49383. this.errors = errors
  49384. if (typeof Error.captureStackTrace === 'function') {
  49385. Error.captureStackTrace(this, this.constructor)
  49386. } else {
  49387. this.stack = (new Error(message)).stack
  49388. }
  49389. }
  49390. HARError.prototype = Error.prototype
  49391. module.exports = HARError
  49392. },{}],279:[function(require,module,exports){
  49393. var Ajv = require('ajv')
  49394. var HARError = require('./error')
  49395. var schemas = require('har-schema')
  49396. var ajv
  49397. function createAjvInstance () {
  49398. var ajv = new Ajv({
  49399. allErrors: true
  49400. })
  49401. ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
  49402. ajv.addSchema(schemas)
  49403. return ajv
  49404. }
  49405. function validate (name, data) {
  49406. data = data || {}
  49407. // validator config
  49408. ajv = ajv || createAjvInstance()
  49409. var validate = ajv.getSchema(name + '.json')
  49410. return new Promise(function (resolve, reject) {
  49411. var valid = validate(data)
  49412. !valid ? reject(new HARError(validate.errors)) : resolve(data)
  49413. })
  49414. }
  49415. exports.afterRequest = function (data) {
  49416. return validate('afterRequest', data)
  49417. }
  49418. exports.beforeRequest = function (data) {
  49419. return validate('beforeRequest', data)
  49420. }
  49421. exports.browser = function (data) {
  49422. return validate('browser', data)
  49423. }
  49424. exports.cache = function (data) {
  49425. return validate('cache', data)
  49426. }
  49427. exports.content = function (data) {
  49428. return validate('content', data)
  49429. }
  49430. exports.cookie = function (data) {
  49431. return validate('cookie', data)
  49432. }
  49433. exports.creator = function (data) {
  49434. return validate('creator', data)
  49435. }
  49436. exports.entry = function (data) {
  49437. return validate('entry', data)
  49438. }
  49439. exports.har = function (data) {
  49440. return validate('har', data)
  49441. }
  49442. exports.header = function (data) {
  49443. return validate('header', data)
  49444. }
  49445. exports.log = function (data) {
  49446. return validate('log', data)
  49447. }
  49448. exports.page = function (data) {
  49449. return validate('page', data)
  49450. }
  49451. exports.pageTimings = function (data) {
  49452. return validate('pageTimings', data)
  49453. }
  49454. exports.postData = function (data) {
  49455. return validate('postData', data)
  49456. }
  49457. exports.query = function (data) {
  49458. return validate('query', data)
  49459. }
  49460. exports.request = function (data) {
  49461. return validate('request', data)
  49462. }
  49463. exports.response = function (data) {
  49464. return validate('response', data)
  49465. }
  49466. exports.timings = function (data) {
  49467. return validate('timings', data)
  49468. }
  49469. },{"./error":278,"ajv":39,"ajv/lib/refs/json-schema-draft-06.json":80,"har-schema":269}],280:[function(require,module,exports){
  49470. (function (global){(function (){
  49471. 'use strict';
  49472. var origSymbol = global.Symbol;
  49473. var hasSymbolSham = require('./shams');
  49474. module.exports = function hasNativeSymbols() {
  49475. if (typeof origSymbol !== 'function') { return false; }
  49476. if (typeof Symbol !== 'function') { return false; }
  49477. if (typeof origSymbol('foo') !== 'symbol') { return false; }
  49478. if (typeof Symbol('bar') !== 'symbol') { return false; }
  49479. return hasSymbolSham();
  49480. };
  49481. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  49482. },{"./shams":281}],281:[function(require,module,exports){
  49483. 'use strict';
  49484. /* eslint complexity: [2, 18], max-statements: [2, 33] */
  49485. module.exports = function hasSymbols() {
  49486. if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
  49487. if (typeof Symbol.iterator === 'symbol') { return true; }
  49488. var obj = {};
  49489. var sym = Symbol('test');
  49490. var symObj = Object(sym);
  49491. if (typeof sym === 'string') { return false; }
  49492. if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
  49493. if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
  49494. // temp disabled per https://github.com/ljharb/object.assign/issues/17
  49495. // if (sym instanceof Symbol) { return false; }
  49496. // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
  49497. // if (!(symObj instanceof Symbol)) { return false; }
  49498. // if (typeof Symbol.prototype.toString !== 'function') { return false; }
  49499. // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
  49500. var symVal = 42;
  49501. obj[sym] = symVal;
  49502. for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax
  49503. if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
  49504. if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
  49505. var syms = Object.getOwnPropertySymbols(obj);
  49506. if (syms.length !== 1 || syms[0] !== sym) { return false; }
  49507. if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
  49508. if (typeof Object.getOwnPropertyDescriptor === 'function') {
  49509. var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
  49510. if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
  49511. }
  49512. return true;
  49513. };
  49514. },{}],282:[function(require,module,exports){
  49515. 'use strict';
  49516. var bind = require('function-bind');
  49517. module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
  49518. },{"function-bind":257}],283:[function(require,module,exports){
  49519. 'use strict'
  49520. var Buffer = require('safe-buffer').Buffer
  49521. var Transform = require('readable-stream').Transform
  49522. var inherits = require('inherits')
  49523. function throwIfNotStringOrBuffer (val, prefix) {
  49524. if (!Buffer.isBuffer(val) && typeof val !== 'string') {
  49525. throw new TypeError(prefix + ' must be a string or a buffer')
  49526. }
  49527. }
  49528. function HashBase (blockSize) {
  49529. Transform.call(this)
  49530. this._block = Buffer.allocUnsafe(blockSize)
  49531. this._blockSize = blockSize
  49532. this._blockOffset = 0
  49533. this._length = [0, 0, 0, 0]
  49534. this._finalized = false
  49535. }
  49536. inherits(HashBase, Transform)
  49537. HashBase.prototype._transform = function (chunk, encoding, callback) {
  49538. var error = null
  49539. try {
  49540. this.update(chunk, encoding)
  49541. } catch (err) {
  49542. error = err
  49543. }
  49544. callback(error)
  49545. }
  49546. HashBase.prototype._flush = function (callback) {
  49547. var error = null
  49548. try {
  49549. this.push(this.digest())
  49550. } catch (err) {
  49551. error = err
  49552. }
  49553. callback(error)
  49554. }
  49555. HashBase.prototype.update = function (data, encoding) {
  49556. throwIfNotStringOrBuffer(data, 'Data')
  49557. if (this._finalized) throw new Error('Digest already called')
  49558. if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
  49559. // consume data
  49560. var block = this._block
  49561. var offset = 0
  49562. while (this._blockOffset + data.length - offset >= this._blockSize) {
  49563. for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
  49564. this._update()
  49565. this._blockOffset = 0
  49566. }
  49567. while (offset < data.length) block[this._blockOffset++] = data[offset++]
  49568. // update length
  49569. for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
  49570. this._length[j] += carry
  49571. carry = (this._length[j] / 0x0100000000) | 0
  49572. if (carry > 0) this._length[j] -= 0x0100000000 * carry
  49573. }
  49574. return this
  49575. }
  49576. HashBase.prototype._update = function () {
  49577. throw new Error('_update is not implemented')
  49578. }
  49579. HashBase.prototype.digest = function (encoding) {
  49580. if (this._finalized) throw new Error('Digest already called')
  49581. this._finalized = true
  49582. var digest = this._digest()
  49583. if (encoding !== undefined) digest = digest.toString(encoding)
  49584. // reset state
  49585. this._block.fill(0)
  49586. this._blockOffset = 0
  49587. for (var i = 0; i < 4; ++i) this._length[i] = 0
  49588. return digest
  49589. }
  49590. HashBase.prototype._digest = function () {
  49591. throw new Error('_digest is not implemented')
  49592. }
  49593. module.exports = HashBase
  49594. },{"inherits":320,"readable-stream":298,"safe-buffer":299}],284:[function(require,module,exports){
  49595. arguments[4][172][0].apply(exports,arguments)
  49596. },{"dup":172}],285:[function(require,module,exports){
  49597. arguments[4][173][0].apply(exports,arguments)
  49598. },{"./_stream_readable":287,"./_stream_writable":289,"_process":525,"dup":173,"inherits":320}],286:[function(require,module,exports){
  49599. arguments[4][174][0].apply(exports,arguments)
  49600. },{"./_stream_transform":288,"dup":174,"inherits":320}],287:[function(require,module,exports){
  49601. arguments[4][175][0].apply(exports,arguments)
  49602. },{"../errors":284,"./_stream_duplex":285,"./internal/streams/async_iterator":290,"./internal/streams/buffer_list":291,"./internal/streams/destroy":292,"./internal/streams/from":294,"./internal/streams/state":296,"./internal/streams/stream":297,"_process":525,"buffer":193,"dup":175,"events":247,"inherits":320,"string_decoder/":631,"util":144}],288:[function(require,module,exports){
  49603. arguments[4][176][0].apply(exports,arguments)
  49604. },{"../errors":284,"./_stream_duplex":285,"dup":176,"inherits":320}],289:[function(require,module,exports){
  49605. arguments[4][177][0].apply(exports,arguments)
  49606. },{"../errors":284,"./_stream_duplex":285,"./internal/streams/destroy":292,"./internal/streams/state":296,"./internal/streams/stream":297,"_process":525,"buffer":193,"dup":177,"inherits":320,"util-deprecate":655}],290:[function(require,module,exports){
  49607. arguments[4][178][0].apply(exports,arguments)
  49608. },{"./end-of-stream":293,"_process":525,"dup":178}],291:[function(require,module,exports){
  49609. arguments[4][179][0].apply(exports,arguments)
  49610. },{"buffer":193,"dup":179,"util":144}],292:[function(require,module,exports){
  49611. arguments[4][180][0].apply(exports,arguments)
  49612. },{"_process":525,"dup":180}],293:[function(require,module,exports){
  49613. arguments[4][181][0].apply(exports,arguments)
  49614. },{"../../../errors":284,"dup":181}],294:[function(require,module,exports){
  49615. arguments[4][182][0].apply(exports,arguments)
  49616. },{"dup":182}],295:[function(require,module,exports){
  49617. arguments[4][183][0].apply(exports,arguments)
  49618. },{"../../../errors":284,"./end-of-stream":293,"dup":183}],296:[function(require,module,exports){
  49619. arguments[4][184][0].apply(exports,arguments)
  49620. },{"../../../errors":284,"dup":184}],297:[function(require,module,exports){
  49621. arguments[4][185][0].apply(exports,arguments)
  49622. },{"dup":185,"events":247}],298:[function(require,module,exports){
  49623. arguments[4][186][0].apply(exports,arguments)
  49624. },{"./lib/_stream_duplex.js":285,"./lib/_stream_passthrough.js":286,"./lib/_stream_readable.js":287,"./lib/_stream_transform.js":288,"./lib/_stream_writable.js":289,"./lib/internal/streams/end-of-stream.js":293,"./lib/internal/streams/pipeline.js":295,"dup":186}],299:[function(require,module,exports){
  49625. arguments[4][187][0].apply(exports,arguments)
  49626. },{"buffer":193,"dup":187}],300:[function(require,module,exports){
  49627. var hash = exports;
  49628. hash.utils = require('./hash/utils');
  49629. hash.common = require('./hash/common');
  49630. hash.sha = require('./hash/sha');
  49631. hash.ripemd = require('./hash/ripemd');
  49632. hash.hmac = require('./hash/hmac');
  49633. // Proxy hash functions to the main object
  49634. hash.sha1 = hash.sha.sha1;
  49635. hash.sha256 = hash.sha.sha256;
  49636. hash.sha224 = hash.sha.sha224;
  49637. hash.sha384 = hash.sha.sha384;
  49638. hash.sha512 = hash.sha.sha512;
  49639. hash.ripemd160 = hash.ripemd.ripemd160;
  49640. },{"./hash/common":301,"./hash/hmac":302,"./hash/ripemd":303,"./hash/sha":304,"./hash/utils":311}],301:[function(require,module,exports){
  49641. 'use strict';
  49642. var utils = require('./utils');
  49643. var assert = require('minimalistic-assert');
  49644. function BlockHash() {
  49645. this.pending = null;
  49646. this.pendingTotal = 0;
  49647. this.blockSize = this.constructor.blockSize;
  49648. this.outSize = this.constructor.outSize;
  49649. this.hmacStrength = this.constructor.hmacStrength;
  49650. this.padLength = this.constructor.padLength / 8;
  49651. this.endian = 'big';
  49652. this._delta8 = this.blockSize / 8;
  49653. this._delta32 = this.blockSize / 32;
  49654. }
  49655. exports.BlockHash = BlockHash;
  49656. BlockHash.prototype.update = function update(msg, enc) {
  49657. // Convert message to array, pad it, and join into 32bit blocks
  49658. msg = utils.toArray(msg, enc);
  49659. if (!this.pending)
  49660. this.pending = msg;
  49661. else
  49662. this.pending = this.pending.concat(msg);
  49663. this.pendingTotal += msg.length;
  49664. // Enough data, try updating
  49665. if (this.pending.length >= this._delta8) {
  49666. msg = this.pending;
  49667. // Process pending data in blocks
  49668. var r = msg.length % this._delta8;
  49669. this.pending = msg.slice(msg.length - r, msg.length);
  49670. if (this.pending.length === 0)
  49671. this.pending = null;
  49672. msg = utils.join32(msg, 0, msg.length - r, this.endian);
  49673. for (var i = 0; i < msg.length; i += this._delta32)
  49674. this._update(msg, i, i + this._delta32);
  49675. }
  49676. return this;
  49677. };
  49678. BlockHash.prototype.digest = function digest(enc) {
  49679. this.update(this._pad());
  49680. assert(this.pending === null);
  49681. return this._digest(enc);
  49682. };
  49683. BlockHash.prototype._pad = function pad() {
  49684. var len = this.pendingTotal;
  49685. var bytes = this._delta8;
  49686. var k = bytes - ((len + this.padLength) % bytes);
  49687. var res = new Array(k + this.padLength);
  49688. res[0] = 0x80;
  49689. for (var i = 1; i < k; i++)
  49690. res[i] = 0;
  49691. // Append length
  49692. len <<= 3;
  49693. if (this.endian === 'big') {
  49694. for (var t = 8; t < this.padLength; t++)
  49695. res[i++] = 0;
  49696. res[i++] = 0;
  49697. res[i++] = 0;
  49698. res[i++] = 0;
  49699. res[i++] = 0;
  49700. res[i++] = (len >>> 24) & 0xff;
  49701. res[i++] = (len >>> 16) & 0xff;
  49702. res[i++] = (len >>> 8) & 0xff;
  49703. res[i++] = len & 0xff;
  49704. } else {
  49705. res[i++] = len & 0xff;
  49706. res[i++] = (len >>> 8) & 0xff;
  49707. res[i++] = (len >>> 16) & 0xff;
  49708. res[i++] = (len >>> 24) & 0xff;
  49709. res[i++] = 0;
  49710. res[i++] = 0;
  49711. res[i++] = 0;
  49712. res[i++] = 0;
  49713. for (t = 8; t < this.padLength; t++)
  49714. res[i++] = 0;
  49715. }
  49716. return res;
  49717. };
  49718. },{"./utils":311,"minimalistic-assert":345}],302:[function(require,module,exports){
  49719. 'use strict';
  49720. var utils = require('./utils');
  49721. var assert = require('minimalistic-assert');
  49722. function Hmac(hash, key, enc) {
  49723. if (!(this instanceof Hmac))
  49724. return new Hmac(hash, key, enc);
  49725. this.Hash = hash;
  49726. this.blockSize = hash.blockSize / 8;
  49727. this.outSize = hash.outSize / 8;
  49728. this.inner = null;
  49729. this.outer = null;
  49730. this._init(utils.toArray(key, enc));
  49731. }
  49732. module.exports = Hmac;
  49733. Hmac.prototype._init = function init(key) {
  49734. // Shorten key, if needed
  49735. if (key.length > this.blockSize)
  49736. key = new this.Hash().update(key).digest();
  49737. assert(key.length <= this.blockSize);
  49738. // Add padding to key
  49739. for (var i = key.length; i < this.blockSize; i++)
  49740. key.push(0);
  49741. for (i = 0; i < key.length; i++)
  49742. key[i] ^= 0x36;
  49743. this.inner = new this.Hash().update(key);
  49744. // 0x36 ^ 0x5c = 0x6a
  49745. for (i = 0; i < key.length; i++)
  49746. key[i] ^= 0x6a;
  49747. this.outer = new this.Hash().update(key);
  49748. };
  49749. Hmac.prototype.update = function update(msg, enc) {
  49750. this.inner.update(msg, enc);
  49751. return this;
  49752. };
  49753. Hmac.prototype.digest = function digest(enc) {
  49754. this.outer.update(this.inner.digest());
  49755. return this.outer.digest(enc);
  49756. };
  49757. },{"./utils":311,"minimalistic-assert":345}],303:[function(require,module,exports){
  49758. 'use strict';
  49759. var utils = require('./utils');
  49760. var common = require('./common');
  49761. var rotl32 = utils.rotl32;
  49762. var sum32 = utils.sum32;
  49763. var sum32_3 = utils.sum32_3;
  49764. var sum32_4 = utils.sum32_4;
  49765. var BlockHash = common.BlockHash;
  49766. function RIPEMD160() {
  49767. if (!(this instanceof RIPEMD160))
  49768. return new RIPEMD160();
  49769. BlockHash.call(this);
  49770. this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
  49771. this.endian = 'little';
  49772. }
  49773. utils.inherits(RIPEMD160, BlockHash);
  49774. exports.ripemd160 = RIPEMD160;
  49775. RIPEMD160.blockSize = 512;
  49776. RIPEMD160.outSize = 160;
  49777. RIPEMD160.hmacStrength = 192;
  49778. RIPEMD160.padLength = 64;
  49779. RIPEMD160.prototype._update = function update(msg, start) {
  49780. var A = this.h[0];
  49781. var B = this.h[1];
  49782. var C = this.h[2];
  49783. var D = this.h[3];
  49784. var E = this.h[4];
  49785. var Ah = A;
  49786. var Bh = B;
  49787. var Ch = C;
  49788. var Dh = D;
  49789. var Eh = E;
  49790. for (var j = 0; j < 80; j++) {
  49791. var T = sum32(
  49792. rotl32(
  49793. sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
  49794. s[j]),
  49795. E);
  49796. A = E;
  49797. E = D;
  49798. D = rotl32(C, 10);
  49799. C = B;
  49800. B = T;
  49801. T = sum32(
  49802. rotl32(
  49803. sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
  49804. sh[j]),
  49805. Eh);
  49806. Ah = Eh;
  49807. Eh = Dh;
  49808. Dh = rotl32(Ch, 10);
  49809. Ch = Bh;
  49810. Bh = T;
  49811. }
  49812. T = sum32_3(this.h[1], C, Dh);
  49813. this.h[1] = sum32_3(this.h[2], D, Eh);
  49814. this.h[2] = sum32_3(this.h[3], E, Ah);
  49815. this.h[3] = sum32_3(this.h[4], A, Bh);
  49816. this.h[4] = sum32_3(this.h[0], B, Ch);
  49817. this.h[0] = T;
  49818. };
  49819. RIPEMD160.prototype._digest = function digest(enc) {
  49820. if (enc === 'hex')
  49821. return utils.toHex32(this.h, 'little');
  49822. else
  49823. return utils.split32(this.h, 'little');
  49824. };
  49825. function f(j, x, y, z) {
  49826. if (j <= 15)
  49827. return x ^ y ^ z;
  49828. else if (j <= 31)
  49829. return (x & y) | ((~x) & z);
  49830. else if (j <= 47)
  49831. return (x | (~y)) ^ z;
  49832. else if (j <= 63)
  49833. return (x & z) | (y & (~z));
  49834. else
  49835. return x ^ (y | (~z));
  49836. }
  49837. function K(j) {
  49838. if (j <= 15)
  49839. return 0x00000000;
  49840. else if (j <= 31)
  49841. return 0x5a827999;
  49842. else if (j <= 47)
  49843. return 0x6ed9eba1;
  49844. else if (j <= 63)
  49845. return 0x8f1bbcdc;
  49846. else
  49847. return 0xa953fd4e;
  49848. }
  49849. function Kh(j) {
  49850. if (j <= 15)
  49851. return 0x50a28be6;
  49852. else if (j <= 31)
  49853. return 0x5c4dd124;
  49854. else if (j <= 47)
  49855. return 0x6d703ef3;
  49856. else if (j <= 63)
  49857. return 0x7a6d76e9;
  49858. else
  49859. return 0x00000000;
  49860. }
  49861. var r = [
  49862. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  49863. 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  49864. 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  49865. 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  49866. 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
  49867. ];
  49868. var rh = [
  49869. 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  49870. 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  49871. 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  49872. 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  49873. 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
  49874. ];
  49875. var s = [
  49876. 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  49877. 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  49878. 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  49879. 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  49880. 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
  49881. ];
  49882. var sh = [
  49883. 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  49884. 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  49885. 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  49886. 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  49887. 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
  49888. ];
  49889. },{"./common":301,"./utils":311}],304:[function(require,module,exports){
  49890. 'use strict';
  49891. exports.sha1 = require('./sha/1');
  49892. exports.sha224 = require('./sha/224');
  49893. exports.sha256 = require('./sha/256');
  49894. exports.sha384 = require('./sha/384');
  49895. exports.sha512 = require('./sha/512');
  49896. },{"./sha/1":305,"./sha/224":306,"./sha/256":307,"./sha/384":308,"./sha/512":309}],305:[function(require,module,exports){
  49897. 'use strict';
  49898. var utils = require('../utils');
  49899. var common = require('../common');
  49900. var shaCommon = require('./common');
  49901. var rotl32 = utils.rotl32;
  49902. var sum32 = utils.sum32;
  49903. var sum32_5 = utils.sum32_5;
  49904. var ft_1 = shaCommon.ft_1;
  49905. var BlockHash = common.BlockHash;
  49906. var sha1_K = [
  49907. 0x5A827999, 0x6ED9EBA1,
  49908. 0x8F1BBCDC, 0xCA62C1D6
  49909. ];
  49910. function SHA1() {
  49911. if (!(this instanceof SHA1))
  49912. return new SHA1();
  49913. BlockHash.call(this);
  49914. this.h = [
  49915. 0x67452301, 0xefcdab89, 0x98badcfe,
  49916. 0x10325476, 0xc3d2e1f0 ];
  49917. this.W = new Array(80);
  49918. }
  49919. utils.inherits(SHA1, BlockHash);
  49920. module.exports = SHA1;
  49921. SHA1.blockSize = 512;
  49922. SHA1.outSize = 160;
  49923. SHA1.hmacStrength = 80;
  49924. SHA1.padLength = 64;
  49925. SHA1.prototype._update = function _update(msg, start) {
  49926. var W = this.W;
  49927. for (var i = 0; i < 16; i++)
  49928. W[i] = msg[start + i];
  49929. for(; i < W.length; i++)
  49930. W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
  49931. var a = this.h[0];
  49932. var b = this.h[1];
  49933. var c = this.h[2];
  49934. var d = this.h[3];
  49935. var e = this.h[4];
  49936. for (i = 0; i < W.length; i++) {
  49937. var s = ~~(i / 20);
  49938. var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
  49939. e = d;
  49940. d = c;
  49941. c = rotl32(b, 30);
  49942. b = a;
  49943. a = t;
  49944. }
  49945. this.h[0] = sum32(this.h[0], a);
  49946. this.h[1] = sum32(this.h[1], b);
  49947. this.h[2] = sum32(this.h[2], c);
  49948. this.h[3] = sum32(this.h[3], d);
  49949. this.h[4] = sum32(this.h[4], e);
  49950. };
  49951. SHA1.prototype._digest = function digest(enc) {
  49952. if (enc === 'hex')
  49953. return utils.toHex32(this.h, 'big');
  49954. else
  49955. return utils.split32(this.h, 'big');
  49956. };
  49957. },{"../common":301,"../utils":311,"./common":310}],306:[function(require,module,exports){
  49958. 'use strict';
  49959. var utils = require('../utils');
  49960. var SHA256 = require('./256');
  49961. function SHA224() {
  49962. if (!(this instanceof SHA224))
  49963. return new SHA224();
  49964. SHA256.call(this);
  49965. this.h = [
  49966. 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
  49967. 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
  49968. }
  49969. utils.inherits(SHA224, SHA256);
  49970. module.exports = SHA224;
  49971. SHA224.blockSize = 512;
  49972. SHA224.outSize = 224;
  49973. SHA224.hmacStrength = 192;
  49974. SHA224.padLength = 64;
  49975. SHA224.prototype._digest = function digest(enc) {
  49976. // Just truncate output
  49977. if (enc === 'hex')
  49978. return utils.toHex32(this.h.slice(0, 7), 'big');
  49979. else
  49980. return utils.split32(this.h.slice(0, 7), 'big');
  49981. };
  49982. },{"../utils":311,"./256":307}],307:[function(require,module,exports){
  49983. 'use strict';
  49984. var utils = require('../utils');
  49985. var common = require('../common');
  49986. var shaCommon = require('./common');
  49987. var assert = require('minimalistic-assert');
  49988. var sum32 = utils.sum32;
  49989. var sum32_4 = utils.sum32_4;
  49990. var sum32_5 = utils.sum32_5;
  49991. var ch32 = shaCommon.ch32;
  49992. var maj32 = shaCommon.maj32;
  49993. var s0_256 = shaCommon.s0_256;
  49994. var s1_256 = shaCommon.s1_256;
  49995. var g0_256 = shaCommon.g0_256;
  49996. var g1_256 = shaCommon.g1_256;
  49997. var BlockHash = common.BlockHash;
  49998. var sha256_K = [
  49999. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  50000. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  50001. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  50002. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  50003. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  50004. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  50005. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  50006. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  50007. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  50008. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  50009. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  50010. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  50011. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  50012. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  50013. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  50014. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  50015. ];
  50016. function SHA256() {
  50017. if (!(this instanceof SHA256))
  50018. return new SHA256();
  50019. BlockHash.call(this);
  50020. this.h = [
  50021. 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
  50022. 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  50023. ];
  50024. this.k = sha256_K;
  50025. this.W = new Array(64);
  50026. }
  50027. utils.inherits(SHA256, BlockHash);
  50028. module.exports = SHA256;
  50029. SHA256.blockSize = 512;
  50030. SHA256.outSize = 256;
  50031. SHA256.hmacStrength = 192;
  50032. SHA256.padLength = 64;
  50033. SHA256.prototype._update = function _update(msg, start) {
  50034. var W = this.W;
  50035. for (var i = 0; i < 16; i++)
  50036. W[i] = msg[start + i];
  50037. for (; i < W.length; i++)
  50038. W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
  50039. var a = this.h[0];
  50040. var b = this.h[1];
  50041. var c = this.h[2];
  50042. var d = this.h[3];
  50043. var e = this.h[4];
  50044. var f = this.h[5];
  50045. var g = this.h[6];
  50046. var h = this.h[7];
  50047. assert(this.k.length === W.length);
  50048. for (i = 0; i < W.length; i++) {
  50049. var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
  50050. var T2 = sum32(s0_256(a), maj32(a, b, c));
  50051. h = g;
  50052. g = f;
  50053. f = e;
  50054. e = sum32(d, T1);
  50055. d = c;
  50056. c = b;
  50057. b = a;
  50058. a = sum32(T1, T2);
  50059. }
  50060. this.h[0] = sum32(this.h[0], a);
  50061. this.h[1] = sum32(this.h[1], b);
  50062. this.h[2] = sum32(this.h[2], c);
  50063. this.h[3] = sum32(this.h[3], d);
  50064. this.h[4] = sum32(this.h[4], e);
  50065. this.h[5] = sum32(this.h[5], f);
  50066. this.h[6] = sum32(this.h[6], g);
  50067. this.h[7] = sum32(this.h[7], h);
  50068. };
  50069. SHA256.prototype._digest = function digest(enc) {
  50070. if (enc === 'hex')
  50071. return utils.toHex32(this.h, 'big');
  50072. else
  50073. return utils.split32(this.h, 'big');
  50074. };
  50075. },{"../common":301,"../utils":311,"./common":310,"minimalistic-assert":345}],308:[function(require,module,exports){
  50076. 'use strict';
  50077. var utils = require('../utils');
  50078. var SHA512 = require('./512');
  50079. function SHA384() {
  50080. if (!(this instanceof SHA384))
  50081. return new SHA384();
  50082. SHA512.call(this);
  50083. this.h = [
  50084. 0xcbbb9d5d, 0xc1059ed8,
  50085. 0x629a292a, 0x367cd507,
  50086. 0x9159015a, 0x3070dd17,
  50087. 0x152fecd8, 0xf70e5939,
  50088. 0x67332667, 0xffc00b31,
  50089. 0x8eb44a87, 0x68581511,
  50090. 0xdb0c2e0d, 0x64f98fa7,
  50091. 0x47b5481d, 0xbefa4fa4 ];
  50092. }
  50093. utils.inherits(SHA384, SHA512);
  50094. module.exports = SHA384;
  50095. SHA384.blockSize = 1024;
  50096. SHA384.outSize = 384;
  50097. SHA384.hmacStrength = 192;
  50098. SHA384.padLength = 128;
  50099. SHA384.prototype._digest = function digest(enc) {
  50100. if (enc === 'hex')
  50101. return utils.toHex32(this.h.slice(0, 12), 'big');
  50102. else
  50103. return utils.split32(this.h.slice(0, 12), 'big');
  50104. };
  50105. },{"../utils":311,"./512":309}],309:[function(require,module,exports){
  50106. 'use strict';
  50107. var utils = require('../utils');
  50108. var common = require('../common');
  50109. var assert = require('minimalistic-assert');
  50110. var rotr64_hi = utils.rotr64_hi;
  50111. var rotr64_lo = utils.rotr64_lo;
  50112. var shr64_hi = utils.shr64_hi;
  50113. var shr64_lo = utils.shr64_lo;
  50114. var sum64 = utils.sum64;
  50115. var sum64_hi = utils.sum64_hi;
  50116. var sum64_lo = utils.sum64_lo;
  50117. var sum64_4_hi = utils.sum64_4_hi;
  50118. var sum64_4_lo = utils.sum64_4_lo;
  50119. var sum64_5_hi = utils.sum64_5_hi;
  50120. var sum64_5_lo = utils.sum64_5_lo;
  50121. var BlockHash = common.BlockHash;
  50122. var sha512_K = [
  50123. 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  50124. 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  50125. 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  50126. 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  50127. 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  50128. 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  50129. 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  50130. 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  50131. 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  50132. 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  50133. 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  50134. 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  50135. 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  50136. 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  50137. 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  50138. 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  50139. 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  50140. 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  50141. 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  50142. 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  50143. 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  50144. 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  50145. 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  50146. 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  50147. 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  50148. 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  50149. 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  50150. 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  50151. 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  50152. 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  50153. 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  50154. 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  50155. 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  50156. 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  50157. 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  50158. 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  50159. 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  50160. 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  50161. 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  50162. 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  50163. ];
  50164. function SHA512() {
  50165. if (!(this instanceof SHA512))
  50166. return new SHA512();
  50167. BlockHash.call(this);
  50168. this.h = [
  50169. 0x6a09e667, 0xf3bcc908,
  50170. 0xbb67ae85, 0x84caa73b,
  50171. 0x3c6ef372, 0xfe94f82b,
  50172. 0xa54ff53a, 0x5f1d36f1,
  50173. 0x510e527f, 0xade682d1,
  50174. 0x9b05688c, 0x2b3e6c1f,
  50175. 0x1f83d9ab, 0xfb41bd6b,
  50176. 0x5be0cd19, 0x137e2179 ];
  50177. this.k = sha512_K;
  50178. this.W = new Array(160);
  50179. }
  50180. utils.inherits(SHA512, BlockHash);
  50181. module.exports = SHA512;
  50182. SHA512.blockSize = 1024;
  50183. SHA512.outSize = 512;
  50184. SHA512.hmacStrength = 192;
  50185. SHA512.padLength = 128;
  50186. SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
  50187. var W = this.W;
  50188. // 32 x 32bit words
  50189. for (var i = 0; i < 32; i++)
  50190. W[i] = msg[start + i];
  50191. for (; i < W.length; i += 2) {
  50192. var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
  50193. var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
  50194. var c1_hi = W[i - 14]; // i - 7
  50195. var c1_lo = W[i - 13];
  50196. var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
  50197. var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
  50198. var c3_hi = W[i - 32]; // i - 16
  50199. var c3_lo = W[i - 31];
  50200. W[i] = sum64_4_hi(
  50201. c0_hi, c0_lo,
  50202. c1_hi, c1_lo,
  50203. c2_hi, c2_lo,
  50204. c3_hi, c3_lo);
  50205. W[i + 1] = sum64_4_lo(
  50206. c0_hi, c0_lo,
  50207. c1_hi, c1_lo,
  50208. c2_hi, c2_lo,
  50209. c3_hi, c3_lo);
  50210. }
  50211. };
  50212. SHA512.prototype._update = function _update(msg, start) {
  50213. this._prepareBlock(msg, start);
  50214. var W = this.W;
  50215. var ah = this.h[0];
  50216. var al = this.h[1];
  50217. var bh = this.h[2];
  50218. var bl = this.h[3];
  50219. var ch = this.h[4];
  50220. var cl = this.h[5];
  50221. var dh = this.h[6];
  50222. var dl = this.h[7];
  50223. var eh = this.h[8];
  50224. var el = this.h[9];
  50225. var fh = this.h[10];
  50226. var fl = this.h[11];
  50227. var gh = this.h[12];
  50228. var gl = this.h[13];
  50229. var hh = this.h[14];
  50230. var hl = this.h[15];
  50231. assert(this.k.length === W.length);
  50232. for (var i = 0; i < W.length; i += 2) {
  50233. var c0_hi = hh;
  50234. var c0_lo = hl;
  50235. var c1_hi = s1_512_hi(eh, el);
  50236. var c1_lo = s1_512_lo(eh, el);
  50237. var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
  50238. var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
  50239. var c3_hi = this.k[i];
  50240. var c3_lo = this.k[i + 1];
  50241. var c4_hi = W[i];
  50242. var c4_lo = W[i + 1];
  50243. var T1_hi = sum64_5_hi(
  50244. c0_hi, c0_lo,
  50245. c1_hi, c1_lo,
  50246. c2_hi, c2_lo,
  50247. c3_hi, c3_lo,
  50248. c4_hi, c4_lo);
  50249. var T1_lo = sum64_5_lo(
  50250. c0_hi, c0_lo,
  50251. c1_hi, c1_lo,
  50252. c2_hi, c2_lo,
  50253. c3_hi, c3_lo,
  50254. c4_hi, c4_lo);
  50255. c0_hi = s0_512_hi(ah, al);
  50256. c0_lo = s0_512_lo(ah, al);
  50257. c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
  50258. c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
  50259. var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
  50260. var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
  50261. hh = gh;
  50262. hl = gl;
  50263. gh = fh;
  50264. gl = fl;
  50265. fh = eh;
  50266. fl = el;
  50267. eh = sum64_hi(dh, dl, T1_hi, T1_lo);
  50268. el = sum64_lo(dl, dl, T1_hi, T1_lo);
  50269. dh = ch;
  50270. dl = cl;
  50271. ch = bh;
  50272. cl = bl;
  50273. bh = ah;
  50274. bl = al;
  50275. ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
  50276. al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
  50277. }
  50278. sum64(this.h, 0, ah, al);
  50279. sum64(this.h, 2, bh, bl);
  50280. sum64(this.h, 4, ch, cl);
  50281. sum64(this.h, 6, dh, dl);
  50282. sum64(this.h, 8, eh, el);
  50283. sum64(this.h, 10, fh, fl);
  50284. sum64(this.h, 12, gh, gl);
  50285. sum64(this.h, 14, hh, hl);
  50286. };
  50287. SHA512.prototype._digest = function digest(enc) {
  50288. if (enc === 'hex')
  50289. return utils.toHex32(this.h, 'big');
  50290. else
  50291. return utils.split32(this.h, 'big');
  50292. };
  50293. function ch64_hi(xh, xl, yh, yl, zh) {
  50294. var r = (xh & yh) ^ ((~xh) & zh);
  50295. if (r < 0)
  50296. r += 0x100000000;
  50297. return r;
  50298. }
  50299. function ch64_lo(xh, xl, yh, yl, zh, zl) {
  50300. var r = (xl & yl) ^ ((~xl) & zl);
  50301. if (r < 0)
  50302. r += 0x100000000;
  50303. return r;
  50304. }
  50305. function maj64_hi(xh, xl, yh, yl, zh) {
  50306. var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
  50307. if (r < 0)
  50308. r += 0x100000000;
  50309. return r;
  50310. }
  50311. function maj64_lo(xh, xl, yh, yl, zh, zl) {
  50312. var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
  50313. if (r < 0)
  50314. r += 0x100000000;
  50315. return r;
  50316. }
  50317. function s0_512_hi(xh, xl) {
  50318. var c0_hi = rotr64_hi(xh, xl, 28);
  50319. var c1_hi = rotr64_hi(xl, xh, 2); // 34
  50320. var c2_hi = rotr64_hi(xl, xh, 7); // 39
  50321. var r = c0_hi ^ c1_hi ^ c2_hi;
  50322. if (r < 0)
  50323. r += 0x100000000;
  50324. return r;
  50325. }
  50326. function s0_512_lo(xh, xl) {
  50327. var c0_lo = rotr64_lo(xh, xl, 28);
  50328. var c1_lo = rotr64_lo(xl, xh, 2); // 34
  50329. var c2_lo = rotr64_lo(xl, xh, 7); // 39
  50330. var r = c0_lo ^ c1_lo ^ c2_lo;
  50331. if (r < 0)
  50332. r += 0x100000000;
  50333. return r;
  50334. }
  50335. function s1_512_hi(xh, xl) {
  50336. var c0_hi = rotr64_hi(xh, xl, 14);
  50337. var c1_hi = rotr64_hi(xh, xl, 18);
  50338. var c2_hi = rotr64_hi(xl, xh, 9); // 41
  50339. var r = c0_hi ^ c1_hi ^ c2_hi;
  50340. if (r < 0)
  50341. r += 0x100000000;
  50342. return r;
  50343. }
  50344. function s1_512_lo(xh, xl) {
  50345. var c0_lo = rotr64_lo(xh, xl, 14);
  50346. var c1_lo = rotr64_lo(xh, xl, 18);
  50347. var c2_lo = rotr64_lo(xl, xh, 9); // 41
  50348. var r = c0_lo ^ c1_lo ^ c2_lo;
  50349. if (r < 0)
  50350. r += 0x100000000;
  50351. return r;
  50352. }
  50353. function g0_512_hi(xh, xl) {
  50354. var c0_hi = rotr64_hi(xh, xl, 1);
  50355. var c1_hi = rotr64_hi(xh, xl, 8);
  50356. var c2_hi = shr64_hi(xh, xl, 7);
  50357. var r = c0_hi ^ c1_hi ^ c2_hi;
  50358. if (r < 0)
  50359. r += 0x100000000;
  50360. return r;
  50361. }
  50362. function g0_512_lo(xh, xl) {
  50363. var c0_lo = rotr64_lo(xh, xl, 1);
  50364. var c1_lo = rotr64_lo(xh, xl, 8);
  50365. var c2_lo = shr64_lo(xh, xl, 7);
  50366. var r = c0_lo ^ c1_lo ^ c2_lo;
  50367. if (r < 0)
  50368. r += 0x100000000;
  50369. return r;
  50370. }
  50371. function g1_512_hi(xh, xl) {
  50372. var c0_hi = rotr64_hi(xh, xl, 19);
  50373. var c1_hi = rotr64_hi(xl, xh, 29); // 61
  50374. var c2_hi = shr64_hi(xh, xl, 6);
  50375. var r = c0_hi ^ c1_hi ^ c2_hi;
  50376. if (r < 0)
  50377. r += 0x100000000;
  50378. return r;
  50379. }
  50380. function g1_512_lo(xh, xl) {
  50381. var c0_lo = rotr64_lo(xh, xl, 19);
  50382. var c1_lo = rotr64_lo(xl, xh, 29); // 61
  50383. var c2_lo = shr64_lo(xh, xl, 6);
  50384. var r = c0_lo ^ c1_lo ^ c2_lo;
  50385. if (r < 0)
  50386. r += 0x100000000;
  50387. return r;
  50388. }
  50389. },{"../common":301,"../utils":311,"minimalistic-assert":345}],310:[function(require,module,exports){
  50390. 'use strict';
  50391. var utils = require('../utils');
  50392. var rotr32 = utils.rotr32;
  50393. function ft_1(s, x, y, z) {
  50394. if (s === 0)
  50395. return ch32(x, y, z);
  50396. if (s === 1 || s === 3)
  50397. return p32(x, y, z);
  50398. if (s === 2)
  50399. return maj32(x, y, z);
  50400. }
  50401. exports.ft_1 = ft_1;
  50402. function ch32(x, y, z) {
  50403. return (x & y) ^ ((~x) & z);
  50404. }
  50405. exports.ch32 = ch32;
  50406. function maj32(x, y, z) {
  50407. return (x & y) ^ (x & z) ^ (y & z);
  50408. }
  50409. exports.maj32 = maj32;
  50410. function p32(x, y, z) {
  50411. return x ^ y ^ z;
  50412. }
  50413. exports.p32 = p32;
  50414. function s0_256(x) {
  50415. return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
  50416. }
  50417. exports.s0_256 = s0_256;
  50418. function s1_256(x) {
  50419. return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
  50420. }
  50421. exports.s1_256 = s1_256;
  50422. function g0_256(x) {
  50423. return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
  50424. }
  50425. exports.g0_256 = g0_256;
  50426. function g1_256(x) {
  50427. return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
  50428. }
  50429. exports.g1_256 = g1_256;
  50430. },{"../utils":311}],311:[function(require,module,exports){
  50431. 'use strict';
  50432. var assert = require('minimalistic-assert');
  50433. var inherits = require('inherits');
  50434. exports.inherits = inherits;
  50435. function isSurrogatePair(msg, i) {
  50436. if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
  50437. return false;
  50438. }
  50439. if (i < 0 || i + 1 >= msg.length) {
  50440. return false;
  50441. }
  50442. return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
  50443. }
  50444. function toArray(msg, enc) {
  50445. if (Array.isArray(msg))
  50446. return msg.slice();
  50447. if (!msg)
  50448. return [];
  50449. var res = [];
  50450. if (typeof msg === 'string') {
  50451. if (!enc) {
  50452. // Inspired by stringToUtf8ByteArray() in closure-library by Google
  50453. // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
  50454. // Apache License 2.0
  50455. // https://github.com/google/closure-library/blob/master/LICENSE
  50456. var p = 0;
  50457. for (var i = 0; i < msg.length; i++) {
  50458. var c = msg.charCodeAt(i);
  50459. if (c < 128) {
  50460. res[p++] = c;
  50461. } else if (c < 2048) {
  50462. res[p++] = (c >> 6) | 192;
  50463. res[p++] = (c & 63) | 128;
  50464. } else if (isSurrogatePair(msg, i)) {
  50465. c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
  50466. res[p++] = (c >> 18) | 240;
  50467. res[p++] = ((c >> 12) & 63) | 128;
  50468. res[p++] = ((c >> 6) & 63) | 128;
  50469. res[p++] = (c & 63) | 128;
  50470. } else {
  50471. res[p++] = (c >> 12) | 224;
  50472. res[p++] = ((c >> 6) & 63) | 128;
  50473. res[p++] = (c & 63) | 128;
  50474. }
  50475. }
  50476. } else if (enc === 'hex') {
  50477. msg = msg.replace(/[^a-z0-9]+/ig, '');
  50478. if (msg.length % 2 !== 0)
  50479. msg = '0' + msg;
  50480. for (i = 0; i < msg.length; i += 2)
  50481. res.push(parseInt(msg[i] + msg[i + 1], 16));
  50482. }
  50483. } else {
  50484. for (i = 0; i < msg.length; i++)
  50485. res[i] = msg[i] | 0;
  50486. }
  50487. return res;
  50488. }
  50489. exports.toArray = toArray;
  50490. function toHex(msg) {
  50491. var res = '';
  50492. for (var i = 0; i < msg.length; i++)
  50493. res += zero2(msg[i].toString(16));
  50494. return res;
  50495. }
  50496. exports.toHex = toHex;
  50497. function htonl(w) {
  50498. var res = (w >>> 24) |
  50499. ((w >>> 8) & 0xff00) |
  50500. ((w << 8) & 0xff0000) |
  50501. ((w & 0xff) << 24);
  50502. return res >>> 0;
  50503. }
  50504. exports.htonl = htonl;
  50505. function toHex32(msg, endian) {
  50506. var res = '';
  50507. for (var i = 0; i < msg.length; i++) {
  50508. var w = msg[i];
  50509. if (endian === 'little')
  50510. w = htonl(w);
  50511. res += zero8(w.toString(16));
  50512. }
  50513. return res;
  50514. }
  50515. exports.toHex32 = toHex32;
  50516. function zero2(word) {
  50517. if (word.length === 1)
  50518. return '0' + word;
  50519. else
  50520. return word;
  50521. }
  50522. exports.zero2 = zero2;
  50523. function zero8(word) {
  50524. if (word.length === 7)
  50525. return '0' + word;
  50526. else if (word.length === 6)
  50527. return '00' + word;
  50528. else if (word.length === 5)
  50529. return '000' + word;
  50530. else if (word.length === 4)
  50531. return '0000' + word;
  50532. else if (word.length === 3)
  50533. return '00000' + word;
  50534. else if (word.length === 2)
  50535. return '000000' + word;
  50536. else if (word.length === 1)
  50537. return '0000000' + word;
  50538. else
  50539. return word;
  50540. }
  50541. exports.zero8 = zero8;
  50542. function join32(msg, start, end, endian) {
  50543. var len = end - start;
  50544. assert(len % 4 === 0);
  50545. var res = new Array(len / 4);
  50546. for (var i = 0, k = start; i < res.length; i++, k += 4) {
  50547. var w;
  50548. if (endian === 'big')
  50549. w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
  50550. else
  50551. w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
  50552. res[i] = w >>> 0;
  50553. }
  50554. return res;
  50555. }
  50556. exports.join32 = join32;
  50557. function split32(msg, endian) {
  50558. var res = new Array(msg.length * 4);
  50559. for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
  50560. var m = msg[i];
  50561. if (endian === 'big') {
  50562. res[k] = m >>> 24;
  50563. res[k + 1] = (m >>> 16) & 0xff;
  50564. res[k + 2] = (m >>> 8) & 0xff;
  50565. res[k + 3] = m & 0xff;
  50566. } else {
  50567. res[k + 3] = m >>> 24;
  50568. res[k + 2] = (m >>> 16) & 0xff;
  50569. res[k + 1] = (m >>> 8) & 0xff;
  50570. res[k] = m & 0xff;
  50571. }
  50572. }
  50573. return res;
  50574. }
  50575. exports.split32 = split32;
  50576. function rotr32(w, b) {
  50577. return (w >>> b) | (w << (32 - b));
  50578. }
  50579. exports.rotr32 = rotr32;
  50580. function rotl32(w, b) {
  50581. return (w << b) | (w >>> (32 - b));
  50582. }
  50583. exports.rotl32 = rotl32;
  50584. function sum32(a, b) {
  50585. return (a + b) >>> 0;
  50586. }
  50587. exports.sum32 = sum32;
  50588. function sum32_3(a, b, c) {
  50589. return (a + b + c) >>> 0;
  50590. }
  50591. exports.sum32_3 = sum32_3;
  50592. function sum32_4(a, b, c, d) {
  50593. return (a + b + c + d) >>> 0;
  50594. }
  50595. exports.sum32_4 = sum32_4;
  50596. function sum32_5(a, b, c, d, e) {
  50597. return (a + b + c + d + e) >>> 0;
  50598. }
  50599. exports.sum32_5 = sum32_5;
  50600. function sum64(buf, pos, ah, al) {
  50601. var bh = buf[pos];
  50602. var bl = buf[pos + 1];
  50603. var lo = (al + bl) >>> 0;
  50604. var hi = (lo < al ? 1 : 0) + ah + bh;
  50605. buf[pos] = hi >>> 0;
  50606. buf[pos + 1] = lo;
  50607. }
  50608. exports.sum64 = sum64;
  50609. function sum64_hi(ah, al, bh, bl) {
  50610. var lo = (al + bl) >>> 0;
  50611. var hi = (lo < al ? 1 : 0) + ah + bh;
  50612. return hi >>> 0;
  50613. }
  50614. exports.sum64_hi = sum64_hi;
  50615. function sum64_lo(ah, al, bh, bl) {
  50616. var lo = al + bl;
  50617. return lo >>> 0;
  50618. }
  50619. exports.sum64_lo = sum64_lo;
  50620. function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  50621. var carry = 0;
  50622. var lo = al;
  50623. lo = (lo + bl) >>> 0;
  50624. carry += lo < al ? 1 : 0;
  50625. lo = (lo + cl) >>> 0;
  50626. carry += lo < cl ? 1 : 0;
  50627. lo = (lo + dl) >>> 0;
  50628. carry += lo < dl ? 1 : 0;
  50629. var hi = ah + bh + ch + dh + carry;
  50630. return hi >>> 0;
  50631. }
  50632. exports.sum64_4_hi = sum64_4_hi;
  50633. function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  50634. var lo = al + bl + cl + dl;
  50635. return lo >>> 0;
  50636. }
  50637. exports.sum64_4_lo = sum64_4_lo;
  50638. function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  50639. var carry = 0;
  50640. var lo = al;
  50641. lo = (lo + bl) >>> 0;
  50642. carry += lo < al ? 1 : 0;
  50643. lo = (lo + cl) >>> 0;
  50644. carry += lo < cl ? 1 : 0;
  50645. lo = (lo + dl) >>> 0;
  50646. carry += lo < dl ? 1 : 0;
  50647. lo = (lo + el) >>> 0;
  50648. carry += lo < el ? 1 : 0;
  50649. var hi = ah + bh + ch + dh + eh + carry;
  50650. return hi >>> 0;
  50651. }
  50652. exports.sum64_5_hi = sum64_5_hi;
  50653. function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  50654. var lo = al + bl + cl + dl + el;
  50655. return lo >>> 0;
  50656. }
  50657. exports.sum64_5_lo = sum64_5_lo;
  50658. function rotr64_hi(ah, al, num) {
  50659. var r = (al << (32 - num)) | (ah >>> num);
  50660. return r >>> 0;
  50661. }
  50662. exports.rotr64_hi = rotr64_hi;
  50663. function rotr64_lo(ah, al, num) {
  50664. var r = (ah << (32 - num)) | (al >>> num);
  50665. return r >>> 0;
  50666. }
  50667. exports.rotr64_lo = rotr64_lo;
  50668. function shr64_hi(ah, al, num) {
  50669. return ah >>> num;
  50670. }
  50671. exports.shr64_hi = shr64_hi;
  50672. function shr64_lo(ah, al, num) {
  50673. var r = (ah << (32 - num)) | (al >>> num);
  50674. return r >>> 0;
  50675. }
  50676. exports.shr64_lo = shr64_lo;
  50677. },{"inherits":320,"minimalistic-assert":345}],312:[function(require,module,exports){
  50678. 'use strict';
  50679. var hash = require('hash.js');
  50680. var utils = require('minimalistic-crypto-utils');
  50681. var assert = require('minimalistic-assert');
  50682. function HmacDRBG(options) {
  50683. if (!(this instanceof HmacDRBG))
  50684. return new HmacDRBG(options);
  50685. this.hash = options.hash;
  50686. this.predResist = !!options.predResist;
  50687. this.outLen = this.hash.outSize;
  50688. this.minEntropy = options.minEntropy || this.hash.hmacStrength;
  50689. this._reseed = null;
  50690. this.reseedInterval = null;
  50691. this.K = null;
  50692. this.V = null;
  50693. var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
  50694. var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
  50695. var pers = utils.toArray(options.pers, options.persEnc || 'hex');
  50696. assert(entropy.length >= (this.minEntropy / 8),
  50697. 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  50698. this._init(entropy, nonce, pers);
  50699. }
  50700. module.exports = HmacDRBG;
  50701. HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
  50702. var seed = entropy.concat(nonce).concat(pers);
  50703. this.K = new Array(this.outLen / 8);
  50704. this.V = new Array(this.outLen / 8);
  50705. for (var i = 0; i < this.V.length; i++) {
  50706. this.K[i] = 0x00;
  50707. this.V[i] = 0x01;
  50708. }
  50709. this._update(seed);
  50710. this._reseed = 1;
  50711. this.reseedInterval = 0x1000000000000; // 2^48
  50712. };
  50713. HmacDRBG.prototype._hmac = function hmac() {
  50714. return new hash.hmac(this.hash, this.K);
  50715. };
  50716. HmacDRBG.prototype._update = function update(seed) {
  50717. var kmac = this._hmac()
  50718. .update(this.V)
  50719. .update([ 0x00 ]);
  50720. if (seed)
  50721. kmac = kmac.update(seed);
  50722. this.K = kmac.digest();
  50723. this.V = this._hmac().update(this.V).digest();
  50724. if (!seed)
  50725. return;
  50726. this.K = this._hmac()
  50727. .update(this.V)
  50728. .update([ 0x01 ])
  50729. .update(seed)
  50730. .digest();
  50731. this.V = this._hmac().update(this.V).digest();
  50732. };
  50733. HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
  50734. // Optional entropy enc
  50735. if (typeof entropyEnc !== 'string') {
  50736. addEnc = add;
  50737. add = entropyEnc;
  50738. entropyEnc = null;
  50739. }
  50740. entropy = utils.toArray(entropy, entropyEnc);
  50741. add = utils.toArray(add, addEnc);
  50742. assert(entropy.length >= (this.minEntropy / 8),
  50743. 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  50744. this._update(entropy.concat(add || []));
  50745. this._reseed = 1;
  50746. };
  50747. HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
  50748. if (this._reseed > this.reseedInterval)
  50749. throw new Error('Reseed is required');
  50750. // Optional encoding
  50751. if (typeof enc !== 'string') {
  50752. addEnc = add;
  50753. add = enc;
  50754. enc = null;
  50755. }
  50756. // Optional additional data
  50757. if (add) {
  50758. add = utils.toArray(add, addEnc || 'hex');
  50759. this._update(add);
  50760. }
  50761. var temp = [];
  50762. while (temp.length < len) {
  50763. this.V = this._hmac().update(this.V).digest();
  50764. temp = temp.concat(this.V);
  50765. }
  50766. var res = temp.slice(0, len);
  50767. this._update(add);
  50768. this._reseed++;
  50769. return utils.encode(res, enc);
  50770. };
  50771. },{"hash.js":300,"minimalistic-assert":345,"minimalistic-crypto-utils":346}],313:[function(require,module,exports){
  50772. // Copyright 2015 Joyent, Inc.
  50773. var parser = require('./parser');
  50774. var signer = require('./signer');
  50775. var verify = require('./verify');
  50776. var utils = require('./utils');
  50777. ///--- API
  50778. module.exports = {
  50779. parse: parser.parseRequest,
  50780. parseRequest: parser.parseRequest,
  50781. sign: signer.signRequest,
  50782. signRequest: signer.signRequest,
  50783. createSigner: signer.createSigner,
  50784. isSigner: signer.isSigner,
  50785. sshKeyToPEM: utils.sshKeyToPEM,
  50786. sshKeyFingerprint: utils.fingerprint,
  50787. pemToRsaSSHKey: utils.pemToRsaSSHKey,
  50788. verify: verify.verifySignature,
  50789. verifySignature: verify.verifySignature,
  50790. verifyHMAC: verify.verifyHMAC
  50791. };
  50792. },{"./parser":314,"./signer":315,"./utils":316,"./verify":317}],314:[function(require,module,exports){
  50793. // Copyright 2012 Joyent, Inc. All rights reserved.
  50794. var assert = require('assert-plus');
  50795. var util = require('util');
  50796. var utils = require('./utils');
  50797. ///--- Globals
  50798. var HASH_ALGOS = utils.HASH_ALGOS;
  50799. var PK_ALGOS = utils.PK_ALGOS;
  50800. var HttpSignatureError = utils.HttpSignatureError;
  50801. var InvalidAlgorithmError = utils.InvalidAlgorithmError;
  50802. var validateAlgorithm = utils.validateAlgorithm;
  50803. var State = {
  50804. New: 0,
  50805. Params: 1
  50806. };
  50807. var ParamsState = {
  50808. Name: 0,
  50809. Quote: 1,
  50810. Value: 2,
  50811. Comma: 3
  50812. };
  50813. ///--- Specific Errors
  50814. function ExpiredRequestError(message) {
  50815. HttpSignatureError.call(this, message, ExpiredRequestError);
  50816. }
  50817. util.inherits(ExpiredRequestError, HttpSignatureError);
  50818. function InvalidHeaderError(message) {
  50819. HttpSignatureError.call(this, message, InvalidHeaderError);
  50820. }
  50821. util.inherits(InvalidHeaderError, HttpSignatureError);
  50822. function InvalidParamsError(message) {
  50823. HttpSignatureError.call(this, message, InvalidParamsError);
  50824. }
  50825. util.inherits(InvalidParamsError, HttpSignatureError);
  50826. function MissingHeaderError(message) {
  50827. HttpSignatureError.call(this, message, MissingHeaderError);
  50828. }
  50829. util.inherits(MissingHeaderError, HttpSignatureError);
  50830. function StrictParsingError(message) {
  50831. HttpSignatureError.call(this, message, StrictParsingError);
  50832. }
  50833. util.inherits(StrictParsingError, HttpSignatureError);
  50834. ///--- Exported API
  50835. module.exports = {
  50836. /**
  50837. * Parses the 'Authorization' header out of an http.ServerRequest object.
  50838. *
  50839. * Note that this API will fully validate the Authorization header, and throw
  50840. * on any error. It will not however check the signature, or the keyId format
  50841. * as those are specific to your environment. You can use the options object
  50842. * to pass in extra constraints.
  50843. *
  50844. * As a response object you can expect this:
  50845. *
  50846. * {
  50847. * "scheme": "Signature",
  50848. * "params": {
  50849. * "keyId": "foo",
  50850. * "algorithm": "rsa-sha256",
  50851. * "headers": [
  50852. * "date" or "x-date",
  50853. * "digest"
  50854. * ],
  50855. * "signature": "base64"
  50856. * },
  50857. * "signingString": "ready to be passed to crypto.verify()"
  50858. * }
  50859. *
  50860. * @param {Object} request an http.ServerRequest.
  50861. * @param {Object} options an optional options object with:
  50862. * - clockSkew: allowed clock skew in seconds (default 300).
  50863. * - headers: required header names (def: date or x-date)
  50864. * - algorithms: algorithms to support (default: all).
  50865. * - strict: should enforce latest spec parsing
  50866. * (default: false).
  50867. * @return {Object} parsed out object (see above).
  50868. * @throws {TypeError} on invalid input.
  50869. * @throws {InvalidHeaderError} on an invalid Authorization header error.
  50870. * @throws {InvalidParamsError} if the params in the scheme are invalid.
  50871. * @throws {MissingHeaderError} if the params indicate a header not present,
  50872. * either in the request headers from the params,
  50873. * or not in the params from a required header
  50874. * in options.
  50875. * @throws {StrictParsingError} if old attributes are used in strict parsing
  50876. * mode.
  50877. * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew.
  50878. */
  50879. parseRequest: function parseRequest(request, options) {
  50880. assert.object(request, 'request');
  50881. assert.object(request.headers, 'request.headers');
  50882. if (options === undefined) {
  50883. options = {};
  50884. }
  50885. if (options.headers === undefined) {
  50886. options.headers = [request.headers['x-date'] ? 'x-date' : 'date'];
  50887. }
  50888. assert.object(options, 'options');
  50889. assert.arrayOfString(options.headers, 'options.headers');
  50890. assert.optionalFinite(options.clockSkew, 'options.clockSkew');
  50891. var authzHeaderName = options.authorizationHeaderName || 'authorization';
  50892. if (!request.headers[authzHeaderName]) {
  50893. throw new MissingHeaderError('no ' + authzHeaderName + ' header ' +
  50894. 'present in the request');
  50895. }
  50896. options.clockSkew = options.clockSkew || 300;
  50897. var i = 0;
  50898. var state = State.New;
  50899. var substate = ParamsState.Name;
  50900. var tmpName = '';
  50901. var tmpValue = '';
  50902. var parsed = {
  50903. scheme: '',
  50904. params: {},
  50905. signingString: ''
  50906. };
  50907. var authz = request.headers[authzHeaderName];
  50908. for (i = 0; i < authz.length; i++) {
  50909. var c = authz.charAt(i);
  50910. switch (Number(state)) {
  50911. case State.New:
  50912. if (c !== ' ') parsed.scheme += c;
  50913. else state = State.Params;
  50914. break;
  50915. case State.Params:
  50916. switch (Number(substate)) {
  50917. case ParamsState.Name:
  50918. var code = c.charCodeAt(0);
  50919. // restricted name of A-Z / a-z
  50920. if ((code >= 0x41 && code <= 0x5a) || // A-Z
  50921. (code >= 0x61 && code <= 0x7a)) { // a-z
  50922. tmpName += c;
  50923. } else if (c === '=') {
  50924. if (tmpName.length === 0)
  50925. throw new InvalidHeaderError('bad param format');
  50926. substate = ParamsState.Quote;
  50927. } else {
  50928. throw new InvalidHeaderError('bad param format');
  50929. }
  50930. break;
  50931. case ParamsState.Quote:
  50932. if (c === '"') {
  50933. tmpValue = '';
  50934. substate = ParamsState.Value;
  50935. } else {
  50936. throw new InvalidHeaderError('bad param format');
  50937. }
  50938. break;
  50939. case ParamsState.Value:
  50940. if (c === '"') {
  50941. parsed.params[tmpName] = tmpValue;
  50942. substate = ParamsState.Comma;
  50943. } else {
  50944. tmpValue += c;
  50945. }
  50946. break;
  50947. case ParamsState.Comma:
  50948. if (c === ',') {
  50949. tmpName = '';
  50950. substate = ParamsState.Name;
  50951. } else {
  50952. throw new InvalidHeaderError('bad param format');
  50953. }
  50954. break;
  50955. default:
  50956. throw new Error('Invalid substate');
  50957. }
  50958. break;
  50959. default:
  50960. throw new Error('Invalid substate');
  50961. }
  50962. }
  50963. if (!parsed.params.headers || parsed.params.headers === '') {
  50964. if (request.headers['x-date']) {
  50965. parsed.params.headers = ['x-date'];
  50966. } else {
  50967. parsed.params.headers = ['date'];
  50968. }
  50969. } else {
  50970. parsed.params.headers = parsed.params.headers.split(' ');
  50971. }
  50972. // Minimally validate the parsed object
  50973. if (!parsed.scheme || parsed.scheme !== 'Signature')
  50974. throw new InvalidHeaderError('scheme was not "Signature"');
  50975. if (!parsed.params.keyId)
  50976. throw new InvalidHeaderError('keyId was not specified');
  50977. if (!parsed.params.algorithm)
  50978. throw new InvalidHeaderError('algorithm was not specified');
  50979. if (!parsed.params.signature)
  50980. throw new InvalidHeaderError('signature was not specified');
  50981. // Check the algorithm against the official list
  50982. parsed.params.algorithm = parsed.params.algorithm.toLowerCase();
  50983. try {
  50984. validateAlgorithm(parsed.params.algorithm);
  50985. } catch (e) {
  50986. if (e instanceof InvalidAlgorithmError)
  50987. throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' +
  50988. 'supported'));
  50989. else
  50990. throw (e);
  50991. }
  50992. // Build the signingString
  50993. for (i = 0; i < parsed.params.headers.length; i++) {
  50994. var h = parsed.params.headers[i].toLowerCase();
  50995. parsed.params.headers[i] = h;
  50996. if (h === 'request-line') {
  50997. if (!options.strict) {
  50998. /*
  50999. * We allow headers from the older spec drafts if strict parsing isn't
  51000. * specified in options.
  51001. */
  51002. parsed.signingString +=
  51003. request.method + ' ' + request.url + ' HTTP/' + request.httpVersion;
  51004. } else {
  51005. /* Strict parsing doesn't allow older draft headers. */
  51006. throw (new StrictParsingError('request-line is not a valid header ' +
  51007. 'with strict parsing enabled.'));
  51008. }
  51009. } else if (h === '(request-target)') {
  51010. parsed.signingString +=
  51011. '(request-target): ' + request.method.toLowerCase() + ' ' +
  51012. request.url;
  51013. } else {
  51014. var value = request.headers[h];
  51015. if (value === undefined)
  51016. throw new MissingHeaderError(h + ' was not in the request');
  51017. parsed.signingString += h + ': ' + value;
  51018. }
  51019. if ((i + 1) < parsed.params.headers.length)
  51020. parsed.signingString += '\n';
  51021. }
  51022. // Check against the constraints
  51023. var date;
  51024. if (request.headers.date || request.headers['x-date']) {
  51025. if (request.headers['x-date']) {
  51026. date = new Date(request.headers['x-date']);
  51027. } else {
  51028. date = new Date(request.headers.date);
  51029. }
  51030. var now = new Date();
  51031. var skew = Math.abs(now.getTime() - date.getTime());
  51032. if (skew > options.clockSkew * 1000) {
  51033. throw new ExpiredRequestError('clock skew of ' +
  51034. (skew / 1000) +
  51035. 's was greater than ' +
  51036. options.clockSkew + 's');
  51037. }
  51038. }
  51039. options.headers.forEach(function (hdr) {
  51040. // Remember that we already checked any headers in the params
  51041. // were in the request, so if this passes we're good.
  51042. if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0)
  51043. throw new MissingHeaderError(hdr + ' was not a signed header');
  51044. });
  51045. if (options.algorithms) {
  51046. if (options.algorithms.indexOf(parsed.params.algorithm) === -1)
  51047. throw new InvalidParamsError(parsed.params.algorithm +
  51048. ' is not a supported algorithm');
  51049. }
  51050. parsed.algorithm = parsed.params.algorithm.toUpperCase();
  51051. parsed.keyId = parsed.params.keyId;
  51052. return parsed;
  51053. }
  51054. };
  51055. },{"./utils":316,"assert-plus":104,"util":658}],315:[function(require,module,exports){
  51056. (function (Buffer){(function (){
  51057. // Copyright 2012 Joyent, Inc. All rights reserved.
  51058. var assert = require('assert-plus');
  51059. var crypto = require('crypto');
  51060. var http = require('http');
  51061. var util = require('util');
  51062. var sshpk = require('sshpk');
  51063. var jsprim = require('jsprim');
  51064. var utils = require('./utils');
  51065. var sprintf = require('util').format;
  51066. var HASH_ALGOS = utils.HASH_ALGOS;
  51067. var PK_ALGOS = utils.PK_ALGOS;
  51068. var InvalidAlgorithmError = utils.InvalidAlgorithmError;
  51069. var HttpSignatureError = utils.HttpSignatureError;
  51070. var validateAlgorithm = utils.validateAlgorithm;
  51071. ///--- Globals
  51072. var AUTHZ_FMT =
  51073. 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
  51074. ///--- Specific Errors
  51075. function MissingHeaderError(message) {
  51076. HttpSignatureError.call(this, message, MissingHeaderError);
  51077. }
  51078. util.inherits(MissingHeaderError, HttpSignatureError);
  51079. function StrictParsingError(message) {
  51080. HttpSignatureError.call(this, message, StrictParsingError);
  51081. }
  51082. util.inherits(StrictParsingError, HttpSignatureError);
  51083. /* See createSigner() */
  51084. function RequestSigner(options) {
  51085. assert.object(options, 'options');
  51086. var alg = [];
  51087. if (options.algorithm !== undefined) {
  51088. assert.string(options.algorithm, 'options.algorithm');
  51089. alg = validateAlgorithm(options.algorithm);
  51090. }
  51091. this.rs_alg = alg;
  51092. /*
  51093. * RequestSigners come in two varieties: ones with an rs_signFunc, and ones
  51094. * with an rs_signer.
  51095. *
  51096. * rs_signFunc-based RequestSigners have to build up their entire signing
  51097. * string within the rs_lines array and give it to rs_signFunc as a single
  51098. * concat'd blob. rs_signer-based RequestSigners can add a line at a time to
  51099. * their signing state by using rs_signer.update(), thus only needing to
  51100. * buffer the hash function state and one line at a time.
  51101. */
  51102. if (options.sign !== undefined) {
  51103. assert.func(options.sign, 'options.sign');
  51104. this.rs_signFunc = options.sign;
  51105. } else if (alg[0] === 'hmac' && options.key !== undefined) {
  51106. assert.string(options.keyId, 'options.keyId');
  51107. this.rs_keyId = options.keyId;
  51108. if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
  51109. throw (new TypeError('options.key for HMAC must be a string or Buffer'));
  51110. /*
  51111. * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their
  51112. * data in chunks rather than requiring it all to be given in one go
  51113. * at the end, so they are more similar to signers than signFuncs.
  51114. */
  51115. this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key);
  51116. this.rs_signer.sign = function () {
  51117. var digest = this.digest('base64');
  51118. return ({
  51119. hashAlgorithm: alg[1],
  51120. toString: function () { return (digest); }
  51121. });
  51122. };
  51123. } else if (options.key !== undefined) {
  51124. var key = options.key;
  51125. if (typeof (key) === 'string' || Buffer.isBuffer(key))
  51126. key = sshpk.parsePrivateKey(key);
  51127. assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
  51128. 'options.key must be a sshpk.PrivateKey');
  51129. this.rs_key = key;
  51130. assert.string(options.keyId, 'options.keyId');
  51131. this.rs_keyId = options.keyId;
  51132. if (!PK_ALGOS[key.type]) {
  51133. throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
  51134. 'keys are not supported'));
  51135. }
  51136. if (alg[0] !== undefined && key.type !== alg[0]) {
  51137. throw (new InvalidAlgorithmError('options.key must be a ' +
  51138. alg[0].toUpperCase() + ' key, was given a ' +
  51139. key.type.toUpperCase() + ' key instead'));
  51140. }
  51141. this.rs_signer = key.createSign(alg[1]);
  51142. } else {
  51143. throw (new TypeError('options.sign (func) or options.key is required'));
  51144. }
  51145. this.rs_headers = [];
  51146. this.rs_lines = [];
  51147. }
  51148. /**
  51149. * Adds a header to be signed, with its value, into this signer.
  51150. *
  51151. * @param {String} header
  51152. * @param {String} value
  51153. * @return {String} value written
  51154. */
  51155. RequestSigner.prototype.writeHeader = function (header, value) {
  51156. assert.string(header, 'header');
  51157. header = header.toLowerCase();
  51158. assert.string(value, 'value');
  51159. this.rs_headers.push(header);
  51160. if (this.rs_signFunc) {
  51161. this.rs_lines.push(header + ': ' + value);
  51162. } else {
  51163. var line = header + ': ' + value;
  51164. if (this.rs_headers.length > 0)
  51165. line = '\n' + line;
  51166. this.rs_signer.update(line);
  51167. }
  51168. return (value);
  51169. };
  51170. /**
  51171. * Adds a default Date header, returning its value.
  51172. *
  51173. * @return {String}
  51174. */
  51175. RequestSigner.prototype.writeDateHeader = function () {
  51176. return (this.writeHeader('date', jsprim.rfc1123(new Date())));
  51177. };
  51178. /**
  51179. * Adds the request target line to be signed.
  51180. *
  51181. * @param {String} method, HTTP method (e.g. 'get', 'post', 'put')
  51182. * @param {String} path
  51183. */
  51184. RequestSigner.prototype.writeTarget = function (method, path) {
  51185. assert.string(method, 'method');
  51186. assert.string(path, 'path');
  51187. method = method.toLowerCase();
  51188. this.writeHeader('(request-target)', method + ' ' + path);
  51189. };
  51190. /**
  51191. * Calculate the value for the Authorization header on this request
  51192. * asynchronously.
  51193. *
  51194. * @param {Func} callback (err, authz)
  51195. */
  51196. RequestSigner.prototype.sign = function (cb) {
  51197. assert.func(cb, 'callback');
  51198. if (this.rs_headers.length < 1)
  51199. throw (new Error('At least one header must be signed'));
  51200. var alg, authz;
  51201. if (this.rs_signFunc) {
  51202. var data = this.rs_lines.join('\n');
  51203. var self = this;
  51204. this.rs_signFunc(data, function (err, sig) {
  51205. if (err) {
  51206. cb(err);
  51207. return;
  51208. }
  51209. try {
  51210. assert.object(sig, 'signature');
  51211. assert.string(sig.keyId, 'signature.keyId');
  51212. assert.string(sig.algorithm, 'signature.algorithm');
  51213. assert.string(sig.signature, 'signature.signature');
  51214. alg = validateAlgorithm(sig.algorithm);
  51215. authz = sprintf(AUTHZ_FMT,
  51216. sig.keyId,
  51217. sig.algorithm,
  51218. self.rs_headers.join(' '),
  51219. sig.signature);
  51220. } catch (e) {
  51221. cb(e);
  51222. return;
  51223. }
  51224. cb(null, authz);
  51225. });
  51226. } else {
  51227. try {
  51228. var sigObj = this.rs_signer.sign();
  51229. } catch (e) {
  51230. cb(e);
  51231. return;
  51232. }
  51233. alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm;
  51234. var signature = sigObj.toString();
  51235. authz = sprintf(AUTHZ_FMT,
  51236. this.rs_keyId,
  51237. alg,
  51238. this.rs_headers.join(' '),
  51239. signature);
  51240. cb(null, authz);
  51241. }
  51242. };
  51243. ///--- Exported API
  51244. module.exports = {
  51245. /**
  51246. * Identifies whether a given object is a request signer or not.
  51247. *
  51248. * @param {Object} object, the object to identify
  51249. * @returns {Boolean}
  51250. */
  51251. isSigner: function (obj) {
  51252. if (typeof (obj) === 'object' && obj instanceof RequestSigner)
  51253. return (true);
  51254. return (false);
  51255. },
  51256. /**
  51257. * Creates a request signer, used to asynchronously build a signature
  51258. * for a request (does not have to be an http.ClientRequest).
  51259. *
  51260. * @param {Object} options, either:
  51261. * - {String} keyId
  51262. * - {String|Buffer} key
  51263. * - {String} algorithm (optional, required for HMAC)
  51264. * or:
  51265. * - {Func} sign (data, cb)
  51266. * @return {RequestSigner}
  51267. */
  51268. createSigner: function createSigner(options) {
  51269. return (new RequestSigner(options));
  51270. },
  51271. /**
  51272. * Adds an 'Authorization' header to an http.ClientRequest object.
  51273. *
  51274. * Note that this API will add a Date header if it's not already set. Any
  51275. * other headers in the options.headers array MUST be present, or this
  51276. * will throw.
  51277. *
  51278. * You shouldn't need to check the return type; it's just there if you want
  51279. * to be pedantic.
  51280. *
  51281. * The optional flag indicates whether parsing should use strict enforcement
  51282. * of the version draft-cavage-http-signatures-04 of the spec or beyond.
  51283. * The default is to be loose and support
  51284. * older versions for compatibility.
  51285. *
  51286. * @param {Object} request an instance of http.ClientRequest.
  51287. * @param {Object} options signing parameters object:
  51288. * - {String} keyId required.
  51289. * - {String} key required (either a PEM or HMAC key).
  51290. * - {Array} headers optional; defaults to ['date'].
  51291. * - {String} algorithm optional (unless key is HMAC);
  51292. * default is the same as the sshpk default
  51293. * signing algorithm for the type of key given
  51294. * - {String} httpVersion optional; defaults to '1.1'.
  51295. * - {Boolean} strict optional; defaults to 'false'.
  51296. * @return {Boolean} true if Authorization (and optionally Date) were added.
  51297. * @throws {TypeError} on bad parameter types (input).
  51298. * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with
  51299. * the given key.
  51300. * @throws {sshpk.KeyParseError} if key was bad.
  51301. * @throws {MissingHeaderError} if a header to be signed was specified but
  51302. * was not present.
  51303. */
  51304. signRequest: function signRequest(request, options) {
  51305. assert.object(request, 'request');
  51306. assert.object(options, 'options');
  51307. assert.optionalString(options.algorithm, 'options.algorithm');
  51308. assert.string(options.keyId, 'options.keyId');
  51309. assert.optionalArrayOfString(options.headers, 'options.headers');
  51310. assert.optionalString(options.httpVersion, 'options.httpVersion');
  51311. if (!request.getHeader('Date'))
  51312. request.setHeader('Date', jsprim.rfc1123(new Date()));
  51313. if (!options.headers)
  51314. options.headers = ['date'];
  51315. if (!options.httpVersion)
  51316. options.httpVersion = '1.1';
  51317. var alg = [];
  51318. if (options.algorithm) {
  51319. options.algorithm = options.algorithm.toLowerCase();
  51320. alg = validateAlgorithm(options.algorithm);
  51321. }
  51322. var i;
  51323. var stringToSign = '';
  51324. for (i = 0; i < options.headers.length; i++) {
  51325. if (typeof (options.headers[i]) !== 'string')
  51326. throw new TypeError('options.headers must be an array of Strings');
  51327. var h = options.headers[i].toLowerCase();
  51328. if (h === 'request-line') {
  51329. if (!options.strict) {
  51330. /**
  51331. * We allow headers from the older spec drafts if strict parsing isn't
  51332. * specified in options.
  51333. */
  51334. stringToSign +=
  51335. request.method + ' ' + request.path + ' HTTP/' +
  51336. options.httpVersion;
  51337. } else {
  51338. /* Strict parsing doesn't allow older draft headers. */
  51339. throw (new StrictParsingError('request-line is not a valid header ' +
  51340. 'with strict parsing enabled.'));
  51341. }
  51342. } else if (h === '(request-target)') {
  51343. stringToSign +=
  51344. '(request-target): ' + request.method.toLowerCase() + ' ' +
  51345. request.path;
  51346. } else {
  51347. var value = request.getHeader(h);
  51348. if (value === undefined || value === '') {
  51349. throw new MissingHeaderError(h + ' was not in the request');
  51350. }
  51351. stringToSign += h + ': ' + value;
  51352. }
  51353. if ((i + 1) < options.headers.length)
  51354. stringToSign += '\n';
  51355. }
  51356. /* This is just for unit tests. */
  51357. if (request.hasOwnProperty('_stringToSign')) {
  51358. request._stringToSign = stringToSign;
  51359. }
  51360. var signature;
  51361. if (alg[0] === 'hmac') {
  51362. if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
  51363. throw (new TypeError('options.key must be a string or Buffer'));
  51364. var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key);
  51365. hmac.update(stringToSign);
  51366. signature = hmac.digest('base64');
  51367. } else {
  51368. var key = options.key;
  51369. if (typeof (key) === 'string' || Buffer.isBuffer(key))
  51370. key = sshpk.parsePrivateKey(options.key);
  51371. assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
  51372. 'options.key must be a sshpk.PrivateKey');
  51373. if (!PK_ALGOS[key.type]) {
  51374. throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
  51375. 'keys are not supported'));
  51376. }
  51377. if (alg[0] !== undefined && key.type !== alg[0]) {
  51378. throw (new InvalidAlgorithmError('options.key must be a ' +
  51379. alg[0].toUpperCase() + ' key, was given a ' +
  51380. key.type.toUpperCase() + ' key instead'));
  51381. }
  51382. var signer = key.createSign(alg[1]);
  51383. signer.update(stringToSign);
  51384. var sigObj = signer.sign();
  51385. if (!HASH_ALGOS[sigObj.hashAlgorithm]) {
  51386. throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() +
  51387. ' is not a supported hash algorithm'));
  51388. }
  51389. options.algorithm = key.type + '-' + sigObj.hashAlgorithm;
  51390. signature = sigObj.toString();
  51391. assert.notStrictEqual(signature, '', 'empty signature produced');
  51392. }
  51393. var authzHeaderName = options.authorizationHeaderName || 'Authorization';
  51394. request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT,
  51395. options.keyId,
  51396. options.algorithm,
  51397. options.headers.join(' '),
  51398. signature));
  51399. return true;
  51400. }
  51401. };
  51402. }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  51403. },{"../../is-buffer/index.js":322,"./utils":316,"assert-plus":104,"crypto":208,"http":612,"jsprim":332,"sshpk":591,"util":658}],316:[function(require,module,exports){
  51404. // Copyright 2012 Joyent, Inc. All rights reserved.
  51405. var assert = require('assert-plus');
  51406. var sshpk = require('sshpk');
  51407. var util = require('util');
  51408. var HASH_ALGOS = {
  51409. 'sha1': true,
  51410. 'sha256': true,
  51411. 'sha512': true
  51412. };
  51413. var PK_ALGOS = {
  51414. 'rsa': true,
  51415. 'dsa': true,
  51416. 'ecdsa': true
  51417. };
  51418. function HttpSignatureError(message, caller) {
  51419. if (Error.captureStackTrace)
  51420. Error.captureStackTrace(this, caller || HttpSignatureError);
  51421. this.message = message;
  51422. this.name = caller.name;
  51423. }
  51424. util.inherits(HttpSignatureError, Error);
  51425. function InvalidAlgorithmError(message) {
  51426. HttpSignatureError.call(this, message, InvalidAlgorithmError);
  51427. }
  51428. util.inherits(InvalidAlgorithmError, HttpSignatureError);
  51429. function validateAlgorithm(algorithm) {
  51430. var alg = algorithm.toLowerCase().split('-');
  51431. if (alg.length !== 2) {
  51432. throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' +
  51433. 'valid algorithm'));
  51434. }
  51435. if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) {
  51436. throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' +
  51437. 'are not supported'));
  51438. }
  51439. if (!HASH_ALGOS[alg[1]]) {
  51440. throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' +
  51441. 'supported hash algorithm'));
  51442. }
  51443. return (alg);
  51444. }
  51445. ///--- API
  51446. module.exports = {
  51447. HASH_ALGOS: HASH_ALGOS,
  51448. PK_ALGOS: PK_ALGOS,
  51449. HttpSignatureError: HttpSignatureError,
  51450. InvalidAlgorithmError: InvalidAlgorithmError,
  51451. validateAlgorithm: validateAlgorithm,
  51452. /**
  51453. * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
  51454. *
  51455. * The intent of this module is to interoperate with OpenSSL only,
  51456. * specifically the node crypto module's `verify` method.
  51457. *
  51458. * @param {String} key an OpenSSH public key.
  51459. * @return {String} PEM encoded form of the RSA public key.
  51460. * @throws {TypeError} on bad input.
  51461. * @throws {Error} on invalid ssh key formatted data.
  51462. */
  51463. sshKeyToPEM: function sshKeyToPEM(key) {
  51464. assert.string(key, 'ssh_key');
  51465. var k = sshpk.parseKey(key, 'ssh');
  51466. return (k.toString('pem'));
  51467. },
  51468. /**
  51469. * Generates an OpenSSH fingerprint from an ssh public key.
  51470. *
  51471. * @param {String} key an OpenSSH public key.
  51472. * @return {String} key fingerprint.
  51473. * @throws {TypeError} on bad input.
  51474. * @throws {Error} if what you passed doesn't look like an ssh public key.
  51475. */
  51476. fingerprint: function fingerprint(key) {
  51477. assert.string(key, 'ssh_key');
  51478. var k = sshpk.parseKey(key, 'ssh');
  51479. return (k.fingerprint('md5').toString('hex'));
  51480. },
  51481. /**
  51482. * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
  51483. *
  51484. * The reverse of the above function.
  51485. */
  51486. pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
  51487. assert.equal('string', typeof (pem), 'typeof pem');
  51488. var k = sshpk.parseKey(pem, 'pem');
  51489. k.comment = comment;
  51490. return (k.toString('ssh'));
  51491. }
  51492. };
  51493. },{"assert-plus":104,"sshpk":591,"util":658}],317:[function(require,module,exports){
  51494. (function (Buffer){(function (){
  51495. // Copyright 2015 Joyent, Inc.
  51496. var assert = require('assert-plus');
  51497. var crypto = require('crypto');
  51498. var sshpk = require('sshpk');
  51499. var utils = require('./utils');
  51500. var HASH_ALGOS = utils.HASH_ALGOS;
  51501. var PK_ALGOS = utils.PK_ALGOS;
  51502. var InvalidAlgorithmError = utils.InvalidAlgorithmError;
  51503. var HttpSignatureError = utils.HttpSignatureError;
  51504. var validateAlgorithm = utils.validateAlgorithm;
  51505. ///--- Exported API
  51506. module.exports = {
  51507. /**
  51508. * Verify RSA/DSA signature against public key. You are expected to pass in
  51509. * an object that was returned from `parse()`.
  51510. *
  51511. * @param {Object} parsedSignature the object you got from `parse`.
  51512. * @param {String} pubkey RSA/DSA private key PEM.
  51513. * @return {Boolean} true if valid, false otherwise.
  51514. * @throws {TypeError} if you pass in bad arguments.
  51515. * @throws {InvalidAlgorithmError}
  51516. */
  51517. verifySignature: function verifySignature(parsedSignature, pubkey) {
  51518. assert.object(parsedSignature, 'parsedSignature');
  51519. if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey))
  51520. pubkey = sshpk.parseKey(pubkey);
  51521. assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key');
  51522. var alg = validateAlgorithm(parsedSignature.algorithm);
  51523. if (alg[0] === 'hmac' || alg[0] !== pubkey.type)
  51524. return (false);
  51525. var v = pubkey.createVerify(alg[1]);
  51526. v.update(parsedSignature.signingString);
  51527. return (v.verify(parsedSignature.params.signature, 'base64'));
  51528. },
  51529. /**
  51530. * Verify HMAC against shared secret. You are expected to pass in an object
  51531. * that was returned from `parse()`.
  51532. *
  51533. * @param {Object} parsedSignature the object you got from `parse`.
  51534. * @param {String} secret HMAC shared secret.
  51535. * @return {Boolean} true if valid, false otherwise.
  51536. * @throws {TypeError} if you pass in bad arguments.
  51537. * @throws {InvalidAlgorithmError}
  51538. */
  51539. verifyHMAC: function verifyHMAC(parsedSignature, secret) {
  51540. assert.object(parsedSignature, 'parsedHMAC');
  51541. assert.string(secret, 'secret');
  51542. var alg = validateAlgorithm(parsedSignature.algorithm);
  51543. if (alg[0] !== 'hmac')
  51544. return (false);
  51545. var hashAlg = alg[1].toUpperCase();
  51546. var hmac = crypto.createHmac(hashAlg, secret);
  51547. hmac.update(parsedSignature.signingString);
  51548. /*
  51549. * Now double-hash to avoid leaking timing information - there's
  51550. * no easy constant-time compare in JS, so we use this approach
  51551. * instead. See for more info:
  51552. * https://www.isecpartners.com/blog/2011/february/double-hmac-
  51553. * verification.aspx
  51554. */
  51555. var h1 = crypto.createHmac(hashAlg, secret);
  51556. h1.update(hmac.digest());
  51557. h1 = h1.digest();
  51558. var h2 = crypto.createHmac(hashAlg, secret);
  51559. h2.update(new Buffer(parsedSignature.params.signature, 'base64'));
  51560. h2 = h2.digest();
  51561. /* Node 0.8 returns strings from .digest(). */
  51562. if (typeof (h1) === 'string')
  51563. return (h1 === h2);
  51564. /* And node 0.10 lacks the .equals() method on Buffers. */
  51565. if (Buffer.isBuffer(h1) && !h1.equals)
  51566. return (h1.toString('binary') === h2.toString('binary'));
  51567. return (h1.equals(h2));
  51568. }
  51569. };
  51570. }).call(this)}).call(this,require("buffer").Buffer)
  51571. },{"./utils":316,"assert-plus":104,"buffer":193,"crypto":208,"sshpk":591}],318:[function(require,module,exports){
  51572. var http = require('http')
  51573. var url = require('url')
  51574. var https = module.exports
  51575. for (var key in http) {
  51576. if (http.hasOwnProperty(key)) https[key] = http[key]
  51577. }
  51578. https.request = function (params, cb) {
  51579. params = validateParams(params)
  51580. return http.request.call(this, params, cb)
  51581. }
  51582. https.get = function (params, cb) {
  51583. params = validateParams(params)
  51584. return http.get.call(this, params, cb)
  51585. }
  51586. function validateParams (params) {
  51587. if (typeof params === 'string') {
  51588. params = url.parse(params)
  51589. }
  51590. if (!params.protocol) {
  51591. params.protocol = 'https:'
  51592. }
  51593. if (params.protocol !== 'https:') {
  51594. throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
  51595. }
  51596. return params
  51597. }
  51598. },{"http":612,"url":653}],319:[function(require,module,exports){
  51599. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  51600. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  51601. var e, m
  51602. var eLen = (nBytes * 8) - mLen - 1
  51603. var eMax = (1 << eLen) - 1
  51604. var eBias = eMax >> 1
  51605. var nBits = -7
  51606. var i = isLE ? (nBytes - 1) : 0
  51607. var d = isLE ? -1 : 1
  51608. var s = buffer[offset + i]
  51609. i += d
  51610. e = s & ((1 << (-nBits)) - 1)
  51611. s >>= (-nBits)
  51612. nBits += eLen
  51613. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  51614. m = e & ((1 << (-nBits)) - 1)
  51615. e >>= (-nBits)
  51616. nBits += mLen
  51617. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  51618. if (e === 0) {
  51619. e = 1 - eBias
  51620. } else if (e === eMax) {
  51621. return m ? NaN : ((s ? -1 : 1) * Infinity)
  51622. } else {
  51623. m = m + Math.pow(2, mLen)
  51624. e = e - eBias
  51625. }
  51626. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  51627. }
  51628. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  51629. var e, m, c
  51630. var eLen = (nBytes * 8) - mLen - 1
  51631. var eMax = (1 << eLen) - 1
  51632. var eBias = eMax >> 1
  51633. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  51634. var i = isLE ? 0 : (nBytes - 1)
  51635. var d = isLE ? 1 : -1
  51636. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  51637. value = Math.abs(value)
  51638. if (isNaN(value) || value === Infinity) {
  51639. m = isNaN(value) ? 1 : 0
  51640. e = eMax
  51641. } else {
  51642. e = Math.floor(Math.log(value) / Math.LN2)
  51643. if (value * (c = Math.pow(2, -e)) < 1) {
  51644. e--
  51645. c *= 2
  51646. }
  51647. if (e + eBias >= 1) {
  51648. value += rt / c
  51649. } else {
  51650. value += rt * Math.pow(2, 1 - eBias)
  51651. }
  51652. if (value * c >= 2) {
  51653. e++
  51654. c /= 2
  51655. }
  51656. if (e + eBias >= eMax) {
  51657. m = 0
  51658. e = eMax
  51659. } else if (e + eBias >= 1) {
  51660. m = ((value * c) - 1) * Math.pow(2, mLen)
  51661. e = e + eBias
  51662. } else {
  51663. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  51664. e = 0
  51665. }
  51666. }
  51667. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  51668. e = (e << mLen) | m
  51669. eLen += mLen
  51670. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  51671. buffer[offset + i - d] |= s * 128
  51672. }
  51673. },{}],320:[function(require,module,exports){
  51674. if (typeof Object.create === 'function') {
  51675. // implementation from standard node.js 'util' module
  51676. module.exports = function inherits(ctor, superCtor) {
  51677. if (superCtor) {
  51678. ctor.super_ = superCtor
  51679. ctor.prototype = Object.create(superCtor.prototype, {
  51680. constructor: {
  51681. value: ctor,
  51682. enumerable: false,
  51683. writable: true,
  51684. configurable: true
  51685. }
  51686. })
  51687. }
  51688. };
  51689. } else {
  51690. // old school shim for old browsers
  51691. module.exports = function inherits(ctor, superCtor) {
  51692. if (superCtor) {
  51693. ctor.super_ = superCtor
  51694. var TempCtor = function () {}
  51695. TempCtor.prototype = superCtor.prototype
  51696. ctor.prototype = new TempCtor()
  51697. ctor.prototype.constructor = ctor
  51698. }
  51699. }
  51700. }
  51701. },{}],321:[function(require,module,exports){
  51702. 'use strict';
  51703. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  51704. var callBound = require('call-bind/callBound');
  51705. var $toString = callBound('Object.prototype.toString');
  51706. var isStandardArguments = function isArguments(value) {
  51707. if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
  51708. return false;
  51709. }
  51710. return $toString(value) === '[object Arguments]';
  51711. };
  51712. var isLegacyArguments = function isArguments(value) {
  51713. if (isStandardArguments(value)) {
  51714. return true;
  51715. }
  51716. return value !== null &&
  51717. typeof value === 'object' &&
  51718. typeof value.length === 'number' &&
  51719. value.length >= 0 &&
  51720. $toString(value) !== '[object Array]' &&
  51721. $toString(value.callee) === '[object Function]';
  51722. };
  51723. var supportsStandardArguments = (function () {
  51724. return isStandardArguments(arguments);
  51725. }());
  51726. isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests
  51727. module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
  51728. },{"call-bind/callBound":195}],322:[function(require,module,exports){
  51729. /*!
  51730. * Determine if an object is a Buffer
  51731. *
  51732. * @author Feross Aboukhadijeh <https://feross.org>
  51733. * @license MIT
  51734. */
  51735. // The _isBuffer check is for Safari 5-7 support, because it's missing
  51736. // Object.prototype.constructor. Remove this eventually
  51737. module.exports = function (obj) {
  51738. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  51739. }
  51740. function isBuffer (obj) {
  51741. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  51742. }
  51743. // For Node v0.10 support. Remove this eventually.
  51744. function isSlowBuffer (obj) {
  51745. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  51746. }
  51747. },{}],323:[function(require,module,exports){
  51748. 'use strict';
  51749. var toStr = Object.prototype.toString;
  51750. var fnToStr = Function.prototype.toString;
  51751. var isFnRegex = /^\s*(?:function)?\*/;
  51752. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  51753. var getProto = Object.getPrototypeOf;
  51754. var getGeneratorFunc = function () { // eslint-disable-line consistent-return
  51755. if (!hasToStringTag) {
  51756. return false;
  51757. }
  51758. try {
  51759. return Function('return function*() {}')();
  51760. } catch (e) {
  51761. }
  51762. };
  51763. var generatorFunc = getGeneratorFunc();
  51764. var GeneratorFunction = getProto && generatorFunc ? getProto(generatorFunc) : false;
  51765. module.exports = function isGeneratorFunction(fn) {
  51766. if (typeof fn !== 'function') {
  51767. return false;
  51768. }
  51769. if (isFnRegex.test(fnToStr.call(fn))) {
  51770. return true;
  51771. }
  51772. if (!hasToStringTag) {
  51773. var str = toStr.call(fn);
  51774. return str === '[object GeneratorFunction]';
  51775. }
  51776. return getProto && getProto(fn) === GeneratorFunction;
  51777. };
  51778. },{}],324:[function(require,module,exports){
  51779. (function (global){(function (){
  51780. 'use strict';
  51781. var forEach = require('foreach');
  51782. var availableTypedArrays = require('available-typed-arrays');
  51783. var callBound = require('call-bind/callBound');
  51784. var $toString = callBound('Object.prototype.toString');
  51785. var hasSymbols = require('has-symbols')();
  51786. var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol';
  51787. var typedArrays = availableTypedArrays();
  51788. var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
  51789. for (var i = 0; i < array.length; i += 1) {
  51790. if (array[i] === value) {
  51791. return i;
  51792. }
  51793. }
  51794. return -1;
  51795. };
  51796. var $slice = callBound('String.prototype.slice');
  51797. var toStrTags = {};
  51798. var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');
  51799. var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
  51800. if (hasToStringTag && gOPD && getPrototypeOf) {
  51801. forEach(typedArrays, function (typedArray) {
  51802. var arr = new global[typedArray]();
  51803. if (!(Symbol.toStringTag in arr)) {
  51804. throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.');
  51805. }
  51806. var proto = getPrototypeOf(arr);
  51807. var descriptor = gOPD(proto, Symbol.toStringTag);
  51808. if (!descriptor) {
  51809. var superProto = getPrototypeOf(proto);
  51810. descriptor = gOPD(superProto, Symbol.toStringTag);
  51811. }
  51812. toStrTags[typedArray] = descriptor.get;
  51813. });
  51814. }
  51815. var tryTypedArrays = function tryAllTypedArrays(value) {
  51816. var anyTrue = false;
  51817. forEach(toStrTags, function (getter, typedArray) {
  51818. if (!anyTrue) {
  51819. try {
  51820. anyTrue = getter.call(value) === typedArray;
  51821. } catch (e) { /**/ }
  51822. }
  51823. });
  51824. return anyTrue;
  51825. };
  51826. module.exports = function isTypedArray(value) {
  51827. if (!value || typeof value !== 'object') { return false; }
  51828. if (!hasToStringTag) {
  51829. var tag = $slice($toString(value), 8, -1);
  51830. return $indexOf(typedArrays, tag) > -1;
  51831. }
  51832. if (!gOPD) { return false; }
  51833. return tryTypedArrays(value);
  51834. };
  51835. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  51836. },{"available-typed-arrays":110,"call-bind/callBound":195,"es-abstract/helpers/getOwnPropertyDescriptor":246,"foreach":253,"has-symbols":280}],325:[function(require,module,exports){
  51837. module.exports = isTypedArray
  51838. isTypedArray.strict = isStrictTypedArray
  51839. isTypedArray.loose = isLooseTypedArray
  51840. var toString = Object.prototype.toString
  51841. var names = {
  51842. '[object Int8Array]': true
  51843. , '[object Int16Array]': true
  51844. , '[object Int32Array]': true
  51845. , '[object Uint8Array]': true
  51846. , '[object Uint8ClampedArray]': true
  51847. , '[object Uint16Array]': true
  51848. , '[object Uint32Array]': true
  51849. , '[object Float32Array]': true
  51850. , '[object Float64Array]': true
  51851. }
  51852. function isTypedArray(arr) {
  51853. return (
  51854. isStrictTypedArray(arr)
  51855. || isLooseTypedArray(arr)
  51856. )
  51857. }
  51858. function isStrictTypedArray(arr) {
  51859. return (
  51860. arr instanceof Int8Array
  51861. || arr instanceof Int16Array
  51862. || arr instanceof Int32Array
  51863. || arr instanceof Uint8Array
  51864. || arr instanceof Uint8ClampedArray
  51865. || arr instanceof Uint16Array
  51866. || arr instanceof Uint32Array
  51867. || arr instanceof Float32Array
  51868. || arr instanceof Float64Array
  51869. )
  51870. }
  51871. function isLooseTypedArray(arr) {
  51872. return names[toString.call(arr)]
  51873. }
  51874. },{}],326:[function(require,module,exports){
  51875. var stream = require('stream')
  51876. function isStream (obj) {
  51877. return obj instanceof stream.Stream
  51878. }
  51879. function isReadable (obj) {
  51880. return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
  51881. }
  51882. function isWritable (obj) {
  51883. return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
  51884. }
  51885. function isDuplex (obj) {
  51886. return isReadable(obj) && isWritable(obj)
  51887. }
  51888. module.exports = isStream
  51889. module.exports.isReadable = isReadable
  51890. module.exports.isWritable = isWritable
  51891. module.exports.isDuplex = isDuplex
  51892. },{"stream":597}],327:[function(require,module,exports){
  51893. (function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,e.JSBI=t())})(this,function(){'use strict';var v=Math.imul,f=Math.clz32;function e(t){"@babel/helpers - typeof";return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var _,n=0;n<t.length;n++)_=t[n],_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(e,_.key,_)}function _(e,t,_){return t&&i(e.prototype,t),_&&i(e,_),e}function n(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&g(e,t)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function g(e,t){return g=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},g(e,t)}function o(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}function a(){return a=o()?Reflect.construct:function(e,t,i){var _=[null];_.push.apply(_,t);var n=Function.bind.apply(e,_),l=new n;return i&&g(l,i.prototype),l},a.apply(null,arguments)}function s(e){return-1!==Function.toString.call(e).indexOf("[native code]")}function u(e){var t="function"==typeof Map?new Map:void 0;return u=function(e){function i(){return a(e,arguments,l(this).constructor)}if(null===e||!s(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if("undefined"!=typeof t){if(t.has(e))return t.get(e);t.set(e,i)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),g(i,e)},u(e)}function r(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function d(e,t){return t&&("object"==typeof t||"function"==typeof t)?t:r(e)}function h(e){var t=o();return function(){var i,_=l(e);if(t){var n=l(this).constructor;i=Reflect.construct(_,arguments,n)}else i=_.apply(this,arguments);return d(this,i)}}function b(e,t){if(e){if("string"==typeof e)return m(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?m(e,t):void 0}}function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var _=0,n=Array(t);_<t;_++)n[_]=e[_];return n}function c(e,t){var _;if("undefined"==typeof Symbol||null==e[Symbol.iterator]){if(Array.isArray(e)||(_=b(e))||t&&e&&"number"==typeof e.length){_&&(e=_);var n=0,l=function(){};return{s:l,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(t){throw t},f:l}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var g,a=!0,s=!1;return{s:function(){_=e[Symbol.iterator]()},n:function(){var e=_.next();return a=e.done,e},e:function(t){s=!0,g=t},f:function(){try{a||null==_.return||_.return()}finally{if(s)throw g}}}}var y=function(i){var g=Math.abs,o=Math.max;function l(e,i){var _;if(t(this,l),e>l.__kMaxLength)throw new RangeError("Maximum BigInt size exceeded");return _=a.call(this,e),_.sign=i,_}n(l,i);var a=h(l);return _(l,[{key:"toDebugString",value:function(){var e,t=["BigInt["],i=c(this);try{for(i.s();!(e=i.n()).done;){var _=e.value;t.push((_?(_>>>0).toString(16):_)+", ")}}catch(e){i.e(e)}finally{i.f()}return t.push("]"),t.join("")}},{key:"toString",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:10;if(2>e||36<e)throw new RangeError("toString() radix argument must be between 2 and 36");return 0===this.length?"0":0==(e&e-1)?l.__toStringBasePowerOfTwo(this,e):l.__toStringGeneric(this,e,!1)}},{key:"__copy",value:function(){for(var e=new l(this.length,this.sign),t=0;t<this.length;t++)e[t]=this[t];return e}},{key:"__trim",value:function(){for(var e=this.length,t=this[e-1];0===t;)e--,t=this[e-1],this.pop();return 0===e&&(this.sign=!1),this}},{key:"__initializeDigits",value:function(){for(var e=0;e<this.length;e++)this[e]=0}},{key:"__clzmsd",value:function(){return l.__clz32(this[this.length-1])}},{key:"__inplaceMultiplyAdd",value:function(e,t,_){_>this.length&&(_=this.length);for(var n=65535&e,g=e>>>16,o=0,a=65535&t,s=t>>>16,u=0;u<_;u++){var r=this.__digit(u),d=65535&r,h=r>>>16,b=l.__imul(d,n),m=l.__imul(d,g),c=l.__imul(h,n),v=l.__imul(h,g),f=a+(65535&b),y=s+o+(f>>>16)+(b>>>16)+(65535&m)+(65535&c);a=(m>>>16)+(c>>>16)+(65535&v)+(y>>>16),o=a>>>16,a&=65535,s=v>>>16;this.__setDigit(u,65535&f|y<<16)}if(0!==o||0!==a||0!==s)throw new Error("implementation bug")}},{key:"__inplaceAdd",value:function(e,t,_){for(var n,l=0,g=0;g<_;g++)n=this.__halfDigit(t+g)+e.__halfDigit(g)+l,l=n>>>16,this.__setHalfDigit(t+g,n);return l}},{key:"__inplaceSub",value:function(e,t,_){var n=0;if(1&t){t>>=1;for(var l=this.__digit(t),g=65535&l,o=0;o<_-1>>>1;o++){var a=e.__digit(o),s=(l>>>16)-(65535&a)-n;n=1&s>>>16,this.__setDigit(t+o,s<<16|65535&g),l=this.__digit(t+o+1),g=(65535&l)-(a>>>16)-n,n=1&g>>>16}var u=e.__digit(o),r=(l>>>16)-(65535&u)-n;n=1&r>>>16,this.__setDigit(t+o,r<<16|65535&g);if(t+o+1>=this.length)throw new RangeError("out of bounds");0==(1&_)&&(l=this.__digit(t+o+1),g=(65535&l)-(u>>>16)-n,n=1&g>>>16,this.__setDigit(t+e.length,4294901760&l|65535&g))}else{t>>=1;for(var d=0;d<e.length-1;d++){var h=this.__digit(t+d),b=e.__digit(d),m=(65535&h)-(65535&b)-n;n=1&m>>>16;var c=(h>>>16)-(b>>>16)-n;n=1&c>>>16,this.__setDigit(t+d,c<<16|65535&m)}var v=this.__digit(t+d),f=e.__digit(d),y=(65535&v)-(65535&f)-n;n=1&y>>>16;var k=0;0==(1&_)&&(k=(v>>>16)-(f>>>16)-n,n=1&k>>>16),this.__setDigit(t+d,k<<16|65535&y)}return n}},{key:"__inplaceRightShift",value:function(e){if(0!==e){for(var t,_=this.__digit(0)>>>e,n=this.length-1,l=0;l<n;l++)t=this.__digit(l+1),this.__setDigit(l,t<<32-e|_),_=t>>>e;this.__setDigit(n,_)}}},{key:"__digit",value:function(e){return this[e]}},{key:"__unsignedDigit",value:function(e){return this[e]>>>0}},{key:"__setDigit",value:function(e,t){this[e]=0|t}},{key:"__setDigitGrow",value:function(e,t){this[e]=0|t}},{key:"__halfDigitLength",value:function(){var e=this.length;return 65535>=this.__unsignedDigit(e-1)?2*e-1:2*e}},{key:"__halfDigit",value:function(e){return 65535&this[e>>>1]>>>((1&e)<<4)}},{key:"__setHalfDigit",value:function(e,t){var i=e>>>1,_=this.__digit(i),n=1&e?65535&_|t<<16:4294901760&_|65535&t;this.__setDigit(i,n)}}],[{key:"BigInt",value:function(t){var i=Math.floor,_=Number.isFinite;if("number"==typeof t){if(0===t)return l.__zero();if((0|t)===t)return 0>t?l.__oneDigit(-t,!0):l.__oneDigit(t,!1);if(!_(t)||i(t)!==t)throw new RangeError("The number "+t+" cannot be converted to BigInt because it is not an integer");return l.__fromDouble(t)}if("string"==typeof t){var n=l.__fromString(t);if(null===n)throw new SyntaxError("Cannot convert "+t+" to a BigInt");return n}if("boolean"==typeof t)return!0===t?l.__oneDigit(1,!1):l.__zero();if("object"===e(t)){if(t.constructor===l)return t;var g=l.__toPrimitive(t);return l.BigInt(g)}throw new TypeError("Cannot convert "+t+" to a BigInt")}},{key:"toNumber",value:function(e){var t=e.length;if(0===t)return 0;if(1===t){var i=e.__unsignedDigit(0);return e.sign?-i:i}var _=e.__digit(t-1),n=l.__clz32(_),g=32*t-n;if(1024<g)return e.sign?-Infinity:1/0;var o=g-1,a=_,s=t-1,u=n+1,r=32===u?0:a<<u;r>>>=12;var d=u-12,h=12<=u?0:a<<20+u,b=20+u;0<d&&0<s&&(s--,a=e.__digit(s),r|=a>>>32-d,h=a<<d,b=d),0<b&&0<s&&(s--,a=e.__digit(s),h|=a>>>32-b,b-=32);var m=l.__decideRounding(e,b,s,a);if((1===m||0===m&&1==(1&h))&&(h=h+1>>>0,0===h&&(r++,0!=r>>>20&&(r=0,o++,1023<o))))return e.sign?-Infinity:1/0;var c=e.sign?-2147483648:0;return o=o+1023<<20,l.__kBitConversionInts[1]=c|o|r,l.__kBitConversionInts[0]=h,l.__kBitConversionDouble[0]}},{key:"unaryMinus",value:function(e){if(0===e.length)return e;var t=e.__copy();return t.sign=!e.sign,t}},{key:"bitwiseNot",value:function(e){return e.sign?l.__absoluteSubOne(e).__trim():l.__absoluteAddOne(e,!0)}},{key:"exponentiate",value:function(e,t){if(t.sign)throw new RangeError("Exponent must be positive");if(0===t.length)return l.__oneDigit(1,!1);if(0===e.length)return e;if(1===e.length&&1===e.__digit(0))return e.sign&&0==(1&t.__digit(0))?l.unaryMinus(e):e;if(1<t.length)throw new RangeError("BigInt too big");var i=t.__unsignedDigit(0);if(1===i)return e;if(i>=l.__kMaxLengthBits)throw new RangeError("BigInt too big");if(1===e.length&&2===e.__digit(0)){var _=1+(i>>>5),n=e.sign&&0!=(1&i),g=new l(_,n);g.__initializeDigits();var o=1<<(31&i);return g.__setDigit(_-1,o),g}var a=null,s=e;for(0!=(1&i)&&(a=e),i>>=1;0!==i;i>>=1)s=l.multiply(s,s),0!=(1&i)&&(null===a?a=s:a=l.multiply(a,s));return a}},{key:"multiply",value:function(e,t){if(0===e.length)return e;if(0===t.length)return t;var _=e.length+t.length;32<=e.__clzmsd()+t.__clzmsd()&&_--;var n=new l(_,e.sign!==t.sign);n.__initializeDigits();for(var g=0;g<e.length;g++)l.__multiplyAccumulate(t,e.__digit(g),n,g);return n.__trim()}},{key:"divide",value:function(e,t){if(0===t.length)throw new RangeError("Division by zero");if(0>l.__absoluteCompare(e,t))return l.__zero();var i,_=e.sign!==t.sign,n=t.__unsignedDigit(0);if(1===t.length&&65535>=n){if(1===n)return _===e.sign?e:l.unaryMinus(e);i=l.__absoluteDivSmall(e,n,null)}else i=l.__absoluteDivLarge(e,t,!0,!1);return i.sign=_,i.__trim()}},{key:"remainder",value:function e(t,i){if(0===i.length)throw new RangeError("Division by zero");if(0>l.__absoluteCompare(t,i))return t;var _=i.__unsignedDigit(0);if(1===i.length&&65535>=_){if(1===_)return l.__zero();var n=l.__absoluteModSmall(t,_);return 0===n?l.__zero():l.__oneDigit(n,t.sign)}var e=l.__absoluteDivLarge(t,i,!1,!0);return e.sign=t.sign,e.__trim()}},{key:"add",value:function(e,t){var i=e.sign;return i===t.sign?l.__absoluteAdd(e,t,i):0<=l.__absoluteCompare(e,t)?l.__absoluteSub(e,t,i):l.__absoluteSub(t,e,!i)}},{key:"subtract",value:function(e,t){var i=e.sign;return i===t.sign?0<=l.__absoluteCompare(e,t)?l.__absoluteSub(e,t,i):l.__absoluteSub(t,e,!i):l.__absoluteAdd(e,t,i)}},{key:"leftShift",value:function(e,t){return 0===t.length||0===e.length?e:t.sign?l.__rightShiftByAbsolute(e,t):l.__leftShiftByAbsolute(e,t)}},{key:"signedRightShift",value:function(e,t){return 0===t.length||0===e.length?e:t.sign?l.__leftShiftByAbsolute(e,t):l.__rightShiftByAbsolute(e,t)}},{key:"unsignedRightShift",value:function(){throw new TypeError("BigInts have no unsigned right shift; use >> instead")}},{key:"lessThan",value:function(e,t){return 0>l.__compareToBigInt(e,t)}},{key:"lessThanOrEqual",value:function(e,t){return 0>=l.__compareToBigInt(e,t)}},{key:"greaterThan",value:function(e,t){return 0<l.__compareToBigInt(e,t)}},{key:"greaterThanOrEqual",value:function(e,t){return 0<=l.__compareToBigInt(e,t)}},{key:"equal",value:function(e,t){if(e.sign!==t.sign)return!1;if(e.length!==t.length)return!1;for(var _=0;_<e.length;_++)if(e.__digit(_)!==t.__digit(_))return!1;return!0}},{key:"notEqual",value:function(e,t){return!l.equal(e,t)}},{key:"bitwiseAnd",value:function(e,t){if(!e.sign&&!t.sign)return l.__absoluteAnd(e,t).__trim();if(e.sign&&t.sign){var i=o(e.length,t.length)+1,_=l.__absoluteSubOne(e,i),n=l.__absoluteSubOne(t);return _=l.__absoluteOr(_,n,_),l.__absoluteAddOne(_,!0,_).__trim()}if(e.sign){var g=[t,e];e=g[0],t=g[1]}return l.__absoluteAndNot(e,l.__absoluteSubOne(t)).__trim()}},{key:"bitwiseXor",value:function(e,t){if(!e.sign&&!t.sign)return l.__absoluteXor(e,t).__trim();if(e.sign&&t.sign){var i=o(e.length,t.length),_=l.__absoluteSubOne(e,i),n=l.__absoluteSubOne(t);return l.__absoluteXor(_,n,_).__trim()}var g=o(e.length,t.length)+1;if(e.sign){var a=[t,e];e=a[0],t=a[1]}var s=l.__absoluteSubOne(t,g);return s=l.__absoluteXor(s,e,s),l.__absoluteAddOne(s,!0,s).__trim()}},{key:"bitwiseOr",value:function(e,t){var i=o(e.length,t.length);if(!e.sign&&!t.sign)return l.__absoluteOr(e,t).__trim();if(e.sign&&t.sign){var _=l.__absoluteSubOne(e,i),n=l.__absoluteSubOne(t);return _=l.__absoluteAnd(_,n,_),l.__absoluteAddOne(_,!0,_).__trim()}if(e.sign){var g=[t,e];e=g[0],t=g[1]}var a=l.__absoluteSubOne(t,i);return a=l.__absoluteAndNot(a,e,a),l.__absoluteAddOne(a,!0,a).__trim()}},{key:"asIntN",value:function(e,t){if(0===t.length)return t;if(0===e)return l.__zero();if(e>=l.__kMaxLengthBits)return t;var _=e+31>>>5;if(t.length<_)return t;var n=t.__unsignedDigit(_-1),g=1<<(31&e-1);if(t.length===_&&n<g)return t;if(!((n&g)===g))return l.__truncateToNBits(e,t);if(!t.sign)return l.__truncateAndSubFromPowerOfTwo(e,t,!0);if(0==(n&g-1)){for(var o=_-2;0<=o;o--)if(0!==t.__digit(o))return l.__truncateAndSubFromPowerOfTwo(e,t,!1);return t.length===_&&n===g?t:l.__truncateToNBits(e,t)}return l.__truncateAndSubFromPowerOfTwo(e,t,!1)}},{key:"asUintN",value:function(e,t){if(0===t.length)return t;if(0===e)return l.__zero();if(t.sign){if(e>l.__kMaxLengthBits)throw new RangeError("BigInt too big");return l.__truncateAndSubFromPowerOfTwo(e,t,!1)}if(e>=l.__kMaxLengthBits)return t;var i=e+31>>>5;if(t.length<i)return t;var _=31&e;if(t.length==i){if(0===_)return t;var n=t.__digit(i-1);if(0==n>>>_)return t}return l.__truncateToNBits(e,t)}},{key:"ADD",value:function(e,t){if(e=l.__toPrimitive(e),t=l.__toPrimitive(t),"string"==typeof e)return"string"!=typeof t&&(t=t.toString()),e+t;if("string"==typeof t)return e.toString()+t;if(e=l.__toNumeric(e),t=l.__toNumeric(t),l.__isBigInt(e)&&l.__isBigInt(t))return l.add(e,t);if("number"==typeof e&&"number"==typeof t)return e+t;throw new TypeError("Cannot mix BigInt and other types, use explicit conversions")}},{key:"LT",value:function(e,t){return l.__compare(e,t,0)}},{key:"LE",value:function(e,t){return l.__compare(e,t,1)}},{key:"GT",value:function(e,t){return l.__compare(e,t,2)}},{key:"GE",value:function(e,t){return l.__compare(e,t,3)}},{key:"EQ",value:function(t,i){for(;;){if(l.__isBigInt(t))return l.__isBigInt(i)?l.equal(t,i):l.EQ(i,t);if("number"==typeof t){if(l.__isBigInt(i))return l.__equalToNumber(i,t);if("object"!==e(i))return t==i;i=l.__toPrimitive(i)}else if("string"==typeof t){if(l.__isBigInt(i))return t=l.__fromString(t),null!==t&&l.equal(t,i);if("object"!==e(i))return t==i;i=l.__toPrimitive(i)}else if("boolean"==typeof t){if(l.__isBigInt(i))return l.__equalToNumber(i,+t);if("object"!==e(i))return t==i;i=l.__toPrimitive(i)}else if("symbol"===e(t)){if(l.__isBigInt(i))return!1;if("object"!==e(i))return t==i;i=l.__toPrimitive(i)}else if("object"===e(t)){if("object"===e(i)&&i.constructor!==l)return t==i;t=l.__toPrimitive(t)}else return t==i}}},{key:"NE",value:function(e,t){return!l.EQ(e,t)}},{key:"__zero",value:function(){return new l(0,!1)}},{key:"__oneDigit",value:function(e,t){var i=new l(1,t);return i.__setDigit(0,e),i}},{key:"__decideRounding",value:function(e,t,i,_){if(0<t)return-1;var n;if(0>t)n=-t-1;else{if(0===i)return-1;i--,_=e.__digit(i),n=31}var l=1<<n;if(0==(_&l))return-1;if(l-=1,0!=(_&l))return 1;for(;0<i;)if(i--,0!==e.__digit(i))return 1;return 0}},{key:"__fromDouble",value:function(e){l.__kBitConversionDouble[0]=e;var t,i=2047&l.__kBitConversionInts[1]>>>20,_=i-1023,n=(_>>>5)+1,g=new l(n,0>e),o=1048575&l.__kBitConversionInts[1]|1048576,a=l.__kBitConversionInts[0],s=20,u=31&_,r=0;if(u<s){var d=s-u;r=d+32,t=o>>>d,o=o<<32-d|a>>>d,a<<=32-d}else if(u===s)r=32,t=o,o=a;else{var h=u-s;r=32-h,t=o<<h|a>>>32-h,o=a<<h}g.__setDigit(n-1,t);for(var b=n-2;0<=b;b--)0<r?(r-=32,t=o,o=a):t=0,g.__setDigit(b,t);return g.__trim()}},{key:"__isWhitespace",value:function(e){return!!(13>=e&&9<=e)||(159>=e?32==e:131071>=e?160==e||5760==e:196607>=e?(e&=131071,10>=e||40==e||41==e||47==e||95==e||4096==e):65279==e)}},{key:"__fromString",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,i=0,_=e.length,n=0;if(n===_)return l.__zero();for(var g=e.charCodeAt(n);l.__isWhitespace(g);){if(++n===_)return l.__zero();g=e.charCodeAt(n)}if(43===g){if(++n===_)return null;g=e.charCodeAt(n),i=1}else if(45===g){if(++n===_)return null;g=e.charCodeAt(n),i=-1}if(0===t){if(t=10,48===g){if(++n===_)return l.__zero();if(g=e.charCodeAt(n),88===g||120===g){if(t=16,++n===_)return null;g=e.charCodeAt(n)}else if(79===g||111===g){if(t=8,++n===_)return null;g=e.charCodeAt(n)}else if(66===g||98===g){if(t=2,++n===_)return null;g=e.charCodeAt(n)}}}else if(16===t&&48===g){if(++n===_)return l.__zero();if(g=e.charCodeAt(n),88===g||120===g){if(++n===_)return null;g=e.charCodeAt(n)}}for(;48===g;){if(++n===_)return l.__zero();g=e.charCodeAt(n)}var o=_-n,a=l.__kMaxBitsPerChar[t],s=l.__kBitsPerCharTableMultiplier-1;if(o>1073741824/a)return null;var u=a*o+s>>>l.__kBitsPerCharTableShift,r=new l(u+31>>>5,!1),h=10>t?t:10,b=10<t?t-10:0;if(0==(t&t-1)){a>>=l.__kBitsPerCharTableShift;var c=[],v=[],f=!1;do{for(var y,k=0,D=0;;){if(y=void 0,g-48>>>0<h)y=g-48;else if((32|g)-97>>>0<b)y=(32|g)-87;else{f=!0;break}if(D+=a,k=k<<a|y,++n===_){f=!0;break}if(g=e.charCodeAt(n),32<D+a)break}c.push(k),v.push(D)}while(!f);l.__fillFromParts(r,c,v)}else{r.__initializeDigits();var p=!1,B=0;do{for(var S,C=0,A=1;;){if(S=void 0,g-48>>>0<h)S=g-48;else if((32|g)-97>>>0<b)S=(32|g)-87;else{p=!0;break}var T=A*t;if(4294967295<T)break;if(A=T,C=C*t+S,B++,++n===_){p=!0;break}g=e.charCodeAt(n)}s=32*l.__kBitsPerCharTableMultiplier-1;var m=a*B+s>>>l.__kBitsPerCharTableShift+5;r.__inplaceMultiplyAdd(A,C,m)}while(!p)}if(n!==_){if(!l.__isWhitespace(g))return null;for(n++;n<_;n++)if(g=e.charCodeAt(n),!l.__isWhitespace(g))return null}return 0!==i&&10!==t?null:(r.sign=-1===i,r.__trim())}},{key:"__fillFromParts",value:function(e,t,_){for(var n=0,l=0,g=0,o=t.length-1;0<=o;o--){var a=t[o],s=_[o];l|=a<<g,g+=s,32===g?(e.__setDigit(n++,l),g=0,l=0):32<g&&(e.__setDigit(n++,l),g-=32,l=a>>>s-g)}if(0!==l){if(n>=e.length)throw new Error("implementation bug");e.__setDigit(n++,l)}for(;n<e.length;n++)e.__setDigit(n,0)}},{key:"__toStringBasePowerOfTwo",value:function(e,t){var _=e.length,n=t-1;n=(85&n>>>1)+(85&n),n=(51&n>>>2)+(51&n),n=(15&n>>>4)+(15&n);var g=n,o=t-1,a=e.__digit(_-1),s=l.__clz32(a),u=0|(32*_-s+g-1)/g;if(e.sign&&u++,268435456<u)throw new Error("string too long");for(var r=Array(u),d=u-1,h=0,b=0,m=0;m<_-1;m++){var c=e.__digit(m),v=(h|c<<b)&o;r[d--]=l.__kConversionChars[v];var f=g-b;for(h=c>>>f,b=32-f;b>=g;)r[d--]=l.__kConversionChars[h&o],h>>>=g,b-=g}var y=(h|a<<b)&o;for(r[d--]=l.__kConversionChars[y],h=a>>>g-b;0!==h;)r[d--]=l.__kConversionChars[h&o],h>>>=g;if(e.sign&&(r[d--]="-"),-1!==d)throw new Error("implementation bug");return r.join("")}},{key:"__toStringGeneric",value:function(e,t,_){var n=e.length;if(0===n)return"";if(1===n){var g=e.__unsignedDigit(0).toString(t);return!1===_&&e.sign&&(g="-"+g),g}var o=32*n-l.__clz32(e.__digit(n-1)),a=l.__kMaxBitsPerChar[t],s=a-1,u=o*l.__kBitsPerCharTableMultiplier;u+=s-1,u=0|u/s;var r,d,h=u+1>>1,b=l.exponentiate(l.__oneDigit(t,!1),l.__oneDigit(h,!1)),m=b.__unsignedDigit(0);if(1===b.length&&65535>=m){r=new l(e.length,!1),r.__initializeDigits();for(var c,v=0,f=2*e.length-1;0<=f;f--)c=v<<16|e.__halfDigit(f),r.__setHalfDigit(f,0|c/m),v=0|c%m;d=v.toString(t)}else{var y=l.__absoluteDivLarge(e,b,!0,!0);r=y.quotient;var k=y.remainder.__trim();d=l.__toStringGeneric(k,t,!0)}r.__trim();for(var D=l.__toStringGeneric(r,t,!0);d.length<h;)d="0"+d;return!1===_&&e.sign&&(D="-"+D),D+d}},{key:"__unequalSign",value:function(e){return e?-1:1}},{key:"__absoluteGreater",value:function(e){return e?-1:1}},{key:"__absoluteLess",value:function(e){return e?1:-1}},{key:"__compareToBigInt",value:function(e,t){var i=e.sign;if(i!==t.sign)return l.__unequalSign(i);var _=l.__absoluteCompare(e,t);return 0<_?l.__absoluteGreater(i):0>_?l.__absoluteLess(i):0}},{key:"__compareToNumber",value:function(e,t){if(!0|t){var i=e.sign,_=0>t;if(i!==_)return l.__unequalSign(i);if(0===e.length){if(_)throw new Error("implementation bug");return 0===t?0:-1}if(1<e.length)return l.__absoluteGreater(i);var n=g(t),o=e.__unsignedDigit(0);return o>n?l.__absoluteGreater(i):o<n?l.__absoluteLess(i):0}return l.__compareToDouble(e,t)}},{key:"__compareToDouble",value:function(e,t){if(t!==t)return t;if(t===1/0)return-1;if(t===-Infinity)return 1;var i=e.sign;if(i!==0>t)return l.__unequalSign(i);if(0===t)throw new Error("implementation bug: should be handled elsewhere");if(0===e.length)return-1;l.__kBitConversionDouble[0]=t;var _=2047&l.__kBitConversionInts[1]>>>20;if(2047==_)throw new Error("implementation bug: handled elsewhere");var n=_-1023;if(0>n)return l.__absoluteGreater(i);var g=e.length,o=e.__digit(g-1),a=l.__clz32(o),s=32*g-a,u=n+1;if(s<u)return l.__absoluteLess(i);if(s>u)return l.__absoluteGreater(i);var r=1048576|1048575&l.__kBitConversionInts[1],d=l.__kBitConversionInts[0],h=20,b=31-a;if(b!==(s-1)%31)throw new Error("implementation bug");var m,c=0;if(b<h){var v=h-b;c=v+32,m=r>>>v,r=r<<32-v|d>>>v,d<<=32-v}else if(b===h)c=32,m=r,r=d;else{var f=b-h;c=32-f,m=r<<f|d>>>32-f,r=d<<f}if(o>>>=0,m>>>=0,o>m)return l.__absoluteGreater(i);if(o<m)return l.__absoluteLess(i);for(var y=g-2;0<=y;y--){0<c?(c-=32,m=r>>>0,r=d,d=0):m=0;var k=e.__unsignedDigit(y);if(k>m)return l.__absoluteGreater(i);if(k<m)return l.__absoluteLess(i)}if(0!==r||0!==d){if(0===c)throw new Error("implementation bug");return l.__absoluteLess(i)}return 0}},{key:"__equalToNumber",value:function(e,t){return t|0===t?0===t?0===e.length:1===e.length&&e.sign===0>t&&e.__unsignedDigit(0)===g(t):0===l.__compareToDouble(e,t)}},{key:"__comparisonResultToBool",value:function(e,t){switch(t){case 0:return 0>e;case 1:return 0>=e;case 2:return 0<e;case 3:return 0<=e;}throw new Error("unreachable")}},{key:"__compare",value:function(e,t,i){if(e=l.__toPrimitive(e),t=l.__toPrimitive(t),"string"==typeof e&&"string"==typeof t)switch(i){case 0:return e<t;case 1:return e<=t;case 2:return e>t;case 3:return e>=t;}if(l.__isBigInt(e)&&"string"==typeof t)return t=l.__fromString(t),null!==t&&l.__comparisonResultToBool(l.__compareToBigInt(e,t),i);if("string"==typeof e&&l.__isBigInt(t))return e=l.__fromString(e),null!==e&&l.__comparisonResultToBool(l.__compareToBigInt(e,t),i);if(e=l.__toNumeric(e),t=l.__toNumeric(t),l.__isBigInt(e)){if(l.__isBigInt(t))return l.__comparisonResultToBool(l.__compareToBigInt(e,t),i);if("number"!=typeof t)throw new Error("implementation bug");return l.__comparisonResultToBool(l.__compareToNumber(e,t),i)}if("number"!=typeof e)throw new Error("implementation bug");if(l.__isBigInt(t))return l.__comparisonResultToBool(l.__compareToNumber(t,e),2^i);if("number"!=typeof t)throw new Error("implementation bug");return 0===i?e<t:1===i?e<=t:2===i?e>t:3===i?e>=t:void 0}},{key:"__absoluteAdd",value:function(e,t,_){if(e.length<t.length)return l.__absoluteAdd(t,e,_);if(0===e.length)return e;if(0===t.length)return e.sign===_?e:l.unaryMinus(e);var n=e.length;(0===e.__clzmsd()||t.length===e.length&&0===t.__clzmsd())&&n++;for(var g=new l(n,_),o=0,a=0;a<t.length;a++){var s=t.__digit(a),u=e.__digit(a),r=(65535&u)+(65535&s)+o,d=(u>>>16)+(s>>>16)+(r>>>16);o=d>>>16,g.__setDigit(a,65535&r|d<<16)}for(;a<e.length;a++){var h=e.__digit(a),b=(65535&h)+o,m=(h>>>16)+(b>>>16);o=m>>>16,g.__setDigit(a,65535&b|m<<16)}return a<g.length&&g.__setDigit(a,o),g.__trim()}},{key:"__absoluteSub",value:function(e,t,_){if(0===e.length)return e;if(0===t.length)return e.sign===_?e:l.unaryMinus(e);for(var n=new l(e.length,_),g=0,o=0;o<t.length;o++){var a=e.__digit(o),s=t.__digit(o),u=(65535&a)-(65535&s)-g;g=1&u>>>16;var r=(a>>>16)-(s>>>16)-g;g=1&r>>>16,n.__setDigit(o,65535&u|r<<16)}for(;o<e.length;o++){var d=e.__digit(o),h=(65535&d)-g;g=1&h>>>16;var b=(d>>>16)-g;g=1&b>>>16,n.__setDigit(o,65535&h|b<<16)}return n.__trim()}},{key:"__absoluteAddOne",value:function(e,t){var _=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,n=e.length;null===_?_=new l(n,t):_.sign=t;for(var g,o=!0,a=0;a<n;a++){if(g=e.__digit(a),o){var s=-1===g;g=0|g+1,o=s}_.__setDigit(a,g)}return o&&_.__setDigitGrow(n,1),_}},{key:"__absoluteSubOne",value:function(e,t){var _=e.length;t=t||_;for(var n,g=new l(t,!1),o=!0,a=0;a<_;a++){if(n=e.__digit(a),o){var s=0===n;n=0|n-1,o=s}g.__setDigit(a,n)}if(o)throw new Error("implementation bug");for(var u=_;u<t;u++)g.__setDigit(u,0);return g}},{key:"__absoluteAnd",value:function(e,t){var _=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,n=e.length,g=t.length,o=g;if(n<g){o=n;var a=e,s=n;e=t,n=g,t=a,g=s}var u=o;null===_?_=new l(u,!1):u=_.length;for(var r=0;r<o;r++)_.__setDigit(r,e.__digit(r)&t.__digit(r));for(;r<u;r++)_.__setDigit(r,0);return _}},{key:"__absoluteAndNot",value:function(e,t){var _=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,n=e.length,g=t.length,o=g;n<g&&(o=n);var a=n;null===_?_=new l(a,!1):a=_.length;for(var s=0;s<o;s++)_.__setDigit(s,e.__digit(s)&~t.__digit(s));for(;s<n;s++)_.__setDigit(s,e.__digit(s));for(;s<a;s++)_.__setDigit(s,0);return _}},{key:"__absoluteOr",value:function(e,t){var _=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,n=e.length,g=t.length,o=g;if(n<g){o=n;var a=e,s=n;e=t,n=g,t=a,g=s}var u=n;null===_?_=new l(u,!1):u=_.length;for(var r=0;r<o;r++)_.__setDigit(r,e.__digit(r)|t.__digit(r));for(;r<n;r++)_.__setDigit(r,e.__digit(r));for(;r<u;r++)_.__setDigit(r,0);return _}},{key:"__absoluteXor",value:function(e,t){var _=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null,n=e.length,g=t.length,o=g;if(n<g){o=n;var a=e,s=n;e=t,n=g,t=a,g=s}var u=n;null===_?_=new l(u,!1):u=_.length;for(var r=0;r<o;r++)_.__setDigit(r,e.__digit(r)^t.__digit(r));for(;r<n;r++)_.__setDigit(r,e.__digit(r));for(;r<u;r++)_.__setDigit(r,0);return _}},{key:"__absoluteCompare",value:function(e,t){var _=e.length-t.length;if(0!=_)return _;for(var n=e.length-1;0<=n&&e.__digit(n)===t.__digit(n);)n--;return 0>n?0:e.__unsignedDigit(n)>t.__unsignedDigit(n)?1:-1}},{key:"__multiplyAccumulate",value:function(e,t,_,n){if(0!==t){for(var g=65535&t,o=t>>>16,a=0,s=0,u=0,r=0;r<e.length;r++,n++){var d=_.__digit(n),h=65535&d,b=d>>>16,m=e.__digit(r),c=65535&m,v=m>>>16,f=l.__imul(c,g),y=l.__imul(c,o),k=l.__imul(v,g),D=l.__imul(v,o);h+=s+(65535&f),b+=u+a+(h>>>16)+(f>>>16)+(65535&y)+(65535&k),a=b>>>16,s=(y>>>16)+(k>>>16)+(65535&D)+a,a=s>>>16,s&=65535,u=D>>>16,d=65535&h|b<<16,_.__setDigit(n,d)}for(;0!==a||0!==s||0!==u;n++){var p=_.__digit(n),B=(65535&p)+s,S=(p>>>16)+(B>>>16)+u+a;s=0,u=0,a=S>>>16,p=65535&B|S<<16,_.__setDigit(n,p)}}}},{key:"__internalMultiplyAdd",value:function(e,t,_,g,o){for(var a=_,s=0,u=0;u<g;u++){var r=e.__digit(u),d=l.__imul(65535&r,t),h=(65535&d)+s+a;a=h>>>16;var b=l.__imul(r>>>16,t),m=(65535&b)+(d>>>16)+a;a=m>>>16,s=b>>>16,o.__setDigit(u,m<<16|65535&h)}if(o.length>g)for(o.__setDigit(g++,a+s);g<o.length;)o.__setDigit(g++,0);else if(0!==a+s)throw new Error("implementation bug")}},{key:"__absoluteDivSmall",value:function(e,t,_){null===_&&(_=new l(e.length,!1));for(var n=0,g=2*e.length-1;0<=g;g-=2){var o=(n<<16|e.__halfDigit(g))>>>0,a=0|o/t;n=0|o%t,o=(n<<16|e.__halfDigit(g-1))>>>0;var s=0|o/t;n=0|o%t,_.__setDigit(g>>>1,a<<16|s)}return _}},{key:"__absoluteModSmall",value:function(e,t){for(var _,n=0,l=2*e.length-1;0<=l;l--)_=(n<<16|e.__halfDigit(l))>>>0,n=0|_%t;return n}},{key:"__absoluteDivLarge",value:function(e,t,i,_){var g=t.__halfDigitLength(),n=t.length,o=e.__halfDigitLength()-g,a=null;i&&(a=new l(o+2>>>1,!1),a.__initializeDigits());var s=new l(g+2>>>1,!1);s.__initializeDigits();var r=l.__clz16(t.__halfDigit(g-1));0<r&&(t=l.__specialLeftShift(t,r,0));for(var d=l.__specialLeftShift(e,r,1),u=t.__halfDigit(g-1),h=0,b=o;0<=b;b--){var m=65535,v=d.__halfDigit(b+g);if(v!==u){var f=(v<<16|d.__halfDigit(b+g-1))>>>0;m=0|f/u;for(var y=0|f%u,k=t.__halfDigit(g-2),D=d.__halfDigit(b+g-2);l.__imul(m,k)>>>0>(y<<16|D)>>>0&&(m--,y+=u,!(65535<y)););}l.__internalMultiplyAdd(t,m,0,n,s);var p=d.__inplaceSub(s,b,g+1);0!==p&&(p=d.__inplaceAdd(t,b,g),d.__setHalfDigit(b+g,d.__halfDigit(b+g)+p),m--),i&&(1&b?h=m<<16:a.__setDigit(b>>>1,h|m))}return _?(d.__inplaceRightShift(r),i?{quotient:a,remainder:d}:d):i?a:void 0}},{key:"__clz16",value:function(e){return l.__clz32(e)-16}},{key:"__specialLeftShift",value:function(e,t,_){var g=e.length,n=new l(g+_,!1);if(0===t){for(var o=0;o<g;o++)n.__setDigit(o,e.__digit(o));return 0<_&&n.__setDigit(g,0),n}for(var a,s=0,u=0;u<g;u++)a=e.__digit(u),n.__setDigit(u,a<<t|s),s=a>>>32-t;return 0<_&&n.__setDigit(g,s),n}},{key:"__leftShiftByAbsolute",value:function(e,t){var _=l.__toShiftAmount(t);if(0>_)throw new RangeError("BigInt too big");var n=_>>>5,g=31&_,o=e.length,a=0!==g&&0!=e.__digit(o-1)>>>32-g,s=o+n+(a?1:0),u=new l(s,e.sign);if(0===g){for(var r=0;r<n;r++)u.__setDigit(r,0);for(;r<s;r++)u.__setDigit(r,e.__digit(r-n))}else{for(var h=0,b=0;b<n;b++)u.__setDigit(b,0);for(var m,c=0;c<o;c++)m=e.__digit(c),u.__setDigit(c+n,m<<g|h),h=m>>>32-g;if(a)u.__setDigit(o+n,h);else if(0!==h)throw new Error("implementation bug")}return u.__trim()}},{key:"__rightShiftByAbsolute",value:function(e,t){var _=e.length,n=e.sign,g=l.__toShiftAmount(t);if(0>g)return l.__rightShiftByMaximum(n);var o=g>>>5,a=31&g,s=_-o;if(0>=s)return l.__rightShiftByMaximum(n);var u=!1;if(n){if(0!=(e.__digit(o)&(1<<a)-1))u=!0;else for(var r=0;r<o;r++)if(0!==e.__digit(r)){u=!0;break}}if(u&&0===a){var h=e.__digit(_-1);0==~h&&s++}var b=new l(s,n);if(0===a)for(var m=o;m<_;m++)b.__setDigit(m-o,e.__digit(m));else{for(var c,v=e.__digit(o)>>>a,f=_-o-1,y=0;y<f;y++)c=e.__digit(y+o+1),b.__setDigit(y,c<<32-a|v),v=c>>>a;b.__setDigit(f,v)}return u&&(b=l.__absoluteAddOne(b,!0,b)),b.__trim()}},{key:"__rightShiftByMaximum",value:function(e){return e?l.__oneDigit(1,!0):l.__zero()}},{key:"__toShiftAmount",value:function(e){if(1<e.length)return-1;var t=e.__unsignedDigit(0);return t>l.__kMaxLengthBits?-1:t}},{key:"__toPrimitive",value:function(t){var i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"default";if("object"!==e(t))return t;if(t.constructor===l)return t;var _=t[Symbol.toPrimitive];if(_){var n=_(i);if("object"!==e(n))return n;throw new TypeError("Cannot convert object to primitive value")}var g=t.valueOf;if(g){var o=g.call(t);if("object"!==e(o))return o}var a=t.toString;if(a){var s=a.call(t);if("object"!==e(s))return s}throw new TypeError("Cannot convert object to primitive value")}},{key:"__toNumeric",value:function(e){return l.__isBigInt(e)?e:+e}},{key:"__isBigInt",value:function(t){return"object"===e(t)&&t.constructor===l}},{key:"__truncateToNBits",value:function(e,t){for(var _=e+31>>>5,n=new l(_,t.sign),g=_-1,o=0;o<g;o++)n.__setDigit(o,t.__digit(o));var a=t.__digit(g);if(0!=(31&e)){var s=32-(31&e);a=a<<s>>>s}return n.__setDigit(g,a),n.__trim()}},{key:"__truncateAndSubFromPowerOfTwo",value:function(e,t,_){for(var n=Math.min,g=e+31>>>5,o=new l(g,_),a=0,s=g-1,u=0,r=n(s,t.length);a<r;a++){var d=t.__digit(a),h=0-(65535&d)-u;u=1&h>>>16;var b=0-(d>>>16)-u;u=1&b>>>16,o.__setDigit(a,65535&h|b<<16)}for(;a<s;a++)o.__setDigit(a,0|-u);var m,c=s<t.length?t.__digit(s):0,v=31&e;if(0===v){var f=0-(65535&c)-u;u=1&f>>>16;var y=0-(c>>>16)-u;m=65535&f|y<<16}else{var k=32-v;c=c<<k>>>k;var D=1<<32-k,p=(65535&D)-(65535&c)-u;u=1&p>>>16;var B=(D>>>16)-(c>>>16)-u;m=65535&p|B<<16,m&=D-1}return o.__setDigit(s,m),o.__trim()}},{key:"__digitPow",value:function(e,t){for(var i=1;0<t;)1&t&&(i*=e),t>>>=1,e*=e;return i}}]),l}(u(Array));return y.__kMaxLength=33554432,y.__kMaxLengthBits=y.__kMaxLength<<5,y.__kMaxBitsPerChar=[0,0,32,51,64,75,83,90,96,102,107,111,115,119,122,126,128,131,134,136,139,141,143,145,147,149,151,153,154,156,158,159,160,162,163,165,166],y.__kBitsPerCharTableShift=5,y.__kBitsPerCharTableMultiplier=1<<y.__kBitsPerCharTableShift,y.__kConversionChars=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],y.__kBitConversionBuffer=new ArrayBuffer(8),y.__kBitConversionDouble=new Float64Array(y.__kBitConversionBuffer),y.__kBitConversionInts=new Int32Array(y.__kBitConversionBuffer),y.__clz32=f||function(e){var t=Math.LN2,i=Math.log;return 0===e?32:0|31-(0|i(e>>>0)/t)},y.__imul=v||function(e,t){return 0|e*t},y});
  51894. },{}],328:[function(require,module,exports){
  51895. (function(){
  51896. // Copyright (c) 2005 Tom Wu
  51897. // All Rights Reserved.
  51898. // See "LICENSE" for details.
  51899. // Basic JavaScript BN library - subset useful for RSA encryption.
  51900. // Bits per digit
  51901. var dbits;
  51902. // JavaScript engine analysis
  51903. var canary = 0xdeadbeefcafe;
  51904. var j_lm = ((canary&0xffffff)==0xefcafe);
  51905. // (public) Constructor
  51906. function BigInteger(a,b,c) {
  51907. if(a != null)
  51908. if("number" == typeof a) this.fromNumber(a,b,c);
  51909. else if(b == null && "string" != typeof a) this.fromString(a,256);
  51910. else this.fromString(a,b);
  51911. }
  51912. // return new, unset BigInteger
  51913. function nbi() { return new BigInteger(null); }
  51914. // am: Compute w_j += (x*this_i), propagate carries,
  51915. // c is initial carry, returns final carry.
  51916. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  51917. // We need to select the fastest one that works in this environment.
  51918. // am1: use a single mult and divide to get the high bits,
  51919. // max digit bits should be 26 because
  51920. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  51921. function am1(i,x,w,j,c,n) {
  51922. while(--n >= 0) {
  51923. var v = x*this[i++]+w[j]+c;
  51924. c = Math.floor(v/0x4000000);
  51925. w[j++] = v&0x3ffffff;
  51926. }
  51927. return c;
  51928. }
  51929. // am2 avoids a big mult-and-extract completely.
  51930. // Max digit bits should be <= 30 because we do bitwise ops
  51931. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  51932. function am2(i,x,w,j,c,n) {
  51933. var xl = x&0x7fff, xh = x>>15;
  51934. while(--n >= 0) {
  51935. var l = this[i]&0x7fff;
  51936. var h = this[i++]>>15;
  51937. var m = xh*l+h*xl;
  51938. l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
  51939. c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
  51940. w[j++] = l&0x3fffffff;
  51941. }
  51942. return c;
  51943. }
  51944. // Alternately, set max digit bits to 28 since some
  51945. // browsers slow down when dealing with 32-bit numbers.
  51946. function am3(i,x,w,j,c,n) {
  51947. var xl = x&0x3fff, xh = x>>14;
  51948. while(--n >= 0) {
  51949. var l = this[i]&0x3fff;
  51950. var h = this[i++]>>14;
  51951. var m = xh*l+h*xl;
  51952. l = xl*l+((m&0x3fff)<<14)+w[j]+c;
  51953. c = (l>>28)+(m>>14)+xh*h;
  51954. w[j++] = l&0xfffffff;
  51955. }
  51956. return c;
  51957. }
  51958. var inBrowser = typeof navigator !== "undefined";
  51959. if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
  51960. BigInteger.prototype.am = am2;
  51961. dbits = 30;
  51962. }
  51963. else if(inBrowser && j_lm && (navigator.appName != "Netscape")) {
  51964. BigInteger.prototype.am = am1;
  51965. dbits = 26;
  51966. }
  51967. else { // Mozilla/Netscape seems to prefer am3
  51968. BigInteger.prototype.am = am3;
  51969. dbits = 28;
  51970. }
  51971. BigInteger.prototype.DB = dbits;
  51972. BigInteger.prototype.DM = ((1<<dbits)-1);
  51973. BigInteger.prototype.DV = (1<<dbits);
  51974. var BI_FP = 52;
  51975. BigInteger.prototype.FV = Math.pow(2,BI_FP);
  51976. BigInteger.prototype.F1 = BI_FP-dbits;
  51977. BigInteger.prototype.F2 = 2*dbits-BI_FP;
  51978. // Digit conversions
  51979. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  51980. var BI_RC = new Array();
  51981. var rr,vv;
  51982. rr = "0".charCodeAt(0);
  51983. for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  51984. rr = "a".charCodeAt(0);
  51985. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  51986. rr = "A".charCodeAt(0);
  51987. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  51988. function int2char(n) { return BI_RM.charAt(n); }
  51989. function intAt(s,i) {
  51990. var c = BI_RC[s.charCodeAt(i)];
  51991. return (c==null)?-1:c;
  51992. }
  51993. // (protected) copy this to r
  51994. function bnpCopyTo(r) {
  51995. for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
  51996. r.t = this.t;
  51997. r.s = this.s;
  51998. }
  51999. // (protected) set from integer value x, -DV <= x < DV
  52000. function bnpFromInt(x) {
  52001. this.t = 1;
  52002. this.s = (x<0)?-1:0;
  52003. if(x > 0) this[0] = x;
  52004. else if(x < -1) this[0] = x+this.DV;
  52005. else this.t = 0;
  52006. }
  52007. // return bigint initialized to value
  52008. function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
  52009. // (protected) set from string and radix
  52010. function bnpFromString(s,b) {
  52011. var k;
  52012. if(b == 16) k = 4;
  52013. else if(b == 8) k = 3;
  52014. else if(b == 256) k = 8; // byte array
  52015. else if(b == 2) k = 1;
  52016. else if(b == 32) k = 5;
  52017. else if(b == 4) k = 2;
  52018. else { this.fromRadix(s,b); return; }
  52019. this.t = 0;
  52020. this.s = 0;
  52021. var i = s.length, mi = false, sh = 0;
  52022. while(--i >= 0) {
  52023. var x = (k==8)?s[i]&0xff:intAt(s,i);
  52024. if(x < 0) {
  52025. if(s.charAt(i) == "-") mi = true;
  52026. continue;
  52027. }
  52028. mi = false;
  52029. if(sh == 0)
  52030. this[this.t++] = x;
  52031. else if(sh+k > this.DB) {
  52032. this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
  52033. this[this.t++] = (x>>(this.DB-sh));
  52034. }
  52035. else
  52036. this[this.t-1] |= x<<sh;
  52037. sh += k;
  52038. if(sh >= this.DB) sh -= this.DB;
  52039. }
  52040. if(k == 8 && (s[0]&0x80) != 0) {
  52041. this.s = -1;
  52042. if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
  52043. }
  52044. this.clamp();
  52045. if(mi) BigInteger.ZERO.subTo(this,this);
  52046. }
  52047. // (protected) clamp off excess high words
  52048. function bnpClamp() {
  52049. var c = this.s&this.DM;
  52050. while(this.t > 0 && this[this.t-1] == c) --this.t;
  52051. }
  52052. // (public) return string representation in given radix
  52053. function bnToString(b) {
  52054. if(this.s < 0) return "-"+this.negate().toString(b);
  52055. var k;
  52056. if(b == 16) k = 4;
  52057. else if(b == 8) k = 3;
  52058. else if(b == 2) k = 1;
  52059. else if(b == 32) k = 5;
  52060. else if(b == 4) k = 2;
  52061. else return this.toRadix(b);
  52062. var km = (1<<k)-1, d, m = false, r = "", i = this.t;
  52063. var p = this.DB-(i*this.DB)%k;
  52064. if(i-- > 0) {
  52065. if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
  52066. while(i >= 0) {
  52067. if(p < k) {
  52068. d = (this[i]&((1<<p)-1))<<(k-p);
  52069. d |= this[--i]>>(p+=this.DB-k);
  52070. }
  52071. else {
  52072. d = (this[i]>>(p-=k))&km;
  52073. if(p <= 0) { p += this.DB; --i; }
  52074. }
  52075. if(d > 0) m = true;
  52076. if(m) r += int2char(d);
  52077. }
  52078. }
  52079. return m?r:"0";
  52080. }
  52081. // (public) -this
  52082. function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
  52083. // (public) |this|
  52084. function bnAbs() { return (this.s<0)?this.negate():this; }
  52085. // (public) return + if this > a, - if this < a, 0 if equal
  52086. function bnCompareTo(a) {
  52087. var r = this.s-a.s;
  52088. if(r != 0) return r;
  52089. var i = this.t;
  52090. r = i-a.t;
  52091. if(r != 0) return (this.s<0)?-r:r;
  52092. while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
  52093. return 0;
  52094. }
  52095. // returns bit length of the integer x
  52096. function nbits(x) {
  52097. var r = 1, t;
  52098. if((t=x>>>16) != 0) { x = t; r += 16; }
  52099. if((t=x>>8) != 0) { x = t; r += 8; }
  52100. if((t=x>>4) != 0) { x = t; r += 4; }
  52101. if((t=x>>2) != 0) { x = t; r += 2; }
  52102. if((t=x>>1) != 0) { x = t; r += 1; }
  52103. return r;
  52104. }
  52105. // (public) return the number of bits in "this"
  52106. function bnBitLength() {
  52107. if(this.t <= 0) return 0;
  52108. return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
  52109. }
  52110. // (protected) r = this << n*DB
  52111. function bnpDLShiftTo(n,r) {
  52112. var i;
  52113. for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
  52114. for(i = n-1; i >= 0; --i) r[i] = 0;
  52115. r.t = this.t+n;
  52116. r.s = this.s;
  52117. }
  52118. // (protected) r = this >> n*DB
  52119. function bnpDRShiftTo(n,r) {
  52120. for(var i = n; i < this.t; ++i) r[i-n] = this[i];
  52121. r.t = Math.max(this.t-n,0);
  52122. r.s = this.s;
  52123. }
  52124. // (protected) r = this << n
  52125. function bnpLShiftTo(n,r) {
  52126. var bs = n%this.DB;
  52127. var cbs = this.DB-bs;
  52128. var bm = (1<<cbs)-1;
  52129. var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
  52130. for(i = this.t-1; i >= 0; --i) {
  52131. r[i+ds+1] = (this[i]>>cbs)|c;
  52132. c = (this[i]&bm)<<bs;
  52133. }
  52134. for(i = ds-1; i >= 0; --i) r[i] = 0;
  52135. r[ds] = c;
  52136. r.t = this.t+ds+1;
  52137. r.s = this.s;
  52138. r.clamp();
  52139. }
  52140. // (protected) r = this >> n
  52141. function bnpRShiftTo(n,r) {
  52142. r.s = this.s;
  52143. var ds = Math.floor(n/this.DB);
  52144. if(ds >= this.t) { r.t = 0; return; }
  52145. var bs = n%this.DB;
  52146. var cbs = this.DB-bs;
  52147. var bm = (1<<bs)-1;
  52148. r[0] = this[ds]>>bs;
  52149. for(var i = ds+1; i < this.t; ++i) {
  52150. r[i-ds-1] |= (this[i]&bm)<<cbs;
  52151. r[i-ds] = this[i]>>bs;
  52152. }
  52153. if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
  52154. r.t = this.t-ds;
  52155. r.clamp();
  52156. }
  52157. // (protected) r = this - a
  52158. function bnpSubTo(a,r) {
  52159. var i = 0, c = 0, m = Math.min(a.t,this.t);
  52160. while(i < m) {
  52161. c += this[i]-a[i];
  52162. r[i++] = c&this.DM;
  52163. c >>= this.DB;
  52164. }
  52165. if(a.t < this.t) {
  52166. c -= a.s;
  52167. while(i < this.t) {
  52168. c += this[i];
  52169. r[i++] = c&this.DM;
  52170. c >>= this.DB;
  52171. }
  52172. c += this.s;
  52173. }
  52174. else {
  52175. c += this.s;
  52176. while(i < a.t) {
  52177. c -= a[i];
  52178. r[i++] = c&this.DM;
  52179. c >>= this.DB;
  52180. }
  52181. c -= a.s;
  52182. }
  52183. r.s = (c<0)?-1:0;
  52184. if(c < -1) r[i++] = this.DV+c;
  52185. else if(c > 0) r[i++] = c;
  52186. r.t = i;
  52187. r.clamp();
  52188. }
  52189. // (protected) r = this * a, r != this,a (HAC 14.12)
  52190. // "this" should be the larger one if appropriate.
  52191. function bnpMultiplyTo(a,r) {
  52192. var x = this.abs(), y = a.abs();
  52193. var i = x.t;
  52194. r.t = i+y.t;
  52195. while(--i >= 0) r[i] = 0;
  52196. for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
  52197. r.s = 0;
  52198. r.clamp();
  52199. if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
  52200. }
  52201. // (protected) r = this^2, r != this (HAC 14.16)
  52202. function bnpSquareTo(r) {
  52203. var x = this.abs();
  52204. var i = r.t = 2*x.t;
  52205. while(--i >= 0) r[i] = 0;
  52206. for(i = 0; i < x.t-1; ++i) {
  52207. var c = x.am(i,x[i],r,2*i,0,1);
  52208. if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
  52209. r[i+x.t] -= x.DV;
  52210. r[i+x.t+1] = 1;
  52211. }
  52212. }
  52213. if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
  52214. r.s = 0;
  52215. r.clamp();
  52216. }
  52217. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  52218. // r != q, this != m. q or r may be null.
  52219. function bnpDivRemTo(m,q,r) {
  52220. var pm = m.abs();
  52221. if(pm.t <= 0) return;
  52222. var pt = this.abs();
  52223. if(pt.t < pm.t) {
  52224. if(q != null) q.fromInt(0);
  52225. if(r != null) this.copyTo(r);
  52226. return;
  52227. }
  52228. if(r == null) r = nbi();
  52229. var y = nbi(), ts = this.s, ms = m.s;
  52230. var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus
  52231. if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
  52232. else { pm.copyTo(y); pt.copyTo(r); }
  52233. var ys = y.t;
  52234. var y0 = y[ys-1];
  52235. if(y0 == 0) return;
  52236. var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
  52237. var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
  52238. var i = r.t, j = i-ys, t = (q==null)?nbi():q;
  52239. y.dlShiftTo(j,t);
  52240. if(r.compareTo(t) >= 0) {
  52241. r[r.t++] = 1;
  52242. r.subTo(t,r);
  52243. }
  52244. BigInteger.ONE.dlShiftTo(ys,t);
  52245. t.subTo(y,y); // "negative" y so we can replace sub with am later
  52246. while(y.t < ys) y[y.t++] = 0;
  52247. while(--j >= 0) {
  52248. // Estimate quotient digit
  52249. var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
  52250. if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
  52251. y.dlShiftTo(j,t);
  52252. r.subTo(t,r);
  52253. while(r[i] < --qd) r.subTo(t,r);
  52254. }
  52255. }
  52256. if(q != null) {
  52257. r.drShiftTo(ys,q);
  52258. if(ts != ms) BigInteger.ZERO.subTo(q,q);
  52259. }
  52260. r.t = ys;
  52261. r.clamp();
  52262. if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
  52263. if(ts < 0) BigInteger.ZERO.subTo(r,r);
  52264. }
  52265. // (public) this mod a
  52266. function bnMod(a) {
  52267. var r = nbi();
  52268. this.abs().divRemTo(a,null,r);
  52269. if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
  52270. return r;
  52271. }
  52272. // Modular reduction using "classic" algorithm
  52273. function Classic(m) { this.m = m; }
  52274. function cConvert(x) {
  52275. if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  52276. else return x;
  52277. }
  52278. function cRevert(x) { return x; }
  52279. function cReduce(x) { x.divRemTo(this.m,null,x); }
  52280. function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  52281. function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  52282. Classic.prototype.convert = cConvert;
  52283. Classic.prototype.revert = cRevert;
  52284. Classic.prototype.reduce = cReduce;
  52285. Classic.prototype.mulTo = cMulTo;
  52286. Classic.prototype.sqrTo = cSqrTo;
  52287. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  52288. // justification:
  52289. // xy == 1 (mod m)
  52290. // xy = 1+km
  52291. // xy(2-xy) = (1+km)(1-km)
  52292. // x[y(2-xy)] = 1-k^2m^2
  52293. // x[y(2-xy)] == 1 (mod m^2)
  52294. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  52295. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  52296. // JS multiply "overflows" differently from C/C++, so care is needed here.
  52297. function bnpInvDigit() {
  52298. if(this.t < 1) return 0;
  52299. var x = this[0];
  52300. if((x&1) == 0) return 0;
  52301. var y = x&3; // y == 1/x mod 2^2
  52302. y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
  52303. y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
  52304. y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
  52305. // last step - calculate inverse mod DV directly;
  52306. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  52307. y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
  52308. // we really want the negative inverse, and -DV < y < DV
  52309. return (y>0)?this.DV-y:-y;
  52310. }
  52311. // Montgomery reduction
  52312. function Montgomery(m) {
  52313. this.m = m;
  52314. this.mp = m.invDigit();
  52315. this.mpl = this.mp&0x7fff;
  52316. this.mph = this.mp>>15;
  52317. this.um = (1<<(m.DB-15))-1;
  52318. this.mt2 = 2*m.t;
  52319. }
  52320. // xR mod m
  52321. function montConvert(x) {
  52322. var r = nbi();
  52323. x.abs().dlShiftTo(this.m.t,r);
  52324. r.divRemTo(this.m,null,r);
  52325. if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
  52326. return r;
  52327. }
  52328. // x/R mod m
  52329. function montRevert(x) {
  52330. var r = nbi();
  52331. x.copyTo(r);
  52332. this.reduce(r);
  52333. return r;
  52334. }
  52335. // x = x/R mod m (HAC 14.32)
  52336. function montReduce(x) {
  52337. while(x.t <= this.mt2) // pad x so am has enough room later
  52338. x[x.t++] = 0;
  52339. for(var i = 0; i < this.m.t; ++i) {
  52340. // faster way of calculating u0 = x[i]*mp mod DV
  52341. var j = x[i]&0x7fff;
  52342. var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
  52343. // use am to combine the multiply-shift-add into one call
  52344. j = i+this.m.t;
  52345. x[j] += this.m.am(0,u0,x,i,0,this.m.t);
  52346. // propagate carry
  52347. while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
  52348. }
  52349. x.clamp();
  52350. x.drShiftTo(this.m.t,x);
  52351. if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  52352. }
  52353. // r = "x^2/R mod m"; x != r
  52354. function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  52355. // r = "xy/R mod m"; x,y != r
  52356. function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  52357. Montgomery.prototype.convert = montConvert;
  52358. Montgomery.prototype.revert = montRevert;
  52359. Montgomery.prototype.reduce = montReduce;
  52360. Montgomery.prototype.mulTo = montMulTo;
  52361. Montgomery.prototype.sqrTo = montSqrTo;
  52362. // (protected) true iff this is even
  52363. function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
  52364. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  52365. function bnpExp(e,z) {
  52366. if(e > 0xffffffff || e < 1) return BigInteger.ONE;
  52367. var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
  52368. g.copyTo(r);
  52369. while(--i >= 0) {
  52370. z.sqrTo(r,r2);
  52371. if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
  52372. else { var t = r; r = r2; r2 = t; }
  52373. }
  52374. return z.revert(r);
  52375. }
  52376. // (public) this^e % m, 0 <= e < 2^32
  52377. function bnModPowInt(e,m) {
  52378. var z;
  52379. if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
  52380. return this.exp(e,z);
  52381. }
  52382. // protected
  52383. BigInteger.prototype.copyTo = bnpCopyTo;
  52384. BigInteger.prototype.fromInt = bnpFromInt;
  52385. BigInteger.prototype.fromString = bnpFromString;
  52386. BigInteger.prototype.clamp = bnpClamp;
  52387. BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  52388. BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  52389. BigInteger.prototype.lShiftTo = bnpLShiftTo;
  52390. BigInteger.prototype.rShiftTo = bnpRShiftTo;
  52391. BigInteger.prototype.subTo = bnpSubTo;
  52392. BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  52393. BigInteger.prototype.squareTo = bnpSquareTo;
  52394. BigInteger.prototype.divRemTo = bnpDivRemTo;
  52395. BigInteger.prototype.invDigit = bnpInvDigit;
  52396. BigInteger.prototype.isEven = bnpIsEven;
  52397. BigInteger.prototype.exp = bnpExp;
  52398. // public
  52399. BigInteger.prototype.toString = bnToString;
  52400. BigInteger.prototype.negate = bnNegate;
  52401. BigInteger.prototype.abs = bnAbs;
  52402. BigInteger.prototype.compareTo = bnCompareTo;
  52403. BigInteger.prototype.bitLength = bnBitLength;
  52404. BigInteger.prototype.mod = bnMod;
  52405. BigInteger.prototype.modPowInt = bnModPowInt;
  52406. // "constants"
  52407. BigInteger.ZERO = nbv(0);
  52408. BigInteger.ONE = nbv(1);
  52409. // Copyright (c) 2005-2009 Tom Wu
  52410. // All Rights Reserved.
  52411. // See "LICENSE" for details.
  52412. // Extended JavaScript BN functions, required for RSA private ops.
  52413. // Version 1.1: new BigInteger("0", 10) returns "proper" zero
  52414. // Version 1.2: square() API, isProbablePrime fix
  52415. // (public)
  52416. function bnClone() { var r = nbi(); this.copyTo(r); return r; }
  52417. // (public) return value as integer
  52418. function bnIntValue() {
  52419. if(this.s < 0) {
  52420. if(this.t == 1) return this[0]-this.DV;
  52421. else if(this.t == 0) return -1;
  52422. }
  52423. else if(this.t == 1) return this[0];
  52424. else if(this.t == 0) return 0;
  52425. // assumes 16 < DB < 32
  52426. return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];
  52427. }
  52428. // (public) return value as byte
  52429. function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
  52430. // (public) return value as short (assumes DB>=16)
  52431. function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
  52432. // (protected) return x s.t. r^x < DV
  52433. function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
  52434. // (public) 0 if this == 0, 1 if this > 0
  52435. function bnSigNum() {
  52436. if(this.s < 0) return -1;
  52437. else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
  52438. else return 1;
  52439. }
  52440. // (protected) convert to radix string
  52441. function bnpToRadix(b) {
  52442. if(b == null) b = 10;
  52443. if(this.signum() == 0 || b < 2 || b > 36) return "0";
  52444. var cs = this.chunkSize(b);
  52445. var a = Math.pow(b,cs);
  52446. var d = nbv(a), y = nbi(), z = nbi(), r = "";
  52447. this.divRemTo(d,y,z);
  52448. while(y.signum() > 0) {
  52449. r = (a+z.intValue()).toString(b).substr(1) + r;
  52450. y.divRemTo(d,y,z);
  52451. }
  52452. return z.intValue().toString(b) + r;
  52453. }
  52454. // (protected) convert from radix string
  52455. function bnpFromRadix(s,b) {
  52456. this.fromInt(0);
  52457. if(b == null) b = 10;
  52458. var cs = this.chunkSize(b);
  52459. var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
  52460. for(var i = 0; i < s.length; ++i) {
  52461. var x = intAt(s,i);
  52462. if(x < 0) {
  52463. if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
  52464. continue;
  52465. }
  52466. w = b*w+x;
  52467. if(++j >= cs) {
  52468. this.dMultiply(d);
  52469. this.dAddOffset(w,0);
  52470. j = 0;
  52471. w = 0;
  52472. }
  52473. }
  52474. if(j > 0) {
  52475. this.dMultiply(Math.pow(b,j));
  52476. this.dAddOffset(w,0);
  52477. }
  52478. if(mi) BigInteger.ZERO.subTo(this,this);
  52479. }
  52480. // (protected) alternate constructor
  52481. function bnpFromNumber(a,b,c) {
  52482. if("number" == typeof b) {
  52483. // new BigInteger(int,int,RNG)
  52484. if(a < 2) this.fromInt(1);
  52485. else {
  52486. this.fromNumber(a,c);
  52487. if(!this.testBit(a-1)) // force MSB set
  52488. this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
  52489. if(this.isEven()) this.dAddOffset(1,0); // force odd
  52490. while(!this.isProbablePrime(b)) {
  52491. this.dAddOffset(2,0);
  52492. if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
  52493. }
  52494. }
  52495. }
  52496. else {
  52497. // new BigInteger(int,RNG)
  52498. var x = new Array(), t = a&7;
  52499. x.length = (a>>3)+1;
  52500. b.nextBytes(x);
  52501. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  52502. this.fromString(x,256);
  52503. }
  52504. }
  52505. // (public) convert to bigendian byte array
  52506. function bnToByteArray() {
  52507. var i = this.t, r = new Array();
  52508. r[0] = this.s;
  52509. var p = this.DB-(i*this.DB)%8, d, k = 0;
  52510. if(i-- > 0) {
  52511. if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
  52512. r[k++] = d|(this.s<<(this.DB-p));
  52513. while(i >= 0) {
  52514. if(p < 8) {
  52515. d = (this[i]&((1<<p)-1))<<(8-p);
  52516. d |= this[--i]>>(p+=this.DB-8);
  52517. }
  52518. else {
  52519. d = (this[i]>>(p-=8))&0xff;
  52520. if(p <= 0) { p += this.DB; --i; }
  52521. }
  52522. if((d&0x80) != 0) d |= -256;
  52523. if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
  52524. if(k > 0 || d != this.s) r[k++] = d;
  52525. }
  52526. }
  52527. return r;
  52528. }
  52529. function bnEquals(a) { return(this.compareTo(a)==0); }
  52530. function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
  52531. function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
  52532. // (protected) r = this op a (bitwise)
  52533. function bnpBitwiseTo(a,op,r) {
  52534. var i, f, m = Math.min(a.t,this.t);
  52535. for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
  52536. if(a.t < this.t) {
  52537. f = a.s&this.DM;
  52538. for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
  52539. r.t = this.t;
  52540. }
  52541. else {
  52542. f = this.s&this.DM;
  52543. for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
  52544. r.t = a.t;
  52545. }
  52546. r.s = op(this.s,a.s);
  52547. r.clamp();
  52548. }
  52549. // (public) this & a
  52550. function op_and(x,y) { return x&y; }
  52551. function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
  52552. // (public) this | a
  52553. function op_or(x,y) { return x|y; }
  52554. function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
  52555. // (public) this ^ a
  52556. function op_xor(x,y) { return x^y; }
  52557. function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
  52558. // (public) this & ~a
  52559. function op_andnot(x,y) { return x&~y; }
  52560. function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
  52561. // (public) ~this
  52562. function bnNot() {
  52563. var r = nbi();
  52564. for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
  52565. r.t = this.t;
  52566. r.s = ~this.s;
  52567. return r;
  52568. }
  52569. // (public) this << n
  52570. function bnShiftLeft(n) {
  52571. var r = nbi();
  52572. if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
  52573. return r;
  52574. }
  52575. // (public) this >> n
  52576. function bnShiftRight(n) {
  52577. var r = nbi();
  52578. if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
  52579. return r;
  52580. }
  52581. // return index of lowest 1-bit in x, x < 2^31
  52582. function lbit(x) {
  52583. if(x == 0) return -1;
  52584. var r = 0;
  52585. if((x&0xffff) == 0) { x >>= 16; r += 16; }
  52586. if((x&0xff) == 0) { x >>= 8; r += 8; }
  52587. if((x&0xf) == 0) { x >>= 4; r += 4; }
  52588. if((x&3) == 0) { x >>= 2; r += 2; }
  52589. if((x&1) == 0) ++r;
  52590. return r;
  52591. }
  52592. // (public) returns index of lowest 1-bit (or -1 if none)
  52593. function bnGetLowestSetBit() {
  52594. for(var i = 0; i < this.t; ++i)
  52595. if(this[i] != 0) return i*this.DB+lbit(this[i]);
  52596. if(this.s < 0) return this.t*this.DB;
  52597. return -1;
  52598. }
  52599. // return number of 1 bits in x
  52600. function cbit(x) {
  52601. var r = 0;
  52602. while(x != 0) { x &= x-1; ++r; }
  52603. return r;
  52604. }
  52605. // (public) return number of set bits
  52606. function bnBitCount() {
  52607. var r = 0, x = this.s&this.DM;
  52608. for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
  52609. return r;
  52610. }
  52611. // (public) true iff nth bit is set
  52612. function bnTestBit(n) {
  52613. var j = Math.floor(n/this.DB);
  52614. if(j >= this.t) return(this.s!=0);
  52615. return((this[j]&(1<<(n%this.DB)))!=0);
  52616. }
  52617. // (protected) this op (1<<n)
  52618. function bnpChangeBit(n,op) {
  52619. var r = BigInteger.ONE.shiftLeft(n);
  52620. this.bitwiseTo(r,op,r);
  52621. return r;
  52622. }
  52623. // (public) this | (1<<n)
  52624. function bnSetBit(n) { return this.changeBit(n,op_or); }
  52625. // (public) this & ~(1<<n)
  52626. function bnClearBit(n) { return this.changeBit(n,op_andnot); }
  52627. // (public) this ^ (1<<n)
  52628. function bnFlipBit(n) { return this.changeBit(n,op_xor); }
  52629. // (protected) r = this + a
  52630. function bnpAddTo(a,r) {
  52631. var i = 0, c = 0, m = Math.min(a.t,this.t);
  52632. while(i < m) {
  52633. c += this[i]+a[i];
  52634. r[i++] = c&this.DM;
  52635. c >>= this.DB;
  52636. }
  52637. if(a.t < this.t) {
  52638. c += a.s;
  52639. while(i < this.t) {
  52640. c += this[i];
  52641. r[i++] = c&this.DM;
  52642. c >>= this.DB;
  52643. }
  52644. c += this.s;
  52645. }
  52646. else {
  52647. c += this.s;
  52648. while(i < a.t) {
  52649. c += a[i];
  52650. r[i++] = c&this.DM;
  52651. c >>= this.DB;
  52652. }
  52653. c += a.s;
  52654. }
  52655. r.s = (c<0)?-1:0;
  52656. if(c > 0) r[i++] = c;
  52657. else if(c < -1) r[i++] = this.DV+c;
  52658. r.t = i;
  52659. r.clamp();
  52660. }
  52661. // (public) this + a
  52662. function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
  52663. // (public) this - a
  52664. function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
  52665. // (public) this * a
  52666. function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
  52667. // (public) this^2
  52668. function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
  52669. // (public) this / a
  52670. function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
  52671. // (public) this % a
  52672. function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
  52673. // (public) [this/a,this%a]
  52674. function bnDivideAndRemainder(a) {
  52675. var q = nbi(), r = nbi();
  52676. this.divRemTo(a,q,r);
  52677. return new Array(q,r);
  52678. }
  52679. // (protected) this *= n, this >= 0, 1 < n < DV
  52680. function bnpDMultiply(n) {
  52681. this[this.t] = this.am(0,n-1,this,0,0,this.t);
  52682. ++this.t;
  52683. this.clamp();
  52684. }
  52685. // (protected) this += n << w words, this >= 0
  52686. function bnpDAddOffset(n,w) {
  52687. if(n == 0) return;
  52688. while(this.t <= w) this[this.t++] = 0;
  52689. this[w] += n;
  52690. while(this[w] >= this.DV) {
  52691. this[w] -= this.DV;
  52692. if(++w >= this.t) this[this.t++] = 0;
  52693. ++this[w];
  52694. }
  52695. }
  52696. // A "null" reducer
  52697. function NullExp() {}
  52698. function nNop(x) { return x; }
  52699. function nMulTo(x,y,r) { x.multiplyTo(y,r); }
  52700. function nSqrTo(x,r) { x.squareTo(r); }
  52701. NullExp.prototype.convert = nNop;
  52702. NullExp.prototype.revert = nNop;
  52703. NullExp.prototype.mulTo = nMulTo;
  52704. NullExp.prototype.sqrTo = nSqrTo;
  52705. // (public) this^e
  52706. function bnPow(e) { return this.exp(e,new NullExp()); }
  52707. // (protected) r = lower n words of "this * a", a.t <= n
  52708. // "this" should be the larger one if appropriate.
  52709. function bnpMultiplyLowerTo(a,n,r) {
  52710. var i = Math.min(this.t+a.t,n);
  52711. r.s = 0; // assumes a,this >= 0
  52712. r.t = i;
  52713. while(i > 0) r[--i] = 0;
  52714. var j;
  52715. for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
  52716. for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
  52717. r.clamp();
  52718. }
  52719. // (protected) r = "this * a" without lower n words, n > 0
  52720. // "this" should be the larger one if appropriate.
  52721. function bnpMultiplyUpperTo(a,n,r) {
  52722. --n;
  52723. var i = r.t = this.t+a.t-n;
  52724. r.s = 0; // assumes a,this >= 0
  52725. while(--i >= 0) r[i] = 0;
  52726. for(i = Math.max(n-this.t,0); i < a.t; ++i)
  52727. r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
  52728. r.clamp();
  52729. r.drShiftTo(1,r);
  52730. }
  52731. // Barrett modular reduction
  52732. function Barrett(m) {
  52733. // setup Barrett
  52734. this.r2 = nbi();
  52735. this.q3 = nbi();
  52736. BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
  52737. this.mu = this.r2.divide(m);
  52738. this.m = m;
  52739. }
  52740. function barrettConvert(x) {
  52741. if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
  52742. else if(x.compareTo(this.m) < 0) return x;
  52743. else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
  52744. }
  52745. function barrettRevert(x) { return x; }
  52746. // x = x mod m (HAC 14.42)
  52747. function barrettReduce(x) {
  52748. x.drShiftTo(this.m.t-1,this.r2);
  52749. if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
  52750. this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
  52751. this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
  52752. while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
  52753. x.subTo(this.r2,x);
  52754. while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  52755. }
  52756. // r = x^2 mod m; x != r
  52757. function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  52758. // r = x*y mod m; x,y != r
  52759. function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  52760. Barrett.prototype.convert = barrettConvert;
  52761. Barrett.prototype.revert = barrettRevert;
  52762. Barrett.prototype.reduce = barrettReduce;
  52763. Barrett.prototype.mulTo = barrettMulTo;
  52764. Barrett.prototype.sqrTo = barrettSqrTo;
  52765. // (public) this^e % m (HAC 14.85)
  52766. function bnModPow(e,m) {
  52767. var i = e.bitLength(), k, r = nbv(1), z;
  52768. if(i <= 0) return r;
  52769. else if(i < 18) k = 1;
  52770. else if(i < 48) k = 3;
  52771. else if(i < 144) k = 4;
  52772. else if(i < 768) k = 5;
  52773. else k = 6;
  52774. if(i < 8)
  52775. z = new Classic(m);
  52776. else if(m.isEven())
  52777. z = new Barrett(m);
  52778. else
  52779. z = new Montgomery(m);
  52780. // precomputation
  52781. var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
  52782. g[1] = z.convert(this);
  52783. if(k > 1) {
  52784. var g2 = nbi();
  52785. z.sqrTo(g[1],g2);
  52786. while(n <= km) {
  52787. g[n] = nbi();
  52788. z.mulTo(g2,g[n-2],g[n]);
  52789. n += 2;
  52790. }
  52791. }
  52792. var j = e.t-1, w, is1 = true, r2 = nbi(), t;
  52793. i = nbits(e[j])-1;
  52794. while(j >= 0) {
  52795. if(i >= k1) w = (e[j]>>(i-k1))&km;
  52796. else {
  52797. w = (e[j]&((1<<(i+1))-1))<<(k1-i);
  52798. if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
  52799. }
  52800. n = k;
  52801. while((w&1) == 0) { w >>= 1; --n; }
  52802. if((i -= n) < 0) { i += this.DB; --j; }
  52803. if(is1) { // ret == 1, don't bother squaring or multiplying it
  52804. g[w].copyTo(r);
  52805. is1 = false;
  52806. }
  52807. else {
  52808. while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
  52809. if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
  52810. z.mulTo(r2,g[w],r);
  52811. }
  52812. while(j >= 0 && (e[j]&(1<<i)) == 0) {
  52813. z.sqrTo(r,r2); t = r; r = r2; r2 = t;
  52814. if(--i < 0) { i = this.DB-1; --j; }
  52815. }
  52816. }
  52817. return z.revert(r);
  52818. }
  52819. // (public) gcd(this,a) (HAC 14.54)
  52820. function bnGCD(a) {
  52821. var x = (this.s<0)?this.negate():this.clone();
  52822. var y = (a.s<0)?a.negate():a.clone();
  52823. if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
  52824. var i = x.getLowestSetBit(), g = y.getLowestSetBit();
  52825. if(g < 0) return x;
  52826. if(i < g) g = i;
  52827. if(g > 0) {
  52828. x.rShiftTo(g,x);
  52829. y.rShiftTo(g,y);
  52830. }
  52831. while(x.signum() > 0) {
  52832. if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
  52833. if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
  52834. if(x.compareTo(y) >= 0) {
  52835. x.subTo(y,x);
  52836. x.rShiftTo(1,x);
  52837. }
  52838. else {
  52839. y.subTo(x,y);
  52840. y.rShiftTo(1,y);
  52841. }
  52842. }
  52843. if(g > 0) y.lShiftTo(g,y);
  52844. return y;
  52845. }
  52846. // (protected) this % n, n < 2^26
  52847. function bnpModInt(n) {
  52848. if(n <= 0) return 0;
  52849. var d = this.DV%n, r = (this.s<0)?n-1:0;
  52850. if(this.t > 0)
  52851. if(d == 0) r = this[0]%n;
  52852. else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
  52853. return r;
  52854. }
  52855. // (public) 1/this % m (HAC 14.61)
  52856. function bnModInverse(m) {
  52857. var ac = m.isEven();
  52858. if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
  52859. var u = m.clone(), v = this.clone();
  52860. var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
  52861. while(u.signum() != 0) {
  52862. while(u.isEven()) {
  52863. u.rShiftTo(1,u);
  52864. if(ac) {
  52865. if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
  52866. a.rShiftTo(1,a);
  52867. }
  52868. else if(!b.isEven()) b.subTo(m,b);
  52869. b.rShiftTo(1,b);
  52870. }
  52871. while(v.isEven()) {
  52872. v.rShiftTo(1,v);
  52873. if(ac) {
  52874. if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
  52875. c.rShiftTo(1,c);
  52876. }
  52877. else if(!d.isEven()) d.subTo(m,d);
  52878. d.rShiftTo(1,d);
  52879. }
  52880. if(u.compareTo(v) >= 0) {
  52881. u.subTo(v,u);
  52882. if(ac) a.subTo(c,a);
  52883. b.subTo(d,b);
  52884. }
  52885. else {
  52886. v.subTo(u,v);
  52887. if(ac) c.subTo(a,c);
  52888. d.subTo(b,d);
  52889. }
  52890. }
  52891. if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
  52892. if(d.compareTo(m) >= 0) return d.subtract(m);
  52893. if(d.signum() < 0) d.addTo(m,d); else return d;
  52894. if(d.signum() < 0) return d.add(m); else return d;
  52895. }
  52896. var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
  52897. var lplim = (1<<26)/lowprimes[lowprimes.length-1];
  52898. // (public) test primality with certainty >= 1-.5^t
  52899. function bnIsProbablePrime(t) {
  52900. var i, x = this.abs();
  52901. if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
  52902. for(i = 0; i < lowprimes.length; ++i)
  52903. if(x[0] == lowprimes[i]) return true;
  52904. return false;
  52905. }
  52906. if(x.isEven()) return false;
  52907. i = 1;
  52908. while(i < lowprimes.length) {
  52909. var m = lowprimes[i], j = i+1;
  52910. while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
  52911. m = x.modInt(m);
  52912. while(i < j) if(m%lowprimes[i++] == 0) return false;
  52913. }
  52914. return x.millerRabin(t);
  52915. }
  52916. // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
  52917. function bnpMillerRabin(t) {
  52918. var n1 = this.subtract(BigInteger.ONE);
  52919. var k = n1.getLowestSetBit();
  52920. if(k <= 0) return false;
  52921. var r = n1.shiftRight(k);
  52922. t = (t+1)>>1;
  52923. if(t > lowprimes.length) t = lowprimes.length;
  52924. var a = nbi();
  52925. for(var i = 0; i < t; ++i) {
  52926. //Pick bases at random, instead of starting at 2
  52927. a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
  52928. var y = a.modPow(r,this);
  52929. if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  52930. var j = 1;
  52931. while(j++ < k && y.compareTo(n1) != 0) {
  52932. y = y.modPowInt(2,this);
  52933. if(y.compareTo(BigInteger.ONE) == 0) return false;
  52934. }
  52935. if(y.compareTo(n1) != 0) return false;
  52936. }
  52937. }
  52938. return true;
  52939. }
  52940. // protected
  52941. BigInteger.prototype.chunkSize = bnpChunkSize;
  52942. BigInteger.prototype.toRadix = bnpToRadix;
  52943. BigInteger.prototype.fromRadix = bnpFromRadix;
  52944. BigInteger.prototype.fromNumber = bnpFromNumber;
  52945. BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  52946. BigInteger.prototype.changeBit = bnpChangeBit;
  52947. BigInteger.prototype.addTo = bnpAddTo;
  52948. BigInteger.prototype.dMultiply = bnpDMultiply;
  52949. BigInteger.prototype.dAddOffset = bnpDAddOffset;
  52950. BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  52951. BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  52952. BigInteger.prototype.modInt = bnpModInt;
  52953. BigInteger.prototype.millerRabin = bnpMillerRabin;
  52954. // public
  52955. BigInteger.prototype.clone = bnClone;
  52956. BigInteger.prototype.intValue = bnIntValue;
  52957. BigInteger.prototype.byteValue = bnByteValue;
  52958. BigInteger.prototype.shortValue = bnShortValue;
  52959. BigInteger.prototype.signum = bnSigNum;
  52960. BigInteger.prototype.toByteArray = bnToByteArray;
  52961. BigInteger.prototype.equals = bnEquals;
  52962. BigInteger.prototype.min = bnMin;
  52963. BigInteger.prototype.max = bnMax;
  52964. BigInteger.prototype.and = bnAnd;
  52965. BigInteger.prototype.or = bnOr;
  52966. BigInteger.prototype.xor = bnXor;
  52967. BigInteger.prototype.andNot = bnAndNot;
  52968. BigInteger.prototype.not = bnNot;
  52969. BigInteger.prototype.shiftLeft = bnShiftLeft;
  52970. BigInteger.prototype.shiftRight = bnShiftRight;
  52971. BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
  52972. BigInteger.prototype.bitCount = bnBitCount;
  52973. BigInteger.prototype.testBit = bnTestBit;
  52974. BigInteger.prototype.setBit = bnSetBit;
  52975. BigInteger.prototype.clearBit = bnClearBit;
  52976. BigInteger.prototype.flipBit = bnFlipBit;
  52977. BigInteger.prototype.add = bnAdd;
  52978. BigInteger.prototype.subtract = bnSubtract;
  52979. BigInteger.prototype.multiply = bnMultiply;
  52980. BigInteger.prototype.divide = bnDivide;
  52981. BigInteger.prototype.remainder = bnRemainder;
  52982. BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
  52983. BigInteger.prototype.modPow = bnModPow;
  52984. BigInteger.prototype.modInverse = bnModInverse;
  52985. BigInteger.prototype.pow = bnPow;
  52986. BigInteger.prototype.gcd = bnGCD;
  52987. BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  52988. // JSBN-specific extension
  52989. BigInteger.prototype.square = bnSquare;
  52990. // Expose the Barrett function
  52991. BigInteger.prototype.Barrett = Barrett
  52992. // BigInteger interfaces not implemented in jsbn:
  52993. // BigInteger(int signum, byte[] magnitude)
  52994. // double doubleValue()
  52995. // float floatValue()
  52996. // int hashCode()
  52997. // long longValue()
  52998. // static BigInteger valueOf(long val)
  52999. // Random number generator - requires a PRNG backend, e.g. prng4.js
  53000. // For best results, put code like
  53001. // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
  53002. // in your main HTML document.
  53003. var rng_state;
  53004. var rng_pool;
  53005. var rng_pptr;
  53006. // Mix in a 32-bit integer into the pool
  53007. function rng_seed_int(x) {
  53008. rng_pool[rng_pptr++] ^= x & 255;
  53009. rng_pool[rng_pptr++] ^= (x >> 8) & 255;
  53010. rng_pool[rng_pptr++] ^= (x >> 16) & 255;
  53011. rng_pool[rng_pptr++] ^= (x >> 24) & 255;
  53012. if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
  53013. }
  53014. // Mix in the current time (w/milliseconds) into the pool
  53015. function rng_seed_time() {
  53016. rng_seed_int(new Date().getTime());
  53017. }
  53018. // Initialize the pool with junk if needed.
  53019. if(rng_pool == null) {
  53020. rng_pool = new Array();
  53021. rng_pptr = 0;
  53022. var t;
  53023. if(typeof window !== "undefined" && window.crypto) {
  53024. if (window.crypto.getRandomValues) {
  53025. // Use webcrypto if available
  53026. var ua = new Uint8Array(32);
  53027. window.crypto.getRandomValues(ua);
  53028. for(t = 0; t < 32; ++t)
  53029. rng_pool[rng_pptr++] = ua[t];
  53030. }
  53031. else if(navigator.appName == "Netscape" && navigator.appVersion < "5") {
  53032. // Extract entropy (256 bits) from NS4 RNG if available
  53033. var z = window.crypto.random(32);
  53034. for(t = 0; t < z.length; ++t)
  53035. rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
  53036. }
  53037. }
  53038. while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
  53039. t = Math.floor(65536 * Math.random());
  53040. rng_pool[rng_pptr++] = t >>> 8;
  53041. rng_pool[rng_pptr++] = t & 255;
  53042. }
  53043. rng_pptr = 0;
  53044. rng_seed_time();
  53045. //rng_seed_int(window.screenX);
  53046. //rng_seed_int(window.screenY);
  53047. }
  53048. function rng_get_byte() {
  53049. if(rng_state == null) {
  53050. rng_seed_time();
  53051. rng_state = prng_newstate();
  53052. rng_state.init(rng_pool);
  53053. for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
  53054. rng_pool[rng_pptr] = 0;
  53055. rng_pptr = 0;
  53056. //rng_pool = null;
  53057. }
  53058. // TODO: allow reseeding after first request
  53059. return rng_state.next();
  53060. }
  53061. function rng_get_bytes(ba) {
  53062. var i;
  53063. for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
  53064. }
  53065. function SecureRandom() {}
  53066. SecureRandom.prototype.nextBytes = rng_get_bytes;
  53067. // prng4.js - uses Arcfour as a PRNG
  53068. function Arcfour() {
  53069. this.i = 0;
  53070. this.j = 0;
  53071. this.S = new Array();
  53072. }
  53073. // Initialize arcfour context from key, an array of ints, each from [0..255]
  53074. function ARC4init(key) {
  53075. var i, j, t;
  53076. for(i = 0; i < 256; ++i)
  53077. this.S[i] = i;
  53078. j = 0;
  53079. for(i = 0; i < 256; ++i) {
  53080. j = (j + this.S[i] + key[i % key.length]) & 255;
  53081. t = this.S[i];
  53082. this.S[i] = this.S[j];
  53083. this.S[j] = t;
  53084. }
  53085. this.i = 0;
  53086. this.j = 0;
  53087. }
  53088. function ARC4next() {
  53089. var t;
  53090. this.i = (this.i + 1) & 255;
  53091. this.j = (this.j + this.S[this.i]) & 255;
  53092. t = this.S[this.i];
  53093. this.S[this.i] = this.S[this.j];
  53094. this.S[this.j] = t;
  53095. return this.S[(t + this.S[this.i]) & 255];
  53096. }
  53097. Arcfour.prototype.init = ARC4init;
  53098. Arcfour.prototype.next = ARC4next;
  53099. // Plug in your RNG constructor here
  53100. function prng_newstate() {
  53101. return new Arcfour();
  53102. }
  53103. // Pool size must be a multiple of 4 and greater than 32.
  53104. // An array of bytes the size of the pool will be passed to init()
  53105. var rng_psize = 256;
  53106. BigInteger.SecureRandom = SecureRandom;
  53107. BigInteger.BigInteger = BigInteger;
  53108. if (typeof exports !== 'undefined') {
  53109. exports = module.exports = BigInteger;
  53110. } else {
  53111. this.BigInteger = BigInteger;
  53112. this.SecureRandom = SecureRandom;
  53113. }
  53114. }).call(this);
  53115. },{}],329:[function(require,module,exports){
  53116. 'use strict';
  53117. var traverse = module.exports = function (schema, opts, cb) {
  53118. // Legacy support for v0.3.1 and earlier.
  53119. if (typeof opts == 'function') {
  53120. cb = opts;
  53121. opts = {};
  53122. }
  53123. cb = opts.cb || cb;
  53124. var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  53125. var post = cb.post || function() {};
  53126. _traverse(opts, pre, post, schema, '', schema);
  53127. };
  53128. traverse.keywords = {
  53129. additionalItems: true,
  53130. items: true,
  53131. contains: true,
  53132. additionalProperties: true,
  53133. propertyNames: true,
  53134. not: true
  53135. };
  53136. traverse.arrayKeywords = {
  53137. items: true,
  53138. allOf: true,
  53139. anyOf: true,
  53140. oneOf: true
  53141. };
  53142. traverse.propsKeywords = {
  53143. definitions: true,
  53144. properties: true,
  53145. patternProperties: true,
  53146. dependencies: true
  53147. };
  53148. traverse.skipKeywords = {
  53149. default: true,
  53150. enum: true,
  53151. const: true,
  53152. required: true,
  53153. maximum: true,
  53154. minimum: true,
  53155. exclusiveMaximum: true,
  53156. exclusiveMinimum: true,
  53157. multipleOf: true,
  53158. maxLength: true,
  53159. minLength: true,
  53160. pattern: true,
  53161. format: true,
  53162. maxItems: true,
  53163. minItems: true,
  53164. uniqueItems: true,
  53165. maxProperties: true,
  53166. minProperties: true
  53167. };
  53168. function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  53169. if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
  53170. pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  53171. for (var key in schema) {
  53172. var sch = schema[key];
  53173. if (Array.isArray(sch)) {
  53174. if (key in traverse.arrayKeywords) {
  53175. for (var i=0; i<sch.length; i++)
  53176. _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
  53177. }
  53178. } else if (key in traverse.propsKeywords) {
  53179. if (sch && typeof sch == 'object') {
  53180. for (var prop in sch)
  53181. _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
  53182. }
  53183. } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
  53184. _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
  53185. }
  53186. }
  53187. post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  53188. }
  53189. }
  53190. function escapeJsonPtr(str) {
  53191. return str.replace(/~/g, '~0').replace(/\//g, '~1');
  53192. }
  53193. },{}],330:[function(require,module,exports){
  53194. /**
  53195. * JSONSchema Validator - Validates JavaScript objects using JSON Schemas
  53196. * (http://www.json.com/json-schema-proposal/)
  53197. *
  53198. * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
  53199. * Licensed under the MIT (MIT-LICENSE.txt) license.
  53200. To use the validator call the validate function with an instance object and an optional schema object.
  53201. If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
  53202. that schema will be used to validate and the schema parameter is not necessary (if both exist,
  53203. both validations will occur).
  53204. The validate method will return an array of validation errors. If there are no errors, then an
  53205. empty list will be returned. A validation error will have two properties:
  53206. "property" which indicates which property had the error
  53207. "message" which indicates what the error was
  53208. */
  53209. (function (root, factory) {
  53210. if (typeof define === 'function' && define.amd) {
  53211. // AMD. Register as an anonymous module.
  53212. define([], function () {
  53213. return factory();
  53214. });
  53215. } else if (typeof module === 'object' && module.exports) {
  53216. // Node. Does not work with strict CommonJS, but
  53217. // only CommonJS-like environments that support module.exports,
  53218. // like Node.
  53219. module.exports = factory();
  53220. } else {
  53221. // Browser globals
  53222. root.jsonSchema = factory();
  53223. }
  53224. }(this, function () {// setup primitive classes to be JSON Schema types
  53225. var exports = validate
  53226. exports.Integer = {type:"integer"};
  53227. var primitiveConstructors = {
  53228. String: String,
  53229. Boolean: Boolean,
  53230. Number: Number,
  53231. Object: Object,
  53232. Array: Array,
  53233. Date: Date
  53234. }
  53235. exports.validate = validate;
  53236. function validate(/*Any*/instance,/*Object*/schema) {
  53237. // Summary:
  53238. // To use the validator call JSONSchema.validate with an instance object and an optional schema object.
  53239. // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
  53240. // that schema will be used to validate and the schema parameter is not necessary (if both exist,
  53241. // both validations will occur).
  53242. // The validate method will return an object with two properties:
  53243. // valid: A boolean indicating if the instance is valid by the schema
  53244. // errors: An array of validation errors. If there are no errors, then an
  53245. // empty list will be returned. A validation error will have two properties:
  53246. // property: which indicates which property had the error
  53247. // message: which indicates what the error was
  53248. //
  53249. return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false});
  53250. };
  53251. exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) {
  53252. // Summary:
  53253. // The checkPropertyChange method will check to see if an value can legally be in property with the given schema
  53254. // This is slightly different than the validate method in that it will fail if the schema is readonly and it will
  53255. // not check for self-validation, it is assumed that the passed in value is already internally valid.
  53256. // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for
  53257. // information.
  53258. //
  53259. return validate(value, schema, {changing: property || "property"});
  53260. };
  53261. var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) {
  53262. if (!options) options = {};
  53263. var _changing = options.changing;
  53264. function getType(schema){
  53265. return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase());
  53266. }
  53267. var errors = [];
  53268. // validate a value against a property definition
  53269. function checkProp(value, schema, path,i){
  53270. var l;
  53271. path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i;
  53272. function addError(message){
  53273. errors.push({property:path,message:message});
  53274. }
  53275. if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){
  53276. if(typeof schema == 'function'){
  53277. if(!(value instanceof schema)){
  53278. addError("is not an instance of the class/constructor " + schema.name);
  53279. }
  53280. }else if(schema){
  53281. addError("Invalid schema/property definition " + schema);
  53282. }
  53283. return null;
  53284. }
  53285. if(_changing && schema.readonly){
  53286. addError("is a readonly field, it can not be changed");
  53287. }
  53288. if(schema['extends']){ // if it extends another schema, it must pass that schema as well
  53289. checkProp(value,schema['extends'],path,i);
  53290. }
  53291. // validate a value against a type definition
  53292. function checkType(type,value){
  53293. if(type){
  53294. if(typeof type == 'string' && type != 'any' &&
  53295. (type == 'null' ? value !== null : typeof value != type) &&
  53296. !(value instanceof Array && type == 'array') &&
  53297. !(value instanceof Date && type == 'date') &&
  53298. !(type == 'integer' && value%1===0)){
  53299. return [{property:path,message:(typeof value) + " value found, but a " + type + " is required"}];
  53300. }
  53301. if(type instanceof Array){
  53302. var unionErrors=[];
  53303. for(var j = 0; j < type.length; j++){ // a union type
  53304. if(!(unionErrors=checkType(type[j],value)).length){
  53305. break;
  53306. }
  53307. }
  53308. if(unionErrors.length){
  53309. return unionErrors;
  53310. }
  53311. }else if(typeof type == 'object'){
  53312. var priorErrors = errors;
  53313. errors = [];
  53314. checkProp(value,type,path);
  53315. var theseErrors = errors;
  53316. errors = priorErrors;
  53317. return theseErrors;
  53318. }
  53319. }
  53320. return [];
  53321. }
  53322. if(value === undefined){
  53323. if(schema.required){
  53324. addError("is missing and it is required");
  53325. }
  53326. }else{
  53327. errors = errors.concat(checkType(getType(schema),value));
  53328. if(schema.disallow && !checkType(schema.disallow,value).length){
  53329. addError(" disallowed value was matched");
  53330. }
  53331. if(value !== null){
  53332. if(value instanceof Array){
  53333. if(schema.items){
  53334. var itemsIsArray = schema.items instanceof Array;
  53335. var propDef = schema.items;
  53336. for (i = 0, l = value.length; i < l; i += 1) {
  53337. if (itemsIsArray)
  53338. propDef = schema.items[i];
  53339. if (options.coerce)
  53340. value[i] = options.coerce(value[i], propDef);
  53341. errors.concat(checkProp(value[i],propDef,path,i));
  53342. }
  53343. }
  53344. if(schema.minItems && value.length < schema.minItems){
  53345. addError("There must be a minimum of " + schema.minItems + " in the array");
  53346. }
  53347. if(schema.maxItems && value.length > schema.maxItems){
  53348. addError("There must be a maximum of " + schema.maxItems + " in the array");
  53349. }
  53350. }else if(schema.properties || schema.additionalProperties){
  53351. errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties));
  53352. }
  53353. if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){
  53354. addError("does not match the regex pattern " + schema.pattern);
  53355. }
  53356. if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){
  53357. addError("may only be " + schema.maxLength + " characters long");
  53358. }
  53359. if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){
  53360. addError("must be at least " + schema.minLength + " characters long");
  53361. }
  53362. if(typeof schema.minimum !== undefined && typeof value == typeof schema.minimum &&
  53363. schema.minimum > value){
  53364. addError("must have a minimum value of " + schema.minimum);
  53365. }
  53366. if(typeof schema.maximum !== undefined && typeof value == typeof schema.maximum &&
  53367. schema.maximum < value){
  53368. addError("must have a maximum value of " + schema.maximum);
  53369. }
  53370. if(schema['enum']){
  53371. var enumer = schema['enum'];
  53372. l = enumer.length;
  53373. var found;
  53374. for(var j = 0; j < l; j++){
  53375. if(enumer[j]===value){
  53376. found=1;
  53377. break;
  53378. }
  53379. }
  53380. if(!found){
  53381. addError("does not have a value in the enumeration " + enumer.join(", "));
  53382. }
  53383. }
  53384. if(typeof schema.maxDecimal == 'number' &&
  53385. (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){
  53386. addError("may only have " + schema.maxDecimal + " digits of decimal places");
  53387. }
  53388. }
  53389. }
  53390. return null;
  53391. }
  53392. // validate an object against a schema
  53393. function checkObj(instance,objTypeDef,path,additionalProp){
  53394. if(typeof objTypeDef =='object'){
  53395. if(typeof instance != 'object' || instance instanceof Array){
  53396. errors.push({property:path,message:"an object is required"});
  53397. }
  53398. for(var i in objTypeDef){
  53399. if(objTypeDef.hasOwnProperty(i)){
  53400. var value = instance[i];
  53401. // skip _not_ specified properties
  53402. if (value === undefined && options.existingOnly) continue;
  53403. var propDef = objTypeDef[i];
  53404. // set default
  53405. if(value === undefined && propDef["default"]){
  53406. value = instance[i] = propDef["default"];
  53407. }
  53408. if(options.coerce && i in instance){
  53409. value = instance[i] = options.coerce(value, propDef);
  53410. }
  53411. checkProp(value,propDef,path,i);
  53412. }
  53413. }
  53414. }
  53415. for(i in instance){
  53416. if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){
  53417. if (options.filter) {
  53418. delete instance[i];
  53419. continue;
  53420. } else {
  53421. errors.push({property:path,message:(typeof value) + "The property " + i +
  53422. " is not defined in the schema and the schema does not allow additional properties"});
  53423. }
  53424. }
  53425. var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
  53426. if(requires && !(requires in instance)){
  53427. errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"});
  53428. }
  53429. value = instance[i];
  53430. if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){
  53431. if(options.coerce){
  53432. value = instance[i] = options.coerce(value, additionalProp);
  53433. }
  53434. checkProp(value,additionalProp,path,i);
  53435. }
  53436. if(!_changing && value && value.$schema){
  53437. errors = errors.concat(checkProp(value,value.$schema,path,i));
  53438. }
  53439. }
  53440. return errors;
  53441. }
  53442. if(schema){
  53443. checkProp(instance,schema,'',_changing || '');
  53444. }
  53445. if(!_changing && instance && instance.$schema){
  53446. checkProp(instance,instance.$schema,'','');
  53447. }
  53448. return {valid:!errors.length,errors:errors};
  53449. };
  53450. exports.mustBeValid = function(result){
  53451. // summary:
  53452. // This checks to ensure that the result is valid and will throw an appropriate error message if it is not
  53453. // result: the result returned from checkPropertyChange or validate
  53454. if(!result.valid){
  53455. throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n"));
  53456. }
  53457. }
  53458. return exports;
  53459. }));
  53460. },{}],331:[function(require,module,exports){
  53461. exports = module.exports = stringify
  53462. exports.getSerialize = serializer
  53463. function stringify(obj, replacer, spaces, cycleReplacer) {
  53464. return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
  53465. }
  53466. function serializer(replacer, cycleReplacer) {
  53467. var stack = [], keys = []
  53468. if (cycleReplacer == null) cycleReplacer = function(key, value) {
  53469. if (stack[0] === value) return "[Circular ~]"
  53470. return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
  53471. }
  53472. return function(key, value) {
  53473. if (stack.length > 0) {
  53474. var thisPos = stack.indexOf(this)
  53475. ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
  53476. ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
  53477. if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
  53478. }
  53479. else stack.push(value)
  53480. return replacer == null ? value : replacer.call(this, key, value)
  53481. }
  53482. }
  53483. },{}],332:[function(require,module,exports){
  53484. /*
  53485. * lib/jsprim.js: utilities for primitive JavaScript types
  53486. */
  53487. var mod_assert = require('assert-plus');
  53488. var mod_util = require('util');
  53489. var mod_extsprintf = require('extsprintf');
  53490. var mod_verror = require('verror');
  53491. var mod_jsonschema = require('json-schema');
  53492. /*
  53493. * Public interface
  53494. */
  53495. exports.deepCopy = deepCopy;
  53496. exports.deepEqual = deepEqual;
  53497. exports.isEmpty = isEmpty;
  53498. exports.hasKey = hasKey;
  53499. exports.forEachKey = forEachKey;
  53500. exports.pluck = pluck;
  53501. exports.flattenObject = flattenObject;
  53502. exports.flattenIter = flattenIter;
  53503. exports.validateJsonObject = validateJsonObjectJS;
  53504. exports.validateJsonObjectJS = validateJsonObjectJS;
  53505. exports.randElt = randElt;
  53506. exports.extraProperties = extraProperties;
  53507. exports.mergeObjects = mergeObjects;
  53508. exports.startsWith = startsWith;
  53509. exports.endsWith = endsWith;
  53510. exports.parseInteger = parseInteger;
  53511. exports.iso8601 = iso8601;
  53512. exports.rfc1123 = rfc1123;
  53513. exports.parseDateTime = parseDateTime;
  53514. exports.hrtimediff = hrtimeDiff;
  53515. exports.hrtimeDiff = hrtimeDiff;
  53516. exports.hrtimeAccum = hrtimeAccum;
  53517. exports.hrtimeAdd = hrtimeAdd;
  53518. exports.hrtimeNanosec = hrtimeNanosec;
  53519. exports.hrtimeMicrosec = hrtimeMicrosec;
  53520. exports.hrtimeMillisec = hrtimeMillisec;
  53521. /*
  53522. * Deep copy an acyclic *basic* Javascript object. This only handles basic
  53523. * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects
  53524. * containing these. This does *not* handle instances of other classes.
  53525. */
  53526. function deepCopy(obj)
  53527. {
  53528. var ret, key;
  53529. var marker = '__deepCopy';
  53530. if (obj && obj[marker])
  53531. throw (new Error('attempted deep copy of cyclic object'));
  53532. if (obj && obj.constructor == Object) {
  53533. ret = {};
  53534. obj[marker] = true;
  53535. for (key in obj) {
  53536. if (key == marker)
  53537. continue;
  53538. ret[key] = deepCopy(obj[key]);
  53539. }
  53540. delete (obj[marker]);
  53541. return (ret);
  53542. }
  53543. if (obj && obj.constructor == Array) {
  53544. ret = [];
  53545. obj[marker] = true;
  53546. for (key = 0; key < obj.length; key++)
  53547. ret.push(deepCopy(obj[key]));
  53548. delete (obj[marker]);
  53549. return (ret);
  53550. }
  53551. /*
  53552. * It must be a primitive type -- just return it.
  53553. */
  53554. return (obj);
  53555. }
  53556. function deepEqual(obj1, obj2)
  53557. {
  53558. if (typeof (obj1) != typeof (obj2))
  53559. return (false);
  53560. if (obj1 === null || obj2 === null || typeof (obj1) != 'object')
  53561. return (obj1 === obj2);
  53562. if (obj1.constructor != obj2.constructor)
  53563. return (false);
  53564. var k;
  53565. for (k in obj1) {
  53566. if (!obj2.hasOwnProperty(k))
  53567. return (false);
  53568. if (!deepEqual(obj1[k], obj2[k]))
  53569. return (false);
  53570. }
  53571. for (k in obj2) {
  53572. if (!obj1.hasOwnProperty(k))
  53573. return (false);
  53574. }
  53575. return (true);
  53576. }
  53577. function isEmpty(obj)
  53578. {
  53579. var key;
  53580. for (key in obj)
  53581. return (false);
  53582. return (true);
  53583. }
  53584. function hasKey(obj, key)
  53585. {
  53586. mod_assert.equal(typeof (key), 'string');
  53587. return (Object.prototype.hasOwnProperty.call(obj, key));
  53588. }
  53589. function forEachKey(obj, callback)
  53590. {
  53591. for (var key in obj) {
  53592. if (hasKey(obj, key)) {
  53593. callback(key, obj[key]);
  53594. }
  53595. }
  53596. }
  53597. function pluck(obj, key)
  53598. {
  53599. mod_assert.equal(typeof (key), 'string');
  53600. return (pluckv(obj, key));
  53601. }
  53602. function pluckv(obj, key)
  53603. {
  53604. if (obj === null || typeof (obj) !== 'object')
  53605. return (undefined);
  53606. if (obj.hasOwnProperty(key))
  53607. return (obj[key]);
  53608. var i = key.indexOf('.');
  53609. if (i == -1)
  53610. return (undefined);
  53611. var key1 = key.substr(0, i);
  53612. if (!obj.hasOwnProperty(key1))
  53613. return (undefined);
  53614. return (pluckv(obj[key1], key.substr(i + 1)));
  53615. }
  53616. /*
  53617. * Invoke callback(row) for each entry in the array that would be returned by
  53618. * flattenObject(data, depth). This is just like flattenObject(data,
  53619. * depth).forEach(callback), except that the intermediate array is never
  53620. * created.
  53621. */
  53622. function flattenIter(data, depth, callback)
  53623. {
  53624. doFlattenIter(data, depth, [], callback);
  53625. }
  53626. function doFlattenIter(data, depth, accum, callback)
  53627. {
  53628. var each;
  53629. var key;
  53630. if (depth === 0) {
  53631. each = accum.slice(0);
  53632. each.push(data);
  53633. callback(each);
  53634. return;
  53635. }
  53636. mod_assert.ok(data !== null);
  53637. mod_assert.equal(typeof (data), 'object');
  53638. mod_assert.equal(typeof (depth), 'number');
  53639. mod_assert.ok(depth >= 0);
  53640. for (key in data) {
  53641. each = accum.slice(0);
  53642. each.push(key);
  53643. doFlattenIter(data[key], depth - 1, each, callback);
  53644. }
  53645. }
  53646. function flattenObject(data, depth)
  53647. {
  53648. if (depth === 0)
  53649. return ([ data ]);
  53650. mod_assert.ok(data !== null);
  53651. mod_assert.equal(typeof (data), 'object');
  53652. mod_assert.equal(typeof (depth), 'number');
  53653. mod_assert.ok(depth >= 0);
  53654. var rv = [];
  53655. var key;
  53656. for (key in data) {
  53657. flattenObject(data[key], depth - 1).forEach(function (p) {
  53658. rv.push([ key ].concat(p));
  53659. });
  53660. }
  53661. return (rv);
  53662. }
  53663. function startsWith(str, prefix)
  53664. {
  53665. return (str.substr(0, prefix.length) == prefix);
  53666. }
  53667. function endsWith(str, suffix)
  53668. {
  53669. return (str.substr(
  53670. str.length - suffix.length, suffix.length) == suffix);
  53671. }
  53672. function iso8601(d)
  53673. {
  53674. if (typeof (d) == 'number')
  53675. d = new Date(d);
  53676. mod_assert.ok(d.constructor === Date);
  53677. return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ',
  53678. d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(),
  53679. d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(),
  53680. d.getUTCMilliseconds()));
  53681. }
  53682. var RFC1123_MONTHS = [
  53683. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  53684. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  53685. var RFC1123_DAYS = [
  53686. 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  53687. function rfc1123(date) {
  53688. return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT',
  53689. RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(),
  53690. RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(),
  53691. date.getUTCHours(), date.getUTCMinutes(),
  53692. date.getUTCSeconds()));
  53693. }
  53694. /*
  53695. * Parses a date expressed as a string, as either a number of milliseconds since
  53696. * the epoch or any string format that Date accepts, giving preference to the
  53697. * former where these two sets overlap (e.g., small numbers).
  53698. */
  53699. function parseDateTime(str)
  53700. {
  53701. /*
  53702. * This is irritatingly implicit, but significantly more concise than
  53703. * alternatives. The "+str" will convert a string containing only a
  53704. * number directly to a Number, or NaN for other strings. Thus, if the
  53705. * conversion succeeds, we use it (this is the milliseconds-since-epoch
  53706. * case). Otherwise, we pass the string directly to the Date
  53707. * constructor to parse.
  53708. */
  53709. var numeric = +str;
  53710. if (!isNaN(numeric)) {
  53711. return (new Date(numeric));
  53712. } else {
  53713. return (new Date(str));
  53714. }
  53715. }
  53716. /*
  53717. * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode
  53718. * the ES6 definitions here, while allowing for them to someday be higher.
  53719. */
  53720. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  53721. var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  53722. /*
  53723. * Default options for parseInteger().
  53724. */
  53725. var PI_DEFAULTS = {
  53726. base: 10,
  53727. allowSign: true,
  53728. allowPrefix: false,
  53729. allowTrailing: false,
  53730. allowImprecise: false,
  53731. trimWhitespace: false,
  53732. leadingZeroIsOctal: false
  53733. };
  53734. var CP_0 = 0x30;
  53735. var CP_9 = 0x39;
  53736. var CP_A = 0x41;
  53737. var CP_B = 0x42;
  53738. var CP_O = 0x4f;
  53739. var CP_T = 0x54;
  53740. var CP_X = 0x58;
  53741. var CP_Z = 0x5a;
  53742. var CP_a = 0x61;
  53743. var CP_b = 0x62;
  53744. var CP_o = 0x6f;
  53745. var CP_t = 0x74;
  53746. var CP_x = 0x78;
  53747. var CP_z = 0x7a;
  53748. var PI_CONV_DEC = 0x30;
  53749. var PI_CONV_UC = 0x37;
  53750. var PI_CONV_LC = 0x57;
  53751. /*
  53752. * A stricter version of parseInt() that provides options for changing what
  53753. * is an acceptable string (for example, disallowing trailing characters).
  53754. */
  53755. function parseInteger(str, uopts)
  53756. {
  53757. mod_assert.string(str, 'str');
  53758. mod_assert.optionalObject(uopts, 'options');
  53759. var baseOverride = false;
  53760. var options = PI_DEFAULTS;
  53761. if (uopts) {
  53762. baseOverride = hasKey(uopts, 'base');
  53763. options = mergeObjects(options, uopts);
  53764. mod_assert.number(options.base, 'options.base');
  53765. mod_assert.ok(options.base >= 2, 'options.base >= 2');
  53766. mod_assert.ok(options.base <= 36, 'options.base <= 36');
  53767. mod_assert.bool(options.allowSign, 'options.allowSign');
  53768. mod_assert.bool(options.allowPrefix, 'options.allowPrefix');
  53769. mod_assert.bool(options.allowTrailing,
  53770. 'options.allowTrailing');
  53771. mod_assert.bool(options.allowImprecise,
  53772. 'options.allowImprecise');
  53773. mod_assert.bool(options.trimWhitespace,
  53774. 'options.trimWhitespace');
  53775. mod_assert.bool(options.leadingZeroIsOctal,
  53776. 'options.leadingZeroIsOctal');
  53777. if (options.leadingZeroIsOctal) {
  53778. mod_assert.ok(!baseOverride,
  53779. '"base" and "leadingZeroIsOctal" are ' +
  53780. 'mutually exclusive');
  53781. }
  53782. }
  53783. var c;
  53784. var pbase = -1;
  53785. var base = options.base;
  53786. var start;
  53787. var mult = 1;
  53788. var value = 0;
  53789. var idx = 0;
  53790. var len = str.length;
  53791. /* Trim any whitespace on the left side. */
  53792. if (options.trimWhitespace) {
  53793. while (idx < len && isSpace(str.charCodeAt(idx))) {
  53794. ++idx;
  53795. }
  53796. }
  53797. /* Check the number for a leading sign. */
  53798. if (options.allowSign) {
  53799. if (str[idx] === '-') {
  53800. idx += 1;
  53801. mult = -1;
  53802. } else if (str[idx] === '+') {
  53803. idx += 1;
  53804. }
  53805. }
  53806. /* Parse the base-indicating prefix if there is one. */
  53807. if (str[idx] === '0') {
  53808. if (options.allowPrefix) {
  53809. pbase = prefixToBase(str.charCodeAt(idx + 1));
  53810. if (pbase !== -1 && (!baseOverride || pbase === base)) {
  53811. base = pbase;
  53812. idx += 2;
  53813. }
  53814. }
  53815. if (pbase === -1 && options.leadingZeroIsOctal) {
  53816. base = 8;
  53817. }
  53818. }
  53819. /* Parse the actual digits. */
  53820. for (start = idx; idx < len; ++idx) {
  53821. c = translateDigit(str.charCodeAt(idx));
  53822. if (c !== -1 && c < base) {
  53823. value *= base;
  53824. value += c;
  53825. } else {
  53826. break;
  53827. }
  53828. }
  53829. /* If we didn't parse any digits, we have an invalid number. */
  53830. if (start === idx) {
  53831. return (new Error('invalid number: ' + JSON.stringify(str)));
  53832. }
  53833. /* Trim any whitespace on the right side. */
  53834. if (options.trimWhitespace) {
  53835. while (idx < len && isSpace(str.charCodeAt(idx))) {
  53836. ++idx;
  53837. }
  53838. }
  53839. /* Check for trailing characters. */
  53840. if (idx < len && !options.allowTrailing) {
  53841. return (new Error('trailing characters after number: ' +
  53842. JSON.stringify(str.slice(idx))));
  53843. }
  53844. /* If our value is 0, we return now, to avoid returning -0. */
  53845. if (value === 0) {
  53846. return (0);
  53847. }
  53848. /* Calculate our final value. */
  53849. var result = value * mult;
  53850. /*
  53851. * If the string represents a value that cannot be precisely represented
  53852. * by JavaScript, then we want to check that:
  53853. *
  53854. * - We never increased the value past MAX_SAFE_INTEGER
  53855. * - We don't make the result negative and below MIN_SAFE_INTEGER
  53856. *
  53857. * Because we only ever increment the value during parsing, there's no
  53858. * chance of moving past MAX_SAFE_INTEGER and then dropping below it
  53859. * again, losing precision in the process. This means that we only need
  53860. * to do our checks here, at the end.
  53861. */
  53862. if (!options.allowImprecise &&
  53863. (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) {
  53864. return (new Error('number is outside of the supported range: ' +
  53865. JSON.stringify(str.slice(start, idx))));
  53866. }
  53867. return (result);
  53868. }
  53869. /*
  53870. * Interpret a character code as a base-36 digit.
  53871. */
  53872. function translateDigit(d)
  53873. {
  53874. if (d >= CP_0 && d <= CP_9) {
  53875. /* '0' to '9' -> 0 to 9 */
  53876. return (d - PI_CONV_DEC);
  53877. } else if (d >= CP_A && d <= CP_Z) {
  53878. /* 'A' - 'Z' -> 10 to 35 */
  53879. return (d - PI_CONV_UC);
  53880. } else if (d >= CP_a && d <= CP_z) {
  53881. /* 'a' - 'z' -> 10 to 35 */
  53882. return (d - PI_CONV_LC);
  53883. } else {
  53884. /* Invalid character code */
  53885. return (-1);
  53886. }
  53887. }
  53888. /*
  53889. * Test if a value matches the ECMAScript definition of trimmable whitespace.
  53890. */
  53891. function isSpace(c)
  53892. {
  53893. return (c === 0x20) ||
  53894. (c >= 0x0009 && c <= 0x000d) ||
  53895. (c === 0x00a0) ||
  53896. (c === 0x1680) ||
  53897. (c === 0x180e) ||
  53898. (c >= 0x2000 && c <= 0x200a) ||
  53899. (c === 0x2028) ||
  53900. (c === 0x2029) ||
  53901. (c === 0x202f) ||
  53902. (c === 0x205f) ||
  53903. (c === 0x3000) ||
  53904. (c === 0xfeff);
  53905. }
  53906. /*
  53907. * Determine which base a character indicates (e.g., 'x' indicates hex).
  53908. */
  53909. function prefixToBase(c)
  53910. {
  53911. if (c === CP_b || c === CP_B) {
  53912. /* 0b/0B (binary) */
  53913. return (2);
  53914. } else if (c === CP_o || c === CP_O) {
  53915. /* 0o/0O (octal) */
  53916. return (8);
  53917. } else if (c === CP_t || c === CP_T) {
  53918. /* 0t/0T (decimal) */
  53919. return (10);
  53920. } else if (c === CP_x || c === CP_X) {
  53921. /* 0x/0X (hexadecimal) */
  53922. return (16);
  53923. } else {
  53924. /* Not a meaningful character */
  53925. return (-1);
  53926. }
  53927. }
  53928. function validateJsonObjectJS(schema, input)
  53929. {
  53930. var report = mod_jsonschema.validate(input, schema);
  53931. if (report.errors.length === 0)
  53932. return (null);
  53933. /* Currently, we only do anything useful with the first error. */
  53934. var error = report.errors[0];
  53935. /* The failed property is given by a URI with an irrelevant prefix. */
  53936. var propname = error['property'];
  53937. var reason = error['message'].toLowerCase();
  53938. var i, j;
  53939. /*
  53940. * There's at least one case where the property error message is
  53941. * confusing at best. We work around this here.
  53942. */
  53943. if ((i = reason.indexOf('the property ')) != -1 &&
  53944. (j = reason.indexOf(' is not defined in the schema and the ' +
  53945. 'schema does not allow additional properties')) != -1) {
  53946. i += 'the property '.length;
  53947. if (propname === '')
  53948. propname = reason.substr(i, j - i);
  53949. else
  53950. propname = propname + '.' + reason.substr(i, j - i);
  53951. reason = 'unsupported property';
  53952. }
  53953. var rv = new mod_verror.VError('property "%s": %s', propname, reason);
  53954. rv.jsv_details = error;
  53955. return (rv);
  53956. }
  53957. function randElt(arr)
  53958. {
  53959. mod_assert.ok(Array.isArray(arr) && arr.length > 0,
  53960. 'randElt argument must be a non-empty array');
  53961. return (arr[Math.floor(Math.random() * arr.length)]);
  53962. }
  53963. function assertHrtime(a)
  53964. {
  53965. mod_assert.ok(a[0] >= 0 && a[1] >= 0,
  53966. 'negative numbers not allowed in hrtimes');
  53967. mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow');
  53968. }
  53969. /*
  53970. * Compute the time elapsed between hrtime readings A and B, where A is later
  53971. * than B. hrtime readings come from Node's process.hrtime(). There is no
  53972. * defined way to represent negative deltas, so it's illegal to diff B from A
  53973. * where the time denoted by B is later than the time denoted by A. If this
  53974. * becomes valuable, we can define a representation and extend the
  53975. * implementation to support it.
  53976. */
  53977. function hrtimeDiff(a, b)
  53978. {
  53979. assertHrtime(a);
  53980. assertHrtime(b);
  53981. mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]),
  53982. 'negative differences not allowed');
  53983. var rv = [ a[0] - b[0], 0 ];
  53984. if (a[1] >= b[1]) {
  53985. rv[1] = a[1] - b[1];
  53986. } else {
  53987. rv[0]--;
  53988. rv[1] = 1e9 - (b[1] - a[1]);
  53989. }
  53990. return (rv);
  53991. }
  53992. /*
  53993. * Convert a hrtime reading from the array format returned by Node's
  53994. * process.hrtime() into a scalar number of nanoseconds.
  53995. */
  53996. function hrtimeNanosec(a)
  53997. {
  53998. assertHrtime(a);
  53999. return (Math.floor(a[0] * 1e9 + a[1]));
  54000. }
  54001. /*
  54002. * Convert a hrtime reading from the array format returned by Node's
  54003. * process.hrtime() into a scalar number of microseconds.
  54004. */
  54005. function hrtimeMicrosec(a)
  54006. {
  54007. assertHrtime(a);
  54008. return (Math.floor(a[0] * 1e6 + a[1] / 1e3));
  54009. }
  54010. /*
  54011. * Convert a hrtime reading from the array format returned by Node's
  54012. * process.hrtime() into a scalar number of milliseconds.
  54013. */
  54014. function hrtimeMillisec(a)
  54015. {
  54016. assertHrtime(a);
  54017. return (Math.floor(a[0] * 1e3 + a[1] / 1e6));
  54018. }
  54019. /*
  54020. * Add two hrtime readings A and B, overwriting A with the result of the
  54021. * addition. This function is useful for accumulating several hrtime intervals
  54022. * into a counter. Returns A.
  54023. */
  54024. function hrtimeAccum(a, b)
  54025. {
  54026. assertHrtime(a);
  54027. assertHrtime(b);
  54028. /*
  54029. * Accumulate the nanosecond component.
  54030. */
  54031. a[1] += b[1];
  54032. if (a[1] >= 1e9) {
  54033. /*
  54034. * The nanosecond component overflowed, so carry to the seconds
  54035. * field.
  54036. */
  54037. a[0]++;
  54038. a[1] -= 1e9;
  54039. }
  54040. /*
  54041. * Accumulate the seconds component.
  54042. */
  54043. a[0] += b[0];
  54044. return (a);
  54045. }
  54046. /*
  54047. * Add two hrtime readings A and B, returning the result as a new hrtime array.
  54048. * Does not modify either input argument.
  54049. */
  54050. function hrtimeAdd(a, b)
  54051. {
  54052. assertHrtime(a);
  54053. var rv = [ a[0], a[1] ];
  54054. return (hrtimeAccum(rv, b));
  54055. }
  54056. /*
  54057. * Check an object for unexpected properties. Accepts the object to check, and
  54058. * an array of allowed property names (strings). Returns an array of key names
  54059. * that were found on the object, but did not appear in the list of allowed
  54060. * properties. If no properties were found, the returned array will be of
  54061. * zero length.
  54062. */
  54063. function extraProperties(obj, allowed)
  54064. {
  54065. mod_assert.ok(typeof (obj) === 'object' && obj !== null,
  54066. 'obj argument must be a non-null object');
  54067. mod_assert.ok(Array.isArray(allowed),
  54068. 'allowed argument must be an array of strings');
  54069. for (var i = 0; i < allowed.length; i++) {
  54070. mod_assert.ok(typeof (allowed[i]) === 'string',
  54071. 'allowed argument must be an array of strings');
  54072. }
  54073. return (Object.keys(obj).filter(function (key) {
  54074. return (allowed.indexOf(key) === -1);
  54075. }));
  54076. }
  54077. /*
  54078. * Given three sets of properties "provided" (may be undefined), "overrides"
  54079. * (required), and "defaults" (may be undefined), construct an object containing
  54080. * the union of these sets with "overrides" overriding "provided", and
  54081. * "provided" overriding "defaults". None of the input objects are modified.
  54082. */
  54083. function mergeObjects(provided, overrides, defaults)
  54084. {
  54085. var rv, k;
  54086. rv = {};
  54087. if (defaults) {
  54088. for (k in defaults)
  54089. rv[k] = defaults[k];
  54090. }
  54091. if (provided) {
  54092. for (k in provided)
  54093. rv[k] = provided[k];
  54094. }
  54095. if (overrides) {
  54096. for (k in overrides)
  54097. rv[k] = overrides[k];
  54098. }
  54099. return (rv);
  54100. }
  54101. },{"assert-plus":104,"extsprintf":250,"json-schema":330,"util":658,"verror":664}],333:[function(require,module,exports){
  54102. var bufferEqual = require('buffer-equal-constant-time');
  54103. var Buffer = require('safe-buffer').Buffer;
  54104. var crypto = require('crypto');
  54105. var formatEcdsa = require('ecdsa-sig-formatter');
  54106. var util = require('util');
  54107. var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".'
  54108. var MSG_INVALID_SECRET = 'secret must be a string or buffer';
  54109. var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';
  54110. var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';
  54111. var supportsKeyObjects = typeof crypto.createPublicKey === 'function';
  54112. if (supportsKeyObjects) {
  54113. MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';
  54114. MSG_INVALID_SECRET += 'or a KeyObject';
  54115. }
  54116. function checkIsPublicKey(key) {
  54117. if (Buffer.isBuffer(key)) {
  54118. return;
  54119. }
  54120. if (typeof key === 'string') {
  54121. return;
  54122. }
  54123. if (!supportsKeyObjects) {
  54124. throw typeError(MSG_INVALID_VERIFIER_KEY);
  54125. }
  54126. if (typeof key !== 'object') {
  54127. throw typeError(MSG_INVALID_VERIFIER_KEY);
  54128. }
  54129. if (typeof key.type !== 'string') {
  54130. throw typeError(MSG_INVALID_VERIFIER_KEY);
  54131. }
  54132. if (typeof key.asymmetricKeyType !== 'string') {
  54133. throw typeError(MSG_INVALID_VERIFIER_KEY);
  54134. }
  54135. if (typeof key.export !== 'function') {
  54136. throw typeError(MSG_INVALID_VERIFIER_KEY);
  54137. }
  54138. };
  54139. function checkIsPrivateKey(key) {
  54140. if (Buffer.isBuffer(key)) {
  54141. return;
  54142. }
  54143. if (typeof key === 'string') {
  54144. return;
  54145. }
  54146. if (typeof key === 'object') {
  54147. return;
  54148. }
  54149. throw typeError(MSG_INVALID_SIGNER_KEY);
  54150. };
  54151. function checkIsSecretKey(key) {
  54152. if (Buffer.isBuffer(key)) {
  54153. return;
  54154. }
  54155. if (typeof key === 'string') {
  54156. return key;
  54157. }
  54158. if (!supportsKeyObjects) {
  54159. throw typeError(MSG_INVALID_SECRET);
  54160. }
  54161. if (typeof key !== 'object') {
  54162. throw typeError(MSG_INVALID_SECRET);
  54163. }
  54164. if (key.type !== 'secret') {
  54165. throw typeError(MSG_INVALID_SECRET);
  54166. }
  54167. if (typeof key.export !== 'function') {
  54168. throw typeError(MSG_INVALID_SECRET);
  54169. }
  54170. }
  54171. function fromBase64(base64) {
  54172. return base64
  54173. .replace(/=/g, '')
  54174. .replace(/\+/g, '-')
  54175. .replace(/\//g, '_');
  54176. }
  54177. function toBase64(base64url) {
  54178. base64url = base64url.toString();
  54179. var padding = 4 - base64url.length % 4;
  54180. if (padding !== 4) {
  54181. for (var i = 0; i < padding; ++i) {
  54182. base64url += '=';
  54183. }
  54184. }
  54185. return base64url
  54186. .replace(/\-/g, '+')
  54187. .replace(/_/g, '/');
  54188. }
  54189. function typeError(template) {
  54190. var args = [].slice.call(arguments, 1);
  54191. var errMsg = util.format.bind(util, template).apply(null, args);
  54192. return new TypeError(errMsg);
  54193. }
  54194. function bufferOrString(obj) {
  54195. return Buffer.isBuffer(obj) || typeof obj === 'string';
  54196. }
  54197. function normalizeInput(thing) {
  54198. if (!bufferOrString(thing))
  54199. thing = JSON.stringify(thing);
  54200. return thing;
  54201. }
  54202. function createHmacSigner(bits) {
  54203. return function sign(thing, secret) {
  54204. checkIsSecretKey(secret);
  54205. thing = normalizeInput(thing);
  54206. var hmac = crypto.createHmac('sha' + bits, secret);
  54207. var sig = (hmac.update(thing), hmac.digest('base64'))
  54208. return fromBase64(sig);
  54209. }
  54210. }
  54211. function createHmacVerifier(bits) {
  54212. return function verify(thing, signature, secret) {
  54213. var computedSig = createHmacSigner(bits)(thing, secret);
  54214. return bufferEqual(Buffer.from(signature), Buffer.from(computedSig));
  54215. }
  54216. }
  54217. function createKeySigner(bits) {
  54218. return function sign(thing, privateKey) {
  54219. checkIsPrivateKey(privateKey);
  54220. thing = normalizeInput(thing);
  54221. // Even though we are specifying "RSA" here, this works with ECDSA
  54222. // keys as well.
  54223. var signer = crypto.createSign('RSA-SHA' + bits);
  54224. var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));
  54225. return fromBase64(sig);
  54226. }
  54227. }
  54228. function createKeyVerifier(bits) {
  54229. return function verify(thing, signature, publicKey) {
  54230. checkIsPublicKey(publicKey);
  54231. thing = normalizeInput(thing);
  54232. signature = toBase64(signature);
  54233. var verifier = crypto.createVerify('RSA-SHA' + bits);
  54234. verifier.update(thing);
  54235. return verifier.verify(publicKey, signature, 'base64');
  54236. }
  54237. }
  54238. function createPSSKeySigner(bits) {
  54239. return function sign(thing, privateKey) {
  54240. checkIsPrivateKey(privateKey);
  54241. thing = normalizeInput(thing);
  54242. var signer = crypto.createSign('RSA-SHA' + bits);
  54243. var sig = (signer.update(thing), signer.sign({
  54244. key: privateKey,
  54245. padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
  54246. saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
  54247. }, 'base64'));
  54248. return fromBase64(sig);
  54249. }
  54250. }
  54251. function createPSSKeyVerifier(bits) {
  54252. return function verify(thing, signature, publicKey) {
  54253. checkIsPublicKey(publicKey);
  54254. thing = normalizeInput(thing);
  54255. signature = toBase64(signature);
  54256. var verifier = crypto.createVerify('RSA-SHA' + bits);
  54257. verifier.update(thing);
  54258. return verifier.verify({
  54259. key: publicKey,
  54260. padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
  54261. saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
  54262. }, signature, 'base64');
  54263. }
  54264. }
  54265. function createECDSASigner(bits) {
  54266. var inner = createKeySigner(bits);
  54267. return function sign() {
  54268. var signature = inner.apply(null, arguments);
  54269. signature = formatEcdsa.derToJose(signature, 'ES' + bits);
  54270. return signature;
  54271. };
  54272. }
  54273. function createECDSAVerifer(bits) {
  54274. var inner = createKeyVerifier(bits);
  54275. return function verify(thing, signature, publicKey) {
  54276. signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');
  54277. var result = inner(thing, signature, publicKey);
  54278. return result;
  54279. };
  54280. }
  54281. function createNoneSigner() {
  54282. return function sign() {
  54283. return '';
  54284. }
  54285. }
  54286. function createNoneVerifier() {
  54287. return function verify(thing, signature) {
  54288. return signature === '';
  54289. }
  54290. }
  54291. module.exports = function jwa(algorithm) {
  54292. var signerFactories = {
  54293. hs: createHmacSigner,
  54294. rs: createKeySigner,
  54295. ps: createPSSKeySigner,
  54296. es: createECDSASigner,
  54297. none: createNoneSigner,
  54298. }
  54299. var verifierFactories = {
  54300. hs: createHmacVerifier,
  54301. rs: createKeyVerifier,
  54302. ps: createPSSKeyVerifier,
  54303. es: createECDSAVerifer,
  54304. none: createNoneVerifier,
  54305. }
  54306. var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i);
  54307. if (!match)
  54308. throw typeError(MSG_INVALID_ALGORITHM, algorithm);
  54309. var algo = (match[1] || match[3]).toLowerCase();
  54310. var bits = match[2];
  54311. return {
  54312. sign: signerFactories[algo](bits),
  54313. verify: verifierFactories[algo](bits),
  54314. }
  54315. };
  54316. },{"buffer-equal-constant-time":191,"crypto":208,"ecdsa-sig-formatter":226,"safe-buffer":561,"util":658}],334:[function(require,module,exports){
  54317. /*global exports*/
  54318. var SignStream = require('./lib/sign-stream');
  54319. var VerifyStream = require('./lib/verify-stream');
  54320. var ALGORITHMS = [
  54321. 'HS256', 'HS384', 'HS512',
  54322. 'RS256', 'RS384', 'RS512',
  54323. 'PS256', 'PS384', 'PS512',
  54324. 'ES256', 'ES384', 'ES512'
  54325. ];
  54326. exports.ALGORITHMS = ALGORITHMS;
  54327. exports.sign = SignStream.sign;
  54328. exports.verify = VerifyStream.verify;
  54329. exports.decode = VerifyStream.decode;
  54330. exports.isValid = VerifyStream.isValid;
  54331. exports.createSign = function createSign(opts) {
  54332. return new SignStream(opts);
  54333. };
  54334. exports.createVerify = function createVerify(opts) {
  54335. return new VerifyStream(opts);
  54336. };
  54337. },{"./lib/sign-stream":336,"./lib/verify-stream":338}],335:[function(require,module,exports){
  54338. (function (process){(function (){
  54339. /*global module, process*/
  54340. var Buffer = require('safe-buffer').Buffer;
  54341. var Stream = require('stream');
  54342. var util = require('util');
  54343. function DataStream(data) {
  54344. this.buffer = null;
  54345. this.writable = true;
  54346. this.readable = true;
  54347. // No input
  54348. if (!data) {
  54349. this.buffer = Buffer.alloc(0);
  54350. return this;
  54351. }
  54352. // Stream
  54353. if (typeof data.pipe === 'function') {
  54354. this.buffer = Buffer.alloc(0);
  54355. data.pipe(this);
  54356. return this;
  54357. }
  54358. // Buffer or String
  54359. // or Object (assumedly a passworded key)
  54360. if (data.length || typeof data === 'object') {
  54361. this.buffer = data;
  54362. this.writable = false;
  54363. process.nextTick(function () {
  54364. this.emit('end', data);
  54365. this.readable = false;
  54366. this.emit('close');
  54367. }.bind(this));
  54368. return this;
  54369. }
  54370. throw new TypeError('Unexpected data type ('+ typeof data + ')');
  54371. }
  54372. util.inherits(DataStream, Stream);
  54373. DataStream.prototype.write = function write(data) {
  54374. this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);
  54375. this.emit('data', data);
  54376. };
  54377. DataStream.prototype.end = function end(data) {
  54378. if (data)
  54379. this.write(data);
  54380. this.emit('end', data);
  54381. this.emit('close');
  54382. this.writable = false;
  54383. this.readable = false;
  54384. };
  54385. module.exports = DataStream;
  54386. }).call(this)}).call(this,require('_process'))
  54387. },{"_process":525,"safe-buffer":561,"stream":597,"util":658}],336:[function(require,module,exports){
  54388. /*global module*/
  54389. var Buffer = require('safe-buffer').Buffer;
  54390. var DataStream = require('./data-stream');
  54391. var jwa = require('jwa');
  54392. var Stream = require('stream');
  54393. var toString = require('./tostring');
  54394. var util = require('util');
  54395. function base64url(string, encoding) {
  54396. return Buffer
  54397. .from(string, encoding)
  54398. .toString('base64')
  54399. .replace(/=/g, '')
  54400. .replace(/\+/g, '-')
  54401. .replace(/\//g, '_');
  54402. }
  54403. function jwsSecuredInput(header, payload, encoding) {
  54404. encoding = encoding || 'utf8';
  54405. var encodedHeader = base64url(toString(header), 'binary');
  54406. var encodedPayload = base64url(toString(payload), encoding);
  54407. return util.format('%s.%s', encodedHeader, encodedPayload);
  54408. }
  54409. function jwsSign(opts) {
  54410. var header = opts.header;
  54411. var payload = opts.payload;
  54412. var secretOrKey = opts.secret || opts.privateKey;
  54413. var encoding = opts.encoding;
  54414. var algo = jwa(header.alg);
  54415. var securedInput = jwsSecuredInput(header, payload, encoding);
  54416. var signature = algo.sign(securedInput, secretOrKey);
  54417. return util.format('%s.%s', securedInput, signature);
  54418. }
  54419. function SignStream(opts) {
  54420. var secret = opts.secret||opts.privateKey||opts.key;
  54421. var secretStream = new DataStream(secret);
  54422. this.readable = true;
  54423. this.header = opts.header;
  54424. this.encoding = opts.encoding;
  54425. this.secret = this.privateKey = this.key = secretStream;
  54426. this.payload = new DataStream(opts.payload);
  54427. this.secret.once('close', function () {
  54428. if (!this.payload.writable && this.readable)
  54429. this.sign();
  54430. }.bind(this));
  54431. this.payload.once('close', function () {
  54432. if (!this.secret.writable && this.readable)
  54433. this.sign();
  54434. }.bind(this));
  54435. }
  54436. util.inherits(SignStream, Stream);
  54437. SignStream.prototype.sign = function sign() {
  54438. try {
  54439. var signature = jwsSign({
  54440. header: this.header,
  54441. payload: this.payload.buffer,
  54442. secret: this.secret.buffer,
  54443. encoding: this.encoding
  54444. });
  54445. this.emit('done', signature);
  54446. this.emit('data', signature);
  54447. this.emit('end');
  54448. this.readable = false;
  54449. return signature;
  54450. } catch (e) {
  54451. this.readable = false;
  54452. this.emit('error', e);
  54453. this.emit('close');
  54454. }
  54455. };
  54456. SignStream.sign = jwsSign;
  54457. module.exports = SignStream;
  54458. },{"./data-stream":335,"./tostring":337,"jwa":333,"safe-buffer":561,"stream":597,"util":658}],337:[function(require,module,exports){
  54459. /*global module*/
  54460. var Buffer = require('buffer').Buffer;
  54461. module.exports = function toString(obj) {
  54462. if (typeof obj === 'string')
  54463. return obj;
  54464. if (typeof obj === 'number' || Buffer.isBuffer(obj))
  54465. return obj.toString();
  54466. return JSON.stringify(obj);
  54467. };
  54468. },{"buffer":193}],338:[function(require,module,exports){
  54469. /*global module*/
  54470. var Buffer = require('safe-buffer').Buffer;
  54471. var DataStream = require('./data-stream');
  54472. var jwa = require('jwa');
  54473. var Stream = require('stream');
  54474. var toString = require('./tostring');
  54475. var util = require('util');
  54476. var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
  54477. function isObject(thing) {
  54478. return Object.prototype.toString.call(thing) === '[object Object]';
  54479. }
  54480. function safeJsonParse(thing) {
  54481. if (isObject(thing))
  54482. return thing;
  54483. try { return JSON.parse(thing); }
  54484. catch (e) { return undefined; }
  54485. }
  54486. function headerFromJWS(jwsSig) {
  54487. var encodedHeader = jwsSig.split('.', 1)[0];
  54488. return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));
  54489. }
  54490. function securedInputFromJWS(jwsSig) {
  54491. return jwsSig.split('.', 2).join('.');
  54492. }
  54493. function signatureFromJWS(jwsSig) {
  54494. return jwsSig.split('.')[2];
  54495. }
  54496. function payloadFromJWS(jwsSig, encoding) {
  54497. encoding = encoding || 'utf8';
  54498. var payload = jwsSig.split('.')[1];
  54499. return Buffer.from(payload, 'base64').toString(encoding);
  54500. }
  54501. function isValidJws(string) {
  54502. return JWS_REGEX.test(string) && !!headerFromJWS(string);
  54503. }
  54504. function jwsVerify(jwsSig, algorithm, secretOrKey) {
  54505. if (!algorithm) {
  54506. var err = new Error("Missing algorithm parameter for jws.verify");
  54507. err.code = "MISSING_ALGORITHM";
  54508. throw err;
  54509. }
  54510. jwsSig = toString(jwsSig);
  54511. var signature = signatureFromJWS(jwsSig);
  54512. var securedInput = securedInputFromJWS(jwsSig);
  54513. var algo = jwa(algorithm);
  54514. return algo.verify(securedInput, signature, secretOrKey);
  54515. }
  54516. function jwsDecode(jwsSig, opts) {
  54517. opts = opts || {};
  54518. jwsSig = toString(jwsSig);
  54519. if (!isValidJws(jwsSig))
  54520. return null;
  54521. var header = headerFromJWS(jwsSig);
  54522. if (!header)
  54523. return null;
  54524. var payload = payloadFromJWS(jwsSig);
  54525. if (header.typ === 'JWT' || opts.json)
  54526. payload = JSON.parse(payload, opts.encoding);
  54527. return {
  54528. header: header,
  54529. payload: payload,
  54530. signature: signatureFromJWS(jwsSig)
  54531. };
  54532. }
  54533. function VerifyStream(opts) {
  54534. opts = opts || {};
  54535. var secretOrKey = opts.secret||opts.publicKey||opts.key;
  54536. var secretStream = new DataStream(secretOrKey);
  54537. this.readable = true;
  54538. this.algorithm = opts.algorithm;
  54539. this.encoding = opts.encoding;
  54540. this.secret = this.publicKey = this.key = secretStream;
  54541. this.signature = new DataStream(opts.signature);
  54542. this.secret.once('close', function () {
  54543. if (!this.signature.writable && this.readable)
  54544. this.verify();
  54545. }.bind(this));
  54546. this.signature.once('close', function () {
  54547. if (!this.secret.writable && this.readable)
  54548. this.verify();
  54549. }.bind(this));
  54550. }
  54551. util.inherits(VerifyStream, Stream);
  54552. VerifyStream.prototype.verify = function verify() {
  54553. try {
  54554. var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);
  54555. var obj = jwsDecode(this.signature.buffer, this.encoding);
  54556. this.emit('done', valid, obj);
  54557. this.emit('data', valid);
  54558. this.emit('end');
  54559. this.readable = false;
  54560. return valid;
  54561. } catch (e) {
  54562. this.readable = false;
  54563. this.emit('error', e);
  54564. this.emit('close');
  54565. }
  54566. };
  54567. VerifyStream.decode = jwsDecode;
  54568. VerifyStream.isValid = isValidJws;
  54569. VerifyStream.verify = jwsVerify;
  54570. module.exports = VerifyStream;
  54571. },{"./data-stream":335,"./tostring":337,"jwa":333,"safe-buffer":561,"stream":597,"util":658}],339:[function(require,module,exports){
  54572. 'use strict'
  54573. var inherits = require('inherits')
  54574. var HashBase = require('hash-base')
  54575. var Buffer = require('safe-buffer').Buffer
  54576. var ARRAY16 = new Array(16)
  54577. function MD5 () {
  54578. HashBase.call(this, 64)
  54579. // state
  54580. this._a = 0x67452301
  54581. this._b = 0xefcdab89
  54582. this._c = 0x98badcfe
  54583. this._d = 0x10325476
  54584. }
  54585. inherits(MD5, HashBase)
  54586. MD5.prototype._update = function () {
  54587. var M = ARRAY16
  54588. for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
  54589. var a = this._a
  54590. var b = this._b
  54591. var c = this._c
  54592. var d = this._d
  54593. a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
  54594. d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
  54595. c = fnF(c, d, a, b, M[2], 0x242070db, 17)
  54596. b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
  54597. a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
  54598. d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
  54599. c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
  54600. b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
  54601. a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
  54602. d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
  54603. c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
  54604. b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
  54605. a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
  54606. d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
  54607. c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
  54608. b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
  54609. a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
  54610. d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
  54611. c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
  54612. b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
  54613. a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
  54614. d = fnG(d, a, b, c, M[10], 0x02441453, 9)
  54615. c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
  54616. b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
  54617. a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
  54618. d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
  54619. c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
  54620. b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
  54621. a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
  54622. d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
  54623. c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
  54624. b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
  54625. a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
  54626. d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
  54627. c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
  54628. b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
  54629. a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
  54630. d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
  54631. c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
  54632. b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
  54633. a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
  54634. d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
  54635. c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
  54636. b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
  54637. a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
  54638. d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
  54639. c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
  54640. b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
  54641. a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
  54642. d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
  54643. c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
  54644. b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
  54645. a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
  54646. d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
  54647. c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
  54648. b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
  54649. a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
  54650. d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
  54651. c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
  54652. b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
  54653. a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
  54654. d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
  54655. c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
  54656. b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
  54657. this._a = (this._a + a) | 0
  54658. this._b = (this._b + b) | 0
  54659. this._c = (this._c + c) | 0
  54660. this._d = (this._d + d) | 0
  54661. }
  54662. MD5.prototype._digest = function () {
  54663. // create padding and handle blocks
  54664. this._block[this._blockOffset++] = 0x80
  54665. if (this._blockOffset > 56) {
  54666. this._block.fill(0, this._blockOffset, 64)
  54667. this._update()
  54668. this._blockOffset = 0
  54669. }
  54670. this._block.fill(0, this._blockOffset, 56)
  54671. this._block.writeUInt32LE(this._length[0], 56)
  54672. this._block.writeUInt32LE(this._length[1], 60)
  54673. this._update()
  54674. // produce result
  54675. var buffer = Buffer.allocUnsafe(16)
  54676. buffer.writeInt32LE(this._a, 0)
  54677. buffer.writeInt32LE(this._b, 4)
  54678. buffer.writeInt32LE(this._c, 8)
  54679. buffer.writeInt32LE(this._d, 12)
  54680. return buffer
  54681. }
  54682. function rotl (x, n) {
  54683. return (x << n) | (x >>> (32 - n))
  54684. }
  54685. function fnF (a, b, c, d, m, k, s) {
  54686. return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
  54687. }
  54688. function fnG (a, b, c, d, m, k, s) {
  54689. return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
  54690. }
  54691. function fnH (a, b, c, d, m, k, s) {
  54692. return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
  54693. }
  54694. function fnI (a, b, c, d, m, k, s) {
  54695. return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
  54696. }
  54697. module.exports = MD5
  54698. },{"hash-base":283,"inherits":320,"safe-buffer":561}],340:[function(require,module,exports){
  54699. var bn = require('bn.js');
  54700. var brorand = require('brorand');
  54701. function MillerRabin(rand) {
  54702. this.rand = rand || new brorand.Rand();
  54703. }
  54704. module.exports = MillerRabin;
  54705. MillerRabin.create = function create(rand) {
  54706. return new MillerRabin(rand);
  54707. };
  54708. MillerRabin.prototype._randbelow = function _randbelow(n) {
  54709. var len = n.bitLength();
  54710. var min_bytes = Math.ceil(len / 8);
  54711. // Generage random bytes until a number less than n is found.
  54712. // This ensures that 0..n-1 have an equal probability of being selected.
  54713. do
  54714. var a = new bn(this.rand.generate(min_bytes));
  54715. while (a.cmp(n) >= 0);
  54716. return a;
  54717. };
  54718. MillerRabin.prototype._randrange = function _randrange(start, stop) {
  54719. // Generate a random number greater than or equal to start and less than stop.
  54720. var size = stop.sub(start);
  54721. return start.add(this._randbelow(size));
  54722. };
  54723. MillerRabin.prototype.test = function test(n, k, cb) {
  54724. var len = n.bitLength();
  54725. var red = bn.mont(n);
  54726. var rone = new bn(1).toRed(red);
  54727. if (!k)
  54728. k = Math.max(1, (len / 48) | 0);
  54729. // Find d and s, (n - 1) = (2 ^ s) * d;
  54730. var n1 = n.subn(1);
  54731. for (var s = 0; !n1.testn(s); s++) {}
  54732. var d = n.shrn(s);
  54733. var rn1 = n1.toRed(red);
  54734. var prime = true;
  54735. for (; k > 0; k--) {
  54736. var a = this._randrange(new bn(2), n1);
  54737. if (cb)
  54738. cb(a);
  54739. var x = a.toRed(red).redPow(d);
  54740. if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
  54741. continue;
  54742. for (var i = 1; i < s; i++) {
  54743. x = x.redSqr();
  54744. if (x.cmp(rone) === 0)
  54745. return false;
  54746. if (x.cmp(rn1) === 0)
  54747. break;
  54748. }
  54749. if (i === s)
  54750. return false;
  54751. }
  54752. return prime;
  54753. };
  54754. MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
  54755. var len = n.bitLength();
  54756. var red = bn.mont(n);
  54757. var rone = new bn(1).toRed(red);
  54758. if (!k)
  54759. k = Math.max(1, (len / 48) | 0);
  54760. // Find d and s, (n - 1) = (2 ^ s) * d;
  54761. var n1 = n.subn(1);
  54762. for (var s = 0; !n1.testn(s); s++) {}
  54763. var d = n.shrn(s);
  54764. var rn1 = n1.toRed(red);
  54765. for (; k > 0; k--) {
  54766. var a = this._randrange(new bn(2), n1);
  54767. var g = n.gcd(a);
  54768. if (g.cmpn(1) !== 0)
  54769. return g;
  54770. var x = a.toRed(red).redPow(d);
  54771. if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
  54772. continue;
  54773. for (var i = 1; i < s; i++) {
  54774. x = x.redSqr();
  54775. if (x.cmp(rone) === 0)
  54776. return x.fromRed().subn(1).gcd(n);
  54777. if (x.cmp(rn1) === 0)
  54778. break;
  54779. }
  54780. if (i === s) {
  54781. x = x.redSqr();
  54782. return x.fromRed().subn(1).gcd(n);
  54783. }
  54784. }
  54785. return false;
  54786. };
  54787. },{"bn.js":341,"brorand":143}],341:[function(require,module,exports){
  54788. arguments[4][97][0].apply(exports,arguments)
  54789. },{"buffer":144,"dup":97}],342:[function(require,module,exports){
  54790. module.exports={
  54791. "application/1d-interleaved-parityfec": {
  54792. "source": "iana"
  54793. },
  54794. "application/3gpdash-qoe-report+xml": {
  54795. "source": "iana",
  54796. "charset": "UTF-8",
  54797. "compressible": true
  54798. },
  54799. "application/3gpp-ims+xml": {
  54800. "source": "iana",
  54801. "compressible": true
  54802. },
  54803. "application/a2l": {
  54804. "source": "iana"
  54805. },
  54806. "application/activemessage": {
  54807. "source": "iana"
  54808. },
  54809. "application/activity+json": {
  54810. "source": "iana",
  54811. "compressible": true
  54812. },
  54813. "application/alto-costmap+json": {
  54814. "source": "iana",
  54815. "compressible": true
  54816. },
  54817. "application/alto-costmapfilter+json": {
  54818. "source": "iana",
  54819. "compressible": true
  54820. },
  54821. "application/alto-directory+json": {
  54822. "source": "iana",
  54823. "compressible": true
  54824. },
  54825. "application/alto-endpointcost+json": {
  54826. "source": "iana",
  54827. "compressible": true
  54828. },
  54829. "application/alto-endpointcostparams+json": {
  54830. "source": "iana",
  54831. "compressible": true
  54832. },
  54833. "application/alto-endpointprop+json": {
  54834. "source": "iana",
  54835. "compressible": true
  54836. },
  54837. "application/alto-endpointpropparams+json": {
  54838. "source": "iana",
  54839. "compressible": true
  54840. },
  54841. "application/alto-error+json": {
  54842. "source": "iana",
  54843. "compressible": true
  54844. },
  54845. "application/alto-networkmap+json": {
  54846. "source": "iana",
  54847. "compressible": true
  54848. },
  54849. "application/alto-networkmapfilter+json": {
  54850. "source": "iana",
  54851. "compressible": true
  54852. },
  54853. "application/alto-updatestreamcontrol+json": {
  54854. "source": "iana",
  54855. "compressible": true
  54856. },
  54857. "application/alto-updatestreamparams+json": {
  54858. "source": "iana",
  54859. "compressible": true
  54860. },
  54861. "application/aml": {
  54862. "source": "iana"
  54863. },
  54864. "application/andrew-inset": {
  54865. "source": "iana",
  54866. "extensions": ["ez"]
  54867. },
  54868. "application/applefile": {
  54869. "source": "iana"
  54870. },
  54871. "application/applixware": {
  54872. "source": "apache",
  54873. "extensions": ["aw"]
  54874. },
  54875. "application/atf": {
  54876. "source": "iana"
  54877. },
  54878. "application/atfx": {
  54879. "source": "iana"
  54880. },
  54881. "application/atom+xml": {
  54882. "source": "iana",
  54883. "compressible": true,
  54884. "extensions": ["atom"]
  54885. },
  54886. "application/atomcat+xml": {
  54887. "source": "iana",
  54888. "compressible": true,
  54889. "extensions": ["atomcat"]
  54890. },
  54891. "application/atomdeleted+xml": {
  54892. "source": "iana",
  54893. "compressible": true,
  54894. "extensions": ["atomdeleted"]
  54895. },
  54896. "application/atomicmail": {
  54897. "source": "iana"
  54898. },
  54899. "application/atomsvc+xml": {
  54900. "source": "iana",
  54901. "compressible": true,
  54902. "extensions": ["atomsvc"]
  54903. },
  54904. "application/atsc-dwd+xml": {
  54905. "source": "iana",
  54906. "compressible": true,
  54907. "extensions": ["dwd"]
  54908. },
  54909. "application/atsc-dynamic-event-message": {
  54910. "source": "iana"
  54911. },
  54912. "application/atsc-held+xml": {
  54913. "source": "iana",
  54914. "compressible": true,
  54915. "extensions": ["held"]
  54916. },
  54917. "application/atsc-rdt+json": {
  54918. "source": "iana",
  54919. "compressible": true
  54920. },
  54921. "application/atsc-rsat+xml": {
  54922. "source": "iana",
  54923. "compressible": true,
  54924. "extensions": ["rsat"]
  54925. },
  54926. "application/atxml": {
  54927. "source": "iana"
  54928. },
  54929. "application/auth-policy+xml": {
  54930. "source": "iana",
  54931. "compressible": true
  54932. },
  54933. "application/bacnet-xdd+zip": {
  54934. "source": "iana",
  54935. "compressible": false
  54936. },
  54937. "application/batch-smtp": {
  54938. "source": "iana"
  54939. },
  54940. "application/bdoc": {
  54941. "compressible": false,
  54942. "extensions": ["bdoc"]
  54943. },
  54944. "application/beep+xml": {
  54945. "source": "iana",
  54946. "charset": "UTF-8",
  54947. "compressible": true
  54948. },
  54949. "application/calendar+json": {
  54950. "source": "iana",
  54951. "compressible": true
  54952. },
  54953. "application/calendar+xml": {
  54954. "source": "iana",
  54955. "compressible": true,
  54956. "extensions": ["xcs"]
  54957. },
  54958. "application/call-completion": {
  54959. "source": "iana"
  54960. },
  54961. "application/cals-1840": {
  54962. "source": "iana"
  54963. },
  54964. "application/cap+xml": {
  54965. "source": "iana",
  54966. "charset": "UTF-8",
  54967. "compressible": true
  54968. },
  54969. "application/cbor": {
  54970. "source": "iana"
  54971. },
  54972. "application/cbor-seq": {
  54973. "source": "iana"
  54974. },
  54975. "application/cccex": {
  54976. "source": "iana"
  54977. },
  54978. "application/ccmp+xml": {
  54979. "source": "iana",
  54980. "compressible": true
  54981. },
  54982. "application/ccxml+xml": {
  54983. "source": "iana",
  54984. "compressible": true,
  54985. "extensions": ["ccxml"]
  54986. },
  54987. "application/cdfx+xml": {
  54988. "source": "iana",
  54989. "compressible": true,
  54990. "extensions": ["cdfx"]
  54991. },
  54992. "application/cdmi-capability": {
  54993. "source": "iana",
  54994. "extensions": ["cdmia"]
  54995. },
  54996. "application/cdmi-container": {
  54997. "source": "iana",
  54998. "extensions": ["cdmic"]
  54999. },
  55000. "application/cdmi-domain": {
  55001. "source": "iana",
  55002. "extensions": ["cdmid"]
  55003. },
  55004. "application/cdmi-object": {
  55005. "source": "iana",
  55006. "extensions": ["cdmio"]
  55007. },
  55008. "application/cdmi-queue": {
  55009. "source": "iana",
  55010. "extensions": ["cdmiq"]
  55011. },
  55012. "application/cdni": {
  55013. "source": "iana"
  55014. },
  55015. "application/cea": {
  55016. "source": "iana"
  55017. },
  55018. "application/cea-2018+xml": {
  55019. "source": "iana",
  55020. "compressible": true
  55021. },
  55022. "application/cellml+xml": {
  55023. "source": "iana",
  55024. "compressible": true
  55025. },
  55026. "application/cfw": {
  55027. "source": "iana"
  55028. },
  55029. "application/clue+xml": {
  55030. "source": "iana",
  55031. "compressible": true
  55032. },
  55033. "application/clue_info+xml": {
  55034. "source": "iana",
  55035. "compressible": true
  55036. },
  55037. "application/cms": {
  55038. "source": "iana"
  55039. },
  55040. "application/cnrp+xml": {
  55041. "source": "iana",
  55042. "compressible": true
  55043. },
  55044. "application/coap-group+json": {
  55045. "source": "iana",
  55046. "compressible": true
  55047. },
  55048. "application/coap-payload": {
  55049. "source": "iana"
  55050. },
  55051. "application/commonground": {
  55052. "source": "iana"
  55053. },
  55054. "application/conference-info+xml": {
  55055. "source": "iana",
  55056. "compressible": true
  55057. },
  55058. "application/cose": {
  55059. "source": "iana"
  55060. },
  55061. "application/cose-key": {
  55062. "source": "iana"
  55063. },
  55064. "application/cose-key-set": {
  55065. "source": "iana"
  55066. },
  55067. "application/cpl+xml": {
  55068. "source": "iana",
  55069. "compressible": true
  55070. },
  55071. "application/csrattrs": {
  55072. "source": "iana"
  55073. },
  55074. "application/csta+xml": {
  55075. "source": "iana",
  55076. "compressible": true
  55077. },
  55078. "application/cstadata+xml": {
  55079. "source": "iana",
  55080. "compressible": true
  55081. },
  55082. "application/csvm+json": {
  55083. "source": "iana",
  55084. "compressible": true
  55085. },
  55086. "application/cu-seeme": {
  55087. "source": "apache",
  55088. "extensions": ["cu"]
  55089. },
  55090. "application/cwt": {
  55091. "source": "iana"
  55092. },
  55093. "application/cybercash": {
  55094. "source": "iana"
  55095. },
  55096. "application/dart": {
  55097. "compressible": true
  55098. },
  55099. "application/dash+xml": {
  55100. "source": "iana",
  55101. "compressible": true,
  55102. "extensions": ["mpd"]
  55103. },
  55104. "application/dashdelta": {
  55105. "source": "iana"
  55106. },
  55107. "application/davmount+xml": {
  55108. "source": "iana",
  55109. "compressible": true,
  55110. "extensions": ["davmount"]
  55111. },
  55112. "application/dca-rft": {
  55113. "source": "iana"
  55114. },
  55115. "application/dcd": {
  55116. "source": "iana"
  55117. },
  55118. "application/dec-dx": {
  55119. "source": "iana"
  55120. },
  55121. "application/dialog-info+xml": {
  55122. "source": "iana",
  55123. "compressible": true
  55124. },
  55125. "application/dicom": {
  55126. "source": "iana"
  55127. },
  55128. "application/dicom+json": {
  55129. "source": "iana",
  55130. "compressible": true
  55131. },
  55132. "application/dicom+xml": {
  55133. "source": "iana",
  55134. "compressible": true
  55135. },
  55136. "application/dii": {
  55137. "source": "iana"
  55138. },
  55139. "application/dit": {
  55140. "source": "iana"
  55141. },
  55142. "application/dns": {
  55143. "source": "iana"
  55144. },
  55145. "application/dns+json": {
  55146. "source": "iana",
  55147. "compressible": true
  55148. },
  55149. "application/dns-message": {
  55150. "source": "iana"
  55151. },
  55152. "application/docbook+xml": {
  55153. "source": "apache",
  55154. "compressible": true,
  55155. "extensions": ["dbk"]
  55156. },
  55157. "application/dots+cbor": {
  55158. "source": "iana"
  55159. },
  55160. "application/dskpp+xml": {
  55161. "source": "iana",
  55162. "compressible": true
  55163. },
  55164. "application/dssc+der": {
  55165. "source": "iana",
  55166. "extensions": ["dssc"]
  55167. },
  55168. "application/dssc+xml": {
  55169. "source": "iana",
  55170. "compressible": true,
  55171. "extensions": ["xdssc"]
  55172. },
  55173. "application/dvcs": {
  55174. "source": "iana"
  55175. },
  55176. "application/ecmascript": {
  55177. "source": "iana",
  55178. "compressible": true,
  55179. "extensions": ["ecma","es"]
  55180. },
  55181. "application/edi-consent": {
  55182. "source": "iana"
  55183. },
  55184. "application/edi-x12": {
  55185. "source": "iana",
  55186. "compressible": false
  55187. },
  55188. "application/edifact": {
  55189. "source": "iana",
  55190. "compressible": false
  55191. },
  55192. "application/efi": {
  55193. "source": "iana"
  55194. },
  55195. "application/emergencycalldata.comment+xml": {
  55196. "source": "iana",
  55197. "compressible": true
  55198. },
  55199. "application/emergencycalldata.control+xml": {
  55200. "source": "iana",
  55201. "compressible": true
  55202. },
  55203. "application/emergencycalldata.deviceinfo+xml": {
  55204. "source": "iana",
  55205. "compressible": true
  55206. },
  55207. "application/emergencycalldata.ecall.msd": {
  55208. "source": "iana"
  55209. },
  55210. "application/emergencycalldata.providerinfo+xml": {
  55211. "source": "iana",
  55212. "compressible": true
  55213. },
  55214. "application/emergencycalldata.serviceinfo+xml": {
  55215. "source": "iana",
  55216. "compressible": true
  55217. },
  55218. "application/emergencycalldata.subscriberinfo+xml": {
  55219. "source": "iana",
  55220. "compressible": true
  55221. },
  55222. "application/emergencycalldata.veds+xml": {
  55223. "source": "iana",
  55224. "compressible": true
  55225. },
  55226. "application/emma+xml": {
  55227. "source": "iana",
  55228. "compressible": true,
  55229. "extensions": ["emma"]
  55230. },
  55231. "application/emotionml+xml": {
  55232. "source": "iana",
  55233. "compressible": true,
  55234. "extensions": ["emotionml"]
  55235. },
  55236. "application/encaprtp": {
  55237. "source": "iana"
  55238. },
  55239. "application/epp+xml": {
  55240. "source": "iana",
  55241. "compressible": true
  55242. },
  55243. "application/epub+zip": {
  55244. "source": "iana",
  55245. "compressible": false,
  55246. "extensions": ["epub"]
  55247. },
  55248. "application/eshop": {
  55249. "source": "iana"
  55250. },
  55251. "application/exi": {
  55252. "source": "iana",
  55253. "extensions": ["exi"]
  55254. },
  55255. "application/expect-ct-report+json": {
  55256. "source": "iana",
  55257. "compressible": true
  55258. },
  55259. "application/fastinfoset": {
  55260. "source": "iana"
  55261. },
  55262. "application/fastsoap": {
  55263. "source": "iana"
  55264. },
  55265. "application/fdt+xml": {
  55266. "source": "iana",
  55267. "compressible": true,
  55268. "extensions": ["fdt"]
  55269. },
  55270. "application/fhir+json": {
  55271. "source": "iana",
  55272. "charset": "UTF-8",
  55273. "compressible": true
  55274. },
  55275. "application/fhir+xml": {
  55276. "source": "iana",
  55277. "charset": "UTF-8",
  55278. "compressible": true
  55279. },
  55280. "application/fido.trusted-apps+json": {
  55281. "compressible": true
  55282. },
  55283. "application/fits": {
  55284. "source": "iana"
  55285. },
  55286. "application/flexfec": {
  55287. "source": "iana"
  55288. },
  55289. "application/font-sfnt": {
  55290. "source": "iana"
  55291. },
  55292. "application/font-tdpfr": {
  55293. "source": "iana",
  55294. "extensions": ["pfr"]
  55295. },
  55296. "application/font-woff": {
  55297. "source": "iana",
  55298. "compressible": false
  55299. },
  55300. "application/framework-attributes+xml": {
  55301. "source": "iana",
  55302. "compressible": true
  55303. },
  55304. "application/geo+json": {
  55305. "source": "iana",
  55306. "compressible": true,
  55307. "extensions": ["geojson"]
  55308. },
  55309. "application/geo+json-seq": {
  55310. "source": "iana"
  55311. },
  55312. "application/geopackage+sqlite3": {
  55313. "source": "iana"
  55314. },
  55315. "application/geoxacml+xml": {
  55316. "source": "iana",
  55317. "compressible": true
  55318. },
  55319. "application/gltf-buffer": {
  55320. "source": "iana"
  55321. },
  55322. "application/gml+xml": {
  55323. "source": "iana",
  55324. "compressible": true,
  55325. "extensions": ["gml"]
  55326. },
  55327. "application/gpx+xml": {
  55328. "source": "apache",
  55329. "compressible": true,
  55330. "extensions": ["gpx"]
  55331. },
  55332. "application/gxf": {
  55333. "source": "apache",
  55334. "extensions": ["gxf"]
  55335. },
  55336. "application/gzip": {
  55337. "source": "iana",
  55338. "compressible": false,
  55339. "extensions": ["gz"]
  55340. },
  55341. "application/h224": {
  55342. "source": "iana"
  55343. },
  55344. "application/held+xml": {
  55345. "source": "iana",
  55346. "compressible": true
  55347. },
  55348. "application/hjson": {
  55349. "extensions": ["hjson"]
  55350. },
  55351. "application/http": {
  55352. "source": "iana"
  55353. },
  55354. "application/hyperstudio": {
  55355. "source": "iana",
  55356. "extensions": ["stk"]
  55357. },
  55358. "application/ibe-key-request+xml": {
  55359. "source": "iana",
  55360. "compressible": true
  55361. },
  55362. "application/ibe-pkg-reply+xml": {
  55363. "source": "iana",
  55364. "compressible": true
  55365. },
  55366. "application/ibe-pp-data": {
  55367. "source": "iana"
  55368. },
  55369. "application/iges": {
  55370. "source": "iana"
  55371. },
  55372. "application/im-iscomposing+xml": {
  55373. "source": "iana",
  55374. "charset": "UTF-8",
  55375. "compressible": true
  55376. },
  55377. "application/index": {
  55378. "source": "iana"
  55379. },
  55380. "application/index.cmd": {
  55381. "source": "iana"
  55382. },
  55383. "application/index.obj": {
  55384. "source": "iana"
  55385. },
  55386. "application/index.response": {
  55387. "source": "iana"
  55388. },
  55389. "application/index.vnd": {
  55390. "source": "iana"
  55391. },
  55392. "application/inkml+xml": {
  55393. "source": "iana",
  55394. "compressible": true,
  55395. "extensions": ["ink","inkml"]
  55396. },
  55397. "application/iotp": {
  55398. "source": "iana"
  55399. },
  55400. "application/ipfix": {
  55401. "source": "iana",
  55402. "extensions": ["ipfix"]
  55403. },
  55404. "application/ipp": {
  55405. "source": "iana"
  55406. },
  55407. "application/isup": {
  55408. "source": "iana"
  55409. },
  55410. "application/its+xml": {
  55411. "source": "iana",
  55412. "compressible": true,
  55413. "extensions": ["its"]
  55414. },
  55415. "application/java-archive": {
  55416. "source": "apache",
  55417. "compressible": false,
  55418. "extensions": ["jar","war","ear"]
  55419. },
  55420. "application/java-serialized-object": {
  55421. "source": "apache",
  55422. "compressible": false,
  55423. "extensions": ["ser"]
  55424. },
  55425. "application/java-vm": {
  55426. "source": "apache",
  55427. "compressible": false,
  55428. "extensions": ["class"]
  55429. },
  55430. "application/javascript": {
  55431. "source": "iana",
  55432. "charset": "UTF-8",
  55433. "compressible": true,
  55434. "extensions": ["js","mjs"]
  55435. },
  55436. "application/jf2feed+json": {
  55437. "source": "iana",
  55438. "compressible": true
  55439. },
  55440. "application/jose": {
  55441. "source": "iana"
  55442. },
  55443. "application/jose+json": {
  55444. "source": "iana",
  55445. "compressible": true
  55446. },
  55447. "application/jrd+json": {
  55448. "source": "iana",
  55449. "compressible": true
  55450. },
  55451. "application/json": {
  55452. "source": "iana",
  55453. "charset": "UTF-8",
  55454. "compressible": true,
  55455. "extensions": ["json","map"]
  55456. },
  55457. "application/json-patch+json": {
  55458. "source": "iana",
  55459. "compressible": true
  55460. },
  55461. "application/json-seq": {
  55462. "source": "iana"
  55463. },
  55464. "application/json5": {
  55465. "extensions": ["json5"]
  55466. },
  55467. "application/jsonml+json": {
  55468. "source": "apache",
  55469. "compressible": true,
  55470. "extensions": ["jsonml"]
  55471. },
  55472. "application/jwk+json": {
  55473. "source": "iana",
  55474. "compressible": true
  55475. },
  55476. "application/jwk-set+json": {
  55477. "source": "iana",
  55478. "compressible": true
  55479. },
  55480. "application/jwt": {
  55481. "source": "iana"
  55482. },
  55483. "application/kpml-request+xml": {
  55484. "source": "iana",
  55485. "compressible": true
  55486. },
  55487. "application/kpml-response+xml": {
  55488. "source": "iana",
  55489. "compressible": true
  55490. },
  55491. "application/ld+json": {
  55492. "source": "iana",
  55493. "compressible": true,
  55494. "extensions": ["jsonld"]
  55495. },
  55496. "application/lgr+xml": {
  55497. "source": "iana",
  55498. "compressible": true,
  55499. "extensions": ["lgr"]
  55500. },
  55501. "application/link-format": {
  55502. "source": "iana"
  55503. },
  55504. "application/load-control+xml": {
  55505. "source": "iana",
  55506. "compressible": true
  55507. },
  55508. "application/lost+xml": {
  55509. "source": "iana",
  55510. "compressible": true,
  55511. "extensions": ["lostxml"]
  55512. },
  55513. "application/lostsync+xml": {
  55514. "source": "iana",
  55515. "compressible": true
  55516. },
  55517. "application/lpf+zip": {
  55518. "source": "iana",
  55519. "compressible": false
  55520. },
  55521. "application/lxf": {
  55522. "source": "iana"
  55523. },
  55524. "application/mac-binhex40": {
  55525. "source": "iana",
  55526. "extensions": ["hqx"]
  55527. },
  55528. "application/mac-compactpro": {
  55529. "source": "apache",
  55530. "extensions": ["cpt"]
  55531. },
  55532. "application/macwriteii": {
  55533. "source": "iana"
  55534. },
  55535. "application/mads+xml": {
  55536. "source": "iana",
  55537. "compressible": true,
  55538. "extensions": ["mads"]
  55539. },
  55540. "application/manifest+json": {
  55541. "charset": "UTF-8",
  55542. "compressible": true,
  55543. "extensions": ["webmanifest"]
  55544. },
  55545. "application/marc": {
  55546. "source": "iana",
  55547. "extensions": ["mrc"]
  55548. },
  55549. "application/marcxml+xml": {
  55550. "source": "iana",
  55551. "compressible": true,
  55552. "extensions": ["mrcx"]
  55553. },
  55554. "application/mathematica": {
  55555. "source": "iana",
  55556. "extensions": ["ma","nb","mb"]
  55557. },
  55558. "application/mathml+xml": {
  55559. "source": "iana",
  55560. "compressible": true,
  55561. "extensions": ["mathml"]
  55562. },
  55563. "application/mathml-content+xml": {
  55564. "source": "iana",
  55565. "compressible": true
  55566. },
  55567. "application/mathml-presentation+xml": {
  55568. "source": "iana",
  55569. "compressible": true
  55570. },
  55571. "application/mbms-associated-procedure-description+xml": {
  55572. "source": "iana",
  55573. "compressible": true
  55574. },
  55575. "application/mbms-deregister+xml": {
  55576. "source": "iana",
  55577. "compressible": true
  55578. },
  55579. "application/mbms-envelope+xml": {
  55580. "source": "iana",
  55581. "compressible": true
  55582. },
  55583. "application/mbms-msk+xml": {
  55584. "source": "iana",
  55585. "compressible": true
  55586. },
  55587. "application/mbms-msk-response+xml": {
  55588. "source": "iana",
  55589. "compressible": true
  55590. },
  55591. "application/mbms-protection-description+xml": {
  55592. "source": "iana",
  55593. "compressible": true
  55594. },
  55595. "application/mbms-reception-report+xml": {
  55596. "source": "iana",
  55597. "compressible": true
  55598. },
  55599. "application/mbms-register+xml": {
  55600. "source": "iana",
  55601. "compressible": true
  55602. },
  55603. "application/mbms-register-response+xml": {
  55604. "source": "iana",
  55605. "compressible": true
  55606. },
  55607. "application/mbms-schedule+xml": {
  55608. "source": "iana",
  55609. "compressible": true
  55610. },
  55611. "application/mbms-user-service-description+xml": {
  55612. "source": "iana",
  55613. "compressible": true
  55614. },
  55615. "application/mbox": {
  55616. "source": "iana",
  55617. "extensions": ["mbox"]
  55618. },
  55619. "application/media-policy-dataset+xml": {
  55620. "source": "iana",
  55621. "compressible": true
  55622. },
  55623. "application/media_control+xml": {
  55624. "source": "iana",
  55625. "compressible": true
  55626. },
  55627. "application/mediaservercontrol+xml": {
  55628. "source": "iana",
  55629. "compressible": true,
  55630. "extensions": ["mscml"]
  55631. },
  55632. "application/merge-patch+json": {
  55633. "source": "iana",
  55634. "compressible": true
  55635. },
  55636. "application/metalink+xml": {
  55637. "source": "apache",
  55638. "compressible": true,
  55639. "extensions": ["metalink"]
  55640. },
  55641. "application/metalink4+xml": {
  55642. "source": "iana",
  55643. "compressible": true,
  55644. "extensions": ["meta4"]
  55645. },
  55646. "application/mets+xml": {
  55647. "source": "iana",
  55648. "compressible": true,
  55649. "extensions": ["mets"]
  55650. },
  55651. "application/mf4": {
  55652. "source": "iana"
  55653. },
  55654. "application/mikey": {
  55655. "source": "iana"
  55656. },
  55657. "application/mipc": {
  55658. "source": "iana"
  55659. },
  55660. "application/mmt-aei+xml": {
  55661. "source": "iana",
  55662. "compressible": true,
  55663. "extensions": ["maei"]
  55664. },
  55665. "application/mmt-usd+xml": {
  55666. "source": "iana",
  55667. "compressible": true,
  55668. "extensions": ["musd"]
  55669. },
  55670. "application/mods+xml": {
  55671. "source": "iana",
  55672. "compressible": true,
  55673. "extensions": ["mods"]
  55674. },
  55675. "application/moss-keys": {
  55676. "source": "iana"
  55677. },
  55678. "application/moss-signature": {
  55679. "source": "iana"
  55680. },
  55681. "application/mosskey-data": {
  55682. "source": "iana"
  55683. },
  55684. "application/mosskey-request": {
  55685. "source": "iana"
  55686. },
  55687. "application/mp21": {
  55688. "source": "iana",
  55689. "extensions": ["m21","mp21"]
  55690. },
  55691. "application/mp4": {
  55692. "source": "iana",
  55693. "extensions": ["mp4s","m4p"]
  55694. },
  55695. "application/mpeg4-generic": {
  55696. "source": "iana"
  55697. },
  55698. "application/mpeg4-iod": {
  55699. "source": "iana"
  55700. },
  55701. "application/mpeg4-iod-xmt": {
  55702. "source": "iana"
  55703. },
  55704. "application/mrb-consumer+xml": {
  55705. "source": "iana",
  55706. "compressible": true,
  55707. "extensions": ["xdf"]
  55708. },
  55709. "application/mrb-publish+xml": {
  55710. "source": "iana",
  55711. "compressible": true,
  55712. "extensions": ["xdf"]
  55713. },
  55714. "application/msc-ivr+xml": {
  55715. "source": "iana",
  55716. "charset": "UTF-8",
  55717. "compressible": true
  55718. },
  55719. "application/msc-mixer+xml": {
  55720. "source": "iana",
  55721. "charset": "UTF-8",
  55722. "compressible": true
  55723. },
  55724. "application/msword": {
  55725. "source": "iana",
  55726. "compressible": false,
  55727. "extensions": ["doc","dot"]
  55728. },
  55729. "application/mud+json": {
  55730. "source": "iana",
  55731. "compressible": true
  55732. },
  55733. "application/multipart-core": {
  55734. "source": "iana"
  55735. },
  55736. "application/mxf": {
  55737. "source": "iana",
  55738. "extensions": ["mxf"]
  55739. },
  55740. "application/n-quads": {
  55741. "source": "iana",
  55742. "extensions": ["nq"]
  55743. },
  55744. "application/n-triples": {
  55745. "source": "iana",
  55746. "extensions": ["nt"]
  55747. },
  55748. "application/nasdata": {
  55749. "source": "iana"
  55750. },
  55751. "application/news-checkgroups": {
  55752. "source": "iana",
  55753. "charset": "US-ASCII"
  55754. },
  55755. "application/news-groupinfo": {
  55756. "source": "iana",
  55757. "charset": "US-ASCII"
  55758. },
  55759. "application/news-transmission": {
  55760. "source": "iana"
  55761. },
  55762. "application/nlsml+xml": {
  55763. "source": "iana",
  55764. "compressible": true
  55765. },
  55766. "application/node": {
  55767. "source": "iana",
  55768. "extensions": ["cjs"]
  55769. },
  55770. "application/nss": {
  55771. "source": "iana"
  55772. },
  55773. "application/ocsp-request": {
  55774. "source": "iana"
  55775. },
  55776. "application/ocsp-response": {
  55777. "source": "iana"
  55778. },
  55779. "application/octet-stream": {
  55780. "source": "iana",
  55781. "compressible": false,
  55782. "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]
  55783. },
  55784. "application/oda": {
  55785. "source": "iana",
  55786. "extensions": ["oda"]
  55787. },
  55788. "application/odm+xml": {
  55789. "source": "iana",
  55790. "compressible": true
  55791. },
  55792. "application/odx": {
  55793. "source": "iana"
  55794. },
  55795. "application/oebps-package+xml": {
  55796. "source": "iana",
  55797. "compressible": true,
  55798. "extensions": ["opf"]
  55799. },
  55800. "application/ogg": {
  55801. "source": "iana",
  55802. "compressible": false,
  55803. "extensions": ["ogx"]
  55804. },
  55805. "application/omdoc+xml": {
  55806. "source": "apache",
  55807. "compressible": true,
  55808. "extensions": ["omdoc"]
  55809. },
  55810. "application/onenote": {
  55811. "source": "apache",
  55812. "extensions": ["onetoc","onetoc2","onetmp","onepkg"]
  55813. },
  55814. "application/oscore": {
  55815. "source": "iana"
  55816. },
  55817. "application/oxps": {
  55818. "source": "iana",
  55819. "extensions": ["oxps"]
  55820. },
  55821. "application/p2p-overlay+xml": {
  55822. "source": "iana",
  55823. "compressible": true,
  55824. "extensions": ["relo"]
  55825. },
  55826. "application/parityfec": {
  55827. "source": "iana"
  55828. },
  55829. "application/passport": {
  55830. "source": "iana"
  55831. },
  55832. "application/patch-ops-error+xml": {
  55833. "source": "iana",
  55834. "compressible": true,
  55835. "extensions": ["xer"]
  55836. },
  55837. "application/pdf": {
  55838. "source": "iana",
  55839. "compressible": false,
  55840. "extensions": ["pdf"]
  55841. },
  55842. "application/pdx": {
  55843. "source": "iana"
  55844. },
  55845. "application/pem-certificate-chain": {
  55846. "source": "iana"
  55847. },
  55848. "application/pgp-encrypted": {
  55849. "source": "iana",
  55850. "compressible": false,
  55851. "extensions": ["pgp"]
  55852. },
  55853. "application/pgp-keys": {
  55854. "source": "iana"
  55855. },
  55856. "application/pgp-signature": {
  55857. "source": "iana",
  55858. "extensions": ["asc","sig"]
  55859. },
  55860. "application/pics-rules": {
  55861. "source": "apache",
  55862. "extensions": ["prf"]
  55863. },
  55864. "application/pidf+xml": {
  55865. "source": "iana",
  55866. "charset": "UTF-8",
  55867. "compressible": true
  55868. },
  55869. "application/pidf-diff+xml": {
  55870. "source": "iana",
  55871. "charset": "UTF-8",
  55872. "compressible": true
  55873. },
  55874. "application/pkcs10": {
  55875. "source": "iana",
  55876. "extensions": ["p10"]
  55877. },
  55878. "application/pkcs12": {
  55879. "source": "iana"
  55880. },
  55881. "application/pkcs7-mime": {
  55882. "source": "iana",
  55883. "extensions": ["p7m","p7c"]
  55884. },
  55885. "application/pkcs7-signature": {
  55886. "source": "iana",
  55887. "extensions": ["p7s"]
  55888. },
  55889. "application/pkcs8": {
  55890. "source": "iana",
  55891. "extensions": ["p8"]
  55892. },
  55893. "application/pkcs8-encrypted": {
  55894. "source": "iana"
  55895. },
  55896. "application/pkix-attr-cert": {
  55897. "source": "iana",
  55898. "extensions": ["ac"]
  55899. },
  55900. "application/pkix-cert": {
  55901. "source": "iana",
  55902. "extensions": ["cer"]
  55903. },
  55904. "application/pkix-crl": {
  55905. "source": "iana",
  55906. "extensions": ["crl"]
  55907. },
  55908. "application/pkix-pkipath": {
  55909. "source": "iana",
  55910. "extensions": ["pkipath"]
  55911. },
  55912. "application/pkixcmp": {
  55913. "source": "iana",
  55914. "extensions": ["pki"]
  55915. },
  55916. "application/pls+xml": {
  55917. "source": "iana",
  55918. "compressible": true,
  55919. "extensions": ["pls"]
  55920. },
  55921. "application/poc-settings+xml": {
  55922. "source": "iana",
  55923. "charset": "UTF-8",
  55924. "compressible": true
  55925. },
  55926. "application/postscript": {
  55927. "source": "iana",
  55928. "compressible": true,
  55929. "extensions": ["ai","eps","ps"]
  55930. },
  55931. "application/ppsp-tracker+json": {
  55932. "source": "iana",
  55933. "compressible": true
  55934. },
  55935. "application/problem+json": {
  55936. "source": "iana",
  55937. "compressible": true
  55938. },
  55939. "application/problem+xml": {
  55940. "source": "iana",
  55941. "compressible": true
  55942. },
  55943. "application/provenance+xml": {
  55944. "source": "iana",
  55945. "compressible": true,
  55946. "extensions": ["provx"]
  55947. },
  55948. "application/prs.alvestrand.titrax-sheet": {
  55949. "source": "iana"
  55950. },
  55951. "application/prs.cww": {
  55952. "source": "iana",
  55953. "extensions": ["cww"]
  55954. },
  55955. "application/prs.hpub+zip": {
  55956. "source": "iana",
  55957. "compressible": false
  55958. },
  55959. "application/prs.nprend": {
  55960. "source": "iana"
  55961. },
  55962. "application/prs.plucker": {
  55963. "source": "iana"
  55964. },
  55965. "application/prs.rdf-xml-crypt": {
  55966. "source": "iana"
  55967. },
  55968. "application/prs.xsf+xml": {
  55969. "source": "iana",
  55970. "compressible": true
  55971. },
  55972. "application/pskc+xml": {
  55973. "source": "iana",
  55974. "compressible": true,
  55975. "extensions": ["pskcxml"]
  55976. },
  55977. "application/pvd+json": {
  55978. "source": "iana",
  55979. "compressible": true
  55980. },
  55981. "application/qsig": {
  55982. "source": "iana"
  55983. },
  55984. "application/raml+yaml": {
  55985. "compressible": true,
  55986. "extensions": ["raml"]
  55987. },
  55988. "application/raptorfec": {
  55989. "source": "iana"
  55990. },
  55991. "application/rdap+json": {
  55992. "source": "iana",
  55993. "compressible": true
  55994. },
  55995. "application/rdf+xml": {
  55996. "source": "iana",
  55997. "compressible": true,
  55998. "extensions": ["rdf","owl"]
  55999. },
  56000. "application/reginfo+xml": {
  56001. "source": "iana",
  56002. "compressible": true,
  56003. "extensions": ["rif"]
  56004. },
  56005. "application/relax-ng-compact-syntax": {
  56006. "source": "iana",
  56007. "extensions": ["rnc"]
  56008. },
  56009. "application/remote-printing": {
  56010. "source": "iana"
  56011. },
  56012. "application/reputon+json": {
  56013. "source": "iana",
  56014. "compressible": true
  56015. },
  56016. "application/resource-lists+xml": {
  56017. "source": "iana",
  56018. "compressible": true,
  56019. "extensions": ["rl"]
  56020. },
  56021. "application/resource-lists-diff+xml": {
  56022. "source": "iana",
  56023. "compressible": true,
  56024. "extensions": ["rld"]
  56025. },
  56026. "application/rfc+xml": {
  56027. "source": "iana",
  56028. "compressible": true
  56029. },
  56030. "application/riscos": {
  56031. "source": "iana"
  56032. },
  56033. "application/rlmi+xml": {
  56034. "source": "iana",
  56035. "compressible": true
  56036. },
  56037. "application/rls-services+xml": {
  56038. "source": "iana",
  56039. "compressible": true,
  56040. "extensions": ["rs"]
  56041. },
  56042. "application/route-apd+xml": {
  56043. "source": "iana",
  56044. "compressible": true,
  56045. "extensions": ["rapd"]
  56046. },
  56047. "application/route-s-tsid+xml": {
  56048. "source": "iana",
  56049. "compressible": true,
  56050. "extensions": ["sls"]
  56051. },
  56052. "application/route-usd+xml": {
  56053. "source": "iana",
  56054. "compressible": true,
  56055. "extensions": ["rusd"]
  56056. },
  56057. "application/rpki-ghostbusters": {
  56058. "source": "iana",
  56059. "extensions": ["gbr"]
  56060. },
  56061. "application/rpki-manifest": {
  56062. "source": "iana",
  56063. "extensions": ["mft"]
  56064. },
  56065. "application/rpki-publication": {
  56066. "source": "iana"
  56067. },
  56068. "application/rpki-roa": {
  56069. "source": "iana",
  56070. "extensions": ["roa"]
  56071. },
  56072. "application/rpki-updown": {
  56073. "source": "iana"
  56074. },
  56075. "application/rsd+xml": {
  56076. "source": "apache",
  56077. "compressible": true,
  56078. "extensions": ["rsd"]
  56079. },
  56080. "application/rss+xml": {
  56081. "source": "apache",
  56082. "compressible": true,
  56083. "extensions": ["rss"]
  56084. },
  56085. "application/rtf": {
  56086. "source": "iana",
  56087. "compressible": true,
  56088. "extensions": ["rtf"]
  56089. },
  56090. "application/rtploopback": {
  56091. "source": "iana"
  56092. },
  56093. "application/rtx": {
  56094. "source": "iana"
  56095. },
  56096. "application/samlassertion+xml": {
  56097. "source": "iana",
  56098. "compressible": true
  56099. },
  56100. "application/samlmetadata+xml": {
  56101. "source": "iana",
  56102. "compressible": true
  56103. },
  56104. "application/sbe": {
  56105. "source": "iana"
  56106. },
  56107. "application/sbml+xml": {
  56108. "source": "iana",
  56109. "compressible": true,
  56110. "extensions": ["sbml"]
  56111. },
  56112. "application/scaip+xml": {
  56113. "source": "iana",
  56114. "compressible": true
  56115. },
  56116. "application/scim+json": {
  56117. "source": "iana",
  56118. "compressible": true
  56119. },
  56120. "application/scvp-cv-request": {
  56121. "source": "iana",
  56122. "extensions": ["scq"]
  56123. },
  56124. "application/scvp-cv-response": {
  56125. "source": "iana",
  56126. "extensions": ["scs"]
  56127. },
  56128. "application/scvp-vp-request": {
  56129. "source": "iana",
  56130. "extensions": ["spq"]
  56131. },
  56132. "application/scvp-vp-response": {
  56133. "source": "iana",
  56134. "extensions": ["spp"]
  56135. },
  56136. "application/sdp": {
  56137. "source": "iana",
  56138. "extensions": ["sdp"]
  56139. },
  56140. "application/secevent+jwt": {
  56141. "source": "iana"
  56142. },
  56143. "application/senml+cbor": {
  56144. "source": "iana"
  56145. },
  56146. "application/senml+json": {
  56147. "source": "iana",
  56148. "compressible": true
  56149. },
  56150. "application/senml+xml": {
  56151. "source": "iana",
  56152. "compressible": true,
  56153. "extensions": ["senmlx"]
  56154. },
  56155. "application/senml-etch+cbor": {
  56156. "source": "iana"
  56157. },
  56158. "application/senml-etch+json": {
  56159. "source": "iana",
  56160. "compressible": true
  56161. },
  56162. "application/senml-exi": {
  56163. "source": "iana"
  56164. },
  56165. "application/sensml+cbor": {
  56166. "source": "iana"
  56167. },
  56168. "application/sensml+json": {
  56169. "source": "iana",
  56170. "compressible": true
  56171. },
  56172. "application/sensml+xml": {
  56173. "source": "iana",
  56174. "compressible": true,
  56175. "extensions": ["sensmlx"]
  56176. },
  56177. "application/sensml-exi": {
  56178. "source": "iana"
  56179. },
  56180. "application/sep+xml": {
  56181. "source": "iana",
  56182. "compressible": true
  56183. },
  56184. "application/sep-exi": {
  56185. "source": "iana"
  56186. },
  56187. "application/session-info": {
  56188. "source": "iana"
  56189. },
  56190. "application/set-payment": {
  56191. "source": "iana"
  56192. },
  56193. "application/set-payment-initiation": {
  56194. "source": "iana",
  56195. "extensions": ["setpay"]
  56196. },
  56197. "application/set-registration": {
  56198. "source": "iana"
  56199. },
  56200. "application/set-registration-initiation": {
  56201. "source": "iana",
  56202. "extensions": ["setreg"]
  56203. },
  56204. "application/sgml": {
  56205. "source": "iana"
  56206. },
  56207. "application/sgml-open-catalog": {
  56208. "source": "iana"
  56209. },
  56210. "application/shf+xml": {
  56211. "source": "iana",
  56212. "compressible": true,
  56213. "extensions": ["shf"]
  56214. },
  56215. "application/sieve": {
  56216. "source": "iana",
  56217. "extensions": ["siv","sieve"]
  56218. },
  56219. "application/simple-filter+xml": {
  56220. "source": "iana",
  56221. "compressible": true
  56222. },
  56223. "application/simple-message-summary": {
  56224. "source": "iana"
  56225. },
  56226. "application/simplesymbolcontainer": {
  56227. "source": "iana"
  56228. },
  56229. "application/sipc": {
  56230. "source": "iana"
  56231. },
  56232. "application/slate": {
  56233. "source": "iana"
  56234. },
  56235. "application/smil": {
  56236. "source": "iana"
  56237. },
  56238. "application/smil+xml": {
  56239. "source": "iana",
  56240. "compressible": true,
  56241. "extensions": ["smi","smil"]
  56242. },
  56243. "application/smpte336m": {
  56244. "source": "iana"
  56245. },
  56246. "application/soap+fastinfoset": {
  56247. "source": "iana"
  56248. },
  56249. "application/soap+xml": {
  56250. "source": "iana",
  56251. "compressible": true
  56252. },
  56253. "application/sparql-query": {
  56254. "source": "iana",
  56255. "extensions": ["rq"]
  56256. },
  56257. "application/sparql-results+xml": {
  56258. "source": "iana",
  56259. "compressible": true,
  56260. "extensions": ["srx"]
  56261. },
  56262. "application/spirits-event+xml": {
  56263. "source": "iana",
  56264. "compressible": true
  56265. },
  56266. "application/sql": {
  56267. "source": "iana"
  56268. },
  56269. "application/srgs": {
  56270. "source": "iana",
  56271. "extensions": ["gram"]
  56272. },
  56273. "application/srgs+xml": {
  56274. "source": "iana",
  56275. "compressible": true,
  56276. "extensions": ["grxml"]
  56277. },
  56278. "application/sru+xml": {
  56279. "source": "iana",
  56280. "compressible": true,
  56281. "extensions": ["sru"]
  56282. },
  56283. "application/ssdl+xml": {
  56284. "source": "apache",
  56285. "compressible": true,
  56286. "extensions": ["ssdl"]
  56287. },
  56288. "application/ssml+xml": {
  56289. "source": "iana",
  56290. "compressible": true,
  56291. "extensions": ["ssml"]
  56292. },
  56293. "application/stix+json": {
  56294. "source": "iana",
  56295. "compressible": true
  56296. },
  56297. "application/swid+xml": {
  56298. "source": "iana",
  56299. "compressible": true,
  56300. "extensions": ["swidtag"]
  56301. },
  56302. "application/tamp-apex-update": {
  56303. "source": "iana"
  56304. },
  56305. "application/tamp-apex-update-confirm": {
  56306. "source": "iana"
  56307. },
  56308. "application/tamp-community-update": {
  56309. "source": "iana"
  56310. },
  56311. "application/tamp-community-update-confirm": {
  56312. "source": "iana"
  56313. },
  56314. "application/tamp-error": {
  56315. "source": "iana"
  56316. },
  56317. "application/tamp-sequence-adjust": {
  56318. "source": "iana"
  56319. },
  56320. "application/tamp-sequence-adjust-confirm": {
  56321. "source": "iana"
  56322. },
  56323. "application/tamp-status-query": {
  56324. "source": "iana"
  56325. },
  56326. "application/tamp-status-response": {
  56327. "source": "iana"
  56328. },
  56329. "application/tamp-update": {
  56330. "source": "iana"
  56331. },
  56332. "application/tamp-update-confirm": {
  56333. "source": "iana"
  56334. },
  56335. "application/tar": {
  56336. "compressible": true
  56337. },
  56338. "application/taxii+json": {
  56339. "source": "iana",
  56340. "compressible": true
  56341. },
  56342. "application/td+json": {
  56343. "source": "iana",
  56344. "compressible": true
  56345. },
  56346. "application/tei+xml": {
  56347. "source": "iana",
  56348. "compressible": true,
  56349. "extensions": ["tei","teicorpus"]
  56350. },
  56351. "application/tetra_isi": {
  56352. "source": "iana"
  56353. },
  56354. "application/thraud+xml": {
  56355. "source": "iana",
  56356. "compressible": true,
  56357. "extensions": ["tfi"]
  56358. },
  56359. "application/timestamp-query": {
  56360. "source": "iana"
  56361. },
  56362. "application/timestamp-reply": {
  56363. "source": "iana"
  56364. },
  56365. "application/timestamped-data": {
  56366. "source": "iana",
  56367. "extensions": ["tsd"]
  56368. },
  56369. "application/tlsrpt+gzip": {
  56370. "source": "iana"
  56371. },
  56372. "application/tlsrpt+json": {
  56373. "source": "iana",
  56374. "compressible": true
  56375. },
  56376. "application/tnauthlist": {
  56377. "source": "iana"
  56378. },
  56379. "application/toml": {
  56380. "compressible": true,
  56381. "extensions": ["toml"]
  56382. },
  56383. "application/trickle-ice-sdpfrag": {
  56384. "source": "iana"
  56385. },
  56386. "application/trig": {
  56387. "source": "iana"
  56388. },
  56389. "application/ttml+xml": {
  56390. "source": "iana",
  56391. "compressible": true,
  56392. "extensions": ["ttml"]
  56393. },
  56394. "application/tve-trigger": {
  56395. "source": "iana"
  56396. },
  56397. "application/tzif": {
  56398. "source": "iana"
  56399. },
  56400. "application/tzif-leap": {
  56401. "source": "iana"
  56402. },
  56403. "application/ulpfec": {
  56404. "source": "iana"
  56405. },
  56406. "application/urc-grpsheet+xml": {
  56407. "source": "iana",
  56408. "compressible": true
  56409. },
  56410. "application/urc-ressheet+xml": {
  56411. "source": "iana",
  56412. "compressible": true,
  56413. "extensions": ["rsheet"]
  56414. },
  56415. "application/urc-targetdesc+xml": {
  56416. "source": "iana",
  56417. "compressible": true
  56418. },
  56419. "application/urc-uisocketdesc+xml": {
  56420. "source": "iana",
  56421. "compressible": true
  56422. },
  56423. "application/vcard+json": {
  56424. "source": "iana",
  56425. "compressible": true
  56426. },
  56427. "application/vcard+xml": {
  56428. "source": "iana",
  56429. "compressible": true
  56430. },
  56431. "application/vemmi": {
  56432. "source": "iana"
  56433. },
  56434. "application/vividence.scriptfile": {
  56435. "source": "apache"
  56436. },
  56437. "application/vnd.1000minds.decision-model+xml": {
  56438. "source": "iana",
  56439. "compressible": true,
  56440. "extensions": ["1km"]
  56441. },
  56442. "application/vnd.3gpp-prose+xml": {
  56443. "source": "iana",
  56444. "compressible": true
  56445. },
  56446. "application/vnd.3gpp-prose-pc3ch+xml": {
  56447. "source": "iana",
  56448. "compressible": true
  56449. },
  56450. "application/vnd.3gpp-v2x-local-service-information": {
  56451. "source": "iana"
  56452. },
  56453. "application/vnd.3gpp.access-transfer-events+xml": {
  56454. "source": "iana",
  56455. "compressible": true
  56456. },
  56457. "application/vnd.3gpp.bsf+xml": {
  56458. "source": "iana",
  56459. "compressible": true
  56460. },
  56461. "application/vnd.3gpp.gmop+xml": {
  56462. "source": "iana",
  56463. "compressible": true
  56464. },
  56465. "application/vnd.3gpp.mc-signalling-ear": {
  56466. "source": "iana"
  56467. },
  56468. "application/vnd.3gpp.mcdata-affiliation-command+xml": {
  56469. "source": "iana",
  56470. "compressible": true
  56471. },
  56472. "application/vnd.3gpp.mcdata-info+xml": {
  56473. "source": "iana",
  56474. "compressible": true
  56475. },
  56476. "application/vnd.3gpp.mcdata-payload": {
  56477. "source": "iana"
  56478. },
  56479. "application/vnd.3gpp.mcdata-service-config+xml": {
  56480. "source": "iana",
  56481. "compressible": true
  56482. },
  56483. "application/vnd.3gpp.mcdata-signalling": {
  56484. "source": "iana"
  56485. },
  56486. "application/vnd.3gpp.mcdata-ue-config+xml": {
  56487. "source": "iana",
  56488. "compressible": true
  56489. },
  56490. "application/vnd.3gpp.mcdata-user-profile+xml": {
  56491. "source": "iana",
  56492. "compressible": true
  56493. },
  56494. "application/vnd.3gpp.mcptt-affiliation-command+xml": {
  56495. "source": "iana",
  56496. "compressible": true
  56497. },
  56498. "application/vnd.3gpp.mcptt-floor-request+xml": {
  56499. "source": "iana",
  56500. "compressible": true
  56501. },
  56502. "application/vnd.3gpp.mcptt-info+xml": {
  56503. "source": "iana",
  56504. "compressible": true
  56505. },
  56506. "application/vnd.3gpp.mcptt-location-info+xml": {
  56507. "source": "iana",
  56508. "compressible": true
  56509. },
  56510. "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
  56511. "source": "iana",
  56512. "compressible": true
  56513. },
  56514. "application/vnd.3gpp.mcptt-service-config+xml": {
  56515. "source": "iana",
  56516. "compressible": true
  56517. },
  56518. "application/vnd.3gpp.mcptt-signed+xml": {
  56519. "source": "iana",
  56520. "compressible": true
  56521. },
  56522. "application/vnd.3gpp.mcptt-ue-config+xml": {
  56523. "source": "iana",
  56524. "compressible": true
  56525. },
  56526. "application/vnd.3gpp.mcptt-ue-init-config+xml": {
  56527. "source": "iana",
  56528. "compressible": true
  56529. },
  56530. "application/vnd.3gpp.mcptt-user-profile+xml": {
  56531. "source": "iana",
  56532. "compressible": true
  56533. },
  56534. "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
  56535. "source": "iana",
  56536. "compressible": true
  56537. },
  56538. "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
  56539. "source": "iana",
  56540. "compressible": true
  56541. },
  56542. "application/vnd.3gpp.mcvideo-info+xml": {
  56543. "source": "iana",
  56544. "compressible": true
  56545. },
  56546. "application/vnd.3gpp.mcvideo-location-info+xml": {
  56547. "source": "iana",
  56548. "compressible": true
  56549. },
  56550. "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
  56551. "source": "iana",
  56552. "compressible": true
  56553. },
  56554. "application/vnd.3gpp.mcvideo-service-config+xml": {
  56555. "source": "iana",
  56556. "compressible": true
  56557. },
  56558. "application/vnd.3gpp.mcvideo-transmission-request+xml": {
  56559. "source": "iana",
  56560. "compressible": true
  56561. },
  56562. "application/vnd.3gpp.mcvideo-ue-config+xml": {
  56563. "source": "iana",
  56564. "compressible": true
  56565. },
  56566. "application/vnd.3gpp.mcvideo-user-profile+xml": {
  56567. "source": "iana",
  56568. "compressible": true
  56569. },
  56570. "application/vnd.3gpp.mid-call+xml": {
  56571. "source": "iana",
  56572. "compressible": true
  56573. },
  56574. "application/vnd.3gpp.pic-bw-large": {
  56575. "source": "iana",
  56576. "extensions": ["plb"]
  56577. },
  56578. "application/vnd.3gpp.pic-bw-small": {
  56579. "source": "iana",
  56580. "extensions": ["psb"]
  56581. },
  56582. "application/vnd.3gpp.pic-bw-var": {
  56583. "source": "iana",
  56584. "extensions": ["pvb"]
  56585. },
  56586. "application/vnd.3gpp.sms": {
  56587. "source": "iana"
  56588. },
  56589. "application/vnd.3gpp.sms+xml": {
  56590. "source": "iana",
  56591. "compressible": true
  56592. },
  56593. "application/vnd.3gpp.srvcc-ext+xml": {
  56594. "source": "iana",
  56595. "compressible": true
  56596. },
  56597. "application/vnd.3gpp.srvcc-info+xml": {
  56598. "source": "iana",
  56599. "compressible": true
  56600. },
  56601. "application/vnd.3gpp.state-and-event-info+xml": {
  56602. "source": "iana",
  56603. "compressible": true
  56604. },
  56605. "application/vnd.3gpp.ussd+xml": {
  56606. "source": "iana",
  56607. "compressible": true
  56608. },
  56609. "application/vnd.3gpp2.bcmcsinfo+xml": {
  56610. "source": "iana",
  56611. "compressible": true
  56612. },
  56613. "application/vnd.3gpp2.sms": {
  56614. "source": "iana"
  56615. },
  56616. "application/vnd.3gpp2.tcap": {
  56617. "source": "iana",
  56618. "extensions": ["tcap"]
  56619. },
  56620. "application/vnd.3lightssoftware.imagescal": {
  56621. "source": "iana"
  56622. },
  56623. "application/vnd.3m.post-it-notes": {
  56624. "source": "iana",
  56625. "extensions": ["pwn"]
  56626. },
  56627. "application/vnd.accpac.simply.aso": {
  56628. "source": "iana",
  56629. "extensions": ["aso"]
  56630. },
  56631. "application/vnd.accpac.simply.imp": {
  56632. "source": "iana",
  56633. "extensions": ["imp"]
  56634. },
  56635. "application/vnd.acucobol": {
  56636. "source": "iana",
  56637. "extensions": ["acu"]
  56638. },
  56639. "application/vnd.acucorp": {
  56640. "source": "iana",
  56641. "extensions": ["atc","acutc"]
  56642. },
  56643. "application/vnd.adobe.air-application-installer-package+zip": {
  56644. "source": "apache",
  56645. "compressible": false,
  56646. "extensions": ["air"]
  56647. },
  56648. "application/vnd.adobe.flash.movie": {
  56649. "source": "iana"
  56650. },
  56651. "application/vnd.adobe.formscentral.fcdt": {
  56652. "source": "iana",
  56653. "extensions": ["fcdt"]
  56654. },
  56655. "application/vnd.adobe.fxp": {
  56656. "source": "iana",
  56657. "extensions": ["fxp","fxpl"]
  56658. },
  56659. "application/vnd.adobe.partial-upload": {
  56660. "source": "iana"
  56661. },
  56662. "application/vnd.adobe.xdp+xml": {
  56663. "source": "iana",
  56664. "compressible": true,
  56665. "extensions": ["xdp"]
  56666. },
  56667. "application/vnd.adobe.xfdf": {
  56668. "source": "iana",
  56669. "extensions": ["xfdf"]
  56670. },
  56671. "application/vnd.aether.imp": {
  56672. "source": "iana"
  56673. },
  56674. "application/vnd.afpc.afplinedata": {
  56675. "source": "iana"
  56676. },
  56677. "application/vnd.afpc.afplinedata-pagedef": {
  56678. "source": "iana"
  56679. },
  56680. "application/vnd.afpc.foca-charset": {
  56681. "source": "iana"
  56682. },
  56683. "application/vnd.afpc.foca-codedfont": {
  56684. "source": "iana"
  56685. },
  56686. "application/vnd.afpc.foca-codepage": {
  56687. "source": "iana"
  56688. },
  56689. "application/vnd.afpc.modca": {
  56690. "source": "iana"
  56691. },
  56692. "application/vnd.afpc.modca-formdef": {
  56693. "source": "iana"
  56694. },
  56695. "application/vnd.afpc.modca-mediummap": {
  56696. "source": "iana"
  56697. },
  56698. "application/vnd.afpc.modca-objectcontainer": {
  56699. "source": "iana"
  56700. },
  56701. "application/vnd.afpc.modca-overlay": {
  56702. "source": "iana"
  56703. },
  56704. "application/vnd.afpc.modca-pagesegment": {
  56705. "source": "iana"
  56706. },
  56707. "application/vnd.ah-barcode": {
  56708. "source": "iana"
  56709. },
  56710. "application/vnd.ahead.space": {
  56711. "source": "iana",
  56712. "extensions": ["ahead"]
  56713. },
  56714. "application/vnd.airzip.filesecure.azf": {
  56715. "source": "iana",
  56716. "extensions": ["azf"]
  56717. },
  56718. "application/vnd.airzip.filesecure.azs": {
  56719. "source": "iana",
  56720. "extensions": ["azs"]
  56721. },
  56722. "application/vnd.amadeus+json": {
  56723. "source": "iana",
  56724. "compressible": true
  56725. },
  56726. "application/vnd.amazon.ebook": {
  56727. "source": "apache",
  56728. "extensions": ["azw"]
  56729. },
  56730. "application/vnd.amazon.mobi8-ebook": {
  56731. "source": "iana"
  56732. },
  56733. "application/vnd.americandynamics.acc": {
  56734. "source": "iana",
  56735. "extensions": ["acc"]
  56736. },
  56737. "application/vnd.amiga.ami": {
  56738. "source": "iana",
  56739. "extensions": ["ami"]
  56740. },
  56741. "application/vnd.amundsen.maze+xml": {
  56742. "source": "iana",
  56743. "compressible": true
  56744. },
  56745. "application/vnd.android.ota": {
  56746. "source": "iana"
  56747. },
  56748. "application/vnd.android.package-archive": {
  56749. "source": "apache",
  56750. "compressible": false,
  56751. "extensions": ["apk"]
  56752. },
  56753. "application/vnd.anki": {
  56754. "source": "iana"
  56755. },
  56756. "application/vnd.anser-web-certificate-issue-initiation": {
  56757. "source": "iana",
  56758. "extensions": ["cii"]
  56759. },
  56760. "application/vnd.anser-web-funds-transfer-initiation": {
  56761. "source": "apache",
  56762. "extensions": ["fti"]
  56763. },
  56764. "application/vnd.antix.game-component": {
  56765. "source": "iana",
  56766. "extensions": ["atx"]
  56767. },
  56768. "application/vnd.apache.thrift.binary": {
  56769. "source": "iana"
  56770. },
  56771. "application/vnd.apache.thrift.compact": {
  56772. "source": "iana"
  56773. },
  56774. "application/vnd.apache.thrift.json": {
  56775. "source": "iana"
  56776. },
  56777. "application/vnd.api+json": {
  56778. "source": "iana",
  56779. "compressible": true
  56780. },
  56781. "application/vnd.aplextor.warrp+json": {
  56782. "source": "iana",
  56783. "compressible": true
  56784. },
  56785. "application/vnd.apothekende.reservation+json": {
  56786. "source": "iana",
  56787. "compressible": true
  56788. },
  56789. "application/vnd.apple.installer+xml": {
  56790. "source": "iana",
  56791. "compressible": true,
  56792. "extensions": ["mpkg"]
  56793. },
  56794. "application/vnd.apple.keynote": {
  56795. "source": "iana",
  56796. "extensions": ["keynote"]
  56797. },
  56798. "application/vnd.apple.mpegurl": {
  56799. "source": "iana",
  56800. "extensions": ["m3u8"]
  56801. },
  56802. "application/vnd.apple.numbers": {
  56803. "source": "iana",
  56804. "extensions": ["numbers"]
  56805. },
  56806. "application/vnd.apple.pages": {
  56807. "source": "iana",
  56808. "extensions": ["pages"]
  56809. },
  56810. "application/vnd.apple.pkpass": {
  56811. "compressible": false,
  56812. "extensions": ["pkpass"]
  56813. },
  56814. "application/vnd.arastra.swi": {
  56815. "source": "iana"
  56816. },
  56817. "application/vnd.aristanetworks.swi": {
  56818. "source": "iana",
  56819. "extensions": ["swi"]
  56820. },
  56821. "application/vnd.artisan+json": {
  56822. "source": "iana",
  56823. "compressible": true
  56824. },
  56825. "application/vnd.artsquare": {
  56826. "source": "iana"
  56827. },
  56828. "application/vnd.astraea-software.iota": {
  56829. "source": "iana",
  56830. "extensions": ["iota"]
  56831. },
  56832. "application/vnd.audiograph": {
  56833. "source": "iana",
  56834. "extensions": ["aep"]
  56835. },
  56836. "application/vnd.autopackage": {
  56837. "source": "iana"
  56838. },
  56839. "application/vnd.avalon+json": {
  56840. "source": "iana",
  56841. "compressible": true
  56842. },
  56843. "application/vnd.avistar+xml": {
  56844. "source": "iana",
  56845. "compressible": true
  56846. },
  56847. "application/vnd.balsamiq.bmml+xml": {
  56848. "source": "iana",
  56849. "compressible": true,
  56850. "extensions": ["bmml"]
  56851. },
  56852. "application/vnd.balsamiq.bmpr": {
  56853. "source": "iana"
  56854. },
  56855. "application/vnd.banana-accounting": {
  56856. "source": "iana"
  56857. },
  56858. "application/vnd.bbf.usp.error": {
  56859. "source": "iana"
  56860. },
  56861. "application/vnd.bbf.usp.msg": {
  56862. "source": "iana"
  56863. },
  56864. "application/vnd.bbf.usp.msg+json": {
  56865. "source": "iana",
  56866. "compressible": true
  56867. },
  56868. "application/vnd.bekitzur-stech+json": {
  56869. "source": "iana",
  56870. "compressible": true
  56871. },
  56872. "application/vnd.bint.med-content": {
  56873. "source": "iana"
  56874. },
  56875. "application/vnd.biopax.rdf+xml": {
  56876. "source": "iana",
  56877. "compressible": true
  56878. },
  56879. "application/vnd.blink-idb-value-wrapper": {
  56880. "source": "iana"
  56881. },
  56882. "application/vnd.blueice.multipass": {
  56883. "source": "iana",
  56884. "extensions": ["mpm"]
  56885. },
  56886. "application/vnd.bluetooth.ep.oob": {
  56887. "source": "iana"
  56888. },
  56889. "application/vnd.bluetooth.le.oob": {
  56890. "source": "iana"
  56891. },
  56892. "application/vnd.bmi": {
  56893. "source": "iana",
  56894. "extensions": ["bmi"]
  56895. },
  56896. "application/vnd.bpf": {
  56897. "source": "iana"
  56898. },
  56899. "application/vnd.bpf3": {
  56900. "source": "iana"
  56901. },
  56902. "application/vnd.businessobjects": {
  56903. "source": "iana",
  56904. "extensions": ["rep"]
  56905. },
  56906. "application/vnd.byu.uapi+json": {
  56907. "source": "iana",
  56908. "compressible": true
  56909. },
  56910. "application/vnd.cab-jscript": {
  56911. "source": "iana"
  56912. },
  56913. "application/vnd.canon-cpdl": {
  56914. "source": "iana"
  56915. },
  56916. "application/vnd.canon-lips": {
  56917. "source": "iana"
  56918. },
  56919. "application/vnd.capasystems-pg+json": {
  56920. "source": "iana",
  56921. "compressible": true
  56922. },
  56923. "application/vnd.cendio.thinlinc.clientconf": {
  56924. "source": "iana"
  56925. },
  56926. "application/vnd.century-systems.tcp_stream": {
  56927. "source": "iana"
  56928. },
  56929. "application/vnd.chemdraw+xml": {
  56930. "source": "iana",
  56931. "compressible": true,
  56932. "extensions": ["cdxml"]
  56933. },
  56934. "application/vnd.chess-pgn": {
  56935. "source": "iana"
  56936. },
  56937. "application/vnd.chipnuts.karaoke-mmd": {
  56938. "source": "iana",
  56939. "extensions": ["mmd"]
  56940. },
  56941. "application/vnd.ciedi": {
  56942. "source": "iana"
  56943. },
  56944. "application/vnd.cinderella": {
  56945. "source": "iana",
  56946. "extensions": ["cdy"]
  56947. },
  56948. "application/vnd.cirpack.isdn-ext": {
  56949. "source": "iana"
  56950. },
  56951. "application/vnd.citationstyles.style+xml": {
  56952. "source": "iana",
  56953. "compressible": true,
  56954. "extensions": ["csl"]
  56955. },
  56956. "application/vnd.claymore": {
  56957. "source": "iana",
  56958. "extensions": ["cla"]
  56959. },
  56960. "application/vnd.cloanto.rp9": {
  56961. "source": "iana",
  56962. "extensions": ["rp9"]
  56963. },
  56964. "application/vnd.clonk.c4group": {
  56965. "source": "iana",
  56966. "extensions": ["c4g","c4d","c4f","c4p","c4u"]
  56967. },
  56968. "application/vnd.cluetrust.cartomobile-config": {
  56969. "source": "iana",
  56970. "extensions": ["c11amc"]
  56971. },
  56972. "application/vnd.cluetrust.cartomobile-config-pkg": {
  56973. "source": "iana",
  56974. "extensions": ["c11amz"]
  56975. },
  56976. "application/vnd.coffeescript": {
  56977. "source": "iana"
  56978. },
  56979. "application/vnd.collabio.xodocuments.document": {
  56980. "source": "iana"
  56981. },
  56982. "application/vnd.collabio.xodocuments.document-template": {
  56983. "source": "iana"
  56984. },
  56985. "application/vnd.collabio.xodocuments.presentation": {
  56986. "source": "iana"
  56987. },
  56988. "application/vnd.collabio.xodocuments.presentation-template": {
  56989. "source": "iana"
  56990. },
  56991. "application/vnd.collabio.xodocuments.spreadsheet": {
  56992. "source": "iana"
  56993. },
  56994. "application/vnd.collabio.xodocuments.spreadsheet-template": {
  56995. "source": "iana"
  56996. },
  56997. "application/vnd.collection+json": {
  56998. "source": "iana",
  56999. "compressible": true
  57000. },
  57001. "application/vnd.collection.doc+json": {
  57002. "source": "iana",
  57003. "compressible": true
  57004. },
  57005. "application/vnd.collection.next+json": {
  57006. "source": "iana",
  57007. "compressible": true
  57008. },
  57009. "application/vnd.comicbook+zip": {
  57010. "source": "iana",
  57011. "compressible": false
  57012. },
  57013. "application/vnd.comicbook-rar": {
  57014. "source": "iana"
  57015. },
  57016. "application/vnd.commerce-battelle": {
  57017. "source": "iana"
  57018. },
  57019. "application/vnd.commonspace": {
  57020. "source": "iana",
  57021. "extensions": ["csp"]
  57022. },
  57023. "application/vnd.contact.cmsg": {
  57024. "source": "iana",
  57025. "extensions": ["cdbcmsg"]
  57026. },
  57027. "application/vnd.coreos.ignition+json": {
  57028. "source": "iana",
  57029. "compressible": true
  57030. },
  57031. "application/vnd.cosmocaller": {
  57032. "source": "iana",
  57033. "extensions": ["cmc"]
  57034. },
  57035. "application/vnd.crick.clicker": {
  57036. "source": "iana",
  57037. "extensions": ["clkx"]
  57038. },
  57039. "application/vnd.crick.clicker.keyboard": {
  57040. "source": "iana",
  57041. "extensions": ["clkk"]
  57042. },
  57043. "application/vnd.crick.clicker.palette": {
  57044. "source": "iana",
  57045. "extensions": ["clkp"]
  57046. },
  57047. "application/vnd.crick.clicker.template": {
  57048. "source": "iana",
  57049. "extensions": ["clkt"]
  57050. },
  57051. "application/vnd.crick.clicker.wordbank": {
  57052. "source": "iana",
  57053. "extensions": ["clkw"]
  57054. },
  57055. "application/vnd.criticaltools.wbs+xml": {
  57056. "source": "iana",
  57057. "compressible": true,
  57058. "extensions": ["wbs"]
  57059. },
  57060. "application/vnd.cryptii.pipe+json": {
  57061. "source": "iana",
  57062. "compressible": true
  57063. },
  57064. "application/vnd.crypto-shade-file": {
  57065. "source": "iana"
  57066. },
  57067. "application/vnd.ctc-posml": {
  57068. "source": "iana",
  57069. "extensions": ["pml"]
  57070. },
  57071. "application/vnd.ctct.ws+xml": {
  57072. "source": "iana",
  57073. "compressible": true
  57074. },
  57075. "application/vnd.cups-pdf": {
  57076. "source": "iana"
  57077. },
  57078. "application/vnd.cups-postscript": {
  57079. "source": "iana"
  57080. },
  57081. "application/vnd.cups-ppd": {
  57082. "source": "iana",
  57083. "extensions": ["ppd"]
  57084. },
  57085. "application/vnd.cups-raster": {
  57086. "source": "iana"
  57087. },
  57088. "application/vnd.cups-raw": {
  57089. "source": "iana"
  57090. },
  57091. "application/vnd.curl": {
  57092. "source": "iana"
  57093. },
  57094. "application/vnd.curl.car": {
  57095. "source": "apache",
  57096. "extensions": ["car"]
  57097. },
  57098. "application/vnd.curl.pcurl": {
  57099. "source": "apache",
  57100. "extensions": ["pcurl"]
  57101. },
  57102. "application/vnd.cyan.dean.root+xml": {
  57103. "source": "iana",
  57104. "compressible": true
  57105. },
  57106. "application/vnd.cybank": {
  57107. "source": "iana"
  57108. },
  57109. "application/vnd.d2l.coursepackage1p0+zip": {
  57110. "source": "iana",
  57111. "compressible": false
  57112. },
  57113. "application/vnd.dart": {
  57114. "source": "iana",
  57115. "compressible": true,
  57116. "extensions": ["dart"]
  57117. },
  57118. "application/vnd.data-vision.rdz": {
  57119. "source": "iana",
  57120. "extensions": ["rdz"]
  57121. },
  57122. "application/vnd.datapackage+json": {
  57123. "source": "iana",
  57124. "compressible": true
  57125. },
  57126. "application/vnd.dataresource+json": {
  57127. "source": "iana",
  57128. "compressible": true
  57129. },
  57130. "application/vnd.dbf": {
  57131. "source": "iana"
  57132. },
  57133. "application/vnd.debian.binary-package": {
  57134. "source": "iana"
  57135. },
  57136. "application/vnd.dece.data": {
  57137. "source": "iana",
  57138. "extensions": ["uvf","uvvf","uvd","uvvd"]
  57139. },
  57140. "application/vnd.dece.ttml+xml": {
  57141. "source": "iana",
  57142. "compressible": true,
  57143. "extensions": ["uvt","uvvt"]
  57144. },
  57145. "application/vnd.dece.unspecified": {
  57146. "source": "iana",
  57147. "extensions": ["uvx","uvvx"]
  57148. },
  57149. "application/vnd.dece.zip": {
  57150. "source": "iana",
  57151. "extensions": ["uvz","uvvz"]
  57152. },
  57153. "application/vnd.denovo.fcselayout-link": {
  57154. "source": "iana",
  57155. "extensions": ["fe_launch"]
  57156. },
  57157. "application/vnd.desmume.movie": {
  57158. "source": "iana"
  57159. },
  57160. "application/vnd.dir-bi.plate-dl-nosuffix": {
  57161. "source": "iana"
  57162. },
  57163. "application/vnd.dm.delegation+xml": {
  57164. "source": "iana",
  57165. "compressible": true
  57166. },
  57167. "application/vnd.dna": {
  57168. "source": "iana",
  57169. "extensions": ["dna"]
  57170. },
  57171. "application/vnd.document+json": {
  57172. "source": "iana",
  57173. "compressible": true
  57174. },
  57175. "application/vnd.dolby.mlp": {
  57176. "source": "apache",
  57177. "extensions": ["mlp"]
  57178. },
  57179. "application/vnd.dolby.mobile.1": {
  57180. "source": "iana"
  57181. },
  57182. "application/vnd.dolby.mobile.2": {
  57183. "source": "iana"
  57184. },
  57185. "application/vnd.doremir.scorecloud-binary-document": {
  57186. "source": "iana"
  57187. },
  57188. "application/vnd.dpgraph": {
  57189. "source": "iana",
  57190. "extensions": ["dpg"]
  57191. },
  57192. "application/vnd.dreamfactory": {
  57193. "source": "iana",
  57194. "extensions": ["dfac"]
  57195. },
  57196. "application/vnd.drive+json": {
  57197. "source": "iana",
  57198. "compressible": true
  57199. },
  57200. "application/vnd.ds-keypoint": {
  57201. "source": "apache",
  57202. "extensions": ["kpxx"]
  57203. },
  57204. "application/vnd.dtg.local": {
  57205. "source": "iana"
  57206. },
  57207. "application/vnd.dtg.local.flash": {
  57208. "source": "iana"
  57209. },
  57210. "application/vnd.dtg.local.html": {
  57211. "source": "iana"
  57212. },
  57213. "application/vnd.dvb.ait": {
  57214. "source": "iana",
  57215. "extensions": ["ait"]
  57216. },
  57217. "application/vnd.dvb.dvbisl+xml": {
  57218. "source": "iana",
  57219. "compressible": true
  57220. },
  57221. "application/vnd.dvb.dvbj": {
  57222. "source": "iana"
  57223. },
  57224. "application/vnd.dvb.esgcontainer": {
  57225. "source": "iana"
  57226. },
  57227. "application/vnd.dvb.ipdcdftnotifaccess": {
  57228. "source": "iana"
  57229. },
  57230. "application/vnd.dvb.ipdcesgaccess": {
  57231. "source": "iana"
  57232. },
  57233. "application/vnd.dvb.ipdcesgaccess2": {
  57234. "source": "iana"
  57235. },
  57236. "application/vnd.dvb.ipdcesgpdd": {
  57237. "source": "iana"
  57238. },
  57239. "application/vnd.dvb.ipdcroaming": {
  57240. "source": "iana"
  57241. },
  57242. "application/vnd.dvb.iptv.alfec-base": {
  57243. "source": "iana"
  57244. },
  57245. "application/vnd.dvb.iptv.alfec-enhancement": {
  57246. "source": "iana"
  57247. },
  57248. "application/vnd.dvb.notif-aggregate-root+xml": {
  57249. "source": "iana",
  57250. "compressible": true
  57251. },
  57252. "application/vnd.dvb.notif-container+xml": {
  57253. "source": "iana",
  57254. "compressible": true
  57255. },
  57256. "application/vnd.dvb.notif-generic+xml": {
  57257. "source": "iana",
  57258. "compressible": true
  57259. },
  57260. "application/vnd.dvb.notif-ia-msglist+xml": {
  57261. "source": "iana",
  57262. "compressible": true
  57263. },
  57264. "application/vnd.dvb.notif-ia-registration-request+xml": {
  57265. "source": "iana",
  57266. "compressible": true
  57267. },
  57268. "application/vnd.dvb.notif-ia-registration-response+xml": {
  57269. "source": "iana",
  57270. "compressible": true
  57271. },
  57272. "application/vnd.dvb.notif-init+xml": {
  57273. "source": "iana",
  57274. "compressible": true
  57275. },
  57276. "application/vnd.dvb.pfr": {
  57277. "source": "iana"
  57278. },
  57279. "application/vnd.dvb.service": {
  57280. "source": "iana",
  57281. "extensions": ["svc"]
  57282. },
  57283. "application/vnd.dxr": {
  57284. "source": "iana"
  57285. },
  57286. "application/vnd.dynageo": {
  57287. "source": "iana",
  57288. "extensions": ["geo"]
  57289. },
  57290. "application/vnd.dzr": {
  57291. "source": "iana"
  57292. },
  57293. "application/vnd.easykaraoke.cdgdownload": {
  57294. "source": "iana"
  57295. },
  57296. "application/vnd.ecdis-update": {
  57297. "source": "iana"
  57298. },
  57299. "application/vnd.ecip.rlp": {
  57300. "source": "iana"
  57301. },
  57302. "application/vnd.ecowin.chart": {
  57303. "source": "iana",
  57304. "extensions": ["mag"]
  57305. },
  57306. "application/vnd.ecowin.filerequest": {
  57307. "source": "iana"
  57308. },
  57309. "application/vnd.ecowin.fileupdate": {
  57310. "source": "iana"
  57311. },
  57312. "application/vnd.ecowin.series": {
  57313. "source": "iana"
  57314. },
  57315. "application/vnd.ecowin.seriesrequest": {
  57316. "source": "iana"
  57317. },
  57318. "application/vnd.ecowin.seriesupdate": {
  57319. "source": "iana"
  57320. },
  57321. "application/vnd.efi.img": {
  57322. "source": "iana"
  57323. },
  57324. "application/vnd.efi.iso": {
  57325. "source": "iana"
  57326. },
  57327. "application/vnd.emclient.accessrequest+xml": {
  57328. "source": "iana",
  57329. "compressible": true
  57330. },
  57331. "application/vnd.enliven": {
  57332. "source": "iana",
  57333. "extensions": ["nml"]
  57334. },
  57335. "application/vnd.enphase.envoy": {
  57336. "source": "iana"
  57337. },
  57338. "application/vnd.eprints.data+xml": {
  57339. "source": "iana",
  57340. "compressible": true
  57341. },
  57342. "application/vnd.epson.esf": {
  57343. "source": "iana",
  57344. "extensions": ["esf"]
  57345. },
  57346. "application/vnd.epson.msf": {
  57347. "source": "iana",
  57348. "extensions": ["msf"]
  57349. },
  57350. "application/vnd.epson.quickanime": {
  57351. "source": "iana",
  57352. "extensions": ["qam"]
  57353. },
  57354. "application/vnd.epson.salt": {
  57355. "source": "iana",
  57356. "extensions": ["slt"]
  57357. },
  57358. "application/vnd.epson.ssf": {
  57359. "source": "iana",
  57360. "extensions": ["ssf"]
  57361. },
  57362. "application/vnd.ericsson.quickcall": {
  57363. "source": "iana"
  57364. },
  57365. "application/vnd.espass-espass+zip": {
  57366. "source": "iana",
  57367. "compressible": false
  57368. },
  57369. "application/vnd.eszigno3+xml": {
  57370. "source": "iana",
  57371. "compressible": true,
  57372. "extensions": ["es3","et3"]
  57373. },
  57374. "application/vnd.etsi.aoc+xml": {
  57375. "source": "iana",
  57376. "compressible": true
  57377. },
  57378. "application/vnd.etsi.asic-e+zip": {
  57379. "source": "iana",
  57380. "compressible": false
  57381. },
  57382. "application/vnd.etsi.asic-s+zip": {
  57383. "source": "iana",
  57384. "compressible": false
  57385. },
  57386. "application/vnd.etsi.cug+xml": {
  57387. "source": "iana",
  57388. "compressible": true
  57389. },
  57390. "application/vnd.etsi.iptvcommand+xml": {
  57391. "source": "iana",
  57392. "compressible": true
  57393. },
  57394. "application/vnd.etsi.iptvdiscovery+xml": {
  57395. "source": "iana",
  57396. "compressible": true
  57397. },
  57398. "application/vnd.etsi.iptvprofile+xml": {
  57399. "source": "iana",
  57400. "compressible": true
  57401. },
  57402. "application/vnd.etsi.iptvsad-bc+xml": {
  57403. "source": "iana",
  57404. "compressible": true
  57405. },
  57406. "application/vnd.etsi.iptvsad-cod+xml": {
  57407. "source": "iana",
  57408. "compressible": true
  57409. },
  57410. "application/vnd.etsi.iptvsad-npvr+xml": {
  57411. "source": "iana",
  57412. "compressible": true
  57413. },
  57414. "application/vnd.etsi.iptvservice+xml": {
  57415. "source": "iana",
  57416. "compressible": true
  57417. },
  57418. "application/vnd.etsi.iptvsync+xml": {
  57419. "source": "iana",
  57420. "compressible": true
  57421. },
  57422. "application/vnd.etsi.iptvueprofile+xml": {
  57423. "source": "iana",
  57424. "compressible": true
  57425. },
  57426. "application/vnd.etsi.mcid+xml": {
  57427. "source": "iana",
  57428. "compressible": true
  57429. },
  57430. "application/vnd.etsi.mheg5": {
  57431. "source": "iana"
  57432. },
  57433. "application/vnd.etsi.overload-control-policy-dataset+xml": {
  57434. "source": "iana",
  57435. "compressible": true
  57436. },
  57437. "application/vnd.etsi.pstn+xml": {
  57438. "source": "iana",
  57439. "compressible": true
  57440. },
  57441. "application/vnd.etsi.sci+xml": {
  57442. "source": "iana",
  57443. "compressible": true
  57444. },
  57445. "application/vnd.etsi.simservs+xml": {
  57446. "source": "iana",
  57447. "compressible": true
  57448. },
  57449. "application/vnd.etsi.timestamp-token": {
  57450. "source": "iana"
  57451. },
  57452. "application/vnd.etsi.tsl+xml": {
  57453. "source": "iana",
  57454. "compressible": true
  57455. },
  57456. "application/vnd.etsi.tsl.der": {
  57457. "source": "iana"
  57458. },
  57459. "application/vnd.eudora.data": {
  57460. "source": "iana"
  57461. },
  57462. "application/vnd.evolv.ecig.profile": {
  57463. "source": "iana"
  57464. },
  57465. "application/vnd.evolv.ecig.settings": {
  57466. "source": "iana"
  57467. },
  57468. "application/vnd.evolv.ecig.theme": {
  57469. "source": "iana"
  57470. },
  57471. "application/vnd.exstream-empower+zip": {
  57472. "source": "iana",
  57473. "compressible": false
  57474. },
  57475. "application/vnd.exstream-package": {
  57476. "source": "iana"
  57477. },
  57478. "application/vnd.ezpix-album": {
  57479. "source": "iana",
  57480. "extensions": ["ez2"]
  57481. },
  57482. "application/vnd.ezpix-package": {
  57483. "source": "iana",
  57484. "extensions": ["ez3"]
  57485. },
  57486. "application/vnd.f-secure.mobile": {
  57487. "source": "iana"
  57488. },
  57489. "application/vnd.fastcopy-disk-image": {
  57490. "source": "iana"
  57491. },
  57492. "application/vnd.fdf": {
  57493. "source": "iana",
  57494. "extensions": ["fdf"]
  57495. },
  57496. "application/vnd.fdsn.mseed": {
  57497. "source": "iana",
  57498. "extensions": ["mseed"]
  57499. },
  57500. "application/vnd.fdsn.seed": {
  57501. "source": "iana",
  57502. "extensions": ["seed","dataless"]
  57503. },
  57504. "application/vnd.ffsns": {
  57505. "source": "iana"
  57506. },
  57507. "application/vnd.ficlab.flb+zip": {
  57508. "source": "iana",
  57509. "compressible": false
  57510. },
  57511. "application/vnd.filmit.zfc": {
  57512. "source": "iana"
  57513. },
  57514. "application/vnd.fints": {
  57515. "source": "iana"
  57516. },
  57517. "application/vnd.firemonkeys.cloudcell": {
  57518. "source": "iana"
  57519. },
  57520. "application/vnd.flographit": {
  57521. "source": "iana",
  57522. "extensions": ["gph"]
  57523. },
  57524. "application/vnd.fluxtime.clip": {
  57525. "source": "iana",
  57526. "extensions": ["ftc"]
  57527. },
  57528. "application/vnd.font-fontforge-sfd": {
  57529. "source": "iana"
  57530. },
  57531. "application/vnd.framemaker": {
  57532. "source": "iana",
  57533. "extensions": ["fm","frame","maker","book"]
  57534. },
  57535. "application/vnd.frogans.fnc": {
  57536. "source": "iana",
  57537. "extensions": ["fnc"]
  57538. },
  57539. "application/vnd.frogans.ltf": {
  57540. "source": "iana",
  57541. "extensions": ["ltf"]
  57542. },
  57543. "application/vnd.fsc.weblaunch": {
  57544. "source": "iana",
  57545. "extensions": ["fsc"]
  57546. },
  57547. "application/vnd.fujitsu.oasys": {
  57548. "source": "iana",
  57549. "extensions": ["oas"]
  57550. },
  57551. "application/vnd.fujitsu.oasys2": {
  57552. "source": "iana",
  57553. "extensions": ["oa2"]
  57554. },
  57555. "application/vnd.fujitsu.oasys3": {
  57556. "source": "iana",
  57557. "extensions": ["oa3"]
  57558. },
  57559. "application/vnd.fujitsu.oasysgp": {
  57560. "source": "iana",
  57561. "extensions": ["fg5"]
  57562. },
  57563. "application/vnd.fujitsu.oasysprs": {
  57564. "source": "iana",
  57565. "extensions": ["bh2"]
  57566. },
  57567. "application/vnd.fujixerox.art-ex": {
  57568. "source": "iana"
  57569. },
  57570. "application/vnd.fujixerox.art4": {
  57571. "source": "iana"
  57572. },
  57573. "application/vnd.fujixerox.ddd": {
  57574. "source": "iana",
  57575. "extensions": ["ddd"]
  57576. },
  57577. "application/vnd.fujixerox.docuworks": {
  57578. "source": "iana",
  57579. "extensions": ["xdw"]
  57580. },
  57581. "application/vnd.fujixerox.docuworks.binder": {
  57582. "source": "iana",
  57583. "extensions": ["xbd"]
  57584. },
  57585. "application/vnd.fujixerox.docuworks.container": {
  57586. "source": "iana"
  57587. },
  57588. "application/vnd.fujixerox.hbpl": {
  57589. "source": "iana"
  57590. },
  57591. "application/vnd.fut-misnet": {
  57592. "source": "iana"
  57593. },
  57594. "application/vnd.futoin+cbor": {
  57595. "source": "iana"
  57596. },
  57597. "application/vnd.futoin+json": {
  57598. "source": "iana",
  57599. "compressible": true
  57600. },
  57601. "application/vnd.fuzzysheet": {
  57602. "source": "iana",
  57603. "extensions": ["fzs"]
  57604. },
  57605. "application/vnd.genomatix.tuxedo": {
  57606. "source": "iana",
  57607. "extensions": ["txd"]
  57608. },
  57609. "application/vnd.gentics.grd+json": {
  57610. "source": "iana",
  57611. "compressible": true
  57612. },
  57613. "application/vnd.geo+json": {
  57614. "source": "iana",
  57615. "compressible": true
  57616. },
  57617. "application/vnd.geocube+xml": {
  57618. "source": "iana",
  57619. "compressible": true
  57620. },
  57621. "application/vnd.geogebra.file": {
  57622. "source": "iana",
  57623. "extensions": ["ggb"]
  57624. },
  57625. "application/vnd.geogebra.tool": {
  57626. "source": "iana",
  57627. "extensions": ["ggt"]
  57628. },
  57629. "application/vnd.geometry-explorer": {
  57630. "source": "iana",
  57631. "extensions": ["gex","gre"]
  57632. },
  57633. "application/vnd.geonext": {
  57634. "source": "iana",
  57635. "extensions": ["gxt"]
  57636. },
  57637. "application/vnd.geoplan": {
  57638. "source": "iana",
  57639. "extensions": ["g2w"]
  57640. },
  57641. "application/vnd.geospace": {
  57642. "source": "iana",
  57643. "extensions": ["g3w"]
  57644. },
  57645. "application/vnd.gerber": {
  57646. "source": "iana"
  57647. },
  57648. "application/vnd.globalplatform.card-content-mgt": {
  57649. "source": "iana"
  57650. },
  57651. "application/vnd.globalplatform.card-content-mgt-response": {
  57652. "source": "iana"
  57653. },
  57654. "application/vnd.gmx": {
  57655. "source": "iana",
  57656. "extensions": ["gmx"]
  57657. },
  57658. "application/vnd.google-apps.document": {
  57659. "compressible": false,
  57660. "extensions": ["gdoc"]
  57661. },
  57662. "application/vnd.google-apps.presentation": {
  57663. "compressible": false,
  57664. "extensions": ["gslides"]
  57665. },
  57666. "application/vnd.google-apps.spreadsheet": {
  57667. "compressible": false,
  57668. "extensions": ["gsheet"]
  57669. },
  57670. "application/vnd.google-earth.kml+xml": {
  57671. "source": "iana",
  57672. "compressible": true,
  57673. "extensions": ["kml"]
  57674. },
  57675. "application/vnd.google-earth.kmz": {
  57676. "source": "iana",
  57677. "compressible": false,
  57678. "extensions": ["kmz"]
  57679. },
  57680. "application/vnd.gov.sk.e-form+xml": {
  57681. "source": "iana",
  57682. "compressible": true
  57683. },
  57684. "application/vnd.gov.sk.e-form+zip": {
  57685. "source": "iana",
  57686. "compressible": false
  57687. },
  57688. "application/vnd.gov.sk.xmldatacontainer+xml": {
  57689. "source": "iana",
  57690. "compressible": true
  57691. },
  57692. "application/vnd.grafeq": {
  57693. "source": "iana",
  57694. "extensions": ["gqf","gqs"]
  57695. },
  57696. "application/vnd.gridmp": {
  57697. "source": "iana"
  57698. },
  57699. "application/vnd.groove-account": {
  57700. "source": "iana",
  57701. "extensions": ["gac"]
  57702. },
  57703. "application/vnd.groove-help": {
  57704. "source": "iana",
  57705. "extensions": ["ghf"]
  57706. },
  57707. "application/vnd.groove-identity-message": {
  57708. "source": "iana",
  57709. "extensions": ["gim"]
  57710. },
  57711. "application/vnd.groove-injector": {
  57712. "source": "iana",
  57713. "extensions": ["grv"]
  57714. },
  57715. "application/vnd.groove-tool-message": {
  57716. "source": "iana",
  57717. "extensions": ["gtm"]
  57718. },
  57719. "application/vnd.groove-tool-template": {
  57720. "source": "iana",
  57721. "extensions": ["tpl"]
  57722. },
  57723. "application/vnd.groove-vcard": {
  57724. "source": "iana",
  57725. "extensions": ["vcg"]
  57726. },
  57727. "application/vnd.hal+json": {
  57728. "source": "iana",
  57729. "compressible": true
  57730. },
  57731. "application/vnd.hal+xml": {
  57732. "source": "iana",
  57733. "compressible": true,
  57734. "extensions": ["hal"]
  57735. },
  57736. "application/vnd.handheld-entertainment+xml": {
  57737. "source": "iana",
  57738. "compressible": true,
  57739. "extensions": ["zmm"]
  57740. },
  57741. "application/vnd.hbci": {
  57742. "source": "iana",
  57743. "extensions": ["hbci"]
  57744. },
  57745. "application/vnd.hc+json": {
  57746. "source": "iana",
  57747. "compressible": true
  57748. },
  57749. "application/vnd.hcl-bireports": {
  57750. "source": "iana"
  57751. },
  57752. "application/vnd.hdt": {
  57753. "source": "iana"
  57754. },
  57755. "application/vnd.heroku+json": {
  57756. "source": "iana",
  57757. "compressible": true
  57758. },
  57759. "application/vnd.hhe.lesson-player": {
  57760. "source": "iana",
  57761. "extensions": ["les"]
  57762. },
  57763. "application/vnd.hp-hpgl": {
  57764. "source": "iana",
  57765. "extensions": ["hpgl"]
  57766. },
  57767. "application/vnd.hp-hpid": {
  57768. "source": "iana",
  57769. "extensions": ["hpid"]
  57770. },
  57771. "application/vnd.hp-hps": {
  57772. "source": "iana",
  57773. "extensions": ["hps"]
  57774. },
  57775. "application/vnd.hp-jlyt": {
  57776. "source": "iana",
  57777. "extensions": ["jlt"]
  57778. },
  57779. "application/vnd.hp-pcl": {
  57780. "source": "iana",
  57781. "extensions": ["pcl"]
  57782. },
  57783. "application/vnd.hp-pclxl": {
  57784. "source": "iana",
  57785. "extensions": ["pclxl"]
  57786. },
  57787. "application/vnd.httphone": {
  57788. "source": "iana"
  57789. },
  57790. "application/vnd.hydrostatix.sof-data": {
  57791. "source": "iana",
  57792. "extensions": ["sfd-hdstx"]
  57793. },
  57794. "application/vnd.hyper+json": {
  57795. "source": "iana",
  57796. "compressible": true
  57797. },
  57798. "application/vnd.hyper-item+json": {
  57799. "source": "iana",
  57800. "compressible": true
  57801. },
  57802. "application/vnd.hyperdrive+json": {
  57803. "source": "iana",
  57804. "compressible": true
  57805. },
  57806. "application/vnd.hzn-3d-crossword": {
  57807. "source": "iana"
  57808. },
  57809. "application/vnd.ibm.afplinedata": {
  57810. "source": "iana"
  57811. },
  57812. "application/vnd.ibm.electronic-media": {
  57813. "source": "iana"
  57814. },
  57815. "application/vnd.ibm.minipay": {
  57816. "source": "iana",
  57817. "extensions": ["mpy"]
  57818. },
  57819. "application/vnd.ibm.modcap": {
  57820. "source": "iana",
  57821. "extensions": ["afp","listafp","list3820"]
  57822. },
  57823. "application/vnd.ibm.rights-management": {
  57824. "source": "iana",
  57825. "extensions": ["irm"]
  57826. },
  57827. "application/vnd.ibm.secure-container": {
  57828. "source": "iana",
  57829. "extensions": ["sc"]
  57830. },
  57831. "application/vnd.iccprofile": {
  57832. "source": "iana",
  57833. "extensions": ["icc","icm"]
  57834. },
  57835. "application/vnd.ieee.1905": {
  57836. "source": "iana"
  57837. },
  57838. "application/vnd.igloader": {
  57839. "source": "iana",
  57840. "extensions": ["igl"]
  57841. },
  57842. "application/vnd.imagemeter.folder+zip": {
  57843. "source": "iana",
  57844. "compressible": false
  57845. },
  57846. "application/vnd.imagemeter.image+zip": {
  57847. "source": "iana",
  57848. "compressible": false
  57849. },
  57850. "application/vnd.immervision-ivp": {
  57851. "source": "iana",
  57852. "extensions": ["ivp"]
  57853. },
  57854. "application/vnd.immervision-ivu": {
  57855. "source": "iana",
  57856. "extensions": ["ivu"]
  57857. },
  57858. "application/vnd.ims.imsccv1p1": {
  57859. "source": "iana"
  57860. },
  57861. "application/vnd.ims.imsccv1p2": {
  57862. "source": "iana"
  57863. },
  57864. "application/vnd.ims.imsccv1p3": {
  57865. "source": "iana"
  57866. },
  57867. "application/vnd.ims.lis.v2.result+json": {
  57868. "source": "iana",
  57869. "compressible": true
  57870. },
  57871. "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
  57872. "source": "iana",
  57873. "compressible": true
  57874. },
  57875. "application/vnd.ims.lti.v2.toolproxy+json": {
  57876. "source": "iana",
  57877. "compressible": true
  57878. },
  57879. "application/vnd.ims.lti.v2.toolproxy.id+json": {
  57880. "source": "iana",
  57881. "compressible": true
  57882. },
  57883. "application/vnd.ims.lti.v2.toolsettings+json": {
  57884. "source": "iana",
  57885. "compressible": true
  57886. },
  57887. "application/vnd.ims.lti.v2.toolsettings.simple+json": {
  57888. "source": "iana",
  57889. "compressible": true
  57890. },
  57891. "application/vnd.informedcontrol.rms+xml": {
  57892. "source": "iana",
  57893. "compressible": true
  57894. },
  57895. "application/vnd.informix-visionary": {
  57896. "source": "iana"
  57897. },
  57898. "application/vnd.infotech.project": {
  57899. "source": "iana"
  57900. },
  57901. "application/vnd.infotech.project+xml": {
  57902. "source": "iana",
  57903. "compressible": true
  57904. },
  57905. "application/vnd.innopath.wamp.notification": {
  57906. "source": "iana"
  57907. },
  57908. "application/vnd.insors.igm": {
  57909. "source": "iana",
  57910. "extensions": ["igm"]
  57911. },
  57912. "application/vnd.intercon.formnet": {
  57913. "source": "iana",
  57914. "extensions": ["xpw","xpx"]
  57915. },
  57916. "application/vnd.intergeo": {
  57917. "source": "iana",
  57918. "extensions": ["i2g"]
  57919. },
  57920. "application/vnd.intertrust.digibox": {
  57921. "source": "iana"
  57922. },
  57923. "application/vnd.intertrust.nncp": {
  57924. "source": "iana"
  57925. },
  57926. "application/vnd.intu.qbo": {
  57927. "source": "iana",
  57928. "extensions": ["qbo"]
  57929. },
  57930. "application/vnd.intu.qfx": {
  57931. "source": "iana",
  57932. "extensions": ["qfx"]
  57933. },
  57934. "application/vnd.iptc.g2.catalogitem+xml": {
  57935. "source": "iana",
  57936. "compressible": true
  57937. },
  57938. "application/vnd.iptc.g2.conceptitem+xml": {
  57939. "source": "iana",
  57940. "compressible": true
  57941. },
  57942. "application/vnd.iptc.g2.knowledgeitem+xml": {
  57943. "source": "iana",
  57944. "compressible": true
  57945. },
  57946. "application/vnd.iptc.g2.newsitem+xml": {
  57947. "source": "iana",
  57948. "compressible": true
  57949. },
  57950. "application/vnd.iptc.g2.newsmessage+xml": {
  57951. "source": "iana",
  57952. "compressible": true
  57953. },
  57954. "application/vnd.iptc.g2.packageitem+xml": {
  57955. "source": "iana",
  57956. "compressible": true
  57957. },
  57958. "application/vnd.iptc.g2.planningitem+xml": {
  57959. "source": "iana",
  57960. "compressible": true
  57961. },
  57962. "application/vnd.ipunplugged.rcprofile": {
  57963. "source": "iana",
  57964. "extensions": ["rcprofile"]
  57965. },
  57966. "application/vnd.irepository.package+xml": {
  57967. "source": "iana",
  57968. "compressible": true,
  57969. "extensions": ["irp"]
  57970. },
  57971. "application/vnd.is-xpr": {
  57972. "source": "iana",
  57973. "extensions": ["xpr"]
  57974. },
  57975. "application/vnd.isac.fcs": {
  57976. "source": "iana",
  57977. "extensions": ["fcs"]
  57978. },
  57979. "application/vnd.iso11783-10+zip": {
  57980. "source": "iana",
  57981. "compressible": false
  57982. },
  57983. "application/vnd.jam": {
  57984. "source": "iana",
  57985. "extensions": ["jam"]
  57986. },
  57987. "application/vnd.japannet-directory-service": {
  57988. "source": "iana"
  57989. },
  57990. "application/vnd.japannet-jpnstore-wakeup": {
  57991. "source": "iana"
  57992. },
  57993. "application/vnd.japannet-payment-wakeup": {
  57994. "source": "iana"
  57995. },
  57996. "application/vnd.japannet-registration": {
  57997. "source": "iana"
  57998. },
  57999. "application/vnd.japannet-registration-wakeup": {
  58000. "source": "iana"
  58001. },
  58002. "application/vnd.japannet-setstore-wakeup": {
  58003. "source": "iana"
  58004. },
  58005. "application/vnd.japannet-verification": {
  58006. "source": "iana"
  58007. },
  58008. "application/vnd.japannet-verification-wakeup": {
  58009. "source": "iana"
  58010. },
  58011. "application/vnd.jcp.javame.midlet-rms": {
  58012. "source": "iana",
  58013. "extensions": ["rms"]
  58014. },
  58015. "application/vnd.jisp": {
  58016. "source": "iana",
  58017. "extensions": ["jisp"]
  58018. },
  58019. "application/vnd.joost.joda-archive": {
  58020. "source": "iana",
  58021. "extensions": ["joda"]
  58022. },
  58023. "application/vnd.jsk.isdn-ngn": {
  58024. "source": "iana"
  58025. },
  58026. "application/vnd.kahootz": {
  58027. "source": "iana",
  58028. "extensions": ["ktz","ktr"]
  58029. },
  58030. "application/vnd.kde.karbon": {
  58031. "source": "iana",
  58032. "extensions": ["karbon"]
  58033. },
  58034. "application/vnd.kde.kchart": {
  58035. "source": "iana",
  58036. "extensions": ["chrt"]
  58037. },
  58038. "application/vnd.kde.kformula": {
  58039. "source": "iana",
  58040. "extensions": ["kfo"]
  58041. },
  58042. "application/vnd.kde.kivio": {
  58043. "source": "iana",
  58044. "extensions": ["flw"]
  58045. },
  58046. "application/vnd.kde.kontour": {
  58047. "source": "iana",
  58048. "extensions": ["kon"]
  58049. },
  58050. "application/vnd.kde.kpresenter": {
  58051. "source": "iana",
  58052. "extensions": ["kpr","kpt"]
  58053. },
  58054. "application/vnd.kde.kspread": {
  58055. "source": "iana",
  58056. "extensions": ["ksp"]
  58057. },
  58058. "application/vnd.kde.kword": {
  58059. "source": "iana",
  58060. "extensions": ["kwd","kwt"]
  58061. },
  58062. "application/vnd.kenameaapp": {
  58063. "source": "iana",
  58064. "extensions": ["htke"]
  58065. },
  58066. "application/vnd.kidspiration": {
  58067. "source": "iana",
  58068. "extensions": ["kia"]
  58069. },
  58070. "application/vnd.kinar": {
  58071. "source": "iana",
  58072. "extensions": ["kne","knp"]
  58073. },
  58074. "application/vnd.koan": {
  58075. "source": "iana",
  58076. "extensions": ["skp","skd","skt","skm"]
  58077. },
  58078. "application/vnd.kodak-descriptor": {
  58079. "source": "iana",
  58080. "extensions": ["sse"]
  58081. },
  58082. "application/vnd.las": {
  58083. "source": "iana"
  58084. },
  58085. "application/vnd.las.las+json": {
  58086. "source": "iana",
  58087. "compressible": true
  58088. },
  58089. "application/vnd.las.las+xml": {
  58090. "source": "iana",
  58091. "compressible": true,
  58092. "extensions": ["lasxml"]
  58093. },
  58094. "application/vnd.laszip": {
  58095. "source": "iana"
  58096. },
  58097. "application/vnd.leap+json": {
  58098. "source": "iana",
  58099. "compressible": true
  58100. },
  58101. "application/vnd.liberty-request+xml": {
  58102. "source": "iana",
  58103. "compressible": true
  58104. },
  58105. "application/vnd.llamagraphics.life-balance.desktop": {
  58106. "source": "iana",
  58107. "extensions": ["lbd"]
  58108. },
  58109. "application/vnd.llamagraphics.life-balance.exchange+xml": {
  58110. "source": "iana",
  58111. "compressible": true,
  58112. "extensions": ["lbe"]
  58113. },
  58114. "application/vnd.logipipe.circuit+zip": {
  58115. "source": "iana",
  58116. "compressible": false
  58117. },
  58118. "application/vnd.loom": {
  58119. "source": "iana"
  58120. },
  58121. "application/vnd.lotus-1-2-3": {
  58122. "source": "iana",
  58123. "extensions": ["123"]
  58124. },
  58125. "application/vnd.lotus-approach": {
  58126. "source": "iana",
  58127. "extensions": ["apr"]
  58128. },
  58129. "application/vnd.lotus-freelance": {
  58130. "source": "iana",
  58131. "extensions": ["pre"]
  58132. },
  58133. "application/vnd.lotus-notes": {
  58134. "source": "iana",
  58135. "extensions": ["nsf"]
  58136. },
  58137. "application/vnd.lotus-organizer": {
  58138. "source": "iana",
  58139. "extensions": ["org"]
  58140. },
  58141. "application/vnd.lotus-screencam": {
  58142. "source": "iana",
  58143. "extensions": ["scm"]
  58144. },
  58145. "application/vnd.lotus-wordpro": {
  58146. "source": "iana",
  58147. "extensions": ["lwp"]
  58148. },
  58149. "application/vnd.macports.portpkg": {
  58150. "source": "iana",
  58151. "extensions": ["portpkg"]
  58152. },
  58153. "application/vnd.mapbox-vector-tile": {
  58154. "source": "iana"
  58155. },
  58156. "application/vnd.marlin.drm.actiontoken+xml": {
  58157. "source": "iana",
  58158. "compressible": true
  58159. },
  58160. "application/vnd.marlin.drm.conftoken+xml": {
  58161. "source": "iana",
  58162. "compressible": true
  58163. },
  58164. "application/vnd.marlin.drm.license+xml": {
  58165. "source": "iana",
  58166. "compressible": true
  58167. },
  58168. "application/vnd.marlin.drm.mdcf": {
  58169. "source": "iana"
  58170. },
  58171. "application/vnd.mason+json": {
  58172. "source": "iana",
  58173. "compressible": true
  58174. },
  58175. "application/vnd.maxmind.maxmind-db": {
  58176. "source": "iana"
  58177. },
  58178. "application/vnd.mcd": {
  58179. "source": "iana",
  58180. "extensions": ["mcd"]
  58181. },
  58182. "application/vnd.medcalcdata": {
  58183. "source": "iana",
  58184. "extensions": ["mc1"]
  58185. },
  58186. "application/vnd.mediastation.cdkey": {
  58187. "source": "iana",
  58188. "extensions": ["cdkey"]
  58189. },
  58190. "application/vnd.meridian-slingshot": {
  58191. "source": "iana"
  58192. },
  58193. "application/vnd.mfer": {
  58194. "source": "iana",
  58195. "extensions": ["mwf"]
  58196. },
  58197. "application/vnd.mfmp": {
  58198. "source": "iana",
  58199. "extensions": ["mfm"]
  58200. },
  58201. "application/vnd.micro+json": {
  58202. "source": "iana",
  58203. "compressible": true
  58204. },
  58205. "application/vnd.micrografx.flo": {
  58206. "source": "iana",
  58207. "extensions": ["flo"]
  58208. },
  58209. "application/vnd.micrografx.igx": {
  58210. "source": "iana",
  58211. "extensions": ["igx"]
  58212. },
  58213. "application/vnd.microsoft.portable-executable": {
  58214. "source": "iana"
  58215. },
  58216. "application/vnd.microsoft.windows.thumbnail-cache": {
  58217. "source": "iana"
  58218. },
  58219. "application/vnd.miele+json": {
  58220. "source": "iana",
  58221. "compressible": true
  58222. },
  58223. "application/vnd.mif": {
  58224. "source": "iana",
  58225. "extensions": ["mif"]
  58226. },
  58227. "application/vnd.minisoft-hp3000-save": {
  58228. "source": "iana"
  58229. },
  58230. "application/vnd.mitsubishi.misty-guard.trustweb": {
  58231. "source": "iana"
  58232. },
  58233. "application/vnd.mobius.daf": {
  58234. "source": "iana",
  58235. "extensions": ["daf"]
  58236. },
  58237. "application/vnd.mobius.dis": {
  58238. "source": "iana",
  58239. "extensions": ["dis"]
  58240. },
  58241. "application/vnd.mobius.mbk": {
  58242. "source": "iana",
  58243. "extensions": ["mbk"]
  58244. },
  58245. "application/vnd.mobius.mqy": {
  58246. "source": "iana",
  58247. "extensions": ["mqy"]
  58248. },
  58249. "application/vnd.mobius.msl": {
  58250. "source": "iana",
  58251. "extensions": ["msl"]
  58252. },
  58253. "application/vnd.mobius.plc": {
  58254. "source": "iana",
  58255. "extensions": ["plc"]
  58256. },
  58257. "application/vnd.mobius.txf": {
  58258. "source": "iana",
  58259. "extensions": ["txf"]
  58260. },
  58261. "application/vnd.mophun.application": {
  58262. "source": "iana",
  58263. "extensions": ["mpn"]
  58264. },
  58265. "application/vnd.mophun.certificate": {
  58266. "source": "iana",
  58267. "extensions": ["mpc"]
  58268. },
  58269. "application/vnd.motorola.flexsuite": {
  58270. "source": "iana"
  58271. },
  58272. "application/vnd.motorola.flexsuite.adsi": {
  58273. "source": "iana"
  58274. },
  58275. "application/vnd.motorola.flexsuite.fis": {
  58276. "source": "iana"
  58277. },
  58278. "application/vnd.motorola.flexsuite.gotap": {
  58279. "source": "iana"
  58280. },
  58281. "application/vnd.motorola.flexsuite.kmr": {
  58282. "source": "iana"
  58283. },
  58284. "application/vnd.motorola.flexsuite.ttc": {
  58285. "source": "iana"
  58286. },
  58287. "application/vnd.motorola.flexsuite.wem": {
  58288. "source": "iana"
  58289. },
  58290. "application/vnd.motorola.iprm": {
  58291. "source": "iana"
  58292. },
  58293. "application/vnd.mozilla.xul+xml": {
  58294. "source": "iana",
  58295. "compressible": true,
  58296. "extensions": ["xul"]
  58297. },
  58298. "application/vnd.ms-3mfdocument": {
  58299. "source": "iana"
  58300. },
  58301. "application/vnd.ms-artgalry": {
  58302. "source": "iana",
  58303. "extensions": ["cil"]
  58304. },
  58305. "application/vnd.ms-asf": {
  58306. "source": "iana"
  58307. },
  58308. "application/vnd.ms-cab-compressed": {
  58309. "source": "iana",
  58310. "extensions": ["cab"]
  58311. },
  58312. "application/vnd.ms-color.iccprofile": {
  58313. "source": "apache"
  58314. },
  58315. "application/vnd.ms-excel": {
  58316. "source": "iana",
  58317. "compressible": false,
  58318. "extensions": ["xls","xlm","xla","xlc","xlt","xlw"]
  58319. },
  58320. "application/vnd.ms-excel.addin.macroenabled.12": {
  58321. "source": "iana",
  58322. "extensions": ["xlam"]
  58323. },
  58324. "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
  58325. "source": "iana",
  58326. "extensions": ["xlsb"]
  58327. },
  58328. "application/vnd.ms-excel.sheet.macroenabled.12": {
  58329. "source": "iana",
  58330. "extensions": ["xlsm"]
  58331. },
  58332. "application/vnd.ms-excel.template.macroenabled.12": {
  58333. "source": "iana",
  58334. "extensions": ["xltm"]
  58335. },
  58336. "application/vnd.ms-fontobject": {
  58337. "source": "iana",
  58338. "compressible": true,
  58339. "extensions": ["eot"]
  58340. },
  58341. "application/vnd.ms-htmlhelp": {
  58342. "source": "iana",
  58343. "extensions": ["chm"]
  58344. },
  58345. "application/vnd.ms-ims": {
  58346. "source": "iana",
  58347. "extensions": ["ims"]
  58348. },
  58349. "application/vnd.ms-lrm": {
  58350. "source": "iana",
  58351. "extensions": ["lrm"]
  58352. },
  58353. "application/vnd.ms-office.activex+xml": {
  58354. "source": "iana",
  58355. "compressible": true
  58356. },
  58357. "application/vnd.ms-officetheme": {
  58358. "source": "iana",
  58359. "extensions": ["thmx"]
  58360. },
  58361. "application/vnd.ms-opentype": {
  58362. "source": "apache",
  58363. "compressible": true
  58364. },
  58365. "application/vnd.ms-outlook": {
  58366. "compressible": false,
  58367. "extensions": ["msg"]
  58368. },
  58369. "application/vnd.ms-package.obfuscated-opentype": {
  58370. "source": "apache"
  58371. },
  58372. "application/vnd.ms-pki.seccat": {
  58373. "source": "apache",
  58374. "extensions": ["cat"]
  58375. },
  58376. "application/vnd.ms-pki.stl": {
  58377. "source": "apache",
  58378. "extensions": ["stl"]
  58379. },
  58380. "application/vnd.ms-playready.initiator+xml": {
  58381. "source": "iana",
  58382. "compressible": true
  58383. },
  58384. "application/vnd.ms-powerpoint": {
  58385. "source": "iana",
  58386. "compressible": false,
  58387. "extensions": ["ppt","pps","pot"]
  58388. },
  58389. "application/vnd.ms-powerpoint.addin.macroenabled.12": {
  58390. "source": "iana",
  58391. "extensions": ["ppam"]
  58392. },
  58393. "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
  58394. "source": "iana",
  58395. "extensions": ["pptm"]
  58396. },
  58397. "application/vnd.ms-powerpoint.slide.macroenabled.12": {
  58398. "source": "iana",
  58399. "extensions": ["sldm"]
  58400. },
  58401. "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
  58402. "source": "iana",
  58403. "extensions": ["ppsm"]
  58404. },
  58405. "application/vnd.ms-powerpoint.template.macroenabled.12": {
  58406. "source": "iana",
  58407. "extensions": ["potm"]
  58408. },
  58409. "application/vnd.ms-printdevicecapabilities+xml": {
  58410. "source": "iana",
  58411. "compressible": true
  58412. },
  58413. "application/vnd.ms-printing.printticket+xml": {
  58414. "source": "apache",
  58415. "compressible": true
  58416. },
  58417. "application/vnd.ms-printschematicket+xml": {
  58418. "source": "iana",
  58419. "compressible": true
  58420. },
  58421. "application/vnd.ms-project": {
  58422. "source": "iana",
  58423. "extensions": ["mpp","mpt"]
  58424. },
  58425. "application/vnd.ms-tnef": {
  58426. "source": "iana"
  58427. },
  58428. "application/vnd.ms-windows.devicepairing": {
  58429. "source": "iana"
  58430. },
  58431. "application/vnd.ms-windows.nwprinting.oob": {
  58432. "source": "iana"
  58433. },
  58434. "application/vnd.ms-windows.printerpairing": {
  58435. "source": "iana"
  58436. },
  58437. "application/vnd.ms-windows.wsd.oob": {
  58438. "source": "iana"
  58439. },
  58440. "application/vnd.ms-wmdrm.lic-chlg-req": {
  58441. "source": "iana"
  58442. },
  58443. "application/vnd.ms-wmdrm.lic-resp": {
  58444. "source": "iana"
  58445. },
  58446. "application/vnd.ms-wmdrm.meter-chlg-req": {
  58447. "source": "iana"
  58448. },
  58449. "application/vnd.ms-wmdrm.meter-resp": {
  58450. "source": "iana"
  58451. },
  58452. "application/vnd.ms-word.document.macroenabled.12": {
  58453. "source": "iana",
  58454. "extensions": ["docm"]
  58455. },
  58456. "application/vnd.ms-word.template.macroenabled.12": {
  58457. "source": "iana",
  58458. "extensions": ["dotm"]
  58459. },
  58460. "application/vnd.ms-works": {
  58461. "source": "iana",
  58462. "extensions": ["wps","wks","wcm","wdb"]
  58463. },
  58464. "application/vnd.ms-wpl": {
  58465. "source": "iana",
  58466. "extensions": ["wpl"]
  58467. },
  58468. "application/vnd.ms-xpsdocument": {
  58469. "source": "iana",
  58470. "compressible": false,
  58471. "extensions": ["xps"]
  58472. },
  58473. "application/vnd.msa-disk-image": {
  58474. "source": "iana"
  58475. },
  58476. "application/vnd.mseq": {
  58477. "source": "iana",
  58478. "extensions": ["mseq"]
  58479. },
  58480. "application/vnd.msign": {
  58481. "source": "iana"
  58482. },
  58483. "application/vnd.multiad.creator": {
  58484. "source": "iana"
  58485. },
  58486. "application/vnd.multiad.creator.cif": {
  58487. "source": "iana"
  58488. },
  58489. "application/vnd.music-niff": {
  58490. "source": "iana"
  58491. },
  58492. "application/vnd.musician": {
  58493. "source": "iana",
  58494. "extensions": ["mus"]
  58495. },
  58496. "application/vnd.muvee.style": {
  58497. "source": "iana",
  58498. "extensions": ["msty"]
  58499. },
  58500. "application/vnd.mynfc": {
  58501. "source": "iana",
  58502. "extensions": ["taglet"]
  58503. },
  58504. "application/vnd.ncd.control": {
  58505. "source": "iana"
  58506. },
  58507. "application/vnd.ncd.reference": {
  58508. "source": "iana"
  58509. },
  58510. "application/vnd.nearst.inv+json": {
  58511. "source": "iana",
  58512. "compressible": true
  58513. },
  58514. "application/vnd.nervana": {
  58515. "source": "iana"
  58516. },
  58517. "application/vnd.netfpx": {
  58518. "source": "iana"
  58519. },
  58520. "application/vnd.neurolanguage.nlu": {
  58521. "source": "iana",
  58522. "extensions": ["nlu"]
  58523. },
  58524. "application/vnd.nimn": {
  58525. "source": "iana"
  58526. },
  58527. "application/vnd.nintendo.nitro.rom": {
  58528. "source": "iana"
  58529. },
  58530. "application/vnd.nintendo.snes.rom": {
  58531. "source": "iana"
  58532. },
  58533. "application/vnd.nitf": {
  58534. "source": "iana",
  58535. "extensions": ["ntf","nitf"]
  58536. },
  58537. "application/vnd.noblenet-directory": {
  58538. "source": "iana",
  58539. "extensions": ["nnd"]
  58540. },
  58541. "application/vnd.noblenet-sealer": {
  58542. "source": "iana",
  58543. "extensions": ["nns"]
  58544. },
  58545. "application/vnd.noblenet-web": {
  58546. "source": "iana",
  58547. "extensions": ["nnw"]
  58548. },
  58549. "application/vnd.nokia.catalogs": {
  58550. "source": "iana"
  58551. },
  58552. "application/vnd.nokia.conml+wbxml": {
  58553. "source": "iana"
  58554. },
  58555. "application/vnd.nokia.conml+xml": {
  58556. "source": "iana",
  58557. "compressible": true
  58558. },
  58559. "application/vnd.nokia.iptv.config+xml": {
  58560. "source": "iana",
  58561. "compressible": true
  58562. },
  58563. "application/vnd.nokia.isds-radio-presets": {
  58564. "source": "iana"
  58565. },
  58566. "application/vnd.nokia.landmark+wbxml": {
  58567. "source": "iana"
  58568. },
  58569. "application/vnd.nokia.landmark+xml": {
  58570. "source": "iana",
  58571. "compressible": true
  58572. },
  58573. "application/vnd.nokia.landmarkcollection+xml": {
  58574. "source": "iana",
  58575. "compressible": true
  58576. },
  58577. "application/vnd.nokia.n-gage.ac+xml": {
  58578. "source": "iana",
  58579. "compressible": true,
  58580. "extensions": ["ac"]
  58581. },
  58582. "application/vnd.nokia.n-gage.data": {
  58583. "source": "iana",
  58584. "extensions": ["ngdat"]
  58585. },
  58586. "application/vnd.nokia.n-gage.symbian.install": {
  58587. "source": "iana",
  58588. "extensions": ["n-gage"]
  58589. },
  58590. "application/vnd.nokia.ncd": {
  58591. "source": "iana"
  58592. },
  58593. "application/vnd.nokia.pcd+wbxml": {
  58594. "source": "iana"
  58595. },
  58596. "application/vnd.nokia.pcd+xml": {
  58597. "source": "iana",
  58598. "compressible": true
  58599. },
  58600. "application/vnd.nokia.radio-preset": {
  58601. "source": "iana",
  58602. "extensions": ["rpst"]
  58603. },
  58604. "application/vnd.nokia.radio-presets": {
  58605. "source": "iana",
  58606. "extensions": ["rpss"]
  58607. },
  58608. "application/vnd.novadigm.edm": {
  58609. "source": "iana",
  58610. "extensions": ["edm"]
  58611. },
  58612. "application/vnd.novadigm.edx": {
  58613. "source": "iana",
  58614. "extensions": ["edx"]
  58615. },
  58616. "application/vnd.novadigm.ext": {
  58617. "source": "iana",
  58618. "extensions": ["ext"]
  58619. },
  58620. "application/vnd.ntt-local.content-share": {
  58621. "source": "iana"
  58622. },
  58623. "application/vnd.ntt-local.file-transfer": {
  58624. "source": "iana"
  58625. },
  58626. "application/vnd.ntt-local.ogw_remote-access": {
  58627. "source": "iana"
  58628. },
  58629. "application/vnd.ntt-local.sip-ta_remote": {
  58630. "source": "iana"
  58631. },
  58632. "application/vnd.ntt-local.sip-ta_tcp_stream": {
  58633. "source": "iana"
  58634. },
  58635. "application/vnd.oasis.opendocument.chart": {
  58636. "source": "iana",
  58637. "extensions": ["odc"]
  58638. },
  58639. "application/vnd.oasis.opendocument.chart-template": {
  58640. "source": "iana",
  58641. "extensions": ["otc"]
  58642. },
  58643. "application/vnd.oasis.opendocument.database": {
  58644. "source": "iana",
  58645. "extensions": ["odb"]
  58646. },
  58647. "application/vnd.oasis.opendocument.formula": {
  58648. "source": "iana",
  58649. "extensions": ["odf"]
  58650. },
  58651. "application/vnd.oasis.opendocument.formula-template": {
  58652. "source": "iana",
  58653. "extensions": ["odft"]
  58654. },
  58655. "application/vnd.oasis.opendocument.graphics": {
  58656. "source": "iana",
  58657. "compressible": false,
  58658. "extensions": ["odg"]
  58659. },
  58660. "application/vnd.oasis.opendocument.graphics-template": {
  58661. "source": "iana",
  58662. "extensions": ["otg"]
  58663. },
  58664. "application/vnd.oasis.opendocument.image": {
  58665. "source": "iana",
  58666. "extensions": ["odi"]
  58667. },
  58668. "application/vnd.oasis.opendocument.image-template": {
  58669. "source": "iana",
  58670. "extensions": ["oti"]
  58671. },
  58672. "application/vnd.oasis.opendocument.presentation": {
  58673. "source": "iana",
  58674. "compressible": false,
  58675. "extensions": ["odp"]
  58676. },
  58677. "application/vnd.oasis.opendocument.presentation-template": {
  58678. "source": "iana",
  58679. "extensions": ["otp"]
  58680. },
  58681. "application/vnd.oasis.opendocument.spreadsheet": {
  58682. "source": "iana",
  58683. "compressible": false,
  58684. "extensions": ["ods"]
  58685. },
  58686. "application/vnd.oasis.opendocument.spreadsheet-template": {
  58687. "source": "iana",
  58688. "extensions": ["ots"]
  58689. },
  58690. "application/vnd.oasis.opendocument.text": {
  58691. "source": "iana",
  58692. "compressible": false,
  58693. "extensions": ["odt"]
  58694. },
  58695. "application/vnd.oasis.opendocument.text-master": {
  58696. "source": "iana",
  58697. "extensions": ["odm"]
  58698. },
  58699. "application/vnd.oasis.opendocument.text-template": {
  58700. "source": "iana",
  58701. "extensions": ["ott"]
  58702. },
  58703. "application/vnd.oasis.opendocument.text-web": {
  58704. "source": "iana",
  58705. "extensions": ["oth"]
  58706. },
  58707. "application/vnd.obn": {
  58708. "source": "iana"
  58709. },
  58710. "application/vnd.ocf+cbor": {
  58711. "source": "iana"
  58712. },
  58713. "application/vnd.oci.image.manifest.v1+json": {
  58714. "source": "iana",
  58715. "compressible": true
  58716. },
  58717. "application/vnd.oftn.l10n+json": {
  58718. "source": "iana",
  58719. "compressible": true
  58720. },
  58721. "application/vnd.oipf.contentaccessdownload+xml": {
  58722. "source": "iana",
  58723. "compressible": true
  58724. },
  58725. "application/vnd.oipf.contentaccessstreaming+xml": {
  58726. "source": "iana",
  58727. "compressible": true
  58728. },
  58729. "application/vnd.oipf.cspg-hexbinary": {
  58730. "source": "iana"
  58731. },
  58732. "application/vnd.oipf.dae.svg+xml": {
  58733. "source": "iana",
  58734. "compressible": true
  58735. },
  58736. "application/vnd.oipf.dae.xhtml+xml": {
  58737. "source": "iana",
  58738. "compressible": true
  58739. },
  58740. "application/vnd.oipf.mippvcontrolmessage+xml": {
  58741. "source": "iana",
  58742. "compressible": true
  58743. },
  58744. "application/vnd.oipf.pae.gem": {
  58745. "source": "iana"
  58746. },
  58747. "application/vnd.oipf.spdiscovery+xml": {
  58748. "source": "iana",
  58749. "compressible": true
  58750. },
  58751. "application/vnd.oipf.spdlist+xml": {
  58752. "source": "iana",
  58753. "compressible": true
  58754. },
  58755. "application/vnd.oipf.ueprofile+xml": {
  58756. "source": "iana",
  58757. "compressible": true
  58758. },
  58759. "application/vnd.oipf.userprofile+xml": {
  58760. "source": "iana",
  58761. "compressible": true
  58762. },
  58763. "application/vnd.olpc-sugar": {
  58764. "source": "iana",
  58765. "extensions": ["xo"]
  58766. },
  58767. "application/vnd.oma-scws-config": {
  58768. "source": "iana"
  58769. },
  58770. "application/vnd.oma-scws-http-request": {
  58771. "source": "iana"
  58772. },
  58773. "application/vnd.oma-scws-http-response": {
  58774. "source": "iana"
  58775. },
  58776. "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
  58777. "source": "iana",
  58778. "compressible": true
  58779. },
  58780. "application/vnd.oma.bcast.drm-trigger+xml": {
  58781. "source": "iana",
  58782. "compressible": true
  58783. },
  58784. "application/vnd.oma.bcast.imd+xml": {
  58785. "source": "iana",
  58786. "compressible": true
  58787. },
  58788. "application/vnd.oma.bcast.ltkm": {
  58789. "source": "iana"
  58790. },
  58791. "application/vnd.oma.bcast.notification+xml": {
  58792. "source": "iana",
  58793. "compressible": true
  58794. },
  58795. "application/vnd.oma.bcast.provisioningtrigger": {
  58796. "source": "iana"
  58797. },
  58798. "application/vnd.oma.bcast.sgboot": {
  58799. "source": "iana"
  58800. },
  58801. "application/vnd.oma.bcast.sgdd+xml": {
  58802. "source": "iana",
  58803. "compressible": true
  58804. },
  58805. "application/vnd.oma.bcast.sgdu": {
  58806. "source": "iana"
  58807. },
  58808. "application/vnd.oma.bcast.simple-symbol-container": {
  58809. "source": "iana"
  58810. },
  58811. "application/vnd.oma.bcast.smartcard-trigger+xml": {
  58812. "source": "iana",
  58813. "compressible": true
  58814. },
  58815. "application/vnd.oma.bcast.sprov+xml": {
  58816. "source": "iana",
  58817. "compressible": true
  58818. },
  58819. "application/vnd.oma.bcast.stkm": {
  58820. "source": "iana"
  58821. },
  58822. "application/vnd.oma.cab-address-book+xml": {
  58823. "source": "iana",
  58824. "compressible": true
  58825. },
  58826. "application/vnd.oma.cab-feature-handler+xml": {
  58827. "source": "iana",
  58828. "compressible": true
  58829. },
  58830. "application/vnd.oma.cab-pcc+xml": {
  58831. "source": "iana",
  58832. "compressible": true
  58833. },
  58834. "application/vnd.oma.cab-subs-invite+xml": {
  58835. "source": "iana",
  58836. "compressible": true
  58837. },
  58838. "application/vnd.oma.cab-user-prefs+xml": {
  58839. "source": "iana",
  58840. "compressible": true
  58841. },
  58842. "application/vnd.oma.dcd": {
  58843. "source": "iana"
  58844. },
  58845. "application/vnd.oma.dcdc": {
  58846. "source": "iana"
  58847. },
  58848. "application/vnd.oma.dd2+xml": {
  58849. "source": "iana",
  58850. "compressible": true,
  58851. "extensions": ["dd2"]
  58852. },
  58853. "application/vnd.oma.drm.risd+xml": {
  58854. "source": "iana",
  58855. "compressible": true
  58856. },
  58857. "application/vnd.oma.group-usage-list+xml": {
  58858. "source": "iana",
  58859. "compressible": true
  58860. },
  58861. "application/vnd.oma.lwm2m+json": {
  58862. "source": "iana",
  58863. "compressible": true
  58864. },
  58865. "application/vnd.oma.lwm2m+tlv": {
  58866. "source": "iana"
  58867. },
  58868. "application/vnd.oma.pal+xml": {
  58869. "source": "iana",
  58870. "compressible": true
  58871. },
  58872. "application/vnd.oma.poc.detailed-progress-report+xml": {
  58873. "source": "iana",
  58874. "compressible": true
  58875. },
  58876. "application/vnd.oma.poc.final-report+xml": {
  58877. "source": "iana",
  58878. "compressible": true
  58879. },
  58880. "application/vnd.oma.poc.groups+xml": {
  58881. "source": "iana",
  58882. "compressible": true
  58883. },
  58884. "application/vnd.oma.poc.invocation-descriptor+xml": {
  58885. "source": "iana",
  58886. "compressible": true
  58887. },
  58888. "application/vnd.oma.poc.optimized-progress-report+xml": {
  58889. "source": "iana",
  58890. "compressible": true
  58891. },
  58892. "application/vnd.oma.push": {
  58893. "source": "iana"
  58894. },
  58895. "application/vnd.oma.scidm.messages+xml": {
  58896. "source": "iana",
  58897. "compressible": true
  58898. },
  58899. "application/vnd.oma.xcap-directory+xml": {
  58900. "source": "iana",
  58901. "compressible": true
  58902. },
  58903. "application/vnd.omads-email+xml": {
  58904. "source": "iana",
  58905. "charset": "UTF-8",
  58906. "compressible": true
  58907. },
  58908. "application/vnd.omads-file+xml": {
  58909. "source": "iana",
  58910. "charset": "UTF-8",
  58911. "compressible": true
  58912. },
  58913. "application/vnd.omads-folder+xml": {
  58914. "source": "iana",
  58915. "charset": "UTF-8",
  58916. "compressible": true
  58917. },
  58918. "application/vnd.omaloc-supl-init": {
  58919. "source": "iana"
  58920. },
  58921. "application/vnd.onepager": {
  58922. "source": "iana"
  58923. },
  58924. "application/vnd.onepagertamp": {
  58925. "source": "iana"
  58926. },
  58927. "application/vnd.onepagertamx": {
  58928. "source": "iana"
  58929. },
  58930. "application/vnd.onepagertat": {
  58931. "source": "iana"
  58932. },
  58933. "application/vnd.onepagertatp": {
  58934. "source": "iana"
  58935. },
  58936. "application/vnd.onepagertatx": {
  58937. "source": "iana"
  58938. },
  58939. "application/vnd.openblox.game+xml": {
  58940. "source": "iana",
  58941. "compressible": true,
  58942. "extensions": ["obgx"]
  58943. },
  58944. "application/vnd.openblox.game-binary": {
  58945. "source": "iana"
  58946. },
  58947. "application/vnd.openeye.oeb": {
  58948. "source": "iana"
  58949. },
  58950. "application/vnd.openofficeorg.extension": {
  58951. "source": "apache",
  58952. "extensions": ["oxt"]
  58953. },
  58954. "application/vnd.openstreetmap.data+xml": {
  58955. "source": "iana",
  58956. "compressible": true,
  58957. "extensions": ["osm"]
  58958. },
  58959. "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
  58960. "source": "iana",
  58961. "compressible": true
  58962. },
  58963. "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
  58964. "source": "iana",
  58965. "compressible": true
  58966. },
  58967. "application/vnd.openxmlformats-officedocument.drawing+xml": {
  58968. "source": "iana",
  58969. "compressible": true
  58970. },
  58971. "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
  58972. "source": "iana",
  58973. "compressible": true
  58974. },
  58975. "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
  58976. "source": "iana",
  58977. "compressible": true
  58978. },
  58979. "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
  58980. "source": "iana",
  58981. "compressible": true
  58982. },
  58983. "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
  58984. "source": "iana",
  58985. "compressible": true
  58986. },
  58987. "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
  58988. "source": "iana",
  58989. "compressible": true
  58990. },
  58991. "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
  58992. "source": "iana",
  58993. "compressible": true
  58994. },
  58995. "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
  58996. "source": "iana",
  58997. "compressible": true
  58998. },
  58999. "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
  59000. "source": "iana",
  59001. "compressible": true
  59002. },
  59003. "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
  59004. "source": "iana",
  59005. "compressible": true
  59006. },
  59007. "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
  59008. "source": "iana",
  59009. "compressible": true
  59010. },
  59011. "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
  59012. "source": "iana",
  59013. "compressible": true
  59014. },
  59015. "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
  59016. "source": "iana",
  59017. "compressible": true
  59018. },
  59019. "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
  59020. "source": "iana",
  59021. "compressible": false,
  59022. "extensions": ["pptx"]
  59023. },
  59024. "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
  59025. "source": "iana",
  59026. "compressible": true
  59027. },
  59028. "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
  59029. "source": "iana",
  59030. "compressible": true
  59031. },
  59032. "application/vnd.openxmlformats-officedocument.presentationml.slide": {
  59033. "source": "iana",
  59034. "extensions": ["sldx"]
  59035. },
  59036. "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
  59037. "source": "iana",
  59038. "compressible": true
  59039. },
  59040. "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
  59041. "source": "iana",
  59042. "compressible": true
  59043. },
  59044. "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
  59045. "source": "iana",
  59046. "compressible": true
  59047. },
  59048. "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
  59049. "source": "iana",
  59050. "extensions": ["ppsx"]
  59051. },
  59052. "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
  59053. "source": "iana",
  59054. "compressible": true
  59055. },
  59056. "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
  59057. "source": "iana",
  59058. "compressible": true
  59059. },
  59060. "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
  59061. "source": "iana",
  59062. "compressible": true
  59063. },
  59064. "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
  59065. "source": "iana",
  59066. "compressible": true
  59067. },
  59068. "application/vnd.openxmlformats-officedocument.presentationml.template": {
  59069. "source": "iana",
  59070. "extensions": ["potx"]
  59071. },
  59072. "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
  59073. "source": "iana",
  59074. "compressible": true
  59075. },
  59076. "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
  59077. "source": "iana",
  59078. "compressible": true
  59079. },
  59080. "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
  59081. "source": "iana",
  59082. "compressible": true
  59083. },
  59084. "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
  59085. "source": "iana",
  59086. "compressible": true
  59087. },
  59088. "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
  59089. "source": "iana",
  59090. "compressible": true
  59091. },
  59092. "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
  59093. "source": "iana",
  59094. "compressible": true
  59095. },
  59096. "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
  59097. "source": "iana",
  59098. "compressible": true
  59099. },
  59100. "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
  59101. "source": "iana",
  59102. "compressible": true
  59103. },
  59104. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
  59105. "source": "iana",
  59106. "compressible": true
  59107. },
  59108. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
  59109. "source": "iana",
  59110. "compressible": true
  59111. },
  59112. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
  59113. "source": "iana",
  59114. "compressible": true
  59115. },
  59116. "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
  59117. "source": "iana",
  59118. "compressible": true
  59119. },
  59120. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
  59121. "source": "iana",
  59122. "compressible": true
  59123. },
  59124. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
  59125. "source": "iana",
  59126. "compressible": true
  59127. },
  59128. "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
  59129. "source": "iana",
  59130. "compressible": true
  59131. },
  59132. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
  59133. "source": "iana",
  59134. "compressible": false,
  59135. "extensions": ["xlsx"]
  59136. },
  59137. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
  59138. "source": "iana",
  59139. "compressible": true
  59140. },
  59141. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
  59142. "source": "iana",
  59143. "compressible": true
  59144. },
  59145. "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
  59146. "source": "iana",
  59147. "compressible": true
  59148. },
  59149. "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
  59150. "source": "iana",
  59151. "compressible": true
  59152. },
  59153. "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
  59154. "source": "iana",
  59155. "compressible": true
  59156. },
  59157. "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
  59158. "source": "iana",
  59159. "extensions": ["xltx"]
  59160. },
  59161. "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
  59162. "source": "iana",
  59163. "compressible": true
  59164. },
  59165. "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
  59166. "source": "iana",
  59167. "compressible": true
  59168. },
  59169. "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
  59170. "source": "iana",
  59171. "compressible": true
  59172. },
  59173. "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
  59174. "source": "iana",
  59175. "compressible": true
  59176. },
  59177. "application/vnd.openxmlformats-officedocument.theme+xml": {
  59178. "source": "iana",
  59179. "compressible": true
  59180. },
  59181. "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
  59182. "source": "iana",
  59183. "compressible": true
  59184. },
  59185. "application/vnd.openxmlformats-officedocument.vmldrawing": {
  59186. "source": "iana"
  59187. },
  59188. "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
  59189. "source": "iana",
  59190. "compressible": true
  59191. },
  59192. "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
  59193. "source": "iana",
  59194. "compressible": false,
  59195. "extensions": ["docx"]
  59196. },
  59197. "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
  59198. "source": "iana",
  59199. "compressible": true
  59200. },
  59201. "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
  59202. "source": "iana",
  59203. "compressible": true
  59204. },
  59205. "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
  59206. "source": "iana",
  59207. "compressible": true
  59208. },
  59209. "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
  59210. "source": "iana",
  59211. "compressible": true
  59212. },
  59213. "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
  59214. "source": "iana",
  59215. "compressible": true
  59216. },
  59217. "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
  59218. "source": "iana",
  59219. "compressible": true
  59220. },
  59221. "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
  59222. "source": "iana",
  59223. "compressible": true
  59224. },
  59225. "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
  59226. "source": "iana",
  59227. "compressible": true
  59228. },
  59229. "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
  59230. "source": "iana",
  59231. "compressible": true
  59232. },
  59233. "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
  59234. "source": "iana",
  59235. "extensions": ["dotx"]
  59236. },
  59237. "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
  59238. "source": "iana",
  59239. "compressible": true
  59240. },
  59241. "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
  59242. "source": "iana",
  59243. "compressible": true
  59244. },
  59245. "application/vnd.openxmlformats-package.core-properties+xml": {
  59246. "source": "iana",
  59247. "compressible": true
  59248. },
  59249. "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
  59250. "source": "iana",
  59251. "compressible": true
  59252. },
  59253. "application/vnd.openxmlformats-package.relationships+xml": {
  59254. "source": "iana",
  59255. "compressible": true
  59256. },
  59257. "application/vnd.oracle.resource+json": {
  59258. "source": "iana",
  59259. "compressible": true
  59260. },
  59261. "application/vnd.orange.indata": {
  59262. "source": "iana"
  59263. },
  59264. "application/vnd.osa.netdeploy": {
  59265. "source": "iana"
  59266. },
  59267. "application/vnd.osgeo.mapguide.package": {
  59268. "source": "iana",
  59269. "extensions": ["mgp"]
  59270. },
  59271. "application/vnd.osgi.bundle": {
  59272. "source": "iana"
  59273. },
  59274. "application/vnd.osgi.dp": {
  59275. "source": "iana",
  59276. "extensions": ["dp"]
  59277. },
  59278. "application/vnd.osgi.subsystem": {
  59279. "source": "iana",
  59280. "extensions": ["esa"]
  59281. },
  59282. "application/vnd.otps.ct-kip+xml": {
  59283. "source": "iana",
  59284. "compressible": true
  59285. },
  59286. "application/vnd.oxli.countgraph": {
  59287. "source": "iana"
  59288. },
  59289. "application/vnd.pagerduty+json": {
  59290. "source": "iana",
  59291. "compressible": true
  59292. },
  59293. "application/vnd.palm": {
  59294. "source": "iana",
  59295. "extensions": ["pdb","pqa","oprc"]
  59296. },
  59297. "application/vnd.panoply": {
  59298. "source": "iana"
  59299. },
  59300. "application/vnd.paos.xml": {
  59301. "source": "iana"
  59302. },
  59303. "application/vnd.patentdive": {
  59304. "source": "iana"
  59305. },
  59306. "application/vnd.patientecommsdoc": {
  59307. "source": "iana"
  59308. },
  59309. "application/vnd.pawaafile": {
  59310. "source": "iana",
  59311. "extensions": ["paw"]
  59312. },
  59313. "application/vnd.pcos": {
  59314. "source": "iana"
  59315. },
  59316. "application/vnd.pg.format": {
  59317. "source": "iana",
  59318. "extensions": ["str"]
  59319. },
  59320. "application/vnd.pg.osasli": {
  59321. "source": "iana",
  59322. "extensions": ["ei6"]
  59323. },
  59324. "application/vnd.piaccess.application-licence": {
  59325. "source": "iana"
  59326. },
  59327. "application/vnd.picsel": {
  59328. "source": "iana",
  59329. "extensions": ["efif"]
  59330. },
  59331. "application/vnd.pmi.widget": {
  59332. "source": "iana",
  59333. "extensions": ["wg"]
  59334. },
  59335. "application/vnd.poc.group-advertisement+xml": {
  59336. "source": "iana",
  59337. "compressible": true
  59338. },
  59339. "application/vnd.pocketlearn": {
  59340. "source": "iana",
  59341. "extensions": ["plf"]
  59342. },
  59343. "application/vnd.powerbuilder6": {
  59344. "source": "iana",
  59345. "extensions": ["pbd"]
  59346. },
  59347. "application/vnd.powerbuilder6-s": {
  59348. "source": "iana"
  59349. },
  59350. "application/vnd.powerbuilder7": {
  59351. "source": "iana"
  59352. },
  59353. "application/vnd.powerbuilder7-s": {
  59354. "source": "iana"
  59355. },
  59356. "application/vnd.powerbuilder75": {
  59357. "source": "iana"
  59358. },
  59359. "application/vnd.powerbuilder75-s": {
  59360. "source": "iana"
  59361. },
  59362. "application/vnd.preminet": {
  59363. "source": "iana"
  59364. },
  59365. "application/vnd.previewsystems.box": {
  59366. "source": "iana",
  59367. "extensions": ["box"]
  59368. },
  59369. "application/vnd.proteus.magazine": {
  59370. "source": "iana",
  59371. "extensions": ["mgz"]
  59372. },
  59373. "application/vnd.psfs": {
  59374. "source": "iana"
  59375. },
  59376. "application/vnd.publishare-delta-tree": {
  59377. "source": "iana",
  59378. "extensions": ["qps"]
  59379. },
  59380. "application/vnd.pvi.ptid1": {
  59381. "source": "iana",
  59382. "extensions": ["ptid"]
  59383. },
  59384. "application/vnd.pwg-multiplexed": {
  59385. "source": "iana"
  59386. },
  59387. "application/vnd.pwg-xhtml-print+xml": {
  59388. "source": "iana",
  59389. "compressible": true
  59390. },
  59391. "application/vnd.qualcomm.brew-app-res": {
  59392. "source": "iana"
  59393. },
  59394. "application/vnd.quarantainenet": {
  59395. "source": "iana"
  59396. },
  59397. "application/vnd.quark.quarkxpress": {
  59398. "source": "iana",
  59399. "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"]
  59400. },
  59401. "application/vnd.quobject-quoxdocument": {
  59402. "source": "iana"
  59403. },
  59404. "application/vnd.radisys.moml+xml": {
  59405. "source": "iana",
  59406. "compressible": true
  59407. },
  59408. "application/vnd.radisys.msml+xml": {
  59409. "source": "iana",
  59410. "compressible": true
  59411. },
  59412. "application/vnd.radisys.msml-audit+xml": {
  59413. "source": "iana",
  59414. "compressible": true
  59415. },
  59416. "application/vnd.radisys.msml-audit-conf+xml": {
  59417. "source": "iana",
  59418. "compressible": true
  59419. },
  59420. "application/vnd.radisys.msml-audit-conn+xml": {
  59421. "source": "iana",
  59422. "compressible": true
  59423. },
  59424. "application/vnd.radisys.msml-audit-dialog+xml": {
  59425. "source": "iana",
  59426. "compressible": true
  59427. },
  59428. "application/vnd.radisys.msml-audit-stream+xml": {
  59429. "source": "iana",
  59430. "compressible": true
  59431. },
  59432. "application/vnd.radisys.msml-conf+xml": {
  59433. "source": "iana",
  59434. "compressible": true
  59435. },
  59436. "application/vnd.radisys.msml-dialog+xml": {
  59437. "source": "iana",
  59438. "compressible": true
  59439. },
  59440. "application/vnd.radisys.msml-dialog-base+xml": {
  59441. "source": "iana",
  59442. "compressible": true
  59443. },
  59444. "application/vnd.radisys.msml-dialog-fax-detect+xml": {
  59445. "source": "iana",
  59446. "compressible": true
  59447. },
  59448. "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
  59449. "source": "iana",
  59450. "compressible": true
  59451. },
  59452. "application/vnd.radisys.msml-dialog-group+xml": {
  59453. "source": "iana",
  59454. "compressible": true
  59455. },
  59456. "application/vnd.radisys.msml-dialog-speech+xml": {
  59457. "source": "iana",
  59458. "compressible": true
  59459. },
  59460. "application/vnd.radisys.msml-dialog-transform+xml": {
  59461. "source": "iana",
  59462. "compressible": true
  59463. },
  59464. "application/vnd.rainstor.data": {
  59465. "source": "iana"
  59466. },
  59467. "application/vnd.rapid": {
  59468. "source": "iana"
  59469. },
  59470. "application/vnd.rar": {
  59471. "source": "iana"
  59472. },
  59473. "application/vnd.realvnc.bed": {
  59474. "source": "iana",
  59475. "extensions": ["bed"]
  59476. },
  59477. "application/vnd.recordare.musicxml": {
  59478. "source": "iana",
  59479. "extensions": ["mxl"]
  59480. },
  59481. "application/vnd.recordare.musicxml+xml": {
  59482. "source": "iana",
  59483. "compressible": true,
  59484. "extensions": ["musicxml"]
  59485. },
  59486. "application/vnd.renlearn.rlprint": {
  59487. "source": "iana"
  59488. },
  59489. "application/vnd.restful+json": {
  59490. "source": "iana",
  59491. "compressible": true
  59492. },
  59493. "application/vnd.rig.cryptonote": {
  59494. "source": "iana",
  59495. "extensions": ["cryptonote"]
  59496. },
  59497. "application/vnd.rim.cod": {
  59498. "source": "apache",
  59499. "extensions": ["cod"]
  59500. },
  59501. "application/vnd.rn-realmedia": {
  59502. "source": "apache",
  59503. "extensions": ["rm"]
  59504. },
  59505. "application/vnd.rn-realmedia-vbr": {
  59506. "source": "apache",
  59507. "extensions": ["rmvb"]
  59508. },
  59509. "application/vnd.route66.link66+xml": {
  59510. "source": "iana",
  59511. "compressible": true,
  59512. "extensions": ["link66"]
  59513. },
  59514. "application/vnd.rs-274x": {
  59515. "source": "iana"
  59516. },
  59517. "application/vnd.ruckus.download": {
  59518. "source": "iana"
  59519. },
  59520. "application/vnd.s3sms": {
  59521. "source": "iana"
  59522. },
  59523. "application/vnd.sailingtracker.track": {
  59524. "source": "iana",
  59525. "extensions": ["st"]
  59526. },
  59527. "application/vnd.sar": {
  59528. "source": "iana"
  59529. },
  59530. "application/vnd.sbm.cid": {
  59531. "source": "iana"
  59532. },
  59533. "application/vnd.sbm.mid2": {
  59534. "source": "iana"
  59535. },
  59536. "application/vnd.scribus": {
  59537. "source": "iana"
  59538. },
  59539. "application/vnd.sealed.3df": {
  59540. "source": "iana"
  59541. },
  59542. "application/vnd.sealed.csf": {
  59543. "source": "iana"
  59544. },
  59545. "application/vnd.sealed.doc": {
  59546. "source": "iana"
  59547. },
  59548. "application/vnd.sealed.eml": {
  59549. "source": "iana"
  59550. },
  59551. "application/vnd.sealed.mht": {
  59552. "source": "iana"
  59553. },
  59554. "application/vnd.sealed.net": {
  59555. "source": "iana"
  59556. },
  59557. "application/vnd.sealed.ppt": {
  59558. "source": "iana"
  59559. },
  59560. "application/vnd.sealed.tiff": {
  59561. "source": "iana"
  59562. },
  59563. "application/vnd.sealed.xls": {
  59564. "source": "iana"
  59565. },
  59566. "application/vnd.sealedmedia.softseal.html": {
  59567. "source": "iana"
  59568. },
  59569. "application/vnd.sealedmedia.softseal.pdf": {
  59570. "source": "iana"
  59571. },
  59572. "application/vnd.seemail": {
  59573. "source": "iana",
  59574. "extensions": ["see"]
  59575. },
  59576. "application/vnd.sema": {
  59577. "source": "iana",
  59578. "extensions": ["sema"]
  59579. },
  59580. "application/vnd.semd": {
  59581. "source": "iana",
  59582. "extensions": ["semd"]
  59583. },
  59584. "application/vnd.semf": {
  59585. "source": "iana",
  59586. "extensions": ["semf"]
  59587. },
  59588. "application/vnd.shade-save-file": {
  59589. "source": "iana"
  59590. },
  59591. "application/vnd.shana.informed.formdata": {
  59592. "source": "iana",
  59593. "extensions": ["ifm"]
  59594. },
  59595. "application/vnd.shana.informed.formtemplate": {
  59596. "source": "iana",
  59597. "extensions": ["itp"]
  59598. },
  59599. "application/vnd.shana.informed.interchange": {
  59600. "source": "iana",
  59601. "extensions": ["iif"]
  59602. },
  59603. "application/vnd.shana.informed.package": {
  59604. "source": "iana",
  59605. "extensions": ["ipk"]
  59606. },
  59607. "application/vnd.shootproof+json": {
  59608. "source": "iana",
  59609. "compressible": true
  59610. },
  59611. "application/vnd.shopkick+json": {
  59612. "source": "iana",
  59613. "compressible": true
  59614. },
  59615. "application/vnd.shp": {
  59616. "source": "iana"
  59617. },
  59618. "application/vnd.shx": {
  59619. "source": "iana"
  59620. },
  59621. "application/vnd.sigrok.session": {
  59622. "source": "iana"
  59623. },
  59624. "application/vnd.simtech-mindmapper": {
  59625. "source": "iana",
  59626. "extensions": ["twd","twds"]
  59627. },
  59628. "application/vnd.siren+json": {
  59629. "source": "iana",
  59630. "compressible": true
  59631. },
  59632. "application/vnd.smaf": {
  59633. "source": "iana",
  59634. "extensions": ["mmf"]
  59635. },
  59636. "application/vnd.smart.notebook": {
  59637. "source": "iana"
  59638. },
  59639. "application/vnd.smart.teacher": {
  59640. "source": "iana",
  59641. "extensions": ["teacher"]
  59642. },
  59643. "application/vnd.snesdev-page-table": {
  59644. "source": "iana"
  59645. },
  59646. "application/vnd.software602.filler.form+xml": {
  59647. "source": "iana",
  59648. "compressible": true,
  59649. "extensions": ["fo"]
  59650. },
  59651. "application/vnd.software602.filler.form-xml-zip": {
  59652. "source": "iana"
  59653. },
  59654. "application/vnd.solent.sdkm+xml": {
  59655. "source": "iana",
  59656. "compressible": true,
  59657. "extensions": ["sdkm","sdkd"]
  59658. },
  59659. "application/vnd.spotfire.dxp": {
  59660. "source": "iana",
  59661. "extensions": ["dxp"]
  59662. },
  59663. "application/vnd.spotfire.sfs": {
  59664. "source": "iana",
  59665. "extensions": ["sfs"]
  59666. },
  59667. "application/vnd.sqlite3": {
  59668. "source": "iana"
  59669. },
  59670. "application/vnd.sss-cod": {
  59671. "source": "iana"
  59672. },
  59673. "application/vnd.sss-dtf": {
  59674. "source": "iana"
  59675. },
  59676. "application/vnd.sss-ntf": {
  59677. "source": "iana"
  59678. },
  59679. "application/vnd.stardivision.calc": {
  59680. "source": "apache",
  59681. "extensions": ["sdc"]
  59682. },
  59683. "application/vnd.stardivision.draw": {
  59684. "source": "apache",
  59685. "extensions": ["sda"]
  59686. },
  59687. "application/vnd.stardivision.impress": {
  59688. "source": "apache",
  59689. "extensions": ["sdd"]
  59690. },
  59691. "application/vnd.stardivision.math": {
  59692. "source": "apache",
  59693. "extensions": ["smf"]
  59694. },
  59695. "application/vnd.stardivision.writer": {
  59696. "source": "apache",
  59697. "extensions": ["sdw","vor"]
  59698. },
  59699. "application/vnd.stardivision.writer-global": {
  59700. "source": "apache",
  59701. "extensions": ["sgl"]
  59702. },
  59703. "application/vnd.stepmania.package": {
  59704. "source": "iana",
  59705. "extensions": ["smzip"]
  59706. },
  59707. "application/vnd.stepmania.stepchart": {
  59708. "source": "iana",
  59709. "extensions": ["sm"]
  59710. },
  59711. "application/vnd.street-stream": {
  59712. "source": "iana"
  59713. },
  59714. "application/vnd.sun.wadl+xml": {
  59715. "source": "iana",
  59716. "compressible": true,
  59717. "extensions": ["wadl"]
  59718. },
  59719. "application/vnd.sun.xml.calc": {
  59720. "source": "apache",
  59721. "extensions": ["sxc"]
  59722. },
  59723. "application/vnd.sun.xml.calc.template": {
  59724. "source": "apache",
  59725. "extensions": ["stc"]
  59726. },
  59727. "application/vnd.sun.xml.draw": {
  59728. "source": "apache",
  59729. "extensions": ["sxd"]
  59730. },
  59731. "application/vnd.sun.xml.draw.template": {
  59732. "source": "apache",
  59733. "extensions": ["std"]
  59734. },
  59735. "application/vnd.sun.xml.impress": {
  59736. "source": "apache",
  59737. "extensions": ["sxi"]
  59738. },
  59739. "application/vnd.sun.xml.impress.template": {
  59740. "source": "apache",
  59741. "extensions": ["sti"]
  59742. },
  59743. "application/vnd.sun.xml.math": {
  59744. "source": "apache",
  59745. "extensions": ["sxm"]
  59746. },
  59747. "application/vnd.sun.xml.writer": {
  59748. "source": "apache",
  59749. "extensions": ["sxw"]
  59750. },
  59751. "application/vnd.sun.xml.writer.global": {
  59752. "source": "apache",
  59753. "extensions": ["sxg"]
  59754. },
  59755. "application/vnd.sun.xml.writer.template": {
  59756. "source": "apache",
  59757. "extensions": ["stw"]
  59758. },
  59759. "application/vnd.sus-calendar": {
  59760. "source": "iana",
  59761. "extensions": ["sus","susp"]
  59762. },
  59763. "application/vnd.svd": {
  59764. "source": "iana",
  59765. "extensions": ["svd"]
  59766. },
  59767. "application/vnd.swiftview-ics": {
  59768. "source": "iana"
  59769. },
  59770. "application/vnd.symbian.install": {
  59771. "source": "apache",
  59772. "extensions": ["sis","sisx"]
  59773. },
  59774. "application/vnd.syncml+xml": {
  59775. "source": "iana",
  59776. "charset": "UTF-8",
  59777. "compressible": true,
  59778. "extensions": ["xsm"]
  59779. },
  59780. "application/vnd.syncml.dm+wbxml": {
  59781. "source": "iana",
  59782. "charset": "UTF-8",
  59783. "extensions": ["bdm"]
  59784. },
  59785. "application/vnd.syncml.dm+xml": {
  59786. "source": "iana",
  59787. "charset": "UTF-8",
  59788. "compressible": true,
  59789. "extensions": ["xdm"]
  59790. },
  59791. "application/vnd.syncml.dm.notification": {
  59792. "source": "iana"
  59793. },
  59794. "application/vnd.syncml.dmddf+wbxml": {
  59795. "source": "iana"
  59796. },
  59797. "application/vnd.syncml.dmddf+xml": {
  59798. "source": "iana",
  59799. "charset": "UTF-8",
  59800. "compressible": true,
  59801. "extensions": ["ddf"]
  59802. },
  59803. "application/vnd.syncml.dmtnds+wbxml": {
  59804. "source": "iana"
  59805. },
  59806. "application/vnd.syncml.dmtnds+xml": {
  59807. "source": "iana",
  59808. "charset": "UTF-8",
  59809. "compressible": true
  59810. },
  59811. "application/vnd.syncml.ds.notification": {
  59812. "source": "iana"
  59813. },
  59814. "application/vnd.tableschema+json": {
  59815. "source": "iana",
  59816. "compressible": true
  59817. },
  59818. "application/vnd.tao.intent-module-archive": {
  59819. "source": "iana",
  59820. "extensions": ["tao"]
  59821. },
  59822. "application/vnd.tcpdump.pcap": {
  59823. "source": "iana",
  59824. "extensions": ["pcap","cap","dmp"]
  59825. },
  59826. "application/vnd.think-cell.ppttc+json": {
  59827. "source": "iana",
  59828. "compressible": true
  59829. },
  59830. "application/vnd.tmd.mediaflex.api+xml": {
  59831. "source": "iana",
  59832. "compressible": true
  59833. },
  59834. "application/vnd.tml": {
  59835. "source": "iana"
  59836. },
  59837. "application/vnd.tmobile-livetv": {
  59838. "source": "iana",
  59839. "extensions": ["tmo"]
  59840. },
  59841. "application/vnd.tri.onesource": {
  59842. "source": "iana"
  59843. },
  59844. "application/vnd.trid.tpt": {
  59845. "source": "iana",
  59846. "extensions": ["tpt"]
  59847. },
  59848. "application/vnd.triscape.mxs": {
  59849. "source": "iana",
  59850. "extensions": ["mxs"]
  59851. },
  59852. "application/vnd.trueapp": {
  59853. "source": "iana",
  59854. "extensions": ["tra"]
  59855. },
  59856. "application/vnd.truedoc": {
  59857. "source": "iana"
  59858. },
  59859. "application/vnd.ubisoft.webplayer": {
  59860. "source": "iana"
  59861. },
  59862. "application/vnd.ufdl": {
  59863. "source": "iana",
  59864. "extensions": ["ufd","ufdl"]
  59865. },
  59866. "application/vnd.uiq.theme": {
  59867. "source": "iana",
  59868. "extensions": ["utz"]
  59869. },
  59870. "application/vnd.umajin": {
  59871. "source": "iana",
  59872. "extensions": ["umj"]
  59873. },
  59874. "application/vnd.unity": {
  59875. "source": "iana",
  59876. "extensions": ["unityweb"]
  59877. },
  59878. "application/vnd.uoml+xml": {
  59879. "source": "iana",
  59880. "compressible": true,
  59881. "extensions": ["uoml"]
  59882. },
  59883. "application/vnd.uplanet.alert": {
  59884. "source": "iana"
  59885. },
  59886. "application/vnd.uplanet.alert-wbxml": {
  59887. "source": "iana"
  59888. },
  59889. "application/vnd.uplanet.bearer-choice": {
  59890. "source": "iana"
  59891. },
  59892. "application/vnd.uplanet.bearer-choice-wbxml": {
  59893. "source": "iana"
  59894. },
  59895. "application/vnd.uplanet.cacheop": {
  59896. "source": "iana"
  59897. },
  59898. "application/vnd.uplanet.cacheop-wbxml": {
  59899. "source": "iana"
  59900. },
  59901. "application/vnd.uplanet.channel": {
  59902. "source": "iana"
  59903. },
  59904. "application/vnd.uplanet.channel-wbxml": {
  59905. "source": "iana"
  59906. },
  59907. "application/vnd.uplanet.list": {
  59908. "source": "iana"
  59909. },
  59910. "application/vnd.uplanet.list-wbxml": {
  59911. "source": "iana"
  59912. },
  59913. "application/vnd.uplanet.listcmd": {
  59914. "source": "iana"
  59915. },
  59916. "application/vnd.uplanet.listcmd-wbxml": {
  59917. "source": "iana"
  59918. },
  59919. "application/vnd.uplanet.signal": {
  59920. "source": "iana"
  59921. },
  59922. "application/vnd.uri-map": {
  59923. "source": "iana"
  59924. },
  59925. "application/vnd.valve.source.material": {
  59926. "source": "iana"
  59927. },
  59928. "application/vnd.vcx": {
  59929. "source": "iana",
  59930. "extensions": ["vcx"]
  59931. },
  59932. "application/vnd.vd-study": {
  59933. "source": "iana"
  59934. },
  59935. "application/vnd.vectorworks": {
  59936. "source": "iana"
  59937. },
  59938. "application/vnd.vel+json": {
  59939. "source": "iana",
  59940. "compressible": true
  59941. },
  59942. "application/vnd.verimatrix.vcas": {
  59943. "source": "iana"
  59944. },
  59945. "application/vnd.veryant.thin": {
  59946. "source": "iana"
  59947. },
  59948. "application/vnd.ves.encrypted": {
  59949. "source": "iana"
  59950. },
  59951. "application/vnd.vidsoft.vidconference": {
  59952. "source": "iana"
  59953. },
  59954. "application/vnd.visio": {
  59955. "source": "iana",
  59956. "extensions": ["vsd","vst","vss","vsw"]
  59957. },
  59958. "application/vnd.visionary": {
  59959. "source": "iana",
  59960. "extensions": ["vis"]
  59961. },
  59962. "application/vnd.vividence.scriptfile": {
  59963. "source": "iana"
  59964. },
  59965. "application/vnd.vsf": {
  59966. "source": "iana",
  59967. "extensions": ["vsf"]
  59968. },
  59969. "application/vnd.wap.sic": {
  59970. "source": "iana"
  59971. },
  59972. "application/vnd.wap.slc": {
  59973. "source": "iana"
  59974. },
  59975. "application/vnd.wap.wbxml": {
  59976. "source": "iana",
  59977. "charset": "UTF-8",
  59978. "extensions": ["wbxml"]
  59979. },
  59980. "application/vnd.wap.wmlc": {
  59981. "source": "iana",
  59982. "extensions": ["wmlc"]
  59983. },
  59984. "application/vnd.wap.wmlscriptc": {
  59985. "source": "iana",
  59986. "extensions": ["wmlsc"]
  59987. },
  59988. "application/vnd.webturbo": {
  59989. "source": "iana",
  59990. "extensions": ["wtb"]
  59991. },
  59992. "application/vnd.wfa.p2p": {
  59993. "source": "iana"
  59994. },
  59995. "application/vnd.wfa.wsc": {
  59996. "source": "iana"
  59997. },
  59998. "application/vnd.windows.devicepairing": {
  59999. "source": "iana"
  60000. },
  60001. "application/vnd.wmc": {
  60002. "source": "iana"
  60003. },
  60004. "application/vnd.wmf.bootstrap": {
  60005. "source": "iana"
  60006. },
  60007. "application/vnd.wolfram.mathematica": {
  60008. "source": "iana"
  60009. },
  60010. "application/vnd.wolfram.mathematica.package": {
  60011. "source": "iana"
  60012. },
  60013. "application/vnd.wolfram.player": {
  60014. "source": "iana",
  60015. "extensions": ["nbp"]
  60016. },
  60017. "application/vnd.wordperfect": {
  60018. "source": "iana",
  60019. "extensions": ["wpd"]
  60020. },
  60021. "application/vnd.wqd": {
  60022. "source": "iana",
  60023. "extensions": ["wqd"]
  60024. },
  60025. "application/vnd.wrq-hp3000-labelled": {
  60026. "source": "iana"
  60027. },
  60028. "application/vnd.wt.stf": {
  60029. "source": "iana",
  60030. "extensions": ["stf"]
  60031. },
  60032. "application/vnd.wv.csp+wbxml": {
  60033. "source": "iana"
  60034. },
  60035. "application/vnd.wv.csp+xml": {
  60036. "source": "iana",
  60037. "compressible": true
  60038. },
  60039. "application/vnd.wv.ssp+xml": {
  60040. "source": "iana",
  60041. "compressible": true
  60042. },
  60043. "application/vnd.xacml+json": {
  60044. "source": "iana",
  60045. "compressible": true
  60046. },
  60047. "application/vnd.xara": {
  60048. "source": "iana",
  60049. "extensions": ["xar"]
  60050. },
  60051. "application/vnd.xfdl": {
  60052. "source": "iana",
  60053. "extensions": ["xfdl"]
  60054. },
  60055. "application/vnd.xfdl.webform": {
  60056. "source": "iana"
  60057. },
  60058. "application/vnd.xmi+xml": {
  60059. "source": "iana",
  60060. "compressible": true
  60061. },
  60062. "application/vnd.xmpie.cpkg": {
  60063. "source": "iana"
  60064. },
  60065. "application/vnd.xmpie.dpkg": {
  60066. "source": "iana"
  60067. },
  60068. "application/vnd.xmpie.plan": {
  60069. "source": "iana"
  60070. },
  60071. "application/vnd.xmpie.ppkg": {
  60072. "source": "iana"
  60073. },
  60074. "application/vnd.xmpie.xlim": {
  60075. "source": "iana"
  60076. },
  60077. "application/vnd.yamaha.hv-dic": {
  60078. "source": "iana",
  60079. "extensions": ["hvd"]
  60080. },
  60081. "application/vnd.yamaha.hv-script": {
  60082. "source": "iana",
  60083. "extensions": ["hvs"]
  60084. },
  60085. "application/vnd.yamaha.hv-voice": {
  60086. "source": "iana",
  60087. "extensions": ["hvp"]
  60088. },
  60089. "application/vnd.yamaha.openscoreformat": {
  60090. "source": "iana",
  60091. "extensions": ["osf"]
  60092. },
  60093. "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
  60094. "source": "iana",
  60095. "compressible": true,
  60096. "extensions": ["osfpvg"]
  60097. },
  60098. "application/vnd.yamaha.remote-setup": {
  60099. "source": "iana"
  60100. },
  60101. "application/vnd.yamaha.smaf-audio": {
  60102. "source": "iana",
  60103. "extensions": ["saf"]
  60104. },
  60105. "application/vnd.yamaha.smaf-phrase": {
  60106. "source": "iana",
  60107. "extensions": ["spf"]
  60108. },
  60109. "application/vnd.yamaha.through-ngn": {
  60110. "source": "iana"
  60111. },
  60112. "application/vnd.yamaha.tunnel-udpencap": {
  60113. "source": "iana"
  60114. },
  60115. "application/vnd.yaoweme": {
  60116. "source": "iana"
  60117. },
  60118. "application/vnd.yellowriver-custom-menu": {
  60119. "source": "iana",
  60120. "extensions": ["cmp"]
  60121. },
  60122. "application/vnd.youtube.yt": {
  60123. "source": "iana"
  60124. },
  60125. "application/vnd.zul": {
  60126. "source": "iana",
  60127. "extensions": ["zir","zirz"]
  60128. },
  60129. "application/vnd.zzazz.deck+xml": {
  60130. "source": "iana",
  60131. "compressible": true,
  60132. "extensions": ["zaz"]
  60133. },
  60134. "application/voicexml+xml": {
  60135. "source": "iana",
  60136. "compressible": true,
  60137. "extensions": ["vxml"]
  60138. },
  60139. "application/voucher-cms+json": {
  60140. "source": "iana",
  60141. "compressible": true
  60142. },
  60143. "application/vq-rtcpxr": {
  60144. "source": "iana"
  60145. },
  60146. "application/wasm": {
  60147. "compressible": true,
  60148. "extensions": ["wasm"]
  60149. },
  60150. "application/watcherinfo+xml": {
  60151. "source": "iana",
  60152. "compressible": true
  60153. },
  60154. "application/webpush-options+json": {
  60155. "source": "iana",
  60156. "compressible": true
  60157. },
  60158. "application/whoispp-query": {
  60159. "source": "iana"
  60160. },
  60161. "application/whoispp-response": {
  60162. "source": "iana"
  60163. },
  60164. "application/widget": {
  60165. "source": "iana",
  60166. "extensions": ["wgt"]
  60167. },
  60168. "application/winhlp": {
  60169. "source": "apache",
  60170. "extensions": ["hlp"]
  60171. },
  60172. "application/wita": {
  60173. "source": "iana"
  60174. },
  60175. "application/wordperfect5.1": {
  60176. "source": "iana"
  60177. },
  60178. "application/wsdl+xml": {
  60179. "source": "iana",
  60180. "compressible": true,
  60181. "extensions": ["wsdl"]
  60182. },
  60183. "application/wspolicy+xml": {
  60184. "source": "iana",
  60185. "compressible": true,
  60186. "extensions": ["wspolicy"]
  60187. },
  60188. "application/x-7z-compressed": {
  60189. "source": "apache",
  60190. "compressible": false,
  60191. "extensions": ["7z"]
  60192. },
  60193. "application/x-abiword": {
  60194. "source": "apache",
  60195. "extensions": ["abw"]
  60196. },
  60197. "application/x-ace-compressed": {
  60198. "source": "apache",
  60199. "extensions": ["ace"]
  60200. },
  60201. "application/x-amf": {
  60202. "source": "apache"
  60203. },
  60204. "application/x-apple-diskimage": {
  60205. "source": "apache",
  60206. "extensions": ["dmg"]
  60207. },
  60208. "application/x-arj": {
  60209. "compressible": false,
  60210. "extensions": ["arj"]
  60211. },
  60212. "application/x-authorware-bin": {
  60213. "source": "apache",
  60214. "extensions": ["aab","x32","u32","vox"]
  60215. },
  60216. "application/x-authorware-map": {
  60217. "source": "apache",
  60218. "extensions": ["aam"]
  60219. },
  60220. "application/x-authorware-seg": {
  60221. "source": "apache",
  60222. "extensions": ["aas"]
  60223. },
  60224. "application/x-bcpio": {
  60225. "source": "apache",
  60226. "extensions": ["bcpio"]
  60227. },
  60228. "application/x-bdoc": {
  60229. "compressible": false,
  60230. "extensions": ["bdoc"]
  60231. },
  60232. "application/x-bittorrent": {
  60233. "source": "apache",
  60234. "extensions": ["torrent"]
  60235. },
  60236. "application/x-blorb": {
  60237. "source": "apache",
  60238. "extensions": ["blb","blorb"]
  60239. },
  60240. "application/x-bzip": {
  60241. "source": "apache",
  60242. "compressible": false,
  60243. "extensions": ["bz"]
  60244. },
  60245. "application/x-bzip2": {
  60246. "source": "apache",
  60247. "compressible": false,
  60248. "extensions": ["bz2","boz"]
  60249. },
  60250. "application/x-cbr": {
  60251. "source": "apache",
  60252. "extensions": ["cbr","cba","cbt","cbz","cb7"]
  60253. },
  60254. "application/x-cdlink": {
  60255. "source": "apache",
  60256. "extensions": ["vcd"]
  60257. },
  60258. "application/x-cfs-compressed": {
  60259. "source": "apache",
  60260. "extensions": ["cfs"]
  60261. },
  60262. "application/x-chat": {
  60263. "source": "apache",
  60264. "extensions": ["chat"]
  60265. },
  60266. "application/x-chess-pgn": {
  60267. "source": "apache",
  60268. "extensions": ["pgn"]
  60269. },
  60270. "application/x-chrome-extension": {
  60271. "extensions": ["crx"]
  60272. },
  60273. "application/x-cocoa": {
  60274. "source": "nginx",
  60275. "extensions": ["cco"]
  60276. },
  60277. "application/x-compress": {
  60278. "source": "apache"
  60279. },
  60280. "application/x-conference": {
  60281. "source": "apache",
  60282. "extensions": ["nsc"]
  60283. },
  60284. "application/x-cpio": {
  60285. "source": "apache",
  60286. "extensions": ["cpio"]
  60287. },
  60288. "application/x-csh": {
  60289. "source": "apache",
  60290. "extensions": ["csh"]
  60291. },
  60292. "application/x-deb": {
  60293. "compressible": false
  60294. },
  60295. "application/x-debian-package": {
  60296. "source": "apache",
  60297. "extensions": ["deb","udeb"]
  60298. },
  60299. "application/x-dgc-compressed": {
  60300. "source": "apache",
  60301. "extensions": ["dgc"]
  60302. },
  60303. "application/x-director": {
  60304. "source": "apache",
  60305. "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]
  60306. },
  60307. "application/x-doom": {
  60308. "source": "apache",
  60309. "extensions": ["wad"]
  60310. },
  60311. "application/x-dtbncx+xml": {
  60312. "source": "apache",
  60313. "compressible": true,
  60314. "extensions": ["ncx"]
  60315. },
  60316. "application/x-dtbook+xml": {
  60317. "source": "apache",
  60318. "compressible": true,
  60319. "extensions": ["dtb"]
  60320. },
  60321. "application/x-dtbresource+xml": {
  60322. "source": "apache",
  60323. "compressible": true,
  60324. "extensions": ["res"]
  60325. },
  60326. "application/x-dvi": {
  60327. "source": "apache",
  60328. "compressible": false,
  60329. "extensions": ["dvi"]
  60330. },
  60331. "application/x-envoy": {
  60332. "source": "apache",
  60333. "extensions": ["evy"]
  60334. },
  60335. "application/x-eva": {
  60336. "source": "apache",
  60337. "extensions": ["eva"]
  60338. },
  60339. "application/x-font-bdf": {
  60340. "source": "apache",
  60341. "extensions": ["bdf"]
  60342. },
  60343. "application/x-font-dos": {
  60344. "source": "apache"
  60345. },
  60346. "application/x-font-framemaker": {
  60347. "source": "apache"
  60348. },
  60349. "application/x-font-ghostscript": {
  60350. "source": "apache",
  60351. "extensions": ["gsf"]
  60352. },
  60353. "application/x-font-libgrx": {
  60354. "source": "apache"
  60355. },
  60356. "application/x-font-linux-psf": {
  60357. "source": "apache",
  60358. "extensions": ["psf"]
  60359. },
  60360. "application/x-font-pcf": {
  60361. "source": "apache",
  60362. "extensions": ["pcf"]
  60363. },
  60364. "application/x-font-snf": {
  60365. "source": "apache",
  60366. "extensions": ["snf"]
  60367. },
  60368. "application/x-font-speedo": {
  60369. "source": "apache"
  60370. },
  60371. "application/x-font-sunos-news": {
  60372. "source": "apache"
  60373. },
  60374. "application/x-font-type1": {
  60375. "source": "apache",
  60376. "extensions": ["pfa","pfb","pfm","afm"]
  60377. },
  60378. "application/x-font-vfont": {
  60379. "source": "apache"
  60380. },
  60381. "application/x-freearc": {
  60382. "source": "apache",
  60383. "extensions": ["arc"]
  60384. },
  60385. "application/x-futuresplash": {
  60386. "source": "apache",
  60387. "extensions": ["spl"]
  60388. },
  60389. "application/x-gca-compressed": {
  60390. "source": "apache",
  60391. "extensions": ["gca"]
  60392. },
  60393. "application/x-glulx": {
  60394. "source": "apache",
  60395. "extensions": ["ulx"]
  60396. },
  60397. "application/x-gnumeric": {
  60398. "source": "apache",
  60399. "extensions": ["gnumeric"]
  60400. },
  60401. "application/x-gramps-xml": {
  60402. "source": "apache",
  60403. "extensions": ["gramps"]
  60404. },
  60405. "application/x-gtar": {
  60406. "source": "apache",
  60407. "extensions": ["gtar"]
  60408. },
  60409. "application/x-gzip": {
  60410. "source": "apache"
  60411. },
  60412. "application/x-hdf": {
  60413. "source": "apache",
  60414. "extensions": ["hdf"]
  60415. },
  60416. "application/x-httpd-php": {
  60417. "compressible": true,
  60418. "extensions": ["php"]
  60419. },
  60420. "application/x-install-instructions": {
  60421. "source": "apache",
  60422. "extensions": ["install"]
  60423. },
  60424. "application/x-iso9660-image": {
  60425. "source": "apache",
  60426. "extensions": ["iso"]
  60427. },
  60428. "application/x-java-archive-diff": {
  60429. "source": "nginx",
  60430. "extensions": ["jardiff"]
  60431. },
  60432. "application/x-java-jnlp-file": {
  60433. "source": "apache",
  60434. "compressible": false,
  60435. "extensions": ["jnlp"]
  60436. },
  60437. "application/x-javascript": {
  60438. "compressible": true
  60439. },
  60440. "application/x-keepass2": {
  60441. "extensions": ["kdbx"]
  60442. },
  60443. "application/x-latex": {
  60444. "source": "apache",
  60445. "compressible": false,
  60446. "extensions": ["latex"]
  60447. },
  60448. "application/x-lua-bytecode": {
  60449. "extensions": ["luac"]
  60450. },
  60451. "application/x-lzh-compressed": {
  60452. "source": "apache",
  60453. "extensions": ["lzh","lha"]
  60454. },
  60455. "application/x-makeself": {
  60456. "source": "nginx",
  60457. "extensions": ["run"]
  60458. },
  60459. "application/x-mie": {
  60460. "source": "apache",
  60461. "extensions": ["mie"]
  60462. },
  60463. "application/x-mobipocket-ebook": {
  60464. "source": "apache",
  60465. "extensions": ["prc","mobi"]
  60466. },
  60467. "application/x-mpegurl": {
  60468. "compressible": false
  60469. },
  60470. "application/x-ms-application": {
  60471. "source": "apache",
  60472. "extensions": ["application"]
  60473. },
  60474. "application/x-ms-shortcut": {
  60475. "source": "apache",
  60476. "extensions": ["lnk"]
  60477. },
  60478. "application/x-ms-wmd": {
  60479. "source": "apache",
  60480. "extensions": ["wmd"]
  60481. },
  60482. "application/x-ms-wmz": {
  60483. "source": "apache",
  60484. "extensions": ["wmz"]
  60485. },
  60486. "application/x-ms-xbap": {
  60487. "source": "apache",
  60488. "extensions": ["xbap"]
  60489. },
  60490. "application/x-msaccess": {
  60491. "source": "apache",
  60492. "extensions": ["mdb"]
  60493. },
  60494. "application/x-msbinder": {
  60495. "source": "apache",
  60496. "extensions": ["obd"]
  60497. },
  60498. "application/x-mscardfile": {
  60499. "source": "apache",
  60500. "extensions": ["crd"]
  60501. },
  60502. "application/x-msclip": {
  60503. "source": "apache",
  60504. "extensions": ["clp"]
  60505. },
  60506. "application/x-msdos-program": {
  60507. "extensions": ["exe"]
  60508. },
  60509. "application/x-msdownload": {
  60510. "source": "apache",
  60511. "extensions": ["exe","dll","com","bat","msi"]
  60512. },
  60513. "application/x-msmediaview": {
  60514. "source": "apache",
  60515. "extensions": ["mvb","m13","m14"]
  60516. },
  60517. "application/x-msmetafile": {
  60518. "source": "apache",
  60519. "extensions": ["wmf","wmz","emf","emz"]
  60520. },
  60521. "application/x-msmoney": {
  60522. "source": "apache",
  60523. "extensions": ["mny"]
  60524. },
  60525. "application/x-mspublisher": {
  60526. "source": "apache",
  60527. "extensions": ["pub"]
  60528. },
  60529. "application/x-msschedule": {
  60530. "source": "apache",
  60531. "extensions": ["scd"]
  60532. },
  60533. "application/x-msterminal": {
  60534. "source": "apache",
  60535. "extensions": ["trm"]
  60536. },
  60537. "application/x-mswrite": {
  60538. "source": "apache",
  60539. "extensions": ["wri"]
  60540. },
  60541. "application/x-netcdf": {
  60542. "source": "apache",
  60543. "extensions": ["nc","cdf"]
  60544. },
  60545. "application/x-ns-proxy-autoconfig": {
  60546. "compressible": true,
  60547. "extensions": ["pac"]
  60548. },
  60549. "application/x-nzb": {
  60550. "source": "apache",
  60551. "extensions": ["nzb"]
  60552. },
  60553. "application/x-perl": {
  60554. "source": "nginx",
  60555. "extensions": ["pl","pm"]
  60556. },
  60557. "application/x-pilot": {
  60558. "source": "nginx",
  60559. "extensions": ["prc","pdb"]
  60560. },
  60561. "application/x-pkcs12": {
  60562. "source": "apache",
  60563. "compressible": false,
  60564. "extensions": ["p12","pfx"]
  60565. },
  60566. "application/x-pkcs7-certificates": {
  60567. "source": "apache",
  60568. "extensions": ["p7b","spc"]
  60569. },
  60570. "application/x-pkcs7-certreqresp": {
  60571. "source": "apache",
  60572. "extensions": ["p7r"]
  60573. },
  60574. "application/x-pki-message": {
  60575. "source": "iana"
  60576. },
  60577. "application/x-rar-compressed": {
  60578. "source": "apache",
  60579. "compressible": false,
  60580. "extensions": ["rar"]
  60581. },
  60582. "application/x-redhat-package-manager": {
  60583. "source": "nginx",
  60584. "extensions": ["rpm"]
  60585. },
  60586. "application/x-research-info-systems": {
  60587. "source": "apache",
  60588. "extensions": ["ris"]
  60589. },
  60590. "application/x-sea": {
  60591. "source": "nginx",
  60592. "extensions": ["sea"]
  60593. },
  60594. "application/x-sh": {
  60595. "source": "apache",
  60596. "compressible": true,
  60597. "extensions": ["sh"]
  60598. },
  60599. "application/x-shar": {
  60600. "source": "apache",
  60601. "extensions": ["shar"]
  60602. },
  60603. "application/x-shockwave-flash": {
  60604. "source": "apache",
  60605. "compressible": false,
  60606. "extensions": ["swf"]
  60607. },
  60608. "application/x-silverlight-app": {
  60609. "source": "apache",
  60610. "extensions": ["xap"]
  60611. },
  60612. "application/x-sql": {
  60613. "source": "apache",
  60614. "extensions": ["sql"]
  60615. },
  60616. "application/x-stuffit": {
  60617. "source": "apache",
  60618. "compressible": false,
  60619. "extensions": ["sit"]
  60620. },
  60621. "application/x-stuffitx": {
  60622. "source": "apache",
  60623. "extensions": ["sitx"]
  60624. },
  60625. "application/x-subrip": {
  60626. "source": "apache",
  60627. "extensions": ["srt"]
  60628. },
  60629. "application/x-sv4cpio": {
  60630. "source": "apache",
  60631. "extensions": ["sv4cpio"]
  60632. },
  60633. "application/x-sv4crc": {
  60634. "source": "apache",
  60635. "extensions": ["sv4crc"]
  60636. },
  60637. "application/x-t3vm-image": {
  60638. "source": "apache",
  60639. "extensions": ["t3"]
  60640. },
  60641. "application/x-tads": {
  60642. "source": "apache",
  60643. "extensions": ["gam"]
  60644. },
  60645. "application/x-tar": {
  60646. "source": "apache",
  60647. "compressible": true,
  60648. "extensions": ["tar"]
  60649. },
  60650. "application/x-tcl": {
  60651. "source": "apache",
  60652. "extensions": ["tcl","tk"]
  60653. },
  60654. "application/x-tex": {
  60655. "source": "apache",
  60656. "extensions": ["tex"]
  60657. },
  60658. "application/x-tex-tfm": {
  60659. "source": "apache",
  60660. "extensions": ["tfm"]
  60661. },
  60662. "application/x-texinfo": {
  60663. "source": "apache",
  60664. "extensions": ["texinfo","texi"]
  60665. },
  60666. "application/x-tgif": {
  60667. "source": "apache",
  60668. "extensions": ["obj"]
  60669. },
  60670. "application/x-ustar": {
  60671. "source": "apache",
  60672. "extensions": ["ustar"]
  60673. },
  60674. "application/x-virtualbox-hdd": {
  60675. "compressible": true,
  60676. "extensions": ["hdd"]
  60677. },
  60678. "application/x-virtualbox-ova": {
  60679. "compressible": true,
  60680. "extensions": ["ova"]
  60681. },
  60682. "application/x-virtualbox-ovf": {
  60683. "compressible": true,
  60684. "extensions": ["ovf"]
  60685. },
  60686. "application/x-virtualbox-vbox": {
  60687. "compressible": true,
  60688. "extensions": ["vbox"]
  60689. },
  60690. "application/x-virtualbox-vbox-extpack": {
  60691. "compressible": false,
  60692. "extensions": ["vbox-extpack"]
  60693. },
  60694. "application/x-virtualbox-vdi": {
  60695. "compressible": true,
  60696. "extensions": ["vdi"]
  60697. },
  60698. "application/x-virtualbox-vhd": {
  60699. "compressible": true,
  60700. "extensions": ["vhd"]
  60701. },
  60702. "application/x-virtualbox-vmdk": {
  60703. "compressible": true,
  60704. "extensions": ["vmdk"]
  60705. },
  60706. "application/x-wais-source": {
  60707. "source": "apache",
  60708. "extensions": ["src"]
  60709. },
  60710. "application/x-web-app-manifest+json": {
  60711. "compressible": true,
  60712. "extensions": ["webapp"]
  60713. },
  60714. "application/x-www-form-urlencoded": {
  60715. "source": "iana",
  60716. "compressible": true
  60717. },
  60718. "application/x-x509-ca-cert": {
  60719. "source": "iana",
  60720. "extensions": ["der","crt","pem"]
  60721. },
  60722. "application/x-x509-ca-ra-cert": {
  60723. "source": "iana"
  60724. },
  60725. "application/x-x509-next-ca-cert": {
  60726. "source": "iana"
  60727. },
  60728. "application/x-xfig": {
  60729. "source": "apache",
  60730. "extensions": ["fig"]
  60731. },
  60732. "application/x-xliff+xml": {
  60733. "source": "apache",
  60734. "compressible": true,
  60735. "extensions": ["xlf"]
  60736. },
  60737. "application/x-xpinstall": {
  60738. "source": "apache",
  60739. "compressible": false,
  60740. "extensions": ["xpi"]
  60741. },
  60742. "application/x-xz": {
  60743. "source": "apache",
  60744. "extensions": ["xz"]
  60745. },
  60746. "application/x-zmachine": {
  60747. "source": "apache",
  60748. "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"]
  60749. },
  60750. "application/x400-bp": {
  60751. "source": "iana"
  60752. },
  60753. "application/xacml+xml": {
  60754. "source": "iana",
  60755. "compressible": true
  60756. },
  60757. "application/xaml+xml": {
  60758. "source": "apache",
  60759. "compressible": true,
  60760. "extensions": ["xaml"]
  60761. },
  60762. "application/xcap-att+xml": {
  60763. "source": "iana",
  60764. "compressible": true,
  60765. "extensions": ["xav"]
  60766. },
  60767. "application/xcap-caps+xml": {
  60768. "source": "iana",
  60769. "compressible": true,
  60770. "extensions": ["xca"]
  60771. },
  60772. "application/xcap-diff+xml": {
  60773. "source": "iana",
  60774. "compressible": true,
  60775. "extensions": ["xdf"]
  60776. },
  60777. "application/xcap-el+xml": {
  60778. "source": "iana",
  60779. "compressible": true,
  60780. "extensions": ["xel"]
  60781. },
  60782. "application/xcap-error+xml": {
  60783. "source": "iana",
  60784. "compressible": true,
  60785. "extensions": ["xer"]
  60786. },
  60787. "application/xcap-ns+xml": {
  60788. "source": "iana",
  60789. "compressible": true,
  60790. "extensions": ["xns"]
  60791. },
  60792. "application/xcon-conference-info+xml": {
  60793. "source": "iana",
  60794. "compressible": true
  60795. },
  60796. "application/xcon-conference-info-diff+xml": {
  60797. "source": "iana",
  60798. "compressible": true
  60799. },
  60800. "application/xenc+xml": {
  60801. "source": "iana",
  60802. "compressible": true,
  60803. "extensions": ["xenc"]
  60804. },
  60805. "application/xhtml+xml": {
  60806. "source": "iana",
  60807. "compressible": true,
  60808. "extensions": ["xhtml","xht"]
  60809. },
  60810. "application/xhtml-voice+xml": {
  60811. "source": "apache",
  60812. "compressible": true
  60813. },
  60814. "application/xliff+xml": {
  60815. "source": "iana",
  60816. "compressible": true,
  60817. "extensions": ["xlf"]
  60818. },
  60819. "application/xml": {
  60820. "source": "iana",
  60821. "compressible": true,
  60822. "extensions": ["xml","xsl","xsd","rng"]
  60823. },
  60824. "application/xml-dtd": {
  60825. "source": "iana",
  60826. "compressible": true,
  60827. "extensions": ["dtd"]
  60828. },
  60829. "application/xml-external-parsed-entity": {
  60830. "source": "iana"
  60831. },
  60832. "application/xml-patch+xml": {
  60833. "source": "iana",
  60834. "compressible": true
  60835. },
  60836. "application/xmpp+xml": {
  60837. "source": "iana",
  60838. "compressible": true
  60839. },
  60840. "application/xop+xml": {
  60841. "source": "iana",
  60842. "compressible": true,
  60843. "extensions": ["xop"]
  60844. },
  60845. "application/xproc+xml": {
  60846. "source": "apache",
  60847. "compressible": true,
  60848. "extensions": ["xpl"]
  60849. },
  60850. "application/xslt+xml": {
  60851. "source": "iana",
  60852. "compressible": true,
  60853. "extensions": ["xslt"]
  60854. },
  60855. "application/xspf+xml": {
  60856. "source": "apache",
  60857. "compressible": true,
  60858. "extensions": ["xspf"]
  60859. },
  60860. "application/xv+xml": {
  60861. "source": "iana",
  60862. "compressible": true,
  60863. "extensions": ["mxml","xhvml","xvml","xvm"]
  60864. },
  60865. "application/yang": {
  60866. "source": "iana",
  60867. "extensions": ["yang"]
  60868. },
  60869. "application/yang-data+json": {
  60870. "source": "iana",
  60871. "compressible": true
  60872. },
  60873. "application/yang-data+xml": {
  60874. "source": "iana",
  60875. "compressible": true
  60876. },
  60877. "application/yang-patch+json": {
  60878. "source": "iana",
  60879. "compressible": true
  60880. },
  60881. "application/yang-patch+xml": {
  60882. "source": "iana",
  60883. "compressible": true
  60884. },
  60885. "application/yin+xml": {
  60886. "source": "iana",
  60887. "compressible": true,
  60888. "extensions": ["yin"]
  60889. },
  60890. "application/zip": {
  60891. "source": "iana",
  60892. "compressible": false,
  60893. "extensions": ["zip"]
  60894. },
  60895. "application/zlib": {
  60896. "source": "iana"
  60897. },
  60898. "application/zstd": {
  60899. "source": "iana"
  60900. },
  60901. "audio/1d-interleaved-parityfec": {
  60902. "source": "iana"
  60903. },
  60904. "audio/32kadpcm": {
  60905. "source": "iana"
  60906. },
  60907. "audio/3gpp": {
  60908. "source": "iana",
  60909. "compressible": false,
  60910. "extensions": ["3gpp"]
  60911. },
  60912. "audio/3gpp2": {
  60913. "source": "iana"
  60914. },
  60915. "audio/aac": {
  60916. "source": "iana"
  60917. },
  60918. "audio/ac3": {
  60919. "source": "iana"
  60920. },
  60921. "audio/adpcm": {
  60922. "source": "apache",
  60923. "extensions": ["adp"]
  60924. },
  60925. "audio/amr": {
  60926. "source": "iana"
  60927. },
  60928. "audio/amr-wb": {
  60929. "source": "iana"
  60930. },
  60931. "audio/amr-wb+": {
  60932. "source": "iana"
  60933. },
  60934. "audio/aptx": {
  60935. "source": "iana"
  60936. },
  60937. "audio/asc": {
  60938. "source": "iana"
  60939. },
  60940. "audio/atrac-advanced-lossless": {
  60941. "source": "iana"
  60942. },
  60943. "audio/atrac-x": {
  60944. "source": "iana"
  60945. },
  60946. "audio/atrac3": {
  60947. "source": "iana"
  60948. },
  60949. "audio/basic": {
  60950. "source": "iana",
  60951. "compressible": false,
  60952. "extensions": ["au","snd"]
  60953. },
  60954. "audio/bv16": {
  60955. "source": "iana"
  60956. },
  60957. "audio/bv32": {
  60958. "source": "iana"
  60959. },
  60960. "audio/clearmode": {
  60961. "source": "iana"
  60962. },
  60963. "audio/cn": {
  60964. "source": "iana"
  60965. },
  60966. "audio/dat12": {
  60967. "source": "iana"
  60968. },
  60969. "audio/dls": {
  60970. "source": "iana"
  60971. },
  60972. "audio/dsr-es201108": {
  60973. "source": "iana"
  60974. },
  60975. "audio/dsr-es202050": {
  60976. "source": "iana"
  60977. },
  60978. "audio/dsr-es202211": {
  60979. "source": "iana"
  60980. },
  60981. "audio/dsr-es202212": {
  60982. "source": "iana"
  60983. },
  60984. "audio/dv": {
  60985. "source": "iana"
  60986. },
  60987. "audio/dvi4": {
  60988. "source": "iana"
  60989. },
  60990. "audio/eac3": {
  60991. "source": "iana"
  60992. },
  60993. "audio/encaprtp": {
  60994. "source": "iana"
  60995. },
  60996. "audio/evrc": {
  60997. "source": "iana"
  60998. },
  60999. "audio/evrc-qcp": {
  61000. "source": "iana"
  61001. },
  61002. "audio/evrc0": {
  61003. "source": "iana"
  61004. },
  61005. "audio/evrc1": {
  61006. "source": "iana"
  61007. },
  61008. "audio/evrcb": {
  61009. "source": "iana"
  61010. },
  61011. "audio/evrcb0": {
  61012. "source": "iana"
  61013. },
  61014. "audio/evrcb1": {
  61015. "source": "iana"
  61016. },
  61017. "audio/evrcnw": {
  61018. "source": "iana"
  61019. },
  61020. "audio/evrcnw0": {
  61021. "source": "iana"
  61022. },
  61023. "audio/evrcnw1": {
  61024. "source": "iana"
  61025. },
  61026. "audio/evrcwb": {
  61027. "source": "iana"
  61028. },
  61029. "audio/evrcwb0": {
  61030. "source": "iana"
  61031. },
  61032. "audio/evrcwb1": {
  61033. "source": "iana"
  61034. },
  61035. "audio/evs": {
  61036. "source": "iana"
  61037. },
  61038. "audio/flexfec": {
  61039. "source": "iana"
  61040. },
  61041. "audio/fwdred": {
  61042. "source": "iana"
  61043. },
  61044. "audio/g711-0": {
  61045. "source": "iana"
  61046. },
  61047. "audio/g719": {
  61048. "source": "iana"
  61049. },
  61050. "audio/g722": {
  61051. "source": "iana"
  61052. },
  61053. "audio/g7221": {
  61054. "source": "iana"
  61055. },
  61056. "audio/g723": {
  61057. "source": "iana"
  61058. },
  61059. "audio/g726-16": {
  61060. "source": "iana"
  61061. },
  61062. "audio/g726-24": {
  61063. "source": "iana"
  61064. },
  61065. "audio/g726-32": {
  61066. "source": "iana"
  61067. },
  61068. "audio/g726-40": {
  61069. "source": "iana"
  61070. },
  61071. "audio/g728": {
  61072. "source": "iana"
  61073. },
  61074. "audio/g729": {
  61075. "source": "iana"
  61076. },
  61077. "audio/g7291": {
  61078. "source": "iana"
  61079. },
  61080. "audio/g729d": {
  61081. "source": "iana"
  61082. },
  61083. "audio/g729e": {
  61084. "source": "iana"
  61085. },
  61086. "audio/gsm": {
  61087. "source": "iana"
  61088. },
  61089. "audio/gsm-efr": {
  61090. "source": "iana"
  61091. },
  61092. "audio/gsm-hr-08": {
  61093. "source": "iana"
  61094. },
  61095. "audio/ilbc": {
  61096. "source": "iana"
  61097. },
  61098. "audio/ip-mr_v2.5": {
  61099. "source": "iana"
  61100. },
  61101. "audio/isac": {
  61102. "source": "apache"
  61103. },
  61104. "audio/l16": {
  61105. "source": "iana"
  61106. },
  61107. "audio/l20": {
  61108. "source": "iana"
  61109. },
  61110. "audio/l24": {
  61111. "source": "iana",
  61112. "compressible": false
  61113. },
  61114. "audio/l8": {
  61115. "source": "iana"
  61116. },
  61117. "audio/lpc": {
  61118. "source": "iana"
  61119. },
  61120. "audio/melp": {
  61121. "source": "iana"
  61122. },
  61123. "audio/melp1200": {
  61124. "source": "iana"
  61125. },
  61126. "audio/melp2400": {
  61127. "source": "iana"
  61128. },
  61129. "audio/melp600": {
  61130. "source": "iana"
  61131. },
  61132. "audio/mhas": {
  61133. "source": "iana"
  61134. },
  61135. "audio/midi": {
  61136. "source": "apache",
  61137. "extensions": ["mid","midi","kar","rmi"]
  61138. },
  61139. "audio/mobile-xmf": {
  61140. "source": "iana",
  61141. "extensions": ["mxmf"]
  61142. },
  61143. "audio/mp3": {
  61144. "compressible": false,
  61145. "extensions": ["mp3"]
  61146. },
  61147. "audio/mp4": {
  61148. "source": "iana",
  61149. "compressible": false,
  61150. "extensions": ["m4a","mp4a"]
  61151. },
  61152. "audio/mp4a-latm": {
  61153. "source": "iana"
  61154. },
  61155. "audio/mpa": {
  61156. "source": "iana"
  61157. },
  61158. "audio/mpa-robust": {
  61159. "source": "iana"
  61160. },
  61161. "audio/mpeg": {
  61162. "source": "iana",
  61163. "compressible": false,
  61164. "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"]
  61165. },
  61166. "audio/mpeg4-generic": {
  61167. "source": "iana"
  61168. },
  61169. "audio/musepack": {
  61170. "source": "apache"
  61171. },
  61172. "audio/ogg": {
  61173. "source": "iana",
  61174. "compressible": false,
  61175. "extensions": ["oga","ogg","spx"]
  61176. },
  61177. "audio/opus": {
  61178. "source": "iana"
  61179. },
  61180. "audio/parityfec": {
  61181. "source": "iana"
  61182. },
  61183. "audio/pcma": {
  61184. "source": "iana"
  61185. },
  61186. "audio/pcma-wb": {
  61187. "source": "iana"
  61188. },
  61189. "audio/pcmu": {
  61190. "source": "iana"
  61191. },
  61192. "audio/pcmu-wb": {
  61193. "source": "iana"
  61194. },
  61195. "audio/prs.sid": {
  61196. "source": "iana"
  61197. },
  61198. "audio/qcelp": {
  61199. "source": "iana"
  61200. },
  61201. "audio/raptorfec": {
  61202. "source": "iana"
  61203. },
  61204. "audio/red": {
  61205. "source": "iana"
  61206. },
  61207. "audio/rtp-enc-aescm128": {
  61208. "source": "iana"
  61209. },
  61210. "audio/rtp-midi": {
  61211. "source": "iana"
  61212. },
  61213. "audio/rtploopback": {
  61214. "source": "iana"
  61215. },
  61216. "audio/rtx": {
  61217. "source": "iana"
  61218. },
  61219. "audio/s3m": {
  61220. "source": "apache",
  61221. "extensions": ["s3m"]
  61222. },
  61223. "audio/silk": {
  61224. "source": "apache",
  61225. "extensions": ["sil"]
  61226. },
  61227. "audio/smv": {
  61228. "source": "iana"
  61229. },
  61230. "audio/smv-qcp": {
  61231. "source": "iana"
  61232. },
  61233. "audio/smv0": {
  61234. "source": "iana"
  61235. },
  61236. "audio/sp-midi": {
  61237. "source": "iana"
  61238. },
  61239. "audio/speex": {
  61240. "source": "iana"
  61241. },
  61242. "audio/t140c": {
  61243. "source": "iana"
  61244. },
  61245. "audio/t38": {
  61246. "source": "iana"
  61247. },
  61248. "audio/telephone-event": {
  61249. "source": "iana"
  61250. },
  61251. "audio/tetra_acelp": {
  61252. "source": "iana"
  61253. },
  61254. "audio/tetra_acelp_bb": {
  61255. "source": "iana"
  61256. },
  61257. "audio/tone": {
  61258. "source": "iana"
  61259. },
  61260. "audio/uemclip": {
  61261. "source": "iana"
  61262. },
  61263. "audio/ulpfec": {
  61264. "source": "iana"
  61265. },
  61266. "audio/usac": {
  61267. "source": "iana"
  61268. },
  61269. "audio/vdvi": {
  61270. "source": "iana"
  61271. },
  61272. "audio/vmr-wb": {
  61273. "source": "iana"
  61274. },
  61275. "audio/vnd.3gpp.iufp": {
  61276. "source": "iana"
  61277. },
  61278. "audio/vnd.4sb": {
  61279. "source": "iana"
  61280. },
  61281. "audio/vnd.audiokoz": {
  61282. "source": "iana"
  61283. },
  61284. "audio/vnd.celp": {
  61285. "source": "iana"
  61286. },
  61287. "audio/vnd.cisco.nse": {
  61288. "source": "iana"
  61289. },
  61290. "audio/vnd.cmles.radio-events": {
  61291. "source": "iana"
  61292. },
  61293. "audio/vnd.cns.anp1": {
  61294. "source": "iana"
  61295. },
  61296. "audio/vnd.cns.inf1": {
  61297. "source": "iana"
  61298. },
  61299. "audio/vnd.dece.audio": {
  61300. "source": "iana",
  61301. "extensions": ["uva","uvva"]
  61302. },
  61303. "audio/vnd.digital-winds": {
  61304. "source": "iana",
  61305. "extensions": ["eol"]
  61306. },
  61307. "audio/vnd.dlna.adts": {
  61308. "source": "iana"
  61309. },
  61310. "audio/vnd.dolby.heaac.1": {
  61311. "source": "iana"
  61312. },
  61313. "audio/vnd.dolby.heaac.2": {
  61314. "source": "iana"
  61315. },
  61316. "audio/vnd.dolby.mlp": {
  61317. "source": "iana"
  61318. },
  61319. "audio/vnd.dolby.mps": {
  61320. "source": "iana"
  61321. },
  61322. "audio/vnd.dolby.pl2": {
  61323. "source": "iana"
  61324. },
  61325. "audio/vnd.dolby.pl2x": {
  61326. "source": "iana"
  61327. },
  61328. "audio/vnd.dolby.pl2z": {
  61329. "source": "iana"
  61330. },
  61331. "audio/vnd.dolby.pulse.1": {
  61332. "source": "iana"
  61333. },
  61334. "audio/vnd.dra": {
  61335. "source": "iana",
  61336. "extensions": ["dra"]
  61337. },
  61338. "audio/vnd.dts": {
  61339. "source": "iana",
  61340. "extensions": ["dts"]
  61341. },
  61342. "audio/vnd.dts.hd": {
  61343. "source": "iana",
  61344. "extensions": ["dtshd"]
  61345. },
  61346. "audio/vnd.dts.uhd": {
  61347. "source": "iana"
  61348. },
  61349. "audio/vnd.dvb.file": {
  61350. "source": "iana"
  61351. },
  61352. "audio/vnd.everad.plj": {
  61353. "source": "iana"
  61354. },
  61355. "audio/vnd.hns.audio": {
  61356. "source": "iana"
  61357. },
  61358. "audio/vnd.lucent.voice": {
  61359. "source": "iana",
  61360. "extensions": ["lvp"]
  61361. },
  61362. "audio/vnd.ms-playready.media.pya": {
  61363. "source": "iana",
  61364. "extensions": ["pya"]
  61365. },
  61366. "audio/vnd.nokia.mobile-xmf": {
  61367. "source": "iana"
  61368. },
  61369. "audio/vnd.nortel.vbk": {
  61370. "source": "iana"
  61371. },
  61372. "audio/vnd.nuera.ecelp4800": {
  61373. "source": "iana",
  61374. "extensions": ["ecelp4800"]
  61375. },
  61376. "audio/vnd.nuera.ecelp7470": {
  61377. "source": "iana",
  61378. "extensions": ["ecelp7470"]
  61379. },
  61380. "audio/vnd.nuera.ecelp9600": {
  61381. "source": "iana",
  61382. "extensions": ["ecelp9600"]
  61383. },
  61384. "audio/vnd.octel.sbc": {
  61385. "source": "iana"
  61386. },
  61387. "audio/vnd.presonus.multitrack": {
  61388. "source": "iana"
  61389. },
  61390. "audio/vnd.qcelp": {
  61391. "source": "iana"
  61392. },
  61393. "audio/vnd.rhetorex.32kadpcm": {
  61394. "source": "iana"
  61395. },
  61396. "audio/vnd.rip": {
  61397. "source": "iana",
  61398. "extensions": ["rip"]
  61399. },
  61400. "audio/vnd.rn-realaudio": {
  61401. "compressible": false
  61402. },
  61403. "audio/vnd.sealedmedia.softseal.mpeg": {
  61404. "source": "iana"
  61405. },
  61406. "audio/vnd.vmx.cvsd": {
  61407. "source": "iana"
  61408. },
  61409. "audio/vnd.wave": {
  61410. "compressible": false
  61411. },
  61412. "audio/vorbis": {
  61413. "source": "iana",
  61414. "compressible": false
  61415. },
  61416. "audio/vorbis-config": {
  61417. "source": "iana"
  61418. },
  61419. "audio/wav": {
  61420. "compressible": false,
  61421. "extensions": ["wav"]
  61422. },
  61423. "audio/wave": {
  61424. "compressible": false,
  61425. "extensions": ["wav"]
  61426. },
  61427. "audio/webm": {
  61428. "source": "apache",
  61429. "compressible": false,
  61430. "extensions": ["weba"]
  61431. },
  61432. "audio/x-aac": {
  61433. "source": "apache",
  61434. "compressible": false,
  61435. "extensions": ["aac"]
  61436. },
  61437. "audio/x-aiff": {
  61438. "source": "apache",
  61439. "extensions": ["aif","aiff","aifc"]
  61440. },
  61441. "audio/x-caf": {
  61442. "source": "apache",
  61443. "compressible": false,
  61444. "extensions": ["caf"]
  61445. },
  61446. "audio/x-flac": {
  61447. "source": "apache",
  61448. "extensions": ["flac"]
  61449. },
  61450. "audio/x-m4a": {
  61451. "source": "nginx",
  61452. "extensions": ["m4a"]
  61453. },
  61454. "audio/x-matroska": {
  61455. "source": "apache",
  61456. "extensions": ["mka"]
  61457. },
  61458. "audio/x-mpegurl": {
  61459. "source": "apache",
  61460. "extensions": ["m3u"]
  61461. },
  61462. "audio/x-ms-wax": {
  61463. "source": "apache",
  61464. "extensions": ["wax"]
  61465. },
  61466. "audio/x-ms-wma": {
  61467. "source": "apache",
  61468. "extensions": ["wma"]
  61469. },
  61470. "audio/x-pn-realaudio": {
  61471. "source": "apache",
  61472. "extensions": ["ram","ra"]
  61473. },
  61474. "audio/x-pn-realaudio-plugin": {
  61475. "source": "apache",
  61476. "extensions": ["rmp"]
  61477. },
  61478. "audio/x-realaudio": {
  61479. "source": "nginx",
  61480. "extensions": ["ra"]
  61481. },
  61482. "audio/x-tta": {
  61483. "source": "apache"
  61484. },
  61485. "audio/x-wav": {
  61486. "source": "apache",
  61487. "extensions": ["wav"]
  61488. },
  61489. "audio/xm": {
  61490. "source": "apache",
  61491. "extensions": ["xm"]
  61492. },
  61493. "chemical/x-cdx": {
  61494. "source": "apache",
  61495. "extensions": ["cdx"]
  61496. },
  61497. "chemical/x-cif": {
  61498. "source": "apache",
  61499. "extensions": ["cif"]
  61500. },
  61501. "chemical/x-cmdf": {
  61502. "source": "apache",
  61503. "extensions": ["cmdf"]
  61504. },
  61505. "chemical/x-cml": {
  61506. "source": "apache",
  61507. "extensions": ["cml"]
  61508. },
  61509. "chemical/x-csml": {
  61510. "source": "apache",
  61511. "extensions": ["csml"]
  61512. },
  61513. "chemical/x-pdb": {
  61514. "source": "apache"
  61515. },
  61516. "chemical/x-xyz": {
  61517. "source": "apache",
  61518. "extensions": ["xyz"]
  61519. },
  61520. "font/collection": {
  61521. "source": "iana",
  61522. "extensions": ["ttc"]
  61523. },
  61524. "font/otf": {
  61525. "source": "iana",
  61526. "compressible": true,
  61527. "extensions": ["otf"]
  61528. },
  61529. "font/sfnt": {
  61530. "source": "iana"
  61531. },
  61532. "font/ttf": {
  61533. "source": "iana",
  61534. "compressible": true,
  61535. "extensions": ["ttf"]
  61536. },
  61537. "font/woff": {
  61538. "source": "iana",
  61539. "extensions": ["woff"]
  61540. },
  61541. "font/woff2": {
  61542. "source": "iana",
  61543. "extensions": ["woff2"]
  61544. },
  61545. "image/aces": {
  61546. "source": "iana",
  61547. "extensions": ["exr"]
  61548. },
  61549. "image/apng": {
  61550. "compressible": false,
  61551. "extensions": ["apng"]
  61552. },
  61553. "image/avci": {
  61554. "source": "iana"
  61555. },
  61556. "image/avcs": {
  61557. "source": "iana"
  61558. },
  61559. "image/bmp": {
  61560. "source": "iana",
  61561. "compressible": true,
  61562. "extensions": ["bmp"]
  61563. },
  61564. "image/cgm": {
  61565. "source": "iana",
  61566. "extensions": ["cgm"]
  61567. },
  61568. "image/dicom-rle": {
  61569. "source": "iana",
  61570. "extensions": ["drle"]
  61571. },
  61572. "image/emf": {
  61573. "source": "iana",
  61574. "extensions": ["emf"]
  61575. },
  61576. "image/fits": {
  61577. "source": "iana",
  61578. "extensions": ["fits"]
  61579. },
  61580. "image/g3fax": {
  61581. "source": "iana",
  61582. "extensions": ["g3"]
  61583. },
  61584. "image/gif": {
  61585. "source": "iana",
  61586. "compressible": false,
  61587. "extensions": ["gif"]
  61588. },
  61589. "image/heic": {
  61590. "source": "iana",
  61591. "extensions": ["heic"]
  61592. },
  61593. "image/heic-sequence": {
  61594. "source": "iana",
  61595. "extensions": ["heics"]
  61596. },
  61597. "image/heif": {
  61598. "source": "iana",
  61599. "extensions": ["heif"]
  61600. },
  61601. "image/heif-sequence": {
  61602. "source": "iana",
  61603. "extensions": ["heifs"]
  61604. },
  61605. "image/hej2k": {
  61606. "source": "iana",
  61607. "extensions": ["hej2"]
  61608. },
  61609. "image/hsj2": {
  61610. "source": "iana",
  61611. "extensions": ["hsj2"]
  61612. },
  61613. "image/ief": {
  61614. "source": "iana",
  61615. "extensions": ["ief"]
  61616. },
  61617. "image/jls": {
  61618. "source": "iana",
  61619. "extensions": ["jls"]
  61620. },
  61621. "image/jp2": {
  61622. "source": "iana",
  61623. "compressible": false,
  61624. "extensions": ["jp2","jpg2"]
  61625. },
  61626. "image/jpeg": {
  61627. "source": "iana",
  61628. "compressible": false,
  61629. "extensions": ["jpeg","jpg","jpe"]
  61630. },
  61631. "image/jph": {
  61632. "source": "iana",
  61633. "extensions": ["jph"]
  61634. },
  61635. "image/jphc": {
  61636. "source": "iana",
  61637. "extensions": ["jhc"]
  61638. },
  61639. "image/jpm": {
  61640. "source": "iana",
  61641. "compressible": false,
  61642. "extensions": ["jpm"]
  61643. },
  61644. "image/jpx": {
  61645. "source": "iana",
  61646. "compressible": false,
  61647. "extensions": ["jpx","jpf"]
  61648. },
  61649. "image/jxr": {
  61650. "source": "iana",
  61651. "extensions": ["jxr"]
  61652. },
  61653. "image/jxra": {
  61654. "source": "iana",
  61655. "extensions": ["jxra"]
  61656. },
  61657. "image/jxrs": {
  61658. "source": "iana",
  61659. "extensions": ["jxrs"]
  61660. },
  61661. "image/jxs": {
  61662. "source": "iana",
  61663. "extensions": ["jxs"]
  61664. },
  61665. "image/jxsc": {
  61666. "source": "iana",
  61667. "extensions": ["jxsc"]
  61668. },
  61669. "image/jxsi": {
  61670. "source": "iana",
  61671. "extensions": ["jxsi"]
  61672. },
  61673. "image/jxss": {
  61674. "source": "iana",
  61675. "extensions": ["jxss"]
  61676. },
  61677. "image/ktx": {
  61678. "source": "iana",
  61679. "extensions": ["ktx"]
  61680. },
  61681. "image/naplps": {
  61682. "source": "iana"
  61683. },
  61684. "image/pjpeg": {
  61685. "compressible": false
  61686. },
  61687. "image/png": {
  61688. "source": "iana",
  61689. "compressible": false,
  61690. "extensions": ["png"]
  61691. },
  61692. "image/prs.btif": {
  61693. "source": "iana",
  61694. "extensions": ["btif"]
  61695. },
  61696. "image/prs.pti": {
  61697. "source": "iana",
  61698. "extensions": ["pti"]
  61699. },
  61700. "image/pwg-raster": {
  61701. "source": "iana"
  61702. },
  61703. "image/sgi": {
  61704. "source": "apache",
  61705. "extensions": ["sgi"]
  61706. },
  61707. "image/svg+xml": {
  61708. "source": "iana",
  61709. "compressible": true,
  61710. "extensions": ["svg","svgz"]
  61711. },
  61712. "image/t38": {
  61713. "source": "iana",
  61714. "extensions": ["t38"]
  61715. },
  61716. "image/tiff": {
  61717. "source": "iana",
  61718. "compressible": false,
  61719. "extensions": ["tif","tiff"]
  61720. },
  61721. "image/tiff-fx": {
  61722. "source": "iana",
  61723. "extensions": ["tfx"]
  61724. },
  61725. "image/vnd.adobe.photoshop": {
  61726. "source": "iana",
  61727. "compressible": true,
  61728. "extensions": ["psd"]
  61729. },
  61730. "image/vnd.airzip.accelerator.azv": {
  61731. "source": "iana",
  61732. "extensions": ["azv"]
  61733. },
  61734. "image/vnd.cns.inf2": {
  61735. "source": "iana"
  61736. },
  61737. "image/vnd.dece.graphic": {
  61738. "source": "iana",
  61739. "extensions": ["uvi","uvvi","uvg","uvvg"]
  61740. },
  61741. "image/vnd.djvu": {
  61742. "source": "iana",
  61743. "extensions": ["djvu","djv"]
  61744. },
  61745. "image/vnd.dvb.subtitle": {
  61746. "source": "iana",
  61747. "extensions": ["sub"]
  61748. },
  61749. "image/vnd.dwg": {
  61750. "source": "iana",
  61751. "extensions": ["dwg"]
  61752. },
  61753. "image/vnd.dxf": {
  61754. "source": "iana",
  61755. "extensions": ["dxf"]
  61756. },
  61757. "image/vnd.fastbidsheet": {
  61758. "source": "iana",
  61759. "extensions": ["fbs"]
  61760. },
  61761. "image/vnd.fpx": {
  61762. "source": "iana",
  61763. "extensions": ["fpx"]
  61764. },
  61765. "image/vnd.fst": {
  61766. "source": "iana",
  61767. "extensions": ["fst"]
  61768. },
  61769. "image/vnd.fujixerox.edmics-mmr": {
  61770. "source": "iana",
  61771. "extensions": ["mmr"]
  61772. },
  61773. "image/vnd.fujixerox.edmics-rlc": {
  61774. "source": "iana",
  61775. "extensions": ["rlc"]
  61776. },
  61777. "image/vnd.globalgraphics.pgb": {
  61778. "source": "iana"
  61779. },
  61780. "image/vnd.microsoft.icon": {
  61781. "source": "iana",
  61782. "extensions": ["ico"]
  61783. },
  61784. "image/vnd.mix": {
  61785. "source": "iana"
  61786. },
  61787. "image/vnd.mozilla.apng": {
  61788. "source": "iana"
  61789. },
  61790. "image/vnd.ms-dds": {
  61791. "extensions": ["dds"]
  61792. },
  61793. "image/vnd.ms-modi": {
  61794. "source": "iana",
  61795. "extensions": ["mdi"]
  61796. },
  61797. "image/vnd.ms-photo": {
  61798. "source": "apache",
  61799. "extensions": ["wdp"]
  61800. },
  61801. "image/vnd.net-fpx": {
  61802. "source": "iana",
  61803. "extensions": ["npx"]
  61804. },
  61805. "image/vnd.radiance": {
  61806. "source": "iana"
  61807. },
  61808. "image/vnd.sealed.png": {
  61809. "source": "iana"
  61810. },
  61811. "image/vnd.sealedmedia.softseal.gif": {
  61812. "source": "iana"
  61813. },
  61814. "image/vnd.sealedmedia.softseal.jpg": {
  61815. "source": "iana"
  61816. },
  61817. "image/vnd.svf": {
  61818. "source": "iana"
  61819. },
  61820. "image/vnd.tencent.tap": {
  61821. "source": "iana",
  61822. "extensions": ["tap"]
  61823. },
  61824. "image/vnd.valve.source.texture": {
  61825. "source": "iana",
  61826. "extensions": ["vtf"]
  61827. },
  61828. "image/vnd.wap.wbmp": {
  61829. "source": "iana",
  61830. "extensions": ["wbmp"]
  61831. },
  61832. "image/vnd.xiff": {
  61833. "source": "iana",
  61834. "extensions": ["xif"]
  61835. },
  61836. "image/vnd.zbrush.pcx": {
  61837. "source": "iana",
  61838. "extensions": ["pcx"]
  61839. },
  61840. "image/webp": {
  61841. "source": "apache",
  61842. "extensions": ["webp"]
  61843. },
  61844. "image/wmf": {
  61845. "source": "iana",
  61846. "extensions": ["wmf"]
  61847. },
  61848. "image/x-3ds": {
  61849. "source": "apache",
  61850. "extensions": ["3ds"]
  61851. },
  61852. "image/x-cmu-raster": {
  61853. "source": "apache",
  61854. "extensions": ["ras"]
  61855. },
  61856. "image/x-cmx": {
  61857. "source": "apache",
  61858. "extensions": ["cmx"]
  61859. },
  61860. "image/x-freehand": {
  61861. "source": "apache",
  61862. "extensions": ["fh","fhc","fh4","fh5","fh7"]
  61863. },
  61864. "image/x-icon": {
  61865. "source": "apache",
  61866. "compressible": true,
  61867. "extensions": ["ico"]
  61868. },
  61869. "image/x-jng": {
  61870. "source": "nginx",
  61871. "extensions": ["jng"]
  61872. },
  61873. "image/x-mrsid-image": {
  61874. "source": "apache",
  61875. "extensions": ["sid"]
  61876. },
  61877. "image/x-ms-bmp": {
  61878. "source": "nginx",
  61879. "compressible": true,
  61880. "extensions": ["bmp"]
  61881. },
  61882. "image/x-pcx": {
  61883. "source": "apache",
  61884. "extensions": ["pcx"]
  61885. },
  61886. "image/x-pict": {
  61887. "source": "apache",
  61888. "extensions": ["pic","pct"]
  61889. },
  61890. "image/x-portable-anymap": {
  61891. "source": "apache",
  61892. "extensions": ["pnm"]
  61893. },
  61894. "image/x-portable-bitmap": {
  61895. "source": "apache",
  61896. "extensions": ["pbm"]
  61897. },
  61898. "image/x-portable-graymap": {
  61899. "source": "apache",
  61900. "extensions": ["pgm"]
  61901. },
  61902. "image/x-portable-pixmap": {
  61903. "source": "apache",
  61904. "extensions": ["ppm"]
  61905. },
  61906. "image/x-rgb": {
  61907. "source": "apache",
  61908. "extensions": ["rgb"]
  61909. },
  61910. "image/x-tga": {
  61911. "source": "apache",
  61912. "extensions": ["tga"]
  61913. },
  61914. "image/x-xbitmap": {
  61915. "source": "apache",
  61916. "extensions": ["xbm"]
  61917. },
  61918. "image/x-xcf": {
  61919. "compressible": false
  61920. },
  61921. "image/x-xpixmap": {
  61922. "source": "apache",
  61923. "extensions": ["xpm"]
  61924. },
  61925. "image/x-xwindowdump": {
  61926. "source": "apache",
  61927. "extensions": ["xwd"]
  61928. },
  61929. "message/cpim": {
  61930. "source": "iana"
  61931. },
  61932. "message/delivery-status": {
  61933. "source": "iana"
  61934. },
  61935. "message/disposition-notification": {
  61936. "source": "iana",
  61937. "extensions": [
  61938. "disposition-notification"
  61939. ]
  61940. },
  61941. "message/external-body": {
  61942. "source": "iana"
  61943. },
  61944. "message/feedback-report": {
  61945. "source": "iana"
  61946. },
  61947. "message/global": {
  61948. "source": "iana",
  61949. "extensions": ["u8msg"]
  61950. },
  61951. "message/global-delivery-status": {
  61952. "source": "iana",
  61953. "extensions": ["u8dsn"]
  61954. },
  61955. "message/global-disposition-notification": {
  61956. "source": "iana",
  61957. "extensions": ["u8mdn"]
  61958. },
  61959. "message/global-headers": {
  61960. "source": "iana",
  61961. "extensions": ["u8hdr"]
  61962. },
  61963. "message/http": {
  61964. "source": "iana",
  61965. "compressible": false
  61966. },
  61967. "message/imdn+xml": {
  61968. "source": "iana",
  61969. "compressible": true
  61970. },
  61971. "message/news": {
  61972. "source": "iana"
  61973. },
  61974. "message/partial": {
  61975. "source": "iana",
  61976. "compressible": false
  61977. },
  61978. "message/rfc822": {
  61979. "source": "iana",
  61980. "compressible": true,
  61981. "extensions": ["eml","mime"]
  61982. },
  61983. "message/s-http": {
  61984. "source": "iana"
  61985. },
  61986. "message/sip": {
  61987. "source": "iana"
  61988. },
  61989. "message/sipfrag": {
  61990. "source": "iana"
  61991. },
  61992. "message/tracking-status": {
  61993. "source": "iana"
  61994. },
  61995. "message/vnd.si.simp": {
  61996. "source": "iana"
  61997. },
  61998. "message/vnd.wfa.wsc": {
  61999. "source": "iana",
  62000. "extensions": ["wsc"]
  62001. },
  62002. "model/3mf": {
  62003. "source": "iana",
  62004. "extensions": ["3mf"]
  62005. },
  62006. "model/gltf+json": {
  62007. "source": "iana",
  62008. "compressible": true,
  62009. "extensions": ["gltf"]
  62010. },
  62011. "model/gltf-binary": {
  62012. "source": "iana",
  62013. "compressible": true,
  62014. "extensions": ["glb"]
  62015. },
  62016. "model/iges": {
  62017. "source": "iana",
  62018. "compressible": false,
  62019. "extensions": ["igs","iges"]
  62020. },
  62021. "model/mesh": {
  62022. "source": "iana",
  62023. "compressible": false,
  62024. "extensions": ["msh","mesh","silo"]
  62025. },
  62026. "model/mtl": {
  62027. "source": "iana",
  62028. "extensions": ["mtl"]
  62029. },
  62030. "model/obj": {
  62031. "source": "iana",
  62032. "extensions": ["obj"]
  62033. },
  62034. "model/stl": {
  62035. "source": "iana",
  62036. "extensions": ["stl"]
  62037. },
  62038. "model/vnd.collada+xml": {
  62039. "source": "iana",
  62040. "compressible": true,
  62041. "extensions": ["dae"]
  62042. },
  62043. "model/vnd.dwf": {
  62044. "source": "iana",
  62045. "extensions": ["dwf"]
  62046. },
  62047. "model/vnd.flatland.3dml": {
  62048. "source": "iana"
  62049. },
  62050. "model/vnd.gdl": {
  62051. "source": "iana",
  62052. "extensions": ["gdl"]
  62053. },
  62054. "model/vnd.gs-gdl": {
  62055. "source": "apache"
  62056. },
  62057. "model/vnd.gs.gdl": {
  62058. "source": "iana"
  62059. },
  62060. "model/vnd.gtw": {
  62061. "source": "iana",
  62062. "extensions": ["gtw"]
  62063. },
  62064. "model/vnd.moml+xml": {
  62065. "source": "iana",
  62066. "compressible": true
  62067. },
  62068. "model/vnd.mts": {
  62069. "source": "iana",
  62070. "extensions": ["mts"]
  62071. },
  62072. "model/vnd.opengex": {
  62073. "source": "iana",
  62074. "extensions": ["ogex"]
  62075. },
  62076. "model/vnd.parasolid.transmit.binary": {
  62077. "source": "iana",
  62078. "extensions": ["x_b"]
  62079. },
  62080. "model/vnd.parasolid.transmit.text": {
  62081. "source": "iana",
  62082. "extensions": ["x_t"]
  62083. },
  62084. "model/vnd.rosette.annotated-data-model": {
  62085. "source": "iana"
  62086. },
  62087. "model/vnd.usdz+zip": {
  62088. "source": "iana",
  62089. "compressible": false,
  62090. "extensions": ["usdz"]
  62091. },
  62092. "model/vnd.valve.source.compiled-map": {
  62093. "source": "iana",
  62094. "extensions": ["bsp"]
  62095. },
  62096. "model/vnd.vtu": {
  62097. "source": "iana",
  62098. "extensions": ["vtu"]
  62099. },
  62100. "model/vrml": {
  62101. "source": "iana",
  62102. "compressible": false,
  62103. "extensions": ["wrl","vrml"]
  62104. },
  62105. "model/x3d+binary": {
  62106. "source": "apache",
  62107. "compressible": false,
  62108. "extensions": ["x3db","x3dbz"]
  62109. },
  62110. "model/x3d+fastinfoset": {
  62111. "source": "iana",
  62112. "extensions": ["x3db"]
  62113. },
  62114. "model/x3d+vrml": {
  62115. "source": "apache",
  62116. "compressible": false,
  62117. "extensions": ["x3dv","x3dvz"]
  62118. },
  62119. "model/x3d+xml": {
  62120. "source": "iana",
  62121. "compressible": true,
  62122. "extensions": ["x3d","x3dz"]
  62123. },
  62124. "model/x3d-vrml": {
  62125. "source": "iana",
  62126. "extensions": ["x3dv"]
  62127. },
  62128. "multipart/alternative": {
  62129. "source": "iana",
  62130. "compressible": false
  62131. },
  62132. "multipart/appledouble": {
  62133. "source": "iana"
  62134. },
  62135. "multipart/byteranges": {
  62136. "source": "iana"
  62137. },
  62138. "multipart/digest": {
  62139. "source": "iana"
  62140. },
  62141. "multipart/encrypted": {
  62142. "source": "iana",
  62143. "compressible": false
  62144. },
  62145. "multipart/form-data": {
  62146. "source": "iana",
  62147. "compressible": false
  62148. },
  62149. "multipart/header-set": {
  62150. "source": "iana"
  62151. },
  62152. "multipart/mixed": {
  62153. "source": "iana"
  62154. },
  62155. "multipart/multilingual": {
  62156. "source": "iana"
  62157. },
  62158. "multipart/parallel": {
  62159. "source": "iana"
  62160. },
  62161. "multipart/related": {
  62162. "source": "iana",
  62163. "compressible": false
  62164. },
  62165. "multipart/report": {
  62166. "source": "iana"
  62167. },
  62168. "multipart/signed": {
  62169. "source": "iana",
  62170. "compressible": false
  62171. },
  62172. "multipart/vnd.bint.med-plus": {
  62173. "source": "iana"
  62174. },
  62175. "multipart/voice-message": {
  62176. "source": "iana"
  62177. },
  62178. "multipart/x-mixed-replace": {
  62179. "source": "iana"
  62180. },
  62181. "text/1d-interleaved-parityfec": {
  62182. "source": "iana"
  62183. },
  62184. "text/cache-manifest": {
  62185. "source": "iana",
  62186. "compressible": true,
  62187. "extensions": ["appcache","manifest"]
  62188. },
  62189. "text/calendar": {
  62190. "source": "iana",
  62191. "extensions": ["ics","ifb"]
  62192. },
  62193. "text/calender": {
  62194. "compressible": true
  62195. },
  62196. "text/cmd": {
  62197. "compressible": true
  62198. },
  62199. "text/coffeescript": {
  62200. "extensions": ["coffee","litcoffee"]
  62201. },
  62202. "text/css": {
  62203. "source": "iana",
  62204. "charset": "UTF-8",
  62205. "compressible": true,
  62206. "extensions": ["css"]
  62207. },
  62208. "text/csv": {
  62209. "source": "iana",
  62210. "compressible": true,
  62211. "extensions": ["csv"]
  62212. },
  62213. "text/csv-schema": {
  62214. "source": "iana"
  62215. },
  62216. "text/directory": {
  62217. "source": "iana"
  62218. },
  62219. "text/dns": {
  62220. "source": "iana"
  62221. },
  62222. "text/ecmascript": {
  62223. "source": "iana"
  62224. },
  62225. "text/encaprtp": {
  62226. "source": "iana"
  62227. },
  62228. "text/enriched": {
  62229. "source": "iana"
  62230. },
  62231. "text/flexfec": {
  62232. "source": "iana"
  62233. },
  62234. "text/fwdred": {
  62235. "source": "iana"
  62236. },
  62237. "text/grammar-ref-list": {
  62238. "source": "iana"
  62239. },
  62240. "text/html": {
  62241. "source": "iana",
  62242. "compressible": true,
  62243. "extensions": ["html","htm","shtml"]
  62244. },
  62245. "text/jade": {
  62246. "extensions": ["jade"]
  62247. },
  62248. "text/javascript": {
  62249. "source": "iana",
  62250. "compressible": true
  62251. },
  62252. "text/jcr-cnd": {
  62253. "source": "iana"
  62254. },
  62255. "text/jsx": {
  62256. "compressible": true,
  62257. "extensions": ["jsx"]
  62258. },
  62259. "text/less": {
  62260. "compressible": true,
  62261. "extensions": ["less"]
  62262. },
  62263. "text/markdown": {
  62264. "source": "iana",
  62265. "compressible": true,
  62266. "extensions": ["markdown","md"]
  62267. },
  62268. "text/mathml": {
  62269. "source": "nginx",
  62270. "extensions": ["mml"]
  62271. },
  62272. "text/mdx": {
  62273. "compressible": true,
  62274. "extensions": ["mdx"]
  62275. },
  62276. "text/mizar": {
  62277. "source": "iana"
  62278. },
  62279. "text/n3": {
  62280. "source": "iana",
  62281. "charset": "UTF-8",
  62282. "compressible": true,
  62283. "extensions": ["n3"]
  62284. },
  62285. "text/parameters": {
  62286. "source": "iana",
  62287. "charset": "UTF-8"
  62288. },
  62289. "text/parityfec": {
  62290. "source": "iana"
  62291. },
  62292. "text/plain": {
  62293. "source": "iana",
  62294. "compressible": true,
  62295. "extensions": ["txt","text","conf","def","list","log","in","ini"]
  62296. },
  62297. "text/provenance-notation": {
  62298. "source": "iana",
  62299. "charset": "UTF-8"
  62300. },
  62301. "text/prs.fallenstein.rst": {
  62302. "source": "iana"
  62303. },
  62304. "text/prs.lines.tag": {
  62305. "source": "iana",
  62306. "extensions": ["dsc"]
  62307. },
  62308. "text/prs.prop.logic": {
  62309. "source": "iana"
  62310. },
  62311. "text/raptorfec": {
  62312. "source": "iana"
  62313. },
  62314. "text/red": {
  62315. "source": "iana"
  62316. },
  62317. "text/rfc822-headers": {
  62318. "source": "iana"
  62319. },
  62320. "text/richtext": {
  62321. "source": "iana",
  62322. "compressible": true,
  62323. "extensions": ["rtx"]
  62324. },
  62325. "text/rtf": {
  62326. "source": "iana",
  62327. "compressible": true,
  62328. "extensions": ["rtf"]
  62329. },
  62330. "text/rtp-enc-aescm128": {
  62331. "source": "iana"
  62332. },
  62333. "text/rtploopback": {
  62334. "source": "iana"
  62335. },
  62336. "text/rtx": {
  62337. "source": "iana"
  62338. },
  62339. "text/sgml": {
  62340. "source": "iana",
  62341. "extensions": ["sgml","sgm"]
  62342. },
  62343. "text/shex": {
  62344. "extensions": ["shex"]
  62345. },
  62346. "text/slim": {
  62347. "extensions": ["slim","slm"]
  62348. },
  62349. "text/strings": {
  62350. "source": "iana"
  62351. },
  62352. "text/stylus": {
  62353. "extensions": ["stylus","styl"]
  62354. },
  62355. "text/t140": {
  62356. "source": "iana"
  62357. },
  62358. "text/tab-separated-values": {
  62359. "source": "iana",
  62360. "compressible": true,
  62361. "extensions": ["tsv"]
  62362. },
  62363. "text/troff": {
  62364. "source": "iana",
  62365. "extensions": ["t","tr","roff","man","me","ms"]
  62366. },
  62367. "text/turtle": {
  62368. "source": "iana",
  62369. "charset": "UTF-8",
  62370. "extensions": ["ttl"]
  62371. },
  62372. "text/ulpfec": {
  62373. "source": "iana"
  62374. },
  62375. "text/uri-list": {
  62376. "source": "iana",
  62377. "compressible": true,
  62378. "extensions": ["uri","uris","urls"]
  62379. },
  62380. "text/vcard": {
  62381. "source": "iana",
  62382. "compressible": true,
  62383. "extensions": ["vcard"]
  62384. },
  62385. "text/vnd.a": {
  62386. "source": "iana"
  62387. },
  62388. "text/vnd.abc": {
  62389. "source": "iana"
  62390. },
  62391. "text/vnd.ascii-art": {
  62392. "source": "iana"
  62393. },
  62394. "text/vnd.curl": {
  62395. "source": "iana",
  62396. "extensions": ["curl"]
  62397. },
  62398. "text/vnd.curl.dcurl": {
  62399. "source": "apache",
  62400. "extensions": ["dcurl"]
  62401. },
  62402. "text/vnd.curl.mcurl": {
  62403. "source": "apache",
  62404. "extensions": ["mcurl"]
  62405. },
  62406. "text/vnd.curl.scurl": {
  62407. "source": "apache",
  62408. "extensions": ["scurl"]
  62409. },
  62410. "text/vnd.debian.copyright": {
  62411. "source": "iana",
  62412. "charset": "UTF-8"
  62413. },
  62414. "text/vnd.dmclientscript": {
  62415. "source": "iana"
  62416. },
  62417. "text/vnd.dvb.subtitle": {
  62418. "source": "iana",
  62419. "extensions": ["sub"]
  62420. },
  62421. "text/vnd.esmertec.theme-descriptor": {
  62422. "source": "iana",
  62423. "charset": "UTF-8"
  62424. },
  62425. "text/vnd.ficlab.flt": {
  62426. "source": "iana"
  62427. },
  62428. "text/vnd.fly": {
  62429. "source": "iana",
  62430. "extensions": ["fly"]
  62431. },
  62432. "text/vnd.fmi.flexstor": {
  62433. "source": "iana",
  62434. "extensions": ["flx"]
  62435. },
  62436. "text/vnd.gml": {
  62437. "source": "iana"
  62438. },
  62439. "text/vnd.graphviz": {
  62440. "source": "iana",
  62441. "extensions": ["gv"]
  62442. },
  62443. "text/vnd.hgl": {
  62444. "source": "iana"
  62445. },
  62446. "text/vnd.in3d.3dml": {
  62447. "source": "iana",
  62448. "extensions": ["3dml"]
  62449. },
  62450. "text/vnd.in3d.spot": {
  62451. "source": "iana",
  62452. "extensions": ["spot"]
  62453. },
  62454. "text/vnd.iptc.newsml": {
  62455. "source": "iana"
  62456. },
  62457. "text/vnd.iptc.nitf": {
  62458. "source": "iana"
  62459. },
  62460. "text/vnd.latex-z": {
  62461. "source": "iana"
  62462. },
  62463. "text/vnd.motorola.reflex": {
  62464. "source": "iana"
  62465. },
  62466. "text/vnd.ms-mediapackage": {
  62467. "source": "iana"
  62468. },
  62469. "text/vnd.net2phone.commcenter.command": {
  62470. "source": "iana"
  62471. },
  62472. "text/vnd.radisys.msml-basic-layout": {
  62473. "source": "iana"
  62474. },
  62475. "text/vnd.senx.warpscript": {
  62476. "source": "iana"
  62477. },
  62478. "text/vnd.si.uricatalogue": {
  62479. "source": "iana"
  62480. },
  62481. "text/vnd.sosi": {
  62482. "source": "iana"
  62483. },
  62484. "text/vnd.sun.j2me.app-descriptor": {
  62485. "source": "iana",
  62486. "charset": "UTF-8",
  62487. "extensions": ["jad"]
  62488. },
  62489. "text/vnd.trolltech.linguist": {
  62490. "source": "iana",
  62491. "charset": "UTF-8"
  62492. },
  62493. "text/vnd.wap.si": {
  62494. "source": "iana"
  62495. },
  62496. "text/vnd.wap.sl": {
  62497. "source": "iana"
  62498. },
  62499. "text/vnd.wap.wml": {
  62500. "source": "iana",
  62501. "extensions": ["wml"]
  62502. },
  62503. "text/vnd.wap.wmlscript": {
  62504. "source": "iana",
  62505. "extensions": ["wmls"]
  62506. },
  62507. "text/vtt": {
  62508. "source": "iana",
  62509. "charset": "UTF-8",
  62510. "compressible": true,
  62511. "extensions": ["vtt"]
  62512. },
  62513. "text/x-asm": {
  62514. "source": "apache",
  62515. "extensions": ["s","asm"]
  62516. },
  62517. "text/x-c": {
  62518. "source": "apache",
  62519. "extensions": ["c","cc","cxx","cpp","h","hh","dic"]
  62520. },
  62521. "text/x-component": {
  62522. "source": "nginx",
  62523. "extensions": ["htc"]
  62524. },
  62525. "text/x-fortran": {
  62526. "source": "apache",
  62527. "extensions": ["f","for","f77","f90"]
  62528. },
  62529. "text/x-gwt-rpc": {
  62530. "compressible": true
  62531. },
  62532. "text/x-handlebars-template": {
  62533. "extensions": ["hbs"]
  62534. },
  62535. "text/x-java-source": {
  62536. "source": "apache",
  62537. "extensions": ["java"]
  62538. },
  62539. "text/x-jquery-tmpl": {
  62540. "compressible": true
  62541. },
  62542. "text/x-lua": {
  62543. "extensions": ["lua"]
  62544. },
  62545. "text/x-markdown": {
  62546. "compressible": true,
  62547. "extensions": ["mkd"]
  62548. },
  62549. "text/x-nfo": {
  62550. "source": "apache",
  62551. "extensions": ["nfo"]
  62552. },
  62553. "text/x-opml": {
  62554. "source": "apache",
  62555. "extensions": ["opml"]
  62556. },
  62557. "text/x-org": {
  62558. "compressible": true,
  62559. "extensions": ["org"]
  62560. },
  62561. "text/x-pascal": {
  62562. "source": "apache",
  62563. "extensions": ["p","pas"]
  62564. },
  62565. "text/x-processing": {
  62566. "compressible": true,
  62567. "extensions": ["pde"]
  62568. },
  62569. "text/x-sass": {
  62570. "extensions": ["sass"]
  62571. },
  62572. "text/x-scss": {
  62573. "extensions": ["scss"]
  62574. },
  62575. "text/x-setext": {
  62576. "source": "apache",
  62577. "extensions": ["etx"]
  62578. },
  62579. "text/x-sfv": {
  62580. "source": "apache",
  62581. "extensions": ["sfv"]
  62582. },
  62583. "text/x-suse-ymp": {
  62584. "compressible": true,
  62585. "extensions": ["ymp"]
  62586. },
  62587. "text/x-uuencode": {
  62588. "source": "apache",
  62589. "extensions": ["uu"]
  62590. },
  62591. "text/x-vcalendar": {
  62592. "source": "apache",
  62593. "extensions": ["vcs"]
  62594. },
  62595. "text/x-vcard": {
  62596. "source": "apache",
  62597. "extensions": ["vcf"]
  62598. },
  62599. "text/xml": {
  62600. "source": "iana",
  62601. "compressible": true,
  62602. "extensions": ["xml"]
  62603. },
  62604. "text/xml-external-parsed-entity": {
  62605. "source": "iana"
  62606. },
  62607. "text/yaml": {
  62608. "extensions": ["yaml","yml"]
  62609. },
  62610. "video/1d-interleaved-parityfec": {
  62611. "source": "iana"
  62612. },
  62613. "video/3gpp": {
  62614. "source": "iana",
  62615. "extensions": ["3gp","3gpp"]
  62616. },
  62617. "video/3gpp-tt": {
  62618. "source": "iana"
  62619. },
  62620. "video/3gpp2": {
  62621. "source": "iana",
  62622. "extensions": ["3g2"]
  62623. },
  62624. "video/bmpeg": {
  62625. "source": "iana"
  62626. },
  62627. "video/bt656": {
  62628. "source": "iana"
  62629. },
  62630. "video/celb": {
  62631. "source": "iana"
  62632. },
  62633. "video/dv": {
  62634. "source": "iana"
  62635. },
  62636. "video/encaprtp": {
  62637. "source": "iana"
  62638. },
  62639. "video/flexfec": {
  62640. "source": "iana"
  62641. },
  62642. "video/h261": {
  62643. "source": "iana",
  62644. "extensions": ["h261"]
  62645. },
  62646. "video/h263": {
  62647. "source": "iana",
  62648. "extensions": ["h263"]
  62649. },
  62650. "video/h263-1998": {
  62651. "source": "iana"
  62652. },
  62653. "video/h263-2000": {
  62654. "source": "iana"
  62655. },
  62656. "video/h264": {
  62657. "source": "iana",
  62658. "extensions": ["h264"]
  62659. },
  62660. "video/h264-rcdo": {
  62661. "source": "iana"
  62662. },
  62663. "video/h264-svc": {
  62664. "source": "iana"
  62665. },
  62666. "video/h265": {
  62667. "source": "iana"
  62668. },
  62669. "video/iso.segment": {
  62670. "source": "iana"
  62671. },
  62672. "video/jpeg": {
  62673. "source": "iana",
  62674. "extensions": ["jpgv"]
  62675. },
  62676. "video/jpeg2000": {
  62677. "source": "iana"
  62678. },
  62679. "video/jpm": {
  62680. "source": "apache",
  62681. "extensions": ["jpm","jpgm"]
  62682. },
  62683. "video/mj2": {
  62684. "source": "iana",
  62685. "extensions": ["mj2","mjp2"]
  62686. },
  62687. "video/mp1s": {
  62688. "source": "iana"
  62689. },
  62690. "video/mp2p": {
  62691. "source": "iana"
  62692. },
  62693. "video/mp2t": {
  62694. "source": "iana",
  62695. "extensions": ["ts"]
  62696. },
  62697. "video/mp4": {
  62698. "source": "iana",
  62699. "compressible": false,
  62700. "extensions": ["mp4","mp4v","mpg4"]
  62701. },
  62702. "video/mp4v-es": {
  62703. "source": "iana"
  62704. },
  62705. "video/mpeg": {
  62706. "source": "iana",
  62707. "compressible": false,
  62708. "extensions": ["mpeg","mpg","mpe","m1v","m2v"]
  62709. },
  62710. "video/mpeg4-generic": {
  62711. "source": "iana"
  62712. },
  62713. "video/mpv": {
  62714. "source": "iana"
  62715. },
  62716. "video/nv": {
  62717. "source": "iana"
  62718. },
  62719. "video/ogg": {
  62720. "source": "iana",
  62721. "compressible": false,
  62722. "extensions": ["ogv"]
  62723. },
  62724. "video/parityfec": {
  62725. "source": "iana"
  62726. },
  62727. "video/pointer": {
  62728. "source": "iana"
  62729. },
  62730. "video/quicktime": {
  62731. "source": "iana",
  62732. "compressible": false,
  62733. "extensions": ["qt","mov"]
  62734. },
  62735. "video/raptorfec": {
  62736. "source": "iana"
  62737. },
  62738. "video/raw": {
  62739. "source": "iana"
  62740. },
  62741. "video/rtp-enc-aescm128": {
  62742. "source": "iana"
  62743. },
  62744. "video/rtploopback": {
  62745. "source": "iana"
  62746. },
  62747. "video/rtx": {
  62748. "source": "iana"
  62749. },
  62750. "video/smpte291": {
  62751. "source": "iana"
  62752. },
  62753. "video/smpte292m": {
  62754. "source": "iana"
  62755. },
  62756. "video/ulpfec": {
  62757. "source": "iana"
  62758. },
  62759. "video/vc1": {
  62760. "source": "iana"
  62761. },
  62762. "video/vc2": {
  62763. "source": "iana"
  62764. },
  62765. "video/vnd.cctv": {
  62766. "source": "iana"
  62767. },
  62768. "video/vnd.dece.hd": {
  62769. "source": "iana",
  62770. "extensions": ["uvh","uvvh"]
  62771. },
  62772. "video/vnd.dece.mobile": {
  62773. "source": "iana",
  62774. "extensions": ["uvm","uvvm"]
  62775. },
  62776. "video/vnd.dece.mp4": {
  62777. "source": "iana"
  62778. },
  62779. "video/vnd.dece.pd": {
  62780. "source": "iana",
  62781. "extensions": ["uvp","uvvp"]
  62782. },
  62783. "video/vnd.dece.sd": {
  62784. "source": "iana",
  62785. "extensions": ["uvs","uvvs"]
  62786. },
  62787. "video/vnd.dece.video": {
  62788. "source": "iana",
  62789. "extensions": ["uvv","uvvv"]
  62790. },
  62791. "video/vnd.directv.mpeg": {
  62792. "source": "iana"
  62793. },
  62794. "video/vnd.directv.mpeg-tts": {
  62795. "source": "iana"
  62796. },
  62797. "video/vnd.dlna.mpeg-tts": {
  62798. "source": "iana"
  62799. },
  62800. "video/vnd.dvb.file": {
  62801. "source": "iana",
  62802. "extensions": ["dvb"]
  62803. },
  62804. "video/vnd.fvt": {
  62805. "source": "iana",
  62806. "extensions": ["fvt"]
  62807. },
  62808. "video/vnd.hns.video": {
  62809. "source": "iana"
  62810. },
  62811. "video/vnd.iptvforum.1dparityfec-1010": {
  62812. "source": "iana"
  62813. },
  62814. "video/vnd.iptvforum.1dparityfec-2005": {
  62815. "source": "iana"
  62816. },
  62817. "video/vnd.iptvforum.2dparityfec-1010": {
  62818. "source": "iana"
  62819. },
  62820. "video/vnd.iptvforum.2dparityfec-2005": {
  62821. "source": "iana"
  62822. },
  62823. "video/vnd.iptvforum.ttsavc": {
  62824. "source": "iana"
  62825. },
  62826. "video/vnd.iptvforum.ttsmpeg2": {
  62827. "source": "iana"
  62828. },
  62829. "video/vnd.motorola.video": {
  62830. "source": "iana"
  62831. },
  62832. "video/vnd.motorola.videop": {
  62833. "source": "iana"
  62834. },
  62835. "video/vnd.mpegurl": {
  62836. "source": "iana",
  62837. "extensions": ["mxu","m4u"]
  62838. },
  62839. "video/vnd.ms-playready.media.pyv": {
  62840. "source": "iana",
  62841. "extensions": ["pyv"]
  62842. },
  62843. "video/vnd.nokia.interleaved-multimedia": {
  62844. "source": "iana"
  62845. },
  62846. "video/vnd.nokia.mp4vr": {
  62847. "source": "iana"
  62848. },
  62849. "video/vnd.nokia.videovoip": {
  62850. "source": "iana"
  62851. },
  62852. "video/vnd.objectvideo": {
  62853. "source": "iana"
  62854. },
  62855. "video/vnd.radgamettools.bink": {
  62856. "source": "iana"
  62857. },
  62858. "video/vnd.radgamettools.smacker": {
  62859. "source": "iana"
  62860. },
  62861. "video/vnd.sealed.mpeg1": {
  62862. "source": "iana"
  62863. },
  62864. "video/vnd.sealed.mpeg4": {
  62865. "source": "iana"
  62866. },
  62867. "video/vnd.sealed.swf": {
  62868. "source": "iana"
  62869. },
  62870. "video/vnd.sealedmedia.softseal.mov": {
  62871. "source": "iana"
  62872. },
  62873. "video/vnd.uvvu.mp4": {
  62874. "source": "iana",
  62875. "extensions": ["uvu","uvvu"]
  62876. },
  62877. "video/vnd.vivo": {
  62878. "source": "iana",
  62879. "extensions": ["viv"]
  62880. },
  62881. "video/vnd.youtube.yt": {
  62882. "source": "iana"
  62883. },
  62884. "video/vp8": {
  62885. "source": "iana"
  62886. },
  62887. "video/webm": {
  62888. "source": "apache",
  62889. "compressible": false,
  62890. "extensions": ["webm"]
  62891. },
  62892. "video/x-f4v": {
  62893. "source": "apache",
  62894. "extensions": ["f4v"]
  62895. },
  62896. "video/x-fli": {
  62897. "source": "apache",
  62898. "extensions": ["fli"]
  62899. },
  62900. "video/x-flv": {
  62901. "source": "apache",
  62902. "compressible": false,
  62903. "extensions": ["flv"]
  62904. },
  62905. "video/x-m4v": {
  62906. "source": "apache",
  62907. "extensions": ["m4v"]
  62908. },
  62909. "video/x-matroska": {
  62910. "source": "apache",
  62911. "compressible": false,
  62912. "extensions": ["mkv","mk3d","mks"]
  62913. },
  62914. "video/x-mng": {
  62915. "source": "apache",
  62916. "extensions": ["mng"]
  62917. },
  62918. "video/x-ms-asf": {
  62919. "source": "apache",
  62920. "extensions": ["asf","asx"]
  62921. },
  62922. "video/x-ms-vob": {
  62923. "source": "apache",
  62924. "extensions": ["vob"]
  62925. },
  62926. "video/x-ms-wm": {
  62927. "source": "apache",
  62928. "extensions": ["wm"]
  62929. },
  62930. "video/x-ms-wmv": {
  62931. "source": "apache",
  62932. "compressible": false,
  62933. "extensions": ["wmv"]
  62934. },
  62935. "video/x-ms-wmx": {
  62936. "source": "apache",
  62937. "extensions": ["wmx"]
  62938. },
  62939. "video/x-ms-wvx": {
  62940. "source": "apache",
  62941. "extensions": ["wvx"]
  62942. },
  62943. "video/x-msvideo": {
  62944. "source": "apache",
  62945. "extensions": ["avi"]
  62946. },
  62947. "video/x-sgi-movie": {
  62948. "source": "apache",
  62949. "extensions": ["movie"]
  62950. },
  62951. "video/x-smv": {
  62952. "source": "apache",
  62953. "extensions": ["smv"]
  62954. },
  62955. "x-conference/x-cooltalk": {
  62956. "source": "apache",
  62957. "extensions": ["ice"]
  62958. },
  62959. "x-shader/x-fragment": {
  62960. "compressible": true
  62961. },
  62962. "x-shader/x-vertex": {
  62963. "compressible": true
  62964. }
  62965. }
  62966. },{}],343:[function(require,module,exports){
  62967. /*!
  62968. * mime-db
  62969. * Copyright(c) 2014 Jonathan Ong
  62970. * MIT Licensed
  62971. */
  62972. /**
  62973. * Module exports.
  62974. */
  62975. module.exports = require('./db.json')
  62976. },{"./db.json":342}],344:[function(require,module,exports){
  62977. /*!
  62978. * mime-types
  62979. * Copyright(c) 2014 Jonathan Ong
  62980. * Copyright(c) 2015 Douglas Christopher Wilson
  62981. * MIT Licensed
  62982. */
  62983. 'use strict'
  62984. /**
  62985. * Module dependencies.
  62986. * @private
  62987. */
  62988. var db = require('mime-db')
  62989. var extname = require('path').extname
  62990. /**
  62991. * Module variables.
  62992. * @private
  62993. */
  62994. var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
  62995. var TEXT_TYPE_REGEXP = /^text\//i
  62996. /**
  62997. * Module exports.
  62998. * @public
  62999. */
  63000. exports.charset = charset
  63001. exports.charsets = { lookup: charset }
  63002. exports.contentType = contentType
  63003. exports.extension = extension
  63004. exports.extensions = Object.create(null)
  63005. exports.lookup = lookup
  63006. exports.types = Object.create(null)
  63007. // Populate the extensions/types maps
  63008. populateMaps(exports.extensions, exports.types)
  63009. /**
  63010. * Get the default charset for a MIME type.
  63011. *
  63012. * @param {string} type
  63013. * @return {boolean|string}
  63014. */
  63015. function charset (type) {
  63016. if (!type || typeof type !== 'string') {
  63017. return false
  63018. }
  63019. // TODO: use media-typer
  63020. var match = EXTRACT_TYPE_REGEXP.exec(type)
  63021. var mime = match && db[match[1].toLowerCase()]
  63022. if (mime && mime.charset) {
  63023. return mime.charset
  63024. }
  63025. // default text/* to utf-8
  63026. if (match && TEXT_TYPE_REGEXP.test(match[1])) {
  63027. return 'UTF-8'
  63028. }
  63029. return false
  63030. }
  63031. /**
  63032. * Create a full Content-Type header given a MIME type or extension.
  63033. *
  63034. * @param {string} str
  63035. * @return {boolean|string}
  63036. */
  63037. function contentType (str) {
  63038. // TODO: should this even be in this module?
  63039. if (!str || typeof str !== 'string') {
  63040. return false
  63041. }
  63042. var mime = str.indexOf('/') === -1
  63043. ? exports.lookup(str)
  63044. : str
  63045. if (!mime) {
  63046. return false
  63047. }
  63048. // TODO: use content-type or other module
  63049. if (mime.indexOf('charset') === -1) {
  63050. var charset = exports.charset(mime)
  63051. if (charset) mime += '; charset=' + charset.toLowerCase()
  63052. }
  63053. return mime
  63054. }
  63055. /**
  63056. * Get the default extension for a MIME type.
  63057. *
  63058. * @param {string} type
  63059. * @return {boolean|string}
  63060. */
  63061. function extension (type) {
  63062. if (!type || typeof type !== 'string') {
  63063. return false
  63064. }
  63065. // TODO: use media-typer
  63066. var match = EXTRACT_TYPE_REGEXP.exec(type)
  63067. // get extensions
  63068. var exts = match && exports.extensions[match[1].toLowerCase()]
  63069. if (!exts || !exts.length) {
  63070. return false
  63071. }
  63072. return exts[0]
  63073. }
  63074. /**
  63075. * Lookup the MIME type for a file path/extension.
  63076. *
  63077. * @param {string} path
  63078. * @return {boolean|string}
  63079. */
  63080. function lookup (path) {
  63081. if (!path || typeof path !== 'string') {
  63082. return false
  63083. }
  63084. // get the extension ("ext" or ".ext" or full path)
  63085. var extension = extname('x.' + path)
  63086. .toLowerCase()
  63087. .substr(1)
  63088. if (!extension) {
  63089. return false
  63090. }
  63091. return exports.types[extension] || false
  63092. }
  63093. /**
  63094. * Populate the extensions and types maps.
  63095. * @private
  63096. */
  63097. function populateMaps (extensions, types) {
  63098. // source preference (least -> most)
  63099. var preference = ['nginx', 'apache', undefined, 'iana']
  63100. Object.keys(db).forEach(function forEachMimeType (type) {
  63101. var mime = db[type]
  63102. var exts = mime.extensions
  63103. if (!exts || !exts.length) {
  63104. return
  63105. }
  63106. // mime -> extensions
  63107. extensions[type] = exts
  63108. // extension -> mime
  63109. for (var i = 0; i < exts.length; i++) {
  63110. var extension = exts[i]
  63111. if (types[extension]) {
  63112. var from = preference.indexOf(db[types[extension]].source)
  63113. var to = preference.indexOf(mime.source)
  63114. if (types[extension] !== 'application/octet-stream' &&
  63115. (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
  63116. // skip the remapping
  63117. continue
  63118. }
  63119. }
  63120. // set the extension -> mime
  63121. types[extension] = type
  63122. }
  63123. })
  63124. }
  63125. },{"mime-db":343,"path":517}],345:[function(require,module,exports){
  63126. module.exports = assert;
  63127. function assert(val, msg) {
  63128. if (!val)
  63129. throw new Error(msg || 'Assertion failed');
  63130. }
  63131. assert.equal = function assertEqual(l, r, msg) {
  63132. if (l != r)
  63133. throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
  63134. };
  63135. },{}],346:[function(require,module,exports){
  63136. 'use strict';
  63137. var utils = exports;
  63138. function toArray(msg, enc) {
  63139. if (Array.isArray(msg))
  63140. return msg.slice();
  63141. if (!msg)
  63142. return [];
  63143. var res = [];
  63144. if (typeof msg !== 'string') {
  63145. for (var i = 0; i < msg.length; i++)
  63146. res[i] = msg[i] | 0;
  63147. return res;
  63148. }
  63149. if (enc === 'hex') {
  63150. msg = msg.replace(/[^a-z0-9]+/ig, '');
  63151. if (msg.length % 2 !== 0)
  63152. msg = '0' + msg;
  63153. for (var i = 0; i < msg.length; i += 2)
  63154. res.push(parseInt(msg[i] + msg[i + 1], 16));
  63155. } else {
  63156. for (var i = 0; i < msg.length; i++) {
  63157. var c = msg.charCodeAt(i);
  63158. var hi = c >> 8;
  63159. var lo = c & 0xff;
  63160. if (hi)
  63161. res.push(hi, lo);
  63162. else
  63163. res.push(lo);
  63164. }
  63165. }
  63166. return res;
  63167. }
  63168. utils.toArray = toArray;
  63169. function zero2(word) {
  63170. if (word.length === 1)
  63171. return '0' + word;
  63172. else
  63173. return word;
  63174. }
  63175. utils.zero2 = zero2;
  63176. function toHex(msg) {
  63177. var res = '';
  63178. for (var i = 0; i < msg.length; i++)
  63179. res += zero2(msg[i].toString(16));
  63180. return res;
  63181. }
  63182. utils.toHex = toHex;
  63183. utils.encode = function encode(arr, enc) {
  63184. if (enc === 'hex')
  63185. return toHex(arr);
  63186. else
  63187. return arr;
  63188. };
  63189. },{}],347:[function(require,module,exports){
  63190. module.exports = require('./lib/tedious')
  63191. },{"./lib/tedious":366}],348:[function(require,module,exports){
  63192. (function (process,setImmediate){(function (){
  63193. 'use strict'
  63194. const { EventEmitter } = require('events')
  63195. const debug = require('debug')('mssql:base')
  63196. const tarn = require('tarn')
  63197. const { IDS } = require('../utils')
  63198. const ConnectionString = require('../connectionstring')
  63199. const ConnectionError = require('../error/connection-error')
  63200. const shared = require('../shared')
  63201. /**
  63202. * Class ConnectionPool.
  63203. *
  63204. * Internally, each `Connection` instance is a separate pool of TDS connections. Once you create a new `Request`/`Transaction`/`Prepared Statement`, a new TDS connection is acquired from the pool and reserved for desired action. Once the action is complete, connection is released back to the pool.
  63205. *
  63206. * @property {Boolean} connected If true, connection is established.
  63207. * @property {Boolean} connecting If true, connection is being established.
  63208. *
  63209. * @fires ConnectionPool#connect
  63210. * @fires ConnectionPool#close
  63211. */
  63212. class ConnectionPool extends EventEmitter {
  63213. /**
  63214. * Create new Connection.
  63215. *
  63216. * @param {Object|String} config Connection configuration object or connection string.
  63217. * @param {basicCallback} [callback] A callback which is called after connection has established, or an error has occurred.
  63218. */
  63219. constructor (config, callback) {
  63220. super()
  63221. IDS.add(this, 'ConnectionPool')
  63222. debug('pool(%d): created', IDS.get(this))
  63223. this._connectStack = []
  63224. this._closeStack = []
  63225. this._connected = false
  63226. this._connecting = false
  63227. this._healthy = false
  63228. if (typeof config === 'string') {
  63229. try {
  63230. this.config = ConnectionString.resolve(config, shared.driver.name)
  63231. } catch (ex) {
  63232. if (typeof callback === 'function') {
  63233. return setImmediate(callback, ex)
  63234. }
  63235. throw ex
  63236. }
  63237. } else {
  63238. this.config = Object.assign({}, config)
  63239. }
  63240. // set defaults
  63241. this.config.port = this.config.port || 1433
  63242. this.config.options = this.config.options || {}
  63243. this.config.stream = this.config.stream || false
  63244. this.config.parseJSON = this.config.parseJSON || false
  63245. if (/^(.*)\\(.*)$/.exec(this.config.server)) {
  63246. this.config.server = RegExp.$1
  63247. this.config.options.instanceName = RegExp.$2
  63248. }
  63249. if (typeof callback === 'function') {
  63250. this.connect(callback)
  63251. }
  63252. }
  63253. get connected () {
  63254. return this._connected
  63255. }
  63256. get connecting () {
  63257. return this._connecting
  63258. }
  63259. get healthy () {
  63260. return this._healthy
  63261. }
  63262. /**
  63263. * Acquire connection from this connection pool.
  63264. *
  63265. * @param {ConnectionPool|Transaction|PreparedStatement} requester Requester.
  63266. * @param {acquireCallback} [callback] A callback which is called after connection has been acquired, or an error has occurred. If omited, method returns Promise.
  63267. * @return {ConnectionPool|Promise}
  63268. */
  63269. acquire (requester, callback) {
  63270. const acquirePromise = shared.Promise.resolve(this._acquire().promise).catch(err => {
  63271. this.emit('error', err)
  63272. throw err
  63273. })
  63274. if (typeof callback === 'function') {
  63275. acquirePromise.then(connection => callback(null, connection, this.config)).catch(callback)
  63276. return this
  63277. }
  63278. return acquirePromise
  63279. }
  63280. _acquire () {
  63281. if (!this.pool) {
  63282. return shared.Promise.reject(new ConnectionError('Connection not yet open.', 'ENOTOPEN'))
  63283. } else if (this.pool.destroyed) {
  63284. return shared.Promise.reject(new ConnectionError('Connection is closing', 'ENOTOPEN'))
  63285. }
  63286. return this.pool.acquire()
  63287. }
  63288. /**
  63289. * Release connection back to the pool.
  63290. *
  63291. * @param {Connection} connection Previously acquired connection.
  63292. * @return {ConnectionPool}
  63293. */
  63294. release (connection) {
  63295. debug('connection(%d): released', IDS.get(connection))
  63296. if (this.pool) {
  63297. this.pool.release(connection)
  63298. }
  63299. return this
  63300. }
  63301. /**
  63302. * Creates a new connection pool with one active connection. This one initial connection serves as a probe to find out whether the configuration is valid.
  63303. *
  63304. * @param {basicCallback} [callback] A callback which is called after connection has established, or an error has occurred. If omited, method returns Promise.
  63305. * @return {ConnectionPool|Promise}
  63306. */
  63307. connect (callback) {
  63308. if (typeof callback === 'function') {
  63309. this._connect(callback)
  63310. return this
  63311. }
  63312. return new shared.Promise((resolve, reject) => {
  63313. return this._connect(err => {
  63314. if (err) return reject(err)
  63315. resolve(this)
  63316. })
  63317. })
  63318. }
  63319. /**
  63320. * @private
  63321. * @param {basicCallback} callback
  63322. */
  63323. _connect (callback) {
  63324. if (this._connected) {
  63325. debug('pool(%d): already connected, executing connect callback immediately', IDS.get(this))
  63326. return setImmediate(callback, null, this)
  63327. }
  63328. this._connectStack.push(callback)
  63329. if (this._connecting) {
  63330. return
  63331. }
  63332. this._connecting = true
  63333. debug('pool(%d): connecting', IDS.get(this))
  63334. // create one test connection to check if everything is ok
  63335. this._poolCreate().then((connection) => {
  63336. debug('pool(%d): connected', IDS.get(this))
  63337. this._healthy = true
  63338. return this._poolDestroy(connection).then(() => {
  63339. // prepare pool
  63340. this.pool = new tarn.Pool(
  63341. Object.assign({
  63342. create: () => this._poolCreate()
  63343. .then(connection => {
  63344. this._healthy = true
  63345. return connection
  63346. })
  63347. .catch(err => {
  63348. if (this.pool.numUsed() + this.pool.numFree() <= 0) {
  63349. this._healthy = false
  63350. }
  63351. throw err
  63352. }),
  63353. validate: this._poolValidate.bind(this),
  63354. destroy: this._poolDestroy.bind(this),
  63355. max: 10,
  63356. min: 0,
  63357. idleTimeoutMillis: 30000,
  63358. propagateCreateError: true
  63359. }, this.config.pool)
  63360. )
  63361. const self = this
  63362. Object.defineProperties(this.pool, {
  63363. size: {
  63364. get: () => {
  63365. const message = 'the `size` property on pool is deprecated, access it directly on the `ConnectionPool`'
  63366. self.emit('debug', message)
  63367. process.emitWarning(message)
  63368. return self.size
  63369. }
  63370. },
  63371. available: {
  63372. get: () => {
  63373. const message = 'the `available` property on pool is deprecated, access it directly on the `ConnectionPool`'
  63374. self.emit('debug', message)
  63375. process.emitWarning(message)
  63376. return self.available
  63377. }
  63378. },
  63379. pending: {
  63380. get: () => {
  63381. const message = 'the `pending` property on pool is deprecate, access it directly on the `ConnectionPool`'
  63382. self.emit('debug', message)
  63383. process.emitWarning(message)
  63384. return self.pending
  63385. }
  63386. },
  63387. borrowed: {
  63388. get: () => {
  63389. const message = 'the `borrowed` property on pool is deprecated, access it directly on the `ConnectionPool`'
  63390. self.emit('debug', message)
  63391. process.emitWarning(message)
  63392. return self.borrowed
  63393. }
  63394. }
  63395. })
  63396. this._connecting = false
  63397. this._connected = true
  63398. })
  63399. }).then(() => {
  63400. this._connectStack.forEach((cb) => {
  63401. setImmediate(cb, null, this)
  63402. })
  63403. }).catch(err => {
  63404. this._connecting = false
  63405. this._connectStack.forEach((cb) => {
  63406. setImmediate(cb, err)
  63407. })
  63408. }).then(() => {
  63409. this._connectStack = []
  63410. })
  63411. }
  63412. get size () {
  63413. return this.pool.numFree() + this.pool.numUsed() + this.pool.numPendingCreates()
  63414. }
  63415. get available () {
  63416. return this.pool.numFree()
  63417. }
  63418. get pending () {
  63419. return this.pool.numPendingAcquires()
  63420. }
  63421. get borrowed () {
  63422. return this.pool.numUsed()
  63423. }
  63424. /**
  63425. * Close all active connections in the pool.
  63426. *
  63427. * @param {basicCallback} [callback] A callback which is called after connection has closed, or an error has occurred. If omited, method returns Promise.
  63428. * @return {ConnectionPool|Promise}
  63429. */
  63430. close (callback) {
  63431. if (typeof callback === 'function') {
  63432. this._close(callback)
  63433. return this
  63434. }
  63435. return new shared.Promise((resolve, reject) => {
  63436. this._close(err => {
  63437. if (err) return reject(err)
  63438. resolve(this)
  63439. })
  63440. })
  63441. }
  63442. /**
  63443. * @private
  63444. * @param {basicCallback} callback
  63445. */
  63446. _close (callback) {
  63447. // we don't allow pools in a connecting state to be closed because it means there are far too many
  63448. // edge cases to deal with
  63449. if (this._connecting) {
  63450. debug('pool(%d): close called while connecting', IDS.get(this))
  63451. setImmediate(callback, new ConnectionError('Cannot close a pool while it is connecting'))
  63452. }
  63453. if (!this.pool) {
  63454. debug('pool(%d): already closed, executing close callback immediately', IDS.get(this))
  63455. return setImmediate(callback, null)
  63456. }
  63457. this._closeStack.push(callback)
  63458. if (this.pool.destroyed) return
  63459. this._connecting = this._connected = this._healthy = false
  63460. this.pool.destroy().then(() => {
  63461. debug('pool(%d): pool closed, removing pool reference and executing close callbacks', IDS.get(this))
  63462. this.pool = null
  63463. this._closeStack.forEach(cb => {
  63464. setImmediate(cb, null)
  63465. })
  63466. }).catch(err => {
  63467. this.pool = null
  63468. this._closeStack.forEach(cb => {
  63469. setImmediate(cb, err)
  63470. })
  63471. }).then(() => {
  63472. this._closeStack = []
  63473. })
  63474. }
  63475. /**
  63476. * Returns new request using this connection.
  63477. *
  63478. * @return {Request}
  63479. */
  63480. request () {
  63481. return new shared.driver.Request(this)
  63482. }
  63483. /**
  63484. * Returns new transaction using this connection.
  63485. *
  63486. * @return {Transaction}
  63487. */
  63488. transaction () {
  63489. return new shared.driver.Transaction(this)
  63490. }
  63491. /**
  63492. * Creates a new query using this connection from a tagged template string.
  63493. *
  63494. * @variation 1
  63495. * @param {Array} strings Array of string literals.
  63496. * @param {...*} keys Values.
  63497. * @return {Request}
  63498. */
  63499. /**
  63500. * Execute the SQL command.
  63501. *
  63502. * @variation 2
  63503. * @param {String} command T-SQL command to be executed.
  63504. * @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  63505. * @return {Request|Promise}
  63506. */
  63507. query () {
  63508. if (typeof arguments[0] === 'string') { return new shared.driver.Request(this).query(arguments[0], arguments[1]) }
  63509. const values = Array.prototype.slice.call(arguments)
  63510. const strings = values.shift()
  63511. return new shared.driver.Request(this)._template(strings, values, 'query')
  63512. }
  63513. /**
  63514. * Creates a new batch using this connection from a tagged template string.
  63515. *
  63516. * @variation 1
  63517. * @param {Array} strings Array of string literals.
  63518. * @param {...*} keys Values.
  63519. * @return {Request}
  63520. */
  63521. /**
  63522. * Execute the SQL command.
  63523. *
  63524. * @variation 2
  63525. * @param {String} command T-SQL command to be executed.
  63526. * @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  63527. * @return {Request|Promise}
  63528. */
  63529. batch () {
  63530. if (typeof arguments[0] === 'string') { return new shared.driver.Request(this).batch(arguments[0], arguments[1]) }
  63531. const values = Array.prototype.slice.call(arguments)
  63532. const strings = values.shift()
  63533. return new shared.driver.Request(this)._template(strings, values, 'batch')
  63534. }
  63535. }
  63536. module.exports = ConnectionPool
  63537. }).call(this)}).call(this,require('_process'),require("timers").setImmediate)
  63538. },{"../connectionstring":353,"../error/connection-error":355,"../shared":363,"../utils":370,"_process":525,"debug":372,"events":247,"tarn":637,"timers":639}],349:[function(require,module,exports){
  63539. 'use strict'
  63540. const ConnectionPool = require('./connection-pool')
  63541. const PreparedStatement = require('./prepared-statement')
  63542. const Request = require('./request')
  63543. const Transaction = require('./transaction')
  63544. const { ConnectionError, TransactionError, RequestError, PreparedStatementError, MSSQLError } = require('../error')
  63545. const shared = require('../shared')
  63546. const Table = require('../table')
  63547. const ISOLATION_LEVEL = require('../isolationlevel')
  63548. const { TYPES } = require('../datatypes')
  63549. const { connect, close, on, off, removeListener, query, batch } = require('../global-connection')
  63550. module.exports = {
  63551. ConnectionPool,
  63552. Transaction,
  63553. Request,
  63554. PreparedStatement,
  63555. ConnectionError,
  63556. TransactionError,
  63557. RequestError,
  63558. PreparedStatementError,
  63559. MSSQLError,
  63560. driver: shared.driver,
  63561. exports: {
  63562. ConnectionError,
  63563. TransactionError,
  63564. RequestError,
  63565. PreparedStatementError,
  63566. MSSQLError,
  63567. Table,
  63568. ISOLATION_LEVEL,
  63569. TYPES,
  63570. MAX: 65535, // (1 << 16) - 1
  63571. map: shared.map,
  63572. getTypeByValue: shared.getTypeByValue,
  63573. connect,
  63574. close,
  63575. on,
  63576. removeListener,
  63577. off,
  63578. query,
  63579. batch
  63580. }
  63581. }
  63582. Object.defineProperty(module.exports, 'Promise', {
  63583. enumerable: true,
  63584. get: () => {
  63585. return shared.Promise
  63586. },
  63587. set: (value) => {
  63588. shared.Promise = value
  63589. }
  63590. })
  63591. for (const key in TYPES) {
  63592. const value = TYPES[key]
  63593. module.exports.exports[key] = value
  63594. module.exports.exports[key.toUpperCase()] = value
  63595. }
  63596. /**
  63597. * @callback Request~requestCallback
  63598. * @param {Error} err Error on error, otherwise null.
  63599. * @param {Object} [result] Request result.
  63600. */
  63601. /**
  63602. * @callback Request~bulkCallback
  63603. * @param {Error} err Error on error, otherwise null.
  63604. * @param {Number} [rowsAffected] Number of affected rows.
  63605. */
  63606. /**
  63607. * @callback basicCallback
  63608. * @param {Error} err Error on error, otherwise null.
  63609. * @param {Connection} [connection] Acquired connection.
  63610. */
  63611. /**
  63612. * @callback acquireCallback
  63613. * @param {Error} err Error on error, otherwise null.
  63614. * @param {Connection} [connection] Acquired connection.
  63615. * @param {Object} [config] Connection config
  63616. */
  63617. /**
  63618. * Dispatched after connection has established.
  63619. * @event ConnectionPool#connect
  63620. */
  63621. /**
  63622. * Dispatched after connection has closed a pool (by calling close).
  63623. * @event ConnectionPool#close
  63624. */
  63625. /**
  63626. * Dispatched when transaction begin.
  63627. * @event Transaction#begin
  63628. */
  63629. /**
  63630. * Dispatched on successful commit.
  63631. * @event Transaction#commit
  63632. */
  63633. /**
  63634. * Dispatched on successful rollback.
  63635. * @event Transaction#rollback
  63636. */
  63637. /**
  63638. * Dispatched when metadata for new recordset are parsed.
  63639. * @event Request#recordset
  63640. */
  63641. /**
  63642. * Dispatched when new row is parsed.
  63643. * @event Request#row
  63644. */
  63645. /**
  63646. * Dispatched when request is complete.
  63647. * @event Request#done
  63648. */
  63649. /**
  63650. * Dispatched on error.
  63651. * @event Request#error
  63652. */
  63653. },{"../datatypes":354,"../error":356,"../global-connection":361,"../isolationlevel":362,"../shared":363,"../table":364,"./connection-pool":348,"./prepared-statement":350,"./request":351,"./transaction":352}],350:[function(require,module,exports){
  63654. (function (setImmediate){(function (){
  63655. 'use strict'
  63656. const debug = require('debug')('mssql:base')
  63657. const { EventEmitter } = require('events')
  63658. const { IDS, objectHasProperty } = require('../utils')
  63659. const globalConnection = require('../global-connection')
  63660. const { TransactionError, PreparedStatementError } = require('../error')
  63661. const shared = require('../shared')
  63662. const { TYPES, declare } = require('../datatypes')
  63663. /**
  63664. * Class PreparedStatement.
  63665. *
  63666. * IMPORTANT: Rememeber that each prepared statement means one reserved connection from the pool. Don't forget to unprepare a prepared statement!
  63667. *
  63668. * @property {String} statement Prepared SQL statement.
  63669. */
  63670. class PreparedStatement extends EventEmitter {
  63671. /**
  63672. * Creates a new Prepared Statement.
  63673. *
  63674. * @param {ConnectionPool|Transaction} [holder]
  63675. */
  63676. constructor (parent) {
  63677. super()
  63678. IDS.add(this, 'PreparedStatement')
  63679. debug('ps(%d): created', IDS.get(this))
  63680. this.parent = parent || globalConnection.pool
  63681. this._handle = 0
  63682. this.prepared = false
  63683. this.parameters = {}
  63684. }
  63685. get connected () {
  63686. return this.parent.connected
  63687. }
  63688. /**
  63689. * Acquire connection from connection pool.
  63690. *
  63691. * @param {Request} request Request.
  63692. * @param {ConnectionPool~acquireCallback} [callback] A callback which is called after connection has established, or an error has occurred. If omited, method returns Promise.
  63693. * @return {PreparedStatement|Promise}
  63694. */
  63695. acquire (request, callback) {
  63696. if (!this._acquiredConnection) {
  63697. setImmediate(callback, new PreparedStatementError('Statement is not prepared. Call prepare() first.', 'ENOTPREPARED'))
  63698. return this
  63699. }
  63700. if (this._activeRequest) {
  63701. setImmediate(callback, new TransactionError("Can't acquire connection for the request. There is another request in progress.", 'EREQINPROG'))
  63702. return this
  63703. }
  63704. this._activeRequest = request
  63705. setImmediate(callback, null, this._acquiredConnection, this._acquiredConfig)
  63706. return this
  63707. }
  63708. /**
  63709. * Release connection back to the pool.
  63710. *
  63711. * @param {Connection} connection Previously acquired connection.
  63712. * @return {PreparedStatement}
  63713. */
  63714. release (connection) {
  63715. if (connection === this._acquiredConnection) {
  63716. this._activeRequest = null
  63717. }
  63718. return this
  63719. }
  63720. /**
  63721. * Add an input parameter to the prepared statement.
  63722. *
  63723. * @param {String} name Name of the input parameter without @ char.
  63724. * @param {*} type SQL data type of input parameter.
  63725. * @return {PreparedStatement}
  63726. */
  63727. input (name, type) {
  63728. if ((/(--| |\/\*|\*\/|')/).test(name)) {
  63729. throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
  63730. }
  63731. if (arguments.length < 2) {
  63732. throw new PreparedStatementError('Invalid number of arguments. 2 arguments expected.', 'EARGS')
  63733. }
  63734. if (type instanceof Function) {
  63735. type = type()
  63736. }
  63737. if (objectHasProperty(this.parameters, name)) {
  63738. throw new PreparedStatementError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
  63739. }
  63740. this.parameters[name] = {
  63741. name,
  63742. type: type.type,
  63743. io: 1,
  63744. length: type.length,
  63745. scale: type.scale,
  63746. precision: type.precision,
  63747. tvpType: type.tvpType
  63748. }
  63749. return this
  63750. }
  63751. /**
  63752. * Replace an input parameter on the request.
  63753. *
  63754. * @param {String} name Name of the input parameter without @ char.
  63755. * @param {*} [type] SQL data type of input parameter. If you omit type, module automaticaly decide which SQL data type should be used based on JS data type.
  63756. * @param {*} value Input parameter value. `undefined` and `NaN` values are automatically converted to `null` values.
  63757. * @return {Request}
  63758. */
  63759. replaceInput (name, type, value) {
  63760. delete this.parameters[name]
  63761. return this.input(name, type, value)
  63762. }
  63763. /**
  63764. * Add an output parameter to the prepared statement.
  63765. *
  63766. * @param {String} name Name of the output parameter without @ char.
  63767. * @param {*} type SQL data type of output parameter.
  63768. * @return {PreparedStatement}
  63769. */
  63770. output (name, type) {
  63771. if (/(--| |\/\*|\*\/|')/.test(name)) {
  63772. throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
  63773. }
  63774. if (arguments.length < 2) {
  63775. throw new PreparedStatementError('Invalid number of arguments. 2 arguments expected.', 'EARGS')
  63776. }
  63777. if (type instanceof Function) type = type()
  63778. if (objectHasProperty(this.parameters, name)) {
  63779. throw new PreparedStatementError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
  63780. }
  63781. this.parameters[name] = {
  63782. name,
  63783. type: type.type,
  63784. io: 2,
  63785. length: type.length,
  63786. scale: type.scale,
  63787. precision: type.precision
  63788. }
  63789. return this
  63790. }
  63791. /**
  63792. * Replace an output parameter on the request.
  63793. *
  63794. * @param {String} name Name of the output parameter without @ char.
  63795. * @param {*} type SQL data type of output parameter.
  63796. * @return {PreparedStatement}
  63797. */
  63798. replaceOutput (name, type) {
  63799. delete this.parameters[name]
  63800. return this.output(name, type)
  63801. }
  63802. /**
  63803. * Prepare a statement.
  63804. *
  63805. * @param {String} statement SQL statement to prepare.
  63806. * @param {basicCallback} [callback] A callback which is called after preparation has completed, or an error has occurred. If omited, method returns Promise.
  63807. * @return {PreparedStatement|Promise}
  63808. */
  63809. prepare (statement, callback) {
  63810. if (typeof callback === 'function') {
  63811. this._prepare(statement, callback)
  63812. return this
  63813. }
  63814. return new shared.Promise((resolve, reject) => {
  63815. this._prepare(statement, err => {
  63816. if (err) return reject(err)
  63817. resolve(this)
  63818. })
  63819. })
  63820. }
  63821. /**
  63822. * @private
  63823. * @param {String} statement
  63824. * @param {basicCallback} callback
  63825. */
  63826. _prepare (statement, callback) {
  63827. debug('ps(%d): prepare', IDS.get(this))
  63828. if (typeof statement === 'function') {
  63829. callback = statement
  63830. statement = undefined
  63831. }
  63832. if (this.prepared) {
  63833. return setImmediate(callback, new PreparedStatementError('Statement is already prepared.', 'EALREADYPREPARED'))
  63834. }
  63835. this.statement = statement || this.statement
  63836. this.parent.acquire(this, (err, connection, config) => {
  63837. if (err) return callback(err)
  63838. this._acquiredConnection = connection
  63839. this._acquiredConfig = config
  63840. const req = new shared.driver.Request(this)
  63841. req.stream = false
  63842. req.output('handle', TYPES.Int)
  63843. req.input('params', TYPES.NVarChar, ((() => {
  63844. const result = []
  63845. for (const name in this.parameters) {
  63846. if (!objectHasProperty(this.parameters, name)) {
  63847. continue
  63848. }
  63849. const param = this.parameters[name]
  63850. result.push(`@${name} ${declare(param.type, param)}${param.io === 2 ? ' output' : ''}`)
  63851. }
  63852. return result
  63853. })()).join(','))
  63854. req.input('stmt', TYPES.NVarChar, this.statement)
  63855. req.execute('sp_prepare', (err, result) => {
  63856. if (err) {
  63857. this.parent.release(this._acquiredConnection)
  63858. this._acquiredConnection = null
  63859. this._acquiredConfig = null
  63860. return callback(err)
  63861. }
  63862. debug('ps(%d): prepared', IDS.get(this))
  63863. this._handle = result.output.handle
  63864. this.prepared = true
  63865. callback(null)
  63866. })
  63867. })
  63868. }
  63869. /**
  63870. * Execute a prepared statement.
  63871. *
  63872. * @param {Object} values An object whose names correspond to the names of parameters that were added to the prepared statement before it was prepared.
  63873. * @param {basicCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  63874. * @return {Request|Promise}
  63875. */
  63876. execute (values, callback) {
  63877. if (this.stream || (typeof callback === 'function')) {
  63878. return this._execute(values, callback)
  63879. }
  63880. return new shared.Promise((resolve, reject) => {
  63881. this._execute(values, (err, recordset) => {
  63882. if (err) return reject(err)
  63883. resolve(recordset)
  63884. })
  63885. })
  63886. }
  63887. /**
  63888. * @private
  63889. * @param {Object} values
  63890. * @param {basicCallback} callback
  63891. */
  63892. _execute (values, callback) {
  63893. const req = new shared.driver.Request(this)
  63894. req.stream = this.stream
  63895. req.input('handle', TYPES.Int, this._handle)
  63896. // copy parameters with new values
  63897. for (const name in this.parameters) {
  63898. if (!objectHasProperty(this.parameters, name)) {
  63899. continue
  63900. }
  63901. const param = this.parameters[name]
  63902. req.parameters[name] = {
  63903. name,
  63904. type: param.type,
  63905. io: param.io,
  63906. value: values[name],
  63907. length: param.length,
  63908. scale: param.scale,
  63909. precision: param.precision
  63910. }
  63911. }
  63912. req.execute('sp_execute', (err, result) => {
  63913. if (err) return callback(err)
  63914. callback(null, result)
  63915. })
  63916. return req
  63917. }
  63918. /**
  63919. * Unprepare a prepared statement.
  63920. *
  63921. * @param {basicCallback} [callback] A callback which is called after unpreparation has completed, or an error has occurred. If omited, method returns Promise.
  63922. * @return {PreparedStatement|Promise}
  63923. */
  63924. unprepare (callback) {
  63925. if (typeof callback === 'function') {
  63926. this._unprepare(callback)
  63927. return this
  63928. }
  63929. return new shared.Promise((resolve, reject) => {
  63930. this._unprepare(err => {
  63931. if (err) return reject(err)
  63932. resolve()
  63933. })
  63934. })
  63935. }
  63936. /**
  63937. * @private
  63938. * @param {basicCallback} callback
  63939. */
  63940. _unprepare (callback) {
  63941. debug('ps(%d): unprepare', IDS.get(this))
  63942. if (!this.prepared) {
  63943. return setImmediate(callback, new PreparedStatementError('Statement is not prepared. Call prepare() first.', 'ENOTPREPARED'))
  63944. }
  63945. if (this._activeRequest) {
  63946. return setImmediate(callback, new TransactionError("Can't unprepare the statement. There is a request in progress.", 'EREQINPROG'))
  63947. }
  63948. const req = new shared.driver.Request(this)
  63949. req.stream = false
  63950. req.input('handle', TYPES.Int, this._handle)
  63951. req.execute('sp_unprepare', err => {
  63952. if (err) return callback(err)
  63953. this.parent.release(this._acquiredConnection)
  63954. this._acquiredConnection = null
  63955. this._acquiredConfig = null
  63956. this._handle = 0
  63957. this.prepared = false
  63958. debug('ps(%d): unprepared', IDS.get(this))
  63959. return callback(null)
  63960. })
  63961. }
  63962. }
  63963. module.exports = PreparedStatement
  63964. }).call(this)}).call(this,require("timers").setImmediate)
  63965. },{"../datatypes":354,"../error":356,"../global-connection":361,"../shared":363,"../utils":370,"debug":372,"events":247,"timers":639}],351:[function(require,module,exports){
  63966. (function (setImmediate){(function (){
  63967. 'use strict'
  63968. const debug = require('debug')('mssql:base')
  63969. const { EventEmitter } = require('events')
  63970. const { IDS, objectHasProperty } = require('../utils')
  63971. const globalConnection = require('../global-connection')
  63972. const { RequestError, ConnectionError } = require('../error')
  63973. const { TYPES } = require('../datatypes')
  63974. const shared = require('../shared')
  63975. /**
  63976. * Class Request.
  63977. *
  63978. * @property {Transaction} transaction Reference to transaction when request was created in transaction.
  63979. * @property {*} parameters Collection of input and output parameters.
  63980. * @property {Boolean} canceled `true` if request was canceled.
  63981. *
  63982. * @fires Request#recordset
  63983. * @fires Request#row
  63984. * @fires Request#done
  63985. * @fires Request#error
  63986. */
  63987. class Request extends EventEmitter {
  63988. /**
  63989. * Create new Request.
  63990. *
  63991. * @param {Connection|ConnectionPool|Transaction|PreparedStatement} parent If ommited, global connection is used instead.
  63992. */
  63993. constructor (parent) {
  63994. super()
  63995. IDS.add(this, 'Request')
  63996. debug('request(%d): created', IDS.get(this))
  63997. this.canceled = false
  63998. this._paused = false
  63999. this.parent = parent || globalConnection.pool
  64000. this.parameters = {}
  64001. }
  64002. get paused () {
  64003. return this._paused
  64004. }
  64005. /**
  64006. * Generate sql string and set imput parameters from tagged template string.
  64007. *
  64008. * @param {Template literal} template
  64009. * @return {String}
  64010. */
  64011. template () {
  64012. const values = Array.prototype.slice.call(arguments)
  64013. const strings = values.shift()
  64014. return this._template(strings, values)
  64015. }
  64016. /**
  64017. * Fetch request from tagged template string.
  64018. *
  64019. * @private
  64020. * @param {Array} strings
  64021. * @param {Array} values
  64022. * @param {String} [method] If provided, method is automatically called with serialized command on this object.
  64023. * @return {Request}
  64024. */
  64025. _template (strings, values, method) {
  64026. const command = [strings[0]]
  64027. for (let index = 0; index < values.length; index++) {
  64028. const value = values[index]
  64029. // if value is an array, prepare each items as it's own comma separated parameter
  64030. if (Array.isArray(value)) {
  64031. for (let parameterIndex = 0; parameterIndex < value.length; parameterIndex++) {
  64032. this.input(`param${index + 1}_${parameterIndex}`, value[parameterIndex])
  64033. command.push(`@param${index + 1}_${parameterIndex}`)
  64034. if (parameterIndex < value.length - 1) {
  64035. command.push(', ')
  64036. }
  64037. }
  64038. command.push(strings[index + 1])
  64039. } else {
  64040. this.input(`param${index + 1}`, value)
  64041. command.push(`@param${index + 1}`, strings[index + 1])
  64042. }
  64043. }
  64044. if (method) {
  64045. return this[method](command.join(''))
  64046. } else {
  64047. return command.join('')
  64048. }
  64049. }
  64050. /**
  64051. * Add an input parameter to the request.
  64052. *
  64053. * @param {String} name Name of the input parameter without @ char.
  64054. * @param {*} [type] SQL data type of input parameter. If you omit type, module automaticaly decide which SQL data type should be used based on JS data type.
  64055. * @param {*} value Input parameter value. `undefined` and `NaN` values are automatically converted to `null` values.
  64056. * @return {Request}
  64057. */
  64058. input (name, type, value) {
  64059. if ((/(--| |\/\*|\*\/|')/).test(name)) {
  64060. throw new RequestError(`SQL injection warning for param '${name}'`, 'EINJECT')
  64061. }
  64062. if (arguments.length < 2) {
  64063. throw new RequestError('Invalid number of arguments. At least 2 arguments expected.', 'EARGS')
  64064. } else if (arguments.length === 2) {
  64065. value = type
  64066. type = shared.getTypeByValue(value)
  64067. }
  64068. // support for custom data types
  64069. if (value && typeof value.valueOf === 'function' && !(value instanceof Date)) value = value.valueOf()
  64070. if (value === undefined) value = null // undefined to null
  64071. if (typeof value === 'number' && isNaN(value)) value = null // NaN to null
  64072. if (type instanceof Function) type = type()
  64073. if (objectHasProperty(this.parameters, name)) {
  64074. throw new RequestError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
  64075. }
  64076. this.parameters[name] = {
  64077. name,
  64078. type: type.type,
  64079. io: 1,
  64080. value,
  64081. length: type.length,
  64082. scale: type.scale,
  64083. precision: type.precision,
  64084. tvpType: type.tvpType
  64085. }
  64086. return this
  64087. }
  64088. /**
  64089. * Replace an input parameter on the request.
  64090. *
  64091. * @param {String} name Name of the input parameter without @ char.
  64092. * @param {*} [type] SQL data type of input parameter. If you omit type, module automaticaly decide which SQL data type should be used based on JS data type.
  64093. * @param {*} value Input parameter value. `undefined` and `NaN` values are automatically converted to `null` values.
  64094. * @return {Request}
  64095. */
  64096. replaceInput (name, type, value) {
  64097. delete this.parameters[name]
  64098. return this.input(name, type, value)
  64099. }
  64100. /**
  64101. * Add an output parameter to the request.
  64102. *
  64103. * @param {String} name Name of the output parameter without @ char.
  64104. * @param {*} type SQL data type of output parameter.
  64105. * @param {*} [value] Output parameter value initial value. `undefined` and `NaN` values are automatically converted to `null` values. Optional.
  64106. * @return {Request}
  64107. */
  64108. output (name, type, value) {
  64109. if (!type) { type = TYPES.NVarChar }
  64110. if ((/(--| |\/\*|\*\/|')/).test(name)) {
  64111. throw new RequestError(`SQL injection warning for param '${name}'`, 'EINJECT')
  64112. }
  64113. if ((type === TYPES.Text) || (type === TYPES.NText) || (type === TYPES.Image)) {
  64114. throw new RequestError('Deprecated types (Text, NText, Image) are not supported as OUTPUT parameters.', 'EDEPRECATED')
  64115. }
  64116. // support for custom data types
  64117. if (value && typeof value.valueOf === 'function' && !(value instanceof Date)) value = value.valueOf()
  64118. if (value === undefined) value = null // undefined to null
  64119. if (typeof value === 'number' && isNaN(value)) value = null // NaN to null
  64120. if (type instanceof Function) type = type()
  64121. if (objectHasProperty(this.parameters, name)) {
  64122. throw new RequestError(`The parameter name ${name} has already been declared. Parameter names must be unique`, 'EDUPEPARAM')
  64123. }
  64124. this.parameters[name] = {
  64125. name,
  64126. type: type.type,
  64127. io: 2,
  64128. value,
  64129. length: type.length,
  64130. scale: type.scale,
  64131. precision: type.precision
  64132. }
  64133. return this
  64134. }
  64135. /**
  64136. * Replace an output parameter on the request.
  64137. *
  64138. * @param {String} name Name of the output parameter without @ char.
  64139. * @param {*} type SQL data type of output parameter.
  64140. * @param {*} [value] Output parameter value initial value. `undefined` and `NaN` values are automatically converted to `null` values. Optional.
  64141. * @return {Request}
  64142. */
  64143. replaceOutput (name, type, value) {
  64144. delete this.parameters[name]
  64145. return this.output(name, type, value)
  64146. }
  64147. /**
  64148. * Execute the SQL batch.
  64149. *
  64150. * @param {String} batch T-SQL batch to be executed.
  64151. * @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  64152. * @return {Request|Promise}
  64153. */
  64154. batch (batch, callback) {
  64155. if (this.stream == null && this.connection) this.stream = this.connection.config.stream
  64156. this.rowsAffected = 0
  64157. if (typeof callback === 'function') {
  64158. this._batch(batch, (err, recordsets, output, rowsAffected) => {
  64159. if (this.stream) {
  64160. if (err) this.emit('error', err)
  64161. err = null
  64162. this.emit('done', {
  64163. output,
  64164. rowsAffected
  64165. })
  64166. }
  64167. if (err) return callback(err)
  64168. callback(null, {
  64169. recordsets,
  64170. recordset: recordsets && recordsets[0],
  64171. output,
  64172. rowsAffected
  64173. })
  64174. })
  64175. return this
  64176. }
  64177. // Check is method was called as tagged template
  64178. if (typeof batch === 'object') {
  64179. const values = Array.prototype.slice.call(arguments)
  64180. const strings = values.shift()
  64181. batch = this._template(strings, values)
  64182. }
  64183. return new shared.Promise((resolve, reject) => {
  64184. this._batch(batch, (err, recordsets, output, rowsAffected) => {
  64185. if (this.stream) {
  64186. if (err) this.emit('error', err)
  64187. err = null
  64188. this.emit('done', {
  64189. output,
  64190. rowsAffected
  64191. })
  64192. }
  64193. if (err) return reject(err)
  64194. resolve({
  64195. recordsets,
  64196. recordset: recordsets && recordsets[0],
  64197. output,
  64198. rowsAffected
  64199. })
  64200. })
  64201. })
  64202. }
  64203. /**
  64204. * @private
  64205. * @param {String} batch
  64206. * @param {Request~requestCallback} callback
  64207. */
  64208. _batch (batch, callback) {
  64209. if (!this.connection) {
  64210. return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
  64211. }
  64212. if (!this.connection.connected) {
  64213. return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
  64214. }
  64215. this.canceled = false
  64216. setImmediate(callback)
  64217. }
  64218. /**
  64219. * Bulk load.
  64220. *
  64221. * @param {Table} table SQL table.
  64222. * @param {object} [options] Options to be passed to the underlying driver (tedious only).
  64223. * @param {Request~bulkCallback} [callback] A callback which is called after bulk load has completed, or an error has occurred. If omited, method returns Promise.
  64224. * @return {Request|Promise}
  64225. */
  64226. bulk (table, options, callback) {
  64227. if (typeof options === 'function') {
  64228. callback = options
  64229. options = {}
  64230. } else if (typeof options === 'undefined') {
  64231. options = {}
  64232. }
  64233. if (this.stream == null && this.connection) this.stream = this.connection.config.stream
  64234. if (this.stream || typeof callback === 'function') {
  64235. this._bulk(table, options, (err, rowsAffected) => {
  64236. if (this.stream) {
  64237. if (err) this.emit('error', err)
  64238. return this.emit('done', {
  64239. rowsAffected
  64240. })
  64241. }
  64242. if (err) return callback(err)
  64243. callback(null, {
  64244. rowsAffected
  64245. })
  64246. })
  64247. return this
  64248. }
  64249. return new shared.Promise((resolve, reject) => {
  64250. this._bulk(table, options, (err, rowsAffected) => {
  64251. if (err) return reject(err)
  64252. resolve({
  64253. rowsAffected
  64254. })
  64255. })
  64256. })
  64257. }
  64258. /**
  64259. * @private
  64260. * @param {Table} table
  64261. * @param {object} options
  64262. * @param {Request~bulkCallback} callback
  64263. */
  64264. _bulk (table, options, callback) {
  64265. if (!this.parent) {
  64266. return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
  64267. }
  64268. if (!this.parent.connected) {
  64269. return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
  64270. }
  64271. this.canceled = false
  64272. setImmediate(callback)
  64273. }
  64274. /**
  64275. * Sets request to `stream` mode and pulls all rows from all recordsets to a given stream.
  64276. *
  64277. * @param {Stream} stream Stream to pipe data into.
  64278. * @return {Stream}
  64279. */
  64280. pipe (stream) {
  64281. this.stream = true
  64282. this.on('row', stream.write.bind(stream))
  64283. this.on('error', stream.emit.bind(stream, 'error'))
  64284. this.on('done', () => {
  64285. setImmediate(() => stream.end())
  64286. })
  64287. stream.emit('pipe', this)
  64288. return stream
  64289. }
  64290. /**
  64291. * Execute the SQL command.
  64292. *
  64293. * @param {String} command T-SQL command to be executed.
  64294. * @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  64295. * @return {Request|Promise}
  64296. */
  64297. query (command, callback) {
  64298. if (this.stream == null && this.connection) this.stream = this.connection.config.stream
  64299. this.rowsAffected = 0
  64300. if (typeof callback === 'function') {
  64301. this._query(command, (err, recordsets, output, rowsAffected) => {
  64302. if (this.stream) {
  64303. if (err) this.emit('error', err)
  64304. err = null
  64305. this.emit('done', {
  64306. output,
  64307. rowsAffected
  64308. })
  64309. }
  64310. if (err) return callback(err)
  64311. callback(null, {
  64312. recordsets,
  64313. recordset: recordsets && recordsets[0],
  64314. output,
  64315. rowsAffected
  64316. })
  64317. })
  64318. return this
  64319. }
  64320. // Check is method was called as tagged template
  64321. if (typeof command === 'object') {
  64322. const values = Array.prototype.slice.call(arguments)
  64323. const strings = values.shift()
  64324. command = this._template(strings, values)
  64325. }
  64326. return new shared.Promise((resolve, reject) => {
  64327. this._query(command, (err, recordsets, output, rowsAffected) => {
  64328. if (this.stream) {
  64329. if (err) this.emit('error', err)
  64330. err = null
  64331. this.emit('done', {
  64332. output,
  64333. rowsAffected
  64334. })
  64335. }
  64336. if (err) return reject(err)
  64337. resolve({
  64338. recordsets,
  64339. recordset: recordsets && recordsets[0],
  64340. output,
  64341. rowsAffected
  64342. })
  64343. })
  64344. })
  64345. }
  64346. /**
  64347. * @private
  64348. * @param {String} command
  64349. * @param {Request~bulkCallback} callback
  64350. */
  64351. _query (command, callback) {
  64352. if (!this.parent) {
  64353. return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
  64354. }
  64355. if (!this.parent.connected) {
  64356. return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
  64357. }
  64358. this.canceled = false
  64359. setImmediate(callback)
  64360. }
  64361. /**
  64362. * Call a stored procedure.
  64363. *
  64364. * @param {String} procedure Name of the stored procedure to be executed.
  64365. * @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  64366. * @return {Request|Promise}
  64367. */
  64368. execute (command, callback) {
  64369. if (this.stream == null && this.connection) this.stream = this.connection.config.stream
  64370. this.rowsAffected = 0
  64371. if (typeof callback === 'function') {
  64372. this._execute(command, (err, recordsets, output, returnValue, rowsAffected) => {
  64373. if (this.stream) {
  64374. if (err) this.emit('error', err)
  64375. err = null
  64376. this.emit('done', {
  64377. output,
  64378. rowsAffected,
  64379. returnValue
  64380. })
  64381. }
  64382. if (err) return callback(err)
  64383. callback(null, {
  64384. recordsets,
  64385. recordset: recordsets && recordsets[0],
  64386. output,
  64387. rowsAffected,
  64388. returnValue
  64389. })
  64390. })
  64391. return this
  64392. }
  64393. return new shared.Promise((resolve, reject) => {
  64394. this._execute(command, (err, recordsets, output, returnValue, rowsAffected) => {
  64395. if (this.stream) {
  64396. if (err) this.emit('error', err)
  64397. err = null
  64398. this.emit('done', {
  64399. output,
  64400. rowsAffected,
  64401. returnValue
  64402. })
  64403. }
  64404. if (err) return reject(err)
  64405. resolve({
  64406. recordsets,
  64407. recordset: recordsets && recordsets[0],
  64408. output,
  64409. rowsAffected,
  64410. returnValue
  64411. })
  64412. })
  64413. })
  64414. }
  64415. /**
  64416. * @private
  64417. * @param {String} procedure
  64418. * @param {Request~bulkCallback} callback
  64419. */
  64420. _execute (procedure, callback) {
  64421. if (!this.parent) {
  64422. return setImmediate(callback, new RequestError('No connection is specified for that request.', 'ENOCONN'))
  64423. }
  64424. if (!this.parent.connected) {
  64425. return setImmediate(callback, new ConnectionError('Connection is closed.', 'ECONNCLOSED'))
  64426. }
  64427. this.canceled = false
  64428. setImmediate(callback)
  64429. }
  64430. /**
  64431. * Cancel currently executed request.
  64432. *
  64433. * @return {Boolean}
  64434. */
  64435. cancel () {
  64436. this._cancel()
  64437. return true
  64438. }
  64439. /**
  64440. * @private
  64441. */
  64442. _cancel () {
  64443. this.canceled = true
  64444. }
  64445. pause () {
  64446. if (this.stream) {
  64447. this._pause()
  64448. return true
  64449. }
  64450. return false
  64451. }
  64452. _pause () {
  64453. this._paused = true
  64454. }
  64455. resume () {
  64456. if (this.stream) {
  64457. this._resume()
  64458. return true
  64459. }
  64460. return false
  64461. }
  64462. _resume () {
  64463. this._paused = false
  64464. }
  64465. _setCurrentRequest (request) {
  64466. this._currentRequest = request
  64467. if (this._paused) {
  64468. this.pause()
  64469. }
  64470. return this
  64471. }
  64472. }
  64473. module.exports = Request
  64474. }).call(this)}).call(this,require("timers").setImmediate)
  64475. },{"../datatypes":354,"../error":356,"../global-connection":361,"../shared":363,"../utils":370,"debug":372,"events":247,"timers":639}],352:[function(require,module,exports){
  64476. (function (setImmediate){(function (){
  64477. 'use strict'
  64478. const debug = require('debug')('mssql:base')
  64479. const { EventEmitter } = require('events')
  64480. const { IDS } = require('../utils')
  64481. const globalConnection = require('../global-connection')
  64482. const { TransactionError } = require('../error')
  64483. const shared = require('../shared')
  64484. const ISOLATION_LEVEL = require('../isolationlevel')
  64485. /**
  64486. * Class Transaction.
  64487. *
  64488. * @property {Number} isolationLevel Controls the locking and row versioning behavior of TSQL statements issued by a connection. READ_COMMITTED by default.
  64489. * @property {String} name Transaction name. Empty string by default.
  64490. *
  64491. * @fires Transaction#begin
  64492. * @fires Transaction#commit
  64493. * @fires Transaction#rollback
  64494. */
  64495. class Transaction extends EventEmitter {
  64496. /**
  64497. * Create new Transaction.
  64498. *
  64499. * @param {Connection} [parent] If ommited, global connection is used instead.
  64500. */
  64501. constructor (parent) {
  64502. super()
  64503. IDS.add(this, 'Transaction')
  64504. debug('transaction(%d): created', IDS.get(this))
  64505. this.parent = parent || globalConnection.pool
  64506. this.isolationLevel = Transaction.defaultIsolationLevel
  64507. this.name = ''
  64508. }
  64509. get connected () {
  64510. return this.parent.connected
  64511. }
  64512. /**
  64513. * Acquire connection from connection pool.
  64514. *
  64515. * @param {Request} request Request.
  64516. * @param {ConnectionPool~acquireCallback} [callback] A callback which is called after connection has established, or an error has occurred. If omited, method returns Promise.
  64517. * @return {Transaction|Promise}
  64518. */
  64519. acquire (request, callback) {
  64520. if (!this._acquiredConnection) {
  64521. setImmediate(callback, new TransactionError('Transaction has not begun. Call begin() first.', 'ENOTBEGUN'))
  64522. return this
  64523. }
  64524. if (this._activeRequest) {
  64525. setImmediate(callback, new TransactionError("Can't acquire connection for the request. There is another request in progress.", 'EREQINPROG'))
  64526. return this
  64527. }
  64528. this._activeRequest = request
  64529. setImmediate(callback, null, this._acquiredConnection, this._acquiredConfig)
  64530. return this
  64531. }
  64532. /**
  64533. * Release connection back to the pool.
  64534. *
  64535. * @param {Connection} connection Previously acquired connection.
  64536. * @return {Transaction}
  64537. */
  64538. release (connection) {
  64539. if (connection === this._acquiredConnection) {
  64540. this._activeRequest = null
  64541. }
  64542. return this
  64543. }
  64544. /**
  64545. * Begin a transaction.
  64546. *
  64547. * @param {Number} [isolationLevel] Controls the locking and row versioning behavior of TSQL statements issued by a connection.
  64548. * @param {basicCallback} [callback] A callback which is called after transaction has began, or an error has occurred. If omited, method returns Promise.
  64549. * @return {Transaction|Promise}
  64550. */
  64551. begin (isolationLevel, callback) {
  64552. if (isolationLevel instanceof Function) {
  64553. callback = isolationLevel
  64554. isolationLevel = undefined
  64555. }
  64556. if (typeof callback === 'function') {
  64557. this._begin(isolationLevel, err => {
  64558. if (!err) {
  64559. this.emit('begin')
  64560. }
  64561. callback(err)
  64562. })
  64563. return this
  64564. }
  64565. return new shared.Promise((resolve, reject) => {
  64566. this._begin(isolationLevel, err => {
  64567. if (err) return reject(err)
  64568. this.emit('begin')
  64569. resolve(this)
  64570. })
  64571. })
  64572. }
  64573. /**
  64574. * @private
  64575. * @param {Number} [isolationLevel]
  64576. * @param {basicCallback} [callback]
  64577. * @return {Transaction}
  64578. */
  64579. _begin (isolationLevel, callback) {
  64580. if (this._acquiredConnection) {
  64581. return setImmediate(callback, new TransactionError('Transaction has already begun.', 'EALREADYBEGUN'))
  64582. }
  64583. this._aborted = false
  64584. this._rollbackRequested = false
  64585. if (isolationLevel) {
  64586. if (Object.keys(ISOLATION_LEVEL).some(key => {
  64587. return ISOLATION_LEVEL[key] === isolationLevel
  64588. })) {
  64589. this.isolationLevel = isolationLevel
  64590. } else {
  64591. throw new TransactionError('Invalid isolation level.')
  64592. }
  64593. }
  64594. setImmediate(callback)
  64595. }
  64596. /**
  64597. * Commit a transaction.
  64598. *
  64599. * @param {basicCallback} [callback] A callback which is called after transaction has commited, or an error has occurred. If omited, method returns Promise.
  64600. * @return {Transaction|Promise}
  64601. */
  64602. commit (callback) {
  64603. if (typeof callback === 'function') {
  64604. this._commit(err => {
  64605. if (!err) {
  64606. this.emit('commit')
  64607. }
  64608. callback(err)
  64609. })
  64610. return this
  64611. }
  64612. return new shared.Promise((resolve, reject) => {
  64613. this._commit(err => {
  64614. if (err) return reject(err)
  64615. this.emit('commit')
  64616. resolve()
  64617. })
  64618. })
  64619. }
  64620. /**
  64621. * @private
  64622. * @param {basicCallback} [callback]
  64623. * @return {Transaction}
  64624. */
  64625. _commit (callback) {
  64626. if (this._aborted) {
  64627. return setImmediate(callback, new TransactionError('Transaction has been aborted.', 'EABORT'))
  64628. }
  64629. if (!this._acquiredConnection) {
  64630. return setImmediate(callback, new TransactionError('Transaction has not begun. Call begin() first.', 'ENOTBEGUN'))
  64631. }
  64632. if (this._activeRequest) {
  64633. return setImmediate(callback, new TransactionError("Can't commit transaction. There is a request in progress.", 'EREQINPROG'))
  64634. }
  64635. setImmediate(callback)
  64636. }
  64637. /**
  64638. * Returns new request using this transaction.
  64639. *
  64640. * @return {Request}
  64641. */
  64642. request () {
  64643. return new shared.driver.Request(this)
  64644. }
  64645. /**
  64646. * Rollback a transaction.
  64647. *
  64648. * @param {basicCallback} [callback] A callback which is called after transaction has rolled back, or an error has occurred. If omited, method returns Promise.
  64649. * @return {Transaction|Promise}
  64650. */
  64651. rollback (callback) {
  64652. if (typeof callback === 'function') {
  64653. this._rollback(err => {
  64654. if (!err) {
  64655. this.emit('rollback', this._aborted)
  64656. }
  64657. callback(err)
  64658. })
  64659. return this
  64660. }
  64661. return new shared.Promise((resolve, reject) => {
  64662. return this._rollback(err => {
  64663. if (err) return reject(err)
  64664. this.emit('rollback', this._aborted)
  64665. resolve()
  64666. })
  64667. })
  64668. }
  64669. /**
  64670. * @private
  64671. * @param {basicCallback} [callback]
  64672. * @return {Transaction}
  64673. */
  64674. _rollback (callback) {
  64675. if (this._aborted) {
  64676. return setImmediate(callback, new TransactionError('Transaction has been aborted.', 'EABORT'))
  64677. }
  64678. if (!this._acquiredConnection) {
  64679. return setImmediate(callback, new TransactionError('Transaction has not begun. Call begin() first.', 'ENOTBEGUN'))
  64680. }
  64681. if (this._activeRequest) {
  64682. return setImmediate(callback, new TransactionError("Can't rollback transaction. There is a request in progress.", 'EREQINPROG'))
  64683. }
  64684. this._rollbackRequested = true
  64685. setImmediate(callback)
  64686. }
  64687. }
  64688. /**
  64689. * Default isolation level used for any transactions that don't explicitly specify an isolation level.
  64690. *
  64691. * @type {number}
  64692. */
  64693. Transaction.defaultIsolationLevel = ISOLATION_LEVEL.READ_COMMITTED
  64694. module.exports = Transaction
  64695. }).call(this)}).call(this,require("timers").setImmediate)
  64696. },{"../error":356,"../global-connection":361,"../isolationlevel":362,"../shared":363,"../utils":370,"debug":372,"events":247,"timers":639}],353:[function(require,module,exports){
  64697. 'use strict'
  64698. const URL = require('url').URL
  64699. const IGNORE_KEYS = ['stream']
  64700. const oror = function () {
  64701. for (let i = 0, l = arguments.length; i < l; i++) {
  64702. if (arguments[i] !== null && arguments[i] !== undefined) {
  64703. return arguments[i]
  64704. }
  64705. }
  64706. }
  64707. const parseConnectionURI = function (uri) {
  64708. const parsed = new URL(uri)
  64709. let instance
  64710. let user
  64711. let password
  64712. const path = parsed.pathname.substr(1).split('/')
  64713. if (path.length > 1) {
  64714. instance = path.shift()
  64715. }
  64716. if (parsed.username) {
  64717. const auth = [parsed.username, parsed.password]
  64718. user = decodeURIComponent(auth.shift())
  64719. password = decodeURIComponent(auth.join(':'))
  64720. }
  64721. const port = parsed.port ? `,${parsed.port}` : (instance ? `\\${instance}` : '')
  64722. const object = {
  64723. server: `${parsed.hostname}${port}`,
  64724. uid: user || '',
  64725. pwd: password || '',
  64726. database: path[0]
  64727. }
  64728. if (parsed.searchParams) {
  64729. parsed.searchParams.forEach((value, key) => {
  64730. if (key === 'domain') {
  64731. object.uid = `${value}\\${object.uid}`
  64732. } else {
  64733. object[key] = value
  64734. }
  64735. })
  64736. }
  64737. Object.defineProperty(object, 'toString', {
  64738. value () {
  64739. const out = []
  64740. for (const key in this) {
  64741. if (IGNORE_KEYS.indexOf(key) === -1) {
  64742. out.push(`${key}={${this[key]}}`)
  64743. }
  64744. }
  64745. return out.join(';')
  64746. }
  64747. })
  64748. return object
  64749. }
  64750. const parseConnectionString = function (string) {
  64751. let cursor = 0
  64752. let parsing = 'name'
  64753. let param = null
  64754. let buffer = ''
  64755. let quotes = null
  64756. const parsed = {}
  64757. const original = {}
  64758. Object.defineProperty(parsed, '__original__', { value: original })
  64759. Object.defineProperty(parsed, 'toString', {
  64760. value () {
  64761. const out = []
  64762. for (const key in this) {
  64763. if (IGNORE_KEYS.indexOf(key) === -1) {
  64764. const esc = original[key].escape || ['', '']
  64765. out.push(`${original[key].name}=${esc[0] || ''}${this[key]}${esc[1] || ''}`)
  64766. }
  64767. }
  64768. return out.join(';')
  64769. }
  64770. })
  64771. while (cursor < string.length) {
  64772. const char = string.charAt(cursor)
  64773. switch (char) {
  64774. case '=':
  64775. if (parsing === 'name') {
  64776. buffer = buffer.trim()
  64777. param = buffer.toLowerCase()
  64778. original[param] = { name: buffer }
  64779. parsing = 'value'
  64780. buffer = ''
  64781. } else {
  64782. buffer += char
  64783. }
  64784. break
  64785. case '\'': case '"':
  64786. if (parsing === 'value') {
  64787. if (!buffer.trim().length) {
  64788. // value is wrapped in qotes
  64789. original[param].escape = [char, char]
  64790. quotes = char
  64791. buffer = ''
  64792. } else if (quotes) {
  64793. if (char === quotes) {
  64794. // found same char as used for wrapping quotes
  64795. if (char === string.charAt(cursor + 1)) {
  64796. // escaped quote
  64797. buffer += char
  64798. cursor++
  64799. } else {
  64800. // end of value
  64801. parsed[param] = buffer
  64802. param = null
  64803. parsing = null
  64804. buffer = ''
  64805. quotes = null
  64806. }
  64807. } else {
  64808. buffer += char
  64809. }
  64810. } else {
  64811. buffer += char
  64812. }
  64813. } else {
  64814. throw new Error('Invalid connection string.')
  64815. }
  64816. break
  64817. case '{':
  64818. if (parsing === 'value') {
  64819. if (buffer.trim().length === 0) {
  64820. // value is wrapped in qotes
  64821. original[param].escape = ['{', '}']
  64822. quotes = '{}'
  64823. buffer = ''
  64824. } else {
  64825. buffer += char
  64826. }
  64827. } else {
  64828. throw new Error('Invalid connection string.')
  64829. }
  64830. break
  64831. case '}':
  64832. if (parsing === 'value') {
  64833. if (quotes === '{}') {
  64834. // end of value
  64835. parsed[param] = buffer
  64836. param = null
  64837. parsing = null
  64838. buffer = ''
  64839. quotes = null
  64840. } else {
  64841. buffer += char
  64842. }
  64843. } else {
  64844. throw new Error('Invalid connection string.')
  64845. }
  64846. break
  64847. case ';':
  64848. if (parsing === 'value') {
  64849. if (quotes) {
  64850. buffer += char
  64851. } else {
  64852. // end of value
  64853. parsed[param] = buffer
  64854. param = null
  64855. parsing = 'name'
  64856. buffer = ''
  64857. }
  64858. } else {
  64859. buffer = ''
  64860. parsing = 'name'
  64861. }
  64862. break
  64863. default:
  64864. buffer += char
  64865. }
  64866. cursor++
  64867. }
  64868. if (parsing === 'value') {
  64869. // end of value
  64870. parsed[param] = buffer
  64871. }
  64872. return parsed
  64873. }
  64874. const resolveConnectionString = function (string, driver) {
  64875. const parsed = /^(mssql|tedious|msnodesql|tds):\/\//i.test(string) ? parseConnectionURI(string) : parseConnectionString(string)
  64876. const stream = (parsed.stream || '').toLowerCase()
  64877. const encrypt = (parsed.encrypt || '').toLowerCase()
  64878. if (driver === 'msnodesqlv8') {
  64879. parsed.driver = 'SQL Server Native Client 11.0'
  64880. if (parsed.__original__) {
  64881. parsed.__original__.driver = { name: 'Driver', escape: ['{', '}'] }
  64882. }
  64883. return { connectionString: parsed.toString() }
  64884. }
  64885. let user = parsed.uid || parsed.uid || parsed['user id']
  64886. let server = parsed.server || parsed.address || parsed.addr || parsed['data source'] || parsed['network address']
  64887. const config = {
  64888. password: oror(parsed.pwd, parsed.password),
  64889. database: oror(parsed.database, parsed['initial catalog']),
  64890. connectionTimeout: oror(parsed.connectionTimeout, parsed.timeout, parsed['connect timeout'], parsed['connection timeout']),
  64891. requestTimeout: oror(parsed.requestTimeout, parsed['request timeout']),
  64892. stream: stream === 'true' || stream === 'yes' || stream === '1',
  64893. options: {
  64894. readOnlyIntent: parsed.applicationintent && parsed.applicationintent.toLowerCase() === 'readonly',
  64895. encrypt: encrypt === 'true' || encrypt === 'yes' || encrypt === '1'
  64896. }
  64897. }
  64898. if (parsed.useUTC != null) {
  64899. const utc = parsed.useUTC.toLowerCase()
  64900. config.options.useUTC = utc === 'true' || utc === 'yes' || utc === '1'
  64901. }
  64902. if (config.connectionTimeout != null) {
  64903. config.connectionTimeout = parseInt(config.connectionTimeout, 10) * 1000
  64904. }
  64905. if (config.requestTimeout != null) {
  64906. config.requestTimeout = parseInt(config.requestTimeout, 10)
  64907. }
  64908. if (parsed.multisubnetfailover != null) {
  64909. config.options.multiSubnetFailover = parsed.multisubnetfailover.toLowerCase() === 'true'
  64910. }
  64911. if (/^(.*)\\(.*)$/.exec(user)) {
  64912. config.domain = RegExp.$1
  64913. user = RegExp.$2
  64914. }
  64915. if (server) {
  64916. server = server.trim()
  64917. if (/^np:/i.test(server)) {
  64918. throw new Error('Connection via Named Pipes is not supported.')
  64919. }
  64920. if (/^tcp:/i.test(server)) {
  64921. server = server.substr(4)
  64922. }
  64923. if (/^(.*)\\(.*)$/.exec(server)) {
  64924. server = RegExp.$1
  64925. config.options.instanceName = RegExp.$2
  64926. }
  64927. if (/^(.*),(.*)$/.exec(server)) {
  64928. server = RegExp.$1.trim()
  64929. config.port = parseInt(RegExp.$2.trim(), 10)
  64930. }
  64931. if (server === '.' || server === '(.)' || server.toLowerCase() === '(localdb)' || server.toLowerCase() === '(local)') {
  64932. server = 'localhost'
  64933. }
  64934. }
  64935. config.user = user
  64936. config.server = server
  64937. return config
  64938. }
  64939. module.exports = {
  64940. parse: parseConnectionString,
  64941. resolve: resolveConnectionString
  64942. }
  64943. },{"url":653}],354:[function(require,module,exports){
  64944. (function (Buffer){(function (){
  64945. 'use strict'
  64946. const objectHasProperty = require('./utils').objectHasProperty
  64947. const inspect = Symbol.for('nodejs.util.inspect.custom')
  64948. const TYPES = {
  64949. VarChar (length) {
  64950. return { type: TYPES.VarChar, length }
  64951. },
  64952. NVarChar (length) {
  64953. return { type: TYPES.NVarChar, length }
  64954. },
  64955. Text () {
  64956. return { type: TYPES.Text }
  64957. },
  64958. Int () {
  64959. return { type: TYPES.Int }
  64960. },
  64961. BigInt () {
  64962. return { type: TYPES.BigInt }
  64963. },
  64964. TinyInt () {
  64965. return { type: TYPES.TinyInt }
  64966. },
  64967. SmallInt () {
  64968. return { type: TYPES.SmallInt }
  64969. },
  64970. Bit () {
  64971. return { type: TYPES.Bit }
  64972. },
  64973. Float () {
  64974. return { type: TYPES.Float }
  64975. },
  64976. Numeric (precision, scale) {
  64977. return { type: TYPES.Numeric, precision, scale }
  64978. },
  64979. Decimal (precision, scale) {
  64980. return { type: TYPES.Decimal, precision, scale }
  64981. },
  64982. Real () {
  64983. return { type: TYPES.Real }
  64984. },
  64985. Date () {
  64986. return { type: TYPES.Date }
  64987. },
  64988. DateTime () {
  64989. return { type: TYPES.DateTime }
  64990. },
  64991. DateTime2 (scale) {
  64992. return { type: TYPES.DateTime2, scale }
  64993. },
  64994. DateTimeOffset (scale) {
  64995. return { type: TYPES.DateTimeOffset, scale }
  64996. },
  64997. SmallDateTime () {
  64998. return { type: TYPES.SmallDateTime }
  64999. },
  65000. Time (scale) {
  65001. return { type: TYPES.Time, scale }
  65002. },
  65003. UniqueIdentifier () {
  65004. return { type: TYPES.UniqueIdentifier }
  65005. },
  65006. SmallMoney () {
  65007. return { type: TYPES.SmallMoney }
  65008. },
  65009. Money () {
  65010. return { type: TYPES.Money }
  65011. },
  65012. Binary (length) {
  65013. return { type: TYPES.Binary, length }
  65014. },
  65015. VarBinary (length) {
  65016. return { type: TYPES.VarBinary, length }
  65017. },
  65018. Image () {
  65019. return { type: TYPES.Image }
  65020. },
  65021. Xml () {
  65022. return { type: TYPES.Xml }
  65023. },
  65024. Char (length) {
  65025. return { type: TYPES.Char, length }
  65026. },
  65027. NChar (length) {
  65028. return { type: TYPES.NChar, length }
  65029. },
  65030. NText () {
  65031. return { type: TYPES.NText }
  65032. },
  65033. TVP (tvpType) {
  65034. return { type: TYPES.TVP, tvpType }
  65035. },
  65036. UDT () {
  65037. return { type: TYPES.UDT }
  65038. },
  65039. Geography () {
  65040. return { type: TYPES.Geography }
  65041. },
  65042. Geometry () {
  65043. return { type: TYPES.Geometry }
  65044. },
  65045. Variant () {
  65046. return { type: TYPES.Variant }
  65047. }
  65048. }
  65049. module.exports.TYPES = TYPES
  65050. module.exports.DECLARATIONS = {}
  65051. const zero = function (value, length) {
  65052. if (length == null) length = 2
  65053. value = String(value)
  65054. if (value.length < length) {
  65055. for (let i = 1; i <= length - value.length; i++) {
  65056. value = `0${value}`
  65057. }
  65058. }
  65059. return value
  65060. }
  65061. for (const key in TYPES) {
  65062. if (objectHasProperty(TYPES, key)) {
  65063. const value = TYPES[key]
  65064. value.declaration = key.toLowerCase()
  65065. module.exports.DECLARATIONS[value.declaration] = value;
  65066. ((key, value) => {
  65067. value[inspect] = () => `[sql.${key}]`
  65068. })(key, value)
  65069. }
  65070. }
  65071. module.exports.declare = (type, options) => {
  65072. switch (type) {
  65073. case TYPES.VarChar: case TYPES.VarBinary:
  65074. return `${type.declaration} (${options.length > 8000 ? 'MAX' : (options.length == null ? 'MAX' : options.length)})`
  65075. case TYPES.NVarChar:
  65076. return `${type.declaration} (${options.length > 4000 ? 'MAX' : (options.length == null ? 'MAX' : options.length)})`
  65077. case TYPES.Char: case TYPES.NChar: case TYPES.Binary:
  65078. return `${type.declaration} (${options.length == null ? 1 : options.length})`
  65079. case TYPES.Decimal: case TYPES.Numeric:
  65080. return `${type.declaration} (${options.precision == null ? 18 : options.precision}, ${options.scale == null ? 0 : options.scale})`
  65081. case TYPES.Time: case TYPES.DateTime2: case TYPES.DateTimeOffset:
  65082. return `${type.declaration} (${options.scale == null ? 7 : options.scale})`
  65083. case TYPES.TVP:
  65084. return `${options.tvpType} readonly`
  65085. default:
  65086. return type.declaration
  65087. }
  65088. }
  65089. module.exports.cast = (value, type, options) => {
  65090. if (value == null) {
  65091. return null
  65092. }
  65093. switch (typeof value) {
  65094. case 'string':
  65095. return `N'${value.replace(/'/g, '\'\'')}'`
  65096. case 'number':
  65097. return value
  65098. case 'boolean':
  65099. return value ? 1 : 0
  65100. case 'object':
  65101. if (value instanceof Date) {
  65102. let ns = value.getUTCMilliseconds() / 1000
  65103. if (value.nanosecondDelta != null) {
  65104. ns += value.nanosecondDelta
  65105. }
  65106. const scale = options.scale == null ? 7 : options.scale
  65107. if (scale > 0) {
  65108. ns = String(ns).substr(1, scale + 1)
  65109. } else {
  65110. ns = ''
  65111. }
  65112. return `N'${value.getUTCFullYear()}-${zero(value.getUTCMonth() + 1)}-${zero(value.getUTCDate())} ${zero(value.getUTCHours())}:${zero(value.getUTCMinutes())}:${zero(value.getUTCSeconds())}${ns}'`
  65113. } else if (Buffer.isBuffer(value)) {
  65114. return `0x${value.toString('hex')}`
  65115. }
  65116. return null
  65117. default:
  65118. return null
  65119. }
  65120. }
  65121. }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  65122. },{"../../is-buffer/index.js":322,"./utils":370}],355:[function(require,module,exports){
  65123. 'use strict'
  65124. const MSSQLError = require('./mssql-error')
  65125. /**
  65126. * Class ConnectionError.
  65127. */
  65128. class ConnectionError extends MSSQLError {
  65129. /**
  65130. * Creates a new ConnectionError.
  65131. *
  65132. * @param {String} message Error message.
  65133. * @param {String} [code] Error code.
  65134. */
  65135. constructor (message, code) {
  65136. super(message, code)
  65137. this.name = 'ConnectionError'
  65138. }
  65139. }
  65140. module.exports = ConnectionError
  65141. },{"./mssql-error":357}],356:[function(require,module,exports){
  65142. 'use strict'
  65143. const ConnectionError = require('./connection-error')
  65144. const MSSQLError = require('./mssql-error')
  65145. const PreparedStatementError = require('./prepared-statement-error')
  65146. const RequestError = require('./request-error')
  65147. const TransactionError = require('./transaction-error')
  65148. module.exports = {
  65149. ConnectionError,
  65150. MSSQLError,
  65151. PreparedStatementError,
  65152. RequestError,
  65153. TransactionError
  65154. }
  65155. },{"./connection-error":355,"./mssql-error":357,"./prepared-statement-error":358,"./request-error":359,"./transaction-error":360}],357:[function(require,module,exports){
  65156. 'use strict'
  65157. class MSSQLError extends Error {
  65158. /**
  65159. * Creates a new ConnectionError.
  65160. *
  65161. * @param {String} message Error message.
  65162. * @param {String} [code] Error code.
  65163. */
  65164. constructor (message, code) {
  65165. if (message instanceof Error) {
  65166. super(message.message)
  65167. this.code = message.code || code
  65168. Error.captureStackTrace(this, this.constructor)
  65169. Object.defineProperty(this, 'originalError', { enumerable: true, value: message })
  65170. } else {
  65171. super(message)
  65172. this.code = code
  65173. }
  65174. this.name = 'MSSQLError'
  65175. }
  65176. }
  65177. module.exports = MSSQLError
  65178. },{}],358:[function(require,module,exports){
  65179. 'use strict'
  65180. const MSSQLError = require('./mssql-error')
  65181. /**
  65182. * Class PreparedStatementError.
  65183. */
  65184. class PreparedStatementError extends MSSQLError {
  65185. /**
  65186. * Creates a new PreparedStatementError.
  65187. *
  65188. * @param {String} message Error message.
  65189. * @param {String} [code] Error code.
  65190. */
  65191. constructor (message, code) {
  65192. super(message, code)
  65193. this.name = 'PreparedStatementError'
  65194. }
  65195. }
  65196. module.exports = PreparedStatementError
  65197. },{"./mssql-error":357}],359:[function(require,module,exports){
  65198. 'use strict'
  65199. const MSSQLError = require('./mssql-error')
  65200. /**
  65201. * Class RequestError.
  65202. *
  65203. * @property {String} number Error number.
  65204. * @property {Number} lineNumber Line number.
  65205. * @property {String} state Error state.
  65206. * @property {String} class Error class.
  65207. * @property {String} serverName Server name.
  65208. * @property {String} procName Procedure name.
  65209. */
  65210. class RequestError extends MSSQLError {
  65211. /**
  65212. * Creates a new RequestError.
  65213. *
  65214. * @param {String} message Error message.
  65215. * @param {String} [code] Error code.
  65216. */
  65217. constructor (message, code) {
  65218. super(message, code)
  65219. if (message instanceof Error) {
  65220. if (message.info) {
  65221. this.number = message.info.number || message.code // err.code is returned by msnodesql driver
  65222. this.lineNumber = message.info.lineNumber
  65223. this.state = message.info.state || message.sqlstate // err.sqlstate is returned by msnodesql driver
  65224. this.class = message.info.class
  65225. this.serverName = message.info.serverName
  65226. this.procName = message.info.procName
  65227. } else {
  65228. this.number = message.code // err.code is returned by msnodesql driver
  65229. this.state = message.sqlstate // err.sqlstate is returned by msnodesql driver
  65230. }
  65231. }
  65232. this.name = 'RequestError'
  65233. if ((/^\[Microsoft\]\[SQL Server Native Client 11\.0\](?:\[SQL Server\])?([\s\S]*)$/).exec(this.message)) {
  65234. this.message = RegExp.$1
  65235. }
  65236. }
  65237. }
  65238. module.exports = RequestError
  65239. },{"./mssql-error":357}],360:[function(require,module,exports){
  65240. 'use strict'
  65241. const MSSQLError = require('./mssql-error')
  65242. /**
  65243. * Class TransactionError.
  65244. */
  65245. class TransactionError extends MSSQLError {
  65246. /**
  65247. * Creates a new TransactionError.
  65248. *
  65249. * @param {String} message Error message.
  65250. * @param {String} [code] Error code.
  65251. */
  65252. constructor (message, code) {
  65253. super(message, code)
  65254. this.name = 'TransactionError'
  65255. }
  65256. }
  65257. module.exports = TransactionError
  65258. },{"./mssql-error":357}],361:[function(require,module,exports){
  65259. (function (setImmediate){(function (){
  65260. 'use strict'
  65261. const shared = require('./shared')
  65262. let globalConnection = null
  65263. const globalConnectionHandlers = {}
  65264. /**
  65265. * Open global connection pool.
  65266. *
  65267. * @param {Object|String} config Connection configuration object or connection string.
  65268. * @param {basicCallback} [callback] A callback which is called after connection has established, or an error has occurred. If omited, method returns Promise.
  65269. * @return {Promise.<ConnectionPool>}
  65270. */
  65271. function connect (config, callback) {
  65272. if (!globalConnection) {
  65273. globalConnection = new shared.driver.ConnectionPool(config)
  65274. for (const event in globalConnectionHandlers) {
  65275. for (let i = 0, l = globalConnectionHandlers[event].length; i < l; i++) {
  65276. globalConnection.on(event, globalConnectionHandlers[event][i])
  65277. }
  65278. }
  65279. const ogClose = globalConnection.close
  65280. const globalClose = function (callback) {
  65281. // remove event handlers from the global connection
  65282. for (const event in globalConnectionHandlers) {
  65283. for (let i = 0, l = globalConnectionHandlers[event].length; i < l; i++) {
  65284. this.removeListener(event, globalConnectionHandlers[event][i])
  65285. }
  65286. }
  65287. // attach error handler to prevent process crash in case of error
  65288. this.on('error', err => {
  65289. if (globalConnectionHandlers.error) {
  65290. for (let i = 0, l = globalConnectionHandlers.error.length; i < l; i++) {
  65291. globalConnectionHandlers.error[i].call(this, err)
  65292. }
  65293. }
  65294. })
  65295. globalConnection = null
  65296. return ogClose.call(this, callback)
  65297. }
  65298. globalConnection.close = globalClose.bind(globalConnection)
  65299. }
  65300. if (typeof callback === 'function') {
  65301. return globalConnection.connect((err, connection) => {
  65302. if (err) {
  65303. globalConnection = null
  65304. }
  65305. callback(err, connection)
  65306. })
  65307. }
  65308. return globalConnection.connect().catch((err) => {
  65309. globalConnection = null
  65310. return shared.Promise.reject(err)
  65311. })
  65312. }
  65313. /**
  65314. * Close all active connections in the global pool.
  65315. *
  65316. * @param {basicCallback} [callback] A callback which is called after connection has closed, or an error has occurred. If omited, method returns Promise.
  65317. * @return {ConnectionPool|Promise}
  65318. */
  65319. function close (callback) {
  65320. if (globalConnection) {
  65321. const gc = globalConnection
  65322. globalConnection = null
  65323. return gc.close(callback)
  65324. }
  65325. if (typeof callback === 'function') {
  65326. setImmediate(callback)
  65327. return null
  65328. }
  65329. return new shared.Promise((resolve) => {
  65330. resolve(globalConnection)
  65331. })
  65332. }
  65333. /**
  65334. * Attach event handler to global connection pool.
  65335. *
  65336. * @param {String} event Event name.
  65337. * @param {Function} handler Event handler.
  65338. * @return {ConnectionPool}
  65339. */
  65340. function on (event, handler) {
  65341. if (!globalConnectionHandlers[event]) globalConnectionHandlers[event] = []
  65342. globalConnectionHandlers[event].push(handler)
  65343. if (globalConnection) globalConnection.on(event, handler)
  65344. return globalConnection
  65345. }
  65346. /**
  65347. * Detach event handler from global connection.
  65348. *
  65349. * @param {String} event Event name.
  65350. * @param {Function} handler Event handler.
  65351. * @return {ConnectionPool}
  65352. */
  65353. function removeListener (event, handler) {
  65354. if (!globalConnectionHandlers[event]) return globalConnection
  65355. const index = globalConnectionHandlers[event].indexOf(handler)
  65356. if (index === -1) return globalConnection
  65357. globalConnectionHandlers[event].splice(index, 1)
  65358. if (globalConnectionHandlers[event].length === 0) globalConnectionHandlers[event] = undefined
  65359. if (globalConnection) globalConnection.removeListener(event, handler)
  65360. return globalConnection
  65361. }
  65362. /**
  65363. * Creates a new query using global connection from a tagged template string.
  65364. *
  65365. * @variation 1
  65366. * @param {Array|String} strings Array of string literals or sql command.
  65367. * @param {...*} keys Values.
  65368. * @return {Request}
  65369. */
  65370. /**
  65371. * Execute the SQL command.
  65372. *
  65373. * @variation 2
  65374. * @param {String} command T-SQL command to be executed.
  65375. * @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  65376. * @return {Request|Promise}
  65377. */
  65378. function query () {
  65379. if (typeof arguments[0] === 'string') { return new shared.driver.Request().query(arguments[0], arguments[1]) }
  65380. const values = Array.prototype.slice.call(arguments)
  65381. const strings = values.shift()
  65382. return new shared.driver.Request()._template(strings, values, 'query')
  65383. }
  65384. /**
  65385. * Creates a new batch using global connection from a tagged template string.
  65386. *
  65387. * @variation 1
  65388. * @param {Array} strings Array of string literals.
  65389. * @param {...*} keys Values.
  65390. * @return {Request}
  65391. */
  65392. /**
  65393. * Execute the SQL command.
  65394. *
  65395. * @variation 2
  65396. * @param {String} command T-SQL command to be executed.
  65397. * @param {Request~requestCallback} [callback] A callback which is called after execution has completed, or an error has occurred. If omited, method returns Promise.
  65398. * @return {Request|Promise}
  65399. */
  65400. function batch () {
  65401. if (typeof arguments[0] === 'string') { return new shared.driver.Request().batch(arguments[0], arguments[1]) }
  65402. const values = Array.prototype.slice.call(arguments)
  65403. const strings = values.shift()
  65404. return new shared.driver.Request()._template(strings, values, 'batch')
  65405. }
  65406. module.exports = {
  65407. batch,
  65408. close,
  65409. connect,
  65410. off: removeListener,
  65411. on,
  65412. query,
  65413. removeListener
  65414. }
  65415. Object.defineProperty(module.exports, 'pool', {
  65416. get: () => {
  65417. return globalConnection
  65418. },
  65419. set: () => {}
  65420. })
  65421. }).call(this)}).call(this,require("timers").setImmediate)
  65422. },{"./shared":363,"timers":639}],362:[function(require,module,exports){
  65423. 'use strict'
  65424. module.exports = {
  65425. READ_UNCOMMITTED: 0x01,
  65426. READ_COMMITTED: 0x02,
  65427. REPEATABLE_READ: 0x03,
  65428. SERIALIZABLE: 0x04,
  65429. SNAPSHOT: 0x05
  65430. }
  65431. },{}],363:[function(require,module,exports){
  65432. (function (Buffer){(function (){
  65433. 'use strict'
  65434. const TYPES = require('./datatypes').TYPES
  65435. const Table = require('./table')
  65436. let PromiseLibrary = Promise
  65437. const driver = {}
  65438. const map = []
  65439. /**
  65440. * Register you own type map.
  65441. *
  65442. * @path module.exports.map
  65443. * @param {*} jstype JS data type.
  65444. * @param {*} sqltype SQL data type.
  65445. */
  65446. map.register = function (jstype, sqltype) {
  65447. for (let index = 0; index < this.length; index++) {
  65448. const item = this[index]
  65449. if (item.js === jstype) {
  65450. this.splice(index, 1)
  65451. break
  65452. }
  65453. }
  65454. this.push({
  65455. js: jstype,
  65456. sql: sqltype
  65457. })
  65458. return null
  65459. }
  65460. map.register(String, TYPES.NVarChar)
  65461. map.register(Number, TYPES.Int)
  65462. map.register(Boolean, TYPES.Bit)
  65463. map.register(Date, TYPES.DateTime)
  65464. map.register(Buffer, TYPES.VarBinary)
  65465. map.register(Table, TYPES.TVP)
  65466. /**
  65467. * @ignore
  65468. */
  65469. const getTypeByValue = function (value) {
  65470. if ((value === null) || (value === undefined)) { return TYPES.NVarChar }
  65471. switch (typeof value) {
  65472. case 'string':
  65473. for (var item of Array.from(map)) {
  65474. if (item.js === String) {
  65475. return item.sql
  65476. }
  65477. }
  65478. return TYPES.NVarChar
  65479. case 'number':
  65480. if (value % 1 === 0) {
  65481. return TYPES.Int
  65482. } else {
  65483. return TYPES.Float
  65484. }
  65485. case 'boolean':
  65486. for (item of Array.from(map)) {
  65487. if (item.js === Boolean) {
  65488. return item.sql
  65489. }
  65490. }
  65491. return TYPES.Bit
  65492. case 'object':
  65493. for (item of Array.from(map)) {
  65494. if (value instanceof item.js) {
  65495. return item.sql
  65496. }
  65497. }
  65498. return TYPES.NVarChar
  65499. default:
  65500. return TYPES.NVarChar
  65501. }
  65502. }
  65503. module.exports = {
  65504. driver,
  65505. getTypeByValue,
  65506. map
  65507. }
  65508. Object.defineProperty(module.exports, 'Promise', {
  65509. get: () => {
  65510. return PromiseLibrary
  65511. },
  65512. set: (value) => {
  65513. PromiseLibrary = value
  65514. }
  65515. })
  65516. }).call(this)}).call(this,require("buffer").Buffer)
  65517. },{"./datatypes":354,"./table":364,"buffer":193}],364:[function(require,module,exports){
  65518. 'use strict'
  65519. const TYPES = require('./datatypes').TYPES
  65520. const declareType = require('./datatypes').declare
  65521. const objectHasProperty = require('./utils').objectHasProperty
  65522. const MAX = 65535 // (1 << 16) - 1
  65523. const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
  65524. function Table (name) {
  65525. if (name) {
  65526. const parsed = Table.parseName(name)
  65527. this.name = parsed.name
  65528. this.schema = parsed.schema
  65529. this.database = parsed.database
  65530. this.path = (this.database ? `[${this.database}].` : '') + (this.schema ? `[${this.schema}].` : '') + `[${this.name}]`
  65531. this.temporary = this.name.charAt(0) === '#'
  65532. }
  65533. this.columns = []
  65534. this.rows = []
  65535. Object.defineProperty(this.columns, 'add', {
  65536. value (name, column, options) {
  65537. if (column == null) {
  65538. throw new Error('Column data type is not defined.')
  65539. }
  65540. if (column instanceof Function) {
  65541. column = column()
  65542. }
  65543. options = options || {}
  65544. column.name = name;
  65545. ['nullable', 'primary', 'identity', 'readOnly', 'length'].forEach(prop => {
  65546. if (objectHasProperty(options, prop)) {
  65547. column[prop] = options[prop]
  65548. }
  65549. })
  65550. return this.push(column)
  65551. }
  65552. })
  65553. Object.defineProperty(this.rows, 'add', {
  65554. value () {
  65555. return this.push(Array.prototype.slice.call(arguments))
  65556. }
  65557. }
  65558. )
  65559. }
  65560. /*
  65561. @private
  65562. */
  65563. Table.prototype._makeBulk = function _makeBulk () {
  65564. for (let i = 0; i < this.columns.length; i++) {
  65565. const col = this.columns[i]
  65566. switch (col.type) {
  65567. case TYPES.Date:
  65568. case TYPES.DateTime:
  65569. case TYPES.DateTime2:
  65570. for (let j = 0; j < this.rows.length; j++) {
  65571. const dateValue = this.rows[j][i]
  65572. if (typeof dateValue === 'string' || typeof dateValue === 'number') {
  65573. const date = new Date(dateValue)
  65574. if (isNaN(date.getDate())) {
  65575. throw new TypeError('Invalid date value passed to bulk rows')
  65576. }
  65577. this.rows[j][i] = date
  65578. }
  65579. }
  65580. break
  65581. case TYPES.Xml:
  65582. col.type = TYPES.NVarChar(MAX).type
  65583. break
  65584. case TYPES.UDT:
  65585. case TYPES.Geography:
  65586. case TYPES.Geometry:
  65587. col.type = TYPES.VarBinary(MAX).type
  65588. break
  65589. default:
  65590. break
  65591. }
  65592. }
  65593. return this
  65594. }
  65595. Table.prototype.declare = function declare () {
  65596. const pkey = this.columns.filter(col => col.primary === true).map(col => col.name)
  65597. const cols = this.columns.map(col => {
  65598. const def = [`[${col.name}] ${declareType(col.type, col)}`]
  65599. if (col.nullable === true) {
  65600. def.push('null')
  65601. } else if (col.nullable === false) {
  65602. def.push('not null')
  65603. }
  65604. if (col.primary === true && pkey.length === 1) {
  65605. def.push('primary key')
  65606. }
  65607. return def.join(' ')
  65608. })
  65609. const constraint = pkey.length > 1 ? `, constraint PK_${this.temporary ? this.name.substr(1) : this.name} primary key (${pkey.join(', ')})` : ''
  65610. return `create table ${this.path} (${cols.join(', ')}${constraint})`
  65611. }
  65612. Table.fromRecordset = function fromRecordset (recordset, name) {
  65613. const t = new this(name)
  65614. for (const colName in recordset.columns) {
  65615. if (objectHasProperty(recordset.columns, colName)) {
  65616. const col = recordset.columns[colName]
  65617. t.columns.add(colName, {
  65618. type: col.type,
  65619. length: col.length,
  65620. scale: col.scale,
  65621. precision: col.precision
  65622. }, {
  65623. nullable: col.nullable,
  65624. identity: col.identity,
  65625. readOnly: col.readOnly
  65626. })
  65627. }
  65628. }
  65629. if (t.columns.length === 1 && t.columns[0].name === JSON_COLUMN_ID) {
  65630. for (let i = 0; i < recordset.length; i++) {
  65631. t.rows.add(JSON.stringify(recordset[i]))
  65632. }
  65633. } else {
  65634. for (let i = 0; i < recordset.length; i++) {
  65635. t.rows.add.apply(t.rows, t.columns.map(col => recordset[i][col.name]))
  65636. }
  65637. }
  65638. return t
  65639. }
  65640. Table.parseName = function parseName (name) {
  65641. const length = name.length
  65642. let cursor = -1
  65643. let buffer = ''
  65644. let escaped = false
  65645. const path = []
  65646. while (++cursor < length) {
  65647. const char = name.charAt(cursor)
  65648. if (char === '[') {
  65649. if (escaped) {
  65650. buffer += char
  65651. } else {
  65652. escaped = true
  65653. }
  65654. } else if (char === ']') {
  65655. if (escaped) {
  65656. escaped = false
  65657. } else {
  65658. throw new Error('Invalid table name.')
  65659. }
  65660. } else if (char === '.') {
  65661. if (escaped) {
  65662. buffer += char
  65663. } else {
  65664. path.push(buffer)
  65665. buffer = ''
  65666. }
  65667. } else {
  65668. buffer += char
  65669. }
  65670. }
  65671. if (buffer) {
  65672. path.push(buffer)
  65673. }
  65674. switch (path.length) {
  65675. case 1:
  65676. return {
  65677. name: path[0],
  65678. schema: null,
  65679. database: null
  65680. }
  65681. case 2:
  65682. return {
  65683. name: path[1],
  65684. schema: path[0],
  65685. database: null
  65686. }
  65687. case 3:
  65688. return {
  65689. name: path[2],
  65690. schema: path[1],
  65691. database: path[0]
  65692. }
  65693. default:
  65694. throw new Error('Invalid table name.')
  65695. }
  65696. }
  65697. module.exports = Table
  65698. },{"./datatypes":354,"./utils":370}],365:[function(require,module,exports){
  65699. 'use strict'
  65700. const tds = require('tedious')
  65701. const debug = require('debug')('mssql:tedi')
  65702. const BaseConnectionPool = require('../base/connection-pool')
  65703. const { IDS } = require('../utils')
  65704. const shared = require('../shared')
  65705. const ConnectionError = require('../error/connection-error')
  65706. class ConnectionPool extends BaseConnectionPool {
  65707. _poolCreate () {
  65708. return new shared.Promise((resolve, reject) => {
  65709. const resolveOnce = (v) => {
  65710. resolve(v)
  65711. resolve = reject = () => {}
  65712. }
  65713. const rejectOnce = (e) => {
  65714. reject(e)
  65715. resolve = reject = () => {}
  65716. }
  65717. const cfg = {
  65718. server: this.config.server,
  65719. options: Object.assign({
  65720. encrypt: typeof this.config.encrypt === 'boolean' ? this.config.encrypt : true
  65721. }, this.config.options),
  65722. authentication: Object.assign({
  65723. type: this.config.domain !== undefined ? 'ntlm' : 'default',
  65724. options: {
  65725. userName: this.config.user,
  65726. password: this.config.password,
  65727. domain: this.config.domain
  65728. }
  65729. }, this.config.authentication)
  65730. }
  65731. cfg.options.database = this.config.database
  65732. cfg.options.port = this.config.port
  65733. cfg.options.connectTimeout = this.config.connectionTimeout || this.config.timeout || 15000
  65734. cfg.options.requestTimeout = this.config.requestTimeout != null ? this.config.requestTimeout : 15000
  65735. cfg.options.tdsVersion = cfg.options.tdsVersion || '7_4'
  65736. cfg.options.rowCollectionOnDone = false
  65737. cfg.options.rowCollectionOnRequestCompletion = false
  65738. cfg.options.useColumnNames = false
  65739. cfg.options.appName = cfg.options.appName || 'node-mssql'
  65740. // tedious always connect via tcp when port is specified
  65741. if (cfg.options.instanceName) delete cfg.options.port
  65742. if (isNaN(cfg.options.requestTimeout)) cfg.options.requestTimeout = 15000
  65743. if (cfg.options.requestTimeout === Infinity) cfg.options.requestTimeout = 0
  65744. if (cfg.options.requestTimeout < 0) cfg.options.requestTimeout = 0
  65745. if (this.config.debug) {
  65746. cfg.options.debug = {
  65747. packet: true,
  65748. token: true,
  65749. data: true,
  65750. payload: true
  65751. }
  65752. }
  65753. const tedious = new tds.Connection(cfg)
  65754. IDS.add(tedious, 'Connection')
  65755. debug('pool(%d): connection #%d created', IDS.get(this), IDS.get(tedious))
  65756. debug('connection(%d): establishing', IDS.get(tedious))
  65757. tedious.once('connect', err => {
  65758. if (err) {
  65759. err = new ConnectionError(err)
  65760. return rejectOnce(err)
  65761. }
  65762. debug('connection(%d): established', IDS.get(tedious))
  65763. resolveOnce(tedious)
  65764. })
  65765. tedious.on('end', () => {
  65766. const err = new ConnectionError('The connection ended without ever completing the connection')
  65767. rejectOnce(err)
  65768. })
  65769. tedious.on('error', err => {
  65770. if (err.code === 'ESOCKET') {
  65771. tedious.hasError = true
  65772. } else {
  65773. this.emit('error', err)
  65774. }
  65775. rejectOnce(err)
  65776. })
  65777. if (this.config.debug) {
  65778. tedious.on('debug', this.emit.bind(this, 'debug', tedious))
  65779. }
  65780. if (typeof this.config.beforeConnect === 'function') {
  65781. this.config.beforeConnect(tedious)
  65782. }
  65783. })
  65784. }
  65785. _poolValidate (tedious) {
  65786. return tedious && !tedious.closed && !tedious.hasError
  65787. }
  65788. _poolDestroy (tedious) {
  65789. return new shared.Promise((resolve, reject) => {
  65790. if (!tedious) {
  65791. resolve()
  65792. return
  65793. }
  65794. debug('connection(%d): destroying', IDS.get(tedious))
  65795. if (tedious.closed) {
  65796. debug('connection(%d): already closed', IDS.get(tedious))
  65797. resolve()
  65798. } else {
  65799. tedious.once('end', () => {
  65800. debug('connection(%d): destroyed', IDS.get(tedious))
  65801. resolve()
  65802. })
  65803. tedious.close()
  65804. }
  65805. })
  65806. }
  65807. }
  65808. module.exports = ConnectionPool
  65809. },{"../base/connection-pool":348,"../error/connection-error":355,"../shared":363,"../utils":370,"debug":372,"tedious":476}],366:[function(require,module,exports){
  65810. 'use struct'
  65811. const base = require('../base')
  65812. const ConnectionPool = require('./connection-pool')
  65813. const Transaction = require('./transaction')
  65814. const Request = require('./request')
  65815. module.exports = Object.assign({
  65816. ConnectionPool,
  65817. Transaction,
  65818. Request,
  65819. PreparedStatement: base.PreparedStatement
  65820. }, base.exports)
  65821. Object.defineProperty(module.exports, 'Promise', {
  65822. enumerable: true,
  65823. get: () => {
  65824. return base.Promise
  65825. },
  65826. set: (value) => {
  65827. base.Promise = value
  65828. }
  65829. })
  65830. base.driver.name = 'tedious'
  65831. base.driver.ConnectionPool = ConnectionPool
  65832. base.driver.Transaction = Transaction
  65833. base.driver.Request = Request
  65834. },{"../base":349,"./connection-pool":365,"./request":367,"./transaction":368}],367:[function(require,module,exports){
  65835. 'use strict'
  65836. const tds = require('tedious')
  65837. const debug = require('debug')('mssql:tedi')
  65838. const BaseRequest = require('../base/request')
  65839. const RequestError = require('../error/request-error')
  65840. const { IDS, objectHasProperty } = require('../utils')
  65841. const { TYPES, DECLARATIONS, declare, cast } = require('../datatypes')
  65842. const Table = require('../table')
  65843. const { PARSERS: UDT } = require('../udt')
  65844. const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
  65845. const XML_COLUMN_ID = 'XML_F52E2B61-18A1-11d1-B105-00805F49916B'
  65846. const N_TYPES = {
  65847. BitN: 0x68,
  65848. DateTimeN: 0x6F,
  65849. DecimalN: 0x6A,
  65850. FloatN: 0x6D,
  65851. IntN: 0x26,
  65852. MoneyN: 0x6E,
  65853. NumericN: 0x6C
  65854. }
  65855. const getTediousType = function (type) {
  65856. switch (type) {
  65857. case TYPES.VarChar: return tds.TYPES.VarChar
  65858. case TYPES.NVarChar: return tds.TYPES.NVarChar
  65859. case TYPES.Text: return tds.TYPES.Text
  65860. case TYPES.Int: return tds.TYPES.Int
  65861. case TYPES.BigInt: return tds.TYPES.BigInt
  65862. case TYPES.TinyInt: return tds.TYPES.TinyInt
  65863. case TYPES.SmallInt: return tds.TYPES.SmallInt
  65864. case TYPES.Bit: return tds.TYPES.Bit
  65865. case TYPES.Float: return tds.TYPES.Float
  65866. case TYPES.Decimal: return tds.TYPES.Decimal
  65867. case TYPES.Numeric: return tds.TYPES.Numeric
  65868. case TYPES.Real: return tds.TYPES.Real
  65869. case TYPES.Money: return tds.TYPES.Money
  65870. case TYPES.SmallMoney: return tds.TYPES.SmallMoney
  65871. case TYPES.Time: return tds.TYPES.Time
  65872. case TYPES.Date: return tds.TYPES.Date
  65873. case TYPES.DateTime: return tds.TYPES.DateTime
  65874. case TYPES.DateTime2: return tds.TYPES.DateTime2
  65875. case TYPES.DateTimeOffset: return tds.TYPES.DateTimeOffset
  65876. case TYPES.SmallDateTime: return tds.TYPES.SmallDateTime
  65877. case TYPES.UniqueIdentifier: return tds.TYPES.UniqueIdentifier
  65878. case TYPES.Xml: return tds.TYPES.NVarChar
  65879. case TYPES.Char: return tds.TYPES.Char
  65880. case TYPES.NChar: return tds.TYPES.NChar
  65881. case TYPES.NText: return tds.TYPES.NVarChar
  65882. case TYPES.Image: return tds.TYPES.Image
  65883. case TYPES.Binary: return tds.TYPES.Binary
  65884. case TYPES.VarBinary: return tds.TYPES.VarBinary
  65885. case TYPES.UDT: case TYPES.Geography: case TYPES.Geometry: return tds.TYPES.UDT
  65886. case TYPES.TVP: return tds.TYPES.TVP
  65887. case TYPES.Variant: return tds.TYPES.Variant
  65888. default: return type
  65889. }
  65890. }
  65891. const getMssqlType = function (type, length) {
  65892. if (typeof type !== 'object') return undefined
  65893. switch (type) {
  65894. case tds.TYPES.Char: return TYPES.Char
  65895. case tds.TYPES.NChar: return TYPES.NChar
  65896. case tds.TYPES.VarChar: return TYPES.VarChar
  65897. case tds.TYPES.NVarChar: return TYPES.NVarChar
  65898. case tds.TYPES.Text: return TYPES.Text
  65899. case tds.TYPES.NText: return TYPES.NText
  65900. case tds.TYPES.Int: return TYPES.Int
  65901. case tds.TYPES.BigInt: return TYPES.BigInt
  65902. case tds.TYPES.TinyInt: return TYPES.TinyInt
  65903. case tds.TYPES.SmallInt: return TYPES.SmallInt
  65904. case tds.TYPES.Bit: return TYPES.Bit
  65905. case tds.TYPES.Float: return TYPES.Float
  65906. case tds.TYPES.Real: return TYPES.Real
  65907. case tds.TYPES.Money: return TYPES.Money
  65908. case tds.TYPES.SmallMoney: return TYPES.SmallMoney
  65909. case tds.TYPES.Numeric: return TYPES.Numeric
  65910. case tds.TYPES.Decimal: return TYPES.Decimal
  65911. case tds.TYPES.DateTime: return TYPES.DateTime
  65912. case tds.TYPES.Time: return TYPES.Time
  65913. case tds.TYPES.Date: return TYPES.Date
  65914. case tds.TYPES.DateTime2: return TYPES.DateTime2
  65915. case tds.TYPES.DateTimeOffset: return TYPES.DateTimeOffset
  65916. case tds.TYPES.SmallDateTime: return TYPES.SmallDateTime
  65917. case tds.TYPES.UniqueIdentifier: return TYPES.UniqueIdentifier
  65918. case tds.TYPES.Image: return TYPES.Image
  65919. case tds.TYPES.Binary: return TYPES.Binary
  65920. case tds.TYPES.VarBinary: return TYPES.VarBinary
  65921. case tds.TYPES.Xml: return TYPES.Xml
  65922. case tds.TYPES.UDT: return TYPES.UDT
  65923. case tds.TYPES.TVP: return TYPES.TVP
  65924. case tds.TYPES.Variant: return TYPES.Variant
  65925. default:
  65926. switch (type.id) {
  65927. case N_TYPES.BitN: return TYPES.Bit
  65928. case N_TYPES.NumericN: return TYPES.Numeric
  65929. case N_TYPES.DecimalN: return TYPES.Decimal
  65930. case N_TYPES.IntN:
  65931. if (length === 8) return TYPES.BigInt
  65932. if (length === 4) return TYPES.Int
  65933. if (length === 2) return TYPES.SmallInt
  65934. return TYPES.TinyInt
  65935. case N_TYPES.FloatN:
  65936. if (length === 8) return TYPES.Float
  65937. return TYPES.Real
  65938. case N_TYPES.MoneyN:
  65939. if (length === 8) return TYPES.Money
  65940. return TYPES.SmallMoney
  65941. case N_TYPES.DateTimeN:
  65942. if (length === 8) return TYPES.DateTime
  65943. return TYPES.SmallDateTime
  65944. }
  65945. }
  65946. }
  65947. const createColumns = function (metadata) {
  65948. const out = {}
  65949. for (let index = 0, length = metadata.length; index < length; index++) {
  65950. const column = metadata[index]
  65951. out[column.colName] = {
  65952. index,
  65953. name: column.colName,
  65954. length: column.dataLength,
  65955. type: getMssqlType(column.type, column.dataLength),
  65956. scale: column.scale,
  65957. precision: column.precision,
  65958. nullable: !!(column.flags & 0x01),
  65959. caseSensitive: !!(column.flags & 0x02),
  65960. identity: !!(column.flags & 0x10),
  65961. readOnly: !(column.flags & 0x0C)
  65962. }
  65963. if (column.udtInfo) {
  65964. out[column.colName].udt = {
  65965. name: column.udtInfo.typeName,
  65966. database: column.udtInfo.dbname,
  65967. schema: column.udtInfo.owningSchema,
  65968. assembly: column.udtInfo.assemblyName
  65969. }
  65970. if (DECLARATIONS[column.udtInfo.typeName]) {
  65971. out[column.colName].type = DECLARATIONS[column.udtInfo.typeName]
  65972. }
  65973. }
  65974. }
  65975. return out
  65976. }
  65977. const valueCorrection = function (value, metadata) {
  65978. if ((metadata.type === tds.TYPES.UDT) && (value != null)) {
  65979. if (UDT[metadata.udtInfo.typeName]) {
  65980. return UDT[metadata.udtInfo.typeName](value)
  65981. } else {
  65982. return value
  65983. }
  65984. } else {
  65985. return value
  65986. }
  65987. }
  65988. const parameterCorrection = function (value) {
  65989. if (value instanceof Table) {
  65990. const tvp = {
  65991. name: value.name,
  65992. schema: value.schema,
  65993. columns: [],
  65994. rows: value.rows
  65995. }
  65996. for (const col of value.columns) {
  65997. tvp.columns.push({
  65998. name: col.name,
  65999. type: getTediousType(col.type),
  66000. length: col.length,
  66001. scale: col.scale,
  66002. precision: col.precision
  66003. })
  66004. }
  66005. return tvp
  66006. } else {
  66007. return value
  66008. }
  66009. }
  66010. class Request extends BaseRequest {
  66011. /*
  66012. Execute specified sql batch.
  66013. */
  66014. _batch (batch, callback) {
  66015. this._isBatch = true
  66016. this._query(batch, callback)
  66017. }
  66018. /*
  66019. Bulk load.
  66020. */
  66021. _bulk (table, options, callback) {
  66022. super._bulk(table, options, err => {
  66023. if (err) return callback(err)
  66024. table._makeBulk()
  66025. if (!table.name) {
  66026. return callback(new RequestError('Table name must be specified for bulk insert.', 'ENAME'))
  66027. }
  66028. if (table.name.charAt(0) === '@') {
  66029. return callback(new RequestError("You can't use table variables for bulk insert.", 'ENAME'))
  66030. }
  66031. const errors = []
  66032. const errorHandlers = {}
  66033. let hasReturned = false
  66034. const handleError = (doReturn, connection, info) => {
  66035. let err = new Error(info.message)
  66036. err.info = info
  66037. err = new RequestError(err, 'EREQUEST')
  66038. if (this.stream) {
  66039. this.emit('error', err)
  66040. } else {
  66041. if (doReturn && !hasReturned) {
  66042. if (connection) {
  66043. for (const event in errorHandlers) {
  66044. connection.removeListener(event, errorHandlers[event])
  66045. }
  66046. this.parent.release(connection)
  66047. }
  66048. hasReturned = true
  66049. callback(err)
  66050. }
  66051. }
  66052. // we must collect errors even in stream mode
  66053. errors.push(err)
  66054. }
  66055. const handleInfo = msg => {
  66056. this.emit('info', {
  66057. message: msg.message,
  66058. number: msg.number,
  66059. state: msg.state,
  66060. class: msg.class,
  66061. lineNumber: msg.lineNumber,
  66062. serverName: msg.serverName,
  66063. procName: msg.procName
  66064. })
  66065. }
  66066. this.parent.acquire(this, (err, connection) => {
  66067. if (err) return callback(err)
  66068. debug('connection(%d): borrowed to request #%d', IDS.get(connection), IDS.get(this))
  66069. if (this.canceled) {
  66070. debug('request(%d): canceled', IDS.get(this))
  66071. this.parent.release(connection)
  66072. return callback(new RequestError('Canceled.', 'ECANCEL'))
  66073. }
  66074. this._cancel = () => {
  66075. debug('request(%d): cancel', IDS.get(this))
  66076. connection.cancel()
  66077. }
  66078. // attach handler to handle multiple error messages
  66079. connection.on('infoMessage', errorHandlers.infoMessage = handleInfo)
  66080. connection.on('errorMessage', errorHandlers.errorMessage = handleError.bind(null, false, connection))
  66081. connection.on('error', errorHandlers.error = handleError.bind(null, true, connection))
  66082. const done = (err, rowCount) => {
  66083. // to make sure we handle no-sql errors as well
  66084. if (err && (!errors.length || (errors.length && err.message !== errors[errors.length - 1].message))) {
  66085. err = new RequestError(err, 'EREQUEST')
  66086. if (this.stream) this.emit('error', err)
  66087. errors.push(err)
  66088. }
  66089. delete this._cancel
  66090. let error
  66091. if (errors.length && !this.stream) {
  66092. error = errors.pop()
  66093. error.precedingErrors = errors
  66094. }
  66095. if (!hasReturned) {
  66096. for (const event in errorHandlers) {
  66097. connection.removeListener(event, errorHandlers[event])
  66098. }
  66099. this.parent.release(connection)
  66100. hasReturned = true
  66101. if (this.stream) {
  66102. callback(null, rowCount)
  66103. } else {
  66104. callback(error, rowCount)
  66105. }
  66106. }
  66107. }
  66108. const bulk = connection.newBulkLoad(table.path, options, done)
  66109. for (const col of table.columns) {
  66110. bulk.addColumn(col.name, getTediousType(col.type), { nullable: col.nullable, length: col.length, scale: col.scale, precision: col.precision })
  66111. }
  66112. for (const row of table.rows) {
  66113. bulk.addRow(row)
  66114. }
  66115. if (table.create) {
  66116. const objectid = table.temporary ? `tempdb..[${table.name}]` : table.path
  66117. const req = new tds.Request(`if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`, err => {
  66118. if (err) return done(err)
  66119. connection.execBulkLoad(bulk)
  66120. })
  66121. this._setCurrentRequest(req)
  66122. connection.execSqlBatch(req)
  66123. } else {
  66124. connection.execBulkLoad(bulk)
  66125. }
  66126. })
  66127. })
  66128. }
  66129. /*
  66130. Execute specified sql command.
  66131. */
  66132. _query (command, callback) {
  66133. super._query(command, err => {
  66134. if (err) return callback(err)
  66135. const recordsets = []
  66136. const errors = []
  66137. const errorHandlers = {}
  66138. const output = {}
  66139. const rowsAffected = []
  66140. let columns = {}
  66141. let recordset = []
  66142. let batchLastRow = null
  66143. let batchHasOutput = false
  66144. let isChunkedRecordset = false
  66145. let chunksBuffer = null
  66146. let hasReturned = false
  66147. const handleError = (doReturn, connection, info) => {
  66148. let err = new Error(info.message)
  66149. err.info = info
  66150. err = new RequestError(err, 'EREQUEST')
  66151. if (this.stream) {
  66152. this.emit('error', err)
  66153. } else {
  66154. if (doReturn && !hasReturned) {
  66155. if (connection) {
  66156. for (const event in errorHandlers) {
  66157. connection.removeListener(event, errorHandlers[event])
  66158. }
  66159. this.parent.release(connection)
  66160. }
  66161. hasReturned = true
  66162. callback(err)
  66163. }
  66164. }
  66165. // we must collect errors even in stream mode
  66166. errors.push(err)
  66167. }
  66168. const handleInfo = msg => {
  66169. this.emit('info', {
  66170. message: msg.message,
  66171. number: msg.number,
  66172. state: msg.state,
  66173. class: msg.class,
  66174. lineNumber: msg.lineNumber,
  66175. serverName: msg.serverName,
  66176. procName: msg.procName
  66177. })
  66178. }
  66179. this.parent.acquire(this, (err, connection, config) => {
  66180. if (err) return callback(err)
  66181. debug('connection(%d): borrowed to request #%d', IDS.get(connection), IDS.get(this))
  66182. let row
  66183. if (this.canceled) {
  66184. debug('request(%d): canceled', IDS.get(this))
  66185. this.parent.release(connection)
  66186. return callback(new RequestError('Canceled.', 'ECANCEL'))
  66187. }
  66188. this._cancel = () => {
  66189. debug('request(%d): cancel', IDS.get(this))
  66190. connection.cancel()
  66191. }
  66192. // attach handler to handle multiple error messages
  66193. connection.on('infoMessage', errorHandlers.infoMessage = handleInfo)
  66194. connection.on('errorMessage', errorHandlers.errorMessage = handleError.bind(null, false, connection))
  66195. connection.on('error', errorHandlers.error = handleError.bind(null, true, connection))
  66196. debug('request(%d): query', IDS.get(this), command)
  66197. const req = new tds.Request(command, err => {
  66198. // to make sure we handle no-sql errors as well
  66199. if (err && (!errors.length || (errors.length && err.message !== errors[errors.length - 1].message))) {
  66200. err = new RequestError(err, 'EREQUEST')
  66201. if (this.stream) this.emit('error', err)
  66202. errors.push(err)
  66203. }
  66204. // process batch outputs
  66205. if (batchHasOutput) {
  66206. if (!this.stream) batchLastRow = recordsets.pop()[0]
  66207. for (const name in batchLastRow) {
  66208. const value = batchLastRow[name]
  66209. if (name !== '___return___') {
  66210. output[name] = value
  66211. }
  66212. }
  66213. }
  66214. delete this._cancel
  66215. let error
  66216. if (errors.length && !this.stream) {
  66217. error = errors.pop()
  66218. error.precedingErrors = errors
  66219. }
  66220. if (!hasReturned) {
  66221. for (const event in errorHandlers) {
  66222. connection.removeListener(event, errorHandlers[event])
  66223. }
  66224. this.parent.release(connection)
  66225. hasReturned = true
  66226. if (error) {
  66227. debug('request(%d): failed', IDS.get(this), error)
  66228. } else {
  66229. debug('request(%d): completed', IDS.get(this))
  66230. }
  66231. if (this.stream) {
  66232. callback(null, null, output, rowsAffected)
  66233. } else {
  66234. callback(error, recordsets, output, rowsAffected)
  66235. }
  66236. }
  66237. })
  66238. this._setCurrentRequest(req)
  66239. req.on('columnMetadata', metadata => {
  66240. columns = createColumns(metadata)
  66241. isChunkedRecordset = false
  66242. if (metadata.length === 1 && (metadata[0].colName === JSON_COLUMN_ID || metadata[0].colName === XML_COLUMN_ID)) {
  66243. isChunkedRecordset = true
  66244. chunksBuffer = []
  66245. }
  66246. if (this.stream) {
  66247. if (this._isBatch) {
  66248. // don't stream recordset with output values in batches
  66249. if (!columns.___return___) {
  66250. this.emit('recordset', columns)
  66251. }
  66252. } else {
  66253. this.emit('recordset', columns)
  66254. }
  66255. }
  66256. })
  66257. const doneHandler = (rowCount, more) => {
  66258. if (rowCount != null) rowsAffected.push(rowCount)
  66259. // this function is called even when select only set variables so we should skip adding a new recordset
  66260. if (Object.keys(columns).length === 0) return
  66261. if (isChunkedRecordset) {
  66262. const concatenatedChunks = chunksBuffer.join('')
  66263. if (columns[JSON_COLUMN_ID] && config.parseJSON === true) {
  66264. try {
  66265. if (concatenatedChunks === '') {
  66266. row = null
  66267. } else {
  66268. row = JSON.parse(concatenatedChunks)
  66269. }
  66270. } catch (ex) {
  66271. row = null
  66272. const ex2 = new RequestError(new Error(`Failed to parse incoming JSON. ${ex.message}`), 'EJSON')
  66273. if (this.stream) this.emit('error', ex2)
  66274. // we must collect errors even in stream mode
  66275. errors.push(ex2)
  66276. }
  66277. } else {
  66278. row = {}
  66279. row[Object.keys(columns)[0]] = concatenatedChunks
  66280. }
  66281. chunksBuffer = null
  66282. if (this.stream) {
  66283. this.emit('row', row)
  66284. } else {
  66285. recordset.push(row)
  66286. }
  66287. }
  66288. if (!this.stream) {
  66289. // all rows of current recordset loaded
  66290. Object.defineProperty(recordset, 'columns', {
  66291. enumerable: false,
  66292. configurable: true,
  66293. value: columns
  66294. })
  66295. Object.defineProperty(recordset, 'toTable', {
  66296. enumerable: false,
  66297. configurable: true,
  66298. value (name) { return Table.fromRecordset(this, name) }
  66299. })
  66300. recordsets.push(recordset)
  66301. }
  66302. recordset = []
  66303. columns = {}
  66304. }
  66305. req.on('doneInProc', doneHandler) // doneInProc handlers are used in both queries and batches
  66306. req.on('done', doneHandler) // done handlers are used in batches
  66307. req.on('returnValue', (parameterName, value, metadata) => {
  66308. output[parameterName] = value
  66309. })
  66310. req.on('row', columns => {
  66311. if (!recordset) recordset = []
  66312. if (isChunkedRecordset) {
  66313. return chunksBuffer.push(columns[0].value)
  66314. }
  66315. row = {}
  66316. for (const col of columns) {
  66317. col.value = valueCorrection(col.value, col.metadata)
  66318. const exi = row[col.metadata.colName]
  66319. if (exi != null) {
  66320. if (exi instanceof Array) {
  66321. exi.push(col.value)
  66322. } else {
  66323. row[col.metadata.colName] = [exi, col.value]
  66324. }
  66325. } else {
  66326. row[col.metadata.colName] = col.value
  66327. }
  66328. }
  66329. if (this.stream) {
  66330. if (this._isBatch) {
  66331. // dont stream recordset with output values in batches
  66332. if (row.___return___) {
  66333. batchLastRow = row
  66334. } else {
  66335. this.emit('row', row)
  66336. }
  66337. } else {
  66338. this.emit('row', row)
  66339. }
  66340. } else {
  66341. recordset.push(row)
  66342. }
  66343. })
  66344. if (this._isBatch) {
  66345. if (Object.keys(this.parameters).length) {
  66346. for (const name in this.parameters) {
  66347. if (!objectHasProperty(this.parameters, name)) {
  66348. continue
  66349. }
  66350. const param = this.parameters[name]
  66351. let value = getTediousType(param.type).validate(param.value)
  66352. if (value instanceof TypeError) {
  66353. value = new RequestError(`Validation failed for parameter '${name}'. ${value.message}`, 'EPARAM')
  66354. this.parent.release(connection)
  66355. return callback(value)
  66356. }
  66357. param.value = value
  66358. }
  66359. const declarations = []
  66360. for (const name in this.parameters) {
  66361. if (!objectHasProperty(this.parameters, name)) {
  66362. continue
  66363. }
  66364. const param = this.parameters[name]
  66365. declarations.push(`@${name} ${declare(param.type, param)}`)
  66366. }
  66367. const assigns = []
  66368. for (const name in this.parameters) {
  66369. if (!objectHasProperty(this.parameters, name)) {
  66370. continue
  66371. }
  66372. const param = this.parameters[name]
  66373. assigns.push(`@${name} = ${cast(param.value, param.type, param)}`)
  66374. }
  66375. const selects = []
  66376. for (const name in this.parameters) {
  66377. if (!objectHasProperty(this.parameters, name)) {
  66378. continue
  66379. }
  66380. const param = this.parameters[name]
  66381. if (param.io === 2) {
  66382. selects.push(`@${name} as [${name}]`)
  66383. }
  66384. }
  66385. batchHasOutput = selects.length > 0
  66386. req.sqlTextOrProcedure = `declare ${declarations.join(', ')};select ${assigns.join(', ')};${req.sqlTextOrProcedure};${batchHasOutput ? (`select 1 as [___return___], ${selects.join(', ')}`) : ''}`
  66387. }
  66388. } else {
  66389. for (const name in this.parameters) {
  66390. if (!objectHasProperty(this.parameters, name)) {
  66391. continue
  66392. }
  66393. const param = this.parameters[name]
  66394. if (param.io === 1) {
  66395. req.addParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
  66396. } else {
  66397. req.addOutputParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
  66398. }
  66399. }
  66400. }
  66401. try {
  66402. connection[this._isBatch ? 'execSqlBatch' : 'execSql'](req)
  66403. } catch (error) {
  66404. handleError(true, connection, error)
  66405. }
  66406. })
  66407. })
  66408. }
  66409. /*
  66410. Execute stored procedure with specified parameters.
  66411. */
  66412. _execute (procedure, callback) {
  66413. super._execute(procedure, err => {
  66414. if (err) return callback(err)
  66415. const recordsets = []
  66416. const errors = []
  66417. const errorHandlers = {}
  66418. const output = {}
  66419. const rowsAffected = []
  66420. let columns = {}
  66421. let recordset = []
  66422. let returnValue = 0
  66423. let isChunkedRecordset = false
  66424. let chunksBuffer = null
  66425. let hasReturned = false
  66426. const handleError = (doReturn, connection, info) => {
  66427. let err = new Error(info.message)
  66428. err.info = info
  66429. err = new RequestError(err, 'EREQUEST')
  66430. if (this.stream) {
  66431. this.emit('error', err)
  66432. } else {
  66433. if (doReturn && !hasReturned) {
  66434. if (connection) {
  66435. for (const event in errorHandlers) {
  66436. connection.removeListener(event, errorHandlers[event])
  66437. }
  66438. this.parent.release(connection)
  66439. }
  66440. hasReturned = true
  66441. callback(err)
  66442. }
  66443. }
  66444. // we must collect errors even in stream mode
  66445. errors.push(err)
  66446. }
  66447. const handleInfo = msg => {
  66448. this.emit('info', {
  66449. message: msg.message,
  66450. number: msg.number,
  66451. state: msg.state,
  66452. class: msg.class,
  66453. lineNumber: msg.lineNumber,
  66454. serverName: msg.serverName,
  66455. procName: msg.procName
  66456. })
  66457. }
  66458. this.parent.acquire(this, (err, connection, config) => {
  66459. if (err) return callback(err)
  66460. debug('connection(%d): borrowed to request #%d', IDS.get(connection), IDS.get(this))
  66461. let row
  66462. if (this.canceled) {
  66463. debug('request(%d): canceled', IDS.get(this))
  66464. this.parent.release(connection)
  66465. return callback(new RequestError('Canceled.', 'ECANCEL'))
  66466. }
  66467. this._cancel = () => {
  66468. debug('request(%d): cancel', IDS.get(this))
  66469. connection.cancel()
  66470. }
  66471. // attach handler to handle multiple error messages
  66472. connection.on('infoMessage', errorHandlers.infoMessage = handleInfo)
  66473. connection.on('errorMessage', errorHandlers.errorMessage = handleError.bind(null, false, connection))
  66474. connection.on('error', errorHandlers.error = handleError.bind(null, true, connection))
  66475. if (debug.enabled) {
  66476. // log stored procedure executions and provided parameters
  66477. const params = Object.keys(this.parameters).map(k => this.parameters[k])
  66478. // cut long string parameters short to keep log somewhat clean
  66479. const logValue = s => typeof s === 'string' && s.length > 50 ? s.substring(0, 47) + '...' : s
  66480. // format parameter names as 'my_parameter [sql.Int]'
  66481. const logName = param => param.name + ' [sql.' + param.type.name + ']'
  66482. const logParams = {}
  66483. params.forEach(p => { logParams[logName(p)] = logValue(p.value) })
  66484. debug('request(%d): execute %s %O', IDS.get(this), procedure, logParams)
  66485. }
  66486. const req = new tds.Request(procedure, err => {
  66487. // to make sure we handle no-sql errors as well
  66488. if (err && (!errors.length || (errors.length && err.message !== errors[errors.length - 1].message))) {
  66489. err = new RequestError(err, 'EREQUEST')
  66490. if (this.stream) this.emit('error', err)
  66491. errors.push(err)
  66492. }
  66493. delete this._cancel
  66494. let error
  66495. if (errors.length && !this.stream) {
  66496. error = errors.pop()
  66497. error.precedingErrors = errors
  66498. }
  66499. if (!hasReturned) {
  66500. for (const event in errorHandlers) {
  66501. connection.removeListener(event, errorHandlers[event])
  66502. }
  66503. this.parent.release(connection)
  66504. hasReturned = true
  66505. if (error) {
  66506. debug('request(%d): failed', IDS.get(this), error)
  66507. } else {
  66508. debug('request(%d): complete', IDS.get(this))
  66509. }
  66510. if (this.stream) {
  66511. callback(null, null, output, returnValue, rowsAffected)
  66512. } else {
  66513. callback(error, recordsets, output, returnValue, rowsAffected)
  66514. }
  66515. }
  66516. })
  66517. this._setCurrentRequest(req)
  66518. req.on('columnMetadata', metadata => {
  66519. columns = createColumns(metadata)
  66520. isChunkedRecordset = false
  66521. if ((metadata.length === 1) && (metadata[0].colName === JSON_COLUMN_ID || metadata[0].colName === XML_COLUMN_ID)) {
  66522. isChunkedRecordset = true
  66523. chunksBuffer = []
  66524. }
  66525. if (this.stream) this.emit('recordset', columns)
  66526. })
  66527. req.on('row', columns => {
  66528. if (!recordset) recordset = []
  66529. if (isChunkedRecordset) {
  66530. return chunksBuffer.push(columns[0].value)
  66531. }
  66532. row = {}
  66533. for (const col of columns) {
  66534. col.value = valueCorrection(col.value, col.metadata)
  66535. const exi = row[col.metadata.colName]
  66536. if (exi != null) {
  66537. if (exi instanceof Array) {
  66538. exi.push(col.value)
  66539. } else {
  66540. row[col.metadata.colName] = [exi, col.value]
  66541. }
  66542. } else {
  66543. row[col.metadata.colName] = col.value
  66544. }
  66545. }
  66546. if (this.stream) {
  66547. this.emit('row', row)
  66548. } else {
  66549. recordset.push(row)
  66550. }
  66551. })
  66552. req.on('doneInProc', (rowCount, more) => {
  66553. if (rowCount != null) rowsAffected.push(rowCount)
  66554. // filter empty recordsets when NOCOUNT is OFF
  66555. if (Object.keys(columns).length === 0) return
  66556. if (isChunkedRecordset) {
  66557. if (columns[JSON_COLUMN_ID] && config.parseJSON === true) {
  66558. try {
  66559. if (chunksBuffer.length === 0) {
  66560. row = null
  66561. } else {
  66562. row = JSON.parse(chunksBuffer.join(''))
  66563. }
  66564. } catch (ex) {
  66565. row = null
  66566. const ex2 = new RequestError(new Error(`Failed to parse incoming JSON. ${ex.message}`), 'EJSON')
  66567. if (this.stream) this.emit('error', ex2)
  66568. // we must collect errors even in stream mode
  66569. errors.push(ex2)
  66570. }
  66571. } else {
  66572. row = {}
  66573. row[Object.keys(columns)[0]] = chunksBuffer.join('')
  66574. }
  66575. chunksBuffer = null
  66576. if (this.stream) {
  66577. this.emit('row', row)
  66578. } else {
  66579. recordset.push(row)
  66580. }
  66581. }
  66582. if (!this.stream) {
  66583. // all rows of current recordset loaded
  66584. Object.defineProperty(recordset, 'columns', {
  66585. enumerable: false,
  66586. configurable: true,
  66587. value: columns
  66588. })
  66589. Object.defineProperty(recordset, 'toTable', {
  66590. enumerable: false,
  66591. configurable: true,
  66592. value (name) { return Table.fromRecordset(this, name) }
  66593. })
  66594. recordsets.push(recordset)
  66595. }
  66596. recordset = []
  66597. columns = {}
  66598. })
  66599. req.on('doneProc', (rowCount, more, returnStatus) => {
  66600. returnValue = returnStatus
  66601. })
  66602. req.on('returnValue', (parameterName, value, metadata) => {
  66603. output[parameterName] = value
  66604. })
  66605. for (const name in this.parameters) {
  66606. if (!objectHasProperty(this.parameters, name)) {
  66607. continue
  66608. }
  66609. const param = this.parameters[name]
  66610. if (param.io === 1) {
  66611. req.addParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
  66612. } else {
  66613. req.addOutputParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
  66614. }
  66615. }
  66616. connection.callProcedure(req)
  66617. })
  66618. })
  66619. }
  66620. _pause () {
  66621. super._pause()
  66622. if (this._currentRequest) {
  66623. this._currentRequest.pause()
  66624. }
  66625. }
  66626. _resume () {
  66627. super._resume()
  66628. if (this._currentRequest) {
  66629. this._currentRequest.resume()
  66630. }
  66631. }
  66632. }
  66633. module.exports = Request
  66634. },{"../base/request":351,"../datatypes":354,"../error/request-error":359,"../table":364,"../udt":369,"../utils":370,"debug":372,"tedious":476}],368:[function(require,module,exports){
  66635. (function (setImmediate){(function (){
  66636. 'use strict'
  66637. const debug = require('debug')('mssql:tedi')
  66638. const BaseTransaction = require('../base/transaction')
  66639. const { IDS } = require('../utils')
  66640. const TransactionError = require('../error/transaction-error')
  66641. class Transaction extends BaseTransaction {
  66642. constructor (parent) {
  66643. super(parent)
  66644. this._abort = () => {
  66645. if (!this._rollbackRequested) {
  66646. // transaction interrupted because of XACT_ABORT
  66647. const pc = this._acquiredConnection
  66648. // defer releasing so connection can switch from SentClientRequest to LoggedIn state
  66649. setImmediate(this.parent.release.bind(this.parent), pc)
  66650. this._acquiredConnection.removeListener('rollbackTransaction', this._abort)
  66651. this._acquiredConnection = null
  66652. this._acquiredConfig = null
  66653. this._aborted = true
  66654. this.emit('rollback', true)
  66655. }
  66656. }
  66657. }
  66658. _begin (isolationLevel, callback) {
  66659. super._begin(isolationLevel, err => {
  66660. if (err) return callback(err)
  66661. debug('transaction(%d): begin', IDS.get(this))
  66662. this.parent.acquire(this, (err, connection, config) => {
  66663. if (err) return callback(err)
  66664. this._acquiredConnection = connection
  66665. this._acquiredConnection.on('rollbackTransaction', this._abort)
  66666. this._acquiredConfig = config
  66667. connection.beginTransaction(err => {
  66668. if (err) err = new TransactionError(err)
  66669. debug('transaction(%d): begun', IDS.get(this))
  66670. callback(err)
  66671. }, this.name, this.isolationLevel)
  66672. })
  66673. })
  66674. }
  66675. _commit (callback) {
  66676. super._commit(err => {
  66677. if (err) return callback(err)
  66678. debug('transaction(%d): commit', IDS.get(this))
  66679. this._acquiredConnection.commitTransaction(err => {
  66680. if (err) err = new TransactionError(err)
  66681. this._acquiredConnection.removeListener('rollbackTransaction', this._abort)
  66682. this.parent.release(this._acquiredConnection)
  66683. this._acquiredConnection = null
  66684. this._acquiredConfig = null
  66685. if (!err) debug('transaction(%d): commited', IDS.get(this))
  66686. callback(err)
  66687. })
  66688. })
  66689. }
  66690. _rollback (callback) {
  66691. super._rollback(err => {
  66692. if (err) return callback(err)
  66693. debug('transaction(%d): rollback', IDS.get(this))
  66694. this._acquiredConnection.rollbackTransaction(err => {
  66695. if (err) err = new TransactionError(err)
  66696. this._acquiredConnection.removeListener('rollbackTransaction', this._abort)
  66697. this.parent.release(this._acquiredConnection)
  66698. this._acquiredConnection = null
  66699. this._acquiredConfig = null
  66700. if (!err) debug('transaction(%d): rolled back', IDS.get(this))
  66701. callback(err)
  66702. })
  66703. })
  66704. }
  66705. }
  66706. module.exports = Transaction
  66707. }).call(this)}).call(this,require("timers").setImmediate)
  66708. },{"../base/transaction":352,"../error/transaction-error":360,"../utils":370,"debug":372,"timers":639}],369:[function(require,module,exports){
  66709. 'use strict'
  66710. /* const FIGURE = {
  66711. INTERIOR_RING: 0x00,
  66712. STROKE: 0x01,
  66713. EXTERIOR_RING: 0x02
  66714. };
  66715. const FIGURE_V2 = {
  66716. POINT: 0x00,
  66717. LINE: 0x01,
  66718. ARC: 0x02,
  66719. COMPOSITE_CURVE: 0x03
  66720. };
  66721. const SHAPE = {
  66722. POINT: 0x01,
  66723. LINESTRING: 0x02,
  66724. POLYGON: 0x03,
  66725. MULTIPOINT: 0x04,
  66726. MULTILINESTRING: 0x05,
  66727. MULTIPOLYGON: 0x06,
  66728. GEOMETRY_COLLECTION: 0x07
  66729. };
  66730. const SHAPE_V2 = {
  66731. POINT: 0x01,
  66732. LINESTRING: 0x02,
  66733. POLYGON: 0x03,
  66734. MULTIPOINT: 0x04,
  66735. MULTILINESTRING: 0x05,
  66736. MULTIPOLYGON: 0x06,
  66737. GEOMETRY_COLLECTION: 0x07,
  66738. CIRCULAR_STRING: 0x08,
  66739. COMPOUND_CURVE: 0x09,
  66740. CURVE_POLYGON: 0x0A,
  66741. FULL_GLOBE: 0x0B
  66742. };
  66743. const SEGMENT = {
  66744. LINE: 0x00,
  66745. ARC: 0x01,
  66746. FIRST_LINE: 0x02,
  66747. FIRST_ARC: 0x03
  66748. }; */
  66749. class Point {
  66750. constructor () {
  66751. this.x = 0
  66752. this.y = 0
  66753. this.z = null
  66754. this.m = null
  66755. }
  66756. }
  66757. const parsePoints = (buffer, count) => {
  66758. // s2.1.5 + s2.1.6
  66759. const points = []
  66760. if (count < 1) {
  66761. return points
  66762. }
  66763. for (let i = 1; i <= count; i++) {
  66764. const point = new Point()
  66765. points.push(point)
  66766. point.x = buffer.readDoubleLE(buffer.position)
  66767. point.y = buffer.readDoubleLE(buffer.position + 8)
  66768. buffer.position += 16
  66769. }
  66770. return points
  66771. }
  66772. const parseZ = (buffer, points) => {
  66773. // s2.1.1 + s.2.1.2
  66774. if (points < 1) {
  66775. return
  66776. }
  66777. points.forEach(point => {
  66778. point.z = buffer.readDoubleLE(buffer.position)
  66779. buffer.position += 8
  66780. })
  66781. }
  66782. const parseM = (buffer, points) => {
  66783. // s2.1.1 + s.2.1.2
  66784. if (points < 1) {
  66785. return
  66786. }
  66787. points.forEach(point => {
  66788. point.m = buffer.readDoubleLE(buffer.position)
  66789. buffer.position += 8
  66790. })
  66791. }
  66792. const parseFigures = (buffer, count, properties) => {
  66793. // s2.1.3
  66794. const figures = []
  66795. if (count < 1) {
  66796. return figures
  66797. }
  66798. if (properties.P) {
  66799. figures.push({
  66800. attribute: 0x01,
  66801. pointOffset: 0
  66802. })
  66803. } else if (properties.L) {
  66804. figures.push({
  66805. attribute: 0x01,
  66806. pointOffset: 0
  66807. })
  66808. } else {
  66809. for (let i = 1; i <= count; i++) {
  66810. figures.push({
  66811. attribute: buffer.readUInt8(buffer.position),
  66812. pointOffset: buffer.readInt32LE(buffer.position + 1)
  66813. })
  66814. buffer.position += 5
  66815. }
  66816. }
  66817. return figures
  66818. }
  66819. const parseShapes = (buffer, count, properties) => {
  66820. // s2.1.4
  66821. const shapes = []
  66822. if (count < 1) {
  66823. return shapes
  66824. }
  66825. if (properties.P) {
  66826. shapes.push({
  66827. parentOffset: -1,
  66828. figureOffset: 0,
  66829. type: 0x01
  66830. })
  66831. } else if (properties.L) {
  66832. shapes.push({
  66833. parentOffset: -1,
  66834. figureOffset: 0,
  66835. type: 0x02
  66836. })
  66837. } else {
  66838. for (let i = 1; i <= count; i++) {
  66839. shapes.push({
  66840. parentOffset: buffer.readInt32LE(buffer.position),
  66841. figureOffset: buffer.readInt32LE(buffer.position + 4),
  66842. type: buffer.readUInt8(buffer.position + 8)
  66843. })
  66844. buffer.position += 9
  66845. }
  66846. }
  66847. return shapes
  66848. }
  66849. const parseSegments = (buffer, count) => {
  66850. // s2.1.7
  66851. const segments = []
  66852. if (count < 1) {
  66853. return segments
  66854. }
  66855. for (let i = 1; i <= count; i++) {
  66856. segments.push({ type: buffer.readUInt8(buffer.position) })
  66857. buffer.position++
  66858. }
  66859. return segments
  66860. }
  66861. const parseGeography = buffer => {
  66862. // s2.1.1 + s.2.1.2
  66863. const srid = buffer.readInt32LE(0)
  66864. if (srid === -1) {
  66865. return null
  66866. }
  66867. const value = {
  66868. srid,
  66869. version: buffer.readUInt8(4)
  66870. }
  66871. const flags = buffer.readUInt8(5)
  66872. buffer.position = 6
  66873. // console.log("srid", srid)
  66874. // console.log("version", version)
  66875. const properties = {
  66876. Z: (flags & (1 << 0)) > 0,
  66877. M: (flags & (1 << 1)) > 0,
  66878. V: (flags & (1 << 2)) > 0,
  66879. P: (flags & (1 << 3)) > 0,
  66880. L: (flags & (1 << 4)) > 0
  66881. }
  66882. if (value.version === 2) {
  66883. properties.H = (flags & (1 << 3)) > 0
  66884. }
  66885. // console.log("properties", properties);
  66886. let numberOfPoints
  66887. if (properties.P) {
  66888. numberOfPoints = 1
  66889. } else if (properties.L) {
  66890. numberOfPoints = 2
  66891. } else {
  66892. numberOfPoints = buffer.readUInt32LE(buffer.position)
  66893. buffer.position += 4
  66894. }
  66895. // console.log("numberOfPoints", numberOfPoints)
  66896. value.points = parsePoints(buffer, numberOfPoints)
  66897. if (properties.Z) {
  66898. parseZ(buffer, value.points)
  66899. }
  66900. if (properties.M) {
  66901. parseM(buffer, value.points)
  66902. }
  66903. // console.log("points", points)
  66904. let numberOfFigures
  66905. if (properties.P) {
  66906. numberOfFigures = 1
  66907. } else if (properties.L) {
  66908. numberOfFigures = 1
  66909. } else {
  66910. numberOfFigures = buffer.readUInt32LE(buffer.position)
  66911. buffer.position += 4
  66912. }
  66913. // console.log("numberOfFigures", numberOfFigures)
  66914. value.figures = parseFigures(buffer, numberOfFigures, properties)
  66915. // console.log("figures", figures)
  66916. let numberOfShapes
  66917. if (properties.P) {
  66918. numberOfShapes = 1
  66919. } else if (properties.L) {
  66920. numberOfShapes = 1
  66921. } else {
  66922. numberOfShapes = buffer.readUInt32LE(buffer.position)
  66923. buffer.position += 4
  66924. }
  66925. // console.log("numberOfShapes", numberOfShapes)
  66926. value.shapes = parseShapes(buffer, numberOfShapes, properties)
  66927. // console.log( "shapes", shapes)
  66928. if (value.version === 2) {
  66929. const numberOfSegments = buffer.readUInt32LE(buffer.position)
  66930. buffer.position += 4
  66931. // console.log("numberOfSegments", numberOfSegments)
  66932. value.segments = parseSegments(buffer, numberOfSegments)
  66933. // console.log("segments", segments)
  66934. } else {
  66935. value.segments = []
  66936. }
  66937. return value
  66938. }
  66939. module.exports.PARSERS = {
  66940. geography (buffer) {
  66941. return parseGeography(buffer)
  66942. },
  66943. geometry (buffer) {
  66944. return parseGeography(buffer)
  66945. }
  66946. }
  66947. },{}],370:[function(require,module,exports){
  66948. const IDS = new WeakMap()
  66949. const INCREMENT = {
  66950. Connection: 1,
  66951. ConnectionPool: 1,
  66952. Request: 1,
  66953. Transaction: 1,
  66954. PreparedStatement: 1
  66955. }
  66956. module.exports = {
  66957. objectHasProperty: (object, property) => Object.prototype.hasOwnProperty.call(object, property),
  66958. INCREMENT: INCREMENT,
  66959. IDS: {
  66960. get: IDS.get.bind(IDS),
  66961. add: (object, type, id) => {
  66962. if (id) return IDS.set(object, id)
  66963. IDS.set(object, INCREMENT[type]++)
  66964. }
  66965. }
  66966. }
  66967. },{}],371:[function(require,module,exports){
  66968. (function (Buffer){(function (){
  66969. 'use strict'
  66970. var DuplexStream = require('readable-stream').Duplex
  66971. , util = require('util')
  66972. function BufferList (callback) {
  66973. if (!(this instanceof BufferList))
  66974. return new BufferList(callback)
  66975. this._bufs = []
  66976. this.length = 0
  66977. if (typeof callback == 'function') {
  66978. this._callback = callback
  66979. var piper = function piper (err) {
  66980. if (this._callback) {
  66981. this._callback(err)
  66982. this._callback = null
  66983. }
  66984. }.bind(this)
  66985. this.on('pipe', function onPipe (src) {
  66986. src.on('error', piper)
  66987. })
  66988. this.on('unpipe', function onUnpipe (src) {
  66989. src.removeListener('error', piper)
  66990. })
  66991. } else {
  66992. this.append(callback)
  66993. }
  66994. DuplexStream.call(this)
  66995. }
  66996. util.inherits(BufferList, DuplexStream)
  66997. BufferList.prototype._offset = function _offset (offset) {
  66998. var tot = 0, i = 0, _t
  66999. if (offset === 0) return [ 0, 0 ]
  67000. for (; i < this._bufs.length; i++) {
  67001. _t = tot + this._bufs[i].length
  67002. if (offset < _t || i == this._bufs.length - 1) {
  67003. return [ i, offset - tot ]
  67004. }
  67005. tot = _t
  67006. }
  67007. }
  67008. BufferList.prototype._reverseOffset = function (blOffset) {
  67009. var bufferId = blOffset[0]
  67010. var offset = blOffset[1]
  67011. for (var i = 0; i < bufferId; i++) {
  67012. offset += this._bufs[i].length
  67013. }
  67014. return offset
  67015. }
  67016. BufferList.prototype.append = function append (buf) {
  67017. var i = 0
  67018. if (Buffer.isBuffer(buf)) {
  67019. this._appendBuffer(buf)
  67020. } else if (Array.isArray(buf)) {
  67021. for (; i < buf.length; i++)
  67022. this.append(buf[i])
  67023. } else if (buf instanceof BufferList) {
  67024. // unwrap argument into individual BufferLists
  67025. for (; i < buf._bufs.length; i++)
  67026. this.append(buf._bufs[i])
  67027. } else if (buf != null) {
  67028. // coerce number arguments to strings, since Buffer(number) does
  67029. // uninitialized memory allocation
  67030. if (typeof buf == 'number')
  67031. buf = buf.toString()
  67032. this._appendBuffer(Buffer.from(buf))
  67033. }
  67034. return this
  67035. }
  67036. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  67037. this._bufs.push(buf)
  67038. this.length += buf.length
  67039. }
  67040. BufferList.prototype._write = function _write (buf, encoding, callback) {
  67041. this._appendBuffer(buf)
  67042. if (typeof callback == 'function')
  67043. callback()
  67044. }
  67045. BufferList.prototype._read = function _read (size) {
  67046. if (!this.length)
  67047. return this.push(null)
  67048. size = Math.min(size, this.length)
  67049. this.push(this.slice(0, size))
  67050. this.consume(size)
  67051. }
  67052. BufferList.prototype.end = function end (chunk) {
  67053. DuplexStream.prototype.end.call(this, chunk)
  67054. if (this._callback) {
  67055. this._callback(null, this.slice())
  67056. this._callback = null
  67057. }
  67058. }
  67059. BufferList.prototype.get = function get (index) {
  67060. if (index > this.length || index < 0) {
  67061. return undefined
  67062. }
  67063. var offset = this._offset(index)
  67064. return this._bufs[offset[0]][offset[1]]
  67065. }
  67066. BufferList.prototype.slice = function slice (start, end) {
  67067. if (typeof start == 'number' && start < 0)
  67068. start += this.length
  67069. if (typeof end == 'number' && end < 0)
  67070. end += this.length
  67071. return this.copy(null, 0, start, end)
  67072. }
  67073. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  67074. if (typeof srcStart != 'number' || srcStart < 0)
  67075. srcStart = 0
  67076. if (typeof srcEnd != 'number' || srcEnd > this.length)
  67077. srcEnd = this.length
  67078. if (srcStart >= this.length)
  67079. return dst || Buffer.alloc(0)
  67080. if (srcEnd <= 0)
  67081. return dst || Buffer.alloc(0)
  67082. var copy = !!dst
  67083. , off = this._offset(srcStart)
  67084. , len = srcEnd - srcStart
  67085. , bytes = len
  67086. , bufoff = (copy && dstStart) || 0
  67087. , start = off[1]
  67088. , l
  67089. , i
  67090. // copy/slice everything
  67091. if (srcStart === 0 && srcEnd == this.length) {
  67092. if (!copy) { // slice, but full concat if multiple buffers
  67093. return this._bufs.length === 1
  67094. ? this._bufs[0]
  67095. : Buffer.concat(this._bufs, this.length)
  67096. }
  67097. // copy, need to copy individual buffers
  67098. for (i = 0; i < this._bufs.length; i++) {
  67099. this._bufs[i].copy(dst, bufoff)
  67100. bufoff += this._bufs[i].length
  67101. }
  67102. return dst
  67103. }
  67104. // easy, cheap case where it's a subset of one of the buffers
  67105. if (bytes <= this._bufs[off[0]].length - start) {
  67106. return copy
  67107. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  67108. : this._bufs[off[0]].slice(start, start + bytes)
  67109. }
  67110. if (!copy) // a slice, we need something to copy in to
  67111. dst = Buffer.allocUnsafe(len)
  67112. for (i = off[0]; i < this._bufs.length; i++) {
  67113. l = this._bufs[i].length - start
  67114. if (bytes > l) {
  67115. this._bufs[i].copy(dst, bufoff, start)
  67116. bufoff += l
  67117. } else {
  67118. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  67119. bufoff += l
  67120. break
  67121. }
  67122. bytes -= l
  67123. if (start)
  67124. start = 0
  67125. }
  67126. // safeguard so that we don't return uninitialized memory
  67127. if (dst.length > bufoff) return dst.slice(0, bufoff)
  67128. return dst
  67129. }
  67130. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  67131. start = start || 0
  67132. end = typeof end !== 'number' ? this.length : end
  67133. if (start < 0)
  67134. start += this.length
  67135. if (end < 0)
  67136. end += this.length
  67137. if (start === end) {
  67138. return new BufferList()
  67139. }
  67140. var startOffset = this._offset(start)
  67141. , endOffset = this._offset(end)
  67142. , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  67143. if (endOffset[1] == 0)
  67144. buffers.pop()
  67145. else
  67146. buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
  67147. if (startOffset[1] != 0)
  67148. buffers[0] = buffers[0].slice(startOffset[1])
  67149. return new BufferList(buffers)
  67150. }
  67151. BufferList.prototype.toString = function toString (encoding, start, end) {
  67152. return this.slice(start, end).toString(encoding)
  67153. }
  67154. BufferList.prototype.consume = function consume (bytes) {
  67155. // first, normalize the argument, in accordance with how Buffer does it
  67156. bytes = Math.trunc(bytes)
  67157. // do nothing if not a positive number
  67158. if (Number.isNaN(bytes) || bytes <= 0) return this
  67159. while (this._bufs.length) {
  67160. if (bytes >= this._bufs[0].length) {
  67161. bytes -= this._bufs[0].length
  67162. this.length -= this._bufs[0].length
  67163. this._bufs.shift()
  67164. } else {
  67165. this._bufs[0] = this._bufs[0].slice(bytes)
  67166. this.length -= bytes
  67167. break
  67168. }
  67169. }
  67170. return this
  67171. }
  67172. BufferList.prototype.duplicate = function duplicate () {
  67173. var i = 0
  67174. , copy = new BufferList()
  67175. for (; i < this._bufs.length; i++)
  67176. copy.append(this._bufs[i])
  67177. return copy
  67178. }
  67179. BufferList.prototype._destroy = function _destroy (err, cb) {
  67180. this._bufs.length = 0
  67181. this.length = 0
  67182. cb(err)
  67183. }
  67184. BufferList.prototype.indexOf = function (search, offset, encoding) {
  67185. if (encoding === undefined && typeof offset === 'string') {
  67186. encoding = offset
  67187. offset = undefined
  67188. }
  67189. if (typeof search === 'function' || Array.isArray(search)) {
  67190. throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.')
  67191. } else if (typeof search === 'number') {
  67192. search = Buffer.from([search])
  67193. } else if (typeof search === 'string') {
  67194. search = Buffer.from(search, encoding)
  67195. } else if (search instanceof BufferList) {
  67196. search = search.slice()
  67197. } else if (!Buffer.isBuffer(search)) {
  67198. search = Buffer.from(search)
  67199. }
  67200. offset = Number(offset || 0)
  67201. if (isNaN(offset)) {
  67202. offset = 0
  67203. }
  67204. if (offset < 0) {
  67205. offset = this.length + offset
  67206. }
  67207. if (offset < 0) {
  67208. offset = 0
  67209. }
  67210. if (search.length === 0) {
  67211. return offset > this.length ? this.length : offset
  67212. }
  67213. var blOffset = this._offset(offset)
  67214. var blIndex = blOffset[0] // index of which internal buffer we're working on
  67215. var buffOffset = blOffset[1] // offset of the internal buffer we're working on
  67216. // scan over each buffer
  67217. for (blIndex; blIndex < this._bufs.length; blIndex++) {
  67218. var buff = this._bufs[blIndex]
  67219. while(buffOffset < buff.length) {
  67220. var availableWindow = buff.length - buffOffset
  67221. if (availableWindow >= search.length) {
  67222. var nativeSearchResult = buff.indexOf(search, buffOffset)
  67223. if (nativeSearchResult !== -1) {
  67224. return this._reverseOffset([blIndex, nativeSearchResult])
  67225. }
  67226. buffOffset = buff.length - search.length + 1 // end of native search window
  67227. } else {
  67228. var revOffset = this._reverseOffset([blIndex, buffOffset])
  67229. if (this._match(revOffset, search)) {
  67230. return revOffset
  67231. }
  67232. buffOffset++
  67233. }
  67234. }
  67235. buffOffset = 0
  67236. }
  67237. return -1
  67238. }
  67239. BufferList.prototype._match = function(offset, search) {
  67240. if (this.length - offset < search.length) {
  67241. return false
  67242. }
  67243. for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) {
  67244. if(this.get(offset + searchOffset) !== search[searchOffset]){
  67245. return false
  67246. }
  67247. }
  67248. return true
  67249. }
  67250. ;(function () {
  67251. var methods = {
  67252. 'readDoubleBE' : 8
  67253. , 'readDoubleLE' : 8
  67254. , 'readFloatBE' : 4
  67255. , 'readFloatLE' : 4
  67256. , 'readInt32BE' : 4
  67257. , 'readInt32LE' : 4
  67258. , 'readUInt32BE' : 4
  67259. , 'readUInt32LE' : 4
  67260. , 'readInt16BE' : 2
  67261. , 'readInt16LE' : 2
  67262. , 'readUInt16BE' : 2
  67263. , 'readUInt16LE' : 2
  67264. , 'readInt8' : 1
  67265. , 'readUInt8' : 1
  67266. , 'readIntBE' : null
  67267. , 'readIntLE' : null
  67268. , 'readUIntBE' : null
  67269. , 'readUIntLE' : null
  67270. }
  67271. for (var m in methods) {
  67272. (function (m) {
  67273. if (methods[m] === null) {
  67274. BufferList.prototype[m] = function (offset, byteLength) {
  67275. return this.slice(offset, offset + byteLength)[m](0, byteLength)
  67276. }
  67277. }
  67278. else {
  67279. BufferList.prototype[m] = function (offset) {
  67280. return this.slice(offset, offset + methods[m])[m](0)
  67281. }
  67282. }
  67283. }(m))
  67284. }
  67285. }())
  67286. module.exports = BufferList
  67287. }).call(this)}).call(this,require("buffer").Buffer)
  67288. },{"buffer":193,"readable-stream":409,"util":658}],372:[function(require,module,exports){
  67289. (function (process){(function (){
  67290. /* eslint-env browser */
  67291. /**
  67292. * This is the web browser implementation of `debug()`.
  67293. */
  67294. exports.formatArgs = formatArgs;
  67295. exports.save = save;
  67296. exports.load = load;
  67297. exports.useColors = useColors;
  67298. exports.storage = localstorage();
  67299. exports.destroy = (() => {
  67300. let warned = false;
  67301. return () => {
  67302. if (!warned) {
  67303. warned = true;
  67304. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  67305. }
  67306. };
  67307. })();
  67308. /**
  67309. * Colors.
  67310. */
  67311. exports.colors = [
  67312. '#0000CC',
  67313. '#0000FF',
  67314. '#0033CC',
  67315. '#0033FF',
  67316. '#0066CC',
  67317. '#0066FF',
  67318. '#0099CC',
  67319. '#0099FF',
  67320. '#00CC00',
  67321. '#00CC33',
  67322. '#00CC66',
  67323. '#00CC99',
  67324. '#00CCCC',
  67325. '#00CCFF',
  67326. '#3300CC',
  67327. '#3300FF',
  67328. '#3333CC',
  67329. '#3333FF',
  67330. '#3366CC',
  67331. '#3366FF',
  67332. '#3399CC',
  67333. '#3399FF',
  67334. '#33CC00',
  67335. '#33CC33',
  67336. '#33CC66',
  67337. '#33CC99',
  67338. '#33CCCC',
  67339. '#33CCFF',
  67340. '#6600CC',
  67341. '#6600FF',
  67342. '#6633CC',
  67343. '#6633FF',
  67344. '#66CC00',
  67345. '#66CC33',
  67346. '#9900CC',
  67347. '#9900FF',
  67348. '#9933CC',
  67349. '#9933FF',
  67350. '#99CC00',
  67351. '#99CC33',
  67352. '#CC0000',
  67353. '#CC0033',
  67354. '#CC0066',
  67355. '#CC0099',
  67356. '#CC00CC',
  67357. '#CC00FF',
  67358. '#CC3300',
  67359. '#CC3333',
  67360. '#CC3366',
  67361. '#CC3399',
  67362. '#CC33CC',
  67363. '#CC33FF',
  67364. '#CC6600',
  67365. '#CC6633',
  67366. '#CC9900',
  67367. '#CC9933',
  67368. '#CCCC00',
  67369. '#CCCC33',
  67370. '#FF0000',
  67371. '#FF0033',
  67372. '#FF0066',
  67373. '#FF0099',
  67374. '#FF00CC',
  67375. '#FF00FF',
  67376. '#FF3300',
  67377. '#FF3333',
  67378. '#FF3366',
  67379. '#FF3399',
  67380. '#FF33CC',
  67381. '#FF33FF',
  67382. '#FF6600',
  67383. '#FF6633',
  67384. '#FF9900',
  67385. '#FF9933',
  67386. '#FFCC00',
  67387. '#FFCC33'
  67388. ];
  67389. /**
  67390. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  67391. * and the Firebug extension (any Firefox version) are known
  67392. * to support "%c" CSS customizations.
  67393. *
  67394. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  67395. */
  67396. // eslint-disable-next-line complexity
  67397. function useColors() {
  67398. // NB: In an Electron preload script, document will be defined but not fully
  67399. // initialized. Since we know we're in Chrome, we'll just detect this case
  67400. // explicitly
  67401. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  67402. return true;
  67403. }
  67404. // Internet Explorer and Edge do not support colors.
  67405. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  67406. return false;
  67407. }
  67408. // Is webkit? http://stackoverflow.com/a/16459606/376773
  67409. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  67410. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  67411. // Is firebug? http://stackoverflow.com/a/398120/376773
  67412. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  67413. // Is firefox >= v31?
  67414. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  67415. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  67416. // Double check webkit in userAgent just in case we are in a worker
  67417. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  67418. }
  67419. /**
  67420. * Colorize log arguments if enabled.
  67421. *
  67422. * @api public
  67423. */
  67424. function formatArgs(args) {
  67425. args[0] = (this.useColors ? '%c' : '') +
  67426. this.namespace +
  67427. (this.useColors ? ' %c' : ' ') +
  67428. args[0] +
  67429. (this.useColors ? '%c ' : ' ') +
  67430. '+' + module.exports.humanize(this.diff);
  67431. if (!this.useColors) {
  67432. return;
  67433. }
  67434. const c = 'color: ' + this.color;
  67435. args.splice(1, 0, c, 'color: inherit');
  67436. // The final "%c" is somewhat tricky, because there could be other
  67437. // arguments passed either before or after the %c, so we need to
  67438. // figure out the correct index to insert the CSS into
  67439. let index = 0;
  67440. let lastC = 0;
  67441. args[0].replace(/%[a-zA-Z%]/g, match => {
  67442. if (match === '%%') {
  67443. return;
  67444. }
  67445. index++;
  67446. if (match === '%c') {
  67447. // We only are interested in the *last* %c
  67448. // (the user may have provided their own)
  67449. lastC = index;
  67450. }
  67451. });
  67452. args.splice(lastC, 0, c);
  67453. }
  67454. /**
  67455. * Invokes `console.debug()` when available.
  67456. * No-op when `console.debug` is not a "function".
  67457. * If `console.debug` is not available, falls back
  67458. * to `console.log`.
  67459. *
  67460. * @api public
  67461. */
  67462. exports.log = console.debug || console.log || (() => {});
  67463. /**
  67464. * Save `namespaces`.
  67465. *
  67466. * @param {String} namespaces
  67467. * @api private
  67468. */
  67469. function save(namespaces) {
  67470. try {
  67471. if (namespaces) {
  67472. exports.storage.setItem('debug', namespaces);
  67473. } else {
  67474. exports.storage.removeItem('debug');
  67475. }
  67476. } catch (error) {
  67477. // Swallow
  67478. // XXX (@Qix-) should we be logging these?
  67479. }
  67480. }
  67481. /**
  67482. * Load `namespaces`.
  67483. *
  67484. * @return {String} returns the previously persisted debug modes
  67485. * @api private
  67486. */
  67487. function load() {
  67488. let r;
  67489. try {
  67490. r = exports.storage.getItem('debug');
  67491. } catch (error) {
  67492. // Swallow
  67493. // XXX (@Qix-) should we be logging these?
  67494. }
  67495. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  67496. if (!r && typeof process !== 'undefined' && 'env' in process) {
  67497. r = process.env.DEBUG;
  67498. }
  67499. return r;
  67500. }
  67501. /**
  67502. * Localstorage attempts to return the localstorage.
  67503. *
  67504. * This is necessary because safari throws
  67505. * when a user disables cookies/localstorage
  67506. * and you attempt to access it.
  67507. *
  67508. * @return {LocalStorage}
  67509. * @api private
  67510. */
  67511. function localstorage() {
  67512. try {
  67513. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  67514. // The Browser also has localStorage in the global context.
  67515. return localStorage;
  67516. } catch (error) {
  67517. // Swallow
  67518. // XXX (@Qix-) should we be logging these?
  67519. }
  67520. }
  67521. module.exports = require('./common')(exports);
  67522. const {formatters} = module.exports;
  67523. /**
  67524. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  67525. */
  67526. formatters.j = function (v) {
  67527. try {
  67528. return JSON.stringify(v);
  67529. } catch (error) {
  67530. return '[UnexpectedJSONParseError]: ' + error.message;
  67531. }
  67532. };
  67533. }).call(this)}).call(this,require('_process'))
  67534. },{"./common":373,"_process":525}],373:[function(require,module,exports){
  67535. /**
  67536. * This is the common logic for both the Node.js and web browser
  67537. * implementations of `debug()`.
  67538. */
  67539. function setup(env) {
  67540. createDebug.debug = createDebug;
  67541. createDebug.default = createDebug;
  67542. createDebug.coerce = coerce;
  67543. createDebug.disable = disable;
  67544. createDebug.enable = enable;
  67545. createDebug.enabled = enabled;
  67546. createDebug.humanize = require('ms');
  67547. createDebug.destroy = destroy;
  67548. Object.keys(env).forEach(key => {
  67549. createDebug[key] = env[key];
  67550. });
  67551. /**
  67552. * The currently active debug mode names, and names to skip.
  67553. */
  67554. createDebug.names = [];
  67555. createDebug.skips = [];
  67556. /**
  67557. * Map of special "%n" handling functions, for the debug "format" argument.
  67558. *
  67559. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  67560. */
  67561. createDebug.formatters = {};
  67562. /**
  67563. * Selects a color for a debug namespace
  67564. * @param {String} namespace The namespace string for the for the debug instance to be colored
  67565. * @return {Number|String} An ANSI color code for the given namespace
  67566. * @api private
  67567. */
  67568. function selectColor(namespace) {
  67569. let hash = 0;
  67570. for (let i = 0; i < namespace.length; i++) {
  67571. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  67572. hash |= 0; // Convert to 32bit integer
  67573. }
  67574. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  67575. }
  67576. createDebug.selectColor = selectColor;
  67577. /**
  67578. * Create a debugger with the given `namespace`.
  67579. *
  67580. * @param {String} namespace
  67581. * @return {Function}
  67582. * @api public
  67583. */
  67584. function createDebug(namespace) {
  67585. let prevTime;
  67586. let enableOverride = null;
  67587. function debug(...args) {
  67588. // Disabled?
  67589. if (!debug.enabled) {
  67590. return;
  67591. }
  67592. const self = debug;
  67593. // Set `diff` timestamp
  67594. const curr = Number(new Date());
  67595. const ms = curr - (prevTime || curr);
  67596. self.diff = ms;
  67597. self.prev = prevTime;
  67598. self.curr = curr;
  67599. prevTime = curr;
  67600. args[0] = createDebug.coerce(args[0]);
  67601. if (typeof args[0] !== 'string') {
  67602. // Anything else let's inspect with %O
  67603. args.unshift('%O');
  67604. }
  67605. // Apply any `formatters` transformations
  67606. let index = 0;
  67607. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  67608. // If we encounter an escaped % then don't increase the array index
  67609. if (match === '%%') {
  67610. return '%';
  67611. }
  67612. index++;
  67613. const formatter = createDebug.formatters[format];
  67614. if (typeof formatter === 'function') {
  67615. const val = args[index];
  67616. match = formatter.call(self, val);
  67617. // Now we need to remove `args[index]` since it's inlined in the `format`
  67618. args.splice(index, 1);
  67619. index--;
  67620. }
  67621. return match;
  67622. });
  67623. // Apply env-specific formatting (colors, etc.)
  67624. createDebug.formatArgs.call(self, args);
  67625. const logFn = self.log || createDebug.log;
  67626. logFn.apply(self, args);
  67627. }
  67628. debug.namespace = namespace;
  67629. debug.useColors = createDebug.useColors();
  67630. debug.color = createDebug.selectColor(namespace);
  67631. debug.extend = extend;
  67632. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  67633. Object.defineProperty(debug, 'enabled', {
  67634. enumerable: true,
  67635. configurable: false,
  67636. get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,
  67637. set: v => {
  67638. enableOverride = v;
  67639. }
  67640. });
  67641. // Env-specific initialization logic for debug instances
  67642. if (typeof createDebug.init === 'function') {
  67643. createDebug.init(debug);
  67644. }
  67645. return debug;
  67646. }
  67647. function extend(namespace, delimiter) {
  67648. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  67649. newDebug.log = this.log;
  67650. return newDebug;
  67651. }
  67652. /**
  67653. * Enables a debug mode by namespaces. This can include modes
  67654. * separated by a colon and wildcards.
  67655. *
  67656. * @param {String} namespaces
  67657. * @api public
  67658. */
  67659. function enable(namespaces) {
  67660. createDebug.save(namespaces);
  67661. createDebug.names = [];
  67662. createDebug.skips = [];
  67663. let i;
  67664. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  67665. const len = split.length;
  67666. for (i = 0; i < len; i++) {
  67667. if (!split[i]) {
  67668. // ignore empty strings
  67669. continue;
  67670. }
  67671. namespaces = split[i].replace(/\*/g, '.*?');
  67672. if (namespaces[0] === '-') {
  67673. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  67674. } else {
  67675. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  67676. }
  67677. }
  67678. }
  67679. /**
  67680. * Disable debug output.
  67681. *
  67682. * @return {String} namespaces
  67683. * @api public
  67684. */
  67685. function disable() {
  67686. const namespaces = [
  67687. ...createDebug.names.map(toNamespace),
  67688. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  67689. ].join(',');
  67690. createDebug.enable('');
  67691. return namespaces;
  67692. }
  67693. /**
  67694. * Returns true if the given mode name is enabled, false otherwise.
  67695. *
  67696. * @param {String} name
  67697. * @return {Boolean}
  67698. * @api public
  67699. */
  67700. function enabled(name) {
  67701. if (name[name.length - 1] === '*') {
  67702. return true;
  67703. }
  67704. let i;
  67705. let len;
  67706. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  67707. if (createDebug.skips[i].test(name)) {
  67708. return false;
  67709. }
  67710. }
  67711. for (i = 0, len = createDebug.names.length; i < len; i++) {
  67712. if (createDebug.names[i].test(name)) {
  67713. return true;
  67714. }
  67715. }
  67716. return false;
  67717. }
  67718. /**
  67719. * Convert regexp to namespace
  67720. *
  67721. * @param {RegExp} regxep
  67722. * @return {String} namespace
  67723. * @api private
  67724. */
  67725. function toNamespace(regexp) {
  67726. return regexp.toString()
  67727. .substring(2, regexp.toString().length - 2)
  67728. .replace(/\.\*\?$/, '*');
  67729. }
  67730. /**
  67731. * Coerce `val`.
  67732. *
  67733. * @param {Mixed} val
  67734. * @return {Mixed}
  67735. * @api private
  67736. */
  67737. function coerce(val) {
  67738. if (val instanceof Error) {
  67739. return val.stack || val.message;
  67740. }
  67741. return val;
  67742. }
  67743. /**
  67744. * XXX DO NOT USE. This is a temporary stub function.
  67745. * XXX It WILL be removed in the next major release.
  67746. */
  67747. function destroy() {
  67748. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  67749. }
  67750. createDebug.enable(createDebug.load());
  67751. return createDebug;
  67752. }
  67753. module.exports = setup;
  67754. },{"ms":394}],374:[function(require,module,exports){
  67755. "use strict";
  67756. var Buffer = require("safer-buffer").Buffer;
  67757. // Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
  67758. // Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
  67759. // To save memory and loading time, we read table files only when requested.
  67760. exports._dbcs = DBCSCodec;
  67761. var UNASSIGNED = -1,
  67762. GB18030_CODE = -2,
  67763. SEQ_START = -10,
  67764. NODE_START = -1000,
  67765. UNASSIGNED_NODE = new Array(0x100),
  67766. DEF_CHAR = -1;
  67767. for (var i = 0; i < 0x100; i++)
  67768. UNASSIGNED_NODE[i] = UNASSIGNED;
  67769. // Class DBCSCodec reads and initializes mapping tables.
  67770. function DBCSCodec(codecOptions, iconv) {
  67771. this.encodingName = codecOptions.encodingName;
  67772. if (!codecOptions)
  67773. throw new Error("DBCS codec is called without the data.")
  67774. if (!codecOptions.table)
  67775. throw new Error("Encoding '" + this.encodingName + "' has no data.");
  67776. // Load tables.
  67777. var mappingTable = codecOptions.table();
  67778. // Decode tables: MBCS -> Unicode.
  67779. // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
  67780. // Trie root is decodeTables[0].
  67781. // Values: >= 0 -> unicode character code. can be > 0xFFFF
  67782. // == UNASSIGNED -> unknown/unassigned sequence.
  67783. // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
  67784. // <= NODE_START -> index of the next node in our trie to process next byte.
  67785. // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.
  67786. this.decodeTables = [];
  67787. this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
  67788. // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here.
  67789. this.decodeTableSeq = [];
  67790. // Actual mapping tables consist of chunks. Use them to fill up decode tables.
  67791. for (var i = 0; i < mappingTable.length; i++)
  67792. this._addDecodeChunk(mappingTable[i]);
  67793. this.defaultCharUnicode = iconv.defaultCharUnicode;
  67794. // Encode tables: Unicode -> DBCS.
  67795. // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
  67796. // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
  67797. // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
  67798. // == UNASSIGNED -> no conversion found. Output a default char.
  67799. // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.
  67800. this.encodeTable = [];
  67801. // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
  67802. // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
  67803. // means end of sequence (needed when one sequence is a strict subsequence of another).
  67804. // Objects are kept separately from encodeTable to increase performance.
  67805. this.encodeTableSeq = [];
  67806. // Some chars can be decoded, but need not be encoded.
  67807. var skipEncodeChars = {};
  67808. if (codecOptions.encodeSkipVals)
  67809. for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
  67810. var val = codecOptions.encodeSkipVals[i];
  67811. if (typeof val === 'number')
  67812. skipEncodeChars[val] = true;
  67813. else
  67814. for (var j = val.from; j <= val.to; j++)
  67815. skipEncodeChars[j] = true;
  67816. }
  67817. // Use decode trie to recursively fill out encode tables.
  67818. this._fillEncodeTable(0, 0, skipEncodeChars);
  67819. // Add more encoding pairs when needed.
  67820. if (codecOptions.encodeAdd) {
  67821. for (var uChar in codecOptions.encodeAdd)
  67822. if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
  67823. this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
  67824. }
  67825. this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
  67826. if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
  67827. if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
  67828. // Load & create GB18030 tables when needed.
  67829. if (typeof codecOptions.gb18030 === 'function') {
  67830. this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
  67831. // Add GB18030 decode tables.
  67832. var thirdByteNodeIdx = this.decodeTables.length;
  67833. var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);
  67834. var fourthByteNodeIdx = this.decodeTables.length;
  67835. var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);
  67836. for (var i = 0x81; i <= 0xFE; i++) {
  67837. var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];
  67838. var secondByteNode = this.decodeTables[secondByteNodeIdx];
  67839. for (var j = 0x30; j <= 0x39; j++)
  67840. secondByteNode[j] = NODE_START - thirdByteNodeIdx;
  67841. }
  67842. for (var i = 0x81; i <= 0xFE; i++)
  67843. thirdByteNode[i] = NODE_START - fourthByteNodeIdx;
  67844. for (var i = 0x30; i <= 0x39; i++)
  67845. fourthByteNode[i] = GB18030_CODE
  67846. }
  67847. }
  67848. DBCSCodec.prototype.encoder = DBCSEncoder;
  67849. DBCSCodec.prototype.decoder = DBCSDecoder;
  67850. // Decoder helpers
  67851. DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
  67852. var bytes = [];
  67853. for (; addr > 0; addr >>= 8)
  67854. bytes.push(addr & 0xFF);
  67855. if (bytes.length == 0)
  67856. bytes.push(0);
  67857. var node = this.decodeTables[0];
  67858. for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
  67859. var val = node[bytes[i]];
  67860. if (val == UNASSIGNED) { // Create new node.
  67861. node[bytes[i]] = NODE_START - this.decodeTables.length;
  67862. this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
  67863. }
  67864. else if (val <= NODE_START) { // Existing node.
  67865. node = this.decodeTables[NODE_START - val];
  67866. }
  67867. else
  67868. throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
  67869. }
  67870. return node;
  67871. }
  67872. DBCSCodec.prototype._addDecodeChunk = function(chunk) {
  67873. // First element of chunk is the hex mbcs code where we start.
  67874. var curAddr = parseInt(chunk[0], 16);
  67875. // Choose the decoding node where we'll write our chars.
  67876. var writeTable = this._getDecodeTrieNode(curAddr);
  67877. curAddr = curAddr & 0xFF;
  67878. // Write all other elements of the chunk to the table.
  67879. for (var k = 1; k < chunk.length; k++) {
  67880. var part = chunk[k];
  67881. if (typeof part === "string") { // String, write as-is.
  67882. for (var l = 0; l < part.length;) {
  67883. var code = part.charCodeAt(l++);
  67884. if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
  67885. var codeTrail = part.charCodeAt(l++);
  67886. if (0xDC00 <= codeTrail && codeTrail < 0xE000)
  67887. writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
  67888. else
  67889. throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]);
  67890. }
  67891. else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
  67892. var len = 0xFFF - code + 2;
  67893. var seq = [];
  67894. for (var m = 0; m < len; m++)
  67895. seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
  67896. writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
  67897. this.decodeTableSeq.push(seq);
  67898. }
  67899. else
  67900. writeTable[curAddr++] = code; // Basic char
  67901. }
  67902. }
  67903. else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
  67904. var charCode = writeTable[curAddr - 1] + 1;
  67905. for (var l = 0; l < part; l++)
  67906. writeTable[curAddr++] = charCode++;
  67907. }
  67908. else
  67909. throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]);
  67910. }
  67911. if (curAddr > 0xFF)
  67912. throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
  67913. }
  67914. // Encoder helpers
  67915. DBCSCodec.prototype._getEncodeBucket = function(uCode) {
  67916. var high = uCode >> 8; // This could be > 0xFF because of astral characters.
  67917. if (this.encodeTable[high] === undefined)
  67918. this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
  67919. return this.encodeTable[high];
  67920. }
  67921. DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
  67922. var bucket = this._getEncodeBucket(uCode);
  67923. var low = uCode & 0xFF;
  67924. if (bucket[low] <= SEQ_START)
  67925. this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
  67926. else if (bucket[low] == UNASSIGNED)
  67927. bucket[low] = dbcsCode;
  67928. }
  67929. DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
  67930. // Get the root of character tree according to first character of the sequence.
  67931. var uCode = seq[0];
  67932. var bucket = this._getEncodeBucket(uCode);
  67933. var low = uCode & 0xFF;
  67934. var node;
  67935. if (bucket[low] <= SEQ_START) {
  67936. // There's already a sequence with - use it.
  67937. node = this.encodeTableSeq[SEQ_START-bucket[low]];
  67938. }
  67939. else {
  67940. // There was no sequence object - allocate a new one.
  67941. node = {};
  67942. if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
  67943. bucket[low] = SEQ_START - this.encodeTableSeq.length;
  67944. this.encodeTableSeq.push(node);
  67945. }
  67946. // Traverse the character tree, allocating new nodes as needed.
  67947. for (var j = 1; j < seq.length-1; j++) {
  67948. var oldVal = node[uCode];
  67949. if (typeof oldVal === 'object')
  67950. node = oldVal;
  67951. else {
  67952. node = node[uCode] = {}
  67953. if (oldVal !== undefined)
  67954. node[DEF_CHAR] = oldVal
  67955. }
  67956. }
  67957. // Set the leaf to given dbcsCode.
  67958. uCode = seq[seq.length-1];
  67959. node[uCode] = dbcsCode;
  67960. }
  67961. DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
  67962. var node = this.decodeTables[nodeIdx];
  67963. for (var i = 0; i < 0x100; i++) {
  67964. var uCode = node[i];
  67965. var mbCode = prefix + i;
  67966. if (skipEncodeChars[mbCode])
  67967. continue;
  67968. if (uCode >= 0)
  67969. this._setEncodeChar(uCode, mbCode);
  67970. else if (uCode <= NODE_START)
  67971. this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);
  67972. else if (uCode <= SEQ_START)
  67973. this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
  67974. }
  67975. }
  67976. // == Encoder ==================================================================
  67977. function DBCSEncoder(options, codec) {
  67978. // Encoder state
  67979. this.leadSurrogate = -1;
  67980. this.seqObj = undefined;
  67981. // Static data
  67982. this.encodeTable = codec.encodeTable;
  67983. this.encodeTableSeq = codec.encodeTableSeq;
  67984. this.defaultCharSingleByte = codec.defCharSB;
  67985. this.gb18030 = codec.gb18030;
  67986. }
  67987. DBCSEncoder.prototype.write = function(str) {
  67988. var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
  67989. leadSurrogate = this.leadSurrogate,
  67990. seqObj = this.seqObj, nextChar = -1,
  67991. i = 0, j = 0;
  67992. while (true) {
  67993. // 0. Get next character.
  67994. if (nextChar === -1) {
  67995. if (i == str.length) break;
  67996. var uCode = str.charCodeAt(i++);
  67997. }
  67998. else {
  67999. var uCode = nextChar;
  68000. nextChar = -1;
  68001. }
  68002. // 1. Handle surrogates.
  68003. if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
  68004. if (uCode < 0xDC00) { // We've got lead surrogate.
  68005. if (leadSurrogate === -1) {
  68006. leadSurrogate = uCode;
  68007. continue;
  68008. } else {
  68009. leadSurrogate = uCode;
  68010. // Double lead surrogate found.
  68011. uCode = UNASSIGNED;
  68012. }
  68013. } else { // We've got trail surrogate.
  68014. if (leadSurrogate !== -1) {
  68015. uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
  68016. leadSurrogate = -1;
  68017. } else {
  68018. // Incomplete surrogate pair - only trail surrogate found.
  68019. uCode = UNASSIGNED;
  68020. }
  68021. }
  68022. }
  68023. else if (leadSurrogate !== -1) {
  68024. // Incomplete surrogate pair - only lead surrogate found.
  68025. nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
  68026. leadSurrogate = -1;
  68027. }
  68028. // 2. Convert uCode character.
  68029. var dbcsCode = UNASSIGNED;
  68030. if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
  68031. var resCode = seqObj[uCode];
  68032. if (typeof resCode === 'object') { // Sequence continues.
  68033. seqObj = resCode;
  68034. continue;
  68035. } else if (typeof resCode == 'number') { // Sequence finished. Write it.
  68036. dbcsCode = resCode;
  68037. } else if (resCode == undefined) { // Current character is not part of the sequence.
  68038. // Try default character for this sequence
  68039. resCode = seqObj[DEF_CHAR];
  68040. if (resCode !== undefined) {
  68041. dbcsCode = resCode; // Found. Write it.
  68042. nextChar = uCode; // Current character will be written too in the next iteration.
  68043. } else {
  68044. // TODO: What if we have no default? (resCode == undefined)
  68045. // Then, we should write first char of the sequence as-is and try the rest recursively.
  68046. // Didn't do it for now because no encoding has this situation yet.
  68047. // Currently, just skip the sequence and write current char.
  68048. }
  68049. }
  68050. seqObj = undefined;
  68051. }
  68052. else if (uCode >= 0) { // Regular character
  68053. var subtable = this.encodeTable[uCode >> 8];
  68054. if (subtable !== undefined)
  68055. dbcsCode = subtable[uCode & 0xFF];
  68056. if (dbcsCode <= SEQ_START) { // Sequence start
  68057. seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
  68058. continue;
  68059. }
  68060. if (dbcsCode == UNASSIGNED && this.gb18030) {
  68061. // Use GB18030 algorithm to find character(s) to write.
  68062. var idx = findIdx(this.gb18030.uChars, uCode);
  68063. if (idx != -1) {
  68064. var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
  68065. newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
  68066. newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
  68067. newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
  68068. newBuf[j++] = 0x30 + dbcsCode;
  68069. continue;
  68070. }
  68071. }
  68072. }
  68073. // 3. Write dbcsCode character.
  68074. if (dbcsCode === UNASSIGNED)
  68075. dbcsCode = this.defaultCharSingleByte;
  68076. if (dbcsCode < 0x100) {
  68077. newBuf[j++] = dbcsCode;
  68078. }
  68079. else if (dbcsCode < 0x10000) {
  68080. newBuf[j++] = dbcsCode >> 8; // high byte
  68081. newBuf[j++] = dbcsCode & 0xFF; // low byte
  68082. }
  68083. else {
  68084. newBuf[j++] = dbcsCode >> 16;
  68085. newBuf[j++] = (dbcsCode >> 8) & 0xFF;
  68086. newBuf[j++] = dbcsCode & 0xFF;
  68087. }
  68088. }
  68089. this.seqObj = seqObj;
  68090. this.leadSurrogate = leadSurrogate;
  68091. return newBuf.slice(0, j);
  68092. }
  68093. DBCSEncoder.prototype.end = function() {
  68094. if (this.leadSurrogate === -1 && this.seqObj === undefined)
  68095. return; // All clean. Most often case.
  68096. var newBuf = Buffer.alloc(10), j = 0;
  68097. if (this.seqObj) { // We're in the sequence.
  68098. var dbcsCode = this.seqObj[DEF_CHAR];
  68099. if (dbcsCode !== undefined) { // Write beginning of the sequence.
  68100. if (dbcsCode < 0x100) {
  68101. newBuf[j++] = dbcsCode;
  68102. }
  68103. else {
  68104. newBuf[j++] = dbcsCode >> 8; // high byte
  68105. newBuf[j++] = dbcsCode & 0xFF; // low byte
  68106. }
  68107. } else {
  68108. // See todo above.
  68109. }
  68110. this.seqObj = undefined;
  68111. }
  68112. if (this.leadSurrogate !== -1) {
  68113. // Incomplete surrogate pair - only lead surrogate found.
  68114. newBuf[j++] = this.defaultCharSingleByte;
  68115. this.leadSurrogate = -1;
  68116. }
  68117. return newBuf.slice(0, j);
  68118. }
  68119. // Export for testing
  68120. DBCSEncoder.prototype.findIdx = findIdx;
  68121. // == Decoder ==================================================================
  68122. function DBCSDecoder(options, codec) {
  68123. // Decoder state
  68124. this.nodeIdx = 0;
  68125. this.prevBuf = Buffer.alloc(0);
  68126. // Static data
  68127. this.decodeTables = codec.decodeTables;
  68128. this.decodeTableSeq = codec.decodeTableSeq;
  68129. this.defaultCharUnicode = codec.defaultCharUnicode;
  68130. this.gb18030 = codec.gb18030;
  68131. }
  68132. DBCSDecoder.prototype.write = function(buf) {
  68133. var newBuf = Buffer.alloc(buf.length*2),
  68134. nodeIdx = this.nodeIdx,
  68135. prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length,
  68136. seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence.
  68137. uCode;
  68138. if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later.
  68139. prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]);
  68140. for (var i = 0, j = 0; i < buf.length; i++) {
  68141. var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];
  68142. // Lookup in current trie node.
  68143. var uCode = this.decodeTables[nodeIdx][curByte];
  68144. if (uCode >= 0) {
  68145. // Normal character, just use it.
  68146. }
  68147. else if (uCode === UNASSIGNED) { // Unknown char.
  68148. // TODO: Callback with seq.
  68149. //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
  68150. i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle).
  68151. uCode = this.defaultCharUnicode.charCodeAt(0);
  68152. }
  68153. else if (uCode === GB18030_CODE) {
  68154. var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
  68155. var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30);
  68156. var idx = findIdx(this.gb18030.gbChars, ptr);
  68157. uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
  68158. }
  68159. else if (uCode <= NODE_START) { // Go to next trie node.
  68160. nodeIdx = NODE_START - uCode;
  68161. continue;
  68162. }
  68163. else if (uCode <= SEQ_START) { // Output a sequence of chars.
  68164. var seq = this.decodeTableSeq[SEQ_START - uCode];
  68165. for (var k = 0; k < seq.length - 1; k++) {
  68166. uCode = seq[k];
  68167. newBuf[j++] = uCode & 0xFF;
  68168. newBuf[j++] = uCode >> 8;
  68169. }
  68170. uCode = seq[seq.length-1];
  68171. }
  68172. else
  68173. throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
  68174. // Write the character to buffer, handling higher planes using surrogate pair.
  68175. if (uCode > 0xFFFF) {
  68176. uCode -= 0x10000;
  68177. var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);
  68178. newBuf[j++] = uCodeLead & 0xFF;
  68179. newBuf[j++] = uCodeLead >> 8;
  68180. uCode = 0xDC00 + uCode % 0x400;
  68181. }
  68182. newBuf[j++] = uCode & 0xFF;
  68183. newBuf[j++] = uCode >> 8;
  68184. // Reset trie node.
  68185. nodeIdx = 0; seqStart = i+1;
  68186. }
  68187. this.nodeIdx = nodeIdx;
  68188. this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
  68189. return newBuf.slice(0, j).toString('ucs2');
  68190. }
  68191. DBCSDecoder.prototype.end = function() {
  68192. var ret = '';
  68193. // Try to parse all remaining chars.
  68194. while (this.prevBuf.length > 0) {
  68195. // Skip 1 character in the buffer.
  68196. ret += this.defaultCharUnicode;
  68197. var buf = this.prevBuf.slice(1);
  68198. // Parse remaining as usual.
  68199. this.prevBuf = Buffer.alloc(0);
  68200. this.nodeIdx = 0;
  68201. if (buf.length > 0)
  68202. ret += this.write(buf);
  68203. }
  68204. this.nodeIdx = 0;
  68205. return ret;
  68206. }
  68207. // Binary search for GB18030. Returns largest i such that table[i] <= val.
  68208. function findIdx(table, val) {
  68209. if (table[0] > val)
  68210. return -1;
  68211. var l = 0, r = table.length;
  68212. while (l < r-1) { // always table[l] <= val < table[r]
  68213. var mid = l + Math.floor((r-l+1)/2);
  68214. if (table[mid] <= val)
  68215. l = mid;
  68216. else
  68217. r = mid;
  68218. }
  68219. return l;
  68220. }
  68221. },{"safer-buffer":562}],375:[function(require,module,exports){
  68222. "use strict";
  68223. // Description of supported double byte encodings and aliases.
  68224. // Tables are not require()-d until they are needed to speed up library load.
  68225. // require()-s are direct to support Browserify.
  68226. module.exports = {
  68227. // == Japanese/ShiftJIS ====================================================
  68228. // All japanese encodings are based on JIS X set of standards:
  68229. // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
  68230. // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes.
  68231. // Has several variations in 1978, 1983, 1990 and 1997.
  68232. // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
  68233. // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
  68234. // 2 planes, first is superset of 0208, second - revised 0212.
  68235. // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
  68236. // Byte encodings are:
  68237. // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
  68238. // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
  68239. // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
  68240. // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes.
  68241. // 0x00-0x7F - lower part of 0201
  68242. // 0x8E, 0xA1-0xDF - upper part of 0201
  68243. // (0xA1-0xFE)x2 - 0208 plane (94x94).
  68244. // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
  68245. // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
  68246. // Used as-is in ISO2022 family.
  68247. // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII,
  68248. // 0201-1976 Roman, 0208-1978, 0208-1983.
  68249. // * ISO2022-JP-1: Adds esc seq for 0212-1990.
  68250. // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
  68251. // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
  68252. // * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
  68253. //
  68254. // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
  68255. //
  68256. // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
  68257. 'shiftjis': {
  68258. type: '_dbcs',
  68259. table: function() { return require('./tables/shiftjis.json') },
  68260. encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
  68261. encodeSkipVals: [{from: 0xED40, to: 0xF940}],
  68262. },
  68263. 'csshiftjis': 'shiftjis',
  68264. 'mskanji': 'shiftjis',
  68265. 'sjis': 'shiftjis',
  68266. 'windows31j': 'shiftjis',
  68267. 'ms31j': 'shiftjis',
  68268. 'xsjis': 'shiftjis',
  68269. 'windows932': 'shiftjis',
  68270. 'ms932': 'shiftjis',
  68271. '932': 'shiftjis',
  68272. 'cp932': 'shiftjis',
  68273. 'eucjp': {
  68274. type: '_dbcs',
  68275. table: function() { return require('./tables/eucjp.json') },
  68276. encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
  68277. },
  68278. // TODO: KDDI extension to Shift_JIS
  68279. // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
  68280. // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
  68281. // == Chinese/GBK ==========================================================
  68282. // http://en.wikipedia.org/wiki/GBK
  68283. // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
  68284. // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
  68285. 'gb2312': 'cp936',
  68286. 'gb231280': 'cp936',
  68287. 'gb23121980': 'cp936',
  68288. 'csgb2312': 'cp936',
  68289. 'csiso58gb231280': 'cp936',
  68290. 'euccn': 'cp936',
  68291. // Microsoft's CP936 is a subset and approximation of GBK.
  68292. 'windows936': 'cp936',
  68293. 'ms936': 'cp936',
  68294. '936': 'cp936',
  68295. 'cp936': {
  68296. type: '_dbcs',
  68297. table: function() { return require('./tables/cp936.json') },
  68298. },
  68299. // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
  68300. 'gbk': {
  68301. type: '_dbcs',
  68302. table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
  68303. },
  68304. 'xgbk': 'gbk',
  68305. 'isoir58': 'gbk',
  68306. // GB18030 is an algorithmic extension of GBK.
  68307. // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
  68308. // http://icu-project.org/docs/papers/gb18030.html
  68309. // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
  68310. // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
  68311. 'gb18030': {
  68312. type: '_dbcs',
  68313. table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
  68314. gb18030: function() { return require('./tables/gb18030-ranges.json') },
  68315. encodeSkipVals: [0x80],
  68316. encodeAdd: {'€': 0xA2E3},
  68317. },
  68318. 'chinese': 'gb18030',
  68319. // == Korean ===============================================================
  68320. // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
  68321. 'windows949': 'cp949',
  68322. 'ms949': 'cp949',
  68323. '949': 'cp949',
  68324. 'cp949': {
  68325. type: '_dbcs',
  68326. table: function() { return require('./tables/cp949.json') },
  68327. },
  68328. 'cseuckr': 'cp949',
  68329. 'csksc56011987': 'cp949',
  68330. 'euckr': 'cp949',
  68331. 'isoir149': 'cp949',
  68332. 'korean': 'cp949',
  68333. 'ksc56011987': 'cp949',
  68334. 'ksc56011989': 'cp949',
  68335. 'ksc5601': 'cp949',
  68336. // == Big5/Taiwan/Hong Kong ================================================
  68337. // There are lots of tables for Big5 and cp950. Please see the following links for history:
  68338. // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
  68339. // Variations, in roughly number of defined chars:
  68340. // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
  68341. // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
  68342. // * Big5-2003 (Taiwan standard) almost superset of cp950.
  68343. // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
  68344. // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard.
  68345. // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
  68346. // Plus, it has 4 combining sequences.
  68347. // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
  68348. // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
  68349. // Implementations are not consistent within browsers; sometimes labeled as just big5.
  68350. // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
  68351. // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
  68352. // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
  68353. // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
  68354. // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
  68355. //
  68356. // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
  68357. // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
  68358. 'windows950': 'cp950',
  68359. 'ms950': 'cp950',
  68360. '950': 'cp950',
  68361. 'cp950': {
  68362. type: '_dbcs',
  68363. table: function() { return require('./tables/cp950.json') },
  68364. },
  68365. // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
  68366. 'big5': 'big5hkscs',
  68367. 'big5hkscs': {
  68368. type: '_dbcs',
  68369. table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) },
  68370. encodeSkipVals: [0xa2cc],
  68371. },
  68372. 'cnbig5': 'big5hkscs',
  68373. 'csbig5': 'big5hkscs',
  68374. 'xxbig5': 'big5hkscs',
  68375. };
  68376. },{"./tables/big5-added.json":381,"./tables/cp936.json":382,"./tables/cp949.json":383,"./tables/cp950.json":384,"./tables/eucjp.json":385,"./tables/gb18030-ranges.json":386,"./tables/gbk-added.json":387,"./tables/shiftjis.json":388}],376:[function(require,module,exports){
  68377. "use strict";
  68378. // Update this array if you add/rename/remove files in this directory.
  68379. // We support Browserify by skipping automatic module discovery and requiring modules directly.
  68380. var modules = [
  68381. require("./internal"),
  68382. require("./utf32"),
  68383. require("./utf16"),
  68384. require("./utf7"),
  68385. require("./sbcs-codec"),
  68386. require("./sbcs-data"),
  68387. require("./sbcs-data-generated"),
  68388. require("./dbcs-codec"),
  68389. require("./dbcs-data"),
  68390. ];
  68391. // Put all encoding/alias/codec definitions to single object and export it.
  68392. for (var i = 0; i < modules.length; i++) {
  68393. var module = modules[i];
  68394. for (var enc in module)
  68395. if (Object.prototype.hasOwnProperty.call(module, enc))
  68396. exports[enc] = module[enc];
  68397. }
  68398. },{"./dbcs-codec":374,"./dbcs-data":375,"./internal":377,"./sbcs-codec":378,"./sbcs-data":380,"./sbcs-data-generated":379,"./utf16":389,"./utf32":390,"./utf7":391}],377:[function(require,module,exports){
  68399. "use strict";
  68400. var Buffer = require("safer-buffer").Buffer;
  68401. // Export Node.js internal encodings.
  68402. module.exports = {
  68403. // Encodings
  68404. utf8: { type: "_internal", bomAware: true},
  68405. cesu8: { type: "_internal", bomAware: true},
  68406. unicode11utf8: "utf8",
  68407. ucs2: { type: "_internal", bomAware: true},
  68408. utf16le: "ucs2",
  68409. binary: { type: "_internal" },
  68410. base64: { type: "_internal" },
  68411. hex: { type: "_internal" },
  68412. // Codec.
  68413. _internal: InternalCodec,
  68414. };
  68415. //------------------------------------------------------------------------------
  68416. function InternalCodec(codecOptions, iconv) {
  68417. this.enc = codecOptions.encodingName;
  68418. this.bomAware = codecOptions.bomAware;
  68419. if (this.enc === "base64")
  68420. this.encoder = InternalEncoderBase64;
  68421. else if (this.enc === "cesu8") {
  68422. this.enc = "utf8"; // Use utf8 for decoding.
  68423. this.encoder = InternalEncoderCesu8;
  68424. // Add decoder for versions of Node not supporting CESU-8
  68425. if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
  68426. this.decoder = InternalDecoderCesu8;
  68427. this.defaultCharUnicode = iconv.defaultCharUnicode;
  68428. }
  68429. }
  68430. }
  68431. InternalCodec.prototype.encoder = InternalEncoder;
  68432. InternalCodec.prototype.decoder = InternalDecoder;
  68433. //------------------------------------------------------------------------------
  68434. // We use node.js internal decoder. Its signature is the same as ours.
  68435. var StringDecoder = require('string_decoder').StringDecoder;
  68436. if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
  68437. StringDecoder.prototype.end = function() {};
  68438. function InternalDecoder(options, codec) {
  68439. StringDecoder.call(this, codec.enc);
  68440. }
  68441. InternalDecoder.prototype = StringDecoder.prototype;
  68442. //------------------------------------------------------------------------------
  68443. // Encoder is mostly trivial
  68444. function InternalEncoder(options, codec) {
  68445. this.enc = codec.enc;
  68446. }
  68447. InternalEncoder.prototype.write = function(str) {
  68448. return Buffer.from(str, this.enc);
  68449. }
  68450. InternalEncoder.prototype.end = function() {
  68451. }
  68452. //------------------------------------------------------------------------------
  68453. // Except base64 encoder, which must keep its state.
  68454. function InternalEncoderBase64(options, codec) {
  68455. this.prevStr = '';
  68456. }
  68457. InternalEncoderBase64.prototype.write = function(str) {
  68458. str = this.prevStr + str;
  68459. var completeQuads = str.length - (str.length % 4);
  68460. this.prevStr = str.slice(completeQuads);
  68461. str = str.slice(0, completeQuads);
  68462. return Buffer.from(str, "base64");
  68463. }
  68464. InternalEncoderBase64.prototype.end = function() {
  68465. return Buffer.from(this.prevStr, "base64");
  68466. }
  68467. //------------------------------------------------------------------------------
  68468. // CESU-8 encoder is also special.
  68469. function InternalEncoderCesu8(options, codec) {
  68470. }
  68471. InternalEncoderCesu8.prototype.write = function(str) {
  68472. var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
  68473. for (var i = 0; i < str.length; i++) {
  68474. var charCode = str.charCodeAt(i);
  68475. // Naive implementation, but it works because CESU-8 is especially easy
  68476. // to convert from UTF-16 (which all JS strings are encoded in).
  68477. if (charCode < 0x80)
  68478. buf[bufIdx++] = charCode;
  68479. else if (charCode < 0x800) {
  68480. buf[bufIdx++] = 0xC0 + (charCode >>> 6);
  68481. buf[bufIdx++] = 0x80 + (charCode & 0x3f);
  68482. }
  68483. else { // charCode will always be < 0x10000 in javascript.
  68484. buf[bufIdx++] = 0xE0 + (charCode >>> 12);
  68485. buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
  68486. buf[bufIdx++] = 0x80 + (charCode & 0x3f);
  68487. }
  68488. }
  68489. return buf.slice(0, bufIdx);
  68490. }
  68491. InternalEncoderCesu8.prototype.end = function() {
  68492. }
  68493. //------------------------------------------------------------------------------
  68494. // CESU-8 decoder is not implemented in Node v4.0+
  68495. function InternalDecoderCesu8(options, codec) {
  68496. this.acc = 0;
  68497. this.contBytes = 0;
  68498. this.accBytes = 0;
  68499. this.defaultCharUnicode = codec.defaultCharUnicode;
  68500. }
  68501. InternalDecoderCesu8.prototype.write = function(buf) {
  68502. var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes,
  68503. res = '';
  68504. for (var i = 0; i < buf.length; i++) {
  68505. var curByte = buf[i];
  68506. if ((curByte & 0xC0) !== 0x80) { // Leading byte
  68507. if (contBytes > 0) { // Previous code is invalid
  68508. res += this.defaultCharUnicode;
  68509. contBytes = 0;
  68510. }
  68511. if (curByte < 0x80) { // Single-byte code
  68512. res += String.fromCharCode(curByte);
  68513. } else if (curByte < 0xE0) { // Two-byte code
  68514. acc = curByte & 0x1F;
  68515. contBytes = 1; accBytes = 1;
  68516. } else if (curByte < 0xF0) { // Three-byte code
  68517. acc = curByte & 0x0F;
  68518. contBytes = 2; accBytes = 1;
  68519. } else { // Four or more are not supported for CESU-8.
  68520. res += this.defaultCharUnicode;
  68521. }
  68522. } else { // Continuation byte
  68523. if (contBytes > 0) { // We're waiting for it.
  68524. acc = (acc << 6) | (curByte & 0x3f);
  68525. contBytes--; accBytes++;
  68526. if (contBytes === 0) {
  68527. // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
  68528. if (accBytes === 2 && acc < 0x80 && acc > 0)
  68529. res += this.defaultCharUnicode;
  68530. else if (accBytes === 3 && acc < 0x800)
  68531. res += this.defaultCharUnicode;
  68532. else
  68533. // Actually add character.
  68534. res += String.fromCharCode(acc);
  68535. }
  68536. } else { // Unexpected continuation byte
  68537. res += this.defaultCharUnicode;
  68538. }
  68539. }
  68540. }
  68541. this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
  68542. return res;
  68543. }
  68544. InternalDecoderCesu8.prototype.end = function() {
  68545. var res = 0;
  68546. if (this.contBytes > 0)
  68547. res += this.defaultCharUnicode;
  68548. return res;
  68549. }
  68550. },{"safer-buffer":562,"string_decoder":631}],378:[function(require,module,exports){
  68551. "use strict";
  68552. var Buffer = require("safer-buffer").Buffer;
  68553. // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
  68554. // correspond to encoded bytes (if 128 - then lower half is ASCII).
  68555. exports._sbcs = SBCSCodec;
  68556. function SBCSCodec(codecOptions, iconv) {
  68557. if (!codecOptions)
  68558. throw new Error("SBCS codec is called without the data.")
  68559. // Prepare char buffer for decoding.
  68560. if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
  68561. throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
  68562. if (codecOptions.chars.length === 128) {
  68563. var asciiString = "";
  68564. for (var i = 0; i < 128; i++)
  68565. asciiString += String.fromCharCode(i);
  68566. codecOptions.chars = asciiString + codecOptions.chars;
  68567. }
  68568. this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
  68569. // Encoding buffer.
  68570. var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
  68571. for (var i = 0; i < codecOptions.chars.length; i++)
  68572. encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
  68573. this.encodeBuf = encodeBuf;
  68574. }
  68575. SBCSCodec.prototype.encoder = SBCSEncoder;
  68576. SBCSCodec.prototype.decoder = SBCSDecoder;
  68577. function SBCSEncoder(options, codec) {
  68578. this.encodeBuf = codec.encodeBuf;
  68579. }
  68580. SBCSEncoder.prototype.write = function(str) {
  68581. var buf = Buffer.alloc(str.length);
  68582. for (var i = 0; i < str.length; i++)
  68583. buf[i] = this.encodeBuf[str.charCodeAt(i)];
  68584. return buf;
  68585. }
  68586. SBCSEncoder.prototype.end = function() {
  68587. }
  68588. function SBCSDecoder(options, codec) {
  68589. this.decodeBuf = codec.decodeBuf;
  68590. }
  68591. SBCSDecoder.prototype.write = function(buf) {
  68592. // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
  68593. var decodeBuf = this.decodeBuf;
  68594. var newBuf = Buffer.alloc(buf.length*2);
  68595. var idx1 = 0, idx2 = 0;
  68596. for (var i = 0; i < buf.length; i++) {
  68597. idx1 = buf[i]*2; idx2 = i*2;
  68598. newBuf[idx2] = decodeBuf[idx1];
  68599. newBuf[idx2+1] = decodeBuf[idx1+1];
  68600. }
  68601. return newBuf.toString('ucs2');
  68602. }
  68603. SBCSDecoder.prototype.end = function() {
  68604. }
  68605. },{"safer-buffer":562}],379:[function(require,module,exports){
  68606. "use strict";
  68607. // Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
  68608. module.exports = {
  68609. "437": "cp437",
  68610. "737": "cp737",
  68611. "775": "cp775",
  68612. "850": "cp850",
  68613. "852": "cp852",
  68614. "855": "cp855",
  68615. "856": "cp856",
  68616. "857": "cp857",
  68617. "858": "cp858",
  68618. "860": "cp860",
  68619. "861": "cp861",
  68620. "862": "cp862",
  68621. "863": "cp863",
  68622. "864": "cp864",
  68623. "865": "cp865",
  68624. "866": "cp866",
  68625. "869": "cp869",
  68626. "874": "windows874",
  68627. "922": "cp922",
  68628. "1046": "cp1046",
  68629. "1124": "cp1124",
  68630. "1125": "cp1125",
  68631. "1129": "cp1129",
  68632. "1133": "cp1133",
  68633. "1161": "cp1161",
  68634. "1162": "cp1162",
  68635. "1163": "cp1163",
  68636. "1250": "windows1250",
  68637. "1251": "windows1251",
  68638. "1252": "windows1252",
  68639. "1253": "windows1253",
  68640. "1254": "windows1254",
  68641. "1255": "windows1255",
  68642. "1256": "windows1256",
  68643. "1257": "windows1257",
  68644. "1258": "windows1258",
  68645. "28591": "iso88591",
  68646. "28592": "iso88592",
  68647. "28593": "iso88593",
  68648. "28594": "iso88594",
  68649. "28595": "iso88595",
  68650. "28596": "iso88596",
  68651. "28597": "iso88597",
  68652. "28598": "iso88598",
  68653. "28599": "iso88599",
  68654. "28600": "iso885910",
  68655. "28601": "iso885911",
  68656. "28603": "iso885913",
  68657. "28604": "iso885914",
  68658. "28605": "iso885915",
  68659. "28606": "iso885916",
  68660. "windows874": {
  68661. "type": "_sbcs",
  68662. "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  68663. },
  68664. "win874": "windows874",
  68665. "cp874": "windows874",
  68666. "windows1250": {
  68667. "type": "_sbcs",
  68668. "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
  68669. },
  68670. "win1250": "windows1250",
  68671. "cp1250": "windows1250",
  68672. "windows1251": {
  68673. "type": "_sbcs",
  68674. "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
  68675. },
  68676. "win1251": "windows1251",
  68677. "cp1251": "windows1251",
  68678. "windows1252": {
  68679. "type": "_sbcs",
  68680. "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  68681. },
  68682. "win1252": "windows1252",
  68683. "cp1252": "windows1252",
  68684. "windows1253": {
  68685. "type": "_sbcs",
  68686. "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
  68687. },
  68688. "win1253": "windows1253",
  68689. "cp1253": "windows1253",
  68690. "windows1254": {
  68691. "type": "_sbcs",
  68692. "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
  68693. },
  68694. "win1254": "windows1254",
  68695. "cp1254": "windows1254",
  68696. "windows1255": {
  68697. "type": "_sbcs",
  68698. "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
  68699. },
  68700. "win1255": "windows1255",
  68701. "cp1255": "windows1255",
  68702. "windows1256": {
  68703. "type": "_sbcs",
  68704. "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"
  68705. },
  68706. "win1256": "windows1256",
  68707. "cp1256": "windows1256",
  68708. "windows1257": {
  68709. "type": "_sbcs",
  68710. "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
  68711. },
  68712. "win1257": "windows1257",
  68713. "cp1257": "windows1257",
  68714. "windows1258": {
  68715. "type": "_sbcs",
  68716. "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
  68717. },
  68718. "win1258": "windows1258",
  68719. "cp1258": "windows1258",
  68720. "iso88591": {
  68721. "type": "_sbcs",
  68722. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  68723. },
  68724. "cp28591": "iso88591",
  68725. "iso88592": {
  68726. "type": "_sbcs",
  68727. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
  68728. },
  68729. "cp28592": "iso88592",
  68730. "iso88593": {
  68731. "type": "_sbcs",
  68732. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
  68733. },
  68734. "cp28593": "iso88593",
  68735. "iso88594": {
  68736. "type": "_sbcs",
  68737. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
  68738. },
  68739. "cp28594": "iso88594",
  68740. "iso88595": {
  68741. "type": "_sbcs",
  68742. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
  68743. },
  68744. "cp28595": "iso88595",
  68745. "iso88596": {
  68746. "type": "_sbcs",
  68747. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
  68748. },
  68749. "cp28596": "iso88596",
  68750. "iso88597": {
  68751. "type": "_sbcs",
  68752. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
  68753. },
  68754. "cp28597": "iso88597",
  68755. "iso88598": {
  68756. "type": "_sbcs",
  68757. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
  68758. },
  68759. "cp28598": "iso88598",
  68760. "iso88599": {
  68761. "type": "_sbcs",
  68762. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
  68763. },
  68764. "cp28599": "iso88599",
  68765. "iso885910": {
  68766. "type": "_sbcs",
  68767. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
  68768. },
  68769. "cp28600": "iso885910",
  68770. "iso885911": {
  68771. "type": "_sbcs",
  68772. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  68773. },
  68774. "cp28601": "iso885911",
  68775. "iso885913": {
  68776. "type": "_sbcs",
  68777. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
  68778. },
  68779. "cp28603": "iso885913",
  68780. "iso885914": {
  68781. "type": "_sbcs",
  68782. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
  68783. },
  68784. "cp28604": "iso885914",
  68785. "iso885915": {
  68786. "type": "_sbcs",
  68787. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  68788. },
  68789. "cp28605": "iso885915",
  68790. "iso885916": {
  68791. "type": "_sbcs",
  68792. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
  68793. },
  68794. "cp28606": "iso885916",
  68795. "cp437": {
  68796. "type": "_sbcs",
  68797. "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  68798. },
  68799. "ibm437": "cp437",
  68800. "csibm437": "cp437",
  68801. "cp737": {
  68802. "type": "_sbcs",
  68803. "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
  68804. },
  68805. "ibm737": "cp737",
  68806. "csibm737": "cp737",
  68807. "cp775": {
  68808. "type": "_sbcs",
  68809. "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "
  68810. },
  68811. "ibm775": "cp775",
  68812. "csibm775": "cp775",
  68813. "cp850": {
  68814. "type": "_sbcs",
  68815. "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
  68816. },
  68817. "ibm850": "cp850",
  68818. "csibm850": "cp850",
  68819. "cp852": {
  68820. "type": "_sbcs",
  68821. "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "
  68822. },
  68823. "ibm852": "cp852",
  68824. "csibm852": "cp852",
  68825. "cp855": {
  68826. "type": "_sbcs",
  68827. "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "
  68828. },
  68829. "ibm855": "cp855",
  68830. "csibm855": "cp855",
  68831. "cp856": {
  68832. "type": "_sbcs",
  68833. "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "
  68834. },
  68835. "ibm856": "cp856",
  68836. "csibm856": "cp856",
  68837. "cp857": {
  68838. "type": "_sbcs",
  68839. "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "
  68840. },
  68841. "ibm857": "cp857",
  68842. "csibm857": "cp857",
  68843. "cp858": {
  68844. "type": "_sbcs",
  68845. "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
  68846. },
  68847. "ibm858": "cp858",
  68848. "csibm858": "cp858",
  68849. "cp860": {
  68850. "type": "_sbcs",
  68851. "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  68852. },
  68853. "ibm860": "cp860",
  68854. "csibm860": "cp860",
  68855. "cp861": {
  68856. "type": "_sbcs",
  68857. "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  68858. },
  68859. "ibm861": "cp861",
  68860. "csibm861": "cp861",
  68861. "cp862": {
  68862. "type": "_sbcs",
  68863. "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  68864. },
  68865. "ibm862": "cp862",
  68866. "csibm862": "cp862",
  68867. "cp863": {
  68868. "type": "_sbcs",
  68869. "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  68870. },
  68871. "ibm863": "cp863",
  68872. "csibm863": "cp863",
  68873. "cp864": {
  68874. "type": "_sbcs",
  68875. "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
  68876. },
  68877. "ibm864": "cp864",
  68878. "csibm864": "cp864",
  68879. "cp865": {
  68880. "type": "_sbcs",
  68881. "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  68882. },
  68883. "ibm865": "cp865",
  68884. "csibm865": "cp865",
  68885. "cp866": {
  68886. "type": "_sbcs",
  68887. "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
  68888. },
  68889. "ibm866": "cp866",
  68890. "csibm866": "cp866",
  68891. "cp869": {
  68892. "type": "_sbcs",
  68893. "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "
  68894. },
  68895. "ibm869": "cp869",
  68896. "csibm869": "cp869",
  68897. "cp922": {
  68898. "type": "_sbcs",
  68899. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
  68900. },
  68901. "ibm922": "cp922",
  68902. "csibm922": "cp922",
  68903. "cp1046": {
  68904. "type": "_sbcs",
  68905. "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
  68906. },
  68907. "ibm1046": "cp1046",
  68908. "csibm1046": "cp1046",
  68909. "cp1124": {
  68910. "type": "_sbcs",
  68911. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
  68912. },
  68913. "ibm1124": "cp1124",
  68914. "csibm1124": "cp1124",
  68915. "cp1125": {
  68916. "type": "_sbcs",
  68917. "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
  68918. },
  68919. "ibm1125": "cp1125",
  68920. "csibm1125": "cp1125",
  68921. "cp1129": {
  68922. "type": "_sbcs",
  68923. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
  68924. },
  68925. "ibm1129": "cp1129",
  68926. "csibm1129": "cp1129",
  68927. "cp1133": {
  68928. "type": "_sbcs",
  68929. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
  68930. },
  68931. "ibm1133": "cp1133",
  68932. "csibm1133": "cp1133",
  68933. "cp1161": {
  68934. "type": "_sbcs",
  68935. "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
  68936. },
  68937. "ibm1161": "cp1161",
  68938. "csibm1161": "cp1161",
  68939. "cp1162": {
  68940. "type": "_sbcs",
  68941. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  68942. },
  68943. "ibm1162": "cp1162",
  68944. "csibm1162": "cp1162",
  68945. "cp1163": {
  68946. "type": "_sbcs",
  68947. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
  68948. },
  68949. "ibm1163": "cp1163",
  68950. "csibm1163": "cp1163",
  68951. "maccroatian": {
  68952. "type": "_sbcs",
  68953. "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
  68954. },
  68955. "maccyrillic": {
  68956. "type": "_sbcs",
  68957. "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
  68958. },
  68959. "macgreek": {
  68960. "type": "_sbcs",
  68961. "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
  68962. },
  68963. "maciceland": {
  68964. "type": "_sbcs",
  68965. "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  68966. },
  68967. "macroman": {
  68968. "type": "_sbcs",
  68969. "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  68970. },
  68971. "macromania": {
  68972. "type": "_sbcs",
  68973. "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  68974. },
  68975. "macthai": {
  68976. "type": "_sbcs",
  68977. "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
  68978. },
  68979. "macturkish": {
  68980. "type": "_sbcs",
  68981. "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
  68982. },
  68983. "macukraine": {
  68984. "type": "_sbcs",
  68985. "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
  68986. },
  68987. "koi8r": {
  68988. "type": "_sbcs",
  68989. "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  68990. },
  68991. "koi8u": {
  68992. "type": "_sbcs",
  68993. "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  68994. },
  68995. "koi8ru": {
  68996. "type": "_sbcs",
  68997. "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  68998. },
  68999. "koi8t": {
  69000. "type": "_sbcs",
  69001. "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
  69002. },
  69003. "armscii8": {
  69004. "type": "_sbcs",
  69005. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
  69006. },
  69007. "rk1048": {
  69008. "type": "_sbcs",
  69009. "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
  69010. },
  69011. "tcvn": {
  69012. "type": "_sbcs",
  69013. "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
  69014. },
  69015. "georgianacademy": {
  69016. "type": "_sbcs",
  69017. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  69018. },
  69019. "georgianps": {
  69020. "type": "_sbcs",
  69021. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
  69022. },
  69023. "pt154": {
  69024. "type": "_sbcs",
  69025. "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
  69026. },
  69027. "viscii": {
  69028. "type": "_sbcs",
  69029. "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
  69030. },
  69031. "iso646cn": {
  69032. "type": "_sbcs",
  69033. "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
  69034. },
  69035. "iso646jp": {
  69036. "type": "_sbcs",
  69037. "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
  69038. },
  69039. "hproman8": {
  69040. "type": "_sbcs",
  69041. "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
  69042. },
  69043. "macintosh": {
  69044. "type": "_sbcs",
  69045. "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
  69046. },
  69047. "ascii": {
  69048. "type": "_sbcs",
  69049. "chars": "��������������������������������������������������������������������������������������������������������������������������������"
  69050. },
  69051. "tis620": {
  69052. "type": "_sbcs",
  69053. "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
  69054. }
  69055. }
  69056. },{}],380:[function(require,module,exports){
  69057. "use strict";
  69058. // Manually added data to be used by sbcs codec in addition to generated one.
  69059. module.exports = {
  69060. // Not supported by iconv, not sure why.
  69061. "10029": "maccenteuro",
  69062. "maccenteuro": {
  69063. "type": "_sbcs",
  69064. "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
  69065. },
  69066. "808": "cp808",
  69067. "ibm808": "cp808",
  69068. "cp808": {
  69069. "type": "_sbcs",
  69070. "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
  69071. },
  69072. "mik": {
  69073. "type": "_sbcs",
  69074. "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
  69075. },
  69076. "cp720": {
  69077. "type": "_sbcs",
  69078. "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0"
  69079. },
  69080. // Aliases of generated encodings.
  69081. "ascii8bit": "ascii",
  69082. "usascii": "ascii",
  69083. "ansix34": "ascii",
  69084. "ansix341968": "ascii",
  69085. "ansix341986": "ascii",
  69086. "csascii": "ascii",
  69087. "cp367": "ascii",
  69088. "ibm367": "ascii",
  69089. "isoir6": "ascii",
  69090. "iso646us": "ascii",
  69091. "iso646irv": "ascii",
  69092. "us": "ascii",
  69093. "latin1": "iso88591",
  69094. "latin2": "iso88592",
  69095. "latin3": "iso88593",
  69096. "latin4": "iso88594",
  69097. "latin5": "iso88599",
  69098. "latin6": "iso885910",
  69099. "latin7": "iso885913",
  69100. "latin8": "iso885914",
  69101. "latin9": "iso885915",
  69102. "latin10": "iso885916",
  69103. "csisolatin1": "iso88591",
  69104. "csisolatin2": "iso88592",
  69105. "csisolatin3": "iso88593",
  69106. "csisolatin4": "iso88594",
  69107. "csisolatincyrillic": "iso88595",
  69108. "csisolatinarabic": "iso88596",
  69109. "csisolatingreek" : "iso88597",
  69110. "csisolatinhebrew": "iso88598",
  69111. "csisolatin5": "iso88599",
  69112. "csisolatin6": "iso885910",
  69113. "l1": "iso88591",
  69114. "l2": "iso88592",
  69115. "l3": "iso88593",
  69116. "l4": "iso88594",
  69117. "l5": "iso88599",
  69118. "l6": "iso885910",
  69119. "l7": "iso885913",
  69120. "l8": "iso885914",
  69121. "l9": "iso885915",
  69122. "l10": "iso885916",
  69123. "isoir14": "iso646jp",
  69124. "isoir57": "iso646cn",
  69125. "isoir100": "iso88591",
  69126. "isoir101": "iso88592",
  69127. "isoir109": "iso88593",
  69128. "isoir110": "iso88594",
  69129. "isoir144": "iso88595",
  69130. "isoir127": "iso88596",
  69131. "isoir126": "iso88597",
  69132. "isoir138": "iso88598",
  69133. "isoir148": "iso88599",
  69134. "isoir157": "iso885910",
  69135. "isoir166": "tis620",
  69136. "isoir179": "iso885913",
  69137. "isoir199": "iso885914",
  69138. "isoir203": "iso885915",
  69139. "isoir226": "iso885916",
  69140. "cp819": "iso88591",
  69141. "ibm819": "iso88591",
  69142. "cyrillic": "iso88595",
  69143. "arabic": "iso88596",
  69144. "arabic8": "iso88596",
  69145. "ecma114": "iso88596",
  69146. "asmo708": "iso88596",
  69147. "greek" : "iso88597",
  69148. "greek8" : "iso88597",
  69149. "ecma118" : "iso88597",
  69150. "elot928" : "iso88597",
  69151. "hebrew": "iso88598",
  69152. "hebrew8": "iso88598",
  69153. "turkish": "iso88599",
  69154. "turkish8": "iso88599",
  69155. "thai": "iso885911",
  69156. "thai8": "iso885911",
  69157. "celtic": "iso885914",
  69158. "celtic8": "iso885914",
  69159. "isoceltic": "iso885914",
  69160. "tis6200": "tis620",
  69161. "tis62025291": "tis620",
  69162. "tis62025330": "tis620",
  69163. "10000": "macroman",
  69164. "10006": "macgreek",
  69165. "10007": "maccyrillic",
  69166. "10079": "maciceland",
  69167. "10081": "macturkish",
  69168. "cspc8codepage437": "cp437",
  69169. "cspc775baltic": "cp775",
  69170. "cspc850multilingual": "cp850",
  69171. "cspcp852": "cp852",
  69172. "cspc862latinhebrew": "cp862",
  69173. "cpgr": "cp869",
  69174. "msee": "cp1250",
  69175. "mscyrl": "cp1251",
  69176. "msansi": "cp1252",
  69177. "msgreek": "cp1253",
  69178. "msturk": "cp1254",
  69179. "mshebr": "cp1255",
  69180. "msarab": "cp1256",
  69181. "winbaltrim": "cp1257",
  69182. "cp20866": "koi8r",
  69183. "20866": "koi8r",
  69184. "ibm878": "koi8r",
  69185. "cskoi8r": "koi8r",
  69186. "cp21866": "koi8u",
  69187. "21866": "koi8u",
  69188. "ibm1168": "koi8u",
  69189. "strk10482002": "rk1048",
  69190. "tcvn5712": "tcvn",
  69191. "tcvn57121": "tcvn",
  69192. "gb198880": "iso646cn",
  69193. "cn": "iso646cn",
  69194. "csiso14jisc6220ro": "iso646jp",
  69195. "jisc62201969ro": "iso646jp",
  69196. "jp": "iso646jp",
  69197. "cshproman8": "hproman8",
  69198. "r8": "hproman8",
  69199. "roman8": "hproman8",
  69200. "xroman8": "hproman8",
  69201. "ibm1051": "hproman8",
  69202. "mac": "macintosh",
  69203. "csmacintosh": "macintosh",
  69204. };
  69205. },{}],381:[function(require,module,exports){
  69206. module.exports=[
  69207. ["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"],
  69208. ["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"],
  69209. ["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"],
  69210. ["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"],
  69211. ["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"],
  69212. ["8940","𪎩𡅅"],
  69213. ["8943","攊"],
  69214. ["8946","丽滝鵎釟"],
  69215. ["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"],
  69216. ["89a1","琑糼緍楆竉刧"],
  69217. ["89ab","醌碸酞肼"],
  69218. ["89b0","贋胶𠧧"],
  69219. ["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"],
  69220. ["89c1","溚舾甙"],
  69221. ["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"],
  69222. ["8a40","𧶄唥"],
  69223. ["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"],
  69224. ["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"],
  69225. ["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"],
  69226. ["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"],
  69227. ["8aac","䠋𠆩㿺塳𢶍"],
  69228. ["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"],
  69229. ["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"],
  69230. ["8ac9","𪘁𠸉𢫏𢳉"],
  69231. ["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"],
  69232. ["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"],
  69233. ["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"],
  69234. ["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"],
  69235. ["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"],
  69236. ["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"],
  69237. ["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"],
  69238. ["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"],
  69239. ["8ca1","𣏹椙橃𣱣泿"],
  69240. ["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"],
  69241. ["8cc9","顨杫䉶圽"],
  69242. ["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"],
  69243. ["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"],
  69244. ["8d40","𠮟"],
  69245. ["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"],
  69246. ["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"],
  69247. ["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"],
  69248. ["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"],
  69249. ["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"],
  69250. ["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"],
  69251. ["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"],
  69252. ["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"],
  69253. ["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"],
  69254. ["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"],
  69255. ["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"],
  69256. ["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"],
  69257. ["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"],
  69258. ["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"],
  69259. ["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"],
  69260. ["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"],
  69261. ["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"],
  69262. ["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"],
  69263. ["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"],
  69264. ["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"],
  69265. ["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"],
  69266. ["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"],
  69267. ["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"],
  69268. ["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"],
  69269. ["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"],
  69270. ["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"],
  69271. ["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"],
  69272. ["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"],
  69273. ["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"],
  69274. ["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"],
  69275. ["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"],
  69276. ["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"],
  69277. ["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"],
  69278. ["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"],
  69279. ["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"],
  69280. ["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"],
  69281. ["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"],
  69282. ["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"],
  69283. ["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"],
  69284. ["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"],
  69285. ["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"],
  69286. ["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"],
  69287. ["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"],
  69288. ["9fae","酙隁酜"],
  69289. ["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"],
  69290. ["9fc1","𤤙盖鮝个𠳔莾衂"],
  69291. ["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"],
  69292. ["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"],
  69293. ["9fe7","毺蠘罸"],
  69294. ["9feb","嘠𪙊蹷齓"],
  69295. ["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"],
  69296. ["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"],
  69297. ["a055","𡠻𦸅"],
  69298. ["a058","詾𢔛"],
  69299. ["a05b","惽癧髗鵄鍮鮏蟵"],
  69300. ["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"],
  69301. ["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"],
  69302. ["a0a1","嵗𨯂迚𨸹"],
  69303. ["a0a6","僙𡵆礆匲阸𠼻䁥"],
  69304. ["a0ae","矾"],
  69305. ["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"],
  69306. ["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"],
  69307. ["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"],
  69308. ["a3c0","␀",31,"␡"],
  69309. ["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23],
  69310. ["c740","す",58,"ァアィイ"],
  69311. ["c7a1","ゥ",81,"А",5,"ЁЖ",4],
  69312. ["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"],
  69313. ["c8a1","龰冈龱𧘇"],
  69314. ["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"],
  69315. ["c8f5","ʃɐɛɔɵœøŋʊɪ"],
  69316. ["f9fe","■"],
  69317. ["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"],
  69318. ["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"],
  69319. ["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"],
  69320. ["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"],
  69321. ["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"],
  69322. ["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"],
  69323. ["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"],
  69324. ["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"],
  69325. ["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"],
  69326. ["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"]
  69327. ]
  69328. },{}],382:[function(require,module,exports){
  69329. module.exports=[
  69330. ["0","\u0000",127,"€"],
  69331. ["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"],
  69332. ["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"],
  69333. ["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11],
  69334. ["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"],
  69335. ["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"],
  69336. ["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5],
  69337. ["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"],
  69338. ["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"],
  69339. ["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"],
  69340. ["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"],
  69341. ["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"],
  69342. ["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"],
  69343. ["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4],
  69344. ["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6],
  69345. ["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"],
  69346. ["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7],
  69347. ["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"],
  69348. ["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"],
  69349. ["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"],
  69350. ["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5],
  69351. ["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"],
  69352. ["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6],
  69353. ["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"],
  69354. ["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4],
  69355. ["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4],
  69356. ["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"],
  69357. ["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"],
  69358. ["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6],
  69359. ["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"],
  69360. ["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"],
  69361. ["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"],
  69362. ["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6],
  69363. ["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"],
  69364. ["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"],
  69365. ["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"],
  69366. ["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"],
  69367. ["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"],
  69368. ["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"],
  69369. ["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8],
  69370. ["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"],
  69371. ["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"],
  69372. ["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"],
  69373. ["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"],
  69374. ["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5],
  69375. ["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"],
  69376. ["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"],
  69377. ["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"],
  69378. ["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"],
  69379. ["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5],
  69380. ["9980","檧檨檪檭",114,"欥欦欨",6],
  69381. ["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"],
  69382. ["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"],
  69383. ["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"],
  69384. ["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"],
  69385. ["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"],
  69386. ["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5],
  69387. ["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"],
  69388. ["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"],
  69389. ["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6],
  69390. ["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"],
  69391. ["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"],
  69392. ["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4],
  69393. ["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19],
  69394. ["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"],
  69395. ["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"],
  69396. ["a2a1","ⅰ",9],
  69397. ["a2b1","⒈",19,"⑴",19,"①",9],
  69398. ["a2e5","㈠",9],
  69399. ["a2f1","Ⅰ",11],
  69400. ["a3a1","!"#¥%",88," ̄"],
  69401. ["a4a1","ぁ",82],
  69402. ["a5a1","ァ",85],
  69403. ["a6a1","Α",16,"Σ",6],
  69404. ["a6c1","α",16,"σ",6],
  69405. ["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"],
  69406. ["a6ee","︻︼︷︸︱"],
  69407. ["a6f4","︳︴"],
  69408. ["a7a1","А",5,"ЁЖ",25],
  69409. ["a7d1","а",5,"ёж",25],
  69410. ["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6],
  69411. ["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"],
  69412. ["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"],
  69413. ["a8bd","ńň"],
  69414. ["a8c0","ɡ"],
  69415. ["a8c5","ㄅ",36],
  69416. ["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"],
  69417. ["a959","℡㈱"],
  69418. ["a95c","‐"],
  69419. ["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8],
  69420. ["a980","﹢",4,"﹨﹩﹪﹫"],
  69421. ["a996","〇"],
  69422. ["a9a4","─",75],
  69423. ["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8],
  69424. ["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"],
  69425. ["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4],
  69426. ["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4],
  69427. ["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11],
  69428. ["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"],
  69429. ["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12],
  69430. ["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"],
  69431. ["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"],
  69432. ["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"],
  69433. ["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"],
  69434. ["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"],
  69435. ["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"],
  69436. ["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"],
  69437. ["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"],
  69438. ["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"],
  69439. ["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4],
  69440. ["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"],
  69441. ["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"],
  69442. ["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"],
  69443. ["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9],
  69444. ["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"],
  69445. ["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"],
  69446. ["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"],
  69447. ["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"],
  69448. ["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"],
  69449. ["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16],
  69450. ["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"],
  69451. ["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"],
  69452. ["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"],
  69453. ["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"],
  69454. ["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"],
  69455. ["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"],
  69456. ["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"],
  69457. ["bb40","籃",9,"籎",36,"籵",5,"籾",9],
  69458. ["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"],
  69459. ["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5],
  69460. ["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"],
  69461. ["bd40","紷",54,"絯",7],
  69462. ["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"],
  69463. ["be40","継",12,"綧",6,"綯",42],
  69464. ["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"],
  69465. ["bf40","緻",62],
  69466. ["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"],
  69467. ["c040","繞",35,"纃",23,"纜纝纞"],
  69468. ["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"],
  69469. ["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"],
  69470. ["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"],
  69471. ["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"],
  69472. ["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"],
  69473. ["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"],
  69474. ["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"],
  69475. ["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"],
  69476. ["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"],
  69477. ["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"],
  69478. ["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"],
  69479. ["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"],
  69480. ["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"],
  69481. ["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"],
  69482. ["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"],
  69483. ["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"],
  69484. ["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"],
  69485. ["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"],
  69486. ["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"],
  69487. ["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10],
  69488. ["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"],
  69489. ["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"],
  69490. ["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"],
  69491. ["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"],
  69492. ["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"],
  69493. ["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"],
  69494. ["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"],
  69495. ["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"],
  69496. ["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"],
  69497. ["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9],
  69498. ["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"],
  69499. ["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"],
  69500. ["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"],
  69501. ["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5],
  69502. ["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"],
  69503. ["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"],
  69504. ["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"],
  69505. ["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6],
  69506. ["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"],
  69507. ["d440","訞",31,"訿",8,"詉",21],
  69508. ["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"],
  69509. ["d540","誁",7,"誋",7,"誔",46],
  69510. ["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"],
  69511. ["d640","諤",34,"謈",27],
  69512. ["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"],
  69513. ["d740","譆",31,"譧",4,"譭",25],
  69514. ["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"],
  69515. ["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"],
  69516. ["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"],
  69517. ["d940","貮",62],
  69518. ["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"],
  69519. ["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"],
  69520. ["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"],
  69521. ["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"],
  69522. ["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"],
  69523. ["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7],
  69524. ["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"],
  69525. ["dd40","軥",62],
  69526. ["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"],
  69527. ["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"],
  69528. ["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"],
  69529. ["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"],
  69530. ["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"],
  69531. ["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"],
  69532. ["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"],
  69533. ["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"],
  69534. ["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"],
  69535. ["e240","釦",62],
  69536. ["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"],
  69537. ["e340","鉆",45,"鉵",16],
  69538. ["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"],
  69539. ["e440","銨",5,"銯",24,"鋉",31],
  69540. ["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"],
  69541. ["e540","錊",51,"錿",10],
  69542. ["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"],
  69543. ["e640","鍬",34,"鎐",27],
  69544. ["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"],
  69545. ["e740","鏎",7,"鏗",54],
  69546. ["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"],
  69547. ["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"],
  69548. ["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"],
  69549. ["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42],
  69550. ["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"],
  69551. ["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"],
  69552. ["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"],
  69553. ["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"],
  69554. ["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"],
  69555. ["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7],
  69556. ["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"],
  69557. ["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46],
  69558. ["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"],
  69559. ["ee40","頏",62],
  69560. ["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"],
  69561. ["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4],
  69562. ["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"],
  69563. ["f040","餈",4,"餎餏餑",28,"餯",26],
  69564. ["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"],
  69565. ["f140","馌馎馚",10,"馦馧馩",47],
  69566. ["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"],
  69567. ["f240","駺",62],
  69568. ["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"],
  69569. ["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"],
  69570. ["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"],
  69571. ["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5],
  69572. ["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"],
  69573. ["f540","魼",62],
  69574. ["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"],
  69575. ["f640","鯜",62],
  69576. ["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"],
  69577. ["f740","鰼",62],
  69578. ["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"],
  69579. ["f840","鳣",62],
  69580. ["f880","鴢",32],
  69581. ["f940","鵃",62],
  69582. ["f980","鶂",32],
  69583. ["fa40","鶣",62],
  69584. ["fa80","鷢",32],
  69585. ["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"],
  69586. ["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"],
  69587. ["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6],
  69588. ["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"],
  69589. ["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38],
  69590. ["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"],
  69591. ["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"]
  69592. ]
  69593. },{}],383:[function(require,module,exports){
  69594. module.exports=[
  69595. ["0","\u0000",127],
  69596. ["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"],
  69597. ["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"],
  69598. ["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"],
  69599. ["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5],
  69600. ["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"],
  69601. ["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18],
  69602. ["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7],
  69603. ["8361","긝",18,"긲긳긵긶긹긻긼"],
  69604. ["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8],
  69605. ["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8],
  69606. ["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18],
  69607. ["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"],
  69608. ["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4],
  69609. ["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"],
  69610. ["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"],
  69611. ["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"],
  69612. ["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10],
  69613. ["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"],
  69614. ["8741","놞",9,"놩",15],
  69615. ["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"],
  69616. ["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4],
  69617. ["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4],
  69618. ["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"],
  69619. ["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"],
  69620. ["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"],
  69621. ["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"],
  69622. ["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15],
  69623. ["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"],
  69624. ["8a61","둧",4,"둭",18,"뒁뒂"],
  69625. ["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"],
  69626. ["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"],
  69627. ["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8],
  69628. ["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18],
  69629. ["8c41","똀",15,"똒똓똕똖똗똙",4],
  69630. ["8c61","똞",6,"똦",5,"똭",6,"똵",5],
  69631. ["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16],
  69632. ["8d41","뛃",16,"뛕",8],
  69633. ["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"],
  69634. ["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"],
  69635. ["8e41","랟랡",6,"랪랮",5,"랶랷랹",8],
  69636. ["8e61","럂",4,"럈럊",19],
  69637. ["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7],
  69638. ["8f41","뢅",7,"뢎",17],
  69639. ["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4],
  69640. ["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5],
  69641. ["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"],
  69642. ["9061","륾",5,"릆릈릋릌릏",15],
  69643. ["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"],
  69644. ["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5],
  69645. ["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5],
  69646. ["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6],
  69647. ["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"],
  69648. ["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4],
  69649. ["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"],
  69650. ["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"],
  69651. ["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8],
  69652. ["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"],
  69653. ["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8],
  69654. ["9461","봞",5,"봥",6,"봭",12],
  69655. ["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24],
  69656. ["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"],
  69657. ["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"],
  69658. ["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14],
  69659. ["9641","뺸",23,"뻒뻓"],
  69660. ["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8],
  69661. ["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44],
  69662. ["9741","뾃",16,"뾕",8],
  69663. ["9761","뾞",17,"뾱",7],
  69664. ["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"],
  69665. ["9841","쁀",16,"쁒",5,"쁙쁚쁛"],
  69666. ["9861","쁝쁞쁟쁡",6,"쁪",15],
  69667. ["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"],
  69668. ["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"],
  69669. ["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"],
  69670. ["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"],
  69671. ["9a41","숤숥숦숧숪숬숮숰숳숵",16],
  69672. ["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"],
  69673. ["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"],
  69674. ["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8],
  69675. ["9b61","쌳",17,"썆",7],
  69676. ["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"],
  69677. ["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5],
  69678. ["9c61","쏿",8,"쐉",6,"쐑",9],
  69679. ["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12],
  69680. ["9d41","쒪",13,"쒹쒺쒻쒽",8],
  69681. ["9d61","쓆",25],
  69682. ["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"],
  69683. ["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"],
  69684. ["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"],
  69685. ["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"],
  69686. ["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"],
  69687. ["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"],
  69688. ["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"],
  69689. ["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"],
  69690. ["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13],
  69691. ["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"],
  69692. ["a141","좥좦좧좩",18,"좾좿죀죁"],
  69693. ["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"],
  69694. ["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"],
  69695. ["a241","줐줒",5,"줙",18],
  69696. ["a261","줭",6,"줵",18],
  69697. ["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"],
  69698. ["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"],
  69699. ["a361","즑",6,"즚즜즞",16],
  69700. ["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"],
  69701. ["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"],
  69702. ["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12],
  69703. ["a481","쨦쨧쨨쨪",28,"ㄱ",93],
  69704. ["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"],
  69705. ["a561","쩫",17,"쩾",5,"쪅쪆"],
  69706. ["a581","쪇",16,"쪙",14,"ⅰ",9],
  69707. ["a5b0","Ⅰ",9],
  69708. ["a5c1","Α",16,"Σ",6],
  69709. ["a5e1","α",16,"σ",6],
  69710. ["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"],
  69711. ["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6],
  69712. ["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7],
  69713. ["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7],
  69714. ["a761","쬪",22,"쭂쭃쭄"],
  69715. ["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"],
  69716. ["a841","쭭",10,"쭺",14],
  69717. ["a861","쮉",18,"쮝",6],
  69718. ["a881","쮤",19,"쮹",11,"ÆÐªĦ"],
  69719. ["a8a6","IJ"],
  69720. ["a8a8","ĿŁØŒºÞŦŊ"],
  69721. ["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"],
  69722. ["a941","쯅",14,"쯕",10],
  69723. ["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18],
  69724. ["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"],
  69725. ["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"],
  69726. ["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"],
  69727. ["aa81","챳챴챶",29,"ぁ",82],
  69728. ["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"],
  69729. ["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5],
  69730. ["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85],
  69731. ["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"],
  69732. ["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4],
  69733. ["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25],
  69734. ["acd1","а",5,"ёж",25],
  69735. ["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7],
  69736. ["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"],
  69737. ["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"],
  69738. ["ae41","췆",5,"췍췎췏췑",16],
  69739. ["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4],
  69740. ["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"],
  69741. ["af41","츬츭츮츯츲츴츶",19],
  69742. ["af61","칊",13,"칚칛칝칞칢",5,"칪칬"],
  69743. ["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"],
  69744. ["b041","캚",5,"캢캦",5,"캮",12],
  69745. ["b061","캻",5,"컂",19],
  69746. ["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"],
  69747. ["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"],
  69748. ["b161","켥",6,"켮켲",5,"켹",11],
  69749. ["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"],
  69750. ["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"],
  69751. ["b261","쾎",18,"쾢",5,"쾩"],
  69752. ["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"],
  69753. ["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"],
  69754. ["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5],
  69755. ["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"],
  69756. ["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5],
  69757. ["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"],
  69758. ["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"],
  69759. ["b541","킕",14,"킦킧킩킪킫킭",5],
  69760. ["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4],
  69761. ["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"],
  69762. ["b641","턅",7,"턎",17],
  69763. ["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"],
  69764. ["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"],
  69765. ["b741","텮",13,"텽",6,"톅톆톇톉톊"],
  69766. ["b761","톋",20,"톢톣톥톦톧"],
  69767. ["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"],
  69768. ["b841","퇐",7,"퇙",17],
  69769. ["b861","퇫",8,"퇵퇶퇷퇹",13],
  69770. ["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"],
  69771. ["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"],
  69772. ["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"],
  69773. ["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"],
  69774. ["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"],
  69775. ["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5],
  69776. ["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"],
  69777. ["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"],
  69778. ["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"],
  69779. ["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"],
  69780. ["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"],
  69781. ["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"],
  69782. ["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"],
  69783. ["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"],
  69784. ["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13],
  69785. ["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"],
  69786. ["be41","퐸",7,"푁푂푃푅",14],
  69787. ["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"],
  69788. ["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"],
  69789. ["bf41","풞",10,"풪",14],
  69790. ["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"],
  69791. ["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"],
  69792. ["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5],
  69793. ["c061","픞",25],
  69794. ["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"],
  69795. ["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"],
  69796. ["c161","햌햍햎햏햑",19,"햦햧"],
  69797. ["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"],
  69798. ["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"],
  69799. ["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"],
  69800. ["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"],
  69801. ["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4],
  69802. ["c361","홢",4,"홨홪",5,"홲홳홵",11],
  69803. ["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"],
  69804. ["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"],
  69805. ["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4],
  69806. ["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"],
  69807. ["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"],
  69808. ["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4],
  69809. ["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"],
  69810. ["c641","힍힎힏힑",6,"힚힜힞",5],
  69811. ["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"],
  69812. ["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"],
  69813. ["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"],
  69814. ["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"],
  69815. ["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"],
  69816. ["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"],
  69817. ["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"],
  69818. ["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"],
  69819. ["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"],
  69820. ["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"],
  69821. ["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"],
  69822. ["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"],
  69823. ["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"],
  69824. ["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"],
  69825. ["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"],
  69826. ["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"],
  69827. ["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"],
  69828. ["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"],
  69829. ["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"],
  69830. ["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"],
  69831. ["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"],
  69832. ["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"],
  69833. ["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"],
  69834. ["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"],
  69835. ["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"],
  69836. ["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"],
  69837. ["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"],
  69838. ["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"],
  69839. ["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"],
  69840. ["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"],
  69841. ["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"],
  69842. ["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"],
  69843. ["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"],
  69844. ["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"],
  69845. ["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"],
  69846. ["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"],
  69847. ["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"],
  69848. ["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"],
  69849. ["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"],
  69850. ["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"],
  69851. ["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"],
  69852. ["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"],
  69853. ["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"],
  69854. ["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"],
  69855. ["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"],
  69856. ["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"],
  69857. ["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"],
  69858. ["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"],
  69859. ["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"],
  69860. ["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"],
  69861. ["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"],
  69862. ["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"],
  69863. ["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"],
  69864. ["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"],
  69865. ["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"]
  69866. ]
  69867. },{}],384:[function(require,module,exports){
  69868. module.exports=[
  69869. ["0","\u0000",127],
  69870. ["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"],
  69871. ["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"],
  69872. ["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"],
  69873. ["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21],
  69874. ["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10],
  69875. ["a3a1","ㄐ",25,"˙ˉˊˇˋ"],
  69876. ["a3e1","€"],
  69877. ["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"],
  69878. ["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"],
  69879. ["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"],
  69880. ["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"],
  69881. ["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"],
  69882. ["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"],
  69883. ["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"],
  69884. ["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"],
  69885. ["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"],
  69886. ["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"],
  69887. ["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"],
  69888. ["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"],
  69889. ["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"],
  69890. ["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"],
  69891. ["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"],
  69892. ["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"],
  69893. ["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"],
  69894. ["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"],
  69895. ["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"],
  69896. ["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"],
  69897. ["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"],
  69898. ["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"],
  69899. ["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"],
  69900. ["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"],
  69901. ["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"],
  69902. ["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"],
  69903. ["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"],
  69904. ["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"],
  69905. ["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"],
  69906. ["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"],
  69907. ["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"],
  69908. ["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"],
  69909. ["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"],
  69910. ["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"],
  69911. ["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"],
  69912. ["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"],
  69913. ["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"],
  69914. ["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"],
  69915. ["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"],
  69916. ["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"],
  69917. ["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"],
  69918. ["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"],
  69919. ["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"],
  69920. ["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"],
  69921. ["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"],
  69922. ["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"],
  69923. ["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"],
  69924. ["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"],
  69925. ["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"],
  69926. ["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"],
  69927. ["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"],
  69928. ["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"],
  69929. ["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"],
  69930. ["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"],
  69931. ["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"],
  69932. ["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"],
  69933. ["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"],
  69934. ["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"],
  69935. ["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"],
  69936. ["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"],
  69937. ["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"],
  69938. ["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"],
  69939. ["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"],
  69940. ["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"],
  69941. ["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"],
  69942. ["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"],
  69943. ["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"],
  69944. ["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"],
  69945. ["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"],
  69946. ["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"],
  69947. ["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"],
  69948. ["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"],
  69949. ["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"],
  69950. ["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"],
  69951. ["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"],
  69952. ["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"],
  69953. ["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"],
  69954. ["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"],
  69955. ["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"],
  69956. ["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"],
  69957. ["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"],
  69958. ["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"],
  69959. ["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"],
  69960. ["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"],
  69961. ["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"],
  69962. ["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"],
  69963. ["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"],
  69964. ["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"],
  69965. ["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"],
  69966. ["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"],
  69967. ["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"],
  69968. ["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"],
  69969. ["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"],
  69970. ["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"],
  69971. ["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"],
  69972. ["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"],
  69973. ["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"],
  69974. ["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"],
  69975. ["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"],
  69976. ["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"],
  69977. ["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"],
  69978. ["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"],
  69979. ["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"],
  69980. ["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"],
  69981. ["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"],
  69982. ["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"],
  69983. ["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"],
  69984. ["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"],
  69985. ["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"],
  69986. ["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"],
  69987. ["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"],
  69988. ["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"],
  69989. ["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"],
  69990. ["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"],
  69991. ["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"],
  69992. ["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"],
  69993. ["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"],
  69994. ["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"],
  69995. ["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"],
  69996. ["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"],
  69997. ["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"],
  69998. ["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"],
  69999. ["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"],
  70000. ["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"],
  70001. ["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"],
  70002. ["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"],
  70003. ["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"],
  70004. ["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"],
  70005. ["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"],
  70006. ["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"],
  70007. ["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"],
  70008. ["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"],
  70009. ["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"],
  70010. ["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"],
  70011. ["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"],
  70012. ["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"],
  70013. ["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"],
  70014. ["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"],
  70015. ["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"],
  70016. ["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"],
  70017. ["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"],
  70018. ["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"],
  70019. ["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"],
  70020. ["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"],
  70021. ["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"],
  70022. ["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"],
  70023. ["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"],
  70024. ["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"],
  70025. ["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"],
  70026. ["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"],
  70027. ["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"],
  70028. ["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"],
  70029. ["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"],
  70030. ["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"],
  70031. ["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"],
  70032. ["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"],
  70033. ["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"],
  70034. ["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"],
  70035. ["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"],
  70036. ["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"],
  70037. ["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"],
  70038. ["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"],
  70039. ["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"],
  70040. ["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"],
  70041. ["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"],
  70042. ["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"],
  70043. ["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"]
  70044. ]
  70045. },{}],385:[function(require,module,exports){
  70046. module.exports=[
  70047. ["0","\u0000",127],
  70048. ["8ea1","。",62],
  70049. ["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"],
  70050. ["a2a1","◆□■△▲▽▼※〒→←↑↓〓"],
  70051. ["a2ba","∈∋⊆⊇⊂⊃∪∩"],
  70052. ["a2ca","∧∨¬⇒⇔∀∃"],
  70053. ["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],
  70054. ["a2f2","ʼn♯♭♪†‡¶"],
  70055. ["a2fe","◯"],
  70056. ["a3b0","0",9],
  70057. ["a3c1","A",25],
  70058. ["a3e1","a",25],
  70059. ["a4a1","ぁ",82],
  70060. ["a5a1","ァ",85],
  70061. ["a6a1","Α",16,"Σ",6],
  70062. ["a6c1","α",16,"σ",6],
  70063. ["a7a1","А",5,"ЁЖ",25],
  70064. ["a7d1","а",5,"ёж",25],
  70065. ["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],
  70066. ["ada1","①",19,"Ⅰ",9],
  70067. ["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],
  70068. ["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],
  70069. ["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],
  70070. ["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"],
  70071. ["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],
  70072. ["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"],
  70073. ["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],
  70074. ["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"],
  70075. ["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],
  70076. ["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"],
  70077. ["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],
  70078. ["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"],
  70079. ["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],
  70080. ["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"],
  70081. ["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],
  70082. ["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"],
  70083. ["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],
  70084. ["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"],
  70085. ["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],
  70086. ["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"],
  70087. ["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],
  70088. ["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"],
  70089. ["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],
  70090. ["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"],
  70091. ["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],
  70092. ["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"],
  70093. ["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],
  70094. ["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"],
  70095. ["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],
  70096. ["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"],
  70097. ["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],
  70098. ["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"],
  70099. ["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],
  70100. ["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],
  70101. ["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],
  70102. ["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"],
  70103. ["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],
  70104. ["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"],
  70105. ["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],
  70106. ["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"],
  70107. ["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],
  70108. ["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"],
  70109. ["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],
  70110. ["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"],
  70111. ["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],
  70112. ["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"],
  70113. ["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],
  70114. ["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"],
  70115. ["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],
  70116. ["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"],
  70117. ["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],
  70118. ["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"],
  70119. ["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],
  70120. ["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"],
  70121. ["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],
  70122. ["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"],
  70123. ["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],
  70124. ["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"],
  70125. ["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],
  70126. ["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"],
  70127. ["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],
  70128. ["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"],
  70129. ["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],
  70130. ["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"],
  70131. ["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],
  70132. ["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"],
  70133. ["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],
  70134. ["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"],
  70135. ["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],
  70136. ["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"],
  70137. ["f4a1","堯槇遙瑤凜熙"],
  70138. ["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"],
  70139. ["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],
  70140. ["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"],
  70141. ["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],
  70142. ["fcf1","ⅰ",9,"¬¦'""],
  70143. ["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"],
  70144. ["8fa2c2","¡¦¿"],
  70145. ["8fa2eb","ºª©®™¤№"],
  70146. ["8fa6e1","ΆΈΉΊΪ"],
  70147. ["8fa6e7","Ό"],
  70148. ["8fa6e9","ΎΫ"],
  70149. ["8fa6ec","Ώ"],
  70150. ["8fa6f1","άέήίϊΐόςύϋΰώ"],
  70151. ["8fa7c2","Ђ",10,"ЎЏ"],
  70152. ["8fa7f2","ђ",10,"ўџ"],
  70153. ["8fa9a1","ÆĐ"],
  70154. ["8fa9a4","Ħ"],
  70155. ["8fa9a6","IJ"],
  70156. ["8fa9a8","ŁĿ"],
  70157. ["8fa9ab","ŊØŒ"],
  70158. ["8fa9af","ŦÞ"],
  70159. ["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"],
  70160. ["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"],
  70161. ["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"],
  70162. ["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"],
  70163. ["8fabbd","ġĥíìïîǐ"],
  70164. ["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"],
  70165. ["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"],
  70166. ["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"],
  70167. ["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"],
  70168. ["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"],
  70169. ["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"],
  70170. ["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"],
  70171. ["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"],
  70172. ["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"],
  70173. ["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"],
  70174. ["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"],
  70175. ["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"],
  70176. ["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"],
  70177. ["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"],
  70178. ["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"],
  70179. ["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"],
  70180. ["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"],
  70181. ["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"],
  70182. ["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"],
  70183. ["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"],
  70184. ["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"],
  70185. ["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"],
  70186. ["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"],
  70187. ["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"],
  70188. ["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"],
  70189. ["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"],
  70190. ["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"],
  70191. ["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"],
  70192. ["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"],
  70193. ["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"],
  70194. ["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"],
  70195. ["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"],
  70196. ["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"],
  70197. ["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"],
  70198. ["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"],
  70199. ["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5],
  70200. ["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"],
  70201. ["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"],
  70202. ["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"],
  70203. ["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"],
  70204. ["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"],
  70205. ["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"],
  70206. ["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"],
  70207. ["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"],
  70208. ["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"],
  70209. ["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"],
  70210. ["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"],
  70211. ["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"],
  70212. ["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"],
  70213. ["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"],
  70214. ["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"],
  70215. ["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"],
  70216. ["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"],
  70217. ["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"],
  70218. ["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"],
  70219. ["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"],
  70220. ["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"],
  70221. ["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"],
  70222. ["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4],
  70223. ["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"],
  70224. ["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"],
  70225. ["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"],
  70226. ["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"]
  70227. ]
  70228. },{}],386:[function(require,module,exports){
  70229. module.exports={"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]}
  70230. },{}],387:[function(require,module,exports){
  70231. module.exports=[
  70232. ["a140","",62],
  70233. ["a180","",32],
  70234. ["a240","",62],
  70235. ["a280","",32],
  70236. ["a2ab","",5],
  70237. ["a2e3","€"],
  70238. ["a2ef",""],
  70239. ["a2fd",""],
  70240. ["a340","",62],
  70241. ["a380","",31," "],
  70242. ["a440","",62],
  70243. ["a480","",32],
  70244. ["a4f4","",10],
  70245. ["a540","",62],
  70246. ["a580","",32],
  70247. ["a5f7","",7],
  70248. ["a640","",62],
  70249. ["a680","",32],
  70250. ["a6b9","",7],
  70251. ["a6d9","",6],
  70252. ["a6ec",""],
  70253. ["a6f3",""],
  70254. ["a6f6","",8],
  70255. ["a740","",62],
  70256. ["a780","",32],
  70257. ["a7c2","",14],
  70258. ["a7f2","",12],
  70259. ["a896","",10],
  70260. ["a8bc",""],
  70261. ["a8bf","ǹ"],
  70262. ["a8c1",""],
  70263. ["a8ea","",20],
  70264. ["a958",""],
  70265. ["a95b",""],
  70266. ["a95d",""],
  70267. ["a989","〾⿰",11],
  70268. ["a997","",12],
  70269. ["a9f0","",14],
  70270. ["aaa1","",93],
  70271. ["aba1","",93],
  70272. ["aca1","",93],
  70273. ["ada1","",93],
  70274. ["aea1","",93],
  70275. ["afa1","",93],
  70276. ["d7fa","",4],
  70277. ["f8a1","",93],
  70278. ["f9a1","",93],
  70279. ["faa1","",93],
  70280. ["fba1","",93],
  70281. ["fca1","",93],
  70282. ["fda1","",93],
  70283. ["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"],
  70284. ["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93]
  70285. ]
  70286. },{}],388:[function(require,module,exports){
  70287. module.exports=[
  70288. ["0","\u0000",128],
  70289. ["a1","。",62],
  70290. ["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"],
  70291. ["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"],
  70292. ["81b8","∈∋⊆⊇⊂⊃∪∩"],
  70293. ["81c8","∧∨¬⇒⇔∀∃"],
  70294. ["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],
  70295. ["81f0","ʼn♯♭♪†‡¶"],
  70296. ["81fc","◯"],
  70297. ["824f","0",9],
  70298. ["8260","A",25],
  70299. ["8281","a",25],
  70300. ["829f","ぁ",82],
  70301. ["8340","ァ",62],
  70302. ["8380","ム",22],
  70303. ["839f","Α",16,"Σ",6],
  70304. ["83bf","α",16,"σ",6],
  70305. ["8440","А",5,"ЁЖ",25],
  70306. ["8470","а",5,"ёж",7],
  70307. ["8480","о",17],
  70308. ["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],
  70309. ["8740","①",19,"Ⅰ",9],
  70310. ["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],
  70311. ["877e","㍻"],
  70312. ["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],
  70313. ["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],
  70314. ["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],
  70315. ["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],
  70316. ["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],
  70317. ["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],
  70318. ["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],
  70319. ["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],
  70320. ["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],
  70321. ["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],
  70322. ["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],
  70323. ["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],
  70324. ["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],
  70325. ["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],
  70326. ["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],
  70327. ["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],
  70328. ["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],
  70329. ["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],
  70330. ["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],
  70331. ["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],
  70332. ["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],
  70333. ["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],
  70334. ["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],
  70335. ["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],
  70336. ["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],
  70337. ["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],
  70338. ["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],
  70339. ["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],
  70340. ["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],
  70341. ["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],
  70342. ["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],
  70343. ["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],
  70344. ["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],
  70345. ["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],
  70346. ["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],
  70347. ["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],
  70348. ["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],
  70349. ["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],
  70350. ["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],
  70351. ["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],
  70352. ["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],
  70353. ["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],
  70354. ["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],
  70355. ["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],
  70356. ["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],
  70357. ["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],
  70358. ["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],
  70359. ["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],
  70360. ["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],
  70361. ["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],
  70362. ["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],
  70363. ["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],
  70364. ["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],
  70365. ["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],
  70366. ["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],
  70367. ["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],
  70368. ["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],
  70369. ["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],
  70370. ["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],
  70371. ["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],
  70372. ["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],
  70373. ["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],
  70374. ["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],
  70375. ["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],
  70376. ["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],
  70377. ["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],
  70378. ["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],
  70379. ["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],
  70380. ["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],
  70381. ["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"],
  70382. ["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"],
  70383. ["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],
  70384. ["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"],
  70385. ["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],
  70386. ["eeef","ⅰ",9,"¬¦'""],
  70387. ["f040","",62],
  70388. ["f080","",124],
  70389. ["f140","",62],
  70390. ["f180","",124],
  70391. ["f240","",62],
  70392. ["f280","",124],
  70393. ["f340","",62],
  70394. ["f380","",124],
  70395. ["f440","",62],
  70396. ["f480","",124],
  70397. ["f540","",62],
  70398. ["f580","",124],
  70399. ["f640","",62],
  70400. ["f680","",124],
  70401. ["f740","",62],
  70402. ["f780","",124],
  70403. ["f840","",62],
  70404. ["f880","",124],
  70405. ["f940",""],
  70406. ["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"],
  70407. ["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"],
  70408. ["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"],
  70409. ["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"],
  70410. ["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]
  70411. ]
  70412. },{}],389:[function(require,module,exports){
  70413. "use strict";
  70414. var Buffer = require("safer-buffer").Buffer;
  70415. // Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js
  70416. // == UTF16-BE codec. ==========================================================
  70417. exports.utf16be = Utf16BECodec;
  70418. function Utf16BECodec() {
  70419. }
  70420. Utf16BECodec.prototype.encoder = Utf16BEEncoder;
  70421. Utf16BECodec.prototype.decoder = Utf16BEDecoder;
  70422. Utf16BECodec.prototype.bomAware = true;
  70423. // -- Encoding
  70424. function Utf16BEEncoder() {
  70425. }
  70426. Utf16BEEncoder.prototype.write = function(str) {
  70427. var buf = Buffer.from(str, 'ucs2');
  70428. for (var i = 0; i < buf.length; i += 2) {
  70429. var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
  70430. }
  70431. return buf;
  70432. }
  70433. Utf16BEEncoder.prototype.end = function() {
  70434. }
  70435. // -- Decoding
  70436. function Utf16BEDecoder() {
  70437. this.overflowByte = -1;
  70438. }
  70439. Utf16BEDecoder.prototype.write = function(buf) {
  70440. if (buf.length == 0)
  70441. return '';
  70442. var buf2 = Buffer.alloc(buf.length + 1),
  70443. i = 0, j = 0;
  70444. if (this.overflowByte !== -1) {
  70445. buf2[0] = buf[0];
  70446. buf2[1] = this.overflowByte;
  70447. i = 1; j = 2;
  70448. }
  70449. for (; i < buf.length-1; i += 2, j+= 2) {
  70450. buf2[j] = buf[i+1];
  70451. buf2[j+1] = buf[i];
  70452. }
  70453. this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;
  70454. return buf2.slice(0, j).toString('ucs2');
  70455. }
  70456. Utf16BEDecoder.prototype.end = function() {
  70457. }
  70458. // == UTF-16 codec =============================================================
  70459. // Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
  70460. // Defaults to UTF-16LE, as it's prevalent and default in Node.
  70461. // http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
  70462. // Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});
  70463. // Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).
  70464. exports.utf16 = Utf16Codec;
  70465. function Utf16Codec(codecOptions, iconv) {
  70466. this.iconv = iconv;
  70467. }
  70468. Utf16Codec.prototype.encoder = Utf16Encoder;
  70469. Utf16Codec.prototype.decoder = Utf16Decoder;
  70470. // -- Encoding (pass-through)
  70471. function Utf16Encoder(options, codec) {
  70472. options = options || {};
  70473. if (options.addBOM === undefined)
  70474. options.addBOM = true;
  70475. this.encoder = codec.iconv.getEncoder('utf-16le', options);
  70476. }
  70477. Utf16Encoder.prototype.write = function(str) {
  70478. return this.encoder.write(str);
  70479. }
  70480. Utf16Encoder.prototype.end = function() {
  70481. return this.encoder.end();
  70482. }
  70483. // -- Decoding
  70484. function Utf16Decoder(options, codec) {
  70485. this.decoder = null;
  70486. this.initialBytes = [];
  70487. this.initialBytesLen = 0;
  70488. this.options = options || {};
  70489. this.iconv = codec.iconv;
  70490. }
  70491. Utf16Decoder.prototype.write = function(buf) {
  70492. if (!this.decoder) {
  70493. // Codec is not chosen yet. Accumulate initial bytes.
  70494. this.initialBytes.push(buf);
  70495. this.initialBytesLen += buf.length;
  70496. if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below)
  70497. return '';
  70498. // We have enough bytes -> detect endianness.
  70499. var buf = Buffer.concat(this.initialBytes),
  70500. encoding = detectEncoding(buf, this.options.defaultEncoding);
  70501. this.decoder = this.iconv.getDecoder(encoding, this.options);
  70502. this.initialBytes.length = this.initialBytesLen = 0;
  70503. }
  70504. return this.decoder.write(buf);
  70505. }
  70506. Utf16Decoder.prototype.end = function() {
  70507. if (!this.decoder) {
  70508. var buf = Buffer.concat(this.initialBytes),
  70509. encoding = detectEncoding(buf, this.options.defaultEncoding);
  70510. this.decoder = this.iconv.getDecoder(encoding, this.options);
  70511. var res = this.decoder.write(buf),
  70512. trail = this.decoder.end();
  70513. return trail ? (res + trail) : res;
  70514. }
  70515. return this.decoder.end();
  70516. }
  70517. function detectEncoding(buf, defaultEncoding) {
  70518. var enc = defaultEncoding || 'utf-16le';
  70519. if (buf.length >= 2) {
  70520. // Check BOM.
  70521. if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM
  70522. enc = 'utf-16be';
  70523. else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM
  70524. enc = 'utf-16le';
  70525. else {
  70526. // No BOM found. Try to deduce encoding from initial content.
  70527. // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
  70528. // So, we count ASCII as if it was LE or BE, and decide from that.
  70529. var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions
  70530. _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even.
  70531. for (var i = 0; i < _len; i += 2) {
  70532. if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++;
  70533. if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++;
  70534. }
  70535. if (asciiCharsBE > asciiCharsLE)
  70536. enc = 'utf-16be';
  70537. else if (asciiCharsBE < asciiCharsLE)
  70538. enc = 'utf-16le';
  70539. }
  70540. }
  70541. return enc;
  70542. }
  70543. },{"safer-buffer":562}],390:[function(require,module,exports){
  70544. 'use strict';
  70545. var Buffer = require('safer-buffer').Buffer;
  70546. // == UTF32-LE/BE codec. ==========================================================
  70547. exports._utf32 = Utf32Codec;
  70548. function Utf32Codec(codecOptions, iconv) {
  70549. this.iconv = iconv;
  70550. this.bomAware = true;
  70551. this.isLE = codecOptions.isLE;
  70552. }
  70553. exports.utf32le = { type: '_utf32', isLE: true };
  70554. exports.utf32be = { type: '_utf32', isLE: false };
  70555. // Aliases
  70556. exports.ucs4le = 'utf32le';
  70557. exports.ucs4be = 'utf32be';
  70558. Utf32Codec.prototype.encoder = Utf32Encoder;
  70559. Utf32Codec.prototype.decoder = Utf32Decoder;
  70560. // -- Encoding
  70561. function Utf32Encoder(options, codec) {
  70562. this.isLE = codec.isLE;
  70563. this.highSurrogate = 0;
  70564. }
  70565. Utf32Encoder.prototype.write = function(str) {
  70566. var src = Buffer.from(str, 'ucs2');
  70567. var dst = Buffer.alloc(src.length * 2);
  70568. var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
  70569. var offset = 0;
  70570. for (var i = 0; i < src.length; i += 2) {
  70571. var code = src.readUInt16LE(i);
  70572. var isHighSurrogate = (0xD800 <= code && code < 0xDC00);
  70573. var isLowSurrogate = (0xDC00 <= code && code < 0xE000);
  70574. if (this.highSurrogate) {
  70575. if (isHighSurrogate || !isLowSurrogate) {
  70576. // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low
  70577. // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character
  70578. // (technically wrong, but expected by some applications, like Windows file names).
  70579. write32.call(dst, this.highSurrogate, offset);
  70580. offset += 4;
  70581. }
  70582. else {
  70583. // Create 32-bit value from high and low surrogates;
  70584. var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;
  70585. write32.call(dst, codepoint, offset);
  70586. offset += 4;
  70587. this.highSurrogate = 0;
  70588. continue;
  70589. }
  70590. }
  70591. if (isHighSurrogate)
  70592. this.highSurrogate = code;
  70593. else {
  70594. // Even if the current character is a low surrogate, with no previous high surrogate, we'll
  70595. // encode it as a semi-invalid stand-alone character for the same reasons expressed above for
  70596. // unpaired high surrogates.
  70597. write32.call(dst, code, offset);
  70598. offset += 4;
  70599. this.highSurrogate = 0;
  70600. }
  70601. }
  70602. if (offset < dst.length)
  70603. dst = dst.slice(0, offset);
  70604. return dst;
  70605. };
  70606. Utf32Encoder.prototype.end = function() {
  70607. // Treat any leftover high surrogate as a semi-valid independent character.
  70608. if (!this.highSurrogate)
  70609. return;
  70610. var buf = Buffer.alloc(4);
  70611. if (this.isLE)
  70612. buf.writeUInt32LE(this.highSurrogate, 0);
  70613. else
  70614. buf.writeUInt32BE(this.highSurrogate, 0);
  70615. this.highSurrogate = 0;
  70616. return buf;
  70617. };
  70618. // -- Decoding
  70619. function Utf32Decoder(options, codec) {
  70620. this.isLE = codec.isLE;
  70621. this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
  70622. this.overflow = null;
  70623. }
  70624. Utf32Decoder.prototype.write = function(src) {
  70625. if (src.length === 0)
  70626. return '';
  70627. if (this.overflow)
  70628. src = Buffer.concat([this.overflow, src]);
  70629. var goodLength = src.length - src.length % 4;
  70630. if (src.length !== goodLength) {
  70631. this.overflow = src.slice(goodLength);
  70632. src = src.slice(0, goodLength);
  70633. }
  70634. else
  70635. this.overflow = null;
  70636. var dst = Buffer.alloc(goodLength);
  70637. var offset = 0;
  70638. for (var i = 0; i < goodLength; i += 4) {
  70639. var codepoint = this.isLE ? src.readUInt32LE(i) : src.readUInt32BE(i);
  70640. if (codepoint < 0x10000) {
  70641. // Simple 16-bit character
  70642. dst.writeUInt16LE(codepoint, offset);
  70643. offset += 2;
  70644. }
  70645. else {
  70646. if (codepoint > 0x10FFFF) {
  70647. // Not a valid Unicode codepoint
  70648. dst.writeUInt16LE(this.badChar, offset);
  70649. offset += 2;
  70650. }
  70651. else {
  70652. // Create high and low surrogates.
  70653. codepoint -= 0x10000;
  70654. var high = 0xD800 | (codepoint >> 10);
  70655. var low = 0xDC00 + (codepoint & 0x3FF);
  70656. dst.writeUInt16LE(high, offset);
  70657. offset += 2;
  70658. dst.writeUInt16LE(low, offset);
  70659. offset += 2;
  70660. }
  70661. }
  70662. }
  70663. return dst.slice(0, offset).toString('ucs2');
  70664. };
  70665. Utf32Decoder.prototype.end = function() {
  70666. this.overflow = null;
  70667. };
  70668. // == UTF-32 Auto codec =============================================================
  70669. // Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.
  70670. // Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32
  70671. // Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});
  70672. // Encoder prepends BOM (which can be overridden with (addBOM: false}).
  70673. exports.utf32 = Utf32AutoCodec;
  70674. exports.ucs4 = Utf32AutoCodec;
  70675. function Utf32AutoCodec(options, iconv) {
  70676. this.iconv = iconv;
  70677. }
  70678. Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
  70679. Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;
  70680. // -- Encoding
  70681. function Utf32AutoEncoder(options, codec) {
  70682. options = options || {};
  70683. if (options.addBOM === undefined)
  70684. options.addBOM = true;
  70685. this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);
  70686. }
  70687. Utf32AutoEncoder.prototype.write = function(str) {
  70688. return this.encoder.write(str);
  70689. };
  70690. Utf32AutoEncoder.prototype.end = function() {
  70691. return this.encoder.end();
  70692. };
  70693. // -- Decoding
  70694. function Utf32AutoDecoder(options, codec) {
  70695. this.decoder = null;
  70696. this.initialBytes = [];
  70697. this.initialBytesLen = 0;
  70698. this.options = options || {};
  70699. this.iconv = codec.iconv;
  70700. }
  70701. Utf32AutoDecoder.prototype.write = function(buf) {
  70702. if (!this.decoder) {
  70703. // Codec is not chosen yet. Accumulate initial bytes.
  70704. this.initialBytes.push(buf);
  70705. this.initialBytesLen += buf.length;
  70706. if (this.initialBytesLen < 32) // We need more bytes to use space heuristic (see below)
  70707. return '';
  70708. // We have enough bytes -> detect endianness.
  70709. var buf2 = Buffer.concat(this.initialBytes),
  70710. encoding = detectEncoding(buf2, this.options.defaultEncoding);
  70711. this.decoder = this.iconv.getDecoder(encoding, this.options);
  70712. this.initialBytes.length = this.initialBytesLen = 0;
  70713. }
  70714. return this.decoder.write(buf);
  70715. };
  70716. Utf32AutoDecoder.prototype.end = function() {
  70717. if (!this.decoder) {
  70718. var buf = Buffer.concat(this.initialBytes),
  70719. encoding = detectEncoding(buf, this.options.defaultEncoding);
  70720. this.decoder = this.iconv.getDecoder(encoding, this.options);
  70721. var res = this.decoder.write(buf),
  70722. trail = this.decoder.end();
  70723. return trail ? (res + trail) : res;
  70724. }
  70725. return this.decoder.end();
  70726. };
  70727. function detectEncoding(buf, defaultEncoding) {
  70728. var enc = defaultEncoding || 'utf-32le';
  70729. if (buf.length >= 4) {
  70730. // Check BOM.
  70731. if (buf.readUInt32BE(0) === 0xFEFF) // UTF-32LE BOM
  70732. enc = 'utf-32be';
  70733. else if (buf.readUInt32LE(0) === 0xFEFF) // UTF-32LE BOM
  70734. enc = 'utf-32le';
  70735. else {
  70736. // No BOM found. Try to deduce encoding from initial content.
  70737. // Using the wrong endian-ism for UTF-32 will very often result in codepoints that are beyond
  70738. // the valid Unicode limit of 0x10FFFF. That will be used as the primary determinant.
  70739. //
  70740. // Further, we can suppose the content is mostly plain ASCII chars (U+00**).
  70741. // So, we count ASCII as if it was LE or BE, and decide from that.
  70742. var invalidLE = 0, invalidBE = 0;
  70743. var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions
  70744. _len = Math.min(buf.length - (buf.length % 4), 128); // Len is always even.
  70745. for (var i = 0; i < _len; i += 4) {
  70746. var b0 = buf[i], b1 = buf[i + 1], b2 = buf[i + 2], b3 = buf[i + 3];
  70747. if (b0 !== 0 || b1 > 0x10) ++invalidBE;
  70748. if (b3 !== 0 || b2 > 0x10) ++invalidLE;
  70749. if (b0 === 0 && b1 === 0 && b2 === 0 && b3 !== 0) asciiCharsBE++;
  70750. if (b0 !== 0 && b1 === 0 && b2 === 0 && b3 === 0) asciiCharsLE++;
  70751. }
  70752. if (invalidBE < invalidLE)
  70753. enc = 'utf-32be';
  70754. else if (invalidLE < invalidBE)
  70755. enc = 'utf-32le';
  70756. if (asciiCharsBE > asciiCharsLE)
  70757. enc = 'utf-32be';
  70758. else if (asciiCharsBE < asciiCharsLE)
  70759. enc = 'utf-32le';
  70760. }
  70761. }
  70762. return enc;
  70763. }
  70764. },{"safer-buffer":562}],391:[function(require,module,exports){
  70765. "use strict";
  70766. var Buffer = require("safer-buffer").Buffer;
  70767. // UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
  70768. // See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3
  70769. exports.utf7 = Utf7Codec;
  70770. exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
  70771. function Utf7Codec(codecOptions, iconv) {
  70772. this.iconv = iconv;
  70773. };
  70774. Utf7Codec.prototype.encoder = Utf7Encoder;
  70775. Utf7Codec.prototype.decoder = Utf7Decoder;
  70776. Utf7Codec.prototype.bomAware = true;
  70777. // -- Encoding
  70778. var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
  70779. function Utf7Encoder(options, codec) {
  70780. this.iconv = codec.iconv;
  70781. }
  70782. Utf7Encoder.prototype.write = function(str) {
  70783. // Naive implementation.
  70784. // Non-direct chars are encoded as "+<base64>-"; single "+" char is encoded as "+-".
  70785. return Buffer.from(str.replace(nonDirectChars, function(chunk) {
  70786. return "+" + (chunk === '+' ? '' :
  70787. this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, ''))
  70788. + "-";
  70789. }.bind(this)));
  70790. }
  70791. Utf7Encoder.prototype.end = function() {
  70792. }
  70793. // -- Decoding
  70794. function Utf7Decoder(options, codec) {
  70795. this.iconv = codec.iconv;
  70796. this.inBase64 = false;
  70797. this.base64Accum = '';
  70798. }
  70799. var base64Regex = /[A-Za-z0-9\/+]/;
  70800. var base64Chars = [];
  70801. for (var i = 0; i < 256; i++)
  70802. base64Chars[i] = base64Regex.test(String.fromCharCode(i));
  70803. var plusChar = '+'.charCodeAt(0),
  70804. minusChar = '-'.charCodeAt(0),
  70805. andChar = '&'.charCodeAt(0);
  70806. Utf7Decoder.prototype.write = function(buf) {
  70807. var res = "", lastI = 0,
  70808. inBase64 = this.inBase64,
  70809. base64Accum = this.base64Accum;
  70810. // The decoder is more involved as we must handle chunks in stream.
  70811. for (var i = 0; i < buf.length; i++) {
  70812. if (!inBase64) { // We're in direct mode.
  70813. // Write direct chars until '+'
  70814. if (buf[i] == plusChar) {
  70815. res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
  70816. lastI = i+1;
  70817. inBase64 = true;
  70818. }
  70819. } else { // We decode base64.
  70820. if (!base64Chars[buf[i]]) { // Base64 ended.
  70821. if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
  70822. res += "+";
  70823. } else {
  70824. var b64str = base64Accum + buf.slice(lastI, i).toString();
  70825. res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
  70826. }
  70827. if (buf[i] != minusChar) // Minus is absorbed after base64.
  70828. i--;
  70829. lastI = i+1;
  70830. inBase64 = false;
  70831. base64Accum = '';
  70832. }
  70833. }
  70834. }
  70835. if (!inBase64) {
  70836. res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
  70837. } else {
  70838. var b64str = base64Accum + buf.slice(lastI).toString();
  70839. var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
  70840. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
  70841. b64str = b64str.slice(0, canBeDecoded);
  70842. res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
  70843. }
  70844. this.inBase64 = inBase64;
  70845. this.base64Accum = base64Accum;
  70846. return res;
  70847. }
  70848. Utf7Decoder.prototype.end = function() {
  70849. var res = "";
  70850. if (this.inBase64 && this.base64Accum.length > 0)
  70851. res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
  70852. this.inBase64 = false;
  70853. this.base64Accum = '';
  70854. return res;
  70855. }
  70856. // UTF-7-IMAP codec.
  70857. // RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
  70858. // Differences:
  70859. // * Base64 part is started by "&" instead of "+"
  70860. // * Direct characters are 0x20-0x7E, except "&" (0x26)
  70861. // * In Base64, "," is used instead of "/"
  70862. // * Base64 must not be used to represent direct characters.
  70863. // * No implicit shift back from Base64 (should always end with '-')
  70864. // * String must end in non-shifted position.
  70865. // * "-&" while in base64 is not allowed.
  70866. exports.utf7imap = Utf7IMAPCodec;
  70867. function Utf7IMAPCodec(codecOptions, iconv) {
  70868. this.iconv = iconv;
  70869. };
  70870. Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
  70871. Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
  70872. Utf7IMAPCodec.prototype.bomAware = true;
  70873. // -- Encoding
  70874. function Utf7IMAPEncoder(options, codec) {
  70875. this.iconv = codec.iconv;
  70876. this.inBase64 = false;
  70877. this.base64Accum = Buffer.alloc(6);
  70878. this.base64AccumIdx = 0;
  70879. }
  70880. Utf7IMAPEncoder.prototype.write = function(str) {
  70881. var inBase64 = this.inBase64,
  70882. base64Accum = this.base64Accum,
  70883. base64AccumIdx = this.base64AccumIdx,
  70884. buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;
  70885. for (var i = 0; i < str.length; i++) {
  70886. var uChar = str.charCodeAt(i);
  70887. if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
  70888. if (inBase64) {
  70889. if (base64AccumIdx > 0) {
  70890. bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
  70891. base64AccumIdx = 0;
  70892. }
  70893. buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
  70894. inBase64 = false;
  70895. }
  70896. if (!inBase64) {
  70897. buf[bufIdx++] = uChar; // Write direct character
  70898. if (uChar === andChar) // Ampersand -> '&-'
  70899. buf[bufIdx++] = minusChar;
  70900. }
  70901. } else { // Non-direct character
  70902. if (!inBase64) {
  70903. buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
  70904. inBase64 = true;
  70905. }
  70906. if (inBase64) {
  70907. base64Accum[base64AccumIdx++] = uChar >> 8;
  70908. base64Accum[base64AccumIdx++] = uChar & 0xFF;
  70909. if (base64AccumIdx == base64Accum.length) {
  70910. bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
  70911. base64AccumIdx = 0;
  70912. }
  70913. }
  70914. }
  70915. }
  70916. this.inBase64 = inBase64;
  70917. this.base64AccumIdx = base64AccumIdx;
  70918. return buf.slice(0, bufIdx);
  70919. }
  70920. Utf7IMAPEncoder.prototype.end = function() {
  70921. var buf = Buffer.alloc(10), bufIdx = 0;
  70922. if (this.inBase64) {
  70923. if (this.base64AccumIdx > 0) {
  70924. bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
  70925. this.base64AccumIdx = 0;
  70926. }
  70927. buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
  70928. this.inBase64 = false;
  70929. }
  70930. return buf.slice(0, bufIdx);
  70931. }
  70932. // -- Decoding
  70933. function Utf7IMAPDecoder(options, codec) {
  70934. this.iconv = codec.iconv;
  70935. this.inBase64 = false;
  70936. this.base64Accum = '';
  70937. }
  70938. var base64IMAPChars = base64Chars.slice();
  70939. base64IMAPChars[','.charCodeAt(0)] = true;
  70940. Utf7IMAPDecoder.prototype.write = function(buf) {
  70941. var res = "", lastI = 0,
  70942. inBase64 = this.inBase64,
  70943. base64Accum = this.base64Accum;
  70944. // The decoder is more involved as we must handle chunks in stream.
  70945. // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).
  70946. for (var i = 0; i < buf.length; i++) {
  70947. if (!inBase64) { // We're in direct mode.
  70948. // Write direct chars until '&'
  70949. if (buf[i] == andChar) {
  70950. res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
  70951. lastI = i+1;
  70952. inBase64 = true;
  70953. }
  70954. } else { // We decode base64.
  70955. if (!base64IMAPChars[buf[i]]) { // Base64 ended.
  70956. if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
  70957. res += "&";
  70958. } else {
  70959. var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/');
  70960. res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
  70961. }
  70962. if (buf[i] != minusChar) // Minus may be absorbed after base64.
  70963. i--;
  70964. lastI = i+1;
  70965. inBase64 = false;
  70966. base64Accum = '';
  70967. }
  70968. }
  70969. }
  70970. if (!inBase64) {
  70971. res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
  70972. } else {
  70973. var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/');
  70974. var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
  70975. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
  70976. b64str = b64str.slice(0, canBeDecoded);
  70977. res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
  70978. }
  70979. this.inBase64 = inBase64;
  70980. this.base64Accum = base64Accum;
  70981. return res;
  70982. }
  70983. Utf7IMAPDecoder.prototype.end = function() {
  70984. var res = "";
  70985. if (this.inBase64 && this.base64Accum.length > 0)
  70986. res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
  70987. this.inBase64 = false;
  70988. this.base64Accum = '';
  70989. return res;
  70990. }
  70991. },{"safer-buffer":562}],392:[function(require,module,exports){
  70992. "use strict";
  70993. var BOMChar = '\uFEFF';
  70994. exports.PrependBOM = PrependBOMWrapper
  70995. function PrependBOMWrapper(encoder, options) {
  70996. this.encoder = encoder;
  70997. this.addBOM = true;
  70998. }
  70999. PrependBOMWrapper.prototype.write = function(str) {
  71000. if (this.addBOM) {
  71001. str = BOMChar + str;
  71002. this.addBOM = false;
  71003. }
  71004. return this.encoder.write(str);
  71005. }
  71006. PrependBOMWrapper.prototype.end = function() {
  71007. return this.encoder.end();
  71008. }
  71009. //------------------------------------------------------------------------------
  71010. exports.StripBOM = StripBOMWrapper;
  71011. function StripBOMWrapper(decoder, options) {
  71012. this.decoder = decoder;
  71013. this.pass = false;
  71014. this.options = options || {};
  71015. }
  71016. StripBOMWrapper.prototype.write = function(buf) {
  71017. var res = this.decoder.write(buf);
  71018. if (this.pass || !res)
  71019. return res;
  71020. if (res[0] === BOMChar) {
  71021. res = res.slice(1);
  71022. if (typeof this.options.stripBOM === 'function')
  71023. this.options.stripBOM();
  71024. }
  71025. this.pass = true;
  71026. return res;
  71027. }
  71028. StripBOMWrapper.prototype.end = function() {
  71029. return this.decoder.end();
  71030. }
  71031. },{}],393:[function(require,module,exports){
  71032. (function (process){(function (){
  71033. "use strict";
  71034. // Some environments don't have global Buffer (e.g. React Native).
  71035. // Solution would be installing npm modules "buffer" and "stream" explicitly.
  71036. var Buffer = require("safer-buffer").Buffer;
  71037. var bomHandling = require("./bom-handling"),
  71038. iconv = module.exports;
  71039. // All codecs and aliases are kept here, keyed by encoding name/alias.
  71040. // They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
  71041. iconv.encodings = null;
  71042. // Characters emitted in case of error.
  71043. iconv.defaultCharUnicode = '�';
  71044. iconv.defaultCharSingleByte = '?';
  71045. // Public API.
  71046. iconv.encode = function encode(str, encoding, options) {
  71047. str = "" + (str || ""); // Ensure string.
  71048. var encoder = iconv.getEncoder(encoding, options);
  71049. var res = encoder.write(str);
  71050. var trail = encoder.end();
  71051. return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
  71052. }
  71053. iconv.decode = function decode(buf, encoding, options) {
  71054. if (typeof buf === 'string') {
  71055. if (!iconv.skipDecodeWarning) {
  71056. console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
  71057. iconv.skipDecodeWarning = true;
  71058. }
  71059. buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
  71060. }
  71061. var decoder = iconv.getDecoder(encoding, options);
  71062. var res = decoder.write(buf);
  71063. var trail = decoder.end();
  71064. return trail ? (res + trail) : res;
  71065. }
  71066. iconv.encodingExists = function encodingExists(enc) {
  71067. try {
  71068. iconv.getCodec(enc);
  71069. return true;
  71070. } catch (e) {
  71071. return false;
  71072. }
  71073. }
  71074. // Legacy aliases to convert functions
  71075. iconv.toEncoding = iconv.encode;
  71076. iconv.fromEncoding = iconv.decode;
  71077. // Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
  71078. iconv._codecDataCache = {};
  71079. iconv.getCodec = function getCodec(encoding) {
  71080. if (!iconv.encodings)
  71081. iconv.encodings = require("../encodings"); // Lazy load all encoding definitions.
  71082. // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
  71083. var enc = iconv._canonicalizeEncoding(encoding);
  71084. // Traverse iconv.encodings to find actual codec.
  71085. var codecOptions = {};
  71086. while (true) {
  71087. var codec = iconv._codecDataCache[enc];
  71088. if (codec)
  71089. return codec;
  71090. var codecDef = iconv.encodings[enc];
  71091. switch (typeof codecDef) {
  71092. case "string": // Direct alias to other encoding.
  71093. enc = codecDef;
  71094. break;
  71095. case "object": // Alias with options. Can be layered.
  71096. for (var key in codecDef)
  71097. codecOptions[key] = codecDef[key];
  71098. if (!codecOptions.encodingName)
  71099. codecOptions.encodingName = enc;
  71100. enc = codecDef.type;
  71101. break;
  71102. case "function": // Codec itself.
  71103. if (!codecOptions.encodingName)
  71104. codecOptions.encodingName = enc;
  71105. // The codec function must load all tables and return object with .encoder and .decoder methods.
  71106. // It'll be called only once (for each different options object).
  71107. codec = new codecDef(codecOptions, iconv);
  71108. iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
  71109. return codec;
  71110. default:
  71111. throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
  71112. }
  71113. }
  71114. }
  71115. iconv._canonicalizeEncoding = function(encoding) {
  71116. // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
  71117. return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
  71118. }
  71119. iconv.getEncoder = function getEncoder(encoding, options) {
  71120. var codec = iconv.getCodec(encoding),
  71121. encoder = new codec.encoder(options, codec);
  71122. if (codec.bomAware && options && options.addBOM)
  71123. encoder = new bomHandling.PrependBOM(encoder, options);
  71124. return encoder;
  71125. }
  71126. iconv.getDecoder = function getDecoder(encoding, options) {
  71127. var codec = iconv.getCodec(encoding),
  71128. decoder = new codec.decoder(options, codec);
  71129. if (codec.bomAware && !(options && options.stripBOM === false))
  71130. decoder = new bomHandling.StripBOM(decoder, options);
  71131. return decoder;
  71132. }
  71133. // Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json.
  71134. var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node;
  71135. if (nodeVer) {
  71136. // Load streaming support in Node v0.10+
  71137. var nodeVerArr = nodeVer.split(".").map(Number);
  71138. if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) {
  71139. require("./streams")(iconv);
  71140. }
  71141. // Load Node primitive extensions.
  71142. require("./extend-node")(iconv);
  71143. }
  71144. if ("Ā" != "\u0100") {
  71145. console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.");
  71146. }
  71147. }).call(this)}).call(this,require('_process'))
  71148. },{"../encodings":376,"./bom-handling":392,"./extend-node":144,"./streams":144,"_process":525,"safer-buffer":562}],394:[function(require,module,exports){
  71149. /**
  71150. * Helpers.
  71151. */
  71152. var s = 1000;
  71153. var m = s * 60;
  71154. var h = m * 60;
  71155. var d = h * 24;
  71156. var w = d * 7;
  71157. var y = d * 365.25;
  71158. /**
  71159. * Parse or format the given `val`.
  71160. *
  71161. * Options:
  71162. *
  71163. * - `long` verbose formatting [false]
  71164. *
  71165. * @param {String|Number} val
  71166. * @param {Object} [options]
  71167. * @throws {Error} throw an error if val is not a non-empty string or a number
  71168. * @return {String|Number}
  71169. * @api public
  71170. */
  71171. module.exports = function(val, options) {
  71172. options = options || {};
  71173. var type = typeof val;
  71174. if (type === 'string' && val.length > 0) {
  71175. return parse(val);
  71176. } else if (type === 'number' && isFinite(val)) {
  71177. return options.long ? fmtLong(val) : fmtShort(val);
  71178. }
  71179. throw new Error(
  71180. 'val is not a non-empty string or a valid number. val=' +
  71181. JSON.stringify(val)
  71182. );
  71183. };
  71184. /**
  71185. * Parse the given `str` and return milliseconds.
  71186. *
  71187. * @param {String} str
  71188. * @return {Number}
  71189. * @api private
  71190. */
  71191. function parse(str) {
  71192. str = String(str);
  71193. if (str.length > 100) {
  71194. return;
  71195. }
  71196. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  71197. str
  71198. );
  71199. if (!match) {
  71200. return;
  71201. }
  71202. var n = parseFloat(match[1]);
  71203. var type = (match[2] || 'ms').toLowerCase();
  71204. switch (type) {
  71205. case 'years':
  71206. case 'year':
  71207. case 'yrs':
  71208. case 'yr':
  71209. case 'y':
  71210. return n * y;
  71211. case 'weeks':
  71212. case 'week':
  71213. case 'w':
  71214. return n * w;
  71215. case 'days':
  71216. case 'day':
  71217. case 'd':
  71218. return n * d;
  71219. case 'hours':
  71220. case 'hour':
  71221. case 'hrs':
  71222. case 'hr':
  71223. case 'h':
  71224. return n * h;
  71225. case 'minutes':
  71226. case 'minute':
  71227. case 'mins':
  71228. case 'min':
  71229. case 'm':
  71230. return n * m;
  71231. case 'seconds':
  71232. case 'second':
  71233. case 'secs':
  71234. case 'sec':
  71235. case 's':
  71236. return n * s;
  71237. case 'milliseconds':
  71238. case 'millisecond':
  71239. case 'msecs':
  71240. case 'msec':
  71241. case 'ms':
  71242. return n;
  71243. default:
  71244. return undefined;
  71245. }
  71246. }
  71247. /**
  71248. * Short format for `ms`.
  71249. *
  71250. * @param {Number} ms
  71251. * @return {String}
  71252. * @api private
  71253. */
  71254. function fmtShort(ms) {
  71255. var msAbs = Math.abs(ms);
  71256. if (msAbs >= d) {
  71257. return Math.round(ms / d) + 'd';
  71258. }
  71259. if (msAbs >= h) {
  71260. return Math.round(ms / h) + 'h';
  71261. }
  71262. if (msAbs >= m) {
  71263. return Math.round(ms / m) + 'm';
  71264. }
  71265. if (msAbs >= s) {
  71266. return Math.round(ms / s) + 's';
  71267. }
  71268. return ms + 'ms';
  71269. }
  71270. /**
  71271. * Long format for `ms`.
  71272. *
  71273. * @param {Number} ms
  71274. * @return {String}
  71275. * @api private
  71276. */
  71277. function fmtLong(ms) {
  71278. var msAbs = Math.abs(ms);
  71279. if (msAbs >= d) {
  71280. return plural(ms, msAbs, d, 'day');
  71281. }
  71282. if (msAbs >= h) {
  71283. return plural(ms, msAbs, h, 'hour');
  71284. }
  71285. if (msAbs >= m) {
  71286. return plural(ms, msAbs, m, 'minute');
  71287. }
  71288. if (msAbs >= s) {
  71289. return plural(ms, msAbs, s, 'second');
  71290. }
  71291. return ms + ' ms';
  71292. }
  71293. /**
  71294. * Pluralization helper.
  71295. */
  71296. function plural(ms, msAbs, n, name) {
  71297. var isPlural = msAbs >= n * 1.5;
  71298. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  71299. }
  71300. },{}],395:[function(require,module,exports){
  71301. arguments[4][172][0].apply(exports,arguments)
  71302. },{"dup":172}],396:[function(require,module,exports){
  71303. arguments[4][173][0].apply(exports,arguments)
  71304. },{"./_stream_readable":398,"./_stream_writable":400,"_process":525,"dup":173,"inherits":320}],397:[function(require,module,exports){
  71305. arguments[4][174][0].apply(exports,arguments)
  71306. },{"./_stream_transform":399,"dup":174,"inherits":320}],398:[function(require,module,exports){
  71307. arguments[4][175][0].apply(exports,arguments)
  71308. },{"../errors":395,"./_stream_duplex":396,"./internal/streams/async_iterator":401,"./internal/streams/buffer_list":402,"./internal/streams/destroy":403,"./internal/streams/from":405,"./internal/streams/state":407,"./internal/streams/stream":408,"_process":525,"buffer":193,"dup":175,"events":247,"inherits":320,"string_decoder/":631,"util":144}],399:[function(require,module,exports){
  71309. arguments[4][176][0].apply(exports,arguments)
  71310. },{"../errors":395,"./_stream_duplex":396,"dup":176,"inherits":320}],400:[function(require,module,exports){
  71311. arguments[4][177][0].apply(exports,arguments)
  71312. },{"../errors":395,"./_stream_duplex":396,"./internal/streams/destroy":403,"./internal/streams/state":407,"./internal/streams/stream":408,"_process":525,"buffer":193,"dup":177,"inherits":320,"util-deprecate":655}],401:[function(require,module,exports){
  71313. arguments[4][178][0].apply(exports,arguments)
  71314. },{"./end-of-stream":404,"_process":525,"dup":178}],402:[function(require,module,exports){
  71315. arguments[4][179][0].apply(exports,arguments)
  71316. },{"buffer":193,"dup":179,"util":144}],403:[function(require,module,exports){
  71317. arguments[4][180][0].apply(exports,arguments)
  71318. },{"_process":525,"dup":180}],404:[function(require,module,exports){
  71319. arguments[4][181][0].apply(exports,arguments)
  71320. },{"../../../errors":395,"dup":181}],405:[function(require,module,exports){
  71321. arguments[4][182][0].apply(exports,arguments)
  71322. },{"dup":182}],406:[function(require,module,exports){
  71323. arguments[4][183][0].apply(exports,arguments)
  71324. },{"../../../errors":395,"./end-of-stream":404,"dup":183}],407:[function(require,module,exports){
  71325. arguments[4][184][0].apply(exports,arguments)
  71326. },{"../../../errors":395,"dup":184}],408:[function(require,module,exports){
  71327. arguments[4][185][0].apply(exports,arguments)
  71328. },{"dup":185,"events":247}],409:[function(require,module,exports){
  71329. arguments[4][186][0].apply(exports,arguments)
  71330. },{"./lib/_stream_duplex.js":396,"./lib/_stream_passthrough.js":397,"./lib/_stream_readable.js":398,"./lib/_stream_transform.js":399,"./lib/_stream_writable.js":400,"./lib/internal/streams/end-of-stream.js":404,"./lib/internal/streams/pipeline.js":406,"dup":186}],410:[function(require,module,exports){
  71331. /* global window, exports, define */
  71332. !function() {
  71333. 'use strict'
  71334. var re = {
  71335. not_string: /[^s]/,
  71336. not_bool: /[^t]/,
  71337. not_type: /[^T]/,
  71338. not_primitive: /[^v]/,
  71339. number: /[diefg]/,
  71340. numeric_arg: /[bcdiefguxX]/,
  71341. json: /[j]/,
  71342. not_json: /[^j]/,
  71343. text: /^[^\x25]+/,
  71344. modulo: /^\x25{2}/,
  71345. placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
  71346. key: /^([a-z_][a-z_\d]*)/i,
  71347. key_access: /^\.([a-z_][a-z_\d]*)/i,
  71348. index_access: /^\[(\d+)\]/,
  71349. sign: /^[+-]/
  71350. }
  71351. function sprintf(key) {
  71352. // `arguments` is not an array, but should be fine for this call
  71353. return sprintf_format(sprintf_parse(key), arguments)
  71354. }
  71355. function vsprintf(fmt, argv) {
  71356. return sprintf.apply(null, [fmt].concat(argv || []))
  71357. }
  71358. function sprintf_format(parse_tree, argv) {
  71359. var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
  71360. for (i = 0; i < tree_length; i++) {
  71361. if (typeof parse_tree[i] === 'string') {
  71362. output += parse_tree[i]
  71363. }
  71364. else if (typeof parse_tree[i] === 'object') {
  71365. ph = parse_tree[i] // convenience purposes only
  71366. if (ph.keys) { // keyword argument
  71367. arg = argv[cursor]
  71368. for (k = 0; k < ph.keys.length; k++) {
  71369. if (arg == undefined) {
  71370. throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
  71371. }
  71372. arg = arg[ph.keys[k]]
  71373. }
  71374. }
  71375. else if (ph.param_no) { // positional argument (explicit)
  71376. arg = argv[ph.param_no]
  71377. }
  71378. else { // positional argument (implicit)
  71379. arg = argv[cursor++]
  71380. }
  71381. if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
  71382. arg = arg()
  71383. }
  71384. if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
  71385. throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
  71386. }
  71387. if (re.number.test(ph.type)) {
  71388. is_positive = arg >= 0
  71389. }
  71390. switch (ph.type) {
  71391. case 'b':
  71392. arg = parseInt(arg, 10).toString(2)
  71393. break
  71394. case 'c':
  71395. arg = String.fromCharCode(parseInt(arg, 10))
  71396. break
  71397. case 'd':
  71398. case 'i':
  71399. arg = parseInt(arg, 10)
  71400. break
  71401. case 'j':
  71402. arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
  71403. break
  71404. case 'e':
  71405. arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
  71406. break
  71407. case 'f':
  71408. arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
  71409. break
  71410. case 'g':
  71411. arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
  71412. break
  71413. case 'o':
  71414. arg = (parseInt(arg, 10) >>> 0).toString(8)
  71415. break
  71416. case 's':
  71417. arg = String(arg)
  71418. arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
  71419. break
  71420. case 't':
  71421. arg = String(!!arg)
  71422. arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
  71423. break
  71424. case 'T':
  71425. arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
  71426. arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
  71427. break
  71428. case 'u':
  71429. arg = parseInt(arg, 10) >>> 0
  71430. break
  71431. case 'v':
  71432. arg = arg.valueOf()
  71433. arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
  71434. break
  71435. case 'x':
  71436. arg = (parseInt(arg, 10) >>> 0).toString(16)
  71437. break
  71438. case 'X':
  71439. arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
  71440. break
  71441. }
  71442. if (re.json.test(ph.type)) {
  71443. output += arg
  71444. }
  71445. else {
  71446. if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
  71447. sign = is_positive ? '+' : '-'
  71448. arg = arg.toString().replace(re.sign, '')
  71449. }
  71450. else {
  71451. sign = ''
  71452. }
  71453. pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
  71454. pad_length = ph.width - (sign + arg).length
  71455. pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
  71456. output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
  71457. }
  71458. }
  71459. }
  71460. return output
  71461. }
  71462. var sprintf_cache = Object.create(null)
  71463. function sprintf_parse(fmt) {
  71464. if (sprintf_cache[fmt]) {
  71465. return sprintf_cache[fmt]
  71466. }
  71467. var _fmt = fmt, match, parse_tree = [], arg_names = 0
  71468. while (_fmt) {
  71469. if ((match = re.text.exec(_fmt)) !== null) {
  71470. parse_tree.push(match[0])
  71471. }
  71472. else if ((match = re.modulo.exec(_fmt)) !== null) {
  71473. parse_tree.push('%')
  71474. }
  71475. else if ((match = re.placeholder.exec(_fmt)) !== null) {
  71476. if (match[2]) {
  71477. arg_names |= 1
  71478. var field_list = [], replacement_field = match[2], field_match = []
  71479. if ((field_match = re.key.exec(replacement_field)) !== null) {
  71480. field_list.push(field_match[1])
  71481. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  71482. if ((field_match = re.key_access.exec(replacement_field)) !== null) {
  71483. field_list.push(field_match[1])
  71484. }
  71485. else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
  71486. field_list.push(field_match[1])
  71487. }
  71488. else {
  71489. throw new SyntaxError('[sprintf] failed to parse named argument key')
  71490. }
  71491. }
  71492. }
  71493. else {
  71494. throw new SyntaxError('[sprintf] failed to parse named argument key')
  71495. }
  71496. match[2] = field_list
  71497. }
  71498. else {
  71499. arg_names |= 2
  71500. }
  71501. if (arg_names === 3) {
  71502. throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
  71503. }
  71504. parse_tree.push(
  71505. {
  71506. placeholder: match[0],
  71507. param_no: match[1],
  71508. keys: match[2],
  71509. sign: match[3],
  71510. pad_char: match[4],
  71511. align: match[5],
  71512. width: match[6],
  71513. precision: match[7],
  71514. type: match[8]
  71515. }
  71516. )
  71517. }
  71518. else {
  71519. throw new SyntaxError('[sprintf] unexpected placeholder')
  71520. }
  71521. _fmt = _fmt.substring(match[0].length)
  71522. }
  71523. return sprintf_cache[fmt] = parse_tree
  71524. }
  71525. /**
  71526. * export to either browser or node.js
  71527. */
  71528. /* eslint-disable quote-props */
  71529. if (typeof exports !== 'undefined') {
  71530. exports['sprintf'] = sprintf
  71531. exports['vsprintf'] = vsprintf
  71532. }
  71533. if (typeof window !== 'undefined') {
  71534. window['sprintf'] = sprintf
  71535. window['vsprintf'] = vsprintf
  71536. if (typeof define === 'function' && define['amd']) {
  71537. define(function() {
  71538. return {
  71539. 'sprintf': sprintf,
  71540. 'vsprintf': vsprintf
  71541. }
  71542. })
  71543. }
  71544. }
  71545. /* eslint-enable quote-props */
  71546. }(); // eslint-disable-line
  71547. },{}],411:[function(require,module,exports){
  71548. "use strict";
  71549. Object.defineProperty(exports, "__esModule", {
  71550. value: true
  71551. });
  71552. exports.writeToTrackingBuffer = writeToTrackingBuffer;
  71553. const TYPE = {
  71554. QUERY_NOTIFICATIONS: 1,
  71555. TXN_DESCRIPTOR: 2,
  71556. TRACE_ACTIVITY: 3
  71557. };
  71558. const TXNDESCRIPTOR_HEADER_DATA_LEN = 4 + 8;
  71559. const TXNDESCRIPTOR_HEADER_LEN = 4 + 2 + TXNDESCRIPTOR_HEADER_DATA_LEN;
  71560. function writeToTrackingBuffer(buffer, txnDescriptor, outstandingRequestCount) {
  71561. buffer.writeUInt32LE(0);
  71562. buffer.writeUInt32LE(TXNDESCRIPTOR_HEADER_LEN);
  71563. buffer.writeUInt16LE(TYPE.TXN_DESCRIPTOR);
  71564. buffer.writeBuffer(txnDescriptor);
  71565. buffer.writeUInt32LE(outstandingRequestCount);
  71566. const data = buffer.data;
  71567. data.writeUInt32LE(data.length, 0);
  71568. return buffer;
  71569. }
  71570. },{}],412:[function(require,module,exports){
  71571. (function (process){(function (){
  71572. "use strict";
  71573. Object.defineProperty(exports, "__esModule", {
  71574. value: true
  71575. });
  71576. exports.default = void 0;
  71577. var _events = require("events");
  71578. var _writableTrackingBuffer = _interopRequireDefault(require("./tracking-buffer/writable-tracking-buffer"));
  71579. var _readableStream = require("readable-stream");
  71580. var _token = require("./token/token");
  71581. var _message = _interopRequireDefault(require("./message"));
  71582. var _packet = require("./packet");
  71583. var _errors = require("./errors");
  71584. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  71585. const FLAGS = {
  71586. nullable: 1 << 0,
  71587. caseSen: 1 << 1,
  71588. updateableReadWrite: 1 << 2,
  71589. updateableUnknown: 1 << 3,
  71590. identity: 1 << 4,
  71591. computed: 1 << 5,
  71592. // introduced in TDS 7.2
  71593. fixedLenCLRType: 1 << 8,
  71594. // introduced in TDS 7.2
  71595. sparseColumnSet: 1 << 10,
  71596. // introduced in TDS 7.3.B
  71597. hidden: 1 << 13,
  71598. // introduced in TDS 7.2
  71599. key: 1 << 14,
  71600. // introduced in TDS 7.2
  71601. nullableUnknown: 1 << 15 // introduced in TDS 7.2
  71602. };
  71603. const DONE_STATUS = {
  71604. FINAL: 0x00,
  71605. MORE: 0x1,
  71606. ERROR: 0x2,
  71607. INXACT: 0x4,
  71608. COUNT: 0x10,
  71609. ATTN: 0x20,
  71610. SRVERROR: 0x100
  71611. };
  71612. class BulkLoad extends _events.EventEmitter {
  71613. constructor(table, connectionOptions, {
  71614. checkConstraints = false,
  71615. fireTriggers = false,
  71616. keepNulls = false,
  71617. lockTable = false
  71618. }, callback) {
  71619. if (typeof checkConstraints !== 'boolean') {
  71620. throw new TypeError('The "options.checkConstraints" property must be of type boolean.');
  71621. }
  71622. if (typeof fireTriggers !== 'boolean') {
  71623. throw new TypeError('The "options.fireTriggers" property must be of type boolean.');
  71624. }
  71625. if (typeof keepNulls !== 'boolean') {
  71626. throw new TypeError('The "options.keepNulls" property must be of type boolean.');
  71627. }
  71628. if (typeof lockTable !== 'boolean') {
  71629. throw new TypeError('The "options.lockTable" property must be of type boolean.');
  71630. }
  71631. super();
  71632. this.error = void 0;
  71633. this.canceled = void 0;
  71634. this.executionStarted = void 0;
  71635. this.streamingMode = void 0;
  71636. this.table = void 0;
  71637. this.connection = void 0;
  71638. this.timeout = void 0;
  71639. this.rows = void 0;
  71640. this.rst = void 0;
  71641. this.rowCount = void 0;
  71642. this.paused = void 0;
  71643. this.options = void 0;
  71644. this.callback = void 0;
  71645. this.columns = void 0;
  71646. this.columnsByName = void 0;
  71647. this.firstRowWritten = void 0;
  71648. this.rowToPacketTransform = void 0;
  71649. this.bulkOptions = void 0;
  71650. this.error = undefined;
  71651. this.canceled = false;
  71652. this.executionStarted = false;
  71653. this.table = table;
  71654. this.options = connectionOptions;
  71655. this.callback = callback;
  71656. this.columns = [];
  71657. this.columnsByName = {};
  71658. this.firstRowWritten = false;
  71659. this.streamingMode = false;
  71660. this.rowToPacketTransform = new RowTransform(this); // eslint-disable-line no-use-before-define
  71661. this.bulkOptions = {
  71662. checkConstraints,
  71663. fireTriggers,
  71664. keepNulls,
  71665. lockTable
  71666. };
  71667. }
  71668. addColumn(name, type, {
  71669. output = false,
  71670. length,
  71671. precision,
  71672. scale,
  71673. objName = name,
  71674. nullable = true
  71675. }) {
  71676. if (this.firstRowWritten) {
  71677. throw new Error('Columns cannot be added to bulk insert after the first row has been written.');
  71678. }
  71679. if (this.executionStarted) {
  71680. throw new Error('Columns cannot be added to bulk insert after execution has started.');
  71681. }
  71682. const column = {
  71683. type: type,
  71684. name: name,
  71685. value: null,
  71686. output: output,
  71687. length: length,
  71688. precision: precision,
  71689. scale: scale,
  71690. objName: objName,
  71691. nullable: nullable
  71692. };
  71693. if ((type.id & 0x30) === 0x20) {
  71694. if (column.length == null && type.resolveLength) {
  71695. column.length = type.resolveLength(column);
  71696. }
  71697. }
  71698. if (type.resolvePrecision && column.precision == null) {
  71699. column.precision = type.resolvePrecision(column);
  71700. }
  71701. if (type.resolveScale && column.scale == null) {
  71702. column.scale = type.resolveScale(column);
  71703. }
  71704. this.columns.push(column);
  71705. this.columnsByName[name] = column;
  71706. }
  71707. addRow(...input) {
  71708. this.firstRowWritten = true;
  71709. let row;
  71710. if (input.length > 1 || !input[0] || typeof input[0] !== 'object') {
  71711. row = input;
  71712. } else {
  71713. row = input[0];
  71714. } // write each column
  71715. if (Array.isArray(row)) {
  71716. this.rowToPacketTransform.write(row);
  71717. } else {
  71718. const object = row;
  71719. this.rowToPacketTransform.write(this.columns.map(column => {
  71720. return object[column.objName];
  71721. }));
  71722. }
  71723. }
  71724. getOptionsSql() {
  71725. const addOptions = [];
  71726. if (this.bulkOptions.checkConstraints) {
  71727. addOptions.push('CHECK_CONSTRAINTS');
  71728. }
  71729. if (this.bulkOptions.fireTriggers) {
  71730. addOptions.push('FIRE_TRIGGERS');
  71731. }
  71732. if (this.bulkOptions.keepNulls) {
  71733. addOptions.push('KEEP_NULLS');
  71734. }
  71735. if (this.bulkOptions.lockTable) {
  71736. addOptions.push('TABLOCK');
  71737. }
  71738. if (addOptions.length > 0) {
  71739. return ` WITH (${addOptions.join(',')})`;
  71740. } else {
  71741. return '';
  71742. }
  71743. }
  71744. getBulkInsertSql() {
  71745. let sql = 'insert bulk ' + this.table + '(';
  71746. for (let i = 0, len = this.columns.length; i < len; i++) {
  71747. const c = this.columns[i];
  71748. if (i !== 0) {
  71749. sql += ', ';
  71750. }
  71751. sql += '[' + c.name + '] ' + c.type.declaration(c);
  71752. }
  71753. sql += ')';
  71754. sql += this.getOptionsSql();
  71755. return sql;
  71756. }
  71757. getTableCreationSql() {
  71758. let sql = 'CREATE TABLE ' + this.table + '(\n';
  71759. for (let i = 0, len = this.columns.length; i < len; i++) {
  71760. const c = this.columns[i];
  71761. if (i !== 0) {
  71762. sql += ',\n';
  71763. }
  71764. sql += '[' + c.name + '] ' + c.type.declaration(c);
  71765. if (c.nullable !== undefined) {
  71766. sql += ' ' + (c.nullable ? 'NULL' : 'NOT NULL');
  71767. }
  71768. }
  71769. sql += '\n)';
  71770. return sql;
  71771. }
  71772. getColMetaData() {
  71773. const tBuf = new _writableTrackingBuffer.default(100, null, true); // TokenType
  71774. tBuf.writeUInt8(_token.TYPE.COLMETADATA); // Count
  71775. tBuf.writeUInt16LE(this.columns.length);
  71776. for (let j = 0, len = this.columns.length; j < len; j++) {
  71777. const c = this.columns[j]; // UserType
  71778. if (this.options.tdsVersion < '7_2') {
  71779. tBuf.writeUInt16LE(0);
  71780. } else {
  71781. tBuf.writeUInt32LE(0);
  71782. } // Flags
  71783. let flags = FLAGS.updateableReadWrite;
  71784. if (c.nullable) {
  71785. flags |= FLAGS.nullable;
  71786. } else if (c.nullable === undefined && this.options.tdsVersion >= '7_2') {
  71787. flags |= FLAGS.nullableUnknown;
  71788. }
  71789. tBuf.writeUInt16LE(flags); // TYPE_INFO
  71790. c.type.writeTypeInfo(tBuf, c, this.options); // ColName
  71791. tBuf.writeBVarchar(c.name, 'ucs2');
  71792. }
  71793. return tBuf.data;
  71794. }
  71795. setTimeout(timeout) {
  71796. this.timeout = timeout;
  71797. }
  71798. createDoneToken() {
  71799. // It might be nice to make DoneToken a class if anything needs to create them, but for now, just do it here
  71800. const tBuf = new _writableTrackingBuffer.default(this.options.tdsVersion < '7_2' ? 9 : 13);
  71801. tBuf.writeUInt8(_token.TYPE.DONE);
  71802. const status = DONE_STATUS.FINAL;
  71803. tBuf.writeUInt16LE(status);
  71804. tBuf.writeUInt16LE(0); // CurCmd (TDS ignores this)
  71805. tBuf.writeUInt32LE(0); // row count - doesn't really matter
  71806. if (this.options.tdsVersion >= '7_2') {
  71807. tBuf.writeUInt32LE(0); // row count is 64 bits in >= TDS 7.2
  71808. }
  71809. return tBuf.data;
  71810. } // This method switches the BulkLoad object into streaming mode and returns
  71811. // a stream.Writable for streaming rows to the server.
  71812. getRowStream() {
  71813. if (this.firstRowWritten) {
  71814. throw new Error('BulkLoad cannot be switched to streaming mode after first row has been written using addRow().');
  71815. }
  71816. if (this.executionStarted) {
  71817. throw new Error('BulkLoad cannot be switched to streaming mode after execution has started.');
  71818. }
  71819. this.streamingMode = true;
  71820. return this.rowToPacketTransform;
  71821. }
  71822. getMessageStream() {
  71823. const message = new _message.default({
  71824. type: _packet.TYPE.BULK_LOAD
  71825. });
  71826. this.rowToPacketTransform.pipe(message);
  71827. this.rowToPacketTransform.once('finish', () => {
  71828. this.removeListener('cancel', onCancel);
  71829. });
  71830. const onCancel = () => {
  71831. this.rowToPacketTransform.emit('error', (0, _errors.RequestError)('Canceled.', 'ECANCEL'));
  71832. this.rowToPacketTransform.destroy();
  71833. };
  71834. this.once('cancel', onCancel);
  71835. return message;
  71836. }
  71837. cancel() {
  71838. if (this.canceled) {
  71839. return;
  71840. }
  71841. this.canceled = true;
  71842. this.emit('cancel');
  71843. }
  71844. }
  71845. var _default = BulkLoad;
  71846. exports.default = _default;
  71847. module.exports = BulkLoad; // A transform that converts rows to packets.
  71848. class RowTransform extends _readableStream.Transform {
  71849. constructor(bulkLoad) {
  71850. super({
  71851. writableObjectMode: true
  71852. });
  71853. this.columnMetadataWritten = void 0;
  71854. this.bulkLoad = void 0;
  71855. this.mainOptions = void 0;
  71856. this.columns = void 0;
  71857. this.bulkLoad = bulkLoad;
  71858. this.mainOptions = bulkLoad.options;
  71859. this.columns = bulkLoad.columns;
  71860. this.columnMetadataWritten = false;
  71861. }
  71862. _transform(row, _encoding, callback) {
  71863. if (!this.columnMetadataWritten) {
  71864. this.push(this.bulkLoad.getColMetaData());
  71865. this.columnMetadataWritten = true;
  71866. }
  71867. const buf = new _writableTrackingBuffer.default(64, 'ucs2', true);
  71868. buf.writeUInt8(_token.TYPE.ROW);
  71869. for (let i = 0; i < this.columns.length; i++) {
  71870. const c = this.columns[i];
  71871. c.type.writeParameterData(buf, {
  71872. length: c.length,
  71873. scale: c.scale,
  71874. precision: c.precision,
  71875. value: row[i]
  71876. }, this.mainOptions, () => {});
  71877. }
  71878. this.push(buf.data);
  71879. process.nextTick(callback);
  71880. }
  71881. _flush(callback) {
  71882. this.push(this.bulkLoad.createDoneToken());
  71883. process.nextTick(callback);
  71884. }
  71885. }
  71886. }).call(this)}).call(this,require('_process'))
  71887. },{"./errors":457,"./message":464,"./packet":469,"./token/token":492,"./tracking-buffer/writable-tracking-buffer":493,"_process":525,"events":247,"readable-stream":409}],413:[function(require,module,exports){
  71888. "use strict";
  71889. Object.defineProperty(exports, "__esModule", {
  71890. value: true
  71891. });
  71892. exports.codepageBySortId = exports.codepageByLcid = void 0;
  71893. // http://technet.microsoft.com/en-us/library/aa176553(v=sql.80).aspx
  71894. const codepageByLcid = {
  71895. [0x436]: 'CP1252',
  71896. [0x401]: 'CP1256',
  71897. [0x801]: 'CP1256',
  71898. [0xC01]: 'CP1256',
  71899. [0x1001]: 'CP1256',
  71900. [0x1401]: 'CP1256',
  71901. [0x1801]: 'CP1256',
  71902. [0x1C01]: 'CP1256',
  71903. [0x2001]: 'CP1256',
  71904. [0x2401]: 'CP1256',
  71905. [0x2801]: 'CP1256',
  71906. [0x2C01]: 'CP1256',
  71907. [0x3001]: 'CP1256',
  71908. [0x3401]: 'CP1256',
  71909. [0x3801]: 'CP1256',
  71910. [0x3C01]: 'CP1256',
  71911. [0x4001]: 'CP1256',
  71912. [0x42D]: 'CP1252',
  71913. [0x423]: 'CP1251',
  71914. [0x402]: 'CP1251',
  71915. [0x403]: 'CP1252',
  71916. [0x30404]: 'CP950',
  71917. [0x404]: 'CP950',
  71918. [0x804]: 'CP936',
  71919. [0x20804]: 'CP936',
  71920. [0x1004]: 'CP936',
  71921. [0x41a]: 'CP1250',
  71922. [0x405]: 'CP1250',
  71923. [0x406]: 'CP1252',
  71924. [0x413]: 'CP1252',
  71925. [0x813]: 'CP1252',
  71926. [0x409]: 'CP1252',
  71927. [0x809]: 'CP1252',
  71928. [0x1009]: 'CP1252',
  71929. [0x1409]: 'CP1252',
  71930. [0xC09]: 'CP1252',
  71931. [0x1809]: 'CP1252',
  71932. [0x1C09]: 'CP1252',
  71933. [0x2409]: 'CP1252',
  71934. [0x2009]: 'CP1252',
  71935. [0x425]: 'CP1257',
  71936. [0x0438]: 'CP1252',
  71937. [0x429]: 'CP1256',
  71938. [0x40B]: 'CP1252',
  71939. [0x40C]: 'CP1252',
  71940. [0x80C]: 'CP1252',
  71941. [0x100C]: 'CP1252',
  71942. [0xC0C]: 'CP1252',
  71943. [0x140C]: 'CP1252',
  71944. [0x10437]: 'CP1252',
  71945. [0x10407]: 'CP1252',
  71946. [0x407]: 'CP1252',
  71947. [0x807]: 'CP1252',
  71948. [0xC07]: 'CP1252',
  71949. [0x1007]: 'CP1252',
  71950. [0x1407]: 'CP1252',
  71951. [0x408]: 'CP1253',
  71952. [0x40D]: 'CP1255',
  71953. [0x439]: 'CPUTF8',
  71954. [0x40E]: 'CP1250',
  71955. [0x104E]: 'CP1250',
  71956. [0x40F]: 'CP1252',
  71957. [0x421]: 'CP1252',
  71958. [0x410]: 'CP1252',
  71959. [0x810]: 'CP1252',
  71960. [0x411]: 'CP932',
  71961. [0x10411]: 'CP932',
  71962. [0x412]: 'CP949',
  71963. [0x426]: 'CP1257',
  71964. [0x427]: 'CP1257',
  71965. [0x827]: 'CP1257',
  71966. [0x41C]: 'CP1251',
  71967. [0x414]: 'CP1252',
  71968. [0x814]: 'CP1252',
  71969. [0x415]: 'CP1250',
  71970. [0x816]: 'CP1252',
  71971. [0x416]: 'CP1252',
  71972. [0x418]: 'CP1250',
  71973. [0x419]: 'CP1251',
  71974. [0x81A]: 'CP1251',
  71975. [0xC1A]: 'CP1251',
  71976. [0x41B]: 'CP1250',
  71977. [0x424]: 'CP1250',
  71978. [0x80A]: 'CP1252',
  71979. [0x40A]: 'CP1252',
  71980. [0xC0A]: 'CP1252',
  71981. [0x100A]: 'CP1252',
  71982. [0x140A]: 'CP1252',
  71983. [0x180A]: 'CP1252',
  71984. [0x1C0A]: 'CP1252',
  71985. [0x200A]: 'CP1252',
  71986. [0x240A]: 'CP1252',
  71987. [0x280A]: 'CP1252',
  71988. [0x2C0A]: 'CP1252',
  71989. [0x300A]: 'CP1252',
  71990. [0x340A]: 'CP1252',
  71991. [0x380A]: 'CP1252',
  71992. [0x3C0A]: 'CP1252',
  71993. [0x400A]: 'CP1252',
  71994. [0x41D]: 'CP1252',
  71995. [0x41E]: 'CP874',
  71996. [0x41F]: 'CP1254',
  71997. [0x422]: 'CP1251',
  71998. [0x420]: 'CP1256',
  71999. [0x42A]: 'CP1258'
  72000. };
  72001. exports.codepageByLcid = codepageByLcid;
  72002. const codepageBySortId = {
  72003. [30]: 'CP437',
  72004. // SQL_Latin1_General_CP437_BIN
  72005. [31]: 'CP437',
  72006. // SQL_Latin1_General_CP437_CS_AS
  72007. [32]: 'CP437',
  72008. // SQL_Latin1_General_CP437_CI_AS
  72009. [33]: 'CP437',
  72010. // SQL_Latin1_General_Pref_CP437_CI_AS
  72011. [34]: 'CP437',
  72012. // SQL_Latin1_General_CP437_CI_AI
  72013. [40]: 'CP850',
  72014. // SQL_Latin1_General_CP850_BIN
  72015. [41]: 'CP850',
  72016. // SQL_Latin1_General_CP850_CS_AS
  72017. [42]: 'CP850',
  72018. // SQL_Latin1_General_CP850_CI_AS
  72019. [43]: 'CP850',
  72020. // SQL_Latin1_General_Pref_CP850_CI_AS
  72021. [44]: 'CP850',
  72022. // SQL_Latin1_General_CP850_CI_AI
  72023. [49]: 'CP850',
  72024. // SQL_1xCompat_CP850_CI_AS
  72025. [51]: 'CP1252',
  72026. // SQL_Latin1_General_Cp1_CS_AS_KI_WI
  72027. [52]: 'CP1252',
  72028. // SQL_Latin1_General_Cp1_CI_AS_KI_WI
  72029. [53]: 'CP1252',
  72030. // SQL_Latin1_General_Pref_Cp1_CI_AS_KI_WI
  72031. [54]: 'CP1252',
  72032. // SQL_Latin1_General_Cp1_CI_AI_KI_WI
  72033. [55]: 'CP850',
  72034. // SQL_AltDiction_CP850_CS_AS
  72035. [56]: 'CP850',
  72036. // SQL_AltDiction_Pref_CP850_CI_AS
  72037. [57]: 'CP850',
  72038. // SQL_AltDiction_CP850_CI_AI
  72039. [58]: 'CP850',
  72040. // SQL_Scandinavian_Pref_CP850_CI_AS
  72041. [59]: 'CP850',
  72042. // SQL_Scandinavian_CP850_CS_AS
  72043. [60]: 'CP850',
  72044. // SQL_Scandinavian_CP850_CI_AS
  72045. [61]: 'CP850',
  72046. // SQL_AltDiction_CP850_CI_AS
  72047. [80]: 'CP1250',
  72048. // SQL_Latin1_General_1250_BIN
  72049. [81]: 'CP1250',
  72050. // SQL_Latin1_General_CP1250_CS_AS
  72051. [82]: 'CP1250',
  72052. // SQL_Latin1_General_Cp1250_CI_AS_KI_WI
  72053. [83]: 'CP1250',
  72054. // SQL_Czech_Cp1250_CS_AS_KI_WI
  72055. [84]: 'CP1250',
  72056. // SQL_Czech_Cp1250_CI_AS_KI_WI
  72057. [85]: 'CP1250',
  72058. // SQL_Hungarian_Cp1250_CS_AS_KI_WI
  72059. [86]: 'CP1250',
  72060. // SQL_Hungarian_Cp1250_CI_AS_KI_WI
  72061. [87]: 'CP1250',
  72062. // SQL_Polish_Cp1250_CS_AS_KI_WI
  72063. [88]: 'CP1250',
  72064. // SQL_Polish_Cp1250_CI_AS_KI_WI
  72065. [89]: 'CP1250',
  72066. // SQL_Romanian_Cp1250_CS_AS_KI_WI
  72067. [90]: 'CP1250',
  72068. // SQL_Romanian_Cp1250_CI_AS_KI_WI
  72069. [91]: 'CP1250',
  72070. // SQL_Croatian_Cp1250_CS_AS_KI_WI
  72071. [92]: 'CP1250',
  72072. // SQL_Croatian_Cp1250_CI_AS_KI_WI
  72073. [93]: 'CP1250',
  72074. // SQL_Slovak_Cp1250_CS_AS_KI_WI
  72075. [94]: 'CP1250',
  72076. // SQL_Slovak_Cp1250_CI_AS_KI_WI
  72077. [95]: 'CP1250',
  72078. // SQL_Slovenian_Cp1250_CS_AS_KI_WI
  72079. [96]: 'CP1250',
  72080. // SQL_Slovenian_Cp1250_CI_AS_KI_WI
  72081. [104]: 'CP1251',
  72082. // SQL_Latin1_General_1251_BIN
  72083. [105]: 'CP1251',
  72084. // SQL_Latin1_General_CP1251_CS_AS
  72085. [106]: 'CP1251',
  72086. // SQL_Latin1_General_CP1251_CI_AS
  72087. [107]: 'CP1251',
  72088. // SQL_Ukrainian_Cp1251_CS_AS_KI_WI
  72089. [108]: 'CP1251',
  72090. // SQL_Ukrainian_Cp1251_CI_AS_KI_WI
  72091. [112]: 'CP1253',
  72092. // SQL_Latin1_General_1253_BIN
  72093. [113]: 'CP1253',
  72094. // SQL_Latin1_General_CP1253_CS_AS
  72095. [114]: 'CP1253',
  72096. // SQL_Latin1_General_CP1253_CI_AS
  72097. [120]: 'CP1253',
  72098. // SQL_MixDiction_CP1253_CS_AS
  72099. [121]: 'CP1253',
  72100. // SQL_AltDiction_CP1253_CS_AS
  72101. [122]: 'CP1253',
  72102. // SQL_AltDiction2_CP1253_CS_AS
  72103. [124]: 'CP1253',
  72104. // SQL_Latin1_General_CP1253_CI_AI
  72105. [128]: 'CP1254',
  72106. // SQL_Latin1_General_1254_BIN
  72107. [129]: 'CP1254',
  72108. // SQL_Latin1_General_Cp1254_CS_AS_KI_WI
  72109. [130]: 'CP1254',
  72110. // SQL_Latin1_General_Cp1254_CI_AS_KI_WI
  72111. [136]: 'CP1255',
  72112. // SQL_Latin1_General_1255_BIN
  72113. [137]: 'CP1255',
  72114. // SQL_Latin1_General_CP1255_CS_AS
  72115. [138]: 'CP1255',
  72116. // SQL_Latin1_General_CP1255_CI_AS
  72117. [144]: 'CP1256',
  72118. // SQL_Latin1_General_1256_BIN
  72119. [145]: 'CP1256',
  72120. // SQL_Latin1_General_CP1256_CS_AS
  72121. [146]: 'CP1256',
  72122. // SQL_Latin1_General_CP1256_CI_AS
  72123. [152]: 'CP1257',
  72124. // SQL_Latin1_General_1257_BIN
  72125. [153]: 'CP1257',
  72126. // SQL_Latin1_General_CP1257_CS_AS
  72127. [154]: 'CP1257',
  72128. // SQL_Latin1_General_CP1257_CI_AS
  72129. [155]: 'CP1257',
  72130. // SQL_Estonian_Cp1257_CS_AS_KI_WI
  72131. [156]: 'CP1257',
  72132. // SQL_Estonian_Cp1257_CI_AS_KI_WI
  72133. [157]: 'CP1257',
  72134. // SQL_Latvian_Cp1257_CS_AS_KI_WI
  72135. [158]: 'CP1257',
  72136. // SQL_Latvian_Cp1257_CI_AS_KI_WI
  72137. [159]: 'CP1257',
  72138. // SQL_Lithuanian_Cp1257_CS_AS_KI_WI
  72139. [160]: 'CP1257',
  72140. // SQL_Lithuanian_Cp1257_CI_AS_KI_WI
  72141. [183]: 'CP1252',
  72142. // SQL_Danish_Pref_Cp1_CI_AS_KI_WI
  72143. [184]: 'CP1252',
  72144. // SQL_SwedishPhone_Pref_Cp1_CI_AS_KI_WI
  72145. [185]: 'CP1252',
  72146. // SQL_SwedishStd_Pref_Cp1_CI_AS_KI_WI
  72147. [186]: 'CP1252' // SQL_Icelandic_Pref_Cp1_CI_AS_KI_WI
  72148. };
  72149. exports.codepageBySortId = codepageBySortId;
  72150. },{}],414:[function(require,module,exports){
  72151. (function (process,Buffer){(function (){
  72152. "use strict";
  72153. Object.defineProperty(exports, "__esModule", {
  72154. value: true
  72155. });
  72156. exports.default = void 0;
  72157. var _crypto = _interopRequireDefault(require("crypto"));
  72158. var _os = _interopRequireDefault(require("os"));
  72159. var _constants = _interopRequireDefault(require("constants"));
  72160. var _tls = require("tls");
  72161. var _msRestNodeauth = require("@azure/ms-rest-nodeauth");
  72162. var _bulkLoad = _interopRequireDefault(require("./bulk-load"));
  72163. var _debug = _interopRequireDefault(require("./debug"));
  72164. var _events = require("events");
  72165. var _instanceLookup = require("./instance-lookup");
  72166. var _transientErrorLookup = require("./transient-error-lookup");
  72167. var _packet = require("./packet");
  72168. var _preloginPayload = _interopRequireDefault(require("./prelogin-payload"));
  72169. var _login7Payload = _interopRequireDefault(require("./login7-payload"));
  72170. var _ntlmPayload = _interopRequireDefault(require("./ntlm-payload"));
  72171. var _request = _interopRequireDefault(require("./request"));
  72172. var _rpcrequestPayload = _interopRequireDefault(require("./rpcrequest-payload"));
  72173. var _sqlbatchPayload = _interopRequireDefault(require("./sqlbatch-payload"));
  72174. var _messageIo = _interopRequireDefault(require("./message-io"));
  72175. var _tokenStreamParser = require("./token/token-stream-parser");
  72176. var _transaction = require("./transaction");
  72177. var _errors = require("./errors");
  72178. var _connector = require("./connector");
  72179. var _library = require("./library");
  72180. var _tdsVersions = require("./tds-versions");
  72181. var _ntlm = require("./ntlm");
  72182. var _depd = _interopRequireDefault(require("depd"));
  72183. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  72184. const deprecate = (0, _depd.default)('tedious'); // A rather basic state machine for managing a connection.
  72185. // Implements something approximating s3.2.1.
  72186. const KEEP_ALIVE_INITIAL_DELAY = 30 * 1000;
  72187. const DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
  72188. const DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000;
  72189. const DEFAULT_CANCEL_TIMEOUT = 5 * 1000;
  72190. const DEFAULT_CONNECT_RETRY_INTERVAL = 500;
  72191. const DEFAULT_PACKET_SIZE = 4 * 1024;
  72192. const DEFAULT_TEXTSIZE = '2147483647';
  72193. const DEFAULT_DATEFIRST = 7;
  72194. const DEFAULT_PORT = 1433;
  72195. const DEFAULT_TDS_VERSION = '7_4';
  72196. const DEFAULT_LANGUAGE = 'us_english';
  72197. const DEFAULT_DATEFORMAT = 'mdy';
  72198. const CLEANUP_TYPE = {
  72199. NORMAL: 0,
  72200. REDIRECT: 1,
  72201. RETRY: 2
  72202. };
  72203. class Connection extends _events.EventEmitter {
  72204. constructor(config) {
  72205. super();
  72206. this.fedAuthRequired = void 0;
  72207. this.fedAuthInfoToken = void 0;
  72208. this.config = void 0;
  72209. this.secureContext = void 0;
  72210. this.inTransaction = void 0;
  72211. this.transactionDescriptors = void 0;
  72212. this.transactionDepth = void 0;
  72213. this.isSqlBatch = void 0;
  72214. this.curTransientRetryCount = void 0;
  72215. this.transientErrorLookup = void 0;
  72216. this.closed = void 0;
  72217. this.loggedIn = void 0;
  72218. this.loginError = void 0;
  72219. this.debug = void 0;
  72220. this.tokenStreamParser = void 0;
  72221. this.ntlmpacket = void 0;
  72222. this.ntlmpacketBuffer = void 0;
  72223. this.routingData = void 0;
  72224. this.state = void 0;
  72225. this.resetConnectionOnNextRequest = void 0;
  72226. this.attentionReceived = void 0;
  72227. this.request = void 0;
  72228. this.procReturnStatusValue = void 0;
  72229. this.socket = void 0;
  72230. this.messageBuffer = void 0;
  72231. this.connectTimer = void 0;
  72232. this.cancelTimer = void 0;
  72233. this.requestTimer = void 0;
  72234. this.retryTimer = void 0;
  72235. if (typeof config !== 'object' || config === null) {
  72236. throw new TypeError('The "config" argument is required and must be of type Object.');
  72237. }
  72238. if (typeof config.server !== 'string') {
  72239. throw new TypeError('The "config.server" property is required and must be of type string.');
  72240. }
  72241. this.fedAuthRequired = false;
  72242. this.fedAuthInfoToken = undefined;
  72243. let authentication;
  72244. if (config.authentication !== undefined) {
  72245. if (typeof config.authentication !== 'object' || config.authentication === null) {
  72246. throw new TypeError('The "config.authentication" property must be of type Object.');
  72247. }
  72248. const type = config.authentication.type;
  72249. const options = config.authentication.options === undefined ? {} : config.authentication.options;
  72250. if (typeof type !== 'string') {
  72251. throw new TypeError('The "config.authentication.type" property must be of type string.');
  72252. }
  72253. if (type !== 'default' && type !== 'ntlm' && type !== 'azure-active-directory-password' && type !== 'azure-active-directory-access-token' && type !== 'azure-active-directory-msi-vm' && type !== 'azure-active-directory-msi-app-service' && type !== 'azure-active-directory-service-principal-secret') {
  72254. throw new TypeError('The "type" property must one of "default", "ntlm", "azure-active-directory-password", "azure-active-directory-access-token", "azure-active-directory-msi-vm" or "azure-active-directory-msi-app-service" or "azure-active-directory-service-principal-secret".');
  72255. }
  72256. if (typeof options !== 'object' || options === null) {
  72257. throw new TypeError('The "config.authentication.options" property must be of type object.');
  72258. }
  72259. if (type === 'ntlm') {
  72260. if (typeof options.domain !== 'string') {
  72261. throw new TypeError('The "config.authentication.options.domain" property must be of type string.');
  72262. }
  72263. if (options.userName !== undefined && typeof options.userName !== 'string') {
  72264. throw new TypeError('The "config.authentication.options.userName" property must be of type string.');
  72265. }
  72266. if (options.password !== undefined && typeof options.password !== 'string') {
  72267. throw new TypeError('The "config.authentication.options.password" property must be of type string.');
  72268. }
  72269. authentication = {
  72270. type: 'ntlm',
  72271. options: {
  72272. userName: options.userName,
  72273. password: options.password,
  72274. domain: options.domain && options.domain.toUpperCase()
  72275. }
  72276. };
  72277. } else if (type === 'azure-active-directory-password') {
  72278. if (options.userName !== undefined && typeof options.userName !== 'string') {
  72279. throw new TypeError('The "config.authentication.options.userName" property must be of type string.');
  72280. }
  72281. if (options.password !== undefined && typeof options.password !== 'string') {
  72282. throw new TypeError('The "config.authentication.options.password" property must be of type string.');
  72283. }
  72284. authentication = {
  72285. type: 'azure-active-directory-password',
  72286. options: {
  72287. userName: options.userName,
  72288. password: options.password
  72289. }
  72290. };
  72291. } else if (type === 'azure-active-directory-access-token') {
  72292. if (typeof options.token !== 'string') {
  72293. throw new TypeError('The "config.authentication.options.token" property must be of type string.');
  72294. }
  72295. authentication = {
  72296. type: 'azure-active-directory-access-token',
  72297. options: {
  72298. token: options.token
  72299. }
  72300. };
  72301. } else if (type === 'azure-active-directory-msi-vm') {
  72302. if (options.clientId !== undefined && typeof options.clientId !== 'string') {
  72303. throw new TypeError('The "config.authentication.options.clientId" property must be of type string.');
  72304. }
  72305. if (options.msiEndpoint !== undefined && typeof options.msiEndpoint !== 'string') {
  72306. throw new TypeError('The "config.authentication.options.msiEndpoint" property must be of type string.');
  72307. }
  72308. authentication = {
  72309. type: 'azure-active-directory-msi-vm',
  72310. options: {
  72311. clientId: options.clientId,
  72312. msiEndpoint: options.msiEndpoint
  72313. }
  72314. };
  72315. } else if (type === 'azure-active-directory-msi-app-service') {
  72316. if (options.clientId !== undefined && typeof options.clientId !== 'string') {
  72317. throw new TypeError('The "config.authentication.options.clientId" property must be of type string.');
  72318. }
  72319. if (options.msiEndpoint !== undefined && typeof options.msiEndpoint !== 'string') {
  72320. throw new TypeError('The "config.authentication.options.msiEndpoint" property must be of type string.');
  72321. }
  72322. if (options.msiSecret !== undefined && typeof options.msiSecret !== 'string') {
  72323. throw new TypeError('The "config.authentication.options.msiSecret" property must be of type string.');
  72324. }
  72325. authentication = {
  72326. type: 'azure-active-directory-msi-app-service',
  72327. options: {
  72328. clientId: options.clientId,
  72329. msiEndpoint: options.msiEndpoint,
  72330. msiSecret: options.msiSecret
  72331. }
  72332. };
  72333. } else if (type === 'azure-active-directory-service-principal-secret') {
  72334. if (typeof options.clientId !== 'string') {
  72335. throw new TypeError('The "config.authentication.options.clientId" property must be of type string.');
  72336. }
  72337. if (typeof options.clientSecret !== 'string') {
  72338. throw new TypeError('The "config.authentication.options.clientSecret" property must be of type string.');
  72339. }
  72340. if (typeof options.tenantId !== 'string') {
  72341. throw new TypeError('The "config.authentication.options.tenantId" property must be of type string.');
  72342. }
  72343. authentication = {
  72344. type: 'azure-active-directory-service-principal-secret',
  72345. options: {
  72346. clientId: options.clientId,
  72347. clientSecret: options.clientSecret,
  72348. tenantId: options.tenantId
  72349. }
  72350. };
  72351. } else {
  72352. if (options.userName !== undefined && typeof options.userName !== 'string') {
  72353. throw new TypeError('The "config.authentication.options.userName" property must be of type string.');
  72354. }
  72355. if (options.password !== undefined && typeof options.password !== 'string') {
  72356. throw new TypeError('The "config.authentication.options.password" property must be of type string.');
  72357. }
  72358. authentication = {
  72359. type: 'default',
  72360. options: {
  72361. userName: options.userName,
  72362. password: options.password
  72363. }
  72364. };
  72365. }
  72366. } else {
  72367. authentication = {
  72368. type: 'default',
  72369. options: {
  72370. userName: undefined,
  72371. password: undefined
  72372. }
  72373. };
  72374. }
  72375. this.config = {
  72376. server: config.server,
  72377. authentication: authentication,
  72378. options: {
  72379. abortTransactionOnError: false,
  72380. appName: undefined,
  72381. camelCaseColumns: false,
  72382. cancelTimeout: DEFAULT_CANCEL_TIMEOUT,
  72383. columnNameReplacer: undefined,
  72384. connectionRetryInterval: DEFAULT_CONNECT_RETRY_INTERVAL,
  72385. connectTimeout: DEFAULT_CONNECT_TIMEOUT,
  72386. connectionIsolationLevel: _transaction.ISOLATION_LEVEL.READ_COMMITTED,
  72387. cryptoCredentialsDetails: {},
  72388. database: undefined,
  72389. datefirst: DEFAULT_DATEFIRST,
  72390. dateFormat: DEFAULT_DATEFORMAT,
  72391. debug: {
  72392. data: false,
  72393. packet: false,
  72394. payload: false,
  72395. token: false
  72396. },
  72397. enableAnsiNull: true,
  72398. enableAnsiNullDefault: true,
  72399. enableAnsiPadding: true,
  72400. enableAnsiWarnings: true,
  72401. enableArithAbort: false,
  72402. enableConcatNullYieldsNull: true,
  72403. enableCursorCloseOnCommit: null,
  72404. enableImplicitTransactions: false,
  72405. enableNumericRoundabort: false,
  72406. enableQuotedIdentifier: true,
  72407. encrypt: true,
  72408. fallbackToDefaultDb: false,
  72409. instanceName: undefined,
  72410. isolationLevel: _transaction.ISOLATION_LEVEL.READ_COMMITTED,
  72411. language: DEFAULT_LANGUAGE,
  72412. localAddress: undefined,
  72413. maxRetriesOnTransientErrors: 3,
  72414. multiSubnetFailover: false,
  72415. packetSize: DEFAULT_PACKET_SIZE,
  72416. port: DEFAULT_PORT,
  72417. readOnlyIntent: false,
  72418. requestTimeout: DEFAULT_CLIENT_REQUEST_TIMEOUT,
  72419. rowCollectionOnDone: false,
  72420. rowCollectionOnRequestCompletion: false,
  72421. tdsVersion: DEFAULT_TDS_VERSION,
  72422. textsize: DEFAULT_TEXTSIZE,
  72423. trustServerCertificate: true,
  72424. useColumnNames: false,
  72425. useUTC: true,
  72426. lowerCaseGuids: false
  72427. }
  72428. };
  72429. if (config.options) {
  72430. if (config.options.port && config.options.instanceName) {
  72431. throw new Error('Port and instanceName are mutually exclusive, but ' + config.options.port + ' and ' + config.options.instanceName + ' provided');
  72432. }
  72433. if (config.options.abortTransactionOnError !== undefined) {
  72434. if (typeof config.options.abortTransactionOnError !== 'boolean' && config.options.abortTransactionOnError !== null) {
  72435. throw new TypeError('The "config.options.abortTransactionOnError" property must be of type string or null.');
  72436. }
  72437. this.config.options.abortTransactionOnError = config.options.abortTransactionOnError;
  72438. }
  72439. if (config.options.appName !== undefined) {
  72440. if (typeof config.options.appName !== 'string') {
  72441. throw new TypeError('The "config.options.appName" property must be of type string.');
  72442. }
  72443. this.config.options.appName = config.options.appName;
  72444. }
  72445. if (config.options.camelCaseColumns !== undefined) {
  72446. if (typeof config.options.camelCaseColumns !== 'boolean') {
  72447. throw new TypeError('The "config.options.camelCaseColumns" property must be of type boolean.');
  72448. }
  72449. this.config.options.camelCaseColumns = config.options.camelCaseColumns;
  72450. }
  72451. if (config.options.cancelTimeout !== undefined) {
  72452. if (typeof config.options.cancelTimeout !== 'number') {
  72453. throw new TypeError('The "config.options.cancelTimeout" property must be of type number.');
  72454. }
  72455. this.config.options.cancelTimeout = config.options.cancelTimeout;
  72456. }
  72457. if (config.options.columnNameReplacer) {
  72458. if (typeof config.options.columnNameReplacer !== 'function') {
  72459. throw new TypeError('The "config.options.cancelTimeout" property must be of type function.');
  72460. }
  72461. this.config.options.columnNameReplacer = config.options.columnNameReplacer;
  72462. }
  72463. if (config.options.connectTimeout !== undefined) {
  72464. if (typeof config.options.connectTimeout !== 'number') {
  72465. throw new TypeError('The "config.options.connectTimeout" property must be of type number.');
  72466. }
  72467. this.config.options.connectTimeout = config.options.connectTimeout;
  72468. }
  72469. if (config.options.connectionIsolationLevel !== undefined) {
  72470. this.config.options.connectionIsolationLevel = config.options.connectionIsolationLevel;
  72471. }
  72472. if (config.options.connectTimeout !== undefined) {
  72473. if (typeof config.options.connectTimeout !== 'number') {
  72474. throw new TypeError('The "config.options.connectTimeout" property must be of type number.');
  72475. }
  72476. this.config.options.connectTimeout = config.options.connectTimeout;
  72477. }
  72478. if (config.options.cryptoCredentialsDetails !== undefined) {
  72479. if (typeof config.options.cryptoCredentialsDetails !== 'object' || config.options.cryptoCredentialsDetails === null) {
  72480. throw new TypeError('The "config.options.cryptoCredentialsDetails" property must be of type Object.');
  72481. }
  72482. this.config.options.cryptoCredentialsDetails = config.options.cryptoCredentialsDetails;
  72483. }
  72484. if (config.options.database !== undefined) {
  72485. if (typeof config.options.database !== 'string') {
  72486. throw new TypeError('The "config.options.database" property must be of type string.');
  72487. }
  72488. this.config.options.database = config.options.database;
  72489. }
  72490. if (config.options.datefirst !== undefined) {
  72491. if (typeof config.options.datefirst !== 'number' && config.options.datefirst !== null) {
  72492. throw new TypeError('The "config.options.datefirst" property must be of type number.');
  72493. }
  72494. if (config.options.datefirst !== null && (config.options.datefirst < 1 || config.options.datefirst > 7)) {
  72495. throw new RangeError('The "config.options.datefirst" property must be >= 1 and <= 7');
  72496. }
  72497. this.config.options.datefirst = config.options.datefirst;
  72498. }
  72499. if (config.options.dateFormat !== undefined) {
  72500. if (typeof config.options.dateFormat !== 'string' && config.options.dateFormat !== null) {
  72501. throw new TypeError('The "config.options.dateFormat" property must be of type string or null.');
  72502. }
  72503. this.config.options.dateFormat = config.options.dateFormat;
  72504. }
  72505. if (config.options.debug) {
  72506. if (config.options.debug.data !== undefined) {
  72507. if (typeof config.options.debug.data !== 'boolean') {
  72508. throw new TypeError('The "config.options.debug.data" property must be of type boolean.');
  72509. }
  72510. this.config.options.debug.data = config.options.debug.data;
  72511. }
  72512. if (config.options.debug.packet !== undefined) {
  72513. if (typeof config.options.debug.packet !== 'boolean') {
  72514. throw new TypeError('The "config.options.debug.packet" property must be of type boolean.');
  72515. }
  72516. this.config.options.debug.packet = config.options.debug.packet;
  72517. }
  72518. if (config.options.debug.payload !== undefined) {
  72519. if (typeof config.options.debug.payload !== 'boolean') {
  72520. throw new TypeError('The "config.options.debug.payload" property must be of type boolean.');
  72521. }
  72522. this.config.options.debug.payload = config.options.debug.payload;
  72523. }
  72524. if (config.options.debug.token !== undefined) {
  72525. if (typeof config.options.debug.token !== 'boolean') {
  72526. throw new TypeError('The "config.options.debug.token" property must be of type boolean.');
  72527. }
  72528. this.config.options.debug.token = config.options.debug.token;
  72529. }
  72530. }
  72531. if (config.options.enableAnsiNull !== undefined) {
  72532. if (typeof config.options.enableAnsiNull !== 'boolean' && config.options.enableAnsiNull !== null) {
  72533. throw new TypeError('The "config.options.enableAnsiNull" property must be of type boolean or null.');
  72534. }
  72535. this.config.options.enableAnsiNull = config.options.enableAnsiNull;
  72536. }
  72537. if (config.options.enableAnsiNullDefault !== undefined) {
  72538. if (typeof config.options.enableAnsiNullDefault !== 'boolean' && config.options.enableAnsiNullDefault !== null) {
  72539. throw new TypeError('The "config.options.enableAnsiNullDefault" property must be of type boolean or null.');
  72540. }
  72541. this.config.options.enableAnsiNullDefault = config.options.enableAnsiNullDefault;
  72542. }
  72543. if (config.options.enableAnsiPadding !== undefined) {
  72544. if (typeof config.options.enableAnsiPadding !== 'boolean' && config.options.enableAnsiPadding !== null) {
  72545. throw new TypeError('The "config.options.enableAnsiPadding" property must be of type boolean or null.');
  72546. }
  72547. this.config.options.enableAnsiPadding = config.options.enableAnsiPadding;
  72548. }
  72549. if (config.options.enableAnsiWarnings !== undefined) {
  72550. if (typeof config.options.enableAnsiWarnings !== 'boolean' && config.options.enableAnsiWarnings !== null) {
  72551. throw new TypeError('The "config.options.enableAnsiWarnings" property must be of type boolean or null.');
  72552. }
  72553. this.config.options.enableAnsiWarnings = config.options.enableAnsiWarnings;
  72554. }
  72555. if (config.options.enableArithAbort !== undefined) {
  72556. if (typeof config.options.enableArithAbort !== 'boolean' && config.options.enableArithAbort !== null) {
  72557. throw new TypeError('The "config.options.enableArithAbort" property must be of type boolean or null.');
  72558. }
  72559. this.config.options.enableArithAbort = config.options.enableArithAbort;
  72560. } else {
  72561. deprecate('The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or `false` explicitly to silence this message.');
  72562. }
  72563. if (config.options.enableConcatNullYieldsNull !== undefined) {
  72564. if (typeof config.options.enableConcatNullYieldsNull !== 'boolean' && config.options.enableConcatNullYieldsNull !== null) {
  72565. throw new TypeError('The "config.options.enableConcatNullYieldsNull" property must be of type boolean or null.');
  72566. }
  72567. this.config.options.enableConcatNullYieldsNull = config.options.enableConcatNullYieldsNull;
  72568. }
  72569. if (config.options.enableCursorCloseOnCommit !== undefined) {
  72570. if (typeof config.options.enableCursorCloseOnCommit !== 'boolean' && config.options.enableCursorCloseOnCommit !== null) {
  72571. throw new TypeError('The "config.options.enableCursorCloseOnCommit" property must be of type boolean or null.');
  72572. }
  72573. this.config.options.enableCursorCloseOnCommit = config.options.enableCursorCloseOnCommit;
  72574. }
  72575. if (config.options.enableImplicitTransactions !== undefined) {
  72576. if (typeof config.options.enableImplicitTransactions !== 'boolean' && config.options.enableImplicitTransactions !== null) {
  72577. throw new TypeError('The "config.options.enableImplicitTransactions" property must be of type boolean or null.');
  72578. }
  72579. this.config.options.enableImplicitTransactions = config.options.enableImplicitTransactions;
  72580. }
  72581. if (config.options.enableNumericRoundabort !== undefined) {
  72582. if (typeof config.options.enableNumericRoundabort !== 'boolean' && config.options.enableNumericRoundabort !== null) {
  72583. throw new TypeError('The "config.options.enableNumericRoundabort" property must be of type boolean or null.');
  72584. }
  72585. this.config.options.enableNumericRoundabort = config.options.enableNumericRoundabort;
  72586. }
  72587. if (config.options.enableQuotedIdentifier !== undefined) {
  72588. if (typeof config.options.enableQuotedIdentifier !== 'boolean' && config.options.enableQuotedIdentifier !== null) {
  72589. throw new TypeError('The "config.options.enableQuotedIdentifier" property must be of type boolean or null.');
  72590. }
  72591. this.config.options.enableQuotedIdentifier = config.options.enableQuotedIdentifier;
  72592. }
  72593. if (config.options.encrypt !== undefined) {
  72594. if (typeof config.options.encrypt !== 'boolean') {
  72595. throw new TypeError('The "config.options.encrypt" property must be of type boolean.');
  72596. }
  72597. this.config.options.encrypt = config.options.encrypt;
  72598. }
  72599. if (config.options.fallbackToDefaultDb !== undefined) {
  72600. if (typeof config.options.fallbackToDefaultDb !== 'boolean') {
  72601. throw new TypeError('The "config.options.fallbackToDefaultDb" property must be of type boolean.');
  72602. }
  72603. this.config.options.fallbackToDefaultDb = config.options.fallbackToDefaultDb;
  72604. }
  72605. if (config.options.instanceName !== undefined) {
  72606. if (typeof config.options.instanceName !== 'string') {
  72607. throw new TypeError('The "config.options.instanceName" property must be of type string.');
  72608. }
  72609. this.config.options.instanceName = config.options.instanceName;
  72610. this.config.options.port = undefined;
  72611. }
  72612. if (config.options.isolationLevel !== undefined) {
  72613. if (typeof config.options.isolationLevel !== 'number') {
  72614. throw new TypeError('The "config.options.isolationLevel" property must be of type number.');
  72615. }
  72616. this.config.options.isolationLevel = config.options.isolationLevel;
  72617. }
  72618. if (config.options.language !== undefined) {
  72619. if (typeof config.options.language !== 'string' && config.options.language !== null) {
  72620. throw new TypeError('The "config.options.language" property must be of type string or null.');
  72621. }
  72622. this.config.options.language = config.options.language;
  72623. }
  72624. if (config.options.localAddress !== undefined) {
  72625. if (typeof config.options.localAddress !== 'string') {
  72626. throw new TypeError('The "config.options.localAddress" property must be of type string.');
  72627. }
  72628. this.config.options.localAddress = config.options.localAddress;
  72629. }
  72630. if (config.options.multiSubnetFailover !== undefined) {
  72631. if (typeof config.options.multiSubnetFailover !== 'boolean') {
  72632. throw new TypeError('The "config.options.multiSubnetFailover" property must be of type boolean.');
  72633. }
  72634. this.config.options.multiSubnetFailover = config.options.multiSubnetFailover;
  72635. }
  72636. if (config.options.packetSize !== undefined) {
  72637. if (typeof config.options.packetSize !== 'number') {
  72638. throw new TypeError('The "config.options.packetSize" property must be of type number.');
  72639. }
  72640. this.config.options.packetSize = config.options.packetSize;
  72641. }
  72642. if (config.options.port !== undefined) {
  72643. if (typeof config.options.port !== 'number') {
  72644. throw new TypeError('The "config.options.port" property must be of type number.');
  72645. }
  72646. if (config.options.port <= 0 || config.options.port >= 65536) {
  72647. throw new RangeError('The "config.options.port" property must be > 0 and < 65536');
  72648. }
  72649. this.config.options.port = config.options.port;
  72650. this.config.options.instanceName = undefined;
  72651. }
  72652. if (config.options.readOnlyIntent !== undefined) {
  72653. if (typeof config.options.readOnlyIntent !== 'boolean') {
  72654. throw new TypeError('The "config.options.readOnlyIntent" property must be of type boolean.');
  72655. }
  72656. this.config.options.readOnlyIntent = config.options.readOnlyIntent;
  72657. }
  72658. if (config.options.requestTimeout !== undefined) {
  72659. if (typeof config.options.requestTimeout !== 'number') {
  72660. throw new TypeError('The "config.options.requestTimeout" property must be of type number.');
  72661. }
  72662. this.config.options.requestTimeout = config.options.requestTimeout;
  72663. }
  72664. if (config.options.maxRetriesOnTransientErrors !== undefined) {
  72665. if (typeof config.options.maxRetriesOnTransientErrors !== 'number') {
  72666. throw new TypeError('The "config.options.maxRetriesOnTransientErrors" property must be of type number.');
  72667. }
  72668. if (config.options.maxRetriesOnTransientErrors < 0) {
  72669. throw new TypeError('The "config.options.maxRetriesOnTransientErrors" property must be equal or greater than 0.');
  72670. }
  72671. this.config.options.maxRetriesOnTransientErrors = config.options.maxRetriesOnTransientErrors;
  72672. }
  72673. if (config.options.connectionRetryInterval !== undefined) {
  72674. if (typeof config.options.connectionRetryInterval !== 'number') {
  72675. throw new TypeError('The "config.options.connectionRetryInterval" property must be of type number.');
  72676. }
  72677. if (config.options.connectionRetryInterval <= 0) {
  72678. throw new TypeError('The "config.options.connectionRetryInterval" property must be greater than 0.');
  72679. }
  72680. this.config.options.connectionRetryInterval = config.options.connectionRetryInterval;
  72681. }
  72682. if (config.options.rowCollectionOnDone !== undefined) {
  72683. if (typeof config.options.rowCollectionOnDone !== 'boolean') {
  72684. throw new TypeError('The "config.options.rowCollectionOnDone" property must be of type boolean.');
  72685. }
  72686. this.config.options.rowCollectionOnDone = config.options.rowCollectionOnDone;
  72687. }
  72688. if (config.options.rowCollectionOnRequestCompletion !== undefined) {
  72689. if (typeof config.options.rowCollectionOnRequestCompletion !== 'boolean') {
  72690. throw new TypeError('The "config.options.rowCollectionOnRequestCompletion" property must be of type boolean.');
  72691. }
  72692. this.config.options.rowCollectionOnRequestCompletion = config.options.rowCollectionOnRequestCompletion;
  72693. }
  72694. if (config.options.tdsVersion !== undefined) {
  72695. if (typeof config.options.tdsVersion !== 'string') {
  72696. throw new TypeError('The "config.options.tdsVersion" property must be of type string.');
  72697. }
  72698. this.config.options.tdsVersion = config.options.tdsVersion;
  72699. }
  72700. if (config.options.textsize !== undefined) {
  72701. if (typeof config.options.textsize !== 'number' && config.options.textsize !== null) {
  72702. throw new TypeError('The "config.options.textsize" property must be of type number or null.');
  72703. }
  72704. this.config.options.textsize = config.options.textsize;
  72705. }
  72706. if (config.options.trustServerCertificate !== undefined) {
  72707. if (typeof config.options.trustServerCertificate !== 'boolean') {
  72708. throw new TypeError('The "config.options.trustServerCertificate" property must be of type boolean.');
  72709. }
  72710. this.config.options.trustServerCertificate = config.options.trustServerCertificate;
  72711. }
  72712. if (config.options.useColumnNames !== undefined) {
  72713. if (typeof config.options.useColumnNames !== 'boolean') {
  72714. throw new TypeError('The "config.options.useColumnNames" property must be of type boolean.');
  72715. }
  72716. this.config.options.useColumnNames = config.options.useColumnNames;
  72717. }
  72718. if (config.options.useUTC !== undefined) {
  72719. if (typeof config.options.useUTC !== 'boolean') {
  72720. throw new TypeError('The "config.options.useUTC" property must be of type boolean.');
  72721. }
  72722. this.config.options.useUTC = config.options.useUTC;
  72723. }
  72724. if (config.options.lowerCaseGuids !== undefined) {
  72725. if (typeof config.options.lowerCaseGuids !== 'boolean') {
  72726. throw new TypeError('The "config.options.lowerCaseGuids" property must be of type boolean.');
  72727. }
  72728. this.config.options.lowerCaseGuids = config.options.lowerCaseGuids;
  72729. }
  72730. }
  72731. let credentialsDetails = this.config.options.cryptoCredentialsDetails;
  72732. if (credentialsDetails.secureOptions === undefined) {
  72733. // If the caller has not specified their own `secureOptions`,
  72734. // we set `SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS` here.
  72735. // Older SQL Server instances running on older Windows versions have
  72736. // trouble with the BEAST workaround in OpenSSL.
  72737. // As BEAST is a browser specific exploit, we can just disable this option here.
  72738. credentialsDetails = Object.create(credentialsDetails, {
  72739. secureOptions: {
  72740. value: _constants.default.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  72741. }
  72742. });
  72743. }
  72744. this.secureContext = (0, _tls.createSecureContext)(credentialsDetails);
  72745. this.debug = this.createDebug();
  72746. this.tokenStreamParser = this.createTokenStreamParser();
  72747. this.inTransaction = false;
  72748. this.transactionDescriptors = [Buffer.from([0, 0, 0, 0, 0, 0, 0, 0])]; // 'beginTransaction', 'commitTransaction' and 'rollbackTransaction'
  72749. // events are utilized to maintain inTransaction property state which in
  72750. // turn is used in managing transactions. These events are only fired for
  72751. // TDS version 7.2 and beyond. The properties below are used to emulate
  72752. // equivalent behavior for TDS versions before 7.2.
  72753. this.transactionDepth = 0;
  72754. this.isSqlBatch = false;
  72755. this.closed = false;
  72756. this.loggedIn = false;
  72757. this.messageBuffer = Buffer.alloc(0);
  72758. this.curTransientRetryCount = 0;
  72759. this.transientErrorLookup = new _transientErrorLookup.TransientErrorLookup();
  72760. this.state = this.STATE.CONNECTING;
  72761. this.state.enter.call(this);
  72762. }
  72763. close() {
  72764. this.transitionTo(this.STATE.FINAL);
  72765. }
  72766. initialiseConnection() {
  72767. this.connect();
  72768. this.createConnectTimer();
  72769. }
  72770. cleanupConnection(cleanupType) {
  72771. if (!this.closed) {
  72772. this.clearConnectTimer();
  72773. this.clearRequestTimer();
  72774. this.clearRetryTimer();
  72775. this.closeConnection();
  72776. if (cleanupType === CLEANUP_TYPE.REDIRECT) {
  72777. this.emit('rerouting');
  72778. } else if (cleanupType !== CLEANUP_TYPE.RETRY) {
  72779. process.nextTick(() => {
  72780. this.emit('end');
  72781. });
  72782. }
  72783. const request = this.request;
  72784. if (request) {
  72785. const err = (0, _errors.RequestError)('Connection closed before request completed.', 'ECLOSE');
  72786. request.callback(err);
  72787. this.request = undefined;
  72788. }
  72789. this.closed = true;
  72790. this.loggedIn = false;
  72791. this.loginError = undefined;
  72792. }
  72793. }
  72794. createDebug() {
  72795. const debug = new _debug.default(this.config.options.debug);
  72796. debug.on('debug', message => {
  72797. this.emit('debug', message);
  72798. });
  72799. return debug;
  72800. }
  72801. createTokenStreamParser() {
  72802. const tokenStreamParser = new _tokenStreamParser.Parser(this.debug, undefined, this.config.options);
  72803. tokenStreamParser.on('infoMessage', token => {
  72804. this.emit('infoMessage', token);
  72805. });
  72806. tokenStreamParser.on('sspichallenge', token => {
  72807. if (token.ntlmpacket) {
  72808. this.ntlmpacket = token.ntlmpacket;
  72809. this.ntlmpacketBuffer = token.ntlmpacketBuffer;
  72810. }
  72811. this.emit('sspichallenge', token);
  72812. });
  72813. tokenStreamParser.on('errorMessage', token => {
  72814. this.emit('errorMessage', token);
  72815. if (this.loggedIn) {
  72816. const request = this.request;
  72817. if (request) {
  72818. if (!request.canceled) {
  72819. const error = new _errors.RequestError(token.message, 'EREQUEST');
  72820. error.number = token.number;
  72821. error.state = token.state;
  72822. error.class = token.class;
  72823. error.serverName = token.serverName;
  72824. error.procName = token.procName;
  72825. error.lineNumber = token.lineNumber;
  72826. request.error = error;
  72827. }
  72828. }
  72829. } else {
  72830. const error = (0, _errors.ConnectionError)(token.message, 'ELOGIN');
  72831. const isLoginErrorTransient = this.transientErrorLookup.isTransientError(token.number);
  72832. if (isLoginErrorTransient && this.curTransientRetryCount !== this.config.options.maxRetriesOnTransientErrors) {
  72833. error.isTransient = true;
  72834. }
  72835. this.loginError = error;
  72836. }
  72837. });
  72838. tokenStreamParser.on('databaseChange', token => {
  72839. this.emit('databaseChange', token.newValue);
  72840. });
  72841. tokenStreamParser.on('languageChange', token => {
  72842. this.emit('languageChange', token.newValue);
  72843. });
  72844. tokenStreamParser.on('charsetChange', token => {
  72845. this.emit('charsetChange', token.newValue);
  72846. });
  72847. tokenStreamParser.on('fedAuthInfo', token => {
  72848. this.dispatchEvent('fedAuthInfo', token);
  72849. });
  72850. tokenStreamParser.on('featureExtAck', token => {
  72851. this.dispatchEvent('featureExtAck', token);
  72852. });
  72853. tokenStreamParser.on('loginack', token => {
  72854. if (!token.tdsVersion) {
  72855. // unsupported TDS version
  72856. this.loginError = (0, _errors.ConnectionError)('Server responded with unknown TDS version.', 'ETDS');
  72857. this.loggedIn = false;
  72858. return;
  72859. }
  72860. if (!token.interface) {
  72861. // unsupported interface
  72862. this.loginError = (0, _errors.ConnectionError)('Server responded with unsupported interface.', 'EINTERFACENOTSUPP');
  72863. this.loggedIn = false;
  72864. return;
  72865. } // use negotiated version
  72866. this.config.options.tdsVersion = token.tdsVersion;
  72867. this.loggedIn = true;
  72868. });
  72869. tokenStreamParser.on('routingChange', token => {
  72870. this.routingData = token.newValue;
  72871. this.dispatchEvent('routingChange');
  72872. });
  72873. tokenStreamParser.on('packetSizeChange', token => {
  72874. this.messageIo.packetSize(token.newValue);
  72875. }); // A new top-level transaction was started. This is not fired
  72876. // for nested transactions.
  72877. tokenStreamParser.on('beginTransaction', token => {
  72878. this.transactionDescriptors.push(token.newValue);
  72879. this.inTransaction = true;
  72880. }); // A top-level transaction was committed. This is not fired
  72881. // for nested transactions.
  72882. tokenStreamParser.on('commitTransaction', () => {
  72883. this.transactionDescriptors.length = 1;
  72884. this.inTransaction = false;
  72885. }); // A top-level transaction was rolled back. This is not fired
  72886. // for nested transactions. This is also fired if a batch
  72887. // aborting error happened that caused a rollback.
  72888. tokenStreamParser.on('rollbackTransaction', () => {
  72889. this.transactionDescriptors.length = 1; // An outermost transaction was rolled back. Reset the transaction counter
  72890. this.inTransaction = false;
  72891. this.emit('rollbackTransaction');
  72892. });
  72893. tokenStreamParser.on('columnMetadata', token => {
  72894. const request = this.request;
  72895. if (request) {
  72896. if (!request.canceled) {
  72897. if (this.config.options.useColumnNames) {
  72898. const columns = {};
  72899. for (let j = 0, len = token.columns.length; j < len; j++) {
  72900. const col = token.columns[j];
  72901. if (columns[col.colName] == null) {
  72902. columns[col.colName] = col;
  72903. }
  72904. }
  72905. request.emit('columnMetadata', columns);
  72906. } else {
  72907. request.emit('columnMetadata', token.columns);
  72908. }
  72909. }
  72910. } else {
  72911. this.emit('error', new Error("Received 'columnMetadata' when no sqlRequest is in progress"));
  72912. this.close();
  72913. }
  72914. });
  72915. tokenStreamParser.on('order', token => {
  72916. const request = this.request;
  72917. if (request) {
  72918. if (!request.canceled) {
  72919. request.emit('order', token.orderColumns);
  72920. }
  72921. } else {
  72922. this.emit('error', new Error("Received 'order' when no sqlRequest is in progress"));
  72923. this.close();
  72924. }
  72925. });
  72926. tokenStreamParser.on('row', token => {
  72927. const request = this.request;
  72928. if (request) {
  72929. if (!request.canceled) {
  72930. if (this.config.options.rowCollectionOnRequestCompletion) {
  72931. request.rows.push(token.columns);
  72932. }
  72933. if (this.config.options.rowCollectionOnDone) {
  72934. request.rst.push(token.columns);
  72935. }
  72936. if (!(this.state === this.STATE.SENT_ATTENTION && request.paused)) {
  72937. request.emit('row', token.columns);
  72938. }
  72939. }
  72940. } else {
  72941. this.emit('error', new Error("Received 'row' when no sqlRequest is in progress"));
  72942. this.close();
  72943. }
  72944. });
  72945. tokenStreamParser.on('returnStatus', token => {
  72946. const request = this.request;
  72947. if (request) {
  72948. if (!request.canceled) {
  72949. // Keep value for passing in 'doneProc' event.
  72950. this.procReturnStatusValue = token.value;
  72951. }
  72952. }
  72953. });
  72954. tokenStreamParser.on('returnValue', token => {
  72955. const request = this.request;
  72956. if (request) {
  72957. if (!request.canceled) {
  72958. request.emit('returnValue', token.paramName, token.value, token.metadata);
  72959. }
  72960. }
  72961. });
  72962. tokenStreamParser.on('doneProc', token => {
  72963. const request = this.request;
  72964. if (request) {
  72965. if (!request.canceled) {
  72966. request.emit('doneProc', token.rowCount, token.more, this.procReturnStatusValue, request.rst);
  72967. this.procReturnStatusValue = undefined;
  72968. if (token.rowCount !== undefined) {
  72969. request.rowCount += token.rowCount;
  72970. }
  72971. if (this.config.options.rowCollectionOnDone) {
  72972. request.rst = [];
  72973. }
  72974. }
  72975. }
  72976. });
  72977. tokenStreamParser.on('doneInProc', token => {
  72978. const request = this.request;
  72979. if (request) {
  72980. if (!request.canceled) {
  72981. request.emit('doneInProc', token.rowCount, token.more, request.rst);
  72982. if (token.rowCount !== undefined) {
  72983. request.rowCount += token.rowCount;
  72984. }
  72985. if (this.config.options.rowCollectionOnDone) {
  72986. request.rst = [];
  72987. }
  72988. }
  72989. }
  72990. });
  72991. tokenStreamParser.on('done', token => {
  72992. const request = this.request;
  72993. if (request) {
  72994. if (token.attention) {
  72995. this.dispatchEvent('attention');
  72996. }
  72997. if (request.canceled) {
  72998. // If we received a `DONE` token with `DONE_ERROR`, but no previous `ERROR` token,
  72999. // We assume this is the indication that an in-flight request was canceled.
  73000. if (token.sqlError && !request.error) {
  73001. this.clearCancelTimer();
  73002. request.error = (0, _errors.RequestError)('Canceled.', 'ECANCEL');
  73003. }
  73004. } else {
  73005. if (token.sqlError && !request.error) {
  73006. // check if the DONE_ERROR flags was set, but an ERROR token was not sent.
  73007. request.error = (0, _errors.RequestError)('An unknown error has occurred.', 'UNKNOWN');
  73008. }
  73009. request.emit('done', token.rowCount, token.more, request.rst);
  73010. if (token.rowCount !== undefined) {
  73011. request.rowCount += token.rowCount;
  73012. }
  73013. if (this.config.options.rowCollectionOnDone) {
  73014. request.rst = [];
  73015. }
  73016. }
  73017. }
  73018. });
  73019. tokenStreamParser.on('endOfMessage', () => {
  73020. // EOM pseudo token received
  73021. if (this.state === this.STATE.SENT_CLIENT_REQUEST) {
  73022. this.dispatchEvent('endOfMessageMarkerReceived');
  73023. }
  73024. });
  73025. tokenStreamParser.on('resetConnection', () => {
  73026. this.emit('resetConnection');
  73027. });
  73028. tokenStreamParser.on('drain', () => {
  73029. // Bridge the release of backpressure from the token stream parser
  73030. // transform to the packet stream transform.
  73031. this.messageIo.resume();
  73032. });
  73033. return tokenStreamParser;
  73034. }
  73035. connect() {
  73036. if (this.config.options.port) {
  73037. return this.connectOnPort(this.config.options.port, this.config.options.multiSubnetFailover);
  73038. } else {
  73039. return new _instanceLookup.InstanceLookup().instanceLookup({
  73040. server: this.config.server,
  73041. instanceName: this.config.options.instanceName,
  73042. timeout: this.config.options.connectTimeout
  73043. }, (message, port) => {
  73044. if (this.state === this.STATE.FINAL) {
  73045. return;
  73046. }
  73047. if (message) {
  73048. this.emit('connect', (0, _errors.ConnectionError)(message, 'EINSTLOOKUP'));
  73049. } else {
  73050. this.connectOnPort(port, this.config.options.multiSubnetFailover);
  73051. }
  73052. });
  73053. }
  73054. }
  73055. connectOnPort(port, multiSubnetFailover) {
  73056. const connectOpts = {
  73057. host: this.routingData ? this.routingData.server : this.config.server,
  73058. port: this.routingData ? this.routingData.port : port,
  73059. localAddress: this.config.options.localAddress
  73060. };
  73061. new _connector.Connector(connectOpts, multiSubnetFailover).execute((err, socket) => {
  73062. if (err) {
  73063. return this.socketError(err);
  73064. }
  73065. if (this.state === this.STATE.FINAL) {
  73066. socket.destroy();
  73067. return;
  73068. }
  73069. socket.on('error', error => {
  73070. this.socketError(error);
  73071. });
  73072. socket.on('close', () => {
  73073. this.socketClose();
  73074. });
  73075. socket.on('end', () => {
  73076. this.socketEnd();
  73077. });
  73078. socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY);
  73079. this.messageIo = new _messageIo.default(socket, this.config.options.packetSize, this.debug);
  73080. this.messageIo.on('data', data => {
  73081. this.dispatchEvent('data', data);
  73082. });
  73083. this.messageIo.on('message', () => {
  73084. this.dispatchEvent('message');
  73085. });
  73086. this.messageIo.on('secure', cleartext => {
  73087. this.emit('secure', cleartext);
  73088. });
  73089. this.socket = socket;
  73090. this.socketConnect();
  73091. });
  73092. }
  73093. closeConnection() {
  73094. if (this.socket) {
  73095. this.socket.destroy();
  73096. }
  73097. }
  73098. createConnectTimer() {
  73099. this.connectTimer = setTimeout(() => {
  73100. this.connectTimeout();
  73101. }, this.config.options.connectTimeout);
  73102. }
  73103. createCancelTimer() {
  73104. this.clearCancelTimer();
  73105. const timeout = this.config.options.cancelTimeout;
  73106. if (timeout > 0) {
  73107. this.cancelTimer = setTimeout(() => {
  73108. this.cancelTimeout();
  73109. }, timeout);
  73110. }
  73111. }
  73112. createRequestTimer() {
  73113. this.clearRequestTimer(); // release old timer, just to be safe
  73114. const request = this.request;
  73115. const timeout = request.timeout !== undefined ? request.timeout : this.config.options.requestTimeout;
  73116. if (timeout) {
  73117. this.requestTimer = setTimeout(() => {
  73118. this.requestTimeout();
  73119. }, timeout);
  73120. }
  73121. }
  73122. createRetryTimer() {
  73123. this.clearRetryTimer();
  73124. this.retryTimer = setTimeout(() => {
  73125. this.retryTimeout();
  73126. }, this.config.options.connectionRetryInterval);
  73127. }
  73128. connectTimeout() {
  73129. const message = `Failed to connect to ${this.config.server}${this.config.options.port ? `:${this.config.options.port}` : `\\${this.config.options.instanceName}`} in ${this.config.options.connectTimeout}ms`;
  73130. this.debug.log(message);
  73131. this.emit('connect', (0, _errors.ConnectionError)(message, 'ETIMEOUT'));
  73132. this.connectTimer = undefined;
  73133. this.dispatchEvent('connectTimeout');
  73134. }
  73135. cancelTimeout() {
  73136. const message = `Failed to cancel request in ${this.config.options.cancelTimeout}ms`;
  73137. this.debug.log(message);
  73138. this.dispatchEvent('socketError', (0, _errors.ConnectionError)(message, 'ETIMEOUT'));
  73139. }
  73140. requestTimeout() {
  73141. this.requestTimer = undefined;
  73142. const request = this.request;
  73143. request.cancel();
  73144. const timeout = request.timeout !== undefined ? request.timeout : this.config.options.requestTimeout;
  73145. const message = 'Timeout: Request failed to complete in ' + timeout + 'ms';
  73146. request.error = (0, _errors.RequestError)(message, 'ETIMEOUT');
  73147. }
  73148. retryTimeout() {
  73149. this.retryTimer = undefined;
  73150. this.emit('retry');
  73151. this.transitionTo(this.STATE.CONNECTING);
  73152. }
  73153. clearConnectTimer() {
  73154. if (this.connectTimer) {
  73155. clearTimeout(this.connectTimer);
  73156. }
  73157. }
  73158. clearCancelTimer() {
  73159. if (this.cancelTimer) {
  73160. clearTimeout(this.cancelTimer);
  73161. }
  73162. }
  73163. clearRequestTimer() {
  73164. if (this.requestTimer) {
  73165. clearTimeout(this.requestTimer);
  73166. this.requestTimer = undefined;
  73167. }
  73168. }
  73169. clearRetryTimer() {
  73170. if (this.retryTimer) {
  73171. clearTimeout(this.retryTimer);
  73172. this.retryTimer = undefined;
  73173. }
  73174. }
  73175. transitionTo(newState) {
  73176. if (this.state === newState) {
  73177. this.debug.log('State is already ' + newState.name);
  73178. return;
  73179. }
  73180. if (this.state && this.state.exit) {
  73181. this.state.exit.call(this, newState);
  73182. }
  73183. this.debug.log('State change: ' + (this.state ? this.state.name : 'undefined') + ' -> ' + newState.name);
  73184. this.state = newState;
  73185. if (this.state.enter) {
  73186. this.state.enter.apply(this);
  73187. }
  73188. }
  73189. getEventHandler(eventName) {
  73190. const handler = this.state.events[eventName];
  73191. if (!handler) {
  73192. throw new Error(`No event '${eventName}' in state '${this.state.name}'`);
  73193. }
  73194. return handler;
  73195. }
  73196. dispatchEvent(eventName, ...args) {
  73197. const handler = this.state.events[eventName];
  73198. if (handler) {
  73199. handler.apply(this, args);
  73200. } else {
  73201. this.emit('error', new Error(`No event '${eventName}' in state '${this.state.name}'`));
  73202. this.close();
  73203. }
  73204. }
  73205. socketError(error) {
  73206. if (this.state === this.STATE.CONNECTING || this.state === this.STATE.SENT_TLSSSLNEGOTIATION) {
  73207. const message = `Failed to connect to ${this.config.server}:${this.config.options.port} - ${error.message}`;
  73208. this.debug.log(message);
  73209. this.emit('connect', (0, _errors.ConnectionError)(message, 'ESOCKET'));
  73210. } else {
  73211. const message = `Connection lost - ${error.message}`;
  73212. this.debug.log(message);
  73213. this.emit('error', (0, _errors.ConnectionError)(message, 'ESOCKET'));
  73214. }
  73215. this.dispatchEvent('socketError', error);
  73216. }
  73217. socketConnect() {
  73218. this.closed = false;
  73219. this.debug.log('connected to ' + this.config.server + ':' + this.config.options.port);
  73220. this.dispatchEvent('socketConnect');
  73221. }
  73222. socketEnd() {
  73223. this.debug.log('socket ended');
  73224. if (this.state !== this.STATE.FINAL) {
  73225. const error = new Error('socket hang up');
  73226. error.code = 'ECONNRESET';
  73227. this.socketError(error);
  73228. }
  73229. }
  73230. socketClose() {
  73231. this.debug.log('connection to ' + this.config.server + ':' + this.config.options.port + ' closed');
  73232. if (this.state === this.STATE.REROUTING) {
  73233. this.debug.log('Rerouting to ' + this.routingData.server + ':' + this.routingData.port);
  73234. this.dispatchEvent('reconnect');
  73235. } else if (this.state === this.STATE.TRANSIENT_FAILURE_RETRY) {
  73236. const server = this.routingData ? this.routingData.server : this.config.server;
  73237. const port = this.routingData ? this.routingData.port : this.config.options.port;
  73238. this.debug.log('Retry after transient failure connecting to ' + server + ':' + port);
  73239. this.dispatchEvent('retry');
  73240. } else {
  73241. this.transitionTo(this.STATE.FINAL);
  73242. }
  73243. }
  73244. sendPreLogin() {
  73245. const payload = new _preloginPayload.default({
  73246. encrypt: this.config.options.encrypt
  73247. });
  73248. this.messageIo.sendMessage(_packet.TYPE.PRELOGIN, payload.data);
  73249. this.debug.payload(function () {
  73250. return payload.toString(' ');
  73251. });
  73252. }
  73253. emptyMessageBuffer() {
  73254. this.messageBuffer = Buffer.alloc(0);
  73255. }
  73256. addToMessageBuffer(data) {
  73257. this.messageBuffer = Buffer.concat([this.messageBuffer, data]);
  73258. }
  73259. sendLogin7Packet() {
  73260. const payload = new _login7Payload.default({
  73261. tdsVersion: _tdsVersions.versions[this.config.options.tdsVersion],
  73262. packetSize: this.config.options.packetSize,
  73263. clientProgVer: 0,
  73264. clientPid: process.pid,
  73265. connectionId: 0,
  73266. clientTimeZone: new Date().getTimezoneOffset(),
  73267. clientLcid: 0x00000409
  73268. });
  73269. const authentication = this.config.authentication;
  73270. switch (authentication.type) {
  73271. case 'azure-active-directory-password':
  73272. payload.fedAuth = {
  73273. type: 'ADAL',
  73274. echo: this.fedAuthRequired,
  73275. workflow: 'default'
  73276. };
  73277. break;
  73278. case 'azure-active-directory-access-token':
  73279. payload.fedAuth = {
  73280. type: 'SECURITYTOKEN',
  73281. echo: this.fedAuthRequired,
  73282. fedAuthToken: authentication.options.token
  73283. };
  73284. break;
  73285. case 'azure-active-directory-msi-vm':
  73286. case 'azure-active-directory-msi-app-service':
  73287. case 'azure-active-directory-service-principal-secret':
  73288. payload.fedAuth = {
  73289. type: 'ADAL',
  73290. echo: this.fedAuthRequired,
  73291. workflow: 'integrated'
  73292. };
  73293. break;
  73294. case 'ntlm':
  73295. payload.sspi = (0, _ntlm.createNTLMRequest)({
  73296. domain: authentication.options.domain
  73297. });
  73298. break;
  73299. default:
  73300. payload.userName = authentication.options.userName;
  73301. payload.password = authentication.options.password;
  73302. }
  73303. payload.hostname = _os.default.hostname();
  73304. payload.serverName = this.routingData ? this.routingData.server : this.config.server;
  73305. payload.appName = this.config.options.appName || 'Tedious';
  73306. payload.libraryName = _library.name;
  73307. payload.language = this.config.options.language;
  73308. payload.database = this.config.options.database;
  73309. payload.clientId = Buffer.from([1, 2, 3, 4, 5, 6]);
  73310. payload.readOnlyIntent = this.config.options.readOnlyIntent;
  73311. payload.initDbFatal = !this.config.options.fallbackToDefaultDb;
  73312. this.routingData = undefined;
  73313. this.messageIo.sendMessage(_packet.TYPE.LOGIN7, payload.toBuffer());
  73314. this.debug.payload(function () {
  73315. return payload.toString(' ');
  73316. });
  73317. }
  73318. sendFedAuthTokenMessage(token) {
  73319. const accessTokenLen = Buffer.byteLength(token, 'ucs2');
  73320. const data = Buffer.alloc(8 + accessTokenLen);
  73321. let offset = 0;
  73322. offset = data.writeUInt32LE(accessTokenLen + 4, offset);
  73323. offset = data.writeUInt32LE(accessTokenLen, offset);
  73324. data.write(token, offset, 'ucs2');
  73325. this.messageIo.sendMessage(_packet.TYPE.FEDAUTH_TOKEN, data); // sent the fedAuth token message, the rest is similar to standard login 7
  73326. this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
  73327. } // Returns false to apply backpressure.
  73328. sendDataToTokenStreamParser(data) {
  73329. return this.tokenStreamParser.addBuffer(data);
  73330. } // This is an internal method that is called from Request.pause().
  73331. // It has to check whether the passed Request object represents the currently
  73332. // active request, because the application might have called Request.pause()
  73333. // on an old inactive Request object.
  73334. pauseRequest(request) {
  73335. if (this.isRequestActive(request)) {
  73336. this.tokenStreamParser.pause();
  73337. }
  73338. } // This is an internal method that is called from Request.resume().
  73339. resumeRequest(request) {
  73340. if (this.isRequestActive(request)) {
  73341. this.tokenStreamParser.resume();
  73342. }
  73343. } // Returns true if the passed request is the currently active request of the connection.
  73344. isRequestActive(request) {
  73345. return request === this.request && this.state === this.STATE.SENT_CLIENT_REQUEST;
  73346. }
  73347. sendInitialSql() {
  73348. const payload = new _sqlbatchPayload.default(this.getInitialSql(), this.currentTransactionDescriptor(), this.config.options);
  73349. payload.getData(data => {
  73350. return this.messageIo.sendMessage(_packet.TYPE.SQL_BATCH, data);
  73351. });
  73352. }
  73353. getInitialSql() {
  73354. const options = [];
  73355. if (this.config.options.enableAnsiNull === true) {
  73356. options.push('set ansi_nulls on');
  73357. } else if (this.config.options.enableAnsiNull === false) {
  73358. options.push('set ansi_nulls off');
  73359. }
  73360. if (this.config.options.enableAnsiNullDefault === true) {
  73361. options.push('set ansi_null_dflt_on on');
  73362. } else if (this.config.options.enableAnsiNullDefault === false) {
  73363. options.push('set ansi_null_dflt_on off');
  73364. }
  73365. if (this.config.options.enableAnsiPadding === true) {
  73366. options.push('set ansi_padding on');
  73367. } else if (this.config.options.enableAnsiPadding === false) {
  73368. options.push('set ansi_padding off');
  73369. }
  73370. if (this.config.options.enableAnsiWarnings === true) {
  73371. options.push('set ansi_warnings on');
  73372. } else if (this.config.options.enableAnsiWarnings === false) {
  73373. options.push('set ansi_warnings off');
  73374. }
  73375. if (this.config.options.enableArithAbort === true) {
  73376. options.push('set arithabort on');
  73377. } else if (this.config.options.enableArithAbort === false) {
  73378. options.push('set arithabort off');
  73379. }
  73380. if (this.config.options.enableConcatNullYieldsNull === true) {
  73381. options.push('set concat_null_yields_null on');
  73382. } else if (this.config.options.enableConcatNullYieldsNull === false) {
  73383. options.push('set concat_null_yields_null off');
  73384. }
  73385. if (this.config.options.enableCursorCloseOnCommit === true) {
  73386. options.push('set cursor_close_on_commit on');
  73387. } else if (this.config.options.enableCursorCloseOnCommit === false) {
  73388. options.push('set cursor_close_on_commit off');
  73389. }
  73390. if (this.config.options.datefirst !== null) {
  73391. options.push(`set datefirst ${this.config.options.datefirst}`);
  73392. }
  73393. if (this.config.options.dateFormat !== null) {
  73394. options.push(`set dateformat ${this.config.options.dateFormat}`);
  73395. }
  73396. if (this.config.options.enableImplicitTransactions === true) {
  73397. options.push('set implicit_transactions on');
  73398. } else if (this.config.options.enableImplicitTransactions === false) {
  73399. options.push('set implicit_transactions off');
  73400. }
  73401. if (this.config.options.language !== null) {
  73402. options.push(`set language ${this.config.options.language}`);
  73403. }
  73404. if (this.config.options.enableNumericRoundabort === true) {
  73405. options.push('set numeric_roundabort on');
  73406. } else if (this.config.options.enableNumericRoundabort === false) {
  73407. options.push('set numeric_roundabort off');
  73408. }
  73409. if (this.config.options.enableQuotedIdentifier === true) {
  73410. options.push('set quoted_identifier on');
  73411. } else if (this.config.options.enableQuotedIdentifier === false) {
  73412. options.push('set quoted_identifier off');
  73413. }
  73414. if (this.config.options.textsize !== null) {
  73415. options.push(`set textsize ${this.config.options.textsize}`);
  73416. }
  73417. if (this.config.options.connectionIsolationLevel !== null) {
  73418. options.push(`set transaction isolation level ${this.getIsolationLevelText(this.config.options.connectionIsolationLevel)}`);
  73419. }
  73420. if (this.config.options.abortTransactionOnError === true) {
  73421. options.push('set xact_abort on');
  73422. } else if (this.config.options.abortTransactionOnError === false) {
  73423. options.push('set xact_abort off');
  73424. }
  73425. return options.join('\n');
  73426. }
  73427. processedInitialSql() {
  73428. this.clearConnectTimer();
  73429. this.emit('connect');
  73430. }
  73431. execSqlBatch(request) {
  73432. this.makeRequest(request, _packet.TYPE.SQL_BATCH, new _sqlbatchPayload.default(request.sqlTextOrProcedure, this.currentTransactionDescriptor(), this.config.options));
  73433. }
  73434. execSql(request) {
  73435. request.transformIntoExecuteSqlRpc();
  73436. const error = request.error;
  73437. if (error != null) {
  73438. process.nextTick(() => {
  73439. this.debug.log(error.message);
  73440. request.callback(error);
  73441. });
  73442. return;
  73443. }
  73444. this.makeRequest(request, _packet.TYPE.RPC_REQUEST, new _rpcrequestPayload.default(request, this.currentTransactionDescriptor(), this.config.options));
  73445. }
  73446. /**
  73447. @function newBulkLoad
  73448. @param {string} table - Table's name.
  73449. @param {Object} [options] - BulkLoad options.
  73450. @param {boolean} [options.checkConstraints=false] - Honors constraints during bulk load, it is disabled by default.
  73451. @param {boolean} [options.fireTriggers=false] - Honors insert triggers during bulk load, it is disabled by default.
  73452. @param {boolean} [options.keepNulls=false] - Honors null value passed, ignores the default values set on table.
  73453. @param {boolean} [options.tableLock=false] - Places a bulk update(BU) lock on table while performing bulk load. Uses row locks by default.
  73454. @param {callback} callback - Function to call after BulkLoad executes.
  73455. */
  73456. newBulkLoad(table, callbackOrOptions, callback) {
  73457. let options;
  73458. if (callback === undefined) {
  73459. callback = callbackOrOptions;
  73460. options = {};
  73461. } else {
  73462. options = callbackOrOptions;
  73463. }
  73464. if (typeof options !== 'object') {
  73465. throw new TypeError('"options" argument must be an object');
  73466. }
  73467. return new _bulkLoad.default(table, this.config.options, options, callback);
  73468. }
  73469. execBulkLoad(bulkLoad) {
  73470. bulkLoad.executionStarted = true;
  73471. const request = new _request.default(bulkLoad.getBulkInsertSql(), error => {
  73472. if (error) {
  73473. if (error.code === 'UNKNOWN') {
  73474. error.message += ' This is likely because the schema of the BulkLoad does not match the schema of the table you are attempting to insert into.';
  73475. }
  73476. bulkLoad.error = error;
  73477. bulkLoad.callback(error);
  73478. return;
  73479. }
  73480. this.makeRequest(bulkLoad, _packet.TYPE.BULK_LOAD);
  73481. });
  73482. bulkLoad.once('cancel', () => {
  73483. request.cancel();
  73484. });
  73485. this.execSqlBatch(request);
  73486. }
  73487. prepare(request) {
  73488. request.transformIntoPrepareRpc();
  73489. this.makeRequest(request, _packet.TYPE.RPC_REQUEST, new _rpcrequestPayload.default(request, this.currentTransactionDescriptor(), this.config.options));
  73490. }
  73491. unprepare(request) {
  73492. request.transformIntoUnprepareRpc();
  73493. this.makeRequest(request, _packet.TYPE.RPC_REQUEST, new _rpcrequestPayload.default(request, this.currentTransactionDescriptor(), this.config.options));
  73494. }
  73495. execute(request, parameters) {
  73496. request.transformIntoExecuteRpc(parameters);
  73497. const error = request.error;
  73498. if (error != null) {
  73499. process.nextTick(() => {
  73500. this.debug.log(error.message);
  73501. request.callback(error);
  73502. });
  73503. return;
  73504. }
  73505. this.makeRequest(request, _packet.TYPE.RPC_REQUEST, new _rpcrequestPayload.default(request, this.currentTransactionDescriptor(), this.config.options));
  73506. }
  73507. callProcedure(request) {
  73508. request.validateParameters();
  73509. const error = request.error;
  73510. if (error != null) {
  73511. process.nextTick(() => {
  73512. this.debug.log(error.message);
  73513. request.callback(error);
  73514. });
  73515. return;
  73516. }
  73517. this.makeRequest(request, _packet.TYPE.RPC_REQUEST, new _rpcrequestPayload.default(request, this.currentTransactionDescriptor(), this.config.options));
  73518. }
  73519. beginTransaction(callback, name = '', isolationLevel = this.config.options.isolationLevel) {
  73520. const transaction = new _transaction.Transaction(name, isolationLevel);
  73521. if (this.config.options.tdsVersion < '7_2') {
  73522. return this.execSqlBatch(new _request.default('SET TRANSACTION ISOLATION LEVEL ' + transaction.isolationLevelToTSQL() + ';BEGIN TRAN ' + transaction.name, err => {
  73523. this.transactionDepth++;
  73524. if (this.transactionDepth === 1) {
  73525. this.inTransaction = true;
  73526. }
  73527. callback(err);
  73528. }));
  73529. }
  73530. const request = new _request.default(undefined, err => {
  73531. return callback(err, this.currentTransactionDescriptor());
  73532. });
  73533. return this.makeRequest(request, _packet.TYPE.TRANSACTION_MANAGER, transaction.beginPayload(this.currentTransactionDescriptor()));
  73534. }
  73535. commitTransaction(callback, name = '') {
  73536. const transaction = new _transaction.Transaction(name);
  73537. if (this.config.options.tdsVersion < '7_2') {
  73538. return this.execSqlBatch(new _request.default('COMMIT TRAN ' + transaction.name, err => {
  73539. this.transactionDepth--;
  73540. if (this.transactionDepth === 0) {
  73541. this.inTransaction = false;
  73542. }
  73543. callback(err);
  73544. }));
  73545. }
  73546. const request = new _request.default(undefined, callback);
  73547. return this.makeRequest(request, _packet.TYPE.TRANSACTION_MANAGER, transaction.commitPayload(this.currentTransactionDescriptor()));
  73548. }
  73549. rollbackTransaction(callback, name = '') {
  73550. const transaction = new _transaction.Transaction(name);
  73551. if (this.config.options.tdsVersion < '7_2') {
  73552. return this.execSqlBatch(new _request.default('ROLLBACK TRAN ' + transaction.name, err => {
  73553. this.transactionDepth--;
  73554. if (this.transactionDepth === 0) {
  73555. this.inTransaction = false;
  73556. }
  73557. callback(err);
  73558. }));
  73559. }
  73560. const request = new _request.default(undefined, callback);
  73561. return this.makeRequest(request, _packet.TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(this.currentTransactionDescriptor()));
  73562. }
  73563. saveTransaction(callback, name) {
  73564. const transaction = new _transaction.Transaction(name);
  73565. if (this.config.options.tdsVersion < '7_2') {
  73566. return this.execSqlBatch(new _request.default('SAVE TRAN ' + transaction.name, err => {
  73567. this.transactionDepth++;
  73568. callback(err);
  73569. }));
  73570. }
  73571. const request = new _request.default(undefined, callback);
  73572. return this.makeRequest(request, _packet.TYPE.TRANSACTION_MANAGER, transaction.savePayload(this.currentTransactionDescriptor()));
  73573. }
  73574. transaction(cb, isolationLevel) {
  73575. if (typeof cb !== 'function') {
  73576. throw new TypeError('`cb` must be a function');
  73577. }
  73578. const useSavepoint = this.inTransaction;
  73579. const name = '_tedious_' + _crypto.default.randomBytes(10).toString('hex');
  73580. const txDone = (err, done, ...args) => {
  73581. if (err) {
  73582. if (this.inTransaction && this.state === this.STATE.LOGGED_IN) {
  73583. this.rollbackTransaction(txErr => {
  73584. done(txErr || err, ...args);
  73585. }, name);
  73586. } else {
  73587. done(err, ...args);
  73588. }
  73589. } else if (useSavepoint) {
  73590. if (this.config.options.tdsVersion < '7_2') {
  73591. this.transactionDepth--;
  73592. }
  73593. done(null, ...args);
  73594. } else {
  73595. this.commitTransaction(txErr => {
  73596. done(txErr, ...args);
  73597. }, name);
  73598. }
  73599. };
  73600. if (useSavepoint) {
  73601. return this.saveTransaction(err => {
  73602. if (err) {
  73603. return cb(err);
  73604. }
  73605. if (isolationLevel) {
  73606. return this.execSqlBatch(new _request.default('SET transaction isolation level ' + this.getIsolationLevelText(isolationLevel), err => {
  73607. return cb(err, txDone);
  73608. }));
  73609. } else {
  73610. return cb(null, txDone);
  73611. }
  73612. }, name);
  73613. } else {
  73614. return this.beginTransaction(err => {
  73615. if (err) {
  73616. return cb(err);
  73617. }
  73618. return cb(null, txDone);
  73619. }, name, isolationLevel);
  73620. }
  73621. }
  73622. makeRequest(request, packetType, payload) {
  73623. if (this.state !== this.STATE.LOGGED_IN) {
  73624. const message = 'Requests can only be made in the ' + this.STATE.LOGGED_IN.name + ' state, not the ' + this.state.name + ' state';
  73625. this.debug.log(message);
  73626. request.callback((0, _errors.RequestError)(message, 'EINVALIDSTATE'));
  73627. } else if (request.canceled) {
  73628. process.nextTick(() => {
  73629. request.callback((0, _errors.RequestError)('Canceled.', 'ECANCEL'));
  73630. });
  73631. } else {
  73632. if (packetType === _packet.TYPE.SQL_BATCH) {
  73633. this.isSqlBatch = true;
  73634. } else {
  73635. this.isSqlBatch = false;
  73636. }
  73637. this.request = request;
  73638. request.connection = this;
  73639. request.rowCount = 0;
  73640. request.rows = [];
  73641. request.rst = [];
  73642. let message;
  73643. request.once('cancel', () => {
  73644. if (!this.isRequestActive(request)) {
  73645. // Cancel was called on a request that is no longer active on this connection
  73646. return;
  73647. } // There's three ways to handle request cancelation:
  73648. if (this.state === this.STATE.BUILDING_CLIENT_REQUEST) {
  73649. // The request was cancelled before buffering finished
  73650. this.request = undefined;
  73651. request.callback((0, _errors.RequestError)('Canceled.', 'ECANCEL'));
  73652. this.transitionTo(this.STATE.LOGGED_IN);
  73653. } else if (message.writable) {
  73654. // - if the message is still writable, we'll set the ignore bit
  73655. // and end the message.
  73656. message.ignore = true;
  73657. message.end();
  73658. } else {
  73659. // - but if the message has been ended (and thus has been fully sent off),
  73660. // we need to send an `ATTENTION` message to the server
  73661. this.messageIo.sendMessage(_packet.TYPE.ATTENTION);
  73662. this.transitionTo(this.STATE.SENT_ATTENTION);
  73663. }
  73664. this.clearRequestTimer();
  73665. this.createCancelTimer();
  73666. });
  73667. if (request instanceof _bulkLoad.default) {
  73668. message = request.getMessageStream(); // If the bulkload was not put into streaming mode by the user,
  73669. // we end the rowToPacketTransform here for them.
  73670. //
  73671. // If it was put into streaming mode, it's the user's responsibility
  73672. // to end the stream.
  73673. if (!request.streamingMode) {
  73674. request.rowToPacketTransform.end();
  73675. }
  73676. this.messageIo.outgoingMessageStream.write(message);
  73677. this.transitionTo(this.STATE.SENT_CLIENT_REQUEST);
  73678. if (request.paused) {
  73679. // Request.pause() has been called before the request was started
  73680. this.pauseRequest(request);
  73681. }
  73682. } else {
  73683. this.createRequestTimer(); // Transition to an intermediate state to ensure that no new requests
  73684. // are made on the connection while the buffer is being populated.
  73685. this.transitionTo(this.STATE.BUILDING_CLIENT_REQUEST);
  73686. payload.getData(data => {
  73687. if (this.state !== this.STATE.BUILDING_CLIENT_REQUEST) {
  73688. // Something else has happened on the connection since starting to
  73689. // build the request. That state change should have invoked the
  73690. // request handler so there is nothing to do at this point.
  73691. return;
  73692. }
  73693. message = this.messageIo.sendMessage(packetType, data, this.resetConnectionOnNextRequest);
  73694. this.resetConnectionOnNextRequest = false;
  73695. this.debug.payload(function () {
  73696. return payload.toString(' ');
  73697. });
  73698. this.transitionTo(this.STATE.SENT_CLIENT_REQUEST);
  73699. if (request.paused) {
  73700. // Request.pause() has been called before the request was started
  73701. this.pauseRequest(request);
  73702. }
  73703. });
  73704. }
  73705. }
  73706. }
  73707. cancel() {
  73708. if (!this.request) {
  73709. return false;
  73710. }
  73711. if (this.request.canceled) {
  73712. return false;
  73713. }
  73714. this.request.cancel();
  73715. return true;
  73716. }
  73717. reset(callback) {
  73718. const request = new _request.default(this.getInitialSql(), err => {
  73719. if (this.config.options.tdsVersion < '7_2') {
  73720. this.inTransaction = false;
  73721. }
  73722. callback(err);
  73723. });
  73724. this.resetConnectionOnNextRequest = true;
  73725. this.execSqlBatch(request);
  73726. }
  73727. currentTransactionDescriptor() {
  73728. return this.transactionDescriptors[this.transactionDescriptors.length - 1];
  73729. }
  73730. getIsolationLevelText(isolationLevel) {
  73731. switch (isolationLevel) {
  73732. case _transaction.ISOLATION_LEVEL.READ_UNCOMMITTED:
  73733. return 'read uncommitted';
  73734. case _transaction.ISOLATION_LEVEL.REPEATABLE_READ:
  73735. return 'repeatable read';
  73736. case _transaction.ISOLATION_LEVEL.SERIALIZABLE:
  73737. return 'serializable';
  73738. case _transaction.ISOLATION_LEVEL.SNAPSHOT:
  73739. return 'snapshot';
  73740. default:
  73741. return 'read committed';
  73742. }
  73743. }
  73744. }
  73745. var _default = Connection;
  73746. exports.default = _default;
  73747. module.exports = Connection;
  73748. Connection.prototype.STATE = {
  73749. CONNECTING: {
  73750. name: 'Connecting',
  73751. enter: function enter() {
  73752. this.initialiseConnection();
  73753. },
  73754. events: {
  73755. socketError: function socketError() {
  73756. this.transitionTo(this.STATE.FINAL);
  73757. },
  73758. connectTimeout: function connectTimeout() {
  73759. this.transitionTo(this.STATE.FINAL);
  73760. },
  73761. socketConnect: function socketConnect() {
  73762. this.sendPreLogin();
  73763. this.transitionTo(this.STATE.SENT_PRELOGIN);
  73764. }
  73765. }
  73766. },
  73767. SENT_PRELOGIN: {
  73768. name: 'SentPrelogin',
  73769. enter: function enter() {
  73770. this.emptyMessageBuffer();
  73771. },
  73772. events: {
  73773. socketError: function socketError() {
  73774. this.transitionTo(this.STATE.FINAL);
  73775. },
  73776. connectTimeout: function connectTimeout() {
  73777. this.transitionTo(this.STATE.FINAL);
  73778. },
  73779. data: function (_data) {
  73780. function data(_x) {
  73781. return _data.apply(this, arguments);
  73782. }
  73783. data.toString = function () {
  73784. return _data.toString();
  73785. };
  73786. return data;
  73787. }(function (data) {
  73788. this.addToMessageBuffer(data);
  73789. }),
  73790. message: function message() {
  73791. const preloginPayload = new _preloginPayload.default(this.messageBuffer);
  73792. this.debug.payload(function () {
  73793. return preloginPayload.toString(' ');
  73794. });
  73795. if (preloginPayload.fedAuthRequired === 1) {
  73796. this.fedAuthRequired = true;
  73797. }
  73798. if (preloginPayload.encryptionString === 'ON' || preloginPayload.encryptionString === 'REQ') {
  73799. if (!this.config.options.encrypt) {
  73800. this.emit('connect', (0, _errors.ConnectionError)("Server requires encryption, set 'encrypt' config option to true.", 'EENCRYPT'));
  73801. return this.close();
  73802. }
  73803. this.messageIo.startTls(this.secureContext, this.config.server, this.config.options.trustServerCertificate);
  73804. this.transitionTo(this.STATE.SENT_TLSSSLNEGOTIATION);
  73805. } else {
  73806. this.sendLogin7Packet();
  73807. const authentication = this.config.authentication;
  73808. if (authentication.type === 'ntlm') {
  73809. this.transitionTo(this.STATE.SENT_LOGIN7_WITH_NTLM);
  73810. } else {
  73811. this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
  73812. }
  73813. }
  73814. }
  73815. }
  73816. },
  73817. REROUTING: {
  73818. name: 'ReRouting',
  73819. enter: function enter() {
  73820. this.cleanupConnection(CLEANUP_TYPE.REDIRECT);
  73821. },
  73822. events: {
  73823. message: function message() {},
  73824. socketError: function socketError() {
  73825. this.transitionTo(this.STATE.FINAL);
  73826. },
  73827. connectTimeout: function connectTimeout() {
  73828. this.transitionTo(this.STATE.FINAL);
  73829. },
  73830. reconnect: function reconnect() {
  73831. this.transitionTo(this.STATE.CONNECTING);
  73832. }
  73833. }
  73834. },
  73835. TRANSIENT_FAILURE_RETRY: {
  73836. name: 'TRANSIENT_FAILURE_RETRY',
  73837. enter: function enter() {
  73838. this.curTransientRetryCount++;
  73839. this.cleanupConnection(CLEANUP_TYPE.RETRY);
  73840. },
  73841. events: {
  73842. message: function message() {},
  73843. socketError: function socketError() {
  73844. this.transitionTo(this.STATE.FINAL);
  73845. },
  73846. connectTimeout: function connectTimeout() {
  73847. this.transitionTo(this.STATE.FINAL);
  73848. },
  73849. retry: function retry() {
  73850. this.createRetryTimer();
  73851. }
  73852. }
  73853. },
  73854. SENT_TLSSSLNEGOTIATION: {
  73855. name: 'SentTLSSSLNegotiation',
  73856. events: {
  73857. socketError: function socketError() {
  73858. this.transitionTo(this.STATE.FINAL);
  73859. },
  73860. connectTimeout: function connectTimeout() {
  73861. this.transitionTo(this.STATE.FINAL);
  73862. },
  73863. data: function (_data2) {
  73864. function data(_x2) {
  73865. return _data2.apply(this, arguments);
  73866. }
  73867. data.toString = function () {
  73868. return _data2.toString();
  73869. };
  73870. return data;
  73871. }(function (data) {
  73872. this.messageIo.tlsHandshakeData(data);
  73873. }),
  73874. message: function message() {
  73875. if (this.messageIo.tlsNegotiationComplete) {
  73876. this.sendLogin7Packet();
  73877. const authentication = this.config.authentication;
  73878. if (authentication.type === 'azure-active-directory-password' || authentication.type === 'azure-active-directory-msi-vm' || authentication.type === 'azure-active-directory-msi-app-service' || authentication.type === 'azure-active-directory-service-principal-secret') {
  73879. this.transitionTo(this.STATE.SENT_LOGIN7_WITH_FEDAUTH);
  73880. } else if (authentication.type === 'ntlm') {
  73881. this.transitionTo(this.STATE.SENT_LOGIN7_WITH_NTLM);
  73882. } else {
  73883. this.transitionTo(this.STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN);
  73884. }
  73885. }
  73886. }
  73887. }
  73888. },
  73889. SENT_LOGIN7_WITH_STANDARD_LOGIN: {
  73890. name: 'SentLogin7WithStandardLogin',
  73891. events: {
  73892. socketError: function socketError() {
  73893. this.transitionTo(this.STATE.FINAL);
  73894. },
  73895. connectTimeout: function connectTimeout() {
  73896. this.transitionTo(this.STATE.FINAL);
  73897. },
  73898. data: function (_data3) {
  73899. function data(_x3) {
  73900. return _data3.apply(this, arguments);
  73901. }
  73902. data.toString = function () {
  73903. return _data3.toString();
  73904. };
  73905. return data;
  73906. }(function (data) {
  73907. this.sendDataToTokenStreamParser(data);
  73908. }),
  73909. routingChange: function routingChange() {
  73910. this.transitionTo(this.STATE.REROUTING);
  73911. },
  73912. featureExtAck: function featureExtAck(token) {
  73913. const authentication = this.config.authentication;
  73914. if (authentication.type === 'azure-active-directory-password' || authentication.type === 'azure-active-directory-access-token' || authentication.type === 'azure-active-directory-msi-vm' || authentication.type === 'azure-active-directory-msi-app-service' || authentication.type === 'azure-active-directory-service-principal-secret') {
  73915. if (token.fedAuth === undefined) {
  73916. this.loginError = (0, _errors.ConnectionError)('Did not receive Active Directory authentication acknowledgement');
  73917. this.loggedIn = false;
  73918. } else if (token.fedAuth.length !== 0) {
  73919. this.loginError = (0, _errors.ConnectionError)(`Active Directory authentication acknowledgment for ${authentication.type} authentication method includes extra data`);
  73920. this.loggedIn = false;
  73921. }
  73922. } else if (token.fedAuth === undefined) {
  73923. this.loginError = (0, _errors.ConnectionError)('Received acknowledgement for unknown feature');
  73924. this.loggedIn = false;
  73925. } else {
  73926. this.loginError = (0, _errors.ConnectionError)('Did not request Active Directory authentication, but received the acknowledgment');
  73927. this.loggedIn = false;
  73928. }
  73929. },
  73930. message: function message() {
  73931. if (this.loggedIn) {
  73932. this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
  73933. } else if (this.loginError) {
  73934. if (this.loginError.isTransient) {
  73935. this.debug.log('Initiating retry on transient error');
  73936. this.transitionTo(this.STATE.TRANSIENT_FAILURE_RETRY);
  73937. } else {
  73938. this.emit('connect', this.loginError);
  73939. this.transitionTo(this.STATE.FINAL);
  73940. }
  73941. } else {
  73942. this.emit('connect', (0, _errors.ConnectionError)('Login failed.', 'ELOGIN'));
  73943. this.transitionTo(this.STATE.FINAL);
  73944. }
  73945. }
  73946. }
  73947. },
  73948. SENT_LOGIN7_WITH_NTLM: {
  73949. name: 'SentLogin7WithNTLMLogin',
  73950. events: {
  73951. socketError: function socketError() {
  73952. this.transitionTo(this.STATE.FINAL);
  73953. },
  73954. connectTimeout: function connectTimeout() {
  73955. this.transitionTo(this.STATE.FINAL);
  73956. },
  73957. data: function (_data4) {
  73958. function data(_x4) {
  73959. return _data4.apply(this, arguments);
  73960. }
  73961. data.toString = function () {
  73962. return _data4.toString();
  73963. };
  73964. return data;
  73965. }(function (data) {
  73966. this.sendDataToTokenStreamParser(data);
  73967. }),
  73968. message: function message() {
  73969. if (this.ntlmpacket) {
  73970. const authentication = this.config.authentication;
  73971. const payload = new _ntlmPayload.default({
  73972. domain: authentication.options.domain,
  73973. userName: authentication.options.userName,
  73974. password: authentication.options.password,
  73975. ntlmpacket: this.ntlmpacket
  73976. });
  73977. this.messageIo.sendMessage(_packet.TYPE.NTLMAUTH_PKT, payload.data);
  73978. this.debug.payload(function () {
  73979. return payload.toString(' ');
  73980. });
  73981. this.ntlmpacket = undefined;
  73982. } else if (this.loggedIn) {
  73983. this.transitionTo(this.STATE.LOGGED_IN_SENDING_INITIAL_SQL);
  73984. } else if (this.loginError) {
  73985. if (this.loginError.isTransient) {
  73986. this.debug.log('Initiating retry on transient error');
  73987. this.transitionTo(this.STATE.TRANSIENT_FAILURE_RETRY);
  73988. } else {
  73989. this.emit('connect', this.loginError);
  73990. this.transitionTo(this.STATE.FINAL);
  73991. }
  73992. } else {
  73993. this.emit('connect', (0, _errors.ConnectionError)('Login failed.', 'ELOGIN'));
  73994. this.transitionTo(this.STATE.FINAL);
  73995. }
  73996. }
  73997. }
  73998. },
  73999. SENT_LOGIN7_WITH_FEDAUTH: {
  74000. name: 'SentLogin7Withfedauth',
  74001. events: {
  74002. socketError: function socketError() {
  74003. this.transitionTo(this.STATE.FINAL);
  74004. },
  74005. connectTimeout: function connectTimeout() {
  74006. this.transitionTo(this.STATE.FINAL);
  74007. },
  74008. data: function (_data5) {
  74009. function data(_x5) {
  74010. return _data5.apply(this, arguments);
  74011. }
  74012. data.toString = function () {
  74013. return _data5.toString();
  74014. };
  74015. return data;
  74016. }(function (data) {
  74017. this.sendDataToTokenStreamParser(data);
  74018. }),
  74019. routingChange: function routingChange() {
  74020. this.transitionTo(this.STATE.REROUTING);
  74021. },
  74022. fedAuthInfo: function fedAuthInfo(token) {
  74023. this.fedAuthInfoToken = token;
  74024. },
  74025. message: function message() {
  74026. const fedAuthInfoToken = this.fedAuthInfoToken;
  74027. if (fedAuthInfoToken && fedAuthInfoToken.stsurl && fedAuthInfoToken.spn) {
  74028. const authentication = this.config.authentication;
  74029. const getToken = callback => {
  74030. const getTokenFromCredentials = (err, credentials) => {
  74031. if (err) {
  74032. return callback(err);
  74033. }
  74034. credentials.getToken().then(tokenResponse => {
  74035. callback(null, tokenResponse.accessToken);
  74036. }, callback);
  74037. };
  74038. if (authentication.type === 'azure-active-directory-password') {
  74039. (0, _msRestNodeauth.loginWithUsernamePassword)(authentication.options.userName, authentication.options.password, {
  74040. clientId: '7f98cb04-cd1e-40df-9140-3bf7e2cea4db',
  74041. tokenAudience: fedAuthInfoToken.spn
  74042. }, getTokenFromCredentials);
  74043. } else if (authentication.type === 'azure-active-directory-msi-vm') {
  74044. (0, _msRestNodeauth.loginWithVmMSI)({
  74045. clientId: authentication.options.clientId,
  74046. msiEndpoint: authentication.options.msiEndpoint,
  74047. resource: fedAuthInfoToken.spn
  74048. }, getTokenFromCredentials);
  74049. } else if (authentication.type === 'azure-active-directory-msi-app-service') {
  74050. (0, _msRestNodeauth.loginWithAppServiceMSI)({
  74051. msiEndpoint: authentication.options.msiEndpoint,
  74052. msiSecret: authentication.options.msiSecret,
  74053. resource: fedAuthInfoToken.spn
  74054. }, getTokenFromCredentials);
  74055. } else if (authentication.type === 'azure-active-directory-service-principal-secret') {
  74056. (0, _msRestNodeauth.loginWithServicePrincipalSecret)(authentication.options.clientId, authentication.options.clientSecret, authentication.options.tenantId, {
  74057. tokenAudience: fedAuthInfoToken.spn
  74058. }, getTokenFromCredentials);
  74059. }
  74060. };
  74061. getToken((err, token) => {
  74062. if (err) {
  74063. this.loginError = (0, _errors.ConnectionError)('Security token could not be authenticated or authorized.', 'EFEDAUTH');
  74064. this.emit('connect', this.loginError);
  74065. this.transitionTo(this.STATE.FINAL);
  74066. return;
  74067. }
  74068. this.sendFedAuthTokenMessage(token);
  74069. });
  74070. } else if (this.loginError) {
  74071. if (this.loginError.isTransient) {
  74072. this.debug.log('Initiating retry on transient error');
  74073. this.transitionTo(this.STATE.TRANSIENT_FAILURE_RETRY);
  74074. } else {
  74075. this.emit('connect', this.loginError);
  74076. this.transitionTo(this.STATE.FINAL);
  74077. }
  74078. } else {
  74079. this.emit('connect', (0, _errors.ConnectionError)('Login failed.', 'ELOGIN'));
  74080. this.transitionTo(this.STATE.FINAL);
  74081. }
  74082. }
  74083. }
  74084. },
  74085. LOGGED_IN_SENDING_INITIAL_SQL: {
  74086. name: 'LoggedInSendingInitialSql',
  74087. enter: function enter() {
  74088. this.sendInitialSql();
  74089. },
  74090. events: {
  74091. socketError: function socketError() {
  74092. this.transitionTo(this.STATE.FINAL);
  74093. },
  74094. connectTimeout: function connectTimeout() {
  74095. this.transitionTo(this.STATE.FINAL);
  74096. },
  74097. data: function (_data6) {
  74098. function data(_x6) {
  74099. return _data6.apply(this, arguments);
  74100. }
  74101. data.toString = function () {
  74102. return _data6.toString();
  74103. };
  74104. return data;
  74105. }(function (data) {
  74106. this.sendDataToTokenStreamParser(data);
  74107. }),
  74108. message: function message() {
  74109. this.transitionTo(this.STATE.LOGGED_IN);
  74110. this.processedInitialSql();
  74111. }
  74112. }
  74113. },
  74114. LOGGED_IN: {
  74115. name: 'LoggedIn',
  74116. events: {
  74117. socketError: function socketError() {
  74118. this.transitionTo(this.STATE.FINAL);
  74119. }
  74120. }
  74121. },
  74122. BUILDING_CLIENT_REQUEST: {
  74123. name: 'BuildingClientRequest',
  74124. events: {
  74125. socketError: function socketError(err) {
  74126. const sqlRequest = this.request;
  74127. this.request = undefined;
  74128. this.transitionTo(this.STATE.FINAL);
  74129. sqlRequest.callback(err);
  74130. }
  74131. }
  74132. },
  74133. SENT_CLIENT_REQUEST: {
  74134. name: 'SentClientRequest',
  74135. exit: function exit(nextState) {
  74136. this.clearRequestTimer();
  74137. if (nextState !== this.STATE.FINAL) {
  74138. this.tokenStreamParser.resume();
  74139. }
  74140. },
  74141. events: {
  74142. socketError: function socketError(err) {
  74143. const sqlRequest = this.request;
  74144. this.request = undefined;
  74145. this.transitionTo(this.STATE.FINAL);
  74146. sqlRequest.callback(err);
  74147. },
  74148. data: function (_data7) {
  74149. function data(_x7) {
  74150. return _data7.apply(this, arguments);
  74151. }
  74152. data.toString = function () {
  74153. return _data7.toString();
  74154. };
  74155. return data;
  74156. }(function (data) {
  74157. this.clearRequestTimer(); // request timer is stopped on first data package
  74158. const ret = this.sendDataToTokenStreamParser(data);
  74159. if (ret === false) {
  74160. // Bridge backpressure from the token stream parser transform to the
  74161. // packet stream transform.
  74162. this.messageIo.pause();
  74163. }
  74164. }),
  74165. message: function message() {
  74166. // We have to channel the 'message' (EOM) event through the token stream
  74167. // parser transform, to keep it in line with the flow of the tokens, when
  74168. // the incoming data flow is paused and resumed.
  74169. this.tokenStreamParser.addEndOfMessageMarker();
  74170. },
  74171. endOfMessageMarkerReceived: function endOfMessageMarkerReceived() {
  74172. this.transitionTo(this.STATE.LOGGED_IN);
  74173. const sqlRequest = this.request;
  74174. this.request = undefined;
  74175. if (this.config.options.tdsVersion < '7_2' && sqlRequest.error && this.isSqlBatch) {
  74176. this.inTransaction = false;
  74177. }
  74178. sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows);
  74179. }
  74180. }
  74181. },
  74182. SENT_ATTENTION: {
  74183. name: 'SentAttention',
  74184. enter: function enter() {
  74185. this.attentionReceived = false;
  74186. },
  74187. events: {
  74188. socketError: function socketError(err) {
  74189. const sqlRequest = this.request;
  74190. this.request = undefined;
  74191. this.transitionTo(this.STATE.FINAL);
  74192. sqlRequest.callback(err);
  74193. },
  74194. data: function (_data8) {
  74195. function data(_x8) {
  74196. return _data8.apply(this, arguments);
  74197. }
  74198. data.toString = function () {
  74199. return _data8.toString();
  74200. };
  74201. return data;
  74202. }(function (data) {
  74203. this.sendDataToTokenStreamParser(data);
  74204. }),
  74205. attention: function attention() {
  74206. this.attentionReceived = true;
  74207. },
  74208. message: function message() {
  74209. // 3.2.5.7 Sent Attention State
  74210. // Discard any data contained in the response, until we receive the attention response
  74211. if (this.attentionReceived) {
  74212. this.clearCancelTimer();
  74213. const sqlRequest = this.request;
  74214. this.request = undefined;
  74215. this.transitionTo(this.STATE.LOGGED_IN);
  74216. if (sqlRequest.error && sqlRequest.error instanceof _errors.RequestError && sqlRequest.error.code === 'ETIMEOUT') {
  74217. sqlRequest.callback(sqlRequest.error);
  74218. } else {
  74219. sqlRequest.callback((0, _errors.RequestError)('Canceled.', 'ECANCEL'));
  74220. }
  74221. }
  74222. }
  74223. }
  74224. },
  74225. FINAL: {
  74226. name: 'Final',
  74227. enter: function enter() {
  74228. this.cleanupConnection(CLEANUP_TYPE.NORMAL);
  74229. },
  74230. events: {
  74231. loginFailed: function loginFailed() {// Do nothing. The connection was probably closed by the client code.
  74232. },
  74233. connectTimeout: function connectTimeout() {// Do nothing, as the timer should be cleaned up.
  74234. },
  74235. message: function message() {// Do nothing
  74236. },
  74237. socketError: function socketError() {// Do nothing
  74238. }
  74239. }
  74240. }
  74241. };
  74242. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  74243. },{"./bulk-load":412,"./connector":415,"./debug":456,"./errors":457,"./instance-lookup":460,"./library":461,"./login7-payload":462,"./message-io":463,"./ntlm":467,"./ntlm-payload":466,"./packet":469,"./prelogin-payload":470,"./request":471,"./rpcrequest-payload":472,"./sqlbatch-payload":474,"./tds-versions":475,"./token/token-stream-parser":491,"./transaction":494,"./transient-error-lookup":495,"@azure/ms-rest-nodeauth":16,"_process":525,"buffer":193,"constants":200,"crypto":208,"depd":211,"events":247,"os":500,"tls":190}],415:[function(require,module,exports){
  74244. "use strict";
  74245. Object.defineProperty(exports, "__esModule", {
  74246. value: true
  74247. });
  74248. exports.Connector = exports.SequentialConnectionStrategy = exports.ParallelConnectionStrategy = void 0;
  74249. var _net = _interopRequireDefault(require("net"));
  74250. var _dns = _interopRequireDefault(require("dns"));
  74251. var punycode = _interopRequireWildcard(require("punycode"));
  74252. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  74253. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  74254. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  74255. class ParallelConnectionStrategy {
  74256. constructor(addresses, options) {
  74257. this.addresses = void 0;
  74258. this.options = void 0;
  74259. this.addresses = addresses;
  74260. this.options = options;
  74261. }
  74262. connect(callback) {
  74263. const addresses = this.addresses;
  74264. const sockets = new Array(addresses.length);
  74265. let errorCount = 0;
  74266. function onError(_err) {
  74267. errorCount += 1;
  74268. this.removeListener('error', onError);
  74269. this.removeListener('connect', onConnect);
  74270. if (errorCount === addresses.length) {
  74271. callback(new Error('Could not connect (parallel)'));
  74272. }
  74273. }
  74274. function onConnect() {
  74275. for (let j = 0; j < sockets.length; j++) {
  74276. const socket = sockets[j];
  74277. if (this === socket) {
  74278. continue;
  74279. }
  74280. socket.removeListener('error', onError);
  74281. socket.removeListener('connect', onConnect);
  74282. socket.destroy();
  74283. }
  74284. callback(null, this);
  74285. }
  74286. for (let i = 0, len = addresses.length; i < len; i++) {
  74287. const socket = sockets[i] = _net.default.connect(Object.create(this.options, {
  74288. host: {
  74289. value: addresses[i].address
  74290. }
  74291. }));
  74292. socket.on('error', onError);
  74293. socket.on('connect', onConnect);
  74294. }
  74295. }
  74296. }
  74297. exports.ParallelConnectionStrategy = ParallelConnectionStrategy;
  74298. class SequentialConnectionStrategy {
  74299. constructor(addresses, options) {
  74300. this.addresses = void 0;
  74301. this.options = void 0;
  74302. this.addresses = addresses;
  74303. this.options = options;
  74304. }
  74305. connect(callback) {
  74306. const next = this.addresses.shift();
  74307. if (!next) {
  74308. return callback(new Error('Could not connect (sequence)'));
  74309. }
  74310. const socket = _net.default.connect(Object.create(this.options, {
  74311. host: {
  74312. value: next.address
  74313. }
  74314. }));
  74315. const onError = _err => {
  74316. socket.removeListener('error', onError);
  74317. socket.removeListener('connect', onConnect);
  74318. socket.destroy();
  74319. this.connect(callback);
  74320. };
  74321. const onConnect = () => {
  74322. socket.removeListener('error', onError);
  74323. socket.removeListener('connect', onConnect);
  74324. callback(null, socket);
  74325. };
  74326. socket.on('error', onError);
  74327. socket.on('connect', onConnect);
  74328. }
  74329. }
  74330. exports.SequentialConnectionStrategy = SequentialConnectionStrategy;
  74331. class Connector {
  74332. constructor(options, multiSubnetFailover) {
  74333. this.options = void 0;
  74334. this.multiSubnetFailover = void 0;
  74335. this.options = options;
  74336. this.multiSubnetFailover = multiSubnetFailover;
  74337. }
  74338. execute(cb) {
  74339. if (_net.default.isIP(this.options.host)) {
  74340. this.executeForIP(cb);
  74341. } else {
  74342. this.executeForHostname(cb);
  74343. }
  74344. }
  74345. executeForIP(cb) {
  74346. const socket = _net.default.connect(this.options);
  74347. const onError = err => {
  74348. socket.removeListener('error', onError);
  74349. socket.removeListener('connect', onConnect);
  74350. socket.destroy();
  74351. cb(err);
  74352. };
  74353. const onConnect = () => {
  74354. socket.removeListener('error', onError);
  74355. socket.removeListener('connect', onConnect);
  74356. cb(null, socket);
  74357. };
  74358. socket.on('error', onError);
  74359. socket.on('connect', onConnect);
  74360. }
  74361. executeForHostname(cb) {
  74362. _dns.default.lookup(punycode.toASCII(this.options.host), {
  74363. all: true
  74364. }, (err, addresses) => {
  74365. if (err) {
  74366. return cb(err);
  74367. }
  74368. if (this.multiSubnetFailover) {
  74369. new ParallelConnectionStrategy(addresses, this.options).connect(cb);
  74370. } else {
  74371. new SequentialConnectionStrategy(addresses, this.options).connect(cb);
  74372. }
  74373. });
  74374. }
  74375. }
  74376. exports.Connector = Connector;
  74377. },{"dns":190,"net":190,"punycode":535}],416:[function(require,module,exports){
  74378. "use strict";
  74379. Object.defineProperty(exports, "__esModule", {
  74380. value: true
  74381. });
  74382. exports.typeByName = exports.TYPE = void 0;
  74383. var _null = _interopRequireDefault(require("./data-types/null"));
  74384. var _tinyint = _interopRequireDefault(require("./data-types/tinyint"));
  74385. var _bit = _interopRequireDefault(require("./data-types/bit"));
  74386. var _smallint = _interopRequireDefault(require("./data-types/smallint"));
  74387. var _int = _interopRequireDefault(require("./data-types/int"));
  74388. var _smalldatetime = _interopRequireDefault(require("./data-types/smalldatetime"));
  74389. var _real = _interopRequireDefault(require("./data-types/real"));
  74390. var _money = _interopRequireDefault(require("./data-types/money"));
  74391. var _datetime = _interopRequireDefault(require("./data-types/datetime"));
  74392. var _float = _interopRequireDefault(require("./data-types/float"));
  74393. var _decimal = _interopRequireDefault(require("./data-types/decimal"));
  74394. var _numeric = _interopRequireDefault(require("./data-types/numeric"));
  74395. var _smallmoney = _interopRequireDefault(require("./data-types/smallmoney"));
  74396. var _bigint = _interopRequireDefault(require("./data-types/bigint"));
  74397. var _image = _interopRequireDefault(require("./data-types/image"));
  74398. var _text = _interopRequireDefault(require("./data-types/text"));
  74399. var _uniqueidentifier = _interopRequireDefault(require("./data-types/uniqueidentifier"));
  74400. var _intn = _interopRequireDefault(require("./data-types/intn"));
  74401. var _ntext = _interopRequireDefault(require("./data-types/ntext"));
  74402. var _bitn = _interopRequireDefault(require("./data-types/bitn"));
  74403. var _decimaln = _interopRequireDefault(require("./data-types/decimaln"));
  74404. var _numericn = _interopRequireDefault(require("./data-types/numericn"));
  74405. var _floatn = _interopRequireDefault(require("./data-types/floatn"));
  74406. var _moneyn = _interopRequireDefault(require("./data-types/moneyn"));
  74407. var _datetimen = _interopRequireDefault(require("./data-types/datetimen"));
  74408. var _varbinary = _interopRequireDefault(require("./data-types/varbinary"));
  74409. var _varchar = _interopRequireDefault(require("./data-types/varchar"));
  74410. var _binary = _interopRequireDefault(require("./data-types/binary"));
  74411. var _char = _interopRequireDefault(require("./data-types/char"));
  74412. var _nvarchar = _interopRequireDefault(require("./data-types/nvarchar"));
  74413. var _nchar = _interopRequireDefault(require("./data-types/nchar"));
  74414. var _xml = _interopRequireDefault(require("./data-types/xml"));
  74415. var _time = _interopRequireDefault(require("./data-types/time"));
  74416. var _date = _interopRequireDefault(require("./data-types/date"));
  74417. var _datetime2 = _interopRequireDefault(require("./data-types/datetime2"));
  74418. var _datetimeoffset = _interopRequireDefault(require("./data-types/datetimeoffset"));
  74419. var _udt = _interopRequireDefault(require("./data-types/udt"));
  74420. var _tvp = _interopRequireDefault(require("./data-types/tvp"));
  74421. var _sqlVariant = _interopRequireDefault(require("./data-types/sql-variant"));
  74422. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  74423. const TYPE = {
  74424. [_null.default.id]: _null.default,
  74425. [_tinyint.default.id]: _tinyint.default,
  74426. [_bit.default.id]: _bit.default,
  74427. [_smallint.default.id]: _smallint.default,
  74428. [_int.default.id]: _int.default,
  74429. [_smalldatetime.default.id]: _smalldatetime.default,
  74430. [_real.default.id]: _real.default,
  74431. [_money.default.id]: _money.default,
  74432. [_datetime.default.id]: _datetime.default,
  74433. [_float.default.id]: _float.default,
  74434. [_decimal.default.id]: _decimal.default,
  74435. [_numeric.default.id]: _numeric.default,
  74436. [_smallmoney.default.id]: _smallmoney.default,
  74437. [_bigint.default.id]: _bigint.default,
  74438. [_image.default.id]: _image.default,
  74439. [_text.default.id]: _text.default,
  74440. [_uniqueidentifier.default.id]: _uniqueidentifier.default,
  74441. [_intn.default.id]: _intn.default,
  74442. [_ntext.default.id]: _ntext.default,
  74443. [_bitn.default.id]: _bitn.default,
  74444. [_decimaln.default.id]: _decimaln.default,
  74445. [_numericn.default.id]: _numericn.default,
  74446. [_floatn.default.id]: _floatn.default,
  74447. [_moneyn.default.id]: _moneyn.default,
  74448. [_datetimen.default.id]: _datetimen.default,
  74449. [_varbinary.default.id]: _varbinary.default,
  74450. [_varchar.default.id]: _varchar.default,
  74451. [_binary.default.id]: _binary.default,
  74452. [_char.default.id]: _char.default,
  74453. [_nvarchar.default.id]: _nvarchar.default,
  74454. [_nchar.default.id]: _nchar.default,
  74455. [_xml.default.id]: _xml.default,
  74456. [_time.default.id]: _time.default,
  74457. [_date.default.id]: _date.default,
  74458. [_datetime2.default.id]: _datetime2.default,
  74459. [_datetimeoffset.default.id]: _datetimeoffset.default,
  74460. [_udt.default.id]: _udt.default,
  74461. [_tvp.default.id]: _tvp.default,
  74462. [_sqlVariant.default.id]: _sqlVariant.default
  74463. };
  74464. exports.TYPE = TYPE;
  74465. const typeByName = {
  74466. TinyInt: _tinyint.default,
  74467. Bit: _bit.default,
  74468. SmallInt: _smallint.default,
  74469. Int: _int.default,
  74470. SmallDateTime: _smalldatetime.default,
  74471. Real: _real.default,
  74472. Money: _money.default,
  74473. DateTime: _datetime.default,
  74474. Float: _float.default,
  74475. Decimal: _decimal.default,
  74476. Numeric: _numeric.default,
  74477. SmallMoney: _smallmoney.default,
  74478. BigInt: _bigint.default,
  74479. Image: _image.default,
  74480. Text: _text.default,
  74481. UniqueIdentifier: _uniqueidentifier.default,
  74482. NText: _ntext.default,
  74483. VarBinary: _varbinary.default,
  74484. VarChar: _varchar.default,
  74485. Binary: _binary.default,
  74486. Char: _char.default,
  74487. NVarChar: _nvarchar.default,
  74488. NChar: _nchar.default,
  74489. Xml: _xml.default,
  74490. Time: _time.default,
  74491. Date: _date.default,
  74492. DateTime2: _datetime2.default,
  74493. DateTimeOffset: _datetimeoffset.default,
  74494. UDT: _udt.default,
  74495. TVP: _tvp.default,
  74496. Variant: _sqlVariant.default
  74497. };
  74498. exports.typeByName = typeByName;
  74499. },{"./data-types/bigint":417,"./data-types/binary":418,"./data-types/bit":419,"./data-types/bitn":420,"./data-types/char":421,"./data-types/date":422,"./data-types/datetime":423,"./data-types/datetime2":424,"./data-types/datetimen":425,"./data-types/datetimeoffset":426,"./data-types/decimal":427,"./data-types/decimaln":428,"./data-types/float":429,"./data-types/floatn":430,"./data-types/image":431,"./data-types/int":432,"./data-types/intn":433,"./data-types/money":434,"./data-types/moneyn":435,"./data-types/nchar":436,"./data-types/ntext":437,"./data-types/null":438,"./data-types/numeric":439,"./data-types/numericn":440,"./data-types/nvarchar":441,"./data-types/real":442,"./data-types/smalldatetime":443,"./data-types/smallint":444,"./data-types/smallmoney":445,"./data-types/sql-variant":446,"./data-types/text":447,"./data-types/time":448,"./data-types/tinyint":449,"./data-types/tvp":450,"./data-types/udt":451,"./data-types/uniqueidentifier":452,"./data-types/varbinary":453,"./data-types/varchar":454,"./data-types/xml":455}],417:[function(require,module,exports){
  74500. "use strict";
  74501. Object.defineProperty(exports, "__esModule", {
  74502. value: true
  74503. });
  74504. exports.default = void 0;
  74505. var _intn = _interopRequireDefault(require("./intn"));
  74506. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  74507. const BigInt = {
  74508. id: 0x7F,
  74509. type: 'INT8',
  74510. name: 'BigInt',
  74511. declaration: function declaration() {
  74512. return 'bigint';
  74513. },
  74514. writeTypeInfo: function writeTypeInfo(buffer) {
  74515. buffer.writeUInt8(_intn.default.id);
  74516. buffer.writeUInt8(8);
  74517. },
  74518. writeParameterData: function writeParameterData(buffer, parameter, _options, cb) {
  74519. if (parameter.value != null) {
  74520. buffer.writeUInt8(8);
  74521. buffer.writeInt64LE(Number(parameter.value));
  74522. } else {
  74523. buffer.writeUInt8(0);
  74524. }
  74525. cb();
  74526. },
  74527. validate: function validate(value) {
  74528. if (value == null) {
  74529. return null;
  74530. }
  74531. if (typeof value !== 'number') {
  74532. value = Number(value);
  74533. }
  74534. if (isNaN(value)) {
  74535. return new TypeError('Invalid number.');
  74536. }
  74537. if (value < Number.MIN_SAFE_INTEGER || value > Number.MAX_SAFE_INTEGER) {
  74538. return new TypeError(`Value must be between ${Number.MIN_SAFE_INTEGER} and ${Number.MAX_SAFE_INTEGER}, inclusive. For smaller or bigger numbers, use VarChar type.`);
  74539. }
  74540. return value;
  74541. }
  74542. };
  74543. var _default = BigInt;
  74544. exports.default = _default;
  74545. module.exports = BigInt;
  74546. },{"./intn":433}],418:[function(require,module,exports){
  74547. (function (Buffer){(function (){
  74548. "use strict";
  74549. Object.defineProperty(exports, "__esModule", {
  74550. value: true
  74551. });
  74552. exports.default = void 0;
  74553. const NULL = (1 << 16) - 1;
  74554. const Binary = {
  74555. id: 0xAD,
  74556. type: 'BIGBinary',
  74557. name: 'Binary',
  74558. maximumLength: 8000,
  74559. declaration: function declaration(parameter) {
  74560. const value = parameter.value;
  74561. var length;
  74562. if (parameter.length) {
  74563. length = parameter.length;
  74564. } else if (value != null) {
  74565. length = value.length || 1;
  74566. } else if (value === null && !parameter.output) {
  74567. length = 1;
  74568. } else {
  74569. length = this.maximumLength;
  74570. }
  74571. return 'binary(' + length + ')';
  74572. },
  74573. resolveLength: function resolveLength(parameter) {
  74574. const value = parameter.value;
  74575. if (value != null) {
  74576. return value.length;
  74577. } else {
  74578. return this.maximumLength;
  74579. }
  74580. },
  74581. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  74582. buffer.writeUInt8(this.id);
  74583. buffer.writeUInt16LE(parameter.length);
  74584. },
  74585. writeParameterData: function writeParameterData(buffer, parameter, _options, cb) {
  74586. if (parameter.value != null) {
  74587. buffer.writeUInt16LE(parameter.length);
  74588. buffer.writeBuffer(parameter.value.slice(0, parameter.length !== undefined ? Math.min(parameter.length, this.maximumLength) : this.maximumLength));
  74589. } else {
  74590. buffer.writeUInt16LE(NULL);
  74591. }
  74592. cb();
  74593. },
  74594. validate: function validate(value) {
  74595. if (value == null) {
  74596. return null;
  74597. }
  74598. if (!Buffer.isBuffer(value)) {
  74599. return new TypeError('Invalid buffer.');
  74600. }
  74601. return value;
  74602. }
  74603. };
  74604. var _default = Binary;
  74605. exports.default = _default;
  74606. module.exports = Binary;
  74607. }).call(this)}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")})
  74608. },{"../../../../../is-buffer/index.js":322}],419:[function(require,module,exports){
  74609. "use strict";
  74610. Object.defineProperty(exports, "__esModule", {
  74611. value: true
  74612. });
  74613. exports.default = void 0;
  74614. var _bitn = _interopRequireDefault(require("./bitn"));
  74615. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  74616. const Bit = {
  74617. id: 0x32,
  74618. type: 'BIT',
  74619. name: 'Bit',
  74620. declaration: function declaration() {
  74621. return 'bit';
  74622. },
  74623. writeTypeInfo: function writeTypeInfo(buffer) {
  74624. buffer.writeUInt8(_bitn.default.id);
  74625. buffer.writeUInt8(1);
  74626. },
  74627. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  74628. if (typeof parameter.value === 'undefined' || parameter.value === null) {
  74629. buffer.writeUInt8(0);
  74630. } else {
  74631. buffer.writeUInt8(1);
  74632. buffer.writeUInt8(parameter.value ? 1 : 0);
  74633. }
  74634. cb();
  74635. },
  74636. validate: function validate(value) {
  74637. if (value == null) {
  74638. return null;
  74639. }
  74640. if (value) {
  74641. return true;
  74642. } else {
  74643. return false;
  74644. }
  74645. }
  74646. };
  74647. var _default = Bit;
  74648. exports.default = _default;
  74649. module.exports = Bit;
  74650. },{"./bitn":420}],420:[function(require,module,exports){
  74651. "use strict";
  74652. Object.defineProperty(exports, "__esModule", {
  74653. value: true
  74654. });
  74655. exports.default = void 0;
  74656. const BitN = {
  74657. id: 0x68,
  74658. type: 'BITN',
  74659. name: 'BitN',
  74660. declaration() {
  74661. throw new Error('not implemented');
  74662. },
  74663. writeTypeInfo() {
  74664. throw new Error('not implemented');
  74665. },
  74666. writeParameterData() {
  74667. throw new Error('not implemented');
  74668. },
  74669. validate() {
  74670. throw new Error('not implemented');
  74671. }
  74672. };
  74673. var _default = BitN;
  74674. exports.default = _default;
  74675. module.exports = BitN;
  74676. },{}],421:[function(require,module,exports){
  74677. (function (Buffer){(function (){
  74678. "use strict";
  74679. Object.defineProperty(exports, "__esModule", {
  74680. value: true
  74681. });
  74682. exports.default = void 0;
  74683. const NULL = (1 << 16) - 1;
  74684. const Char = {
  74685. id: 0xAF,
  74686. type: 'BIGCHAR',
  74687. name: 'Char',
  74688. maximumLength: 8000,
  74689. declaration: function declaration(parameter) {
  74690. // const value = parameter.value as null | string | { toString(): string };
  74691. const value = parameter.value; // Temporary solution. Remove 'any' later.
  74692. let length;
  74693. if (parameter.length) {
  74694. length = parameter.length;
  74695. } else if (value != null) {
  74696. length = value.toString().length || 1;
  74697. } else if (value === null && !parameter.output) {
  74698. length = 1;
  74699. } else {
  74700. length = this.maximumLength;
  74701. }
  74702. if (length < this.maximumLength) {
  74703. return 'char(' + length + ')';
  74704. } else {
  74705. return 'char(' + this.maximumLength + ')';
  74706. }
  74707. },
  74708. // ParameterData<any> is temporary solution. TODO: need to understand what type ParameterData<...> can be.
  74709. resolveLength: function resolveLength(parameter) {
  74710. const value = parameter.value; // Temporary solution. Remove 'any' later.
  74711. if (parameter.length != null) {
  74712. return parameter.length;
  74713. } else if (value != null) {
  74714. if (Buffer.isBuffer(value)) {
  74715. return value.length || 1;
  74716. } else {
  74717. return value.toString().length || 1;
  74718. }
  74719. } else {
  74720. return this.maximumLength;
  74721. }
  74722. },
  74723. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  74724. buffer.writeUInt8(this.id);
  74725. buffer.writeUInt16LE(parameter.length);
  74726. buffer.writeBuffer(Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00]));
  74727. },
  74728. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  74729. const value = parameter.value; // Temporary solution. Remove 'any' later.
  74730. if (value != null) {
  74731. buffer.writeUsVarbyte(value, 'ascii');
  74732. } else {
  74733. buffer.writeUInt16LE(NULL);
  74734. }
  74735. cb();
  74736. },
  74737. validate: function validate(value) {
  74738. if (value == null) {
  74739. return null;
  74740. }
  74741. if (typeof value !== 'string') {
  74742. if (typeof value.toString !== 'function') {
  74743. return TypeError('Invalid string.');
  74744. }
  74745. value = value.toString();
  74746. }
  74747. return value;
  74748. }
  74749. };
  74750. var _default = Char;
  74751. exports.default = _default;
  74752. module.exports = Char;
  74753. }).call(this)}).call(this,require("buffer").Buffer)
  74754. },{"buffer":193}],422:[function(require,module,exports){
  74755. (function (global){(function (){
  74756. "use strict";
  74757. Object.defineProperty(exports, "__esModule", {
  74758. value: true
  74759. });
  74760. exports.default = void 0;
  74761. // globalDate is to be used for JavaScript's global 'Date' object to avoid name clashing with the 'Date' constant below
  74762. const globalDate = global.Date;
  74763. const YEAR_ONE = new globalDate(2000, 0, -730118);
  74764. const UTC_YEAR_ONE = globalDate.UTC(2000, 0, -730118);
  74765. const Date = {
  74766. id: 0x28,
  74767. type: 'DATEN',
  74768. name: 'Date',
  74769. declaration: function declaration() {
  74770. return 'date';
  74771. },
  74772. writeTypeInfo: function writeTypeInfo(buffer) {
  74773. buffer.writeUInt8(this.id);
  74774. },
  74775. // ParameterData<any> is temporary solution. TODO: need to understand what type ParameterData<...> can be.
  74776. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  74777. if (parameter.value != null) {
  74778. buffer.writeUInt8(3);
  74779. if (options.useUTC) {
  74780. buffer.writeUInt24LE(Math.floor((+parameter.value - UTC_YEAR_ONE) / 86400000));
  74781. } else {
  74782. const dstDiff = -(parameter.value.getTimezoneOffset() - YEAR_ONE.getTimezoneOffset()) * 60 * 1000;
  74783. buffer.writeUInt24LE(Math.floor((+parameter.value - +YEAR_ONE + dstDiff) / 86400000));
  74784. }
  74785. } else {
  74786. buffer.writeUInt8(0);
  74787. }
  74788. cb();
  74789. },
  74790. // TODO: value is techincally of type 'unknown'.
  74791. validate: function validate(value) {
  74792. if (value == null) {
  74793. return null;
  74794. }
  74795. if (!(value instanceof globalDate)) {
  74796. value = new globalDate(globalDate.parse(value));
  74797. }
  74798. if (isNaN(value)) {
  74799. return new TypeError('Invalid date.');
  74800. }
  74801. return value;
  74802. }
  74803. };
  74804. var _default = Date;
  74805. exports.default = _default;
  74806. module.exports = Date;
  74807. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  74808. },{}],423:[function(require,module,exports){
  74809. "use strict";
  74810. Object.defineProperty(exports, "__esModule", {
  74811. value: true
  74812. });
  74813. exports.default = void 0;
  74814. var _datetimen = _interopRequireDefault(require("./datetimen"));
  74815. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  74816. const EPOCH_DATE = new Date(1900, 0, 1);
  74817. const UTC_EPOCH_DATE = new Date(Date.UTC(1900, 0, 1));
  74818. const DateTime = {
  74819. id: 0x3D,
  74820. type: 'DATETIME',
  74821. name: 'DateTime',
  74822. declaration: function declaration() {
  74823. return 'datetime';
  74824. },
  74825. writeTypeInfo: function writeTypeInfo(buffer) {
  74826. buffer.writeUInt8(_datetimen.default.id);
  74827. buffer.writeUInt8(8);
  74828. },
  74829. // ParameterData<any> is temporary solution. TODO: need to understand what type ParameterData<...> can be.
  74830. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  74831. if (parameter.value != null) {
  74832. let days, dstDiff, milliseconds, seconds, threeHundredthsOfSecond;
  74833. if (options.useUTC) {
  74834. days = Math.floor((parameter.value.getTime() - UTC_EPOCH_DATE.getTime()) / (1000 * 60 * 60 * 24));
  74835. seconds = parameter.value.getUTCHours() * 60 * 60;
  74836. seconds += parameter.value.getUTCMinutes() * 60;
  74837. seconds += parameter.value.getUTCSeconds();
  74838. milliseconds = seconds * 1000 + parameter.value.getUTCMilliseconds();
  74839. } else {
  74840. dstDiff = -(parameter.value.getTimezoneOffset() - EPOCH_DATE.getTimezoneOffset()) * 60 * 1000;
  74841. days = Math.floor((parameter.value.getTime() - EPOCH_DATE.getTime() + dstDiff) / (1000 * 60 * 60 * 24));
  74842. seconds = parameter.value.getHours() * 60 * 60;
  74843. seconds += parameter.value.getMinutes() * 60;
  74844. seconds += parameter.value.getSeconds();
  74845. milliseconds = seconds * 1000 + parameter.value.getMilliseconds();
  74846. }
  74847. threeHundredthsOfSecond = milliseconds / (3 + 1 / 3);
  74848. threeHundredthsOfSecond = Math.round(threeHundredthsOfSecond); // 25920000 equals one day
  74849. if (threeHundredthsOfSecond === 25920000) {
  74850. days += 1;
  74851. threeHundredthsOfSecond = 0;
  74852. }
  74853. buffer.writeUInt8(8);
  74854. buffer.writeInt32LE(days);
  74855. buffer.writeUInt32LE(threeHundredthsOfSecond);
  74856. } else {
  74857. buffer.writeUInt8(0);
  74858. }
  74859. cb();
  74860. },
  74861. // TODO: type 'any' needs to be revisited.
  74862. validate: function validate(value) {
  74863. if (value == null) {
  74864. return null;
  74865. }
  74866. if (!(value instanceof Date)) {
  74867. value = new Date(Date.parse(value));
  74868. }
  74869. if (isNaN(value)) {
  74870. return new TypeError('Invalid date.');
  74871. }
  74872. return value;
  74873. }
  74874. };
  74875. var _default = DateTime;
  74876. exports.default = _default;
  74877. module.exports = DateTime;
  74878. },{"./datetimen":425}],424:[function(require,module,exports){
  74879. "use strict";
  74880. Object.defineProperty(exports, "__esModule", {
  74881. value: true
  74882. });
  74883. exports.default = void 0;
  74884. const YEAR_ONE = new Date(2000, 0, -730118);
  74885. const UTC_YEAR_ONE = Date.UTC(2000, 0, -730118);
  74886. const DateTime2 = {
  74887. id: 0x2A,
  74888. type: 'DATETIME2N',
  74889. name: 'DateTime2',
  74890. declaration: function declaration(parameter) {
  74891. return 'datetime2(' + this.resolveScale(parameter) + ')';
  74892. },
  74893. resolveScale: function resolveScale(parameter) {
  74894. if (parameter.scale != null) {
  74895. return parameter.scale;
  74896. } else if (parameter.value === null) {
  74897. return 0;
  74898. } else {
  74899. return 7;
  74900. }
  74901. },
  74902. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  74903. buffer.writeUInt8(this.id);
  74904. buffer.writeUInt8(parameter.scale);
  74905. },
  74906. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  74907. if (parameter.value != null) {
  74908. const time = new Date(+parameter.value);
  74909. let timestamp;
  74910. if (options.useUTC) {
  74911. timestamp = ((time.getUTCHours() * 60 + time.getUTCMinutes()) * 60 + time.getUTCSeconds()) * 1000 + time.getUTCMilliseconds();
  74912. } else {
  74913. timestamp = ((time.getHours() * 60 + time.getMinutes()) * 60 + time.getSeconds()) * 1000 + time.getMilliseconds();
  74914. }
  74915. timestamp = timestamp * Math.pow(10, parameter.scale - 3);
  74916. timestamp += (parameter.value.nanosecondDelta != null ? parameter.value.nanosecondDelta : 0) * Math.pow(10, parameter.scale);
  74917. timestamp = Math.round(timestamp);
  74918. switch (parameter.scale) {
  74919. case 0:
  74920. case 1:
  74921. case 2:
  74922. buffer.writeUInt8(6);
  74923. buffer.writeUInt24LE(timestamp);
  74924. break;
  74925. case 3:
  74926. case 4:
  74927. buffer.writeUInt8(7);
  74928. buffer.writeUInt32LE(timestamp);
  74929. break;
  74930. case 5:
  74931. case 6:
  74932. case 7:
  74933. buffer.writeUInt8(8);
  74934. buffer.writeUInt40LE(timestamp);
  74935. }
  74936. if (options.useUTC) {
  74937. buffer.writeUInt24LE(Math.floor((+parameter.value - UTC_YEAR_ONE) / 86400000));
  74938. } else {
  74939. const dstDiff = -(parameter.value.getTimezoneOffset() - YEAR_ONE.getTimezoneOffset()) * 60 * 1000;
  74940. buffer.writeUInt24LE(Math.floor((+parameter.value - +YEAR_ONE + dstDiff) / 86400000));
  74941. }
  74942. } else {
  74943. buffer.writeUInt8(0);
  74944. }
  74945. cb();
  74946. },
  74947. validate: function validate(value) {
  74948. if (value == null) {
  74949. return null;
  74950. }
  74951. if (!(value instanceof Date)) {
  74952. value = new Date(Date.parse(value));
  74953. }
  74954. if (isNaN(value)) {
  74955. return new TypeError('Invalid date.');
  74956. }
  74957. return value;
  74958. }
  74959. };
  74960. var _default = DateTime2;
  74961. exports.default = _default;
  74962. module.exports = DateTime2;
  74963. },{}],425:[function(require,module,exports){
  74964. "use strict";
  74965. Object.defineProperty(exports, "__esModule", {
  74966. value: true
  74967. });
  74968. exports.default = void 0;
  74969. const DateTimeN = {
  74970. id: 0x6F,
  74971. type: 'DATETIMN',
  74972. name: 'DateTimeN',
  74973. declaration() {
  74974. throw new Error('not implemented');
  74975. },
  74976. writeTypeInfo() {
  74977. throw new Error('not implemented');
  74978. },
  74979. writeParameterData() {
  74980. throw new Error('not implemented');
  74981. },
  74982. validate() {
  74983. throw new Error('not implemented');
  74984. }
  74985. };
  74986. var _default = DateTimeN;
  74987. exports.default = _default;
  74988. module.exports = DateTimeN;
  74989. },{}],426:[function(require,module,exports){
  74990. "use strict";
  74991. Object.defineProperty(exports, "__esModule", {
  74992. value: true
  74993. });
  74994. exports.default = void 0;
  74995. const UTC_YEAR_ONE = Date.UTC(2000, 0, -730118);
  74996. const DateTimeOffset = {
  74997. id: 0x2B,
  74998. type: 'DATETIMEOFFSETN',
  74999. name: 'DateTimeOffset',
  75000. declaration: function declaration(parameter) {
  75001. return 'datetimeoffset(' + this.resolveScale(parameter) + ')';
  75002. },
  75003. resolveScale: function resolveScale(parameter) {
  75004. if (parameter.scale != null) {
  75005. return parameter.scale;
  75006. } else if (parameter.value === null) {
  75007. return 0;
  75008. } else {
  75009. return 7;
  75010. }
  75011. },
  75012. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  75013. buffer.writeUInt8(this.id);
  75014. buffer.writeUInt8(parameter.scale);
  75015. },
  75016. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75017. if (parameter.value != null) {
  75018. const time = new Date(+parameter.value);
  75019. time.setUTCFullYear(1970);
  75020. time.setUTCMonth(0);
  75021. time.setUTCDate(1);
  75022. let timestamp;
  75023. timestamp = +time * Math.pow(10, parameter.scale - 3);
  75024. timestamp += (parameter.value.nanosecondDelta != null ? parameter.value.nanosecondDelta : 0) * Math.pow(10, parameter.scale);
  75025. timestamp = Math.round(timestamp);
  75026. const offset = -parameter.value.getTimezoneOffset();
  75027. switch (parameter.scale) {
  75028. case 0:
  75029. case 1:
  75030. case 2:
  75031. buffer.writeUInt8(8);
  75032. buffer.writeUInt24LE(timestamp);
  75033. break;
  75034. case 3:
  75035. case 4:
  75036. buffer.writeUInt8(9);
  75037. buffer.writeUInt32LE(timestamp);
  75038. break;
  75039. case 5:
  75040. case 6:
  75041. case 7:
  75042. buffer.writeUInt8(10);
  75043. buffer.writeUInt40LE(timestamp);
  75044. }
  75045. buffer.writeUInt24LE(Math.floor((+parameter.value - UTC_YEAR_ONE) / 86400000));
  75046. buffer.writeInt16LE(offset);
  75047. } else {
  75048. buffer.writeUInt8(0);
  75049. }
  75050. cb();
  75051. },
  75052. validate: function validate(value) {
  75053. if (value == null) {
  75054. return null;
  75055. }
  75056. if (!(value instanceof Date)) {
  75057. value = new Date(Date.parse(value));
  75058. }
  75059. if (isNaN(value)) {
  75060. return new TypeError('Invalid date.');
  75061. }
  75062. return value;
  75063. }
  75064. };
  75065. var _default = DateTimeOffset;
  75066. exports.default = _default;
  75067. module.exports = DateTimeOffset;
  75068. },{}],427:[function(require,module,exports){
  75069. "use strict";
  75070. Object.defineProperty(exports, "__esModule", {
  75071. value: true
  75072. });
  75073. exports.default = void 0;
  75074. var _decimaln = _interopRequireDefault(require("./decimaln"));
  75075. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75076. const Decimal = {
  75077. id: 0x37,
  75078. type: 'DECIMAL',
  75079. name: 'Decimal',
  75080. declaration: function declaration(parameter) {
  75081. return 'decimal(' + this.resolvePrecision(parameter) + ', ' + this.resolveScale(parameter) + ')';
  75082. },
  75083. resolvePrecision: function resolvePrecision(parameter) {
  75084. if (parameter.precision != null) {
  75085. return parameter.precision;
  75086. } else if (parameter.value === null) {
  75087. return 1;
  75088. } else {
  75089. return 18;
  75090. }
  75091. },
  75092. resolveScale: function resolveScale(parameter) {
  75093. if (parameter.scale != null) {
  75094. return parameter.scale;
  75095. } else {
  75096. return 0;
  75097. }
  75098. },
  75099. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  75100. buffer.writeUInt8(_decimaln.default.id);
  75101. if (parameter.precision <= 9) {
  75102. buffer.writeUInt8(5);
  75103. } else if (parameter.precision <= 19) {
  75104. buffer.writeUInt8(9);
  75105. } else if (parameter.precision <= 28) {
  75106. buffer.writeUInt8(13);
  75107. } else {
  75108. buffer.writeUInt8(17);
  75109. }
  75110. buffer.writeUInt8(parameter.precision);
  75111. buffer.writeUInt8(parameter.scale);
  75112. },
  75113. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75114. if (parameter.value != null) {
  75115. const sign = parameter.value < 0 ? 0 : 1;
  75116. const value = Math.round(Math.abs(parameter.value * Math.pow(10, parameter.scale)));
  75117. if (parameter.precision <= 9) {
  75118. buffer.writeUInt8(5);
  75119. buffer.writeUInt8(sign);
  75120. buffer.writeUInt32LE(value);
  75121. } else if (parameter.precision <= 19) {
  75122. buffer.writeUInt8(9);
  75123. buffer.writeUInt8(sign);
  75124. buffer.writeUInt64LE(value);
  75125. } else if (parameter.precision <= 28) {
  75126. buffer.writeUInt8(13);
  75127. buffer.writeUInt8(sign);
  75128. buffer.writeUInt64LE(value);
  75129. buffer.writeUInt32LE(0x00000000);
  75130. } else {
  75131. buffer.writeUInt8(17);
  75132. buffer.writeUInt8(sign);
  75133. buffer.writeUInt64LE(value);
  75134. buffer.writeUInt32LE(0x00000000);
  75135. buffer.writeUInt32LE(0x00000000);
  75136. }
  75137. } else {
  75138. buffer.writeUInt8(0);
  75139. }
  75140. cb();
  75141. },
  75142. validate: function validate(value) {
  75143. if (value == null) {
  75144. return null;
  75145. }
  75146. value = parseFloat(value);
  75147. if (isNaN(value)) {
  75148. return new TypeError('Invalid number.');
  75149. }
  75150. return value;
  75151. }
  75152. };
  75153. var _default = Decimal;
  75154. exports.default = _default;
  75155. module.exports = Decimal;
  75156. },{"./decimaln":428}],428:[function(require,module,exports){
  75157. "use strict";
  75158. Object.defineProperty(exports, "__esModule", {
  75159. value: true
  75160. });
  75161. exports.default = void 0;
  75162. const DecimalN = {
  75163. id: 0x6A,
  75164. type: 'DECIMALN',
  75165. name: 'DecimalN',
  75166. declaration() {
  75167. throw new Error('not implemented');
  75168. },
  75169. writeTypeInfo() {
  75170. throw new Error('not implemented');
  75171. },
  75172. writeParameterData() {
  75173. throw new Error('not implemented');
  75174. },
  75175. validate() {
  75176. throw new Error('not implemented');
  75177. }
  75178. };
  75179. var _default = DecimalN;
  75180. exports.default = _default;
  75181. module.exports = DecimalN;
  75182. },{}],429:[function(require,module,exports){
  75183. "use strict";
  75184. Object.defineProperty(exports, "__esModule", {
  75185. value: true
  75186. });
  75187. exports.default = void 0;
  75188. var _floatn = _interopRequireDefault(require("./floatn"));
  75189. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75190. const Float = {
  75191. id: 0x3E,
  75192. type: 'FLT8',
  75193. name: 'Float',
  75194. declaration: function declaration() {
  75195. return 'float';
  75196. },
  75197. writeTypeInfo: function writeTypeInfo(buffer) {
  75198. buffer.writeUInt8(_floatn.default.id);
  75199. buffer.writeUInt8(8);
  75200. },
  75201. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75202. if (parameter.value != null) {
  75203. buffer.writeUInt8(8);
  75204. buffer.writeDoubleLE(parseFloat(parameter.value));
  75205. } else {
  75206. buffer.writeUInt8(0);
  75207. }
  75208. cb();
  75209. },
  75210. validate: function validate(value) {
  75211. if (value == null) {
  75212. return null;
  75213. }
  75214. value = parseFloat(value);
  75215. if (isNaN(value)) {
  75216. return new TypeError('Invalid number.');
  75217. }
  75218. return value;
  75219. }
  75220. };
  75221. var _default = Float;
  75222. exports.default = _default;
  75223. module.exports = Float;
  75224. },{"./floatn":430}],430:[function(require,module,exports){
  75225. "use strict";
  75226. Object.defineProperty(exports, "__esModule", {
  75227. value: true
  75228. });
  75229. exports.default = void 0;
  75230. const FloatN = {
  75231. id: 0x6D,
  75232. type: 'FLTN',
  75233. name: 'FloatN',
  75234. declaration() {
  75235. throw new Error('not implemented');
  75236. },
  75237. writeTypeInfo() {
  75238. throw new Error('not implemented');
  75239. },
  75240. writeParameterData() {
  75241. throw new Error('not implemented');
  75242. },
  75243. validate() {
  75244. throw new Error('not implemented');
  75245. }
  75246. };
  75247. var _default = FloatN;
  75248. exports.default = _default;
  75249. module.exports = FloatN;
  75250. },{}],431:[function(require,module,exports){
  75251. (function (Buffer){(function (){
  75252. "use strict";
  75253. Object.defineProperty(exports, "__esModule", {
  75254. value: true
  75255. });
  75256. exports.default = void 0;
  75257. const Image = {
  75258. id: 0x22,
  75259. type: 'IMAGE',
  75260. name: 'Image',
  75261. hasTableName: true,
  75262. declaration: function declaration() {
  75263. return 'image';
  75264. },
  75265. resolveLength: function resolveLength(parameter) {
  75266. if (parameter.value != null) {
  75267. const value = parameter.value; // TODO: Temporary solution. Replace 'any' more with specific type;
  75268. return value.length;
  75269. } else {
  75270. return -1;
  75271. }
  75272. },
  75273. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  75274. buffer.writeUInt8(this.id);
  75275. buffer.writeInt32LE(parameter.length);
  75276. },
  75277. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75278. if (parameter.value != null) {
  75279. buffer.writeInt32LE(parameter.length);
  75280. buffer.writeBuffer(parameter.value);
  75281. } else {
  75282. buffer.writeInt32LE(parameter.length);
  75283. }
  75284. cb();
  75285. },
  75286. validate: function validate(value) {
  75287. if (value == null) {
  75288. return null;
  75289. }
  75290. if (!Buffer.isBuffer(value)) {
  75291. return new TypeError('Invalid buffer.');
  75292. }
  75293. return value;
  75294. }
  75295. };
  75296. var _default = Image;
  75297. exports.default = _default;
  75298. module.exports = Image;
  75299. }).call(this)}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")})
  75300. },{"../../../../../is-buffer/index.js":322}],432:[function(require,module,exports){
  75301. "use strict";
  75302. Object.defineProperty(exports, "__esModule", {
  75303. value: true
  75304. });
  75305. exports.default = void 0;
  75306. var _intn = _interopRequireDefault(require("./intn"));
  75307. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75308. const Int = {
  75309. id: 0x38,
  75310. type: 'INT4',
  75311. name: 'Int',
  75312. declaration: function declaration() {
  75313. return 'int';
  75314. },
  75315. writeTypeInfo: function writeTypeInfo(buffer) {
  75316. buffer.writeUInt8(_intn.default.id);
  75317. buffer.writeUInt8(4);
  75318. },
  75319. writeParameterData: function writeParameterData(buffer, parameter, _options, cb) {
  75320. if (parameter.value != null) {
  75321. buffer.writeUInt8(4);
  75322. buffer.writeInt32LE(Number(parameter.value));
  75323. } else {
  75324. buffer.writeUInt8(0);
  75325. }
  75326. cb();
  75327. },
  75328. validate: function validate(value) {
  75329. if (value == null) {
  75330. return null;
  75331. }
  75332. if (typeof value !== 'number') {
  75333. value = Number(value);
  75334. }
  75335. if (isNaN(value)) {
  75336. return new TypeError('Invalid number.');
  75337. }
  75338. if (value < -2147483648 || value > 2147483647) {
  75339. return new TypeError('Value must be between -2147483648 and 2147483647, inclusive.');
  75340. }
  75341. return value | 0;
  75342. }
  75343. };
  75344. var _default = Int;
  75345. exports.default = _default;
  75346. module.exports = Int;
  75347. },{"./intn":433}],433:[function(require,module,exports){
  75348. "use strict";
  75349. Object.defineProperty(exports, "__esModule", {
  75350. value: true
  75351. });
  75352. exports.default = void 0;
  75353. const IntN = {
  75354. id: 0x26,
  75355. type: 'INTN',
  75356. name: 'IntN',
  75357. declaration() {
  75358. throw new Error('not implemented');
  75359. },
  75360. writeTypeInfo() {
  75361. throw new Error('not implemented');
  75362. },
  75363. writeParameterData() {
  75364. throw new Error('not implemented');
  75365. },
  75366. validate() {
  75367. throw new Error('not implemented');
  75368. }
  75369. };
  75370. var _default = IntN;
  75371. exports.default = _default;
  75372. module.exports = IntN;
  75373. },{}],434:[function(require,module,exports){
  75374. "use strict";
  75375. Object.defineProperty(exports, "__esModule", {
  75376. value: true
  75377. });
  75378. exports.default = void 0;
  75379. var _moneyn = _interopRequireDefault(require("./moneyn"));
  75380. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75381. const Money = {
  75382. id: 0x3C,
  75383. type: 'MONEY',
  75384. name: 'Money',
  75385. declaration: function declaration() {
  75386. return 'money';
  75387. },
  75388. writeTypeInfo: function writeTypeInfo(buffer) {
  75389. buffer.writeUInt8(_moneyn.default.id);
  75390. buffer.writeUInt8(8);
  75391. },
  75392. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75393. if (parameter.value != null) {
  75394. buffer.writeUInt8(8);
  75395. buffer.writeMoney(parameter.value * 10000);
  75396. } else {
  75397. buffer.writeUInt8(0);
  75398. }
  75399. cb();
  75400. },
  75401. validate: function validate(value) {
  75402. if (value == null) {
  75403. return null;
  75404. }
  75405. value = parseFloat(value);
  75406. if (isNaN(value)) {
  75407. return new TypeError('Invalid number.');
  75408. }
  75409. return value;
  75410. }
  75411. };
  75412. var _default = Money;
  75413. exports.default = _default;
  75414. module.exports = Money;
  75415. },{"./moneyn":435}],435:[function(require,module,exports){
  75416. "use strict";
  75417. Object.defineProperty(exports, "__esModule", {
  75418. value: true
  75419. });
  75420. exports.default = void 0;
  75421. const MoneyN = {
  75422. id: 0x6E,
  75423. type: 'MONEYN',
  75424. name: 'MoneyN',
  75425. declaration() {
  75426. throw new Error('not implemented');
  75427. },
  75428. writeTypeInfo() {
  75429. throw new Error('not implemented');
  75430. },
  75431. writeParameterData() {
  75432. throw new Error('not implemented');
  75433. },
  75434. validate() {
  75435. throw new Error('not implemented');
  75436. }
  75437. };
  75438. var _default = MoneyN;
  75439. exports.default = _default;
  75440. module.exports = MoneyN;
  75441. },{}],436:[function(require,module,exports){
  75442. (function (Buffer){(function (){
  75443. "use strict";
  75444. Object.defineProperty(exports, "__esModule", {
  75445. value: true
  75446. });
  75447. exports.default = void 0;
  75448. const NULL = (1 << 16) - 1;
  75449. const NChar = {
  75450. id: 0xEF,
  75451. type: 'NCHAR',
  75452. name: 'NChar',
  75453. maximumLength: 4000,
  75454. declaration: function declaration(parameter) {
  75455. // const value = parameter.value as null | string | { toString(): string };
  75456. const value = parameter.value; // Temporary solution. Remove 'any' later.
  75457. let length;
  75458. if (parameter.length) {
  75459. length = parameter.length;
  75460. } else if (parameter.value != null) {
  75461. length = value.toString().length || 1;
  75462. } else if (parameter.value === null && !parameter.output) {
  75463. length = 1;
  75464. } else {
  75465. length = this.maximumLength;
  75466. }
  75467. if (length < this.maximumLength) {
  75468. return 'nchar(' + length + ')';
  75469. } else {
  75470. return 'nchar(' + this.maximumLength + ')';
  75471. }
  75472. },
  75473. resolveLength: function resolveLength(parameter) {
  75474. // const value = parameter.value as null | string | { toString(): string };
  75475. const value = parameter.value; // Temporary solution. Remove 'any' later.
  75476. if (parameter.length != null) {
  75477. return parameter.length;
  75478. } else if (parameter.value != null) {
  75479. if (Buffer.isBuffer(parameter.value)) {
  75480. return parameter.value.length / 2 || 1;
  75481. } else {
  75482. return value.toString().length || 1;
  75483. }
  75484. } else {
  75485. return this.maximumLength;
  75486. }
  75487. },
  75488. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  75489. buffer.writeUInt8(this.id);
  75490. buffer.writeUInt16LE(parameter.length * 2);
  75491. buffer.writeBuffer(Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00]));
  75492. },
  75493. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75494. if (parameter.value != null) {
  75495. buffer.writeUsVarbyte(parameter.value, 'ucs2');
  75496. } else {
  75497. buffer.writeUInt16LE(NULL);
  75498. }
  75499. cb();
  75500. },
  75501. validate: function validate(value) {
  75502. if (value == null) {
  75503. return null;
  75504. }
  75505. if (typeof value !== 'string') {
  75506. if (typeof value.toString !== 'function') {
  75507. return TypeError('Invalid string.');
  75508. }
  75509. value = value.toString();
  75510. }
  75511. return value;
  75512. }
  75513. };
  75514. var _default = NChar;
  75515. exports.default = _default;
  75516. module.exports = NChar;
  75517. }).call(this)}).call(this,require("buffer").Buffer)
  75518. },{"buffer":193}],437:[function(require,module,exports){
  75519. "use strict";
  75520. Object.defineProperty(exports, "__esModule", {
  75521. value: true
  75522. });
  75523. exports.default = void 0;
  75524. const NText = {
  75525. id: 0x63,
  75526. type: 'NTEXT',
  75527. name: 'NText',
  75528. hasTableName: true,
  75529. declaration() {
  75530. throw new Error('not implemented');
  75531. },
  75532. writeTypeInfo() {
  75533. throw new Error('not implemented');
  75534. },
  75535. writeParameterData() {
  75536. throw new Error('not implemented');
  75537. },
  75538. validate() {
  75539. throw new Error('not implemented');
  75540. }
  75541. };
  75542. var _default = NText;
  75543. exports.default = _default;
  75544. module.exports = NText;
  75545. },{}],438:[function(require,module,exports){
  75546. "use strict";
  75547. Object.defineProperty(exports, "__esModule", {
  75548. value: true
  75549. });
  75550. exports.default = void 0;
  75551. const Null = {
  75552. id: 0x1F,
  75553. type: 'NULL',
  75554. name: 'Null',
  75555. declaration() {
  75556. throw new Error('not implemented');
  75557. },
  75558. writeTypeInfo() {
  75559. throw new Error('not implemented');
  75560. },
  75561. writeParameterData() {
  75562. throw new Error('not implemented');
  75563. },
  75564. validate() {
  75565. throw new Error('not implemented');
  75566. }
  75567. };
  75568. var _default = Null;
  75569. exports.default = _default;
  75570. module.exports = Null;
  75571. },{}],439:[function(require,module,exports){
  75572. "use strict";
  75573. Object.defineProperty(exports, "__esModule", {
  75574. value: true
  75575. });
  75576. exports.default = void 0;
  75577. var _numericn = _interopRequireDefault(require("./numericn"));
  75578. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75579. const Numeric = {
  75580. id: 0x3F,
  75581. type: 'NUMERIC',
  75582. name: 'Numeric',
  75583. declaration: function declaration(parameter) {
  75584. return 'numeric(' + this.resolvePrecision(parameter) + ', ' + this.resolveScale(parameter) + ')';
  75585. },
  75586. resolvePrecision: function resolvePrecision(parameter) {
  75587. if (parameter.precision != null) {
  75588. return parameter.precision;
  75589. } else if (parameter.value === null) {
  75590. return 1;
  75591. } else {
  75592. return 18;
  75593. }
  75594. },
  75595. resolveScale: function resolveScale(parameter) {
  75596. if (parameter.scale != null) {
  75597. return parameter.scale;
  75598. } else {
  75599. return 0;
  75600. }
  75601. },
  75602. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  75603. buffer.writeUInt8(_numericn.default.id);
  75604. if (parameter.precision <= 9) {
  75605. buffer.writeUInt8(5);
  75606. } else if (parameter.precision <= 19) {
  75607. buffer.writeUInt8(9);
  75608. } else if (parameter.precision <= 28) {
  75609. buffer.writeUInt8(13);
  75610. } else {
  75611. buffer.writeUInt8(17);
  75612. }
  75613. buffer.writeUInt8(parameter.precision);
  75614. buffer.writeUInt8(parameter.scale);
  75615. },
  75616. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75617. if (parameter.value != null) {
  75618. const sign = parameter.value < 0 ? 0 : 1;
  75619. const value = Math.round(Math.abs(parameter.value * Math.pow(10, parameter.scale)));
  75620. if (parameter.precision <= 9) {
  75621. buffer.writeUInt8(5);
  75622. buffer.writeUInt8(sign);
  75623. buffer.writeUInt32LE(value);
  75624. } else if (parameter.precision <= 19) {
  75625. buffer.writeUInt8(9);
  75626. buffer.writeUInt8(sign);
  75627. buffer.writeUInt64LE(value);
  75628. } else if (parameter.precision <= 28) {
  75629. buffer.writeUInt8(13);
  75630. buffer.writeUInt8(sign);
  75631. buffer.writeUInt64LE(value);
  75632. buffer.writeUInt32LE(0x00000000);
  75633. } else {
  75634. buffer.writeUInt8(17);
  75635. buffer.writeUInt8(sign);
  75636. buffer.writeUInt64LE(value);
  75637. buffer.writeUInt32LE(0x00000000);
  75638. buffer.writeUInt32LE(0x00000000);
  75639. }
  75640. } else {
  75641. buffer.writeUInt8(0);
  75642. }
  75643. cb();
  75644. },
  75645. validate: function validate(value) {
  75646. if (value == null) {
  75647. return null;
  75648. }
  75649. value = parseFloat(value);
  75650. if (isNaN(value)) {
  75651. return new TypeError('Invalid number.');
  75652. }
  75653. return value;
  75654. }
  75655. };
  75656. var _default = Numeric;
  75657. exports.default = _default;
  75658. module.exports = Numeric;
  75659. },{"./numericn":440}],440:[function(require,module,exports){
  75660. "use strict";
  75661. Object.defineProperty(exports, "__esModule", {
  75662. value: true
  75663. });
  75664. exports.default = void 0;
  75665. const NumericN = {
  75666. id: 0x6C,
  75667. type: 'NUMERICN',
  75668. name: 'NumericN',
  75669. declaration() {
  75670. throw new Error('not implemented');
  75671. },
  75672. writeTypeInfo() {
  75673. throw new Error('not implemented');
  75674. },
  75675. writeParameterData() {
  75676. throw new Error('not implemented');
  75677. },
  75678. validate() {
  75679. throw new Error('not implemented');
  75680. }
  75681. };
  75682. var _default = NumericN;
  75683. exports.default = _default;
  75684. module.exports = NumericN;
  75685. },{}],441:[function(require,module,exports){
  75686. (function (Buffer){(function (){
  75687. "use strict";
  75688. Object.defineProperty(exports, "__esModule", {
  75689. value: true
  75690. });
  75691. exports.default = void 0;
  75692. const NULL = (1 << 16) - 1;
  75693. const MAX = (1 << 16) - 1;
  75694. const NVarChar = {
  75695. id: 0xE7,
  75696. type: 'NVARCHAR',
  75697. name: 'NVarChar',
  75698. maximumLength: 4000,
  75699. declaration: function declaration(parameter) {
  75700. const value = parameter.value; // Temporary solution. Remove 'any' later.
  75701. let length;
  75702. if (parameter.length) {
  75703. length = parameter.length;
  75704. } else if (value != null) {
  75705. length = value.toString().length || 1;
  75706. } else if (value === null && !parameter.output) {
  75707. length = 1;
  75708. } else {
  75709. length = this.maximumLength;
  75710. }
  75711. if (length <= this.maximumLength) {
  75712. return 'nvarchar(' + length + ')';
  75713. } else {
  75714. return 'nvarchar(max)';
  75715. }
  75716. },
  75717. resolveLength: function resolveLength(parameter) {
  75718. const value = parameter.value; // Temporary solution. Remove 'any' later.
  75719. if (parameter.length != null) {
  75720. return parameter.length;
  75721. } else if (value != null) {
  75722. if (Buffer.isBuffer(value)) {
  75723. return value.length / 2 || 1;
  75724. } else {
  75725. return value.toString().length || 1;
  75726. }
  75727. } else {
  75728. return this.maximumLength;
  75729. }
  75730. },
  75731. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  75732. buffer.writeUInt8(this.id);
  75733. if (parameter.length <= this.maximumLength) {
  75734. buffer.writeUInt16LE(parameter.length * 2);
  75735. } else {
  75736. buffer.writeUInt16LE(MAX);
  75737. }
  75738. buffer.writeBuffer(Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00]));
  75739. },
  75740. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75741. if (parameter.value != null) {
  75742. if (parameter.length <= this.maximumLength) {
  75743. buffer.writeUsVarbyte(parameter.value, 'ucs2');
  75744. } else {
  75745. buffer.writePLPBody(parameter.value, 'ucs2');
  75746. }
  75747. } else if (parameter.length <= this.maximumLength) {
  75748. buffer.writeUInt16LE(NULL);
  75749. } else {
  75750. buffer.writeUInt32LE(0xFFFFFFFF);
  75751. buffer.writeUInt32LE(0xFFFFFFFF);
  75752. }
  75753. cb();
  75754. },
  75755. validate: function validate(value) {
  75756. if (value == null) {
  75757. return null;
  75758. }
  75759. if (typeof value !== 'string') {
  75760. if (typeof value.toString !== 'function') {
  75761. return TypeError('Invalid string.');
  75762. }
  75763. value = value.toString();
  75764. }
  75765. return value;
  75766. }
  75767. };
  75768. var _default = NVarChar;
  75769. exports.default = _default;
  75770. module.exports = NVarChar;
  75771. }).call(this)}).call(this,require("buffer").Buffer)
  75772. },{"buffer":193}],442:[function(require,module,exports){
  75773. "use strict";
  75774. Object.defineProperty(exports, "__esModule", {
  75775. value: true
  75776. });
  75777. exports.default = void 0;
  75778. var _floatn = _interopRequireDefault(require("./floatn"));
  75779. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75780. const Real = {
  75781. id: 0x3B,
  75782. type: 'FLT4',
  75783. name: 'Real',
  75784. declaration: function declaration() {
  75785. return 'real';
  75786. },
  75787. writeTypeInfo: function writeTypeInfo(buffer) {
  75788. buffer.writeUInt8(_floatn.default.id);
  75789. buffer.writeUInt8(4);
  75790. },
  75791. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75792. if (parameter.value != null) {
  75793. buffer.writeUInt8(4);
  75794. buffer.writeFloatLE(parseFloat(parameter.value));
  75795. } else {
  75796. buffer.writeUInt8(0);
  75797. }
  75798. cb();
  75799. },
  75800. validate: function validate(value) {
  75801. if (value == null) {
  75802. return null;
  75803. }
  75804. value = parseFloat(value);
  75805. if (isNaN(value)) {
  75806. return new TypeError('Invalid number.');
  75807. }
  75808. return value;
  75809. }
  75810. };
  75811. var _default = Real;
  75812. exports.default = _default;
  75813. module.exports = Real;
  75814. },{"./floatn":430}],443:[function(require,module,exports){
  75815. "use strict";
  75816. Object.defineProperty(exports, "__esModule", {
  75817. value: true
  75818. });
  75819. exports.default = void 0;
  75820. var _datetimen = _interopRequireDefault(require("./datetimen"));
  75821. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75822. const EPOCH_DATE = new Date(1900, 0, 1);
  75823. const UTC_EPOCH_DATE = new Date(Date.UTC(1900, 0, 1));
  75824. const SmallDateTime = {
  75825. id: 0x3A,
  75826. type: 'DATETIM4',
  75827. name: 'SmallDateTime',
  75828. declaration: function declaration() {
  75829. return 'smalldatetime';
  75830. },
  75831. writeTypeInfo: function writeTypeInfo(buffer) {
  75832. buffer.writeUInt8(_datetimen.default.id);
  75833. buffer.writeUInt8(4);
  75834. },
  75835. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75836. if (parameter.value != null) {
  75837. let days, dstDiff, minutes;
  75838. if (options.useUTC) {
  75839. days = Math.floor((parameter.value.getTime() - UTC_EPOCH_DATE.getTime()) / (1000 * 60 * 60 * 24));
  75840. minutes = parameter.value.getUTCHours() * 60 + parameter.value.getUTCMinutes();
  75841. } else {
  75842. dstDiff = -(parameter.value.getTimezoneOffset() - EPOCH_DATE.getTimezoneOffset()) * 60 * 1000;
  75843. days = Math.floor((parameter.value.getTime() - EPOCH_DATE.getTime() + dstDiff) / (1000 * 60 * 60 * 24));
  75844. minutes = parameter.value.getHours() * 60 + parameter.value.getMinutes();
  75845. }
  75846. buffer.writeUInt8(4);
  75847. buffer.writeUInt16LE(days);
  75848. buffer.writeUInt16LE(minutes);
  75849. } else {
  75850. buffer.writeUInt8(0);
  75851. }
  75852. cb();
  75853. },
  75854. validate: function validate(value) {
  75855. if (value == null) {
  75856. return null;
  75857. }
  75858. if (!(value instanceof Date)) {
  75859. value = new Date(Date.parse(value));
  75860. }
  75861. if (isNaN(value)) {
  75862. return new TypeError('Invalid date.');
  75863. }
  75864. return value;
  75865. }
  75866. };
  75867. var _default = SmallDateTime;
  75868. exports.default = _default;
  75869. module.exports = SmallDateTime;
  75870. },{"./datetimen":425}],444:[function(require,module,exports){
  75871. "use strict";
  75872. Object.defineProperty(exports, "__esModule", {
  75873. value: true
  75874. });
  75875. exports.default = void 0;
  75876. var _intn = _interopRequireDefault(require("./intn"));
  75877. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75878. const SmallInt = {
  75879. id: 0x34,
  75880. type: 'INT2',
  75881. name: 'SmallInt',
  75882. declaration: function declaration() {
  75883. return 'smallint';
  75884. },
  75885. writeTypeInfo: function writeTypeInfo(buffer) {
  75886. buffer.writeUInt8(_intn.default.id);
  75887. buffer.writeUInt8(2);
  75888. },
  75889. writeParameterData: function writeParameterData(buffer, parameter, _options, cb) {
  75890. if (parameter.value != null) {
  75891. buffer.writeUInt8(2);
  75892. buffer.writeInt16LE(Number(parameter.value));
  75893. } else {
  75894. buffer.writeUInt8(0);
  75895. }
  75896. cb();
  75897. },
  75898. validate: function validate(value) {
  75899. if (value == null) {
  75900. return null;
  75901. }
  75902. if (typeof value !== 'number') {
  75903. value = Number(value);
  75904. }
  75905. if (isNaN(value)) {
  75906. return new TypeError('Invalid number.');
  75907. }
  75908. if (value < -32768 || value > 32767) {
  75909. return new TypeError('Value must be between -32768 and 32767, inclusive.');
  75910. }
  75911. return value | 0;
  75912. }
  75913. };
  75914. var _default = SmallInt;
  75915. exports.default = _default;
  75916. module.exports = SmallInt;
  75917. },{"./intn":433}],445:[function(require,module,exports){
  75918. "use strict";
  75919. Object.defineProperty(exports, "__esModule", {
  75920. value: true
  75921. });
  75922. exports.default = void 0;
  75923. var _moneyn = _interopRequireDefault(require("./moneyn"));
  75924. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  75925. const SmallMoney = {
  75926. id: 0x7A,
  75927. type: 'MONEY4',
  75928. name: 'SmallMoney',
  75929. declaration: function declaration() {
  75930. return 'smallmoney';
  75931. },
  75932. writeTypeInfo: function writeTypeInfo(buffer) {
  75933. buffer.writeUInt8(_moneyn.default.id);
  75934. buffer.writeUInt8(4);
  75935. },
  75936. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  75937. if (parameter.value != null) {
  75938. buffer.writeUInt8(4);
  75939. buffer.writeInt32LE(parameter.value * 10000);
  75940. } else {
  75941. buffer.writeUInt8(0);
  75942. }
  75943. cb();
  75944. },
  75945. validate: function validate(value) {
  75946. if (value == null) {
  75947. return null;
  75948. }
  75949. value = parseFloat(value);
  75950. if (isNaN(value)) {
  75951. return new TypeError('Invalid number.');
  75952. }
  75953. if (value < -214748.3648 || value > 214748.3647) {
  75954. return new TypeError('Value must be between -214748.3648 and 214748.3647.');
  75955. }
  75956. return value;
  75957. }
  75958. };
  75959. var _default = SmallMoney;
  75960. exports.default = _default;
  75961. module.exports = SmallMoney;
  75962. },{"./moneyn":435}],446:[function(require,module,exports){
  75963. "use strict";
  75964. Object.defineProperty(exports, "__esModule", {
  75965. value: true
  75966. });
  75967. exports.default = void 0;
  75968. const Variant = {
  75969. id: 0x62,
  75970. type: 'SSVARIANTTYPE',
  75971. name: 'Variant',
  75972. declaration: function declaration() {
  75973. return 'sql_variant';
  75974. },
  75975. writeTypeInfo() {
  75976. throw new Error('not implemented');
  75977. },
  75978. writeParameterData() {
  75979. throw new Error('not implemented');
  75980. },
  75981. validate() {
  75982. throw new Error('not implemented');
  75983. }
  75984. };
  75985. var _default = Variant;
  75986. exports.default = _default;
  75987. module.exports = Variant;
  75988. },{}],447:[function(require,module,exports){
  75989. (function (Buffer){(function (){
  75990. "use strict";
  75991. Object.defineProperty(exports, "__esModule", {
  75992. value: true
  75993. });
  75994. exports.default = void 0;
  75995. const Text = {
  75996. id: 0x23,
  75997. type: 'TEXT',
  75998. name: 'Text',
  75999. hasTableName: true,
  76000. declaration: function declaration() {
  76001. return 'text';
  76002. },
  76003. resolveLength: function resolveLength(parameter) {
  76004. const value = parameter.value; // Temporary solution. Remove 'any' later.
  76005. if (value != null) {
  76006. return value.length;
  76007. } else {
  76008. return -1;
  76009. }
  76010. },
  76011. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  76012. buffer.writeUInt8(this.id);
  76013. buffer.writeInt32LE(parameter.length);
  76014. },
  76015. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  76016. buffer.writeBuffer(Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00]));
  76017. if (parameter.value != null) {
  76018. buffer.writeInt32LE(parameter.length);
  76019. buffer.writeString(parameter.value.toString(), 'ascii');
  76020. } else {
  76021. buffer.writeInt32LE(parameter.length);
  76022. }
  76023. cb();
  76024. },
  76025. validate: function validate(value) {
  76026. if (value == null) {
  76027. return null;
  76028. }
  76029. if (typeof value !== 'string') {
  76030. if (typeof value.toString !== 'function') {
  76031. return TypeError('Invalid string.');
  76032. }
  76033. value = value.toString();
  76034. }
  76035. return value;
  76036. }
  76037. };
  76038. var _default = Text;
  76039. exports.default = _default;
  76040. module.exports = Text;
  76041. }).call(this)}).call(this,require("buffer").Buffer)
  76042. },{"buffer":193}],448:[function(require,module,exports){
  76043. "use strict";
  76044. Object.defineProperty(exports, "__esModule", {
  76045. value: true
  76046. });
  76047. exports.default = void 0;
  76048. const Time = {
  76049. id: 0x29,
  76050. type: 'TIMEN',
  76051. name: 'Time',
  76052. declaration: function declaration(parameter) {
  76053. return 'time(' + this.resolveScale(parameter) + ')';
  76054. },
  76055. resolveScale: function resolveScale(parameter) {
  76056. if (parameter.scale != null) {
  76057. return parameter.scale;
  76058. } else if (parameter.value === null) {
  76059. return 0;
  76060. } else {
  76061. return 7;
  76062. }
  76063. },
  76064. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  76065. buffer.writeUInt8(this.id);
  76066. buffer.writeUInt8(parameter.scale);
  76067. },
  76068. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  76069. if (parameter.value != null) {
  76070. const time = parameter.value;
  76071. let timestamp;
  76072. if (options.useUTC) {
  76073. timestamp = ((time.getUTCHours() * 60 + time.getUTCMinutes()) * 60 + time.getUTCSeconds()) * 1000 + time.getUTCMilliseconds();
  76074. } else {
  76075. timestamp = ((time.getHours() * 60 + time.getMinutes()) * 60 + time.getSeconds()) * 1000 + time.getMilliseconds();
  76076. }
  76077. timestamp = timestamp * Math.pow(10, parameter.scale - 3);
  76078. timestamp += (parameter.value.nanosecondDelta != null ? parameter.value.nanosecondDelta : 0) * Math.pow(10, parameter.scale);
  76079. timestamp = Math.round(timestamp);
  76080. switch (parameter.scale) {
  76081. case 0:
  76082. case 1:
  76083. case 2:
  76084. buffer.writeUInt8(3);
  76085. buffer.writeUInt24LE(timestamp);
  76086. break;
  76087. case 3:
  76088. case 4:
  76089. buffer.writeUInt8(4);
  76090. buffer.writeUInt32LE(timestamp);
  76091. break;
  76092. case 5:
  76093. case 6:
  76094. case 7:
  76095. buffer.writeUInt8(5);
  76096. buffer.writeUInt40LE(timestamp);
  76097. }
  76098. } else {
  76099. buffer.writeUInt8(0);
  76100. }
  76101. cb();
  76102. },
  76103. validate: function validate(value) {
  76104. if (value == null) {
  76105. return null;
  76106. }
  76107. if (!(value instanceof Date)) {
  76108. value = new Date(Date.parse(value));
  76109. }
  76110. if (isNaN(value)) {
  76111. return new TypeError('Invalid time.');
  76112. }
  76113. return value;
  76114. }
  76115. };
  76116. var _default = Time;
  76117. exports.default = _default;
  76118. module.exports = Time;
  76119. },{}],449:[function(require,module,exports){
  76120. "use strict";
  76121. Object.defineProperty(exports, "__esModule", {
  76122. value: true
  76123. });
  76124. exports.default = void 0;
  76125. var _intn = _interopRequireDefault(require("./intn"));
  76126. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  76127. const TinyInt = {
  76128. id: 0x30,
  76129. type: 'INT1',
  76130. name: 'TinyInt',
  76131. declaration: function declaration() {
  76132. return 'tinyint';
  76133. },
  76134. writeTypeInfo: function writeTypeInfo(buffer) {
  76135. buffer.writeUInt8(_intn.default.id);
  76136. buffer.writeUInt8(1);
  76137. },
  76138. writeParameterData: function writeParameterData(buffer, parameter, _options, cb) {
  76139. if (parameter.value != null) {
  76140. buffer.writeUInt8(1);
  76141. buffer.writeUInt8(Number(parameter.value));
  76142. } else {
  76143. buffer.writeUInt8(0);
  76144. }
  76145. cb();
  76146. },
  76147. validate: function validate(value) {
  76148. if (value == null) {
  76149. return null;
  76150. }
  76151. if (typeof value !== 'number') {
  76152. value = Number(value);
  76153. }
  76154. if (isNaN(value)) {
  76155. return new TypeError('Invalid number.');
  76156. }
  76157. if (value < 0 || value > 255) {
  76158. return new TypeError('Value must be between 0 and 255, inclusive.');
  76159. }
  76160. return value | 0;
  76161. }
  76162. };
  76163. var _default = TinyInt;
  76164. exports.default = _default;
  76165. module.exports = TinyInt;
  76166. },{"./intn":433}],450:[function(require,module,exports){
  76167. (function (setImmediate){(function (){
  76168. "use strict";
  76169. Object.defineProperty(exports, "__esModule", {
  76170. value: true
  76171. });
  76172. exports.default = void 0;
  76173. const TVP = {
  76174. id: 0xF3,
  76175. type: 'TVPTYPE',
  76176. name: 'TVP',
  76177. declaration: function declaration(parameter) {
  76178. const value = parameter.value; // Temporary solution. Remove 'any' later.
  76179. return value.name + ' readonly';
  76180. },
  76181. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  76182. let ref, ref1, ref2, ref3;
  76183. buffer.writeUInt8(this.id);
  76184. buffer.writeBVarchar('');
  76185. buffer.writeBVarchar((ref = (ref1 = parameter.value) != null ? ref1.schema : undefined) != null ? ref : '');
  76186. buffer.writeBVarchar((ref2 = (ref3 = parameter.value) != null ? ref3.name : undefined) != null ? ref2 : '');
  76187. },
  76188. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  76189. if (parameter.value == null) {
  76190. buffer.writeUInt16LE(0xFFFF);
  76191. buffer.writeUInt8(0x00);
  76192. buffer.writeUInt8(0x00);
  76193. return;
  76194. }
  76195. buffer.writeUInt16LE(parameter.value.columns.length);
  76196. const ref = parameter.value.columns;
  76197. for (let i = 0, len = ref.length; i < len; i++) {
  76198. const column = ref[i];
  76199. buffer.writeUInt32LE(0x00000000);
  76200. buffer.writeUInt16LE(0x0000);
  76201. column.type.writeTypeInfo(buffer, column);
  76202. buffer.writeBVarchar('');
  76203. }
  76204. buffer.writeUInt8(0x00);
  76205. const ref1 = parameter.value.rows;
  76206. const writeNext = i => {
  76207. if (i >= ref1.length) {
  76208. buffer.writeUInt8(0x00);
  76209. cb();
  76210. return;
  76211. }
  76212. const row = ref1[i];
  76213. buffer.writeUInt8(0x01);
  76214. for (let k = 0, len2 = row.length; k < len2; k++) {
  76215. const value = row[k];
  76216. const param = {
  76217. value: value,
  76218. length: parameter.value.columns[k].length,
  76219. scale: parameter.value.columns[k].scale,
  76220. precision: parameter.value.columns[k].precision
  76221. };
  76222. parameter.value.columns[k].type.writeParameterData(buffer, param, options, () => {});
  76223. }
  76224. setImmediate(() => {
  76225. writeNext(i + 1);
  76226. });
  76227. };
  76228. writeNext(0);
  76229. },
  76230. validate: function validate(value) {
  76231. if (value == null) {
  76232. return null;
  76233. }
  76234. if (typeof value !== 'object') {
  76235. return new TypeError('Invalid table.');
  76236. }
  76237. if (!Array.isArray(value.columns)) {
  76238. return new TypeError('Invalid table.');
  76239. }
  76240. if (!Array.isArray(value.rows)) {
  76241. return new TypeError('Invalid table.');
  76242. }
  76243. return value;
  76244. }
  76245. };
  76246. var _default = TVP;
  76247. exports.default = _default;
  76248. module.exports = TVP;
  76249. }).call(this)}).call(this,require("timers").setImmediate)
  76250. },{"timers":639}],451:[function(require,module,exports){
  76251. "use strict";
  76252. Object.defineProperty(exports, "__esModule", {
  76253. value: true
  76254. });
  76255. exports.default = void 0;
  76256. const UDT = {
  76257. id: 0xF0,
  76258. type: 'UDTTYPE',
  76259. name: 'UDT',
  76260. declaration() {
  76261. throw new Error('not implemented');
  76262. },
  76263. writeTypeInfo() {
  76264. throw new Error('not implemented');
  76265. },
  76266. writeParameterData() {
  76267. throw new Error('not implemented');
  76268. },
  76269. validate() {
  76270. throw new Error('not implemented');
  76271. }
  76272. };
  76273. var _default = UDT;
  76274. exports.default = _default;
  76275. module.exports = UDT;
  76276. },{}],452:[function(require,module,exports){
  76277. (function (Buffer){(function (){
  76278. "use strict";
  76279. Object.defineProperty(exports, "__esModule", {
  76280. value: true
  76281. });
  76282. exports.default = void 0;
  76283. var _guidParser = require("../guid-parser");
  76284. const UniqueIdentifier = {
  76285. id: 0x24,
  76286. type: 'GUIDN',
  76287. name: 'UniqueIdentifier',
  76288. declaration: function declaration() {
  76289. return 'uniqueidentifier';
  76290. },
  76291. resolveLength: function resolveLength() {
  76292. return 16;
  76293. },
  76294. writeTypeInfo: function writeTypeInfo(buffer) {
  76295. buffer.writeUInt8(this.id);
  76296. buffer.writeUInt8(0x10);
  76297. },
  76298. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  76299. if (parameter.value != null) {
  76300. buffer.writeUInt8(0x10);
  76301. buffer.writeBuffer(Buffer.from((0, _guidParser.guidToArray)(parameter.value)));
  76302. } else {
  76303. buffer.writeUInt8(0);
  76304. }
  76305. cb();
  76306. },
  76307. validate: function validate(value) {
  76308. if (value == null) {
  76309. return null;
  76310. }
  76311. if (typeof value !== 'string') {
  76312. if (typeof value.toString !== 'function') {
  76313. return TypeError('Invalid string.');
  76314. }
  76315. value = value.toString();
  76316. }
  76317. return value;
  76318. }
  76319. };
  76320. var _default = UniqueIdentifier;
  76321. exports.default = _default;
  76322. module.exports = UniqueIdentifier;
  76323. }).call(this)}).call(this,require("buffer").Buffer)
  76324. },{"../guid-parser":458,"buffer":193}],453:[function(require,module,exports){
  76325. (function (Buffer){(function (){
  76326. "use strict";
  76327. Object.defineProperty(exports, "__esModule", {
  76328. value: true
  76329. });
  76330. exports.default = void 0;
  76331. const NULL = (1 << 16) - 1;
  76332. const MAX = (1 << 16) - 1;
  76333. const VarBinary = {
  76334. id: 0xA5,
  76335. type: 'BIGVARBIN',
  76336. name: 'VarBinary',
  76337. maximumLength: 8000,
  76338. declaration: function declaration(parameter) {
  76339. const value = parameter.value; // Temporary solution. Remove 'any' later.
  76340. let length;
  76341. if (parameter.length) {
  76342. length = parameter.length;
  76343. } else if (value != null) {
  76344. length = value.length || 1;
  76345. } else if (value === null && !parameter.output) {
  76346. length = 1;
  76347. } else {
  76348. length = this.maximumLength;
  76349. }
  76350. if (length <= this.maximumLength) {
  76351. return 'varbinary(' + length + ')';
  76352. } else {
  76353. return 'varbinary(max)';
  76354. }
  76355. },
  76356. resolveLength: function resolveLength(parameter) {
  76357. const value = parameter.value; // Temporary solution. Remove 'any' later.
  76358. if (parameter.length != null) {
  76359. return parameter.length;
  76360. } else if (value != null) {
  76361. return value.length;
  76362. } else {
  76363. return this.maximumLength;
  76364. }
  76365. },
  76366. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  76367. buffer.writeUInt8(this.id);
  76368. if (parameter.length <= this.maximumLength) {
  76369. buffer.writeUInt16LE(this.maximumLength);
  76370. } else {
  76371. buffer.writeUInt16LE(MAX);
  76372. }
  76373. },
  76374. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  76375. if (parameter.value != null) {
  76376. if (parameter.length <= this.maximumLength) {
  76377. buffer.writeUsVarbyte(parameter.value);
  76378. } else {
  76379. buffer.writePLPBody(parameter.value);
  76380. }
  76381. } else if (parameter.length <= this.maximumLength) {
  76382. buffer.writeUInt16LE(NULL);
  76383. } else {
  76384. buffer.writeUInt32LE(0xFFFFFFFF);
  76385. buffer.writeUInt32LE(0xFFFFFFFF);
  76386. }
  76387. cb();
  76388. },
  76389. validate: function validate(value) {
  76390. if (value == null) {
  76391. return null;
  76392. }
  76393. if (!Buffer.isBuffer(value)) {
  76394. return new TypeError('Invalid buffer.');
  76395. }
  76396. return value;
  76397. }
  76398. };
  76399. var _default = VarBinary;
  76400. exports.default = _default;
  76401. module.exports = VarBinary;
  76402. }).call(this)}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")})
  76403. },{"../../../../../is-buffer/index.js":322}],454:[function(require,module,exports){
  76404. (function (Buffer){(function (){
  76405. "use strict";
  76406. Object.defineProperty(exports, "__esModule", {
  76407. value: true
  76408. });
  76409. exports.default = void 0;
  76410. const NULL = (1 << 16) - 1;
  76411. const MAX = (1 << 16) - 1;
  76412. const VarChar = {
  76413. id: 0xA7,
  76414. type: 'BIGVARCHR',
  76415. name: 'VarChar',
  76416. maximumLength: 8000,
  76417. declaration: function declaration(parameter) {
  76418. const value = parameter.value; // Temporary solution. Remove 'any' later.
  76419. let length;
  76420. if (parameter.length) {
  76421. length = parameter.length;
  76422. } else if (value != null) {
  76423. length = value.toString().length || 1;
  76424. } else if (value === null && !parameter.output) {
  76425. length = 1;
  76426. } else {
  76427. length = this.maximumLength;
  76428. }
  76429. if (length <= this.maximumLength) {
  76430. return 'varchar(' + length + ')';
  76431. } else {
  76432. return 'varchar(max)';
  76433. }
  76434. },
  76435. resolveLength: function resolveLength(parameter) {
  76436. const value = parameter.value; // Temporary solution. Remove 'any' later.
  76437. if (parameter.length != null) {
  76438. return parameter.length;
  76439. } else if (value != null) {
  76440. if (Buffer.isBuffer(parameter.value)) {
  76441. return value.length || 1;
  76442. } else {
  76443. return value.toString().length || 1;
  76444. }
  76445. } else {
  76446. return this.maximumLength;
  76447. }
  76448. },
  76449. writeTypeInfo: function writeTypeInfo(buffer, parameter) {
  76450. buffer.writeUInt8(this.id);
  76451. if (parameter.length <= this.maximumLength) {
  76452. buffer.writeUInt16LE(this.maximumLength);
  76453. } else {
  76454. buffer.writeUInt16LE(MAX);
  76455. }
  76456. buffer.writeBuffer(Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00]));
  76457. },
  76458. writeParameterData: function writeParameterData(buffer, parameter, options, cb) {
  76459. if (parameter.value != null) {
  76460. if (parameter.length <= this.maximumLength) {
  76461. buffer.writeUsVarbyte(parameter.value, 'ascii');
  76462. } else {
  76463. buffer.writePLPBody(parameter.value, 'ascii');
  76464. }
  76465. } else if (parameter.length <= this.maximumLength) {
  76466. buffer.writeUInt16LE(NULL);
  76467. } else {
  76468. buffer.writeUInt32LE(0xFFFFFFFF);
  76469. buffer.writeUInt32LE(0xFFFFFFFF);
  76470. }
  76471. cb();
  76472. },
  76473. validate: function validate(value) {
  76474. if (value == null) {
  76475. return null;
  76476. }
  76477. if (typeof value !== 'string') {
  76478. if (typeof value.toString !== 'function') {
  76479. return TypeError('Invalid string.');
  76480. }
  76481. value = value.toString();
  76482. }
  76483. return value;
  76484. }
  76485. };
  76486. var _default = VarChar;
  76487. exports.default = _default;
  76488. module.exports = VarChar;
  76489. }).call(this)}).call(this,require("buffer").Buffer)
  76490. },{"buffer":193}],455:[function(require,module,exports){
  76491. "use strict";
  76492. Object.defineProperty(exports, "__esModule", {
  76493. value: true
  76494. });
  76495. exports.default = void 0;
  76496. const XML = {
  76497. id: 0xF1,
  76498. type: 'XML',
  76499. name: 'Xml',
  76500. declaration() {
  76501. throw new Error('not implemented');
  76502. },
  76503. writeTypeInfo() {
  76504. throw new Error('not implemented');
  76505. },
  76506. writeParameterData() {
  76507. throw new Error('not implemented');
  76508. },
  76509. validate() {
  76510. throw new Error('not implemented');
  76511. }
  76512. };
  76513. var _default = XML;
  76514. exports.default = _default;
  76515. module.exports = XML;
  76516. },{}],456:[function(require,module,exports){
  76517. "use strict";
  76518. Object.defineProperty(exports, "__esModule", {
  76519. value: true
  76520. });
  76521. exports.default = void 0;
  76522. var _events = require("events");
  76523. var util = _interopRequireWildcard(require("util"));
  76524. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  76525. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  76526. class Debug extends _events.EventEmitter {
  76527. /*
  76528. @options Which debug details should be sent.
  76529. data - dump of packet data
  76530. payload - details of decoded payload
  76531. */
  76532. constructor({
  76533. data = false,
  76534. payload = false,
  76535. packet = false,
  76536. token = false
  76537. } = {}) {
  76538. super();
  76539. this.options = void 0;
  76540. this.indent = void 0;
  76541. this.options = {
  76542. data,
  76543. payload,
  76544. packet,
  76545. token
  76546. };
  76547. this.indent = ' ';
  76548. }
  76549. packet(direction, packet) {
  76550. if (this.haveListeners() && this.options.packet) {
  76551. this.log('');
  76552. this.log(direction);
  76553. this.log(packet.headerToString(this.indent));
  76554. }
  76555. }
  76556. data(packet) {
  76557. if (this.haveListeners() && this.options.data) {
  76558. this.log(packet.dataToString(this.indent));
  76559. }
  76560. }
  76561. payload(generatePayloadText) {
  76562. if (this.haveListeners() && this.options.payload) {
  76563. this.log(generatePayloadText());
  76564. }
  76565. }
  76566. token(token) {
  76567. if (this.haveListeners() && this.options.token) {
  76568. this.log(util.inspect(token, {
  76569. showHidden: false,
  76570. depth: 5,
  76571. colors: true
  76572. }));
  76573. }
  76574. }
  76575. haveListeners() {
  76576. return this.listeners('debug').length > 0;
  76577. }
  76578. log(text) {
  76579. this.emit('debug', text);
  76580. }
  76581. }
  76582. var _default = Debug;
  76583. exports.default = _default;
  76584. module.exports = Debug;
  76585. },{"events":247,"util":658}],457:[function(require,module,exports){
  76586. "use strict";
  76587. const util = require('util');
  76588. module.exports.ConnectionError = ConnectionError;
  76589. function ConnectionError(message, code) {
  76590. if (!(this instanceof ConnectionError)) {
  76591. if (message instanceof ConnectionError) {
  76592. return message;
  76593. }
  76594. return new ConnectionError(message, code);
  76595. }
  76596. Error.call(this);
  76597. this.message = message;
  76598. this.code = code;
  76599. Error.captureStackTrace(this, this.constructor);
  76600. }
  76601. util.inherits(ConnectionError, Error);
  76602. ConnectionError.prototype.name = 'ConnectionError';
  76603. module.exports.RequestError = RequestError;
  76604. function RequestError(message, code) {
  76605. if (!(this instanceof RequestError)) {
  76606. if (message instanceof RequestError) {
  76607. return message;
  76608. }
  76609. return new RequestError(message, code);
  76610. }
  76611. Error.call(this);
  76612. this.message = message;
  76613. this.code = code;
  76614. Error.captureStackTrace(this, this.constructor);
  76615. }
  76616. util.inherits(RequestError, Error);
  76617. RequestError.prototype.name = 'RequestError';
  76618. },{"util":658}],458:[function(require,module,exports){
  76619. "use strict";
  76620. Object.defineProperty(exports, "__esModule", {
  76621. value: true
  76622. });
  76623. exports.bufferToUpperCaseGuid = bufferToUpperCaseGuid;
  76624. exports.bufferToLowerCaseGuid = bufferToLowerCaseGuid;
  76625. exports.guidToArray = guidToArray;
  76626. const UPPER_CASE_MAP = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0A', '0B', '0C', '0D', '0E', '0F', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1A', '1B', '1C', '1D', '1E', '1F', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2A', '2B', '2C', '2D', '2E', '2F', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3A', '3B', '3C', '3D', '3E', '3F', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4A', '4B', '4C', '4D', '4E', '4F', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5A', '5B', '5C', '5D', '5E', '5F', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6A', '6B', '6C', '6D', '6E', '6F', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7A', '7B', '7C', '7D', '7E', '7F', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8A', '8B', '8C', '8D', '8E', '8F', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9A', '9B', '9C', '9D', '9E', '9F', 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'E0', 'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'E8', 'E9', 'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'F0', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'FA', 'FB', 'FC', 'FD', 'FE', 'FF'];
  76627. const LOWER_CASE_MAP = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff'];
  76628. function bufferToUpperCaseGuid(buffer) {
  76629. return UPPER_CASE_MAP[buffer[3]] + UPPER_CASE_MAP[buffer[2]] + UPPER_CASE_MAP[buffer[1]] + UPPER_CASE_MAP[buffer[0]] + '-' + UPPER_CASE_MAP[buffer[5]] + UPPER_CASE_MAP[buffer[4]] + '-' + UPPER_CASE_MAP[buffer[7]] + UPPER_CASE_MAP[buffer[6]] + '-' + UPPER_CASE_MAP[buffer[8]] + UPPER_CASE_MAP[buffer[9]] + '-' + UPPER_CASE_MAP[buffer[10]] + UPPER_CASE_MAP[buffer[11]] + UPPER_CASE_MAP[buffer[12]] + UPPER_CASE_MAP[buffer[13]] + UPPER_CASE_MAP[buffer[14]] + UPPER_CASE_MAP[buffer[15]];
  76630. }
  76631. function bufferToLowerCaseGuid(buffer) {
  76632. return LOWER_CASE_MAP[buffer[3]] + LOWER_CASE_MAP[buffer[2]] + LOWER_CASE_MAP[buffer[1]] + LOWER_CASE_MAP[buffer[0]] + '-' + LOWER_CASE_MAP[buffer[5]] + LOWER_CASE_MAP[buffer[4]] + '-' + LOWER_CASE_MAP[buffer[7]] + LOWER_CASE_MAP[buffer[6]] + '-' + LOWER_CASE_MAP[buffer[8]] + LOWER_CASE_MAP[buffer[9]] + '-' + LOWER_CASE_MAP[buffer[10]] + LOWER_CASE_MAP[buffer[11]] + LOWER_CASE_MAP[buffer[12]] + LOWER_CASE_MAP[buffer[13]] + LOWER_CASE_MAP[buffer[14]] + LOWER_CASE_MAP[buffer[15]];
  76633. }
  76634. const CHARCODEMAP = {};
  76635. const hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F'].map(d => d.charCodeAt(0));
  76636. for (let i = 0; i < hexDigits.length; i++) {
  76637. const map = CHARCODEMAP[hexDigits[i]] = {};
  76638. for (let j = 0; j < hexDigits.length; j++) {
  76639. const hex = String.fromCharCode(hexDigits[i], hexDigits[j]);
  76640. const value = parseInt(hex, 16);
  76641. map[hexDigits[j]] = value;
  76642. }
  76643. }
  76644. function guidToArray(guid) {
  76645. return [CHARCODEMAP[guid.charCodeAt(6)][guid.charCodeAt(7)], CHARCODEMAP[guid.charCodeAt(4)][guid.charCodeAt(5)], CHARCODEMAP[guid.charCodeAt(2)][guid.charCodeAt(3)], CHARCODEMAP[guid.charCodeAt(0)][guid.charCodeAt(1)], CHARCODEMAP[guid.charCodeAt(11)][guid.charCodeAt(12)], CHARCODEMAP[guid.charCodeAt(9)][guid.charCodeAt(10)], CHARCODEMAP[guid.charCodeAt(16)][guid.charCodeAt(17)], CHARCODEMAP[guid.charCodeAt(14)][guid.charCodeAt(15)], CHARCODEMAP[guid.charCodeAt(19)][guid.charCodeAt(20)], CHARCODEMAP[guid.charCodeAt(21)][guid.charCodeAt(22)], CHARCODEMAP[guid.charCodeAt(24)][guid.charCodeAt(25)], CHARCODEMAP[guid.charCodeAt(26)][guid.charCodeAt(27)], CHARCODEMAP[guid.charCodeAt(28)][guid.charCodeAt(29)], CHARCODEMAP[guid.charCodeAt(30)][guid.charCodeAt(31)], CHARCODEMAP[guid.charCodeAt(32)][guid.charCodeAt(33)], CHARCODEMAP[guid.charCodeAt(34)][guid.charCodeAt(35)]];
  76646. }
  76647. },{}],459:[function(require,module,exports){
  76648. "use strict";
  76649. Object.defineProperty(exports, "__esModule", {
  76650. value: true
  76651. });
  76652. exports.default = void 0;
  76653. var _bl = _interopRequireDefault(require("bl"));
  76654. var _readableStream = require("readable-stream");
  76655. var _message = _interopRequireDefault(require("./message"));
  76656. var _packet = require("./packet");
  76657. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  76658. /**
  76659. IncomingMessageStream
  76660. Transform received TDS data into individual IncomingMessage streams.
  76661. */
  76662. class IncomingMessageStream extends _readableStream.Transform {
  76663. constructor(debug) {
  76664. super({
  76665. readableObjectMode: true
  76666. });
  76667. this.debug = void 0;
  76668. this.bl = void 0;
  76669. this.currentMessage = void 0;
  76670. this.debug = debug;
  76671. this.currentMessage = undefined;
  76672. this.bl = new _bl.default();
  76673. }
  76674. pause() {
  76675. super.pause();
  76676. if (this.currentMessage) {
  76677. this.currentMessage.pause();
  76678. }
  76679. return this;
  76680. }
  76681. resume() {
  76682. super.resume();
  76683. if (this.currentMessage) {
  76684. this.currentMessage.resume();
  76685. }
  76686. return this;
  76687. }
  76688. processBufferedData(callback) {
  76689. // The packet header is always 8 bytes of length.
  76690. while (this.bl.length >= _packet.HEADER_LENGTH) {
  76691. // Get the full packet length
  76692. const length = this.bl.readUInt16BE(2);
  76693. if (this.bl.length >= length) {
  76694. const data = this.bl.slice(0, length);
  76695. this.bl.consume(length); // TODO: Get rid of creating `Packet` instances here.
  76696. const packet = new _packet.Packet(data);
  76697. this.debug.packet('Received', packet);
  76698. this.debug.data(packet);
  76699. let message = this.currentMessage;
  76700. if (message === undefined) {
  76701. this.currentMessage = message = new _message.default({
  76702. type: packet.type(),
  76703. resetConnection: false
  76704. });
  76705. this.push(message);
  76706. }
  76707. if (packet.isLast()) {
  76708. // Wait until the current message was fully processed before we
  76709. // continue processing any remaining messages.
  76710. message.once('end', () => {
  76711. this.currentMessage = undefined;
  76712. this.processBufferedData(callback);
  76713. });
  76714. message.end(packet.data());
  76715. return;
  76716. } else if (!message.write(packet.data())) {
  76717. // If too much data is buffering up in the
  76718. // current message, wait for it to drain.
  76719. message.once('drain', () => {
  76720. this.processBufferedData(callback);
  76721. });
  76722. return;
  76723. }
  76724. } else {
  76725. break;
  76726. }
  76727. } // Not enough data to read the next packet. Stop here and wait for
  76728. // the next call to `_transform`.
  76729. callback();
  76730. }
  76731. _transform(chunk, _encoding, callback) {
  76732. this.bl.append(chunk);
  76733. this.processBufferedData(callback);
  76734. }
  76735. }
  76736. var _default = IncomingMessageStream;
  76737. exports.default = _default;
  76738. module.exports = IncomingMessageStream;
  76739. },{"./message":464,"./packet":469,"bl":371,"readable-stream":409}],460:[function(require,module,exports){
  76740. (function (Buffer){(function (){
  76741. "use strict";
  76742. Object.defineProperty(exports, "__esModule", {
  76743. value: true
  76744. });
  76745. exports.InstanceLookup = void 0;
  76746. var _sender = require("./sender");
  76747. const SQL_SERVER_BROWSER_PORT = 1434;
  76748. const TIMEOUT = 2 * 1000;
  76749. const RETRIES = 3; // There are three bytes at the start of the response, whose purpose is unknown.
  76750. const MYSTERY_HEADER_LENGTH = 3; // Most of the functionality has been determined from from jTDS's MSSqlServerInfo class.
  76751. class InstanceLookup {
  76752. // Wrapper allows for stubbing Sender when unit testing instance-lookup.
  76753. createSender(host, port, request) {
  76754. return new _sender.Sender(host, port, request);
  76755. }
  76756. instanceLookup(options, callback) {
  76757. const server = options.server;
  76758. if (typeof server !== 'string') {
  76759. throw new TypeError('Invalid arguments: "server" must be a string');
  76760. }
  76761. const instanceName = options.instanceName;
  76762. if (typeof instanceName !== 'string') {
  76763. throw new TypeError('Invalid arguments: "instanceName" must be a string');
  76764. }
  76765. const timeout = options.timeout === undefined ? TIMEOUT : options.timeout;
  76766. if (typeof timeout !== 'number') {
  76767. throw new TypeError('Invalid arguments: "timeout" must be a number');
  76768. }
  76769. const retries = options.retries === undefined ? RETRIES : options.retries;
  76770. if (typeof retries !== 'number') {
  76771. throw new TypeError('Invalid arguments: "retries" must be a number');
  76772. }
  76773. if (typeof callback !== 'function') {
  76774. throw new TypeError('Invalid arguments: "callback" must be a function');
  76775. }
  76776. let sender;
  76777. let timer;
  76778. let retriesLeft = retries;
  76779. const onTimeout = () => {
  76780. sender.cancel();
  76781. makeAttempt();
  76782. };
  76783. const makeAttempt = () => {
  76784. if (retriesLeft > 0) {
  76785. retriesLeft--;
  76786. const request = Buffer.from([0x02]);
  76787. sender = this.createSender(options.server, SQL_SERVER_BROWSER_PORT, request);
  76788. sender.execute((err, response) => {
  76789. clearTimeout(timer);
  76790. if (err) {
  76791. callback('Failed to lookup instance on ' + server + ' - ' + err.message);
  76792. } else {
  76793. const message = response.toString('ascii', MYSTERY_HEADER_LENGTH);
  76794. const port = this.parseBrowserResponse(message, instanceName);
  76795. if (port) {
  76796. callback(undefined, port);
  76797. } else {
  76798. callback('Port for ' + instanceName + ' not found in ' + options.server);
  76799. }
  76800. }
  76801. });
  76802. timer = setTimeout(onTimeout, timeout);
  76803. } else {
  76804. callback('Failed to get response from SQL Server Browser on ' + server);
  76805. }
  76806. };
  76807. makeAttempt();
  76808. }
  76809. parseBrowserResponse(response, instanceName) {
  76810. let getPort;
  76811. const instances = response.split(';;');
  76812. for (let i = 0, len = instances.length; i < len; i++) {
  76813. const instance = instances[i];
  76814. const parts = instance.split(';');
  76815. for (let p = 0, partsLen = parts.length; p < partsLen; p += 2) {
  76816. const name = parts[p];
  76817. const value = parts[p + 1];
  76818. if (name === 'tcp' && getPort) {
  76819. const port = parseInt(value, 10);
  76820. return port;
  76821. }
  76822. if (name === 'InstanceName') {
  76823. if (value.toUpperCase() === instanceName.toUpperCase()) {
  76824. getPort = true;
  76825. } else {
  76826. getPort = false;
  76827. }
  76828. }
  76829. }
  76830. }
  76831. }
  76832. }
  76833. exports.InstanceLookup = InstanceLookup;
  76834. }).call(this)}).call(this,require("buffer").Buffer)
  76835. },{"./sender":473,"buffer":193}],461:[function(require,module,exports){
  76836. "use strict";
  76837. Object.defineProperty(exports, "__esModule", {
  76838. value: true
  76839. });
  76840. exports.name = void 0;
  76841. const name = 'Tedious';
  76842. exports.name = name;
  76843. },{}],462:[function(require,module,exports){
  76844. (function (Buffer){(function (){
  76845. "use strict";
  76846. Object.defineProperty(exports, "__esModule", {
  76847. value: true
  76848. });
  76849. exports.default = void 0;
  76850. var _sprintfJs = require("sprintf-js");
  76851. const FLAGS_1 = {
  76852. ENDIAN_LITTLE: 0x00,
  76853. ENDIAN_BIG: 0x01,
  76854. CHARSET_ASCII: 0x00,
  76855. CHARSET_EBCDIC: 0x02,
  76856. FLOAT_IEEE_754: 0x00,
  76857. FLOAT_VAX: 0x04,
  76858. FLOAT_ND5000: 0x08,
  76859. BCP_DUMPLOAD_ON: 0x00,
  76860. BCP_DUMPLOAD_OFF: 0x10,
  76861. USE_DB_ON: 0x00,
  76862. USE_DB_OFF: 0x20,
  76863. INIT_DB_WARN: 0x00,
  76864. INIT_DB_FATAL: 0x40,
  76865. SET_LANG_WARN_OFF: 0x00,
  76866. SET_LANG_WARN_ON: 0x80
  76867. };
  76868. const FLAGS_2 = {
  76869. INIT_LANG_WARN: 0x00,
  76870. INIT_LANG_FATAL: 0x01,
  76871. ODBC_OFF: 0x00,
  76872. ODBC_ON: 0x02,
  76873. F_TRAN_BOUNDARY: 0x04,
  76874. F_CACHE_CONNECT: 0x08,
  76875. USER_NORMAL: 0x00,
  76876. USER_SERVER: 0x10,
  76877. USER_REMUSER: 0x20,
  76878. USER_SQLREPL: 0x40,
  76879. INTEGRATED_SECURITY_OFF: 0x00,
  76880. INTEGRATED_SECURITY_ON: 0x80
  76881. };
  76882. const TYPE_FLAGS = {
  76883. SQL_DFLT: 0x00,
  76884. SQL_TSQL: 0x08,
  76885. OLEDB_OFF: 0x00,
  76886. OLEDB_ON: 0x10,
  76887. READ_WRITE_INTENT: 0x00,
  76888. READ_ONLY_INTENT: 0x20
  76889. };
  76890. const FLAGS_3 = {
  76891. CHANGE_PASSWORD_NO: 0x00,
  76892. CHANGE_PASSWORD_YES: 0x01,
  76893. BINARY_XML: 0x02,
  76894. SPAWN_USER_INSTANCE: 0x04,
  76895. UNKNOWN_COLLATION_HANDLING: 0x08,
  76896. EXTENSION_USED: 0x10
  76897. };
  76898. const FEDAUTH_OPTIONS = {
  76899. FEATURE_ID: 0x02,
  76900. LIBRARY_SECURITYTOKEN: 0x01,
  76901. LIBRARY_ADAL: 0x02,
  76902. FEDAUTH_YES_ECHO: 0x01,
  76903. FEDAUTH_NO_ECHO: 0x00,
  76904. ADAL_WORKFLOW_USER_PASS: 0x01,
  76905. ADAL_WORKFLOW_INTEGRATED: 0x02
  76906. };
  76907. const FEATURE_EXT_TERMINATOR = 0xFF;
  76908. /*
  76909. s2.2.6.3
  76910. */
  76911. class Login7Payload {
  76912. constructor({
  76913. tdsVersion,
  76914. packetSize,
  76915. clientProgVer,
  76916. clientPid,
  76917. connectionId,
  76918. clientTimeZone,
  76919. clientLcid
  76920. }) {
  76921. this.tdsVersion = void 0;
  76922. this.packetSize = void 0;
  76923. this.clientProgVer = void 0;
  76924. this.clientPid = void 0;
  76925. this.connectionId = void 0;
  76926. this.clientTimeZone = void 0;
  76927. this.clientLcid = void 0;
  76928. this.readOnlyIntent = void 0;
  76929. this.initDbFatal = void 0;
  76930. this.userName = void 0;
  76931. this.password = void 0;
  76932. this.serverName = void 0;
  76933. this.appName = void 0;
  76934. this.hostname = void 0;
  76935. this.libraryName = void 0;
  76936. this.language = void 0;
  76937. this.database = void 0;
  76938. this.clientId = void 0;
  76939. this.sspi = void 0;
  76940. this.attachDbFile = void 0;
  76941. this.changePassword = void 0;
  76942. this.fedAuth = void 0;
  76943. this.tdsVersion = tdsVersion;
  76944. this.packetSize = packetSize;
  76945. this.clientProgVer = clientProgVer;
  76946. this.clientPid = clientPid;
  76947. this.connectionId = connectionId;
  76948. this.clientTimeZone = clientTimeZone;
  76949. this.clientLcid = clientLcid;
  76950. this.readOnlyIntent = false;
  76951. this.initDbFatal = false;
  76952. this.fedAuth = undefined;
  76953. this.userName = undefined;
  76954. this.password = undefined;
  76955. this.serverName = undefined;
  76956. this.appName = undefined;
  76957. this.hostname = undefined;
  76958. this.libraryName = undefined;
  76959. this.language = undefined;
  76960. this.database = undefined;
  76961. this.clientId = undefined;
  76962. this.sspi = undefined;
  76963. this.attachDbFile = undefined;
  76964. this.changePassword = undefined;
  76965. }
  76966. toBuffer() {
  76967. const fixedData = Buffer.alloc(94);
  76968. const buffers = [fixedData];
  76969. let offset = 0;
  76970. let dataOffset = fixedData.length; // Length: 4-byte
  76971. offset = fixedData.writeUInt32LE(0, offset); // TDSVersion: 4-byte
  76972. offset = fixedData.writeUInt32LE(this.tdsVersion, offset); // PacketSize: 4-byte
  76973. offset = fixedData.writeUInt32LE(this.packetSize, offset); // ClientProgVer: 4-byte
  76974. offset = fixedData.writeUInt32LE(this.clientProgVer, offset); // ClientPID: 4-byte
  76975. offset = fixedData.writeUInt32LE(this.clientPid, offset); // ConnectionID: 4-byte
  76976. offset = fixedData.writeUInt32LE(this.connectionId, offset); // OptionFlags1: 1-byte
  76977. offset = fixedData.writeUInt8(this.buildOptionFlags1(), offset); // OptionFlags2: 1-byte
  76978. offset = fixedData.writeUInt8(this.buildOptionFlags2(), offset); // TypeFlags: 1-byte
  76979. offset = fixedData.writeUInt8(this.buildTypeFlags(), offset); // OptionFlags3: 1-byte
  76980. offset = fixedData.writeUInt8(this.buildOptionFlags3(), offset); // ClientTimZone: 4-byte
  76981. offset = fixedData.writeInt32LE(this.clientTimeZone, offset); // ClientLCID: 4-byte
  76982. offset = fixedData.writeUInt32LE(this.clientLcid, offset); // ibHostName: 2-byte
  76983. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchHostName: 2-byte
  76984. if (this.hostname) {
  76985. const buffer = Buffer.from(this.hostname, 'ucs2');
  76986. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  76987. dataOffset += buffer.length;
  76988. buffers.push(buffer);
  76989. } else {
  76990. offset = fixedData.writeUInt16LE(dataOffset, offset);
  76991. } // ibUserName: 2-byte
  76992. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchUserName: 2-byte
  76993. if (this.userName) {
  76994. const buffer = Buffer.from(this.userName, 'ucs2');
  76995. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  76996. dataOffset += buffer.length;
  76997. buffers.push(buffer);
  76998. } else {
  76999. offset = fixedData.writeUInt16LE(0, offset);
  77000. } // ibPassword: 2-byte
  77001. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchPassword: 2-byte
  77002. if (this.password) {
  77003. const buffer = Buffer.from(this.password, 'ucs2');
  77004. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77005. dataOffset += buffer.length;
  77006. buffers.push(this.scramblePassword(buffer));
  77007. } else {
  77008. offset = fixedData.writeUInt16LE(0, offset);
  77009. } // ibAppName: 2-byte
  77010. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchAppName: 2-byte
  77011. if (this.appName) {
  77012. const buffer = Buffer.from(this.appName, 'ucs2');
  77013. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77014. dataOffset += buffer.length;
  77015. buffers.push(buffer);
  77016. } else {
  77017. offset = fixedData.writeUInt16LE(0, offset);
  77018. } // ibServerName: 2-byte
  77019. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchServerName: 2-byte
  77020. if (this.serverName) {
  77021. const buffer = Buffer.from(this.serverName, 'ucs2');
  77022. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77023. dataOffset += buffer.length;
  77024. buffers.push(buffer);
  77025. } else {
  77026. offset = fixedData.writeUInt16LE(0, offset);
  77027. } // (ibUnused / ibExtension): 2-byte
  77028. offset = fixedData.writeUInt16LE(dataOffset, offset); // (cchUnused / cbExtension): 2-byte
  77029. const extensions = this.buildFeatureExt();
  77030. offset = fixedData.writeUInt16LE(4, offset);
  77031. const extensionOffset = Buffer.alloc(4);
  77032. extensionOffset.writeUInt32LE(dataOffset += 4, 0);
  77033. dataOffset += extensions.length;
  77034. buffers.push(extensionOffset, extensions); // ibCltIntName: 2-byte
  77035. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchCltIntName: 2-byte
  77036. if (this.libraryName) {
  77037. const buffer = Buffer.from(this.libraryName, 'ucs2');
  77038. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77039. dataOffset += buffer.length;
  77040. buffers.push(buffer);
  77041. } else {
  77042. offset = fixedData.writeUInt16LE(0, offset);
  77043. } // ibLanguage: 2-byte
  77044. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchLanguage: 2-byte
  77045. if (this.language) {
  77046. const buffer = Buffer.from(this.language, 'ucs2');
  77047. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77048. dataOffset += buffer.length;
  77049. buffers.push(buffer);
  77050. } else {
  77051. offset = fixedData.writeUInt16LE(0, offset);
  77052. } // ibDatabase: 2-byte
  77053. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchDatabase: 2-byte
  77054. if (this.database) {
  77055. const buffer = Buffer.from(this.database, 'ucs2');
  77056. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77057. dataOffset += buffer.length;
  77058. buffers.push(buffer);
  77059. } else {
  77060. offset = fixedData.writeUInt16LE(0, offset);
  77061. } // ClientID: 6-byte
  77062. if (this.clientId) {
  77063. this.clientId.copy(fixedData, offset, 0, 6);
  77064. }
  77065. offset += 6; // ibSSPI: 2-byte
  77066. offset = fixedData.writeUInt16LE(dataOffset, offset); // cbSSPI: 2-byte
  77067. if (this.sspi) {
  77068. if (this.sspi.length > 65535) {
  77069. offset = fixedData.writeUInt16LE(65535, offset);
  77070. } else {
  77071. offset = fixedData.writeUInt16LE(this.sspi.length, offset);
  77072. }
  77073. buffers.push(this.sspi);
  77074. } else {
  77075. offset = fixedData.writeUInt16LE(0, offset);
  77076. } // ibAtchDBFile: 2-byte
  77077. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchAtchDBFile: 2-byte
  77078. if (this.attachDbFile) {
  77079. const buffer = Buffer.from(this.attachDbFile, 'ucs2');
  77080. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77081. dataOffset += buffer.length;
  77082. buffers.push(buffer);
  77083. } else {
  77084. offset = fixedData.writeUInt16LE(0, offset);
  77085. } // ibChangePassword: 2-byte
  77086. offset = fixedData.writeUInt16LE(dataOffset, offset); // cchChangePassword: 2-byte
  77087. if (this.changePassword) {
  77088. const buffer = Buffer.from(this.changePassword, 'ucs2');
  77089. offset = fixedData.writeUInt16LE(buffer.length / 2, offset);
  77090. dataOffset += buffer.length;
  77091. buffers.push(buffer);
  77092. } else {
  77093. offset = fixedData.writeUInt16LE(0, offset);
  77094. } // cbSSPILong: 4-byte
  77095. if (this.sspi && this.sspi.length > 65535) {
  77096. fixedData.writeUInt32LE(this.sspi.length, offset);
  77097. } else {
  77098. fixedData.writeUInt32LE(0, offset);
  77099. }
  77100. const data = Buffer.concat(buffers);
  77101. data.writeUInt32LE(data.length, 0);
  77102. return data;
  77103. }
  77104. buildOptionFlags1() {
  77105. let flags1 = FLAGS_1.ENDIAN_LITTLE | FLAGS_1.CHARSET_ASCII | FLAGS_1.FLOAT_IEEE_754 | FLAGS_1.BCP_DUMPLOAD_OFF | FLAGS_1.USE_DB_OFF | FLAGS_1.SET_LANG_WARN_ON;
  77106. if (this.initDbFatal) {
  77107. flags1 |= FLAGS_1.INIT_DB_FATAL;
  77108. } else {
  77109. flags1 |= FLAGS_1.INIT_DB_WARN;
  77110. }
  77111. return flags1;
  77112. }
  77113. buildFeatureExt() {
  77114. const buffers = [];
  77115. const fedAuth = this.fedAuth;
  77116. if (fedAuth) {
  77117. switch (fedAuth.type) {
  77118. case 'ADAL':
  77119. const buffer = Buffer.alloc(7);
  77120. buffer.writeUInt8(FEDAUTH_OPTIONS.FEATURE_ID, 0);
  77121. buffer.writeUInt32LE(2, 1);
  77122. buffer.writeUInt8(FEDAUTH_OPTIONS.LIBRARY_ADAL << 1 | (fedAuth.echo ? FEDAUTH_OPTIONS.FEDAUTH_YES_ECHO : FEDAUTH_OPTIONS.FEDAUTH_NO_ECHO), 5);
  77123. buffer.writeUInt8(fedAuth.workflow === 'integrated' ? 0x02 : FEDAUTH_OPTIONS.ADAL_WORKFLOW_USER_PASS, 6);
  77124. buffers.push(buffer);
  77125. break;
  77126. case 'SECURITYTOKEN':
  77127. const token = Buffer.from(fedAuth.fedAuthToken, 'ucs2');
  77128. const buf = Buffer.alloc(10);
  77129. let offset = 0;
  77130. offset = buf.writeUInt8(FEDAUTH_OPTIONS.FEATURE_ID, offset);
  77131. offset = buf.writeUInt32LE(token.length + 4 + 1, offset);
  77132. offset = buf.writeUInt8(FEDAUTH_OPTIONS.LIBRARY_SECURITYTOKEN << 1 | (fedAuth.echo ? FEDAUTH_OPTIONS.FEDAUTH_YES_ECHO : FEDAUTH_OPTIONS.FEDAUTH_NO_ECHO), offset);
  77133. buf.writeInt32LE(token.length, offset);
  77134. buffers.push(buf);
  77135. buffers.push(token);
  77136. break;
  77137. }
  77138. }
  77139. buffers.push(Buffer.from([FEATURE_EXT_TERMINATOR]));
  77140. return Buffer.concat(buffers);
  77141. }
  77142. buildOptionFlags2() {
  77143. let flags2 = FLAGS_2.INIT_LANG_WARN | FLAGS_2.ODBC_OFF | FLAGS_2.USER_NORMAL;
  77144. if (this.sspi) {
  77145. flags2 |= FLAGS_2.INTEGRATED_SECURITY_ON;
  77146. } else {
  77147. flags2 |= FLAGS_2.INTEGRATED_SECURITY_OFF;
  77148. }
  77149. return flags2;
  77150. }
  77151. buildTypeFlags() {
  77152. let typeFlags = TYPE_FLAGS.SQL_DFLT | TYPE_FLAGS.OLEDB_OFF;
  77153. if (this.readOnlyIntent) {
  77154. typeFlags |= TYPE_FLAGS.READ_ONLY_INTENT;
  77155. } else {
  77156. typeFlags |= TYPE_FLAGS.READ_WRITE_INTENT;
  77157. }
  77158. return typeFlags;
  77159. }
  77160. buildOptionFlags3() {
  77161. return FLAGS_3.CHANGE_PASSWORD_NO | FLAGS_3.UNKNOWN_COLLATION_HANDLING | FLAGS_3.EXTENSION_USED;
  77162. }
  77163. scramblePassword(password) {
  77164. for (let b = 0, len = password.length; b < len; b++) {
  77165. let byte = password[b];
  77166. const lowNibble = byte & 0x0f;
  77167. const highNibble = byte >> 4;
  77168. byte = lowNibble << 4 | highNibble;
  77169. byte = byte ^ 0xa5;
  77170. password[b] = byte;
  77171. }
  77172. return password;
  77173. }
  77174. toString(indent = '') {
  77175. return indent + 'Login7 - ' + (0, _sprintfJs.sprintf)('TDS:0x%08X, PacketSize:0x%08X, ClientProgVer:0x%08X, ClientPID:0x%08X, ConnectionID:0x%08X', this.tdsVersion, this.packetSize, this.clientProgVer, this.clientPid, this.connectionId) + '\n' + indent + ' ' + (0, _sprintfJs.sprintf)('Flags1:0x%02X, Flags2:0x%02X, TypeFlags:0x%02X, Flags3:0x%02X, ClientTimezone:%d, ClientLCID:0x%08X', this.buildOptionFlags1(), this.buildOptionFlags2(), this.buildTypeFlags(), this.buildOptionFlags3(), this.clientTimeZone, this.clientLcid) + '\n' + indent + ' ' + (0, _sprintfJs.sprintf)("Hostname:'%s', Username:'%s', Password:'%s', AppName:'%s', ServerName:'%s', LibraryName:'%s'", this.hostname, this.userName, this.password, this.appName, this.serverName, this.libraryName) + '\n' + indent + ' ' + (0, _sprintfJs.sprintf)("Language:'%s', Database:'%s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'%s'", this.language, this.database, this.sspi, this.attachDbFile, this.changePassword);
  77176. }
  77177. }
  77178. var _default = Login7Payload;
  77179. exports.default = _default;
  77180. module.exports = Login7Payload;
  77181. }).call(this)}).call(this,require("buffer").Buffer)
  77182. },{"buffer":193,"sprintf-js":410}],463:[function(require,module,exports){
  77183. "use strict";
  77184. Object.defineProperty(exports, "__esModule", {
  77185. value: true
  77186. });
  77187. exports.default = void 0;
  77188. var tls = _interopRequireWildcard(require("tls"));
  77189. var _events = require("events");
  77190. var _message = _interopRequireDefault(require("./message"));
  77191. var _packet = require("./packet");
  77192. var _incomingMessageStream = _interopRequireDefault(require("./incoming-message-stream"));
  77193. var _outgoingMessageStream = _interopRequireDefault(require("./outgoing-message-stream"));
  77194. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  77195. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  77196. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  77197. const DuplexPair = require('native-duplexpair');
  77198. class MessageIO extends _events.EventEmitter {
  77199. constructor(socket, packetSize, debug) {
  77200. super();
  77201. this.socket = void 0;
  77202. this.debug = void 0;
  77203. this.tlsNegotiationComplete = void 0;
  77204. this.incomingMessageStream = void 0;
  77205. this.outgoingMessageStream = void 0;
  77206. this.securePair = void 0;
  77207. this.socket = socket;
  77208. this.debug = debug;
  77209. this.tlsNegotiationComplete = false;
  77210. this.incomingMessageStream = new _incomingMessageStream.default(this.debug);
  77211. this.incomingMessageStream.on('data', message => {
  77212. message.on('data', chunk => {
  77213. this.emit('data', chunk);
  77214. });
  77215. message.on('end', () => {
  77216. this.emit('message');
  77217. });
  77218. });
  77219. this.outgoingMessageStream = new _outgoingMessageStream.default(this.debug, {
  77220. packetSize: packetSize
  77221. });
  77222. this.socket.pipe(this.incomingMessageStream);
  77223. this.outgoingMessageStream.pipe(this.socket);
  77224. }
  77225. packetSize(...args) {
  77226. if (args.length > 0) {
  77227. const packetSize = args[0];
  77228. this.debug.log('Packet size changed from ' + this.outgoingMessageStream.packetSize + ' to ' + packetSize);
  77229. this.outgoingMessageStream.packetSize = packetSize;
  77230. }
  77231. if (this.securePair) {
  77232. this.securePair.cleartext.setMaxSendFragment(this.outgoingMessageStream.packetSize);
  77233. }
  77234. return this.outgoingMessageStream.packetSize;
  77235. }
  77236. startTls(secureContext, hostname, trustServerCertificate) {
  77237. const duplexpair = new DuplexPair();
  77238. const securePair = this.securePair = {
  77239. cleartext: tls.connect({
  77240. socket: duplexpair.socket1,
  77241. servername: hostname,
  77242. secureContext: secureContext,
  77243. rejectUnauthorized: !trustServerCertificate
  77244. }),
  77245. encrypted: duplexpair.socket2
  77246. }; // If an error happens in the TLS layer, there is nothing we can do about it.
  77247. // Forward the error to the socket so the connection gets properly cleaned up.
  77248. securePair.cleartext.on('error', err => {
  77249. // Streams in node.js versions before 8.0.0 don't support `.destroy`
  77250. if (typeof securePair.encrypted.destroy === 'function') {
  77251. securePair.encrypted.destroy();
  77252. }
  77253. this.socket.destroy(err);
  77254. });
  77255. securePair.cleartext.on('secureConnect', () => {
  77256. const cipher = securePair.cleartext.getCipher();
  77257. if (cipher) {
  77258. this.debug.log('TLS negotiated (' + cipher.name + ', ' + cipher.version + ')');
  77259. }
  77260. this.emit('secure', securePair.cleartext);
  77261. this.encryptAllFutureTraffic();
  77262. });
  77263. securePair.encrypted.on('data', data => {
  77264. this.sendMessage(_packet.TYPE.PRELOGIN, data, false);
  77265. });
  77266. }
  77267. encryptAllFutureTraffic() {
  77268. const securePair = this.securePair;
  77269. securePair.cleartext.setMaxSendFragment(this.outgoingMessageStream.packetSize);
  77270. securePair.encrypted.removeAllListeners('data');
  77271. this.outgoingMessageStream.unpipe(this.socket);
  77272. this.socket.unpipe(this.incomingMessageStream);
  77273. this.socket.pipe(securePair.encrypted);
  77274. securePair.encrypted.pipe(this.socket);
  77275. securePair.cleartext.pipe(this.incomingMessageStream);
  77276. this.outgoingMessageStream.pipe(securePair.cleartext);
  77277. this.tlsNegotiationComplete = true;
  77278. }
  77279. tlsHandshakeData(data) {
  77280. const securePair = this.securePair;
  77281. securePair.encrypted.write(data);
  77282. } // TODO listen for 'drain' event when socket.write returns false.
  77283. // TODO implement incomplete request cancelation (2.2.1.6)
  77284. sendMessage(packetType, data, resetConnection) {
  77285. const message = new _message.default({
  77286. type: packetType,
  77287. resetConnection: resetConnection
  77288. });
  77289. message.end(data);
  77290. this.outgoingMessageStream.write(message);
  77291. return message;
  77292. } // Temporarily suspends the flow of incoming packets.
  77293. pause() {
  77294. this.incomingMessageStream.pause();
  77295. } // Resumes the flow of incoming packets.
  77296. resume() {
  77297. this.incomingMessageStream.resume();
  77298. }
  77299. }
  77300. var _default = MessageIO;
  77301. exports.default = _default;
  77302. module.exports = MessageIO;
  77303. },{"./incoming-message-stream":459,"./message":464,"./outgoing-message-stream":468,"./packet":469,"events":247,"native-duplexpair":497,"tls":190}],464:[function(require,module,exports){
  77304. "use strict";
  77305. Object.defineProperty(exports, "__esModule", {
  77306. value: true
  77307. });
  77308. exports.default = void 0;
  77309. var _readableStream = require("readable-stream");
  77310. class Message extends _readableStream.PassThrough {
  77311. constructor({
  77312. type,
  77313. resetConnection = false
  77314. }) {
  77315. super();
  77316. this.type = void 0;
  77317. this.resetConnection = void 0;
  77318. this.ignore = void 0;
  77319. this.type = type;
  77320. this.resetConnection = resetConnection;
  77321. this.ignore = false;
  77322. }
  77323. }
  77324. var _default = Message;
  77325. exports.default = _default;
  77326. module.exports = Message;
  77327. },{"readable-stream":409}],465:[function(require,module,exports){
  77328. "use strict";
  77329. Object.defineProperty(exports, "__esModule", {
  77330. value: true
  77331. });
  77332. exports.readCollation = readCollation;
  77333. exports.default = void 0;
  77334. var _collation = require("./collation");
  77335. var _dataType = require("./data-type");
  77336. var _sprintfJs = require("sprintf-js");
  77337. function readCollation(parser, callback) {
  77338. // s2.2.5.1.2
  77339. parser.readBuffer(5, collationData => {
  77340. let lcid = (collationData[2] & 0x0F) << 16;
  77341. lcid |= collationData[1] << 8;
  77342. lcid |= collationData[0]; // This may not be extracting the correct nibbles in the correct order.
  77343. let flags = collationData[3] >> 4;
  77344. flags |= collationData[2] & 0xF0; // This may not be extracting the correct nibble.
  77345. const version = collationData[3] & 0x0F;
  77346. const sortId = collationData[4];
  77347. const codepage = _collation.codepageBySortId[sortId] || _collation.codepageByLcid[lcid] || 'CP1252';
  77348. callback({
  77349. lcid,
  77350. flags,
  77351. version,
  77352. sortId,
  77353. codepage
  77354. });
  77355. });
  77356. }
  77357. function readSchema(parser, callback) {
  77358. // s2.2.5.5.3
  77359. parser.readUInt8(schemaPresent => {
  77360. if (schemaPresent === 0x01) {
  77361. parser.readBVarChar(dbname => {
  77362. parser.readBVarChar(owningSchema => {
  77363. parser.readUsVarChar(xmlSchemaCollection => {
  77364. callback({
  77365. dbname: dbname,
  77366. owningSchema: owningSchema,
  77367. xmlSchemaCollection: xmlSchemaCollection
  77368. });
  77369. });
  77370. });
  77371. });
  77372. } else {
  77373. callback(undefined);
  77374. }
  77375. });
  77376. }
  77377. function readUDTInfo(parser, callback) {
  77378. parser.readUInt16LE(maxByteSize => {
  77379. parser.readBVarChar(dbname => {
  77380. parser.readBVarChar(owningSchema => {
  77381. parser.readBVarChar(typeName => {
  77382. parser.readUsVarChar(assemblyName => {
  77383. callback({
  77384. maxByteSize: maxByteSize,
  77385. dbname: dbname,
  77386. owningSchema: owningSchema,
  77387. typeName: typeName,
  77388. assemblyName: assemblyName
  77389. });
  77390. });
  77391. });
  77392. });
  77393. });
  77394. });
  77395. }
  77396. function metadataParse(parser, options, callback) {
  77397. (options.tdsVersion < '7_2' ? parser.readUInt16LE : parser.readUInt32LE).call(parser, userType => {
  77398. parser.readUInt16LE(flags => {
  77399. parser.readUInt8(typeNumber => {
  77400. const type = _dataType.TYPE[typeNumber];
  77401. if (!type) {
  77402. return parser.emit('error', new Error((0, _sprintfJs.sprintf)('Unrecognised data type 0x%02X', typeNumber)));
  77403. }
  77404. switch (type.name) {
  77405. case 'Null':
  77406. case 'TinyInt':
  77407. case 'SmallInt':
  77408. case 'Int':
  77409. case 'BigInt':
  77410. case 'Real':
  77411. case 'Float':
  77412. case 'SmallMoney':
  77413. case 'Money':
  77414. case 'Bit':
  77415. case 'SmallDateTime':
  77416. case 'DateTime':
  77417. case 'Date':
  77418. return callback({
  77419. userType: userType,
  77420. flags: flags,
  77421. type: type,
  77422. collation: undefined,
  77423. precision: undefined,
  77424. scale: undefined,
  77425. dataLength: undefined,
  77426. schema: undefined,
  77427. udtInfo: undefined
  77428. });
  77429. case 'IntN':
  77430. case 'FloatN':
  77431. case 'MoneyN':
  77432. case 'BitN':
  77433. case 'UniqueIdentifier':
  77434. case 'DateTimeN':
  77435. return parser.readUInt8(dataLength => {
  77436. callback({
  77437. userType: userType,
  77438. flags: flags,
  77439. type: type,
  77440. collation: undefined,
  77441. precision: undefined,
  77442. scale: undefined,
  77443. dataLength: dataLength,
  77444. schema: undefined,
  77445. udtInfo: undefined
  77446. });
  77447. });
  77448. case 'Variant':
  77449. return parser.readUInt32LE(dataLength => {
  77450. callback({
  77451. userType: userType,
  77452. flags: flags,
  77453. type: type,
  77454. collation: undefined,
  77455. precision: undefined,
  77456. scale: undefined,
  77457. dataLength: dataLength,
  77458. schema: undefined,
  77459. udtInfo: undefined
  77460. });
  77461. });
  77462. case 'VarChar':
  77463. case 'Char':
  77464. case 'NVarChar':
  77465. case 'NChar':
  77466. return parser.readUInt16LE(dataLength => {
  77467. readCollation(parser, collation => {
  77468. callback({
  77469. userType: userType,
  77470. flags: flags,
  77471. type: type,
  77472. collation: collation,
  77473. precision: undefined,
  77474. scale: undefined,
  77475. dataLength: dataLength,
  77476. schema: undefined,
  77477. udtInfo: undefined
  77478. });
  77479. });
  77480. });
  77481. case 'Text':
  77482. case 'NText':
  77483. return parser.readUInt32LE(dataLength => {
  77484. readCollation(parser, collation => {
  77485. callback({
  77486. userType: userType,
  77487. flags: flags,
  77488. type: type,
  77489. collation: collation,
  77490. precision: undefined,
  77491. scale: undefined,
  77492. dataLength: dataLength,
  77493. schema: undefined,
  77494. udtInfo: undefined
  77495. });
  77496. });
  77497. });
  77498. case 'VarBinary':
  77499. case 'Binary':
  77500. return parser.readUInt16LE(dataLength => {
  77501. callback({
  77502. userType: userType,
  77503. flags: flags,
  77504. type: type,
  77505. collation: undefined,
  77506. precision: undefined,
  77507. scale: undefined,
  77508. dataLength: dataLength,
  77509. schema: undefined,
  77510. udtInfo: undefined
  77511. });
  77512. });
  77513. case 'Image':
  77514. return parser.readUInt32LE(dataLength => {
  77515. callback({
  77516. userType: userType,
  77517. flags: flags,
  77518. type: type,
  77519. collation: undefined,
  77520. precision: undefined,
  77521. scale: undefined,
  77522. dataLength: dataLength,
  77523. schema: undefined,
  77524. udtInfo: undefined
  77525. });
  77526. });
  77527. case 'Xml':
  77528. return readSchema(parser, schema => {
  77529. callback({
  77530. userType: userType,
  77531. flags: flags,
  77532. type: type,
  77533. collation: undefined,
  77534. precision: undefined,
  77535. scale: undefined,
  77536. dataLength: undefined,
  77537. schema: schema,
  77538. udtInfo: undefined
  77539. });
  77540. });
  77541. case 'Time':
  77542. case 'DateTime2':
  77543. case 'DateTimeOffset':
  77544. return parser.readUInt8(scale => {
  77545. callback({
  77546. userType: userType,
  77547. flags: flags,
  77548. type: type,
  77549. collation: undefined,
  77550. precision: undefined,
  77551. scale: scale,
  77552. dataLength: undefined,
  77553. schema: undefined,
  77554. udtInfo: undefined
  77555. });
  77556. });
  77557. case 'NumericN':
  77558. case 'DecimalN':
  77559. return parser.readUInt8(dataLength => {
  77560. parser.readUInt8(precision => {
  77561. parser.readUInt8(scale => {
  77562. callback({
  77563. userType: userType,
  77564. flags: flags,
  77565. type: type,
  77566. collation: undefined,
  77567. precision: precision,
  77568. scale: scale,
  77569. dataLength: dataLength,
  77570. schema: undefined,
  77571. udtInfo: undefined
  77572. });
  77573. });
  77574. });
  77575. });
  77576. case 'UDT':
  77577. return readUDTInfo(parser, udtInfo => {
  77578. callback({
  77579. userType: userType,
  77580. flags: flags,
  77581. type: type,
  77582. collation: undefined,
  77583. precision: undefined,
  77584. scale: undefined,
  77585. dataLength: undefined,
  77586. schema: undefined,
  77587. udtInfo: udtInfo
  77588. });
  77589. });
  77590. default:
  77591. return parser.emit('error', new Error((0, _sprintfJs.sprintf)('Unrecognised type %s', type.name)));
  77592. }
  77593. });
  77594. });
  77595. });
  77596. }
  77597. var _default = metadataParse;
  77598. exports.default = _default;
  77599. module.exports = metadataParse;
  77600. module.exports.readCollation = readCollation;
  77601. },{"./collation":413,"./data-type":416,"sprintf-js":410}],466:[function(require,module,exports){
  77602. (function (Buffer){(function (){
  77603. "use strict";
  77604. Object.defineProperty(exports, "__esModule", {
  77605. value: true
  77606. });
  77607. exports.default = void 0;
  77608. var _writableTrackingBuffer = _interopRequireDefault(require("./tracking-buffer/writable-tracking-buffer"));
  77609. var crypto = _interopRequireWildcard(require("crypto"));
  77610. var _jsbi = _interopRequireDefault(require("jsbi"));
  77611. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  77612. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  77613. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  77614. class NTLMResponsePayload {
  77615. constructor(loginData) {
  77616. this.data = void 0;
  77617. this.data = this.createResponse(loginData);
  77618. }
  77619. toString(indent = '') {
  77620. return indent + 'NTLM Auth';
  77621. }
  77622. createResponse(challenge) {
  77623. const client_nonce = this.createClientNonce();
  77624. const lmv2len = 24;
  77625. const ntlmv2len = 16;
  77626. const domain = challenge.domain;
  77627. const username = challenge.userName;
  77628. const password = challenge.password;
  77629. const ntlmData = challenge.ntlmpacket;
  77630. const server_data = ntlmData.target;
  77631. const server_nonce = ntlmData.nonce;
  77632. const bufferLength = 64 + domain.length * 2 + username.length * 2 + lmv2len + ntlmv2len + 8 + 8 + 8 + 4 + server_data.length + 4;
  77633. const data = new _writableTrackingBuffer.default(bufferLength);
  77634. data.position = 0;
  77635. data.writeString('NTLMSSP\u0000', 'utf8');
  77636. data.writeUInt32LE(0x03);
  77637. const baseIdx = 64;
  77638. const dnIdx = baseIdx;
  77639. const unIdx = dnIdx + domain.length * 2;
  77640. const l2Idx = unIdx + username.length * 2;
  77641. const ntIdx = l2Idx + lmv2len;
  77642. data.writeUInt16LE(lmv2len);
  77643. data.writeUInt16LE(lmv2len);
  77644. data.writeUInt32LE(l2Idx);
  77645. data.writeUInt16LE(ntlmv2len);
  77646. data.writeUInt16LE(ntlmv2len);
  77647. data.writeUInt32LE(ntIdx);
  77648. data.writeUInt16LE(domain.length * 2);
  77649. data.writeUInt16LE(domain.length * 2);
  77650. data.writeUInt32LE(dnIdx);
  77651. data.writeUInt16LE(username.length * 2);
  77652. data.writeUInt16LE(username.length * 2);
  77653. data.writeUInt32LE(unIdx);
  77654. data.writeUInt16LE(0);
  77655. data.writeUInt16LE(0);
  77656. data.writeUInt32LE(baseIdx);
  77657. data.writeUInt16LE(0);
  77658. data.writeUInt16LE(0);
  77659. data.writeUInt32LE(baseIdx);
  77660. data.writeUInt16LE(0x8201);
  77661. data.writeUInt16LE(0x08);
  77662. data.writeString(domain, 'ucs2');
  77663. data.writeString(username, 'ucs2');
  77664. const lmv2Data = this.lmv2Response(domain, username, password, server_nonce, client_nonce);
  77665. data.copyFrom(lmv2Data);
  77666. const genTime = new Date().getTime();
  77667. const ntlmDataBuffer = this.ntlmv2Response(domain, username, password, server_nonce, server_data, client_nonce, genTime);
  77668. data.copyFrom(ntlmDataBuffer);
  77669. data.writeUInt32LE(0x0101);
  77670. data.writeUInt32LE(0x0000);
  77671. const timestamp = this.createTimestamp(genTime);
  77672. data.copyFrom(timestamp);
  77673. data.copyFrom(client_nonce);
  77674. data.writeUInt32LE(0x0000);
  77675. data.copyFrom(server_data);
  77676. data.writeUInt32LE(0x0000);
  77677. return data.data;
  77678. }
  77679. createClientNonce() {
  77680. const client_nonce = Buffer.alloc(8, 0);
  77681. let nidx = 0;
  77682. while (nidx < 8) {
  77683. client_nonce.writeUInt8(Math.ceil(Math.random() * 255), nidx);
  77684. nidx++;
  77685. }
  77686. return client_nonce;
  77687. }
  77688. ntlmv2Response(domain, user, password, serverNonce, targetInfo, clientNonce, mytime) {
  77689. const timestamp = this.createTimestamp(mytime);
  77690. const hash = this.ntv2Hash(domain, user, password);
  77691. const dataLength = 40 + targetInfo.length;
  77692. const data = Buffer.alloc(dataLength, 0);
  77693. serverNonce.copy(data, 0, 0, 8);
  77694. data.writeUInt32LE(0x101, 8);
  77695. data.writeUInt32LE(0x0, 12);
  77696. timestamp.copy(data, 16, 0, 8);
  77697. clientNonce.copy(data, 24, 0, 8);
  77698. data.writeUInt32LE(0x0, 32);
  77699. targetInfo.copy(data, 36, 0, targetInfo.length);
  77700. data.writeUInt32LE(0x0, 36 + targetInfo.length);
  77701. return this.hmacMD5(data, hash);
  77702. }
  77703. createTimestamp(time) {
  77704. const tenthsOfAMicrosecond = _jsbi.default.multiply(_jsbi.default.add(_jsbi.default.BigInt(time), _jsbi.default.BigInt(11644473600)), _jsbi.default.BigInt(10000000));
  77705. const lo = _jsbi.default.toNumber(_jsbi.default.bitwiseAnd(tenthsOfAMicrosecond, _jsbi.default.BigInt(0xffffffff)));
  77706. const hi = _jsbi.default.toNumber(_jsbi.default.bitwiseAnd(_jsbi.default.signedRightShift(tenthsOfAMicrosecond, _jsbi.default.BigInt(32)), _jsbi.default.BigInt(0xffffffff)));
  77707. const result = Buffer.alloc(8);
  77708. result.writeUInt32LE(lo, 0);
  77709. result.writeUInt32LE(hi, 4);
  77710. return result;
  77711. }
  77712. lmv2Response(domain, user, password, serverNonce, clientNonce) {
  77713. const hash = this.ntv2Hash(domain, user, password);
  77714. const data = Buffer.alloc(serverNonce.length + clientNonce.length, 0);
  77715. serverNonce.copy(data);
  77716. clientNonce.copy(data, serverNonce.length, 0, clientNonce.length);
  77717. const newhash = this.hmacMD5(data, hash);
  77718. const response = Buffer.alloc(newhash.length + clientNonce.length, 0);
  77719. newhash.copy(response);
  77720. clientNonce.copy(response, newhash.length, 0, clientNonce.length);
  77721. return response;
  77722. }
  77723. ntv2Hash(domain, user, password) {
  77724. const hash = this.ntHash(password);
  77725. const identity = Buffer.from(user.toUpperCase() + domain.toUpperCase(), 'ucs2');
  77726. return this.hmacMD5(identity, hash);
  77727. }
  77728. ntHash(text) {
  77729. const unicodeString = Buffer.from(text, 'ucs2');
  77730. return crypto.createHash('md4').update(unicodeString).digest();
  77731. }
  77732. hmacMD5(data, key) {
  77733. return crypto.createHmac('MD5', key).update(data).digest();
  77734. }
  77735. }
  77736. var _default = NTLMResponsePayload;
  77737. exports.default = _default;
  77738. module.exports = NTLMResponsePayload;
  77739. }).call(this)}).call(this,require("buffer").Buffer)
  77740. },{"./tracking-buffer/writable-tracking-buffer":493,"buffer":193,"crypto":208,"jsbi":327}],467:[function(require,module,exports){
  77741. (function (Buffer){(function (){
  77742. "use strict";
  77743. Object.defineProperty(exports, "__esModule", {
  77744. value: true
  77745. });
  77746. exports.createNTLMRequest = createNTLMRequest;
  77747. const NTLMFlags = {
  77748. NTLM_NegotiateUnicode: 0x00000001,
  77749. NTLM_NegotiateOEM: 0x00000002,
  77750. NTLM_RequestTarget: 0x00000004,
  77751. NTLM_Unknown9: 0x00000008,
  77752. NTLM_NegotiateSign: 0x00000010,
  77753. NTLM_NegotiateSeal: 0x00000020,
  77754. NTLM_NegotiateDatagram: 0x00000040,
  77755. NTLM_NegotiateLanManagerKey: 0x00000080,
  77756. NTLM_Unknown8: 0x00000100,
  77757. NTLM_NegotiateNTLM: 0x00000200,
  77758. NTLM_NegotiateNTOnly: 0x00000400,
  77759. NTLM_Anonymous: 0x00000800,
  77760. NTLM_NegotiateOemDomainSupplied: 0x00001000,
  77761. NTLM_NegotiateOemWorkstationSupplied: 0x00002000,
  77762. NTLM_Unknown6: 0x00004000,
  77763. NTLM_NegotiateAlwaysSign: 0x00008000,
  77764. NTLM_TargetTypeDomain: 0x00010000,
  77765. NTLM_TargetTypeServer: 0x00020000,
  77766. NTLM_TargetTypeShare: 0x00040000,
  77767. NTLM_NegotiateExtendedSecurity: 0x00080000,
  77768. NTLM_NegotiateIdentify: 0x00100000,
  77769. NTLM_Unknown5: 0x00200000,
  77770. NTLM_RequestNonNTSessionKey: 0x00400000,
  77771. NTLM_NegotiateTargetInfo: 0x00800000,
  77772. NTLM_Unknown4: 0x01000000,
  77773. NTLM_NegotiateVersion: 0x02000000,
  77774. NTLM_Unknown3: 0x04000000,
  77775. NTLM_Unknown2: 0x08000000,
  77776. NTLM_Unknown1: 0x10000000,
  77777. NTLM_Negotiate128: 0x20000000,
  77778. NTLM_NegotiateKeyExchange: 0x40000000,
  77779. NTLM_Negotiate56: 0x80000000
  77780. };
  77781. function createNTLMRequest(options) {
  77782. const domain = escape(options.domain.toUpperCase());
  77783. const workstation = options.workstation ? escape(options.workstation.toUpperCase()) : '';
  77784. let type1flags = NTLMFlags.NTLM_NegotiateUnicode + NTLMFlags.NTLM_NegotiateOEM + NTLMFlags.NTLM_RequestTarget + NTLMFlags.NTLM_NegotiateNTLM + NTLMFlags.NTLM_NegotiateOemDomainSupplied + NTLMFlags.NTLM_NegotiateOemWorkstationSupplied + NTLMFlags.NTLM_NegotiateAlwaysSign + NTLMFlags.NTLM_NegotiateVersion + NTLMFlags.NTLM_NegotiateExtendedSecurity + NTLMFlags.NTLM_Negotiate128 + NTLMFlags.NTLM_Negotiate56;
  77785. if (workstation === '') {
  77786. type1flags -= NTLMFlags.NTLM_NegotiateOemWorkstationSupplied;
  77787. }
  77788. const fixedData = Buffer.alloc(40);
  77789. const buffers = [fixedData];
  77790. let offset = 0;
  77791. offset += fixedData.write('NTLMSSP', offset, 7, 'ascii');
  77792. offset = fixedData.writeUInt8(0, offset);
  77793. offset = fixedData.writeUInt32LE(1, offset);
  77794. offset = fixedData.writeUInt32LE(type1flags, offset);
  77795. offset = fixedData.writeUInt16LE(domain.length, offset);
  77796. offset = fixedData.writeUInt16LE(domain.length, offset);
  77797. offset = fixedData.writeUInt32LE(fixedData.length + workstation.length, offset);
  77798. offset = fixedData.writeUInt16LE(workstation.length, offset);
  77799. offset = fixedData.writeUInt16LE(workstation.length, offset);
  77800. offset = fixedData.writeUInt32LE(fixedData.length, offset);
  77801. offset = fixedData.writeUInt8(5, offset);
  77802. offset = fixedData.writeUInt8(0, offset);
  77803. offset = fixedData.writeUInt16LE(2195, offset);
  77804. offset = fixedData.writeUInt8(0, offset);
  77805. offset = fixedData.writeUInt8(0, offset);
  77806. offset = fixedData.writeUInt8(0, offset);
  77807. fixedData.writeUInt8(15, offset);
  77808. buffers.push(Buffer.from(workstation, 'ascii'));
  77809. buffers.push(Buffer.from(domain, 'ascii'));
  77810. return Buffer.concat(buffers);
  77811. }
  77812. }).call(this)}).call(this,require("buffer").Buffer)
  77813. },{"buffer":193}],468:[function(require,module,exports){
  77814. "use strict";
  77815. Object.defineProperty(exports, "__esModule", {
  77816. value: true
  77817. });
  77818. exports.default = void 0;
  77819. var _bl = _interopRequireDefault(require("bl"));
  77820. var _readableStream = require("readable-stream");
  77821. var _packet = require("./packet");
  77822. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  77823. class OutgoingMessageStream extends _readableStream.Duplex {
  77824. constructor(debug, {
  77825. packetSize
  77826. }) {
  77827. super({
  77828. writableObjectMode: true
  77829. });
  77830. this.packetSize = void 0;
  77831. this.debug = void 0;
  77832. this.bl = void 0;
  77833. this.currentMessage = void 0;
  77834. this.packetSize = packetSize;
  77835. this.debug = debug;
  77836. this.bl = new _bl.default(); // When the writable side is ended, push `null`
  77837. // to also end the readable side.
  77838. this.on('finish', () => {
  77839. this.push(null);
  77840. });
  77841. }
  77842. _write(message, _encoding, callback) {
  77843. const length = this.packetSize - _packet.HEADER_LENGTH;
  77844. let packetNumber = 0;
  77845. this.currentMessage = message;
  77846. this.currentMessage.on('data', data => {
  77847. if (message.ignore) {
  77848. return;
  77849. }
  77850. this.bl.append(data);
  77851. while (this.bl.length > length) {
  77852. const data = this.bl.slice(0, length);
  77853. this.bl.consume(length); // TODO: Get rid of creating `Packet` instances here.
  77854. const packet = new _packet.Packet(message.type);
  77855. packet.packetId(packetNumber += 1);
  77856. packet.resetConnection(message.resetConnection);
  77857. packet.addData(data);
  77858. this.debug.packet('Sent', packet);
  77859. this.debug.data(packet);
  77860. if (this.push(packet.buffer) === false) {
  77861. message.pause();
  77862. }
  77863. }
  77864. });
  77865. this.currentMessage.on('end', () => {
  77866. const data = this.bl.slice();
  77867. this.bl.consume(data.length); // TODO: Get rid of creating `Packet` instances here.
  77868. const packet = new _packet.Packet(message.type);
  77869. packet.packetId(packetNumber += 1);
  77870. packet.resetConnection(message.resetConnection);
  77871. packet.last(true);
  77872. packet.ignore(message.ignore);
  77873. packet.addData(data);
  77874. this.debug.packet('Sent', packet);
  77875. this.debug.data(packet);
  77876. this.push(packet.buffer);
  77877. this.currentMessage = undefined;
  77878. callback();
  77879. });
  77880. }
  77881. _read(_size) {
  77882. // If we do have a message, resume it and get data flowing.
  77883. // Otherwise, there is nothing to do.
  77884. if (this.currentMessage) {
  77885. this.currentMessage.resume();
  77886. }
  77887. }
  77888. }
  77889. var _default = OutgoingMessageStream;
  77890. exports.default = _default;
  77891. module.exports = OutgoingMessageStream;
  77892. },{"./packet":469,"bl":371,"readable-stream":409}],469:[function(require,module,exports){
  77893. (function (Buffer){(function (){
  77894. "use strict";
  77895. Object.defineProperty(exports, "__esModule", {
  77896. value: true
  77897. });
  77898. exports.isPacketComplete = isPacketComplete;
  77899. exports.packetLength = packetLength;
  77900. exports.Packet = exports.OFFSET = exports.TYPE = exports.HEADER_LENGTH = void 0;
  77901. var _sprintfJs = require("sprintf-js");
  77902. const HEADER_LENGTH = 8;
  77903. exports.HEADER_LENGTH = HEADER_LENGTH;
  77904. const TYPE = {
  77905. SQL_BATCH: 0x01,
  77906. RPC_REQUEST: 0x03,
  77907. TABULAR_RESULT: 0x04,
  77908. ATTENTION: 0x06,
  77909. BULK_LOAD: 0x07,
  77910. TRANSACTION_MANAGER: 0x0E,
  77911. LOGIN7: 0x10,
  77912. NTLMAUTH_PKT: 0x11,
  77913. PRELOGIN: 0x12,
  77914. FEDAUTH_TOKEN: 0x08
  77915. };
  77916. exports.TYPE = TYPE;
  77917. const typeByValue = {};
  77918. for (const name in TYPE) {
  77919. typeByValue[TYPE[name]] = name;
  77920. }
  77921. const STATUS = {
  77922. NORMAL: 0x00,
  77923. EOM: 0x01,
  77924. IGNORE: 0x02,
  77925. RESETCONNECTION: 0x08,
  77926. RESETCONNECTIONSKIPTRAN: 0x10
  77927. };
  77928. const OFFSET = {
  77929. Type: 0,
  77930. Status: 1,
  77931. Length: 2,
  77932. SPID: 4,
  77933. PacketID: 6,
  77934. Window: 7
  77935. };
  77936. exports.OFFSET = OFFSET;
  77937. const DEFAULT_SPID = 0;
  77938. const DEFAULT_PACKETID = 1;
  77939. const DEFAULT_WINDOW = 0;
  77940. const NL = '\n';
  77941. class Packet {
  77942. constructor(typeOrBuffer) {
  77943. this.buffer = void 0;
  77944. if (typeOrBuffer instanceof Buffer) {
  77945. this.buffer = typeOrBuffer;
  77946. } else {
  77947. const type = typeOrBuffer;
  77948. this.buffer = Buffer.alloc(HEADER_LENGTH, 0);
  77949. this.buffer.writeUInt8(type, OFFSET.Type);
  77950. this.buffer.writeUInt8(STATUS.NORMAL, OFFSET.Status);
  77951. this.buffer.writeUInt16BE(DEFAULT_SPID, OFFSET.SPID);
  77952. this.buffer.writeUInt8(DEFAULT_PACKETID, OFFSET.PacketID);
  77953. this.buffer.writeUInt8(DEFAULT_WINDOW, OFFSET.Window);
  77954. this.setLength();
  77955. }
  77956. }
  77957. setLength() {
  77958. this.buffer.writeUInt16BE(this.buffer.length, OFFSET.Length);
  77959. }
  77960. length() {
  77961. return this.buffer.readUInt16BE(OFFSET.Length);
  77962. }
  77963. resetConnection(reset) {
  77964. let status = this.buffer.readUInt8(OFFSET.Status);
  77965. if (reset) {
  77966. status |= STATUS.RESETCONNECTION;
  77967. } else {
  77968. status &= 0xFF - STATUS.RESETCONNECTION;
  77969. }
  77970. this.buffer.writeUInt8(status, OFFSET.Status);
  77971. }
  77972. last(last) {
  77973. let status = this.buffer.readUInt8(OFFSET.Status);
  77974. if (arguments.length > 0) {
  77975. if (last) {
  77976. status |= STATUS.EOM;
  77977. } else {
  77978. status &= 0xFF - STATUS.EOM;
  77979. }
  77980. this.buffer.writeUInt8(status, OFFSET.Status);
  77981. }
  77982. return this.isLast();
  77983. }
  77984. ignore(last) {
  77985. let status = this.buffer.readUInt8(OFFSET.Status);
  77986. if (last) {
  77987. status |= STATUS.IGNORE;
  77988. } else {
  77989. status &= 0xFF - STATUS.IGNORE;
  77990. }
  77991. this.buffer.writeUInt8(status, OFFSET.Status);
  77992. }
  77993. isLast() {
  77994. return !!(this.buffer.readUInt8(OFFSET.Status) & STATUS.EOM);
  77995. }
  77996. packetId(packetId) {
  77997. if (packetId) {
  77998. this.buffer.writeUInt8(packetId % 256, OFFSET.PacketID);
  77999. }
  78000. return this.buffer.readUInt8(OFFSET.PacketID);
  78001. }
  78002. addData(data) {
  78003. this.buffer = Buffer.concat([this.buffer, data]);
  78004. this.setLength();
  78005. return this;
  78006. }
  78007. data() {
  78008. return this.buffer.slice(HEADER_LENGTH);
  78009. }
  78010. type() {
  78011. return this.buffer.readUInt8(OFFSET.Type);
  78012. }
  78013. statusAsString() {
  78014. const status = this.buffer.readUInt8(OFFSET.Status);
  78015. const statuses = [];
  78016. for (const name in STATUS) {
  78017. const value = STATUS[name];
  78018. if (status & value) {
  78019. statuses.push(name);
  78020. } else {
  78021. statuses.push(undefined);
  78022. }
  78023. }
  78024. return statuses.join(' ').trim();
  78025. }
  78026. headerToString(indent = '') {
  78027. const text = (0, _sprintfJs.sprintf)('type:0x%02X(%s), status:0x%02X(%s), length:0x%04X, spid:0x%04X, packetId:0x%02X, window:0x%02X', this.buffer.readUInt8(OFFSET.Type), typeByValue[this.buffer.readUInt8(OFFSET.Type)], this.buffer.readUInt8(OFFSET.Status), this.statusAsString(), this.buffer.readUInt16BE(OFFSET.Length), this.buffer.readUInt16BE(OFFSET.SPID), this.buffer.readUInt8(OFFSET.PacketID), this.buffer.readUInt8(OFFSET.Window));
  78028. return indent + text;
  78029. }
  78030. dataToString(indent = '') {
  78031. const BYTES_PER_GROUP = 0x04;
  78032. const CHARS_PER_GROUP = 0x08;
  78033. const BYTES_PER_LINE = 0x20;
  78034. const data = this.data();
  78035. let dataDump = '';
  78036. let chars = '';
  78037. for (let offset = 0; offset < data.length; offset++) {
  78038. if (offset % BYTES_PER_LINE === 0) {
  78039. dataDump += indent;
  78040. dataDump += (0, _sprintfJs.sprintf)('%04X ', offset);
  78041. }
  78042. if (data[offset] < 0x20 || data[offset] > 0x7E) {
  78043. chars += '.';
  78044. if ((offset + 1) % CHARS_PER_GROUP === 0 && !((offset + 1) % BYTES_PER_LINE === 0)) {
  78045. chars += ' ';
  78046. }
  78047. } else {
  78048. chars += String.fromCharCode(data[offset]);
  78049. }
  78050. if (data[offset] != null) {
  78051. dataDump += (0, _sprintfJs.sprintf)('%02X', data[offset]);
  78052. }
  78053. if ((offset + 1) % BYTES_PER_GROUP === 0 && !((offset + 1) % BYTES_PER_LINE === 0)) {
  78054. dataDump += ' ';
  78055. }
  78056. if ((offset + 1) % BYTES_PER_LINE === 0) {
  78057. dataDump += ' ' + chars;
  78058. chars = '';
  78059. if (offset < data.length - 1) {
  78060. dataDump += NL;
  78061. }
  78062. }
  78063. }
  78064. if (chars.length) {
  78065. dataDump += ' ' + chars;
  78066. }
  78067. return dataDump;
  78068. }
  78069. toString(indent = '') {
  78070. return this.headerToString(indent) + '\n' + this.dataToString(indent + indent);
  78071. }
  78072. payloadString() {
  78073. return '';
  78074. }
  78075. }
  78076. exports.Packet = Packet;
  78077. function isPacketComplete(potentialPacketBuffer) {
  78078. if (potentialPacketBuffer.length < HEADER_LENGTH) {
  78079. return false;
  78080. } else {
  78081. return potentialPacketBuffer.length >= potentialPacketBuffer.readUInt16BE(OFFSET.Length);
  78082. }
  78083. }
  78084. function packetLength(potentialPacketBuffer) {
  78085. return potentialPacketBuffer.readUInt16BE(OFFSET.Length);
  78086. }
  78087. }).call(this)}).call(this,require("buffer").Buffer)
  78088. },{"buffer":193,"sprintf-js":410}],470:[function(require,module,exports){
  78089. (function (Buffer){(function (){
  78090. "use strict";
  78091. Object.defineProperty(exports, "__esModule", {
  78092. value: true
  78093. });
  78094. exports.default = void 0;
  78095. var _sprintfJs = require("sprintf-js");
  78096. var _writableTrackingBuffer = _interopRequireDefault(require("./tracking-buffer/writable-tracking-buffer"));
  78097. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  78098. const optionBufferSize = 20;
  78099. const VERSION = 0x000000001;
  78100. const SUBBUILD = 0x0001;
  78101. const TOKEN = {
  78102. VERSION: 0x00,
  78103. ENCRYPTION: 0x01,
  78104. INSTOPT: 0x02,
  78105. THREADID: 0x03,
  78106. MARS: 0x04,
  78107. FEDAUTHREQUIRED: 0x06,
  78108. TERMINATOR: 0xFF
  78109. };
  78110. const ENCRYPT = {
  78111. OFF: 0x00,
  78112. ON: 0x01,
  78113. NOT_SUP: 0x02,
  78114. REQ: 0x03
  78115. };
  78116. const encryptByValue = {};
  78117. for (const name in ENCRYPT) {
  78118. const value = ENCRYPT[name];
  78119. encryptByValue[value] = name;
  78120. }
  78121. const MARS = {
  78122. OFF: 0x00,
  78123. ON: 0x01
  78124. };
  78125. const marsByValue = {};
  78126. for (const name in MARS) {
  78127. const value = MARS[name];
  78128. marsByValue[value] = name;
  78129. }
  78130. /*
  78131. s2.2.6.4
  78132. */
  78133. class PreloginPayload {
  78134. constructor(bufferOrOptions = {
  78135. encrypt: false
  78136. }) {
  78137. this.options = void 0;
  78138. if (bufferOrOptions instanceof Buffer) {
  78139. this.data = bufferOrOptions;
  78140. this.options = {
  78141. encrypt: false
  78142. };
  78143. } else {
  78144. this.options = bufferOrOptions;
  78145. this.createOptions();
  78146. }
  78147. this.extractOptions();
  78148. }
  78149. createOptions() {
  78150. const options = [this.createVersionOption(), this.createEncryptionOption(), this.createInstanceOption(), this.createThreadIdOption(), this.createMarsOption(), this.createFedAuthOption()];
  78151. let length = 0;
  78152. for (let i = 0, len = options.length; i < len; i++) {
  78153. const option = options[i];
  78154. length += 5 + option.data.length;
  78155. }
  78156. length++; // terminator
  78157. this.data = Buffer.alloc(length, 0);
  78158. let optionOffset = 0;
  78159. let optionDataOffset = 5 * options.length + 1;
  78160. for (let j = 0, len = options.length; j < len; j++) {
  78161. const option = options[j];
  78162. this.data.writeUInt8(option.token, optionOffset + 0);
  78163. this.data.writeUInt16BE(optionDataOffset, optionOffset + 1);
  78164. this.data.writeUInt16BE(option.data.length, optionOffset + 3);
  78165. optionOffset += 5;
  78166. option.data.copy(this.data, optionDataOffset);
  78167. optionDataOffset += option.data.length;
  78168. }
  78169. this.data.writeUInt8(TOKEN.TERMINATOR, optionOffset);
  78170. }
  78171. createVersionOption() {
  78172. const buffer = new _writableTrackingBuffer.default(optionBufferSize);
  78173. buffer.writeUInt32BE(VERSION);
  78174. buffer.writeUInt16BE(SUBBUILD);
  78175. return {
  78176. token: TOKEN.VERSION,
  78177. data: buffer.data
  78178. };
  78179. }
  78180. createEncryptionOption() {
  78181. const buffer = new _writableTrackingBuffer.default(optionBufferSize);
  78182. if (this.options.encrypt) {
  78183. buffer.writeUInt8(ENCRYPT.ON);
  78184. } else {
  78185. buffer.writeUInt8(ENCRYPT.NOT_SUP);
  78186. }
  78187. return {
  78188. token: TOKEN.ENCRYPTION,
  78189. data: buffer.data
  78190. };
  78191. }
  78192. createInstanceOption() {
  78193. const buffer = new _writableTrackingBuffer.default(optionBufferSize);
  78194. buffer.writeUInt8(0x00);
  78195. return {
  78196. token: TOKEN.INSTOPT,
  78197. data: buffer.data
  78198. };
  78199. }
  78200. createThreadIdOption() {
  78201. const buffer = new _writableTrackingBuffer.default(optionBufferSize);
  78202. buffer.writeUInt32BE(0x00);
  78203. return {
  78204. token: TOKEN.THREADID,
  78205. data: buffer.data
  78206. };
  78207. }
  78208. createMarsOption() {
  78209. const buffer = new _writableTrackingBuffer.default(optionBufferSize);
  78210. buffer.writeUInt8(MARS.OFF);
  78211. return {
  78212. token: TOKEN.MARS,
  78213. data: buffer.data
  78214. };
  78215. }
  78216. createFedAuthOption() {
  78217. const buffer = new _writableTrackingBuffer.default(optionBufferSize);
  78218. buffer.writeUInt8(0x01);
  78219. return {
  78220. token: TOKEN.FEDAUTHREQUIRED,
  78221. data: buffer.data
  78222. };
  78223. }
  78224. extractOptions() {
  78225. let offset = 0;
  78226. while (this.data[offset] !== TOKEN.TERMINATOR) {
  78227. let dataOffset = this.data.readUInt16BE(offset + 1);
  78228. const dataLength = this.data.readUInt16BE(offset + 3);
  78229. switch (this.data[offset]) {
  78230. case TOKEN.VERSION:
  78231. this.extractVersion(dataOffset);
  78232. break;
  78233. case TOKEN.ENCRYPTION:
  78234. this.extractEncryption(dataOffset);
  78235. break;
  78236. case TOKEN.INSTOPT:
  78237. this.extractInstance(dataOffset);
  78238. break;
  78239. case TOKEN.THREADID:
  78240. if (dataLength > 0) {
  78241. this.extractThreadId(dataOffset);
  78242. }
  78243. break;
  78244. case TOKEN.MARS:
  78245. this.extractMars(dataOffset);
  78246. break;
  78247. case TOKEN.FEDAUTHREQUIRED:
  78248. this.extractFedAuth(dataOffset);
  78249. break;
  78250. }
  78251. offset += 5;
  78252. dataOffset += dataLength;
  78253. }
  78254. }
  78255. extractVersion(offset) {
  78256. this.version = {
  78257. major: this.data.readUInt8(offset + 0),
  78258. minor: this.data.readUInt8(offset + 1),
  78259. patch: this.data.readUInt8(offset + 2),
  78260. trivial: this.data.readUInt8(offset + 3),
  78261. subbuild: this.data.readUInt16BE(offset + 4)
  78262. };
  78263. }
  78264. extractEncryption(offset) {
  78265. this.encryption = this.data.readUInt8(offset);
  78266. this.encryptionString = encryptByValue[this.encryption];
  78267. }
  78268. extractInstance(offset) {
  78269. this.instance = this.data.readUInt8(offset);
  78270. }
  78271. extractThreadId(offset) {
  78272. this.threadId = this.data.readUInt32BE(offset);
  78273. }
  78274. extractMars(offset) {
  78275. this.mars = this.data.readUInt8(offset);
  78276. this.marsString = marsByValue[this.mars];
  78277. }
  78278. extractFedAuth(offset) {
  78279. this.fedAuthRequired = this.data.readUInt8(offset);
  78280. }
  78281. toString(indent = '') {
  78282. return indent + 'PreLogin - ' + (0, _sprintfJs.sprintf)('version:%d.%d.%d.%d %d, encryption:0x%02X(%s), instopt:0x%02X, threadId:0x%08X, mars:0x%02X(%s)', this.version.major, this.version.minor, this.version.patch, this.version.trivial, this.version.subbuild, this.encryption ? this.encryption : 0, this.encryptionString ? this.encryptionString : '', this.instance ? this.instance : 0, this.threadId ? this.threadId : 0, this.mars ? this.mars : 0, this.marsString ? this.marsString : '');
  78283. }
  78284. }
  78285. var _default = PreloginPayload;
  78286. exports.default = _default;
  78287. module.exports = PreloginPayload;
  78288. }).call(this)}).call(this,require("buffer").Buffer)
  78289. },{"./tracking-buffer/writable-tracking-buffer":493,"buffer":193,"sprintf-js":410}],471:[function(require,module,exports){
  78290. "use strict";
  78291. Object.defineProperty(exports, "__esModule", {
  78292. value: true
  78293. });
  78294. exports.default = void 0;
  78295. var _events = require("events");
  78296. var _dataType = require("./data-type");
  78297. var _errors = require("./errors");
  78298. class Request extends _events.EventEmitter {
  78299. constructor(sqlTextOrProcedure, callback) {
  78300. super();
  78301. this.sqlTextOrProcedure = void 0;
  78302. this.parameters = void 0;
  78303. this.parametersByName = void 0;
  78304. this.originalParameters = void 0;
  78305. this.preparing = void 0;
  78306. this.canceled = void 0;
  78307. this.paused = void 0;
  78308. this.userCallback = void 0;
  78309. this.handle = void 0;
  78310. this.error = void 0;
  78311. this.connection = void 0;
  78312. this.timeout = void 0;
  78313. this.rows = void 0;
  78314. this.rst = void 0;
  78315. this.rowCount = void 0;
  78316. this.callback = void 0;
  78317. this.sqlTextOrProcedure = sqlTextOrProcedure;
  78318. this.parameters = [];
  78319. this.parametersByName = {};
  78320. this.originalParameters = [];
  78321. this.preparing = false;
  78322. this.handle = undefined;
  78323. this.canceled = false;
  78324. this.paused = false;
  78325. this.error = undefined;
  78326. this.connection = undefined;
  78327. this.timeout = undefined;
  78328. this.userCallback = callback;
  78329. this.callback = function (err, rowCount, rows) {
  78330. if (this.preparing) {
  78331. this.preparing = false;
  78332. if (err) {
  78333. this.emit('error', err);
  78334. } else {
  78335. this.emit('prepared');
  78336. }
  78337. } else {
  78338. this.userCallback(err, rowCount, rows);
  78339. this.emit('requestCompleted');
  78340. }
  78341. };
  78342. } // TODO: `type` must be a valid TDS value type
  78343. addParameter(name, type, value, options) {
  78344. if (options == null) {
  78345. options = {};
  78346. }
  78347. const _options = options,
  78348. _options$output = _options.output,
  78349. output = _options$output === void 0 ? false : _options$output,
  78350. length = _options.length,
  78351. precision = _options.precision,
  78352. scale = _options.scale;
  78353. const parameter = {
  78354. type: type,
  78355. name: name,
  78356. value: value,
  78357. output: output,
  78358. length: length,
  78359. precision: precision,
  78360. scale: scale
  78361. };
  78362. this.parameters.push(parameter);
  78363. this.parametersByName[name] = parameter;
  78364. } // TODO: `type` must be a valid TDS value type
  78365. addOutputParameter(name, type, value, options) {
  78366. if (options == null) {
  78367. options = {};
  78368. }
  78369. options.output = true;
  78370. this.addParameter(name, type, value, options);
  78371. }
  78372. makeParamsParameter(parameters) {
  78373. let paramsParameter = '';
  78374. for (let i = 0, len = parameters.length; i < len; i++) {
  78375. const parameter = parameters[i];
  78376. if (paramsParameter.length > 0) {
  78377. paramsParameter += ', ';
  78378. }
  78379. paramsParameter += '@' + parameter.name + ' ';
  78380. paramsParameter += parameter.type.declaration(parameter);
  78381. if (parameter.output) {
  78382. paramsParameter += ' OUTPUT';
  78383. }
  78384. }
  78385. return paramsParameter;
  78386. }
  78387. transformIntoExecuteSqlRpc() {
  78388. if (this.validateParameters()) {
  78389. return;
  78390. }
  78391. this.originalParameters = this.parameters;
  78392. this.parameters = [];
  78393. this.addParameter('statement', _dataType.typeByName.NVarChar, this.sqlTextOrProcedure);
  78394. if (this.originalParameters.length) {
  78395. this.addParameter('params', _dataType.typeByName.NVarChar, this.makeParamsParameter(this.originalParameters));
  78396. }
  78397. for (let i = 0, len = this.originalParameters.length; i < len; i++) {
  78398. const parameter = this.originalParameters[i];
  78399. this.parameters.push(parameter);
  78400. }
  78401. this.sqlTextOrProcedure = 'sp_executesql';
  78402. }
  78403. transformIntoPrepareRpc() {
  78404. this.originalParameters = this.parameters;
  78405. this.parameters = [];
  78406. this.addOutputParameter('handle', _dataType.typeByName.Int, undefined);
  78407. this.addParameter('params', _dataType.typeByName.NVarChar, this.makeParamsParameter(this.originalParameters));
  78408. this.addParameter('stmt', _dataType.typeByName.NVarChar, this.sqlTextOrProcedure);
  78409. this.sqlTextOrProcedure = 'sp_prepare';
  78410. this.preparing = true;
  78411. this.on('returnValue', (name, value) => {
  78412. if (name === 'handle') {
  78413. this.handle = value;
  78414. } else {
  78415. this.error = (0, _errors.RequestError)(`Tedious > Unexpected output parameter ${name} from sp_prepare`);
  78416. }
  78417. });
  78418. }
  78419. transformIntoUnprepareRpc() {
  78420. this.parameters = [];
  78421. this.addParameter('handle', _dataType.typeByName.Int, this.handle);
  78422. this.sqlTextOrProcedure = 'sp_unprepare';
  78423. }
  78424. transformIntoExecuteRpc(parameters) {
  78425. this.parameters = [];
  78426. this.addParameter('handle', _dataType.typeByName.Int, this.handle);
  78427. for (let i = 0, len = this.originalParameters.length; i < len; i++) {
  78428. const parameter = this.originalParameters[i];
  78429. parameter.value = parameters[parameter.name];
  78430. this.parameters.push(parameter);
  78431. }
  78432. if (this.validateParameters()) {
  78433. return;
  78434. }
  78435. this.sqlTextOrProcedure = 'sp_execute';
  78436. }
  78437. validateParameters() {
  78438. for (let i = 0, len = this.parameters.length; i < len; i++) {
  78439. const parameter = this.parameters[i];
  78440. const value = parameter.type.validate(parameter.value);
  78441. if (value instanceof TypeError) {
  78442. return this.error = new _errors.RequestError('Validation failed for parameter \'' + parameter.name + '\'. ' + value.message, 'EPARAM');
  78443. }
  78444. parameter.value = value;
  78445. }
  78446. return null;
  78447. } // Temporarily suspends the flow of data from the database.
  78448. // No more 'row' events will be emitted until resume() is called.
  78449. pause() {
  78450. if (this.paused) {
  78451. return;
  78452. }
  78453. this.paused = true;
  78454. if (this.connection) {
  78455. this.connection.pauseRequest(this);
  78456. }
  78457. } // Resumes the flow of data from the database.
  78458. resume() {
  78459. if (!this.paused) {
  78460. return;
  78461. }
  78462. this.paused = false;
  78463. if (this.connection) {
  78464. this.connection.resumeRequest(this);
  78465. }
  78466. }
  78467. cancel() {
  78468. if (this.canceled) {
  78469. return;
  78470. }
  78471. this.canceled = true;
  78472. this.emit('cancel');
  78473. }
  78474. setTimeout(timeout) {
  78475. this.timeout = timeout;
  78476. }
  78477. }
  78478. var _default = Request;
  78479. exports.default = _default;
  78480. module.exports = Request;
  78481. },{"./data-type":416,"./errors":457,"events":247}],472:[function(require,module,exports){
  78482. (function (setImmediate){(function (){
  78483. "use strict";
  78484. Object.defineProperty(exports, "__esModule", {
  78485. value: true
  78486. });
  78487. exports.default = void 0;
  78488. var _writableTrackingBuffer = _interopRequireDefault(require("./tracking-buffer/writable-tracking-buffer"));
  78489. var _allHeaders = require("./all-headers");
  78490. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  78491. // const OPTION = {
  78492. // WITH_RECOMPILE: 0x01,
  78493. // NO_METADATA: 0x02,
  78494. // REUSE_METADATA: 0x04
  78495. // };
  78496. const STATUS = {
  78497. BY_REF_VALUE: 0x01,
  78498. DEFAULT_VALUE: 0x02
  78499. };
  78500. /*
  78501. s2.2.6.5
  78502. */
  78503. class RpcRequestPayload {
  78504. constructor(request, txnDescriptor, options) {
  78505. this.request = void 0;
  78506. this.procedure = void 0;
  78507. this.options = void 0;
  78508. this.txnDescriptor = void 0;
  78509. this.request = request;
  78510. this.procedure = this.request.sqlTextOrProcedure;
  78511. this.options = options;
  78512. this.txnDescriptor = txnDescriptor;
  78513. }
  78514. getData(cb) {
  78515. const buffer = new _writableTrackingBuffer.default(500);
  78516. if (this.options.tdsVersion >= '7_2') {
  78517. const outstandingRequestCount = 1;
  78518. (0, _allHeaders.writeToTrackingBuffer)(buffer, this.txnDescriptor, outstandingRequestCount);
  78519. }
  78520. if (typeof this.procedure === 'string') {
  78521. buffer.writeUsVarchar(this.procedure);
  78522. } else {
  78523. buffer.writeUShort(0xFFFF);
  78524. buffer.writeUShort(this.procedure);
  78525. }
  78526. const optionFlags = 0;
  78527. buffer.writeUInt16LE(optionFlags);
  78528. const parameters = this.request.parameters;
  78529. const writeNext = i => {
  78530. if (i >= parameters.length) {
  78531. cb(buffer.data);
  78532. return;
  78533. }
  78534. this._writeParameterData(parameters[i], buffer, () => {
  78535. setImmediate(() => {
  78536. writeNext(i + 1);
  78537. });
  78538. });
  78539. };
  78540. writeNext(0);
  78541. }
  78542. toString(indent = '') {
  78543. return indent + ('RPC Request - ' + this.procedure);
  78544. }
  78545. _writeParameterData(parameter, buffer, cb) {
  78546. buffer.writeBVarchar('@' + parameter.name);
  78547. let statusFlags = 0;
  78548. if (parameter.output) {
  78549. statusFlags |= STATUS.BY_REF_VALUE;
  78550. }
  78551. buffer.writeUInt8(statusFlags);
  78552. const param = {
  78553. value: parameter.value
  78554. };
  78555. const type = parameter.type;
  78556. if ((type.id & 0x30) === 0x20) {
  78557. if (parameter.length) {
  78558. param.length = parameter.length;
  78559. } else if (type.resolveLength) {
  78560. param.length = type.resolveLength(parameter);
  78561. }
  78562. }
  78563. if (parameter.precision) {
  78564. param.precision = parameter.precision;
  78565. } else if (type.resolvePrecision) {
  78566. param.precision = type.resolvePrecision(parameter);
  78567. }
  78568. if (parameter.scale) {
  78569. param.scale = parameter.scale;
  78570. } else if (type.resolveScale) {
  78571. param.scale = type.resolveScale(parameter);
  78572. }
  78573. type.writeTypeInfo(buffer, param, this.options);
  78574. type.writeParameterData(buffer, param, this.options, () => {
  78575. cb();
  78576. });
  78577. }
  78578. }
  78579. var _default = RpcRequestPayload;
  78580. exports.default = _default;
  78581. module.exports = RpcRequestPayload;
  78582. }).call(this)}).call(this,require("timers").setImmediate)
  78583. },{"./all-headers":411,"./tracking-buffer/writable-tracking-buffer":493,"timers":639}],473:[function(require,module,exports){
  78584. "use strict";
  78585. Object.defineProperty(exports, "__esModule", {
  78586. value: true
  78587. });
  78588. exports.Sender = exports.ParallelSendStrategy = void 0;
  78589. var _dgram = _interopRequireDefault(require("dgram"));
  78590. var _dns = _interopRequireDefault(require("dns"));
  78591. var _net = _interopRequireDefault(require("net"));
  78592. var punycode = _interopRequireWildcard(require("punycode"));
  78593. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  78594. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  78595. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  78596. class ParallelSendStrategy {
  78597. constructor(addresses, port, request) {
  78598. this.addresses = void 0;
  78599. this.port = void 0;
  78600. this.request = void 0;
  78601. this.socketV4 = void 0;
  78602. this.socketV6 = void 0;
  78603. this.onMessage = void 0;
  78604. this.onError = void 0;
  78605. this.addresses = addresses;
  78606. this.port = port;
  78607. this.request = request;
  78608. this.socketV4 = null;
  78609. this.socketV6 = null;
  78610. this.onError = null;
  78611. this.onMessage = null;
  78612. }
  78613. clearSockets() {
  78614. const clearSocket = (socket, onError, onMessage) => {
  78615. socket.removeListener('error', onError);
  78616. socket.removeListener('message', onMessage);
  78617. socket.close();
  78618. };
  78619. if (this.socketV4) {
  78620. clearSocket(this.socketV4, this.onError, this.onMessage);
  78621. this.socketV4 = null;
  78622. }
  78623. if (this.socketV6) {
  78624. clearSocket(this.socketV6, this.onError, this.onMessage);
  78625. this.socketV6 = null;
  78626. }
  78627. }
  78628. send(cb) {
  78629. let errorCount = 0;
  78630. const onError = err => {
  78631. errorCount++;
  78632. if (errorCount === this.addresses.length) {
  78633. this.clearSockets();
  78634. cb(err);
  78635. }
  78636. };
  78637. const onMessage = message => {
  78638. this.clearSockets();
  78639. cb(null, message);
  78640. };
  78641. const createDgramSocket = (udpType, onError, onMessage) => {
  78642. const socket = _dgram.default.createSocket(udpType);
  78643. socket.on('error', onError);
  78644. socket.on('message', onMessage);
  78645. return socket;
  78646. };
  78647. for (let j = 0; j < this.addresses.length; j++) {
  78648. const udpTypeV4 = 'udp4';
  78649. const udpTypeV6 = 'udp6';
  78650. const udpType = this.addresses[j].family === 6 ? udpTypeV6 : udpTypeV4;
  78651. let socket;
  78652. if (udpType === udpTypeV4) {
  78653. if (!this.socketV4) {
  78654. this.socketV4 = createDgramSocket(udpTypeV4, onError, onMessage);
  78655. }
  78656. socket = this.socketV4;
  78657. } else {
  78658. if (!this.socketV6) {
  78659. this.socketV6 = createDgramSocket(udpTypeV6, onError, onMessage);
  78660. }
  78661. socket = this.socketV6;
  78662. }
  78663. socket.send(this.request, 0, this.request.length, this.port, this.addresses[j].address);
  78664. }
  78665. this.onError = onError;
  78666. this.onMessage = onMessage;
  78667. }
  78668. cancel() {
  78669. this.clearSockets();
  78670. }
  78671. }
  78672. exports.ParallelSendStrategy = ParallelSendStrategy;
  78673. class Sender {
  78674. constructor(host, port, request) {
  78675. this.host = void 0;
  78676. this.port = void 0;
  78677. this.request = void 0;
  78678. this.parallelSendStrategy = void 0;
  78679. this.host = host;
  78680. this.port = port;
  78681. this.request = request;
  78682. this.parallelSendStrategy = null;
  78683. }
  78684. execute(cb) {
  78685. if (_net.default.isIP(this.host)) {
  78686. this.executeForIP(cb);
  78687. } else {
  78688. this.executeForHostname(cb);
  78689. }
  78690. }
  78691. executeForIP(cb) {
  78692. this.executeForAddresses([{
  78693. address: this.host,
  78694. family: _net.default.isIPv6(this.host) ? 6 : 4
  78695. }], cb);
  78696. } // Wrapper for stubbing. Sinon does not have support for stubbing module functions.
  78697. invokeLookupAll(host, cb) {
  78698. _dns.default.lookup(punycode.toASCII(host), {
  78699. all: true
  78700. }, cb);
  78701. }
  78702. executeForHostname(cb) {
  78703. this.invokeLookupAll(this.host, (err, addresses) => {
  78704. if (err) {
  78705. return cb(err);
  78706. }
  78707. this.executeForAddresses(addresses, cb);
  78708. });
  78709. } // Wrapper for stubbing creation of Strategy object. Sinon support for constructors
  78710. // seems limited.
  78711. createParallelSendStrategy(addresses, port, request) {
  78712. return new ParallelSendStrategy(addresses, port, request);
  78713. }
  78714. executeForAddresses(addresses, cb) {
  78715. this.parallelSendStrategy = this.createParallelSendStrategy(addresses, this.port, this.request);
  78716. this.parallelSendStrategy.send(cb);
  78717. }
  78718. cancel() {
  78719. if (this.parallelSendStrategy) {
  78720. this.parallelSendStrategy.cancel();
  78721. }
  78722. }
  78723. }
  78724. exports.Sender = Sender;
  78725. },{"dgram":190,"dns":190,"net":190,"punycode":535}],474:[function(require,module,exports){
  78726. "use strict";
  78727. Object.defineProperty(exports, "__esModule", {
  78728. value: true
  78729. });
  78730. exports.default = void 0;
  78731. var _writableTrackingBuffer = _interopRequireDefault(require("./tracking-buffer/writable-tracking-buffer"));
  78732. var _allHeaders = require("./all-headers");
  78733. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  78734. /*
  78735. s2.2.6.6
  78736. */
  78737. class SqlBatchPayload {
  78738. constructor(sqlText, txnDescriptor, options) {
  78739. this.sqlText = void 0;
  78740. this.txnDescriptor = void 0;
  78741. this.options = void 0;
  78742. this.sqlText = sqlText;
  78743. this.txnDescriptor = txnDescriptor;
  78744. this.options = options;
  78745. }
  78746. getData(cb) {
  78747. const buffer = new _writableTrackingBuffer.default(100 + 2 * this.sqlText.length, 'ucs2');
  78748. if (this.options.tdsVersion >= '7_2') {
  78749. const outstandingRequestCount = 1;
  78750. (0, _allHeaders.writeToTrackingBuffer)(buffer, this.txnDescriptor, outstandingRequestCount);
  78751. }
  78752. buffer.writeString(this.sqlText, 'ucs2');
  78753. cb(buffer.data);
  78754. }
  78755. toString(indent = '') {
  78756. return indent + ('SQL Batch - ' + this.sqlText);
  78757. }
  78758. }
  78759. var _default = SqlBatchPayload;
  78760. exports.default = _default;
  78761. module.exports = SqlBatchPayload;
  78762. },{"./all-headers":411,"./tracking-buffer/writable-tracking-buffer":493}],475:[function(require,module,exports){
  78763. "use strict";
  78764. Object.defineProperty(exports, "__esModule", {
  78765. value: true
  78766. });
  78767. exports.versionsByValue = exports.versions = void 0;
  78768. const versions = {
  78769. '7_1': 0x71000001,
  78770. '7_2': 0x72090002,
  78771. '7_3_A': 0x730A0003,
  78772. '7_3_B': 0x730B0003,
  78773. '7_4': 0x74000004
  78774. };
  78775. exports.versions = versions;
  78776. const versionsByValue = {};
  78777. exports.versionsByValue = versionsByValue;
  78778. for (const name in versions) {
  78779. versionsByValue[versions[name]] = name;
  78780. }
  78781. },{}],476:[function(require,module,exports){
  78782. "use strict";
  78783. Object.defineProperty(exports, "__esModule", {
  78784. value: true
  78785. });
  78786. Object.defineProperty(exports, "BulkLoad", {
  78787. enumerable: true,
  78788. get: function get() {
  78789. return _bulkLoad.default;
  78790. }
  78791. });
  78792. Object.defineProperty(exports, "Connection", {
  78793. enumerable: true,
  78794. get: function get() {
  78795. return _connection.default;
  78796. }
  78797. });
  78798. Object.defineProperty(exports, "Request", {
  78799. enumerable: true,
  78800. get: function get() {
  78801. return _request.default;
  78802. }
  78803. });
  78804. Object.defineProperty(exports, "ConnectionError", {
  78805. enumerable: true,
  78806. get: function get() {
  78807. return _errors.ConnectionError;
  78808. }
  78809. });
  78810. Object.defineProperty(exports, "RequestError", {
  78811. enumerable: true,
  78812. get: function get() {
  78813. return _errors.RequestError;
  78814. }
  78815. });
  78816. Object.defineProperty(exports, "TYPES", {
  78817. enumerable: true,
  78818. get: function get() {
  78819. return _dataType.typeByName;
  78820. }
  78821. });
  78822. Object.defineProperty(exports, "ISOLATION_LEVEL", {
  78823. enumerable: true,
  78824. get: function get() {
  78825. return _transaction.ISOLATION_LEVEL;
  78826. }
  78827. });
  78828. Object.defineProperty(exports, "TDS_VERSION", {
  78829. enumerable: true,
  78830. get: function get() {
  78831. return _tdsVersions.versions;
  78832. }
  78833. });
  78834. exports.library = void 0;
  78835. var _bulkLoad = _interopRequireDefault(require("./bulk-load"));
  78836. var _connection = _interopRequireDefault(require("./connection"));
  78837. var _request = _interopRequireDefault(require("./request"));
  78838. var _library = require("./library");
  78839. var _errors = require("./errors");
  78840. var _dataType = require("./data-type");
  78841. var _transaction = require("./transaction");
  78842. var _tdsVersions = require("./tds-versions");
  78843. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  78844. const library = {
  78845. name: _library.name
  78846. };
  78847. exports.library = library;
  78848. },{"./bulk-load":412,"./connection":414,"./data-type":416,"./errors":457,"./library":461,"./request":471,"./tds-versions":475,"./transaction":494}],477:[function(require,module,exports){
  78849. "use strict";
  78850. Object.defineProperty(exports, "__esModule", {
  78851. value: true
  78852. });
  78853. exports.default = void 0;
  78854. var _metadataParser = _interopRequireDefault(require("../metadata-parser"));
  78855. var _token = require("./token");
  78856. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  78857. function readTableName(parser, options, metadata, callback) {
  78858. if (metadata.type.hasTableName) {
  78859. if (options.tdsVersion >= '7_2') {
  78860. parser.readUInt8(numberOfTableNameParts => {
  78861. const tableName = [];
  78862. let i = 0;
  78863. function next(done) {
  78864. if (numberOfTableNameParts === i) {
  78865. return done();
  78866. }
  78867. parser.readUsVarChar(part => {
  78868. tableName.push(part);
  78869. i++;
  78870. next(done);
  78871. });
  78872. }
  78873. next(() => {
  78874. callback(tableName);
  78875. });
  78876. });
  78877. } else {
  78878. parser.readUsVarChar(callback);
  78879. }
  78880. } else {
  78881. callback(undefined);
  78882. }
  78883. }
  78884. function readColumnName(parser, options, index, metadata, callback) {
  78885. parser.readBVarChar(colName => {
  78886. if (options.columnNameReplacer) {
  78887. callback(options.columnNameReplacer(colName, index, metadata));
  78888. } else if (options.camelCaseColumns) {
  78889. callback(colName.replace(/^[A-Z]/, function (s) {
  78890. return s.toLowerCase();
  78891. }));
  78892. } else {
  78893. callback(colName);
  78894. }
  78895. });
  78896. }
  78897. function readColumn(parser, options, index, callback) {
  78898. (0, _metadataParser.default)(parser, options, metadata => {
  78899. readTableName(parser, options, metadata, tableName => {
  78900. readColumnName(parser, options, index, metadata, colName => {
  78901. callback({
  78902. userType: metadata.userType,
  78903. flags: metadata.flags,
  78904. type: metadata.type,
  78905. collation: metadata.collation,
  78906. precision: metadata.precision,
  78907. scale: metadata.scale,
  78908. udtInfo: metadata.udtInfo,
  78909. dataLength: metadata.dataLength,
  78910. schema: metadata.schema,
  78911. colName: colName,
  78912. tableName: tableName
  78913. });
  78914. });
  78915. });
  78916. });
  78917. }
  78918. function colMetadataParser(parser, _colMetadata, options, callback) {
  78919. parser.readUInt16LE(columnCount => {
  78920. const columns = [];
  78921. let i = 0;
  78922. function next(done) {
  78923. if (i === columnCount) {
  78924. return done();
  78925. }
  78926. readColumn(parser, options, i, column => {
  78927. columns.push(column);
  78928. i++;
  78929. next(done);
  78930. });
  78931. }
  78932. next(() => {
  78933. callback(new _token.ColMetadataToken(columns));
  78934. });
  78935. });
  78936. }
  78937. var _default = colMetadataParser;
  78938. exports.default = _default;
  78939. module.exports = colMetadataParser;
  78940. },{"../metadata-parser":465,"./token":492}],478:[function(require,module,exports){
  78941. "use strict";
  78942. Object.defineProperty(exports, "__esModule", {
  78943. value: true
  78944. });
  78945. exports.doneParser = doneParser;
  78946. exports.doneInProcParser = doneInProcParser;
  78947. exports.doneProcParser = doneProcParser;
  78948. var _jsbi = _interopRequireDefault(require("jsbi"));
  78949. var _token = require("./token");
  78950. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  78951. // s2.2.7.5/6/7
  78952. const STATUS = {
  78953. MORE: 0x0001,
  78954. ERROR: 0x0002,
  78955. // This bit is not yet in use by SQL Server, so is not exposed in the returned token
  78956. INXACT: 0x0004,
  78957. COUNT: 0x0010,
  78958. ATTN: 0x0020,
  78959. SRVERROR: 0x0100
  78960. };
  78961. function parseToken(parser, options, callback) {
  78962. parser.readUInt16LE(status => {
  78963. const more = !!(status & STATUS.MORE);
  78964. const sqlError = !!(status & STATUS.ERROR);
  78965. const rowCountValid = !!(status & STATUS.COUNT);
  78966. const attention = !!(status & STATUS.ATTN);
  78967. const serverError = !!(status & STATUS.SRVERROR);
  78968. parser.readUInt16LE(curCmd => {
  78969. const next = rowCount => {
  78970. callback({
  78971. more: more,
  78972. sqlError: sqlError,
  78973. attention: attention,
  78974. serverError: serverError,
  78975. rowCount: rowCountValid ? rowCount : undefined,
  78976. curCmd: curCmd
  78977. });
  78978. };
  78979. if (options.tdsVersion < '7_2') {
  78980. parser.readUInt32LE(next);
  78981. } else {
  78982. parser.readBigUInt64LE(rowCount => {
  78983. next(_jsbi.default.toNumber(rowCount));
  78984. });
  78985. }
  78986. });
  78987. });
  78988. }
  78989. function doneParser(parser, _colMetadata, options, callback) {
  78990. parseToken(parser, options, data => {
  78991. callback(new _token.DoneToken(data));
  78992. });
  78993. }
  78994. function doneInProcParser(parser, _colMetadata, options, callback) {
  78995. parseToken(parser, options, data => {
  78996. callback(new _token.DoneInProcToken(data));
  78997. });
  78998. }
  78999. function doneProcParser(parser, _colMetadata, options, callback) {
  79000. parseToken(parser, options, data => {
  79001. callback(new _token.DoneProcToken(data));
  79002. });
  79003. }
  79004. },{"./token":492,"jsbi":327}],479:[function(require,module,exports){
  79005. "use strict";
  79006. Object.defineProperty(exports, "__esModule", {
  79007. value: true
  79008. });
  79009. exports.default = void 0;
  79010. var _token = require("./token");
  79011. const types = {
  79012. 1: {
  79013. name: 'DATABASE',
  79014. event: 'databaseChange'
  79015. },
  79016. 2: {
  79017. name: 'LANGUAGE',
  79018. event: 'languageChange'
  79019. },
  79020. 3: {
  79021. name: 'CHARSET',
  79022. event: 'charsetChange'
  79023. },
  79024. 4: {
  79025. name: 'PACKET_SIZE',
  79026. event: 'packetSizeChange'
  79027. },
  79028. 7: {
  79029. name: 'SQL_COLLATION',
  79030. event: 'sqlCollationChange'
  79031. },
  79032. 8: {
  79033. name: 'BEGIN_TXN',
  79034. event: 'beginTransaction'
  79035. },
  79036. 9: {
  79037. name: 'COMMIT_TXN',
  79038. event: 'commitTransaction'
  79039. },
  79040. 10: {
  79041. name: 'ROLLBACK_TXN',
  79042. event: 'rollbackTransaction'
  79043. },
  79044. 13: {
  79045. name: 'DATABASE_MIRRORING_PARTNER',
  79046. event: 'partnerNode'
  79047. },
  79048. 17: {
  79049. name: 'TXN_ENDED'
  79050. },
  79051. 18: {
  79052. name: 'RESET_CONNECTION',
  79053. event: 'resetConnection'
  79054. },
  79055. 20: {
  79056. name: 'ROUTING_CHANGE',
  79057. event: 'routingChange'
  79058. }
  79059. };
  79060. function readNewAndOldValue(parser, length, type, callback) {
  79061. switch (type.name) {
  79062. case 'DATABASE':
  79063. case 'LANGUAGE':
  79064. case 'CHARSET':
  79065. case 'PACKET_SIZE':
  79066. case 'DATABASE_MIRRORING_PARTNER':
  79067. return parser.readBVarChar(newValue => {
  79068. parser.readBVarChar(oldValue => {
  79069. switch (type.name) {
  79070. case 'PACKET_SIZE':
  79071. return callback(new _token.PacketSizeEnvChangeToken(parseInt(newValue), parseInt(oldValue)));
  79072. case 'DATABASE':
  79073. return callback(new _token.DatabaseEnvChangeToken(newValue, oldValue));
  79074. case 'LANGUAGE':
  79075. return callback(new _token.LanguageEnvChangeToken(newValue, oldValue));
  79076. case 'CHARSET':
  79077. return callback(new _token.CharsetEnvChangeToken(newValue, oldValue));
  79078. case 'DATABASE_MIRRORING_PARTNER':
  79079. return callback(new _token.DatabaseMirroringPartnerEnvChangeToken(newValue, oldValue));
  79080. }
  79081. });
  79082. });
  79083. case 'SQL_COLLATION':
  79084. case 'BEGIN_TXN':
  79085. case 'COMMIT_TXN':
  79086. case 'ROLLBACK_TXN':
  79087. case 'RESET_CONNECTION':
  79088. return parser.readBVarByte(newValue => {
  79089. parser.readBVarByte(oldValue => {
  79090. switch (type.name) {
  79091. case 'SQL_COLLATION':
  79092. return callback(new _token.CollationChangeToken(newValue, oldValue));
  79093. case 'BEGIN_TXN':
  79094. return callback(new _token.BeginTransactionEnvChangeToken(newValue, oldValue));
  79095. case 'COMMIT_TXN':
  79096. return callback(new _token.CommitTransactionEnvChangeToken(newValue, oldValue));
  79097. case 'ROLLBACK_TXN':
  79098. return callback(new _token.RollbackTransactionEnvChangeToken(newValue, oldValue));
  79099. case 'RESET_CONNECTION':
  79100. return callback(new _token.ResetConnectionEnvChangeToken(newValue, oldValue));
  79101. }
  79102. });
  79103. });
  79104. case 'ROUTING_CHANGE':
  79105. return parser.readUInt16LE(valueLength => {
  79106. // Routing Change:
  79107. // Byte 1: Protocol (must be 0)
  79108. // Bytes 2-3 (USHORT): Port number
  79109. // Bytes 4-5 (USHORT): Length of server data in unicode (2byte chars)
  79110. // Bytes 6-*: Server name in unicode characters
  79111. parser.readBuffer(valueLength, routePacket => {
  79112. const protocol = routePacket.readUInt8(0);
  79113. if (protocol !== 0) {
  79114. return parser.emit('error', new Error('Unknown protocol byte in routing change event'));
  79115. }
  79116. const port = routePacket.readUInt16LE(1);
  79117. const serverLen = routePacket.readUInt16LE(3); // 2 bytes per char, starting at offset 5
  79118. const server = routePacket.toString('ucs2', 5, 5 + serverLen * 2);
  79119. const newValue = {
  79120. protocol: protocol,
  79121. port: port,
  79122. server: server
  79123. };
  79124. parser.readUInt16LE(oldValueLength => {
  79125. parser.readBuffer(oldValueLength, oldValue => {
  79126. callback(new _token.RoutingEnvChangeToken(newValue, oldValue));
  79127. });
  79128. });
  79129. });
  79130. });
  79131. default:
  79132. console.error('Tedious > Unsupported ENVCHANGE type ' + type.name); // skip unknown bytes
  79133. parser.readBuffer(length - 1, () => {
  79134. callback(undefined);
  79135. });
  79136. }
  79137. }
  79138. function envChangeParser(parser, _colMetadata, _options, callback) {
  79139. parser.readUInt16LE(length => {
  79140. parser.readUInt8(typeNumber => {
  79141. const type = types[typeNumber];
  79142. if (!type) {
  79143. console.error('Tedious > Unsupported ENVCHANGE type ' + typeNumber); // skip unknown bytes
  79144. return parser.readBuffer(length - 1, () => {
  79145. callback(undefined);
  79146. });
  79147. }
  79148. readNewAndOldValue(parser, length, type, token => {
  79149. callback(token);
  79150. });
  79151. });
  79152. });
  79153. }
  79154. var _default = envChangeParser;
  79155. exports.default = _default;
  79156. module.exports = envChangeParser;
  79157. },{"./token":492}],480:[function(require,module,exports){
  79158. "use strict";
  79159. Object.defineProperty(exports, "__esModule", {
  79160. value: true
  79161. });
  79162. exports.default = void 0;
  79163. var _token = require("./token");
  79164. const FEATURE_ID = {
  79165. SESSIONRECOVERY: 0x01,
  79166. FEDAUTH: 0x02,
  79167. COLUMNENCRYPTION: 0x04,
  79168. GLOBALTRANSACTIONS: 0x05,
  79169. AZURESQLSUPPORT: 0x08,
  79170. TERMINATOR: 0xFF
  79171. };
  79172. function featureExtAckParser(parser, _colMetadata, _options, callback) {
  79173. let fedAuth;
  79174. function next() {
  79175. parser.readUInt8(featureId => {
  79176. if (featureId === FEATURE_ID.TERMINATOR) {
  79177. return callback(new _token.FeatureExtAckToken(fedAuth));
  79178. }
  79179. parser.readUInt32LE(featureAckDataLen => {
  79180. parser.readBuffer(featureAckDataLen, featureData => {
  79181. if (featureId === FEATURE_ID.FEDAUTH) {
  79182. fedAuth = featureData;
  79183. }
  79184. next();
  79185. });
  79186. });
  79187. });
  79188. }
  79189. next();
  79190. }
  79191. var _default = featureExtAckParser;
  79192. exports.default = _default;
  79193. module.exports = featureExtAckParser;
  79194. },{"./token":492}],481:[function(require,module,exports){
  79195. "use strict";
  79196. Object.defineProperty(exports, "__esModule", {
  79197. value: true
  79198. });
  79199. exports.default = void 0;
  79200. var _token = require("./token");
  79201. const FEDAUTHINFOID = {
  79202. STSURL: 0x01,
  79203. SPN: 0x02
  79204. };
  79205. function fedAuthInfoParser(parser, _colMetadata, _options, callback) {
  79206. parser.readUInt32LE(tokenLength => {
  79207. parser.readBuffer(tokenLength, data => {
  79208. let spn, stsurl;
  79209. let offset = 0;
  79210. const countOfInfoIDs = data.readUInt32LE(offset);
  79211. offset += 4;
  79212. for (let i = 0; i < countOfInfoIDs; i++) {
  79213. const fedauthInfoID = data.readUInt8(offset);
  79214. offset += 1;
  79215. const fedAuthInfoDataLen = data.readUInt32LE(offset);
  79216. offset += 4;
  79217. const fedAuthInfoDataOffset = data.readUInt32LE(offset);
  79218. offset += 4;
  79219. switch (fedauthInfoID) {
  79220. case FEDAUTHINFOID.SPN:
  79221. spn = data.toString('ucs2', fedAuthInfoDataOffset, fedAuthInfoDataOffset + fedAuthInfoDataLen);
  79222. break;
  79223. case FEDAUTHINFOID.STSURL:
  79224. stsurl = data.toString('ucs2', fedAuthInfoDataOffset, fedAuthInfoDataOffset + fedAuthInfoDataLen);
  79225. break;
  79226. // ignoring unknown fedauthinfo options
  79227. default:
  79228. break;
  79229. }
  79230. }
  79231. callback(new _token.FedAuthInfoToken(spn, stsurl));
  79232. });
  79233. });
  79234. }
  79235. var _default = fedAuthInfoParser;
  79236. exports.default = _default;
  79237. module.exports = fedAuthInfoParser;
  79238. },{"./token":492}],482:[function(require,module,exports){
  79239. "use strict";
  79240. Object.defineProperty(exports, "__esModule", {
  79241. value: true
  79242. });
  79243. exports.infoParser = infoParser;
  79244. exports.errorParser = errorParser;
  79245. var _token = require("./token");
  79246. function parseToken(parser, options, callback) {
  79247. // length
  79248. parser.readUInt16LE(() => {
  79249. parser.readUInt32LE(number => {
  79250. parser.readUInt8(state => {
  79251. parser.readUInt8(clazz => {
  79252. parser.readUsVarChar(message => {
  79253. parser.readBVarChar(serverName => {
  79254. parser.readBVarChar(procName => {
  79255. (options.tdsVersion < '7_2' ? parser.readUInt16LE : parser.readUInt32LE).call(parser, lineNumber => {
  79256. callback({
  79257. 'number': number,
  79258. 'state': state,
  79259. 'class': clazz,
  79260. 'message': message,
  79261. 'serverName': serverName,
  79262. 'procName': procName,
  79263. 'lineNumber': lineNumber
  79264. });
  79265. });
  79266. });
  79267. });
  79268. });
  79269. });
  79270. });
  79271. });
  79272. });
  79273. }
  79274. function infoParser(parser, _colMetadata, options, callback) {
  79275. parseToken(parser, options, data => {
  79276. callback(new _token.InfoMessageToken(data));
  79277. });
  79278. }
  79279. function errorParser(parser, _colMetadata, options, callback) {
  79280. parseToken(parser, options, data => {
  79281. callback(new _token.ErrorMessageToken(data));
  79282. });
  79283. }
  79284. },{"./token":492}],483:[function(require,module,exports){
  79285. "use strict";
  79286. Object.defineProperty(exports, "__esModule", {
  79287. value: true
  79288. });
  79289. exports.default = void 0;
  79290. var _token = require("./token");
  79291. var _tdsVersions = require("../tds-versions");
  79292. const interfaceTypes = {
  79293. 0: 'SQL_DFLT',
  79294. 1: 'SQL_TSQL'
  79295. };
  79296. function loginAckParser(parser, _colMetadata, _options, callback) {
  79297. // length
  79298. parser.readUInt16LE(() => {
  79299. parser.readUInt8(interfaceNumber => {
  79300. const interfaceType = interfaceTypes[interfaceNumber];
  79301. parser.readUInt32BE(tdsVersionNumber => {
  79302. const tdsVersion = _tdsVersions.versionsByValue[tdsVersionNumber];
  79303. parser.readBVarChar(progName => {
  79304. parser.readUInt8(major => {
  79305. parser.readUInt8(minor => {
  79306. parser.readUInt8(buildNumHi => {
  79307. parser.readUInt8(buildNumLow => {
  79308. callback(new _token.LoginAckToken({
  79309. interface: interfaceType,
  79310. tdsVersion: tdsVersion,
  79311. progName: progName,
  79312. progVersion: {
  79313. major: major,
  79314. minor: minor,
  79315. buildNumHi: buildNumHi,
  79316. buildNumLow: buildNumLow
  79317. }
  79318. }));
  79319. });
  79320. });
  79321. });
  79322. });
  79323. });
  79324. });
  79325. });
  79326. });
  79327. }
  79328. var _default = loginAckParser;
  79329. exports.default = _default;
  79330. module.exports = loginAckParser;
  79331. },{"../tds-versions":475,"./token":492}],484:[function(require,module,exports){
  79332. "use strict";
  79333. Object.defineProperty(exports, "__esModule", {
  79334. value: true
  79335. });
  79336. exports.default = void 0;
  79337. var _token = require("./token");
  79338. var _valueParser = _interopRequireDefault(require("../value-parser"));
  79339. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  79340. // s2.2.7.13 (introduced in TDS 7.3.B)
  79341. function nullHandler(_parser, _columnMetadata, _options, callback) {
  79342. callback(null);
  79343. }
  79344. function nbcRowParser(parser, columnsMetaData, options, callback) {
  79345. const length = Math.ceil(columnsMetaData.length / 8);
  79346. parser.readBuffer(length, bytes => {
  79347. const bitmap = [];
  79348. for (let i = 0, len = bytes.length; i < len; i++) {
  79349. const byte = bytes[i];
  79350. for (let j = 0; j <= 7; j++) {
  79351. bitmap.push(byte & 1 << j ? true : false);
  79352. }
  79353. }
  79354. const columns = [];
  79355. const len = columnsMetaData.length;
  79356. let i = 0;
  79357. function next(done) {
  79358. if (i === len) {
  79359. return done();
  79360. }
  79361. const columnMetaData = columnsMetaData[i];
  79362. (bitmap[i] ? nullHandler : _valueParser.default)(parser, columnMetaData, options, value => {
  79363. columns.push({
  79364. value: value,
  79365. metadata: columnMetaData
  79366. });
  79367. i++;
  79368. next(done);
  79369. });
  79370. }
  79371. next(() => {
  79372. if (options.useColumnNames) {
  79373. const columnsMap = {};
  79374. columns.forEach(column => {
  79375. const colName = column.metadata.colName;
  79376. if (columnsMap[colName] == null) {
  79377. columnsMap[colName] = column;
  79378. }
  79379. });
  79380. callback(new _token.NBCRowToken(columnsMap));
  79381. } else {
  79382. callback(new _token.NBCRowToken(columns));
  79383. }
  79384. });
  79385. });
  79386. }
  79387. var _default = nbcRowParser;
  79388. exports.default = _default;
  79389. module.exports = nbcRowParser;
  79390. },{"../value-parser":496,"./token":492}],485:[function(require,module,exports){
  79391. "use strict";
  79392. Object.defineProperty(exports, "__esModule", {
  79393. value: true
  79394. });
  79395. exports.default = void 0;
  79396. var _token = require("./token");
  79397. // s2.2.7.14
  79398. function orderParser(parser, _colMetadata, _options, callback) {
  79399. parser.readUInt16LE(length => {
  79400. const columnCount = length / 2;
  79401. const orderColumns = [];
  79402. let i = 0;
  79403. function next(done) {
  79404. if (i === columnCount) {
  79405. return done();
  79406. }
  79407. parser.readUInt16LE(column => {
  79408. orderColumns.push(column);
  79409. i++;
  79410. next(done);
  79411. });
  79412. }
  79413. next(() => {
  79414. callback(new _token.OrderToken(orderColumns));
  79415. });
  79416. });
  79417. }
  79418. var _default = orderParser;
  79419. exports.default = _default;
  79420. module.exports = orderParser;
  79421. },{"./token":492}],486:[function(require,module,exports){
  79422. "use strict";
  79423. Object.defineProperty(exports, "__esModule", {
  79424. value: true
  79425. });
  79426. exports.default = void 0;
  79427. var _token = require("./token");
  79428. // s2.2.7.16
  79429. function returnStatusParser(parser, _colMetadata, _options, callback) {
  79430. parser.readInt32LE(value => {
  79431. callback(new _token.ReturnStatusToken(value));
  79432. });
  79433. }
  79434. var _default = returnStatusParser;
  79435. exports.default = _default;
  79436. module.exports = returnStatusParser;
  79437. },{"./token":492}],487:[function(require,module,exports){
  79438. "use strict";
  79439. Object.defineProperty(exports, "__esModule", {
  79440. value: true
  79441. });
  79442. exports.default = void 0;
  79443. var _token = require("./token");
  79444. var _metadataParser = _interopRequireDefault(require("../metadata-parser"));
  79445. var _valueParser = _interopRequireDefault(require("../value-parser"));
  79446. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  79447. // s2.2.7.16
  79448. function returnParser(parser, _colMetadata, options, callback) {
  79449. parser.readUInt16LE(paramOrdinal => {
  79450. parser.readBVarChar(paramName => {
  79451. if (paramName.charAt(0) === '@') {
  79452. paramName = paramName.slice(1);
  79453. } // status
  79454. parser.readUInt8(() => {
  79455. (0, _metadataParser.default)(parser, options, metadata => {
  79456. (0, _valueParser.default)(parser, metadata, options, value => {
  79457. callback(new _token.ReturnValueToken({
  79458. paramOrdinal: paramOrdinal,
  79459. paramName: paramName,
  79460. metadata: metadata,
  79461. value: value
  79462. }));
  79463. });
  79464. });
  79465. });
  79466. });
  79467. });
  79468. }
  79469. var _default = returnParser;
  79470. exports.default = _default;
  79471. module.exports = returnParser;
  79472. },{"../metadata-parser":465,"../value-parser":496,"./token":492}],488:[function(require,module,exports){
  79473. "use strict";
  79474. Object.defineProperty(exports, "__esModule", {
  79475. value: true
  79476. });
  79477. exports.default = void 0;
  79478. var _token = require("./token");
  79479. var _valueParser = _interopRequireDefault(require("../value-parser"));
  79480. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  79481. // s2.2.7.17
  79482. function rowParser(parser, colMetadata, options, callback) {
  79483. const columns = [];
  79484. const len = colMetadata.length;
  79485. let i = 0;
  79486. function next(done) {
  79487. if (i === len) {
  79488. return done();
  79489. }
  79490. const columnMetaData = colMetadata[i];
  79491. (0, _valueParser.default)(parser, columnMetaData, options, value => {
  79492. columns.push({
  79493. value: value,
  79494. metadata: columnMetaData
  79495. });
  79496. i++;
  79497. next(done);
  79498. });
  79499. }
  79500. next(() => {
  79501. if (options.useColumnNames) {
  79502. const columnsMap = {};
  79503. columns.forEach(column => {
  79504. const colName = column.metadata.colName;
  79505. if (columnsMap[colName] == null) {
  79506. columnsMap[colName] = column;
  79507. }
  79508. });
  79509. callback(new _token.RowToken(columnsMap));
  79510. } else {
  79511. callback(new _token.RowToken(columns));
  79512. }
  79513. });
  79514. }
  79515. var _default = rowParser;
  79516. exports.default = _default;
  79517. module.exports = rowParser;
  79518. },{"../value-parser":496,"./token":492}],489:[function(require,module,exports){
  79519. "use strict";
  79520. Object.defineProperty(exports, "__esModule", {
  79521. value: true
  79522. });
  79523. exports.default = void 0;
  79524. var _token = require("./token");
  79525. function parseChallenge(buffer) {
  79526. const challenge = {};
  79527. challenge.magic = buffer.slice(0, 8).toString('utf8');
  79528. challenge.type = buffer.readInt32LE(8);
  79529. challenge.domainLen = buffer.readInt16LE(12);
  79530. challenge.domainMax = buffer.readInt16LE(14);
  79531. challenge.domainOffset = buffer.readInt32LE(16);
  79532. challenge.flags = buffer.readInt32LE(20);
  79533. challenge.nonce = buffer.slice(24, 32);
  79534. challenge.zeroes = buffer.slice(32, 40);
  79535. challenge.targetLen = buffer.readInt16LE(40);
  79536. challenge.targetMax = buffer.readInt16LE(42);
  79537. challenge.targetOffset = buffer.readInt32LE(44);
  79538. challenge.oddData = buffer.slice(48, 56);
  79539. challenge.domain = buffer.slice(56, 56 + challenge.domainLen).toString('ucs2');
  79540. challenge.target = buffer.slice(56 + challenge.domainLen, 56 + challenge.domainLen + challenge.targetLen);
  79541. return challenge;
  79542. }
  79543. function sspiParser(parser, _colMetadata, _options, callback) {
  79544. parser.readUsVarByte(buffer => {
  79545. callback(new _token.SSPIToken(parseChallenge(buffer), buffer));
  79546. });
  79547. }
  79548. var _default = sspiParser;
  79549. exports.default = _default;
  79550. module.exports = sspiParser;
  79551. },{"./token":492}],490:[function(require,module,exports){
  79552. (function (Buffer){(function (){
  79553. "use strict";
  79554. Object.defineProperty(exports, "__esModule", {
  79555. value: true
  79556. });
  79557. exports.default = void 0;
  79558. var _jsbi = _interopRequireDefault(require("jsbi"));
  79559. var _readableStream = require("readable-stream");
  79560. var _token = require("./token");
  79561. var _colmetadataTokenParser = _interopRequireDefault(require("./colmetadata-token-parser"));
  79562. var _doneTokenParser = require("./done-token-parser");
  79563. var _envChangeTokenParser = _interopRequireDefault(require("./env-change-token-parser"));
  79564. var _infoerrorTokenParser = require("./infoerror-token-parser");
  79565. var _fedauthInfoParser = _interopRequireDefault(require("./fedauth-info-parser"));
  79566. var _featureExtAckParser = _interopRequireDefault(require("./feature-ext-ack-parser"));
  79567. var _loginackTokenParser = _interopRequireDefault(require("./loginack-token-parser"));
  79568. var _orderTokenParser = _interopRequireDefault(require("./order-token-parser"));
  79569. var _returnstatusTokenParser = _interopRequireDefault(require("./returnstatus-token-parser"));
  79570. var _returnvalueTokenParser = _interopRequireDefault(require("./returnvalue-token-parser"));
  79571. var _rowTokenParser = _interopRequireDefault(require("./row-token-parser"));
  79572. var _nbcrowTokenParser = _interopRequireDefault(require("./nbcrow-token-parser"));
  79573. var _sspiTokenParser = _interopRequireDefault(require("./sspi-token-parser"));
  79574. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  79575. const tokenParsers = {
  79576. [_token.TYPE.COLMETADATA]: _colmetadataTokenParser.default,
  79577. [_token.TYPE.DONE]: _doneTokenParser.doneParser,
  79578. [_token.TYPE.DONEINPROC]: _doneTokenParser.doneInProcParser,
  79579. [_token.TYPE.DONEPROC]: _doneTokenParser.doneProcParser,
  79580. [_token.TYPE.ENVCHANGE]: _envChangeTokenParser.default,
  79581. [_token.TYPE.ERROR]: _infoerrorTokenParser.errorParser,
  79582. [_token.TYPE.FEDAUTHINFO]: _fedauthInfoParser.default,
  79583. [_token.TYPE.FEATUREEXTACK]: _featureExtAckParser.default,
  79584. [_token.TYPE.INFO]: _infoerrorTokenParser.infoParser,
  79585. [_token.TYPE.LOGINACK]: _loginackTokenParser.default,
  79586. [_token.TYPE.ORDER]: _orderTokenParser.default,
  79587. [_token.TYPE.RETURNSTATUS]: _returnstatusTokenParser.default,
  79588. [_token.TYPE.RETURNVALUE]: _returnvalueTokenParser.default,
  79589. [_token.TYPE.ROW]: _rowTokenParser.default,
  79590. [_token.TYPE.NBCROW]: _nbcrowTokenParser.default,
  79591. [_token.TYPE.SSPI]: _sspiTokenParser.default
  79592. };
  79593. class EndOfMessageMarker {}
  79594. class Parser extends _readableStream.Transform {
  79595. constructor(debug, colMetadata, options) {
  79596. super({
  79597. objectMode: true
  79598. });
  79599. this.debug = void 0;
  79600. this.colMetadata = void 0;
  79601. this.options = void 0;
  79602. this.endOfMessageMarker = void 0;
  79603. this.buffer = void 0;
  79604. this.position = void 0;
  79605. this.suspended = void 0;
  79606. this.next = void 0;
  79607. this.debug = debug;
  79608. this.colMetadata = colMetadata;
  79609. this.options = options;
  79610. this.endOfMessageMarker = new EndOfMessageMarker();
  79611. this.buffer = Buffer.alloc(0);
  79612. this.position = 0;
  79613. this.suspended = false;
  79614. this.next = undefined;
  79615. }
  79616. _transform(input, _encoding, done) {
  79617. if (input instanceof EndOfMessageMarker) {
  79618. return done(undefined, new _token.EndOfMessageToken());
  79619. }
  79620. if (this.position === this.buffer.length) {
  79621. this.buffer = input;
  79622. } else {
  79623. this.buffer = Buffer.concat([this.buffer.slice(this.position), input]);
  79624. }
  79625. this.position = 0;
  79626. if (this.suspended) {
  79627. // Unsuspend and continue from where ever we left off.
  79628. this.suspended = false;
  79629. const next = this.next;
  79630. next();
  79631. } // If we're no longer suspended, parse new tokens
  79632. if (!this.suspended) {
  79633. // Start the parser
  79634. this.parseTokens();
  79635. }
  79636. done();
  79637. }
  79638. parseTokens() {
  79639. const doneParsing = token => {
  79640. if (token) {
  79641. if (token instanceof _token.ColMetadataToken) {
  79642. this.colMetadata = token.columns;
  79643. }
  79644. this.push(token);
  79645. }
  79646. };
  79647. while (!this.suspended && this.position + 1 <= this.buffer.length) {
  79648. const type = this.buffer.readUInt8(this.position);
  79649. this.position += 1;
  79650. if (tokenParsers[type]) {
  79651. tokenParsers[type](this, this.colMetadata, this.options, doneParsing);
  79652. } else {
  79653. this.emit('error', new Error('Unknown type: ' + type));
  79654. }
  79655. }
  79656. }
  79657. suspend(next) {
  79658. this.suspended = true;
  79659. this.next = next;
  79660. }
  79661. awaitData(length, callback) {
  79662. if (this.position + length <= this.buffer.length) {
  79663. callback();
  79664. } else {
  79665. this.suspend(() => {
  79666. this.awaitData(length, callback);
  79667. });
  79668. }
  79669. }
  79670. readInt8(callback) {
  79671. this.awaitData(1, () => {
  79672. const data = this.buffer.readInt8(this.position);
  79673. this.position += 1;
  79674. callback(data);
  79675. });
  79676. }
  79677. readUInt8(callback) {
  79678. this.awaitData(1, () => {
  79679. const data = this.buffer.readUInt8(this.position);
  79680. this.position += 1;
  79681. callback(data);
  79682. });
  79683. }
  79684. readInt16LE(callback) {
  79685. this.awaitData(2, () => {
  79686. const data = this.buffer.readInt16LE(this.position);
  79687. this.position += 2;
  79688. callback(data);
  79689. });
  79690. }
  79691. readInt16BE(callback) {
  79692. this.awaitData(2, () => {
  79693. const data = this.buffer.readInt16BE(this.position);
  79694. this.position += 2;
  79695. callback(data);
  79696. });
  79697. }
  79698. readUInt16LE(callback) {
  79699. this.awaitData(2, () => {
  79700. const data = this.buffer.readUInt16LE(this.position);
  79701. this.position += 2;
  79702. callback(data);
  79703. });
  79704. }
  79705. readUInt16BE(callback) {
  79706. this.awaitData(2, () => {
  79707. const data = this.buffer.readUInt16BE(this.position);
  79708. this.position += 2;
  79709. callback(data);
  79710. });
  79711. }
  79712. readInt32LE(callback) {
  79713. this.awaitData(4, () => {
  79714. const data = this.buffer.readInt32LE(this.position);
  79715. this.position += 4;
  79716. callback(data);
  79717. });
  79718. }
  79719. readInt32BE(callback) {
  79720. this.awaitData(4, () => {
  79721. const data = this.buffer.readInt32BE(this.position);
  79722. this.position += 4;
  79723. callback(data);
  79724. });
  79725. }
  79726. readUInt32LE(callback) {
  79727. this.awaitData(4, () => {
  79728. const data = this.buffer.readUInt32LE(this.position);
  79729. this.position += 4;
  79730. callback(data);
  79731. });
  79732. }
  79733. readUInt32BE(callback) {
  79734. this.awaitData(4, () => {
  79735. const data = this.buffer.readUInt32BE(this.position);
  79736. this.position += 4;
  79737. callback(data);
  79738. });
  79739. }
  79740. readBigInt64LE(callback) {
  79741. this.awaitData(8, () => {
  79742. const result = _jsbi.default.add(_jsbi.default.leftShift(_jsbi.default.BigInt(this.buffer[this.position + 4] + this.buffer[this.position + 5] * Math.pow(2, 8) + this.buffer[this.position + 6] * Math.pow(2, 16) + (this.buffer[this.position + 7] << 24) // Overflow
  79743. ), _jsbi.default.BigInt(32)), _jsbi.default.BigInt(this.buffer[this.position] + this.buffer[this.position + 1] * Math.pow(2, 8) + this.buffer[this.position + 2] * Math.pow(2, 16) + this.buffer[this.position + 3] * Math.pow(2, 24)));
  79744. this.position += 8;
  79745. callback(result);
  79746. });
  79747. }
  79748. readInt64LE(callback) {
  79749. this.awaitData(8, () => {
  79750. const data = Math.pow(2, 32) * this.buffer.readInt32LE(this.position + 4) + ((this.buffer[this.position + 4] & 0x80) === 0x80 ? 1 : -1) * this.buffer.readUInt32LE(this.position);
  79751. this.position += 8;
  79752. callback(data);
  79753. });
  79754. }
  79755. readInt64BE(callback) {
  79756. this.awaitData(8, () => {
  79757. const data = Math.pow(2, 32) * this.buffer.readInt32BE(this.position) + ((this.buffer[this.position] & 0x80) === 0x80 ? 1 : -1) * this.buffer.readUInt32BE(this.position + 4);
  79758. this.position += 8;
  79759. callback(data);
  79760. });
  79761. }
  79762. readBigUInt64LE(callback) {
  79763. this.awaitData(8, () => {
  79764. const low = _jsbi.default.BigInt(this.buffer.readUInt32LE(this.position));
  79765. const high = _jsbi.default.BigInt(this.buffer.readUInt32LE(this.position + 4));
  79766. this.position += 8;
  79767. callback(_jsbi.default.add(low, _jsbi.default.leftShift(high, _jsbi.default.BigInt(32))));
  79768. });
  79769. }
  79770. readUInt64LE(callback) {
  79771. this.awaitData(8, () => {
  79772. const data = Math.pow(2, 32) * this.buffer.readUInt32LE(this.position + 4) + this.buffer.readUInt32LE(this.position);
  79773. this.position += 8;
  79774. callback(data);
  79775. });
  79776. }
  79777. readUInt64BE(callback) {
  79778. this.awaitData(8, () => {
  79779. const data = Math.pow(2, 32) * this.buffer.readUInt32BE(this.position) + this.buffer.readUInt32BE(this.position + 4);
  79780. this.position += 8;
  79781. callback(data);
  79782. });
  79783. }
  79784. readFloatLE(callback) {
  79785. this.awaitData(4, () => {
  79786. const data = this.buffer.readFloatLE(this.position);
  79787. this.position += 4;
  79788. callback(data);
  79789. });
  79790. }
  79791. readFloatBE(callback) {
  79792. this.awaitData(4, () => {
  79793. const data = this.buffer.readFloatBE(this.position);
  79794. this.position += 4;
  79795. callback(data);
  79796. });
  79797. }
  79798. readDoubleLE(callback) {
  79799. this.awaitData(8, () => {
  79800. const data = this.buffer.readDoubleLE(this.position);
  79801. this.position += 8;
  79802. callback(data);
  79803. });
  79804. }
  79805. readDoubleBE(callback) {
  79806. this.awaitData(8, () => {
  79807. const data = this.buffer.readDoubleBE(this.position);
  79808. this.position += 8;
  79809. callback(data);
  79810. });
  79811. }
  79812. readUInt24LE(callback) {
  79813. this.awaitData(3, () => {
  79814. const low = this.buffer.readUInt16LE(this.position);
  79815. const high = this.buffer.readUInt8(this.position + 2);
  79816. this.position += 3;
  79817. callback(low | high << 16);
  79818. });
  79819. }
  79820. readUInt40LE(callback) {
  79821. this.awaitData(5, () => {
  79822. const low = this.buffer.readUInt32LE(this.position);
  79823. const high = this.buffer.readUInt8(this.position + 4);
  79824. this.position += 5;
  79825. callback(0x100000000 * high + low);
  79826. });
  79827. }
  79828. readUNumeric64LE(callback) {
  79829. this.awaitData(8, () => {
  79830. const low = this.buffer.readUInt32LE(this.position);
  79831. const high = this.buffer.readUInt32LE(this.position + 4);
  79832. this.position += 8;
  79833. callback(0x100000000 * high + low);
  79834. });
  79835. }
  79836. readUNumeric96LE(callback) {
  79837. this.awaitData(12, () => {
  79838. const dword1 = this.buffer.readUInt32LE(this.position);
  79839. const dword2 = this.buffer.readUInt32LE(this.position + 4);
  79840. const dword3 = this.buffer.readUInt32LE(this.position + 8);
  79841. this.position += 12;
  79842. callback(dword1 + 0x100000000 * dword2 + 0x100000000 * 0x100000000 * dword3);
  79843. });
  79844. }
  79845. readUNumeric128LE(callback) {
  79846. this.awaitData(16, () => {
  79847. const dword1 = this.buffer.readUInt32LE(this.position);
  79848. const dword2 = this.buffer.readUInt32LE(this.position + 4);
  79849. const dword3 = this.buffer.readUInt32LE(this.position + 8);
  79850. const dword4 = this.buffer.readUInt32LE(this.position + 12);
  79851. this.position += 16;
  79852. callback(dword1 + 0x100000000 * dword2 + 0x100000000 * 0x100000000 * dword3 + 0x100000000 * 0x100000000 * 0x100000000 * dword4);
  79853. });
  79854. } // Variable length data
  79855. readBuffer(length, callback) {
  79856. this.awaitData(length, () => {
  79857. const data = this.buffer.slice(this.position, this.position + length);
  79858. this.position += length;
  79859. callback(data);
  79860. });
  79861. } // Read a Unicode String (BVARCHAR)
  79862. readBVarChar(callback) {
  79863. this.readUInt8(length => {
  79864. this.readBuffer(length * 2, data => {
  79865. callback(data.toString('ucs2'));
  79866. });
  79867. });
  79868. } // Read a Unicode String (USVARCHAR)
  79869. readUsVarChar(callback) {
  79870. this.readUInt16LE(length => {
  79871. this.readBuffer(length * 2, data => {
  79872. callback(data.toString('ucs2'));
  79873. });
  79874. });
  79875. } // Read binary data (BVARBYTE)
  79876. readBVarByte(callback) {
  79877. this.readUInt8(length => {
  79878. this.readBuffer(length, callback);
  79879. });
  79880. } // Read binary data (USVARBYTE)
  79881. readUsVarByte(callback) {
  79882. this.readUInt16LE(length => {
  79883. this.readBuffer(length, callback);
  79884. });
  79885. }
  79886. }
  79887. var _default = Parser;
  79888. exports.default = _default;
  79889. module.exports = Parser;
  79890. }).call(this)}).call(this,require("buffer").Buffer)
  79891. },{"./colmetadata-token-parser":477,"./done-token-parser":478,"./env-change-token-parser":479,"./feature-ext-ack-parser":480,"./fedauth-info-parser":481,"./infoerror-token-parser":482,"./loginack-token-parser":483,"./nbcrow-token-parser":484,"./order-token-parser":485,"./returnstatus-token-parser":486,"./returnvalue-token-parser":487,"./row-token-parser":488,"./sspi-token-parser":489,"./token":492,"buffer":193,"jsbi":327,"readable-stream":409}],491:[function(require,module,exports){
  79892. "use strict";
  79893. Object.defineProperty(exports, "__esModule", {
  79894. value: true
  79895. });
  79896. exports.Parser = void 0;
  79897. var _events = require("events");
  79898. var _streamParser = _interopRequireDefault(require("./stream-parser"));
  79899. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  79900. /*
  79901. Buffers are thrown at the parser (by calling addBuffer).
  79902. Tokens are parsed from the buffer until there are no more tokens in
  79903. the buffer, or there is just a partial token left.
  79904. If there is a partial token left over, then it is kept until another
  79905. buffer is added, which should contain the remainder of the partial
  79906. token, along with (perhaps) more tokens.
  79907. The partial token and the new buffer are concatenated, and the token
  79908. parsing resumes.
  79909. */
  79910. class Parser extends _events.EventEmitter {
  79911. constructor(debug, colMetadata, options) {
  79912. super();
  79913. this.debug = void 0;
  79914. this.colMetadata = void 0;
  79915. this.options = void 0;
  79916. this.parser = void 0;
  79917. this.debug = debug;
  79918. this.colMetadata = colMetadata;
  79919. this.options = options;
  79920. this.parser = new _streamParser.default(this.debug, this.colMetadata, this.options);
  79921. this.parser.on('data', token => {
  79922. if (token.event) {
  79923. this.emit(token.event, token);
  79924. }
  79925. });
  79926. this.parser.on('drain', () => {
  79927. this.emit('drain');
  79928. });
  79929. }
  79930. // Returns false to apply backpressure.
  79931. addBuffer(buffer) {
  79932. return this.parser.write(buffer);
  79933. } // Writes an end-of-message (EOM) marker into the parser transform input
  79934. // queue. StreamParser will emit a 'data' event with an 'endOfMessage'
  79935. // pseudo token when the EOM marker has passed through the transform stream.
  79936. // Returns false to apply backpressure.
  79937. addEndOfMessageMarker() {
  79938. return this.parser.write(this.parser.endOfMessageMarker);
  79939. }
  79940. isEnd() {
  79941. return this.parser.buffer.length === this.parser.position;
  79942. } // Temporarily suspends the token stream parser transform from emitting events.
  79943. pause() {
  79944. this.parser.pause();
  79945. } // Resumes the token stream parser transform.
  79946. resume() {
  79947. this.parser.resume();
  79948. }
  79949. }
  79950. exports.Parser = Parser;
  79951. },{"./stream-parser":490,"events":247}],492:[function(require,module,exports){
  79952. "use strict";
  79953. Object.defineProperty(exports, "__esModule", {
  79954. value: true
  79955. });
  79956. exports.EndOfMessageToken = exports.SSPIToken = exports.RowToken = exports.ReturnValueToken = exports.ReturnStatusToken = exports.OrderToken = exports.NBCRowToken = exports.LoginAckToken = exports.ErrorMessageToken = exports.InfoMessageToken = exports.FedAuthInfoToken = exports.FeatureExtAckToken = exports.RoutingEnvChangeToken = exports.CollationChangeToken = exports.ResetConnectionEnvChangeToken = exports.DatabaseMirroringPartnerEnvChangeToken = exports.RollbackTransactionEnvChangeToken = exports.CommitTransactionEnvChangeToken = exports.BeginTransactionEnvChangeToken = exports.PacketSizeEnvChangeToken = exports.CharsetEnvChangeToken = exports.LanguageEnvChangeToken = exports.DatabaseEnvChangeToken = exports.DoneProcToken = exports.DoneInProcToken = exports.DoneToken = exports.ColMetadataToken = exports.Token = exports.TYPE = void 0;
  79957. const TYPE = {
  79958. ALTMETADATA: 0x88,
  79959. ALTROW: 0xD3,
  79960. COLMETADATA: 0x81,
  79961. COLINFO: 0xA5,
  79962. DONE: 0xFD,
  79963. DONEPROC: 0xFE,
  79964. DONEINPROC: 0xFF,
  79965. ENVCHANGE: 0xE3,
  79966. ERROR: 0xAA,
  79967. FEATUREEXTACK: 0xAE,
  79968. FEDAUTHINFO: 0xEE,
  79969. INFO: 0xAB,
  79970. LOGINACK: 0xAD,
  79971. NBCROW: 0xD2,
  79972. OFFSET: 0x78,
  79973. ORDER: 0xA9,
  79974. RETURNSTATUS: 0x79,
  79975. RETURNVALUE: 0xAC,
  79976. ROW: 0xD1,
  79977. SSPI: 0xED,
  79978. TABNAME: 0xA4
  79979. };
  79980. exports.TYPE = TYPE;
  79981. class Token {
  79982. constructor(name, event) {
  79983. this.name = void 0;
  79984. this.event = void 0;
  79985. this.name = name;
  79986. this.event = event;
  79987. }
  79988. }
  79989. exports.Token = Token;
  79990. class ColMetadataToken extends Token {
  79991. constructor(columns) {
  79992. super('COLMETADATA', 'columnMetadata');
  79993. this.columns = void 0;
  79994. this.columns = columns;
  79995. }
  79996. }
  79997. exports.ColMetadataToken = ColMetadataToken;
  79998. class DoneToken extends Token {
  79999. constructor({
  80000. more,
  80001. sqlError,
  80002. attention,
  80003. serverError,
  80004. rowCount,
  80005. curCmd
  80006. }) {
  80007. super('DONE', 'done');
  80008. this.more = void 0;
  80009. this.sqlError = void 0;
  80010. this.attention = void 0;
  80011. this.serverError = void 0;
  80012. this.rowCount = void 0;
  80013. this.curCmd = void 0;
  80014. this.more = more;
  80015. this.sqlError = sqlError;
  80016. this.attention = attention;
  80017. this.serverError = serverError;
  80018. this.rowCount = rowCount;
  80019. this.curCmd = curCmd;
  80020. }
  80021. }
  80022. exports.DoneToken = DoneToken;
  80023. class DoneInProcToken extends Token {
  80024. constructor({
  80025. more,
  80026. sqlError,
  80027. attention,
  80028. serverError,
  80029. rowCount,
  80030. curCmd
  80031. }) {
  80032. super('DONEINPROC', 'doneInProc');
  80033. this.more = void 0;
  80034. this.sqlError = void 0;
  80035. this.attention = void 0;
  80036. this.serverError = void 0;
  80037. this.rowCount = void 0;
  80038. this.curCmd = void 0;
  80039. this.more = more;
  80040. this.sqlError = sqlError;
  80041. this.attention = attention;
  80042. this.serverError = serverError;
  80043. this.rowCount = rowCount;
  80044. this.curCmd = curCmd;
  80045. }
  80046. }
  80047. exports.DoneInProcToken = DoneInProcToken;
  80048. class DoneProcToken extends Token {
  80049. constructor({
  80050. more,
  80051. sqlError,
  80052. attention,
  80053. serverError,
  80054. rowCount,
  80055. curCmd
  80056. }) {
  80057. super('DONEPROC', 'doneProc');
  80058. this.more = void 0;
  80059. this.sqlError = void 0;
  80060. this.attention = void 0;
  80061. this.serverError = void 0;
  80062. this.rowCount = void 0;
  80063. this.curCmd = void 0;
  80064. this.more = more;
  80065. this.sqlError = sqlError;
  80066. this.attention = attention;
  80067. this.serverError = serverError;
  80068. this.rowCount = rowCount;
  80069. this.curCmd = curCmd;
  80070. }
  80071. }
  80072. exports.DoneProcToken = DoneProcToken;
  80073. class DatabaseEnvChangeToken extends Token {
  80074. constructor(newValue, oldValue) {
  80075. super('ENVCHANGE', 'databaseChange');
  80076. this.type = void 0;
  80077. this.newValue = void 0;
  80078. this.oldValue = void 0;
  80079. this.type = 'DATABASE';
  80080. this.newValue = newValue;
  80081. this.oldValue = oldValue;
  80082. }
  80083. }
  80084. exports.DatabaseEnvChangeToken = DatabaseEnvChangeToken;
  80085. class LanguageEnvChangeToken extends Token {
  80086. constructor(newValue, oldValue) {
  80087. super('ENVCHANGE', 'languageChange');
  80088. this.type = void 0;
  80089. this.newValue = void 0;
  80090. this.oldValue = void 0;
  80091. this.type = 'LANGUAGE';
  80092. this.newValue = newValue;
  80093. this.oldValue = oldValue;
  80094. }
  80095. }
  80096. exports.LanguageEnvChangeToken = LanguageEnvChangeToken;
  80097. class CharsetEnvChangeToken extends Token {
  80098. constructor(newValue, oldValue) {
  80099. super('ENVCHANGE', 'charsetChange');
  80100. this.type = void 0;
  80101. this.newValue = void 0;
  80102. this.oldValue = void 0;
  80103. this.type = 'CHARSET';
  80104. this.newValue = newValue;
  80105. this.oldValue = oldValue;
  80106. }
  80107. }
  80108. exports.CharsetEnvChangeToken = CharsetEnvChangeToken;
  80109. class PacketSizeEnvChangeToken extends Token {
  80110. constructor(newValue, oldValue) {
  80111. super('ENVCHANGE', 'packetSizeChange');
  80112. this.type = void 0;
  80113. this.newValue = void 0;
  80114. this.oldValue = void 0;
  80115. this.type = 'PACKET_SIZE';
  80116. this.newValue = newValue;
  80117. this.oldValue = oldValue;
  80118. }
  80119. }
  80120. exports.PacketSizeEnvChangeToken = PacketSizeEnvChangeToken;
  80121. class BeginTransactionEnvChangeToken extends Token {
  80122. constructor(newValue, oldValue) {
  80123. super('ENVCHANGE', 'beginTransaction');
  80124. this.type = void 0;
  80125. this.newValue = void 0;
  80126. this.oldValue = void 0;
  80127. this.name = 'ENVCHANGE';
  80128. this.event = 'beginTransaction';
  80129. this.type = 'BEGIN_TXN';
  80130. this.newValue = newValue;
  80131. this.oldValue = oldValue;
  80132. }
  80133. }
  80134. exports.BeginTransactionEnvChangeToken = BeginTransactionEnvChangeToken;
  80135. class CommitTransactionEnvChangeToken extends Token {
  80136. constructor(newValue, oldValue) {
  80137. super('ENVCHANGE', 'commitTransaction');
  80138. this.type = void 0;
  80139. this.newValue = void 0;
  80140. this.oldValue = void 0;
  80141. this.type = 'COMMIT_TXN';
  80142. this.newValue = newValue;
  80143. this.oldValue = oldValue;
  80144. }
  80145. }
  80146. exports.CommitTransactionEnvChangeToken = CommitTransactionEnvChangeToken;
  80147. class RollbackTransactionEnvChangeToken extends Token {
  80148. constructor(newValue, oldValue) {
  80149. super('ENVCHANGE', 'rollbackTransaction');
  80150. this.type = void 0;
  80151. this.oldValue = void 0;
  80152. this.newValue = void 0;
  80153. this.type = 'ROLLBACK_TXN';
  80154. this.newValue = newValue;
  80155. this.oldValue = oldValue;
  80156. }
  80157. }
  80158. exports.RollbackTransactionEnvChangeToken = RollbackTransactionEnvChangeToken;
  80159. class DatabaseMirroringPartnerEnvChangeToken extends Token {
  80160. constructor(newValue, oldValue) {
  80161. super('ENVCHANGE', 'partnerNode');
  80162. this.type = void 0;
  80163. this.oldValue = void 0;
  80164. this.newValue = void 0;
  80165. this.name = 'ENVCHANGE';
  80166. this.event = 'partnerNode';
  80167. this.type = 'DATABASE_MIRRORING_PARTNER';
  80168. this.newValue = newValue;
  80169. this.oldValue = oldValue;
  80170. }
  80171. }
  80172. exports.DatabaseMirroringPartnerEnvChangeToken = DatabaseMirroringPartnerEnvChangeToken;
  80173. class ResetConnectionEnvChangeToken extends Token {
  80174. constructor(newValue, oldValue) {
  80175. super('ENVCHANGE', 'resetConnection');
  80176. this.type = void 0;
  80177. this.oldValue = void 0;
  80178. this.newValue = void 0;
  80179. this.type = 'RESET_CONNECTION';
  80180. this.newValue = newValue;
  80181. this.oldValue = oldValue;
  80182. }
  80183. }
  80184. exports.ResetConnectionEnvChangeToken = ResetConnectionEnvChangeToken;
  80185. class CollationChangeToken extends Token {
  80186. constructor(newValue, oldValue) {
  80187. super('ENVCHANGE', 'sqlCollationChange');
  80188. this.type = void 0;
  80189. this.oldValue = void 0;
  80190. this.newValue = void 0;
  80191. this.type = 'SQL_COLLATION';
  80192. this.newValue = newValue;
  80193. this.oldValue = oldValue;
  80194. }
  80195. }
  80196. exports.CollationChangeToken = CollationChangeToken;
  80197. class RoutingEnvChangeToken extends Token {
  80198. constructor(newValue, oldValue) {
  80199. super('ENVCHANGE', 'routingChange');
  80200. this.type = void 0;
  80201. this.newValue = void 0;
  80202. this.oldValue = void 0;
  80203. this.type = 'ROUTING_CHANGE';
  80204. this.newValue = newValue;
  80205. this.oldValue = oldValue;
  80206. }
  80207. }
  80208. exports.RoutingEnvChangeToken = RoutingEnvChangeToken;
  80209. class FeatureExtAckToken extends Token {
  80210. constructor(fedAuth) {
  80211. super('FEATUREEXTACK', 'featureExtAck');
  80212. this.fedAuth = void 0;
  80213. this.fedAuth = fedAuth;
  80214. }
  80215. }
  80216. exports.FeatureExtAckToken = FeatureExtAckToken;
  80217. class FedAuthInfoToken extends Token {
  80218. constructor(spn, stsurl) {
  80219. super('FEDAUTHINFO', 'fedAuthInfo');
  80220. this.spn = void 0;
  80221. this.stsurl = void 0;
  80222. this.spn = spn;
  80223. this.stsurl = stsurl;
  80224. }
  80225. }
  80226. exports.FedAuthInfoToken = FedAuthInfoToken;
  80227. class InfoMessageToken extends Token {
  80228. constructor({
  80229. number,
  80230. state,
  80231. class: clazz,
  80232. message,
  80233. serverName,
  80234. procName,
  80235. lineNumber
  80236. }) {
  80237. super('INFO', 'infoMessage');
  80238. this.number = void 0;
  80239. this.state = void 0;
  80240. this.class = void 0;
  80241. this.message = void 0;
  80242. this.serverName = void 0;
  80243. this.procName = void 0;
  80244. this.lineNumber = void 0;
  80245. this.number = number;
  80246. this.state = state;
  80247. this.class = clazz;
  80248. this.message = message;
  80249. this.serverName = serverName;
  80250. this.procName = procName;
  80251. this.lineNumber = lineNumber;
  80252. }
  80253. }
  80254. exports.InfoMessageToken = InfoMessageToken;
  80255. class ErrorMessageToken extends Token {
  80256. constructor({
  80257. number,
  80258. state,
  80259. class: clazz,
  80260. message,
  80261. serverName,
  80262. procName,
  80263. lineNumber
  80264. }) {
  80265. super('ERROR', 'errorMessage');
  80266. this.number = void 0;
  80267. this.state = void 0;
  80268. this.class = void 0;
  80269. this.message = void 0;
  80270. this.serverName = void 0;
  80271. this.procName = void 0;
  80272. this.lineNumber = void 0;
  80273. this.number = number;
  80274. this.state = state;
  80275. this.class = clazz;
  80276. this.message = message;
  80277. this.serverName = serverName;
  80278. this.procName = procName;
  80279. this.lineNumber = lineNumber;
  80280. }
  80281. }
  80282. exports.ErrorMessageToken = ErrorMessageToken;
  80283. class LoginAckToken extends Token {
  80284. constructor({
  80285. interface: interfaze,
  80286. tdsVersion,
  80287. progName,
  80288. progVersion
  80289. }) {
  80290. super('LOGINACK', 'loginack');
  80291. this.interface = void 0;
  80292. this.tdsVersion = void 0;
  80293. this.progName = void 0;
  80294. this.progVersion = void 0;
  80295. this.interface = interfaze;
  80296. this.tdsVersion = tdsVersion;
  80297. this.progName = progName;
  80298. this.progVersion = progVersion;
  80299. }
  80300. }
  80301. exports.LoginAckToken = LoginAckToken;
  80302. class NBCRowToken extends Token {
  80303. constructor(columns) {
  80304. super('NBCROW', 'row');
  80305. this.columns = void 0;
  80306. this.columns = columns;
  80307. }
  80308. }
  80309. exports.NBCRowToken = NBCRowToken;
  80310. class OrderToken extends Token {
  80311. constructor(orderColumns) {
  80312. super('ORDER', 'order');
  80313. this.orderColumns = void 0;
  80314. this.orderColumns = orderColumns;
  80315. }
  80316. }
  80317. exports.OrderToken = OrderToken;
  80318. class ReturnStatusToken extends Token {
  80319. constructor(value) {
  80320. super('RETURNSTATUS', 'returnStatus');
  80321. this.value = void 0;
  80322. this.value = value;
  80323. }
  80324. }
  80325. exports.ReturnStatusToken = ReturnStatusToken;
  80326. class ReturnValueToken extends Token {
  80327. constructor({
  80328. paramOrdinal,
  80329. paramName,
  80330. metadata,
  80331. value
  80332. }) {
  80333. super('RETURNVALUE', 'returnValue');
  80334. this.paramOrdinal = void 0;
  80335. this.paramName = void 0;
  80336. this.metadata = void 0;
  80337. this.value = void 0;
  80338. this.paramOrdinal = paramOrdinal;
  80339. this.paramName = paramName;
  80340. this.metadata = metadata;
  80341. this.value = value;
  80342. }
  80343. }
  80344. exports.ReturnValueToken = ReturnValueToken;
  80345. class RowToken extends Token {
  80346. constructor(columns) {
  80347. super('ROW', 'row');
  80348. this.columns = void 0;
  80349. this.columns = columns;
  80350. }
  80351. }
  80352. exports.RowToken = RowToken;
  80353. class SSPIToken extends Token {
  80354. constructor(ntlmpacket, ntlmpacketBuffer) {
  80355. super('SSPICHALLENGE', 'sspichallenge');
  80356. this.ntlmpacket = void 0;
  80357. this.ntlmpacketBuffer = void 0;
  80358. this.ntlmpacket = ntlmpacket;
  80359. this.ntlmpacketBuffer = ntlmpacketBuffer;
  80360. }
  80361. }
  80362. exports.SSPIToken = SSPIToken;
  80363. class EndOfMessageToken extends Token {
  80364. constructor() {
  80365. super('EOM', 'endOfMessage');
  80366. }
  80367. }
  80368. exports.EndOfMessageToken = EndOfMessageToken;
  80369. },{}],493:[function(require,module,exports){
  80370. (function (Buffer){(function (){
  80371. "use strict";
  80372. Object.defineProperty(exports, "__esModule", {
  80373. value: true
  80374. });
  80375. exports.default = void 0;
  80376. var _jsbi = _interopRequireDefault(require("jsbi"));
  80377. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  80378. const SHIFT_LEFT_32 = (1 << 16) * (1 << 16);
  80379. const SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
  80380. const UNKNOWN_PLP_LEN = Buffer.from([0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
  80381. const ZERO_LENGTH_BUFFER = Buffer.alloc(0);
  80382. /**
  80383. A Buffer-like class that tracks position.
  80384. As values are written, the position advances by the size of the written data.
  80385. When writing, automatically allocates new buffers if there's not enough space.
  80386. */
  80387. class WritableTrackingBuffer {
  80388. constructor(initialSize, encoding, doubleSizeGrowth) {
  80389. this.initialSize = void 0;
  80390. this.encoding = void 0;
  80391. this.doubleSizeGrowth = void 0;
  80392. this.buffer = void 0;
  80393. this.compositeBuffer = void 0;
  80394. this.position = void 0;
  80395. this.initialSize = initialSize;
  80396. this.encoding = encoding || 'ucs2';
  80397. this.doubleSizeGrowth = doubleSizeGrowth || false;
  80398. this.buffer = Buffer.alloc(this.initialSize, 0);
  80399. this.compositeBuffer = ZERO_LENGTH_BUFFER;
  80400. this.position = 0;
  80401. }
  80402. get data() {
  80403. this.newBuffer(0);
  80404. return this.compositeBuffer;
  80405. }
  80406. copyFrom(buffer) {
  80407. const length = buffer.length;
  80408. this.makeRoomFor(length);
  80409. buffer.copy(this.buffer, this.position);
  80410. this.position += length;
  80411. }
  80412. makeRoomFor(requiredLength) {
  80413. if (this.buffer.length - this.position < requiredLength) {
  80414. if (this.doubleSizeGrowth) {
  80415. let size = Math.max(128, this.buffer.length * 2);
  80416. while (size < requiredLength) {
  80417. size *= 2;
  80418. }
  80419. this.newBuffer(size);
  80420. } else {
  80421. this.newBuffer(requiredLength);
  80422. }
  80423. }
  80424. }
  80425. newBuffer(size) {
  80426. const buffer = this.buffer.slice(0, this.position);
  80427. this.compositeBuffer = Buffer.concat([this.compositeBuffer, buffer]);
  80428. this.buffer = size === 0 ? ZERO_LENGTH_BUFFER : Buffer.alloc(size, 0);
  80429. this.position = 0;
  80430. }
  80431. writeUInt8(value) {
  80432. const length = 1;
  80433. this.makeRoomFor(length);
  80434. this.buffer.writeUInt8(value, this.position);
  80435. this.position += length;
  80436. }
  80437. writeUInt16LE(value) {
  80438. const length = 2;
  80439. this.makeRoomFor(length);
  80440. this.buffer.writeUInt16LE(value, this.position);
  80441. this.position += length;
  80442. }
  80443. writeUShort(value) {
  80444. this.writeUInt16LE(value);
  80445. }
  80446. writeUInt16BE(value) {
  80447. const length = 2;
  80448. this.makeRoomFor(length);
  80449. this.buffer.writeUInt16BE(value, this.position);
  80450. this.position += length;
  80451. }
  80452. writeUInt24LE(value) {
  80453. const length = 3;
  80454. this.makeRoomFor(length);
  80455. this.buffer[this.position + 2] = value >>> 16 & 0xff;
  80456. this.buffer[this.position + 1] = value >>> 8 & 0xff;
  80457. this.buffer[this.position] = value & 0xff;
  80458. this.position += length;
  80459. }
  80460. writeUInt32LE(value) {
  80461. const length = 4;
  80462. this.makeRoomFor(length);
  80463. this.buffer.writeUInt32LE(value, this.position);
  80464. this.position += length;
  80465. }
  80466. writeBigInt64LE(value) {
  80467. this.writeBigU_Int64LE(value);
  80468. }
  80469. writeBigU_Int64LE(value) {
  80470. this.makeRoomFor(8);
  80471. let lo = _jsbi.default.toNumber(_jsbi.default.bitwiseAnd(value, _jsbi.default.BigInt(0xffffffff)));
  80472. this.buffer[this.position++] = lo;
  80473. lo = lo >> 8;
  80474. this.buffer[this.position++] = lo;
  80475. lo = lo >> 8;
  80476. this.buffer[this.position++] = lo;
  80477. lo = lo >> 8;
  80478. this.buffer[this.position++] = lo;
  80479. let hi = _jsbi.default.toNumber(_jsbi.default.bitwiseAnd(_jsbi.default.signedRightShift(value, _jsbi.default.BigInt(32)), _jsbi.default.BigInt(0xffffffff)));
  80480. this.buffer[this.position++] = hi;
  80481. hi = hi >> 8;
  80482. this.buffer[this.position++] = hi;
  80483. hi = hi >> 8;
  80484. this.buffer[this.position++] = hi;
  80485. hi = hi >> 8;
  80486. this.buffer[this.position++] = hi;
  80487. }
  80488. writeInt64LE(value) {
  80489. this.writeBigInt64LE(_jsbi.default.BigInt(value));
  80490. }
  80491. writeUInt32BE(value) {
  80492. const length = 4;
  80493. this.makeRoomFor(length);
  80494. this.buffer.writeUInt32BE(value, this.position);
  80495. this.position += length;
  80496. }
  80497. writeUInt40LE(value) {
  80498. // inspired by https://github.com/dpw/node-buffer-more-ints
  80499. this.writeInt32LE(value & -1);
  80500. this.writeUInt8(Math.floor(value * SHIFT_RIGHT_32));
  80501. }
  80502. writeUInt64LE(value) {
  80503. this.writeBigUInt64LE(_jsbi.default.BigInt(value));
  80504. }
  80505. writeBigUInt64LE(value) {
  80506. this.writeBigU_Int64LE(value);
  80507. }
  80508. writeInt8(value) {
  80509. const length = 1;
  80510. this.makeRoomFor(length);
  80511. this.buffer.writeInt8(value, this.position);
  80512. this.position += length;
  80513. }
  80514. writeInt16LE(value) {
  80515. const length = 2;
  80516. this.makeRoomFor(length);
  80517. this.buffer.writeInt16LE(value, this.position);
  80518. this.position += length;
  80519. }
  80520. writeInt16BE(value) {
  80521. const length = 2;
  80522. this.makeRoomFor(length);
  80523. this.buffer.writeInt16BE(value, this.position);
  80524. this.position += length;
  80525. }
  80526. writeInt32LE(value) {
  80527. const length = 4;
  80528. this.makeRoomFor(length);
  80529. this.buffer.writeInt32LE(value, this.position);
  80530. this.position += length;
  80531. }
  80532. writeInt32BE(value) {
  80533. const length = 4;
  80534. this.makeRoomFor(length);
  80535. this.buffer.writeInt32BE(value, this.position);
  80536. this.position += length;
  80537. }
  80538. writeFloatLE(value) {
  80539. const length = 4;
  80540. this.makeRoomFor(length);
  80541. this.buffer.writeFloatLE(value, this.position);
  80542. this.position += length;
  80543. }
  80544. writeDoubleLE(value) {
  80545. const length = 8;
  80546. this.makeRoomFor(length);
  80547. this.buffer.writeDoubleLE(value, this.position);
  80548. this.position += length;
  80549. }
  80550. writeString(value, encoding) {
  80551. if (encoding == null) {
  80552. encoding = this.encoding;
  80553. }
  80554. const length = Buffer.byteLength(value, encoding);
  80555. this.makeRoomFor(length); // $FlowFixMe https://github.com/facebook/flow/pull/5398
  80556. this.buffer.write(value, this.position, encoding);
  80557. this.position += length;
  80558. }
  80559. writeBVarchar(value, encoding) {
  80560. this.writeUInt8(value.length);
  80561. this.writeString(value, encoding);
  80562. }
  80563. writeUsVarchar(value, encoding) {
  80564. this.writeUInt16LE(value.length);
  80565. this.writeString(value, encoding);
  80566. } // TODO: Figure out what types are passed in other than `Buffer`
  80567. writeUsVarbyte(value, encoding) {
  80568. if (encoding == null) {
  80569. encoding = this.encoding;
  80570. }
  80571. let length;
  80572. if (value instanceof Buffer) {
  80573. length = value.length;
  80574. } else {
  80575. value = value.toString();
  80576. length = Buffer.byteLength(value, encoding);
  80577. }
  80578. this.writeUInt16LE(length);
  80579. if (value instanceof Buffer) {
  80580. this.writeBuffer(value);
  80581. } else {
  80582. this.makeRoomFor(length); // $FlowFixMe https://github.com/facebook/flow/pull/5398
  80583. this.buffer.write(value, this.position, encoding);
  80584. this.position += length;
  80585. }
  80586. }
  80587. writePLPBody(value, encoding) {
  80588. if (encoding == null) {
  80589. encoding = this.encoding;
  80590. }
  80591. let length;
  80592. if (value instanceof Buffer) {
  80593. length = value.length;
  80594. } else {
  80595. value = value.toString();
  80596. length = Buffer.byteLength(value, encoding);
  80597. } // Length of all chunks.
  80598. // this.writeUInt64LE(length);
  80599. // unknown seems to work better here - might revisit later.
  80600. this.writeBuffer(UNKNOWN_PLP_LEN); // In the UNKNOWN_PLP_LEN case, the data is represented as a series of zero or more chunks.
  80601. if (length > 0) {
  80602. // One chunk.
  80603. this.writeUInt32LE(length);
  80604. if (value instanceof Buffer) {
  80605. this.writeBuffer(value);
  80606. } else {
  80607. this.makeRoomFor(length);
  80608. this.buffer.write(value, this.position, encoding);
  80609. this.position += length;
  80610. }
  80611. } // PLP_TERMINATOR (no more chunks).
  80612. this.writeUInt32LE(0);
  80613. }
  80614. writeBuffer(value) {
  80615. const length = value.length;
  80616. this.makeRoomFor(length);
  80617. value.copy(this.buffer, this.position);
  80618. this.position += length;
  80619. }
  80620. writeMoney(value) {
  80621. this.writeInt32LE(Math.floor(value * SHIFT_RIGHT_32));
  80622. this.writeInt32LE(value & -1);
  80623. }
  80624. }
  80625. var _default = WritableTrackingBuffer;
  80626. exports.default = _default;
  80627. module.exports = WritableTrackingBuffer;
  80628. }).call(this)}).call(this,require("buffer").Buffer)
  80629. },{"buffer":193,"jsbi":327}],494:[function(require,module,exports){
  80630. "use strict";
  80631. Object.defineProperty(exports, "__esModule", {
  80632. value: true
  80633. });
  80634. exports.Transaction = exports.isolationLevelByValue = exports.ISOLATION_LEVEL = exports.OPERATION_TYPE = void 0;
  80635. var _writableTrackingBuffer = _interopRequireDefault(require("./tracking-buffer/writable-tracking-buffer"));
  80636. var _allHeaders = require("./all-headers");
  80637. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  80638. /*
  80639. s2.2.6.8
  80640. */
  80641. const OPERATION_TYPE = {
  80642. TM_GET_DTC_ADDRESS: 0x00,
  80643. TM_PROPAGATE_XACT: 0x01,
  80644. TM_BEGIN_XACT: 0x05,
  80645. TM_PROMOTE_XACT: 0x06,
  80646. TM_COMMIT_XACT: 0x07,
  80647. TM_ROLLBACK_XACT: 0x08,
  80648. TM_SAVE_XACT: 0x09
  80649. };
  80650. exports.OPERATION_TYPE = OPERATION_TYPE;
  80651. const ISOLATION_LEVEL = {
  80652. NO_CHANGE: 0x00,
  80653. READ_UNCOMMITTED: 0x01,
  80654. READ_COMMITTED: 0x02,
  80655. REPEATABLE_READ: 0x03,
  80656. SERIALIZABLE: 0x04,
  80657. SNAPSHOT: 0x05
  80658. };
  80659. exports.ISOLATION_LEVEL = ISOLATION_LEVEL;
  80660. const isolationLevelByValue = {};
  80661. exports.isolationLevelByValue = isolationLevelByValue;
  80662. for (const name in ISOLATION_LEVEL) {
  80663. const value = ISOLATION_LEVEL[name];
  80664. isolationLevelByValue[value] = name;
  80665. }
  80666. class Transaction {
  80667. constructor(name, isolationLevel = ISOLATION_LEVEL.NO_CHANGE) {
  80668. this.name = void 0;
  80669. this.isolationLevel = void 0;
  80670. this.outstandingRequestCount = void 0;
  80671. this.name = name;
  80672. this.isolationLevel = isolationLevel;
  80673. this.outstandingRequestCount = 1;
  80674. }
  80675. beginPayload(txnDescriptor) {
  80676. const buffer = new _writableTrackingBuffer.default(100, 'ucs2');
  80677. (0, _allHeaders.writeToTrackingBuffer)(buffer, txnDescriptor, this.outstandingRequestCount);
  80678. buffer.writeUShort(OPERATION_TYPE.TM_BEGIN_XACT);
  80679. buffer.writeUInt8(this.isolationLevel);
  80680. buffer.writeUInt8(this.name.length * 2);
  80681. buffer.writeString(this.name, 'ucs2');
  80682. return {
  80683. getData: cb => {
  80684. cb(buffer.data);
  80685. },
  80686. toString: () => {
  80687. return 'Begin Transaction: name=' + this.name + ', isolationLevel=' + isolationLevelByValue[this.isolationLevel];
  80688. }
  80689. };
  80690. }
  80691. commitPayload(txnDescriptor) {
  80692. const buffer = new _writableTrackingBuffer.default(100, 'ascii');
  80693. (0, _allHeaders.writeToTrackingBuffer)(buffer, txnDescriptor, this.outstandingRequestCount);
  80694. buffer.writeUShort(OPERATION_TYPE.TM_COMMIT_XACT);
  80695. buffer.writeUInt8(this.name.length * 2);
  80696. buffer.writeString(this.name, 'ucs2'); // No fBeginXact flag, so no new transaction is started.
  80697. buffer.writeUInt8(0);
  80698. return {
  80699. getData: cb => {
  80700. cb(buffer.data);
  80701. },
  80702. data: buffer.data,
  80703. toString: () => {
  80704. return 'Commit Transaction: name=' + this.name;
  80705. }
  80706. };
  80707. }
  80708. rollbackPayload(txnDescriptor) {
  80709. const buffer = new _writableTrackingBuffer.default(100, 'ascii');
  80710. (0, _allHeaders.writeToTrackingBuffer)(buffer, txnDescriptor, this.outstandingRequestCount);
  80711. buffer.writeUShort(OPERATION_TYPE.TM_ROLLBACK_XACT);
  80712. buffer.writeUInt8(this.name.length * 2);
  80713. buffer.writeString(this.name, 'ucs2'); // No fBeginXact flag, so no new transaction is started.
  80714. buffer.writeUInt8(0);
  80715. return {
  80716. getData: cb => {
  80717. cb(buffer.data);
  80718. },
  80719. toString: () => {
  80720. return 'Rollback Transaction: name=' + this.name;
  80721. }
  80722. };
  80723. }
  80724. savePayload(txnDescriptor) {
  80725. const buffer = new _writableTrackingBuffer.default(100, 'ascii');
  80726. (0, _allHeaders.writeToTrackingBuffer)(buffer, txnDescriptor, this.outstandingRequestCount);
  80727. buffer.writeUShort(OPERATION_TYPE.TM_SAVE_XACT);
  80728. buffer.writeUInt8(this.name.length * 2);
  80729. buffer.writeString(this.name, 'ucs2');
  80730. return {
  80731. getData: cb => {
  80732. cb(buffer.data);
  80733. },
  80734. toString: () => {
  80735. return 'Save Transaction: name=' + this.name;
  80736. }
  80737. };
  80738. }
  80739. isolationLevelToTSQL() {
  80740. switch (this.isolationLevel) {
  80741. case ISOLATION_LEVEL.READ_UNCOMMITTED:
  80742. return 'READ UNCOMMITTED';
  80743. case ISOLATION_LEVEL.READ_COMMITTED:
  80744. return 'READ COMMITTED';
  80745. case ISOLATION_LEVEL.REPEATABLE_READ:
  80746. return 'REPEATABLE READ';
  80747. case ISOLATION_LEVEL.SERIALIZABLE:
  80748. return 'SERIALIZABLE';
  80749. case ISOLATION_LEVEL.SNAPSHOT:
  80750. return 'SNAPSHOT';
  80751. }
  80752. return '';
  80753. }
  80754. }
  80755. exports.Transaction = Transaction;
  80756. },{"./all-headers":411,"./tracking-buffer/writable-tracking-buffer":493}],495:[function(require,module,exports){
  80757. "use strict";
  80758. Object.defineProperty(exports, "__esModule", {
  80759. value: true
  80760. });
  80761. exports.TransientErrorLookup = void 0;
  80762. // This simple piece of code is factored out into a separate class to make it
  80763. // easy to stub it out in tests. It's hard, if not impossible, to cause a
  80764. // transient error on demand in tests.
  80765. class TransientErrorLookup {
  80766. isTransientError(error) {
  80767. // This list of transient errors comes from Microsoft implementation of SqlClient:
  80768. // - https://github.com/dotnet/corefx/blob/master/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs#L115
  80769. const transientErrors = [4060, 10928, 10929, 40197, 40501, 40613];
  80770. return transientErrors.indexOf(error) !== -1;
  80771. }
  80772. }
  80773. exports.TransientErrorLookup = TransientErrorLookup;
  80774. },{}],496:[function(require,module,exports){
  80775. (function (Buffer){(function (){
  80776. "use strict";
  80777. Object.defineProperty(exports, "__esModule", {
  80778. value: true
  80779. });
  80780. exports.default = void 0;
  80781. var _metadataParser = require("./metadata-parser");
  80782. var _dataType = require("./data-type");
  80783. var _iconvLite = _interopRequireDefault(require("iconv-lite"));
  80784. var _sprintfJs = require("sprintf-js");
  80785. var _guidParser = require("./guid-parser");
  80786. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  80787. const NULL = (1 << 16) - 1;
  80788. const MAX = (1 << 16) - 1;
  80789. const THREE_AND_A_THIRD = 3 + 1 / 3;
  80790. const MONEY_DIVISOR = 10000;
  80791. const PLP_NULL = Buffer.from([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
  80792. const UNKNOWN_PLP_LEN = Buffer.from([0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
  80793. const DEFAULT_ENCODING = 'utf8';
  80794. function readTinyInt(parser, callback) {
  80795. parser.readUInt8(callback);
  80796. }
  80797. function readSmallInt(parser, callback) {
  80798. parser.readInt16LE(callback);
  80799. }
  80800. function readInt(parser, callback) {
  80801. parser.readInt32LE(callback);
  80802. }
  80803. function readBigInt(parser, callback) {
  80804. parser.readBigInt64LE(value => {
  80805. callback(value.toString());
  80806. });
  80807. }
  80808. function readReal(parser, callback) {
  80809. parser.readFloatLE(callback);
  80810. }
  80811. function readFloat(parser, callback) {
  80812. parser.readDoubleLE(callback);
  80813. }
  80814. function readSmallMoney(parser, callback) {
  80815. parser.readInt32LE(value => {
  80816. callback(value / MONEY_DIVISOR);
  80817. });
  80818. }
  80819. function readMoney(parser, callback) {
  80820. parser.readInt32LE(high => {
  80821. parser.readUInt32LE(low => {
  80822. callback((low + 0x100000000 * high) / MONEY_DIVISOR);
  80823. });
  80824. });
  80825. }
  80826. function readBit(parser, callback) {
  80827. parser.readUInt8(value => {
  80828. callback(!!value);
  80829. });
  80830. }
  80831. function valueParse(parser, metadata, options, callback) {
  80832. const type = metadata.type;
  80833. switch (type.name) {
  80834. case 'Null':
  80835. return callback(null);
  80836. case 'TinyInt':
  80837. return readTinyInt(parser, callback);
  80838. case 'SmallInt':
  80839. return readSmallInt(parser, callback);
  80840. case 'Int':
  80841. return readInt(parser, callback);
  80842. case 'BigInt':
  80843. return readBigInt(parser, callback);
  80844. case 'IntN':
  80845. return parser.readUInt8(dataLength => {
  80846. switch (dataLength) {
  80847. case 0:
  80848. return callback(null);
  80849. case 1:
  80850. return readTinyInt(parser, callback);
  80851. case 2:
  80852. return readSmallInt(parser, callback);
  80853. case 4:
  80854. return readInt(parser, callback);
  80855. case 8:
  80856. return readBigInt(parser, callback);
  80857. default:
  80858. return parser.emit('error', new Error('Unsupported dataLength ' + dataLength + ' for IntN'));
  80859. }
  80860. });
  80861. case 'Real':
  80862. return readReal(parser, callback);
  80863. case 'Float':
  80864. return readFloat(parser, callback);
  80865. case 'FloatN':
  80866. return parser.readUInt8(dataLength => {
  80867. switch (dataLength) {
  80868. case 0:
  80869. return callback(null);
  80870. case 4:
  80871. return readReal(parser, callback);
  80872. case 8:
  80873. return readFloat(parser, callback);
  80874. default:
  80875. return parser.emit('error', new Error('Unsupported dataLength ' + dataLength + ' for FloatN'));
  80876. }
  80877. });
  80878. case 'SmallMoney':
  80879. return readSmallMoney(parser, callback);
  80880. case 'Money':
  80881. return readMoney(parser, callback);
  80882. case 'MoneyN':
  80883. return parser.readUInt8(dataLength => {
  80884. switch (dataLength) {
  80885. case 0:
  80886. return callback(null);
  80887. case 4:
  80888. return readSmallMoney(parser, callback);
  80889. case 8:
  80890. return readMoney(parser, callback);
  80891. default:
  80892. return parser.emit('error', new Error('Unsupported dataLength ' + dataLength + ' for MoneyN'));
  80893. }
  80894. });
  80895. case 'Bit':
  80896. return readBit(parser, callback);
  80897. case 'BitN':
  80898. return parser.readUInt8(dataLength => {
  80899. switch (dataLength) {
  80900. case 0:
  80901. return callback(null);
  80902. case 1:
  80903. return readBit(parser, callback);
  80904. default:
  80905. return parser.emit('error', new Error('Unsupported dataLength ' + dataLength + ' for BitN'));
  80906. }
  80907. });
  80908. case 'VarChar':
  80909. case 'Char':
  80910. const codepage = metadata.collation.codepage;
  80911. if (metadata.dataLength === MAX) {
  80912. return readMaxChars(parser, codepage, callback);
  80913. } else {
  80914. return parser.readUInt16LE(dataLength => {
  80915. if (dataLength === NULL) {
  80916. return callback(null);
  80917. }
  80918. readChars(parser, dataLength, codepage, callback);
  80919. });
  80920. }
  80921. case 'NVarChar':
  80922. case 'NChar':
  80923. if (metadata.dataLength === MAX) {
  80924. return readMaxNChars(parser, callback);
  80925. } else {
  80926. return parser.readUInt16LE(dataLength => {
  80927. if (dataLength === NULL) {
  80928. return callback(null);
  80929. }
  80930. readNChars(parser, dataLength, callback);
  80931. });
  80932. }
  80933. case 'VarBinary':
  80934. case 'Binary':
  80935. if (metadata.dataLength === MAX) {
  80936. return readMaxBinary(parser, callback);
  80937. } else {
  80938. return parser.readUInt16LE(dataLength => {
  80939. if (dataLength === NULL) {
  80940. return callback(null);
  80941. }
  80942. readBinary(parser, dataLength, callback);
  80943. });
  80944. }
  80945. case 'Text':
  80946. return parser.readUInt8(textPointerLength => {
  80947. if (textPointerLength === 0) {
  80948. return callback(null);
  80949. }
  80950. parser.readBuffer(textPointerLength, _textPointer => {
  80951. parser.readBuffer(8, _timestamp => {
  80952. parser.readUInt32LE(dataLength => {
  80953. readChars(parser, dataLength, metadata.collation.codepage, callback);
  80954. });
  80955. });
  80956. });
  80957. });
  80958. case 'NText':
  80959. return parser.readUInt8(textPointerLength => {
  80960. if (textPointerLength === 0) {
  80961. return callback(null);
  80962. }
  80963. parser.readBuffer(textPointerLength, _textPointer => {
  80964. parser.readBuffer(8, _timestamp => {
  80965. parser.readUInt32LE(dataLength => {
  80966. readNChars(parser, dataLength, callback);
  80967. });
  80968. });
  80969. });
  80970. });
  80971. case 'Image':
  80972. return parser.readUInt8(textPointerLength => {
  80973. if (textPointerLength === 0) {
  80974. return callback(null);
  80975. }
  80976. parser.readBuffer(textPointerLength, _textPointer => {
  80977. parser.readBuffer(8, _timestamp => {
  80978. parser.readUInt32LE(dataLength => {
  80979. readBinary(parser, dataLength, callback);
  80980. });
  80981. });
  80982. });
  80983. });
  80984. case 'Xml':
  80985. return readMaxNChars(parser, callback);
  80986. case 'SmallDateTime':
  80987. return readSmallDateTime(parser, options.useUTC, callback);
  80988. case 'DateTime':
  80989. return readDateTime(parser, options.useUTC, callback);
  80990. case 'DateTimeN':
  80991. return parser.readUInt8(dataLength => {
  80992. switch (dataLength) {
  80993. case 0:
  80994. return callback(null);
  80995. case 4:
  80996. return readSmallDateTime(parser, options.useUTC, callback);
  80997. case 8:
  80998. return readDateTime(parser, options.useUTC, callback);
  80999. default:
  81000. return parser.emit('error', new Error('Unsupported dataLength ' + dataLength + ' for DateTimeN'));
  81001. }
  81002. });
  81003. case 'Time':
  81004. return parser.readUInt8(dataLength => {
  81005. if (dataLength === 0) {
  81006. return callback(null);
  81007. } else {
  81008. return readTime(parser, dataLength, metadata.scale, options.useUTC, callback);
  81009. }
  81010. });
  81011. case 'Date':
  81012. return parser.readUInt8(dataLength => {
  81013. if (dataLength === 0) {
  81014. return callback(null);
  81015. } else {
  81016. return readDate(parser, options.useUTC, callback);
  81017. }
  81018. });
  81019. case 'DateTime2':
  81020. return parser.readUInt8(dataLength => {
  81021. if (dataLength === 0) {
  81022. return callback(null);
  81023. } else {
  81024. return readDateTime2(parser, dataLength, metadata.scale, options.useUTC, callback);
  81025. }
  81026. });
  81027. case 'DateTimeOffset':
  81028. return parser.readUInt8(dataLength => {
  81029. if (dataLength === 0) {
  81030. return callback(null);
  81031. } else {
  81032. return readDateTimeOffset(parser, dataLength, metadata.scale, callback);
  81033. }
  81034. });
  81035. case 'NumericN':
  81036. case 'DecimalN':
  81037. return parser.readUInt8(dataLength => {
  81038. if (dataLength === 0) {
  81039. return callback(null);
  81040. } else {
  81041. return readNumeric(parser, dataLength, metadata.precision, metadata.scale, callback);
  81042. }
  81043. });
  81044. case 'UniqueIdentifier':
  81045. return parser.readUInt8(dataLength => {
  81046. switch (dataLength) {
  81047. case 0:
  81048. return callback(null);
  81049. case 0x10:
  81050. return readUniqueIdentifier(parser, options, callback);
  81051. default:
  81052. return parser.emit('error', new Error((0, _sprintfJs.sprintf)('Unsupported guid size %d', dataLength - 1)));
  81053. }
  81054. });
  81055. case 'UDT':
  81056. return readMaxBinary(parser, callback);
  81057. case 'Variant':
  81058. return parser.readUInt32LE(dataLength => {
  81059. if (dataLength === 0) {
  81060. return callback(null);
  81061. }
  81062. readVariant(parser, options, dataLength, callback);
  81063. });
  81064. default:
  81065. parser.emit('error', new Error((0, _sprintfJs.sprintf)('Unrecognised type %s', type.name)));
  81066. }
  81067. }
  81068. function readUniqueIdentifier(parser, options, callback) {
  81069. parser.readBuffer(0x10, data => {
  81070. callback(options.lowerCaseGuids ? (0, _guidParser.bufferToLowerCaseGuid)(data) : (0, _guidParser.bufferToUpperCaseGuid)(data));
  81071. });
  81072. }
  81073. function readNumeric(parser, dataLength, _precision, scale, callback) {
  81074. parser.readUInt8(sign => {
  81075. sign = sign === 1 ? 1 : -1;
  81076. let readValue;
  81077. if (dataLength === 5) {
  81078. readValue = parser.readUInt32LE;
  81079. } else if (dataLength === 9) {
  81080. readValue = parser.readUNumeric64LE;
  81081. } else if (dataLength === 13) {
  81082. readValue = parser.readUNumeric96LE;
  81083. } else if (dataLength === 17) {
  81084. readValue = parser.readUNumeric128LE;
  81085. } else {
  81086. return parser.emit('error', new Error((0, _sprintfJs.sprintf)('Unsupported numeric dataLength %d', dataLength)));
  81087. }
  81088. readValue.call(parser, value => {
  81089. callback(value * sign / Math.pow(10, scale));
  81090. });
  81091. });
  81092. }
  81093. function readVariant(parser, options, dataLength, callback) {
  81094. return parser.readUInt8(baseType => {
  81095. const type = _dataType.TYPE[baseType];
  81096. return parser.readUInt8(propBytes => {
  81097. dataLength = dataLength - propBytes - 2;
  81098. switch (type.name) {
  81099. case 'UniqueIdentifier':
  81100. return readUniqueIdentifier(parser, options, callback);
  81101. case 'Bit':
  81102. return readBit(parser, callback);
  81103. case 'TinyInt':
  81104. return readTinyInt(parser, callback);
  81105. case 'SmallInt':
  81106. return readSmallInt(parser, callback);
  81107. case 'Int':
  81108. return readInt(parser, callback);
  81109. case 'BigInt':
  81110. return readBigInt(parser, callback);
  81111. case 'SmallDateTime':
  81112. return readSmallDateTime(parser, options.useUTC, callback);
  81113. case 'DateTime':
  81114. return readDateTime(parser, options.useUTC, callback);
  81115. case 'Real':
  81116. return readReal(parser, callback);
  81117. case 'Float':
  81118. return readFloat(parser, callback);
  81119. case 'SmallMoney':
  81120. return readSmallMoney(parser, callback);
  81121. case 'Money':
  81122. return readMoney(parser, callback);
  81123. case 'Date':
  81124. return readDate(parser, options.useUTC, callback);
  81125. case 'Time':
  81126. return parser.readUInt8(scale => {
  81127. return readTime(parser, dataLength, scale, options.useUTC, callback);
  81128. });
  81129. case 'DateTime2':
  81130. return parser.readUInt8(scale => {
  81131. return readDateTime2(parser, dataLength, scale, options.useUTC, callback);
  81132. });
  81133. case 'DateTimeOffset':
  81134. return parser.readUInt8(scale => {
  81135. return readDateTimeOffset(parser, dataLength, scale, callback);
  81136. });
  81137. case 'VarBinary':
  81138. case 'Binary':
  81139. return parser.readUInt16LE(_maxLength => {
  81140. readBinary(parser, dataLength, callback);
  81141. });
  81142. case 'NumericN':
  81143. case 'DecimalN':
  81144. return parser.readUInt8(precision => {
  81145. parser.readUInt8(scale => {
  81146. readNumeric(parser, dataLength, precision, scale, callback);
  81147. });
  81148. });
  81149. case 'VarChar':
  81150. case 'Char':
  81151. return parser.readUInt16LE(_maxLength => {
  81152. (0, _metadataParser.readCollation)(parser, collation => {
  81153. readChars(parser, dataLength, collation.codepage, callback);
  81154. });
  81155. });
  81156. case 'NVarChar':
  81157. case 'NChar':
  81158. return parser.readUInt16LE(_maxLength => {
  81159. (0, _metadataParser.readCollation)(parser, _collation => {
  81160. readNChars(parser, dataLength, callback);
  81161. });
  81162. });
  81163. default:
  81164. throw new Error('Invalid type!');
  81165. }
  81166. });
  81167. });
  81168. }
  81169. function readBinary(parser, dataLength, callback) {
  81170. return parser.readBuffer(dataLength, callback);
  81171. }
  81172. function readChars(parser, dataLength, codepage, callback) {
  81173. if (codepage == null) {
  81174. codepage = DEFAULT_ENCODING;
  81175. }
  81176. return parser.readBuffer(dataLength, data => {
  81177. callback(_iconvLite.default.decode(data, codepage));
  81178. });
  81179. }
  81180. function readNChars(parser, dataLength, callback) {
  81181. parser.readBuffer(dataLength, data => {
  81182. callback(data.toString('ucs2'));
  81183. });
  81184. }
  81185. function readMaxBinary(parser, callback) {
  81186. return readMax(parser, callback);
  81187. }
  81188. function readMaxChars(parser, codepage, callback) {
  81189. if (codepage == null) {
  81190. codepage = DEFAULT_ENCODING;
  81191. }
  81192. readMax(parser, data => {
  81193. if (data) {
  81194. callback(_iconvLite.default.decode(data, codepage));
  81195. } else {
  81196. callback(null);
  81197. }
  81198. });
  81199. }
  81200. function readMaxNChars(parser, callback) {
  81201. readMax(parser, data => {
  81202. if (data) {
  81203. callback(data.toString('ucs2'));
  81204. } else {
  81205. callback(null);
  81206. }
  81207. });
  81208. }
  81209. function readMax(parser, callback) {
  81210. parser.readBuffer(8, type => {
  81211. if (type.equals(PLP_NULL)) {
  81212. return callback(null);
  81213. } else if (type.equals(UNKNOWN_PLP_LEN)) {
  81214. return readMaxUnknownLength(parser, callback);
  81215. } else {
  81216. const low = type.readUInt32LE(0);
  81217. const high = type.readUInt32LE(4);
  81218. if (high >= 2 << 53 - 32) {
  81219. console.warn('Read UInt64LE > 53 bits : high=' + high + ', low=' + low);
  81220. }
  81221. const expectedLength = low + 0x100000000 * high;
  81222. return readMaxKnownLength(parser, expectedLength, callback);
  81223. }
  81224. });
  81225. }
  81226. function readMaxKnownLength(parser, totalLength, callback) {
  81227. const data = Buffer.alloc(totalLength, 0);
  81228. let offset = 0;
  81229. function next(done) {
  81230. parser.readUInt32LE(chunkLength => {
  81231. if (!chunkLength) {
  81232. return done();
  81233. }
  81234. parser.readBuffer(chunkLength, chunk => {
  81235. chunk.copy(data, offset);
  81236. offset += chunkLength;
  81237. next(done);
  81238. });
  81239. });
  81240. }
  81241. next(() => {
  81242. if (offset !== totalLength) {
  81243. parser.emit('error', new Error('Partially Length-prefixed Bytes unmatched lengths : expected ' + totalLength + ', but got ' + offset + ' bytes'));
  81244. }
  81245. callback(data);
  81246. });
  81247. }
  81248. function readMaxUnknownLength(parser, callback) {
  81249. const chunks = [];
  81250. let length = 0;
  81251. function next(done) {
  81252. parser.readUInt32LE(chunkLength => {
  81253. if (!chunkLength) {
  81254. return done();
  81255. }
  81256. parser.readBuffer(chunkLength, chunk => {
  81257. chunks.push(chunk);
  81258. length += chunkLength;
  81259. next(done);
  81260. });
  81261. });
  81262. }
  81263. next(() => {
  81264. callback(Buffer.concat(chunks, length));
  81265. });
  81266. }
  81267. function readSmallDateTime(parser, useUTC, callback) {
  81268. parser.readUInt16LE(days => {
  81269. parser.readUInt16LE(minutes => {
  81270. let value;
  81271. if (useUTC) {
  81272. value = new Date(Date.UTC(1900, 0, 1 + days, 0, minutes));
  81273. } else {
  81274. value = new Date(1900, 0, 1 + days, 0, minutes);
  81275. }
  81276. callback(value);
  81277. });
  81278. });
  81279. }
  81280. function readDateTime(parser, useUTC, callback) {
  81281. parser.readInt32LE(days => {
  81282. parser.readUInt32LE(threeHundredthsOfSecond => {
  81283. const milliseconds = Math.round(threeHundredthsOfSecond * THREE_AND_A_THIRD);
  81284. let value;
  81285. if (useUTC) {
  81286. value = new Date(Date.UTC(1900, 0, 1 + days, 0, 0, 0, milliseconds));
  81287. } else {
  81288. value = new Date(1900, 0, 1 + days, 0, 0, 0, milliseconds);
  81289. }
  81290. callback(value);
  81291. });
  81292. });
  81293. }
  81294. function readTime(parser, dataLength, scale, useUTC, callback) {
  81295. let readValue;
  81296. switch (dataLength) {
  81297. case 3:
  81298. readValue = parser.readUInt24LE;
  81299. break;
  81300. case 4:
  81301. readValue = parser.readUInt32LE;
  81302. break;
  81303. case 5:
  81304. readValue = parser.readUInt40LE;
  81305. }
  81306. readValue.call(parser, value => {
  81307. if (scale < 7) {
  81308. for (let i = scale; i < 7; i++) {
  81309. value *= 10;
  81310. }
  81311. }
  81312. let date;
  81313. if (useUTC) {
  81314. date = new Date(Date.UTC(1970, 0, 1, 0, 0, 0, value / 10000));
  81315. } else {
  81316. date = new Date(1970, 0, 1, 0, 0, 0, value / 10000);
  81317. }
  81318. Object.defineProperty(date, 'nanosecondsDelta', {
  81319. enumerable: false,
  81320. value: value % 10000 / Math.pow(10, 7)
  81321. });
  81322. callback(date);
  81323. });
  81324. }
  81325. function readDate(parser, useUTC, callback) {
  81326. parser.readUInt24LE(days => {
  81327. if (useUTC) {
  81328. callback(new Date(Date.UTC(2000, 0, days - 730118)));
  81329. } else {
  81330. callback(new Date(2000, 0, days - 730118));
  81331. }
  81332. });
  81333. }
  81334. function readDateTime2(parser, dataLength, scale, useUTC, callback) {
  81335. readTime(parser, dataLength - 3, scale, useUTC, time => {
  81336. // TODO: 'input' is 'time', but TypeScript cannot find "time.nanosecondsDelta";
  81337. parser.readUInt24LE(days => {
  81338. let date;
  81339. if (useUTC) {
  81340. date = new Date(Date.UTC(2000, 0, days - 730118, 0, 0, 0, +time));
  81341. } else {
  81342. date = new Date(2000, 0, days - 730118, time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds());
  81343. }
  81344. Object.defineProperty(date, 'nanosecondsDelta', {
  81345. enumerable: false,
  81346. value: time.nanosecondsDelta
  81347. });
  81348. callback(date);
  81349. });
  81350. });
  81351. }
  81352. function readDateTimeOffset(parser, dataLength, scale, callback) {
  81353. readTime(parser, dataLength - 5, scale, true, time => {
  81354. parser.readUInt24LE(days => {
  81355. // offset
  81356. parser.readInt16LE(() => {
  81357. const date = new Date(Date.UTC(2000, 0, days - 730118, 0, 0, 0, +time));
  81358. Object.defineProperty(date, 'nanosecondsDelta', {
  81359. enumerable: false,
  81360. value: time.nanosecondsDelta
  81361. });
  81362. callback(date);
  81363. });
  81364. });
  81365. });
  81366. }
  81367. var _default = valueParse;
  81368. exports.default = _default;
  81369. module.exports = valueParse;
  81370. }).call(this)}).call(this,require("buffer").Buffer)
  81371. },{"./data-type":416,"./guid-parser":458,"./metadata-parser":465,"buffer":193,"iconv-lite":393,"sprintf-js":410}],497:[function(require,module,exports){
  81372. 'use strict';
  81373. const Duplex = require('stream').Duplex;
  81374. const kCallback = Symbol('Callback');
  81375. const kOtherSide = Symbol('Other');
  81376. class DuplexSocket extends Duplex {
  81377. constructor(options) {
  81378. super(options);
  81379. this[kCallback] = null;
  81380. this[kOtherSide] = null;
  81381. }
  81382. _read() {
  81383. const callback = this[kCallback];
  81384. if (callback) {
  81385. this[kCallback] = null;
  81386. callback();
  81387. }
  81388. }
  81389. _write(chunk, encoding, callback) {
  81390. this[kOtherSide][kCallback] = callback;
  81391. this[kOtherSide].push(chunk);
  81392. }
  81393. _final(callback) {
  81394. this[kOtherSide].on('end', callback);
  81395. this[kOtherSide].push(null);
  81396. }
  81397. }
  81398. class DuplexPair {
  81399. constructor(options) {
  81400. this.socket1 = new DuplexSocket(options);
  81401. this.socket2 = new DuplexSocket(options);
  81402. this.socket1[kOtherSide] = this.socket2;
  81403. this.socket2[kOtherSide] = this.socket1;
  81404. }
  81405. }
  81406. module.exports = DuplexPair;
  81407. },{"stream":597}],498:[function(require,module,exports){
  81408. var crypto = require('crypto')
  81409. function sha (key, body, algorithm) {
  81410. return crypto.createHmac(algorithm, key).update(body).digest('base64')
  81411. }
  81412. function rsa (key, body) {
  81413. return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64')
  81414. }
  81415. function rfc3986 (str) {
  81416. return encodeURIComponent(str)
  81417. .replace(/!/g,'%21')
  81418. .replace(/\*/g,'%2A')
  81419. .replace(/\(/g,'%28')
  81420. .replace(/\)/g,'%29')
  81421. .replace(/'/g,'%27')
  81422. }
  81423. // Maps object to bi-dimensional array
  81424. // Converts { foo: 'A', bar: [ 'b', 'B' ]} to
  81425. // [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ]
  81426. function map (obj) {
  81427. var key, val, arr = []
  81428. for (key in obj) {
  81429. val = obj[key]
  81430. if (Array.isArray(val))
  81431. for (var i = 0; i < val.length; i++)
  81432. arr.push([key, val[i]])
  81433. else if (typeof val === 'object')
  81434. for (var prop in val)
  81435. arr.push([key + '[' + prop + ']', val[prop]])
  81436. else
  81437. arr.push([key, val])
  81438. }
  81439. return arr
  81440. }
  81441. // Compare function for sort
  81442. function compare (a, b) {
  81443. return a > b ? 1 : a < b ? -1 : 0
  81444. }
  81445. function generateBase (httpMethod, base_uri, params) {
  81446. // adapted from https://dev.twitter.com/docs/auth/oauth and
  81447. // https://dev.twitter.com/docs/auth/creating-signature
  81448. // Parameter normalization
  81449. // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
  81450. var normalized = map(params)
  81451. // 1. First, the name and value of each parameter are encoded
  81452. .map(function (p) {
  81453. return [ rfc3986(p[0]), rfc3986(p[1] || '') ]
  81454. })
  81455. // 2. The parameters are sorted by name, using ascending byte value
  81456. // ordering. If two or more parameters share the same name, they
  81457. // are sorted by their value.
  81458. .sort(function (a, b) {
  81459. return compare(a[0], b[0]) || compare(a[1], b[1])
  81460. })
  81461. // 3. The name of each parameter is concatenated to its corresponding
  81462. // value using an "=" character (ASCII code 61) as a separator, even
  81463. // if the value is empty.
  81464. .map(function (p) { return p.join('=') })
  81465. // 4. The sorted name/value pairs are concatenated together into a
  81466. // single string by using an "&" character (ASCII code 38) as
  81467. // separator.
  81468. .join('&')
  81469. var base = [
  81470. rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'),
  81471. rfc3986(base_uri),
  81472. rfc3986(normalized)
  81473. ].join('&')
  81474. return base
  81475. }
  81476. function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) {
  81477. var base = generateBase(httpMethod, base_uri, params)
  81478. var key = [
  81479. consumer_secret || '',
  81480. token_secret || ''
  81481. ].map(rfc3986).join('&')
  81482. return sha(key, base, 'sha1')
  81483. }
  81484. function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) {
  81485. var base = generateBase(httpMethod, base_uri, params)
  81486. var key = [
  81487. consumer_secret || '',
  81488. token_secret || ''
  81489. ].map(rfc3986).join('&')
  81490. return sha(key, base, 'sha256')
  81491. }
  81492. function rsasign (httpMethod, base_uri, params, private_key, token_secret) {
  81493. var base = generateBase(httpMethod, base_uri, params)
  81494. var key = private_key || ''
  81495. return rsa(key, base)
  81496. }
  81497. function plaintext (consumer_secret, token_secret) {
  81498. var key = [
  81499. consumer_secret || '',
  81500. token_secret || ''
  81501. ].map(rfc3986).join('&')
  81502. return key
  81503. }
  81504. function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
  81505. var method
  81506. var skipArgs = 1
  81507. switch (signMethod) {
  81508. case 'RSA-SHA1':
  81509. method = rsasign
  81510. break
  81511. case 'HMAC-SHA1':
  81512. method = hmacsign
  81513. break
  81514. case 'HMAC-SHA256':
  81515. method = hmacsign256
  81516. break
  81517. case 'PLAINTEXT':
  81518. method = plaintext
  81519. skipArgs = 4
  81520. break
  81521. default:
  81522. throw new Error('Signature method not supported: ' + signMethod)
  81523. }
  81524. return method.apply(null, [].slice.call(arguments, skipArgs))
  81525. }
  81526. exports.hmacsign = hmacsign
  81527. exports.hmacsign256 = hmacsign256
  81528. exports.rsasign = rsasign
  81529. exports.plaintext = plaintext
  81530. exports.sign = sign
  81531. exports.rfc3986 = rfc3986
  81532. exports.generateBase = generateBase
  81533. },{"crypto":208}],499:[function(require,module,exports){
  81534. /*
  81535. object-assign
  81536. (c) Sindre Sorhus
  81537. @license MIT
  81538. */
  81539. 'use strict';
  81540. /* eslint-disable no-unused-vars */
  81541. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  81542. var hasOwnProperty = Object.prototype.hasOwnProperty;
  81543. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  81544. function toObject(val) {
  81545. if (val === null || val === undefined) {
  81546. throw new TypeError('Object.assign cannot be called with null or undefined');
  81547. }
  81548. return Object(val);
  81549. }
  81550. function shouldUseNative() {
  81551. try {
  81552. if (!Object.assign) {
  81553. return false;
  81554. }
  81555. // Detect buggy property enumeration order in older V8 versions.
  81556. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  81557. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  81558. test1[5] = 'de';
  81559. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  81560. return false;
  81561. }
  81562. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  81563. var test2 = {};
  81564. for (var i = 0; i < 10; i++) {
  81565. test2['_' + String.fromCharCode(i)] = i;
  81566. }
  81567. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  81568. return test2[n];
  81569. });
  81570. if (order2.join('') !== '0123456789') {
  81571. return false;
  81572. }
  81573. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  81574. var test3 = {};
  81575. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  81576. test3[letter] = letter;
  81577. });
  81578. if (Object.keys(Object.assign({}, test3)).join('') !==
  81579. 'abcdefghijklmnopqrst') {
  81580. return false;
  81581. }
  81582. return true;
  81583. } catch (err) {
  81584. // We don't expect any of the above to throw, but better to be safe.
  81585. return false;
  81586. }
  81587. }
  81588. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  81589. var from;
  81590. var to = toObject(target);
  81591. var symbols;
  81592. for (var s = 1; s < arguments.length; s++) {
  81593. from = Object(arguments[s]);
  81594. for (var key in from) {
  81595. if (hasOwnProperty.call(from, key)) {
  81596. to[key] = from[key];
  81597. }
  81598. }
  81599. if (getOwnPropertySymbols) {
  81600. symbols = getOwnPropertySymbols(from);
  81601. for (var i = 0; i < symbols.length; i++) {
  81602. if (propIsEnumerable.call(from, symbols[i])) {
  81603. to[symbols[i]] = from[symbols[i]];
  81604. }
  81605. }
  81606. }
  81607. }
  81608. return to;
  81609. };
  81610. },{}],500:[function(require,module,exports){
  81611. exports.endianness = function () { return 'LE' };
  81612. exports.hostname = function () {
  81613. if (typeof location !== 'undefined') {
  81614. return location.hostname
  81615. }
  81616. else return '';
  81617. };
  81618. exports.loadavg = function () { return [] };
  81619. exports.uptime = function () { return 0 };
  81620. exports.freemem = function () {
  81621. return Number.MAX_VALUE;
  81622. };
  81623. exports.totalmem = function () {
  81624. return Number.MAX_VALUE;
  81625. };
  81626. exports.cpus = function () { return [] };
  81627. exports.type = function () { return 'Browser' };
  81628. exports.release = function () {
  81629. if (typeof navigator !== 'undefined') {
  81630. return navigator.appVersion;
  81631. }
  81632. return '';
  81633. };
  81634. exports.networkInterfaces
  81635. = exports.getNetworkInterfaces
  81636. = function () { return {} };
  81637. exports.arch = function () { return 'javascript' };
  81638. exports.platform = function () { return 'browser' };
  81639. exports.tmpdir = exports.tmpDir = function () {
  81640. return '/tmp';
  81641. };
  81642. exports.EOL = '\n';
  81643. exports.homedir = function () {
  81644. return '/'
  81645. };
  81646. },{}],501:[function(require,module,exports){
  81647. 'use strict';
  81648. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  81649. (typeof Uint16Array !== 'undefined') &&
  81650. (typeof Int32Array !== 'undefined');
  81651. function _has(obj, key) {
  81652. return Object.prototype.hasOwnProperty.call(obj, key);
  81653. }
  81654. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  81655. var sources = Array.prototype.slice.call(arguments, 1);
  81656. while (sources.length) {
  81657. var source = sources.shift();
  81658. if (!source) { continue; }
  81659. if (typeof source !== 'object') {
  81660. throw new TypeError(source + 'must be non-object');
  81661. }
  81662. for (var p in source) {
  81663. if (_has(source, p)) {
  81664. obj[p] = source[p];
  81665. }
  81666. }
  81667. }
  81668. return obj;
  81669. };
  81670. // reduce buffer size, avoiding mem copy
  81671. exports.shrinkBuf = function (buf, size) {
  81672. if (buf.length === size) { return buf; }
  81673. if (buf.subarray) { return buf.subarray(0, size); }
  81674. buf.length = size;
  81675. return buf;
  81676. };
  81677. var fnTyped = {
  81678. arraySet: function (dest, src, src_offs, len, dest_offs) {
  81679. if (src.subarray && dest.subarray) {
  81680. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  81681. return;
  81682. }
  81683. // Fallback to ordinary array
  81684. for (var i = 0; i < len; i++) {
  81685. dest[dest_offs + i] = src[src_offs + i];
  81686. }
  81687. },
  81688. // Join array of chunks to single array.
  81689. flattenChunks: function (chunks) {
  81690. var i, l, len, pos, chunk, result;
  81691. // calculate data length
  81692. len = 0;
  81693. for (i = 0, l = chunks.length; i < l; i++) {
  81694. len += chunks[i].length;
  81695. }
  81696. // join chunks
  81697. result = new Uint8Array(len);
  81698. pos = 0;
  81699. for (i = 0, l = chunks.length; i < l; i++) {
  81700. chunk = chunks[i];
  81701. result.set(chunk, pos);
  81702. pos += chunk.length;
  81703. }
  81704. return result;
  81705. }
  81706. };
  81707. var fnUntyped = {
  81708. arraySet: function (dest, src, src_offs, len, dest_offs) {
  81709. for (var i = 0; i < len; i++) {
  81710. dest[dest_offs + i] = src[src_offs + i];
  81711. }
  81712. },
  81713. // Join array of chunks to single array.
  81714. flattenChunks: function (chunks) {
  81715. return [].concat.apply([], chunks);
  81716. }
  81717. };
  81718. // Enable/Disable typed arrays use, for testing
  81719. //
  81720. exports.setTyped = function (on) {
  81721. if (on) {
  81722. exports.Buf8 = Uint8Array;
  81723. exports.Buf16 = Uint16Array;
  81724. exports.Buf32 = Int32Array;
  81725. exports.assign(exports, fnTyped);
  81726. } else {
  81727. exports.Buf8 = Array;
  81728. exports.Buf16 = Array;
  81729. exports.Buf32 = Array;
  81730. exports.assign(exports, fnUntyped);
  81731. }
  81732. };
  81733. exports.setTyped(TYPED_OK);
  81734. },{}],502:[function(require,module,exports){
  81735. 'use strict';
  81736. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  81737. // It isn't worth it to make additional optimizations as in original.
  81738. // Small size is preferable.
  81739. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  81740. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  81741. //
  81742. // This software is provided 'as-is', without any express or implied
  81743. // warranty. In no event will the authors be held liable for any damages
  81744. // arising from the use of this software.
  81745. //
  81746. // Permission is granted to anyone to use this software for any purpose,
  81747. // including commercial applications, and to alter it and redistribute it
  81748. // freely, subject to the following restrictions:
  81749. //
  81750. // 1. The origin of this software must not be misrepresented; you must not
  81751. // claim that you wrote the original software. If you use this software
  81752. // in a product, an acknowledgment in the product documentation would be
  81753. // appreciated but is not required.
  81754. // 2. Altered source versions must be plainly marked as such, and must not be
  81755. // misrepresented as being the original software.
  81756. // 3. This notice may not be removed or altered from any source distribution.
  81757. function adler32(adler, buf, len, pos) {
  81758. var s1 = (adler & 0xffff) |0,
  81759. s2 = ((adler >>> 16) & 0xffff) |0,
  81760. n = 0;
  81761. while (len !== 0) {
  81762. // Set limit ~ twice less than 5552, to keep
  81763. // s2 in 31-bits, because we force signed ints.
  81764. // in other case %= will fail.
  81765. n = len > 2000 ? 2000 : len;
  81766. len -= n;
  81767. do {
  81768. s1 = (s1 + buf[pos++]) |0;
  81769. s2 = (s2 + s1) |0;
  81770. } while (--n);
  81771. s1 %= 65521;
  81772. s2 %= 65521;
  81773. }
  81774. return (s1 | (s2 << 16)) |0;
  81775. }
  81776. module.exports = adler32;
  81777. },{}],503:[function(require,module,exports){
  81778. 'use strict';
  81779. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  81780. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  81781. //
  81782. // This software is provided 'as-is', without any express or implied
  81783. // warranty. In no event will the authors be held liable for any damages
  81784. // arising from the use of this software.
  81785. //
  81786. // Permission is granted to anyone to use this software for any purpose,
  81787. // including commercial applications, and to alter it and redistribute it
  81788. // freely, subject to the following restrictions:
  81789. //
  81790. // 1. The origin of this software must not be misrepresented; you must not
  81791. // claim that you wrote the original software. If you use this software
  81792. // in a product, an acknowledgment in the product documentation would be
  81793. // appreciated but is not required.
  81794. // 2. Altered source versions must be plainly marked as such, and must not be
  81795. // misrepresented as being the original software.
  81796. // 3. This notice may not be removed or altered from any source distribution.
  81797. module.exports = {
  81798. /* Allowed flush values; see deflate() and inflate() below for details */
  81799. Z_NO_FLUSH: 0,
  81800. Z_PARTIAL_FLUSH: 1,
  81801. Z_SYNC_FLUSH: 2,
  81802. Z_FULL_FLUSH: 3,
  81803. Z_FINISH: 4,
  81804. Z_BLOCK: 5,
  81805. Z_TREES: 6,
  81806. /* Return codes for the compression/decompression functions. Negative values
  81807. * are errors, positive values are used for special but normal events.
  81808. */
  81809. Z_OK: 0,
  81810. Z_STREAM_END: 1,
  81811. Z_NEED_DICT: 2,
  81812. Z_ERRNO: -1,
  81813. Z_STREAM_ERROR: -2,
  81814. Z_DATA_ERROR: -3,
  81815. //Z_MEM_ERROR: -4,
  81816. Z_BUF_ERROR: -5,
  81817. //Z_VERSION_ERROR: -6,
  81818. /* compression levels */
  81819. Z_NO_COMPRESSION: 0,
  81820. Z_BEST_SPEED: 1,
  81821. Z_BEST_COMPRESSION: 9,
  81822. Z_DEFAULT_COMPRESSION: -1,
  81823. Z_FILTERED: 1,
  81824. Z_HUFFMAN_ONLY: 2,
  81825. Z_RLE: 3,
  81826. Z_FIXED: 4,
  81827. Z_DEFAULT_STRATEGY: 0,
  81828. /* Possible values of the data_type field (though see inflate()) */
  81829. Z_BINARY: 0,
  81830. Z_TEXT: 1,
  81831. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  81832. Z_UNKNOWN: 2,
  81833. /* The deflate compression method */
  81834. Z_DEFLATED: 8
  81835. //Z_NULL: null // Use -1 or null inline, depending on var type
  81836. };
  81837. },{}],504:[function(require,module,exports){
  81838. 'use strict';
  81839. // Note: we can't get significant speed boost here.
  81840. // So write code to minimize size - no pregenerated tables
  81841. // and array tools dependencies.
  81842. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  81843. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  81844. //
  81845. // This software is provided 'as-is', without any express or implied
  81846. // warranty. In no event will the authors be held liable for any damages
  81847. // arising from the use of this software.
  81848. //
  81849. // Permission is granted to anyone to use this software for any purpose,
  81850. // including commercial applications, and to alter it and redistribute it
  81851. // freely, subject to the following restrictions:
  81852. //
  81853. // 1. The origin of this software must not be misrepresented; you must not
  81854. // claim that you wrote the original software. If you use this software
  81855. // in a product, an acknowledgment in the product documentation would be
  81856. // appreciated but is not required.
  81857. // 2. Altered source versions must be plainly marked as such, and must not be
  81858. // misrepresented as being the original software.
  81859. // 3. This notice may not be removed or altered from any source distribution.
  81860. // Use ordinary array, since untyped makes no boost here
  81861. function makeTable() {
  81862. var c, table = [];
  81863. for (var n = 0; n < 256; n++) {
  81864. c = n;
  81865. for (var k = 0; k < 8; k++) {
  81866. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  81867. }
  81868. table[n] = c;
  81869. }
  81870. return table;
  81871. }
  81872. // Create table on load. Just 255 signed longs. Not a problem.
  81873. var crcTable = makeTable();
  81874. function crc32(crc, buf, len, pos) {
  81875. var t = crcTable,
  81876. end = pos + len;
  81877. crc ^= -1;
  81878. for (var i = pos; i < end; i++) {
  81879. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  81880. }
  81881. return (crc ^ (-1)); // >>> 0;
  81882. }
  81883. module.exports = crc32;
  81884. },{}],505:[function(require,module,exports){
  81885. 'use strict';
  81886. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  81887. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  81888. //
  81889. // This software is provided 'as-is', without any express or implied
  81890. // warranty. In no event will the authors be held liable for any damages
  81891. // arising from the use of this software.
  81892. //
  81893. // Permission is granted to anyone to use this software for any purpose,
  81894. // including commercial applications, and to alter it and redistribute it
  81895. // freely, subject to the following restrictions:
  81896. //
  81897. // 1. The origin of this software must not be misrepresented; you must not
  81898. // claim that you wrote the original software. If you use this software
  81899. // in a product, an acknowledgment in the product documentation would be
  81900. // appreciated but is not required.
  81901. // 2. Altered source versions must be plainly marked as such, and must not be
  81902. // misrepresented as being the original software.
  81903. // 3. This notice may not be removed or altered from any source distribution.
  81904. var utils = require('../utils/common');
  81905. var trees = require('./trees');
  81906. var adler32 = require('./adler32');
  81907. var crc32 = require('./crc32');
  81908. var msg = require('./messages');
  81909. /* Public constants ==========================================================*/
  81910. /* ===========================================================================*/
  81911. /* Allowed flush values; see deflate() and inflate() below for details */
  81912. var Z_NO_FLUSH = 0;
  81913. var Z_PARTIAL_FLUSH = 1;
  81914. //var Z_SYNC_FLUSH = 2;
  81915. var Z_FULL_FLUSH = 3;
  81916. var Z_FINISH = 4;
  81917. var Z_BLOCK = 5;
  81918. //var Z_TREES = 6;
  81919. /* Return codes for the compression/decompression functions. Negative values
  81920. * are errors, positive values are used for special but normal events.
  81921. */
  81922. var Z_OK = 0;
  81923. var Z_STREAM_END = 1;
  81924. //var Z_NEED_DICT = 2;
  81925. //var Z_ERRNO = -1;
  81926. var Z_STREAM_ERROR = -2;
  81927. var Z_DATA_ERROR = -3;
  81928. //var Z_MEM_ERROR = -4;
  81929. var Z_BUF_ERROR = -5;
  81930. //var Z_VERSION_ERROR = -6;
  81931. /* compression levels */
  81932. //var Z_NO_COMPRESSION = 0;
  81933. //var Z_BEST_SPEED = 1;
  81934. //var Z_BEST_COMPRESSION = 9;
  81935. var Z_DEFAULT_COMPRESSION = -1;
  81936. var Z_FILTERED = 1;
  81937. var Z_HUFFMAN_ONLY = 2;
  81938. var Z_RLE = 3;
  81939. var Z_FIXED = 4;
  81940. var Z_DEFAULT_STRATEGY = 0;
  81941. /* Possible values of the data_type field (though see inflate()) */
  81942. //var Z_BINARY = 0;
  81943. //var Z_TEXT = 1;
  81944. //var Z_ASCII = 1; // = Z_TEXT
  81945. var Z_UNKNOWN = 2;
  81946. /* The deflate compression method */
  81947. var Z_DEFLATED = 8;
  81948. /*============================================================================*/
  81949. var MAX_MEM_LEVEL = 9;
  81950. /* Maximum value for memLevel in deflateInit2 */
  81951. var MAX_WBITS = 15;
  81952. /* 32K LZ77 window */
  81953. var DEF_MEM_LEVEL = 8;
  81954. var LENGTH_CODES = 29;
  81955. /* number of length codes, not counting the special END_BLOCK code */
  81956. var LITERALS = 256;
  81957. /* number of literal bytes 0..255 */
  81958. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  81959. /* number of Literal or Length codes, including the END_BLOCK code */
  81960. var D_CODES = 30;
  81961. /* number of distance codes */
  81962. var BL_CODES = 19;
  81963. /* number of codes used to transfer the bit lengths */
  81964. var HEAP_SIZE = 2 * L_CODES + 1;
  81965. /* maximum heap size */
  81966. var MAX_BITS = 15;
  81967. /* All codes must not exceed MAX_BITS bits */
  81968. var MIN_MATCH = 3;
  81969. var MAX_MATCH = 258;
  81970. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  81971. var PRESET_DICT = 0x20;
  81972. var INIT_STATE = 42;
  81973. var EXTRA_STATE = 69;
  81974. var NAME_STATE = 73;
  81975. var COMMENT_STATE = 91;
  81976. var HCRC_STATE = 103;
  81977. var BUSY_STATE = 113;
  81978. var FINISH_STATE = 666;
  81979. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  81980. var BS_BLOCK_DONE = 2; /* block flush performed */
  81981. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  81982. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  81983. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  81984. function err(strm, errorCode) {
  81985. strm.msg = msg[errorCode];
  81986. return errorCode;
  81987. }
  81988. function rank(f) {
  81989. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  81990. }
  81991. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  81992. /* =========================================================================
  81993. * Flush as much pending output as possible. All deflate() output goes
  81994. * through this function so some applications may wish to modify it
  81995. * to avoid allocating a large strm->output buffer and copying into it.
  81996. * (See also read_buf()).
  81997. */
  81998. function flush_pending(strm) {
  81999. var s = strm.state;
  82000. //_tr_flush_bits(s);
  82001. var len = s.pending;
  82002. if (len > strm.avail_out) {
  82003. len = strm.avail_out;
  82004. }
  82005. if (len === 0) { return; }
  82006. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  82007. strm.next_out += len;
  82008. s.pending_out += len;
  82009. strm.total_out += len;
  82010. strm.avail_out -= len;
  82011. s.pending -= len;
  82012. if (s.pending === 0) {
  82013. s.pending_out = 0;
  82014. }
  82015. }
  82016. function flush_block_only(s, last) {
  82017. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  82018. s.block_start = s.strstart;
  82019. flush_pending(s.strm);
  82020. }
  82021. function put_byte(s, b) {
  82022. s.pending_buf[s.pending++] = b;
  82023. }
  82024. /* =========================================================================
  82025. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  82026. * IN assertion: the stream state is correct and there is enough room in
  82027. * pending_buf.
  82028. */
  82029. function putShortMSB(s, b) {
  82030. // put_byte(s, (Byte)(b >> 8));
  82031. // put_byte(s, (Byte)(b & 0xff));
  82032. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  82033. s.pending_buf[s.pending++] = b & 0xff;
  82034. }
  82035. /* ===========================================================================
  82036. * Read a new buffer from the current input stream, update the adler32
  82037. * and total number of bytes read. All deflate() input goes through
  82038. * this function so some applications may wish to modify it to avoid
  82039. * allocating a large strm->input buffer and copying from it.
  82040. * (See also flush_pending()).
  82041. */
  82042. function read_buf(strm, buf, start, size) {
  82043. var len = strm.avail_in;
  82044. if (len > size) { len = size; }
  82045. if (len === 0) { return 0; }
  82046. strm.avail_in -= len;
  82047. // zmemcpy(buf, strm->next_in, len);
  82048. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  82049. if (strm.state.wrap === 1) {
  82050. strm.adler = adler32(strm.adler, buf, len, start);
  82051. }
  82052. else if (strm.state.wrap === 2) {
  82053. strm.adler = crc32(strm.adler, buf, len, start);
  82054. }
  82055. strm.next_in += len;
  82056. strm.total_in += len;
  82057. return len;
  82058. }
  82059. /* ===========================================================================
  82060. * Set match_start to the longest match starting at the given string and
  82061. * return its length. Matches shorter or equal to prev_length are discarded,
  82062. * in which case the result is equal to prev_length and match_start is
  82063. * garbage.
  82064. * IN assertions: cur_match is the head of the hash chain for the current
  82065. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82066. * OUT assertion: the match length is not greater than s->lookahead.
  82067. */
  82068. function longest_match(s, cur_match) {
  82069. var chain_length = s.max_chain_length; /* max hash chain length */
  82070. var scan = s.strstart; /* current string */
  82071. var match; /* matched string */
  82072. var len; /* length of current match */
  82073. var best_len = s.prev_length; /* best match length so far */
  82074. var nice_match = s.nice_match; /* stop if match long enough */
  82075. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  82076. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  82077. var _win = s.window; // shortcut
  82078. var wmask = s.w_mask;
  82079. var prev = s.prev;
  82080. /* Stop when cur_match becomes <= limit. To simplify the code,
  82081. * we prevent matches with the string of window index 0.
  82082. */
  82083. var strend = s.strstart + MAX_MATCH;
  82084. var scan_end1 = _win[scan + best_len - 1];
  82085. var scan_end = _win[scan + best_len];
  82086. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82087. * It is easy to get rid of this optimization if necessary.
  82088. */
  82089. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82090. /* Do not waste too much time if we already have a good match: */
  82091. if (s.prev_length >= s.good_match) {
  82092. chain_length >>= 2;
  82093. }
  82094. /* Do not look for matches beyond the end of the input. This is necessary
  82095. * to make deflate deterministic.
  82096. */
  82097. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  82098. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82099. do {
  82100. // Assert(cur_match < s->strstart, "no future");
  82101. match = cur_match;
  82102. /* Skip to next match if the match length cannot increase
  82103. * or if the match length is less than 2. Note that the checks below
  82104. * for insufficient lookahead only occur occasionally for performance
  82105. * reasons. Therefore uninitialized memory will be accessed, and
  82106. * conditional jumps will be made that depend on those values.
  82107. * However the length of the match is limited to the lookahead, so
  82108. * the output of deflate is not affected by the uninitialized values.
  82109. */
  82110. if (_win[match + best_len] !== scan_end ||
  82111. _win[match + best_len - 1] !== scan_end1 ||
  82112. _win[match] !== _win[scan] ||
  82113. _win[++match] !== _win[scan + 1]) {
  82114. continue;
  82115. }
  82116. /* The check at best_len-1 can be removed because it will be made
  82117. * again later. (This heuristic is not always a win.)
  82118. * It is not necessary to compare scan[2] and match[2] since they
  82119. * are always equal when the other bytes match, given that
  82120. * the hash keys are equal and that HASH_BITS >= 8.
  82121. */
  82122. scan += 2;
  82123. match++;
  82124. // Assert(*scan == *match, "match[2]?");
  82125. /* We check for insufficient lookahead only every 8th comparison;
  82126. * the 256th check will be made at strstart+258.
  82127. */
  82128. do {
  82129. /*jshint noempty:false*/
  82130. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  82131. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  82132. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  82133. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  82134. scan < strend);
  82135. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82136. len = MAX_MATCH - (strend - scan);
  82137. scan = strend - MAX_MATCH;
  82138. if (len > best_len) {
  82139. s.match_start = cur_match;
  82140. best_len = len;
  82141. if (len >= nice_match) {
  82142. break;
  82143. }
  82144. scan_end1 = _win[scan + best_len - 1];
  82145. scan_end = _win[scan + best_len];
  82146. }
  82147. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  82148. if (best_len <= s.lookahead) {
  82149. return best_len;
  82150. }
  82151. return s.lookahead;
  82152. }
  82153. /* ===========================================================================
  82154. * Fill the window when the lookahead becomes insufficient.
  82155. * Updates strstart and lookahead.
  82156. *
  82157. * IN assertion: lookahead < MIN_LOOKAHEAD
  82158. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82159. * At least one byte has been read, or avail_in == 0; reads are
  82160. * performed for at least two bytes (required for the zip translate_eol
  82161. * option -- not supported here).
  82162. */
  82163. function fill_window(s) {
  82164. var _w_size = s.w_size;
  82165. var p, n, m, more, str;
  82166. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  82167. do {
  82168. more = s.window_size - s.lookahead - s.strstart;
  82169. // JS ints have 32 bit, block below not needed
  82170. /* Deal with !@#$% 64K limit: */
  82171. //if (sizeof(int) <= 2) {
  82172. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82173. // more = wsize;
  82174. //
  82175. // } else if (more == (unsigned)(-1)) {
  82176. // /* Very unlikely, but possible on 16 bit machine if
  82177. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  82178. // */
  82179. // more--;
  82180. // }
  82181. //}
  82182. /* If the window is almost full and there is insufficient lookahead,
  82183. * move the upper half to the lower one to make room in the upper half.
  82184. */
  82185. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  82186. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  82187. s.match_start -= _w_size;
  82188. s.strstart -= _w_size;
  82189. /* we now have strstart >= MAX_DIST */
  82190. s.block_start -= _w_size;
  82191. /* Slide the hash table (could be avoided with 32 bit values
  82192. at the expense of memory usage). We slide even when level == 0
  82193. to keep the hash table consistent if we switch back to level > 0
  82194. later. (Using level 0 permanently is not an optimal usage of
  82195. zlib, so we don't care about this pathological case.)
  82196. */
  82197. n = s.hash_size;
  82198. p = n;
  82199. do {
  82200. m = s.head[--p];
  82201. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  82202. } while (--n);
  82203. n = _w_size;
  82204. p = n;
  82205. do {
  82206. m = s.prev[--p];
  82207. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  82208. /* If n is not on any hash chain, prev[n] is garbage but
  82209. * its value will never be used.
  82210. */
  82211. } while (--n);
  82212. more += _w_size;
  82213. }
  82214. if (s.strm.avail_in === 0) {
  82215. break;
  82216. }
  82217. /* If there was no sliding:
  82218. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82219. * more == window_size - lookahead - strstart
  82220. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82221. * => more >= window_size - 2*WSIZE + 2
  82222. * In the BIG_MEM or MMAP case (not yet supported),
  82223. * window_size == input_size + MIN_LOOKAHEAD &&
  82224. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82225. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82226. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82227. */
  82228. //Assert(more >= 2, "more < 2");
  82229. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  82230. s.lookahead += n;
  82231. /* Initialize the hash value now that we have some input: */
  82232. if (s.lookahead + s.insert >= MIN_MATCH) {
  82233. str = s.strstart - s.insert;
  82234. s.ins_h = s.window[str];
  82235. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  82236. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  82237. //#if MIN_MATCH != 3
  82238. // Call update_hash() MIN_MATCH-3 more times
  82239. //#endif
  82240. while (s.insert) {
  82241. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  82242. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  82243. s.prev[str & s.w_mask] = s.head[s.ins_h];
  82244. s.head[s.ins_h] = str;
  82245. str++;
  82246. s.insert--;
  82247. if (s.lookahead + s.insert < MIN_MATCH) {
  82248. break;
  82249. }
  82250. }
  82251. }
  82252. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82253. * but this is not important since only literal bytes will be emitted.
  82254. */
  82255. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  82256. /* If the WIN_INIT bytes after the end of the current data have never been
  82257. * written, then zero those bytes in order to avoid memory check reports of
  82258. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  82259. * the longest match routines. Update the high water mark for the next
  82260. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  82261. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  82262. */
  82263. // if (s.high_water < s.window_size) {
  82264. // var curr = s.strstart + s.lookahead;
  82265. // var init = 0;
  82266. //
  82267. // if (s.high_water < curr) {
  82268. // /* Previous high water mark below current data -- zero WIN_INIT
  82269. // * bytes or up to end of window, whichever is less.
  82270. // */
  82271. // init = s.window_size - curr;
  82272. // if (init > WIN_INIT)
  82273. // init = WIN_INIT;
  82274. // zmemzero(s->window + curr, (unsigned)init);
  82275. // s->high_water = curr + init;
  82276. // }
  82277. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  82278. // /* High water mark at or above current data, but below current data
  82279. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  82280. // * to end of window, whichever is less.
  82281. // */
  82282. // init = (ulg)curr + WIN_INIT - s->high_water;
  82283. // if (init > s->window_size - s->high_water)
  82284. // init = s->window_size - s->high_water;
  82285. // zmemzero(s->window + s->high_water, (unsigned)init);
  82286. // s->high_water += init;
  82287. // }
  82288. // }
  82289. //
  82290. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  82291. // "not enough room for search");
  82292. }
  82293. /* ===========================================================================
  82294. * Copy without compression as much as possible from the input stream, return
  82295. * the current block state.
  82296. * This function does not insert new strings in the dictionary since
  82297. * uncompressible data is probably not useful. This function is used
  82298. * only for the level=0 compression option.
  82299. * NOTE: this function should be optimized to avoid extra copying from
  82300. * window to pending_buf.
  82301. */
  82302. function deflate_stored(s, flush) {
  82303. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82304. * to pending_buf_size, and each stored block has a 5 byte header:
  82305. */
  82306. var max_block_size = 0xffff;
  82307. if (max_block_size > s.pending_buf_size - 5) {
  82308. max_block_size = s.pending_buf_size - 5;
  82309. }
  82310. /* Copy as much as possible from input to output: */
  82311. for (;;) {
  82312. /* Fill the window as much as possible: */
  82313. if (s.lookahead <= 1) {
  82314. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82315. // s->block_start >= (long)s->w_size, "slide too late");
  82316. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  82317. // s.block_start >= s.w_size)) {
  82318. // throw new Error("slide too late");
  82319. // }
  82320. fill_window(s);
  82321. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  82322. return BS_NEED_MORE;
  82323. }
  82324. if (s.lookahead === 0) {
  82325. break;
  82326. }
  82327. /* flush the current block */
  82328. }
  82329. //Assert(s->block_start >= 0L, "block gone");
  82330. // if (s.block_start < 0) throw new Error("block gone");
  82331. s.strstart += s.lookahead;
  82332. s.lookahead = 0;
  82333. /* Emit a stored block if pending_buf will be full: */
  82334. var max_start = s.block_start + max_block_size;
  82335. if (s.strstart === 0 || s.strstart >= max_start) {
  82336. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82337. s.lookahead = s.strstart - max_start;
  82338. s.strstart = max_start;
  82339. /*** FLUSH_BLOCK(s, 0); ***/
  82340. flush_block_only(s, false);
  82341. if (s.strm.avail_out === 0) {
  82342. return BS_NEED_MORE;
  82343. }
  82344. /***/
  82345. }
  82346. /* Flush if we may have to slide, otherwise block_start may become
  82347. * negative and the data will be gone:
  82348. */
  82349. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  82350. /*** FLUSH_BLOCK(s, 0); ***/
  82351. flush_block_only(s, false);
  82352. if (s.strm.avail_out === 0) {
  82353. return BS_NEED_MORE;
  82354. }
  82355. /***/
  82356. }
  82357. }
  82358. s.insert = 0;
  82359. if (flush === Z_FINISH) {
  82360. /*** FLUSH_BLOCK(s, 1); ***/
  82361. flush_block_only(s, true);
  82362. if (s.strm.avail_out === 0) {
  82363. return BS_FINISH_STARTED;
  82364. }
  82365. /***/
  82366. return BS_FINISH_DONE;
  82367. }
  82368. if (s.strstart > s.block_start) {
  82369. /*** FLUSH_BLOCK(s, 0); ***/
  82370. flush_block_only(s, false);
  82371. if (s.strm.avail_out === 0) {
  82372. return BS_NEED_MORE;
  82373. }
  82374. /***/
  82375. }
  82376. return BS_NEED_MORE;
  82377. }
  82378. /* ===========================================================================
  82379. * Compress as much as possible from the input stream, return the current
  82380. * block state.
  82381. * This function does not perform lazy evaluation of matches and inserts
  82382. * new strings in the dictionary only for unmatched strings or for short
  82383. * matches. It is used only for the fast compression options.
  82384. */
  82385. function deflate_fast(s, flush) {
  82386. var hash_head; /* head of the hash chain */
  82387. var bflush; /* set if current block must be flushed */
  82388. for (;;) {
  82389. /* Make sure that we always have enough lookahead, except
  82390. * at the end of the input file. We need MAX_MATCH bytes
  82391. * for the next match, plus MIN_MATCH bytes to insert the
  82392. * string following the next match.
  82393. */
  82394. if (s.lookahead < MIN_LOOKAHEAD) {
  82395. fill_window(s);
  82396. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  82397. return BS_NEED_MORE;
  82398. }
  82399. if (s.lookahead === 0) {
  82400. break; /* flush the current block */
  82401. }
  82402. }
  82403. /* Insert the string window[strstart .. strstart+2] in the
  82404. * dictionary, and set hash_head to the head of the hash chain:
  82405. */
  82406. hash_head = 0/*NIL*/;
  82407. if (s.lookahead >= MIN_MATCH) {
  82408. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  82409. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  82410. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  82411. s.head[s.ins_h] = s.strstart;
  82412. /***/
  82413. }
  82414. /* Find the longest match, discarding those <= prev_length.
  82415. * At this point we have always match_length < MIN_MATCH
  82416. */
  82417. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  82418. /* To simplify the code, we prevent matches with the string
  82419. * of window index 0 (in particular we have to avoid a match
  82420. * of the string with itself at the start of the input file).
  82421. */
  82422. s.match_length = longest_match(s, hash_head);
  82423. /* longest_match() sets match_start */
  82424. }
  82425. if (s.match_length >= MIN_MATCH) {
  82426. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  82427. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  82428. s.match_length - MIN_MATCH, bflush); ***/
  82429. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  82430. s.lookahead -= s.match_length;
  82431. /* Insert new strings in the hash table only if the match length
  82432. * is not too large. This saves time but degrades compression.
  82433. */
  82434. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  82435. s.match_length--; /* string at strstart already in table */
  82436. do {
  82437. s.strstart++;
  82438. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  82439. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  82440. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  82441. s.head[s.ins_h] = s.strstart;
  82442. /***/
  82443. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82444. * always MIN_MATCH bytes ahead.
  82445. */
  82446. } while (--s.match_length !== 0);
  82447. s.strstart++;
  82448. } else
  82449. {
  82450. s.strstart += s.match_length;
  82451. s.match_length = 0;
  82452. s.ins_h = s.window[s.strstart];
  82453. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  82454. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  82455. //#if MIN_MATCH != 3
  82456. // Call UPDATE_HASH() MIN_MATCH-3 more times
  82457. //#endif
  82458. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82459. * matter since it will be recomputed at next deflate call.
  82460. */
  82461. }
  82462. } else {
  82463. /* No match, output a literal byte */
  82464. //Tracevv((stderr,"%c", s.window[s.strstart]));
  82465. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  82466. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  82467. s.lookahead--;
  82468. s.strstart++;
  82469. }
  82470. if (bflush) {
  82471. /*** FLUSH_BLOCK(s, 0); ***/
  82472. flush_block_only(s, false);
  82473. if (s.strm.avail_out === 0) {
  82474. return BS_NEED_MORE;
  82475. }
  82476. /***/
  82477. }
  82478. }
  82479. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  82480. if (flush === Z_FINISH) {
  82481. /*** FLUSH_BLOCK(s, 1); ***/
  82482. flush_block_only(s, true);
  82483. if (s.strm.avail_out === 0) {
  82484. return BS_FINISH_STARTED;
  82485. }
  82486. /***/
  82487. return BS_FINISH_DONE;
  82488. }
  82489. if (s.last_lit) {
  82490. /*** FLUSH_BLOCK(s, 0); ***/
  82491. flush_block_only(s, false);
  82492. if (s.strm.avail_out === 0) {
  82493. return BS_NEED_MORE;
  82494. }
  82495. /***/
  82496. }
  82497. return BS_BLOCK_DONE;
  82498. }
  82499. /* ===========================================================================
  82500. * Same as above, but achieves better compression. We use a lazy
  82501. * evaluation for matches: a match is finally adopted only if there is
  82502. * no better match at the next window position.
  82503. */
  82504. function deflate_slow(s, flush) {
  82505. var hash_head; /* head of hash chain */
  82506. var bflush; /* set if current block must be flushed */
  82507. var max_insert;
  82508. /* Process the input block. */
  82509. for (;;) {
  82510. /* Make sure that we always have enough lookahead, except
  82511. * at the end of the input file. We need MAX_MATCH bytes
  82512. * for the next match, plus MIN_MATCH bytes to insert the
  82513. * string following the next match.
  82514. */
  82515. if (s.lookahead < MIN_LOOKAHEAD) {
  82516. fill_window(s);
  82517. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  82518. return BS_NEED_MORE;
  82519. }
  82520. if (s.lookahead === 0) { break; } /* flush the current block */
  82521. }
  82522. /* Insert the string window[strstart .. strstart+2] in the
  82523. * dictionary, and set hash_head to the head of the hash chain:
  82524. */
  82525. hash_head = 0/*NIL*/;
  82526. if (s.lookahead >= MIN_MATCH) {
  82527. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  82528. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  82529. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  82530. s.head[s.ins_h] = s.strstart;
  82531. /***/
  82532. }
  82533. /* Find the longest match, discarding those <= prev_length.
  82534. */
  82535. s.prev_length = s.match_length;
  82536. s.prev_match = s.match_start;
  82537. s.match_length = MIN_MATCH - 1;
  82538. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  82539. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  82540. /* To simplify the code, we prevent matches with the string
  82541. * of window index 0 (in particular we have to avoid a match
  82542. * of the string with itself at the start of the input file).
  82543. */
  82544. s.match_length = longest_match(s, hash_head);
  82545. /* longest_match() sets match_start */
  82546. if (s.match_length <= 5 &&
  82547. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  82548. /* If prev_match is also MIN_MATCH, match_start is garbage
  82549. * but we will ignore the current match anyway.
  82550. */
  82551. s.match_length = MIN_MATCH - 1;
  82552. }
  82553. }
  82554. /* If there was a match at the previous step and the current
  82555. * match is not better, output the previous match:
  82556. */
  82557. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  82558. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  82559. /* Do not insert strings in hash table beyond this. */
  82560. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  82561. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  82562. s.prev_length - MIN_MATCH, bflush);***/
  82563. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  82564. /* Insert in hash table all strings up to the end of the match.
  82565. * strstart-1 and strstart are already inserted. If there is not
  82566. * enough lookahead, the last two strings are not inserted in
  82567. * the hash table.
  82568. */
  82569. s.lookahead -= s.prev_length - 1;
  82570. s.prev_length -= 2;
  82571. do {
  82572. if (++s.strstart <= max_insert) {
  82573. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  82574. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  82575. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  82576. s.head[s.ins_h] = s.strstart;
  82577. /***/
  82578. }
  82579. } while (--s.prev_length !== 0);
  82580. s.match_available = 0;
  82581. s.match_length = MIN_MATCH - 1;
  82582. s.strstart++;
  82583. if (bflush) {
  82584. /*** FLUSH_BLOCK(s, 0); ***/
  82585. flush_block_only(s, false);
  82586. if (s.strm.avail_out === 0) {
  82587. return BS_NEED_MORE;
  82588. }
  82589. /***/
  82590. }
  82591. } else if (s.match_available) {
  82592. /* If there was no match at the previous position, output a
  82593. * single literal. If there was a match but the current match
  82594. * is longer, truncate the previous match to a single literal.
  82595. */
  82596. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82597. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  82598. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  82599. if (bflush) {
  82600. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  82601. flush_block_only(s, false);
  82602. /***/
  82603. }
  82604. s.strstart++;
  82605. s.lookahead--;
  82606. if (s.strm.avail_out === 0) {
  82607. return BS_NEED_MORE;
  82608. }
  82609. } else {
  82610. /* There is no previous match to compare with, wait for
  82611. * the next step to decide.
  82612. */
  82613. s.match_available = 1;
  82614. s.strstart++;
  82615. s.lookahead--;
  82616. }
  82617. }
  82618. //Assert (flush != Z_NO_FLUSH, "no flush?");
  82619. if (s.match_available) {
  82620. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82621. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  82622. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  82623. s.match_available = 0;
  82624. }
  82625. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  82626. if (flush === Z_FINISH) {
  82627. /*** FLUSH_BLOCK(s, 1); ***/
  82628. flush_block_only(s, true);
  82629. if (s.strm.avail_out === 0) {
  82630. return BS_FINISH_STARTED;
  82631. }
  82632. /***/
  82633. return BS_FINISH_DONE;
  82634. }
  82635. if (s.last_lit) {
  82636. /*** FLUSH_BLOCK(s, 0); ***/
  82637. flush_block_only(s, false);
  82638. if (s.strm.avail_out === 0) {
  82639. return BS_NEED_MORE;
  82640. }
  82641. /***/
  82642. }
  82643. return BS_BLOCK_DONE;
  82644. }
  82645. /* ===========================================================================
  82646. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82647. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82648. * deflate switches away from Z_RLE.)
  82649. */
  82650. function deflate_rle(s, flush) {
  82651. var bflush; /* set if current block must be flushed */
  82652. var prev; /* byte at distance one to match */
  82653. var scan, strend; /* scan goes up to strend for length of run */
  82654. var _win = s.window;
  82655. for (;;) {
  82656. /* Make sure that we always have enough lookahead, except
  82657. * at the end of the input file. We need MAX_MATCH bytes
  82658. * for the longest run, plus one for the unrolled loop.
  82659. */
  82660. if (s.lookahead <= MAX_MATCH) {
  82661. fill_window(s);
  82662. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  82663. return BS_NEED_MORE;
  82664. }
  82665. if (s.lookahead === 0) { break; } /* flush the current block */
  82666. }
  82667. /* See how many times the previous byte repeats */
  82668. s.match_length = 0;
  82669. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  82670. scan = s.strstart - 1;
  82671. prev = _win[scan];
  82672. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  82673. strend = s.strstart + MAX_MATCH;
  82674. do {
  82675. /*jshint noempty:false*/
  82676. } while (prev === _win[++scan] && prev === _win[++scan] &&
  82677. prev === _win[++scan] && prev === _win[++scan] &&
  82678. prev === _win[++scan] && prev === _win[++scan] &&
  82679. prev === _win[++scan] && prev === _win[++scan] &&
  82680. scan < strend);
  82681. s.match_length = MAX_MATCH - (strend - scan);
  82682. if (s.match_length > s.lookahead) {
  82683. s.match_length = s.lookahead;
  82684. }
  82685. }
  82686. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  82687. }
  82688. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82689. if (s.match_length >= MIN_MATCH) {
  82690. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  82691. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  82692. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  82693. s.lookahead -= s.match_length;
  82694. s.strstart += s.match_length;
  82695. s.match_length = 0;
  82696. } else {
  82697. /* No match, output a literal byte */
  82698. //Tracevv((stderr,"%c", s->window[s->strstart]));
  82699. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  82700. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  82701. s.lookahead--;
  82702. s.strstart++;
  82703. }
  82704. if (bflush) {
  82705. /*** FLUSH_BLOCK(s, 0); ***/
  82706. flush_block_only(s, false);
  82707. if (s.strm.avail_out === 0) {
  82708. return BS_NEED_MORE;
  82709. }
  82710. /***/
  82711. }
  82712. }
  82713. s.insert = 0;
  82714. if (flush === Z_FINISH) {
  82715. /*** FLUSH_BLOCK(s, 1); ***/
  82716. flush_block_only(s, true);
  82717. if (s.strm.avail_out === 0) {
  82718. return BS_FINISH_STARTED;
  82719. }
  82720. /***/
  82721. return BS_FINISH_DONE;
  82722. }
  82723. if (s.last_lit) {
  82724. /*** FLUSH_BLOCK(s, 0); ***/
  82725. flush_block_only(s, false);
  82726. if (s.strm.avail_out === 0) {
  82727. return BS_NEED_MORE;
  82728. }
  82729. /***/
  82730. }
  82731. return BS_BLOCK_DONE;
  82732. }
  82733. /* ===========================================================================
  82734. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  82735. * (It will be regenerated if this run of deflate switches away from Huffman.)
  82736. */
  82737. function deflate_huff(s, flush) {
  82738. var bflush; /* set if current block must be flushed */
  82739. for (;;) {
  82740. /* Make sure that we have a literal to write. */
  82741. if (s.lookahead === 0) {
  82742. fill_window(s);
  82743. if (s.lookahead === 0) {
  82744. if (flush === Z_NO_FLUSH) {
  82745. return BS_NEED_MORE;
  82746. }
  82747. break; /* flush the current block */
  82748. }
  82749. }
  82750. /* Output a literal byte */
  82751. s.match_length = 0;
  82752. //Tracevv((stderr,"%c", s->window[s->strstart]));
  82753. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  82754. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  82755. s.lookahead--;
  82756. s.strstart++;
  82757. if (bflush) {
  82758. /*** FLUSH_BLOCK(s, 0); ***/
  82759. flush_block_only(s, false);
  82760. if (s.strm.avail_out === 0) {
  82761. return BS_NEED_MORE;
  82762. }
  82763. /***/
  82764. }
  82765. }
  82766. s.insert = 0;
  82767. if (flush === Z_FINISH) {
  82768. /*** FLUSH_BLOCK(s, 1); ***/
  82769. flush_block_only(s, true);
  82770. if (s.strm.avail_out === 0) {
  82771. return BS_FINISH_STARTED;
  82772. }
  82773. /***/
  82774. return BS_FINISH_DONE;
  82775. }
  82776. if (s.last_lit) {
  82777. /*** FLUSH_BLOCK(s, 0); ***/
  82778. flush_block_only(s, false);
  82779. if (s.strm.avail_out === 0) {
  82780. return BS_NEED_MORE;
  82781. }
  82782. /***/
  82783. }
  82784. return BS_BLOCK_DONE;
  82785. }
  82786. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  82787. * the desired pack level (0..9). The values given below have been tuned to
  82788. * exclude worst case performance for pathological files. Better values may be
  82789. * found for specific files.
  82790. */
  82791. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  82792. this.good_length = good_length;
  82793. this.max_lazy = max_lazy;
  82794. this.nice_length = nice_length;
  82795. this.max_chain = max_chain;
  82796. this.func = func;
  82797. }
  82798. var configuration_table;
  82799. configuration_table = [
  82800. /* good lazy nice chain */
  82801. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  82802. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  82803. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  82804. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  82805. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  82806. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  82807. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  82808. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  82809. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  82810. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  82811. ];
  82812. /* ===========================================================================
  82813. * Initialize the "longest match" routines for a new zlib stream
  82814. */
  82815. function lm_init(s) {
  82816. s.window_size = 2 * s.w_size;
  82817. /*** CLEAR_HASH(s); ***/
  82818. zero(s.head); // Fill with NIL (= 0);
  82819. /* Set the default configuration parameters:
  82820. */
  82821. s.max_lazy_match = configuration_table[s.level].max_lazy;
  82822. s.good_match = configuration_table[s.level].good_length;
  82823. s.nice_match = configuration_table[s.level].nice_length;
  82824. s.max_chain_length = configuration_table[s.level].max_chain;
  82825. s.strstart = 0;
  82826. s.block_start = 0;
  82827. s.lookahead = 0;
  82828. s.insert = 0;
  82829. s.match_length = s.prev_length = MIN_MATCH - 1;
  82830. s.match_available = 0;
  82831. s.ins_h = 0;
  82832. }
  82833. function DeflateState() {
  82834. this.strm = null; /* pointer back to this zlib stream */
  82835. this.status = 0; /* as the name implies */
  82836. this.pending_buf = null; /* output still pending */
  82837. this.pending_buf_size = 0; /* size of pending_buf */
  82838. this.pending_out = 0; /* next pending byte to output to the stream */
  82839. this.pending = 0; /* nb of bytes in the pending buffer */
  82840. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  82841. this.gzhead = null; /* gzip header information to write */
  82842. this.gzindex = 0; /* where in extra, name, or comment */
  82843. this.method = Z_DEFLATED; /* can only be DEFLATED */
  82844. this.last_flush = -1; /* value of flush param for previous deflate call */
  82845. this.w_size = 0; /* LZ77 window size (32K by default) */
  82846. this.w_bits = 0; /* log2(w_size) (8..16) */
  82847. this.w_mask = 0; /* w_size - 1 */
  82848. this.window = null;
  82849. /* Sliding window. Input bytes are read into the second half of the window,
  82850. * and move to the first half later to keep a dictionary of at least wSize
  82851. * bytes. With this organization, matches are limited to a distance of
  82852. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  82853. * performed with a length multiple of the block size.
  82854. */
  82855. this.window_size = 0;
  82856. /* Actual size of window: 2*wSize, except when the user input buffer
  82857. * is directly used as sliding window.
  82858. */
  82859. this.prev = null;
  82860. /* Link to older string with same hash index. To limit the size of this
  82861. * array to 64K, this link is maintained only for the last 32K strings.
  82862. * An index in this array is thus a window index modulo 32K.
  82863. */
  82864. this.head = null; /* Heads of the hash chains or NIL. */
  82865. this.ins_h = 0; /* hash index of string to be inserted */
  82866. this.hash_size = 0; /* number of elements in hash table */
  82867. this.hash_bits = 0; /* log2(hash_size) */
  82868. this.hash_mask = 0; /* hash_size-1 */
  82869. this.hash_shift = 0;
  82870. /* Number of bits by which ins_h must be shifted at each input
  82871. * step. It must be such that after MIN_MATCH steps, the oldest
  82872. * byte no longer takes part in the hash key, that is:
  82873. * hash_shift * MIN_MATCH >= hash_bits
  82874. */
  82875. this.block_start = 0;
  82876. /* Window position at the beginning of the current output block. Gets
  82877. * negative when the window is moved backwards.
  82878. */
  82879. this.match_length = 0; /* length of best match */
  82880. this.prev_match = 0; /* previous match */
  82881. this.match_available = 0; /* set if previous match exists */
  82882. this.strstart = 0; /* start of string to insert */
  82883. this.match_start = 0; /* start of matching string */
  82884. this.lookahead = 0; /* number of valid bytes ahead in window */
  82885. this.prev_length = 0;
  82886. /* Length of the best match at previous step. Matches not greater than this
  82887. * are discarded. This is used in the lazy match evaluation.
  82888. */
  82889. this.max_chain_length = 0;
  82890. /* To speed up deflation, hash chains are never searched beyond this
  82891. * length. A higher limit improves compression ratio but degrades the
  82892. * speed.
  82893. */
  82894. this.max_lazy_match = 0;
  82895. /* Attempt to find a better match only when the current match is strictly
  82896. * smaller than this value. This mechanism is used only for compression
  82897. * levels >= 4.
  82898. */
  82899. // That's alias to max_lazy_match, don't use directly
  82900. //this.max_insert_length = 0;
  82901. /* Insert new strings in the hash table only if the match length is not
  82902. * greater than this length. This saves time but degrades compression.
  82903. * max_insert_length is used only for compression levels <= 3.
  82904. */
  82905. this.level = 0; /* compression level (1..9) */
  82906. this.strategy = 0; /* favor or force Huffman coding*/
  82907. this.good_match = 0;
  82908. /* Use a faster search when the previous match is longer than this */
  82909. this.nice_match = 0; /* Stop searching when current match exceeds this */
  82910. /* used by trees.c: */
  82911. /* Didn't use ct_data typedef below to suppress compiler warning */
  82912. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  82913. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  82914. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  82915. // Use flat array of DOUBLE size, with interleaved fata,
  82916. // because JS does not support effective
  82917. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  82918. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  82919. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  82920. zero(this.dyn_ltree);
  82921. zero(this.dyn_dtree);
  82922. zero(this.bl_tree);
  82923. this.l_desc = null; /* desc. for literal tree */
  82924. this.d_desc = null; /* desc. for distance tree */
  82925. this.bl_desc = null; /* desc. for bit length tree */
  82926. //ush bl_count[MAX_BITS+1];
  82927. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  82928. /* number of codes at each bit length for an optimal tree */
  82929. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  82930. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  82931. zero(this.heap);
  82932. this.heap_len = 0; /* number of elements in the heap */
  82933. this.heap_max = 0; /* element of largest frequency */
  82934. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  82935. * The same heap array is used to build all trees.
  82936. */
  82937. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  82938. zero(this.depth);
  82939. /* Depth of each subtree used as tie breaker for trees of equal frequency
  82940. */
  82941. this.l_buf = 0; /* buffer index for literals or lengths */
  82942. this.lit_bufsize = 0;
  82943. /* Size of match buffer for literals/lengths. There are 4 reasons for
  82944. * limiting lit_bufsize to 64K:
  82945. * - frequencies can be kept in 16 bit counters
  82946. * - if compression is not successful for the first block, all input
  82947. * data is still in the window so we can still emit a stored block even
  82948. * when input comes from standard input. (This can also be done for
  82949. * all blocks if lit_bufsize is not greater than 32K.)
  82950. * - if compression is not successful for a file smaller than 64K, we can
  82951. * even emit a stored file instead of a stored block (saving 5 bytes).
  82952. * This is applicable only for zip (not gzip or zlib).
  82953. * - creating new Huffman trees less frequently may not provide fast
  82954. * adaptation to changes in the input data statistics. (Take for
  82955. * example a binary file with poorly compressible code followed by
  82956. * a highly compressible string table.) Smaller buffer sizes give
  82957. * fast adaptation but have of course the overhead of transmitting
  82958. * trees more frequently.
  82959. * - I can't count above 4
  82960. */
  82961. this.last_lit = 0; /* running index in l_buf */
  82962. this.d_buf = 0;
  82963. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  82964. * the same number of elements. To use different lengths, an extra flag
  82965. * array would be necessary.
  82966. */
  82967. this.opt_len = 0; /* bit length of current block with optimal trees */
  82968. this.static_len = 0; /* bit length of current block with static trees */
  82969. this.matches = 0; /* number of string matches in current block */
  82970. this.insert = 0; /* bytes at end of window left to insert */
  82971. this.bi_buf = 0;
  82972. /* Output buffer. bits are inserted starting at the bottom (least
  82973. * significant bits).
  82974. */
  82975. this.bi_valid = 0;
  82976. /* Number of valid bits in bi_buf. All bits above the last valid bit
  82977. * are always zero.
  82978. */
  82979. // Used for window memory init. We safely ignore it for JS. That makes
  82980. // sense only for pointers and memory check tools.
  82981. //this.high_water = 0;
  82982. /* High water mark offset in window for initialized bytes -- bytes above
  82983. * this are set to zero in order to avoid memory check warnings when
  82984. * longest match routines access bytes past the input. This is then
  82985. * updated to the new high water mark.
  82986. */
  82987. }
  82988. function deflateResetKeep(strm) {
  82989. var s;
  82990. if (!strm || !strm.state) {
  82991. return err(strm, Z_STREAM_ERROR);
  82992. }
  82993. strm.total_in = strm.total_out = 0;
  82994. strm.data_type = Z_UNKNOWN;
  82995. s = strm.state;
  82996. s.pending = 0;
  82997. s.pending_out = 0;
  82998. if (s.wrap < 0) {
  82999. s.wrap = -s.wrap;
  83000. /* was made negative by deflate(..., Z_FINISH); */
  83001. }
  83002. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  83003. strm.adler = (s.wrap === 2) ?
  83004. 0 // crc32(0, Z_NULL, 0)
  83005. :
  83006. 1; // adler32(0, Z_NULL, 0)
  83007. s.last_flush = Z_NO_FLUSH;
  83008. trees._tr_init(s);
  83009. return Z_OK;
  83010. }
  83011. function deflateReset(strm) {
  83012. var ret = deflateResetKeep(strm);
  83013. if (ret === Z_OK) {
  83014. lm_init(strm.state);
  83015. }
  83016. return ret;
  83017. }
  83018. function deflateSetHeader(strm, head) {
  83019. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  83020. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  83021. strm.state.gzhead = head;
  83022. return Z_OK;
  83023. }
  83024. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  83025. if (!strm) { // === Z_NULL
  83026. return Z_STREAM_ERROR;
  83027. }
  83028. var wrap = 1;
  83029. if (level === Z_DEFAULT_COMPRESSION) {
  83030. level = 6;
  83031. }
  83032. if (windowBits < 0) { /* suppress zlib wrapper */
  83033. wrap = 0;
  83034. windowBits = -windowBits;
  83035. }
  83036. else if (windowBits > 15) {
  83037. wrap = 2; /* write gzip wrapper instead */
  83038. windowBits -= 16;
  83039. }
  83040. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  83041. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  83042. strategy < 0 || strategy > Z_FIXED) {
  83043. return err(strm, Z_STREAM_ERROR);
  83044. }
  83045. if (windowBits === 8) {
  83046. windowBits = 9;
  83047. }
  83048. /* until 256-byte window bug fixed */
  83049. var s = new DeflateState();
  83050. strm.state = s;
  83051. s.strm = strm;
  83052. s.wrap = wrap;
  83053. s.gzhead = null;
  83054. s.w_bits = windowBits;
  83055. s.w_size = 1 << s.w_bits;
  83056. s.w_mask = s.w_size - 1;
  83057. s.hash_bits = memLevel + 7;
  83058. s.hash_size = 1 << s.hash_bits;
  83059. s.hash_mask = s.hash_size - 1;
  83060. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  83061. s.window = new utils.Buf8(s.w_size * 2);
  83062. s.head = new utils.Buf16(s.hash_size);
  83063. s.prev = new utils.Buf16(s.w_size);
  83064. // Don't need mem init magic for JS.
  83065. //s.high_water = 0; /* nothing written to s->window yet */
  83066. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  83067. s.pending_buf_size = s.lit_bufsize * 4;
  83068. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  83069. //s->pending_buf = (uchf *) overlay;
  83070. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  83071. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  83072. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  83073. s.d_buf = 1 * s.lit_bufsize;
  83074. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  83075. s.l_buf = (1 + 2) * s.lit_bufsize;
  83076. s.level = level;
  83077. s.strategy = strategy;
  83078. s.method = method;
  83079. return deflateReset(strm);
  83080. }
  83081. function deflateInit(strm, level) {
  83082. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  83083. }
  83084. function deflate(strm, flush) {
  83085. var old_flush, s;
  83086. var beg, val; // for gzip header write only
  83087. if (!strm || !strm.state ||
  83088. flush > Z_BLOCK || flush < 0) {
  83089. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  83090. }
  83091. s = strm.state;
  83092. if (!strm.output ||
  83093. (!strm.input && strm.avail_in !== 0) ||
  83094. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  83095. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  83096. }
  83097. s.strm = strm; /* just in case */
  83098. old_flush = s.last_flush;
  83099. s.last_flush = flush;
  83100. /* Write the header */
  83101. if (s.status === INIT_STATE) {
  83102. if (s.wrap === 2) { // GZIP header
  83103. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  83104. put_byte(s, 31);
  83105. put_byte(s, 139);
  83106. put_byte(s, 8);
  83107. if (!s.gzhead) { // s->gzhead == Z_NULL
  83108. put_byte(s, 0);
  83109. put_byte(s, 0);
  83110. put_byte(s, 0);
  83111. put_byte(s, 0);
  83112. put_byte(s, 0);
  83113. put_byte(s, s.level === 9 ? 2 :
  83114. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  83115. 4 : 0));
  83116. put_byte(s, OS_CODE);
  83117. s.status = BUSY_STATE;
  83118. }
  83119. else {
  83120. put_byte(s, (s.gzhead.text ? 1 : 0) +
  83121. (s.gzhead.hcrc ? 2 : 0) +
  83122. (!s.gzhead.extra ? 0 : 4) +
  83123. (!s.gzhead.name ? 0 : 8) +
  83124. (!s.gzhead.comment ? 0 : 16)
  83125. );
  83126. put_byte(s, s.gzhead.time & 0xff);
  83127. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  83128. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  83129. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  83130. put_byte(s, s.level === 9 ? 2 :
  83131. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  83132. 4 : 0));
  83133. put_byte(s, s.gzhead.os & 0xff);
  83134. if (s.gzhead.extra && s.gzhead.extra.length) {
  83135. put_byte(s, s.gzhead.extra.length & 0xff);
  83136. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  83137. }
  83138. if (s.gzhead.hcrc) {
  83139. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  83140. }
  83141. s.gzindex = 0;
  83142. s.status = EXTRA_STATE;
  83143. }
  83144. }
  83145. else // DEFLATE header
  83146. {
  83147. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  83148. var level_flags = -1;
  83149. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  83150. level_flags = 0;
  83151. } else if (s.level < 6) {
  83152. level_flags = 1;
  83153. } else if (s.level === 6) {
  83154. level_flags = 2;
  83155. } else {
  83156. level_flags = 3;
  83157. }
  83158. header |= (level_flags << 6);
  83159. if (s.strstart !== 0) { header |= PRESET_DICT; }
  83160. header += 31 - (header % 31);
  83161. s.status = BUSY_STATE;
  83162. putShortMSB(s, header);
  83163. /* Save the adler32 of the preset dictionary: */
  83164. if (s.strstart !== 0) {
  83165. putShortMSB(s, strm.adler >>> 16);
  83166. putShortMSB(s, strm.adler & 0xffff);
  83167. }
  83168. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  83169. }
  83170. }
  83171. //#ifdef GZIP
  83172. if (s.status === EXTRA_STATE) {
  83173. if (s.gzhead.extra/* != Z_NULL*/) {
  83174. beg = s.pending; /* start of bytes to update crc */
  83175. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  83176. if (s.pending === s.pending_buf_size) {
  83177. if (s.gzhead.hcrc && s.pending > beg) {
  83178. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  83179. }
  83180. flush_pending(strm);
  83181. beg = s.pending;
  83182. if (s.pending === s.pending_buf_size) {
  83183. break;
  83184. }
  83185. }
  83186. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  83187. s.gzindex++;
  83188. }
  83189. if (s.gzhead.hcrc && s.pending > beg) {
  83190. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  83191. }
  83192. if (s.gzindex === s.gzhead.extra.length) {
  83193. s.gzindex = 0;
  83194. s.status = NAME_STATE;
  83195. }
  83196. }
  83197. else {
  83198. s.status = NAME_STATE;
  83199. }
  83200. }
  83201. if (s.status === NAME_STATE) {
  83202. if (s.gzhead.name/* != Z_NULL*/) {
  83203. beg = s.pending; /* start of bytes to update crc */
  83204. //int val;
  83205. do {
  83206. if (s.pending === s.pending_buf_size) {
  83207. if (s.gzhead.hcrc && s.pending > beg) {
  83208. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  83209. }
  83210. flush_pending(strm);
  83211. beg = s.pending;
  83212. if (s.pending === s.pending_buf_size) {
  83213. val = 1;
  83214. break;
  83215. }
  83216. }
  83217. // JS specific: little magic to add zero terminator to end of string
  83218. if (s.gzindex < s.gzhead.name.length) {
  83219. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  83220. } else {
  83221. val = 0;
  83222. }
  83223. put_byte(s, val);
  83224. } while (val !== 0);
  83225. if (s.gzhead.hcrc && s.pending > beg) {
  83226. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  83227. }
  83228. if (val === 0) {
  83229. s.gzindex = 0;
  83230. s.status = COMMENT_STATE;
  83231. }
  83232. }
  83233. else {
  83234. s.status = COMMENT_STATE;
  83235. }
  83236. }
  83237. if (s.status === COMMENT_STATE) {
  83238. if (s.gzhead.comment/* != Z_NULL*/) {
  83239. beg = s.pending; /* start of bytes to update crc */
  83240. //int val;
  83241. do {
  83242. if (s.pending === s.pending_buf_size) {
  83243. if (s.gzhead.hcrc && s.pending > beg) {
  83244. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  83245. }
  83246. flush_pending(strm);
  83247. beg = s.pending;
  83248. if (s.pending === s.pending_buf_size) {
  83249. val = 1;
  83250. break;
  83251. }
  83252. }
  83253. // JS specific: little magic to add zero terminator to end of string
  83254. if (s.gzindex < s.gzhead.comment.length) {
  83255. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  83256. } else {
  83257. val = 0;
  83258. }
  83259. put_byte(s, val);
  83260. } while (val !== 0);
  83261. if (s.gzhead.hcrc && s.pending > beg) {
  83262. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  83263. }
  83264. if (val === 0) {
  83265. s.status = HCRC_STATE;
  83266. }
  83267. }
  83268. else {
  83269. s.status = HCRC_STATE;
  83270. }
  83271. }
  83272. if (s.status === HCRC_STATE) {
  83273. if (s.gzhead.hcrc) {
  83274. if (s.pending + 2 > s.pending_buf_size) {
  83275. flush_pending(strm);
  83276. }
  83277. if (s.pending + 2 <= s.pending_buf_size) {
  83278. put_byte(s, strm.adler & 0xff);
  83279. put_byte(s, (strm.adler >> 8) & 0xff);
  83280. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  83281. s.status = BUSY_STATE;
  83282. }
  83283. }
  83284. else {
  83285. s.status = BUSY_STATE;
  83286. }
  83287. }
  83288. //#endif
  83289. /* Flush as much pending output as possible */
  83290. if (s.pending !== 0) {
  83291. flush_pending(strm);
  83292. if (strm.avail_out === 0) {
  83293. /* Since avail_out is 0, deflate will be called again with
  83294. * more output space, but possibly with both pending and
  83295. * avail_in equal to zero. There won't be anything to do,
  83296. * but this is not an error situation so make sure we
  83297. * return OK instead of BUF_ERROR at next call of deflate:
  83298. */
  83299. s.last_flush = -1;
  83300. return Z_OK;
  83301. }
  83302. /* Make sure there is something to do and avoid duplicate consecutive
  83303. * flushes. For repeated and useless calls with Z_FINISH, we keep
  83304. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  83305. */
  83306. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  83307. flush !== Z_FINISH) {
  83308. return err(strm, Z_BUF_ERROR);
  83309. }
  83310. /* User must not provide more input after the first FINISH: */
  83311. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  83312. return err(strm, Z_BUF_ERROR);
  83313. }
  83314. /* Start a new block or continue the current one.
  83315. */
  83316. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  83317. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  83318. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  83319. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  83320. configuration_table[s.level].func(s, flush));
  83321. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  83322. s.status = FINISH_STATE;
  83323. }
  83324. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  83325. if (strm.avail_out === 0) {
  83326. s.last_flush = -1;
  83327. /* avoid BUF_ERROR next call, see above */
  83328. }
  83329. return Z_OK;
  83330. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  83331. * of deflate should use the same flush parameter to make sure
  83332. * that the flush is complete. So we don't have to output an
  83333. * empty block here, this will be done at next call. This also
  83334. * ensures that for a very small output buffer, we emit at most
  83335. * one empty block.
  83336. */
  83337. }
  83338. if (bstate === BS_BLOCK_DONE) {
  83339. if (flush === Z_PARTIAL_FLUSH) {
  83340. trees._tr_align(s);
  83341. }
  83342. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  83343. trees._tr_stored_block(s, 0, 0, false);
  83344. /* For a full flush, this empty block will be recognized
  83345. * as a special marker by inflate_sync().
  83346. */
  83347. if (flush === Z_FULL_FLUSH) {
  83348. /*** CLEAR_HASH(s); ***/ /* forget history */
  83349. zero(s.head); // Fill with NIL (= 0);
  83350. if (s.lookahead === 0) {
  83351. s.strstart = 0;
  83352. s.block_start = 0;
  83353. s.insert = 0;
  83354. }
  83355. }
  83356. }
  83357. flush_pending(strm);
  83358. if (strm.avail_out === 0) {
  83359. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  83360. return Z_OK;
  83361. }
  83362. }
  83363. }
  83364. //Assert(strm->avail_out > 0, "bug2");
  83365. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  83366. if (flush !== Z_FINISH) { return Z_OK; }
  83367. if (s.wrap <= 0) { return Z_STREAM_END; }
  83368. /* Write the trailer */
  83369. if (s.wrap === 2) {
  83370. put_byte(s, strm.adler & 0xff);
  83371. put_byte(s, (strm.adler >> 8) & 0xff);
  83372. put_byte(s, (strm.adler >> 16) & 0xff);
  83373. put_byte(s, (strm.adler >> 24) & 0xff);
  83374. put_byte(s, strm.total_in & 0xff);
  83375. put_byte(s, (strm.total_in >> 8) & 0xff);
  83376. put_byte(s, (strm.total_in >> 16) & 0xff);
  83377. put_byte(s, (strm.total_in >> 24) & 0xff);
  83378. }
  83379. else
  83380. {
  83381. putShortMSB(s, strm.adler >>> 16);
  83382. putShortMSB(s, strm.adler & 0xffff);
  83383. }
  83384. flush_pending(strm);
  83385. /* If avail_out is zero, the application will call deflate again
  83386. * to flush the rest.
  83387. */
  83388. if (s.wrap > 0) { s.wrap = -s.wrap; }
  83389. /* write the trailer only once! */
  83390. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  83391. }
  83392. function deflateEnd(strm) {
  83393. var status;
  83394. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  83395. return Z_STREAM_ERROR;
  83396. }
  83397. status = strm.state.status;
  83398. if (status !== INIT_STATE &&
  83399. status !== EXTRA_STATE &&
  83400. status !== NAME_STATE &&
  83401. status !== COMMENT_STATE &&
  83402. status !== HCRC_STATE &&
  83403. status !== BUSY_STATE &&
  83404. status !== FINISH_STATE
  83405. ) {
  83406. return err(strm, Z_STREAM_ERROR);
  83407. }
  83408. strm.state = null;
  83409. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  83410. }
  83411. /* =========================================================================
  83412. * Initializes the compression dictionary from the given byte
  83413. * sequence without producing any compressed output.
  83414. */
  83415. function deflateSetDictionary(strm, dictionary) {
  83416. var dictLength = dictionary.length;
  83417. var s;
  83418. var str, n;
  83419. var wrap;
  83420. var avail;
  83421. var next;
  83422. var input;
  83423. var tmpDict;
  83424. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  83425. return Z_STREAM_ERROR;
  83426. }
  83427. s = strm.state;
  83428. wrap = s.wrap;
  83429. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  83430. return Z_STREAM_ERROR;
  83431. }
  83432. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  83433. if (wrap === 1) {
  83434. /* adler32(strm->adler, dictionary, dictLength); */
  83435. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  83436. }
  83437. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  83438. /* if dictionary would fill window, just replace the history */
  83439. if (dictLength >= s.w_size) {
  83440. if (wrap === 0) { /* already empty otherwise */
  83441. /*** CLEAR_HASH(s); ***/
  83442. zero(s.head); // Fill with NIL (= 0);
  83443. s.strstart = 0;
  83444. s.block_start = 0;
  83445. s.insert = 0;
  83446. }
  83447. /* use the tail */
  83448. // dictionary = dictionary.slice(dictLength - s.w_size);
  83449. tmpDict = new utils.Buf8(s.w_size);
  83450. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  83451. dictionary = tmpDict;
  83452. dictLength = s.w_size;
  83453. }
  83454. /* insert dictionary into window and hash */
  83455. avail = strm.avail_in;
  83456. next = strm.next_in;
  83457. input = strm.input;
  83458. strm.avail_in = dictLength;
  83459. strm.next_in = 0;
  83460. strm.input = dictionary;
  83461. fill_window(s);
  83462. while (s.lookahead >= MIN_MATCH) {
  83463. str = s.strstart;
  83464. n = s.lookahead - (MIN_MATCH - 1);
  83465. do {
  83466. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  83467. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  83468. s.prev[str & s.w_mask] = s.head[s.ins_h];
  83469. s.head[s.ins_h] = str;
  83470. str++;
  83471. } while (--n);
  83472. s.strstart = str;
  83473. s.lookahead = MIN_MATCH - 1;
  83474. fill_window(s);
  83475. }
  83476. s.strstart += s.lookahead;
  83477. s.block_start = s.strstart;
  83478. s.insert = s.lookahead;
  83479. s.lookahead = 0;
  83480. s.match_length = s.prev_length = MIN_MATCH - 1;
  83481. s.match_available = 0;
  83482. strm.next_in = next;
  83483. strm.input = input;
  83484. strm.avail_in = avail;
  83485. s.wrap = wrap;
  83486. return Z_OK;
  83487. }
  83488. exports.deflateInit = deflateInit;
  83489. exports.deflateInit2 = deflateInit2;
  83490. exports.deflateReset = deflateReset;
  83491. exports.deflateResetKeep = deflateResetKeep;
  83492. exports.deflateSetHeader = deflateSetHeader;
  83493. exports.deflate = deflate;
  83494. exports.deflateEnd = deflateEnd;
  83495. exports.deflateSetDictionary = deflateSetDictionary;
  83496. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  83497. /* Not implemented
  83498. exports.deflateBound = deflateBound;
  83499. exports.deflateCopy = deflateCopy;
  83500. exports.deflateParams = deflateParams;
  83501. exports.deflatePending = deflatePending;
  83502. exports.deflatePrime = deflatePrime;
  83503. exports.deflateTune = deflateTune;
  83504. */
  83505. },{"../utils/common":501,"./adler32":502,"./crc32":504,"./messages":509,"./trees":510}],506:[function(require,module,exports){
  83506. 'use strict';
  83507. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  83508. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  83509. //
  83510. // This software is provided 'as-is', without any express or implied
  83511. // warranty. In no event will the authors be held liable for any damages
  83512. // arising from the use of this software.
  83513. //
  83514. // Permission is granted to anyone to use this software for any purpose,
  83515. // including commercial applications, and to alter it and redistribute it
  83516. // freely, subject to the following restrictions:
  83517. //
  83518. // 1. The origin of this software must not be misrepresented; you must not
  83519. // claim that you wrote the original software. If you use this software
  83520. // in a product, an acknowledgment in the product documentation would be
  83521. // appreciated but is not required.
  83522. // 2. Altered source versions must be plainly marked as such, and must not be
  83523. // misrepresented as being the original software.
  83524. // 3. This notice may not be removed or altered from any source distribution.
  83525. // See state defs from inflate.js
  83526. var BAD = 30; /* got a data error -- remain here until reset */
  83527. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  83528. /*
  83529. Decode literal, length, and distance codes and write out the resulting
  83530. literal and match bytes until either not enough input or output is
  83531. available, an end-of-block is encountered, or a data error is encountered.
  83532. When large enough input and output buffers are supplied to inflate(), for
  83533. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83534. inflate execution time is spent in this routine.
  83535. Entry assumptions:
  83536. state.mode === LEN
  83537. strm.avail_in >= 6
  83538. strm.avail_out >= 258
  83539. start >= strm.avail_out
  83540. state.bits < 8
  83541. On return, state.mode is one of:
  83542. LEN -- ran out of enough output space or enough available input
  83543. TYPE -- reached end of block code, inflate() to interpret next block
  83544. BAD -- error in block data
  83545. Notes:
  83546. - The maximum input bits used by a length/distance pair is 15 bits for the
  83547. length code, 5 bits for the length extra, 15 bits for the distance code,
  83548. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83549. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  83550. checking for available input while decoding.
  83551. - The maximum bytes that a single length/distance pair can output is 258
  83552. bytes, which is the maximum length that can be coded. inflate_fast()
  83553. requires strm.avail_out >= 258 for each loop to avoid checking for
  83554. output space.
  83555. */
  83556. module.exports = function inflate_fast(strm, start) {
  83557. var state;
  83558. var _in; /* local strm.input */
  83559. var last; /* have enough input while in < last */
  83560. var _out; /* local strm.output */
  83561. var beg; /* inflate()'s initial strm.output */
  83562. var end; /* while out < end, enough space available */
  83563. //#ifdef INFLATE_STRICT
  83564. var dmax; /* maximum distance from zlib header */
  83565. //#endif
  83566. var wsize; /* window size or zero if not using window */
  83567. var whave; /* valid bytes in the window */
  83568. var wnext; /* window write index */
  83569. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  83570. var s_window; /* allocated sliding window, if wsize != 0 */
  83571. var hold; /* local strm.hold */
  83572. var bits; /* local strm.bits */
  83573. var lcode; /* local strm.lencode */
  83574. var dcode; /* local strm.distcode */
  83575. var lmask; /* mask for first level of length codes */
  83576. var dmask; /* mask for first level of distance codes */
  83577. var here; /* retrieved table entry */
  83578. var op; /* code bits, operation, extra bits, or */
  83579. /* window position, window bytes to copy */
  83580. var len; /* match length, unused bytes */
  83581. var dist; /* match distance */
  83582. var from; /* where to copy match from */
  83583. var from_source;
  83584. var input, output; // JS specific, because we have no pointers
  83585. /* copy state to local variables */
  83586. state = strm.state;
  83587. //here = state.here;
  83588. _in = strm.next_in;
  83589. input = strm.input;
  83590. last = _in + (strm.avail_in - 5);
  83591. _out = strm.next_out;
  83592. output = strm.output;
  83593. beg = _out - (start - strm.avail_out);
  83594. end = _out + (strm.avail_out - 257);
  83595. //#ifdef INFLATE_STRICT
  83596. dmax = state.dmax;
  83597. //#endif
  83598. wsize = state.wsize;
  83599. whave = state.whave;
  83600. wnext = state.wnext;
  83601. s_window = state.window;
  83602. hold = state.hold;
  83603. bits = state.bits;
  83604. lcode = state.lencode;
  83605. dcode = state.distcode;
  83606. lmask = (1 << state.lenbits) - 1;
  83607. dmask = (1 << state.distbits) - 1;
  83608. /* decode literals and length/distances until end-of-block or not enough
  83609. input data or output space */
  83610. top:
  83611. do {
  83612. if (bits < 15) {
  83613. hold += input[_in++] << bits;
  83614. bits += 8;
  83615. hold += input[_in++] << bits;
  83616. bits += 8;
  83617. }
  83618. here = lcode[hold & lmask];
  83619. dolen:
  83620. for (;;) { // Goto emulation
  83621. op = here >>> 24/*here.bits*/;
  83622. hold >>>= op;
  83623. bits -= op;
  83624. op = (here >>> 16) & 0xff/*here.op*/;
  83625. if (op === 0) { /* literal */
  83626. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  83627. // "inflate: literal '%c'\n" :
  83628. // "inflate: literal 0x%02x\n", here.val));
  83629. output[_out++] = here & 0xffff/*here.val*/;
  83630. }
  83631. else if (op & 16) { /* length base */
  83632. len = here & 0xffff/*here.val*/;
  83633. op &= 15; /* number of extra bits */
  83634. if (op) {
  83635. if (bits < op) {
  83636. hold += input[_in++] << bits;
  83637. bits += 8;
  83638. }
  83639. len += hold & ((1 << op) - 1);
  83640. hold >>>= op;
  83641. bits -= op;
  83642. }
  83643. //Tracevv((stderr, "inflate: length %u\n", len));
  83644. if (bits < 15) {
  83645. hold += input[_in++] << bits;
  83646. bits += 8;
  83647. hold += input[_in++] << bits;
  83648. bits += 8;
  83649. }
  83650. here = dcode[hold & dmask];
  83651. dodist:
  83652. for (;;) { // goto emulation
  83653. op = here >>> 24/*here.bits*/;
  83654. hold >>>= op;
  83655. bits -= op;
  83656. op = (here >>> 16) & 0xff/*here.op*/;
  83657. if (op & 16) { /* distance base */
  83658. dist = here & 0xffff/*here.val*/;
  83659. op &= 15; /* number of extra bits */
  83660. if (bits < op) {
  83661. hold += input[_in++] << bits;
  83662. bits += 8;
  83663. if (bits < op) {
  83664. hold += input[_in++] << bits;
  83665. bits += 8;
  83666. }
  83667. }
  83668. dist += hold & ((1 << op) - 1);
  83669. //#ifdef INFLATE_STRICT
  83670. if (dist > dmax) {
  83671. strm.msg = 'invalid distance too far back';
  83672. state.mode = BAD;
  83673. break top;
  83674. }
  83675. //#endif
  83676. hold >>>= op;
  83677. bits -= op;
  83678. //Tracevv((stderr, "inflate: distance %u\n", dist));
  83679. op = _out - beg; /* max distance in output */
  83680. if (dist > op) { /* see if copy from window */
  83681. op = dist - op; /* distance back in window */
  83682. if (op > whave) {
  83683. if (state.sane) {
  83684. strm.msg = 'invalid distance too far back';
  83685. state.mode = BAD;
  83686. break top;
  83687. }
  83688. // (!) This block is disabled in zlib defaults,
  83689. // don't enable it for binary compatibility
  83690. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  83691. // if (len <= op - whave) {
  83692. // do {
  83693. // output[_out++] = 0;
  83694. // } while (--len);
  83695. // continue top;
  83696. // }
  83697. // len -= op - whave;
  83698. // do {
  83699. // output[_out++] = 0;
  83700. // } while (--op > whave);
  83701. // if (op === 0) {
  83702. // from = _out - dist;
  83703. // do {
  83704. // output[_out++] = output[from++];
  83705. // } while (--len);
  83706. // continue top;
  83707. // }
  83708. //#endif
  83709. }
  83710. from = 0; // window index
  83711. from_source = s_window;
  83712. if (wnext === 0) { /* very common case */
  83713. from += wsize - op;
  83714. if (op < len) { /* some from window */
  83715. len -= op;
  83716. do {
  83717. output[_out++] = s_window[from++];
  83718. } while (--op);
  83719. from = _out - dist; /* rest from output */
  83720. from_source = output;
  83721. }
  83722. }
  83723. else if (wnext < op) { /* wrap around window */
  83724. from += wsize + wnext - op;
  83725. op -= wnext;
  83726. if (op < len) { /* some from end of window */
  83727. len -= op;
  83728. do {
  83729. output[_out++] = s_window[from++];
  83730. } while (--op);
  83731. from = 0;
  83732. if (wnext < len) { /* some from start of window */
  83733. op = wnext;
  83734. len -= op;
  83735. do {
  83736. output[_out++] = s_window[from++];
  83737. } while (--op);
  83738. from = _out - dist; /* rest from output */
  83739. from_source = output;
  83740. }
  83741. }
  83742. }
  83743. else { /* contiguous in window */
  83744. from += wnext - op;
  83745. if (op < len) { /* some from window */
  83746. len -= op;
  83747. do {
  83748. output[_out++] = s_window[from++];
  83749. } while (--op);
  83750. from = _out - dist; /* rest from output */
  83751. from_source = output;
  83752. }
  83753. }
  83754. while (len > 2) {
  83755. output[_out++] = from_source[from++];
  83756. output[_out++] = from_source[from++];
  83757. output[_out++] = from_source[from++];
  83758. len -= 3;
  83759. }
  83760. if (len) {
  83761. output[_out++] = from_source[from++];
  83762. if (len > 1) {
  83763. output[_out++] = from_source[from++];
  83764. }
  83765. }
  83766. }
  83767. else {
  83768. from = _out - dist; /* copy direct from output */
  83769. do { /* minimum length is three */
  83770. output[_out++] = output[from++];
  83771. output[_out++] = output[from++];
  83772. output[_out++] = output[from++];
  83773. len -= 3;
  83774. } while (len > 2);
  83775. if (len) {
  83776. output[_out++] = output[from++];
  83777. if (len > 1) {
  83778. output[_out++] = output[from++];
  83779. }
  83780. }
  83781. }
  83782. }
  83783. else if ((op & 64) === 0) { /* 2nd level distance code */
  83784. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  83785. continue dodist;
  83786. }
  83787. else {
  83788. strm.msg = 'invalid distance code';
  83789. state.mode = BAD;
  83790. break top;
  83791. }
  83792. break; // need to emulate goto via "continue"
  83793. }
  83794. }
  83795. else if ((op & 64) === 0) { /* 2nd level length code */
  83796. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  83797. continue dolen;
  83798. }
  83799. else if (op & 32) { /* end-of-block */
  83800. //Tracevv((stderr, "inflate: end of block\n"));
  83801. state.mode = TYPE;
  83802. break top;
  83803. }
  83804. else {
  83805. strm.msg = 'invalid literal/length code';
  83806. state.mode = BAD;
  83807. break top;
  83808. }
  83809. break; // need to emulate goto via "continue"
  83810. }
  83811. } while (_in < last && _out < end);
  83812. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83813. len = bits >> 3;
  83814. _in -= len;
  83815. bits -= len << 3;
  83816. hold &= (1 << bits) - 1;
  83817. /* update state and return */
  83818. strm.next_in = _in;
  83819. strm.next_out = _out;
  83820. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  83821. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  83822. state.hold = hold;
  83823. state.bits = bits;
  83824. return;
  83825. };
  83826. },{}],507:[function(require,module,exports){
  83827. 'use strict';
  83828. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  83829. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  83830. //
  83831. // This software is provided 'as-is', without any express or implied
  83832. // warranty. In no event will the authors be held liable for any damages
  83833. // arising from the use of this software.
  83834. //
  83835. // Permission is granted to anyone to use this software for any purpose,
  83836. // including commercial applications, and to alter it and redistribute it
  83837. // freely, subject to the following restrictions:
  83838. //
  83839. // 1. The origin of this software must not be misrepresented; you must not
  83840. // claim that you wrote the original software. If you use this software
  83841. // in a product, an acknowledgment in the product documentation would be
  83842. // appreciated but is not required.
  83843. // 2. Altered source versions must be plainly marked as such, and must not be
  83844. // misrepresented as being the original software.
  83845. // 3. This notice may not be removed or altered from any source distribution.
  83846. var utils = require('../utils/common');
  83847. var adler32 = require('./adler32');
  83848. var crc32 = require('./crc32');
  83849. var inflate_fast = require('./inffast');
  83850. var inflate_table = require('./inftrees');
  83851. var CODES = 0;
  83852. var LENS = 1;
  83853. var DISTS = 2;
  83854. /* Public constants ==========================================================*/
  83855. /* ===========================================================================*/
  83856. /* Allowed flush values; see deflate() and inflate() below for details */
  83857. //var Z_NO_FLUSH = 0;
  83858. //var Z_PARTIAL_FLUSH = 1;
  83859. //var Z_SYNC_FLUSH = 2;
  83860. //var Z_FULL_FLUSH = 3;
  83861. var Z_FINISH = 4;
  83862. var Z_BLOCK = 5;
  83863. var Z_TREES = 6;
  83864. /* Return codes for the compression/decompression functions. Negative values
  83865. * are errors, positive values are used for special but normal events.
  83866. */
  83867. var Z_OK = 0;
  83868. var Z_STREAM_END = 1;
  83869. var Z_NEED_DICT = 2;
  83870. //var Z_ERRNO = -1;
  83871. var Z_STREAM_ERROR = -2;
  83872. var Z_DATA_ERROR = -3;
  83873. var Z_MEM_ERROR = -4;
  83874. var Z_BUF_ERROR = -5;
  83875. //var Z_VERSION_ERROR = -6;
  83876. /* The deflate compression method */
  83877. var Z_DEFLATED = 8;
  83878. /* STATES ====================================================================*/
  83879. /* ===========================================================================*/
  83880. var HEAD = 1; /* i: waiting for magic header */
  83881. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  83882. var TIME = 3; /* i: waiting for modification time (gzip) */
  83883. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  83884. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  83885. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  83886. var NAME = 7; /* i: waiting for end of file name (gzip) */
  83887. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  83888. var HCRC = 9; /* i: waiting for header crc (gzip) */
  83889. var DICTID = 10; /* i: waiting for dictionary check value */
  83890. var DICT = 11; /* waiting for inflateSetDictionary() call */
  83891. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  83892. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  83893. var STORED = 14; /* i: waiting for stored size (length and complement) */
  83894. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  83895. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  83896. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  83897. var LENLENS = 18; /* i: waiting for code length code lengths */
  83898. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  83899. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  83900. var LEN = 21; /* i: waiting for length/lit/eob code */
  83901. var LENEXT = 22; /* i: waiting for length extra bits */
  83902. var DIST = 23; /* i: waiting for distance code */
  83903. var DISTEXT = 24; /* i: waiting for distance extra bits */
  83904. var MATCH = 25; /* o: waiting for output space to copy string */
  83905. var LIT = 26; /* o: waiting for output space to write literal */
  83906. var CHECK = 27; /* i: waiting for 32-bit check value */
  83907. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  83908. var DONE = 29; /* finished check, done -- remain here until reset */
  83909. var BAD = 30; /* got a data error -- remain here until reset */
  83910. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  83911. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  83912. /* ===========================================================================*/
  83913. var ENOUGH_LENS = 852;
  83914. var ENOUGH_DISTS = 592;
  83915. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  83916. var MAX_WBITS = 15;
  83917. /* 32K LZ77 window */
  83918. var DEF_WBITS = MAX_WBITS;
  83919. function zswap32(q) {
  83920. return (((q >>> 24) & 0xff) +
  83921. ((q >>> 8) & 0xff00) +
  83922. ((q & 0xff00) << 8) +
  83923. ((q & 0xff) << 24));
  83924. }
  83925. function InflateState() {
  83926. this.mode = 0; /* current inflate mode */
  83927. this.last = false; /* true if processing last block */
  83928. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  83929. this.havedict = false; /* true if dictionary provided */
  83930. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  83931. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  83932. this.check = 0; /* protected copy of check value */
  83933. this.total = 0; /* protected copy of output count */
  83934. // TODO: may be {}
  83935. this.head = null; /* where to save gzip header information */
  83936. /* sliding window */
  83937. this.wbits = 0; /* log base 2 of requested window size */
  83938. this.wsize = 0; /* window size or zero if not using window */
  83939. this.whave = 0; /* valid bytes in the window */
  83940. this.wnext = 0; /* window write index */
  83941. this.window = null; /* allocated sliding window, if needed */
  83942. /* bit accumulator */
  83943. this.hold = 0; /* input bit accumulator */
  83944. this.bits = 0; /* number of bits in "in" */
  83945. /* for string and stored block copying */
  83946. this.length = 0; /* literal or length of data to copy */
  83947. this.offset = 0; /* distance back to copy string from */
  83948. /* for table and code decoding */
  83949. this.extra = 0; /* extra bits needed */
  83950. /* fixed and dynamic code tables */
  83951. this.lencode = null; /* starting table for length/literal codes */
  83952. this.distcode = null; /* starting table for distance codes */
  83953. this.lenbits = 0; /* index bits for lencode */
  83954. this.distbits = 0; /* index bits for distcode */
  83955. /* dynamic table building */
  83956. this.ncode = 0; /* number of code length code lengths */
  83957. this.nlen = 0; /* number of length code lengths */
  83958. this.ndist = 0; /* number of distance code lengths */
  83959. this.have = 0; /* number of code lengths in lens[] */
  83960. this.next = null; /* next available space in codes[] */
  83961. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  83962. this.work = new utils.Buf16(288); /* work area for code table building */
  83963. /*
  83964. because we don't have pointers in js, we use lencode and distcode directly
  83965. as buffers so we don't need codes
  83966. */
  83967. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  83968. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  83969. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  83970. this.sane = 0; /* if false, allow invalid distance too far */
  83971. this.back = 0; /* bits back of last unprocessed length/lit */
  83972. this.was = 0; /* initial length of match */
  83973. }
  83974. function inflateResetKeep(strm) {
  83975. var state;
  83976. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  83977. state = strm.state;
  83978. strm.total_in = strm.total_out = state.total = 0;
  83979. strm.msg = ''; /*Z_NULL*/
  83980. if (state.wrap) { /* to support ill-conceived Java test suite */
  83981. strm.adler = state.wrap & 1;
  83982. }
  83983. state.mode = HEAD;
  83984. state.last = 0;
  83985. state.havedict = 0;
  83986. state.dmax = 32768;
  83987. state.head = null/*Z_NULL*/;
  83988. state.hold = 0;
  83989. state.bits = 0;
  83990. //state.lencode = state.distcode = state.next = state.codes;
  83991. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  83992. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  83993. state.sane = 1;
  83994. state.back = -1;
  83995. //Tracev((stderr, "inflate: reset\n"));
  83996. return Z_OK;
  83997. }
  83998. function inflateReset(strm) {
  83999. var state;
  84000. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  84001. state = strm.state;
  84002. state.wsize = 0;
  84003. state.whave = 0;
  84004. state.wnext = 0;
  84005. return inflateResetKeep(strm);
  84006. }
  84007. function inflateReset2(strm, windowBits) {
  84008. var wrap;
  84009. var state;
  84010. /* get the state */
  84011. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  84012. state = strm.state;
  84013. /* extract wrap request from windowBits parameter */
  84014. if (windowBits < 0) {
  84015. wrap = 0;
  84016. windowBits = -windowBits;
  84017. }
  84018. else {
  84019. wrap = (windowBits >> 4) + 1;
  84020. if (windowBits < 48) {
  84021. windowBits &= 15;
  84022. }
  84023. }
  84024. /* set number of window bits, free window if different */
  84025. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  84026. return Z_STREAM_ERROR;
  84027. }
  84028. if (state.window !== null && state.wbits !== windowBits) {
  84029. state.window = null;
  84030. }
  84031. /* update state and reset the rest of it */
  84032. state.wrap = wrap;
  84033. state.wbits = windowBits;
  84034. return inflateReset(strm);
  84035. }
  84036. function inflateInit2(strm, windowBits) {
  84037. var ret;
  84038. var state;
  84039. if (!strm) { return Z_STREAM_ERROR; }
  84040. //strm.msg = Z_NULL; /* in case we return an error */
  84041. state = new InflateState();
  84042. //if (state === Z_NULL) return Z_MEM_ERROR;
  84043. //Tracev((stderr, "inflate: allocated\n"));
  84044. strm.state = state;
  84045. state.window = null/*Z_NULL*/;
  84046. ret = inflateReset2(strm, windowBits);
  84047. if (ret !== Z_OK) {
  84048. strm.state = null/*Z_NULL*/;
  84049. }
  84050. return ret;
  84051. }
  84052. function inflateInit(strm) {
  84053. return inflateInit2(strm, DEF_WBITS);
  84054. }
  84055. /*
  84056. Return state with length and distance decoding tables and index sizes set to
  84057. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  84058. If BUILDFIXED is defined, then instead this routine builds the tables the
  84059. first time it's called, and returns those tables the first time and
  84060. thereafter. This reduces the size of the code by about 2K bytes, in
  84061. exchange for a little execution time. However, BUILDFIXED should not be
  84062. used for threaded applications, since the rewriting of the tables and virgin
  84063. may not be thread-safe.
  84064. */
  84065. var virgin = true;
  84066. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  84067. function fixedtables(state) {
  84068. /* build fixed huffman tables if first call (may not be thread safe) */
  84069. if (virgin) {
  84070. var sym;
  84071. lenfix = new utils.Buf32(512);
  84072. distfix = new utils.Buf32(32);
  84073. /* literal/length table */
  84074. sym = 0;
  84075. while (sym < 144) { state.lens[sym++] = 8; }
  84076. while (sym < 256) { state.lens[sym++] = 9; }
  84077. while (sym < 280) { state.lens[sym++] = 7; }
  84078. while (sym < 288) { state.lens[sym++] = 8; }
  84079. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  84080. /* distance table */
  84081. sym = 0;
  84082. while (sym < 32) { state.lens[sym++] = 5; }
  84083. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  84084. /* do this just once */
  84085. virgin = false;
  84086. }
  84087. state.lencode = lenfix;
  84088. state.lenbits = 9;
  84089. state.distcode = distfix;
  84090. state.distbits = 5;
  84091. }
  84092. /*
  84093. Update the window with the last wsize (normally 32K) bytes written before
  84094. returning. If window does not exist yet, create it. This is only called
  84095. when a window is already in use, or when output has been written during this
  84096. inflate call, but the end of the deflate stream has not been reached yet.
  84097. It is also called to create a window for dictionary data when a dictionary
  84098. is loaded.
  84099. Providing output buffers larger than 32K to inflate() should provide a speed
  84100. advantage, since only the last 32K of output is copied to the sliding window
  84101. upon return from inflate(), and since all distances after the first 32K of
  84102. output will fall in the output data, making match copies simpler and faster.
  84103. The advantage may be dependent on the size of the processor's data caches.
  84104. */
  84105. function updatewindow(strm, src, end, copy) {
  84106. var dist;
  84107. var state = strm.state;
  84108. /* if it hasn't been done already, allocate space for the window */
  84109. if (state.window === null) {
  84110. state.wsize = 1 << state.wbits;
  84111. state.wnext = 0;
  84112. state.whave = 0;
  84113. state.window = new utils.Buf8(state.wsize);
  84114. }
  84115. /* copy state->wsize or less output bytes into the circular window */
  84116. if (copy >= state.wsize) {
  84117. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  84118. state.wnext = 0;
  84119. state.whave = state.wsize;
  84120. }
  84121. else {
  84122. dist = state.wsize - state.wnext;
  84123. if (dist > copy) {
  84124. dist = copy;
  84125. }
  84126. //zmemcpy(state->window + state->wnext, end - copy, dist);
  84127. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  84128. copy -= dist;
  84129. if (copy) {
  84130. //zmemcpy(state->window, end - copy, copy);
  84131. utils.arraySet(state.window, src, end - copy, copy, 0);
  84132. state.wnext = copy;
  84133. state.whave = state.wsize;
  84134. }
  84135. else {
  84136. state.wnext += dist;
  84137. if (state.wnext === state.wsize) { state.wnext = 0; }
  84138. if (state.whave < state.wsize) { state.whave += dist; }
  84139. }
  84140. }
  84141. return 0;
  84142. }
  84143. function inflate(strm, flush) {
  84144. var state;
  84145. var input, output; // input/output buffers
  84146. var next; /* next input INDEX */
  84147. var put; /* next output INDEX */
  84148. var have, left; /* available input and output */
  84149. var hold; /* bit buffer */
  84150. var bits; /* bits in bit buffer */
  84151. var _in, _out; /* save starting available input and output */
  84152. var copy; /* number of stored or match bytes to copy */
  84153. var from; /* where to copy match bytes from */
  84154. var from_source;
  84155. var here = 0; /* current decoding table entry */
  84156. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  84157. //var last; /* parent table entry */
  84158. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  84159. var len; /* length to copy for repeats, bits to drop */
  84160. var ret; /* return code */
  84161. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  84162. var opts;
  84163. var n; // temporary var for NEED_BITS
  84164. var order = /* permutation of code lengths */
  84165. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  84166. if (!strm || !strm.state || !strm.output ||
  84167. (!strm.input && strm.avail_in !== 0)) {
  84168. return Z_STREAM_ERROR;
  84169. }
  84170. state = strm.state;
  84171. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  84172. //--- LOAD() ---
  84173. put = strm.next_out;
  84174. output = strm.output;
  84175. left = strm.avail_out;
  84176. next = strm.next_in;
  84177. input = strm.input;
  84178. have = strm.avail_in;
  84179. hold = state.hold;
  84180. bits = state.bits;
  84181. //---
  84182. _in = have;
  84183. _out = left;
  84184. ret = Z_OK;
  84185. inf_leave: // goto emulation
  84186. for (;;) {
  84187. switch (state.mode) {
  84188. case HEAD:
  84189. if (state.wrap === 0) {
  84190. state.mode = TYPEDO;
  84191. break;
  84192. }
  84193. //=== NEEDBITS(16);
  84194. while (bits < 16) {
  84195. if (have === 0) { break inf_leave; }
  84196. have--;
  84197. hold += input[next++] << bits;
  84198. bits += 8;
  84199. }
  84200. //===//
  84201. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  84202. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  84203. //=== CRC2(state.check, hold);
  84204. hbuf[0] = hold & 0xff;
  84205. hbuf[1] = (hold >>> 8) & 0xff;
  84206. state.check = crc32(state.check, hbuf, 2, 0);
  84207. //===//
  84208. //=== INITBITS();
  84209. hold = 0;
  84210. bits = 0;
  84211. //===//
  84212. state.mode = FLAGS;
  84213. break;
  84214. }
  84215. state.flags = 0; /* expect zlib header */
  84216. if (state.head) {
  84217. state.head.done = false;
  84218. }
  84219. if (!(state.wrap & 1) || /* check if zlib header allowed */
  84220. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  84221. strm.msg = 'incorrect header check';
  84222. state.mode = BAD;
  84223. break;
  84224. }
  84225. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  84226. strm.msg = 'unknown compression method';
  84227. state.mode = BAD;
  84228. break;
  84229. }
  84230. //--- DROPBITS(4) ---//
  84231. hold >>>= 4;
  84232. bits -= 4;
  84233. //---//
  84234. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  84235. if (state.wbits === 0) {
  84236. state.wbits = len;
  84237. }
  84238. else if (len > state.wbits) {
  84239. strm.msg = 'invalid window size';
  84240. state.mode = BAD;
  84241. break;
  84242. }
  84243. state.dmax = 1 << len;
  84244. //Tracev((stderr, "inflate: zlib header ok\n"));
  84245. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  84246. state.mode = hold & 0x200 ? DICTID : TYPE;
  84247. //=== INITBITS();
  84248. hold = 0;
  84249. bits = 0;
  84250. //===//
  84251. break;
  84252. case FLAGS:
  84253. //=== NEEDBITS(16); */
  84254. while (bits < 16) {
  84255. if (have === 0) { break inf_leave; }
  84256. have--;
  84257. hold += input[next++] << bits;
  84258. bits += 8;
  84259. }
  84260. //===//
  84261. state.flags = hold;
  84262. if ((state.flags & 0xff) !== Z_DEFLATED) {
  84263. strm.msg = 'unknown compression method';
  84264. state.mode = BAD;
  84265. break;
  84266. }
  84267. if (state.flags & 0xe000) {
  84268. strm.msg = 'unknown header flags set';
  84269. state.mode = BAD;
  84270. break;
  84271. }
  84272. if (state.head) {
  84273. state.head.text = ((hold >> 8) & 1);
  84274. }
  84275. if (state.flags & 0x0200) {
  84276. //=== CRC2(state.check, hold);
  84277. hbuf[0] = hold & 0xff;
  84278. hbuf[1] = (hold >>> 8) & 0xff;
  84279. state.check = crc32(state.check, hbuf, 2, 0);
  84280. //===//
  84281. }
  84282. //=== INITBITS();
  84283. hold = 0;
  84284. bits = 0;
  84285. //===//
  84286. state.mode = TIME;
  84287. /* falls through */
  84288. case TIME:
  84289. //=== NEEDBITS(32); */
  84290. while (bits < 32) {
  84291. if (have === 0) { break inf_leave; }
  84292. have--;
  84293. hold += input[next++] << bits;
  84294. bits += 8;
  84295. }
  84296. //===//
  84297. if (state.head) {
  84298. state.head.time = hold;
  84299. }
  84300. if (state.flags & 0x0200) {
  84301. //=== CRC4(state.check, hold)
  84302. hbuf[0] = hold & 0xff;
  84303. hbuf[1] = (hold >>> 8) & 0xff;
  84304. hbuf[2] = (hold >>> 16) & 0xff;
  84305. hbuf[3] = (hold >>> 24) & 0xff;
  84306. state.check = crc32(state.check, hbuf, 4, 0);
  84307. //===
  84308. }
  84309. //=== INITBITS();
  84310. hold = 0;
  84311. bits = 0;
  84312. //===//
  84313. state.mode = OS;
  84314. /* falls through */
  84315. case OS:
  84316. //=== NEEDBITS(16); */
  84317. while (bits < 16) {
  84318. if (have === 0) { break inf_leave; }
  84319. have--;
  84320. hold += input[next++] << bits;
  84321. bits += 8;
  84322. }
  84323. //===//
  84324. if (state.head) {
  84325. state.head.xflags = (hold & 0xff);
  84326. state.head.os = (hold >> 8);
  84327. }
  84328. if (state.flags & 0x0200) {
  84329. //=== CRC2(state.check, hold);
  84330. hbuf[0] = hold & 0xff;
  84331. hbuf[1] = (hold >>> 8) & 0xff;
  84332. state.check = crc32(state.check, hbuf, 2, 0);
  84333. //===//
  84334. }
  84335. //=== INITBITS();
  84336. hold = 0;
  84337. bits = 0;
  84338. //===//
  84339. state.mode = EXLEN;
  84340. /* falls through */
  84341. case EXLEN:
  84342. if (state.flags & 0x0400) {
  84343. //=== NEEDBITS(16); */
  84344. while (bits < 16) {
  84345. if (have === 0) { break inf_leave; }
  84346. have--;
  84347. hold += input[next++] << bits;
  84348. bits += 8;
  84349. }
  84350. //===//
  84351. state.length = hold;
  84352. if (state.head) {
  84353. state.head.extra_len = hold;
  84354. }
  84355. if (state.flags & 0x0200) {
  84356. //=== CRC2(state.check, hold);
  84357. hbuf[0] = hold & 0xff;
  84358. hbuf[1] = (hold >>> 8) & 0xff;
  84359. state.check = crc32(state.check, hbuf, 2, 0);
  84360. //===//
  84361. }
  84362. //=== INITBITS();
  84363. hold = 0;
  84364. bits = 0;
  84365. //===//
  84366. }
  84367. else if (state.head) {
  84368. state.head.extra = null/*Z_NULL*/;
  84369. }
  84370. state.mode = EXTRA;
  84371. /* falls through */
  84372. case EXTRA:
  84373. if (state.flags & 0x0400) {
  84374. copy = state.length;
  84375. if (copy > have) { copy = have; }
  84376. if (copy) {
  84377. if (state.head) {
  84378. len = state.head.extra_len - state.length;
  84379. if (!state.head.extra) {
  84380. // Use untyped array for more convenient processing later
  84381. state.head.extra = new Array(state.head.extra_len);
  84382. }
  84383. utils.arraySet(
  84384. state.head.extra,
  84385. input,
  84386. next,
  84387. // extra field is limited to 65536 bytes
  84388. // - no need for additional size check
  84389. copy,
  84390. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  84391. len
  84392. );
  84393. //zmemcpy(state.head.extra + len, next,
  84394. // len + copy > state.head.extra_max ?
  84395. // state.head.extra_max - len : copy);
  84396. }
  84397. if (state.flags & 0x0200) {
  84398. state.check = crc32(state.check, input, copy, next);
  84399. }
  84400. have -= copy;
  84401. next += copy;
  84402. state.length -= copy;
  84403. }
  84404. if (state.length) { break inf_leave; }
  84405. }
  84406. state.length = 0;
  84407. state.mode = NAME;
  84408. /* falls through */
  84409. case NAME:
  84410. if (state.flags & 0x0800) {
  84411. if (have === 0) { break inf_leave; }
  84412. copy = 0;
  84413. do {
  84414. // TODO: 2 or 1 bytes?
  84415. len = input[next + copy++];
  84416. /* use constant limit because in js we should not preallocate memory */
  84417. if (state.head && len &&
  84418. (state.length < 65536 /*state.head.name_max*/)) {
  84419. state.head.name += String.fromCharCode(len);
  84420. }
  84421. } while (len && copy < have);
  84422. if (state.flags & 0x0200) {
  84423. state.check = crc32(state.check, input, copy, next);
  84424. }
  84425. have -= copy;
  84426. next += copy;
  84427. if (len) { break inf_leave; }
  84428. }
  84429. else if (state.head) {
  84430. state.head.name = null;
  84431. }
  84432. state.length = 0;
  84433. state.mode = COMMENT;
  84434. /* falls through */
  84435. case COMMENT:
  84436. if (state.flags & 0x1000) {
  84437. if (have === 0) { break inf_leave; }
  84438. copy = 0;
  84439. do {
  84440. len = input[next + copy++];
  84441. /* use constant limit because in js we should not preallocate memory */
  84442. if (state.head && len &&
  84443. (state.length < 65536 /*state.head.comm_max*/)) {
  84444. state.head.comment += String.fromCharCode(len);
  84445. }
  84446. } while (len && copy < have);
  84447. if (state.flags & 0x0200) {
  84448. state.check = crc32(state.check, input, copy, next);
  84449. }
  84450. have -= copy;
  84451. next += copy;
  84452. if (len) { break inf_leave; }
  84453. }
  84454. else if (state.head) {
  84455. state.head.comment = null;
  84456. }
  84457. state.mode = HCRC;
  84458. /* falls through */
  84459. case HCRC:
  84460. if (state.flags & 0x0200) {
  84461. //=== NEEDBITS(16); */
  84462. while (bits < 16) {
  84463. if (have === 0) { break inf_leave; }
  84464. have--;
  84465. hold += input[next++] << bits;
  84466. bits += 8;
  84467. }
  84468. //===//
  84469. if (hold !== (state.check & 0xffff)) {
  84470. strm.msg = 'header crc mismatch';
  84471. state.mode = BAD;
  84472. break;
  84473. }
  84474. //=== INITBITS();
  84475. hold = 0;
  84476. bits = 0;
  84477. //===//
  84478. }
  84479. if (state.head) {
  84480. state.head.hcrc = ((state.flags >> 9) & 1);
  84481. state.head.done = true;
  84482. }
  84483. strm.adler = state.check = 0;
  84484. state.mode = TYPE;
  84485. break;
  84486. case DICTID:
  84487. //=== NEEDBITS(32); */
  84488. while (bits < 32) {
  84489. if (have === 0) { break inf_leave; }
  84490. have--;
  84491. hold += input[next++] << bits;
  84492. bits += 8;
  84493. }
  84494. //===//
  84495. strm.adler = state.check = zswap32(hold);
  84496. //=== INITBITS();
  84497. hold = 0;
  84498. bits = 0;
  84499. //===//
  84500. state.mode = DICT;
  84501. /* falls through */
  84502. case DICT:
  84503. if (state.havedict === 0) {
  84504. //--- RESTORE() ---
  84505. strm.next_out = put;
  84506. strm.avail_out = left;
  84507. strm.next_in = next;
  84508. strm.avail_in = have;
  84509. state.hold = hold;
  84510. state.bits = bits;
  84511. //---
  84512. return Z_NEED_DICT;
  84513. }
  84514. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  84515. state.mode = TYPE;
  84516. /* falls through */
  84517. case TYPE:
  84518. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  84519. /* falls through */
  84520. case TYPEDO:
  84521. if (state.last) {
  84522. //--- BYTEBITS() ---//
  84523. hold >>>= bits & 7;
  84524. bits -= bits & 7;
  84525. //---//
  84526. state.mode = CHECK;
  84527. break;
  84528. }
  84529. //=== NEEDBITS(3); */
  84530. while (bits < 3) {
  84531. if (have === 0) { break inf_leave; }
  84532. have--;
  84533. hold += input[next++] << bits;
  84534. bits += 8;
  84535. }
  84536. //===//
  84537. state.last = (hold & 0x01)/*BITS(1)*/;
  84538. //--- DROPBITS(1) ---//
  84539. hold >>>= 1;
  84540. bits -= 1;
  84541. //---//
  84542. switch ((hold & 0x03)/*BITS(2)*/) {
  84543. case 0: /* stored block */
  84544. //Tracev((stderr, "inflate: stored block%s\n",
  84545. // state.last ? " (last)" : ""));
  84546. state.mode = STORED;
  84547. break;
  84548. case 1: /* fixed block */
  84549. fixedtables(state);
  84550. //Tracev((stderr, "inflate: fixed codes block%s\n",
  84551. // state.last ? " (last)" : ""));
  84552. state.mode = LEN_; /* decode codes */
  84553. if (flush === Z_TREES) {
  84554. //--- DROPBITS(2) ---//
  84555. hold >>>= 2;
  84556. bits -= 2;
  84557. //---//
  84558. break inf_leave;
  84559. }
  84560. break;
  84561. case 2: /* dynamic block */
  84562. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  84563. // state.last ? " (last)" : ""));
  84564. state.mode = TABLE;
  84565. break;
  84566. case 3:
  84567. strm.msg = 'invalid block type';
  84568. state.mode = BAD;
  84569. }
  84570. //--- DROPBITS(2) ---//
  84571. hold >>>= 2;
  84572. bits -= 2;
  84573. //---//
  84574. break;
  84575. case STORED:
  84576. //--- BYTEBITS() ---// /* go to byte boundary */
  84577. hold >>>= bits & 7;
  84578. bits -= bits & 7;
  84579. //---//
  84580. //=== NEEDBITS(32); */
  84581. while (bits < 32) {
  84582. if (have === 0) { break inf_leave; }
  84583. have--;
  84584. hold += input[next++] << bits;
  84585. bits += 8;
  84586. }
  84587. //===//
  84588. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  84589. strm.msg = 'invalid stored block lengths';
  84590. state.mode = BAD;
  84591. break;
  84592. }
  84593. state.length = hold & 0xffff;
  84594. //Tracev((stderr, "inflate: stored length %u\n",
  84595. // state.length));
  84596. //=== INITBITS();
  84597. hold = 0;
  84598. bits = 0;
  84599. //===//
  84600. state.mode = COPY_;
  84601. if (flush === Z_TREES) { break inf_leave; }
  84602. /* falls through */
  84603. case COPY_:
  84604. state.mode = COPY;
  84605. /* falls through */
  84606. case COPY:
  84607. copy = state.length;
  84608. if (copy) {
  84609. if (copy > have) { copy = have; }
  84610. if (copy > left) { copy = left; }
  84611. if (copy === 0) { break inf_leave; }
  84612. //--- zmemcpy(put, next, copy); ---
  84613. utils.arraySet(output, input, next, copy, put);
  84614. //---//
  84615. have -= copy;
  84616. next += copy;
  84617. left -= copy;
  84618. put += copy;
  84619. state.length -= copy;
  84620. break;
  84621. }
  84622. //Tracev((stderr, "inflate: stored end\n"));
  84623. state.mode = TYPE;
  84624. break;
  84625. case TABLE:
  84626. //=== NEEDBITS(14); */
  84627. while (bits < 14) {
  84628. if (have === 0) { break inf_leave; }
  84629. have--;
  84630. hold += input[next++] << bits;
  84631. bits += 8;
  84632. }
  84633. //===//
  84634. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  84635. //--- DROPBITS(5) ---//
  84636. hold >>>= 5;
  84637. bits -= 5;
  84638. //---//
  84639. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  84640. //--- DROPBITS(5) ---//
  84641. hold >>>= 5;
  84642. bits -= 5;
  84643. //---//
  84644. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  84645. //--- DROPBITS(4) ---//
  84646. hold >>>= 4;
  84647. bits -= 4;
  84648. //---//
  84649. //#ifndef PKZIP_BUG_WORKAROUND
  84650. if (state.nlen > 286 || state.ndist > 30) {
  84651. strm.msg = 'too many length or distance symbols';
  84652. state.mode = BAD;
  84653. break;
  84654. }
  84655. //#endif
  84656. //Tracev((stderr, "inflate: table sizes ok\n"));
  84657. state.have = 0;
  84658. state.mode = LENLENS;
  84659. /* falls through */
  84660. case LENLENS:
  84661. while (state.have < state.ncode) {
  84662. //=== NEEDBITS(3);
  84663. while (bits < 3) {
  84664. if (have === 0) { break inf_leave; }
  84665. have--;
  84666. hold += input[next++] << bits;
  84667. bits += 8;
  84668. }
  84669. //===//
  84670. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  84671. //--- DROPBITS(3) ---//
  84672. hold >>>= 3;
  84673. bits -= 3;
  84674. //---//
  84675. }
  84676. while (state.have < 19) {
  84677. state.lens[order[state.have++]] = 0;
  84678. }
  84679. // We have separate tables & no pointers. 2 commented lines below not needed.
  84680. //state.next = state.codes;
  84681. //state.lencode = state.next;
  84682. // Switch to use dynamic table
  84683. state.lencode = state.lendyn;
  84684. state.lenbits = 7;
  84685. opts = { bits: state.lenbits };
  84686. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  84687. state.lenbits = opts.bits;
  84688. if (ret) {
  84689. strm.msg = 'invalid code lengths set';
  84690. state.mode = BAD;
  84691. break;
  84692. }
  84693. //Tracev((stderr, "inflate: code lengths ok\n"));
  84694. state.have = 0;
  84695. state.mode = CODELENS;
  84696. /* falls through */
  84697. case CODELENS:
  84698. while (state.have < state.nlen + state.ndist) {
  84699. for (;;) {
  84700. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  84701. here_bits = here >>> 24;
  84702. here_op = (here >>> 16) & 0xff;
  84703. here_val = here & 0xffff;
  84704. if ((here_bits) <= bits) { break; }
  84705. //--- PULLBYTE() ---//
  84706. if (have === 0) { break inf_leave; }
  84707. have--;
  84708. hold += input[next++] << bits;
  84709. bits += 8;
  84710. //---//
  84711. }
  84712. if (here_val < 16) {
  84713. //--- DROPBITS(here.bits) ---//
  84714. hold >>>= here_bits;
  84715. bits -= here_bits;
  84716. //---//
  84717. state.lens[state.have++] = here_val;
  84718. }
  84719. else {
  84720. if (here_val === 16) {
  84721. //=== NEEDBITS(here.bits + 2);
  84722. n = here_bits + 2;
  84723. while (bits < n) {
  84724. if (have === 0) { break inf_leave; }
  84725. have--;
  84726. hold += input[next++] << bits;
  84727. bits += 8;
  84728. }
  84729. //===//
  84730. //--- DROPBITS(here.bits) ---//
  84731. hold >>>= here_bits;
  84732. bits -= here_bits;
  84733. //---//
  84734. if (state.have === 0) {
  84735. strm.msg = 'invalid bit length repeat';
  84736. state.mode = BAD;
  84737. break;
  84738. }
  84739. len = state.lens[state.have - 1];
  84740. copy = 3 + (hold & 0x03);//BITS(2);
  84741. //--- DROPBITS(2) ---//
  84742. hold >>>= 2;
  84743. bits -= 2;
  84744. //---//
  84745. }
  84746. else if (here_val === 17) {
  84747. //=== NEEDBITS(here.bits + 3);
  84748. n = here_bits + 3;
  84749. while (bits < n) {
  84750. if (have === 0) { break inf_leave; }
  84751. have--;
  84752. hold += input[next++] << bits;
  84753. bits += 8;
  84754. }
  84755. //===//
  84756. //--- DROPBITS(here.bits) ---//
  84757. hold >>>= here_bits;
  84758. bits -= here_bits;
  84759. //---//
  84760. len = 0;
  84761. copy = 3 + (hold & 0x07);//BITS(3);
  84762. //--- DROPBITS(3) ---//
  84763. hold >>>= 3;
  84764. bits -= 3;
  84765. //---//
  84766. }
  84767. else {
  84768. //=== NEEDBITS(here.bits + 7);
  84769. n = here_bits + 7;
  84770. while (bits < n) {
  84771. if (have === 0) { break inf_leave; }
  84772. have--;
  84773. hold += input[next++] << bits;
  84774. bits += 8;
  84775. }
  84776. //===//
  84777. //--- DROPBITS(here.bits) ---//
  84778. hold >>>= here_bits;
  84779. bits -= here_bits;
  84780. //---//
  84781. len = 0;
  84782. copy = 11 + (hold & 0x7f);//BITS(7);
  84783. //--- DROPBITS(7) ---//
  84784. hold >>>= 7;
  84785. bits -= 7;
  84786. //---//
  84787. }
  84788. if (state.have + copy > state.nlen + state.ndist) {
  84789. strm.msg = 'invalid bit length repeat';
  84790. state.mode = BAD;
  84791. break;
  84792. }
  84793. while (copy--) {
  84794. state.lens[state.have++] = len;
  84795. }
  84796. }
  84797. }
  84798. /* handle error breaks in while */
  84799. if (state.mode === BAD) { break; }
  84800. /* check for end-of-block code (better have one) */
  84801. if (state.lens[256] === 0) {
  84802. strm.msg = 'invalid code -- missing end-of-block';
  84803. state.mode = BAD;
  84804. break;
  84805. }
  84806. /* build code tables -- note: do not change the lenbits or distbits
  84807. values here (9 and 6) without reading the comments in inftrees.h
  84808. concerning the ENOUGH constants, which depend on those values */
  84809. state.lenbits = 9;
  84810. opts = { bits: state.lenbits };
  84811. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  84812. // We have separate tables & no pointers. 2 commented lines below not needed.
  84813. // state.next_index = opts.table_index;
  84814. state.lenbits = opts.bits;
  84815. // state.lencode = state.next;
  84816. if (ret) {
  84817. strm.msg = 'invalid literal/lengths set';
  84818. state.mode = BAD;
  84819. break;
  84820. }
  84821. state.distbits = 6;
  84822. //state.distcode.copy(state.codes);
  84823. // Switch to use dynamic table
  84824. state.distcode = state.distdyn;
  84825. opts = { bits: state.distbits };
  84826. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  84827. // We have separate tables & no pointers. 2 commented lines below not needed.
  84828. // state.next_index = opts.table_index;
  84829. state.distbits = opts.bits;
  84830. // state.distcode = state.next;
  84831. if (ret) {
  84832. strm.msg = 'invalid distances set';
  84833. state.mode = BAD;
  84834. break;
  84835. }
  84836. //Tracev((stderr, 'inflate: codes ok\n'));
  84837. state.mode = LEN_;
  84838. if (flush === Z_TREES) { break inf_leave; }
  84839. /* falls through */
  84840. case LEN_:
  84841. state.mode = LEN;
  84842. /* falls through */
  84843. case LEN:
  84844. if (have >= 6 && left >= 258) {
  84845. //--- RESTORE() ---
  84846. strm.next_out = put;
  84847. strm.avail_out = left;
  84848. strm.next_in = next;
  84849. strm.avail_in = have;
  84850. state.hold = hold;
  84851. state.bits = bits;
  84852. //---
  84853. inflate_fast(strm, _out);
  84854. //--- LOAD() ---
  84855. put = strm.next_out;
  84856. output = strm.output;
  84857. left = strm.avail_out;
  84858. next = strm.next_in;
  84859. input = strm.input;
  84860. have = strm.avail_in;
  84861. hold = state.hold;
  84862. bits = state.bits;
  84863. //---
  84864. if (state.mode === TYPE) {
  84865. state.back = -1;
  84866. }
  84867. break;
  84868. }
  84869. state.back = 0;
  84870. for (;;) {
  84871. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  84872. here_bits = here >>> 24;
  84873. here_op = (here >>> 16) & 0xff;
  84874. here_val = here & 0xffff;
  84875. if (here_bits <= bits) { break; }
  84876. //--- PULLBYTE() ---//
  84877. if (have === 0) { break inf_leave; }
  84878. have--;
  84879. hold += input[next++] << bits;
  84880. bits += 8;
  84881. //---//
  84882. }
  84883. if (here_op && (here_op & 0xf0) === 0) {
  84884. last_bits = here_bits;
  84885. last_op = here_op;
  84886. last_val = here_val;
  84887. for (;;) {
  84888. here = state.lencode[last_val +
  84889. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  84890. here_bits = here >>> 24;
  84891. here_op = (here >>> 16) & 0xff;
  84892. here_val = here & 0xffff;
  84893. if ((last_bits + here_bits) <= bits) { break; }
  84894. //--- PULLBYTE() ---//
  84895. if (have === 0) { break inf_leave; }
  84896. have--;
  84897. hold += input[next++] << bits;
  84898. bits += 8;
  84899. //---//
  84900. }
  84901. //--- DROPBITS(last.bits) ---//
  84902. hold >>>= last_bits;
  84903. bits -= last_bits;
  84904. //---//
  84905. state.back += last_bits;
  84906. }
  84907. //--- DROPBITS(here.bits) ---//
  84908. hold >>>= here_bits;
  84909. bits -= here_bits;
  84910. //---//
  84911. state.back += here_bits;
  84912. state.length = here_val;
  84913. if (here_op === 0) {
  84914. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  84915. // "inflate: literal '%c'\n" :
  84916. // "inflate: literal 0x%02x\n", here.val));
  84917. state.mode = LIT;
  84918. break;
  84919. }
  84920. if (here_op & 32) {
  84921. //Tracevv((stderr, "inflate: end of block\n"));
  84922. state.back = -1;
  84923. state.mode = TYPE;
  84924. break;
  84925. }
  84926. if (here_op & 64) {
  84927. strm.msg = 'invalid literal/length code';
  84928. state.mode = BAD;
  84929. break;
  84930. }
  84931. state.extra = here_op & 15;
  84932. state.mode = LENEXT;
  84933. /* falls through */
  84934. case LENEXT:
  84935. if (state.extra) {
  84936. //=== NEEDBITS(state.extra);
  84937. n = state.extra;
  84938. while (bits < n) {
  84939. if (have === 0) { break inf_leave; }
  84940. have--;
  84941. hold += input[next++] << bits;
  84942. bits += 8;
  84943. }
  84944. //===//
  84945. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  84946. //--- DROPBITS(state.extra) ---//
  84947. hold >>>= state.extra;
  84948. bits -= state.extra;
  84949. //---//
  84950. state.back += state.extra;
  84951. }
  84952. //Tracevv((stderr, "inflate: length %u\n", state.length));
  84953. state.was = state.length;
  84954. state.mode = DIST;
  84955. /* falls through */
  84956. case DIST:
  84957. for (;;) {
  84958. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  84959. here_bits = here >>> 24;
  84960. here_op = (here >>> 16) & 0xff;
  84961. here_val = here & 0xffff;
  84962. if ((here_bits) <= bits) { break; }
  84963. //--- PULLBYTE() ---//
  84964. if (have === 0) { break inf_leave; }
  84965. have--;
  84966. hold += input[next++] << bits;
  84967. bits += 8;
  84968. //---//
  84969. }
  84970. if ((here_op & 0xf0) === 0) {
  84971. last_bits = here_bits;
  84972. last_op = here_op;
  84973. last_val = here_val;
  84974. for (;;) {
  84975. here = state.distcode[last_val +
  84976. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  84977. here_bits = here >>> 24;
  84978. here_op = (here >>> 16) & 0xff;
  84979. here_val = here & 0xffff;
  84980. if ((last_bits + here_bits) <= bits) { break; }
  84981. //--- PULLBYTE() ---//
  84982. if (have === 0) { break inf_leave; }
  84983. have--;
  84984. hold += input[next++] << bits;
  84985. bits += 8;
  84986. //---//
  84987. }
  84988. //--- DROPBITS(last.bits) ---//
  84989. hold >>>= last_bits;
  84990. bits -= last_bits;
  84991. //---//
  84992. state.back += last_bits;
  84993. }
  84994. //--- DROPBITS(here.bits) ---//
  84995. hold >>>= here_bits;
  84996. bits -= here_bits;
  84997. //---//
  84998. state.back += here_bits;
  84999. if (here_op & 64) {
  85000. strm.msg = 'invalid distance code';
  85001. state.mode = BAD;
  85002. break;
  85003. }
  85004. state.offset = here_val;
  85005. state.extra = (here_op) & 15;
  85006. state.mode = DISTEXT;
  85007. /* falls through */
  85008. case DISTEXT:
  85009. if (state.extra) {
  85010. //=== NEEDBITS(state.extra);
  85011. n = state.extra;
  85012. while (bits < n) {
  85013. if (have === 0) { break inf_leave; }
  85014. have--;
  85015. hold += input[next++] << bits;
  85016. bits += 8;
  85017. }
  85018. //===//
  85019. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  85020. //--- DROPBITS(state.extra) ---//
  85021. hold >>>= state.extra;
  85022. bits -= state.extra;
  85023. //---//
  85024. state.back += state.extra;
  85025. }
  85026. //#ifdef INFLATE_STRICT
  85027. if (state.offset > state.dmax) {
  85028. strm.msg = 'invalid distance too far back';
  85029. state.mode = BAD;
  85030. break;
  85031. }
  85032. //#endif
  85033. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  85034. state.mode = MATCH;
  85035. /* falls through */
  85036. case MATCH:
  85037. if (left === 0) { break inf_leave; }
  85038. copy = _out - left;
  85039. if (state.offset > copy) { /* copy from window */
  85040. copy = state.offset - copy;
  85041. if (copy > state.whave) {
  85042. if (state.sane) {
  85043. strm.msg = 'invalid distance too far back';
  85044. state.mode = BAD;
  85045. break;
  85046. }
  85047. // (!) This block is disabled in zlib defaults,
  85048. // don't enable it for binary compatibility
  85049. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  85050. // Trace((stderr, "inflate.c too far\n"));
  85051. // copy -= state.whave;
  85052. // if (copy > state.length) { copy = state.length; }
  85053. // if (copy > left) { copy = left; }
  85054. // left -= copy;
  85055. // state.length -= copy;
  85056. // do {
  85057. // output[put++] = 0;
  85058. // } while (--copy);
  85059. // if (state.length === 0) { state.mode = LEN; }
  85060. // break;
  85061. //#endif
  85062. }
  85063. if (copy > state.wnext) {
  85064. copy -= state.wnext;
  85065. from = state.wsize - copy;
  85066. }
  85067. else {
  85068. from = state.wnext - copy;
  85069. }
  85070. if (copy > state.length) { copy = state.length; }
  85071. from_source = state.window;
  85072. }
  85073. else { /* copy from output */
  85074. from_source = output;
  85075. from = put - state.offset;
  85076. copy = state.length;
  85077. }
  85078. if (copy > left) { copy = left; }
  85079. left -= copy;
  85080. state.length -= copy;
  85081. do {
  85082. output[put++] = from_source[from++];
  85083. } while (--copy);
  85084. if (state.length === 0) { state.mode = LEN; }
  85085. break;
  85086. case LIT:
  85087. if (left === 0) { break inf_leave; }
  85088. output[put++] = state.length;
  85089. left--;
  85090. state.mode = LEN;
  85091. break;
  85092. case CHECK:
  85093. if (state.wrap) {
  85094. //=== NEEDBITS(32);
  85095. while (bits < 32) {
  85096. if (have === 0) { break inf_leave; }
  85097. have--;
  85098. // Use '|' instead of '+' to make sure that result is signed
  85099. hold |= input[next++] << bits;
  85100. bits += 8;
  85101. }
  85102. //===//
  85103. _out -= left;
  85104. strm.total_out += _out;
  85105. state.total += _out;
  85106. if (_out) {
  85107. strm.adler = state.check =
  85108. /*UPDATE(state.check, put - _out, _out);*/
  85109. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  85110. }
  85111. _out = left;
  85112. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  85113. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  85114. strm.msg = 'incorrect data check';
  85115. state.mode = BAD;
  85116. break;
  85117. }
  85118. //=== INITBITS();
  85119. hold = 0;
  85120. bits = 0;
  85121. //===//
  85122. //Tracev((stderr, "inflate: check matches trailer\n"));
  85123. }
  85124. state.mode = LENGTH;
  85125. /* falls through */
  85126. case LENGTH:
  85127. if (state.wrap && state.flags) {
  85128. //=== NEEDBITS(32);
  85129. while (bits < 32) {
  85130. if (have === 0) { break inf_leave; }
  85131. have--;
  85132. hold += input[next++] << bits;
  85133. bits += 8;
  85134. }
  85135. //===//
  85136. if (hold !== (state.total & 0xffffffff)) {
  85137. strm.msg = 'incorrect length check';
  85138. state.mode = BAD;
  85139. break;
  85140. }
  85141. //=== INITBITS();
  85142. hold = 0;
  85143. bits = 0;
  85144. //===//
  85145. //Tracev((stderr, "inflate: length matches trailer\n"));
  85146. }
  85147. state.mode = DONE;
  85148. /* falls through */
  85149. case DONE:
  85150. ret = Z_STREAM_END;
  85151. break inf_leave;
  85152. case BAD:
  85153. ret = Z_DATA_ERROR;
  85154. break inf_leave;
  85155. case MEM:
  85156. return Z_MEM_ERROR;
  85157. case SYNC:
  85158. /* falls through */
  85159. default:
  85160. return Z_STREAM_ERROR;
  85161. }
  85162. }
  85163. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  85164. /*
  85165. Return from inflate(), updating the total counts and the check value.
  85166. If there was no progress during the inflate() call, return a buffer
  85167. error. Call updatewindow() to create and/or update the window state.
  85168. Note: a memory error from inflate() is non-recoverable.
  85169. */
  85170. //--- RESTORE() ---
  85171. strm.next_out = put;
  85172. strm.avail_out = left;
  85173. strm.next_in = next;
  85174. strm.avail_in = have;
  85175. state.hold = hold;
  85176. state.bits = bits;
  85177. //---
  85178. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  85179. (state.mode < CHECK || flush !== Z_FINISH))) {
  85180. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  85181. state.mode = MEM;
  85182. return Z_MEM_ERROR;
  85183. }
  85184. }
  85185. _in -= strm.avail_in;
  85186. _out -= strm.avail_out;
  85187. strm.total_in += _in;
  85188. strm.total_out += _out;
  85189. state.total += _out;
  85190. if (state.wrap && _out) {
  85191. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  85192. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  85193. }
  85194. strm.data_type = state.bits + (state.last ? 64 : 0) +
  85195. (state.mode === TYPE ? 128 : 0) +
  85196. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  85197. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  85198. ret = Z_BUF_ERROR;
  85199. }
  85200. return ret;
  85201. }
  85202. function inflateEnd(strm) {
  85203. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  85204. return Z_STREAM_ERROR;
  85205. }
  85206. var state = strm.state;
  85207. if (state.window) {
  85208. state.window = null;
  85209. }
  85210. strm.state = null;
  85211. return Z_OK;
  85212. }
  85213. function inflateGetHeader(strm, head) {
  85214. var state;
  85215. /* check state */
  85216. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  85217. state = strm.state;
  85218. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  85219. /* save header structure */
  85220. state.head = head;
  85221. head.done = false;
  85222. return Z_OK;
  85223. }
  85224. function inflateSetDictionary(strm, dictionary) {
  85225. var dictLength = dictionary.length;
  85226. var state;
  85227. var dictid;
  85228. var ret;
  85229. /* check state */
  85230. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  85231. state = strm.state;
  85232. if (state.wrap !== 0 && state.mode !== DICT) {
  85233. return Z_STREAM_ERROR;
  85234. }
  85235. /* check for correct dictionary identifier */
  85236. if (state.mode === DICT) {
  85237. dictid = 1; /* adler32(0, null, 0)*/
  85238. /* dictid = adler32(dictid, dictionary, dictLength); */
  85239. dictid = adler32(dictid, dictionary, dictLength, 0);
  85240. if (dictid !== state.check) {
  85241. return Z_DATA_ERROR;
  85242. }
  85243. }
  85244. /* copy dictionary to window using updatewindow(), which will amend the
  85245. existing dictionary if appropriate */
  85246. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  85247. if (ret) {
  85248. state.mode = MEM;
  85249. return Z_MEM_ERROR;
  85250. }
  85251. state.havedict = 1;
  85252. // Tracev((stderr, "inflate: dictionary set\n"));
  85253. return Z_OK;
  85254. }
  85255. exports.inflateReset = inflateReset;
  85256. exports.inflateReset2 = inflateReset2;
  85257. exports.inflateResetKeep = inflateResetKeep;
  85258. exports.inflateInit = inflateInit;
  85259. exports.inflateInit2 = inflateInit2;
  85260. exports.inflate = inflate;
  85261. exports.inflateEnd = inflateEnd;
  85262. exports.inflateGetHeader = inflateGetHeader;
  85263. exports.inflateSetDictionary = inflateSetDictionary;
  85264. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  85265. /* Not implemented
  85266. exports.inflateCopy = inflateCopy;
  85267. exports.inflateGetDictionary = inflateGetDictionary;
  85268. exports.inflateMark = inflateMark;
  85269. exports.inflatePrime = inflatePrime;
  85270. exports.inflateSync = inflateSync;
  85271. exports.inflateSyncPoint = inflateSyncPoint;
  85272. exports.inflateUndermine = inflateUndermine;
  85273. */
  85274. },{"../utils/common":501,"./adler32":502,"./crc32":504,"./inffast":506,"./inftrees":508}],508:[function(require,module,exports){
  85275. 'use strict';
  85276. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  85277. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  85278. //
  85279. // This software is provided 'as-is', without any express or implied
  85280. // warranty. In no event will the authors be held liable for any damages
  85281. // arising from the use of this software.
  85282. //
  85283. // Permission is granted to anyone to use this software for any purpose,
  85284. // including commercial applications, and to alter it and redistribute it
  85285. // freely, subject to the following restrictions:
  85286. //
  85287. // 1. The origin of this software must not be misrepresented; you must not
  85288. // claim that you wrote the original software. If you use this software
  85289. // in a product, an acknowledgment in the product documentation would be
  85290. // appreciated but is not required.
  85291. // 2. Altered source versions must be plainly marked as such, and must not be
  85292. // misrepresented as being the original software.
  85293. // 3. This notice may not be removed or altered from any source distribution.
  85294. var utils = require('../utils/common');
  85295. var MAXBITS = 15;
  85296. var ENOUGH_LENS = 852;
  85297. var ENOUGH_DISTS = 592;
  85298. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  85299. var CODES = 0;
  85300. var LENS = 1;
  85301. var DISTS = 2;
  85302. var lbase = [ /* Length codes 257..285 base */
  85303. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  85304. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  85305. ];
  85306. var lext = [ /* Length codes 257..285 extra */
  85307. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  85308. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  85309. ];
  85310. var dbase = [ /* Distance codes 0..29 base */
  85311. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  85312. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  85313. 8193, 12289, 16385, 24577, 0, 0
  85314. ];
  85315. var dext = [ /* Distance codes 0..29 extra */
  85316. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  85317. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  85318. 28, 28, 29, 29, 64, 64
  85319. ];
  85320. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  85321. {
  85322. var bits = opts.bits;
  85323. //here = opts.here; /* table entry for duplication */
  85324. var len = 0; /* a code's length in bits */
  85325. var sym = 0; /* index of code symbols */
  85326. var min = 0, max = 0; /* minimum and maximum code lengths */
  85327. var root = 0; /* number of index bits for root table */
  85328. var curr = 0; /* number of index bits for current table */
  85329. var drop = 0; /* code bits to drop for sub-table */
  85330. var left = 0; /* number of prefix codes available */
  85331. var used = 0; /* code entries in table used */
  85332. var huff = 0; /* Huffman code */
  85333. var incr; /* for incrementing code, index */
  85334. var fill; /* index for replicating entries */
  85335. var low; /* low bits for current root entry */
  85336. var mask; /* mask for low root bits */
  85337. var next; /* next available space in table */
  85338. var base = null; /* base value table to use */
  85339. var base_index = 0;
  85340. // var shoextra; /* extra bits table to use */
  85341. var end; /* use base and extra for symbol > end */
  85342. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  85343. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  85344. var extra = null;
  85345. var extra_index = 0;
  85346. var here_bits, here_op, here_val;
  85347. /*
  85348. Process a set of code lengths to create a canonical Huffman code. The
  85349. code lengths are lens[0..codes-1]. Each length corresponds to the
  85350. symbols 0..codes-1. The Huffman code is generated by first sorting the
  85351. symbols by length from short to long, and retaining the symbol order
  85352. for codes with equal lengths. Then the code starts with all zero bits
  85353. for the first code of the shortest length, and the codes are integer
  85354. increments for the same length, and zeros are appended as the length
  85355. increases. For the deflate format, these bits are stored backwards
  85356. from their more natural integer increment ordering, and so when the
  85357. decoding tables are built in the large loop below, the integer codes
  85358. are incremented backwards.
  85359. This routine assumes, but does not check, that all of the entries in
  85360. lens[] are in the range 0..MAXBITS. The caller must assure this.
  85361. 1..MAXBITS is interpreted as that code length. zero means that that
  85362. symbol does not occur in this code.
  85363. The codes are sorted by computing a count of codes for each length,
  85364. creating from that a table of starting indices for each length in the
  85365. sorted table, and then entering the symbols in order in the sorted
  85366. table. The sorted table is work[], with that space being provided by
  85367. the caller.
  85368. The length counts are used for other purposes as well, i.e. finding
  85369. the minimum and maximum length codes, determining if there are any
  85370. codes at all, checking for a valid set of lengths, and looking ahead
  85371. at length counts to determine sub-table sizes when building the
  85372. decoding tables.
  85373. */
  85374. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  85375. for (len = 0; len <= MAXBITS; len++) {
  85376. count[len] = 0;
  85377. }
  85378. for (sym = 0; sym < codes; sym++) {
  85379. count[lens[lens_index + sym]]++;
  85380. }
  85381. /* bound code lengths, force root to be within code lengths */
  85382. root = bits;
  85383. for (max = MAXBITS; max >= 1; max--) {
  85384. if (count[max] !== 0) { break; }
  85385. }
  85386. if (root > max) {
  85387. root = max;
  85388. }
  85389. if (max === 0) { /* no symbols to code at all */
  85390. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  85391. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  85392. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  85393. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  85394. //table.op[opts.table_index] = 64;
  85395. //table.bits[opts.table_index] = 1;
  85396. //table.val[opts.table_index++] = 0;
  85397. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  85398. opts.bits = 1;
  85399. return 0; /* no symbols, but wait for decoding to report error */
  85400. }
  85401. for (min = 1; min < max; min++) {
  85402. if (count[min] !== 0) { break; }
  85403. }
  85404. if (root < min) {
  85405. root = min;
  85406. }
  85407. /* check for an over-subscribed or incomplete set of lengths */
  85408. left = 1;
  85409. for (len = 1; len <= MAXBITS; len++) {
  85410. left <<= 1;
  85411. left -= count[len];
  85412. if (left < 0) {
  85413. return -1;
  85414. } /* over-subscribed */
  85415. }
  85416. if (left > 0 && (type === CODES || max !== 1)) {
  85417. return -1; /* incomplete set */
  85418. }
  85419. /* generate offsets into symbol table for each length for sorting */
  85420. offs[1] = 0;
  85421. for (len = 1; len < MAXBITS; len++) {
  85422. offs[len + 1] = offs[len] + count[len];
  85423. }
  85424. /* sort symbols by length, by symbol order within each length */
  85425. for (sym = 0; sym < codes; sym++) {
  85426. if (lens[lens_index + sym] !== 0) {
  85427. work[offs[lens[lens_index + sym]]++] = sym;
  85428. }
  85429. }
  85430. /*
  85431. Create and fill in decoding tables. In this loop, the table being
  85432. filled is at next and has curr index bits. The code being used is huff
  85433. with length len. That code is converted to an index by dropping drop
  85434. bits off of the bottom. For codes where len is less than drop + curr,
  85435. those top drop + curr - len bits are incremented through all values to
  85436. fill the table with replicated entries.
  85437. root is the number of index bits for the root table. When len exceeds
  85438. root, sub-tables are created pointed to by the root entry with an index
  85439. of the low root bits of huff. This is saved in low to check for when a
  85440. new sub-table should be started. drop is zero when the root table is
  85441. being filled, and drop is root when sub-tables are being filled.
  85442. When a new sub-table is needed, it is necessary to look ahead in the
  85443. code lengths to determine what size sub-table is needed. The length
  85444. counts are used for this, and so count[] is decremented as codes are
  85445. entered in the tables.
  85446. used keeps track of how many table entries have been allocated from the
  85447. provided *table space. It is checked for LENS and DIST tables against
  85448. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  85449. the initial root table size constants. See the comments in inftrees.h
  85450. for more information.
  85451. sym increments through all symbols, and the loop terminates when
  85452. all codes of length max, i.e. all codes, have been processed. This
  85453. routine permits incomplete codes, so another loop after this one fills
  85454. in the rest of the decoding tables with invalid code markers.
  85455. */
  85456. /* set up for code type */
  85457. // poor man optimization - use if-else instead of switch,
  85458. // to avoid deopts in old v8
  85459. if (type === CODES) {
  85460. base = extra = work; /* dummy value--not used */
  85461. end = 19;
  85462. } else if (type === LENS) {
  85463. base = lbase;
  85464. base_index -= 257;
  85465. extra = lext;
  85466. extra_index -= 257;
  85467. end = 256;
  85468. } else { /* DISTS */
  85469. base = dbase;
  85470. extra = dext;
  85471. end = -1;
  85472. }
  85473. /* initialize opts for loop */
  85474. huff = 0; /* starting code */
  85475. sym = 0; /* starting code symbol */
  85476. len = min; /* starting code length */
  85477. next = table_index; /* current table to fill in */
  85478. curr = root; /* current table index bits */
  85479. drop = 0; /* current bits to drop from code for index */
  85480. low = -1; /* trigger new sub-table when len > root */
  85481. used = 1 << root; /* use root table entries */
  85482. mask = used - 1; /* mask for comparing low */
  85483. /* check available table space */
  85484. if ((type === LENS && used > ENOUGH_LENS) ||
  85485. (type === DISTS && used > ENOUGH_DISTS)) {
  85486. return 1;
  85487. }
  85488. /* process all codes and make table entries */
  85489. for (;;) {
  85490. /* create table entry */
  85491. here_bits = len - drop;
  85492. if (work[sym] < end) {
  85493. here_op = 0;
  85494. here_val = work[sym];
  85495. }
  85496. else if (work[sym] > end) {
  85497. here_op = extra[extra_index + work[sym]];
  85498. here_val = base[base_index + work[sym]];
  85499. }
  85500. else {
  85501. here_op = 32 + 64; /* end of block */
  85502. here_val = 0;
  85503. }
  85504. /* replicate for those indices with low len bits equal to huff */
  85505. incr = 1 << (len - drop);
  85506. fill = 1 << curr;
  85507. min = fill; /* save offset to next table */
  85508. do {
  85509. fill -= incr;
  85510. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  85511. } while (fill !== 0);
  85512. /* backwards increment the len-bit code huff */
  85513. incr = 1 << (len - 1);
  85514. while (huff & incr) {
  85515. incr >>= 1;
  85516. }
  85517. if (incr !== 0) {
  85518. huff &= incr - 1;
  85519. huff += incr;
  85520. } else {
  85521. huff = 0;
  85522. }
  85523. /* go to next symbol, update count, len */
  85524. sym++;
  85525. if (--count[len] === 0) {
  85526. if (len === max) { break; }
  85527. len = lens[lens_index + work[sym]];
  85528. }
  85529. /* create new sub-table if needed */
  85530. if (len > root && (huff & mask) !== low) {
  85531. /* if first time, transition to sub-tables */
  85532. if (drop === 0) {
  85533. drop = root;
  85534. }
  85535. /* increment past last table */
  85536. next += min; /* here min is 1 << curr */
  85537. /* determine length of next table */
  85538. curr = len - drop;
  85539. left = 1 << curr;
  85540. while (curr + drop < max) {
  85541. left -= count[curr + drop];
  85542. if (left <= 0) { break; }
  85543. curr++;
  85544. left <<= 1;
  85545. }
  85546. /* check for enough space */
  85547. used += 1 << curr;
  85548. if ((type === LENS && used > ENOUGH_LENS) ||
  85549. (type === DISTS && used > ENOUGH_DISTS)) {
  85550. return 1;
  85551. }
  85552. /* point entry in root table to sub-table */
  85553. low = huff & mask;
  85554. /*table.op[low] = curr;
  85555. table.bits[low] = root;
  85556. table.val[low] = next - opts.table_index;*/
  85557. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  85558. }
  85559. }
  85560. /* fill in remaining table entry if code is incomplete (guaranteed to have
  85561. at most one remaining entry, since if the code is incomplete, the
  85562. maximum code length that was allowed to get this far is one bit) */
  85563. if (huff !== 0) {
  85564. //table.op[next + huff] = 64; /* invalid code marker */
  85565. //table.bits[next + huff] = len - drop;
  85566. //table.val[next + huff] = 0;
  85567. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  85568. }
  85569. /* set return parameters */
  85570. //opts.table_index += used;
  85571. opts.bits = root;
  85572. return 0;
  85573. };
  85574. },{"../utils/common":501}],509:[function(require,module,exports){
  85575. 'use strict';
  85576. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  85577. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  85578. //
  85579. // This software is provided 'as-is', without any express or implied
  85580. // warranty. In no event will the authors be held liable for any damages
  85581. // arising from the use of this software.
  85582. //
  85583. // Permission is granted to anyone to use this software for any purpose,
  85584. // including commercial applications, and to alter it and redistribute it
  85585. // freely, subject to the following restrictions:
  85586. //
  85587. // 1. The origin of this software must not be misrepresented; you must not
  85588. // claim that you wrote the original software. If you use this software
  85589. // in a product, an acknowledgment in the product documentation would be
  85590. // appreciated but is not required.
  85591. // 2. Altered source versions must be plainly marked as such, and must not be
  85592. // misrepresented as being the original software.
  85593. // 3. This notice may not be removed or altered from any source distribution.
  85594. module.exports = {
  85595. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  85596. 1: 'stream end', /* Z_STREAM_END 1 */
  85597. 0: '', /* Z_OK 0 */
  85598. '-1': 'file error', /* Z_ERRNO (-1) */
  85599. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  85600. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  85601. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  85602. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  85603. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  85604. };
  85605. },{}],510:[function(require,module,exports){
  85606. 'use strict';
  85607. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  85608. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  85609. //
  85610. // This software is provided 'as-is', without any express or implied
  85611. // warranty. In no event will the authors be held liable for any damages
  85612. // arising from the use of this software.
  85613. //
  85614. // Permission is granted to anyone to use this software for any purpose,
  85615. // including commercial applications, and to alter it and redistribute it
  85616. // freely, subject to the following restrictions:
  85617. //
  85618. // 1. The origin of this software must not be misrepresented; you must not
  85619. // claim that you wrote the original software. If you use this software
  85620. // in a product, an acknowledgment in the product documentation would be
  85621. // appreciated but is not required.
  85622. // 2. Altered source versions must be plainly marked as such, and must not be
  85623. // misrepresented as being the original software.
  85624. // 3. This notice may not be removed or altered from any source distribution.
  85625. /* eslint-disable space-unary-ops */
  85626. var utils = require('../utils/common');
  85627. /* Public constants ==========================================================*/
  85628. /* ===========================================================================*/
  85629. //var Z_FILTERED = 1;
  85630. //var Z_HUFFMAN_ONLY = 2;
  85631. //var Z_RLE = 3;
  85632. var Z_FIXED = 4;
  85633. //var Z_DEFAULT_STRATEGY = 0;
  85634. /* Possible values of the data_type field (though see inflate()) */
  85635. var Z_BINARY = 0;
  85636. var Z_TEXT = 1;
  85637. //var Z_ASCII = 1; // = Z_TEXT
  85638. var Z_UNKNOWN = 2;
  85639. /*============================================================================*/
  85640. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  85641. // From zutil.h
  85642. var STORED_BLOCK = 0;
  85643. var STATIC_TREES = 1;
  85644. var DYN_TREES = 2;
  85645. /* The three kinds of block type */
  85646. var MIN_MATCH = 3;
  85647. var MAX_MATCH = 258;
  85648. /* The minimum and maximum match lengths */
  85649. // From deflate.h
  85650. /* ===========================================================================
  85651. * Internal compression state.
  85652. */
  85653. var LENGTH_CODES = 29;
  85654. /* number of length codes, not counting the special END_BLOCK code */
  85655. var LITERALS = 256;
  85656. /* number of literal bytes 0..255 */
  85657. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  85658. /* number of Literal or Length codes, including the END_BLOCK code */
  85659. var D_CODES = 30;
  85660. /* number of distance codes */
  85661. var BL_CODES = 19;
  85662. /* number of codes used to transfer the bit lengths */
  85663. var HEAP_SIZE = 2 * L_CODES + 1;
  85664. /* maximum heap size */
  85665. var MAX_BITS = 15;
  85666. /* All codes must not exceed MAX_BITS bits */
  85667. var Buf_size = 16;
  85668. /* size of bit buffer in bi_buf */
  85669. /* ===========================================================================
  85670. * Constants
  85671. */
  85672. var MAX_BL_BITS = 7;
  85673. /* Bit length codes must not exceed MAX_BL_BITS bits */
  85674. var END_BLOCK = 256;
  85675. /* end of block literal code */
  85676. var REP_3_6 = 16;
  85677. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  85678. var REPZ_3_10 = 17;
  85679. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  85680. var REPZ_11_138 = 18;
  85681. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  85682. /* eslint-disable comma-spacing,array-bracket-spacing */
  85683. var extra_lbits = /* extra bits for each length code */
  85684. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  85685. var extra_dbits = /* extra bits for each distance code */
  85686. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  85687. var extra_blbits = /* extra bits for each bit length code */
  85688. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  85689. var bl_order =
  85690. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  85691. /* eslint-enable comma-spacing,array-bracket-spacing */
  85692. /* The lengths of the bit length codes are sent in order of decreasing
  85693. * probability, to avoid transmitting the lengths for unused bit length codes.
  85694. */
  85695. /* ===========================================================================
  85696. * Local data. These are initialized only once.
  85697. */
  85698. // We pre-fill arrays with 0 to avoid uninitialized gaps
  85699. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  85700. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  85701. var static_ltree = new Array((L_CODES + 2) * 2);
  85702. zero(static_ltree);
  85703. /* The static literal tree. Since the bit lengths are imposed, there is no
  85704. * need for the L_CODES extra codes used during heap construction. However
  85705. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  85706. * below).
  85707. */
  85708. var static_dtree = new Array(D_CODES * 2);
  85709. zero(static_dtree);
  85710. /* The static distance tree. (Actually a trivial tree since all codes use
  85711. * 5 bits.)
  85712. */
  85713. var _dist_code = new Array(DIST_CODE_LEN);
  85714. zero(_dist_code);
  85715. /* Distance codes. The first 256 values correspond to the distances
  85716. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85717. * the 15 bit distances.
  85718. */
  85719. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  85720. zero(_length_code);
  85721. /* length code for each normalized match length (0 == MIN_MATCH) */
  85722. var base_length = new Array(LENGTH_CODES);
  85723. zero(base_length);
  85724. /* First normalized length for each code (0 = MIN_MATCH) */
  85725. var base_dist = new Array(D_CODES);
  85726. zero(base_dist);
  85727. /* First normalized distance for each code (0 = distance of 1) */
  85728. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  85729. this.static_tree = static_tree; /* static tree or NULL */
  85730. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  85731. this.extra_base = extra_base; /* base index for extra_bits */
  85732. this.elems = elems; /* max number of elements in the tree */
  85733. this.max_length = max_length; /* max bit length for the codes */
  85734. // show if `static_tree` has data or dummy - needed for monomorphic objects
  85735. this.has_stree = static_tree && static_tree.length;
  85736. }
  85737. var static_l_desc;
  85738. var static_d_desc;
  85739. var static_bl_desc;
  85740. function TreeDesc(dyn_tree, stat_desc) {
  85741. this.dyn_tree = dyn_tree; /* the dynamic tree */
  85742. this.max_code = 0; /* largest code with non zero frequency */
  85743. this.stat_desc = stat_desc; /* the corresponding static tree */
  85744. }
  85745. function d_code(dist) {
  85746. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  85747. }
  85748. /* ===========================================================================
  85749. * Output a short LSB first on the stream.
  85750. * IN assertion: there is enough room in pendingBuf.
  85751. */
  85752. function put_short(s, w) {
  85753. // put_byte(s, (uch)((w) & 0xff));
  85754. // put_byte(s, (uch)((ush)(w) >> 8));
  85755. s.pending_buf[s.pending++] = (w) & 0xff;
  85756. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  85757. }
  85758. /* ===========================================================================
  85759. * Send a value on a given number of bits.
  85760. * IN assertion: length <= 16 and value fits in length bits.
  85761. */
  85762. function send_bits(s, value, length) {
  85763. if (s.bi_valid > (Buf_size - length)) {
  85764. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  85765. put_short(s, s.bi_buf);
  85766. s.bi_buf = value >> (Buf_size - s.bi_valid);
  85767. s.bi_valid += length - Buf_size;
  85768. } else {
  85769. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  85770. s.bi_valid += length;
  85771. }
  85772. }
  85773. function send_code(s, c, tree) {
  85774. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  85775. }
  85776. /* ===========================================================================
  85777. * Reverse the first len bits of a code, using straightforward code (a faster
  85778. * method would use a table)
  85779. * IN assertion: 1 <= len <= 15
  85780. */
  85781. function bi_reverse(code, len) {
  85782. var res = 0;
  85783. do {
  85784. res |= code & 1;
  85785. code >>>= 1;
  85786. res <<= 1;
  85787. } while (--len > 0);
  85788. return res >>> 1;
  85789. }
  85790. /* ===========================================================================
  85791. * Flush the bit buffer, keeping at most 7 bits in it.
  85792. */
  85793. function bi_flush(s) {
  85794. if (s.bi_valid === 16) {
  85795. put_short(s, s.bi_buf);
  85796. s.bi_buf = 0;
  85797. s.bi_valid = 0;
  85798. } else if (s.bi_valid >= 8) {
  85799. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  85800. s.bi_buf >>= 8;
  85801. s.bi_valid -= 8;
  85802. }
  85803. }
  85804. /* ===========================================================================
  85805. * Compute the optimal bit lengths for a tree and update the total bit length
  85806. * for the current block.
  85807. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85808. * above are the tree nodes sorted by increasing frequency.
  85809. * OUT assertions: the field len is set to the optimal bit length, the
  85810. * array bl_count contains the frequencies for each bit length.
  85811. * The length opt_len is updated; static_len is also updated if stree is
  85812. * not null.
  85813. */
  85814. function gen_bitlen(s, desc)
  85815. // deflate_state *s;
  85816. // tree_desc *desc; /* the tree descriptor */
  85817. {
  85818. var tree = desc.dyn_tree;
  85819. var max_code = desc.max_code;
  85820. var stree = desc.stat_desc.static_tree;
  85821. var has_stree = desc.stat_desc.has_stree;
  85822. var extra = desc.stat_desc.extra_bits;
  85823. var base = desc.stat_desc.extra_base;
  85824. var max_length = desc.stat_desc.max_length;
  85825. var h; /* heap index */
  85826. var n, m; /* iterate over the tree elements */
  85827. var bits; /* bit length */
  85828. var xbits; /* extra bits */
  85829. var f; /* frequency */
  85830. var overflow = 0; /* number of elements with bit length too large */
  85831. for (bits = 0; bits <= MAX_BITS; bits++) {
  85832. s.bl_count[bits] = 0;
  85833. }
  85834. /* In a first pass, compute the optimal bit lengths (which may
  85835. * overflow in the case of the bit length tree).
  85836. */
  85837. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  85838. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  85839. n = s.heap[h];
  85840. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  85841. if (bits > max_length) {
  85842. bits = max_length;
  85843. overflow++;
  85844. }
  85845. tree[n * 2 + 1]/*.Len*/ = bits;
  85846. /* We overwrite tree[n].Dad which is no longer needed */
  85847. if (n > max_code) { continue; } /* not a leaf node */
  85848. s.bl_count[bits]++;
  85849. xbits = 0;
  85850. if (n >= base) {
  85851. xbits = extra[n - base];
  85852. }
  85853. f = tree[n * 2]/*.Freq*/;
  85854. s.opt_len += f * (bits + xbits);
  85855. if (has_stree) {
  85856. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  85857. }
  85858. }
  85859. if (overflow === 0) { return; }
  85860. // Trace((stderr,"\nbit length overflow\n"));
  85861. /* This happens for example on obj2 and pic of the Calgary corpus */
  85862. /* Find the first bit length which could increase: */
  85863. do {
  85864. bits = max_length - 1;
  85865. while (s.bl_count[bits] === 0) { bits--; }
  85866. s.bl_count[bits]--; /* move one leaf down the tree */
  85867. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  85868. s.bl_count[max_length]--;
  85869. /* The brother of the overflow item also moves one step up,
  85870. * but this does not affect bl_count[max_length]
  85871. */
  85872. overflow -= 2;
  85873. } while (overflow > 0);
  85874. /* Now recompute all bit lengths, scanning in increasing frequency.
  85875. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85876. * lengths instead of fixing only the wrong ones. This idea is taken
  85877. * from 'ar' written by Haruhiko Okumura.)
  85878. */
  85879. for (bits = max_length; bits !== 0; bits--) {
  85880. n = s.bl_count[bits];
  85881. while (n !== 0) {
  85882. m = s.heap[--h];
  85883. if (m > max_code) { continue; }
  85884. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  85885. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85886. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  85887. tree[m * 2 + 1]/*.Len*/ = bits;
  85888. }
  85889. n--;
  85890. }
  85891. }
  85892. }
  85893. /* ===========================================================================
  85894. * Generate the codes for a given tree and bit counts (which need not be
  85895. * optimal).
  85896. * IN assertion: the array bl_count contains the bit length statistics for
  85897. * the given tree and the field len is set for all tree elements.
  85898. * OUT assertion: the field code is set for all tree elements of non
  85899. * zero code length.
  85900. */
  85901. function gen_codes(tree, max_code, bl_count)
  85902. // ct_data *tree; /* the tree to decorate */
  85903. // int max_code; /* largest code with non zero frequency */
  85904. // ushf *bl_count; /* number of codes at each bit length */
  85905. {
  85906. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  85907. var code = 0; /* running code value */
  85908. var bits; /* bit index */
  85909. var n; /* code index */
  85910. /* The distribution counts are first used to generate the code values
  85911. * without bit reversal.
  85912. */
  85913. for (bits = 1; bits <= MAX_BITS; bits++) {
  85914. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  85915. }
  85916. /* Check that the bit counts in bl_count are consistent. The last code
  85917. * must be all ones.
  85918. */
  85919. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85920. // "inconsistent bit counts");
  85921. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85922. for (n = 0; n <= max_code; n++) {
  85923. var len = tree[n * 2 + 1]/*.Len*/;
  85924. if (len === 0) { continue; }
  85925. /* Now reverse the bits */
  85926. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  85927. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85928. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85929. }
  85930. }
  85931. /* ===========================================================================
  85932. * Initialize the various 'constant' tables.
  85933. */
  85934. function tr_static_init() {
  85935. var n; /* iterates over tree elements */
  85936. var bits; /* bit counter */
  85937. var length; /* length value */
  85938. var code; /* code value */
  85939. var dist; /* distance index */
  85940. var bl_count = new Array(MAX_BITS + 1);
  85941. /* number of codes at each bit length for an optimal tree */
  85942. // do check in _tr_init()
  85943. //if (static_init_done) return;
  85944. /* For some embedded targets, global variables are not initialized: */
  85945. /*#ifdef NO_INIT_GLOBAL_POINTERS
  85946. static_l_desc.static_tree = static_ltree;
  85947. static_l_desc.extra_bits = extra_lbits;
  85948. static_d_desc.static_tree = static_dtree;
  85949. static_d_desc.extra_bits = extra_dbits;
  85950. static_bl_desc.extra_bits = extra_blbits;
  85951. #endif*/
  85952. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85953. length = 0;
  85954. for (code = 0; code < LENGTH_CODES - 1; code++) {
  85955. base_length[code] = length;
  85956. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  85957. _length_code[length++] = code;
  85958. }
  85959. }
  85960. //Assert (length == 256, "tr_static_init: length != 256");
  85961. /* Note that the length 255 (match length 258) can be represented
  85962. * in two different ways: code 284 + 5 bits or code 285, so we
  85963. * overwrite length_code[255] to use the best encoding:
  85964. */
  85965. _length_code[length - 1] = code;
  85966. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85967. dist = 0;
  85968. for (code = 0; code < 16; code++) {
  85969. base_dist[code] = dist;
  85970. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  85971. _dist_code[dist++] = code;
  85972. }
  85973. }
  85974. //Assert (dist == 256, "tr_static_init: dist != 256");
  85975. dist >>= 7; /* from now on, all distances are divided by 128 */
  85976. for (; code < D_CODES; code++) {
  85977. base_dist[code] = dist << 7;
  85978. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  85979. _dist_code[256 + dist++] = code;
  85980. }
  85981. }
  85982. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85983. /* Construct the codes of the static literal tree */
  85984. for (bits = 0; bits <= MAX_BITS; bits++) {
  85985. bl_count[bits] = 0;
  85986. }
  85987. n = 0;
  85988. while (n <= 143) {
  85989. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  85990. n++;
  85991. bl_count[8]++;
  85992. }
  85993. while (n <= 255) {
  85994. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  85995. n++;
  85996. bl_count[9]++;
  85997. }
  85998. while (n <= 279) {
  85999. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  86000. n++;
  86001. bl_count[7]++;
  86002. }
  86003. while (n <= 287) {
  86004. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  86005. n++;
  86006. bl_count[8]++;
  86007. }
  86008. /* Codes 286 and 287 do not exist, but we must include them in the
  86009. * tree construction to get a canonical Huffman tree (longest code
  86010. * all ones)
  86011. */
  86012. gen_codes(static_ltree, L_CODES + 1, bl_count);
  86013. /* The static distance tree is trivial: */
  86014. for (n = 0; n < D_CODES; n++) {
  86015. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  86016. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  86017. }
  86018. // Now data ready and we can init static trees
  86019. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  86020. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  86021. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  86022. //static_init_done = true;
  86023. }
  86024. /* ===========================================================================
  86025. * Initialize a new block.
  86026. */
  86027. function init_block(s) {
  86028. var n; /* iterates over tree elements */
  86029. /* Initialize the trees. */
  86030. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  86031. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  86032. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  86033. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  86034. s.opt_len = s.static_len = 0;
  86035. s.last_lit = s.matches = 0;
  86036. }
  86037. /* ===========================================================================
  86038. * Flush the bit buffer and align the output on a byte boundary
  86039. */
  86040. function bi_windup(s)
  86041. {
  86042. if (s.bi_valid > 8) {
  86043. put_short(s, s.bi_buf);
  86044. } else if (s.bi_valid > 0) {
  86045. //put_byte(s, (Byte)s->bi_buf);
  86046. s.pending_buf[s.pending++] = s.bi_buf;
  86047. }
  86048. s.bi_buf = 0;
  86049. s.bi_valid = 0;
  86050. }
  86051. /* ===========================================================================
  86052. * Copy a stored block, storing first the length and its
  86053. * one's complement if requested.
  86054. */
  86055. function copy_block(s, buf, len, header)
  86056. //DeflateState *s;
  86057. //charf *buf; /* the input data */
  86058. //unsigned len; /* its length */
  86059. //int header; /* true if block header must be written */
  86060. {
  86061. bi_windup(s); /* align on byte boundary */
  86062. if (header) {
  86063. put_short(s, len);
  86064. put_short(s, ~len);
  86065. }
  86066. // while (len--) {
  86067. // put_byte(s, *buf++);
  86068. // }
  86069. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  86070. s.pending += len;
  86071. }
  86072. /* ===========================================================================
  86073. * Compares to subtrees, using the tree depth as tie breaker when
  86074. * the subtrees have equal frequency. This minimizes the worst case length.
  86075. */
  86076. function smaller(tree, n, m, depth) {
  86077. var _n2 = n * 2;
  86078. var _m2 = m * 2;
  86079. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  86080. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  86081. }
  86082. /* ===========================================================================
  86083. * Restore the heap property by moving down the tree starting at node k,
  86084. * exchanging a node with the smallest of its two sons if necessary, stopping
  86085. * when the heap property is re-established (each father smaller than its
  86086. * two sons).
  86087. */
  86088. function pqdownheap(s, tree, k)
  86089. // deflate_state *s;
  86090. // ct_data *tree; /* the tree to restore */
  86091. // int k; /* node to move down */
  86092. {
  86093. var v = s.heap[k];
  86094. var j = k << 1; /* left son of k */
  86095. while (j <= s.heap_len) {
  86096. /* Set j to the smallest of the two sons: */
  86097. if (j < s.heap_len &&
  86098. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  86099. j++;
  86100. }
  86101. /* Exit if v is smaller than both sons */
  86102. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  86103. /* Exchange v with the smallest son */
  86104. s.heap[k] = s.heap[j];
  86105. k = j;
  86106. /* And continue down the tree, setting j to the left son of k */
  86107. j <<= 1;
  86108. }
  86109. s.heap[k] = v;
  86110. }
  86111. // inlined manually
  86112. // var SMALLEST = 1;
  86113. /* ===========================================================================
  86114. * Send the block data compressed using the given Huffman trees
  86115. */
  86116. function compress_block(s, ltree, dtree)
  86117. // deflate_state *s;
  86118. // const ct_data *ltree; /* literal tree */
  86119. // const ct_data *dtree; /* distance tree */
  86120. {
  86121. var dist; /* distance of matched string */
  86122. var lc; /* match length or unmatched char (if dist == 0) */
  86123. var lx = 0; /* running index in l_buf */
  86124. var code; /* the code to send */
  86125. var extra; /* number of extra bits to send */
  86126. if (s.last_lit !== 0) {
  86127. do {
  86128. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  86129. lc = s.pending_buf[s.l_buf + lx];
  86130. lx++;
  86131. if (dist === 0) {
  86132. send_code(s, lc, ltree); /* send a literal byte */
  86133. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  86134. } else {
  86135. /* Here, lc is the match length - MIN_MATCH */
  86136. code = _length_code[lc];
  86137. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  86138. extra = extra_lbits[code];
  86139. if (extra !== 0) {
  86140. lc -= base_length[code];
  86141. send_bits(s, lc, extra); /* send the extra length bits */
  86142. }
  86143. dist--; /* dist is now the match distance - 1 */
  86144. code = d_code(dist);
  86145. //Assert (code < D_CODES, "bad d_code");
  86146. send_code(s, code, dtree); /* send the distance code */
  86147. extra = extra_dbits[code];
  86148. if (extra !== 0) {
  86149. dist -= base_dist[code];
  86150. send_bits(s, dist, extra); /* send the extra distance bits */
  86151. }
  86152. } /* literal or match pair ? */
  86153. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  86154. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  86155. // "pendingBuf overflow");
  86156. } while (lx < s.last_lit);
  86157. }
  86158. send_code(s, END_BLOCK, ltree);
  86159. }
  86160. /* ===========================================================================
  86161. * Construct one Huffman tree and assigns the code bit strings and lengths.
  86162. * Update the total bit length for the current block.
  86163. * IN assertion: the field freq is set for all tree elements.
  86164. * OUT assertions: the fields len and code are set to the optimal bit length
  86165. * and corresponding code. The length opt_len is updated; static_len is
  86166. * also updated if stree is not null. The field max_code is set.
  86167. */
  86168. function build_tree(s, desc)
  86169. // deflate_state *s;
  86170. // tree_desc *desc; /* the tree descriptor */
  86171. {
  86172. var tree = desc.dyn_tree;
  86173. var stree = desc.stat_desc.static_tree;
  86174. var has_stree = desc.stat_desc.has_stree;
  86175. var elems = desc.stat_desc.elems;
  86176. var n, m; /* iterate over heap elements */
  86177. var max_code = -1; /* largest code with non zero frequency */
  86178. var node; /* new node being created */
  86179. /* Construct the initial heap, with least frequent element in
  86180. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  86181. * heap[0] is not used.
  86182. */
  86183. s.heap_len = 0;
  86184. s.heap_max = HEAP_SIZE;
  86185. for (n = 0; n < elems; n++) {
  86186. if (tree[n * 2]/*.Freq*/ !== 0) {
  86187. s.heap[++s.heap_len] = max_code = n;
  86188. s.depth[n] = 0;
  86189. } else {
  86190. tree[n * 2 + 1]/*.Len*/ = 0;
  86191. }
  86192. }
  86193. /* The pkzip format requires that at least one distance code exists,
  86194. * and that at least one bit should be sent even if there is only one
  86195. * possible code. So to avoid special checks later on we force at least
  86196. * two codes of non zero frequency.
  86197. */
  86198. while (s.heap_len < 2) {
  86199. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  86200. tree[node * 2]/*.Freq*/ = 1;
  86201. s.depth[node] = 0;
  86202. s.opt_len--;
  86203. if (has_stree) {
  86204. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  86205. }
  86206. /* node is 0 or 1 so it does not have extra bits */
  86207. }
  86208. desc.max_code = max_code;
  86209. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  86210. * establish sub-heaps of increasing lengths:
  86211. */
  86212. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  86213. /* Construct the Huffman tree by repeatedly combining the least two
  86214. * frequent nodes.
  86215. */
  86216. node = elems; /* next internal node of the tree */
  86217. do {
  86218. //pqremove(s, tree, n); /* n = node of least frequency */
  86219. /*** pqremove ***/
  86220. n = s.heap[1/*SMALLEST*/];
  86221. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  86222. pqdownheap(s, tree, 1/*SMALLEST*/);
  86223. /***/
  86224. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  86225. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  86226. s.heap[--s.heap_max] = m;
  86227. /* Create a new node father of n and m */
  86228. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  86229. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  86230. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  86231. /* and insert the new node in the heap */
  86232. s.heap[1/*SMALLEST*/] = node++;
  86233. pqdownheap(s, tree, 1/*SMALLEST*/);
  86234. } while (s.heap_len >= 2);
  86235. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  86236. /* At this point, the fields freq and dad are set. We can now
  86237. * generate the bit lengths.
  86238. */
  86239. gen_bitlen(s, desc);
  86240. /* The field len is now set, we can generate the bit codes */
  86241. gen_codes(tree, max_code, s.bl_count);
  86242. }
  86243. /* ===========================================================================
  86244. * Scan a literal or distance tree to determine the frequencies of the codes
  86245. * in the bit length tree.
  86246. */
  86247. function scan_tree(s, tree, max_code)
  86248. // deflate_state *s;
  86249. // ct_data *tree; /* the tree to be scanned */
  86250. // int max_code; /* and its largest code of non zero frequency */
  86251. {
  86252. var n; /* iterates over all tree elements */
  86253. var prevlen = -1; /* last emitted length */
  86254. var curlen; /* length of current code */
  86255. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  86256. var count = 0; /* repeat count of the current code */
  86257. var max_count = 7; /* max repeat count */
  86258. var min_count = 4; /* min repeat count */
  86259. if (nextlen === 0) {
  86260. max_count = 138;
  86261. min_count = 3;
  86262. }
  86263. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  86264. for (n = 0; n <= max_code; n++) {
  86265. curlen = nextlen;
  86266. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  86267. if (++count < max_count && curlen === nextlen) {
  86268. continue;
  86269. } else if (count < min_count) {
  86270. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  86271. } else if (curlen !== 0) {
  86272. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  86273. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  86274. } else if (count <= 10) {
  86275. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  86276. } else {
  86277. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  86278. }
  86279. count = 0;
  86280. prevlen = curlen;
  86281. if (nextlen === 0) {
  86282. max_count = 138;
  86283. min_count = 3;
  86284. } else if (curlen === nextlen) {
  86285. max_count = 6;
  86286. min_count = 3;
  86287. } else {
  86288. max_count = 7;
  86289. min_count = 4;
  86290. }
  86291. }
  86292. }
  86293. /* ===========================================================================
  86294. * Send a literal or distance tree in compressed form, using the codes in
  86295. * bl_tree.
  86296. */
  86297. function send_tree(s, tree, max_code)
  86298. // deflate_state *s;
  86299. // ct_data *tree; /* the tree to be scanned */
  86300. // int max_code; /* and its largest code of non zero frequency */
  86301. {
  86302. var n; /* iterates over all tree elements */
  86303. var prevlen = -1; /* last emitted length */
  86304. var curlen; /* length of current code */
  86305. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  86306. var count = 0; /* repeat count of the current code */
  86307. var max_count = 7; /* max repeat count */
  86308. var min_count = 4; /* min repeat count */
  86309. /* tree[max_code+1].Len = -1; */ /* guard already set */
  86310. if (nextlen === 0) {
  86311. max_count = 138;
  86312. min_count = 3;
  86313. }
  86314. for (n = 0; n <= max_code; n++) {
  86315. curlen = nextlen;
  86316. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  86317. if (++count < max_count && curlen === nextlen) {
  86318. continue;
  86319. } else if (count < min_count) {
  86320. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  86321. } else if (curlen !== 0) {
  86322. if (curlen !== prevlen) {
  86323. send_code(s, curlen, s.bl_tree);
  86324. count--;
  86325. }
  86326. //Assert(count >= 3 && count <= 6, " 3_6?");
  86327. send_code(s, REP_3_6, s.bl_tree);
  86328. send_bits(s, count - 3, 2);
  86329. } else if (count <= 10) {
  86330. send_code(s, REPZ_3_10, s.bl_tree);
  86331. send_bits(s, count - 3, 3);
  86332. } else {
  86333. send_code(s, REPZ_11_138, s.bl_tree);
  86334. send_bits(s, count - 11, 7);
  86335. }
  86336. count = 0;
  86337. prevlen = curlen;
  86338. if (nextlen === 0) {
  86339. max_count = 138;
  86340. min_count = 3;
  86341. } else if (curlen === nextlen) {
  86342. max_count = 6;
  86343. min_count = 3;
  86344. } else {
  86345. max_count = 7;
  86346. min_count = 4;
  86347. }
  86348. }
  86349. }
  86350. /* ===========================================================================
  86351. * Construct the Huffman tree for the bit lengths and return the index in
  86352. * bl_order of the last bit length code to send.
  86353. */
  86354. function build_bl_tree(s) {
  86355. var max_blindex; /* index of last bit length code of non zero freq */
  86356. /* Determine the bit length frequencies for literal and distance trees */
  86357. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  86358. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  86359. /* Build the bit length tree: */
  86360. build_tree(s, s.bl_desc);
  86361. /* opt_len now includes the length of the tree representations, except
  86362. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  86363. */
  86364. /* Determine the number of bit length codes to send. The pkzip format
  86365. * requires that at least 4 bit length codes be sent. (appnote.txt says
  86366. * 3 but the actual value used is 4.)
  86367. */
  86368. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  86369. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  86370. break;
  86371. }
  86372. }
  86373. /* Update opt_len to include the bit length tree and counts */
  86374. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  86375. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  86376. // s->opt_len, s->static_len));
  86377. return max_blindex;
  86378. }
  86379. /* ===========================================================================
  86380. * Send the header for a block using dynamic Huffman trees: the counts, the
  86381. * lengths of the bit length codes, the literal tree and the distance tree.
  86382. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  86383. */
  86384. function send_all_trees(s, lcodes, dcodes, blcodes)
  86385. // deflate_state *s;
  86386. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  86387. {
  86388. var rank; /* index in bl_order */
  86389. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  86390. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  86391. // "too many codes");
  86392. //Tracev((stderr, "\nbl counts: "));
  86393. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  86394. send_bits(s, dcodes - 1, 5);
  86395. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  86396. for (rank = 0; rank < blcodes; rank++) {
  86397. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  86398. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  86399. }
  86400. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  86401. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  86402. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  86403. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  86404. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  86405. }
  86406. /* ===========================================================================
  86407. * Check if the data type is TEXT or BINARY, using the following algorithm:
  86408. * - TEXT if the two conditions below are satisfied:
  86409. * a) There are no non-portable control characters belonging to the
  86410. * "black list" (0..6, 14..25, 28..31).
  86411. * b) There is at least one printable character belonging to the
  86412. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  86413. * - BINARY otherwise.
  86414. * - The following partially-portable control characters form a
  86415. * "gray list" that is ignored in this detection algorithm:
  86416. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  86417. * IN assertion: the fields Freq of dyn_ltree are set.
  86418. */
  86419. function detect_data_type(s) {
  86420. /* black_mask is the bit mask of black-listed bytes
  86421. * set bits 0..6, 14..25, and 28..31
  86422. * 0xf3ffc07f = binary 11110011111111111100000001111111
  86423. */
  86424. var black_mask = 0xf3ffc07f;
  86425. var n;
  86426. /* Check for non-textual ("black-listed") bytes. */
  86427. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  86428. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  86429. return Z_BINARY;
  86430. }
  86431. }
  86432. /* Check for textual ("white-listed") bytes. */
  86433. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  86434. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  86435. return Z_TEXT;
  86436. }
  86437. for (n = 32; n < LITERALS; n++) {
  86438. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  86439. return Z_TEXT;
  86440. }
  86441. }
  86442. /* There are no "black-listed" or "white-listed" bytes:
  86443. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  86444. */
  86445. return Z_BINARY;
  86446. }
  86447. var static_init_done = false;
  86448. /* ===========================================================================
  86449. * Initialize the tree data structures for a new zlib stream.
  86450. */
  86451. function _tr_init(s)
  86452. {
  86453. if (!static_init_done) {
  86454. tr_static_init();
  86455. static_init_done = true;
  86456. }
  86457. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  86458. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  86459. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  86460. s.bi_buf = 0;
  86461. s.bi_valid = 0;
  86462. /* Initialize the first block of the first file: */
  86463. init_block(s);
  86464. }
  86465. /* ===========================================================================
  86466. * Send a stored block
  86467. */
  86468. function _tr_stored_block(s, buf, stored_len, last)
  86469. //DeflateState *s;
  86470. //charf *buf; /* input block */
  86471. //ulg stored_len; /* length of input block */
  86472. //int last; /* one if this is the last block for a file */
  86473. {
  86474. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  86475. copy_block(s, buf, stored_len, true); /* with header */
  86476. }
  86477. /* ===========================================================================
  86478. * Send one empty static block to give enough lookahead for inflate.
  86479. * This takes 10 bits, of which 7 may remain in the bit buffer.
  86480. */
  86481. function _tr_align(s) {
  86482. send_bits(s, STATIC_TREES << 1, 3);
  86483. send_code(s, END_BLOCK, static_ltree);
  86484. bi_flush(s);
  86485. }
  86486. /* ===========================================================================
  86487. * Determine the best encoding for the current block: dynamic trees, static
  86488. * trees or store, and output the encoded block to the zip file.
  86489. */
  86490. function _tr_flush_block(s, buf, stored_len, last)
  86491. //DeflateState *s;
  86492. //charf *buf; /* input block, or NULL if too old */
  86493. //ulg stored_len; /* length of input block */
  86494. //int last; /* one if this is the last block for a file */
  86495. {
  86496. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  86497. var max_blindex = 0; /* index of last bit length code of non zero freq */
  86498. /* Build the Huffman trees unless a stored block is forced */
  86499. if (s.level > 0) {
  86500. /* Check if the file is binary or text */
  86501. if (s.strm.data_type === Z_UNKNOWN) {
  86502. s.strm.data_type = detect_data_type(s);
  86503. }
  86504. /* Construct the literal and distance trees */
  86505. build_tree(s, s.l_desc);
  86506. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  86507. // s->static_len));
  86508. build_tree(s, s.d_desc);
  86509. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  86510. // s->static_len));
  86511. /* At this point, opt_len and static_len are the total bit lengths of
  86512. * the compressed block data, excluding the tree representations.
  86513. */
  86514. /* Build the bit length tree for the above two trees, and get the index
  86515. * in bl_order of the last bit length code to send.
  86516. */
  86517. max_blindex = build_bl_tree(s);
  86518. /* Determine the best encoding. Compute the block lengths in bytes. */
  86519. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  86520. static_lenb = (s.static_len + 3 + 7) >>> 3;
  86521. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  86522. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  86523. // s->last_lit));
  86524. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  86525. } else {
  86526. // Assert(buf != (char*)0, "lost buf");
  86527. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  86528. }
  86529. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  86530. /* 4: two words for the lengths */
  86531. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  86532. * Otherwise we can't have processed more than WSIZE input bytes since
  86533. * the last block flush, because compression would have been
  86534. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  86535. * transform a block into a stored block.
  86536. */
  86537. _tr_stored_block(s, buf, stored_len, last);
  86538. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  86539. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  86540. compress_block(s, static_ltree, static_dtree);
  86541. } else {
  86542. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  86543. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  86544. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  86545. }
  86546. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  86547. /* The above check is made mod 2^32, for files larger than 512 MB
  86548. * and uLong implemented on 32 bits.
  86549. */
  86550. init_block(s);
  86551. if (last) {
  86552. bi_windup(s);
  86553. }
  86554. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  86555. // s->compressed_len-7*last));
  86556. }
  86557. /* ===========================================================================
  86558. * Save the match info and tally the frequency counts. Return true if
  86559. * the current block must be flushed.
  86560. */
  86561. function _tr_tally(s, dist, lc)
  86562. // deflate_state *s;
  86563. // unsigned dist; /* distance of matched string */
  86564. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  86565. {
  86566. //var out_length, in_length, dcode;
  86567. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  86568. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  86569. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  86570. s.last_lit++;
  86571. if (dist === 0) {
  86572. /* lc is the unmatched char */
  86573. s.dyn_ltree[lc * 2]/*.Freq*/++;
  86574. } else {
  86575. s.matches++;
  86576. /* Here, lc is the match length - MIN_MATCH */
  86577. dist--; /* dist = match distance - 1 */
  86578. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  86579. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  86580. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  86581. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  86582. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  86583. }
  86584. // (!) This block is disabled in zlib defaults,
  86585. // don't enable it for binary compatibility
  86586. //#ifdef TRUNCATE_BLOCK
  86587. // /* Try to guess if it is profitable to stop the current block here */
  86588. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  86589. // /* Compute an upper bound for the compressed length */
  86590. // out_length = s.last_lit*8;
  86591. // in_length = s.strstart - s.block_start;
  86592. //
  86593. // for (dcode = 0; dcode < D_CODES; dcode++) {
  86594. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  86595. // }
  86596. // out_length >>>= 3;
  86597. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  86598. // // s->last_lit, in_length, out_length,
  86599. // // 100L - out_length*100L/in_length));
  86600. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  86601. // return true;
  86602. // }
  86603. // }
  86604. //#endif
  86605. return (s.last_lit === s.lit_bufsize - 1);
  86606. /* We avoid equality with lit_bufsize because of wraparound at 64K
  86607. * on 16 bit machines and because stored blocks are restricted to
  86608. * 64K-1 bytes.
  86609. */
  86610. }
  86611. exports._tr_init = _tr_init;
  86612. exports._tr_stored_block = _tr_stored_block;
  86613. exports._tr_flush_block = _tr_flush_block;
  86614. exports._tr_tally = _tr_tally;
  86615. exports._tr_align = _tr_align;
  86616. },{"../utils/common":501}],511:[function(require,module,exports){
  86617. 'use strict';
  86618. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  86619. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  86620. //
  86621. // This software is provided 'as-is', without any express or implied
  86622. // warranty. In no event will the authors be held liable for any damages
  86623. // arising from the use of this software.
  86624. //
  86625. // Permission is granted to anyone to use this software for any purpose,
  86626. // including commercial applications, and to alter it and redistribute it
  86627. // freely, subject to the following restrictions:
  86628. //
  86629. // 1. The origin of this software must not be misrepresented; you must not
  86630. // claim that you wrote the original software. If you use this software
  86631. // in a product, an acknowledgment in the product documentation would be
  86632. // appreciated but is not required.
  86633. // 2. Altered source versions must be plainly marked as such, and must not be
  86634. // misrepresented as being the original software.
  86635. // 3. This notice may not be removed or altered from any source distribution.
  86636. function ZStream() {
  86637. /* next input byte */
  86638. this.input = null; // JS specific, because we have no pointers
  86639. this.next_in = 0;
  86640. /* number of bytes available at input */
  86641. this.avail_in = 0;
  86642. /* total number of input bytes read so far */
  86643. this.total_in = 0;
  86644. /* next output byte should be put there */
  86645. this.output = null; // JS specific, because we have no pointers
  86646. this.next_out = 0;
  86647. /* remaining free space at output */
  86648. this.avail_out = 0;
  86649. /* total number of bytes output so far */
  86650. this.total_out = 0;
  86651. /* last error message, NULL if no error */
  86652. this.msg = ''/*Z_NULL*/;
  86653. /* not visible by applications */
  86654. this.state = null;
  86655. /* best guess about the data type: binary or text */
  86656. this.data_type = 2/*Z_UNKNOWN*/;
  86657. /* adler32 value of the uncompressed data */
  86658. this.adler = 0;
  86659. }
  86660. module.exports = ZStream;
  86661. },{}],512:[function(require,module,exports){
  86662. module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
  86663. "2.16.840.1.101.3.4.1.2": "aes-128-cbc",
  86664. "2.16.840.1.101.3.4.1.3": "aes-128-ofb",
  86665. "2.16.840.1.101.3.4.1.4": "aes-128-cfb",
  86666. "2.16.840.1.101.3.4.1.21": "aes-192-ecb",
  86667. "2.16.840.1.101.3.4.1.22": "aes-192-cbc",
  86668. "2.16.840.1.101.3.4.1.23": "aes-192-ofb",
  86669. "2.16.840.1.101.3.4.1.24": "aes-192-cfb",
  86670. "2.16.840.1.101.3.4.1.41": "aes-256-ecb",
  86671. "2.16.840.1.101.3.4.1.42": "aes-256-cbc",
  86672. "2.16.840.1.101.3.4.1.43": "aes-256-ofb",
  86673. "2.16.840.1.101.3.4.1.44": "aes-256-cfb"
  86674. }
  86675. },{}],513:[function(require,module,exports){
  86676. // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
  86677. // Fedor, you are amazing.
  86678. 'use strict'
  86679. var asn1 = require('asn1.js')
  86680. exports.certificate = require('./certificate')
  86681. var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
  86682. this.seq().obj(
  86683. this.key('version').int(),
  86684. this.key('modulus').int(),
  86685. this.key('publicExponent').int(),
  86686. this.key('privateExponent').int(),
  86687. this.key('prime1').int(),
  86688. this.key('prime2').int(),
  86689. this.key('exponent1').int(),
  86690. this.key('exponent2').int(),
  86691. this.key('coefficient').int()
  86692. )
  86693. })
  86694. exports.RSAPrivateKey = RSAPrivateKey
  86695. var RSAPublicKey = asn1.define('RSAPublicKey', function () {
  86696. this.seq().obj(
  86697. this.key('modulus').int(),
  86698. this.key('publicExponent').int()
  86699. )
  86700. })
  86701. exports.RSAPublicKey = RSAPublicKey
  86702. var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
  86703. this.seq().obj(
  86704. this.key('algorithm').use(AlgorithmIdentifier),
  86705. this.key('subjectPublicKey').bitstr()
  86706. )
  86707. })
  86708. exports.PublicKey = PublicKey
  86709. var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
  86710. this.seq().obj(
  86711. this.key('algorithm').objid(),
  86712. this.key('none').null_().optional(),
  86713. this.key('curve').objid().optional(),
  86714. this.key('params').seq().obj(
  86715. this.key('p').int(),
  86716. this.key('q').int(),
  86717. this.key('g').int()
  86718. ).optional()
  86719. )
  86720. })
  86721. var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
  86722. this.seq().obj(
  86723. this.key('version').int(),
  86724. this.key('algorithm').use(AlgorithmIdentifier),
  86725. this.key('subjectPrivateKey').octstr()
  86726. )
  86727. })
  86728. exports.PrivateKey = PrivateKeyInfo
  86729. var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
  86730. this.seq().obj(
  86731. this.key('algorithm').seq().obj(
  86732. this.key('id').objid(),
  86733. this.key('decrypt').seq().obj(
  86734. this.key('kde').seq().obj(
  86735. this.key('id').objid(),
  86736. this.key('kdeparams').seq().obj(
  86737. this.key('salt').octstr(),
  86738. this.key('iters').int()
  86739. )
  86740. ),
  86741. this.key('cipher').seq().obj(
  86742. this.key('algo').objid(),
  86743. this.key('iv').octstr()
  86744. )
  86745. )
  86746. ),
  86747. this.key('subjectPrivateKey').octstr()
  86748. )
  86749. })
  86750. exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
  86751. var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
  86752. this.seq().obj(
  86753. this.key('version').int(),
  86754. this.key('p').int(),
  86755. this.key('q').int(),
  86756. this.key('g').int(),
  86757. this.key('pub_key').int(),
  86758. this.key('priv_key').int()
  86759. )
  86760. })
  86761. exports.DSAPrivateKey = DSAPrivateKey
  86762. exports.DSAparam = asn1.define('DSAparam', function () {
  86763. this.int()
  86764. })
  86765. var ECPrivateKey = asn1.define('ECPrivateKey', function () {
  86766. this.seq().obj(
  86767. this.key('version').int(),
  86768. this.key('privateKey').octstr(),
  86769. this.key('parameters').optional().explicit(0).use(ECParameters),
  86770. this.key('publicKey').optional().explicit(1).bitstr()
  86771. )
  86772. })
  86773. exports.ECPrivateKey = ECPrivateKey
  86774. var ECParameters = asn1.define('ECParameters', function () {
  86775. this.choice({
  86776. namedCurve: this.objid()
  86777. })
  86778. })
  86779. exports.signature = asn1.define('signature', function () {
  86780. this.seq().obj(
  86781. this.key('r').int(),
  86782. this.key('s').int()
  86783. )
  86784. })
  86785. },{"./certificate":514,"asn1.js":83}],514:[function(require,module,exports){
  86786. // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
  86787. // thanks to @Rantanen
  86788. 'use strict'
  86789. var asn = require('asn1.js')
  86790. var Time = asn.define('Time', function () {
  86791. this.choice({
  86792. utcTime: this.utctime(),
  86793. generalTime: this.gentime()
  86794. })
  86795. })
  86796. var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
  86797. this.seq().obj(
  86798. this.key('type').objid(),
  86799. this.key('value').any()
  86800. )
  86801. })
  86802. var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
  86803. this.seq().obj(
  86804. this.key('algorithm').objid(),
  86805. this.key('parameters').optional(),
  86806. this.key('curve').objid().optional()
  86807. )
  86808. })
  86809. var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
  86810. this.seq().obj(
  86811. this.key('algorithm').use(AlgorithmIdentifier),
  86812. this.key('subjectPublicKey').bitstr()
  86813. )
  86814. })
  86815. var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
  86816. this.setof(AttributeTypeValue)
  86817. })
  86818. var RDNSequence = asn.define('RDNSequence', function () {
  86819. this.seqof(RelativeDistinguishedName)
  86820. })
  86821. var Name = asn.define('Name', function () {
  86822. this.choice({
  86823. rdnSequence: this.use(RDNSequence)
  86824. })
  86825. })
  86826. var Validity = asn.define('Validity', function () {
  86827. this.seq().obj(
  86828. this.key('notBefore').use(Time),
  86829. this.key('notAfter').use(Time)
  86830. )
  86831. })
  86832. var Extension = asn.define('Extension', function () {
  86833. this.seq().obj(
  86834. this.key('extnID').objid(),
  86835. this.key('critical').bool().def(false),
  86836. this.key('extnValue').octstr()
  86837. )
  86838. })
  86839. var TBSCertificate = asn.define('TBSCertificate', function () {
  86840. this.seq().obj(
  86841. this.key('version').explicit(0).int().optional(),
  86842. this.key('serialNumber').int(),
  86843. this.key('signature').use(AlgorithmIdentifier),
  86844. this.key('issuer').use(Name),
  86845. this.key('validity').use(Validity),
  86846. this.key('subject').use(Name),
  86847. this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
  86848. this.key('issuerUniqueID').implicit(1).bitstr().optional(),
  86849. this.key('subjectUniqueID').implicit(2).bitstr().optional(),
  86850. this.key('extensions').explicit(3).seqof(Extension).optional()
  86851. )
  86852. })
  86853. var X509Certificate = asn.define('X509Certificate', function () {
  86854. this.seq().obj(
  86855. this.key('tbsCertificate').use(TBSCertificate),
  86856. this.key('signatureAlgorithm').use(AlgorithmIdentifier),
  86857. this.key('signatureValue').bitstr()
  86858. )
  86859. })
  86860. module.exports = X509Certificate
  86861. },{"asn1.js":83}],515:[function(require,module,exports){
  86862. // adapted from https://github.com/apatil/pemstrip
  86863. var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m
  86864. var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m
  86865. var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m
  86866. var evp = require('evp_bytestokey')
  86867. var ciphers = require('browserify-aes')
  86868. var Buffer = require('safe-buffer').Buffer
  86869. module.exports = function (okey, password) {
  86870. var key = okey.toString()
  86871. var match = key.match(findProc)
  86872. var decrypted
  86873. if (!match) {
  86874. var match2 = key.match(fullRegex)
  86875. decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64')
  86876. } else {
  86877. var suite = 'aes' + match[1]
  86878. var iv = Buffer.from(match[2], 'hex')
  86879. var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64')
  86880. var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
  86881. var out = []
  86882. var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
  86883. out.push(cipher.update(cipherText))
  86884. out.push(cipher.final())
  86885. decrypted = Buffer.concat(out)
  86886. }
  86887. var tag = key.match(startRegex)[1]
  86888. return {
  86889. tag: tag,
  86890. data: decrypted
  86891. }
  86892. }
  86893. },{"browserify-aes":147,"evp_bytestokey":248,"safe-buffer":561}],516:[function(require,module,exports){
  86894. var asn1 = require('./asn1')
  86895. var aesid = require('./aesid.json')
  86896. var fixProc = require('./fixProc')
  86897. var ciphers = require('browserify-aes')
  86898. var compat = require('pbkdf2')
  86899. var Buffer = require('safe-buffer').Buffer
  86900. module.exports = parseKeys
  86901. function parseKeys (buffer) {
  86902. var password
  86903. if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
  86904. password = buffer.passphrase
  86905. buffer = buffer.key
  86906. }
  86907. if (typeof buffer === 'string') {
  86908. buffer = Buffer.from(buffer)
  86909. }
  86910. var stripped = fixProc(buffer, password)
  86911. var type = stripped.tag
  86912. var data = stripped.data
  86913. var subtype, ndata
  86914. switch (type) {
  86915. case 'CERTIFICATE':
  86916. ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
  86917. // falls through
  86918. case 'PUBLIC KEY':
  86919. if (!ndata) {
  86920. ndata = asn1.PublicKey.decode(data, 'der')
  86921. }
  86922. subtype = ndata.algorithm.algorithm.join('.')
  86923. switch (subtype) {
  86924. case '1.2.840.113549.1.1.1':
  86925. return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
  86926. case '1.2.840.10045.2.1':
  86927. ndata.subjectPrivateKey = ndata.subjectPublicKey
  86928. return {
  86929. type: 'ec',
  86930. data: ndata
  86931. }
  86932. case '1.2.840.10040.4.1':
  86933. ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
  86934. return {
  86935. type: 'dsa',
  86936. data: ndata.algorithm.params
  86937. }
  86938. default: throw new Error('unknown key id ' + subtype)
  86939. }
  86940. // throw new Error('unknown key type ' + type)
  86941. case 'ENCRYPTED PRIVATE KEY':
  86942. data = asn1.EncryptedPrivateKey.decode(data, 'der')
  86943. data = decrypt(data, password)
  86944. // falls through
  86945. case 'PRIVATE KEY':
  86946. ndata = asn1.PrivateKey.decode(data, 'der')
  86947. subtype = ndata.algorithm.algorithm.join('.')
  86948. switch (subtype) {
  86949. case '1.2.840.113549.1.1.1':
  86950. return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
  86951. case '1.2.840.10045.2.1':
  86952. return {
  86953. curve: ndata.algorithm.curve,
  86954. privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
  86955. }
  86956. case '1.2.840.10040.4.1':
  86957. ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
  86958. return {
  86959. type: 'dsa',
  86960. params: ndata.algorithm.params
  86961. }
  86962. default: throw new Error('unknown key id ' + subtype)
  86963. }
  86964. // throw new Error('unknown key type ' + type)
  86965. case 'RSA PUBLIC KEY':
  86966. return asn1.RSAPublicKey.decode(data, 'der')
  86967. case 'RSA PRIVATE KEY':
  86968. return asn1.RSAPrivateKey.decode(data, 'der')
  86969. case 'DSA PRIVATE KEY':
  86970. return {
  86971. type: 'dsa',
  86972. params: asn1.DSAPrivateKey.decode(data, 'der')
  86973. }
  86974. case 'EC PRIVATE KEY':
  86975. data = asn1.ECPrivateKey.decode(data, 'der')
  86976. return {
  86977. curve: data.parameters.value,
  86978. privateKey: data.privateKey
  86979. }
  86980. default: throw new Error('unknown key type ' + type)
  86981. }
  86982. }
  86983. parseKeys.signature = asn1.signature
  86984. function decrypt (data, password) {
  86985. var salt = data.algorithm.decrypt.kde.kdeparams.salt
  86986. var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
  86987. var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
  86988. var iv = data.algorithm.decrypt.cipher.iv
  86989. var cipherText = data.subjectPrivateKey
  86990. var keylen = parseInt(algo.split('-')[1], 10) / 8
  86991. var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1')
  86992. var cipher = ciphers.createDecipheriv(algo, key, iv)
  86993. var out = []
  86994. out.push(cipher.update(cipherText))
  86995. out.push(cipher.final())
  86996. return Buffer.concat(out)
  86997. }
  86998. },{"./aesid.json":512,"./asn1":513,"./fixProc":515,"browserify-aes":147,"pbkdf2":518,"safe-buffer":561}],517:[function(require,module,exports){
  86999. (function (process){(function (){
  87000. // 'path' module extracted from Node.js v8.11.1 (only the posix part)
  87001. // transplited with Babel
  87002. // Copyright Joyent, Inc. and other Node contributors.
  87003. //
  87004. // Permission is hereby granted, free of charge, to any person obtaining a
  87005. // copy of this software and associated documentation files (the
  87006. // "Software"), to deal in the Software without restriction, including
  87007. // without limitation the rights to use, copy, modify, merge, publish,
  87008. // distribute, sublicense, and/or sell copies of the Software, and to permit
  87009. // persons to whom the Software is furnished to do so, subject to the
  87010. // following conditions:
  87011. //
  87012. // The above copyright notice and this permission notice shall be included
  87013. // in all copies or substantial portions of the Software.
  87014. //
  87015. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  87016. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  87017. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  87018. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  87019. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  87020. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  87021. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  87022. 'use strict';
  87023. function assertPath(path) {
  87024. if (typeof path !== 'string') {
  87025. throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
  87026. }
  87027. }
  87028. // Resolves . and .. elements in a path with directory names
  87029. function normalizeStringPosix(path, allowAboveRoot) {
  87030. var res = '';
  87031. var lastSegmentLength = 0;
  87032. var lastSlash = -1;
  87033. var dots = 0;
  87034. var code;
  87035. for (var i = 0; i <= path.length; ++i) {
  87036. if (i < path.length)
  87037. code = path.charCodeAt(i);
  87038. else if (code === 47 /*/*/)
  87039. break;
  87040. else
  87041. code = 47 /*/*/;
  87042. if (code === 47 /*/*/) {
  87043. if (lastSlash === i - 1 || dots === 1) {
  87044. // NOOP
  87045. } else if (lastSlash !== i - 1 && dots === 2) {
  87046. if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
  87047. if (res.length > 2) {
  87048. var lastSlashIndex = res.lastIndexOf('/');
  87049. if (lastSlashIndex !== res.length - 1) {
  87050. if (lastSlashIndex === -1) {
  87051. res = '';
  87052. lastSegmentLength = 0;
  87053. } else {
  87054. res = res.slice(0, lastSlashIndex);
  87055. lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
  87056. }
  87057. lastSlash = i;
  87058. dots = 0;
  87059. continue;
  87060. }
  87061. } else if (res.length === 2 || res.length === 1) {
  87062. res = '';
  87063. lastSegmentLength = 0;
  87064. lastSlash = i;
  87065. dots = 0;
  87066. continue;
  87067. }
  87068. }
  87069. if (allowAboveRoot) {
  87070. if (res.length > 0)
  87071. res += '/..';
  87072. else
  87073. res = '..';
  87074. lastSegmentLength = 2;
  87075. }
  87076. } else {
  87077. if (res.length > 0)
  87078. res += '/' + path.slice(lastSlash + 1, i);
  87079. else
  87080. res = path.slice(lastSlash + 1, i);
  87081. lastSegmentLength = i - lastSlash - 1;
  87082. }
  87083. lastSlash = i;
  87084. dots = 0;
  87085. } else if (code === 46 /*.*/ && dots !== -1) {
  87086. ++dots;
  87087. } else {
  87088. dots = -1;
  87089. }
  87090. }
  87091. return res;
  87092. }
  87093. function _format(sep, pathObject) {
  87094. var dir = pathObject.dir || pathObject.root;
  87095. var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
  87096. if (!dir) {
  87097. return base;
  87098. }
  87099. if (dir === pathObject.root) {
  87100. return dir + base;
  87101. }
  87102. return dir + sep + base;
  87103. }
  87104. var posix = {
  87105. // path.resolve([from ...], to)
  87106. resolve: function resolve() {
  87107. var resolvedPath = '';
  87108. var resolvedAbsolute = false;
  87109. var cwd;
  87110. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  87111. var path;
  87112. if (i >= 0)
  87113. path = arguments[i];
  87114. else {
  87115. if (cwd === undefined)
  87116. cwd = process.cwd();
  87117. path = cwd;
  87118. }
  87119. assertPath(path);
  87120. // Skip empty entries
  87121. if (path.length === 0) {
  87122. continue;
  87123. }
  87124. resolvedPath = path + '/' + resolvedPath;
  87125. resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
  87126. }
  87127. // At this point the path should be resolved to a full absolute path, but
  87128. // handle relative paths to be safe (might happen when process.cwd() fails)
  87129. // Normalize the path
  87130. resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
  87131. if (resolvedAbsolute) {
  87132. if (resolvedPath.length > 0)
  87133. return '/' + resolvedPath;
  87134. else
  87135. return '/';
  87136. } else if (resolvedPath.length > 0) {
  87137. return resolvedPath;
  87138. } else {
  87139. return '.';
  87140. }
  87141. },
  87142. normalize: function normalize(path) {
  87143. assertPath(path);
  87144. if (path.length === 0) return '.';
  87145. var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
  87146. var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;
  87147. // Normalize the path
  87148. path = normalizeStringPosix(path, !isAbsolute);
  87149. if (path.length === 0 && !isAbsolute) path = '.';
  87150. if (path.length > 0 && trailingSeparator) path += '/';
  87151. if (isAbsolute) return '/' + path;
  87152. return path;
  87153. },
  87154. isAbsolute: function isAbsolute(path) {
  87155. assertPath(path);
  87156. return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
  87157. },
  87158. join: function join() {
  87159. if (arguments.length === 0)
  87160. return '.';
  87161. var joined;
  87162. for (var i = 0; i < arguments.length; ++i) {
  87163. var arg = arguments[i];
  87164. assertPath(arg);
  87165. if (arg.length > 0) {
  87166. if (joined === undefined)
  87167. joined = arg;
  87168. else
  87169. joined += '/' + arg;
  87170. }
  87171. }
  87172. if (joined === undefined)
  87173. return '.';
  87174. return posix.normalize(joined);
  87175. },
  87176. relative: function relative(from, to) {
  87177. assertPath(from);
  87178. assertPath(to);
  87179. if (from === to) return '';
  87180. from = posix.resolve(from);
  87181. to = posix.resolve(to);
  87182. if (from === to) return '';
  87183. // Trim any leading backslashes
  87184. var fromStart = 1;
  87185. for (; fromStart < from.length; ++fromStart) {
  87186. if (from.charCodeAt(fromStart) !== 47 /*/*/)
  87187. break;
  87188. }
  87189. var fromEnd = from.length;
  87190. var fromLen = fromEnd - fromStart;
  87191. // Trim any leading backslashes
  87192. var toStart = 1;
  87193. for (; toStart < to.length; ++toStart) {
  87194. if (to.charCodeAt(toStart) !== 47 /*/*/)
  87195. break;
  87196. }
  87197. var toEnd = to.length;
  87198. var toLen = toEnd - toStart;
  87199. // Compare paths to find the longest common path from root
  87200. var length = fromLen < toLen ? fromLen : toLen;
  87201. var lastCommonSep = -1;
  87202. var i = 0;
  87203. for (; i <= length; ++i) {
  87204. if (i === length) {
  87205. if (toLen > length) {
  87206. if (to.charCodeAt(toStart + i) === 47 /*/*/) {
  87207. // We get here if `from` is the exact base path for `to`.
  87208. // For example: from='/foo/bar'; to='/foo/bar/baz'
  87209. return to.slice(toStart + i + 1);
  87210. } else if (i === 0) {
  87211. // We get here if `from` is the root
  87212. // For example: from='/'; to='/foo'
  87213. return to.slice(toStart + i);
  87214. }
  87215. } else if (fromLen > length) {
  87216. if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
  87217. // We get here if `to` is the exact base path for `from`.
  87218. // For example: from='/foo/bar/baz'; to='/foo/bar'
  87219. lastCommonSep = i;
  87220. } else if (i === 0) {
  87221. // We get here if `to` is the root.
  87222. // For example: from='/foo'; to='/'
  87223. lastCommonSep = 0;
  87224. }
  87225. }
  87226. break;
  87227. }
  87228. var fromCode = from.charCodeAt(fromStart + i);
  87229. var toCode = to.charCodeAt(toStart + i);
  87230. if (fromCode !== toCode)
  87231. break;
  87232. else if (fromCode === 47 /*/*/)
  87233. lastCommonSep = i;
  87234. }
  87235. var out = '';
  87236. // Generate the relative path based on the path difference between `to`
  87237. // and `from`
  87238. for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
  87239. if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
  87240. if (out.length === 0)
  87241. out += '..';
  87242. else
  87243. out += '/..';
  87244. }
  87245. }
  87246. // Lastly, append the rest of the destination (`to`) path that comes after
  87247. // the common path parts
  87248. if (out.length > 0)
  87249. return out + to.slice(toStart + lastCommonSep);
  87250. else {
  87251. toStart += lastCommonSep;
  87252. if (to.charCodeAt(toStart) === 47 /*/*/)
  87253. ++toStart;
  87254. return to.slice(toStart);
  87255. }
  87256. },
  87257. _makeLong: function _makeLong(path) {
  87258. return path;
  87259. },
  87260. dirname: function dirname(path) {
  87261. assertPath(path);
  87262. if (path.length === 0) return '.';
  87263. var code = path.charCodeAt(0);
  87264. var hasRoot = code === 47 /*/*/;
  87265. var end = -1;
  87266. var matchedSlash = true;
  87267. for (var i = path.length - 1; i >= 1; --i) {
  87268. code = path.charCodeAt(i);
  87269. if (code === 47 /*/*/) {
  87270. if (!matchedSlash) {
  87271. end = i;
  87272. break;
  87273. }
  87274. } else {
  87275. // We saw the first non-path separator
  87276. matchedSlash = false;
  87277. }
  87278. }
  87279. if (end === -1) return hasRoot ? '/' : '.';
  87280. if (hasRoot && end === 1) return '//';
  87281. return path.slice(0, end);
  87282. },
  87283. basename: function basename(path, ext) {
  87284. if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
  87285. assertPath(path);
  87286. var start = 0;
  87287. var end = -1;
  87288. var matchedSlash = true;
  87289. var i;
  87290. if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
  87291. if (ext.length === path.length && ext === path) return '';
  87292. var extIdx = ext.length - 1;
  87293. var firstNonSlashEnd = -1;
  87294. for (i = path.length - 1; i >= 0; --i) {
  87295. var code = path.charCodeAt(i);
  87296. if (code === 47 /*/*/) {
  87297. // If we reached a path separator that was not part of a set of path
  87298. // separators at the end of the string, stop now
  87299. if (!matchedSlash) {
  87300. start = i + 1;
  87301. break;
  87302. }
  87303. } else {
  87304. if (firstNonSlashEnd === -1) {
  87305. // We saw the first non-path separator, remember this index in case
  87306. // we need it if the extension ends up not matching
  87307. matchedSlash = false;
  87308. firstNonSlashEnd = i + 1;
  87309. }
  87310. if (extIdx >= 0) {
  87311. // Try to match the explicit extension
  87312. if (code === ext.charCodeAt(extIdx)) {
  87313. if (--extIdx === -1) {
  87314. // We matched the extension, so mark this as the end of our path
  87315. // component
  87316. end = i;
  87317. }
  87318. } else {
  87319. // Extension does not match, so our result is the entire path
  87320. // component
  87321. extIdx = -1;
  87322. end = firstNonSlashEnd;
  87323. }
  87324. }
  87325. }
  87326. }
  87327. if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;
  87328. return path.slice(start, end);
  87329. } else {
  87330. for (i = path.length - 1; i >= 0; --i) {
  87331. if (path.charCodeAt(i) === 47 /*/*/) {
  87332. // If we reached a path separator that was not part of a set of path
  87333. // separators at the end of the string, stop now
  87334. if (!matchedSlash) {
  87335. start = i + 1;
  87336. break;
  87337. }
  87338. } else if (end === -1) {
  87339. // We saw the first non-path separator, mark this as the end of our
  87340. // path component
  87341. matchedSlash = false;
  87342. end = i + 1;
  87343. }
  87344. }
  87345. if (end === -1) return '';
  87346. return path.slice(start, end);
  87347. }
  87348. },
  87349. extname: function extname(path) {
  87350. assertPath(path);
  87351. var startDot = -1;
  87352. var startPart = 0;
  87353. var end = -1;
  87354. var matchedSlash = true;
  87355. // Track the state of characters (if any) we see before our first dot and
  87356. // after any path separator we find
  87357. var preDotState = 0;
  87358. for (var i = path.length - 1; i >= 0; --i) {
  87359. var code = path.charCodeAt(i);
  87360. if (code === 47 /*/*/) {
  87361. // If we reached a path separator that was not part of a set of path
  87362. // separators at the end of the string, stop now
  87363. if (!matchedSlash) {
  87364. startPart = i + 1;
  87365. break;
  87366. }
  87367. continue;
  87368. }
  87369. if (end === -1) {
  87370. // We saw the first non-path separator, mark this as the end of our
  87371. // extension
  87372. matchedSlash = false;
  87373. end = i + 1;
  87374. }
  87375. if (code === 46 /*.*/) {
  87376. // If this is our first dot, mark it as the start of our extension
  87377. if (startDot === -1)
  87378. startDot = i;
  87379. else if (preDotState !== 1)
  87380. preDotState = 1;
  87381. } else if (startDot !== -1) {
  87382. // We saw a non-dot and non-path separator before our dot, so we should
  87383. // have a good chance at having a non-empty extension
  87384. preDotState = -1;
  87385. }
  87386. }
  87387. if (startDot === -1 || end === -1 ||
  87388. // We saw a non-dot character immediately before the dot
  87389. preDotState === 0 ||
  87390. // The (right-most) trimmed path component is exactly '..'
  87391. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  87392. return '';
  87393. }
  87394. return path.slice(startDot, end);
  87395. },
  87396. format: function format(pathObject) {
  87397. if (pathObject === null || typeof pathObject !== 'object') {
  87398. throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
  87399. }
  87400. return _format('/', pathObject);
  87401. },
  87402. parse: function parse(path) {
  87403. assertPath(path);
  87404. var ret = { root: '', dir: '', base: '', ext: '', name: '' };
  87405. if (path.length === 0) return ret;
  87406. var code = path.charCodeAt(0);
  87407. var isAbsolute = code === 47 /*/*/;
  87408. var start;
  87409. if (isAbsolute) {
  87410. ret.root = '/';
  87411. start = 1;
  87412. } else {
  87413. start = 0;
  87414. }
  87415. var startDot = -1;
  87416. var startPart = 0;
  87417. var end = -1;
  87418. var matchedSlash = true;
  87419. var i = path.length - 1;
  87420. // Track the state of characters (if any) we see before our first dot and
  87421. // after any path separator we find
  87422. var preDotState = 0;
  87423. // Get non-dir info
  87424. for (; i >= start; --i) {
  87425. code = path.charCodeAt(i);
  87426. if (code === 47 /*/*/) {
  87427. // If we reached a path separator that was not part of a set of path
  87428. // separators at the end of the string, stop now
  87429. if (!matchedSlash) {
  87430. startPart = i + 1;
  87431. break;
  87432. }
  87433. continue;
  87434. }
  87435. if (end === -1) {
  87436. // We saw the first non-path separator, mark this as the end of our
  87437. // extension
  87438. matchedSlash = false;
  87439. end = i + 1;
  87440. }
  87441. if (code === 46 /*.*/) {
  87442. // If this is our first dot, mark it as the start of our extension
  87443. if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;
  87444. } else if (startDot !== -1) {
  87445. // We saw a non-dot and non-path separator before our dot, so we should
  87446. // have a good chance at having a non-empty extension
  87447. preDotState = -1;
  87448. }
  87449. }
  87450. if (startDot === -1 || end === -1 ||
  87451. // We saw a non-dot character immediately before the dot
  87452. preDotState === 0 ||
  87453. // The (right-most) trimmed path component is exactly '..'
  87454. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  87455. if (end !== -1) {
  87456. if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);
  87457. }
  87458. } else {
  87459. if (startPart === 0 && isAbsolute) {
  87460. ret.name = path.slice(1, startDot);
  87461. ret.base = path.slice(1, end);
  87462. } else {
  87463. ret.name = path.slice(startPart, startDot);
  87464. ret.base = path.slice(startPart, end);
  87465. }
  87466. ret.ext = path.slice(startDot, end);
  87467. }
  87468. if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';
  87469. return ret;
  87470. },
  87471. sep: '/',
  87472. delimiter: ':',
  87473. win32: null,
  87474. posix: null
  87475. };
  87476. posix.posix = posix;
  87477. module.exports = posix;
  87478. }).call(this)}).call(this,require('_process'))
  87479. },{"_process":525}],518:[function(require,module,exports){
  87480. exports.pbkdf2 = require('./lib/async')
  87481. exports.pbkdf2Sync = require('./lib/sync')
  87482. },{"./lib/async":519,"./lib/sync":522}],519:[function(require,module,exports){
  87483. (function (process,global){(function (){
  87484. var Buffer = require('safe-buffer').Buffer
  87485. var checkParameters = require('./precondition')
  87486. var defaultEncoding = require('./default-encoding')
  87487. var sync = require('./sync')
  87488. var toBuffer = require('./to-buffer')
  87489. var ZERO_BUF
  87490. var subtle = global.crypto && global.crypto.subtle
  87491. var toBrowser = {
  87492. sha: 'SHA-1',
  87493. 'sha-1': 'SHA-1',
  87494. sha1: 'SHA-1',
  87495. sha256: 'SHA-256',
  87496. 'sha-256': 'SHA-256',
  87497. sha384: 'SHA-384',
  87498. 'sha-384': 'SHA-384',
  87499. 'sha-512': 'SHA-512',
  87500. sha512: 'SHA-512'
  87501. }
  87502. var checks = []
  87503. function checkNative (algo) {
  87504. if (global.process && !global.process.browser) {
  87505. return Promise.resolve(false)
  87506. }
  87507. if (!subtle || !subtle.importKey || !subtle.deriveBits) {
  87508. return Promise.resolve(false)
  87509. }
  87510. if (checks[algo] !== undefined) {
  87511. return checks[algo]
  87512. }
  87513. ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
  87514. var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
  87515. .then(function () {
  87516. return true
  87517. }).catch(function () {
  87518. return false
  87519. })
  87520. checks[algo] = prom
  87521. return prom
  87522. }
  87523. function browserPbkdf2 (password, salt, iterations, length, algo) {
  87524. return subtle.importKey(
  87525. 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits']
  87526. ).then(function (key) {
  87527. return subtle.deriveBits({
  87528. name: 'PBKDF2',
  87529. salt: salt,
  87530. iterations: iterations,
  87531. hash: {
  87532. name: algo
  87533. }
  87534. }, key, length << 3)
  87535. }).then(function (res) {
  87536. return Buffer.from(res)
  87537. })
  87538. }
  87539. function resolvePromise (promise, callback) {
  87540. promise.then(function (out) {
  87541. process.nextTick(function () {
  87542. callback(null, out)
  87543. })
  87544. }, function (e) {
  87545. process.nextTick(function () {
  87546. callback(e)
  87547. })
  87548. })
  87549. }
  87550. module.exports = function (password, salt, iterations, keylen, digest, callback) {
  87551. if (typeof digest === 'function') {
  87552. callback = digest
  87553. digest = undefined
  87554. }
  87555. digest = digest || 'sha1'
  87556. var algo = toBrowser[digest.toLowerCase()]
  87557. if (!algo || typeof global.Promise !== 'function') {
  87558. return process.nextTick(function () {
  87559. var out
  87560. try {
  87561. out = sync(password, salt, iterations, keylen, digest)
  87562. } catch (e) {
  87563. return callback(e)
  87564. }
  87565. callback(null, out)
  87566. })
  87567. }
  87568. checkParameters(iterations, keylen)
  87569. password = toBuffer(password, defaultEncoding, 'Password')
  87570. salt = toBuffer(salt, defaultEncoding, 'Salt')
  87571. if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
  87572. resolvePromise(checkNative(algo).then(function (resp) {
  87573. if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)
  87574. return sync(password, salt, iterations, keylen, digest)
  87575. }), callback)
  87576. }
  87577. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  87578. },{"./default-encoding":520,"./precondition":521,"./sync":522,"./to-buffer":523,"_process":525,"safe-buffer":561}],520:[function(require,module,exports){
  87579. (function (process){(function (){
  87580. var defaultEncoding
  87581. /* istanbul ignore next */
  87582. if (process.browser) {
  87583. defaultEncoding = 'utf-8'
  87584. } else if (process.version) {
  87585. var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
  87586. defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
  87587. } else {
  87588. defaultEncoding = 'utf-8'
  87589. }
  87590. module.exports = defaultEncoding
  87591. }).call(this)}).call(this,require('_process'))
  87592. },{"_process":525}],521:[function(require,module,exports){
  87593. var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
  87594. module.exports = function (iterations, keylen) {
  87595. if (typeof iterations !== 'number') {
  87596. throw new TypeError('Iterations not a number')
  87597. }
  87598. if (iterations < 0) {
  87599. throw new TypeError('Bad iterations')
  87600. }
  87601. if (typeof keylen !== 'number') {
  87602. throw new TypeError('Key length not a number')
  87603. }
  87604. if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
  87605. throw new TypeError('Bad key length')
  87606. }
  87607. }
  87608. },{}],522:[function(require,module,exports){
  87609. var md5 = require('create-hash/md5')
  87610. var RIPEMD160 = require('ripemd160')
  87611. var sha = require('sha.js')
  87612. var Buffer = require('safe-buffer').Buffer
  87613. var checkParameters = require('./precondition')
  87614. var defaultEncoding = require('./default-encoding')
  87615. var toBuffer = require('./to-buffer')
  87616. var ZEROS = Buffer.alloc(128)
  87617. var sizes = {
  87618. md5: 16,
  87619. sha1: 20,
  87620. sha224: 28,
  87621. sha256: 32,
  87622. sha384: 48,
  87623. sha512: 64,
  87624. rmd160: 20,
  87625. ripemd160: 20
  87626. }
  87627. function Hmac (alg, key, saltLen) {
  87628. var hash = getDigest(alg)
  87629. var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
  87630. if (key.length > blocksize) {
  87631. key = hash(key)
  87632. } else if (key.length < blocksize) {
  87633. key = Buffer.concat([key, ZEROS], blocksize)
  87634. }
  87635. var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
  87636. var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
  87637. for (var i = 0; i < blocksize; i++) {
  87638. ipad[i] = key[i] ^ 0x36
  87639. opad[i] = key[i] ^ 0x5C
  87640. }
  87641. var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
  87642. ipad.copy(ipad1, 0, 0, blocksize)
  87643. this.ipad1 = ipad1
  87644. this.ipad2 = ipad
  87645. this.opad = opad
  87646. this.alg = alg
  87647. this.blocksize = blocksize
  87648. this.hash = hash
  87649. this.size = sizes[alg]
  87650. }
  87651. Hmac.prototype.run = function (data, ipad) {
  87652. data.copy(ipad, this.blocksize)
  87653. var h = this.hash(ipad)
  87654. h.copy(this.opad, this.blocksize)
  87655. return this.hash(this.opad)
  87656. }
  87657. function getDigest (alg) {
  87658. function shaFunc (data) {
  87659. return sha(alg).update(data).digest()
  87660. }
  87661. function rmd160Func (data) {
  87662. return new RIPEMD160().update(data).digest()
  87663. }
  87664. if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
  87665. if (alg === 'md5') return md5
  87666. return shaFunc
  87667. }
  87668. function pbkdf2 (password, salt, iterations, keylen, digest) {
  87669. checkParameters(iterations, keylen)
  87670. password = toBuffer(password, defaultEncoding, 'Password')
  87671. salt = toBuffer(salt, defaultEncoding, 'Salt')
  87672. digest = digest || 'sha1'
  87673. var hmac = new Hmac(digest, password, salt.length)
  87674. var DK = Buffer.allocUnsafe(keylen)
  87675. var block1 = Buffer.allocUnsafe(salt.length + 4)
  87676. salt.copy(block1, 0, 0, salt.length)
  87677. var destPos = 0
  87678. var hLen = sizes[digest]
  87679. var l = Math.ceil(keylen / hLen)
  87680. for (var i = 1; i <= l; i++) {
  87681. block1.writeUInt32BE(i, salt.length)
  87682. var T = hmac.run(block1, hmac.ipad1)
  87683. var U = T
  87684. for (var j = 1; j < iterations; j++) {
  87685. U = hmac.run(U, hmac.ipad2)
  87686. for (var k = 0; k < hLen; k++) T[k] ^= U[k]
  87687. }
  87688. T.copy(DK, destPos)
  87689. destPos += hLen
  87690. }
  87691. return DK
  87692. }
  87693. module.exports = pbkdf2
  87694. },{"./default-encoding":520,"./precondition":521,"./to-buffer":523,"create-hash/md5":205,"ripemd160":560,"safe-buffer":561,"sha.js":565}],523:[function(require,module,exports){
  87695. var Buffer = require('safe-buffer').Buffer
  87696. module.exports = function (thing, encoding, name) {
  87697. if (Buffer.isBuffer(thing)) {
  87698. return thing
  87699. } else if (typeof thing === 'string') {
  87700. return Buffer.from(thing, encoding)
  87701. } else if (ArrayBuffer.isView(thing)) {
  87702. return Buffer.from(thing.buffer)
  87703. } else {
  87704. throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
  87705. }
  87706. }
  87707. },{"safe-buffer":561}],524:[function(require,module,exports){
  87708. (function (process){(function (){
  87709. // Generated by CoffeeScript 1.12.2
  87710. (function() {
  87711. var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
  87712. if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
  87713. module.exports = function() {
  87714. return performance.now();
  87715. };
  87716. } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
  87717. module.exports = function() {
  87718. return (getNanoSeconds() - nodeLoadTime) / 1e6;
  87719. };
  87720. hrtime = process.hrtime;
  87721. getNanoSeconds = function() {
  87722. var hr;
  87723. hr = hrtime();
  87724. return hr[0] * 1e9 + hr[1];
  87725. };
  87726. moduleLoadTime = getNanoSeconds();
  87727. upTime = process.uptime() * 1e9;
  87728. nodeLoadTime = moduleLoadTime - upTime;
  87729. } else if (Date.now) {
  87730. module.exports = function() {
  87731. return Date.now() - loadTime;
  87732. };
  87733. loadTime = Date.now();
  87734. } else {
  87735. module.exports = function() {
  87736. return new Date().getTime() - loadTime;
  87737. };
  87738. loadTime = new Date().getTime();
  87739. }
  87740. }).call(this);
  87741. }).call(this)}).call(this,require('_process'))
  87742. },{"_process":525}],525:[function(require,module,exports){
  87743. // shim for using process in browser
  87744. var process = module.exports = {};
  87745. // cached from whatever global is present so that test runners that stub it
  87746. // don't break things. But we need to wrap it in a try catch in case it is
  87747. // wrapped in strict mode code which doesn't define any globals. It's inside a
  87748. // function because try/catches deoptimize in certain engines.
  87749. var cachedSetTimeout;
  87750. var cachedClearTimeout;
  87751. function defaultSetTimout() {
  87752. throw new Error('setTimeout has not been defined');
  87753. }
  87754. function defaultClearTimeout () {
  87755. throw new Error('clearTimeout has not been defined');
  87756. }
  87757. (function () {
  87758. try {
  87759. if (typeof setTimeout === 'function') {
  87760. cachedSetTimeout = setTimeout;
  87761. } else {
  87762. cachedSetTimeout = defaultSetTimout;
  87763. }
  87764. } catch (e) {
  87765. cachedSetTimeout = defaultSetTimout;
  87766. }
  87767. try {
  87768. if (typeof clearTimeout === 'function') {
  87769. cachedClearTimeout = clearTimeout;
  87770. } else {
  87771. cachedClearTimeout = defaultClearTimeout;
  87772. }
  87773. } catch (e) {
  87774. cachedClearTimeout = defaultClearTimeout;
  87775. }
  87776. } ())
  87777. function runTimeout(fun) {
  87778. if (cachedSetTimeout === setTimeout) {
  87779. //normal enviroments in sane situations
  87780. return setTimeout(fun, 0);
  87781. }
  87782. // if setTimeout wasn't available but was latter defined
  87783. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  87784. cachedSetTimeout = setTimeout;
  87785. return setTimeout(fun, 0);
  87786. }
  87787. try {
  87788. // when when somebody has screwed with setTimeout but no I.E. maddness
  87789. return cachedSetTimeout(fun, 0);
  87790. } catch(e){
  87791. try {
  87792. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  87793. return cachedSetTimeout.call(null, fun, 0);
  87794. } catch(e){
  87795. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  87796. return cachedSetTimeout.call(this, fun, 0);
  87797. }
  87798. }
  87799. }
  87800. function runClearTimeout(marker) {
  87801. if (cachedClearTimeout === clearTimeout) {
  87802. //normal enviroments in sane situations
  87803. return clearTimeout(marker);
  87804. }
  87805. // if clearTimeout wasn't available but was latter defined
  87806. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  87807. cachedClearTimeout = clearTimeout;
  87808. return clearTimeout(marker);
  87809. }
  87810. try {
  87811. // when when somebody has screwed with setTimeout but no I.E. maddness
  87812. return cachedClearTimeout(marker);
  87813. } catch (e){
  87814. try {
  87815. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  87816. return cachedClearTimeout.call(null, marker);
  87817. } catch (e){
  87818. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  87819. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  87820. return cachedClearTimeout.call(this, marker);
  87821. }
  87822. }
  87823. }
  87824. var queue = [];
  87825. var draining = false;
  87826. var currentQueue;
  87827. var queueIndex = -1;
  87828. function cleanUpNextTick() {
  87829. if (!draining || !currentQueue) {
  87830. return;
  87831. }
  87832. draining = false;
  87833. if (currentQueue.length) {
  87834. queue = currentQueue.concat(queue);
  87835. } else {
  87836. queueIndex = -1;
  87837. }
  87838. if (queue.length) {
  87839. drainQueue();
  87840. }
  87841. }
  87842. function drainQueue() {
  87843. if (draining) {
  87844. return;
  87845. }
  87846. var timeout = runTimeout(cleanUpNextTick);
  87847. draining = true;
  87848. var len = queue.length;
  87849. while(len) {
  87850. currentQueue = queue;
  87851. queue = [];
  87852. while (++queueIndex < len) {
  87853. if (currentQueue) {
  87854. currentQueue[queueIndex].run();
  87855. }
  87856. }
  87857. queueIndex = -1;
  87858. len = queue.length;
  87859. }
  87860. currentQueue = null;
  87861. draining = false;
  87862. runClearTimeout(timeout);
  87863. }
  87864. process.nextTick = function (fun) {
  87865. var args = new Array(arguments.length - 1);
  87866. if (arguments.length > 1) {
  87867. for (var i = 1; i < arguments.length; i++) {
  87868. args[i - 1] = arguments[i];
  87869. }
  87870. }
  87871. queue.push(new Item(fun, args));
  87872. if (queue.length === 1 && !draining) {
  87873. runTimeout(drainQueue);
  87874. }
  87875. };
  87876. // v8 likes predictible objects
  87877. function Item(fun, array) {
  87878. this.fun = fun;
  87879. this.array = array;
  87880. }
  87881. Item.prototype.run = function () {
  87882. this.fun.apply(null, this.array);
  87883. };
  87884. process.title = 'browser';
  87885. process.browser = true;
  87886. process.env = {};
  87887. process.argv = [];
  87888. process.version = ''; // empty string to avoid regexp issues
  87889. process.versions = {};
  87890. function noop() {}
  87891. process.on = noop;
  87892. process.addListener = noop;
  87893. process.once = noop;
  87894. process.off = noop;
  87895. process.removeListener = noop;
  87896. process.removeAllListeners = noop;
  87897. process.emit = noop;
  87898. process.prependListener = noop;
  87899. process.prependOnceListener = noop;
  87900. process.listeners = function (name) { return [] }
  87901. process.binding = function (name) {
  87902. throw new Error('process.binding is not supported');
  87903. };
  87904. process.cwd = function () { return '/' };
  87905. process.chdir = function (dir) {
  87906. throw new Error('process.chdir is not supported');
  87907. };
  87908. process.umask = function() { return 0; };
  87909. },{}],526:[function(require,module,exports){
  87910. module.exports=[
  87911. "ac",
  87912. "com.ac",
  87913. "edu.ac",
  87914. "gov.ac",
  87915. "net.ac",
  87916. "mil.ac",
  87917. "org.ac",
  87918. "ad",
  87919. "nom.ad",
  87920. "ae",
  87921. "co.ae",
  87922. "net.ae",
  87923. "org.ae",
  87924. "sch.ae",
  87925. "ac.ae",
  87926. "gov.ae",
  87927. "mil.ae",
  87928. "aero",
  87929. "accident-investigation.aero",
  87930. "accident-prevention.aero",
  87931. "aerobatic.aero",
  87932. "aeroclub.aero",
  87933. "aerodrome.aero",
  87934. "agents.aero",
  87935. "aircraft.aero",
  87936. "airline.aero",
  87937. "airport.aero",
  87938. "air-surveillance.aero",
  87939. "airtraffic.aero",
  87940. "air-traffic-control.aero",
  87941. "ambulance.aero",
  87942. "amusement.aero",
  87943. "association.aero",
  87944. "author.aero",
  87945. "ballooning.aero",
  87946. "broker.aero",
  87947. "caa.aero",
  87948. "cargo.aero",
  87949. "catering.aero",
  87950. "certification.aero",
  87951. "championship.aero",
  87952. "charter.aero",
  87953. "civilaviation.aero",
  87954. "club.aero",
  87955. "conference.aero",
  87956. "consultant.aero",
  87957. "consulting.aero",
  87958. "control.aero",
  87959. "council.aero",
  87960. "crew.aero",
  87961. "design.aero",
  87962. "dgca.aero",
  87963. "educator.aero",
  87964. "emergency.aero",
  87965. "engine.aero",
  87966. "engineer.aero",
  87967. "entertainment.aero",
  87968. "equipment.aero",
  87969. "exchange.aero",
  87970. "express.aero",
  87971. "federation.aero",
  87972. "flight.aero",
  87973. "freight.aero",
  87974. "fuel.aero",
  87975. "gliding.aero",
  87976. "government.aero",
  87977. "groundhandling.aero",
  87978. "group.aero",
  87979. "hanggliding.aero",
  87980. "homebuilt.aero",
  87981. "insurance.aero",
  87982. "journal.aero",
  87983. "journalist.aero",
  87984. "leasing.aero",
  87985. "logistics.aero",
  87986. "magazine.aero",
  87987. "maintenance.aero",
  87988. "media.aero",
  87989. "microlight.aero",
  87990. "modelling.aero",
  87991. "navigation.aero",
  87992. "parachuting.aero",
  87993. "paragliding.aero",
  87994. "passenger-association.aero",
  87995. "pilot.aero",
  87996. "press.aero",
  87997. "production.aero",
  87998. "recreation.aero",
  87999. "repbody.aero",
  88000. "res.aero",
  88001. "research.aero",
  88002. "rotorcraft.aero",
  88003. "safety.aero",
  88004. "scientist.aero",
  88005. "services.aero",
  88006. "show.aero",
  88007. "skydiving.aero",
  88008. "software.aero",
  88009. "student.aero",
  88010. "trader.aero",
  88011. "trading.aero",
  88012. "trainer.aero",
  88013. "union.aero",
  88014. "workinggroup.aero",
  88015. "works.aero",
  88016. "af",
  88017. "gov.af",
  88018. "com.af",
  88019. "org.af",
  88020. "net.af",
  88021. "edu.af",
  88022. "ag",
  88023. "com.ag",
  88024. "org.ag",
  88025. "net.ag",
  88026. "co.ag",
  88027. "nom.ag",
  88028. "ai",
  88029. "off.ai",
  88030. "com.ai",
  88031. "net.ai",
  88032. "org.ai",
  88033. "al",
  88034. "com.al",
  88035. "edu.al",
  88036. "gov.al",
  88037. "mil.al",
  88038. "net.al",
  88039. "org.al",
  88040. "am",
  88041. "co.am",
  88042. "com.am",
  88043. "commune.am",
  88044. "net.am",
  88045. "org.am",
  88046. "ao",
  88047. "ed.ao",
  88048. "gv.ao",
  88049. "og.ao",
  88050. "co.ao",
  88051. "pb.ao",
  88052. "it.ao",
  88053. "aq",
  88054. "ar",
  88055. "com.ar",
  88056. "edu.ar",
  88057. "gob.ar",
  88058. "gov.ar",
  88059. "int.ar",
  88060. "mil.ar",
  88061. "musica.ar",
  88062. "net.ar",
  88063. "org.ar",
  88064. "tur.ar",
  88065. "arpa",
  88066. "e164.arpa",
  88067. "in-addr.arpa",
  88068. "ip6.arpa",
  88069. "iris.arpa",
  88070. "uri.arpa",
  88071. "urn.arpa",
  88072. "as",
  88073. "gov.as",
  88074. "asia",
  88075. "at",
  88076. "ac.at",
  88077. "co.at",
  88078. "gv.at",
  88079. "or.at",
  88080. "au",
  88081. "com.au",
  88082. "net.au",
  88083. "org.au",
  88084. "edu.au",
  88085. "gov.au",
  88086. "asn.au",
  88087. "id.au",
  88088. "info.au",
  88089. "conf.au",
  88090. "oz.au",
  88091. "act.au",
  88092. "nsw.au",
  88093. "nt.au",
  88094. "qld.au",
  88095. "sa.au",
  88096. "tas.au",
  88097. "vic.au",
  88098. "wa.au",
  88099. "act.edu.au",
  88100. "catholic.edu.au",
  88101. "nsw.edu.au",
  88102. "nt.edu.au",
  88103. "qld.edu.au",
  88104. "sa.edu.au",
  88105. "tas.edu.au",
  88106. "vic.edu.au",
  88107. "wa.edu.au",
  88108. "qld.gov.au",
  88109. "sa.gov.au",
  88110. "tas.gov.au",
  88111. "vic.gov.au",
  88112. "wa.gov.au",
  88113. "education.tas.edu.au",
  88114. "schools.nsw.edu.au",
  88115. "aw",
  88116. "com.aw",
  88117. "ax",
  88118. "az",
  88119. "com.az",
  88120. "net.az",
  88121. "int.az",
  88122. "gov.az",
  88123. "org.az",
  88124. "edu.az",
  88125. "info.az",
  88126. "pp.az",
  88127. "mil.az",
  88128. "name.az",
  88129. "pro.az",
  88130. "biz.az",
  88131. "ba",
  88132. "com.ba",
  88133. "edu.ba",
  88134. "gov.ba",
  88135. "mil.ba",
  88136. "net.ba",
  88137. "org.ba",
  88138. "bb",
  88139. "biz.bb",
  88140. "co.bb",
  88141. "com.bb",
  88142. "edu.bb",
  88143. "gov.bb",
  88144. "info.bb",
  88145. "net.bb",
  88146. "org.bb",
  88147. "store.bb",
  88148. "tv.bb",
  88149. "*.bd",
  88150. "be",
  88151. "ac.be",
  88152. "bf",
  88153. "gov.bf",
  88154. "bg",
  88155. "a.bg",
  88156. "b.bg",
  88157. "c.bg",
  88158. "d.bg",
  88159. "e.bg",
  88160. "f.bg",
  88161. "g.bg",
  88162. "h.bg",
  88163. "i.bg",
  88164. "j.bg",
  88165. "k.bg",
  88166. "l.bg",
  88167. "m.bg",
  88168. "n.bg",
  88169. "o.bg",
  88170. "p.bg",
  88171. "q.bg",
  88172. "r.bg",
  88173. "s.bg",
  88174. "t.bg",
  88175. "u.bg",
  88176. "v.bg",
  88177. "w.bg",
  88178. "x.bg",
  88179. "y.bg",
  88180. "z.bg",
  88181. "0.bg",
  88182. "1.bg",
  88183. "2.bg",
  88184. "3.bg",
  88185. "4.bg",
  88186. "5.bg",
  88187. "6.bg",
  88188. "7.bg",
  88189. "8.bg",
  88190. "9.bg",
  88191. "bh",
  88192. "com.bh",
  88193. "edu.bh",
  88194. "net.bh",
  88195. "org.bh",
  88196. "gov.bh",
  88197. "bi",
  88198. "co.bi",
  88199. "com.bi",
  88200. "edu.bi",
  88201. "or.bi",
  88202. "org.bi",
  88203. "biz",
  88204. "bj",
  88205. "asso.bj",
  88206. "barreau.bj",
  88207. "gouv.bj",
  88208. "bm",
  88209. "com.bm",
  88210. "edu.bm",
  88211. "gov.bm",
  88212. "net.bm",
  88213. "org.bm",
  88214. "bn",
  88215. "com.bn",
  88216. "edu.bn",
  88217. "gov.bn",
  88218. "net.bn",
  88219. "org.bn",
  88220. "bo",
  88221. "com.bo",
  88222. "edu.bo",
  88223. "gob.bo",
  88224. "int.bo",
  88225. "org.bo",
  88226. "net.bo",
  88227. "mil.bo",
  88228. "tv.bo",
  88229. "web.bo",
  88230. "academia.bo",
  88231. "agro.bo",
  88232. "arte.bo",
  88233. "blog.bo",
  88234. "bolivia.bo",
  88235. "ciencia.bo",
  88236. "cooperativa.bo",
  88237. "democracia.bo",
  88238. "deporte.bo",
  88239. "ecologia.bo",
  88240. "economia.bo",
  88241. "empresa.bo",
  88242. "indigena.bo",
  88243. "industria.bo",
  88244. "info.bo",
  88245. "medicina.bo",
  88246. "movimiento.bo",
  88247. "musica.bo",
  88248. "natural.bo",
  88249. "nombre.bo",
  88250. "noticias.bo",
  88251. "patria.bo",
  88252. "politica.bo",
  88253. "profesional.bo",
  88254. "plurinacional.bo",
  88255. "pueblo.bo",
  88256. "revista.bo",
  88257. "salud.bo",
  88258. "tecnologia.bo",
  88259. "tksat.bo",
  88260. "transporte.bo",
  88261. "wiki.bo",
  88262. "br",
  88263. "9guacu.br",
  88264. "abc.br",
  88265. "adm.br",
  88266. "adv.br",
  88267. "agr.br",
  88268. "aju.br",
  88269. "am.br",
  88270. "anani.br",
  88271. "aparecida.br",
  88272. "arq.br",
  88273. "art.br",
  88274. "ato.br",
  88275. "b.br",
  88276. "barueri.br",
  88277. "belem.br",
  88278. "bhz.br",
  88279. "bio.br",
  88280. "blog.br",
  88281. "bmd.br",
  88282. "boavista.br",
  88283. "bsb.br",
  88284. "campinagrande.br",
  88285. "campinas.br",
  88286. "caxias.br",
  88287. "cim.br",
  88288. "cng.br",
  88289. "cnt.br",
  88290. "com.br",
  88291. "contagem.br",
  88292. "coop.br",
  88293. "cri.br",
  88294. "cuiaba.br",
  88295. "curitiba.br",
  88296. "def.br",
  88297. "ecn.br",
  88298. "eco.br",
  88299. "edu.br",
  88300. "emp.br",
  88301. "eng.br",
  88302. "esp.br",
  88303. "etc.br",
  88304. "eti.br",
  88305. "far.br",
  88306. "feira.br",
  88307. "flog.br",
  88308. "floripa.br",
  88309. "fm.br",
  88310. "fnd.br",
  88311. "fortal.br",
  88312. "fot.br",
  88313. "foz.br",
  88314. "fst.br",
  88315. "g12.br",
  88316. "ggf.br",
  88317. "goiania.br",
  88318. "gov.br",
  88319. "ac.gov.br",
  88320. "al.gov.br",
  88321. "am.gov.br",
  88322. "ap.gov.br",
  88323. "ba.gov.br",
  88324. "ce.gov.br",
  88325. "df.gov.br",
  88326. "es.gov.br",
  88327. "go.gov.br",
  88328. "ma.gov.br",
  88329. "mg.gov.br",
  88330. "ms.gov.br",
  88331. "mt.gov.br",
  88332. "pa.gov.br",
  88333. "pb.gov.br",
  88334. "pe.gov.br",
  88335. "pi.gov.br",
  88336. "pr.gov.br",
  88337. "rj.gov.br",
  88338. "rn.gov.br",
  88339. "ro.gov.br",
  88340. "rr.gov.br",
  88341. "rs.gov.br",
  88342. "sc.gov.br",
  88343. "se.gov.br",
  88344. "sp.gov.br",
  88345. "to.gov.br",
  88346. "gru.br",
  88347. "imb.br",
  88348. "ind.br",
  88349. "inf.br",
  88350. "jab.br",
  88351. "jampa.br",
  88352. "jdf.br",
  88353. "joinville.br",
  88354. "jor.br",
  88355. "jus.br",
  88356. "leg.br",
  88357. "lel.br",
  88358. "londrina.br",
  88359. "macapa.br",
  88360. "maceio.br",
  88361. "manaus.br",
  88362. "maringa.br",
  88363. "mat.br",
  88364. "med.br",
  88365. "mil.br",
  88366. "morena.br",
  88367. "mp.br",
  88368. "mus.br",
  88369. "natal.br",
  88370. "net.br",
  88371. "niteroi.br",
  88372. "*.nom.br",
  88373. "not.br",
  88374. "ntr.br",
  88375. "odo.br",
  88376. "ong.br",
  88377. "org.br",
  88378. "osasco.br",
  88379. "palmas.br",
  88380. "poa.br",
  88381. "ppg.br",
  88382. "pro.br",
  88383. "psc.br",
  88384. "psi.br",
  88385. "pvh.br",
  88386. "qsl.br",
  88387. "radio.br",
  88388. "rec.br",
  88389. "recife.br",
  88390. "ribeirao.br",
  88391. "rio.br",
  88392. "riobranco.br",
  88393. "riopreto.br",
  88394. "salvador.br",
  88395. "sampa.br",
  88396. "santamaria.br",
  88397. "santoandre.br",
  88398. "saobernardo.br",
  88399. "saogonca.br",
  88400. "sjc.br",
  88401. "slg.br",
  88402. "slz.br",
  88403. "sorocaba.br",
  88404. "srv.br",
  88405. "taxi.br",
  88406. "tc.br",
  88407. "teo.br",
  88408. "the.br",
  88409. "tmp.br",
  88410. "trd.br",
  88411. "tur.br",
  88412. "tv.br",
  88413. "udi.br",
  88414. "vet.br",
  88415. "vix.br",
  88416. "vlog.br",
  88417. "wiki.br",
  88418. "zlg.br",
  88419. "bs",
  88420. "com.bs",
  88421. "net.bs",
  88422. "org.bs",
  88423. "edu.bs",
  88424. "gov.bs",
  88425. "bt",
  88426. "com.bt",
  88427. "edu.bt",
  88428. "gov.bt",
  88429. "net.bt",
  88430. "org.bt",
  88431. "bv",
  88432. "bw",
  88433. "co.bw",
  88434. "org.bw",
  88435. "by",
  88436. "gov.by",
  88437. "mil.by",
  88438. "com.by",
  88439. "of.by",
  88440. "bz",
  88441. "com.bz",
  88442. "net.bz",
  88443. "org.bz",
  88444. "edu.bz",
  88445. "gov.bz",
  88446. "ca",
  88447. "ab.ca",
  88448. "bc.ca",
  88449. "mb.ca",
  88450. "nb.ca",
  88451. "nf.ca",
  88452. "nl.ca",
  88453. "ns.ca",
  88454. "nt.ca",
  88455. "nu.ca",
  88456. "on.ca",
  88457. "pe.ca",
  88458. "qc.ca",
  88459. "sk.ca",
  88460. "yk.ca",
  88461. "gc.ca",
  88462. "cat",
  88463. "cc",
  88464. "cd",
  88465. "gov.cd",
  88466. "cf",
  88467. "cg",
  88468. "ch",
  88469. "ci",
  88470. "org.ci",
  88471. "or.ci",
  88472. "com.ci",
  88473. "co.ci",
  88474. "edu.ci",
  88475. "ed.ci",
  88476. "ac.ci",
  88477. "net.ci",
  88478. "go.ci",
  88479. "asso.ci",
  88480. "aéroport.ci",
  88481. "int.ci",
  88482. "presse.ci",
  88483. "md.ci",
  88484. "gouv.ci",
  88485. "*.ck",
  88486. "!www.ck",
  88487. "cl",
  88488. "aprendemas.cl",
  88489. "co.cl",
  88490. "gob.cl",
  88491. "gov.cl",
  88492. "mil.cl",
  88493. "cm",
  88494. "co.cm",
  88495. "com.cm",
  88496. "gov.cm",
  88497. "net.cm",
  88498. "cn",
  88499. "ac.cn",
  88500. "com.cn",
  88501. "edu.cn",
  88502. "gov.cn",
  88503. "net.cn",
  88504. "org.cn",
  88505. "mil.cn",
  88506. "公司.cn",
  88507. "网络.cn",
  88508. "網絡.cn",
  88509. "ah.cn",
  88510. "bj.cn",
  88511. "cq.cn",
  88512. "fj.cn",
  88513. "gd.cn",
  88514. "gs.cn",
  88515. "gz.cn",
  88516. "gx.cn",
  88517. "ha.cn",
  88518. "hb.cn",
  88519. "he.cn",
  88520. "hi.cn",
  88521. "hl.cn",
  88522. "hn.cn",
  88523. "jl.cn",
  88524. "js.cn",
  88525. "jx.cn",
  88526. "ln.cn",
  88527. "nm.cn",
  88528. "nx.cn",
  88529. "qh.cn",
  88530. "sc.cn",
  88531. "sd.cn",
  88532. "sh.cn",
  88533. "sn.cn",
  88534. "sx.cn",
  88535. "tj.cn",
  88536. "xj.cn",
  88537. "xz.cn",
  88538. "yn.cn",
  88539. "zj.cn",
  88540. "hk.cn",
  88541. "mo.cn",
  88542. "tw.cn",
  88543. "co",
  88544. "arts.co",
  88545. "com.co",
  88546. "edu.co",
  88547. "firm.co",
  88548. "gov.co",
  88549. "info.co",
  88550. "int.co",
  88551. "mil.co",
  88552. "net.co",
  88553. "nom.co",
  88554. "org.co",
  88555. "rec.co",
  88556. "web.co",
  88557. "com",
  88558. "coop",
  88559. "cr",
  88560. "ac.cr",
  88561. "co.cr",
  88562. "ed.cr",
  88563. "fi.cr",
  88564. "go.cr",
  88565. "or.cr",
  88566. "sa.cr",
  88567. "cu",
  88568. "com.cu",
  88569. "edu.cu",
  88570. "org.cu",
  88571. "net.cu",
  88572. "gov.cu",
  88573. "inf.cu",
  88574. "cv",
  88575. "cw",
  88576. "com.cw",
  88577. "edu.cw",
  88578. "net.cw",
  88579. "org.cw",
  88580. "cx",
  88581. "gov.cx",
  88582. "cy",
  88583. "ac.cy",
  88584. "biz.cy",
  88585. "com.cy",
  88586. "ekloges.cy",
  88587. "gov.cy",
  88588. "ltd.cy",
  88589. "name.cy",
  88590. "net.cy",
  88591. "org.cy",
  88592. "parliament.cy",
  88593. "press.cy",
  88594. "pro.cy",
  88595. "tm.cy",
  88596. "cz",
  88597. "de",
  88598. "dj",
  88599. "dk",
  88600. "dm",
  88601. "com.dm",
  88602. "net.dm",
  88603. "org.dm",
  88604. "edu.dm",
  88605. "gov.dm",
  88606. "do",
  88607. "art.do",
  88608. "com.do",
  88609. "edu.do",
  88610. "gob.do",
  88611. "gov.do",
  88612. "mil.do",
  88613. "net.do",
  88614. "org.do",
  88615. "sld.do",
  88616. "web.do",
  88617. "dz",
  88618. "com.dz",
  88619. "org.dz",
  88620. "net.dz",
  88621. "gov.dz",
  88622. "edu.dz",
  88623. "asso.dz",
  88624. "pol.dz",
  88625. "art.dz",
  88626. "ec",
  88627. "com.ec",
  88628. "info.ec",
  88629. "net.ec",
  88630. "fin.ec",
  88631. "k12.ec",
  88632. "med.ec",
  88633. "pro.ec",
  88634. "org.ec",
  88635. "edu.ec",
  88636. "gov.ec",
  88637. "gob.ec",
  88638. "mil.ec",
  88639. "edu",
  88640. "ee",
  88641. "edu.ee",
  88642. "gov.ee",
  88643. "riik.ee",
  88644. "lib.ee",
  88645. "med.ee",
  88646. "com.ee",
  88647. "pri.ee",
  88648. "aip.ee",
  88649. "org.ee",
  88650. "fie.ee",
  88651. "eg",
  88652. "com.eg",
  88653. "edu.eg",
  88654. "eun.eg",
  88655. "gov.eg",
  88656. "mil.eg",
  88657. "name.eg",
  88658. "net.eg",
  88659. "org.eg",
  88660. "sci.eg",
  88661. "*.er",
  88662. "es",
  88663. "com.es",
  88664. "nom.es",
  88665. "org.es",
  88666. "gob.es",
  88667. "edu.es",
  88668. "et",
  88669. "com.et",
  88670. "gov.et",
  88671. "org.et",
  88672. "edu.et",
  88673. "biz.et",
  88674. "name.et",
  88675. "info.et",
  88676. "net.et",
  88677. "eu",
  88678. "fi",
  88679. "aland.fi",
  88680. "fj",
  88681. "ac.fj",
  88682. "biz.fj",
  88683. "com.fj",
  88684. "gov.fj",
  88685. "info.fj",
  88686. "mil.fj",
  88687. "name.fj",
  88688. "net.fj",
  88689. "org.fj",
  88690. "pro.fj",
  88691. "*.fk",
  88692. "fm",
  88693. "fo",
  88694. "fr",
  88695. "asso.fr",
  88696. "com.fr",
  88697. "gouv.fr",
  88698. "nom.fr",
  88699. "prd.fr",
  88700. "tm.fr",
  88701. "aeroport.fr",
  88702. "avocat.fr",
  88703. "avoues.fr",
  88704. "cci.fr",
  88705. "chambagri.fr",
  88706. "chirurgiens-dentistes.fr",
  88707. "experts-comptables.fr",
  88708. "geometre-expert.fr",
  88709. "greta.fr",
  88710. "huissier-justice.fr",
  88711. "medecin.fr",
  88712. "notaires.fr",
  88713. "pharmacien.fr",
  88714. "port.fr",
  88715. "veterinaire.fr",
  88716. "ga",
  88717. "gb",
  88718. "gd",
  88719. "ge",
  88720. "com.ge",
  88721. "edu.ge",
  88722. "gov.ge",
  88723. "org.ge",
  88724. "mil.ge",
  88725. "net.ge",
  88726. "pvt.ge",
  88727. "gf",
  88728. "gg",
  88729. "co.gg",
  88730. "net.gg",
  88731. "org.gg",
  88732. "gh",
  88733. "com.gh",
  88734. "edu.gh",
  88735. "gov.gh",
  88736. "org.gh",
  88737. "mil.gh",
  88738. "gi",
  88739. "com.gi",
  88740. "ltd.gi",
  88741. "gov.gi",
  88742. "mod.gi",
  88743. "edu.gi",
  88744. "org.gi",
  88745. "gl",
  88746. "co.gl",
  88747. "com.gl",
  88748. "edu.gl",
  88749. "net.gl",
  88750. "org.gl",
  88751. "gm",
  88752. "gn",
  88753. "ac.gn",
  88754. "com.gn",
  88755. "edu.gn",
  88756. "gov.gn",
  88757. "org.gn",
  88758. "net.gn",
  88759. "gov",
  88760. "gp",
  88761. "com.gp",
  88762. "net.gp",
  88763. "mobi.gp",
  88764. "edu.gp",
  88765. "org.gp",
  88766. "asso.gp",
  88767. "gq",
  88768. "gr",
  88769. "com.gr",
  88770. "edu.gr",
  88771. "net.gr",
  88772. "org.gr",
  88773. "gov.gr",
  88774. "gs",
  88775. "gt",
  88776. "com.gt",
  88777. "edu.gt",
  88778. "gob.gt",
  88779. "ind.gt",
  88780. "mil.gt",
  88781. "net.gt",
  88782. "org.gt",
  88783. "gu",
  88784. "com.gu",
  88785. "edu.gu",
  88786. "gov.gu",
  88787. "guam.gu",
  88788. "info.gu",
  88789. "net.gu",
  88790. "org.gu",
  88791. "web.gu",
  88792. "gw",
  88793. "gy",
  88794. "co.gy",
  88795. "com.gy",
  88796. "edu.gy",
  88797. "gov.gy",
  88798. "net.gy",
  88799. "org.gy",
  88800. "hk",
  88801. "com.hk",
  88802. "edu.hk",
  88803. "gov.hk",
  88804. "idv.hk",
  88805. "net.hk",
  88806. "org.hk",
  88807. "公司.hk",
  88808. "教育.hk",
  88809. "敎育.hk",
  88810. "政府.hk",
  88811. "個人.hk",
  88812. "个人.hk",
  88813. "箇人.hk",
  88814. "網络.hk",
  88815. "网络.hk",
  88816. "组織.hk",
  88817. "網絡.hk",
  88818. "网絡.hk",
  88819. "组织.hk",
  88820. "組織.hk",
  88821. "組织.hk",
  88822. "hm",
  88823. "hn",
  88824. "com.hn",
  88825. "edu.hn",
  88826. "org.hn",
  88827. "net.hn",
  88828. "mil.hn",
  88829. "gob.hn",
  88830. "hr",
  88831. "iz.hr",
  88832. "from.hr",
  88833. "name.hr",
  88834. "com.hr",
  88835. "ht",
  88836. "com.ht",
  88837. "shop.ht",
  88838. "firm.ht",
  88839. "info.ht",
  88840. "adult.ht",
  88841. "net.ht",
  88842. "pro.ht",
  88843. "org.ht",
  88844. "med.ht",
  88845. "art.ht",
  88846. "coop.ht",
  88847. "pol.ht",
  88848. "asso.ht",
  88849. "edu.ht",
  88850. "rel.ht",
  88851. "gouv.ht",
  88852. "perso.ht",
  88853. "hu",
  88854. "co.hu",
  88855. "info.hu",
  88856. "org.hu",
  88857. "priv.hu",
  88858. "sport.hu",
  88859. "tm.hu",
  88860. "2000.hu",
  88861. "agrar.hu",
  88862. "bolt.hu",
  88863. "casino.hu",
  88864. "city.hu",
  88865. "erotica.hu",
  88866. "erotika.hu",
  88867. "film.hu",
  88868. "forum.hu",
  88869. "games.hu",
  88870. "hotel.hu",
  88871. "ingatlan.hu",
  88872. "jogasz.hu",
  88873. "konyvelo.hu",
  88874. "lakas.hu",
  88875. "media.hu",
  88876. "news.hu",
  88877. "reklam.hu",
  88878. "sex.hu",
  88879. "shop.hu",
  88880. "suli.hu",
  88881. "szex.hu",
  88882. "tozsde.hu",
  88883. "utazas.hu",
  88884. "video.hu",
  88885. "id",
  88886. "ac.id",
  88887. "biz.id",
  88888. "co.id",
  88889. "desa.id",
  88890. "go.id",
  88891. "mil.id",
  88892. "my.id",
  88893. "net.id",
  88894. "or.id",
  88895. "ponpes.id",
  88896. "sch.id",
  88897. "web.id",
  88898. "ie",
  88899. "gov.ie",
  88900. "il",
  88901. "ac.il",
  88902. "co.il",
  88903. "gov.il",
  88904. "idf.il",
  88905. "k12.il",
  88906. "muni.il",
  88907. "net.il",
  88908. "org.il",
  88909. "im",
  88910. "ac.im",
  88911. "co.im",
  88912. "com.im",
  88913. "ltd.co.im",
  88914. "net.im",
  88915. "org.im",
  88916. "plc.co.im",
  88917. "tt.im",
  88918. "tv.im",
  88919. "in",
  88920. "co.in",
  88921. "firm.in",
  88922. "net.in",
  88923. "org.in",
  88924. "gen.in",
  88925. "ind.in",
  88926. "nic.in",
  88927. "ac.in",
  88928. "edu.in",
  88929. "res.in",
  88930. "gov.in",
  88931. "mil.in",
  88932. "info",
  88933. "int",
  88934. "eu.int",
  88935. "io",
  88936. "com.io",
  88937. "iq",
  88938. "gov.iq",
  88939. "edu.iq",
  88940. "mil.iq",
  88941. "com.iq",
  88942. "org.iq",
  88943. "net.iq",
  88944. "ir",
  88945. "ac.ir",
  88946. "co.ir",
  88947. "gov.ir",
  88948. "id.ir",
  88949. "net.ir",
  88950. "org.ir",
  88951. "sch.ir",
  88952. "ایران.ir",
  88953. "ايران.ir",
  88954. "is",
  88955. "net.is",
  88956. "com.is",
  88957. "edu.is",
  88958. "gov.is",
  88959. "org.is",
  88960. "int.is",
  88961. "it",
  88962. "gov.it",
  88963. "edu.it",
  88964. "abr.it",
  88965. "abruzzo.it",
  88966. "aosta-valley.it",
  88967. "aostavalley.it",
  88968. "bas.it",
  88969. "basilicata.it",
  88970. "cal.it",
  88971. "calabria.it",
  88972. "cam.it",
  88973. "campania.it",
  88974. "emilia-romagna.it",
  88975. "emiliaromagna.it",
  88976. "emr.it",
  88977. "friuli-v-giulia.it",
  88978. "friuli-ve-giulia.it",
  88979. "friuli-vegiulia.it",
  88980. "friuli-venezia-giulia.it",
  88981. "friuli-veneziagiulia.it",
  88982. "friuli-vgiulia.it",
  88983. "friuliv-giulia.it",
  88984. "friulive-giulia.it",
  88985. "friulivegiulia.it",
  88986. "friulivenezia-giulia.it",
  88987. "friuliveneziagiulia.it",
  88988. "friulivgiulia.it",
  88989. "fvg.it",
  88990. "laz.it",
  88991. "lazio.it",
  88992. "lig.it",
  88993. "liguria.it",
  88994. "lom.it",
  88995. "lombardia.it",
  88996. "lombardy.it",
  88997. "lucania.it",
  88998. "mar.it",
  88999. "marche.it",
  89000. "mol.it",
  89001. "molise.it",
  89002. "piedmont.it",
  89003. "piemonte.it",
  89004. "pmn.it",
  89005. "pug.it",
  89006. "puglia.it",
  89007. "sar.it",
  89008. "sardegna.it",
  89009. "sardinia.it",
  89010. "sic.it",
  89011. "sicilia.it",
  89012. "sicily.it",
  89013. "taa.it",
  89014. "tos.it",
  89015. "toscana.it",
  89016. "trentin-sud-tirol.it",
  89017. "trentin-süd-tirol.it",
  89018. "trentin-sudtirol.it",
  89019. "trentin-südtirol.it",
  89020. "trentin-sued-tirol.it",
  89021. "trentin-suedtirol.it",
  89022. "trentino-a-adige.it",
  89023. "trentino-aadige.it",
  89024. "trentino-alto-adige.it",
  89025. "trentino-altoadige.it",
  89026. "trentino-s-tirol.it",
  89027. "trentino-stirol.it",
  89028. "trentino-sud-tirol.it",
  89029. "trentino-süd-tirol.it",
  89030. "trentino-sudtirol.it",
  89031. "trentino-südtirol.it",
  89032. "trentino-sued-tirol.it",
  89033. "trentino-suedtirol.it",
  89034. "trentino.it",
  89035. "trentinoa-adige.it",
  89036. "trentinoaadige.it",
  89037. "trentinoalto-adige.it",
  89038. "trentinoaltoadige.it",
  89039. "trentinos-tirol.it",
  89040. "trentinostirol.it",
  89041. "trentinosud-tirol.it",
  89042. "trentinosüd-tirol.it",
  89043. "trentinosudtirol.it",
  89044. "trentinosüdtirol.it",
  89045. "trentinosued-tirol.it",
  89046. "trentinosuedtirol.it",
  89047. "trentinsud-tirol.it",
  89048. "trentinsüd-tirol.it",
  89049. "trentinsudtirol.it",
  89050. "trentinsüdtirol.it",
  89051. "trentinsued-tirol.it",
  89052. "trentinsuedtirol.it",
  89053. "tuscany.it",
  89054. "umb.it",
  89055. "umbria.it",
  89056. "val-d-aosta.it",
  89057. "val-daosta.it",
  89058. "vald-aosta.it",
  89059. "valdaosta.it",
  89060. "valle-aosta.it",
  89061. "valle-d-aosta.it",
  89062. "valle-daosta.it",
  89063. "valleaosta.it",
  89064. "valled-aosta.it",
  89065. "valledaosta.it",
  89066. "vallee-aoste.it",
  89067. "vallée-aoste.it",
  89068. "vallee-d-aoste.it",
  89069. "vallée-d-aoste.it",
  89070. "valleeaoste.it",
  89071. "valléeaoste.it",
  89072. "valleedaoste.it",
  89073. "valléedaoste.it",
  89074. "vao.it",
  89075. "vda.it",
  89076. "ven.it",
  89077. "veneto.it",
  89078. "ag.it",
  89079. "agrigento.it",
  89080. "al.it",
  89081. "alessandria.it",
  89082. "alto-adige.it",
  89083. "altoadige.it",
  89084. "an.it",
  89085. "ancona.it",
  89086. "andria-barletta-trani.it",
  89087. "andria-trani-barletta.it",
  89088. "andriabarlettatrani.it",
  89089. "andriatranibarletta.it",
  89090. "ao.it",
  89091. "aosta.it",
  89092. "aoste.it",
  89093. "ap.it",
  89094. "aq.it",
  89095. "aquila.it",
  89096. "ar.it",
  89097. "arezzo.it",
  89098. "ascoli-piceno.it",
  89099. "ascolipiceno.it",
  89100. "asti.it",
  89101. "at.it",
  89102. "av.it",
  89103. "avellino.it",
  89104. "ba.it",
  89105. "balsan-sudtirol.it",
  89106. "balsan-südtirol.it",
  89107. "balsan-suedtirol.it",
  89108. "balsan.it",
  89109. "bari.it",
  89110. "barletta-trani-andria.it",
  89111. "barlettatraniandria.it",
  89112. "belluno.it",
  89113. "benevento.it",
  89114. "bergamo.it",
  89115. "bg.it",
  89116. "bi.it",
  89117. "biella.it",
  89118. "bl.it",
  89119. "bn.it",
  89120. "bo.it",
  89121. "bologna.it",
  89122. "bolzano-altoadige.it",
  89123. "bolzano.it",
  89124. "bozen-sudtirol.it",
  89125. "bozen-südtirol.it",
  89126. "bozen-suedtirol.it",
  89127. "bozen.it",
  89128. "br.it",
  89129. "brescia.it",
  89130. "brindisi.it",
  89131. "bs.it",
  89132. "bt.it",
  89133. "bulsan-sudtirol.it",
  89134. "bulsan-südtirol.it",
  89135. "bulsan-suedtirol.it",
  89136. "bulsan.it",
  89137. "bz.it",
  89138. "ca.it",
  89139. "cagliari.it",
  89140. "caltanissetta.it",
  89141. "campidano-medio.it",
  89142. "campidanomedio.it",
  89143. "campobasso.it",
  89144. "carbonia-iglesias.it",
  89145. "carboniaiglesias.it",
  89146. "carrara-massa.it",
  89147. "carraramassa.it",
  89148. "caserta.it",
  89149. "catania.it",
  89150. "catanzaro.it",
  89151. "cb.it",
  89152. "ce.it",
  89153. "cesena-forli.it",
  89154. "cesena-forlì.it",
  89155. "cesenaforli.it",
  89156. "cesenaforlì.it",
  89157. "ch.it",
  89158. "chieti.it",
  89159. "ci.it",
  89160. "cl.it",
  89161. "cn.it",
  89162. "co.it",
  89163. "como.it",
  89164. "cosenza.it",
  89165. "cr.it",
  89166. "cremona.it",
  89167. "crotone.it",
  89168. "cs.it",
  89169. "ct.it",
  89170. "cuneo.it",
  89171. "cz.it",
  89172. "dell-ogliastra.it",
  89173. "dellogliastra.it",
  89174. "en.it",
  89175. "enna.it",
  89176. "fc.it",
  89177. "fe.it",
  89178. "fermo.it",
  89179. "ferrara.it",
  89180. "fg.it",
  89181. "fi.it",
  89182. "firenze.it",
  89183. "florence.it",
  89184. "fm.it",
  89185. "foggia.it",
  89186. "forli-cesena.it",
  89187. "forlì-cesena.it",
  89188. "forlicesena.it",
  89189. "forlìcesena.it",
  89190. "fr.it",
  89191. "frosinone.it",
  89192. "ge.it",
  89193. "genoa.it",
  89194. "genova.it",
  89195. "go.it",
  89196. "gorizia.it",
  89197. "gr.it",
  89198. "grosseto.it",
  89199. "iglesias-carbonia.it",
  89200. "iglesiascarbonia.it",
  89201. "im.it",
  89202. "imperia.it",
  89203. "is.it",
  89204. "isernia.it",
  89205. "kr.it",
  89206. "la-spezia.it",
  89207. "laquila.it",
  89208. "laspezia.it",
  89209. "latina.it",
  89210. "lc.it",
  89211. "le.it",
  89212. "lecce.it",
  89213. "lecco.it",
  89214. "li.it",
  89215. "livorno.it",
  89216. "lo.it",
  89217. "lodi.it",
  89218. "lt.it",
  89219. "lu.it",
  89220. "lucca.it",
  89221. "macerata.it",
  89222. "mantova.it",
  89223. "massa-carrara.it",
  89224. "massacarrara.it",
  89225. "matera.it",
  89226. "mb.it",
  89227. "mc.it",
  89228. "me.it",
  89229. "medio-campidano.it",
  89230. "mediocampidano.it",
  89231. "messina.it",
  89232. "mi.it",
  89233. "milan.it",
  89234. "milano.it",
  89235. "mn.it",
  89236. "mo.it",
  89237. "modena.it",
  89238. "monza-brianza.it",
  89239. "monza-e-della-brianza.it",
  89240. "monza.it",
  89241. "monzabrianza.it",
  89242. "monzaebrianza.it",
  89243. "monzaedellabrianza.it",
  89244. "ms.it",
  89245. "mt.it",
  89246. "na.it",
  89247. "naples.it",
  89248. "napoli.it",
  89249. "no.it",
  89250. "novara.it",
  89251. "nu.it",
  89252. "nuoro.it",
  89253. "og.it",
  89254. "ogliastra.it",
  89255. "olbia-tempio.it",
  89256. "olbiatempio.it",
  89257. "or.it",
  89258. "oristano.it",
  89259. "ot.it",
  89260. "pa.it",
  89261. "padova.it",
  89262. "padua.it",
  89263. "palermo.it",
  89264. "parma.it",
  89265. "pavia.it",
  89266. "pc.it",
  89267. "pd.it",
  89268. "pe.it",
  89269. "perugia.it",
  89270. "pesaro-urbino.it",
  89271. "pesarourbino.it",
  89272. "pescara.it",
  89273. "pg.it",
  89274. "pi.it",
  89275. "piacenza.it",
  89276. "pisa.it",
  89277. "pistoia.it",
  89278. "pn.it",
  89279. "po.it",
  89280. "pordenone.it",
  89281. "potenza.it",
  89282. "pr.it",
  89283. "prato.it",
  89284. "pt.it",
  89285. "pu.it",
  89286. "pv.it",
  89287. "pz.it",
  89288. "ra.it",
  89289. "ragusa.it",
  89290. "ravenna.it",
  89291. "rc.it",
  89292. "re.it",
  89293. "reggio-calabria.it",
  89294. "reggio-emilia.it",
  89295. "reggiocalabria.it",
  89296. "reggioemilia.it",
  89297. "rg.it",
  89298. "ri.it",
  89299. "rieti.it",
  89300. "rimini.it",
  89301. "rm.it",
  89302. "rn.it",
  89303. "ro.it",
  89304. "roma.it",
  89305. "rome.it",
  89306. "rovigo.it",
  89307. "sa.it",
  89308. "salerno.it",
  89309. "sassari.it",
  89310. "savona.it",
  89311. "si.it",
  89312. "siena.it",
  89313. "siracusa.it",
  89314. "so.it",
  89315. "sondrio.it",
  89316. "sp.it",
  89317. "sr.it",
  89318. "ss.it",
  89319. "suedtirol.it",
  89320. "südtirol.it",
  89321. "sv.it",
  89322. "ta.it",
  89323. "taranto.it",
  89324. "te.it",
  89325. "tempio-olbia.it",
  89326. "tempioolbia.it",
  89327. "teramo.it",
  89328. "terni.it",
  89329. "tn.it",
  89330. "to.it",
  89331. "torino.it",
  89332. "tp.it",
  89333. "tr.it",
  89334. "trani-andria-barletta.it",
  89335. "trani-barletta-andria.it",
  89336. "traniandriabarletta.it",
  89337. "tranibarlettaandria.it",
  89338. "trapani.it",
  89339. "trento.it",
  89340. "treviso.it",
  89341. "trieste.it",
  89342. "ts.it",
  89343. "turin.it",
  89344. "tv.it",
  89345. "ud.it",
  89346. "udine.it",
  89347. "urbino-pesaro.it",
  89348. "urbinopesaro.it",
  89349. "va.it",
  89350. "varese.it",
  89351. "vb.it",
  89352. "vc.it",
  89353. "ve.it",
  89354. "venezia.it",
  89355. "venice.it",
  89356. "verbania.it",
  89357. "vercelli.it",
  89358. "verona.it",
  89359. "vi.it",
  89360. "vibo-valentia.it",
  89361. "vibovalentia.it",
  89362. "vicenza.it",
  89363. "viterbo.it",
  89364. "vr.it",
  89365. "vs.it",
  89366. "vt.it",
  89367. "vv.it",
  89368. "je",
  89369. "co.je",
  89370. "net.je",
  89371. "org.je",
  89372. "*.jm",
  89373. "jo",
  89374. "com.jo",
  89375. "org.jo",
  89376. "net.jo",
  89377. "edu.jo",
  89378. "sch.jo",
  89379. "gov.jo",
  89380. "mil.jo",
  89381. "name.jo",
  89382. "jobs",
  89383. "jp",
  89384. "ac.jp",
  89385. "ad.jp",
  89386. "co.jp",
  89387. "ed.jp",
  89388. "go.jp",
  89389. "gr.jp",
  89390. "lg.jp",
  89391. "ne.jp",
  89392. "or.jp",
  89393. "aichi.jp",
  89394. "akita.jp",
  89395. "aomori.jp",
  89396. "chiba.jp",
  89397. "ehime.jp",
  89398. "fukui.jp",
  89399. "fukuoka.jp",
  89400. "fukushima.jp",
  89401. "gifu.jp",
  89402. "gunma.jp",
  89403. "hiroshima.jp",
  89404. "hokkaido.jp",
  89405. "hyogo.jp",
  89406. "ibaraki.jp",
  89407. "ishikawa.jp",
  89408. "iwate.jp",
  89409. "kagawa.jp",
  89410. "kagoshima.jp",
  89411. "kanagawa.jp",
  89412. "kochi.jp",
  89413. "kumamoto.jp",
  89414. "kyoto.jp",
  89415. "mie.jp",
  89416. "miyagi.jp",
  89417. "miyazaki.jp",
  89418. "nagano.jp",
  89419. "nagasaki.jp",
  89420. "nara.jp",
  89421. "niigata.jp",
  89422. "oita.jp",
  89423. "okayama.jp",
  89424. "okinawa.jp",
  89425. "osaka.jp",
  89426. "saga.jp",
  89427. "saitama.jp",
  89428. "shiga.jp",
  89429. "shimane.jp",
  89430. "shizuoka.jp",
  89431. "tochigi.jp",
  89432. "tokushima.jp",
  89433. "tokyo.jp",
  89434. "tottori.jp",
  89435. "toyama.jp",
  89436. "wakayama.jp",
  89437. "yamagata.jp",
  89438. "yamaguchi.jp",
  89439. "yamanashi.jp",
  89440. "栃木.jp",
  89441. "愛知.jp",
  89442. "愛媛.jp",
  89443. "兵庫.jp",
  89444. "熊本.jp",
  89445. "茨城.jp",
  89446. "北海道.jp",
  89447. "千葉.jp",
  89448. "和歌山.jp",
  89449. "長崎.jp",
  89450. "長野.jp",
  89451. "新潟.jp",
  89452. "青森.jp",
  89453. "静岡.jp",
  89454. "東京.jp",
  89455. "石川.jp",
  89456. "埼玉.jp",
  89457. "三重.jp",
  89458. "京都.jp",
  89459. "佐賀.jp",
  89460. "大分.jp",
  89461. "大阪.jp",
  89462. "奈良.jp",
  89463. "宮城.jp",
  89464. "宮崎.jp",
  89465. "富山.jp",
  89466. "山口.jp",
  89467. "山形.jp",
  89468. "山梨.jp",
  89469. "岩手.jp",
  89470. "岐阜.jp",
  89471. "岡山.jp",
  89472. "島根.jp",
  89473. "広島.jp",
  89474. "徳島.jp",
  89475. "沖縄.jp",
  89476. "滋賀.jp",
  89477. "神奈川.jp",
  89478. "福井.jp",
  89479. "福岡.jp",
  89480. "福島.jp",
  89481. "秋田.jp",
  89482. "群馬.jp",
  89483. "香川.jp",
  89484. "高知.jp",
  89485. "鳥取.jp",
  89486. "鹿児島.jp",
  89487. "*.kawasaki.jp",
  89488. "*.kitakyushu.jp",
  89489. "*.kobe.jp",
  89490. "*.nagoya.jp",
  89491. "*.sapporo.jp",
  89492. "*.sendai.jp",
  89493. "*.yokohama.jp",
  89494. "!city.kawasaki.jp",
  89495. "!city.kitakyushu.jp",
  89496. "!city.kobe.jp",
  89497. "!city.nagoya.jp",
  89498. "!city.sapporo.jp",
  89499. "!city.sendai.jp",
  89500. "!city.yokohama.jp",
  89501. "aisai.aichi.jp",
  89502. "ama.aichi.jp",
  89503. "anjo.aichi.jp",
  89504. "asuke.aichi.jp",
  89505. "chiryu.aichi.jp",
  89506. "chita.aichi.jp",
  89507. "fuso.aichi.jp",
  89508. "gamagori.aichi.jp",
  89509. "handa.aichi.jp",
  89510. "hazu.aichi.jp",
  89511. "hekinan.aichi.jp",
  89512. "higashiura.aichi.jp",
  89513. "ichinomiya.aichi.jp",
  89514. "inazawa.aichi.jp",
  89515. "inuyama.aichi.jp",
  89516. "isshiki.aichi.jp",
  89517. "iwakura.aichi.jp",
  89518. "kanie.aichi.jp",
  89519. "kariya.aichi.jp",
  89520. "kasugai.aichi.jp",
  89521. "kira.aichi.jp",
  89522. "kiyosu.aichi.jp",
  89523. "komaki.aichi.jp",
  89524. "konan.aichi.jp",
  89525. "kota.aichi.jp",
  89526. "mihama.aichi.jp",
  89527. "miyoshi.aichi.jp",
  89528. "nishio.aichi.jp",
  89529. "nisshin.aichi.jp",
  89530. "obu.aichi.jp",
  89531. "oguchi.aichi.jp",
  89532. "oharu.aichi.jp",
  89533. "okazaki.aichi.jp",
  89534. "owariasahi.aichi.jp",
  89535. "seto.aichi.jp",
  89536. "shikatsu.aichi.jp",
  89537. "shinshiro.aichi.jp",
  89538. "shitara.aichi.jp",
  89539. "tahara.aichi.jp",
  89540. "takahama.aichi.jp",
  89541. "tobishima.aichi.jp",
  89542. "toei.aichi.jp",
  89543. "togo.aichi.jp",
  89544. "tokai.aichi.jp",
  89545. "tokoname.aichi.jp",
  89546. "toyoake.aichi.jp",
  89547. "toyohashi.aichi.jp",
  89548. "toyokawa.aichi.jp",
  89549. "toyone.aichi.jp",
  89550. "toyota.aichi.jp",
  89551. "tsushima.aichi.jp",
  89552. "yatomi.aichi.jp",
  89553. "akita.akita.jp",
  89554. "daisen.akita.jp",
  89555. "fujisato.akita.jp",
  89556. "gojome.akita.jp",
  89557. "hachirogata.akita.jp",
  89558. "happou.akita.jp",
  89559. "higashinaruse.akita.jp",
  89560. "honjo.akita.jp",
  89561. "honjyo.akita.jp",
  89562. "ikawa.akita.jp",
  89563. "kamikoani.akita.jp",
  89564. "kamioka.akita.jp",
  89565. "katagami.akita.jp",
  89566. "kazuno.akita.jp",
  89567. "kitaakita.akita.jp",
  89568. "kosaka.akita.jp",
  89569. "kyowa.akita.jp",
  89570. "misato.akita.jp",
  89571. "mitane.akita.jp",
  89572. "moriyoshi.akita.jp",
  89573. "nikaho.akita.jp",
  89574. "noshiro.akita.jp",
  89575. "odate.akita.jp",
  89576. "oga.akita.jp",
  89577. "ogata.akita.jp",
  89578. "semboku.akita.jp",
  89579. "yokote.akita.jp",
  89580. "yurihonjo.akita.jp",
  89581. "aomori.aomori.jp",
  89582. "gonohe.aomori.jp",
  89583. "hachinohe.aomori.jp",
  89584. "hashikami.aomori.jp",
  89585. "hiranai.aomori.jp",
  89586. "hirosaki.aomori.jp",
  89587. "itayanagi.aomori.jp",
  89588. "kuroishi.aomori.jp",
  89589. "misawa.aomori.jp",
  89590. "mutsu.aomori.jp",
  89591. "nakadomari.aomori.jp",
  89592. "noheji.aomori.jp",
  89593. "oirase.aomori.jp",
  89594. "owani.aomori.jp",
  89595. "rokunohe.aomori.jp",
  89596. "sannohe.aomori.jp",
  89597. "shichinohe.aomori.jp",
  89598. "shingo.aomori.jp",
  89599. "takko.aomori.jp",
  89600. "towada.aomori.jp",
  89601. "tsugaru.aomori.jp",
  89602. "tsuruta.aomori.jp",
  89603. "abiko.chiba.jp",
  89604. "asahi.chiba.jp",
  89605. "chonan.chiba.jp",
  89606. "chosei.chiba.jp",
  89607. "choshi.chiba.jp",
  89608. "chuo.chiba.jp",
  89609. "funabashi.chiba.jp",
  89610. "futtsu.chiba.jp",
  89611. "hanamigawa.chiba.jp",
  89612. "ichihara.chiba.jp",
  89613. "ichikawa.chiba.jp",
  89614. "ichinomiya.chiba.jp",
  89615. "inzai.chiba.jp",
  89616. "isumi.chiba.jp",
  89617. "kamagaya.chiba.jp",
  89618. "kamogawa.chiba.jp",
  89619. "kashiwa.chiba.jp",
  89620. "katori.chiba.jp",
  89621. "katsuura.chiba.jp",
  89622. "kimitsu.chiba.jp",
  89623. "kisarazu.chiba.jp",
  89624. "kozaki.chiba.jp",
  89625. "kujukuri.chiba.jp",
  89626. "kyonan.chiba.jp",
  89627. "matsudo.chiba.jp",
  89628. "midori.chiba.jp",
  89629. "mihama.chiba.jp",
  89630. "minamiboso.chiba.jp",
  89631. "mobara.chiba.jp",
  89632. "mutsuzawa.chiba.jp",
  89633. "nagara.chiba.jp",
  89634. "nagareyama.chiba.jp",
  89635. "narashino.chiba.jp",
  89636. "narita.chiba.jp",
  89637. "noda.chiba.jp",
  89638. "oamishirasato.chiba.jp",
  89639. "omigawa.chiba.jp",
  89640. "onjuku.chiba.jp",
  89641. "otaki.chiba.jp",
  89642. "sakae.chiba.jp",
  89643. "sakura.chiba.jp",
  89644. "shimofusa.chiba.jp",
  89645. "shirako.chiba.jp",
  89646. "shiroi.chiba.jp",
  89647. "shisui.chiba.jp",
  89648. "sodegaura.chiba.jp",
  89649. "sosa.chiba.jp",
  89650. "tako.chiba.jp",
  89651. "tateyama.chiba.jp",
  89652. "togane.chiba.jp",
  89653. "tohnosho.chiba.jp",
  89654. "tomisato.chiba.jp",
  89655. "urayasu.chiba.jp",
  89656. "yachimata.chiba.jp",
  89657. "yachiyo.chiba.jp",
  89658. "yokaichiba.chiba.jp",
  89659. "yokoshibahikari.chiba.jp",
  89660. "yotsukaido.chiba.jp",
  89661. "ainan.ehime.jp",
  89662. "honai.ehime.jp",
  89663. "ikata.ehime.jp",
  89664. "imabari.ehime.jp",
  89665. "iyo.ehime.jp",
  89666. "kamijima.ehime.jp",
  89667. "kihoku.ehime.jp",
  89668. "kumakogen.ehime.jp",
  89669. "masaki.ehime.jp",
  89670. "matsuno.ehime.jp",
  89671. "matsuyama.ehime.jp",
  89672. "namikata.ehime.jp",
  89673. "niihama.ehime.jp",
  89674. "ozu.ehime.jp",
  89675. "saijo.ehime.jp",
  89676. "seiyo.ehime.jp",
  89677. "shikokuchuo.ehime.jp",
  89678. "tobe.ehime.jp",
  89679. "toon.ehime.jp",
  89680. "uchiko.ehime.jp",
  89681. "uwajima.ehime.jp",
  89682. "yawatahama.ehime.jp",
  89683. "echizen.fukui.jp",
  89684. "eiheiji.fukui.jp",
  89685. "fukui.fukui.jp",
  89686. "ikeda.fukui.jp",
  89687. "katsuyama.fukui.jp",
  89688. "mihama.fukui.jp",
  89689. "minamiechizen.fukui.jp",
  89690. "obama.fukui.jp",
  89691. "ohi.fukui.jp",
  89692. "ono.fukui.jp",
  89693. "sabae.fukui.jp",
  89694. "sakai.fukui.jp",
  89695. "takahama.fukui.jp",
  89696. "tsuruga.fukui.jp",
  89697. "wakasa.fukui.jp",
  89698. "ashiya.fukuoka.jp",
  89699. "buzen.fukuoka.jp",
  89700. "chikugo.fukuoka.jp",
  89701. "chikuho.fukuoka.jp",
  89702. "chikujo.fukuoka.jp",
  89703. "chikushino.fukuoka.jp",
  89704. "chikuzen.fukuoka.jp",
  89705. "chuo.fukuoka.jp",
  89706. "dazaifu.fukuoka.jp",
  89707. "fukuchi.fukuoka.jp",
  89708. "hakata.fukuoka.jp",
  89709. "higashi.fukuoka.jp",
  89710. "hirokawa.fukuoka.jp",
  89711. "hisayama.fukuoka.jp",
  89712. "iizuka.fukuoka.jp",
  89713. "inatsuki.fukuoka.jp",
  89714. "kaho.fukuoka.jp",
  89715. "kasuga.fukuoka.jp",
  89716. "kasuya.fukuoka.jp",
  89717. "kawara.fukuoka.jp",
  89718. "keisen.fukuoka.jp",
  89719. "koga.fukuoka.jp",
  89720. "kurate.fukuoka.jp",
  89721. "kurogi.fukuoka.jp",
  89722. "kurume.fukuoka.jp",
  89723. "minami.fukuoka.jp",
  89724. "miyako.fukuoka.jp",
  89725. "miyama.fukuoka.jp",
  89726. "miyawaka.fukuoka.jp",
  89727. "mizumaki.fukuoka.jp",
  89728. "munakata.fukuoka.jp",
  89729. "nakagawa.fukuoka.jp",
  89730. "nakama.fukuoka.jp",
  89731. "nishi.fukuoka.jp",
  89732. "nogata.fukuoka.jp",
  89733. "ogori.fukuoka.jp",
  89734. "okagaki.fukuoka.jp",
  89735. "okawa.fukuoka.jp",
  89736. "oki.fukuoka.jp",
  89737. "omuta.fukuoka.jp",
  89738. "onga.fukuoka.jp",
  89739. "onojo.fukuoka.jp",
  89740. "oto.fukuoka.jp",
  89741. "saigawa.fukuoka.jp",
  89742. "sasaguri.fukuoka.jp",
  89743. "shingu.fukuoka.jp",
  89744. "shinyoshitomi.fukuoka.jp",
  89745. "shonai.fukuoka.jp",
  89746. "soeda.fukuoka.jp",
  89747. "sue.fukuoka.jp",
  89748. "tachiarai.fukuoka.jp",
  89749. "tagawa.fukuoka.jp",
  89750. "takata.fukuoka.jp",
  89751. "toho.fukuoka.jp",
  89752. "toyotsu.fukuoka.jp",
  89753. "tsuiki.fukuoka.jp",
  89754. "ukiha.fukuoka.jp",
  89755. "umi.fukuoka.jp",
  89756. "usui.fukuoka.jp",
  89757. "yamada.fukuoka.jp",
  89758. "yame.fukuoka.jp",
  89759. "yanagawa.fukuoka.jp",
  89760. "yukuhashi.fukuoka.jp",
  89761. "aizubange.fukushima.jp",
  89762. "aizumisato.fukushima.jp",
  89763. "aizuwakamatsu.fukushima.jp",
  89764. "asakawa.fukushima.jp",
  89765. "bandai.fukushima.jp",
  89766. "date.fukushima.jp",
  89767. "fukushima.fukushima.jp",
  89768. "furudono.fukushima.jp",
  89769. "futaba.fukushima.jp",
  89770. "hanawa.fukushima.jp",
  89771. "higashi.fukushima.jp",
  89772. "hirata.fukushima.jp",
  89773. "hirono.fukushima.jp",
  89774. "iitate.fukushima.jp",
  89775. "inawashiro.fukushima.jp",
  89776. "ishikawa.fukushima.jp",
  89777. "iwaki.fukushima.jp",
  89778. "izumizaki.fukushima.jp",
  89779. "kagamiishi.fukushima.jp",
  89780. "kaneyama.fukushima.jp",
  89781. "kawamata.fukushima.jp",
  89782. "kitakata.fukushima.jp",
  89783. "kitashiobara.fukushima.jp",
  89784. "koori.fukushima.jp",
  89785. "koriyama.fukushima.jp",
  89786. "kunimi.fukushima.jp",
  89787. "miharu.fukushima.jp",
  89788. "mishima.fukushima.jp",
  89789. "namie.fukushima.jp",
  89790. "nango.fukushima.jp",
  89791. "nishiaizu.fukushima.jp",
  89792. "nishigo.fukushima.jp",
  89793. "okuma.fukushima.jp",
  89794. "omotego.fukushima.jp",
  89795. "ono.fukushima.jp",
  89796. "otama.fukushima.jp",
  89797. "samegawa.fukushima.jp",
  89798. "shimogo.fukushima.jp",
  89799. "shirakawa.fukushima.jp",
  89800. "showa.fukushima.jp",
  89801. "soma.fukushima.jp",
  89802. "sukagawa.fukushima.jp",
  89803. "taishin.fukushima.jp",
  89804. "tamakawa.fukushima.jp",
  89805. "tanagura.fukushima.jp",
  89806. "tenei.fukushima.jp",
  89807. "yabuki.fukushima.jp",
  89808. "yamato.fukushima.jp",
  89809. "yamatsuri.fukushima.jp",
  89810. "yanaizu.fukushima.jp",
  89811. "yugawa.fukushima.jp",
  89812. "anpachi.gifu.jp",
  89813. "ena.gifu.jp",
  89814. "gifu.gifu.jp",
  89815. "ginan.gifu.jp",
  89816. "godo.gifu.jp",
  89817. "gujo.gifu.jp",
  89818. "hashima.gifu.jp",
  89819. "hichiso.gifu.jp",
  89820. "hida.gifu.jp",
  89821. "higashishirakawa.gifu.jp",
  89822. "ibigawa.gifu.jp",
  89823. "ikeda.gifu.jp",
  89824. "kakamigahara.gifu.jp",
  89825. "kani.gifu.jp",
  89826. "kasahara.gifu.jp",
  89827. "kasamatsu.gifu.jp",
  89828. "kawaue.gifu.jp",
  89829. "kitagata.gifu.jp",
  89830. "mino.gifu.jp",
  89831. "minokamo.gifu.jp",
  89832. "mitake.gifu.jp",
  89833. "mizunami.gifu.jp",
  89834. "motosu.gifu.jp",
  89835. "nakatsugawa.gifu.jp",
  89836. "ogaki.gifu.jp",
  89837. "sakahogi.gifu.jp",
  89838. "seki.gifu.jp",
  89839. "sekigahara.gifu.jp",
  89840. "shirakawa.gifu.jp",
  89841. "tajimi.gifu.jp",
  89842. "takayama.gifu.jp",
  89843. "tarui.gifu.jp",
  89844. "toki.gifu.jp",
  89845. "tomika.gifu.jp",
  89846. "wanouchi.gifu.jp",
  89847. "yamagata.gifu.jp",
  89848. "yaotsu.gifu.jp",
  89849. "yoro.gifu.jp",
  89850. "annaka.gunma.jp",
  89851. "chiyoda.gunma.jp",
  89852. "fujioka.gunma.jp",
  89853. "higashiagatsuma.gunma.jp",
  89854. "isesaki.gunma.jp",
  89855. "itakura.gunma.jp",
  89856. "kanna.gunma.jp",
  89857. "kanra.gunma.jp",
  89858. "katashina.gunma.jp",
  89859. "kawaba.gunma.jp",
  89860. "kiryu.gunma.jp",
  89861. "kusatsu.gunma.jp",
  89862. "maebashi.gunma.jp",
  89863. "meiwa.gunma.jp",
  89864. "midori.gunma.jp",
  89865. "minakami.gunma.jp",
  89866. "naganohara.gunma.jp",
  89867. "nakanojo.gunma.jp",
  89868. "nanmoku.gunma.jp",
  89869. "numata.gunma.jp",
  89870. "oizumi.gunma.jp",
  89871. "ora.gunma.jp",
  89872. "ota.gunma.jp",
  89873. "shibukawa.gunma.jp",
  89874. "shimonita.gunma.jp",
  89875. "shinto.gunma.jp",
  89876. "showa.gunma.jp",
  89877. "takasaki.gunma.jp",
  89878. "takayama.gunma.jp",
  89879. "tamamura.gunma.jp",
  89880. "tatebayashi.gunma.jp",
  89881. "tomioka.gunma.jp",
  89882. "tsukiyono.gunma.jp",
  89883. "tsumagoi.gunma.jp",
  89884. "ueno.gunma.jp",
  89885. "yoshioka.gunma.jp",
  89886. "asaminami.hiroshima.jp",
  89887. "daiwa.hiroshima.jp",
  89888. "etajima.hiroshima.jp",
  89889. "fuchu.hiroshima.jp",
  89890. "fukuyama.hiroshima.jp",
  89891. "hatsukaichi.hiroshima.jp",
  89892. "higashihiroshima.hiroshima.jp",
  89893. "hongo.hiroshima.jp",
  89894. "jinsekikogen.hiroshima.jp",
  89895. "kaita.hiroshima.jp",
  89896. "kui.hiroshima.jp",
  89897. "kumano.hiroshima.jp",
  89898. "kure.hiroshima.jp",
  89899. "mihara.hiroshima.jp",
  89900. "miyoshi.hiroshima.jp",
  89901. "naka.hiroshima.jp",
  89902. "onomichi.hiroshima.jp",
  89903. "osakikamijima.hiroshima.jp",
  89904. "otake.hiroshima.jp",
  89905. "saka.hiroshima.jp",
  89906. "sera.hiroshima.jp",
  89907. "seranishi.hiroshima.jp",
  89908. "shinichi.hiroshima.jp",
  89909. "shobara.hiroshima.jp",
  89910. "takehara.hiroshima.jp",
  89911. "abashiri.hokkaido.jp",
  89912. "abira.hokkaido.jp",
  89913. "aibetsu.hokkaido.jp",
  89914. "akabira.hokkaido.jp",
  89915. "akkeshi.hokkaido.jp",
  89916. "asahikawa.hokkaido.jp",
  89917. "ashibetsu.hokkaido.jp",
  89918. "ashoro.hokkaido.jp",
  89919. "assabu.hokkaido.jp",
  89920. "atsuma.hokkaido.jp",
  89921. "bibai.hokkaido.jp",
  89922. "biei.hokkaido.jp",
  89923. "bifuka.hokkaido.jp",
  89924. "bihoro.hokkaido.jp",
  89925. "biratori.hokkaido.jp",
  89926. "chippubetsu.hokkaido.jp",
  89927. "chitose.hokkaido.jp",
  89928. "date.hokkaido.jp",
  89929. "ebetsu.hokkaido.jp",
  89930. "embetsu.hokkaido.jp",
  89931. "eniwa.hokkaido.jp",
  89932. "erimo.hokkaido.jp",
  89933. "esan.hokkaido.jp",
  89934. "esashi.hokkaido.jp",
  89935. "fukagawa.hokkaido.jp",
  89936. "fukushima.hokkaido.jp",
  89937. "furano.hokkaido.jp",
  89938. "furubira.hokkaido.jp",
  89939. "haboro.hokkaido.jp",
  89940. "hakodate.hokkaido.jp",
  89941. "hamatonbetsu.hokkaido.jp",
  89942. "hidaka.hokkaido.jp",
  89943. "higashikagura.hokkaido.jp",
  89944. "higashikawa.hokkaido.jp",
  89945. "hiroo.hokkaido.jp",
  89946. "hokuryu.hokkaido.jp",
  89947. "hokuto.hokkaido.jp",
  89948. "honbetsu.hokkaido.jp",
  89949. "horokanai.hokkaido.jp",
  89950. "horonobe.hokkaido.jp",
  89951. "ikeda.hokkaido.jp",
  89952. "imakane.hokkaido.jp",
  89953. "ishikari.hokkaido.jp",
  89954. "iwamizawa.hokkaido.jp",
  89955. "iwanai.hokkaido.jp",
  89956. "kamifurano.hokkaido.jp",
  89957. "kamikawa.hokkaido.jp",
  89958. "kamishihoro.hokkaido.jp",
  89959. "kamisunagawa.hokkaido.jp",
  89960. "kamoenai.hokkaido.jp",
  89961. "kayabe.hokkaido.jp",
  89962. "kembuchi.hokkaido.jp",
  89963. "kikonai.hokkaido.jp",
  89964. "kimobetsu.hokkaido.jp",
  89965. "kitahiroshima.hokkaido.jp",
  89966. "kitami.hokkaido.jp",
  89967. "kiyosato.hokkaido.jp",
  89968. "koshimizu.hokkaido.jp",
  89969. "kunneppu.hokkaido.jp",
  89970. "kuriyama.hokkaido.jp",
  89971. "kuromatsunai.hokkaido.jp",
  89972. "kushiro.hokkaido.jp",
  89973. "kutchan.hokkaido.jp",
  89974. "kyowa.hokkaido.jp",
  89975. "mashike.hokkaido.jp",
  89976. "matsumae.hokkaido.jp",
  89977. "mikasa.hokkaido.jp",
  89978. "minamifurano.hokkaido.jp",
  89979. "mombetsu.hokkaido.jp",
  89980. "moseushi.hokkaido.jp",
  89981. "mukawa.hokkaido.jp",
  89982. "muroran.hokkaido.jp",
  89983. "naie.hokkaido.jp",
  89984. "nakagawa.hokkaido.jp",
  89985. "nakasatsunai.hokkaido.jp",
  89986. "nakatombetsu.hokkaido.jp",
  89987. "nanae.hokkaido.jp",
  89988. "nanporo.hokkaido.jp",
  89989. "nayoro.hokkaido.jp",
  89990. "nemuro.hokkaido.jp",
  89991. "niikappu.hokkaido.jp",
  89992. "niki.hokkaido.jp",
  89993. "nishiokoppe.hokkaido.jp",
  89994. "noboribetsu.hokkaido.jp",
  89995. "numata.hokkaido.jp",
  89996. "obihiro.hokkaido.jp",
  89997. "obira.hokkaido.jp",
  89998. "oketo.hokkaido.jp",
  89999. "okoppe.hokkaido.jp",
  90000. "otaru.hokkaido.jp",
  90001. "otobe.hokkaido.jp",
  90002. "otofuke.hokkaido.jp",
  90003. "otoineppu.hokkaido.jp",
  90004. "oumu.hokkaido.jp",
  90005. "ozora.hokkaido.jp",
  90006. "pippu.hokkaido.jp",
  90007. "rankoshi.hokkaido.jp",
  90008. "rebun.hokkaido.jp",
  90009. "rikubetsu.hokkaido.jp",
  90010. "rishiri.hokkaido.jp",
  90011. "rishirifuji.hokkaido.jp",
  90012. "saroma.hokkaido.jp",
  90013. "sarufutsu.hokkaido.jp",
  90014. "shakotan.hokkaido.jp",
  90015. "shari.hokkaido.jp",
  90016. "shibecha.hokkaido.jp",
  90017. "shibetsu.hokkaido.jp",
  90018. "shikabe.hokkaido.jp",
  90019. "shikaoi.hokkaido.jp",
  90020. "shimamaki.hokkaido.jp",
  90021. "shimizu.hokkaido.jp",
  90022. "shimokawa.hokkaido.jp",
  90023. "shinshinotsu.hokkaido.jp",
  90024. "shintoku.hokkaido.jp",
  90025. "shiranuka.hokkaido.jp",
  90026. "shiraoi.hokkaido.jp",
  90027. "shiriuchi.hokkaido.jp",
  90028. "sobetsu.hokkaido.jp",
  90029. "sunagawa.hokkaido.jp",
  90030. "taiki.hokkaido.jp",
  90031. "takasu.hokkaido.jp",
  90032. "takikawa.hokkaido.jp",
  90033. "takinoue.hokkaido.jp",
  90034. "teshikaga.hokkaido.jp",
  90035. "tobetsu.hokkaido.jp",
  90036. "tohma.hokkaido.jp",
  90037. "tomakomai.hokkaido.jp",
  90038. "tomari.hokkaido.jp",
  90039. "toya.hokkaido.jp",
  90040. "toyako.hokkaido.jp",
  90041. "toyotomi.hokkaido.jp",
  90042. "toyoura.hokkaido.jp",
  90043. "tsubetsu.hokkaido.jp",
  90044. "tsukigata.hokkaido.jp",
  90045. "urakawa.hokkaido.jp",
  90046. "urausu.hokkaido.jp",
  90047. "uryu.hokkaido.jp",
  90048. "utashinai.hokkaido.jp",
  90049. "wakkanai.hokkaido.jp",
  90050. "wassamu.hokkaido.jp",
  90051. "yakumo.hokkaido.jp",
  90052. "yoichi.hokkaido.jp",
  90053. "aioi.hyogo.jp",
  90054. "akashi.hyogo.jp",
  90055. "ako.hyogo.jp",
  90056. "amagasaki.hyogo.jp",
  90057. "aogaki.hyogo.jp",
  90058. "asago.hyogo.jp",
  90059. "ashiya.hyogo.jp",
  90060. "awaji.hyogo.jp",
  90061. "fukusaki.hyogo.jp",
  90062. "goshiki.hyogo.jp",
  90063. "harima.hyogo.jp",
  90064. "himeji.hyogo.jp",
  90065. "ichikawa.hyogo.jp",
  90066. "inagawa.hyogo.jp",
  90067. "itami.hyogo.jp",
  90068. "kakogawa.hyogo.jp",
  90069. "kamigori.hyogo.jp",
  90070. "kamikawa.hyogo.jp",
  90071. "kasai.hyogo.jp",
  90072. "kasuga.hyogo.jp",
  90073. "kawanishi.hyogo.jp",
  90074. "miki.hyogo.jp",
  90075. "minamiawaji.hyogo.jp",
  90076. "nishinomiya.hyogo.jp",
  90077. "nishiwaki.hyogo.jp",
  90078. "ono.hyogo.jp",
  90079. "sanda.hyogo.jp",
  90080. "sannan.hyogo.jp",
  90081. "sasayama.hyogo.jp",
  90082. "sayo.hyogo.jp",
  90083. "shingu.hyogo.jp",
  90084. "shinonsen.hyogo.jp",
  90085. "shiso.hyogo.jp",
  90086. "sumoto.hyogo.jp",
  90087. "taishi.hyogo.jp",
  90088. "taka.hyogo.jp",
  90089. "takarazuka.hyogo.jp",
  90090. "takasago.hyogo.jp",
  90091. "takino.hyogo.jp",
  90092. "tamba.hyogo.jp",
  90093. "tatsuno.hyogo.jp",
  90094. "toyooka.hyogo.jp",
  90095. "yabu.hyogo.jp",
  90096. "yashiro.hyogo.jp",
  90097. "yoka.hyogo.jp",
  90098. "yokawa.hyogo.jp",
  90099. "ami.ibaraki.jp",
  90100. "asahi.ibaraki.jp",
  90101. "bando.ibaraki.jp",
  90102. "chikusei.ibaraki.jp",
  90103. "daigo.ibaraki.jp",
  90104. "fujishiro.ibaraki.jp",
  90105. "hitachi.ibaraki.jp",
  90106. "hitachinaka.ibaraki.jp",
  90107. "hitachiomiya.ibaraki.jp",
  90108. "hitachiota.ibaraki.jp",
  90109. "ibaraki.ibaraki.jp",
  90110. "ina.ibaraki.jp",
  90111. "inashiki.ibaraki.jp",
  90112. "itako.ibaraki.jp",
  90113. "iwama.ibaraki.jp",
  90114. "joso.ibaraki.jp",
  90115. "kamisu.ibaraki.jp",
  90116. "kasama.ibaraki.jp",
  90117. "kashima.ibaraki.jp",
  90118. "kasumigaura.ibaraki.jp",
  90119. "koga.ibaraki.jp",
  90120. "miho.ibaraki.jp",
  90121. "mito.ibaraki.jp",
  90122. "moriya.ibaraki.jp",
  90123. "naka.ibaraki.jp",
  90124. "namegata.ibaraki.jp",
  90125. "oarai.ibaraki.jp",
  90126. "ogawa.ibaraki.jp",
  90127. "omitama.ibaraki.jp",
  90128. "ryugasaki.ibaraki.jp",
  90129. "sakai.ibaraki.jp",
  90130. "sakuragawa.ibaraki.jp",
  90131. "shimodate.ibaraki.jp",
  90132. "shimotsuma.ibaraki.jp",
  90133. "shirosato.ibaraki.jp",
  90134. "sowa.ibaraki.jp",
  90135. "suifu.ibaraki.jp",
  90136. "takahagi.ibaraki.jp",
  90137. "tamatsukuri.ibaraki.jp",
  90138. "tokai.ibaraki.jp",
  90139. "tomobe.ibaraki.jp",
  90140. "tone.ibaraki.jp",
  90141. "toride.ibaraki.jp",
  90142. "tsuchiura.ibaraki.jp",
  90143. "tsukuba.ibaraki.jp",
  90144. "uchihara.ibaraki.jp",
  90145. "ushiku.ibaraki.jp",
  90146. "yachiyo.ibaraki.jp",
  90147. "yamagata.ibaraki.jp",
  90148. "yawara.ibaraki.jp",
  90149. "yuki.ibaraki.jp",
  90150. "anamizu.ishikawa.jp",
  90151. "hakui.ishikawa.jp",
  90152. "hakusan.ishikawa.jp",
  90153. "kaga.ishikawa.jp",
  90154. "kahoku.ishikawa.jp",
  90155. "kanazawa.ishikawa.jp",
  90156. "kawakita.ishikawa.jp",
  90157. "komatsu.ishikawa.jp",
  90158. "nakanoto.ishikawa.jp",
  90159. "nanao.ishikawa.jp",
  90160. "nomi.ishikawa.jp",
  90161. "nonoichi.ishikawa.jp",
  90162. "noto.ishikawa.jp",
  90163. "shika.ishikawa.jp",
  90164. "suzu.ishikawa.jp",
  90165. "tsubata.ishikawa.jp",
  90166. "tsurugi.ishikawa.jp",
  90167. "uchinada.ishikawa.jp",
  90168. "wajima.ishikawa.jp",
  90169. "fudai.iwate.jp",
  90170. "fujisawa.iwate.jp",
  90171. "hanamaki.iwate.jp",
  90172. "hiraizumi.iwate.jp",
  90173. "hirono.iwate.jp",
  90174. "ichinohe.iwate.jp",
  90175. "ichinoseki.iwate.jp",
  90176. "iwaizumi.iwate.jp",
  90177. "iwate.iwate.jp",
  90178. "joboji.iwate.jp",
  90179. "kamaishi.iwate.jp",
  90180. "kanegasaki.iwate.jp",
  90181. "karumai.iwate.jp",
  90182. "kawai.iwate.jp",
  90183. "kitakami.iwate.jp",
  90184. "kuji.iwate.jp",
  90185. "kunohe.iwate.jp",
  90186. "kuzumaki.iwate.jp",
  90187. "miyako.iwate.jp",
  90188. "mizusawa.iwate.jp",
  90189. "morioka.iwate.jp",
  90190. "ninohe.iwate.jp",
  90191. "noda.iwate.jp",
  90192. "ofunato.iwate.jp",
  90193. "oshu.iwate.jp",
  90194. "otsuchi.iwate.jp",
  90195. "rikuzentakata.iwate.jp",
  90196. "shiwa.iwate.jp",
  90197. "shizukuishi.iwate.jp",
  90198. "sumita.iwate.jp",
  90199. "tanohata.iwate.jp",
  90200. "tono.iwate.jp",
  90201. "yahaba.iwate.jp",
  90202. "yamada.iwate.jp",
  90203. "ayagawa.kagawa.jp",
  90204. "higashikagawa.kagawa.jp",
  90205. "kanonji.kagawa.jp",
  90206. "kotohira.kagawa.jp",
  90207. "manno.kagawa.jp",
  90208. "marugame.kagawa.jp",
  90209. "mitoyo.kagawa.jp",
  90210. "naoshima.kagawa.jp",
  90211. "sanuki.kagawa.jp",
  90212. "tadotsu.kagawa.jp",
  90213. "takamatsu.kagawa.jp",
  90214. "tonosho.kagawa.jp",
  90215. "uchinomi.kagawa.jp",
  90216. "utazu.kagawa.jp",
  90217. "zentsuji.kagawa.jp",
  90218. "akune.kagoshima.jp",
  90219. "amami.kagoshima.jp",
  90220. "hioki.kagoshima.jp",
  90221. "isa.kagoshima.jp",
  90222. "isen.kagoshima.jp",
  90223. "izumi.kagoshima.jp",
  90224. "kagoshima.kagoshima.jp",
  90225. "kanoya.kagoshima.jp",
  90226. "kawanabe.kagoshima.jp",
  90227. "kinko.kagoshima.jp",
  90228. "kouyama.kagoshima.jp",
  90229. "makurazaki.kagoshima.jp",
  90230. "matsumoto.kagoshima.jp",
  90231. "minamitane.kagoshima.jp",
  90232. "nakatane.kagoshima.jp",
  90233. "nishinoomote.kagoshima.jp",
  90234. "satsumasendai.kagoshima.jp",
  90235. "soo.kagoshima.jp",
  90236. "tarumizu.kagoshima.jp",
  90237. "yusui.kagoshima.jp",
  90238. "aikawa.kanagawa.jp",
  90239. "atsugi.kanagawa.jp",
  90240. "ayase.kanagawa.jp",
  90241. "chigasaki.kanagawa.jp",
  90242. "ebina.kanagawa.jp",
  90243. "fujisawa.kanagawa.jp",
  90244. "hadano.kanagawa.jp",
  90245. "hakone.kanagawa.jp",
  90246. "hiratsuka.kanagawa.jp",
  90247. "isehara.kanagawa.jp",
  90248. "kaisei.kanagawa.jp",
  90249. "kamakura.kanagawa.jp",
  90250. "kiyokawa.kanagawa.jp",
  90251. "matsuda.kanagawa.jp",
  90252. "minamiashigara.kanagawa.jp",
  90253. "miura.kanagawa.jp",
  90254. "nakai.kanagawa.jp",
  90255. "ninomiya.kanagawa.jp",
  90256. "odawara.kanagawa.jp",
  90257. "oi.kanagawa.jp",
  90258. "oiso.kanagawa.jp",
  90259. "sagamihara.kanagawa.jp",
  90260. "samukawa.kanagawa.jp",
  90261. "tsukui.kanagawa.jp",
  90262. "yamakita.kanagawa.jp",
  90263. "yamato.kanagawa.jp",
  90264. "yokosuka.kanagawa.jp",
  90265. "yugawara.kanagawa.jp",
  90266. "zama.kanagawa.jp",
  90267. "zushi.kanagawa.jp",
  90268. "aki.kochi.jp",
  90269. "geisei.kochi.jp",
  90270. "hidaka.kochi.jp",
  90271. "higashitsuno.kochi.jp",
  90272. "ino.kochi.jp",
  90273. "kagami.kochi.jp",
  90274. "kami.kochi.jp",
  90275. "kitagawa.kochi.jp",
  90276. "kochi.kochi.jp",
  90277. "mihara.kochi.jp",
  90278. "motoyama.kochi.jp",
  90279. "muroto.kochi.jp",
  90280. "nahari.kochi.jp",
  90281. "nakamura.kochi.jp",
  90282. "nankoku.kochi.jp",
  90283. "nishitosa.kochi.jp",
  90284. "niyodogawa.kochi.jp",
  90285. "ochi.kochi.jp",
  90286. "okawa.kochi.jp",
  90287. "otoyo.kochi.jp",
  90288. "otsuki.kochi.jp",
  90289. "sakawa.kochi.jp",
  90290. "sukumo.kochi.jp",
  90291. "susaki.kochi.jp",
  90292. "tosa.kochi.jp",
  90293. "tosashimizu.kochi.jp",
  90294. "toyo.kochi.jp",
  90295. "tsuno.kochi.jp",
  90296. "umaji.kochi.jp",
  90297. "yasuda.kochi.jp",
  90298. "yusuhara.kochi.jp",
  90299. "amakusa.kumamoto.jp",
  90300. "arao.kumamoto.jp",
  90301. "aso.kumamoto.jp",
  90302. "choyo.kumamoto.jp",
  90303. "gyokuto.kumamoto.jp",
  90304. "kamiamakusa.kumamoto.jp",
  90305. "kikuchi.kumamoto.jp",
  90306. "kumamoto.kumamoto.jp",
  90307. "mashiki.kumamoto.jp",
  90308. "mifune.kumamoto.jp",
  90309. "minamata.kumamoto.jp",
  90310. "minamioguni.kumamoto.jp",
  90311. "nagasu.kumamoto.jp",
  90312. "nishihara.kumamoto.jp",
  90313. "oguni.kumamoto.jp",
  90314. "ozu.kumamoto.jp",
  90315. "sumoto.kumamoto.jp",
  90316. "takamori.kumamoto.jp",
  90317. "uki.kumamoto.jp",
  90318. "uto.kumamoto.jp",
  90319. "yamaga.kumamoto.jp",
  90320. "yamato.kumamoto.jp",
  90321. "yatsushiro.kumamoto.jp",
  90322. "ayabe.kyoto.jp",
  90323. "fukuchiyama.kyoto.jp",
  90324. "higashiyama.kyoto.jp",
  90325. "ide.kyoto.jp",
  90326. "ine.kyoto.jp",
  90327. "joyo.kyoto.jp",
  90328. "kameoka.kyoto.jp",
  90329. "kamo.kyoto.jp",
  90330. "kita.kyoto.jp",
  90331. "kizu.kyoto.jp",
  90332. "kumiyama.kyoto.jp",
  90333. "kyotamba.kyoto.jp",
  90334. "kyotanabe.kyoto.jp",
  90335. "kyotango.kyoto.jp",
  90336. "maizuru.kyoto.jp",
  90337. "minami.kyoto.jp",
  90338. "minamiyamashiro.kyoto.jp",
  90339. "miyazu.kyoto.jp",
  90340. "muko.kyoto.jp",
  90341. "nagaokakyo.kyoto.jp",
  90342. "nakagyo.kyoto.jp",
  90343. "nantan.kyoto.jp",
  90344. "oyamazaki.kyoto.jp",
  90345. "sakyo.kyoto.jp",
  90346. "seika.kyoto.jp",
  90347. "tanabe.kyoto.jp",
  90348. "uji.kyoto.jp",
  90349. "ujitawara.kyoto.jp",
  90350. "wazuka.kyoto.jp",
  90351. "yamashina.kyoto.jp",
  90352. "yawata.kyoto.jp",
  90353. "asahi.mie.jp",
  90354. "inabe.mie.jp",
  90355. "ise.mie.jp",
  90356. "kameyama.mie.jp",
  90357. "kawagoe.mie.jp",
  90358. "kiho.mie.jp",
  90359. "kisosaki.mie.jp",
  90360. "kiwa.mie.jp",
  90361. "komono.mie.jp",
  90362. "kumano.mie.jp",
  90363. "kuwana.mie.jp",
  90364. "matsusaka.mie.jp",
  90365. "meiwa.mie.jp",
  90366. "mihama.mie.jp",
  90367. "minamiise.mie.jp",
  90368. "misugi.mie.jp",
  90369. "miyama.mie.jp",
  90370. "nabari.mie.jp",
  90371. "shima.mie.jp",
  90372. "suzuka.mie.jp",
  90373. "tado.mie.jp",
  90374. "taiki.mie.jp",
  90375. "taki.mie.jp",
  90376. "tamaki.mie.jp",
  90377. "toba.mie.jp",
  90378. "tsu.mie.jp",
  90379. "udono.mie.jp",
  90380. "ureshino.mie.jp",
  90381. "watarai.mie.jp",
  90382. "yokkaichi.mie.jp",
  90383. "furukawa.miyagi.jp",
  90384. "higashimatsushima.miyagi.jp",
  90385. "ishinomaki.miyagi.jp",
  90386. "iwanuma.miyagi.jp",
  90387. "kakuda.miyagi.jp",
  90388. "kami.miyagi.jp",
  90389. "kawasaki.miyagi.jp",
  90390. "marumori.miyagi.jp",
  90391. "matsushima.miyagi.jp",
  90392. "minamisanriku.miyagi.jp",
  90393. "misato.miyagi.jp",
  90394. "murata.miyagi.jp",
  90395. "natori.miyagi.jp",
  90396. "ogawara.miyagi.jp",
  90397. "ohira.miyagi.jp",
  90398. "onagawa.miyagi.jp",
  90399. "osaki.miyagi.jp",
  90400. "rifu.miyagi.jp",
  90401. "semine.miyagi.jp",
  90402. "shibata.miyagi.jp",
  90403. "shichikashuku.miyagi.jp",
  90404. "shikama.miyagi.jp",
  90405. "shiogama.miyagi.jp",
  90406. "shiroishi.miyagi.jp",
  90407. "tagajo.miyagi.jp",
  90408. "taiwa.miyagi.jp",
  90409. "tome.miyagi.jp",
  90410. "tomiya.miyagi.jp",
  90411. "wakuya.miyagi.jp",
  90412. "watari.miyagi.jp",
  90413. "yamamoto.miyagi.jp",
  90414. "zao.miyagi.jp",
  90415. "aya.miyazaki.jp",
  90416. "ebino.miyazaki.jp",
  90417. "gokase.miyazaki.jp",
  90418. "hyuga.miyazaki.jp",
  90419. "kadogawa.miyazaki.jp",
  90420. "kawaminami.miyazaki.jp",
  90421. "kijo.miyazaki.jp",
  90422. "kitagawa.miyazaki.jp",
  90423. "kitakata.miyazaki.jp",
  90424. "kitaura.miyazaki.jp",
  90425. "kobayashi.miyazaki.jp",
  90426. "kunitomi.miyazaki.jp",
  90427. "kushima.miyazaki.jp",
  90428. "mimata.miyazaki.jp",
  90429. "miyakonojo.miyazaki.jp",
  90430. "miyazaki.miyazaki.jp",
  90431. "morotsuka.miyazaki.jp",
  90432. "nichinan.miyazaki.jp",
  90433. "nishimera.miyazaki.jp",
  90434. "nobeoka.miyazaki.jp",
  90435. "saito.miyazaki.jp",
  90436. "shiiba.miyazaki.jp",
  90437. "shintomi.miyazaki.jp",
  90438. "takaharu.miyazaki.jp",
  90439. "takanabe.miyazaki.jp",
  90440. "takazaki.miyazaki.jp",
  90441. "tsuno.miyazaki.jp",
  90442. "achi.nagano.jp",
  90443. "agematsu.nagano.jp",
  90444. "anan.nagano.jp",
  90445. "aoki.nagano.jp",
  90446. "asahi.nagano.jp",
  90447. "azumino.nagano.jp",
  90448. "chikuhoku.nagano.jp",
  90449. "chikuma.nagano.jp",
  90450. "chino.nagano.jp",
  90451. "fujimi.nagano.jp",
  90452. "hakuba.nagano.jp",
  90453. "hara.nagano.jp",
  90454. "hiraya.nagano.jp",
  90455. "iida.nagano.jp",
  90456. "iijima.nagano.jp",
  90457. "iiyama.nagano.jp",
  90458. "iizuna.nagano.jp",
  90459. "ikeda.nagano.jp",
  90460. "ikusaka.nagano.jp",
  90461. "ina.nagano.jp",
  90462. "karuizawa.nagano.jp",
  90463. "kawakami.nagano.jp",
  90464. "kiso.nagano.jp",
  90465. "kisofukushima.nagano.jp",
  90466. "kitaaiki.nagano.jp",
  90467. "komagane.nagano.jp",
  90468. "komoro.nagano.jp",
  90469. "matsukawa.nagano.jp",
  90470. "matsumoto.nagano.jp",
  90471. "miasa.nagano.jp",
  90472. "minamiaiki.nagano.jp",
  90473. "minamimaki.nagano.jp",
  90474. "minamiminowa.nagano.jp",
  90475. "minowa.nagano.jp",
  90476. "miyada.nagano.jp",
  90477. "miyota.nagano.jp",
  90478. "mochizuki.nagano.jp",
  90479. "nagano.nagano.jp",
  90480. "nagawa.nagano.jp",
  90481. "nagiso.nagano.jp",
  90482. "nakagawa.nagano.jp",
  90483. "nakano.nagano.jp",
  90484. "nozawaonsen.nagano.jp",
  90485. "obuse.nagano.jp",
  90486. "ogawa.nagano.jp",
  90487. "okaya.nagano.jp",
  90488. "omachi.nagano.jp",
  90489. "omi.nagano.jp",
  90490. "ookuwa.nagano.jp",
  90491. "ooshika.nagano.jp",
  90492. "otaki.nagano.jp",
  90493. "otari.nagano.jp",
  90494. "sakae.nagano.jp",
  90495. "sakaki.nagano.jp",
  90496. "saku.nagano.jp",
  90497. "sakuho.nagano.jp",
  90498. "shimosuwa.nagano.jp",
  90499. "shinanomachi.nagano.jp",
  90500. "shiojiri.nagano.jp",
  90501. "suwa.nagano.jp",
  90502. "suzaka.nagano.jp",
  90503. "takagi.nagano.jp",
  90504. "takamori.nagano.jp",
  90505. "takayama.nagano.jp",
  90506. "tateshina.nagano.jp",
  90507. "tatsuno.nagano.jp",
  90508. "togakushi.nagano.jp",
  90509. "togura.nagano.jp",
  90510. "tomi.nagano.jp",
  90511. "ueda.nagano.jp",
  90512. "wada.nagano.jp",
  90513. "yamagata.nagano.jp",
  90514. "yamanouchi.nagano.jp",
  90515. "yasaka.nagano.jp",
  90516. "yasuoka.nagano.jp",
  90517. "chijiwa.nagasaki.jp",
  90518. "futsu.nagasaki.jp",
  90519. "goto.nagasaki.jp",
  90520. "hasami.nagasaki.jp",
  90521. "hirado.nagasaki.jp",
  90522. "iki.nagasaki.jp",
  90523. "isahaya.nagasaki.jp",
  90524. "kawatana.nagasaki.jp",
  90525. "kuchinotsu.nagasaki.jp",
  90526. "matsuura.nagasaki.jp",
  90527. "nagasaki.nagasaki.jp",
  90528. "obama.nagasaki.jp",
  90529. "omura.nagasaki.jp",
  90530. "oseto.nagasaki.jp",
  90531. "saikai.nagasaki.jp",
  90532. "sasebo.nagasaki.jp",
  90533. "seihi.nagasaki.jp",
  90534. "shimabara.nagasaki.jp",
  90535. "shinkamigoto.nagasaki.jp",
  90536. "togitsu.nagasaki.jp",
  90537. "tsushima.nagasaki.jp",
  90538. "unzen.nagasaki.jp",
  90539. "ando.nara.jp",
  90540. "gose.nara.jp",
  90541. "heguri.nara.jp",
  90542. "higashiyoshino.nara.jp",
  90543. "ikaruga.nara.jp",
  90544. "ikoma.nara.jp",
  90545. "kamikitayama.nara.jp",
  90546. "kanmaki.nara.jp",
  90547. "kashiba.nara.jp",
  90548. "kashihara.nara.jp",
  90549. "katsuragi.nara.jp",
  90550. "kawai.nara.jp",
  90551. "kawakami.nara.jp",
  90552. "kawanishi.nara.jp",
  90553. "koryo.nara.jp",
  90554. "kurotaki.nara.jp",
  90555. "mitsue.nara.jp",
  90556. "miyake.nara.jp",
  90557. "nara.nara.jp",
  90558. "nosegawa.nara.jp",
  90559. "oji.nara.jp",
  90560. "ouda.nara.jp",
  90561. "oyodo.nara.jp",
  90562. "sakurai.nara.jp",
  90563. "sango.nara.jp",
  90564. "shimoichi.nara.jp",
  90565. "shimokitayama.nara.jp",
  90566. "shinjo.nara.jp",
  90567. "soni.nara.jp",
  90568. "takatori.nara.jp",
  90569. "tawaramoto.nara.jp",
  90570. "tenkawa.nara.jp",
  90571. "tenri.nara.jp",
  90572. "uda.nara.jp",
  90573. "yamatokoriyama.nara.jp",
  90574. "yamatotakada.nara.jp",
  90575. "yamazoe.nara.jp",
  90576. "yoshino.nara.jp",
  90577. "aga.niigata.jp",
  90578. "agano.niigata.jp",
  90579. "gosen.niigata.jp",
  90580. "itoigawa.niigata.jp",
  90581. "izumozaki.niigata.jp",
  90582. "joetsu.niigata.jp",
  90583. "kamo.niigata.jp",
  90584. "kariwa.niigata.jp",
  90585. "kashiwazaki.niigata.jp",
  90586. "minamiuonuma.niigata.jp",
  90587. "mitsuke.niigata.jp",
  90588. "muika.niigata.jp",
  90589. "murakami.niigata.jp",
  90590. "myoko.niigata.jp",
  90591. "nagaoka.niigata.jp",
  90592. "niigata.niigata.jp",
  90593. "ojiya.niigata.jp",
  90594. "omi.niigata.jp",
  90595. "sado.niigata.jp",
  90596. "sanjo.niigata.jp",
  90597. "seiro.niigata.jp",
  90598. "seirou.niigata.jp",
  90599. "sekikawa.niigata.jp",
  90600. "shibata.niigata.jp",
  90601. "tagami.niigata.jp",
  90602. "tainai.niigata.jp",
  90603. "tochio.niigata.jp",
  90604. "tokamachi.niigata.jp",
  90605. "tsubame.niigata.jp",
  90606. "tsunan.niigata.jp",
  90607. "uonuma.niigata.jp",
  90608. "yahiko.niigata.jp",
  90609. "yoita.niigata.jp",
  90610. "yuzawa.niigata.jp",
  90611. "beppu.oita.jp",
  90612. "bungoono.oita.jp",
  90613. "bungotakada.oita.jp",
  90614. "hasama.oita.jp",
  90615. "hiji.oita.jp",
  90616. "himeshima.oita.jp",
  90617. "hita.oita.jp",
  90618. "kamitsue.oita.jp",
  90619. "kokonoe.oita.jp",
  90620. "kuju.oita.jp",
  90621. "kunisaki.oita.jp",
  90622. "kusu.oita.jp",
  90623. "oita.oita.jp",
  90624. "saiki.oita.jp",
  90625. "taketa.oita.jp",
  90626. "tsukumi.oita.jp",
  90627. "usa.oita.jp",
  90628. "usuki.oita.jp",
  90629. "yufu.oita.jp",
  90630. "akaiwa.okayama.jp",
  90631. "asakuchi.okayama.jp",
  90632. "bizen.okayama.jp",
  90633. "hayashima.okayama.jp",
  90634. "ibara.okayama.jp",
  90635. "kagamino.okayama.jp",
  90636. "kasaoka.okayama.jp",
  90637. "kibichuo.okayama.jp",
  90638. "kumenan.okayama.jp",
  90639. "kurashiki.okayama.jp",
  90640. "maniwa.okayama.jp",
  90641. "misaki.okayama.jp",
  90642. "nagi.okayama.jp",
  90643. "niimi.okayama.jp",
  90644. "nishiawakura.okayama.jp",
  90645. "okayama.okayama.jp",
  90646. "satosho.okayama.jp",
  90647. "setouchi.okayama.jp",
  90648. "shinjo.okayama.jp",
  90649. "shoo.okayama.jp",
  90650. "soja.okayama.jp",
  90651. "takahashi.okayama.jp",
  90652. "tamano.okayama.jp",
  90653. "tsuyama.okayama.jp",
  90654. "wake.okayama.jp",
  90655. "yakage.okayama.jp",
  90656. "aguni.okinawa.jp",
  90657. "ginowan.okinawa.jp",
  90658. "ginoza.okinawa.jp",
  90659. "gushikami.okinawa.jp",
  90660. "haebaru.okinawa.jp",
  90661. "higashi.okinawa.jp",
  90662. "hirara.okinawa.jp",
  90663. "iheya.okinawa.jp",
  90664. "ishigaki.okinawa.jp",
  90665. "ishikawa.okinawa.jp",
  90666. "itoman.okinawa.jp",
  90667. "izena.okinawa.jp",
  90668. "kadena.okinawa.jp",
  90669. "kin.okinawa.jp",
  90670. "kitadaito.okinawa.jp",
  90671. "kitanakagusuku.okinawa.jp",
  90672. "kumejima.okinawa.jp",
  90673. "kunigami.okinawa.jp",
  90674. "minamidaito.okinawa.jp",
  90675. "motobu.okinawa.jp",
  90676. "nago.okinawa.jp",
  90677. "naha.okinawa.jp",
  90678. "nakagusuku.okinawa.jp",
  90679. "nakijin.okinawa.jp",
  90680. "nanjo.okinawa.jp",
  90681. "nishihara.okinawa.jp",
  90682. "ogimi.okinawa.jp",
  90683. "okinawa.okinawa.jp",
  90684. "onna.okinawa.jp",
  90685. "shimoji.okinawa.jp",
  90686. "taketomi.okinawa.jp",
  90687. "tarama.okinawa.jp",
  90688. "tokashiki.okinawa.jp",
  90689. "tomigusuku.okinawa.jp",
  90690. "tonaki.okinawa.jp",
  90691. "urasoe.okinawa.jp",
  90692. "uruma.okinawa.jp",
  90693. "yaese.okinawa.jp",
  90694. "yomitan.okinawa.jp",
  90695. "yonabaru.okinawa.jp",
  90696. "yonaguni.okinawa.jp",
  90697. "zamami.okinawa.jp",
  90698. "abeno.osaka.jp",
  90699. "chihayaakasaka.osaka.jp",
  90700. "chuo.osaka.jp",
  90701. "daito.osaka.jp",
  90702. "fujiidera.osaka.jp",
  90703. "habikino.osaka.jp",
  90704. "hannan.osaka.jp",
  90705. "higashiosaka.osaka.jp",
  90706. "higashisumiyoshi.osaka.jp",
  90707. "higashiyodogawa.osaka.jp",
  90708. "hirakata.osaka.jp",
  90709. "ibaraki.osaka.jp",
  90710. "ikeda.osaka.jp",
  90711. "izumi.osaka.jp",
  90712. "izumiotsu.osaka.jp",
  90713. "izumisano.osaka.jp",
  90714. "kadoma.osaka.jp",
  90715. "kaizuka.osaka.jp",
  90716. "kanan.osaka.jp",
  90717. "kashiwara.osaka.jp",
  90718. "katano.osaka.jp",
  90719. "kawachinagano.osaka.jp",
  90720. "kishiwada.osaka.jp",
  90721. "kita.osaka.jp",
  90722. "kumatori.osaka.jp",
  90723. "matsubara.osaka.jp",
  90724. "minato.osaka.jp",
  90725. "minoh.osaka.jp",
  90726. "misaki.osaka.jp",
  90727. "moriguchi.osaka.jp",
  90728. "neyagawa.osaka.jp",
  90729. "nishi.osaka.jp",
  90730. "nose.osaka.jp",
  90731. "osakasayama.osaka.jp",
  90732. "sakai.osaka.jp",
  90733. "sayama.osaka.jp",
  90734. "sennan.osaka.jp",
  90735. "settsu.osaka.jp",
  90736. "shijonawate.osaka.jp",
  90737. "shimamoto.osaka.jp",
  90738. "suita.osaka.jp",
  90739. "tadaoka.osaka.jp",
  90740. "taishi.osaka.jp",
  90741. "tajiri.osaka.jp",
  90742. "takaishi.osaka.jp",
  90743. "takatsuki.osaka.jp",
  90744. "tondabayashi.osaka.jp",
  90745. "toyonaka.osaka.jp",
  90746. "toyono.osaka.jp",
  90747. "yao.osaka.jp",
  90748. "ariake.saga.jp",
  90749. "arita.saga.jp",
  90750. "fukudomi.saga.jp",
  90751. "genkai.saga.jp",
  90752. "hamatama.saga.jp",
  90753. "hizen.saga.jp",
  90754. "imari.saga.jp",
  90755. "kamimine.saga.jp",
  90756. "kanzaki.saga.jp",
  90757. "karatsu.saga.jp",
  90758. "kashima.saga.jp",
  90759. "kitagata.saga.jp",
  90760. "kitahata.saga.jp",
  90761. "kiyama.saga.jp",
  90762. "kouhoku.saga.jp",
  90763. "kyuragi.saga.jp",
  90764. "nishiarita.saga.jp",
  90765. "ogi.saga.jp",
  90766. "omachi.saga.jp",
  90767. "ouchi.saga.jp",
  90768. "saga.saga.jp",
  90769. "shiroishi.saga.jp",
  90770. "taku.saga.jp",
  90771. "tara.saga.jp",
  90772. "tosu.saga.jp",
  90773. "yoshinogari.saga.jp",
  90774. "arakawa.saitama.jp",
  90775. "asaka.saitama.jp",
  90776. "chichibu.saitama.jp",
  90777. "fujimi.saitama.jp",
  90778. "fujimino.saitama.jp",
  90779. "fukaya.saitama.jp",
  90780. "hanno.saitama.jp",
  90781. "hanyu.saitama.jp",
  90782. "hasuda.saitama.jp",
  90783. "hatogaya.saitama.jp",
  90784. "hatoyama.saitama.jp",
  90785. "hidaka.saitama.jp",
  90786. "higashichichibu.saitama.jp",
  90787. "higashimatsuyama.saitama.jp",
  90788. "honjo.saitama.jp",
  90789. "ina.saitama.jp",
  90790. "iruma.saitama.jp",
  90791. "iwatsuki.saitama.jp",
  90792. "kamiizumi.saitama.jp",
  90793. "kamikawa.saitama.jp",
  90794. "kamisato.saitama.jp",
  90795. "kasukabe.saitama.jp",
  90796. "kawagoe.saitama.jp",
  90797. "kawaguchi.saitama.jp",
  90798. "kawajima.saitama.jp",
  90799. "kazo.saitama.jp",
  90800. "kitamoto.saitama.jp",
  90801. "koshigaya.saitama.jp",
  90802. "kounosu.saitama.jp",
  90803. "kuki.saitama.jp",
  90804. "kumagaya.saitama.jp",
  90805. "matsubushi.saitama.jp",
  90806. "minano.saitama.jp",
  90807. "misato.saitama.jp",
  90808. "miyashiro.saitama.jp",
  90809. "miyoshi.saitama.jp",
  90810. "moroyama.saitama.jp",
  90811. "nagatoro.saitama.jp",
  90812. "namegawa.saitama.jp",
  90813. "niiza.saitama.jp",
  90814. "ogano.saitama.jp",
  90815. "ogawa.saitama.jp",
  90816. "ogose.saitama.jp",
  90817. "okegawa.saitama.jp",
  90818. "omiya.saitama.jp",
  90819. "otaki.saitama.jp",
  90820. "ranzan.saitama.jp",
  90821. "ryokami.saitama.jp",
  90822. "saitama.saitama.jp",
  90823. "sakado.saitama.jp",
  90824. "satte.saitama.jp",
  90825. "sayama.saitama.jp",
  90826. "shiki.saitama.jp",
  90827. "shiraoka.saitama.jp",
  90828. "soka.saitama.jp",
  90829. "sugito.saitama.jp",
  90830. "toda.saitama.jp",
  90831. "tokigawa.saitama.jp",
  90832. "tokorozawa.saitama.jp",
  90833. "tsurugashima.saitama.jp",
  90834. "urawa.saitama.jp",
  90835. "warabi.saitama.jp",
  90836. "yashio.saitama.jp",
  90837. "yokoze.saitama.jp",
  90838. "yono.saitama.jp",
  90839. "yorii.saitama.jp",
  90840. "yoshida.saitama.jp",
  90841. "yoshikawa.saitama.jp",
  90842. "yoshimi.saitama.jp",
  90843. "aisho.shiga.jp",
  90844. "gamo.shiga.jp",
  90845. "higashiomi.shiga.jp",
  90846. "hikone.shiga.jp",
  90847. "koka.shiga.jp",
  90848. "konan.shiga.jp",
  90849. "kosei.shiga.jp",
  90850. "koto.shiga.jp",
  90851. "kusatsu.shiga.jp",
  90852. "maibara.shiga.jp",
  90853. "moriyama.shiga.jp",
  90854. "nagahama.shiga.jp",
  90855. "nishiazai.shiga.jp",
  90856. "notogawa.shiga.jp",
  90857. "omihachiman.shiga.jp",
  90858. "otsu.shiga.jp",
  90859. "ritto.shiga.jp",
  90860. "ryuoh.shiga.jp",
  90861. "takashima.shiga.jp",
  90862. "takatsuki.shiga.jp",
  90863. "torahime.shiga.jp",
  90864. "toyosato.shiga.jp",
  90865. "yasu.shiga.jp",
  90866. "akagi.shimane.jp",
  90867. "ama.shimane.jp",
  90868. "gotsu.shimane.jp",
  90869. "hamada.shimane.jp",
  90870. "higashiizumo.shimane.jp",
  90871. "hikawa.shimane.jp",
  90872. "hikimi.shimane.jp",
  90873. "izumo.shimane.jp",
  90874. "kakinoki.shimane.jp",
  90875. "masuda.shimane.jp",
  90876. "matsue.shimane.jp",
  90877. "misato.shimane.jp",
  90878. "nishinoshima.shimane.jp",
  90879. "ohda.shimane.jp",
  90880. "okinoshima.shimane.jp",
  90881. "okuizumo.shimane.jp",
  90882. "shimane.shimane.jp",
  90883. "tamayu.shimane.jp",
  90884. "tsuwano.shimane.jp",
  90885. "unnan.shimane.jp",
  90886. "yakumo.shimane.jp",
  90887. "yasugi.shimane.jp",
  90888. "yatsuka.shimane.jp",
  90889. "arai.shizuoka.jp",
  90890. "atami.shizuoka.jp",
  90891. "fuji.shizuoka.jp",
  90892. "fujieda.shizuoka.jp",
  90893. "fujikawa.shizuoka.jp",
  90894. "fujinomiya.shizuoka.jp",
  90895. "fukuroi.shizuoka.jp",
  90896. "gotemba.shizuoka.jp",
  90897. "haibara.shizuoka.jp",
  90898. "hamamatsu.shizuoka.jp",
  90899. "higashiizu.shizuoka.jp",
  90900. "ito.shizuoka.jp",
  90901. "iwata.shizuoka.jp",
  90902. "izu.shizuoka.jp",
  90903. "izunokuni.shizuoka.jp",
  90904. "kakegawa.shizuoka.jp",
  90905. "kannami.shizuoka.jp",
  90906. "kawanehon.shizuoka.jp",
  90907. "kawazu.shizuoka.jp",
  90908. "kikugawa.shizuoka.jp",
  90909. "kosai.shizuoka.jp",
  90910. "makinohara.shizuoka.jp",
  90911. "matsuzaki.shizuoka.jp",
  90912. "minamiizu.shizuoka.jp",
  90913. "mishima.shizuoka.jp",
  90914. "morimachi.shizuoka.jp",
  90915. "nishiizu.shizuoka.jp",
  90916. "numazu.shizuoka.jp",
  90917. "omaezaki.shizuoka.jp",
  90918. "shimada.shizuoka.jp",
  90919. "shimizu.shizuoka.jp",
  90920. "shimoda.shizuoka.jp",
  90921. "shizuoka.shizuoka.jp",
  90922. "susono.shizuoka.jp",
  90923. "yaizu.shizuoka.jp",
  90924. "yoshida.shizuoka.jp",
  90925. "ashikaga.tochigi.jp",
  90926. "bato.tochigi.jp",
  90927. "haga.tochigi.jp",
  90928. "ichikai.tochigi.jp",
  90929. "iwafune.tochigi.jp",
  90930. "kaminokawa.tochigi.jp",
  90931. "kanuma.tochigi.jp",
  90932. "karasuyama.tochigi.jp",
  90933. "kuroiso.tochigi.jp",
  90934. "mashiko.tochigi.jp",
  90935. "mibu.tochigi.jp",
  90936. "moka.tochigi.jp",
  90937. "motegi.tochigi.jp",
  90938. "nasu.tochigi.jp",
  90939. "nasushiobara.tochigi.jp",
  90940. "nikko.tochigi.jp",
  90941. "nishikata.tochigi.jp",
  90942. "nogi.tochigi.jp",
  90943. "ohira.tochigi.jp",
  90944. "ohtawara.tochigi.jp",
  90945. "oyama.tochigi.jp",
  90946. "sakura.tochigi.jp",
  90947. "sano.tochigi.jp",
  90948. "shimotsuke.tochigi.jp",
  90949. "shioya.tochigi.jp",
  90950. "takanezawa.tochigi.jp",
  90951. "tochigi.tochigi.jp",
  90952. "tsuga.tochigi.jp",
  90953. "ujiie.tochigi.jp",
  90954. "utsunomiya.tochigi.jp",
  90955. "yaita.tochigi.jp",
  90956. "aizumi.tokushima.jp",
  90957. "anan.tokushima.jp",
  90958. "ichiba.tokushima.jp",
  90959. "itano.tokushima.jp",
  90960. "kainan.tokushima.jp",
  90961. "komatsushima.tokushima.jp",
  90962. "matsushige.tokushima.jp",
  90963. "mima.tokushima.jp",
  90964. "minami.tokushima.jp",
  90965. "miyoshi.tokushima.jp",
  90966. "mugi.tokushima.jp",
  90967. "nakagawa.tokushima.jp",
  90968. "naruto.tokushima.jp",
  90969. "sanagochi.tokushima.jp",
  90970. "shishikui.tokushima.jp",
  90971. "tokushima.tokushima.jp",
  90972. "wajiki.tokushima.jp",
  90973. "adachi.tokyo.jp",
  90974. "akiruno.tokyo.jp",
  90975. "akishima.tokyo.jp",
  90976. "aogashima.tokyo.jp",
  90977. "arakawa.tokyo.jp",
  90978. "bunkyo.tokyo.jp",
  90979. "chiyoda.tokyo.jp",
  90980. "chofu.tokyo.jp",
  90981. "chuo.tokyo.jp",
  90982. "edogawa.tokyo.jp",
  90983. "fuchu.tokyo.jp",
  90984. "fussa.tokyo.jp",
  90985. "hachijo.tokyo.jp",
  90986. "hachioji.tokyo.jp",
  90987. "hamura.tokyo.jp",
  90988. "higashikurume.tokyo.jp",
  90989. "higashimurayama.tokyo.jp",
  90990. "higashiyamato.tokyo.jp",
  90991. "hino.tokyo.jp",
  90992. "hinode.tokyo.jp",
  90993. "hinohara.tokyo.jp",
  90994. "inagi.tokyo.jp",
  90995. "itabashi.tokyo.jp",
  90996. "katsushika.tokyo.jp",
  90997. "kita.tokyo.jp",
  90998. "kiyose.tokyo.jp",
  90999. "kodaira.tokyo.jp",
  91000. "koganei.tokyo.jp",
  91001. "kokubunji.tokyo.jp",
  91002. "komae.tokyo.jp",
  91003. "koto.tokyo.jp",
  91004. "kouzushima.tokyo.jp",
  91005. "kunitachi.tokyo.jp",
  91006. "machida.tokyo.jp",
  91007. "meguro.tokyo.jp",
  91008. "minato.tokyo.jp",
  91009. "mitaka.tokyo.jp",
  91010. "mizuho.tokyo.jp",
  91011. "musashimurayama.tokyo.jp",
  91012. "musashino.tokyo.jp",
  91013. "nakano.tokyo.jp",
  91014. "nerima.tokyo.jp",
  91015. "ogasawara.tokyo.jp",
  91016. "okutama.tokyo.jp",
  91017. "ome.tokyo.jp",
  91018. "oshima.tokyo.jp",
  91019. "ota.tokyo.jp",
  91020. "setagaya.tokyo.jp",
  91021. "shibuya.tokyo.jp",
  91022. "shinagawa.tokyo.jp",
  91023. "shinjuku.tokyo.jp",
  91024. "suginami.tokyo.jp",
  91025. "sumida.tokyo.jp",
  91026. "tachikawa.tokyo.jp",
  91027. "taito.tokyo.jp",
  91028. "tama.tokyo.jp",
  91029. "toshima.tokyo.jp",
  91030. "chizu.tottori.jp",
  91031. "hino.tottori.jp",
  91032. "kawahara.tottori.jp",
  91033. "koge.tottori.jp",
  91034. "kotoura.tottori.jp",
  91035. "misasa.tottori.jp",
  91036. "nanbu.tottori.jp",
  91037. "nichinan.tottori.jp",
  91038. "sakaiminato.tottori.jp",
  91039. "tottori.tottori.jp",
  91040. "wakasa.tottori.jp",
  91041. "yazu.tottori.jp",
  91042. "yonago.tottori.jp",
  91043. "asahi.toyama.jp",
  91044. "fuchu.toyama.jp",
  91045. "fukumitsu.toyama.jp",
  91046. "funahashi.toyama.jp",
  91047. "himi.toyama.jp",
  91048. "imizu.toyama.jp",
  91049. "inami.toyama.jp",
  91050. "johana.toyama.jp",
  91051. "kamiichi.toyama.jp",
  91052. "kurobe.toyama.jp",
  91053. "nakaniikawa.toyama.jp",
  91054. "namerikawa.toyama.jp",
  91055. "nanto.toyama.jp",
  91056. "nyuzen.toyama.jp",
  91057. "oyabe.toyama.jp",
  91058. "taira.toyama.jp",
  91059. "takaoka.toyama.jp",
  91060. "tateyama.toyama.jp",
  91061. "toga.toyama.jp",
  91062. "tonami.toyama.jp",
  91063. "toyama.toyama.jp",
  91064. "unazuki.toyama.jp",
  91065. "uozu.toyama.jp",
  91066. "yamada.toyama.jp",
  91067. "arida.wakayama.jp",
  91068. "aridagawa.wakayama.jp",
  91069. "gobo.wakayama.jp",
  91070. "hashimoto.wakayama.jp",
  91071. "hidaka.wakayama.jp",
  91072. "hirogawa.wakayama.jp",
  91073. "inami.wakayama.jp",
  91074. "iwade.wakayama.jp",
  91075. "kainan.wakayama.jp",
  91076. "kamitonda.wakayama.jp",
  91077. "katsuragi.wakayama.jp",
  91078. "kimino.wakayama.jp",
  91079. "kinokawa.wakayama.jp",
  91080. "kitayama.wakayama.jp",
  91081. "koya.wakayama.jp",
  91082. "koza.wakayama.jp",
  91083. "kozagawa.wakayama.jp",
  91084. "kudoyama.wakayama.jp",
  91085. "kushimoto.wakayama.jp",
  91086. "mihama.wakayama.jp",
  91087. "misato.wakayama.jp",
  91088. "nachikatsuura.wakayama.jp",
  91089. "shingu.wakayama.jp",
  91090. "shirahama.wakayama.jp",
  91091. "taiji.wakayama.jp",
  91092. "tanabe.wakayama.jp",
  91093. "wakayama.wakayama.jp",
  91094. "yuasa.wakayama.jp",
  91095. "yura.wakayama.jp",
  91096. "asahi.yamagata.jp",
  91097. "funagata.yamagata.jp",
  91098. "higashine.yamagata.jp",
  91099. "iide.yamagata.jp",
  91100. "kahoku.yamagata.jp",
  91101. "kaminoyama.yamagata.jp",
  91102. "kaneyama.yamagata.jp",
  91103. "kawanishi.yamagata.jp",
  91104. "mamurogawa.yamagata.jp",
  91105. "mikawa.yamagata.jp",
  91106. "murayama.yamagata.jp",
  91107. "nagai.yamagata.jp",
  91108. "nakayama.yamagata.jp",
  91109. "nanyo.yamagata.jp",
  91110. "nishikawa.yamagata.jp",
  91111. "obanazawa.yamagata.jp",
  91112. "oe.yamagata.jp",
  91113. "oguni.yamagata.jp",
  91114. "ohkura.yamagata.jp",
  91115. "oishida.yamagata.jp",
  91116. "sagae.yamagata.jp",
  91117. "sakata.yamagata.jp",
  91118. "sakegawa.yamagata.jp",
  91119. "shinjo.yamagata.jp",
  91120. "shirataka.yamagata.jp",
  91121. "shonai.yamagata.jp",
  91122. "takahata.yamagata.jp",
  91123. "tendo.yamagata.jp",
  91124. "tozawa.yamagata.jp",
  91125. "tsuruoka.yamagata.jp",
  91126. "yamagata.yamagata.jp",
  91127. "yamanobe.yamagata.jp",
  91128. "yonezawa.yamagata.jp",
  91129. "yuza.yamagata.jp",
  91130. "abu.yamaguchi.jp",
  91131. "hagi.yamaguchi.jp",
  91132. "hikari.yamaguchi.jp",
  91133. "hofu.yamaguchi.jp",
  91134. "iwakuni.yamaguchi.jp",
  91135. "kudamatsu.yamaguchi.jp",
  91136. "mitou.yamaguchi.jp",
  91137. "nagato.yamaguchi.jp",
  91138. "oshima.yamaguchi.jp",
  91139. "shimonoseki.yamaguchi.jp",
  91140. "shunan.yamaguchi.jp",
  91141. "tabuse.yamaguchi.jp",
  91142. "tokuyama.yamaguchi.jp",
  91143. "toyota.yamaguchi.jp",
  91144. "ube.yamaguchi.jp",
  91145. "yuu.yamaguchi.jp",
  91146. "chuo.yamanashi.jp",
  91147. "doshi.yamanashi.jp",
  91148. "fuefuki.yamanashi.jp",
  91149. "fujikawa.yamanashi.jp",
  91150. "fujikawaguchiko.yamanashi.jp",
  91151. "fujiyoshida.yamanashi.jp",
  91152. "hayakawa.yamanashi.jp",
  91153. "hokuto.yamanashi.jp",
  91154. "ichikawamisato.yamanashi.jp",
  91155. "kai.yamanashi.jp",
  91156. "kofu.yamanashi.jp",
  91157. "koshu.yamanashi.jp",
  91158. "kosuge.yamanashi.jp",
  91159. "minami-alps.yamanashi.jp",
  91160. "minobu.yamanashi.jp",
  91161. "nakamichi.yamanashi.jp",
  91162. "nanbu.yamanashi.jp",
  91163. "narusawa.yamanashi.jp",
  91164. "nirasaki.yamanashi.jp",
  91165. "nishikatsura.yamanashi.jp",
  91166. "oshino.yamanashi.jp",
  91167. "otsuki.yamanashi.jp",
  91168. "showa.yamanashi.jp",
  91169. "tabayama.yamanashi.jp",
  91170. "tsuru.yamanashi.jp",
  91171. "uenohara.yamanashi.jp",
  91172. "yamanakako.yamanashi.jp",
  91173. "yamanashi.yamanashi.jp",
  91174. "ke",
  91175. "ac.ke",
  91176. "co.ke",
  91177. "go.ke",
  91178. "info.ke",
  91179. "me.ke",
  91180. "mobi.ke",
  91181. "ne.ke",
  91182. "or.ke",
  91183. "sc.ke",
  91184. "kg",
  91185. "org.kg",
  91186. "net.kg",
  91187. "com.kg",
  91188. "edu.kg",
  91189. "gov.kg",
  91190. "mil.kg",
  91191. "*.kh",
  91192. "ki",
  91193. "edu.ki",
  91194. "biz.ki",
  91195. "net.ki",
  91196. "org.ki",
  91197. "gov.ki",
  91198. "info.ki",
  91199. "com.ki",
  91200. "km",
  91201. "org.km",
  91202. "nom.km",
  91203. "gov.km",
  91204. "prd.km",
  91205. "tm.km",
  91206. "edu.km",
  91207. "mil.km",
  91208. "ass.km",
  91209. "com.km",
  91210. "coop.km",
  91211. "asso.km",
  91212. "presse.km",
  91213. "medecin.km",
  91214. "notaires.km",
  91215. "pharmaciens.km",
  91216. "veterinaire.km",
  91217. "gouv.km",
  91218. "kn",
  91219. "net.kn",
  91220. "org.kn",
  91221. "edu.kn",
  91222. "gov.kn",
  91223. "kp",
  91224. "com.kp",
  91225. "edu.kp",
  91226. "gov.kp",
  91227. "org.kp",
  91228. "rep.kp",
  91229. "tra.kp",
  91230. "kr",
  91231. "ac.kr",
  91232. "co.kr",
  91233. "es.kr",
  91234. "go.kr",
  91235. "hs.kr",
  91236. "kg.kr",
  91237. "mil.kr",
  91238. "ms.kr",
  91239. "ne.kr",
  91240. "or.kr",
  91241. "pe.kr",
  91242. "re.kr",
  91243. "sc.kr",
  91244. "busan.kr",
  91245. "chungbuk.kr",
  91246. "chungnam.kr",
  91247. "daegu.kr",
  91248. "daejeon.kr",
  91249. "gangwon.kr",
  91250. "gwangju.kr",
  91251. "gyeongbuk.kr",
  91252. "gyeonggi.kr",
  91253. "gyeongnam.kr",
  91254. "incheon.kr",
  91255. "jeju.kr",
  91256. "jeonbuk.kr",
  91257. "jeonnam.kr",
  91258. "seoul.kr",
  91259. "ulsan.kr",
  91260. "kw",
  91261. "com.kw",
  91262. "edu.kw",
  91263. "emb.kw",
  91264. "gov.kw",
  91265. "ind.kw",
  91266. "net.kw",
  91267. "org.kw",
  91268. "ky",
  91269. "edu.ky",
  91270. "gov.ky",
  91271. "com.ky",
  91272. "org.ky",
  91273. "net.ky",
  91274. "kz",
  91275. "org.kz",
  91276. "edu.kz",
  91277. "net.kz",
  91278. "gov.kz",
  91279. "mil.kz",
  91280. "com.kz",
  91281. "la",
  91282. "int.la",
  91283. "net.la",
  91284. "info.la",
  91285. "edu.la",
  91286. "gov.la",
  91287. "per.la",
  91288. "com.la",
  91289. "org.la",
  91290. "lb",
  91291. "com.lb",
  91292. "edu.lb",
  91293. "gov.lb",
  91294. "net.lb",
  91295. "org.lb",
  91296. "lc",
  91297. "com.lc",
  91298. "net.lc",
  91299. "co.lc",
  91300. "org.lc",
  91301. "edu.lc",
  91302. "gov.lc",
  91303. "li",
  91304. "lk",
  91305. "gov.lk",
  91306. "sch.lk",
  91307. "net.lk",
  91308. "int.lk",
  91309. "com.lk",
  91310. "org.lk",
  91311. "edu.lk",
  91312. "ngo.lk",
  91313. "soc.lk",
  91314. "web.lk",
  91315. "ltd.lk",
  91316. "assn.lk",
  91317. "grp.lk",
  91318. "hotel.lk",
  91319. "ac.lk",
  91320. "lr",
  91321. "com.lr",
  91322. "edu.lr",
  91323. "gov.lr",
  91324. "org.lr",
  91325. "net.lr",
  91326. "ls",
  91327. "ac.ls",
  91328. "biz.ls",
  91329. "co.ls",
  91330. "edu.ls",
  91331. "gov.ls",
  91332. "info.ls",
  91333. "net.ls",
  91334. "org.ls",
  91335. "sc.ls",
  91336. "lt",
  91337. "gov.lt",
  91338. "lu",
  91339. "lv",
  91340. "com.lv",
  91341. "edu.lv",
  91342. "gov.lv",
  91343. "org.lv",
  91344. "mil.lv",
  91345. "id.lv",
  91346. "net.lv",
  91347. "asn.lv",
  91348. "conf.lv",
  91349. "ly",
  91350. "com.ly",
  91351. "net.ly",
  91352. "gov.ly",
  91353. "plc.ly",
  91354. "edu.ly",
  91355. "sch.ly",
  91356. "med.ly",
  91357. "org.ly",
  91358. "id.ly",
  91359. "ma",
  91360. "co.ma",
  91361. "net.ma",
  91362. "gov.ma",
  91363. "org.ma",
  91364. "ac.ma",
  91365. "press.ma",
  91366. "mc",
  91367. "tm.mc",
  91368. "asso.mc",
  91369. "md",
  91370. "me",
  91371. "co.me",
  91372. "net.me",
  91373. "org.me",
  91374. "edu.me",
  91375. "ac.me",
  91376. "gov.me",
  91377. "its.me",
  91378. "priv.me",
  91379. "mg",
  91380. "org.mg",
  91381. "nom.mg",
  91382. "gov.mg",
  91383. "prd.mg",
  91384. "tm.mg",
  91385. "edu.mg",
  91386. "mil.mg",
  91387. "com.mg",
  91388. "co.mg",
  91389. "mh",
  91390. "mil",
  91391. "mk",
  91392. "com.mk",
  91393. "org.mk",
  91394. "net.mk",
  91395. "edu.mk",
  91396. "gov.mk",
  91397. "inf.mk",
  91398. "name.mk",
  91399. "ml",
  91400. "com.ml",
  91401. "edu.ml",
  91402. "gouv.ml",
  91403. "gov.ml",
  91404. "net.ml",
  91405. "org.ml",
  91406. "presse.ml",
  91407. "*.mm",
  91408. "mn",
  91409. "gov.mn",
  91410. "edu.mn",
  91411. "org.mn",
  91412. "mo",
  91413. "com.mo",
  91414. "net.mo",
  91415. "org.mo",
  91416. "edu.mo",
  91417. "gov.mo",
  91418. "mobi",
  91419. "mp",
  91420. "mq",
  91421. "mr",
  91422. "gov.mr",
  91423. "ms",
  91424. "com.ms",
  91425. "edu.ms",
  91426. "gov.ms",
  91427. "net.ms",
  91428. "org.ms",
  91429. "mt",
  91430. "com.mt",
  91431. "edu.mt",
  91432. "net.mt",
  91433. "org.mt",
  91434. "mu",
  91435. "com.mu",
  91436. "net.mu",
  91437. "org.mu",
  91438. "gov.mu",
  91439. "ac.mu",
  91440. "co.mu",
  91441. "or.mu",
  91442. "museum",
  91443. "academy.museum",
  91444. "agriculture.museum",
  91445. "air.museum",
  91446. "airguard.museum",
  91447. "alabama.museum",
  91448. "alaska.museum",
  91449. "amber.museum",
  91450. "ambulance.museum",
  91451. "american.museum",
  91452. "americana.museum",
  91453. "americanantiques.museum",
  91454. "americanart.museum",
  91455. "amsterdam.museum",
  91456. "and.museum",
  91457. "annefrank.museum",
  91458. "anthro.museum",
  91459. "anthropology.museum",
  91460. "antiques.museum",
  91461. "aquarium.museum",
  91462. "arboretum.museum",
  91463. "archaeological.museum",
  91464. "archaeology.museum",
  91465. "architecture.museum",
  91466. "art.museum",
  91467. "artanddesign.museum",
  91468. "artcenter.museum",
  91469. "artdeco.museum",
  91470. "arteducation.museum",
  91471. "artgallery.museum",
  91472. "arts.museum",
  91473. "artsandcrafts.museum",
  91474. "asmatart.museum",
  91475. "assassination.museum",
  91476. "assisi.museum",
  91477. "association.museum",
  91478. "astronomy.museum",
  91479. "atlanta.museum",
  91480. "austin.museum",
  91481. "australia.museum",
  91482. "automotive.museum",
  91483. "aviation.museum",
  91484. "axis.museum",
  91485. "badajoz.museum",
  91486. "baghdad.museum",
  91487. "bahn.museum",
  91488. "bale.museum",
  91489. "baltimore.museum",
  91490. "barcelona.museum",
  91491. "baseball.museum",
  91492. "basel.museum",
  91493. "baths.museum",
  91494. "bauern.museum",
  91495. "beauxarts.museum",
  91496. "beeldengeluid.museum",
  91497. "bellevue.museum",
  91498. "bergbau.museum",
  91499. "berkeley.museum",
  91500. "berlin.museum",
  91501. "bern.museum",
  91502. "bible.museum",
  91503. "bilbao.museum",
  91504. "bill.museum",
  91505. "birdart.museum",
  91506. "birthplace.museum",
  91507. "bonn.museum",
  91508. "boston.museum",
  91509. "botanical.museum",
  91510. "botanicalgarden.museum",
  91511. "botanicgarden.museum",
  91512. "botany.museum",
  91513. "brandywinevalley.museum",
  91514. "brasil.museum",
  91515. "bristol.museum",
  91516. "british.museum",
  91517. "britishcolumbia.museum",
  91518. "broadcast.museum",
  91519. "brunel.museum",
  91520. "brussel.museum",
  91521. "brussels.museum",
  91522. "bruxelles.museum",
  91523. "building.museum",
  91524. "burghof.museum",
  91525. "bus.museum",
  91526. "bushey.museum",
  91527. "cadaques.museum",
  91528. "california.museum",
  91529. "cambridge.museum",
  91530. "can.museum",
  91531. "canada.museum",
  91532. "capebreton.museum",
  91533. "carrier.museum",
  91534. "cartoonart.museum",
  91535. "casadelamoneda.museum",
  91536. "castle.museum",
  91537. "castres.museum",
  91538. "celtic.museum",
  91539. "center.museum",
  91540. "chattanooga.museum",
  91541. "cheltenham.museum",
  91542. "chesapeakebay.museum",
  91543. "chicago.museum",
  91544. "children.museum",
  91545. "childrens.museum",
  91546. "childrensgarden.museum",
  91547. "chiropractic.museum",
  91548. "chocolate.museum",
  91549. "christiansburg.museum",
  91550. "cincinnati.museum",
  91551. "cinema.museum",
  91552. "circus.museum",
  91553. "civilisation.museum",
  91554. "civilization.museum",
  91555. "civilwar.museum",
  91556. "clinton.museum",
  91557. "clock.museum",
  91558. "coal.museum",
  91559. "coastaldefence.museum",
  91560. "cody.museum",
  91561. "coldwar.museum",
  91562. "collection.museum",
  91563. "colonialwilliamsburg.museum",
  91564. "coloradoplateau.museum",
  91565. "columbia.museum",
  91566. "columbus.museum",
  91567. "communication.museum",
  91568. "communications.museum",
  91569. "community.museum",
  91570. "computer.museum",
  91571. "computerhistory.museum",
  91572. "comunicações.museum",
  91573. "contemporary.museum",
  91574. "contemporaryart.museum",
  91575. "convent.museum",
  91576. "copenhagen.museum",
  91577. "corporation.museum",
  91578. "correios-e-telecomunicações.museum",
  91579. "corvette.museum",
  91580. "costume.museum",
  91581. "countryestate.museum",
  91582. "county.museum",
  91583. "crafts.museum",
  91584. "cranbrook.museum",
  91585. "creation.museum",
  91586. "cultural.museum",
  91587. "culturalcenter.museum",
  91588. "culture.museum",
  91589. "cyber.museum",
  91590. "cymru.museum",
  91591. "dali.museum",
  91592. "dallas.museum",
  91593. "database.museum",
  91594. "ddr.museum",
  91595. "decorativearts.museum",
  91596. "delaware.museum",
  91597. "delmenhorst.museum",
  91598. "denmark.museum",
  91599. "depot.museum",
  91600. "design.museum",
  91601. "detroit.museum",
  91602. "dinosaur.museum",
  91603. "discovery.museum",
  91604. "dolls.museum",
  91605. "donostia.museum",
  91606. "durham.museum",
  91607. "eastafrica.museum",
  91608. "eastcoast.museum",
  91609. "education.museum",
  91610. "educational.museum",
  91611. "egyptian.museum",
  91612. "eisenbahn.museum",
  91613. "elburg.museum",
  91614. "elvendrell.museum",
  91615. "embroidery.museum",
  91616. "encyclopedic.museum",
  91617. "england.museum",
  91618. "entomology.museum",
  91619. "environment.museum",
  91620. "environmentalconservation.museum",
  91621. "epilepsy.museum",
  91622. "essex.museum",
  91623. "estate.museum",
  91624. "ethnology.museum",
  91625. "exeter.museum",
  91626. "exhibition.museum",
  91627. "family.museum",
  91628. "farm.museum",
  91629. "farmequipment.museum",
  91630. "farmers.museum",
  91631. "farmstead.museum",
  91632. "field.museum",
  91633. "figueres.museum",
  91634. "filatelia.museum",
  91635. "film.museum",
  91636. "fineart.museum",
  91637. "finearts.museum",
  91638. "finland.museum",
  91639. "flanders.museum",
  91640. "florida.museum",
  91641. "force.museum",
  91642. "fortmissoula.museum",
  91643. "fortworth.museum",
  91644. "foundation.museum",
  91645. "francaise.museum",
  91646. "frankfurt.museum",
  91647. "franziskaner.museum",
  91648. "freemasonry.museum",
  91649. "freiburg.museum",
  91650. "fribourg.museum",
  91651. "frog.museum",
  91652. "fundacio.museum",
  91653. "furniture.museum",
  91654. "gallery.museum",
  91655. "garden.museum",
  91656. "gateway.museum",
  91657. "geelvinck.museum",
  91658. "gemological.museum",
  91659. "geology.museum",
  91660. "georgia.museum",
  91661. "giessen.museum",
  91662. "glas.museum",
  91663. "glass.museum",
  91664. "gorge.museum",
  91665. "grandrapids.museum",
  91666. "graz.museum",
  91667. "guernsey.museum",
  91668. "halloffame.museum",
  91669. "hamburg.museum",
  91670. "handson.museum",
  91671. "harvestcelebration.museum",
  91672. "hawaii.museum",
  91673. "health.museum",
  91674. "heimatunduhren.museum",
  91675. "hellas.museum",
  91676. "helsinki.museum",
  91677. "hembygdsforbund.museum",
  91678. "heritage.museum",
  91679. "histoire.museum",
  91680. "historical.museum",
  91681. "historicalsociety.museum",
  91682. "historichouses.museum",
  91683. "historisch.museum",
  91684. "historisches.museum",
  91685. "history.museum",
  91686. "historyofscience.museum",
  91687. "horology.museum",
  91688. "house.museum",
  91689. "humanities.museum",
  91690. "illustration.museum",
  91691. "imageandsound.museum",
  91692. "indian.museum",
  91693. "indiana.museum",
  91694. "indianapolis.museum",
  91695. "indianmarket.museum",
  91696. "intelligence.museum",
  91697. "interactive.museum",
  91698. "iraq.museum",
  91699. "iron.museum",
  91700. "isleofman.museum",
  91701. "jamison.museum",
  91702. "jefferson.museum",
  91703. "jerusalem.museum",
  91704. "jewelry.museum",
  91705. "jewish.museum",
  91706. "jewishart.museum",
  91707. "jfk.museum",
  91708. "journalism.museum",
  91709. "judaica.museum",
  91710. "judygarland.museum",
  91711. "juedisches.museum",
  91712. "juif.museum",
  91713. "karate.museum",
  91714. "karikatur.museum",
  91715. "kids.museum",
  91716. "koebenhavn.museum",
  91717. "koeln.museum",
  91718. "kunst.museum",
  91719. "kunstsammlung.museum",
  91720. "kunstunddesign.museum",
  91721. "labor.museum",
  91722. "labour.museum",
  91723. "lajolla.museum",
  91724. "lancashire.museum",
  91725. "landes.museum",
  91726. "lans.museum",
  91727. "läns.museum",
  91728. "larsson.museum",
  91729. "lewismiller.museum",
  91730. "lincoln.museum",
  91731. "linz.museum",
  91732. "living.museum",
  91733. "livinghistory.museum",
  91734. "localhistory.museum",
  91735. "london.museum",
  91736. "losangeles.museum",
  91737. "louvre.museum",
  91738. "loyalist.museum",
  91739. "lucerne.museum",
  91740. "luxembourg.museum",
  91741. "luzern.museum",
  91742. "mad.museum",
  91743. "madrid.museum",
  91744. "mallorca.museum",
  91745. "manchester.museum",
  91746. "mansion.museum",
  91747. "mansions.museum",
  91748. "manx.museum",
  91749. "marburg.museum",
  91750. "maritime.museum",
  91751. "maritimo.museum",
  91752. "maryland.museum",
  91753. "marylhurst.museum",
  91754. "media.museum",
  91755. "medical.museum",
  91756. "medizinhistorisches.museum",
  91757. "meeres.museum",
  91758. "memorial.museum",
  91759. "mesaverde.museum",
  91760. "michigan.museum",
  91761. "midatlantic.museum",
  91762. "military.museum",
  91763. "mill.museum",
  91764. "miners.museum",
  91765. "mining.museum",
  91766. "minnesota.museum",
  91767. "missile.museum",
  91768. "missoula.museum",
  91769. "modern.museum",
  91770. "moma.museum",
  91771. "money.museum",
  91772. "monmouth.museum",
  91773. "monticello.museum",
  91774. "montreal.museum",
  91775. "moscow.museum",
  91776. "motorcycle.museum",
  91777. "muenchen.museum",
  91778. "muenster.museum",
  91779. "mulhouse.museum",
  91780. "muncie.museum",
  91781. "museet.museum",
  91782. "museumcenter.museum",
  91783. "museumvereniging.museum",
  91784. "music.museum",
  91785. "national.museum",
  91786. "nationalfirearms.museum",
  91787. "nationalheritage.museum",
  91788. "nativeamerican.museum",
  91789. "naturalhistory.museum",
  91790. "naturalhistorymuseum.museum",
  91791. "naturalsciences.museum",
  91792. "nature.museum",
  91793. "naturhistorisches.museum",
  91794. "natuurwetenschappen.museum",
  91795. "naumburg.museum",
  91796. "naval.museum",
  91797. "nebraska.museum",
  91798. "neues.museum",
  91799. "newhampshire.museum",
  91800. "newjersey.museum",
  91801. "newmexico.museum",
  91802. "newport.museum",
  91803. "newspaper.museum",
  91804. "newyork.museum",
  91805. "niepce.museum",
  91806. "norfolk.museum",
  91807. "north.museum",
  91808. "nrw.museum",
  91809. "nyc.museum",
  91810. "nyny.museum",
  91811. "oceanographic.museum",
  91812. "oceanographique.museum",
  91813. "omaha.museum",
  91814. "online.museum",
  91815. "ontario.museum",
  91816. "openair.museum",
  91817. "oregon.museum",
  91818. "oregontrail.museum",
  91819. "otago.museum",
  91820. "oxford.museum",
  91821. "pacific.museum",
  91822. "paderborn.museum",
  91823. "palace.museum",
  91824. "paleo.museum",
  91825. "palmsprings.museum",
  91826. "panama.museum",
  91827. "paris.museum",
  91828. "pasadena.museum",
  91829. "pharmacy.museum",
  91830. "philadelphia.museum",
  91831. "philadelphiaarea.museum",
  91832. "philately.museum",
  91833. "phoenix.museum",
  91834. "photography.museum",
  91835. "pilots.museum",
  91836. "pittsburgh.museum",
  91837. "planetarium.museum",
  91838. "plantation.museum",
  91839. "plants.museum",
  91840. "plaza.museum",
  91841. "portal.museum",
  91842. "portland.museum",
  91843. "portlligat.museum",
  91844. "posts-and-telecommunications.museum",
  91845. "preservation.museum",
  91846. "presidio.museum",
  91847. "press.museum",
  91848. "project.museum",
  91849. "public.museum",
  91850. "pubol.museum",
  91851. "quebec.museum",
  91852. "railroad.museum",
  91853. "railway.museum",
  91854. "research.museum",
  91855. "resistance.museum",
  91856. "riodejaneiro.museum",
  91857. "rochester.museum",
  91858. "rockart.museum",
  91859. "roma.museum",
  91860. "russia.museum",
  91861. "saintlouis.museum",
  91862. "salem.museum",
  91863. "salvadordali.museum",
  91864. "salzburg.museum",
  91865. "sandiego.museum",
  91866. "sanfrancisco.museum",
  91867. "santabarbara.museum",
  91868. "santacruz.museum",
  91869. "santafe.museum",
  91870. "saskatchewan.museum",
  91871. "satx.museum",
  91872. "savannahga.museum",
  91873. "schlesisches.museum",
  91874. "schoenbrunn.museum",
  91875. "schokoladen.museum",
  91876. "school.museum",
  91877. "schweiz.museum",
  91878. "science.museum",
  91879. "scienceandhistory.museum",
  91880. "scienceandindustry.museum",
  91881. "sciencecenter.museum",
  91882. "sciencecenters.museum",
  91883. "science-fiction.museum",
  91884. "sciencehistory.museum",
  91885. "sciences.museum",
  91886. "sciencesnaturelles.museum",
  91887. "scotland.museum",
  91888. "seaport.museum",
  91889. "settlement.museum",
  91890. "settlers.museum",
  91891. "shell.museum",
  91892. "sherbrooke.museum",
  91893. "sibenik.museum",
  91894. "silk.museum",
  91895. "ski.museum",
  91896. "skole.museum",
  91897. "society.museum",
  91898. "sologne.museum",
  91899. "soundandvision.museum",
  91900. "southcarolina.museum",
  91901. "southwest.museum",
  91902. "space.museum",
  91903. "spy.museum",
  91904. "square.museum",
  91905. "stadt.museum",
  91906. "stalbans.museum",
  91907. "starnberg.museum",
  91908. "state.museum",
  91909. "stateofdelaware.museum",
  91910. "station.museum",
  91911. "steam.museum",
  91912. "steiermark.museum",
  91913. "stjohn.museum",
  91914. "stockholm.museum",
  91915. "stpetersburg.museum",
  91916. "stuttgart.museum",
  91917. "suisse.museum",
  91918. "surgeonshall.museum",
  91919. "surrey.museum",
  91920. "svizzera.museum",
  91921. "sweden.museum",
  91922. "sydney.museum",
  91923. "tank.museum",
  91924. "tcm.museum",
  91925. "technology.museum",
  91926. "telekommunikation.museum",
  91927. "television.museum",
  91928. "texas.museum",
  91929. "textile.museum",
  91930. "theater.museum",
  91931. "time.museum",
  91932. "timekeeping.museum",
  91933. "topology.museum",
  91934. "torino.museum",
  91935. "touch.museum",
  91936. "town.museum",
  91937. "transport.museum",
  91938. "tree.museum",
  91939. "trolley.museum",
  91940. "trust.museum",
  91941. "trustee.museum",
  91942. "uhren.museum",
  91943. "ulm.museum",
  91944. "undersea.museum",
  91945. "university.museum",
  91946. "usa.museum",
  91947. "usantiques.museum",
  91948. "usarts.museum",
  91949. "uscountryestate.museum",
  91950. "usculture.museum",
  91951. "usdecorativearts.museum",
  91952. "usgarden.museum",
  91953. "ushistory.museum",
  91954. "ushuaia.museum",
  91955. "uslivinghistory.museum",
  91956. "utah.museum",
  91957. "uvic.museum",
  91958. "valley.museum",
  91959. "vantaa.museum",
  91960. "versailles.museum",
  91961. "viking.museum",
  91962. "village.museum",
  91963. "virginia.museum",
  91964. "virtual.museum",
  91965. "virtuel.museum",
  91966. "vlaanderen.museum",
  91967. "volkenkunde.museum",
  91968. "wales.museum",
  91969. "wallonie.museum",
  91970. "war.museum",
  91971. "washingtondc.museum",
  91972. "watchandclock.museum",
  91973. "watch-and-clock.museum",
  91974. "western.museum",
  91975. "westfalen.museum",
  91976. "whaling.museum",
  91977. "wildlife.museum",
  91978. "williamsburg.museum",
  91979. "windmill.museum",
  91980. "workshop.museum",
  91981. "york.museum",
  91982. "yorkshire.museum",
  91983. "yosemite.museum",
  91984. "youth.museum",
  91985. "zoological.museum",
  91986. "zoology.museum",
  91987. "ירושלים.museum",
  91988. "иком.museum",
  91989. "mv",
  91990. "aero.mv",
  91991. "biz.mv",
  91992. "com.mv",
  91993. "coop.mv",
  91994. "edu.mv",
  91995. "gov.mv",
  91996. "info.mv",
  91997. "int.mv",
  91998. "mil.mv",
  91999. "museum.mv",
  92000. "name.mv",
  92001. "net.mv",
  92002. "org.mv",
  92003. "pro.mv",
  92004. "mw",
  92005. "ac.mw",
  92006. "biz.mw",
  92007. "co.mw",
  92008. "com.mw",
  92009. "coop.mw",
  92010. "edu.mw",
  92011. "gov.mw",
  92012. "int.mw",
  92013. "museum.mw",
  92014. "net.mw",
  92015. "org.mw",
  92016. "mx",
  92017. "com.mx",
  92018. "org.mx",
  92019. "gob.mx",
  92020. "edu.mx",
  92021. "net.mx",
  92022. "my",
  92023. "com.my",
  92024. "net.my",
  92025. "org.my",
  92026. "gov.my",
  92027. "edu.my",
  92028. "mil.my",
  92029. "name.my",
  92030. "mz",
  92031. "ac.mz",
  92032. "adv.mz",
  92033. "co.mz",
  92034. "edu.mz",
  92035. "gov.mz",
  92036. "mil.mz",
  92037. "net.mz",
  92038. "org.mz",
  92039. "na",
  92040. "info.na",
  92041. "pro.na",
  92042. "name.na",
  92043. "school.na",
  92044. "or.na",
  92045. "dr.na",
  92046. "us.na",
  92047. "mx.na",
  92048. "ca.na",
  92049. "in.na",
  92050. "cc.na",
  92051. "tv.na",
  92052. "ws.na",
  92053. "mobi.na",
  92054. "co.na",
  92055. "com.na",
  92056. "org.na",
  92057. "name",
  92058. "nc",
  92059. "asso.nc",
  92060. "nom.nc",
  92061. "ne",
  92062. "net",
  92063. "nf",
  92064. "com.nf",
  92065. "net.nf",
  92066. "per.nf",
  92067. "rec.nf",
  92068. "web.nf",
  92069. "arts.nf",
  92070. "firm.nf",
  92071. "info.nf",
  92072. "other.nf",
  92073. "store.nf",
  92074. "ng",
  92075. "com.ng",
  92076. "edu.ng",
  92077. "gov.ng",
  92078. "i.ng",
  92079. "mil.ng",
  92080. "mobi.ng",
  92081. "name.ng",
  92082. "net.ng",
  92083. "org.ng",
  92084. "sch.ng",
  92085. "ni",
  92086. "ac.ni",
  92087. "biz.ni",
  92088. "co.ni",
  92089. "com.ni",
  92090. "edu.ni",
  92091. "gob.ni",
  92092. "in.ni",
  92093. "info.ni",
  92094. "int.ni",
  92095. "mil.ni",
  92096. "net.ni",
  92097. "nom.ni",
  92098. "org.ni",
  92099. "web.ni",
  92100. "nl",
  92101. "no",
  92102. "fhs.no",
  92103. "vgs.no",
  92104. "fylkesbibl.no",
  92105. "folkebibl.no",
  92106. "museum.no",
  92107. "idrett.no",
  92108. "priv.no",
  92109. "mil.no",
  92110. "stat.no",
  92111. "dep.no",
  92112. "kommune.no",
  92113. "herad.no",
  92114. "aa.no",
  92115. "ah.no",
  92116. "bu.no",
  92117. "fm.no",
  92118. "hl.no",
  92119. "hm.no",
  92120. "jan-mayen.no",
  92121. "mr.no",
  92122. "nl.no",
  92123. "nt.no",
  92124. "of.no",
  92125. "ol.no",
  92126. "oslo.no",
  92127. "rl.no",
  92128. "sf.no",
  92129. "st.no",
  92130. "svalbard.no",
  92131. "tm.no",
  92132. "tr.no",
  92133. "va.no",
  92134. "vf.no",
  92135. "gs.aa.no",
  92136. "gs.ah.no",
  92137. "gs.bu.no",
  92138. "gs.fm.no",
  92139. "gs.hl.no",
  92140. "gs.hm.no",
  92141. "gs.jan-mayen.no",
  92142. "gs.mr.no",
  92143. "gs.nl.no",
  92144. "gs.nt.no",
  92145. "gs.of.no",
  92146. "gs.ol.no",
  92147. "gs.oslo.no",
  92148. "gs.rl.no",
  92149. "gs.sf.no",
  92150. "gs.st.no",
  92151. "gs.svalbard.no",
  92152. "gs.tm.no",
  92153. "gs.tr.no",
  92154. "gs.va.no",
  92155. "gs.vf.no",
  92156. "akrehamn.no",
  92157. "åkrehamn.no",
  92158. "algard.no",
  92159. "ålgård.no",
  92160. "arna.no",
  92161. "brumunddal.no",
  92162. "bryne.no",
  92163. "bronnoysund.no",
  92164. "brønnøysund.no",
  92165. "drobak.no",
  92166. "drøbak.no",
  92167. "egersund.no",
  92168. "fetsund.no",
  92169. "floro.no",
  92170. "florø.no",
  92171. "fredrikstad.no",
  92172. "hokksund.no",
  92173. "honefoss.no",
  92174. "hønefoss.no",
  92175. "jessheim.no",
  92176. "jorpeland.no",
  92177. "jørpeland.no",
  92178. "kirkenes.no",
  92179. "kopervik.no",
  92180. "krokstadelva.no",
  92181. "langevag.no",
  92182. "langevåg.no",
  92183. "leirvik.no",
  92184. "mjondalen.no",
  92185. "mjøndalen.no",
  92186. "mo-i-rana.no",
  92187. "mosjoen.no",
  92188. "mosjøen.no",
  92189. "nesoddtangen.no",
  92190. "orkanger.no",
  92191. "osoyro.no",
  92192. "osøyro.no",
  92193. "raholt.no",
  92194. "råholt.no",
  92195. "sandnessjoen.no",
  92196. "sandnessjøen.no",
  92197. "skedsmokorset.no",
  92198. "slattum.no",
  92199. "spjelkavik.no",
  92200. "stathelle.no",
  92201. "stavern.no",
  92202. "stjordalshalsen.no",
  92203. "stjørdalshalsen.no",
  92204. "tananger.no",
  92205. "tranby.no",
  92206. "vossevangen.no",
  92207. "afjord.no",
  92208. "åfjord.no",
  92209. "agdenes.no",
  92210. "al.no",
  92211. "ål.no",
  92212. "alesund.no",
  92213. "ålesund.no",
  92214. "alstahaug.no",
  92215. "alta.no",
  92216. "áltá.no",
  92217. "alaheadju.no",
  92218. "álaheadju.no",
  92219. "alvdal.no",
  92220. "amli.no",
  92221. "åmli.no",
  92222. "amot.no",
  92223. "åmot.no",
  92224. "andebu.no",
  92225. "andoy.no",
  92226. "andøy.no",
  92227. "andasuolo.no",
  92228. "ardal.no",
  92229. "årdal.no",
  92230. "aremark.no",
  92231. "arendal.no",
  92232. "ås.no",
  92233. "aseral.no",
  92234. "åseral.no",
  92235. "asker.no",
  92236. "askim.no",
  92237. "askvoll.no",
  92238. "askoy.no",
  92239. "askøy.no",
  92240. "asnes.no",
  92241. "åsnes.no",
  92242. "audnedaln.no",
  92243. "aukra.no",
  92244. "aure.no",
  92245. "aurland.no",
  92246. "aurskog-holand.no",
  92247. "aurskog-høland.no",
  92248. "austevoll.no",
  92249. "austrheim.no",
  92250. "averoy.no",
  92251. "averøy.no",
  92252. "balestrand.no",
  92253. "ballangen.no",
  92254. "balat.no",
  92255. "bálát.no",
  92256. "balsfjord.no",
  92257. "bahccavuotna.no",
  92258. "báhccavuotna.no",
  92259. "bamble.no",
  92260. "bardu.no",
  92261. "beardu.no",
  92262. "beiarn.no",
  92263. "bajddar.no",
  92264. "bájddar.no",
  92265. "baidar.no",
  92266. "báidár.no",
  92267. "berg.no",
  92268. "bergen.no",
  92269. "berlevag.no",
  92270. "berlevåg.no",
  92271. "bearalvahki.no",
  92272. "bearalváhki.no",
  92273. "bindal.no",
  92274. "birkenes.no",
  92275. "bjarkoy.no",
  92276. "bjarkøy.no",
  92277. "bjerkreim.no",
  92278. "bjugn.no",
  92279. "bodo.no",
  92280. "bodø.no",
  92281. "badaddja.no",
  92282. "bådåddjå.no",
  92283. "budejju.no",
  92284. "bokn.no",
  92285. "bremanger.no",
  92286. "bronnoy.no",
  92287. "brønnøy.no",
  92288. "bygland.no",
  92289. "bykle.no",
  92290. "barum.no",
  92291. "bærum.no",
  92292. "bo.telemark.no",
  92293. "bø.telemark.no",
  92294. "bo.nordland.no",
  92295. "bø.nordland.no",
  92296. "bievat.no",
  92297. "bievát.no",
  92298. "bomlo.no",
  92299. "bømlo.no",
  92300. "batsfjord.no",
  92301. "båtsfjord.no",
  92302. "bahcavuotna.no",
  92303. "báhcavuotna.no",
  92304. "dovre.no",
  92305. "drammen.no",
  92306. "drangedal.no",
  92307. "dyroy.no",
  92308. "dyrøy.no",
  92309. "donna.no",
  92310. "dønna.no",
  92311. "eid.no",
  92312. "eidfjord.no",
  92313. "eidsberg.no",
  92314. "eidskog.no",
  92315. "eidsvoll.no",
  92316. "eigersund.no",
  92317. "elverum.no",
  92318. "enebakk.no",
  92319. "engerdal.no",
  92320. "etne.no",
  92321. "etnedal.no",
  92322. "evenes.no",
  92323. "evenassi.no",
  92324. "evenášši.no",
  92325. "evje-og-hornnes.no",
  92326. "farsund.no",
  92327. "fauske.no",
  92328. "fuossko.no",
  92329. "fuoisku.no",
  92330. "fedje.no",
  92331. "fet.no",
  92332. "finnoy.no",
  92333. "finnøy.no",
  92334. "fitjar.no",
  92335. "fjaler.no",
  92336. "fjell.no",
  92337. "flakstad.no",
  92338. "flatanger.no",
  92339. "flekkefjord.no",
  92340. "flesberg.no",
  92341. "flora.no",
  92342. "fla.no",
  92343. "flå.no",
  92344. "folldal.no",
  92345. "forsand.no",
  92346. "fosnes.no",
  92347. "frei.no",
  92348. "frogn.no",
  92349. "froland.no",
  92350. "frosta.no",
  92351. "frana.no",
  92352. "fræna.no",
  92353. "froya.no",
  92354. "frøya.no",
  92355. "fusa.no",
  92356. "fyresdal.no",
  92357. "forde.no",
  92358. "førde.no",
  92359. "gamvik.no",
  92360. "gangaviika.no",
  92361. "gáŋgaviika.no",
  92362. "gaular.no",
  92363. "gausdal.no",
  92364. "gildeskal.no",
  92365. "gildeskål.no",
  92366. "giske.no",
  92367. "gjemnes.no",
  92368. "gjerdrum.no",
  92369. "gjerstad.no",
  92370. "gjesdal.no",
  92371. "gjovik.no",
  92372. "gjøvik.no",
  92373. "gloppen.no",
  92374. "gol.no",
  92375. "gran.no",
  92376. "grane.no",
  92377. "granvin.no",
  92378. "gratangen.no",
  92379. "grimstad.no",
  92380. "grong.no",
  92381. "kraanghke.no",
  92382. "kråanghke.no",
  92383. "grue.no",
  92384. "gulen.no",
  92385. "hadsel.no",
  92386. "halden.no",
  92387. "halsa.no",
  92388. "hamar.no",
  92389. "hamaroy.no",
  92390. "habmer.no",
  92391. "hábmer.no",
  92392. "hapmir.no",
  92393. "hápmir.no",
  92394. "hammerfest.no",
  92395. "hammarfeasta.no",
  92396. "hámmárfeasta.no",
  92397. "haram.no",
  92398. "hareid.no",
  92399. "harstad.no",
  92400. "hasvik.no",
  92401. "aknoluokta.no",
  92402. "ákŋoluokta.no",
  92403. "hattfjelldal.no",
  92404. "aarborte.no",
  92405. "haugesund.no",
  92406. "hemne.no",
  92407. "hemnes.no",
  92408. "hemsedal.no",
  92409. "heroy.more-og-romsdal.no",
  92410. "herøy.møre-og-romsdal.no",
  92411. "heroy.nordland.no",
  92412. "herøy.nordland.no",
  92413. "hitra.no",
  92414. "hjartdal.no",
  92415. "hjelmeland.no",
  92416. "hobol.no",
  92417. "hobøl.no",
  92418. "hof.no",
  92419. "hol.no",
  92420. "hole.no",
  92421. "holmestrand.no",
  92422. "holtalen.no",
  92423. "holtålen.no",
  92424. "hornindal.no",
  92425. "horten.no",
  92426. "hurdal.no",
  92427. "hurum.no",
  92428. "hvaler.no",
  92429. "hyllestad.no",
  92430. "hagebostad.no",
  92431. "hægebostad.no",
  92432. "hoyanger.no",
  92433. "høyanger.no",
  92434. "hoylandet.no",
  92435. "høylandet.no",
  92436. "ha.no",
  92437. "hå.no",
  92438. "ibestad.no",
  92439. "inderoy.no",
  92440. "inderøy.no",
  92441. "iveland.no",
  92442. "jevnaker.no",
  92443. "jondal.no",
  92444. "jolster.no",
  92445. "jølster.no",
  92446. "karasjok.no",
  92447. "karasjohka.no",
  92448. "kárášjohka.no",
  92449. "karlsoy.no",
  92450. "galsa.no",
  92451. "gálsá.no",
  92452. "karmoy.no",
  92453. "karmøy.no",
  92454. "kautokeino.no",
  92455. "guovdageaidnu.no",
  92456. "klepp.no",
  92457. "klabu.no",
  92458. "klæbu.no",
  92459. "kongsberg.no",
  92460. "kongsvinger.no",
  92461. "kragero.no",
  92462. "kragerø.no",
  92463. "kristiansand.no",
  92464. "kristiansund.no",
  92465. "krodsherad.no",
  92466. "krødsherad.no",
  92467. "kvalsund.no",
  92468. "rahkkeravju.no",
  92469. "ráhkkerávju.no",
  92470. "kvam.no",
  92471. "kvinesdal.no",
  92472. "kvinnherad.no",
  92473. "kviteseid.no",
  92474. "kvitsoy.no",
  92475. "kvitsøy.no",
  92476. "kvafjord.no",
  92477. "kvæfjord.no",
  92478. "giehtavuoatna.no",
  92479. "kvanangen.no",
  92480. "kvænangen.no",
  92481. "navuotna.no",
  92482. "návuotna.no",
  92483. "kafjord.no",
  92484. "kåfjord.no",
  92485. "gaivuotna.no",
  92486. "gáivuotna.no",
  92487. "larvik.no",
  92488. "lavangen.no",
  92489. "lavagis.no",
  92490. "loabat.no",
  92491. "loabát.no",
  92492. "lebesby.no",
  92493. "davvesiida.no",
  92494. "leikanger.no",
  92495. "leirfjord.no",
  92496. "leka.no",
  92497. "leksvik.no",
  92498. "lenvik.no",
  92499. "leangaviika.no",
  92500. "leaŋgaviika.no",
  92501. "lesja.no",
  92502. "levanger.no",
  92503. "lier.no",
  92504. "lierne.no",
  92505. "lillehammer.no",
  92506. "lillesand.no",
  92507. "lindesnes.no",
  92508. "lindas.no",
  92509. "lindås.no",
  92510. "lom.no",
  92511. "loppa.no",
  92512. "lahppi.no",
  92513. "láhppi.no",
  92514. "lund.no",
  92515. "lunner.no",
  92516. "luroy.no",
  92517. "lurøy.no",
  92518. "luster.no",
  92519. "lyngdal.no",
  92520. "lyngen.no",
  92521. "ivgu.no",
  92522. "lardal.no",
  92523. "lerdal.no",
  92524. "lærdal.no",
  92525. "lodingen.no",
  92526. "lødingen.no",
  92527. "lorenskog.no",
  92528. "lørenskog.no",
  92529. "loten.no",
  92530. "løten.no",
  92531. "malvik.no",
  92532. "masoy.no",
  92533. "måsøy.no",
  92534. "muosat.no",
  92535. "muosát.no",
  92536. "mandal.no",
  92537. "marker.no",
  92538. "marnardal.no",
  92539. "masfjorden.no",
  92540. "meland.no",
  92541. "meldal.no",
  92542. "melhus.no",
  92543. "meloy.no",
  92544. "meløy.no",
  92545. "meraker.no",
  92546. "meråker.no",
  92547. "moareke.no",
  92548. "moåreke.no",
  92549. "midsund.no",
  92550. "midtre-gauldal.no",
  92551. "modalen.no",
  92552. "modum.no",
  92553. "molde.no",
  92554. "moskenes.no",
  92555. "moss.no",
  92556. "mosvik.no",
  92557. "malselv.no",
  92558. "målselv.no",
  92559. "malatvuopmi.no",
  92560. "málatvuopmi.no",
  92561. "namdalseid.no",
  92562. "aejrie.no",
  92563. "namsos.no",
  92564. "namsskogan.no",
  92565. "naamesjevuemie.no",
  92566. "nååmesjevuemie.no",
  92567. "laakesvuemie.no",
  92568. "nannestad.no",
  92569. "narvik.no",
  92570. "narviika.no",
  92571. "naustdal.no",
  92572. "nedre-eiker.no",
  92573. "nes.akershus.no",
  92574. "nes.buskerud.no",
  92575. "nesna.no",
  92576. "nesodden.no",
  92577. "nesseby.no",
  92578. "unjarga.no",
  92579. "unjárga.no",
  92580. "nesset.no",
  92581. "nissedal.no",
  92582. "nittedal.no",
  92583. "nord-aurdal.no",
  92584. "nord-fron.no",
  92585. "nord-odal.no",
  92586. "norddal.no",
  92587. "nordkapp.no",
  92588. "davvenjarga.no",
  92589. "davvenjárga.no",
  92590. "nordre-land.no",
  92591. "nordreisa.no",
  92592. "raisa.no",
  92593. "ráisa.no",
  92594. "nore-og-uvdal.no",
  92595. "notodden.no",
  92596. "naroy.no",
  92597. "nærøy.no",
  92598. "notteroy.no",
  92599. "nøtterøy.no",
  92600. "odda.no",
  92601. "oksnes.no",
  92602. "øksnes.no",
  92603. "oppdal.no",
  92604. "oppegard.no",
  92605. "oppegård.no",
  92606. "orkdal.no",
  92607. "orland.no",
  92608. "ørland.no",
  92609. "orskog.no",
  92610. "ørskog.no",
  92611. "orsta.no",
  92612. "ørsta.no",
  92613. "os.hedmark.no",
  92614. "os.hordaland.no",
  92615. "osen.no",
  92616. "osteroy.no",
  92617. "osterøy.no",
  92618. "ostre-toten.no",
  92619. "østre-toten.no",
  92620. "overhalla.no",
  92621. "ovre-eiker.no",
  92622. "øvre-eiker.no",
  92623. "oyer.no",
  92624. "øyer.no",
  92625. "oygarden.no",
  92626. "øygarden.no",
  92627. "oystre-slidre.no",
  92628. "øystre-slidre.no",
  92629. "porsanger.no",
  92630. "porsangu.no",
  92631. "porsáŋgu.no",
  92632. "porsgrunn.no",
  92633. "radoy.no",
  92634. "radøy.no",
  92635. "rakkestad.no",
  92636. "rana.no",
  92637. "ruovat.no",
  92638. "randaberg.no",
  92639. "rauma.no",
  92640. "rendalen.no",
  92641. "rennebu.no",
  92642. "rennesoy.no",
  92643. "rennesøy.no",
  92644. "rindal.no",
  92645. "ringebu.no",
  92646. "ringerike.no",
  92647. "ringsaker.no",
  92648. "rissa.no",
  92649. "risor.no",
  92650. "risør.no",
  92651. "roan.no",
  92652. "rollag.no",
  92653. "rygge.no",
  92654. "ralingen.no",
  92655. "rælingen.no",
  92656. "rodoy.no",
  92657. "rødøy.no",
  92658. "romskog.no",
  92659. "rømskog.no",
  92660. "roros.no",
  92661. "røros.no",
  92662. "rost.no",
  92663. "røst.no",
  92664. "royken.no",
  92665. "røyken.no",
  92666. "royrvik.no",
  92667. "røyrvik.no",
  92668. "rade.no",
  92669. "råde.no",
  92670. "salangen.no",
  92671. "siellak.no",
  92672. "saltdal.no",
  92673. "salat.no",
  92674. "sálát.no",
  92675. "sálat.no",
  92676. "samnanger.no",
  92677. "sande.more-og-romsdal.no",
  92678. "sande.møre-og-romsdal.no",
  92679. "sande.vestfold.no",
  92680. "sandefjord.no",
  92681. "sandnes.no",
  92682. "sandoy.no",
  92683. "sandøy.no",
  92684. "sarpsborg.no",
  92685. "sauda.no",
  92686. "sauherad.no",
  92687. "sel.no",
  92688. "selbu.no",
  92689. "selje.no",
  92690. "seljord.no",
  92691. "sigdal.no",
  92692. "siljan.no",
  92693. "sirdal.no",
  92694. "skaun.no",
  92695. "skedsmo.no",
  92696. "ski.no",
  92697. "skien.no",
  92698. "skiptvet.no",
  92699. "skjervoy.no",
  92700. "skjervøy.no",
  92701. "skierva.no",
  92702. "skiervá.no",
  92703. "skjak.no",
  92704. "skjåk.no",
  92705. "skodje.no",
  92706. "skanland.no",
  92707. "skånland.no",
  92708. "skanit.no",
  92709. "skánit.no",
  92710. "smola.no",
  92711. "smøla.no",
  92712. "snillfjord.no",
  92713. "snasa.no",
  92714. "snåsa.no",
  92715. "snoasa.no",
  92716. "snaase.no",
  92717. "snåase.no",
  92718. "sogndal.no",
  92719. "sokndal.no",
  92720. "sola.no",
  92721. "solund.no",
  92722. "songdalen.no",
  92723. "sortland.no",
  92724. "spydeberg.no",
  92725. "stange.no",
  92726. "stavanger.no",
  92727. "steigen.no",
  92728. "steinkjer.no",
  92729. "stjordal.no",
  92730. "stjørdal.no",
  92731. "stokke.no",
  92732. "stor-elvdal.no",
  92733. "stord.no",
  92734. "stordal.no",
  92735. "storfjord.no",
  92736. "omasvuotna.no",
  92737. "strand.no",
  92738. "stranda.no",
  92739. "stryn.no",
  92740. "sula.no",
  92741. "suldal.no",
  92742. "sund.no",
  92743. "sunndal.no",
  92744. "surnadal.no",
  92745. "sveio.no",
  92746. "svelvik.no",
  92747. "sykkylven.no",
  92748. "sogne.no",
  92749. "søgne.no",
  92750. "somna.no",
  92751. "sømna.no",
  92752. "sondre-land.no",
  92753. "søndre-land.no",
  92754. "sor-aurdal.no",
  92755. "sør-aurdal.no",
  92756. "sor-fron.no",
  92757. "sør-fron.no",
  92758. "sor-odal.no",
  92759. "sør-odal.no",
  92760. "sor-varanger.no",
  92761. "sør-varanger.no",
  92762. "matta-varjjat.no",
  92763. "mátta-várjjat.no",
  92764. "sorfold.no",
  92765. "sørfold.no",
  92766. "sorreisa.no",
  92767. "sørreisa.no",
  92768. "sorum.no",
  92769. "sørum.no",
  92770. "tana.no",
  92771. "deatnu.no",
  92772. "time.no",
  92773. "tingvoll.no",
  92774. "tinn.no",
  92775. "tjeldsund.no",
  92776. "dielddanuorri.no",
  92777. "tjome.no",
  92778. "tjøme.no",
  92779. "tokke.no",
  92780. "tolga.no",
  92781. "torsken.no",
  92782. "tranoy.no",
  92783. "tranøy.no",
  92784. "tromso.no",
  92785. "tromsø.no",
  92786. "tromsa.no",
  92787. "romsa.no",
  92788. "trondheim.no",
  92789. "troandin.no",
  92790. "trysil.no",
  92791. "trana.no",
  92792. "træna.no",
  92793. "trogstad.no",
  92794. "trøgstad.no",
  92795. "tvedestrand.no",
  92796. "tydal.no",
  92797. "tynset.no",
  92798. "tysfjord.no",
  92799. "divtasvuodna.no",
  92800. "divttasvuotna.no",
  92801. "tysnes.no",
  92802. "tysvar.no",
  92803. "tysvær.no",
  92804. "tonsberg.no",
  92805. "tønsberg.no",
  92806. "ullensaker.no",
  92807. "ullensvang.no",
  92808. "ulvik.no",
  92809. "utsira.no",
  92810. "vadso.no",
  92811. "vadsø.no",
  92812. "cahcesuolo.no",
  92813. "čáhcesuolo.no",
  92814. "vaksdal.no",
  92815. "valle.no",
  92816. "vang.no",
  92817. "vanylven.no",
  92818. "vardo.no",
  92819. "vardø.no",
  92820. "varggat.no",
  92821. "várggát.no",
  92822. "vefsn.no",
  92823. "vaapste.no",
  92824. "vega.no",
  92825. "vegarshei.no",
  92826. "vegårshei.no",
  92827. "vennesla.no",
  92828. "verdal.no",
  92829. "verran.no",
  92830. "vestby.no",
  92831. "vestnes.no",
  92832. "vestre-slidre.no",
  92833. "vestre-toten.no",
  92834. "vestvagoy.no",
  92835. "vestvågøy.no",
  92836. "vevelstad.no",
  92837. "vik.no",
  92838. "vikna.no",
  92839. "vindafjord.no",
  92840. "volda.no",
  92841. "voss.no",
  92842. "varoy.no",
  92843. "værøy.no",
  92844. "vagan.no",
  92845. "vågan.no",
  92846. "voagat.no",
  92847. "vagsoy.no",
  92848. "vågsøy.no",
  92849. "vaga.no",
  92850. "vågå.no",
  92851. "valer.ostfold.no",
  92852. "våler.østfold.no",
  92853. "valer.hedmark.no",
  92854. "våler.hedmark.no",
  92855. "*.np",
  92856. "nr",
  92857. "biz.nr",
  92858. "info.nr",
  92859. "gov.nr",
  92860. "edu.nr",
  92861. "org.nr",
  92862. "net.nr",
  92863. "com.nr",
  92864. "nu",
  92865. "nz",
  92866. "ac.nz",
  92867. "co.nz",
  92868. "cri.nz",
  92869. "geek.nz",
  92870. "gen.nz",
  92871. "govt.nz",
  92872. "health.nz",
  92873. "iwi.nz",
  92874. "kiwi.nz",
  92875. "maori.nz",
  92876. "mil.nz",
  92877. "māori.nz",
  92878. "net.nz",
  92879. "org.nz",
  92880. "parliament.nz",
  92881. "school.nz",
  92882. "om",
  92883. "co.om",
  92884. "com.om",
  92885. "edu.om",
  92886. "gov.om",
  92887. "med.om",
  92888. "museum.om",
  92889. "net.om",
  92890. "org.om",
  92891. "pro.om",
  92892. "onion",
  92893. "org",
  92894. "pa",
  92895. "ac.pa",
  92896. "gob.pa",
  92897. "com.pa",
  92898. "org.pa",
  92899. "sld.pa",
  92900. "edu.pa",
  92901. "net.pa",
  92902. "ing.pa",
  92903. "abo.pa",
  92904. "med.pa",
  92905. "nom.pa",
  92906. "pe",
  92907. "edu.pe",
  92908. "gob.pe",
  92909. "nom.pe",
  92910. "mil.pe",
  92911. "org.pe",
  92912. "com.pe",
  92913. "net.pe",
  92914. "pf",
  92915. "com.pf",
  92916. "org.pf",
  92917. "edu.pf",
  92918. "*.pg",
  92919. "ph",
  92920. "com.ph",
  92921. "net.ph",
  92922. "org.ph",
  92923. "gov.ph",
  92924. "edu.ph",
  92925. "ngo.ph",
  92926. "mil.ph",
  92927. "i.ph",
  92928. "pk",
  92929. "com.pk",
  92930. "net.pk",
  92931. "edu.pk",
  92932. "org.pk",
  92933. "fam.pk",
  92934. "biz.pk",
  92935. "web.pk",
  92936. "gov.pk",
  92937. "gob.pk",
  92938. "gok.pk",
  92939. "gon.pk",
  92940. "gop.pk",
  92941. "gos.pk",
  92942. "info.pk",
  92943. "pl",
  92944. "com.pl",
  92945. "net.pl",
  92946. "org.pl",
  92947. "aid.pl",
  92948. "agro.pl",
  92949. "atm.pl",
  92950. "auto.pl",
  92951. "biz.pl",
  92952. "edu.pl",
  92953. "gmina.pl",
  92954. "gsm.pl",
  92955. "info.pl",
  92956. "mail.pl",
  92957. "miasta.pl",
  92958. "media.pl",
  92959. "mil.pl",
  92960. "nieruchomosci.pl",
  92961. "nom.pl",
  92962. "pc.pl",
  92963. "powiat.pl",
  92964. "priv.pl",
  92965. "realestate.pl",
  92966. "rel.pl",
  92967. "sex.pl",
  92968. "shop.pl",
  92969. "sklep.pl",
  92970. "sos.pl",
  92971. "szkola.pl",
  92972. "targi.pl",
  92973. "tm.pl",
  92974. "tourism.pl",
  92975. "travel.pl",
  92976. "turystyka.pl",
  92977. "gov.pl",
  92978. "ap.gov.pl",
  92979. "ic.gov.pl",
  92980. "is.gov.pl",
  92981. "us.gov.pl",
  92982. "kmpsp.gov.pl",
  92983. "kppsp.gov.pl",
  92984. "kwpsp.gov.pl",
  92985. "psp.gov.pl",
  92986. "wskr.gov.pl",
  92987. "kwp.gov.pl",
  92988. "mw.gov.pl",
  92989. "ug.gov.pl",
  92990. "um.gov.pl",
  92991. "umig.gov.pl",
  92992. "ugim.gov.pl",
  92993. "upow.gov.pl",
  92994. "uw.gov.pl",
  92995. "starostwo.gov.pl",
  92996. "pa.gov.pl",
  92997. "po.gov.pl",
  92998. "psse.gov.pl",
  92999. "pup.gov.pl",
  93000. "rzgw.gov.pl",
  93001. "sa.gov.pl",
  93002. "so.gov.pl",
  93003. "sr.gov.pl",
  93004. "wsa.gov.pl",
  93005. "sko.gov.pl",
  93006. "uzs.gov.pl",
  93007. "wiih.gov.pl",
  93008. "winb.gov.pl",
  93009. "pinb.gov.pl",
  93010. "wios.gov.pl",
  93011. "witd.gov.pl",
  93012. "wzmiuw.gov.pl",
  93013. "piw.gov.pl",
  93014. "wiw.gov.pl",
  93015. "griw.gov.pl",
  93016. "wif.gov.pl",
  93017. "oum.gov.pl",
  93018. "sdn.gov.pl",
  93019. "zp.gov.pl",
  93020. "uppo.gov.pl",
  93021. "mup.gov.pl",
  93022. "wuoz.gov.pl",
  93023. "konsulat.gov.pl",
  93024. "oirm.gov.pl",
  93025. "augustow.pl",
  93026. "babia-gora.pl",
  93027. "bedzin.pl",
  93028. "beskidy.pl",
  93029. "bialowieza.pl",
  93030. "bialystok.pl",
  93031. "bielawa.pl",
  93032. "bieszczady.pl",
  93033. "boleslawiec.pl",
  93034. "bydgoszcz.pl",
  93035. "bytom.pl",
  93036. "cieszyn.pl",
  93037. "czeladz.pl",
  93038. "czest.pl",
  93039. "dlugoleka.pl",
  93040. "elblag.pl",
  93041. "elk.pl",
  93042. "glogow.pl",
  93043. "gniezno.pl",
  93044. "gorlice.pl",
  93045. "grajewo.pl",
  93046. "ilawa.pl",
  93047. "jaworzno.pl",
  93048. "jelenia-gora.pl",
  93049. "jgora.pl",
  93050. "kalisz.pl",
  93051. "kazimierz-dolny.pl",
  93052. "karpacz.pl",
  93053. "kartuzy.pl",
  93054. "kaszuby.pl",
  93055. "katowice.pl",
  93056. "kepno.pl",
  93057. "ketrzyn.pl",
  93058. "klodzko.pl",
  93059. "kobierzyce.pl",
  93060. "kolobrzeg.pl",
  93061. "konin.pl",
  93062. "konskowola.pl",
  93063. "kutno.pl",
  93064. "lapy.pl",
  93065. "lebork.pl",
  93066. "legnica.pl",
  93067. "lezajsk.pl",
  93068. "limanowa.pl",
  93069. "lomza.pl",
  93070. "lowicz.pl",
  93071. "lubin.pl",
  93072. "lukow.pl",
  93073. "malbork.pl",
  93074. "malopolska.pl",
  93075. "mazowsze.pl",
  93076. "mazury.pl",
  93077. "mielec.pl",
  93078. "mielno.pl",
  93079. "mragowo.pl",
  93080. "naklo.pl",
  93081. "nowaruda.pl",
  93082. "nysa.pl",
  93083. "olawa.pl",
  93084. "olecko.pl",
  93085. "olkusz.pl",
  93086. "olsztyn.pl",
  93087. "opoczno.pl",
  93088. "opole.pl",
  93089. "ostroda.pl",
  93090. "ostroleka.pl",
  93091. "ostrowiec.pl",
  93092. "ostrowwlkp.pl",
  93093. "pila.pl",
  93094. "pisz.pl",
  93095. "podhale.pl",
  93096. "podlasie.pl",
  93097. "polkowice.pl",
  93098. "pomorze.pl",
  93099. "pomorskie.pl",
  93100. "prochowice.pl",
  93101. "pruszkow.pl",
  93102. "przeworsk.pl",
  93103. "pulawy.pl",
  93104. "radom.pl",
  93105. "rawa-maz.pl",
  93106. "rybnik.pl",
  93107. "rzeszow.pl",
  93108. "sanok.pl",
  93109. "sejny.pl",
  93110. "slask.pl",
  93111. "slupsk.pl",
  93112. "sosnowiec.pl",
  93113. "stalowa-wola.pl",
  93114. "skoczow.pl",
  93115. "starachowice.pl",
  93116. "stargard.pl",
  93117. "suwalki.pl",
  93118. "swidnica.pl",
  93119. "swiebodzin.pl",
  93120. "swinoujscie.pl",
  93121. "szczecin.pl",
  93122. "szczytno.pl",
  93123. "tarnobrzeg.pl",
  93124. "tgory.pl",
  93125. "turek.pl",
  93126. "tychy.pl",
  93127. "ustka.pl",
  93128. "walbrzych.pl",
  93129. "warmia.pl",
  93130. "warszawa.pl",
  93131. "waw.pl",
  93132. "wegrow.pl",
  93133. "wielun.pl",
  93134. "wlocl.pl",
  93135. "wloclawek.pl",
  93136. "wodzislaw.pl",
  93137. "wolomin.pl",
  93138. "wroclaw.pl",
  93139. "zachpomor.pl",
  93140. "zagan.pl",
  93141. "zarow.pl",
  93142. "zgora.pl",
  93143. "zgorzelec.pl",
  93144. "pm",
  93145. "pn",
  93146. "gov.pn",
  93147. "co.pn",
  93148. "org.pn",
  93149. "edu.pn",
  93150. "net.pn",
  93151. "post",
  93152. "pr",
  93153. "com.pr",
  93154. "net.pr",
  93155. "org.pr",
  93156. "gov.pr",
  93157. "edu.pr",
  93158. "isla.pr",
  93159. "pro.pr",
  93160. "biz.pr",
  93161. "info.pr",
  93162. "name.pr",
  93163. "est.pr",
  93164. "prof.pr",
  93165. "ac.pr",
  93166. "pro",
  93167. "aaa.pro",
  93168. "aca.pro",
  93169. "acct.pro",
  93170. "avocat.pro",
  93171. "bar.pro",
  93172. "cpa.pro",
  93173. "eng.pro",
  93174. "jur.pro",
  93175. "law.pro",
  93176. "med.pro",
  93177. "recht.pro",
  93178. "ps",
  93179. "edu.ps",
  93180. "gov.ps",
  93181. "sec.ps",
  93182. "plo.ps",
  93183. "com.ps",
  93184. "org.ps",
  93185. "net.ps",
  93186. "pt",
  93187. "net.pt",
  93188. "gov.pt",
  93189. "org.pt",
  93190. "edu.pt",
  93191. "int.pt",
  93192. "publ.pt",
  93193. "com.pt",
  93194. "nome.pt",
  93195. "pw",
  93196. "co.pw",
  93197. "ne.pw",
  93198. "or.pw",
  93199. "ed.pw",
  93200. "go.pw",
  93201. "belau.pw",
  93202. "py",
  93203. "com.py",
  93204. "coop.py",
  93205. "edu.py",
  93206. "gov.py",
  93207. "mil.py",
  93208. "net.py",
  93209. "org.py",
  93210. "qa",
  93211. "com.qa",
  93212. "edu.qa",
  93213. "gov.qa",
  93214. "mil.qa",
  93215. "name.qa",
  93216. "net.qa",
  93217. "org.qa",
  93218. "sch.qa",
  93219. "re",
  93220. "asso.re",
  93221. "com.re",
  93222. "nom.re",
  93223. "ro",
  93224. "arts.ro",
  93225. "com.ro",
  93226. "firm.ro",
  93227. "info.ro",
  93228. "nom.ro",
  93229. "nt.ro",
  93230. "org.ro",
  93231. "rec.ro",
  93232. "store.ro",
  93233. "tm.ro",
  93234. "www.ro",
  93235. "rs",
  93236. "ac.rs",
  93237. "co.rs",
  93238. "edu.rs",
  93239. "gov.rs",
  93240. "in.rs",
  93241. "org.rs",
  93242. "ru",
  93243. "rw",
  93244. "ac.rw",
  93245. "co.rw",
  93246. "coop.rw",
  93247. "gov.rw",
  93248. "mil.rw",
  93249. "net.rw",
  93250. "org.rw",
  93251. "sa",
  93252. "com.sa",
  93253. "net.sa",
  93254. "org.sa",
  93255. "gov.sa",
  93256. "med.sa",
  93257. "pub.sa",
  93258. "edu.sa",
  93259. "sch.sa",
  93260. "sb",
  93261. "com.sb",
  93262. "edu.sb",
  93263. "gov.sb",
  93264. "net.sb",
  93265. "org.sb",
  93266. "sc",
  93267. "com.sc",
  93268. "gov.sc",
  93269. "net.sc",
  93270. "org.sc",
  93271. "edu.sc",
  93272. "sd",
  93273. "com.sd",
  93274. "net.sd",
  93275. "org.sd",
  93276. "edu.sd",
  93277. "med.sd",
  93278. "tv.sd",
  93279. "gov.sd",
  93280. "info.sd",
  93281. "se",
  93282. "a.se",
  93283. "ac.se",
  93284. "b.se",
  93285. "bd.se",
  93286. "brand.se",
  93287. "c.se",
  93288. "d.se",
  93289. "e.se",
  93290. "f.se",
  93291. "fh.se",
  93292. "fhsk.se",
  93293. "fhv.se",
  93294. "g.se",
  93295. "h.se",
  93296. "i.se",
  93297. "k.se",
  93298. "komforb.se",
  93299. "kommunalforbund.se",
  93300. "komvux.se",
  93301. "l.se",
  93302. "lanbib.se",
  93303. "m.se",
  93304. "n.se",
  93305. "naturbruksgymn.se",
  93306. "o.se",
  93307. "org.se",
  93308. "p.se",
  93309. "parti.se",
  93310. "pp.se",
  93311. "press.se",
  93312. "r.se",
  93313. "s.se",
  93314. "t.se",
  93315. "tm.se",
  93316. "u.se",
  93317. "w.se",
  93318. "x.se",
  93319. "y.se",
  93320. "z.se",
  93321. "sg",
  93322. "com.sg",
  93323. "net.sg",
  93324. "org.sg",
  93325. "gov.sg",
  93326. "edu.sg",
  93327. "per.sg",
  93328. "sh",
  93329. "com.sh",
  93330. "net.sh",
  93331. "gov.sh",
  93332. "org.sh",
  93333. "mil.sh",
  93334. "si",
  93335. "sj",
  93336. "sk",
  93337. "sl",
  93338. "com.sl",
  93339. "net.sl",
  93340. "edu.sl",
  93341. "gov.sl",
  93342. "org.sl",
  93343. "sm",
  93344. "sn",
  93345. "art.sn",
  93346. "com.sn",
  93347. "edu.sn",
  93348. "gouv.sn",
  93349. "org.sn",
  93350. "perso.sn",
  93351. "univ.sn",
  93352. "so",
  93353. "com.so",
  93354. "edu.so",
  93355. "gov.so",
  93356. "me.so",
  93357. "net.so",
  93358. "org.so",
  93359. "sr",
  93360. "ss",
  93361. "biz.ss",
  93362. "com.ss",
  93363. "edu.ss",
  93364. "gov.ss",
  93365. "net.ss",
  93366. "org.ss",
  93367. "st",
  93368. "co.st",
  93369. "com.st",
  93370. "consulado.st",
  93371. "edu.st",
  93372. "embaixada.st",
  93373. "gov.st",
  93374. "mil.st",
  93375. "net.st",
  93376. "org.st",
  93377. "principe.st",
  93378. "saotome.st",
  93379. "store.st",
  93380. "su",
  93381. "sv",
  93382. "com.sv",
  93383. "edu.sv",
  93384. "gob.sv",
  93385. "org.sv",
  93386. "red.sv",
  93387. "sx",
  93388. "gov.sx",
  93389. "sy",
  93390. "edu.sy",
  93391. "gov.sy",
  93392. "net.sy",
  93393. "mil.sy",
  93394. "com.sy",
  93395. "org.sy",
  93396. "sz",
  93397. "co.sz",
  93398. "ac.sz",
  93399. "org.sz",
  93400. "tc",
  93401. "td",
  93402. "tel",
  93403. "tf",
  93404. "tg",
  93405. "th",
  93406. "ac.th",
  93407. "co.th",
  93408. "go.th",
  93409. "in.th",
  93410. "mi.th",
  93411. "net.th",
  93412. "or.th",
  93413. "tj",
  93414. "ac.tj",
  93415. "biz.tj",
  93416. "co.tj",
  93417. "com.tj",
  93418. "edu.tj",
  93419. "go.tj",
  93420. "gov.tj",
  93421. "int.tj",
  93422. "mil.tj",
  93423. "name.tj",
  93424. "net.tj",
  93425. "nic.tj",
  93426. "org.tj",
  93427. "test.tj",
  93428. "web.tj",
  93429. "tk",
  93430. "tl",
  93431. "gov.tl",
  93432. "tm",
  93433. "com.tm",
  93434. "co.tm",
  93435. "org.tm",
  93436. "net.tm",
  93437. "nom.tm",
  93438. "gov.tm",
  93439. "mil.tm",
  93440. "edu.tm",
  93441. "tn",
  93442. "com.tn",
  93443. "ens.tn",
  93444. "fin.tn",
  93445. "gov.tn",
  93446. "ind.tn",
  93447. "intl.tn",
  93448. "nat.tn",
  93449. "net.tn",
  93450. "org.tn",
  93451. "info.tn",
  93452. "perso.tn",
  93453. "tourism.tn",
  93454. "edunet.tn",
  93455. "rnrt.tn",
  93456. "rns.tn",
  93457. "rnu.tn",
  93458. "mincom.tn",
  93459. "agrinet.tn",
  93460. "defense.tn",
  93461. "turen.tn",
  93462. "to",
  93463. "com.to",
  93464. "gov.to",
  93465. "net.to",
  93466. "org.to",
  93467. "edu.to",
  93468. "mil.to",
  93469. "tr",
  93470. "av.tr",
  93471. "bbs.tr",
  93472. "bel.tr",
  93473. "biz.tr",
  93474. "com.tr",
  93475. "dr.tr",
  93476. "edu.tr",
  93477. "gen.tr",
  93478. "gov.tr",
  93479. "info.tr",
  93480. "mil.tr",
  93481. "k12.tr",
  93482. "kep.tr",
  93483. "name.tr",
  93484. "net.tr",
  93485. "org.tr",
  93486. "pol.tr",
  93487. "tel.tr",
  93488. "tsk.tr",
  93489. "tv.tr",
  93490. "web.tr",
  93491. "nc.tr",
  93492. "gov.nc.tr",
  93493. "tt",
  93494. "co.tt",
  93495. "com.tt",
  93496. "org.tt",
  93497. "net.tt",
  93498. "biz.tt",
  93499. "info.tt",
  93500. "pro.tt",
  93501. "int.tt",
  93502. "coop.tt",
  93503. "jobs.tt",
  93504. "mobi.tt",
  93505. "travel.tt",
  93506. "museum.tt",
  93507. "aero.tt",
  93508. "name.tt",
  93509. "gov.tt",
  93510. "edu.tt",
  93511. "tv",
  93512. "tw",
  93513. "edu.tw",
  93514. "gov.tw",
  93515. "mil.tw",
  93516. "com.tw",
  93517. "net.tw",
  93518. "org.tw",
  93519. "idv.tw",
  93520. "game.tw",
  93521. "ebiz.tw",
  93522. "club.tw",
  93523. "網路.tw",
  93524. "組織.tw",
  93525. "商業.tw",
  93526. "tz",
  93527. "ac.tz",
  93528. "co.tz",
  93529. "go.tz",
  93530. "hotel.tz",
  93531. "info.tz",
  93532. "me.tz",
  93533. "mil.tz",
  93534. "mobi.tz",
  93535. "ne.tz",
  93536. "or.tz",
  93537. "sc.tz",
  93538. "tv.tz",
  93539. "ua",
  93540. "com.ua",
  93541. "edu.ua",
  93542. "gov.ua",
  93543. "in.ua",
  93544. "net.ua",
  93545. "org.ua",
  93546. "cherkassy.ua",
  93547. "cherkasy.ua",
  93548. "chernigov.ua",
  93549. "chernihiv.ua",
  93550. "chernivtsi.ua",
  93551. "chernovtsy.ua",
  93552. "ck.ua",
  93553. "cn.ua",
  93554. "cr.ua",
  93555. "crimea.ua",
  93556. "cv.ua",
  93557. "dn.ua",
  93558. "dnepropetrovsk.ua",
  93559. "dnipropetrovsk.ua",
  93560. "dominic.ua",
  93561. "donetsk.ua",
  93562. "dp.ua",
  93563. "if.ua",
  93564. "ivano-frankivsk.ua",
  93565. "kh.ua",
  93566. "kharkiv.ua",
  93567. "kharkov.ua",
  93568. "kherson.ua",
  93569. "khmelnitskiy.ua",
  93570. "khmelnytskyi.ua",
  93571. "kiev.ua",
  93572. "kirovograd.ua",
  93573. "km.ua",
  93574. "kr.ua",
  93575. "krym.ua",
  93576. "ks.ua",
  93577. "kv.ua",
  93578. "kyiv.ua",
  93579. "lg.ua",
  93580. "lt.ua",
  93581. "lugansk.ua",
  93582. "lutsk.ua",
  93583. "lv.ua",
  93584. "lviv.ua",
  93585. "mk.ua",
  93586. "mykolaiv.ua",
  93587. "nikolaev.ua",
  93588. "od.ua",
  93589. "odesa.ua",
  93590. "odessa.ua",
  93591. "pl.ua",
  93592. "poltava.ua",
  93593. "rivne.ua",
  93594. "rovno.ua",
  93595. "rv.ua",
  93596. "sb.ua",
  93597. "sebastopol.ua",
  93598. "sevastopol.ua",
  93599. "sm.ua",
  93600. "sumy.ua",
  93601. "te.ua",
  93602. "ternopil.ua",
  93603. "uz.ua",
  93604. "uzhgorod.ua",
  93605. "vinnica.ua",
  93606. "vinnytsia.ua",
  93607. "vn.ua",
  93608. "volyn.ua",
  93609. "yalta.ua",
  93610. "zaporizhzhe.ua",
  93611. "zaporizhzhia.ua",
  93612. "zhitomir.ua",
  93613. "zhytomyr.ua",
  93614. "zp.ua",
  93615. "zt.ua",
  93616. "ug",
  93617. "co.ug",
  93618. "or.ug",
  93619. "ac.ug",
  93620. "sc.ug",
  93621. "go.ug",
  93622. "ne.ug",
  93623. "com.ug",
  93624. "org.ug",
  93625. "uk",
  93626. "ac.uk",
  93627. "co.uk",
  93628. "gov.uk",
  93629. "ltd.uk",
  93630. "me.uk",
  93631. "net.uk",
  93632. "nhs.uk",
  93633. "org.uk",
  93634. "plc.uk",
  93635. "police.uk",
  93636. "*.sch.uk",
  93637. "us",
  93638. "dni.us",
  93639. "fed.us",
  93640. "isa.us",
  93641. "kids.us",
  93642. "nsn.us",
  93643. "ak.us",
  93644. "al.us",
  93645. "ar.us",
  93646. "as.us",
  93647. "az.us",
  93648. "ca.us",
  93649. "co.us",
  93650. "ct.us",
  93651. "dc.us",
  93652. "de.us",
  93653. "fl.us",
  93654. "ga.us",
  93655. "gu.us",
  93656. "hi.us",
  93657. "ia.us",
  93658. "id.us",
  93659. "il.us",
  93660. "in.us",
  93661. "ks.us",
  93662. "ky.us",
  93663. "la.us",
  93664. "ma.us",
  93665. "md.us",
  93666. "me.us",
  93667. "mi.us",
  93668. "mn.us",
  93669. "mo.us",
  93670. "ms.us",
  93671. "mt.us",
  93672. "nc.us",
  93673. "nd.us",
  93674. "ne.us",
  93675. "nh.us",
  93676. "nj.us",
  93677. "nm.us",
  93678. "nv.us",
  93679. "ny.us",
  93680. "oh.us",
  93681. "ok.us",
  93682. "or.us",
  93683. "pa.us",
  93684. "pr.us",
  93685. "ri.us",
  93686. "sc.us",
  93687. "sd.us",
  93688. "tn.us",
  93689. "tx.us",
  93690. "ut.us",
  93691. "vi.us",
  93692. "vt.us",
  93693. "va.us",
  93694. "wa.us",
  93695. "wi.us",
  93696. "wv.us",
  93697. "wy.us",
  93698. "k12.ak.us",
  93699. "k12.al.us",
  93700. "k12.ar.us",
  93701. "k12.as.us",
  93702. "k12.az.us",
  93703. "k12.ca.us",
  93704. "k12.co.us",
  93705. "k12.ct.us",
  93706. "k12.dc.us",
  93707. "k12.de.us",
  93708. "k12.fl.us",
  93709. "k12.ga.us",
  93710. "k12.gu.us",
  93711. "k12.ia.us",
  93712. "k12.id.us",
  93713. "k12.il.us",
  93714. "k12.in.us",
  93715. "k12.ks.us",
  93716. "k12.ky.us",
  93717. "k12.la.us",
  93718. "k12.ma.us",
  93719. "k12.md.us",
  93720. "k12.me.us",
  93721. "k12.mi.us",
  93722. "k12.mn.us",
  93723. "k12.mo.us",
  93724. "k12.ms.us",
  93725. "k12.mt.us",
  93726. "k12.nc.us",
  93727. "k12.ne.us",
  93728. "k12.nh.us",
  93729. "k12.nj.us",
  93730. "k12.nm.us",
  93731. "k12.nv.us",
  93732. "k12.ny.us",
  93733. "k12.oh.us",
  93734. "k12.ok.us",
  93735. "k12.or.us",
  93736. "k12.pa.us",
  93737. "k12.pr.us",
  93738. "k12.ri.us",
  93739. "k12.sc.us",
  93740. "k12.tn.us",
  93741. "k12.tx.us",
  93742. "k12.ut.us",
  93743. "k12.vi.us",
  93744. "k12.vt.us",
  93745. "k12.va.us",
  93746. "k12.wa.us",
  93747. "k12.wi.us",
  93748. "k12.wy.us",
  93749. "cc.ak.us",
  93750. "cc.al.us",
  93751. "cc.ar.us",
  93752. "cc.as.us",
  93753. "cc.az.us",
  93754. "cc.ca.us",
  93755. "cc.co.us",
  93756. "cc.ct.us",
  93757. "cc.dc.us",
  93758. "cc.de.us",
  93759. "cc.fl.us",
  93760. "cc.ga.us",
  93761. "cc.gu.us",
  93762. "cc.hi.us",
  93763. "cc.ia.us",
  93764. "cc.id.us",
  93765. "cc.il.us",
  93766. "cc.in.us",
  93767. "cc.ks.us",
  93768. "cc.ky.us",
  93769. "cc.la.us",
  93770. "cc.ma.us",
  93771. "cc.md.us",
  93772. "cc.me.us",
  93773. "cc.mi.us",
  93774. "cc.mn.us",
  93775. "cc.mo.us",
  93776. "cc.ms.us",
  93777. "cc.mt.us",
  93778. "cc.nc.us",
  93779. "cc.nd.us",
  93780. "cc.ne.us",
  93781. "cc.nh.us",
  93782. "cc.nj.us",
  93783. "cc.nm.us",
  93784. "cc.nv.us",
  93785. "cc.ny.us",
  93786. "cc.oh.us",
  93787. "cc.ok.us",
  93788. "cc.or.us",
  93789. "cc.pa.us",
  93790. "cc.pr.us",
  93791. "cc.ri.us",
  93792. "cc.sc.us",
  93793. "cc.sd.us",
  93794. "cc.tn.us",
  93795. "cc.tx.us",
  93796. "cc.ut.us",
  93797. "cc.vi.us",
  93798. "cc.vt.us",
  93799. "cc.va.us",
  93800. "cc.wa.us",
  93801. "cc.wi.us",
  93802. "cc.wv.us",
  93803. "cc.wy.us",
  93804. "lib.ak.us",
  93805. "lib.al.us",
  93806. "lib.ar.us",
  93807. "lib.as.us",
  93808. "lib.az.us",
  93809. "lib.ca.us",
  93810. "lib.co.us",
  93811. "lib.ct.us",
  93812. "lib.dc.us",
  93813. "lib.fl.us",
  93814. "lib.ga.us",
  93815. "lib.gu.us",
  93816. "lib.hi.us",
  93817. "lib.ia.us",
  93818. "lib.id.us",
  93819. "lib.il.us",
  93820. "lib.in.us",
  93821. "lib.ks.us",
  93822. "lib.ky.us",
  93823. "lib.la.us",
  93824. "lib.ma.us",
  93825. "lib.md.us",
  93826. "lib.me.us",
  93827. "lib.mi.us",
  93828. "lib.mn.us",
  93829. "lib.mo.us",
  93830. "lib.ms.us",
  93831. "lib.mt.us",
  93832. "lib.nc.us",
  93833. "lib.nd.us",
  93834. "lib.ne.us",
  93835. "lib.nh.us",
  93836. "lib.nj.us",
  93837. "lib.nm.us",
  93838. "lib.nv.us",
  93839. "lib.ny.us",
  93840. "lib.oh.us",
  93841. "lib.ok.us",
  93842. "lib.or.us",
  93843. "lib.pa.us",
  93844. "lib.pr.us",
  93845. "lib.ri.us",
  93846. "lib.sc.us",
  93847. "lib.sd.us",
  93848. "lib.tn.us",
  93849. "lib.tx.us",
  93850. "lib.ut.us",
  93851. "lib.vi.us",
  93852. "lib.vt.us",
  93853. "lib.va.us",
  93854. "lib.wa.us",
  93855. "lib.wi.us",
  93856. "lib.wy.us",
  93857. "pvt.k12.ma.us",
  93858. "chtr.k12.ma.us",
  93859. "paroch.k12.ma.us",
  93860. "ann-arbor.mi.us",
  93861. "cog.mi.us",
  93862. "dst.mi.us",
  93863. "eaton.mi.us",
  93864. "gen.mi.us",
  93865. "mus.mi.us",
  93866. "tec.mi.us",
  93867. "washtenaw.mi.us",
  93868. "uy",
  93869. "com.uy",
  93870. "edu.uy",
  93871. "gub.uy",
  93872. "mil.uy",
  93873. "net.uy",
  93874. "org.uy",
  93875. "uz",
  93876. "co.uz",
  93877. "com.uz",
  93878. "net.uz",
  93879. "org.uz",
  93880. "va",
  93881. "vc",
  93882. "com.vc",
  93883. "net.vc",
  93884. "org.vc",
  93885. "gov.vc",
  93886. "mil.vc",
  93887. "edu.vc",
  93888. "ve",
  93889. "arts.ve",
  93890. "co.ve",
  93891. "com.ve",
  93892. "e12.ve",
  93893. "edu.ve",
  93894. "firm.ve",
  93895. "gob.ve",
  93896. "gov.ve",
  93897. "info.ve",
  93898. "int.ve",
  93899. "mil.ve",
  93900. "net.ve",
  93901. "org.ve",
  93902. "rec.ve",
  93903. "store.ve",
  93904. "tec.ve",
  93905. "web.ve",
  93906. "vg",
  93907. "vi",
  93908. "co.vi",
  93909. "com.vi",
  93910. "k12.vi",
  93911. "net.vi",
  93912. "org.vi",
  93913. "vn",
  93914. "com.vn",
  93915. "net.vn",
  93916. "org.vn",
  93917. "edu.vn",
  93918. "gov.vn",
  93919. "int.vn",
  93920. "ac.vn",
  93921. "biz.vn",
  93922. "info.vn",
  93923. "name.vn",
  93924. "pro.vn",
  93925. "health.vn",
  93926. "vu",
  93927. "com.vu",
  93928. "edu.vu",
  93929. "net.vu",
  93930. "org.vu",
  93931. "wf",
  93932. "ws",
  93933. "com.ws",
  93934. "net.ws",
  93935. "org.ws",
  93936. "gov.ws",
  93937. "edu.ws",
  93938. "yt",
  93939. "امارات",
  93940. "հայ",
  93941. "বাংলা",
  93942. "бг",
  93943. "бел",
  93944. "中国",
  93945. "中國",
  93946. "الجزائر",
  93947. "مصر",
  93948. "ею",
  93949. "ευ",
  93950. "موريتانيا",
  93951. "გე",
  93952. "ελ",
  93953. "香港",
  93954. "公司.香港",
  93955. "教育.香港",
  93956. "政府.香港",
  93957. "個人.香港",
  93958. "網絡.香港",
  93959. "組織.香港",
  93960. "ಭಾರತ",
  93961. "ଭାରତ",
  93962. "ভাৰত",
  93963. "भारतम्",
  93964. "भारोत",
  93965. "ڀارت",
  93966. "ഭാരതം",
  93967. "भारत",
  93968. "بارت",
  93969. "بھارت",
  93970. "భారత్",
  93971. "ભારત",
  93972. "ਭਾਰਤ",
  93973. "ভারত",
  93974. "இந்தியா",
  93975. "ایران",
  93976. "ايران",
  93977. "عراق",
  93978. "الاردن",
  93979. "한국",
  93980. "қаз",
  93981. "ලංකා",
  93982. "இலங்கை",
  93983. "المغرب",
  93984. "мкд",
  93985. "мон",
  93986. "澳門",
  93987. "澳门",
  93988. "مليسيا",
  93989. "عمان",
  93990. "پاکستان",
  93991. "پاكستان",
  93992. "فلسطين",
  93993. "срб",
  93994. "пр.срб",
  93995. "орг.срб",
  93996. "обр.срб",
  93997. "од.срб",
  93998. "упр.срб",
  93999. "ак.срб",
  94000. "рф",
  94001. "قطر",
  94002. "السعودية",
  94003. "السعودیة",
  94004. "السعودیۃ",
  94005. "السعوديه",
  94006. "سودان",
  94007. "新加坡",
  94008. "சிங்கப்பூர்",
  94009. "سورية",
  94010. "سوريا",
  94011. "ไทย",
  94012. "ศึกษา.ไทย",
  94013. "ธุรกิจ.ไทย",
  94014. "รัฐบาล.ไทย",
  94015. "ทหาร.ไทย",
  94016. "เน็ต.ไทย",
  94017. "องค์กร.ไทย",
  94018. "تونس",
  94019. "台灣",
  94020. "台湾",
  94021. "臺灣",
  94022. "укр",
  94023. "اليمن",
  94024. "xxx",
  94025. "*.ye",
  94026. "ac.za",
  94027. "agric.za",
  94028. "alt.za",
  94029. "co.za",
  94030. "edu.za",
  94031. "gov.za",
  94032. "grondar.za",
  94033. "law.za",
  94034. "mil.za",
  94035. "net.za",
  94036. "ngo.za",
  94037. "nic.za",
  94038. "nis.za",
  94039. "nom.za",
  94040. "org.za",
  94041. "school.za",
  94042. "tm.za",
  94043. "web.za",
  94044. "zm",
  94045. "ac.zm",
  94046. "biz.zm",
  94047. "co.zm",
  94048. "com.zm",
  94049. "edu.zm",
  94050. "gov.zm",
  94051. "info.zm",
  94052. "mil.zm",
  94053. "net.zm",
  94054. "org.zm",
  94055. "sch.zm",
  94056. "zw",
  94057. "ac.zw",
  94058. "co.zw",
  94059. "gov.zw",
  94060. "mil.zw",
  94061. "org.zw",
  94062. "aaa",
  94063. "aarp",
  94064. "abarth",
  94065. "abb",
  94066. "abbott",
  94067. "abbvie",
  94068. "abc",
  94069. "able",
  94070. "abogado",
  94071. "abudhabi",
  94072. "academy",
  94073. "accenture",
  94074. "accountant",
  94075. "accountants",
  94076. "aco",
  94077. "actor",
  94078. "adac",
  94079. "ads",
  94080. "adult",
  94081. "aeg",
  94082. "aetna",
  94083. "afamilycompany",
  94084. "afl",
  94085. "africa",
  94086. "agakhan",
  94087. "agency",
  94088. "aig",
  94089. "aigo",
  94090. "airbus",
  94091. "airforce",
  94092. "airtel",
  94093. "akdn",
  94094. "alfaromeo",
  94095. "alibaba",
  94096. "alipay",
  94097. "allfinanz",
  94098. "allstate",
  94099. "ally",
  94100. "alsace",
  94101. "alstom",
  94102. "amazon",
  94103. "americanexpress",
  94104. "americanfamily",
  94105. "amex",
  94106. "amfam",
  94107. "amica",
  94108. "amsterdam",
  94109. "analytics",
  94110. "android",
  94111. "anquan",
  94112. "anz",
  94113. "aol",
  94114. "apartments",
  94115. "app",
  94116. "apple",
  94117. "aquarelle",
  94118. "arab",
  94119. "aramco",
  94120. "archi",
  94121. "army",
  94122. "art",
  94123. "arte",
  94124. "asda",
  94125. "associates",
  94126. "athleta",
  94127. "attorney",
  94128. "auction",
  94129. "audi",
  94130. "audible",
  94131. "audio",
  94132. "auspost",
  94133. "author",
  94134. "auto",
  94135. "autos",
  94136. "avianca",
  94137. "aws",
  94138. "axa",
  94139. "azure",
  94140. "baby",
  94141. "baidu",
  94142. "banamex",
  94143. "bananarepublic",
  94144. "band",
  94145. "bank",
  94146. "bar",
  94147. "barcelona",
  94148. "barclaycard",
  94149. "barclays",
  94150. "barefoot",
  94151. "bargains",
  94152. "baseball",
  94153. "basketball",
  94154. "bauhaus",
  94155. "bayern",
  94156. "bbc",
  94157. "bbt",
  94158. "bbva",
  94159. "bcg",
  94160. "bcn",
  94161. "beats",
  94162. "beauty",
  94163. "beer",
  94164. "bentley",
  94165. "berlin",
  94166. "best",
  94167. "bestbuy",
  94168. "bet",
  94169. "bharti",
  94170. "bible",
  94171. "bid",
  94172. "bike",
  94173. "bing",
  94174. "bingo",
  94175. "bio",
  94176. "black",
  94177. "blackfriday",
  94178. "blockbuster",
  94179. "blog",
  94180. "bloomberg",
  94181. "blue",
  94182. "bms",
  94183. "bmw",
  94184. "bnpparibas",
  94185. "boats",
  94186. "boehringer",
  94187. "bofa",
  94188. "bom",
  94189. "bond",
  94190. "boo",
  94191. "book",
  94192. "booking",
  94193. "bosch",
  94194. "bostik",
  94195. "boston",
  94196. "bot",
  94197. "boutique",
  94198. "box",
  94199. "bradesco",
  94200. "bridgestone",
  94201. "broadway",
  94202. "broker",
  94203. "brother",
  94204. "brussels",
  94205. "budapest",
  94206. "bugatti",
  94207. "build",
  94208. "builders",
  94209. "business",
  94210. "buy",
  94211. "buzz",
  94212. "bzh",
  94213. "cab",
  94214. "cafe",
  94215. "cal",
  94216. "call",
  94217. "calvinklein",
  94218. "cam",
  94219. "camera",
  94220. "camp",
  94221. "cancerresearch",
  94222. "canon",
  94223. "capetown",
  94224. "capital",
  94225. "capitalone",
  94226. "car",
  94227. "caravan",
  94228. "cards",
  94229. "care",
  94230. "career",
  94231. "careers",
  94232. "cars",
  94233. "casa",
  94234. "case",
  94235. "caseih",
  94236. "cash",
  94237. "casino",
  94238. "catering",
  94239. "catholic",
  94240. "cba",
  94241. "cbn",
  94242. "cbre",
  94243. "cbs",
  94244. "ceb",
  94245. "center",
  94246. "ceo",
  94247. "cern",
  94248. "cfa",
  94249. "cfd",
  94250. "chanel",
  94251. "channel",
  94252. "charity",
  94253. "chase",
  94254. "chat",
  94255. "cheap",
  94256. "chintai",
  94257. "christmas",
  94258. "chrome",
  94259. "church",
  94260. "cipriani",
  94261. "circle",
  94262. "cisco",
  94263. "citadel",
  94264. "citi",
  94265. "citic",
  94266. "city",
  94267. "cityeats",
  94268. "claims",
  94269. "cleaning",
  94270. "click",
  94271. "clinic",
  94272. "clinique",
  94273. "clothing",
  94274. "cloud",
  94275. "club",
  94276. "clubmed",
  94277. "coach",
  94278. "codes",
  94279. "coffee",
  94280. "college",
  94281. "cologne",
  94282. "comcast",
  94283. "commbank",
  94284. "community",
  94285. "company",
  94286. "compare",
  94287. "computer",
  94288. "comsec",
  94289. "condos",
  94290. "construction",
  94291. "consulting",
  94292. "contact",
  94293. "contractors",
  94294. "cooking",
  94295. "cookingchannel",
  94296. "cool",
  94297. "corsica",
  94298. "country",
  94299. "coupon",
  94300. "coupons",
  94301. "courses",
  94302. "cpa",
  94303. "credit",
  94304. "creditcard",
  94305. "creditunion",
  94306. "cricket",
  94307. "crown",
  94308. "crs",
  94309. "cruise",
  94310. "cruises",
  94311. "csc",
  94312. "cuisinella",
  94313. "cymru",
  94314. "cyou",
  94315. "dabur",
  94316. "dad",
  94317. "dance",
  94318. "data",
  94319. "date",
  94320. "dating",
  94321. "datsun",
  94322. "day",
  94323. "dclk",
  94324. "dds",
  94325. "deal",
  94326. "dealer",
  94327. "deals",
  94328. "degree",
  94329. "delivery",
  94330. "dell",
  94331. "deloitte",
  94332. "delta",
  94333. "democrat",
  94334. "dental",
  94335. "dentist",
  94336. "desi",
  94337. "design",
  94338. "dev",
  94339. "dhl",
  94340. "diamonds",
  94341. "diet",
  94342. "digital",
  94343. "direct",
  94344. "directory",
  94345. "discount",
  94346. "discover",
  94347. "dish",
  94348. "diy",
  94349. "dnp",
  94350. "docs",
  94351. "doctor",
  94352. "dog",
  94353. "domains",
  94354. "dot",
  94355. "download",
  94356. "drive",
  94357. "dtv",
  94358. "dubai",
  94359. "duck",
  94360. "dunlop",
  94361. "dupont",
  94362. "durban",
  94363. "dvag",
  94364. "dvr",
  94365. "earth",
  94366. "eat",
  94367. "eco",
  94368. "edeka",
  94369. "education",
  94370. "email",
  94371. "emerck",
  94372. "energy",
  94373. "engineer",
  94374. "engineering",
  94375. "enterprises",
  94376. "epson",
  94377. "equipment",
  94378. "ericsson",
  94379. "erni",
  94380. "esq",
  94381. "estate",
  94382. "esurance",
  94383. "etisalat",
  94384. "eurovision",
  94385. "eus",
  94386. "events",
  94387. "exchange",
  94388. "expert",
  94389. "exposed",
  94390. "express",
  94391. "extraspace",
  94392. "fage",
  94393. "fail",
  94394. "fairwinds",
  94395. "faith",
  94396. "family",
  94397. "fan",
  94398. "fans",
  94399. "farm",
  94400. "farmers",
  94401. "fashion",
  94402. "fast",
  94403. "fedex",
  94404. "feedback",
  94405. "ferrari",
  94406. "ferrero",
  94407. "fiat",
  94408. "fidelity",
  94409. "fido",
  94410. "film",
  94411. "final",
  94412. "finance",
  94413. "financial",
  94414. "fire",
  94415. "firestone",
  94416. "firmdale",
  94417. "fish",
  94418. "fishing",
  94419. "fit",
  94420. "fitness",
  94421. "flickr",
  94422. "flights",
  94423. "flir",
  94424. "florist",
  94425. "flowers",
  94426. "fly",
  94427. "foo",
  94428. "food",
  94429. "foodnetwork",
  94430. "football",
  94431. "ford",
  94432. "forex",
  94433. "forsale",
  94434. "forum",
  94435. "foundation",
  94436. "fox",
  94437. "free",
  94438. "fresenius",
  94439. "frl",
  94440. "frogans",
  94441. "frontdoor",
  94442. "frontier",
  94443. "ftr",
  94444. "fujitsu",
  94445. "fujixerox",
  94446. "fun",
  94447. "fund",
  94448. "furniture",
  94449. "futbol",
  94450. "fyi",
  94451. "gal",
  94452. "gallery",
  94453. "gallo",
  94454. "gallup",
  94455. "game",
  94456. "games",
  94457. "gap",
  94458. "garden",
  94459. "gay",
  94460. "gbiz",
  94461. "gdn",
  94462. "gea",
  94463. "gent",
  94464. "genting",
  94465. "george",
  94466. "ggee",
  94467. "gift",
  94468. "gifts",
  94469. "gives",
  94470. "giving",
  94471. "glade",
  94472. "glass",
  94473. "gle",
  94474. "global",
  94475. "globo",
  94476. "gmail",
  94477. "gmbh",
  94478. "gmo",
  94479. "gmx",
  94480. "godaddy",
  94481. "gold",
  94482. "goldpoint",
  94483. "golf",
  94484. "goo",
  94485. "goodyear",
  94486. "goog",
  94487. "google",
  94488. "gop",
  94489. "got",
  94490. "grainger",
  94491. "graphics",
  94492. "gratis",
  94493. "green",
  94494. "gripe",
  94495. "grocery",
  94496. "group",
  94497. "guardian",
  94498. "gucci",
  94499. "guge",
  94500. "guide",
  94501. "guitars",
  94502. "guru",
  94503. "hair",
  94504. "hamburg",
  94505. "hangout",
  94506. "haus",
  94507. "hbo",
  94508. "hdfc",
  94509. "hdfcbank",
  94510. "health",
  94511. "healthcare",
  94512. "help",
  94513. "helsinki",
  94514. "here",
  94515. "hermes",
  94516. "hgtv",
  94517. "hiphop",
  94518. "hisamitsu",
  94519. "hitachi",
  94520. "hiv",
  94521. "hkt",
  94522. "hockey",
  94523. "holdings",
  94524. "holiday",
  94525. "homedepot",
  94526. "homegoods",
  94527. "homes",
  94528. "homesense",
  94529. "honda",
  94530. "horse",
  94531. "hospital",
  94532. "host",
  94533. "hosting",
  94534. "hot",
  94535. "hoteles",
  94536. "hotels",
  94537. "hotmail",
  94538. "house",
  94539. "how",
  94540. "hsbc",
  94541. "hughes",
  94542. "hyatt",
  94543. "hyundai",
  94544. "ibm",
  94545. "icbc",
  94546. "ice",
  94547. "icu",
  94548. "ieee",
  94549. "ifm",
  94550. "ikano",
  94551. "imamat",
  94552. "imdb",
  94553. "immo",
  94554. "immobilien",
  94555. "inc",
  94556. "industries",
  94557. "infiniti",
  94558. "ing",
  94559. "ink",
  94560. "institute",
  94561. "insurance",
  94562. "insure",
  94563. "intel",
  94564. "international",
  94565. "intuit",
  94566. "investments",
  94567. "ipiranga",
  94568. "irish",
  94569. "ismaili",
  94570. "ist",
  94571. "istanbul",
  94572. "itau",
  94573. "itv",
  94574. "iveco",
  94575. "jaguar",
  94576. "java",
  94577. "jcb",
  94578. "jcp",
  94579. "jeep",
  94580. "jetzt",
  94581. "jewelry",
  94582. "jio",
  94583. "jll",
  94584. "jmp",
  94585. "jnj",
  94586. "joburg",
  94587. "jot",
  94588. "joy",
  94589. "jpmorgan",
  94590. "jprs",
  94591. "juegos",
  94592. "juniper",
  94593. "kaufen",
  94594. "kddi",
  94595. "kerryhotels",
  94596. "kerrylogistics",
  94597. "kerryproperties",
  94598. "kfh",
  94599. "kia",
  94600. "kim",
  94601. "kinder",
  94602. "kindle",
  94603. "kitchen",
  94604. "kiwi",
  94605. "koeln",
  94606. "komatsu",
  94607. "kosher",
  94608. "kpmg",
  94609. "kpn",
  94610. "krd",
  94611. "kred",
  94612. "kuokgroup",
  94613. "kyoto",
  94614. "lacaixa",
  94615. "lamborghini",
  94616. "lamer",
  94617. "lancaster",
  94618. "lancia",
  94619. "land",
  94620. "landrover",
  94621. "lanxess",
  94622. "lasalle",
  94623. "lat",
  94624. "latino",
  94625. "latrobe",
  94626. "law",
  94627. "lawyer",
  94628. "lds",
  94629. "lease",
  94630. "leclerc",
  94631. "lefrak",
  94632. "legal",
  94633. "lego",
  94634. "lexus",
  94635. "lgbt",
  94636. "lidl",
  94637. "life",
  94638. "lifeinsurance",
  94639. "lifestyle",
  94640. "lighting",
  94641. "like",
  94642. "lilly",
  94643. "limited",
  94644. "limo",
  94645. "lincoln",
  94646. "linde",
  94647. "link",
  94648. "lipsy",
  94649. "live",
  94650. "living",
  94651. "lixil",
  94652. "llc",
  94653. "llp",
  94654. "loan",
  94655. "loans",
  94656. "locker",
  94657. "locus",
  94658. "loft",
  94659. "lol",
  94660. "london",
  94661. "lotte",
  94662. "lotto",
  94663. "love",
  94664. "lpl",
  94665. "lplfinancial",
  94666. "ltd",
  94667. "ltda",
  94668. "lundbeck",
  94669. "lupin",
  94670. "luxe",
  94671. "luxury",
  94672. "macys",
  94673. "madrid",
  94674. "maif",
  94675. "maison",
  94676. "makeup",
  94677. "man",
  94678. "management",
  94679. "mango",
  94680. "map",
  94681. "market",
  94682. "marketing",
  94683. "markets",
  94684. "marriott",
  94685. "marshalls",
  94686. "maserati",
  94687. "mattel",
  94688. "mba",
  94689. "mckinsey",
  94690. "med",
  94691. "media",
  94692. "meet",
  94693. "melbourne",
  94694. "meme",
  94695. "memorial",
  94696. "men",
  94697. "menu",
  94698. "merckmsd",
  94699. "metlife",
  94700. "miami",
  94701. "microsoft",
  94702. "mini",
  94703. "mint",
  94704. "mit",
  94705. "mitsubishi",
  94706. "mlb",
  94707. "mls",
  94708. "mma",
  94709. "mobile",
  94710. "moda",
  94711. "moe",
  94712. "moi",
  94713. "mom",
  94714. "monash",
  94715. "money",
  94716. "monster",
  94717. "mormon",
  94718. "mortgage",
  94719. "moscow",
  94720. "moto",
  94721. "motorcycles",
  94722. "mov",
  94723. "movie",
  94724. "msd",
  94725. "mtn",
  94726. "mtr",
  94727. "mutual",
  94728. "nab",
  94729. "nadex",
  94730. "nagoya",
  94731. "nationwide",
  94732. "natura",
  94733. "navy",
  94734. "nba",
  94735. "nec",
  94736. "netbank",
  94737. "netflix",
  94738. "network",
  94739. "neustar",
  94740. "new",
  94741. "newholland",
  94742. "news",
  94743. "next",
  94744. "nextdirect",
  94745. "nexus",
  94746. "nfl",
  94747. "ngo",
  94748. "nhk",
  94749. "nico",
  94750. "nike",
  94751. "nikon",
  94752. "ninja",
  94753. "nissan",
  94754. "nissay",
  94755. "nokia",
  94756. "northwesternmutual",
  94757. "norton",
  94758. "now",
  94759. "nowruz",
  94760. "nowtv",
  94761. "nra",
  94762. "nrw",
  94763. "ntt",
  94764. "nyc",
  94765. "obi",
  94766. "observer",
  94767. "off",
  94768. "office",
  94769. "okinawa",
  94770. "olayan",
  94771. "olayangroup",
  94772. "oldnavy",
  94773. "ollo",
  94774. "omega",
  94775. "one",
  94776. "ong",
  94777. "onl",
  94778. "online",
  94779. "onyourside",
  94780. "ooo",
  94781. "open",
  94782. "oracle",
  94783. "orange",
  94784. "organic",
  94785. "origins",
  94786. "osaka",
  94787. "otsuka",
  94788. "ott",
  94789. "ovh",
  94790. "page",
  94791. "panasonic",
  94792. "paris",
  94793. "pars",
  94794. "partners",
  94795. "parts",
  94796. "party",
  94797. "passagens",
  94798. "pay",
  94799. "pccw",
  94800. "pet",
  94801. "pfizer",
  94802. "pharmacy",
  94803. "phd",
  94804. "philips",
  94805. "phone",
  94806. "photo",
  94807. "photography",
  94808. "photos",
  94809. "physio",
  94810. "pics",
  94811. "pictet",
  94812. "pictures",
  94813. "pid",
  94814. "pin",
  94815. "ping",
  94816. "pink",
  94817. "pioneer",
  94818. "pizza",
  94819. "place",
  94820. "play",
  94821. "playstation",
  94822. "plumbing",
  94823. "plus",
  94824. "pnc",
  94825. "pohl",
  94826. "poker",
  94827. "politie",
  94828. "porn",
  94829. "pramerica",
  94830. "praxi",
  94831. "press",
  94832. "prime",
  94833. "prod",
  94834. "productions",
  94835. "prof",
  94836. "progressive",
  94837. "promo",
  94838. "properties",
  94839. "property",
  94840. "protection",
  94841. "pru",
  94842. "prudential",
  94843. "pub",
  94844. "pwc",
  94845. "qpon",
  94846. "quebec",
  94847. "quest",
  94848. "qvc",
  94849. "racing",
  94850. "radio",
  94851. "raid",
  94852. "read",
  94853. "realestate",
  94854. "realtor",
  94855. "realty",
  94856. "recipes",
  94857. "red",
  94858. "redstone",
  94859. "redumbrella",
  94860. "rehab",
  94861. "reise",
  94862. "reisen",
  94863. "reit",
  94864. "reliance",
  94865. "ren",
  94866. "rent",
  94867. "rentals",
  94868. "repair",
  94869. "report",
  94870. "republican",
  94871. "rest",
  94872. "restaurant",
  94873. "review",
  94874. "reviews",
  94875. "rexroth",
  94876. "rich",
  94877. "richardli",
  94878. "ricoh",
  94879. "rightathome",
  94880. "ril",
  94881. "rio",
  94882. "rip",
  94883. "rmit",
  94884. "rocher",
  94885. "rocks",
  94886. "rodeo",
  94887. "rogers",
  94888. "room",
  94889. "rsvp",
  94890. "rugby",
  94891. "ruhr",
  94892. "run",
  94893. "rwe",
  94894. "ryukyu",
  94895. "saarland",
  94896. "safe",
  94897. "safety",
  94898. "sakura",
  94899. "sale",
  94900. "salon",
  94901. "samsclub",
  94902. "samsung",
  94903. "sandvik",
  94904. "sandvikcoromant",
  94905. "sanofi",
  94906. "sap",
  94907. "sarl",
  94908. "sas",
  94909. "save",
  94910. "saxo",
  94911. "sbi",
  94912. "sbs",
  94913. "sca",
  94914. "scb",
  94915. "schaeffler",
  94916. "schmidt",
  94917. "scholarships",
  94918. "school",
  94919. "schule",
  94920. "schwarz",
  94921. "science",
  94922. "scjohnson",
  94923. "scor",
  94924. "scot",
  94925. "search",
  94926. "seat",
  94927. "secure",
  94928. "security",
  94929. "seek",
  94930. "select",
  94931. "sener",
  94932. "services",
  94933. "ses",
  94934. "seven",
  94935. "sew",
  94936. "sex",
  94937. "sexy",
  94938. "sfr",
  94939. "shangrila",
  94940. "sharp",
  94941. "shaw",
  94942. "shell",
  94943. "shia",
  94944. "shiksha",
  94945. "shoes",
  94946. "shop",
  94947. "shopping",
  94948. "shouji",
  94949. "show",
  94950. "showtime",
  94951. "shriram",
  94952. "silk",
  94953. "sina",
  94954. "singles",
  94955. "site",
  94956. "ski",
  94957. "skin",
  94958. "sky",
  94959. "skype",
  94960. "sling",
  94961. "smart",
  94962. "smile",
  94963. "sncf",
  94964. "soccer",
  94965. "social",
  94966. "softbank",
  94967. "software",
  94968. "sohu",
  94969. "solar",
  94970. "solutions",
  94971. "song",
  94972. "sony",
  94973. "soy",
  94974. "spa",
  94975. "space",
  94976. "sport",
  94977. "spot",
  94978. "spreadbetting",
  94979. "srl",
  94980. "stada",
  94981. "staples",
  94982. "star",
  94983. "statebank",
  94984. "statefarm",
  94985. "stc",
  94986. "stcgroup",
  94987. "stockholm",
  94988. "storage",
  94989. "store",
  94990. "stream",
  94991. "studio",
  94992. "study",
  94993. "style",
  94994. "sucks",
  94995. "supplies",
  94996. "supply",
  94997. "support",
  94998. "surf",
  94999. "surgery",
  95000. "suzuki",
  95001. "swatch",
  95002. "swiftcover",
  95003. "swiss",
  95004. "sydney",
  95005. "symantec",
  95006. "systems",
  95007. "tab",
  95008. "taipei",
  95009. "talk",
  95010. "taobao",
  95011. "target",
  95012. "tatamotors",
  95013. "tatar",
  95014. "tattoo",
  95015. "tax",
  95016. "taxi",
  95017. "tci",
  95018. "tdk",
  95019. "team",
  95020. "tech",
  95021. "technology",
  95022. "temasek",
  95023. "tennis",
  95024. "teva",
  95025. "thd",
  95026. "theater",
  95027. "theatre",
  95028. "tiaa",
  95029. "tickets",
  95030. "tienda",
  95031. "tiffany",
  95032. "tips",
  95033. "tires",
  95034. "tirol",
  95035. "tjmaxx",
  95036. "tjx",
  95037. "tkmaxx",
  95038. "tmall",
  95039. "today",
  95040. "tokyo",
  95041. "tools",
  95042. "top",
  95043. "toray",
  95044. "toshiba",
  95045. "total",
  95046. "tours",
  95047. "town",
  95048. "toyota",
  95049. "toys",
  95050. "trade",
  95051. "trading",
  95052. "training",
  95053. "travel",
  95054. "travelchannel",
  95055. "travelers",
  95056. "travelersinsurance",
  95057. "trust",
  95058. "trv",
  95059. "tube",
  95060. "tui",
  95061. "tunes",
  95062. "tushu",
  95063. "tvs",
  95064. "ubank",
  95065. "ubs",
  95066. "unicom",
  95067. "university",
  95068. "uno",
  95069. "uol",
  95070. "ups",
  95071. "vacations",
  95072. "vana",
  95073. "vanguard",
  95074. "vegas",
  95075. "ventures",
  95076. "verisign",
  95077. "versicherung",
  95078. "vet",
  95079. "viajes",
  95080. "video",
  95081. "vig",
  95082. "viking",
  95083. "villas",
  95084. "vin",
  95085. "vip",
  95086. "virgin",
  95087. "visa",
  95088. "vision",
  95089. "viva",
  95090. "vivo",
  95091. "vlaanderen",
  95092. "vodka",
  95093. "volkswagen",
  95094. "volvo",
  95095. "vote",
  95096. "voting",
  95097. "voto",
  95098. "voyage",
  95099. "vuelos",
  95100. "wales",
  95101. "walmart",
  95102. "walter",
  95103. "wang",
  95104. "wanggou",
  95105. "watch",
  95106. "watches",
  95107. "weather",
  95108. "weatherchannel",
  95109. "webcam",
  95110. "weber",
  95111. "website",
  95112. "wed",
  95113. "wedding",
  95114. "weibo",
  95115. "weir",
  95116. "whoswho",
  95117. "wien",
  95118. "wiki",
  95119. "williamhill",
  95120. "win",
  95121. "windows",
  95122. "wine",
  95123. "winners",
  95124. "wme",
  95125. "wolterskluwer",
  95126. "woodside",
  95127. "work",
  95128. "works",
  95129. "world",
  95130. "wow",
  95131. "wtc",
  95132. "wtf",
  95133. "xbox",
  95134. "xerox",
  95135. "xfinity",
  95136. "xihuan",
  95137. "xin",
  95138. "कॉम",
  95139. "セール",
  95140. "佛山",
  95141. "慈善",
  95142. "集团",
  95143. "在线",
  95144. "大众汽车",
  95145. "点看",
  95146. "คอม",
  95147. "八卦",
  95148. "موقع",
  95149. "公益",
  95150. "公司",
  95151. "香格里拉",
  95152. "网站",
  95153. "移动",
  95154. "我爱你",
  95155. "москва",
  95156. "католик",
  95157. "онлайн",
  95158. "сайт",
  95159. "联通",
  95160. "קום",
  95161. "时尚",
  95162. "微博",
  95163. "淡马锡",
  95164. "ファッション",
  95165. "орг",
  95166. "नेट",
  95167. "ストア",
  95168. "アマゾン",
  95169. "삼성",
  95170. "商标",
  95171. "商店",
  95172. "商城",
  95173. "дети",
  95174. "ポイント",
  95175. "新闻",
  95176. "工行",
  95177. "家電",
  95178. "كوم",
  95179. "中文网",
  95180. "中信",
  95181. "娱乐",
  95182. "谷歌",
  95183. "電訊盈科",
  95184. "购物",
  95185. "クラウド",
  95186. "通販",
  95187. "网店",
  95188. "संगठन",
  95189. "餐厅",
  95190. "网络",
  95191. "ком",
  95192. "亚马逊",
  95193. "诺基亚",
  95194. "食品",
  95195. "飞利浦",
  95196. "手表",
  95197. "手机",
  95198. "ارامكو",
  95199. "العليان",
  95200. "اتصالات",
  95201. "بازار",
  95202. "ابوظبي",
  95203. "كاثوليك",
  95204. "همراه",
  95205. "닷컴",
  95206. "政府",
  95207. "شبكة",
  95208. "بيتك",
  95209. "عرب",
  95210. "机构",
  95211. "组织机构",
  95212. "健康",
  95213. "招聘",
  95214. "рус",
  95215. "珠宝",
  95216. "大拿",
  95217. "みんな",
  95218. "グーグル",
  95219. "世界",
  95220. "書籍",
  95221. "网址",
  95222. "닷넷",
  95223. "コム",
  95224. "天主教",
  95225. "游戏",
  95226. "vermögensberater",
  95227. "vermögensberatung",
  95228. "企业",
  95229. "信息",
  95230. "嘉里大酒店",
  95231. "嘉里",
  95232. "广东",
  95233. "政务",
  95234. "xyz",
  95235. "yachts",
  95236. "yahoo",
  95237. "yamaxun",
  95238. "yandex",
  95239. "yodobashi",
  95240. "yoga",
  95241. "yokohama",
  95242. "you",
  95243. "youtube",
  95244. "yun",
  95245. "zappos",
  95246. "zara",
  95247. "zero",
  95248. "zip",
  95249. "zone",
  95250. "zuerich",
  95251. "cc.ua",
  95252. "inf.ua",
  95253. "ltd.ua",
  95254. "adobeaemcloud.com",
  95255. "adobeaemcloud.net",
  95256. "*.dev.adobeaemcloud.com",
  95257. "beep.pl",
  95258. "barsy.ca",
  95259. "*.compute.estate",
  95260. "*.alces.network",
  95261. "altervista.org",
  95262. "alwaysdata.net",
  95263. "cloudfront.net",
  95264. "*.compute.amazonaws.com",
  95265. "*.compute-1.amazonaws.com",
  95266. "*.compute.amazonaws.com.cn",
  95267. "us-east-1.amazonaws.com",
  95268. "cn-north-1.eb.amazonaws.com.cn",
  95269. "cn-northwest-1.eb.amazonaws.com.cn",
  95270. "elasticbeanstalk.com",
  95271. "ap-northeast-1.elasticbeanstalk.com",
  95272. "ap-northeast-2.elasticbeanstalk.com",
  95273. "ap-northeast-3.elasticbeanstalk.com",
  95274. "ap-south-1.elasticbeanstalk.com",
  95275. "ap-southeast-1.elasticbeanstalk.com",
  95276. "ap-southeast-2.elasticbeanstalk.com",
  95277. "ca-central-1.elasticbeanstalk.com",
  95278. "eu-central-1.elasticbeanstalk.com",
  95279. "eu-west-1.elasticbeanstalk.com",
  95280. "eu-west-2.elasticbeanstalk.com",
  95281. "eu-west-3.elasticbeanstalk.com",
  95282. "sa-east-1.elasticbeanstalk.com",
  95283. "us-east-1.elasticbeanstalk.com",
  95284. "us-east-2.elasticbeanstalk.com",
  95285. "us-gov-west-1.elasticbeanstalk.com",
  95286. "us-west-1.elasticbeanstalk.com",
  95287. "us-west-2.elasticbeanstalk.com",
  95288. "*.elb.amazonaws.com",
  95289. "*.elb.amazonaws.com.cn",
  95290. "s3.amazonaws.com",
  95291. "s3-ap-northeast-1.amazonaws.com",
  95292. "s3-ap-northeast-2.amazonaws.com",
  95293. "s3-ap-south-1.amazonaws.com",
  95294. "s3-ap-southeast-1.amazonaws.com",
  95295. "s3-ap-southeast-2.amazonaws.com",
  95296. "s3-ca-central-1.amazonaws.com",
  95297. "s3-eu-central-1.amazonaws.com",
  95298. "s3-eu-west-1.amazonaws.com",
  95299. "s3-eu-west-2.amazonaws.com",
  95300. "s3-eu-west-3.amazonaws.com",
  95301. "s3-external-1.amazonaws.com",
  95302. "s3-fips-us-gov-west-1.amazonaws.com",
  95303. "s3-sa-east-1.amazonaws.com",
  95304. "s3-us-gov-west-1.amazonaws.com",
  95305. "s3-us-east-2.amazonaws.com",
  95306. "s3-us-west-1.amazonaws.com",
  95307. "s3-us-west-2.amazonaws.com",
  95308. "s3.ap-northeast-2.amazonaws.com",
  95309. "s3.ap-south-1.amazonaws.com",
  95310. "s3.cn-north-1.amazonaws.com.cn",
  95311. "s3.ca-central-1.amazonaws.com",
  95312. "s3.eu-central-1.amazonaws.com",
  95313. "s3.eu-west-2.amazonaws.com",
  95314. "s3.eu-west-3.amazonaws.com",
  95315. "s3.us-east-2.amazonaws.com",
  95316. "s3.dualstack.ap-northeast-1.amazonaws.com",
  95317. "s3.dualstack.ap-northeast-2.amazonaws.com",
  95318. "s3.dualstack.ap-south-1.amazonaws.com",
  95319. "s3.dualstack.ap-southeast-1.amazonaws.com",
  95320. "s3.dualstack.ap-southeast-2.amazonaws.com",
  95321. "s3.dualstack.ca-central-1.amazonaws.com",
  95322. "s3.dualstack.eu-central-1.amazonaws.com",
  95323. "s3.dualstack.eu-west-1.amazonaws.com",
  95324. "s3.dualstack.eu-west-2.amazonaws.com",
  95325. "s3.dualstack.eu-west-3.amazonaws.com",
  95326. "s3.dualstack.sa-east-1.amazonaws.com",
  95327. "s3.dualstack.us-east-1.amazonaws.com",
  95328. "s3.dualstack.us-east-2.amazonaws.com",
  95329. "s3-website-us-east-1.amazonaws.com",
  95330. "s3-website-us-west-1.amazonaws.com",
  95331. "s3-website-us-west-2.amazonaws.com",
  95332. "s3-website-ap-northeast-1.amazonaws.com",
  95333. "s3-website-ap-southeast-1.amazonaws.com",
  95334. "s3-website-ap-southeast-2.amazonaws.com",
  95335. "s3-website-eu-west-1.amazonaws.com",
  95336. "s3-website-sa-east-1.amazonaws.com",
  95337. "s3-website.ap-northeast-2.amazonaws.com",
  95338. "s3-website.ap-south-1.amazonaws.com",
  95339. "s3-website.ca-central-1.amazonaws.com",
  95340. "s3-website.eu-central-1.amazonaws.com",
  95341. "s3-website.eu-west-2.amazonaws.com",
  95342. "s3-website.eu-west-3.amazonaws.com",
  95343. "s3-website.us-east-2.amazonaws.com",
  95344. "amsw.nl",
  95345. "t3l3p0rt.net",
  95346. "tele.amune.org",
  95347. "apigee.io",
  95348. "on-aptible.com",
  95349. "user.aseinet.ne.jp",
  95350. "gv.vc",
  95351. "d.gv.vc",
  95352. "user.party.eus",
  95353. "pimienta.org",
  95354. "poivron.org",
  95355. "potager.org",
  95356. "sweetpepper.org",
  95357. "myasustor.com",
  95358. "myfritz.net",
  95359. "*.awdev.ca",
  95360. "*.advisor.ws",
  95361. "b-data.io",
  95362. "backplaneapp.io",
  95363. "balena-devices.com",
  95364. "app.banzaicloud.io",
  95365. "betainabox.com",
  95366. "bnr.la",
  95367. "blackbaudcdn.net",
  95368. "boomla.net",
  95369. "boxfuse.io",
  95370. "square7.ch",
  95371. "bplaced.com",
  95372. "bplaced.de",
  95373. "square7.de",
  95374. "bplaced.net",
  95375. "square7.net",
  95376. "browsersafetymark.io",
  95377. "uk0.bigv.io",
  95378. "dh.bytemark.co.uk",
  95379. "vm.bytemark.co.uk",
  95380. "mycd.eu",
  95381. "carrd.co",
  95382. "crd.co",
  95383. "uwu.ai",
  95384. "ae.org",
  95385. "ar.com",
  95386. "br.com",
  95387. "cn.com",
  95388. "com.de",
  95389. "com.se",
  95390. "de.com",
  95391. "eu.com",
  95392. "gb.com",
  95393. "gb.net",
  95394. "hu.com",
  95395. "hu.net",
  95396. "jp.net",
  95397. "jpn.com",
  95398. "kr.com",
  95399. "mex.com",
  95400. "no.com",
  95401. "qc.com",
  95402. "ru.com",
  95403. "sa.com",
  95404. "se.net",
  95405. "uk.com",
  95406. "uk.net",
  95407. "us.com",
  95408. "uy.com",
  95409. "za.bz",
  95410. "za.com",
  95411. "africa.com",
  95412. "gr.com",
  95413. "in.net",
  95414. "us.org",
  95415. "co.com",
  95416. "c.la",
  95417. "certmgr.org",
  95418. "xenapponazure.com",
  95419. "discourse.group",
  95420. "discourse.team",
  95421. "virtueeldomein.nl",
  95422. "cleverapps.io",
  95423. "*.lcl.dev",
  95424. "*.stg.dev",
  95425. "c66.me",
  95426. "cloud66.ws",
  95427. "cloud66.zone",
  95428. "jdevcloud.com",
  95429. "wpdevcloud.com",
  95430. "cloudaccess.host",
  95431. "freesite.host",
  95432. "cloudaccess.net",
  95433. "cloudcontrolled.com",
  95434. "cloudcontrolapp.com",
  95435. "cloudera.site",
  95436. "trycloudflare.com",
  95437. "workers.dev",
  95438. "wnext.app",
  95439. "co.ca",
  95440. "*.otap.co",
  95441. "co.cz",
  95442. "c.cdn77.org",
  95443. "cdn77-ssl.net",
  95444. "r.cdn77.net",
  95445. "rsc.cdn77.org",
  95446. "ssl.origin.cdn77-secure.org",
  95447. "cloudns.asia",
  95448. "cloudns.biz",
  95449. "cloudns.club",
  95450. "cloudns.cc",
  95451. "cloudns.eu",
  95452. "cloudns.in",
  95453. "cloudns.info",
  95454. "cloudns.org",
  95455. "cloudns.pro",
  95456. "cloudns.pw",
  95457. "cloudns.us",
  95458. "cloudeity.net",
  95459. "cnpy.gdn",
  95460. "co.nl",
  95461. "co.no",
  95462. "webhosting.be",
  95463. "hosting-cluster.nl",
  95464. "ac.ru",
  95465. "edu.ru",
  95466. "gov.ru",
  95467. "int.ru",
  95468. "mil.ru",
  95469. "test.ru",
  95470. "dyn.cosidns.de",
  95471. "dynamisches-dns.de",
  95472. "dnsupdater.de",
  95473. "internet-dns.de",
  95474. "l-o-g-i-n.de",
  95475. "dynamic-dns.info",
  95476. "feste-ip.net",
  95477. "knx-server.net",
  95478. "static-access.net",
  95479. "realm.cz",
  95480. "*.cryptonomic.net",
  95481. "cupcake.is",
  95482. "*.customer-oci.com",
  95483. "*.oci.customer-oci.com",
  95484. "*.ocp.customer-oci.com",
  95485. "*.ocs.customer-oci.com",
  95486. "cyon.link",
  95487. "cyon.site",
  95488. "daplie.me",
  95489. "localhost.daplie.me",
  95490. "dattolocal.com",
  95491. "dattorelay.com",
  95492. "dattoweb.com",
  95493. "mydatto.com",
  95494. "dattolocal.net",
  95495. "mydatto.net",
  95496. "biz.dk",
  95497. "co.dk",
  95498. "firm.dk",
  95499. "reg.dk",
  95500. "store.dk",
  95501. "*.dapps.earth",
  95502. "*.bzz.dapps.earth",
  95503. "builtwithdark.com",
  95504. "edgestack.me",
  95505. "debian.net",
  95506. "dedyn.io",
  95507. "dnshome.de",
  95508. "online.th",
  95509. "shop.th",
  95510. "drayddns.com",
  95511. "dreamhosters.com",
  95512. "mydrobo.com",
  95513. "drud.io",
  95514. "drud.us",
  95515. "duckdns.org",
  95516. "dy.fi",
  95517. "tunk.org",
  95518. "dyndns-at-home.com",
  95519. "dyndns-at-work.com",
  95520. "dyndns-blog.com",
  95521. "dyndns-free.com",
  95522. "dyndns-home.com",
  95523. "dyndns-ip.com",
  95524. "dyndns-mail.com",
  95525. "dyndns-office.com",
  95526. "dyndns-pics.com",
  95527. "dyndns-remote.com",
  95528. "dyndns-server.com",
  95529. "dyndns-web.com",
  95530. "dyndns-wiki.com",
  95531. "dyndns-work.com",
  95532. "dyndns.biz",
  95533. "dyndns.info",
  95534. "dyndns.org",
  95535. "dyndns.tv",
  95536. "at-band-camp.net",
  95537. "ath.cx",
  95538. "barrel-of-knowledge.info",
  95539. "barrell-of-knowledge.info",
  95540. "better-than.tv",
  95541. "blogdns.com",
  95542. "blogdns.net",
  95543. "blogdns.org",
  95544. "blogsite.org",
  95545. "boldlygoingnowhere.org",
  95546. "broke-it.net",
  95547. "buyshouses.net",
  95548. "cechire.com",
  95549. "dnsalias.com",
  95550. "dnsalias.net",
  95551. "dnsalias.org",
  95552. "dnsdojo.com",
  95553. "dnsdojo.net",
  95554. "dnsdojo.org",
  95555. "does-it.net",
  95556. "doesntexist.com",
  95557. "doesntexist.org",
  95558. "dontexist.com",
  95559. "dontexist.net",
  95560. "dontexist.org",
  95561. "doomdns.com",
  95562. "doomdns.org",
  95563. "dvrdns.org",
  95564. "dyn-o-saur.com",
  95565. "dynalias.com",
  95566. "dynalias.net",
  95567. "dynalias.org",
  95568. "dynathome.net",
  95569. "dyndns.ws",
  95570. "endofinternet.net",
  95571. "endofinternet.org",
  95572. "endoftheinternet.org",
  95573. "est-a-la-maison.com",
  95574. "est-a-la-masion.com",
  95575. "est-le-patron.com",
  95576. "est-mon-blogueur.com",
  95577. "for-better.biz",
  95578. "for-more.biz",
  95579. "for-our.info",
  95580. "for-some.biz",
  95581. "for-the.biz",
  95582. "forgot.her.name",
  95583. "forgot.his.name",
  95584. "from-ak.com",
  95585. "from-al.com",
  95586. "from-ar.com",
  95587. "from-az.net",
  95588. "from-ca.com",
  95589. "from-co.net",
  95590. "from-ct.com",
  95591. "from-dc.com",
  95592. "from-de.com",
  95593. "from-fl.com",
  95594. "from-ga.com",
  95595. "from-hi.com",
  95596. "from-ia.com",
  95597. "from-id.com",
  95598. "from-il.com",
  95599. "from-in.com",
  95600. "from-ks.com",
  95601. "from-ky.com",
  95602. "from-la.net",
  95603. "from-ma.com",
  95604. "from-md.com",
  95605. "from-me.org",
  95606. "from-mi.com",
  95607. "from-mn.com",
  95608. "from-mo.com",
  95609. "from-ms.com",
  95610. "from-mt.com",
  95611. "from-nc.com",
  95612. "from-nd.com",
  95613. "from-ne.com",
  95614. "from-nh.com",
  95615. "from-nj.com",
  95616. "from-nm.com",
  95617. "from-nv.com",
  95618. "from-ny.net",
  95619. "from-oh.com",
  95620. "from-ok.com",
  95621. "from-or.com",
  95622. "from-pa.com",
  95623. "from-pr.com",
  95624. "from-ri.com",
  95625. "from-sc.com",
  95626. "from-sd.com",
  95627. "from-tn.com",
  95628. "from-tx.com",
  95629. "from-ut.com",
  95630. "from-va.com",
  95631. "from-vt.com",
  95632. "from-wa.com",
  95633. "from-wi.com",
  95634. "from-wv.com",
  95635. "from-wy.com",
  95636. "ftpaccess.cc",
  95637. "fuettertdasnetz.de",
  95638. "game-host.org",
  95639. "game-server.cc",
  95640. "getmyip.com",
  95641. "gets-it.net",
  95642. "go.dyndns.org",
  95643. "gotdns.com",
  95644. "gotdns.org",
  95645. "groks-the.info",
  95646. "groks-this.info",
  95647. "ham-radio-op.net",
  95648. "here-for-more.info",
  95649. "hobby-site.com",
  95650. "hobby-site.org",
  95651. "home.dyndns.org",
  95652. "homedns.org",
  95653. "homeftp.net",
  95654. "homeftp.org",
  95655. "homeip.net",
  95656. "homelinux.com",
  95657. "homelinux.net",
  95658. "homelinux.org",
  95659. "homeunix.com",
  95660. "homeunix.net",
  95661. "homeunix.org",
  95662. "iamallama.com",
  95663. "in-the-band.net",
  95664. "is-a-anarchist.com",
  95665. "is-a-blogger.com",
  95666. "is-a-bookkeeper.com",
  95667. "is-a-bruinsfan.org",
  95668. "is-a-bulls-fan.com",
  95669. "is-a-candidate.org",
  95670. "is-a-caterer.com",
  95671. "is-a-celticsfan.org",
  95672. "is-a-chef.com",
  95673. "is-a-chef.net",
  95674. "is-a-chef.org",
  95675. "is-a-conservative.com",
  95676. "is-a-cpa.com",
  95677. "is-a-cubicle-slave.com",
  95678. "is-a-democrat.com",
  95679. "is-a-designer.com",
  95680. "is-a-doctor.com",
  95681. "is-a-financialadvisor.com",
  95682. "is-a-geek.com",
  95683. "is-a-geek.net",
  95684. "is-a-geek.org",
  95685. "is-a-green.com",
  95686. "is-a-guru.com",
  95687. "is-a-hard-worker.com",
  95688. "is-a-hunter.com",
  95689. "is-a-knight.org",
  95690. "is-a-landscaper.com",
  95691. "is-a-lawyer.com",
  95692. "is-a-liberal.com",
  95693. "is-a-libertarian.com",
  95694. "is-a-linux-user.org",
  95695. "is-a-llama.com",
  95696. "is-a-musician.com",
  95697. "is-a-nascarfan.com",
  95698. "is-a-nurse.com",
  95699. "is-a-painter.com",
  95700. "is-a-patsfan.org",
  95701. "is-a-personaltrainer.com",
  95702. "is-a-photographer.com",
  95703. "is-a-player.com",
  95704. "is-a-republican.com",
  95705. "is-a-rockstar.com",
  95706. "is-a-socialist.com",
  95707. "is-a-soxfan.org",
  95708. "is-a-student.com",
  95709. "is-a-teacher.com",
  95710. "is-a-techie.com",
  95711. "is-a-therapist.com",
  95712. "is-an-accountant.com",
  95713. "is-an-actor.com",
  95714. "is-an-actress.com",
  95715. "is-an-anarchist.com",
  95716. "is-an-artist.com",
  95717. "is-an-engineer.com",
  95718. "is-an-entertainer.com",
  95719. "is-by.us",
  95720. "is-certified.com",
  95721. "is-found.org",
  95722. "is-gone.com",
  95723. "is-into-anime.com",
  95724. "is-into-cars.com",
  95725. "is-into-cartoons.com",
  95726. "is-into-games.com",
  95727. "is-leet.com",
  95728. "is-lost.org",
  95729. "is-not-certified.com",
  95730. "is-saved.org",
  95731. "is-slick.com",
  95732. "is-uberleet.com",
  95733. "is-very-bad.org",
  95734. "is-very-evil.org",
  95735. "is-very-good.org",
  95736. "is-very-nice.org",
  95737. "is-very-sweet.org",
  95738. "is-with-theband.com",
  95739. "isa-geek.com",
  95740. "isa-geek.net",
  95741. "isa-geek.org",
  95742. "isa-hockeynut.com",
  95743. "issmarterthanyou.com",
  95744. "isteingeek.de",
  95745. "istmein.de",
  95746. "kicks-ass.net",
  95747. "kicks-ass.org",
  95748. "knowsitall.info",
  95749. "land-4-sale.us",
  95750. "lebtimnetz.de",
  95751. "leitungsen.de",
  95752. "likes-pie.com",
  95753. "likescandy.com",
  95754. "merseine.nu",
  95755. "mine.nu",
  95756. "misconfused.org",
  95757. "mypets.ws",
  95758. "myphotos.cc",
  95759. "neat-url.com",
  95760. "office-on-the.net",
  95761. "on-the-web.tv",
  95762. "podzone.net",
  95763. "podzone.org",
  95764. "readmyblog.org",
  95765. "saves-the-whales.com",
  95766. "scrapper-site.net",
  95767. "scrapping.cc",
  95768. "selfip.biz",
  95769. "selfip.com",
  95770. "selfip.info",
  95771. "selfip.net",
  95772. "selfip.org",
  95773. "sells-for-less.com",
  95774. "sells-for-u.com",
  95775. "sells-it.net",
  95776. "sellsyourhome.org",
  95777. "servebbs.com",
  95778. "servebbs.net",
  95779. "servebbs.org",
  95780. "serveftp.net",
  95781. "serveftp.org",
  95782. "servegame.org",
  95783. "shacknet.nu",
  95784. "simple-url.com",
  95785. "space-to-rent.com",
  95786. "stuff-4-sale.org",
  95787. "stuff-4-sale.us",
  95788. "teaches-yoga.com",
  95789. "thruhere.net",
  95790. "traeumtgerade.de",
  95791. "webhop.biz",
  95792. "webhop.info",
  95793. "webhop.net",
  95794. "webhop.org",
  95795. "worse-than.tv",
  95796. "writesthisblog.com",
  95797. "ddnss.de",
  95798. "dyn.ddnss.de",
  95799. "dyndns.ddnss.de",
  95800. "dyndns1.de",
  95801. "dyn-ip24.de",
  95802. "home-webserver.de",
  95803. "dyn.home-webserver.de",
  95804. "myhome-server.de",
  95805. "ddnss.org",
  95806. "definima.net",
  95807. "definima.io",
  95808. "bci.dnstrace.pro",
  95809. "ddnsfree.com",
  95810. "ddnsgeek.com",
  95811. "giize.com",
  95812. "gleeze.com",
  95813. "kozow.com",
  95814. "loseyourip.com",
  95815. "ooguy.com",
  95816. "theworkpc.com",
  95817. "casacam.net",
  95818. "dynu.net",
  95819. "accesscam.org",
  95820. "camdvr.org",
  95821. "freeddns.org",
  95822. "mywire.org",
  95823. "webredirect.org",
  95824. "myddns.rocks",
  95825. "blogsite.xyz",
  95826. "dynv6.net",
  95827. "e4.cz",
  95828. "en-root.fr",
  95829. "mytuleap.com",
  95830. "onred.one",
  95831. "staging.onred.one",
  95832. "enonic.io",
  95833. "customer.enonic.io",
  95834. "eu.org",
  95835. "al.eu.org",
  95836. "asso.eu.org",
  95837. "at.eu.org",
  95838. "au.eu.org",
  95839. "be.eu.org",
  95840. "bg.eu.org",
  95841. "ca.eu.org",
  95842. "cd.eu.org",
  95843. "ch.eu.org",
  95844. "cn.eu.org",
  95845. "cy.eu.org",
  95846. "cz.eu.org",
  95847. "de.eu.org",
  95848. "dk.eu.org",
  95849. "edu.eu.org",
  95850. "ee.eu.org",
  95851. "es.eu.org",
  95852. "fi.eu.org",
  95853. "fr.eu.org",
  95854. "gr.eu.org",
  95855. "hr.eu.org",
  95856. "hu.eu.org",
  95857. "ie.eu.org",
  95858. "il.eu.org",
  95859. "in.eu.org",
  95860. "int.eu.org",
  95861. "is.eu.org",
  95862. "it.eu.org",
  95863. "jp.eu.org",
  95864. "kr.eu.org",
  95865. "lt.eu.org",
  95866. "lu.eu.org",
  95867. "lv.eu.org",
  95868. "mc.eu.org",
  95869. "me.eu.org",
  95870. "mk.eu.org",
  95871. "mt.eu.org",
  95872. "my.eu.org",
  95873. "net.eu.org",
  95874. "ng.eu.org",
  95875. "nl.eu.org",
  95876. "no.eu.org",
  95877. "nz.eu.org",
  95878. "paris.eu.org",
  95879. "pl.eu.org",
  95880. "pt.eu.org",
  95881. "q-a.eu.org",
  95882. "ro.eu.org",
  95883. "ru.eu.org",
  95884. "se.eu.org",
  95885. "si.eu.org",
  95886. "sk.eu.org",
  95887. "tr.eu.org",
  95888. "uk.eu.org",
  95889. "us.eu.org",
  95890. "eu-1.evennode.com",
  95891. "eu-2.evennode.com",
  95892. "eu-3.evennode.com",
  95893. "eu-4.evennode.com",
  95894. "us-1.evennode.com",
  95895. "us-2.evennode.com",
  95896. "us-3.evennode.com",
  95897. "us-4.evennode.com",
  95898. "twmail.cc",
  95899. "twmail.net",
  95900. "twmail.org",
  95901. "mymailer.com.tw",
  95902. "url.tw",
  95903. "apps.fbsbx.com",
  95904. "ru.net",
  95905. "adygeya.ru",
  95906. "bashkiria.ru",
  95907. "bir.ru",
  95908. "cbg.ru",
  95909. "com.ru",
  95910. "dagestan.ru",
  95911. "grozny.ru",
  95912. "kalmykia.ru",
  95913. "kustanai.ru",
  95914. "marine.ru",
  95915. "mordovia.ru",
  95916. "msk.ru",
  95917. "mytis.ru",
  95918. "nalchik.ru",
  95919. "nov.ru",
  95920. "pyatigorsk.ru",
  95921. "spb.ru",
  95922. "vladikavkaz.ru",
  95923. "vladimir.ru",
  95924. "abkhazia.su",
  95925. "adygeya.su",
  95926. "aktyubinsk.su",
  95927. "arkhangelsk.su",
  95928. "armenia.su",
  95929. "ashgabad.su",
  95930. "azerbaijan.su",
  95931. "balashov.su",
  95932. "bashkiria.su",
  95933. "bryansk.su",
  95934. "bukhara.su",
  95935. "chimkent.su",
  95936. "dagestan.su",
  95937. "east-kazakhstan.su",
  95938. "exnet.su",
  95939. "georgia.su",
  95940. "grozny.su",
  95941. "ivanovo.su",
  95942. "jambyl.su",
  95943. "kalmykia.su",
  95944. "kaluga.su",
  95945. "karacol.su",
  95946. "karaganda.su",
  95947. "karelia.su",
  95948. "khakassia.su",
  95949. "krasnodar.su",
  95950. "kurgan.su",
  95951. "kustanai.su",
  95952. "lenug.su",
  95953. "mangyshlak.su",
  95954. "mordovia.su",
  95955. "msk.su",
  95956. "murmansk.su",
  95957. "nalchik.su",
  95958. "navoi.su",
  95959. "north-kazakhstan.su",
  95960. "nov.su",
  95961. "obninsk.su",
  95962. "penza.su",
  95963. "pokrovsk.su",
  95964. "sochi.su",
  95965. "spb.su",
  95966. "tashkent.su",
  95967. "termez.su",
  95968. "togliatti.su",
  95969. "troitsk.su",
  95970. "tselinograd.su",
  95971. "tula.su",
  95972. "tuva.su",
  95973. "vladikavkaz.su",
  95974. "vladimir.su",
  95975. "vologda.su",
  95976. "channelsdvr.net",
  95977. "u.channelsdvr.net",
  95978. "fastly-terrarium.com",
  95979. "fastlylb.net",
  95980. "map.fastlylb.net",
  95981. "freetls.fastly.net",
  95982. "map.fastly.net",
  95983. "a.prod.fastly.net",
  95984. "global.prod.fastly.net",
  95985. "a.ssl.fastly.net",
  95986. "b.ssl.fastly.net",
  95987. "global.ssl.fastly.net",
  95988. "fastpanel.direct",
  95989. "fastvps-server.com",
  95990. "fhapp.xyz",
  95991. "fedorainfracloud.org",
  95992. "fedorapeople.org",
  95993. "cloud.fedoraproject.org",
  95994. "app.os.fedoraproject.org",
  95995. "app.os.stg.fedoraproject.org",
  95996. "mydobiss.com",
  95997. "filegear.me",
  95998. "filegear-au.me",
  95999. "filegear-de.me",
  96000. "filegear-gb.me",
  96001. "filegear-ie.me",
  96002. "filegear-jp.me",
  96003. "filegear-sg.me",
  96004. "firebaseapp.com",
  96005. "flynnhub.com",
  96006. "flynnhosting.net",
  96007. "0e.vc",
  96008. "freebox-os.com",
  96009. "freeboxos.com",
  96010. "fbx-os.fr",
  96011. "fbxos.fr",
  96012. "freebox-os.fr",
  96013. "freeboxos.fr",
  96014. "freedesktop.org",
  96015. "*.futurecms.at",
  96016. "*.ex.futurecms.at",
  96017. "*.in.futurecms.at",
  96018. "futurehosting.at",
  96019. "futuremailing.at",
  96020. "*.ex.ortsinfo.at",
  96021. "*.kunden.ortsinfo.at",
  96022. "*.statics.cloud",
  96023. "service.gov.uk",
  96024. "gehirn.ne.jp",
  96025. "usercontent.jp",
  96026. "gentapps.com",
  96027. "lab.ms",
  96028. "github.io",
  96029. "githubusercontent.com",
  96030. "gitlab.io",
  96031. "glitch.me",
  96032. "lolipop.io",
  96033. "cloudapps.digital",
  96034. "london.cloudapps.digital",
  96035. "homeoffice.gov.uk",
  96036. "ro.im",
  96037. "shop.ro",
  96038. "goip.de",
  96039. "run.app",
  96040. "a.run.app",
  96041. "web.app",
  96042. "*.0emm.com",
  96043. "appspot.com",
  96044. "*.r.appspot.com",
  96045. "blogspot.ae",
  96046. "blogspot.al",
  96047. "blogspot.am",
  96048. "blogspot.ba",
  96049. "blogspot.be",
  96050. "blogspot.bg",
  96051. "blogspot.bj",
  96052. "blogspot.ca",
  96053. "blogspot.cf",
  96054. "blogspot.ch",
  96055. "blogspot.cl",
  96056. "blogspot.co.at",
  96057. "blogspot.co.id",
  96058. "blogspot.co.il",
  96059. "blogspot.co.ke",
  96060. "blogspot.co.nz",
  96061. "blogspot.co.uk",
  96062. "blogspot.co.za",
  96063. "blogspot.com",
  96064. "blogspot.com.ar",
  96065. "blogspot.com.au",
  96066. "blogspot.com.br",
  96067. "blogspot.com.by",
  96068. "blogspot.com.co",
  96069. "blogspot.com.cy",
  96070. "blogspot.com.ee",
  96071. "blogspot.com.eg",
  96072. "blogspot.com.es",
  96073. "blogspot.com.mt",
  96074. "blogspot.com.ng",
  96075. "blogspot.com.tr",
  96076. "blogspot.com.uy",
  96077. "blogspot.cv",
  96078. "blogspot.cz",
  96079. "blogspot.de",
  96080. "blogspot.dk",
  96081. "blogspot.fi",
  96082. "blogspot.fr",
  96083. "blogspot.gr",
  96084. "blogspot.hk",
  96085. "blogspot.hr",
  96086. "blogspot.hu",
  96087. "blogspot.ie",
  96088. "blogspot.in",
  96089. "blogspot.is",
  96090. "blogspot.it",
  96091. "blogspot.jp",
  96092. "blogspot.kr",
  96093. "blogspot.li",
  96094. "blogspot.lt",
  96095. "blogspot.lu",
  96096. "blogspot.md",
  96097. "blogspot.mk",
  96098. "blogspot.mr",
  96099. "blogspot.mx",
  96100. "blogspot.my",
  96101. "blogspot.nl",
  96102. "blogspot.no",
  96103. "blogspot.pe",
  96104. "blogspot.pt",
  96105. "blogspot.qa",
  96106. "blogspot.re",
  96107. "blogspot.ro",
  96108. "blogspot.rs",
  96109. "blogspot.ru",
  96110. "blogspot.se",
  96111. "blogspot.sg",
  96112. "blogspot.si",
  96113. "blogspot.sk",
  96114. "blogspot.sn",
  96115. "blogspot.td",
  96116. "blogspot.tw",
  96117. "blogspot.ug",
  96118. "blogspot.vn",
  96119. "cloudfunctions.net",
  96120. "cloud.goog",
  96121. "codespot.com",
  96122. "googleapis.com",
  96123. "googlecode.com",
  96124. "pagespeedmobilizer.com",
  96125. "publishproxy.com",
  96126. "withgoogle.com",
  96127. "withyoutube.com",
  96128. "awsmppl.com",
  96129. "fin.ci",
  96130. "free.hr",
  96131. "caa.li",
  96132. "ua.rs",
  96133. "conf.se",
  96134. "hs.zone",
  96135. "hs.run",
  96136. "hashbang.sh",
  96137. "hasura.app",
  96138. "hasura-app.io",
  96139. "hepforge.org",
  96140. "herokuapp.com",
  96141. "herokussl.com",
  96142. "myravendb.com",
  96143. "ravendb.community",
  96144. "ravendb.me",
  96145. "development.run",
  96146. "ravendb.run",
  96147. "bpl.biz",
  96148. "orx.biz",
  96149. "ng.city",
  96150. "biz.gl",
  96151. "ng.ink",
  96152. "col.ng",
  96153. "firm.ng",
  96154. "gen.ng",
  96155. "ltd.ng",
  96156. "ngo.ng",
  96157. "ng.school",
  96158. "sch.so",
  96159. "häkkinen.fi",
  96160. "*.moonscale.io",
  96161. "moonscale.net",
  96162. "iki.fi",
  96163. "dyn-berlin.de",
  96164. "in-berlin.de",
  96165. "in-brb.de",
  96166. "in-butter.de",
  96167. "in-dsl.de",
  96168. "in-dsl.net",
  96169. "in-dsl.org",
  96170. "in-vpn.de",
  96171. "in-vpn.net",
  96172. "in-vpn.org",
  96173. "biz.at",
  96174. "info.at",
  96175. "info.cx",
  96176. "ac.leg.br",
  96177. "al.leg.br",
  96178. "am.leg.br",
  96179. "ap.leg.br",
  96180. "ba.leg.br",
  96181. "ce.leg.br",
  96182. "df.leg.br",
  96183. "es.leg.br",
  96184. "go.leg.br",
  96185. "ma.leg.br",
  96186. "mg.leg.br",
  96187. "ms.leg.br",
  96188. "mt.leg.br",
  96189. "pa.leg.br",
  96190. "pb.leg.br",
  96191. "pe.leg.br",
  96192. "pi.leg.br",
  96193. "pr.leg.br",
  96194. "rj.leg.br",
  96195. "rn.leg.br",
  96196. "ro.leg.br",
  96197. "rr.leg.br",
  96198. "rs.leg.br",
  96199. "sc.leg.br",
  96200. "se.leg.br",
  96201. "sp.leg.br",
  96202. "to.leg.br",
  96203. "pixolino.com",
  96204. "ipifony.net",
  96205. "mein-iserv.de",
  96206. "test-iserv.de",
  96207. "iserv.dev",
  96208. "iobb.net",
  96209. "myjino.ru",
  96210. "*.hosting.myjino.ru",
  96211. "*.landing.myjino.ru",
  96212. "*.spectrum.myjino.ru",
  96213. "*.vps.myjino.ru",
  96214. "*.triton.zone",
  96215. "*.cns.joyent.com",
  96216. "js.org",
  96217. "kaas.gg",
  96218. "khplay.nl",
  96219. "keymachine.de",
  96220. "kinghost.net",
  96221. "uni5.net",
  96222. "knightpoint.systems",
  96223. "oya.to",
  96224. "co.krd",
  96225. "edu.krd",
  96226. "git-repos.de",
  96227. "lcube-server.de",
  96228. "svn-repos.de",
  96229. "leadpages.co",
  96230. "lpages.co",
  96231. "lpusercontent.com",
  96232. "lelux.site",
  96233. "co.business",
  96234. "co.education",
  96235. "co.events",
  96236. "co.financial",
  96237. "co.network",
  96238. "co.place",
  96239. "co.technology",
  96240. "app.lmpm.com",
  96241. "linkitools.space",
  96242. "linkyard.cloud",
  96243. "linkyard-cloud.ch",
  96244. "members.linode.com",
  96245. "nodebalancer.linode.com",
  96246. "we.bs",
  96247. "loginline.app",
  96248. "loginline.dev",
  96249. "loginline.io",
  96250. "loginline.services",
  96251. "loginline.site",
  96252. "krasnik.pl",
  96253. "leczna.pl",
  96254. "lubartow.pl",
  96255. "lublin.pl",
  96256. "poniatowa.pl",
  96257. "swidnik.pl",
  96258. "uklugs.org",
  96259. "glug.org.uk",
  96260. "lug.org.uk",
  96261. "lugs.org.uk",
  96262. "barsy.bg",
  96263. "barsy.co.uk",
  96264. "barsyonline.co.uk",
  96265. "barsycenter.com",
  96266. "barsyonline.com",
  96267. "barsy.club",
  96268. "barsy.de",
  96269. "barsy.eu",
  96270. "barsy.in",
  96271. "barsy.info",
  96272. "barsy.io",
  96273. "barsy.me",
  96274. "barsy.menu",
  96275. "barsy.mobi",
  96276. "barsy.net",
  96277. "barsy.online",
  96278. "barsy.org",
  96279. "barsy.pro",
  96280. "barsy.pub",
  96281. "barsy.shop",
  96282. "barsy.site",
  96283. "barsy.support",
  96284. "barsy.uk",
  96285. "*.magentosite.cloud",
  96286. "mayfirst.info",
  96287. "mayfirst.org",
  96288. "hb.cldmail.ru",
  96289. "miniserver.com",
  96290. "memset.net",
  96291. "cloud.metacentrum.cz",
  96292. "custom.metacentrum.cz",
  96293. "flt.cloud.muni.cz",
  96294. "usr.cloud.muni.cz",
  96295. "meteorapp.com",
  96296. "eu.meteorapp.com",
  96297. "co.pl",
  96298. "azurecontainer.io",
  96299. "azurewebsites.net",
  96300. "azure-mobile.net",
  96301. "cloudapp.net",
  96302. "mozilla-iot.org",
  96303. "bmoattachments.org",
  96304. "net.ru",
  96305. "org.ru",
  96306. "pp.ru",
  96307. "ui.nabu.casa",
  96308. "pony.club",
  96309. "of.fashion",
  96310. "on.fashion",
  96311. "of.football",
  96312. "in.london",
  96313. "of.london",
  96314. "for.men",
  96315. "and.mom",
  96316. "for.mom",
  96317. "for.one",
  96318. "for.sale",
  96319. "of.work",
  96320. "to.work",
  96321. "nctu.me",
  96322. "bitballoon.com",
  96323. "netlify.com",
  96324. "4u.com",
  96325. "ngrok.io",
  96326. "nh-serv.co.uk",
  96327. "nfshost.com",
  96328. "dnsking.ch",
  96329. "mypi.co",
  96330. "n4t.co",
  96331. "001www.com",
  96332. "ddnslive.com",
  96333. "myiphost.com",
  96334. "forumz.info",
  96335. "16-b.it",
  96336. "32-b.it",
  96337. "64-b.it",
  96338. "soundcast.me",
  96339. "tcp4.me",
  96340. "dnsup.net",
  96341. "hicam.net",
  96342. "now-dns.net",
  96343. "ownip.net",
  96344. "vpndns.net",
  96345. "dynserv.org",
  96346. "now-dns.org",
  96347. "x443.pw",
  96348. "now-dns.top",
  96349. "ntdll.top",
  96350. "freeddns.us",
  96351. "crafting.xyz",
  96352. "zapto.xyz",
  96353. "nsupdate.info",
  96354. "nerdpol.ovh",
  96355. "blogsyte.com",
  96356. "brasilia.me",
  96357. "cable-modem.org",
  96358. "ciscofreak.com",
  96359. "collegefan.org",
  96360. "couchpotatofries.org",
  96361. "damnserver.com",
  96362. "ddns.me",
  96363. "ditchyourip.com",
  96364. "dnsfor.me",
  96365. "dnsiskinky.com",
  96366. "dvrcam.info",
  96367. "dynns.com",
  96368. "eating-organic.net",
  96369. "fantasyleague.cc",
  96370. "geekgalaxy.com",
  96371. "golffan.us",
  96372. "health-carereform.com",
  96373. "homesecuritymac.com",
  96374. "homesecuritypc.com",
  96375. "hopto.me",
  96376. "ilovecollege.info",
  96377. "loginto.me",
  96378. "mlbfan.org",
  96379. "mmafan.biz",
  96380. "myactivedirectory.com",
  96381. "mydissent.net",
  96382. "myeffect.net",
  96383. "mymediapc.net",
  96384. "mypsx.net",
  96385. "mysecuritycamera.com",
  96386. "mysecuritycamera.net",
  96387. "mysecuritycamera.org",
  96388. "net-freaks.com",
  96389. "nflfan.org",
  96390. "nhlfan.net",
  96391. "no-ip.ca",
  96392. "no-ip.co.uk",
  96393. "no-ip.net",
  96394. "noip.us",
  96395. "onthewifi.com",
  96396. "pgafan.net",
  96397. "point2this.com",
  96398. "pointto.us",
  96399. "privatizehealthinsurance.net",
  96400. "quicksytes.com",
  96401. "read-books.org",
  96402. "securitytactics.com",
  96403. "serveexchange.com",
  96404. "servehumour.com",
  96405. "servep2p.com",
  96406. "servesarcasm.com",
  96407. "stufftoread.com",
  96408. "ufcfan.org",
  96409. "unusualperson.com",
  96410. "workisboring.com",
  96411. "3utilities.com",
  96412. "bounceme.net",
  96413. "ddns.net",
  96414. "ddnsking.com",
  96415. "gotdns.ch",
  96416. "hopto.org",
  96417. "myftp.biz",
  96418. "myftp.org",
  96419. "myvnc.com",
  96420. "no-ip.biz",
  96421. "no-ip.info",
  96422. "no-ip.org",
  96423. "noip.me",
  96424. "redirectme.net",
  96425. "servebeer.com",
  96426. "serveblog.net",
  96427. "servecounterstrike.com",
  96428. "serveftp.com",
  96429. "servegame.com",
  96430. "servehalflife.com",
  96431. "servehttp.com",
  96432. "serveirc.com",
  96433. "serveminecraft.net",
  96434. "servemp3.com",
  96435. "servepics.com",
  96436. "servequake.com",
  96437. "sytes.net",
  96438. "webhop.me",
  96439. "zapto.org",
  96440. "stage.nodeart.io",
  96441. "nodum.co",
  96442. "nodum.io",
  96443. "pcloud.host",
  96444. "nyc.mn",
  96445. "nom.ae",
  96446. "nom.af",
  96447. "nom.ai",
  96448. "nom.al",
  96449. "nym.by",
  96450. "nom.bz",
  96451. "nym.bz",
  96452. "nom.cl",
  96453. "nym.ec",
  96454. "nom.gd",
  96455. "nom.ge",
  96456. "nom.gl",
  96457. "nym.gr",
  96458. "nom.gt",
  96459. "nym.gy",
  96460. "nym.hk",
  96461. "nom.hn",
  96462. "nym.ie",
  96463. "nom.im",
  96464. "nom.ke",
  96465. "nym.kz",
  96466. "nym.la",
  96467. "nym.lc",
  96468. "nom.li",
  96469. "nym.li",
  96470. "nym.lt",
  96471. "nym.lu",
  96472. "nom.lv",
  96473. "nym.me",
  96474. "nom.mk",
  96475. "nym.mn",
  96476. "nym.mx",
  96477. "nom.nu",
  96478. "nym.nz",
  96479. "nym.pe",
  96480. "nym.pt",
  96481. "nom.pw",
  96482. "nom.qa",
  96483. "nym.ro",
  96484. "nom.rs",
  96485. "nom.si",
  96486. "nym.sk",
  96487. "nom.st",
  96488. "nym.su",
  96489. "nym.sx",
  96490. "nom.tj",
  96491. "nym.tw",
  96492. "nom.ug",
  96493. "nom.uy",
  96494. "nom.vc",
  96495. "nom.vg",
  96496. "static.observableusercontent.com",
  96497. "cya.gg",
  96498. "cloudycluster.net",
  96499. "nid.io",
  96500. "opencraft.hosting",
  96501. "operaunite.com",
  96502. "skygearapp.com",
  96503. "outsystemscloud.com",
  96504. "ownprovider.com",
  96505. "own.pm",
  96506. "ox.rs",
  96507. "oy.lc",
  96508. "pgfog.com",
  96509. "pagefrontapp.com",
  96510. "art.pl",
  96511. "gliwice.pl",
  96512. "krakow.pl",
  96513. "poznan.pl",
  96514. "wroc.pl",
  96515. "zakopane.pl",
  96516. "pantheonsite.io",
  96517. "gotpantheon.com",
  96518. "mypep.link",
  96519. "perspecta.cloud",
  96520. "on-web.fr",
  96521. "*.platform.sh",
  96522. "*.platformsh.site",
  96523. "dyn53.io",
  96524. "co.bn",
  96525. "xen.prgmr.com",
  96526. "priv.at",
  96527. "prvcy.page",
  96528. "*.dweb.link",
  96529. "protonet.io",
  96530. "chirurgiens-dentistes-en-france.fr",
  96531. "byen.site",
  96532. "pubtls.org",
  96533. "qualifioapp.com",
  96534. "qbuser.com",
  96535. "instantcloud.cn",
  96536. "ras.ru",
  96537. "qa2.com",
  96538. "qcx.io",
  96539. "*.sys.qcx.io",
  96540. "dev-myqnapcloud.com",
  96541. "alpha-myqnapcloud.com",
  96542. "myqnapcloud.com",
  96543. "*.quipelements.com",
  96544. "vapor.cloud",
  96545. "vaporcloud.io",
  96546. "rackmaze.com",
  96547. "rackmaze.net",
  96548. "*.on-k3s.io",
  96549. "*.on-rancher.cloud",
  96550. "*.on-rio.io",
  96551. "readthedocs.io",
  96552. "rhcloud.com",
  96553. "app.render.com",
  96554. "onrender.com",
  96555. "repl.co",
  96556. "repl.run",
  96557. "resindevice.io",
  96558. "devices.resinstaging.io",
  96559. "hzc.io",
  96560. "wellbeingzone.eu",
  96561. "ptplus.fit",
  96562. "wellbeingzone.co.uk",
  96563. "git-pages.rit.edu",
  96564. "sandcats.io",
  96565. "logoip.de",
  96566. "logoip.com",
  96567. "schokokeks.net",
  96568. "gov.scot",
  96569. "scrysec.com",
  96570. "firewall-gateway.com",
  96571. "firewall-gateway.de",
  96572. "my-gateway.de",
  96573. "my-router.de",
  96574. "spdns.de",
  96575. "spdns.eu",
  96576. "firewall-gateway.net",
  96577. "my-firewall.org",
  96578. "myfirewall.org",
  96579. "spdns.org",
  96580. "senseering.net",
  96581. "biz.ua",
  96582. "co.ua",
  96583. "pp.ua",
  96584. "shiftedit.io",
  96585. "myshopblocks.com",
  96586. "shopitsite.com",
  96587. "mo-siemens.io",
  96588. "1kapp.com",
  96589. "appchizi.com",
  96590. "applinzi.com",
  96591. "sinaapp.com",
  96592. "vipsinaapp.com",
  96593. "siteleaf.net",
  96594. "bounty-full.com",
  96595. "alpha.bounty-full.com",
  96596. "beta.bounty-full.com",
  96597. "stackhero-network.com",
  96598. "static.land",
  96599. "dev.static.land",
  96600. "sites.static.land",
  96601. "apps.lair.io",
  96602. "*.stolos.io",
  96603. "spacekit.io",
  96604. "customer.speedpartner.de",
  96605. "api.stdlib.com",
  96606. "storj.farm",
  96607. "utwente.io",
  96608. "soc.srcf.net",
  96609. "user.srcf.net",
  96610. "temp-dns.com",
  96611. "applicationcloud.io",
  96612. "scapp.io",
  96613. "*.s5y.io",
  96614. "*.sensiosite.cloud",
  96615. "syncloud.it",
  96616. "diskstation.me",
  96617. "dscloud.biz",
  96618. "dscloud.me",
  96619. "dscloud.mobi",
  96620. "dsmynas.com",
  96621. "dsmynas.net",
  96622. "dsmynas.org",
  96623. "familyds.com",
  96624. "familyds.net",
  96625. "familyds.org",
  96626. "i234.me",
  96627. "myds.me",
  96628. "synology.me",
  96629. "vpnplus.to",
  96630. "direct.quickconnect.to",
  96631. "taifun-dns.de",
  96632. "gda.pl",
  96633. "gdansk.pl",
  96634. "gdynia.pl",
  96635. "med.pl",
  96636. "sopot.pl",
  96637. "edugit.org",
  96638. "telebit.app",
  96639. "telebit.io",
  96640. "*.telebit.xyz",
  96641. "gwiddle.co.uk",
  96642. "thingdustdata.com",
  96643. "cust.dev.thingdust.io",
  96644. "cust.disrec.thingdust.io",
  96645. "cust.prod.thingdust.io",
  96646. "cust.testing.thingdust.io",
  96647. "arvo.network",
  96648. "azimuth.network",
  96649. "bloxcms.com",
  96650. "townnews-staging.com",
  96651. "12hp.at",
  96652. "2ix.at",
  96653. "4lima.at",
  96654. "lima-city.at",
  96655. "12hp.ch",
  96656. "2ix.ch",
  96657. "4lima.ch",
  96658. "lima-city.ch",
  96659. "trafficplex.cloud",
  96660. "de.cool",
  96661. "12hp.de",
  96662. "2ix.de",
  96663. "4lima.de",
  96664. "lima-city.de",
  96665. "1337.pictures",
  96666. "clan.rip",
  96667. "lima-city.rocks",
  96668. "webspace.rocks",
  96669. "lima.zone",
  96670. "*.transurl.be",
  96671. "*.transurl.eu",
  96672. "*.transurl.nl",
  96673. "tuxfamily.org",
  96674. "dd-dns.de",
  96675. "diskstation.eu",
  96676. "diskstation.org",
  96677. "dray-dns.de",
  96678. "draydns.de",
  96679. "dyn-vpn.de",
  96680. "dynvpn.de",
  96681. "mein-vigor.de",
  96682. "my-vigor.de",
  96683. "my-wan.de",
  96684. "syno-ds.de",
  96685. "synology-diskstation.de",
  96686. "synology-ds.de",
  96687. "uber.space",
  96688. "*.uberspace.de",
  96689. "hk.com",
  96690. "hk.org",
  96691. "ltd.hk",
  96692. "inc.hk",
  96693. "virtualuser.de",
  96694. "virtual-user.de",
  96695. "urown.cloud",
  96696. "dnsupdate.info",
  96697. "lib.de.us",
  96698. "2038.io",
  96699. "router.management",
  96700. "v-info.info",
  96701. "voorloper.cloud",
  96702. "v.ua",
  96703. "wafflecell.com",
  96704. "*.webhare.dev",
  96705. "wedeploy.io",
  96706. "wedeploy.me",
  96707. "wedeploy.sh",
  96708. "remotewd.com",
  96709. "wmflabs.org",
  96710. "myforum.community",
  96711. "community-pro.de",
  96712. "diskussionsbereich.de",
  96713. "community-pro.net",
  96714. "meinforum.net",
  96715. "half.host",
  96716. "xnbay.com",
  96717. "u2.xnbay.com",
  96718. "u2-local.xnbay.com",
  96719. "cistron.nl",
  96720. "demon.nl",
  96721. "xs4all.space",
  96722. "yandexcloud.net",
  96723. "storage.yandexcloud.net",
  96724. "website.yandexcloud.net",
  96725. "official.academy",
  96726. "yolasite.com",
  96727. "ybo.faith",
  96728. "yombo.me",
  96729. "homelink.one",
  96730. "ybo.party",
  96731. "ybo.review",
  96732. "ybo.science",
  96733. "ybo.trade",
  96734. "nohost.me",
  96735. "noho.st",
  96736. "za.net",
  96737. "za.org",
  96738. "now.sh",
  96739. "bss.design",
  96740. "basicserver.io",
  96741. "virtualserver.io",
  96742. "enterprisecloud.nu"
  96743. ]
  96744. },{}],527:[function(require,module,exports){
  96745. /*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */
  96746. 'use strict';
  96747. var Punycode = require('punycode');
  96748. var internals = {};
  96749. //
  96750. // Read rules from file.
  96751. //
  96752. internals.rules = require('./data/rules.json').map(function (rule) {
  96753. return {
  96754. rule: rule,
  96755. suffix: rule.replace(/^(\*\.|\!)/, ''),
  96756. punySuffix: -1,
  96757. wildcard: rule.charAt(0) === '*',
  96758. exception: rule.charAt(0) === '!'
  96759. };
  96760. });
  96761. //
  96762. // Check is given string ends with `suffix`.
  96763. //
  96764. internals.endsWith = function (str, suffix) {
  96765. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  96766. };
  96767. //
  96768. // Find rule for a given domain.
  96769. //
  96770. internals.findRule = function (domain) {
  96771. var punyDomain = Punycode.toASCII(domain);
  96772. return internals.rules.reduce(function (memo, rule) {
  96773. if (rule.punySuffix === -1){
  96774. rule.punySuffix = Punycode.toASCII(rule.suffix);
  96775. }
  96776. if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) {
  96777. return memo;
  96778. }
  96779. // This has been commented out as it never seems to run. This is because
  96780. // sub tlds always appear after their parents and we never find a shorter
  96781. // match.
  96782. //if (memo) {
  96783. // var memoSuffix = Punycode.toASCII(memo.suffix);
  96784. // if (memoSuffix.length >= punySuffix.length) {
  96785. // return memo;
  96786. // }
  96787. //}
  96788. return rule;
  96789. }, null);
  96790. };
  96791. //
  96792. // Error codes and messages.
  96793. //
  96794. exports.errorCodes = {
  96795. DOMAIN_TOO_SHORT: 'Domain name too short.',
  96796. DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.',
  96797. LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.',
  96798. LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.',
  96799. LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.',
  96800. LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.',
  96801. LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.'
  96802. };
  96803. //
  96804. // Validate domain name and throw if not valid.
  96805. //
  96806. // From wikipedia:
  96807. //
  96808. // Hostnames are composed of series of labels concatenated with dots, as are all
  96809. // domain names. Each label must be between 1 and 63 characters long, and the
  96810. // entire hostname (including the delimiting dots) has a maximum of 255 chars.
  96811. //
  96812. // Allowed chars:
  96813. //
  96814. // * `a-z`
  96815. // * `0-9`
  96816. // * `-` but not as a starting or ending character
  96817. // * `.` as a separator for the textual portions of a domain name
  96818. //
  96819. // * http://en.wikipedia.org/wiki/Domain_name
  96820. // * http://en.wikipedia.org/wiki/Hostname
  96821. //
  96822. internals.validate = function (input) {
  96823. // Before we can validate we need to take care of IDNs with unicode chars.
  96824. var ascii = Punycode.toASCII(input);
  96825. if (ascii.length < 1) {
  96826. return 'DOMAIN_TOO_SHORT';
  96827. }
  96828. if (ascii.length > 255) {
  96829. return 'DOMAIN_TOO_LONG';
  96830. }
  96831. // Check each part's length and allowed chars.
  96832. var labels = ascii.split('.');
  96833. var label;
  96834. for (var i = 0; i < labels.length; ++i) {
  96835. label = labels[i];
  96836. if (!label.length) {
  96837. return 'LABEL_TOO_SHORT';
  96838. }
  96839. if (label.length > 63) {
  96840. return 'LABEL_TOO_LONG';
  96841. }
  96842. if (label.charAt(0) === '-') {
  96843. return 'LABEL_STARTS_WITH_DASH';
  96844. }
  96845. if (label.charAt(label.length - 1) === '-') {
  96846. return 'LABEL_ENDS_WITH_DASH';
  96847. }
  96848. if (!/^[a-z0-9\-]+$/.test(label)) {
  96849. return 'LABEL_INVALID_CHARS';
  96850. }
  96851. }
  96852. };
  96853. //
  96854. // Public API
  96855. //
  96856. //
  96857. // Parse domain.
  96858. //
  96859. exports.parse = function (input) {
  96860. if (typeof input !== 'string') {
  96861. throw new TypeError('Domain name must be a string.');
  96862. }
  96863. // Force domain to lowercase.
  96864. var domain = input.slice(0).toLowerCase();
  96865. // Handle FQDN.
  96866. // TODO: Simply remove trailing dot?
  96867. if (domain.charAt(domain.length - 1) === '.') {
  96868. domain = domain.slice(0, domain.length - 1);
  96869. }
  96870. // Validate and sanitise input.
  96871. var error = internals.validate(domain);
  96872. if (error) {
  96873. return {
  96874. input: input,
  96875. error: {
  96876. message: exports.errorCodes[error],
  96877. code: error
  96878. }
  96879. };
  96880. }
  96881. var parsed = {
  96882. input: input,
  96883. tld: null,
  96884. sld: null,
  96885. domain: null,
  96886. subdomain: null,
  96887. listed: false
  96888. };
  96889. var domainParts = domain.split('.');
  96890. // Non-Internet TLD
  96891. if (domainParts[domainParts.length - 1] === 'local') {
  96892. return parsed;
  96893. }
  96894. var handlePunycode = function () {
  96895. if (!/xn--/.test(domain)) {
  96896. return parsed;
  96897. }
  96898. if (parsed.domain) {
  96899. parsed.domain = Punycode.toASCII(parsed.domain);
  96900. }
  96901. if (parsed.subdomain) {
  96902. parsed.subdomain = Punycode.toASCII(parsed.subdomain);
  96903. }
  96904. return parsed;
  96905. };
  96906. var rule = internals.findRule(domain);
  96907. // Unlisted tld.
  96908. if (!rule) {
  96909. if (domainParts.length < 2) {
  96910. return parsed;
  96911. }
  96912. parsed.tld = domainParts.pop();
  96913. parsed.sld = domainParts.pop();
  96914. parsed.domain = [parsed.sld, parsed.tld].join('.');
  96915. if (domainParts.length) {
  96916. parsed.subdomain = domainParts.pop();
  96917. }
  96918. return handlePunycode();
  96919. }
  96920. // At this point we know the public suffix is listed.
  96921. parsed.listed = true;
  96922. var tldParts = rule.suffix.split('.');
  96923. var privateParts = domainParts.slice(0, domainParts.length - tldParts.length);
  96924. if (rule.exception) {
  96925. privateParts.push(tldParts.shift());
  96926. }
  96927. parsed.tld = tldParts.join('.');
  96928. if (!privateParts.length) {
  96929. return handlePunycode();
  96930. }
  96931. if (rule.wildcard) {
  96932. tldParts.unshift(privateParts.pop());
  96933. parsed.tld = tldParts.join('.');
  96934. }
  96935. if (!privateParts.length) {
  96936. return handlePunycode();
  96937. }
  96938. parsed.sld = privateParts.pop();
  96939. parsed.domain = [parsed.sld, parsed.tld].join('.');
  96940. if (privateParts.length) {
  96941. parsed.subdomain = privateParts.join('.');
  96942. }
  96943. return handlePunycode();
  96944. };
  96945. //
  96946. // Get domain.
  96947. //
  96948. exports.get = function (domain) {
  96949. if (!domain) {
  96950. return null;
  96951. }
  96952. return exports.parse(domain).domain || null;
  96953. };
  96954. //
  96955. // Check whether domain belongs to a known public suffix.
  96956. //
  96957. exports.isValid = function (domain) {
  96958. var parsed = exports.parse(domain);
  96959. return Boolean(parsed.domain && parsed.listed);
  96960. };
  96961. },{"./data/rules.json":526,"punycode":535}],528:[function(require,module,exports){
  96962. exports.publicEncrypt = require('./publicEncrypt')
  96963. exports.privateDecrypt = require('./privateDecrypt')
  96964. exports.privateEncrypt = function privateEncrypt (key, buf) {
  96965. return exports.publicEncrypt(key, buf, true)
  96966. }
  96967. exports.publicDecrypt = function publicDecrypt (key, buf) {
  96968. return exports.privateDecrypt(key, buf, true)
  96969. }
  96970. },{"./privateDecrypt":531,"./publicEncrypt":532}],529:[function(require,module,exports){
  96971. var createHash = require('create-hash')
  96972. var Buffer = require('safe-buffer').Buffer
  96973. module.exports = function (seed, len) {
  96974. var t = Buffer.alloc(0)
  96975. var i = 0
  96976. var c
  96977. while (t.length < len) {
  96978. c = i2ops(i++)
  96979. t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
  96980. }
  96981. return t.slice(0, len)
  96982. }
  96983. function i2ops (c) {
  96984. var out = Buffer.allocUnsafe(4)
  96985. out.writeUInt32BE(c, 0)
  96986. return out
  96987. }
  96988. },{"create-hash":204,"safe-buffer":561}],530:[function(require,module,exports){
  96989. arguments[4][97][0].apply(exports,arguments)
  96990. },{"buffer":144,"dup":97}],531:[function(require,module,exports){
  96991. var parseKeys = require('parse-asn1')
  96992. var mgf = require('./mgf')
  96993. var xor = require('./xor')
  96994. var BN = require('bn.js')
  96995. var crt = require('browserify-rsa')
  96996. var createHash = require('create-hash')
  96997. var withPublic = require('./withPublic')
  96998. var Buffer = require('safe-buffer').Buffer
  96999. module.exports = function privateDecrypt (privateKey, enc, reverse) {
  97000. var padding
  97001. if (privateKey.padding) {
  97002. padding = privateKey.padding
  97003. } else if (reverse) {
  97004. padding = 1
  97005. } else {
  97006. padding = 4
  97007. }
  97008. var key = parseKeys(privateKey)
  97009. var k = key.modulus.byteLength()
  97010. if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
  97011. throw new Error('decryption error')
  97012. }
  97013. var msg
  97014. if (reverse) {
  97015. msg = withPublic(new BN(enc), key)
  97016. } else {
  97017. msg = crt(enc, key)
  97018. }
  97019. var zBuffer = Buffer.alloc(k - msg.length)
  97020. msg = Buffer.concat([zBuffer, msg], k)
  97021. if (padding === 4) {
  97022. return oaep(key, msg)
  97023. } else if (padding === 1) {
  97024. return pkcs1(key, msg, reverse)
  97025. } else if (padding === 3) {
  97026. return msg
  97027. } else {
  97028. throw new Error('unknown padding')
  97029. }
  97030. }
  97031. function oaep (key, msg) {
  97032. var k = key.modulus.byteLength()
  97033. var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
  97034. var hLen = iHash.length
  97035. if (msg[0] !== 0) {
  97036. throw new Error('decryption error')
  97037. }
  97038. var maskedSeed = msg.slice(1, hLen + 1)
  97039. var maskedDb = msg.slice(hLen + 1)
  97040. var seed = xor(maskedSeed, mgf(maskedDb, hLen))
  97041. var db = xor(maskedDb, mgf(seed, k - hLen - 1))
  97042. if (compare(iHash, db.slice(0, hLen))) {
  97043. throw new Error('decryption error')
  97044. }
  97045. var i = hLen
  97046. while (db[i] === 0) {
  97047. i++
  97048. }
  97049. if (db[i++] !== 1) {
  97050. throw new Error('decryption error')
  97051. }
  97052. return db.slice(i)
  97053. }
  97054. function pkcs1 (key, msg, reverse) {
  97055. var p1 = msg.slice(0, 2)
  97056. var i = 2
  97057. var status = 0
  97058. while (msg[i++] !== 0) {
  97059. if (i >= msg.length) {
  97060. status++
  97061. break
  97062. }
  97063. }
  97064. var ps = msg.slice(2, i - 1)
  97065. if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
  97066. status++
  97067. }
  97068. if (ps.length < 8) {
  97069. status++
  97070. }
  97071. if (status) {
  97072. throw new Error('decryption error')
  97073. }
  97074. return msg.slice(i)
  97075. }
  97076. function compare (a, b) {
  97077. a = Buffer.from(a)
  97078. b = Buffer.from(b)
  97079. var dif = 0
  97080. var len = a.length
  97081. if (a.length !== b.length) {
  97082. dif++
  97083. len = Math.min(a.length, b.length)
  97084. }
  97085. var i = -1
  97086. while (++i < len) {
  97087. dif += (a[i] ^ b[i])
  97088. }
  97089. return dif
  97090. }
  97091. },{"./mgf":529,"./withPublic":533,"./xor":534,"bn.js":530,"browserify-rsa":165,"create-hash":204,"parse-asn1":516,"safe-buffer":561}],532:[function(require,module,exports){
  97092. var parseKeys = require('parse-asn1')
  97093. var randomBytes = require('randombytes')
  97094. var createHash = require('create-hash')
  97095. var mgf = require('./mgf')
  97096. var xor = require('./xor')
  97097. var BN = require('bn.js')
  97098. var withPublic = require('./withPublic')
  97099. var crt = require('browserify-rsa')
  97100. var Buffer = require('safe-buffer').Buffer
  97101. module.exports = function publicEncrypt (publicKey, msg, reverse) {
  97102. var padding
  97103. if (publicKey.padding) {
  97104. padding = publicKey.padding
  97105. } else if (reverse) {
  97106. padding = 1
  97107. } else {
  97108. padding = 4
  97109. }
  97110. var key = parseKeys(publicKey)
  97111. var paddedMsg
  97112. if (padding === 4) {
  97113. paddedMsg = oaep(key, msg)
  97114. } else if (padding === 1) {
  97115. paddedMsg = pkcs1(key, msg, reverse)
  97116. } else if (padding === 3) {
  97117. paddedMsg = new BN(msg)
  97118. if (paddedMsg.cmp(key.modulus) >= 0) {
  97119. throw new Error('data too long for modulus')
  97120. }
  97121. } else {
  97122. throw new Error('unknown padding')
  97123. }
  97124. if (reverse) {
  97125. return crt(paddedMsg, key)
  97126. } else {
  97127. return withPublic(paddedMsg, key)
  97128. }
  97129. }
  97130. function oaep (key, msg) {
  97131. var k = key.modulus.byteLength()
  97132. var mLen = msg.length
  97133. var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
  97134. var hLen = iHash.length
  97135. var hLen2 = 2 * hLen
  97136. if (mLen > k - hLen2 - 2) {
  97137. throw new Error('message too long')
  97138. }
  97139. var ps = Buffer.alloc(k - mLen - hLen2 - 2)
  97140. var dblen = k - hLen - 1
  97141. var seed = randomBytes(hLen)
  97142. var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
  97143. var maskedSeed = xor(seed, mgf(maskedDb, hLen))
  97144. return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
  97145. }
  97146. function pkcs1 (key, msg, reverse) {
  97147. var mLen = msg.length
  97148. var k = key.modulus.byteLength()
  97149. if (mLen > k - 11) {
  97150. throw new Error('message too long')
  97151. }
  97152. var ps
  97153. if (reverse) {
  97154. ps = Buffer.alloc(k - mLen - 3, 0xff)
  97155. } else {
  97156. ps = nonZero(k - mLen - 3)
  97157. }
  97158. return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
  97159. }
  97160. function nonZero (len) {
  97161. var out = Buffer.allocUnsafe(len)
  97162. var i = 0
  97163. var cache = randomBytes(len * 2)
  97164. var cur = 0
  97165. var num
  97166. while (i < len) {
  97167. if (cur === cache.length) {
  97168. cache = randomBytes(len * 2)
  97169. cur = 0
  97170. }
  97171. num = cache[cur++]
  97172. if (num) {
  97173. out[i++] = num
  97174. }
  97175. }
  97176. return out
  97177. }
  97178. },{"./mgf":529,"./withPublic":533,"./xor":534,"bn.js":530,"browserify-rsa":165,"create-hash":204,"parse-asn1":516,"randombytes":544,"safe-buffer":561}],533:[function(require,module,exports){
  97179. var BN = require('bn.js')
  97180. var Buffer = require('safe-buffer').Buffer
  97181. function withPublic (paddedMsg, key) {
  97182. return Buffer.from(paddedMsg
  97183. .toRed(BN.mont(key.modulus))
  97184. .redPow(new BN(key.publicExponent))
  97185. .fromRed()
  97186. .toArray())
  97187. }
  97188. module.exports = withPublic
  97189. },{"bn.js":530,"safe-buffer":561}],534:[function(require,module,exports){
  97190. module.exports = function xor (a, b) {
  97191. var len = a.length
  97192. var i = -1
  97193. while (++i < len) {
  97194. a[i] ^= b[i]
  97195. }
  97196. return a
  97197. }
  97198. },{}],535:[function(require,module,exports){
  97199. (function (global){(function (){
  97200. /*! https://mths.be/punycode v1.4.1 by @mathias */
  97201. ;(function(root) {
  97202. /** Detect free variables */
  97203. var freeExports = typeof exports == 'object' && exports &&
  97204. !exports.nodeType && exports;
  97205. var freeModule = typeof module == 'object' && module &&
  97206. !module.nodeType && module;
  97207. var freeGlobal = typeof global == 'object' && global;
  97208. if (
  97209. freeGlobal.global === freeGlobal ||
  97210. freeGlobal.window === freeGlobal ||
  97211. freeGlobal.self === freeGlobal
  97212. ) {
  97213. root = freeGlobal;
  97214. }
  97215. /**
  97216. * The `punycode` object.
  97217. * @name punycode
  97218. * @type Object
  97219. */
  97220. var punycode,
  97221. /** Highest positive signed 32-bit float value */
  97222. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  97223. /** Bootstring parameters */
  97224. base = 36,
  97225. tMin = 1,
  97226. tMax = 26,
  97227. skew = 38,
  97228. damp = 700,
  97229. initialBias = 72,
  97230. initialN = 128, // 0x80
  97231. delimiter = '-', // '\x2D'
  97232. /** Regular expressions */
  97233. regexPunycode = /^xn--/,
  97234. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  97235. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  97236. /** Error messages */
  97237. errors = {
  97238. 'overflow': 'Overflow: input needs wider integers to process',
  97239. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  97240. 'invalid-input': 'Invalid input'
  97241. },
  97242. /** Convenience shortcuts */
  97243. baseMinusTMin = base - tMin,
  97244. floor = Math.floor,
  97245. stringFromCharCode = String.fromCharCode,
  97246. /** Temporary variable */
  97247. key;
  97248. /*--------------------------------------------------------------------------*/
  97249. /**
  97250. * A generic error utility function.
  97251. * @private
  97252. * @param {String} type The error type.
  97253. * @returns {Error} Throws a `RangeError` with the applicable error message.
  97254. */
  97255. function error(type) {
  97256. throw new RangeError(errors[type]);
  97257. }
  97258. /**
  97259. * A generic `Array#map` utility function.
  97260. * @private
  97261. * @param {Array} array The array to iterate over.
  97262. * @param {Function} callback The function that gets called for every array
  97263. * item.
  97264. * @returns {Array} A new array of values returned by the callback function.
  97265. */
  97266. function map(array, fn) {
  97267. var length = array.length;
  97268. var result = [];
  97269. while (length--) {
  97270. result[length] = fn(array[length]);
  97271. }
  97272. return result;
  97273. }
  97274. /**
  97275. * A simple `Array#map`-like wrapper to work with domain name strings or email
  97276. * addresses.
  97277. * @private
  97278. * @param {String} domain The domain name or email address.
  97279. * @param {Function} callback The function that gets called for every
  97280. * character.
  97281. * @returns {Array} A new string of characters returned by the callback
  97282. * function.
  97283. */
  97284. function mapDomain(string, fn) {
  97285. var parts = string.split('@');
  97286. var result = '';
  97287. if (parts.length > 1) {
  97288. // In email addresses, only the domain name should be punycoded. Leave
  97289. // the local part (i.e. everything up to `@`) intact.
  97290. result = parts[0] + '@';
  97291. string = parts[1];
  97292. }
  97293. // Avoid `split(regex)` for IE8 compatibility. See #17.
  97294. string = string.replace(regexSeparators, '\x2E');
  97295. var labels = string.split('.');
  97296. var encoded = map(labels, fn).join('.');
  97297. return result + encoded;
  97298. }
  97299. /**
  97300. * Creates an array containing the numeric code points of each Unicode
  97301. * character in the string. While JavaScript uses UCS-2 internally,
  97302. * this function will convert a pair of surrogate halves (each of which
  97303. * UCS-2 exposes as separate characters) into a single code point,
  97304. * matching UTF-16.
  97305. * @see `punycode.ucs2.encode`
  97306. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  97307. * @memberOf punycode.ucs2
  97308. * @name decode
  97309. * @param {String} string The Unicode input string (UCS-2).
  97310. * @returns {Array} The new array of code points.
  97311. */
  97312. function ucs2decode(string) {
  97313. var output = [],
  97314. counter = 0,
  97315. length = string.length,
  97316. value,
  97317. extra;
  97318. while (counter < length) {
  97319. value = string.charCodeAt(counter++);
  97320. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  97321. // high surrogate, and there is a next character
  97322. extra = string.charCodeAt(counter++);
  97323. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  97324. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  97325. } else {
  97326. // unmatched surrogate; only append this code unit, in case the next
  97327. // code unit is the high surrogate of a surrogate pair
  97328. output.push(value);
  97329. counter--;
  97330. }
  97331. } else {
  97332. output.push(value);
  97333. }
  97334. }
  97335. return output;
  97336. }
  97337. /**
  97338. * Creates a string based on an array of numeric code points.
  97339. * @see `punycode.ucs2.decode`
  97340. * @memberOf punycode.ucs2
  97341. * @name encode
  97342. * @param {Array} codePoints The array of numeric code points.
  97343. * @returns {String} The new Unicode string (UCS-2).
  97344. */
  97345. function ucs2encode(array) {
  97346. return map(array, function(value) {
  97347. var output = '';
  97348. if (value > 0xFFFF) {
  97349. value -= 0x10000;
  97350. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  97351. value = 0xDC00 | value & 0x3FF;
  97352. }
  97353. output += stringFromCharCode(value);
  97354. return output;
  97355. }).join('');
  97356. }
  97357. /**
  97358. * Converts a basic code point into a digit/integer.
  97359. * @see `digitToBasic()`
  97360. * @private
  97361. * @param {Number} codePoint The basic numeric code point value.
  97362. * @returns {Number} The numeric value of a basic code point (for use in
  97363. * representing integers) in the range `0` to `base - 1`, or `base` if
  97364. * the code point does not represent a value.
  97365. */
  97366. function basicToDigit(codePoint) {
  97367. if (codePoint - 48 < 10) {
  97368. return codePoint - 22;
  97369. }
  97370. if (codePoint - 65 < 26) {
  97371. return codePoint - 65;
  97372. }
  97373. if (codePoint - 97 < 26) {
  97374. return codePoint - 97;
  97375. }
  97376. return base;
  97377. }
  97378. /**
  97379. * Converts a digit/integer into a basic code point.
  97380. * @see `basicToDigit()`
  97381. * @private
  97382. * @param {Number} digit The numeric value of a basic code point.
  97383. * @returns {Number} The basic code point whose value (when used for
  97384. * representing integers) is `digit`, which needs to be in the range
  97385. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  97386. * used; else, the lowercase form is used. The behavior is undefined
  97387. * if `flag` is non-zero and `digit` has no uppercase form.
  97388. */
  97389. function digitToBasic(digit, flag) {
  97390. // 0..25 map to ASCII a..z or A..Z
  97391. // 26..35 map to ASCII 0..9
  97392. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  97393. }
  97394. /**
  97395. * Bias adaptation function as per section 3.4 of RFC 3492.
  97396. * https://tools.ietf.org/html/rfc3492#section-3.4
  97397. * @private
  97398. */
  97399. function adapt(delta, numPoints, firstTime) {
  97400. var k = 0;
  97401. delta = firstTime ? floor(delta / damp) : delta >> 1;
  97402. delta += floor(delta / numPoints);
  97403. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  97404. delta = floor(delta / baseMinusTMin);
  97405. }
  97406. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  97407. }
  97408. /**
  97409. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  97410. * symbols.
  97411. * @memberOf punycode
  97412. * @param {String} input The Punycode string of ASCII-only symbols.
  97413. * @returns {String} The resulting string of Unicode symbols.
  97414. */
  97415. function decode(input) {
  97416. // Don't use UCS-2
  97417. var output = [],
  97418. inputLength = input.length,
  97419. out,
  97420. i = 0,
  97421. n = initialN,
  97422. bias = initialBias,
  97423. basic,
  97424. j,
  97425. index,
  97426. oldi,
  97427. w,
  97428. k,
  97429. digit,
  97430. t,
  97431. /** Cached calculation results */
  97432. baseMinusT;
  97433. // Handle the basic code points: let `basic` be the number of input code
  97434. // points before the last delimiter, or `0` if there is none, then copy
  97435. // the first basic code points to the output.
  97436. basic = input.lastIndexOf(delimiter);
  97437. if (basic < 0) {
  97438. basic = 0;
  97439. }
  97440. for (j = 0; j < basic; ++j) {
  97441. // if it's not a basic code point
  97442. if (input.charCodeAt(j) >= 0x80) {
  97443. error('not-basic');
  97444. }
  97445. output.push(input.charCodeAt(j));
  97446. }
  97447. // Main decoding loop: start just after the last delimiter if any basic code
  97448. // points were copied; start at the beginning otherwise.
  97449. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  97450. // `index` is the index of the next character to be consumed.
  97451. // Decode a generalized variable-length integer into `delta`,
  97452. // which gets added to `i`. The overflow checking is easier
  97453. // if we increase `i` as we go, then subtract off its starting
  97454. // value at the end to obtain `delta`.
  97455. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  97456. if (index >= inputLength) {
  97457. error('invalid-input');
  97458. }
  97459. digit = basicToDigit(input.charCodeAt(index++));
  97460. if (digit >= base || digit > floor((maxInt - i) / w)) {
  97461. error('overflow');
  97462. }
  97463. i += digit * w;
  97464. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  97465. if (digit < t) {
  97466. break;
  97467. }
  97468. baseMinusT = base - t;
  97469. if (w > floor(maxInt / baseMinusT)) {
  97470. error('overflow');
  97471. }
  97472. w *= baseMinusT;
  97473. }
  97474. out = output.length + 1;
  97475. bias = adapt(i - oldi, out, oldi == 0);
  97476. // `i` was supposed to wrap around from `out` to `0`,
  97477. // incrementing `n` each time, so we'll fix that now:
  97478. if (floor(i / out) > maxInt - n) {
  97479. error('overflow');
  97480. }
  97481. n += floor(i / out);
  97482. i %= out;
  97483. // Insert `n` at position `i` of the output
  97484. output.splice(i++, 0, n);
  97485. }
  97486. return ucs2encode(output);
  97487. }
  97488. /**
  97489. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  97490. * Punycode string of ASCII-only symbols.
  97491. * @memberOf punycode
  97492. * @param {String} input The string of Unicode symbols.
  97493. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  97494. */
  97495. function encode(input) {
  97496. var n,
  97497. delta,
  97498. handledCPCount,
  97499. basicLength,
  97500. bias,
  97501. j,
  97502. m,
  97503. q,
  97504. k,
  97505. t,
  97506. currentValue,
  97507. output = [],
  97508. /** `inputLength` will hold the number of code points in `input`. */
  97509. inputLength,
  97510. /** Cached calculation results */
  97511. handledCPCountPlusOne,
  97512. baseMinusT,
  97513. qMinusT;
  97514. // Convert the input in UCS-2 to Unicode
  97515. input = ucs2decode(input);
  97516. // Cache the length
  97517. inputLength = input.length;
  97518. // Initialize the state
  97519. n = initialN;
  97520. delta = 0;
  97521. bias = initialBias;
  97522. // Handle the basic code points
  97523. for (j = 0; j < inputLength; ++j) {
  97524. currentValue = input[j];
  97525. if (currentValue < 0x80) {
  97526. output.push(stringFromCharCode(currentValue));
  97527. }
  97528. }
  97529. handledCPCount = basicLength = output.length;
  97530. // `handledCPCount` is the number of code points that have been handled;
  97531. // `basicLength` is the number of basic code points.
  97532. // Finish the basic string - if it is not empty - with a delimiter
  97533. if (basicLength) {
  97534. output.push(delimiter);
  97535. }
  97536. // Main encoding loop:
  97537. while (handledCPCount < inputLength) {
  97538. // All non-basic code points < n have been handled already. Find the next
  97539. // larger one:
  97540. for (m = maxInt, j = 0; j < inputLength; ++j) {
  97541. currentValue = input[j];
  97542. if (currentValue >= n && currentValue < m) {
  97543. m = currentValue;
  97544. }
  97545. }
  97546. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  97547. // but guard against overflow
  97548. handledCPCountPlusOne = handledCPCount + 1;
  97549. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  97550. error('overflow');
  97551. }
  97552. delta += (m - n) * handledCPCountPlusOne;
  97553. n = m;
  97554. for (j = 0; j < inputLength; ++j) {
  97555. currentValue = input[j];
  97556. if (currentValue < n && ++delta > maxInt) {
  97557. error('overflow');
  97558. }
  97559. if (currentValue == n) {
  97560. // Represent delta as a generalized variable-length integer
  97561. for (q = delta, k = base; /* no condition */; k += base) {
  97562. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  97563. if (q < t) {
  97564. break;
  97565. }
  97566. qMinusT = q - t;
  97567. baseMinusT = base - t;
  97568. output.push(
  97569. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  97570. );
  97571. q = floor(qMinusT / baseMinusT);
  97572. }
  97573. output.push(stringFromCharCode(digitToBasic(q, 0)));
  97574. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  97575. delta = 0;
  97576. ++handledCPCount;
  97577. }
  97578. }
  97579. ++delta;
  97580. ++n;
  97581. }
  97582. return output.join('');
  97583. }
  97584. /**
  97585. * Converts a Punycode string representing a domain name or an email address
  97586. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  97587. * it doesn't matter if you call it on a string that has already been
  97588. * converted to Unicode.
  97589. * @memberOf punycode
  97590. * @param {String} input The Punycoded domain name or email address to
  97591. * convert to Unicode.
  97592. * @returns {String} The Unicode representation of the given Punycode
  97593. * string.
  97594. */
  97595. function toUnicode(input) {
  97596. return mapDomain(input, function(string) {
  97597. return regexPunycode.test(string)
  97598. ? decode(string.slice(4).toLowerCase())
  97599. : string;
  97600. });
  97601. }
  97602. /**
  97603. * Converts a Unicode string representing a domain name or an email address to
  97604. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  97605. * i.e. it doesn't matter if you call it with a domain that's already in
  97606. * ASCII.
  97607. * @memberOf punycode
  97608. * @param {String} input The domain name or email address to convert, as a
  97609. * Unicode string.
  97610. * @returns {String} The Punycode representation of the given domain name or
  97611. * email address.
  97612. */
  97613. function toASCII(input) {
  97614. return mapDomain(input, function(string) {
  97615. return regexNonASCII.test(string)
  97616. ? 'xn--' + encode(string)
  97617. : string;
  97618. });
  97619. }
  97620. /*--------------------------------------------------------------------------*/
  97621. /** Define the public API */
  97622. punycode = {
  97623. /**
  97624. * A string representing the current Punycode.js version number.
  97625. * @memberOf punycode
  97626. * @type String
  97627. */
  97628. 'version': '1.4.1',
  97629. /**
  97630. * An object of methods to convert from JavaScript's internal character
  97631. * representation (UCS-2) to Unicode code points, and back.
  97632. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  97633. * @memberOf punycode
  97634. * @type Object
  97635. */
  97636. 'ucs2': {
  97637. 'decode': ucs2decode,
  97638. 'encode': ucs2encode
  97639. },
  97640. 'decode': decode,
  97641. 'encode': encode,
  97642. 'toASCII': toASCII,
  97643. 'toUnicode': toUnicode
  97644. };
  97645. /** Expose `punycode` */
  97646. // Some AMD build optimizers, like r.js, check for specific condition patterns
  97647. // like the following:
  97648. if (
  97649. typeof define == 'function' &&
  97650. typeof define.amd == 'object' &&
  97651. define.amd
  97652. ) {
  97653. define('punycode', function() {
  97654. return punycode;
  97655. });
  97656. } else if (freeExports && freeModule) {
  97657. if (module.exports == freeExports) {
  97658. // in Node.js, io.js, or RingoJS v0.8.0+
  97659. freeModule.exports = punycode;
  97660. } else {
  97661. // in Narwhal or RingoJS v0.7.0-
  97662. for (key in punycode) {
  97663. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  97664. }
  97665. }
  97666. } else {
  97667. // in Rhino or a web browser
  97668. root.punycode = punycode;
  97669. }
  97670. }(this));
  97671. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  97672. },{}],536:[function(require,module,exports){
  97673. 'use strict';
  97674. var replace = String.prototype.replace;
  97675. var percentTwenties = /%20/g;
  97676. module.exports = {
  97677. 'default': 'RFC3986',
  97678. formatters: {
  97679. RFC1738: function (value) {
  97680. return replace.call(value, percentTwenties, '+');
  97681. },
  97682. RFC3986: function (value) {
  97683. return value;
  97684. }
  97685. },
  97686. RFC1738: 'RFC1738',
  97687. RFC3986: 'RFC3986'
  97688. };
  97689. },{}],537:[function(require,module,exports){
  97690. 'use strict';
  97691. var stringify = require('./stringify');
  97692. var parse = require('./parse');
  97693. var formats = require('./formats');
  97694. module.exports = {
  97695. formats: formats,
  97696. parse: parse,
  97697. stringify: stringify
  97698. };
  97699. },{"./formats":536,"./parse":538,"./stringify":539}],538:[function(require,module,exports){
  97700. 'use strict';
  97701. var utils = require('./utils');
  97702. var has = Object.prototype.hasOwnProperty;
  97703. var defaults = {
  97704. allowDots: false,
  97705. allowPrototypes: false,
  97706. arrayLimit: 20,
  97707. decoder: utils.decode,
  97708. delimiter: '&',
  97709. depth: 5,
  97710. parameterLimit: 1000,
  97711. plainObjects: false,
  97712. strictNullHandling: false
  97713. };
  97714. var parseValues = function parseQueryStringValues(str, options) {
  97715. var obj = {};
  97716. var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
  97717. var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
  97718. var parts = cleanStr.split(options.delimiter, limit);
  97719. for (var i = 0; i < parts.length; ++i) {
  97720. var part = parts[i];
  97721. var bracketEqualsPos = part.indexOf(']=');
  97722. var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
  97723. var key, val;
  97724. if (pos === -1) {
  97725. key = options.decoder(part, defaults.decoder);
  97726. val = options.strictNullHandling ? null : '';
  97727. } else {
  97728. key = options.decoder(part.slice(0, pos), defaults.decoder);
  97729. val = options.decoder(part.slice(pos + 1), defaults.decoder);
  97730. }
  97731. if (has.call(obj, key)) {
  97732. obj[key] = [].concat(obj[key]).concat(val);
  97733. } else {
  97734. obj[key] = val;
  97735. }
  97736. }
  97737. return obj;
  97738. };
  97739. var parseObject = function (chain, val, options) {
  97740. var leaf = val;
  97741. for (var i = chain.length - 1; i >= 0; --i) {
  97742. var obj;
  97743. var root = chain[i];
  97744. if (root === '[]') {
  97745. obj = [];
  97746. obj = obj.concat(leaf);
  97747. } else {
  97748. obj = options.plainObjects ? Object.create(null) : {};
  97749. var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
  97750. var index = parseInt(cleanRoot, 10);
  97751. if (
  97752. !isNaN(index)
  97753. && root !== cleanRoot
  97754. && String(index) === cleanRoot
  97755. && index >= 0
  97756. && (options.parseArrays && index <= options.arrayLimit)
  97757. ) {
  97758. obj = [];
  97759. obj[index] = leaf;
  97760. } else {
  97761. obj[cleanRoot] = leaf;
  97762. }
  97763. }
  97764. leaf = obj;
  97765. }
  97766. return leaf;
  97767. };
  97768. var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
  97769. if (!givenKey) {
  97770. return;
  97771. }
  97772. // Transform dot notation to bracket notation
  97773. var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
  97774. // The regex chunks
  97775. var brackets = /(\[[^[\]]*])/;
  97776. var child = /(\[[^[\]]*])/g;
  97777. // Get the parent
  97778. var segment = brackets.exec(key);
  97779. var parent = segment ? key.slice(0, segment.index) : key;
  97780. // Stash the parent if it exists
  97781. var keys = [];
  97782. if (parent) {
  97783. // If we aren't using plain objects, optionally prefix keys
  97784. // that would overwrite object prototype properties
  97785. if (!options.plainObjects && has.call(Object.prototype, parent)) {
  97786. if (!options.allowPrototypes) {
  97787. return;
  97788. }
  97789. }
  97790. keys.push(parent);
  97791. }
  97792. // Loop through children appending to the array until we hit depth
  97793. var i = 0;
  97794. while ((segment = child.exec(key)) !== null && i < options.depth) {
  97795. i += 1;
  97796. if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
  97797. if (!options.allowPrototypes) {
  97798. return;
  97799. }
  97800. }
  97801. keys.push(segment[1]);
  97802. }
  97803. // If there's a remainder, just add whatever is left
  97804. if (segment) {
  97805. keys.push('[' + key.slice(segment.index) + ']');
  97806. }
  97807. return parseObject(keys, val, options);
  97808. };
  97809. module.exports = function (str, opts) {
  97810. var options = opts ? utils.assign({}, opts) : {};
  97811. if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
  97812. throw new TypeError('Decoder has to be a function.');
  97813. }
  97814. options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
  97815. options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
  97816. options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
  97817. options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
  97818. options.parseArrays = options.parseArrays !== false;
  97819. options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
  97820. options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
  97821. options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
  97822. options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
  97823. options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
  97824. options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
  97825. if (str === '' || str === null || typeof str === 'undefined') {
  97826. return options.plainObjects ? Object.create(null) : {};
  97827. }
  97828. var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
  97829. var obj = options.plainObjects ? Object.create(null) : {};
  97830. // Iterate over the keys and setup the new object
  97831. var keys = Object.keys(tempObj);
  97832. for (var i = 0; i < keys.length; ++i) {
  97833. var key = keys[i];
  97834. var newObj = parseKeys(key, tempObj[key], options);
  97835. obj = utils.merge(obj, newObj, options);
  97836. }
  97837. return utils.compact(obj);
  97838. };
  97839. },{"./utils":540}],539:[function(require,module,exports){
  97840. 'use strict';
  97841. var utils = require('./utils');
  97842. var formats = require('./formats');
  97843. var arrayPrefixGenerators = {
  97844. brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
  97845. return prefix + '[]';
  97846. },
  97847. indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
  97848. return prefix + '[' + key + ']';
  97849. },
  97850. repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
  97851. return prefix;
  97852. }
  97853. };
  97854. var toISO = Date.prototype.toISOString;
  97855. var defaults = {
  97856. delimiter: '&',
  97857. encode: true,
  97858. encoder: utils.encode,
  97859. encodeValuesOnly: false,
  97860. serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
  97861. return toISO.call(date);
  97862. },
  97863. skipNulls: false,
  97864. strictNullHandling: false
  97865. };
  97866. var stringify = function stringify( // eslint-disable-line func-name-matching
  97867. object,
  97868. prefix,
  97869. generateArrayPrefix,
  97870. strictNullHandling,
  97871. skipNulls,
  97872. encoder,
  97873. filter,
  97874. sort,
  97875. allowDots,
  97876. serializeDate,
  97877. formatter,
  97878. encodeValuesOnly
  97879. ) {
  97880. var obj = object;
  97881. if (typeof filter === 'function') {
  97882. obj = filter(prefix, obj);
  97883. } else if (obj instanceof Date) {
  97884. obj = serializeDate(obj);
  97885. } else if (obj === null) {
  97886. if (strictNullHandling) {
  97887. return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix;
  97888. }
  97889. obj = '';
  97890. }
  97891. if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
  97892. if (encoder) {
  97893. var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder);
  97894. return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))];
  97895. }
  97896. return [formatter(prefix) + '=' + formatter(String(obj))];
  97897. }
  97898. var values = [];
  97899. if (typeof obj === 'undefined') {
  97900. return values;
  97901. }
  97902. var objKeys;
  97903. if (Array.isArray(filter)) {
  97904. objKeys = filter;
  97905. } else {
  97906. var keys = Object.keys(obj);
  97907. objKeys = sort ? keys.sort(sort) : keys;
  97908. }
  97909. for (var i = 0; i < objKeys.length; ++i) {
  97910. var key = objKeys[i];
  97911. if (skipNulls && obj[key] === null) {
  97912. continue;
  97913. }
  97914. if (Array.isArray(obj)) {
  97915. values = values.concat(stringify(
  97916. obj[key],
  97917. generateArrayPrefix(prefix, key),
  97918. generateArrayPrefix,
  97919. strictNullHandling,
  97920. skipNulls,
  97921. encoder,
  97922. filter,
  97923. sort,
  97924. allowDots,
  97925. serializeDate,
  97926. formatter,
  97927. encodeValuesOnly
  97928. ));
  97929. } else {
  97930. values = values.concat(stringify(
  97931. obj[key],
  97932. prefix + (allowDots ? '.' + key : '[' + key + ']'),
  97933. generateArrayPrefix,
  97934. strictNullHandling,
  97935. skipNulls,
  97936. encoder,
  97937. filter,
  97938. sort,
  97939. allowDots,
  97940. serializeDate,
  97941. formatter,
  97942. encodeValuesOnly
  97943. ));
  97944. }
  97945. }
  97946. return values;
  97947. };
  97948. module.exports = function (object, opts) {
  97949. var obj = object;
  97950. var options = opts ? utils.assign({}, opts) : {};
  97951. if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
  97952. throw new TypeError('Encoder has to be a function.');
  97953. }
  97954. var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
  97955. var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
  97956. var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
  97957. var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
  97958. var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder;
  97959. var sort = typeof options.sort === 'function' ? options.sort : null;
  97960. var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
  97961. var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
  97962. var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
  97963. if (typeof options.format === 'undefined') {
  97964. options.format = formats['default'];
  97965. } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
  97966. throw new TypeError('Unknown format option provided.');
  97967. }
  97968. var formatter = formats.formatters[options.format];
  97969. var objKeys;
  97970. var filter;
  97971. if (typeof options.filter === 'function') {
  97972. filter = options.filter;
  97973. obj = filter('', obj);
  97974. } else if (Array.isArray(options.filter)) {
  97975. filter = options.filter;
  97976. objKeys = filter;
  97977. }
  97978. var keys = [];
  97979. if (typeof obj !== 'object' || obj === null) {
  97980. return '';
  97981. }
  97982. var arrayFormat;
  97983. if (options.arrayFormat in arrayPrefixGenerators) {
  97984. arrayFormat = options.arrayFormat;
  97985. } else if ('indices' in options) {
  97986. arrayFormat = options.indices ? 'indices' : 'repeat';
  97987. } else {
  97988. arrayFormat = 'indices';
  97989. }
  97990. var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
  97991. if (!objKeys) {
  97992. objKeys = Object.keys(obj);
  97993. }
  97994. if (sort) {
  97995. objKeys.sort(sort);
  97996. }
  97997. for (var i = 0; i < objKeys.length; ++i) {
  97998. var key = objKeys[i];
  97999. if (skipNulls && obj[key] === null) {
  98000. continue;
  98001. }
  98002. keys = keys.concat(stringify(
  98003. obj[key],
  98004. key,
  98005. generateArrayPrefix,
  98006. strictNullHandling,
  98007. skipNulls,
  98008. encode ? encoder : null,
  98009. filter,
  98010. sort,
  98011. allowDots,
  98012. serializeDate,
  98013. formatter,
  98014. encodeValuesOnly
  98015. ));
  98016. }
  98017. var joined = keys.join(delimiter);
  98018. var prefix = options.addQueryPrefix === true ? '?' : '';
  98019. return joined.length > 0 ? prefix + joined : '';
  98020. };
  98021. },{"./formats":536,"./utils":540}],540:[function(require,module,exports){
  98022. 'use strict';
  98023. var has = Object.prototype.hasOwnProperty;
  98024. var hexTable = (function () {
  98025. var array = [];
  98026. for (var i = 0; i < 256; ++i) {
  98027. array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
  98028. }
  98029. return array;
  98030. }());
  98031. var compactQueue = function compactQueue(queue) {
  98032. var obj;
  98033. while (queue.length) {
  98034. var item = queue.pop();
  98035. obj = item.obj[item.prop];
  98036. if (Array.isArray(obj)) {
  98037. var compacted = [];
  98038. for (var j = 0; j < obj.length; ++j) {
  98039. if (typeof obj[j] !== 'undefined') {
  98040. compacted.push(obj[j]);
  98041. }
  98042. }
  98043. item.obj[item.prop] = compacted;
  98044. }
  98045. }
  98046. return obj;
  98047. };
  98048. var arrayToObject = function arrayToObject(source, options) {
  98049. var obj = options && options.plainObjects ? Object.create(null) : {};
  98050. for (var i = 0; i < source.length; ++i) {
  98051. if (typeof source[i] !== 'undefined') {
  98052. obj[i] = source[i];
  98053. }
  98054. }
  98055. return obj;
  98056. };
  98057. var merge = function merge(target, source, options) {
  98058. if (!source) {
  98059. return target;
  98060. }
  98061. if (typeof source !== 'object') {
  98062. if (Array.isArray(target)) {
  98063. target.push(source);
  98064. } else if (typeof target === 'object') {
  98065. if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
  98066. target[source] = true;
  98067. }
  98068. } else {
  98069. return [target, source];
  98070. }
  98071. return target;
  98072. }
  98073. if (typeof target !== 'object') {
  98074. return [target].concat(source);
  98075. }
  98076. var mergeTarget = target;
  98077. if (Array.isArray(target) && !Array.isArray(source)) {
  98078. mergeTarget = arrayToObject(target, options);
  98079. }
  98080. if (Array.isArray(target) && Array.isArray(source)) {
  98081. source.forEach(function (item, i) {
  98082. if (has.call(target, i)) {
  98083. if (target[i] && typeof target[i] === 'object') {
  98084. target[i] = merge(target[i], item, options);
  98085. } else {
  98086. target.push(item);
  98087. }
  98088. } else {
  98089. target[i] = item;
  98090. }
  98091. });
  98092. return target;
  98093. }
  98094. return Object.keys(source).reduce(function (acc, key) {
  98095. var value = source[key];
  98096. if (has.call(acc, key)) {
  98097. acc[key] = merge(acc[key], value, options);
  98098. } else {
  98099. acc[key] = value;
  98100. }
  98101. return acc;
  98102. }, mergeTarget);
  98103. };
  98104. var assign = function assignSingleSource(target, source) {
  98105. return Object.keys(source).reduce(function (acc, key) {
  98106. acc[key] = source[key];
  98107. return acc;
  98108. }, target);
  98109. };
  98110. var decode = function (str) {
  98111. try {
  98112. return decodeURIComponent(str.replace(/\+/g, ' '));
  98113. } catch (e) {
  98114. return str;
  98115. }
  98116. };
  98117. var encode = function encode(str) {
  98118. // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
  98119. // It has been adapted here for stricter adherence to RFC 3986
  98120. if (str.length === 0) {
  98121. return str;
  98122. }
  98123. var string = typeof str === 'string' ? str : String(str);
  98124. var out = '';
  98125. for (var i = 0; i < string.length; ++i) {
  98126. var c = string.charCodeAt(i);
  98127. if (
  98128. c === 0x2D // -
  98129. || c === 0x2E // .
  98130. || c === 0x5F // _
  98131. || c === 0x7E // ~
  98132. || (c >= 0x30 && c <= 0x39) // 0-9
  98133. || (c >= 0x41 && c <= 0x5A) // a-z
  98134. || (c >= 0x61 && c <= 0x7A) // A-Z
  98135. ) {
  98136. out += string.charAt(i);
  98137. continue;
  98138. }
  98139. if (c < 0x80) {
  98140. out = out + hexTable[c];
  98141. continue;
  98142. }
  98143. if (c < 0x800) {
  98144. out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
  98145. continue;
  98146. }
  98147. if (c < 0xD800 || c >= 0xE000) {
  98148. out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
  98149. continue;
  98150. }
  98151. i += 1;
  98152. c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
  98153. out += hexTable[0xF0 | (c >> 18)]
  98154. + hexTable[0x80 | ((c >> 12) & 0x3F)]
  98155. + hexTable[0x80 | ((c >> 6) & 0x3F)]
  98156. + hexTable[0x80 | (c & 0x3F)];
  98157. }
  98158. return out;
  98159. };
  98160. var compact = function compact(value) {
  98161. var queue = [{ obj: { o: value }, prop: 'o' }];
  98162. var refs = [];
  98163. for (var i = 0; i < queue.length; ++i) {
  98164. var item = queue[i];
  98165. var obj = item.obj[item.prop];
  98166. var keys = Object.keys(obj);
  98167. for (var j = 0; j < keys.length; ++j) {
  98168. var key = keys[j];
  98169. var val = obj[key];
  98170. if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
  98171. queue.push({ obj: obj, prop: key });
  98172. refs.push(val);
  98173. }
  98174. }
  98175. }
  98176. return compactQueue(queue);
  98177. };
  98178. var isRegExp = function isRegExp(obj) {
  98179. return Object.prototype.toString.call(obj) === '[object RegExp]';
  98180. };
  98181. var isBuffer = function isBuffer(obj) {
  98182. if (obj === null || typeof obj === 'undefined') {
  98183. return false;
  98184. }
  98185. return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
  98186. };
  98187. module.exports = {
  98188. arrayToObject: arrayToObject,
  98189. assign: assign,
  98190. compact: compact,
  98191. decode: decode,
  98192. encode: encode,
  98193. isBuffer: isBuffer,
  98194. isRegExp: isRegExp,
  98195. merge: merge
  98196. };
  98197. },{}],541:[function(require,module,exports){
  98198. // Copyright Joyent, Inc. and other Node contributors.
  98199. //
  98200. // Permission is hereby granted, free of charge, to any person obtaining a
  98201. // copy of this software and associated documentation files (the
  98202. // "Software"), to deal in the Software without restriction, including
  98203. // without limitation the rights to use, copy, modify, merge, publish,
  98204. // distribute, sublicense, and/or sell copies of the Software, and to permit
  98205. // persons to whom the Software is furnished to do so, subject to the
  98206. // following conditions:
  98207. //
  98208. // The above copyright notice and this permission notice shall be included
  98209. // in all copies or substantial portions of the Software.
  98210. //
  98211. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  98212. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  98213. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  98214. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  98215. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  98216. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  98217. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  98218. 'use strict';
  98219. // If obj.hasOwnProperty has been overridden, then calling
  98220. // obj.hasOwnProperty(prop) will break.
  98221. // See: https://github.com/joyent/node/issues/1707
  98222. function hasOwnProperty(obj, prop) {
  98223. return Object.prototype.hasOwnProperty.call(obj, prop);
  98224. }
  98225. module.exports = function(qs, sep, eq, options) {
  98226. sep = sep || '&';
  98227. eq = eq || '=';
  98228. var obj = {};
  98229. if (typeof qs !== 'string' || qs.length === 0) {
  98230. return obj;
  98231. }
  98232. var regexp = /\+/g;
  98233. qs = qs.split(sep);
  98234. var maxKeys = 1000;
  98235. if (options && typeof options.maxKeys === 'number') {
  98236. maxKeys = options.maxKeys;
  98237. }
  98238. var len = qs.length;
  98239. // maxKeys <= 0 means that we should not limit keys count
  98240. if (maxKeys > 0 && len > maxKeys) {
  98241. len = maxKeys;
  98242. }
  98243. for (var i = 0; i < len; ++i) {
  98244. var x = qs[i].replace(regexp, '%20'),
  98245. idx = x.indexOf(eq),
  98246. kstr, vstr, k, v;
  98247. if (idx >= 0) {
  98248. kstr = x.substr(0, idx);
  98249. vstr = x.substr(idx + 1);
  98250. } else {
  98251. kstr = x;
  98252. vstr = '';
  98253. }
  98254. k = decodeURIComponent(kstr);
  98255. v = decodeURIComponent(vstr);
  98256. if (!hasOwnProperty(obj, k)) {
  98257. obj[k] = v;
  98258. } else if (isArray(obj[k])) {
  98259. obj[k].push(v);
  98260. } else {
  98261. obj[k] = [obj[k], v];
  98262. }
  98263. }
  98264. return obj;
  98265. };
  98266. var isArray = Array.isArray || function (xs) {
  98267. return Object.prototype.toString.call(xs) === '[object Array]';
  98268. };
  98269. },{}],542:[function(require,module,exports){
  98270. // Copyright Joyent, Inc. and other Node contributors.
  98271. //
  98272. // Permission is hereby granted, free of charge, to any person obtaining a
  98273. // copy of this software and associated documentation files (the
  98274. // "Software"), to deal in the Software without restriction, including
  98275. // without limitation the rights to use, copy, modify, merge, publish,
  98276. // distribute, sublicense, and/or sell copies of the Software, and to permit
  98277. // persons to whom the Software is furnished to do so, subject to the
  98278. // following conditions:
  98279. //
  98280. // The above copyright notice and this permission notice shall be included
  98281. // in all copies or substantial portions of the Software.
  98282. //
  98283. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  98284. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  98285. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  98286. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  98287. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  98288. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  98289. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  98290. 'use strict';
  98291. var stringifyPrimitive = function(v) {
  98292. switch (typeof v) {
  98293. case 'string':
  98294. return v;
  98295. case 'boolean':
  98296. return v ? 'true' : 'false';
  98297. case 'number':
  98298. return isFinite(v) ? v : '';
  98299. default:
  98300. return '';
  98301. }
  98302. };
  98303. module.exports = function(obj, sep, eq, name) {
  98304. sep = sep || '&';
  98305. eq = eq || '=';
  98306. if (obj === null) {
  98307. obj = undefined;
  98308. }
  98309. if (typeof obj === 'object') {
  98310. return map(objectKeys(obj), function(k) {
  98311. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  98312. if (isArray(obj[k])) {
  98313. return map(obj[k], function(v) {
  98314. return ks + encodeURIComponent(stringifyPrimitive(v));
  98315. }).join(sep);
  98316. } else {
  98317. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  98318. }
  98319. }).join(sep);
  98320. }
  98321. if (!name) return '';
  98322. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  98323. encodeURIComponent(stringifyPrimitive(obj));
  98324. };
  98325. var isArray = Array.isArray || function (xs) {
  98326. return Object.prototype.toString.call(xs) === '[object Array]';
  98327. };
  98328. function map (xs, f) {
  98329. if (xs.map) return xs.map(f);
  98330. var res = [];
  98331. for (var i = 0; i < xs.length; i++) {
  98332. res.push(f(xs[i], i));
  98333. }
  98334. return res;
  98335. }
  98336. var objectKeys = Object.keys || function (obj) {
  98337. var res = [];
  98338. for (var key in obj) {
  98339. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  98340. }
  98341. return res;
  98342. };
  98343. },{}],543:[function(require,module,exports){
  98344. 'use strict';
  98345. exports.decode = exports.parse = require('./decode');
  98346. exports.encode = exports.stringify = require('./encode');
  98347. },{"./decode":541,"./encode":542}],544:[function(require,module,exports){
  98348. (function (process,global){(function (){
  98349. 'use strict'
  98350. // limit of Crypto.getRandomValues()
  98351. // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
  98352. var MAX_BYTES = 65536
  98353. // Node supports requesting up to this number of bytes
  98354. // https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
  98355. var MAX_UINT32 = 4294967295
  98356. function oldBrowser () {
  98357. throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
  98358. }
  98359. var Buffer = require('safe-buffer').Buffer
  98360. var crypto = global.crypto || global.msCrypto
  98361. if (crypto && crypto.getRandomValues) {
  98362. module.exports = randomBytes
  98363. } else {
  98364. module.exports = oldBrowser
  98365. }
  98366. function randomBytes (size, cb) {
  98367. // phantomjs needs to throw
  98368. if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
  98369. var bytes = Buffer.allocUnsafe(size)
  98370. if (size > 0) { // getRandomValues fails on IE if size == 0
  98371. if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
  98372. // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
  98373. for (var generated = 0; generated < size; generated += MAX_BYTES) {
  98374. // buffer.slice automatically checks if the end is past the end of
  98375. // the buffer so we don't have to here
  98376. crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
  98377. }
  98378. } else {
  98379. crypto.getRandomValues(bytes)
  98380. }
  98381. }
  98382. if (typeof cb === 'function') {
  98383. return process.nextTick(function () {
  98384. cb(null, bytes)
  98385. })
  98386. }
  98387. return bytes
  98388. }
  98389. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  98390. },{"_process":525,"safe-buffer":561}],545:[function(require,module,exports){
  98391. (function (process,global){(function (){
  98392. 'use strict'
  98393. function oldBrowser () {
  98394. throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
  98395. }
  98396. var safeBuffer = require('safe-buffer')
  98397. var randombytes = require('randombytes')
  98398. var Buffer = safeBuffer.Buffer
  98399. var kBufferMaxLength = safeBuffer.kMaxLength
  98400. var crypto = global.crypto || global.msCrypto
  98401. var kMaxUint32 = Math.pow(2, 32) - 1
  98402. function assertOffset (offset, length) {
  98403. if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
  98404. throw new TypeError('offset must be a number')
  98405. }
  98406. if (offset > kMaxUint32 || offset < 0) {
  98407. throw new TypeError('offset must be a uint32')
  98408. }
  98409. if (offset > kBufferMaxLength || offset > length) {
  98410. throw new RangeError('offset out of range')
  98411. }
  98412. }
  98413. function assertSize (size, offset, length) {
  98414. if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
  98415. throw new TypeError('size must be a number')
  98416. }
  98417. if (size > kMaxUint32 || size < 0) {
  98418. throw new TypeError('size must be a uint32')
  98419. }
  98420. if (size + offset > length || size > kBufferMaxLength) {
  98421. throw new RangeError('buffer too small')
  98422. }
  98423. }
  98424. if ((crypto && crypto.getRandomValues) || !process.browser) {
  98425. exports.randomFill = randomFill
  98426. exports.randomFillSync = randomFillSync
  98427. } else {
  98428. exports.randomFill = oldBrowser
  98429. exports.randomFillSync = oldBrowser
  98430. }
  98431. function randomFill (buf, offset, size, cb) {
  98432. if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
  98433. throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  98434. }
  98435. if (typeof offset === 'function') {
  98436. cb = offset
  98437. offset = 0
  98438. size = buf.length
  98439. } else if (typeof size === 'function') {
  98440. cb = size
  98441. size = buf.length - offset
  98442. } else if (typeof cb !== 'function') {
  98443. throw new TypeError('"cb" argument must be a function')
  98444. }
  98445. assertOffset(offset, buf.length)
  98446. assertSize(size, offset, buf.length)
  98447. return actualFill(buf, offset, size, cb)
  98448. }
  98449. function actualFill (buf, offset, size, cb) {
  98450. if (process.browser) {
  98451. var ourBuf = buf.buffer
  98452. var uint = new Uint8Array(ourBuf, offset, size)
  98453. crypto.getRandomValues(uint)
  98454. if (cb) {
  98455. process.nextTick(function () {
  98456. cb(null, buf)
  98457. })
  98458. return
  98459. }
  98460. return buf
  98461. }
  98462. if (cb) {
  98463. randombytes(size, function (err, bytes) {
  98464. if (err) {
  98465. return cb(err)
  98466. }
  98467. bytes.copy(buf, offset)
  98468. cb(null, buf)
  98469. })
  98470. return
  98471. }
  98472. var bytes = randombytes(size)
  98473. bytes.copy(buf, offset)
  98474. return buf
  98475. }
  98476. function randomFillSync (buf, offset, size) {
  98477. if (typeof offset === 'undefined') {
  98478. offset = 0
  98479. }
  98480. if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
  98481. throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
  98482. }
  98483. assertOffset(offset, buf.length)
  98484. if (size === undefined) size = buf.length - offset
  98485. assertSize(size, offset, buf.length)
  98486. return actualFill(buf, offset, size)
  98487. }
  98488. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  98489. },{"_process":525,"randombytes":544,"safe-buffer":561}],546:[function(require,module,exports){
  98490. // Copyright 2010-2012 Mikeal Rogers
  98491. //
  98492. // Licensed under the Apache License, Version 2.0 (the "License");
  98493. // you may not use this file except in compliance with the License.
  98494. // You may obtain a copy of the License at
  98495. //
  98496. // http://www.apache.org/licenses/LICENSE-2.0
  98497. //
  98498. // Unless required by applicable law or agreed to in writing, software
  98499. // distributed under the License is distributed on an "AS IS" BASIS,
  98500. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  98501. // See the License for the specific language governing permissions and
  98502. // limitations under the License.
  98503. 'use strict'
  98504. var extend = require('extend')
  98505. var cookies = require('./lib/cookies')
  98506. var helpers = require('./lib/helpers')
  98507. var paramsHaveRequestBody = helpers.paramsHaveRequestBody
  98508. // organize params for patch, post, put, head, del
  98509. function initParams (uri, options, callback) {
  98510. if (typeof options === 'function') {
  98511. callback = options
  98512. }
  98513. var params = {}
  98514. if (options !== null && typeof options === 'object') {
  98515. extend(params, options, {uri: uri})
  98516. } else if (typeof uri === 'string') {
  98517. extend(params, {uri: uri})
  98518. } else {
  98519. extend(params, uri)
  98520. }
  98521. params.callback = callback || params.callback
  98522. return params
  98523. }
  98524. function request (uri, options, callback) {
  98525. if (typeof uri === 'undefined') {
  98526. throw new Error('undefined is not a valid uri or options object.')
  98527. }
  98528. var params = initParams(uri, options, callback)
  98529. if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
  98530. throw new Error('HTTP HEAD requests MUST NOT include a request body.')
  98531. }
  98532. return new request.Request(params)
  98533. }
  98534. function verbFunc (verb) {
  98535. var method = verb.toUpperCase()
  98536. return function (uri, options, callback) {
  98537. var params = initParams(uri, options, callback)
  98538. params.method = method
  98539. return request(params, params.callback)
  98540. }
  98541. }
  98542. // define like this to please codeintel/intellisense IDEs
  98543. request.get = verbFunc('get')
  98544. request.head = verbFunc('head')
  98545. request.options = verbFunc('options')
  98546. request.post = verbFunc('post')
  98547. request.put = verbFunc('put')
  98548. request.patch = verbFunc('patch')
  98549. request.del = verbFunc('delete')
  98550. request['delete'] = verbFunc('delete')
  98551. request.jar = function (store) {
  98552. return cookies.jar(store)
  98553. }
  98554. request.cookie = function (str) {
  98555. return cookies.parse(str)
  98556. }
  98557. function wrapRequestMethod (method, options, requester, verb) {
  98558. return function (uri, opts, callback) {
  98559. var params = initParams(uri, opts, callback)
  98560. var target = {}
  98561. extend(true, target, options, params)
  98562. target.pool = params.pool || options.pool
  98563. if (verb) {
  98564. target.method = verb.toUpperCase()
  98565. }
  98566. if (typeof requester === 'function') {
  98567. method = requester
  98568. }
  98569. return method(target, target.callback)
  98570. }
  98571. }
  98572. request.defaults = function (options, requester) {
  98573. var self = this
  98574. options = options || {}
  98575. if (typeof options === 'function') {
  98576. requester = options
  98577. options = {}
  98578. }
  98579. var defaults = wrapRequestMethod(self, options, requester)
  98580. var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
  98581. verbs.forEach(function (verb) {
  98582. defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
  98583. })
  98584. defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
  98585. defaults.jar = self.jar
  98586. defaults.defaults = self.defaults
  98587. return defaults
  98588. }
  98589. request.forever = function (agentOptions, optionsArg) {
  98590. var options = {}
  98591. if (optionsArg) {
  98592. extend(options, optionsArg)
  98593. }
  98594. if (agentOptions) {
  98595. options.agentOptions = agentOptions
  98596. }
  98597. options.forever = true
  98598. return request.defaults(options)
  98599. }
  98600. // Exports
  98601. module.exports = request
  98602. request.Request = require('./request')
  98603. request.initParams = initParams
  98604. // Backwards compatibility for request.debug
  98605. Object.defineProperty(request, 'debug', {
  98606. enumerable: true,
  98607. get: function () {
  98608. return request.Request.debug
  98609. },
  98610. set: function (debug) {
  98611. request.Request.debug = debug
  98612. }
  98613. })
  98614. },{"./lib/cookies":548,"./lib/helpers":552,"./request":559,"extend":249}],547:[function(require,module,exports){
  98615. 'use strict'
  98616. var caseless = require('caseless')
  98617. var uuid = require('uuid/v4')
  98618. var helpers = require('./helpers')
  98619. var md5 = helpers.md5
  98620. var toBase64 = helpers.toBase64
  98621. function Auth (request) {
  98622. // define all public properties here
  98623. this.request = request
  98624. this.hasAuth = false
  98625. this.sentAuth = false
  98626. this.bearerToken = null
  98627. this.user = null
  98628. this.pass = null
  98629. }
  98630. Auth.prototype.basic = function (user, pass, sendImmediately) {
  98631. var self = this
  98632. if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
  98633. self.request.emit('error', new Error('auth() received invalid user or password'))
  98634. }
  98635. self.user = user
  98636. self.pass = pass
  98637. self.hasAuth = true
  98638. var header = user + ':' + (pass || '')
  98639. if (sendImmediately || typeof sendImmediately === 'undefined') {
  98640. var authHeader = 'Basic ' + toBase64(header)
  98641. self.sentAuth = true
  98642. return authHeader
  98643. }
  98644. }
  98645. Auth.prototype.bearer = function (bearer, sendImmediately) {
  98646. var self = this
  98647. self.bearerToken = bearer
  98648. self.hasAuth = true
  98649. if (sendImmediately || typeof sendImmediately === 'undefined') {
  98650. if (typeof bearer === 'function') {
  98651. bearer = bearer()
  98652. }
  98653. var authHeader = 'Bearer ' + (bearer || '')
  98654. self.sentAuth = true
  98655. return authHeader
  98656. }
  98657. }
  98658. Auth.prototype.digest = function (method, path, authHeader) {
  98659. // TODO: More complete implementation of RFC 2617.
  98660. // - handle challenge.domain
  98661. // - support qop="auth-int" only
  98662. // - handle Authentication-Info (not necessarily?)
  98663. // - check challenge.stale (not necessarily?)
  98664. // - increase nc (not necessarily?)
  98665. // For reference:
  98666. // http://tools.ietf.org/html/rfc2617#section-3
  98667. // https://github.com/bagder/curl/blob/master/lib/http_digest.c
  98668. var self = this
  98669. var challenge = {}
  98670. var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
  98671. while (true) {
  98672. var match = re.exec(authHeader)
  98673. if (!match) {
  98674. break
  98675. }
  98676. challenge[match[1]] = match[2] || match[3]
  98677. }
  98678. /**
  98679. * RFC 2617: handle both MD5 and MD5-sess algorithms.
  98680. *
  98681. * If the algorithm directive's value is "MD5" or unspecified, then HA1 is
  98682. * HA1=MD5(username:realm:password)
  98683. * If the algorithm directive's value is "MD5-sess", then HA1 is
  98684. * HA1=MD5(MD5(username:realm:password):nonce:cnonce)
  98685. */
  98686. var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
  98687. var ha1 = md5(user + ':' + realm + ':' + pass)
  98688. if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
  98689. return md5(ha1 + ':' + nonce + ':' + cnonce)
  98690. } else {
  98691. return ha1
  98692. }
  98693. }
  98694. var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
  98695. var nc = qop && '00000001'
  98696. var cnonce = qop && uuid().replace(/-/g, '')
  98697. var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce)
  98698. var ha2 = md5(method + ':' + path)
  98699. var digestResponse = qop
  98700. ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
  98701. : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
  98702. var authValues = {
  98703. username: self.user,
  98704. realm: challenge.realm,
  98705. nonce: challenge.nonce,
  98706. uri: path,
  98707. qop: qop,
  98708. response: digestResponse,
  98709. nc: nc,
  98710. cnonce: cnonce,
  98711. algorithm: challenge.algorithm,
  98712. opaque: challenge.opaque
  98713. }
  98714. authHeader = []
  98715. for (var k in authValues) {
  98716. if (authValues[k]) {
  98717. if (k === 'qop' || k === 'nc' || k === 'algorithm') {
  98718. authHeader.push(k + '=' + authValues[k])
  98719. } else {
  98720. authHeader.push(k + '="' + authValues[k] + '"')
  98721. }
  98722. }
  98723. }
  98724. authHeader = 'Digest ' + authHeader.join(', ')
  98725. self.sentAuth = true
  98726. return authHeader
  98727. }
  98728. Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
  98729. var self = this
  98730. var request = self.request
  98731. var authHeader
  98732. if (bearer === undefined && user === undefined) {
  98733. self.request.emit('error', new Error('no auth mechanism defined'))
  98734. } else if (bearer !== undefined) {
  98735. authHeader = self.bearer(bearer, sendImmediately)
  98736. } else {
  98737. authHeader = self.basic(user, pass, sendImmediately)
  98738. }
  98739. if (authHeader) {
  98740. request.setHeader('authorization', authHeader)
  98741. }
  98742. }
  98743. Auth.prototype.onResponse = function (response) {
  98744. var self = this
  98745. var request = self.request
  98746. if (!self.hasAuth || self.sentAuth) { return null }
  98747. var c = caseless(response.headers)
  98748. var authHeader = c.get('www-authenticate')
  98749. var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
  98750. request.debug('reauth', authVerb)
  98751. switch (authVerb) {
  98752. case 'basic':
  98753. return self.basic(self.user, self.pass, true)
  98754. case 'bearer':
  98755. return self.bearer(self.bearerToken, true)
  98756. case 'digest':
  98757. return self.digest(request.method, request.path, authHeader)
  98758. }
  98759. }
  98760. exports.Auth = Auth
  98761. },{"./helpers":552,"caseless":197,"uuid/v4":663}],548:[function(require,module,exports){
  98762. 'use strict'
  98763. var tough = require('tough-cookie')
  98764. var Cookie = tough.Cookie
  98765. var CookieJar = tough.CookieJar
  98766. exports.parse = function (str) {
  98767. if (str && str.uri) {
  98768. str = str.uri
  98769. }
  98770. if (typeof str !== 'string') {
  98771. throw new Error('The cookie function only accepts STRING as param')
  98772. }
  98773. return Cookie.parse(str, {loose: true})
  98774. }
  98775. // Adapt the sometimes-Async api of tough.CookieJar to our requirements
  98776. function RequestJar (store) {
  98777. var self = this
  98778. self._jar = new CookieJar(store, {looseMode: true})
  98779. }
  98780. RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
  98781. var self = this
  98782. return self._jar.setCookieSync(cookieOrStr, uri, options || {})
  98783. }
  98784. RequestJar.prototype.getCookieString = function (uri) {
  98785. var self = this
  98786. return self._jar.getCookieStringSync(uri)
  98787. }
  98788. RequestJar.prototype.getCookies = function (uri) {
  98789. var self = this
  98790. return self._jar.getCookiesSync(uri)
  98791. }
  98792. exports.jar = function (store) {
  98793. return new RequestJar(store)
  98794. }
  98795. },{"tough-cookie":640}],549:[function(require,module,exports){
  98796. (function (process){(function (){
  98797. 'use strict'
  98798. function formatHostname (hostname) {
  98799. // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
  98800. return hostname.replace(/^\.*/, '.').toLowerCase()
  98801. }
  98802. function parseNoProxyZone (zone) {
  98803. zone = zone.trim().toLowerCase()
  98804. var zoneParts = zone.split(':', 2)
  98805. var zoneHost = formatHostname(zoneParts[0])
  98806. var zonePort = zoneParts[1]
  98807. var hasPort = zone.indexOf(':') > -1
  98808. return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
  98809. }
  98810. function uriInNoProxy (uri, noProxy) {
  98811. var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
  98812. var hostname = formatHostname(uri.hostname)
  98813. var noProxyList = noProxy.split(',')
  98814. // iterate through the noProxyList until it finds a match.
  98815. return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
  98816. var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
  98817. var hostnameMatched = (
  98818. isMatchedAt > -1 &&
  98819. (isMatchedAt === hostname.length - noProxyZone.hostname.length)
  98820. )
  98821. if (noProxyZone.hasPort) {
  98822. return (port === noProxyZone.port) && hostnameMatched
  98823. }
  98824. return hostnameMatched
  98825. })
  98826. }
  98827. function getProxyFromURI (uri) {
  98828. // Decide the proper request proxy to use based on the request URI object and the
  98829. // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
  98830. // respect NO_PROXY environment variables (see: https://lynx.invisible-island.net/lynx2.8.7/breakout/lynx_help/keystrokes/environments.html)
  98831. var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
  98832. // if the noProxy is a wildcard then return null
  98833. if (noProxy === '*') {
  98834. return null
  98835. }
  98836. // if the noProxy is not empty and the uri is found return null
  98837. if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
  98838. return null
  98839. }
  98840. // Check for HTTP or HTTPS Proxy in environment Else default to null
  98841. if (uri.protocol === 'http:') {
  98842. return process.env.HTTP_PROXY ||
  98843. process.env.http_proxy || null
  98844. }
  98845. if (uri.protocol === 'https:') {
  98846. return process.env.HTTPS_PROXY ||
  98847. process.env.https_proxy ||
  98848. process.env.HTTP_PROXY ||
  98849. process.env.http_proxy || null
  98850. }
  98851. // if none of that works, return null
  98852. // (What uri protocol are you using then?)
  98853. return null
  98854. }
  98855. module.exports = getProxyFromURI
  98856. }).call(this)}).call(this,require('_process'))
  98857. },{"_process":525}],550:[function(require,module,exports){
  98858. 'use strict'
  98859. var fs = require('fs')
  98860. var qs = require('querystring')
  98861. var validate = require('har-validator')
  98862. var extend = require('extend')
  98863. function Har (request) {
  98864. this.request = request
  98865. }
  98866. Har.prototype.reducer = function (obj, pair) {
  98867. // new property ?
  98868. if (obj[pair.name] === undefined) {
  98869. obj[pair.name] = pair.value
  98870. return obj
  98871. }
  98872. // existing? convert to array
  98873. var arr = [
  98874. obj[pair.name],
  98875. pair.value
  98876. ]
  98877. obj[pair.name] = arr
  98878. return obj
  98879. }
  98880. Har.prototype.prep = function (data) {
  98881. // construct utility properties
  98882. data.queryObj = {}
  98883. data.headersObj = {}
  98884. data.postData.jsonObj = false
  98885. data.postData.paramsObj = false
  98886. // construct query objects
  98887. if (data.queryString && data.queryString.length) {
  98888. data.queryObj = data.queryString.reduce(this.reducer, {})
  98889. }
  98890. // construct headers objects
  98891. if (data.headers && data.headers.length) {
  98892. // loweCase header keys
  98893. data.headersObj = data.headers.reduceRight(function (headers, header) {
  98894. headers[header.name] = header.value
  98895. return headers
  98896. }, {})
  98897. }
  98898. // construct Cookie header
  98899. if (data.cookies && data.cookies.length) {
  98900. var cookies = data.cookies.map(function (cookie) {
  98901. return cookie.name + '=' + cookie.value
  98902. })
  98903. if (cookies.length) {
  98904. data.headersObj.cookie = cookies.join('; ')
  98905. }
  98906. }
  98907. // prep body
  98908. function some (arr) {
  98909. return arr.some(function (type) {
  98910. return data.postData.mimeType.indexOf(type) === 0
  98911. })
  98912. }
  98913. if (some([
  98914. 'multipart/mixed',
  98915. 'multipart/related',
  98916. 'multipart/form-data',
  98917. 'multipart/alternative'])) {
  98918. // reset values
  98919. data.postData.mimeType = 'multipart/form-data'
  98920. } else if (some([
  98921. 'application/x-www-form-urlencoded'])) {
  98922. if (!data.postData.params) {
  98923. data.postData.text = ''
  98924. } else {
  98925. data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
  98926. // always overwrite
  98927. data.postData.text = qs.stringify(data.postData.paramsObj)
  98928. }
  98929. } else if (some([
  98930. 'text/json',
  98931. 'text/x-json',
  98932. 'application/json',
  98933. 'application/x-json'])) {
  98934. data.postData.mimeType = 'application/json'
  98935. if (data.postData.text) {
  98936. try {
  98937. data.postData.jsonObj = JSON.parse(data.postData.text)
  98938. } catch (e) {
  98939. this.request.debug(e)
  98940. // force back to text/plain
  98941. data.postData.mimeType = 'text/plain'
  98942. }
  98943. }
  98944. }
  98945. return data
  98946. }
  98947. Har.prototype.options = function (options) {
  98948. // skip if no har property defined
  98949. if (!options.har) {
  98950. return options
  98951. }
  98952. var har = {}
  98953. extend(har, options.har)
  98954. // only process the first entry
  98955. if (har.log && har.log.entries) {
  98956. har = har.log.entries[0]
  98957. }
  98958. // add optional properties to make validation successful
  98959. har.url = har.url || options.url || options.uri || options.baseUrl || '/'
  98960. har.httpVersion = har.httpVersion || 'HTTP/1.1'
  98961. har.queryString = har.queryString || []
  98962. har.headers = har.headers || []
  98963. har.cookies = har.cookies || []
  98964. har.postData = har.postData || {}
  98965. har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
  98966. har.bodySize = 0
  98967. har.headersSize = 0
  98968. har.postData.size = 0
  98969. if (!validate.request(har)) {
  98970. return options
  98971. }
  98972. // clean up and get some utility properties
  98973. var req = this.prep(har)
  98974. // construct new options
  98975. if (req.url) {
  98976. options.url = req.url
  98977. }
  98978. if (req.method) {
  98979. options.method = req.method
  98980. }
  98981. if (Object.keys(req.queryObj).length) {
  98982. options.qs = req.queryObj
  98983. }
  98984. if (Object.keys(req.headersObj).length) {
  98985. options.headers = req.headersObj
  98986. }
  98987. function test (type) {
  98988. return req.postData.mimeType.indexOf(type) === 0
  98989. }
  98990. if (test('application/x-www-form-urlencoded')) {
  98991. options.form = req.postData.paramsObj
  98992. } else if (test('application/json')) {
  98993. if (req.postData.jsonObj) {
  98994. options.body = req.postData.jsonObj
  98995. options.json = true
  98996. }
  98997. } else if (test('multipart/form-data')) {
  98998. options.formData = {}
  98999. req.postData.params.forEach(function (param) {
  99000. var attachment = {}
  99001. if (!param.fileName && !param.contentType) {
  99002. options.formData[param.name] = param.value
  99003. return
  99004. }
  99005. // attempt to read from disk!
  99006. if (param.fileName && !param.value) {
  99007. attachment.value = fs.createReadStream(param.fileName)
  99008. } else if (param.value) {
  99009. attachment.value = param.value
  99010. }
  99011. if (param.fileName) {
  99012. attachment.options = {
  99013. filename: param.fileName,
  99014. contentType: param.contentType ? param.contentType : null
  99015. }
  99016. }
  99017. options.formData[param.name] = attachment
  99018. })
  99019. } else {
  99020. if (req.postData.text) {
  99021. options.body = req.postData.text
  99022. }
  99023. }
  99024. return options
  99025. }
  99026. exports.Har = Har
  99027. },{"extend":249,"fs":190,"har-validator":279,"querystring":543}],551:[function(require,module,exports){
  99028. 'use strict'
  99029. var crypto = require('crypto')
  99030. function randomString (size) {
  99031. var bits = (size + 1) * 6
  99032. var buffer = crypto.randomBytes(Math.ceil(bits / 8))
  99033. var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
  99034. return string.slice(0, size)
  99035. }
  99036. function calculatePayloadHash (payload, algorithm, contentType) {
  99037. var hash = crypto.createHash(algorithm)
  99038. hash.update('hawk.1.payload\n')
  99039. hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n')
  99040. hash.update(payload || '')
  99041. hash.update('\n')
  99042. return hash.digest('base64')
  99043. }
  99044. exports.calculateMac = function (credentials, opts) {
  99045. var normalized = 'hawk.1.header\n' +
  99046. opts.ts + '\n' +
  99047. opts.nonce + '\n' +
  99048. (opts.method || '').toUpperCase() + '\n' +
  99049. opts.resource + '\n' +
  99050. opts.host.toLowerCase() + '\n' +
  99051. opts.port + '\n' +
  99052. (opts.hash || '') + '\n'
  99053. if (opts.ext) {
  99054. normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n')
  99055. }
  99056. normalized = normalized + '\n'
  99057. if (opts.app) {
  99058. normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n'
  99059. }
  99060. var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized)
  99061. var digest = hmac.digest('base64')
  99062. return digest
  99063. }
  99064. exports.header = function (uri, method, opts) {
  99065. var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000)
  99066. var credentials = opts.credentials
  99067. if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
  99068. return ''
  99069. }
  99070. if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) {
  99071. return ''
  99072. }
  99073. var artifacts = {
  99074. ts: timestamp,
  99075. nonce: opts.nonce || randomString(6),
  99076. method: method,
  99077. resource: uri.pathname + (uri.search || ''),
  99078. host: uri.hostname,
  99079. port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
  99080. hash: opts.hash,
  99081. ext: opts.ext,
  99082. app: opts.app,
  99083. dlg: opts.dlg
  99084. }
  99085. if (!artifacts.hash && (opts.payload || opts.payload === '')) {
  99086. artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType)
  99087. }
  99088. var mac = exports.calculateMac(credentials, artifacts)
  99089. var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''
  99090. var header = 'Hawk id="' + credentials.id +
  99091. '", ts="' + artifacts.ts +
  99092. '", nonce="' + artifacts.nonce +
  99093. (artifacts.hash ? '", hash="' + artifacts.hash : '') +
  99094. (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') +
  99095. '", mac="' + mac + '"'
  99096. if (artifacts.app) {
  99097. header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'
  99098. }
  99099. return header
  99100. }
  99101. },{"crypto":208}],552:[function(require,module,exports){
  99102. (function (process,setImmediate){(function (){
  99103. 'use strict'
  99104. var jsonSafeStringify = require('json-stringify-safe')
  99105. var crypto = require('crypto')
  99106. var Buffer = require('safe-buffer').Buffer
  99107. var defer = typeof setImmediate === 'undefined'
  99108. ? process.nextTick
  99109. : setImmediate
  99110. function paramsHaveRequestBody (params) {
  99111. return (
  99112. params.body ||
  99113. params.requestBodyStream ||
  99114. (params.json && typeof params.json !== 'boolean') ||
  99115. params.multipart
  99116. )
  99117. }
  99118. function safeStringify (obj, replacer) {
  99119. var ret
  99120. try {
  99121. ret = JSON.stringify(obj, replacer)
  99122. } catch (e) {
  99123. ret = jsonSafeStringify(obj, replacer)
  99124. }
  99125. return ret
  99126. }
  99127. function md5 (str) {
  99128. return crypto.createHash('md5').update(str).digest('hex')
  99129. }
  99130. function isReadStream (rs) {
  99131. return rs.readable && rs.path && rs.mode
  99132. }
  99133. function toBase64 (str) {
  99134. return Buffer.from(str || '', 'utf8').toString('base64')
  99135. }
  99136. function copy (obj) {
  99137. var o = {}
  99138. Object.keys(obj).forEach(function (i) {
  99139. o[i] = obj[i]
  99140. })
  99141. return o
  99142. }
  99143. function version () {
  99144. var numbers = process.version.replace('v', '').split('.')
  99145. return {
  99146. major: parseInt(numbers[0], 10),
  99147. minor: parseInt(numbers[1], 10),
  99148. patch: parseInt(numbers[2], 10)
  99149. }
  99150. }
  99151. exports.paramsHaveRequestBody = paramsHaveRequestBody
  99152. exports.safeStringify = safeStringify
  99153. exports.md5 = md5
  99154. exports.isReadStream = isReadStream
  99155. exports.toBase64 = toBase64
  99156. exports.copy = copy
  99157. exports.version = version
  99158. exports.defer = defer
  99159. }).call(this)}).call(this,require('_process'),require("timers").setImmediate)
  99160. },{"_process":525,"crypto":208,"json-stringify-safe":331,"safe-buffer":561,"timers":639}],553:[function(require,module,exports){
  99161. 'use strict'
  99162. var uuid = require('uuid/v4')
  99163. var CombinedStream = require('combined-stream')
  99164. var isstream = require('isstream')
  99165. var Buffer = require('safe-buffer').Buffer
  99166. function Multipart (request) {
  99167. this.request = request
  99168. this.boundary = uuid()
  99169. this.chunked = false
  99170. this.body = null
  99171. }
  99172. Multipart.prototype.isChunked = function (options) {
  99173. var self = this
  99174. var chunked = false
  99175. var parts = options.data || options
  99176. if (!parts.forEach) {
  99177. self.request.emit('error', new Error('Argument error, options.multipart.'))
  99178. }
  99179. if (options.chunked !== undefined) {
  99180. chunked = options.chunked
  99181. }
  99182. if (self.request.getHeader('transfer-encoding') === 'chunked') {
  99183. chunked = true
  99184. }
  99185. if (!chunked) {
  99186. parts.forEach(function (part) {
  99187. if (typeof part.body === 'undefined') {
  99188. self.request.emit('error', new Error('Body attribute missing in multipart.'))
  99189. }
  99190. if (isstream(part.body)) {
  99191. chunked = true
  99192. }
  99193. })
  99194. }
  99195. return chunked
  99196. }
  99197. Multipart.prototype.setHeaders = function (chunked) {
  99198. var self = this
  99199. if (chunked && !self.request.hasHeader('transfer-encoding')) {
  99200. self.request.setHeader('transfer-encoding', 'chunked')
  99201. }
  99202. var header = self.request.getHeader('content-type')
  99203. if (!header || header.indexOf('multipart') === -1) {
  99204. self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
  99205. } else {
  99206. if (header.indexOf('boundary') !== -1) {
  99207. self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
  99208. } else {
  99209. self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
  99210. }
  99211. }
  99212. }
  99213. Multipart.prototype.build = function (parts, chunked) {
  99214. var self = this
  99215. var body = chunked ? new CombinedStream() : []
  99216. function add (part) {
  99217. if (typeof part === 'number') {
  99218. part = part.toString()
  99219. }
  99220. return chunked ? body.append(part) : body.push(Buffer.from(part))
  99221. }
  99222. if (self.request.preambleCRLF) {
  99223. add('\r\n')
  99224. }
  99225. parts.forEach(function (part) {
  99226. var preamble = '--' + self.boundary + '\r\n'
  99227. Object.keys(part).forEach(function (key) {
  99228. if (key === 'body') { return }
  99229. preamble += key + ': ' + part[key] + '\r\n'
  99230. })
  99231. preamble += '\r\n'
  99232. add(preamble)
  99233. add(part.body)
  99234. add('\r\n')
  99235. })
  99236. add('--' + self.boundary + '--')
  99237. if (self.request.postambleCRLF) {
  99238. add('\r\n')
  99239. }
  99240. return body
  99241. }
  99242. Multipart.prototype.onRequest = function (options) {
  99243. var self = this
  99244. var chunked = self.isChunked(options)
  99245. var parts = options.data || options
  99246. self.setHeaders(chunked)
  99247. self.chunked = chunked
  99248. self.body = self.build(parts, chunked)
  99249. }
  99250. exports.Multipart = Multipart
  99251. },{"combined-stream":199,"isstream":326,"safe-buffer":561,"uuid/v4":663}],554:[function(require,module,exports){
  99252. 'use strict'
  99253. var url = require('url')
  99254. var qs = require('qs')
  99255. var caseless = require('caseless')
  99256. var uuid = require('uuid/v4')
  99257. var oauth = require('oauth-sign')
  99258. var crypto = require('crypto')
  99259. var Buffer = require('safe-buffer').Buffer
  99260. function OAuth (request) {
  99261. this.request = request
  99262. this.params = null
  99263. }
  99264. OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
  99265. var oa = {}
  99266. for (var i in _oauth) {
  99267. oa['oauth_' + i] = _oauth[i]
  99268. }
  99269. if (!oa.oauth_version) {
  99270. oa.oauth_version = '1.0'
  99271. }
  99272. if (!oa.oauth_timestamp) {
  99273. oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString()
  99274. }
  99275. if (!oa.oauth_nonce) {
  99276. oa.oauth_nonce = uuid().replace(/-/g, '')
  99277. }
  99278. if (!oa.oauth_signature_method) {
  99279. oa.oauth_signature_method = 'HMAC-SHA1'
  99280. }
  99281. var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase
  99282. delete oa.oauth_consumer_secret
  99283. delete oa.oauth_private_key
  99284. var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase
  99285. delete oa.oauth_token_secret
  99286. var realm = oa.oauth_realm
  99287. delete oa.oauth_realm
  99288. delete oa.oauth_transport_method
  99289. var baseurl = uri.protocol + '//' + uri.host + uri.pathname
  99290. var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
  99291. oa.oauth_signature = oauth.sign(
  99292. oa.oauth_signature_method,
  99293. method,
  99294. baseurl,
  99295. params,
  99296. consumer_secret_or_private_key, // eslint-disable-line camelcase
  99297. token_secret // eslint-disable-line camelcase
  99298. )
  99299. if (realm) {
  99300. oa.realm = realm
  99301. }
  99302. return oa
  99303. }
  99304. OAuth.prototype.buildBodyHash = function (_oauth, body) {
  99305. if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
  99306. this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
  99307. ' signature_method not supported with body_hash signing.'))
  99308. }
  99309. var shasum = crypto.createHash('sha1')
  99310. shasum.update(body || '')
  99311. var sha1 = shasum.digest('hex')
  99312. return Buffer.from(sha1, 'hex').toString('base64')
  99313. }
  99314. OAuth.prototype.concatParams = function (oa, sep, wrap) {
  99315. wrap = wrap || ''
  99316. var params = Object.keys(oa).filter(function (i) {
  99317. return i !== 'realm' && i !== 'oauth_signature'
  99318. }).sort()
  99319. if (oa.realm) {
  99320. params.splice(0, 0, 'realm')
  99321. }
  99322. params.push('oauth_signature')
  99323. return params.map(function (i) {
  99324. return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
  99325. }).join(sep)
  99326. }
  99327. OAuth.prototype.onRequest = function (_oauth) {
  99328. var self = this
  99329. self.params = _oauth
  99330. var uri = self.request.uri || {}
  99331. var method = self.request.method || ''
  99332. var headers = caseless(self.request.headers)
  99333. var body = self.request.body || ''
  99334. var qsLib = self.request.qsLib || qs
  99335. var form
  99336. var query
  99337. var contentType = headers.get('content-type') || ''
  99338. var formContentType = 'application/x-www-form-urlencoded'
  99339. var transport = _oauth.transport_method || 'header'
  99340. if (contentType.slice(0, formContentType.length) === formContentType) {
  99341. contentType = formContentType
  99342. form = body
  99343. }
  99344. if (uri.query) {
  99345. query = uri.query
  99346. }
  99347. if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
  99348. self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
  99349. 'and content-type ' + formContentType))
  99350. }
  99351. if (!form && typeof _oauth.body_hash === 'boolean') {
  99352. _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString())
  99353. }
  99354. var oa = self.buildParams(_oauth, uri, method, query, form, qsLib)
  99355. switch (transport) {
  99356. case 'header':
  99357. self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'))
  99358. break
  99359. case 'query':
  99360. var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&')
  99361. self.request.uri = url.parse(href)
  99362. self.request.path = self.request.uri.path
  99363. break
  99364. case 'body':
  99365. self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&')
  99366. break
  99367. default:
  99368. self.request.emit('error', new Error('oauth: transport_method invalid'))
  99369. }
  99370. }
  99371. exports.OAuth = OAuth
  99372. },{"caseless":197,"crypto":208,"oauth-sign":498,"qs":537,"safe-buffer":561,"url":653,"uuid/v4":663}],555:[function(require,module,exports){
  99373. 'use strict'
  99374. var qs = require('qs')
  99375. var querystring = require('querystring')
  99376. function Querystring (request) {
  99377. this.request = request
  99378. this.lib = null
  99379. this.useQuerystring = null
  99380. this.parseOptions = null
  99381. this.stringifyOptions = null
  99382. }
  99383. Querystring.prototype.init = function (options) {
  99384. if (this.lib) { return }
  99385. this.useQuerystring = options.useQuerystring
  99386. this.lib = (this.useQuerystring ? querystring : qs)
  99387. this.parseOptions = options.qsParseOptions || {}
  99388. this.stringifyOptions = options.qsStringifyOptions || {}
  99389. }
  99390. Querystring.prototype.stringify = function (obj) {
  99391. return (this.useQuerystring)
  99392. ? this.rfc3986(this.lib.stringify(obj,
  99393. this.stringifyOptions.sep || null,
  99394. this.stringifyOptions.eq || null,
  99395. this.stringifyOptions))
  99396. : this.lib.stringify(obj, this.stringifyOptions)
  99397. }
  99398. Querystring.prototype.parse = function (str) {
  99399. return (this.useQuerystring)
  99400. ? this.lib.parse(str,
  99401. this.parseOptions.sep || null,
  99402. this.parseOptions.eq || null,
  99403. this.parseOptions)
  99404. : this.lib.parse(str, this.parseOptions)
  99405. }
  99406. Querystring.prototype.rfc3986 = function (str) {
  99407. return str.replace(/[!'()*]/g, function (c) {
  99408. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  99409. })
  99410. }
  99411. Querystring.prototype.unescape = querystring.unescape
  99412. exports.Querystring = Querystring
  99413. },{"qs":537,"querystring":543}],556:[function(require,module,exports){
  99414. 'use strict'
  99415. var url = require('url')
  99416. var isUrl = /^https?:/
  99417. function Redirect (request) {
  99418. this.request = request
  99419. this.followRedirect = true
  99420. this.followRedirects = true
  99421. this.followAllRedirects = false
  99422. this.followOriginalHttpMethod = false
  99423. this.allowRedirect = function () { return true }
  99424. this.maxRedirects = 10
  99425. this.redirects = []
  99426. this.redirectsFollowed = 0
  99427. this.removeRefererHeader = false
  99428. }
  99429. Redirect.prototype.onRequest = function (options) {
  99430. var self = this
  99431. if (options.maxRedirects !== undefined) {
  99432. self.maxRedirects = options.maxRedirects
  99433. }
  99434. if (typeof options.followRedirect === 'function') {
  99435. self.allowRedirect = options.followRedirect
  99436. }
  99437. if (options.followRedirect !== undefined) {
  99438. self.followRedirects = !!options.followRedirect
  99439. }
  99440. if (options.followAllRedirects !== undefined) {
  99441. self.followAllRedirects = options.followAllRedirects
  99442. }
  99443. if (self.followRedirects || self.followAllRedirects) {
  99444. self.redirects = self.redirects || []
  99445. }
  99446. if (options.removeRefererHeader !== undefined) {
  99447. self.removeRefererHeader = options.removeRefererHeader
  99448. }
  99449. if (options.followOriginalHttpMethod !== undefined) {
  99450. self.followOriginalHttpMethod = options.followOriginalHttpMethod
  99451. }
  99452. }
  99453. Redirect.prototype.redirectTo = function (response) {
  99454. var self = this
  99455. var request = self.request
  99456. var redirectTo = null
  99457. if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
  99458. var location = response.caseless.get('location')
  99459. request.debug('redirect', location)
  99460. if (self.followAllRedirects) {
  99461. redirectTo = location
  99462. } else if (self.followRedirects) {
  99463. switch (request.method) {
  99464. case 'PATCH':
  99465. case 'PUT':
  99466. case 'POST':
  99467. case 'DELETE':
  99468. // Do not follow redirects
  99469. break
  99470. default:
  99471. redirectTo = location
  99472. break
  99473. }
  99474. }
  99475. } else if (response.statusCode === 401) {
  99476. var authHeader = request._auth.onResponse(response)
  99477. if (authHeader) {
  99478. request.setHeader('authorization', authHeader)
  99479. redirectTo = request.uri
  99480. }
  99481. }
  99482. return redirectTo
  99483. }
  99484. Redirect.prototype.onResponse = function (response) {
  99485. var self = this
  99486. var request = self.request
  99487. var redirectTo = self.redirectTo(response)
  99488. if (!redirectTo || !self.allowRedirect.call(request, response)) {
  99489. return false
  99490. }
  99491. request.debug('redirect to', redirectTo)
  99492. // ignore any potential response body. it cannot possibly be useful
  99493. // to us at this point.
  99494. // response.resume should be defined, but check anyway before calling. Workaround for browserify.
  99495. if (response.resume) {
  99496. response.resume()
  99497. }
  99498. if (self.redirectsFollowed >= self.maxRedirects) {
  99499. request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
  99500. return false
  99501. }
  99502. self.redirectsFollowed += 1
  99503. if (!isUrl.test(redirectTo)) {
  99504. redirectTo = url.resolve(request.uri.href, redirectTo)
  99505. }
  99506. var uriPrev = request.uri
  99507. request.uri = url.parse(redirectTo)
  99508. // handle the case where we change protocol from https to http or vice versa
  99509. if (request.uri.protocol !== uriPrev.protocol) {
  99510. delete request.agent
  99511. }
  99512. self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
  99513. if (self.followAllRedirects && request.method !== 'HEAD' &&
  99514. response.statusCode !== 401 && response.statusCode !== 307) {
  99515. request.method = self.followOriginalHttpMethod ? request.method : 'GET'
  99516. }
  99517. // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
  99518. delete request.src
  99519. delete request.req
  99520. delete request._started
  99521. if (response.statusCode !== 401 && response.statusCode !== 307) {
  99522. // Remove parameters from the previous response, unless this is the second request
  99523. // for a server that requires digest authentication.
  99524. delete request.body
  99525. delete request._form
  99526. if (request.headers) {
  99527. request.removeHeader('host')
  99528. request.removeHeader('content-type')
  99529. request.removeHeader('content-length')
  99530. if (request.uri.hostname !== request.originalHost.split(':')[0]) {
  99531. // Remove authorization if changing hostnames (but not if just
  99532. // changing ports or protocols). This matches the behavior of curl:
  99533. // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
  99534. request.removeHeader('authorization')
  99535. }
  99536. }
  99537. }
  99538. if (!self.removeRefererHeader) {
  99539. request.setHeader('referer', uriPrev.href)
  99540. }
  99541. request.emit('redirect')
  99542. request.init()
  99543. return true
  99544. }
  99545. exports.Redirect = Redirect
  99546. },{"url":653}],557:[function(require,module,exports){
  99547. 'use strict'
  99548. var url = require('url')
  99549. var tunnel = require('tunnel-agent')
  99550. var defaultProxyHeaderWhiteList = [
  99551. 'accept',
  99552. 'accept-charset',
  99553. 'accept-encoding',
  99554. 'accept-language',
  99555. 'accept-ranges',
  99556. 'cache-control',
  99557. 'content-encoding',
  99558. 'content-language',
  99559. 'content-location',
  99560. 'content-md5',
  99561. 'content-range',
  99562. 'content-type',
  99563. 'connection',
  99564. 'date',
  99565. 'expect',
  99566. 'max-forwards',
  99567. 'pragma',
  99568. 'referer',
  99569. 'te',
  99570. 'user-agent',
  99571. 'via'
  99572. ]
  99573. var defaultProxyHeaderExclusiveList = [
  99574. 'proxy-authorization'
  99575. ]
  99576. function constructProxyHost (uriObject) {
  99577. var port = uriObject.port
  99578. var protocol = uriObject.protocol
  99579. var proxyHost = uriObject.hostname + ':'
  99580. if (port) {
  99581. proxyHost += port
  99582. } else if (protocol === 'https:') {
  99583. proxyHost += '443'
  99584. } else {
  99585. proxyHost += '80'
  99586. }
  99587. return proxyHost
  99588. }
  99589. function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
  99590. var whiteList = proxyHeaderWhiteList
  99591. .reduce(function (set, header) {
  99592. set[header.toLowerCase()] = true
  99593. return set
  99594. }, {})
  99595. return Object.keys(headers)
  99596. .filter(function (header) {
  99597. return whiteList[header.toLowerCase()]
  99598. })
  99599. .reduce(function (set, header) {
  99600. set[header] = headers[header]
  99601. return set
  99602. }, {})
  99603. }
  99604. function constructTunnelOptions (request, proxyHeaders) {
  99605. var proxy = request.proxy
  99606. var tunnelOptions = {
  99607. proxy: {
  99608. host: proxy.hostname,
  99609. port: +proxy.port,
  99610. proxyAuth: proxy.auth,
  99611. headers: proxyHeaders
  99612. },
  99613. headers: request.headers,
  99614. ca: request.ca,
  99615. cert: request.cert,
  99616. key: request.key,
  99617. passphrase: request.passphrase,
  99618. pfx: request.pfx,
  99619. ciphers: request.ciphers,
  99620. rejectUnauthorized: request.rejectUnauthorized,
  99621. secureOptions: request.secureOptions,
  99622. secureProtocol: request.secureProtocol
  99623. }
  99624. return tunnelOptions
  99625. }
  99626. function constructTunnelFnName (uri, proxy) {
  99627. var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
  99628. var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
  99629. return [uriProtocol, proxyProtocol].join('Over')
  99630. }
  99631. function getTunnelFn (request) {
  99632. var uri = request.uri
  99633. var proxy = request.proxy
  99634. var tunnelFnName = constructTunnelFnName(uri, proxy)
  99635. return tunnel[tunnelFnName]
  99636. }
  99637. function Tunnel (request) {
  99638. this.request = request
  99639. this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
  99640. this.proxyHeaderExclusiveList = []
  99641. if (typeof request.tunnel !== 'undefined') {
  99642. this.tunnelOverride = request.tunnel
  99643. }
  99644. }
  99645. Tunnel.prototype.isEnabled = function () {
  99646. var self = this
  99647. var request = self.request
  99648. // Tunnel HTTPS by default. Allow the user to override this setting.
  99649. // If self.tunnelOverride is set (the user specified a value), use it.
  99650. if (typeof self.tunnelOverride !== 'undefined') {
  99651. return self.tunnelOverride
  99652. }
  99653. // If the destination is HTTPS, tunnel.
  99654. if (request.uri.protocol === 'https:') {
  99655. return true
  99656. }
  99657. // Otherwise, do not use tunnel.
  99658. return false
  99659. }
  99660. Tunnel.prototype.setup = function (options) {
  99661. var self = this
  99662. var request = self.request
  99663. options = options || {}
  99664. if (typeof request.proxy === 'string') {
  99665. request.proxy = url.parse(request.proxy)
  99666. }
  99667. if (!request.proxy || !request.tunnel) {
  99668. return false
  99669. }
  99670. // Setup Proxy Header Exclusive List and White List
  99671. if (options.proxyHeaderWhiteList) {
  99672. self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
  99673. }
  99674. if (options.proxyHeaderExclusiveList) {
  99675. self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
  99676. }
  99677. var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
  99678. var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
  99679. // Setup Proxy Headers and Proxy Headers Host
  99680. // Only send the Proxy White Listed Header names
  99681. var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
  99682. proxyHeaders.host = constructProxyHost(request.uri)
  99683. proxyHeaderExclusiveList.forEach(request.removeHeader, request)
  99684. // Set Agent from Tunnel Data
  99685. var tunnelFn = getTunnelFn(request)
  99686. var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
  99687. request.agent = tunnelFn(tunnelOptions)
  99688. return true
  99689. }
  99690. Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
  99691. Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
  99692. exports.Tunnel = Tunnel
  99693. },{"tunnel-agent":647,"url":653}],558:[function(require,module,exports){
  99694. arguments[4][255][0].apply(exports,arguments)
  99695. },{"dup":255}],559:[function(require,module,exports){
  99696. (function (process){(function (){
  99697. 'use strict'
  99698. var http = require('http')
  99699. var https = require('https')
  99700. var url = require('url')
  99701. var util = require('util')
  99702. var stream = require('stream')
  99703. var zlib = require('zlib')
  99704. var aws2 = require('aws-sign2')
  99705. var aws4 = require('aws4')
  99706. var httpSignature = require('http-signature')
  99707. var mime = require('mime-types')
  99708. var caseless = require('caseless')
  99709. var ForeverAgent = require('forever-agent')
  99710. var FormData = require('form-data')
  99711. var extend = require('extend')
  99712. var isstream = require('isstream')
  99713. var isTypedArray = require('is-typedarray').strict
  99714. var helpers = require('./lib/helpers')
  99715. var cookies = require('./lib/cookies')
  99716. var getProxyFromURI = require('./lib/getProxyFromURI')
  99717. var Querystring = require('./lib/querystring').Querystring
  99718. var Har = require('./lib/har').Har
  99719. var Auth = require('./lib/auth').Auth
  99720. var OAuth = require('./lib/oauth').OAuth
  99721. var hawk = require('./lib/hawk')
  99722. var Multipart = require('./lib/multipart').Multipart
  99723. var Redirect = require('./lib/redirect').Redirect
  99724. var Tunnel = require('./lib/tunnel').Tunnel
  99725. var now = require('performance-now')
  99726. var Buffer = require('safe-buffer').Buffer
  99727. var safeStringify = helpers.safeStringify
  99728. var isReadStream = helpers.isReadStream
  99729. var toBase64 = helpers.toBase64
  99730. var defer = helpers.defer
  99731. var copy = helpers.copy
  99732. var version = helpers.version
  99733. var globalCookieJar = cookies.jar()
  99734. var globalPool = {}
  99735. function filterForNonReserved (reserved, options) {
  99736. // Filter out properties that are not reserved.
  99737. // Reserved values are passed in at call site.
  99738. var object = {}
  99739. for (var i in options) {
  99740. var notReserved = (reserved.indexOf(i) === -1)
  99741. if (notReserved) {
  99742. object[i] = options[i]
  99743. }
  99744. }
  99745. return object
  99746. }
  99747. function filterOutReservedFunctions (reserved, options) {
  99748. // Filter out properties that are functions and are reserved.
  99749. // Reserved values are passed in at call site.
  99750. var object = {}
  99751. for (var i in options) {
  99752. var isReserved = !(reserved.indexOf(i) === -1)
  99753. var isFunction = (typeof options[i] === 'function')
  99754. if (!(isReserved && isFunction)) {
  99755. object[i] = options[i]
  99756. }
  99757. }
  99758. return object
  99759. }
  99760. // Return a simpler request object to allow serialization
  99761. function requestToJSON () {
  99762. var self = this
  99763. return {
  99764. uri: self.uri,
  99765. method: self.method,
  99766. headers: self.headers
  99767. }
  99768. }
  99769. // Return a simpler response object to allow serialization
  99770. function responseToJSON () {
  99771. var self = this
  99772. return {
  99773. statusCode: self.statusCode,
  99774. body: self.body,
  99775. headers: self.headers,
  99776. request: requestToJSON.call(self.request)
  99777. }
  99778. }
  99779. function Request (options) {
  99780. // if given the method property in options, set property explicitMethod to true
  99781. // extend the Request instance with any non-reserved properties
  99782. // remove any reserved functions from the options object
  99783. // set Request instance to be readable and writable
  99784. // call init
  99785. var self = this
  99786. // start with HAR, then override with additional options
  99787. if (options.har) {
  99788. self._har = new Har(self)
  99789. options = self._har.options(options)
  99790. }
  99791. stream.Stream.call(self)
  99792. var reserved = Object.keys(Request.prototype)
  99793. var nonReserved = filterForNonReserved(reserved, options)
  99794. extend(self, nonReserved)
  99795. options = filterOutReservedFunctions(reserved, options)
  99796. self.readable = true
  99797. self.writable = true
  99798. if (options.method) {
  99799. self.explicitMethod = true
  99800. }
  99801. self._qs = new Querystring(self)
  99802. self._auth = new Auth(self)
  99803. self._oauth = new OAuth(self)
  99804. self._multipart = new Multipart(self)
  99805. self._redirect = new Redirect(self)
  99806. self._tunnel = new Tunnel(self)
  99807. self.init(options)
  99808. }
  99809. util.inherits(Request, stream.Stream)
  99810. // Debugging
  99811. Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
  99812. function debug () {
  99813. if (Request.debug) {
  99814. console.error('REQUEST %s', util.format.apply(util, arguments))
  99815. }
  99816. }
  99817. Request.prototype.debug = debug
  99818. Request.prototype.init = function (options) {
  99819. // init() contains all the code to setup the request object.
  99820. // the actual outgoing request is not started until start() is called
  99821. // this function is called from both the constructor and on redirect.
  99822. var self = this
  99823. if (!options) {
  99824. options = {}
  99825. }
  99826. self.headers = self.headers ? copy(self.headers) : {}
  99827. // Delete headers with value undefined since they break
  99828. // ClientRequest.OutgoingMessage.setHeader in node 0.12
  99829. for (var headerName in self.headers) {
  99830. if (typeof self.headers[headerName] === 'undefined') {
  99831. delete self.headers[headerName]
  99832. }
  99833. }
  99834. caseless.httpify(self, self.headers)
  99835. if (!self.method) {
  99836. self.method = options.method || 'GET'
  99837. }
  99838. if (!self.localAddress) {
  99839. self.localAddress = options.localAddress
  99840. }
  99841. self._qs.init(options)
  99842. debug(options)
  99843. if (!self.pool && self.pool !== false) {
  99844. self.pool = globalPool
  99845. }
  99846. self.dests = self.dests || []
  99847. self.__isRequestRequest = true
  99848. // Protect against double callback
  99849. if (!self._callback && self.callback) {
  99850. self._callback = self.callback
  99851. self.callback = function () {
  99852. if (self._callbackCalled) {
  99853. return // Print a warning maybe?
  99854. }
  99855. self._callbackCalled = true
  99856. self._callback.apply(self, arguments)
  99857. }
  99858. self.on('error', self.callback.bind())
  99859. self.on('complete', self.callback.bind(self, null))
  99860. }
  99861. // People use this property instead all the time, so support it
  99862. if (!self.uri && self.url) {
  99863. self.uri = self.url
  99864. delete self.url
  99865. }
  99866. // If there's a baseUrl, then use it as the base URL (i.e. uri must be
  99867. // specified as a relative path and is appended to baseUrl).
  99868. if (self.baseUrl) {
  99869. if (typeof self.baseUrl !== 'string') {
  99870. return self.emit('error', new Error('options.baseUrl must be a string'))
  99871. }
  99872. if (typeof self.uri !== 'string') {
  99873. return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
  99874. }
  99875. if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
  99876. return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
  99877. }
  99878. // Handle all cases to make sure that there's only one slash between
  99879. // baseUrl and uri.
  99880. var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
  99881. var uriStartsWithSlash = self.uri.indexOf('/') === 0
  99882. if (baseUrlEndsWithSlash && uriStartsWithSlash) {
  99883. self.uri = self.baseUrl + self.uri.slice(1)
  99884. } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
  99885. self.uri = self.baseUrl + self.uri
  99886. } else if (self.uri === '') {
  99887. self.uri = self.baseUrl
  99888. } else {
  99889. self.uri = self.baseUrl + '/' + self.uri
  99890. }
  99891. delete self.baseUrl
  99892. }
  99893. // A URI is needed by this point, emit error if we haven't been able to get one
  99894. if (!self.uri) {
  99895. return self.emit('error', new Error('options.uri is a required argument'))
  99896. }
  99897. // If a string URI/URL was given, parse it into a URL object
  99898. if (typeof self.uri === 'string') {
  99899. self.uri = url.parse(self.uri)
  99900. }
  99901. // Some URL objects are not from a URL parsed string and need href added
  99902. if (!self.uri.href) {
  99903. self.uri.href = url.format(self.uri)
  99904. }
  99905. // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
  99906. if (self.uri.protocol === 'unix:') {
  99907. return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
  99908. }
  99909. // Support Unix Sockets
  99910. if (self.uri.host === 'unix') {
  99911. self.enableUnixSocket()
  99912. }
  99913. if (self.strictSSL === false) {
  99914. self.rejectUnauthorized = false
  99915. }
  99916. if (!self.uri.pathname) { self.uri.pathname = '/' }
  99917. if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
  99918. // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
  99919. // Detect and reject it as soon as possible
  99920. var faultyUri = url.format(self.uri)
  99921. var message = 'Invalid URI "' + faultyUri + '"'
  99922. if (Object.keys(options).length === 0) {
  99923. // No option ? This can be the sign of a redirect
  99924. // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
  99925. // they should be warned that it can be caused by a redirection (can save some hair)
  99926. message += '. This can be caused by a crappy redirection.'
  99927. }
  99928. // This error was fatal
  99929. self.abort()
  99930. return self.emit('error', new Error(message))
  99931. }
  99932. if (!self.hasOwnProperty('proxy')) {
  99933. self.proxy = getProxyFromURI(self.uri)
  99934. }
  99935. self.tunnel = self._tunnel.isEnabled()
  99936. if (self.proxy) {
  99937. self._tunnel.setup(options)
  99938. }
  99939. self._redirect.onRequest(options)
  99940. self.setHost = false
  99941. if (!self.hasHeader('host')) {
  99942. var hostHeaderName = self.originalHostHeaderName || 'host'
  99943. self.setHeader(hostHeaderName, self.uri.host)
  99944. // Drop :port suffix from Host header if known protocol.
  99945. if (self.uri.port) {
  99946. if ((self.uri.port === '80' && self.uri.protocol === 'http:') ||
  99947. (self.uri.port === '443' && self.uri.protocol === 'https:')) {
  99948. self.setHeader(hostHeaderName, self.uri.hostname)
  99949. }
  99950. }
  99951. self.setHost = true
  99952. }
  99953. self.jar(self._jar || options.jar)
  99954. if (!self.uri.port) {
  99955. if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 }
  99956. }
  99957. if (self.proxy && !self.tunnel) {
  99958. self.port = self.proxy.port
  99959. self.host = self.proxy.hostname
  99960. } else {
  99961. self.port = self.uri.port
  99962. self.host = self.uri.hostname
  99963. }
  99964. if (options.form) {
  99965. self.form(options.form)
  99966. }
  99967. if (options.formData) {
  99968. var formData = options.formData
  99969. var requestForm = self.form()
  99970. var appendFormValue = function (key, value) {
  99971. if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
  99972. requestForm.append(key, value.value, value.options)
  99973. } else {
  99974. requestForm.append(key, value)
  99975. }
  99976. }
  99977. for (var formKey in formData) {
  99978. if (formData.hasOwnProperty(formKey)) {
  99979. var formValue = formData[formKey]
  99980. if (formValue instanceof Array) {
  99981. for (var j = 0; j < formValue.length; j++) {
  99982. appendFormValue(formKey, formValue[j])
  99983. }
  99984. } else {
  99985. appendFormValue(formKey, formValue)
  99986. }
  99987. }
  99988. }
  99989. }
  99990. if (options.qs) {
  99991. self.qs(options.qs)
  99992. }
  99993. if (self.uri.path) {
  99994. self.path = self.uri.path
  99995. } else {
  99996. self.path = self.uri.pathname + (self.uri.search || '')
  99997. }
  99998. if (self.path.length === 0) {
  99999. self.path = '/'
  100000. }
  100001. // Auth must happen last in case signing is dependent on other headers
  100002. if (options.aws) {
  100003. self.aws(options.aws)
  100004. }
  100005. if (options.hawk) {
  100006. self.hawk(options.hawk)
  100007. }
  100008. if (options.httpSignature) {
  100009. self.httpSignature(options.httpSignature)
  100010. }
  100011. if (options.auth) {
  100012. if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
  100013. options.auth.user = options.auth.username
  100014. }
  100015. if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
  100016. options.auth.pass = options.auth.password
  100017. }
  100018. self.auth(
  100019. options.auth.user,
  100020. options.auth.pass,
  100021. options.auth.sendImmediately,
  100022. options.auth.bearer
  100023. )
  100024. }
  100025. if (self.gzip && !self.hasHeader('accept-encoding')) {
  100026. self.setHeader('accept-encoding', 'gzip, deflate')
  100027. }
  100028. if (self.uri.auth && !self.hasHeader('authorization')) {
  100029. var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) })
  100030. self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
  100031. }
  100032. if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
  100033. var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) })
  100034. var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
  100035. self.setHeader('proxy-authorization', authHeader)
  100036. }
  100037. if (self.proxy && !self.tunnel) {
  100038. self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
  100039. }
  100040. if (options.json) {
  100041. self.json(options.json)
  100042. }
  100043. if (options.multipart) {
  100044. self.multipart(options.multipart)
  100045. }
  100046. if (options.time) {
  100047. self.timing = true
  100048. // NOTE: elapsedTime is deprecated in favor of .timings
  100049. self.elapsedTime = self.elapsedTime || 0
  100050. }
  100051. function setContentLength () {
  100052. if (isTypedArray(self.body)) {
  100053. self.body = Buffer.from(self.body)
  100054. }
  100055. if (!self.hasHeader('content-length')) {
  100056. var length
  100057. if (typeof self.body === 'string') {
  100058. length = Buffer.byteLength(self.body)
  100059. } else if (Array.isArray(self.body)) {
  100060. length = self.body.reduce(function (a, b) { return a + b.length }, 0)
  100061. } else {
  100062. length = self.body.length
  100063. }
  100064. if (length) {
  100065. self.setHeader('content-length', length)
  100066. } else {
  100067. self.emit('error', new Error('Argument error, options.body.'))
  100068. }
  100069. }
  100070. }
  100071. if (self.body && !isstream(self.body)) {
  100072. setContentLength()
  100073. }
  100074. if (options.oauth) {
  100075. self.oauth(options.oauth)
  100076. } else if (self._oauth.params && self.hasHeader('authorization')) {
  100077. self.oauth(self._oauth.params)
  100078. }
  100079. var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
  100080. var defaultModules = {'http:': http, 'https:': https}
  100081. var httpModules = self.httpModules || {}
  100082. self.httpModule = httpModules[protocol] || defaultModules[protocol]
  100083. if (!self.httpModule) {
  100084. return self.emit('error', new Error('Invalid protocol: ' + protocol))
  100085. }
  100086. if (options.ca) {
  100087. self.ca = options.ca
  100088. }
  100089. if (!self.agent) {
  100090. if (options.agentOptions) {
  100091. self.agentOptions = options.agentOptions
  100092. }
  100093. if (options.agentClass) {
  100094. self.agentClass = options.agentClass
  100095. } else if (options.forever) {
  100096. var v = version()
  100097. // use ForeverAgent in node 0.10- only
  100098. if (v.major === 0 && v.minor <= 10) {
  100099. self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
  100100. } else {
  100101. self.agentClass = self.httpModule.Agent
  100102. self.agentOptions = self.agentOptions || {}
  100103. self.agentOptions.keepAlive = true
  100104. }
  100105. } else {
  100106. self.agentClass = self.httpModule.Agent
  100107. }
  100108. }
  100109. if (self.pool === false) {
  100110. self.agent = false
  100111. } else {
  100112. self.agent = self.agent || self.getNewAgent()
  100113. }
  100114. self.on('pipe', function (src) {
  100115. if (self.ntick && self._started) {
  100116. self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
  100117. }
  100118. self.src = src
  100119. if (isReadStream(src)) {
  100120. if (!self.hasHeader('content-type')) {
  100121. self.setHeader('content-type', mime.lookup(src.path))
  100122. }
  100123. } else {
  100124. if (src.headers) {
  100125. for (var i in src.headers) {
  100126. if (!self.hasHeader(i)) {
  100127. self.setHeader(i, src.headers[i])
  100128. }
  100129. }
  100130. }
  100131. if (self._json && !self.hasHeader('content-type')) {
  100132. self.setHeader('content-type', 'application/json')
  100133. }
  100134. if (src.method && !self.explicitMethod) {
  100135. self.method = src.method
  100136. }
  100137. }
  100138. // self.on('pipe', function () {
  100139. // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
  100140. // })
  100141. })
  100142. defer(function () {
  100143. if (self._aborted) {
  100144. return
  100145. }
  100146. var end = function () {
  100147. if (self._form) {
  100148. if (!self._auth.hasAuth) {
  100149. self._form.pipe(self)
  100150. } else if (self._auth.hasAuth && self._auth.sentAuth) {
  100151. self._form.pipe(self)
  100152. }
  100153. }
  100154. if (self._multipart && self._multipart.chunked) {
  100155. self._multipart.body.pipe(self)
  100156. }
  100157. if (self.body) {
  100158. if (isstream(self.body)) {
  100159. self.body.pipe(self)
  100160. } else {
  100161. setContentLength()
  100162. if (Array.isArray(self.body)) {
  100163. self.body.forEach(function (part) {
  100164. self.write(part)
  100165. })
  100166. } else {
  100167. self.write(self.body)
  100168. }
  100169. self.end()
  100170. }
  100171. } else if (self.requestBodyStream) {
  100172. console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
  100173. self.requestBodyStream.pipe(self)
  100174. } else if (!self.src) {
  100175. if (self._auth.hasAuth && !self._auth.sentAuth) {
  100176. self.end()
  100177. return
  100178. }
  100179. if (self.method !== 'GET' && typeof self.method !== 'undefined') {
  100180. self.setHeader('content-length', 0)
  100181. }
  100182. self.end()
  100183. }
  100184. }
  100185. if (self._form && !self.hasHeader('content-length')) {
  100186. // Before ending the request, we had to compute the length of the whole form, asyncly
  100187. self.setHeader(self._form.getHeaders(), true)
  100188. self._form.getLength(function (err, length) {
  100189. if (!err && !isNaN(length)) {
  100190. self.setHeader('content-length', length)
  100191. }
  100192. end()
  100193. })
  100194. } else {
  100195. end()
  100196. }
  100197. self.ntick = true
  100198. })
  100199. }
  100200. Request.prototype.getNewAgent = function () {
  100201. var self = this
  100202. var Agent = self.agentClass
  100203. var options = {}
  100204. if (self.agentOptions) {
  100205. for (var i in self.agentOptions) {
  100206. options[i] = self.agentOptions[i]
  100207. }
  100208. }
  100209. if (self.ca) {
  100210. options.ca = self.ca
  100211. }
  100212. if (self.ciphers) {
  100213. options.ciphers = self.ciphers
  100214. }
  100215. if (self.secureProtocol) {
  100216. options.secureProtocol = self.secureProtocol
  100217. }
  100218. if (self.secureOptions) {
  100219. options.secureOptions = self.secureOptions
  100220. }
  100221. if (typeof self.rejectUnauthorized !== 'undefined') {
  100222. options.rejectUnauthorized = self.rejectUnauthorized
  100223. }
  100224. if (self.cert && self.key) {
  100225. options.key = self.key
  100226. options.cert = self.cert
  100227. }
  100228. if (self.pfx) {
  100229. options.pfx = self.pfx
  100230. }
  100231. if (self.passphrase) {
  100232. options.passphrase = self.passphrase
  100233. }
  100234. var poolKey = ''
  100235. // different types of agents are in different pools
  100236. if (Agent !== self.httpModule.Agent) {
  100237. poolKey += Agent.name
  100238. }
  100239. // ca option is only relevant if proxy or destination are https
  100240. var proxy = self.proxy
  100241. if (typeof proxy === 'string') {
  100242. proxy = url.parse(proxy)
  100243. }
  100244. var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
  100245. if (isHttps) {
  100246. if (options.ca) {
  100247. if (poolKey) {
  100248. poolKey += ':'
  100249. }
  100250. poolKey += options.ca
  100251. }
  100252. if (typeof options.rejectUnauthorized !== 'undefined') {
  100253. if (poolKey) {
  100254. poolKey += ':'
  100255. }
  100256. poolKey += options.rejectUnauthorized
  100257. }
  100258. if (options.cert) {
  100259. if (poolKey) {
  100260. poolKey += ':'
  100261. }
  100262. poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
  100263. }
  100264. if (options.pfx) {
  100265. if (poolKey) {
  100266. poolKey += ':'
  100267. }
  100268. poolKey += options.pfx.toString('ascii')
  100269. }
  100270. if (options.ciphers) {
  100271. if (poolKey) {
  100272. poolKey += ':'
  100273. }
  100274. poolKey += options.ciphers
  100275. }
  100276. if (options.secureProtocol) {
  100277. if (poolKey) {
  100278. poolKey += ':'
  100279. }
  100280. poolKey += options.secureProtocol
  100281. }
  100282. if (options.secureOptions) {
  100283. if (poolKey) {
  100284. poolKey += ':'
  100285. }
  100286. poolKey += options.secureOptions
  100287. }
  100288. }
  100289. if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
  100290. // not doing anything special. Use the globalAgent
  100291. return self.httpModule.globalAgent
  100292. }
  100293. // we're using a stored agent. Make sure it's protocol-specific
  100294. poolKey = self.uri.protocol + poolKey
  100295. // generate a new agent for this setting if none yet exists
  100296. if (!self.pool[poolKey]) {
  100297. self.pool[poolKey] = new Agent(options)
  100298. // properly set maxSockets on new agents
  100299. if (self.pool.maxSockets) {
  100300. self.pool[poolKey].maxSockets = self.pool.maxSockets
  100301. }
  100302. }
  100303. return self.pool[poolKey]
  100304. }
  100305. Request.prototype.start = function () {
  100306. // start() is called once we are ready to send the outgoing HTTP request.
  100307. // this is usually called on the first write(), end() or on nextTick()
  100308. var self = this
  100309. if (self.timing) {
  100310. // All timings will be relative to this request's startTime. In order to do this,
  100311. // we need to capture the wall-clock start time (via Date), immediately followed
  100312. // by the high-resolution timer (via now()). While these two won't be set
  100313. // at the _exact_ same time, they should be close enough to be able to calculate
  100314. // high-resolution, monotonically non-decreasing timestamps relative to startTime.
  100315. var startTime = new Date().getTime()
  100316. var startTimeNow = now()
  100317. }
  100318. if (self._aborted) {
  100319. return
  100320. }
  100321. self._started = true
  100322. self.method = self.method || 'GET'
  100323. self.href = self.uri.href
  100324. if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
  100325. self.setHeader('content-length', self.src.stat.size)
  100326. }
  100327. if (self._aws) {
  100328. self.aws(self._aws, true)
  100329. }
  100330. // We have a method named auth, which is completely different from the http.request
  100331. // auth option. If we don't remove it, we're gonna have a bad time.
  100332. var reqOptions = copy(self)
  100333. delete reqOptions.auth
  100334. debug('make request', self.uri.href)
  100335. // node v6.8.0 now supports a `timeout` value in `http.request()`, but we
  100336. // should delete it for now since we handle timeouts manually for better
  100337. // consistency with node versions before v6.8.0
  100338. delete reqOptions.timeout
  100339. try {
  100340. self.req = self.httpModule.request(reqOptions)
  100341. } catch (err) {
  100342. self.emit('error', err)
  100343. return
  100344. }
  100345. if (self.timing) {
  100346. self.startTime = startTime
  100347. self.startTimeNow = startTimeNow
  100348. // Timing values will all be relative to startTime (by comparing to startTimeNow
  100349. // so we have an accurate clock)
  100350. self.timings = {}
  100351. }
  100352. var timeout
  100353. if (self.timeout && !self.timeoutTimer) {
  100354. if (self.timeout < 0) {
  100355. timeout = 0
  100356. } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
  100357. timeout = self.timeout
  100358. }
  100359. }
  100360. self.req.on('response', self.onRequestResponse.bind(self))
  100361. self.req.on('error', self.onRequestError.bind(self))
  100362. self.req.on('drain', function () {
  100363. self.emit('drain')
  100364. })
  100365. self.req.on('socket', function (socket) {
  100366. // `._connecting` was the old property which was made public in node v6.1.0
  100367. var isConnecting = socket._connecting || socket.connecting
  100368. if (self.timing) {
  100369. self.timings.socket = now() - self.startTimeNow
  100370. if (isConnecting) {
  100371. var onLookupTiming = function () {
  100372. self.timings.lookup = now() - self.startTimeNow
  100373. }
  100374. var onConnectTiming = function () {
  100375. self.timings.connect = now() - self.startTimeNow
  100376. }
  100377. socket.once('lookup', onLookupTiming)
  100378. socket.once('connect', onConnectTiming)
  100379. // clean up timing event listeners if needed on error
  100380. self.req.once('error', function () {
  100381. socket.removeListener('lookup', onLookupTiming)
  100382. socket.removeListener('connect', onConnectTiming)
  100383. })
  100384. }
  100385. }
  100386. var setReqTimeout = function () {
  100387. // This timeout sets the amount of time to wait *between* bytes sent
  100388. // from the server once connected.
  100389. //
  100390. // In particular, it's useful for erroring if the server fails to send
  100391. // data halfway through streaming a response.
  100392. self.req.setTimeout(timeout, function () {
  100393. if (self.req) {
  100394. self.abort()
  100395. var e = new Error('ESOCKETTIMEDOUT')
  100396. e.code = 'ESOCKETTIMEDOUT'
  100397. e.connect = false
  100398. self.emit('error', e)
  100399. }
  100400. })
  100401. }
  100402. if (timeout !== undefined) {
  100403. // Only start the connection timer if we're actually connecting a new
  100404. // socket, otherwise if we're already connected (because this is a
  100405. // keep-alive connection) do not bother. This is important since we won't
  100406. // get a 'connect' event for an already connected socket.
  100407. if (isConnecting) {
  100408. var onReqSockConnect = function () {
  100409. socket.removeListener('connect', onReqSockConnect)
  100410. self.clearTimeout()
  100411. setReqTimeout()
  100412. }
  100413. socket.on('connect', onReqSockConnect)
  100414. self.req.on('error', function (err) { // eslint-disable-line handle-callback-err
  100415. socket.removeListener('connect', onReqSockConnect)
  100416. })
  100417. // Set a timeout in memory - this block will throw if the server takes more
  100418. // than `timeout` to write the HTTP status and headers (corresponding to
  100419. // the on('response') event on the client). NB: this measures wall-clock
  100420. // time, not the time between bytes sent by the server.
  100421. self.timeoutTimer = setTimeout(function () {
  100422. socket.removeListener('connect', onReqSockConnect)
  100423. self.abort()
  100424. var e = new Error('ETIMEDOUT')
  100425. e.code = 'ETIMEDOUT'
  100426. e.connect = true
  100427. self.emit('error', e)
  100428. }, timeout)
  100429. } else {
  100430. // We're already connected
  100431. setReqTimeout()
  100432. }
  100433. }
  100434. self.emit('socket', socket)
  100435. })
  100436. self.emit('request', self.req)
  100437. }
  100438. Request.prototype.onRequestError = function (error) {
  100439. var self = this
  100440. if (self._aborted) {
  100441. return
  100442. }
  100443. if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
  100444. self.agent.addRequestNoreuse) {
  100445. self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
  100446. self.start()
  100447. self.req.end()
  100448. return
  100449. }
  100450. self.clearTimeout()
  100451. self.emit('error', error)
  100452. }
  100453. Request.prototype.onRequestResponse = function (response) {
  100454. var self = this
  100455. if (self.timing) {
  100456. self.timings.response = now() - self.startTimeNow
  100457. }
  100458. debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
  100459. response.on('end', function () {
  100460. if (self.timing) {
  100461. self.timings.end = now() - self.startTimeNow
  100462. response.timingStart = self.startTime
  100463. // fill in the blanks for any periods that didn't trigger, such as
  100464. // no lookup or connect due to keep alive
  100465. if (!self.timings.socket) {
  100466. self.timings.socket = 0
  100467. }
  100468. if (!self.timings.lookup) {
  100469. self.timings.lookup = self.timings.socket
  100470. }
  100471. if (!self.timings.connect) {
  100472. self.timings.connect = self.timings.lookup
  100473. }
  100474. if (!self.timings.response) {
  100475. self.timings.response = self.timings.connect
  100476. }
  100477. debug('elapsed time', self.timings.end)
  100478. // elapsedTime includes all redirects
  100479. self.elapsedTime += Math.round(self.timings.end)
  100480. // NOTE: elapsedTime is deprecated in favor of .timings
  100481. response.elapsedTime = self.elapsedTime
  100482. // timings is just for the final fetch
  100483. response.timings = self.timings
  100484. // pre-calculate phase timings as well
  100485. response.timingPhases = {
  100486. wait: self.timings.socket,
  100487. dns: self.timings.lookup - self.timings.socket,
  100488. tcp: self.timings.connect - self.timings.lookup,
  100489. firstByte: self.timings.response - self.timings.connect,
  100490. download: self.timings.end - self.timings.response,
  100491. total: self.timings.end
  100492. }
  100493. }
  100494. debug('response end', self.uri.href, response.statusCode, response.headers)
  100495. })
  100496. if (self._aborted) {
  100497. debug('aborted', self.uri.href)
  100498. response.resume()
  100499. return
  100500. }
  100501. self.response = response
  100502. response.request = self
  100503. response.toJSON = responseToJSON
  100504. // XXX This is different on 0.10, because SSL is strict by default
  100505. if (self.httpModule === https &&
  100506. self.strictSSL && (!response.hasOwnProperty('socket') ||
  100507. !response.socket.authorized)) {
  100508. debug('strict ssl error', self.uri.href)
  100509. var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
  100510. self.emit('error', new Error('SSL Error: ' + sslErr))
  100511. return
  100512. }
  100513. // Save the original host before any redirect (if it changes, we need to
  100514. // remove any authorization headers). Also remember the case of the header
  100515. // name because lots of broken servers expect Host instead of host and we
  100516. // want the caller to be able to specify this.
  100517. self.originalHost = self.getHeader('host')
  100518. if (!self.originalHostHeaderName) {
  100519. self.originalHostHeaderName = self.hasHeader('host')
  100520. }
  100521. if (self.setHost) {
  100522. self.removeHeader('host')
  100523. }
  100524. self.clearTimeout()
  100525. var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
  100526. var addCookie = function (cookie) {
  100527. // set the cookie if it's domain in the href's domain.
  100528. try {
  100529. targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
  100530. } catch (e) {
  100531. self.emit('error', e)
  100532. }
  100533. }
  100534. response.caseless = caseless(response.headers)
  100535. if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
  100536. var headerName = response.caseless.has('set-cookie')
  100537. if (Array.isArray(response.headers[headerName])) {
  100538. response.headers[headerName].forEach(addCookie)
  100539. } else {
  100540. addCookie(response.headers[headerName])
  100541. }
  100542. }
  100543. if (self._redirect.onResponse(response)) {
  100544. return // Ignore the rest of the response
  100545. } else {
  100546. // Be a good stream and emit end when the response is finished.
  100547. // Hack to emit end on close because of a core bug that never fires end
  100548. response.on('close', function () {
  100549. if (!self._ended) {
  100550. self.response.emit('end')
  100551. }
  100552. })
  100553. response.once('end', function () {
  100554. self._ended = true
  100555. })
  100556. var noBody = function (code) {
  100557. return (
  100558. self.method === 'HEAD' ||
  100559. // Informational
  100560. (code >= 100 && code < 200) ||
  100561. // No Content
  100562. code === 204 ||
  100563. // Not Modified
  100564. code === 304
  100565. )
  100566. }
  100567. var responseContent
  100568. if (self.gzip && !noBody(response.statusCode)) {
  100569. var contentEncoding = response.headers['content-encoding'] || 'identity'
  100570. contentEncoding = contentEncoding.trim().toLowerCase()
  100571. // Be more lenient with decoding compressed responses, since (very rarely)
  100572. // servers send slightly invalid gzip responses that are still accepted
  100573. // by common browsers.
  100574. // Always using Z_SYNC_FLUSH is what cURL does.
  100575. var zlibOptions = {
  100576. flush: zlib.Z_SYNC_FLUSH,
  100577. finishFlush: zlib.Z_SYNC_FLUSH
  100578. }
  100579. if (contentEncoding === 'gzip') {
  100580. responseContent = zlib.createGunzip(zlibOptions)
  100581. response.pipe(responseContent)
  100582. } else if (contentEncoding === 'deflate') {
  100583. responseContent = zlib.createInflate(zlibOptions)
  100584. response.pipe(responseContent)
  100585. } else {
  100586. // Since previous versions didn't check for Content-Encoding header,
  100587. // ignore any invalid values to preserve backwards-compatibility
  100588. if (contentEncoding !== 'identity') {
  100589. debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
  100590. }
  100591. responseContent = response
  100592. }
  100593. } else {
  100594. responseContent = response
  100595. }
  100596. if (self.encoding) {
  100597. if (self.dests.length !== 0) {
  100598. console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
  100599. } else {
  100600. responseContent.setEncoding(self.encoding)
  100601. }
  100602. }
  100603. if (self._paused) {
  100604. responseContent.pause()
  100605. }
  100606. self.responseContent = responseContent
  100607. self.emit('response', response)
  100608. self.dests.forEach(function (dest) {
  100609. self.pipeDest(dest)
  100610. })
  100611. responseContent.on('data', function (chunk) {
  100612. if (self.timing && !self.responseStarted) {
  100613. self.responseStartTime = (new Date()).getTime()
  100614. // NOTE: responseStartTime is deprecated in favor of .timings
  100615. response.responseStartTime = self.responseStartTime
  100616. }
  100617. self._destdata = true
  100618. self.emit('data', chunk)
  100619. })
  100620. responseContent.once('end', function (chunk) {
  100621. self.emit('end', chunk)
  100622. })
  100623. responseContent.on('error', function (error) {
  100624. self.emit('error', error)
  100625. })
  100626. responseContent.on('close', function () { self.emit('close') })
  100627. if (self.callback) {
  100628. self.readResponseBody(response)
  100629. } else { // if no callback
  100630. self.on('end', function () {
  100631. if (self._aborted) {
  100632. debug('aborted', self.uri.href)
  100633. return
  100634. }
  100635. self.emit('complete', response)
  100636. })
  100637. }
  100638. }
  100639. debug('finish init function', self.uri.href)
  100640. }
  100641. Request.prototype.readResponseBody = function (response) {
  100642. var self = this
  100643. debug("reading response's body")
  100644. var buffers = []
  100645. var bufferLength = 0
  100646. var strings = []
  100647. self.on('data', function (chunk) {
  100648. if (!Buffer.isBuffer(chunk)) {
  100649. strings.push(chunk)
  100650. } else if (chunk.length) {
  100651. bufferLength += chunk.length
  100652. buffers.push(chunk)
  100653. }
  100654. })
  100655. self.on('end', function () {
  100656. debug('end event', self.uri.href)
  100657. if (self._aborted) {
  100658. debug('aborted', self.uri.href)
  100659. // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
  100660. // This can lead to leaky behavior if the user retains a reference to the request object.
  100661. buffers = []
  100662. bufferLength = 0
  100663. return
  100664. }
  100665. if (bufferLength) {
  100666. debug('has body', self.uri.href, bufferLength)
  100667. response.body = Buffer.concat(buffers, bufferLength)
  100668. if (self.encoding !== null) {
  100669. response.body = response.body.toString(self.encoding)
  100670. }
  100671. // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
  100672. // This can lead to leaky behavior if the user retains a reference to the request object.
  100673. buffers = []
  100674. bufferLength = 0
  100675. } else if (strings.length) {
  100676. // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
  100677. // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
  100678. if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
  100679. strings[0] = strings[0].substring(1)
  100680. }
  100681. response.body = strings.join('')
  100682. }
  100683. if (self._json) {
  100684. try {
  100685. response.body = JSON.parse(response.body, self._jsonReviver)
  100686. } catch (e) {
  100687. debug('invalid JSON received', self.uri.href)
  100688. }
  100689. }
  100690. debug('emitting complete', self.uri.href)
  100691. if (typeof response.body === 'undefined' && !self._json) {
  100692. response.body = self.encoding === null ? Buffer.alloc(0) : ''
  100693. }
  100694. self.emit('complete', response, response.body)
  100695. })
  100696. }
  100697. Request.prototype.abort = function () {
  100698. var self = this
  100699. self._aborted = true
  100700. if (self.req) {
  100701. self.req.abort()
  100702. } else if (self.response) {
  100703. self.response.destroy()
  100704. }
  100705. self.clearTimeout()
  100706. self.emit('abort')
  100707. }
  100708. Request.prototype.pipeDest = function (dest) {
  100709. var self = this
  100710. var response = self.response
  100711. // Called after the response is received
  100712. if (dest.headers && !dest.headersSent) {
  100713. if (response.caseless.has('content-type')) {
  100714. var ctname = response.caseless.has('content-type')
  100715. if (dest.setHeader) {
  100716. dest.setHeader(ctname, response.headers[ctname])
  100717. } else {
  100718. dest.headers[ctname] = response.headers[ctname]
  100719. }
  100720. }
  100721. if (response.caseless.has('content-length')) {
  100722. var clname = response.caseless.has('content-length')
  100723. if (dest.setHeader) {
  100724. dest.setHeader(clname, response.headers[clname])
  100725. } else {
  100726. dest.headers[clname] = response.headers[clname]
  100727. }
  100728. }
  100729. }
  100730. if (dest.setHeader && !dest.headersSent) {
  100731. for (var i in response.headers) {
  100732. // If the response content is being decoded, the Content-Encoding header
  100733. // of the response doesn't represent the piped content, so don't pass it.
  100734. if (!self.gzip || i !== 'content-encoding') {
  100735. dest.setHeader(i, response.headers[i])
  100736. }
  100737. }
  100738. dest.statusCode = response.statusCode
  100739. }
  100740. if (self.pipefilter) {
  100741. self.pipefilter(response, dest)
  100742. }
  100743. }
  100744. Request.prototype.qs = function (q, clobber) {
  100745. var self = this
  100746. var base
  100747. if (!clobber && self.uri.query) {
  100748. base = self._qs.parse(self.uri.query)
  100749. } else {
  100750. base = {}
  100751. }
  100752. for (var i in q) {
  100753. base[i] = q[i]
  100754. }
  100755. var qs = self._qs.stringify(base)
  100756. if (qs === '') {
  100757. return self
  100758. }
  100759. self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
  100760. self.url = self.uri
  100761. self.path = self.uri.path
  100762. if (self.uri.host === 'unix') {
  100763. self.enableUnixSocket()
  100764. }
  100765. return self
  100766. }
  100767. Request.prototype.form = function (form) {
  100768. var self = this
  100769. if (form) {
  100770. if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
  100771. self.setHeader('content-type', 'application/x-www-form-urlencoded')
  100772. }
  100773. self.body = (typeof form === 'string')
  100774. ? self._qs.rfc3986(form.toString('utf8'))
  100775. : self._qs.stringify(form).toString('utf8')
  100776. return self
  100777. }
  100778. // create form-data object
  100779. self._form = new FormData()
  100780. self._form.on('error', function (err) {
  100781. err.message = 'form-data: ' + err.message
  100782. self.emit('error', err)
  100783. self.abort()
  100784. })
  100785. return self._form
  100786. }
  100787. Request.prototype.multipart = function (multipart) {
  100788. var self = this
  100789. self._multipart.onRequest(multipart)
  100790. if (!self._multipart.chunked) {
  100791. self.body = self._multipart.body
  100792. }
  100793. return self
  100794. }
  100795. Request.prototype.json = function (val) {
  100796. var self = this
  100797. if (!self.hasHeader('accept')) {
  100798. self.setHeader('accept', 'application/json')
  100799. }
  100800. if (typeof self.jsonReplacer === 'function') {
  100801. self._jsonReplacer = self.jsonReplacer
  100802. }
  100803. self._json = true
  100804. if (typeof val === 'boolean') {
  100805. if (self.body !== undefined) {
  100806. if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
  100807. self.body = safeStringify(self.body, self._jsonReplacer)
  100808. } else {
  100809. self.body = self._qs.rfc3986(self.body)
  100810. }
  100811. if (!self.hasHeader('content-type')) {
  100812. self.setHeader('content-type', 'application/json')
  100813. }
  100814. }
  100815. } else {
  100816. self.body = safeStringify(val, self._jsonReplacer)
  100817. if (!self.hasHeader('content-type')) {
  100818. self.setHeader('content-type', 'application/json')
  100819. }
  100820. }
  100821. if (typeof self.jsonReviver === 'function') {
  100822. self._jsonReviver = self.jsonReviver
  100823. }
  100824. return self
  100825. }
  100826. Request.prototype.getHeader = function (name, headers) {
  100827. var self = this
  100828. var result, re, match
  100829. if (!headers) {
  100830. headers = self.headers
  100831. }
  100832. Object.keys(headers).forEach(function (key) {
  100833. if (key.length !== name.length) {
  100834. return
  100835. }
  100836. re = new RegExp(name, 'i')
  100837. match = key.match(re)
  100838. if (match) {
  100839. result = headers[key]
  100840. }
  100841. })
  100842. return result
  100843. }
  100844. Request.prototype.enableUnixSocket = function () {
  100845. // Get the socket & request paths from the URL
  100846. var unixParts = this.uri.path.split(':')
  100847. var host = unixParts[0]
  100848. var path = unixParts[1]
  100849. // Apply unix properties to request
  100850. this.socketPath = host
  100851. this.uri.pathname = path
  100852. this.uri.path = path
  100853. this.uri.host = host
  100854. this.uri.hostname = host
  100855. this.uri.isUnix = true
  100856. }
  100857. Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
  100858. var self = this
  100859. self._auth.onRequest(user, pass, sendImmediately, bearer)
  100860. return self
  100861. }
  100862. Request.prototype.aws = function (opts, now) {
  100863. var self = this
  100864. if (!now) {
  100865. self._aws = opts
  100866. return self
  100867. }
  100868. if (opts.sign_version === 4 || opts.sign_version === '4') {
  100869. // use aws4
  100870. var options = {
  100871. host: self.uri.host,
  100872. path: self.uri.path,
  100873. method: self.method,
  100874. headers: self.headers,
  100875. body: self.body
  100876. }
  100877. if (opts.service) {
  100878. options.service = opts.service
  100879. }
  100880. var signRes = aws4.sign(options, {
  100881. accessKeyId: opts.key,
  100882. secretAccessKey: opts.secret,
  100883. sessionToken: opts.session
  100884. })
  100885. self.setHeader('authorization', signRes.headers.Authorization)
  100886. self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
  100887. if (signRes.headers['X-Amz-Security-Token']) {
  100888. self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
  100889. }
  100890. } else {
  100891. // default: use aws-sign2
  100892. var date = new Date()
  100893. self.setHeader('date', date.toUTCString())
  100894. var auth = {
  100895. key: opts.key,
  100896. secret: opts.secret,
  100897. verb: self.method.toUpperCase(),
  100898. date: date,
  100899. contentType: self.getHeader('content-type') || '',
  100900. md5: self.getHeader('content-md5') || '',
  100901. amazonHeaders: aws2.canonicalizeHeaders(self.headers)
  100902. }
  100903. var path = self.uri.path
  100904. if (opts.bucket && path) {
  100905. auth.resource = '/' + opts.bucket + path
  100906. } else if (opts.bucket && !path) {
  100907. auth.resource = '/' + opts.bucket
  100908. } else if (!opts.bucket && path) {
  100909. auth.resource = path
  100910. } else if (!opts.bucket && !path) {
  100911. auth.resource = '/'
  100912. }
  100913. auth.resource = aws2.canonicalizeResource(auth.resource)
  100914. self.setHeader('authorization', aws2.authorization(auth))
  100915. }
  100916. return self
  100917. }
  100918. Request.prototype.httpSignature = function (opts) {
  100919. var self = this
  100920. httpSignature.signRequest({
  100921. getHeader: function (header) {
  100922. return self.getHeader(header, self.headers)
  100923. },
  100924. setHeader: function (header, value) {
  100925. self.setHeader(header, value)
  100926. },
  100927. method: self.method,
  100928. path: self.path
  100929. }, opts)
  100930. debug('httpSignature authorization', self.getHeader('authorization'))
  100931. return self
  100932. }
  100933. Request.prototype.hawk = function (opts) {
  100934. var self = this
  100935. self.setHeader('Authorization', hawk.header(self.uri, self.method, opts))
  100936. }
  100937. Request.prototype.oauth = function (_oauth) {
  100938. var self = this
  100939. self._oauth.onRequest(_oauth)
  100940. return self
  100941. }
  100942. Request.prototype.jar = function (jar) {
  100943. var self = this
  100944. var cookies
  100945. if (self._redirect.redirectsFollowed === 0) {
  100946. self.originalCookieHeader = self.getHeader('cookie')
  100947. }
  100948. if (!jar) {
  100949. // disable cookies
  100950. cookies = false
  100951. self._disableCookies = true
  100952. } else {
  100953. var targetCookieJar = jar.getCookieString ? jar : globalCookieJar
  100954. var urihref = self.uri.href
  100955. // fetch cookie in the Specified host
  100956. if (targetCookieJar) {
  100957. cookies = targetCookieJar.getCookieString(urihref)
  100958. }
  100959. }
  100960. // if need cookie and cookie is not empty
  100961. if (cookies && cookies.length) {
  100962. if (self.originalCookieHeader) {
  100963. // Don't overwrite existing Cookie header
  100964. self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
  100965. } else {
  100966. self.setHeader('cookie', cookies)
  100967. }
  100968. }
  100969. self._jar = jar
  100970. return self
  100971. }
  100972. // Stream API
  100973. Request.prototype.pipe = function (dest, opts) {
  100974. var self = this
  100975. if (self.response) {
  100976. if (self._destdata) {
  100977. self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
  100978. } else if (self._ended) {
  100979. self.emit('error', new Error('You cannot pipe after the response has been ended.'))
  100980. } else {
  100981. stream.Stream.prototype.pipe.call(self, dest, opts)
  100982. self.pipeDest(dest)
  100983. return dest
  100984. }
  100985. } else {
  100986. self.dests.push(dest)
  100987. stream.Stream.prototype.pipe.call(self, dest, opts)
  100988. return dest
  100989. }
  100990. }
  100991. Request.prototype.write = function () {
  100992. var self = this
  100993. if (self._aborted) { return }
  100994. if (!self._started) {
  100995. self.start()
  100996. }
  100997. if (self.req) {
  100998. return self.req.write.apply(self.req, arguments)
  100999. }
  101000. }
  101001. Request.prototype.end = function (chunk) {
  101002. var self = this
  101003. if (self._aborted) { return }
  101004. if (chunk) {
  101005. self.write(chunk)
  101006. }
  101007. if (!self._started) {
  101008. self.start()
  101009. }
  101010. if (self.req) {
  101011. self.req.end()
  101012. }
  101013. }
  101014. Request.prototype.pause = function () {
  101015. var self = this
  101016. if (!self.responseContent) {
  101017. self._paused = true
  101018. } else {
  101019. self.responseContent.pause.apply(self.responseContent, arguments)
  101020. }
  101021. }
  101022. Request.prototype.resume = function () {
  101023. var self = this
  101024. if (!self.responseContent) {
  101025. self._paused = false
  101026. } else {
  101027. self.responseContent.resume.apply(self.responseContent, arguments)
  101028. }
  101029. }
  101030. Request.prototype.destroy = function () {
  101031. var self = this
  101032. this.clearTimeout()
  101033. if (!self._ended) {
  101034. self.end()
  101035. } else if (self.response) {
  101036. self.response.destroy()
  101037. }
  101038. }
  101039. Request.prototype.clearTimeout = function () {
  101040. if (this.timeoutTimer) {
  101041. clearTimeout(this.timeoutTimer)
  101042. this.timeoutTimer = null
  101043. }
  101044. }
  101045. Request.defaultProxyHeaderWhiteList =
  101046. Tunnel.defaultProxyHeaderWhiteList.slice()
  101047. Request.defaultProxyHeaderExclusiveList =
  101048. Tunnel.defaultProxyHeaderExclusiveList.slice()
  101049. // Exports
  101050. Request.prototype.toJSON = requestToJSON
  101051. module.exports = Request
  101052. }).call(this)}).call(this,require('_process'))
  101053. },{"./lib/auth":547,"./lib/cookies":548,"./lib/getProxyFromURI":549,"./lib/har":550,"./lib/hawk":551,"./lib/helpers":552,"./lib/multipart":553,"./lib/oauth":554,"./lib/querystring":555,"./lib/redirect":556,"./lib/tunnel":557,"_process":525,"aws-sign2":111,"aws4":112,"caseless":197,"extend":249,"forever-agent":254,"form-data":558,"http":612,"http-signature":313,"https":318,"is-typedarray":325,"isstream":326,"mime-types":344,"performance-now":524,"safe-buffer":561,"stream":597,"url":653,"util":658,"zlib":189}],560:[function(require,module,exports){
  101054. 'use strict'
  101055. var Buffer = require('buffer').Buffer
  101056. var inherits = require('inherits')
  101057. var HashBase = require('hash-base')
  101058. var ARRAY16 = new Array(16)
  101059. var zl = [
  101060. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  101061. 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  101062. 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  101063. 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  101064. 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
  101065. ]
  101066. var zr = [
  101067. 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  101068. 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  101069. 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  101070. 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  101071. 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
  101072. ]
  101073. var sl = [
  101074. 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  101075. 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  101076. 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  101077. 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  101078. 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
  101079. ]
  101080. var sr = [
  101081. 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  101082. 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  101083. 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  101084. 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  101085. 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
  101086. ]
  101087. var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
  101088. var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]
  101089. function RIPEMD160 () {
  101090. HashBase.call(this, 64)
  101091. // state
  101092. this._a = 0x67452301
  101093. this._b = 0xefcdab89
  101094. this._c = 0x98badcfe
  101095. this._d = 0x10325476
  101096. this._e = 0xc3d2e1f0
  101097. }
  101098. inherits(RIPEMD160, HashBase)
  101099. RIPEMD160.prototype._update = function () {
  101100. var words = ARRAY16
  101101. for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)
  101102. var al = this._a | 0
  101103. var bl = this._b | 0
  101104. var cl = this._c | 0
  101105. var dl = this._d | 0
  101106. var el = this._e | 0
  101107. var ar = this._a | 0
  101108. var br = this._b | 0
  101109. var cr = this._c | 0
  101110. var dr = this._d | 0
  101111. var er = this._e | 0
  101112. // computation
  101113. for (var i = 0; i < 80; i += 1) {
  101114. var tl
  101115. var tr
  101116. if (i < 16) {
  101117. tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
  101118. tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
  101119. } else if (i < 32) {
  101120. tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
  101121. tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
  101122. } else if (i < 48) {
  101123. tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
  101124. tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
  101125. } else if (i < 64) {
  101126. tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
  101127. tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
  101128. } else { // if (i<80) {
  101129. tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
  101130. tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
  101131. }
  101132. al = el
  101133. el = dl
  101134. dl = rotl(cl, 10)
  101135. cl = bl
  101136. bl = tl
  101137. ar = er
  101138. er = dr
  101139. dr = rotl(cr, 10)
  101140. cr = br
  101141. br = tr
  101142. }
  101143. // update state
  101144. var t = (this._b + cl + dr) | 0
  101145. this._b = (this._c + dl + er) | 0
  101146. this._c = (this._d + el + ar) | 0
  101147. this._d = (this._e + al + br) | 0
  101148. this._e = (this._a + bl + cr) | 0
  101149. this._a = t
  101150. }
  101151. RIPEMD160.prototype._digest = function () {
  101152. // create padding and handle blocks
  101153. this._block[this._blockOffset++] = 0x80
  101154. if (this._blockOffset > 56) {
  101155. this._block.fill(0, this._blockOffset, 64)
  101156. this._update()
  101157. this._blockOffset = 0
  101158. }
  101159. this._block.fill(0, this._blockOffset, 56)
  101160. this._block.writeUInt32LE(this._length[0], 56)
  101161. this._block.writeUInt32LE(this._length[1], 60)
  101162. this._update()
  101163. // produce result
  101164. var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
  101165. buffer.writeInt32LE(this._a, 0)
  101166. buffer.writeInt32LE(this._b, 4)
  101167. buffer.writeInt32LE(this._c, 8)
  101168. buffer.writeInt32LE(this._d, 12)
  101169. buffer.writeInt32LE(this._e, 16)
  101170. return buffer
  101171. }
  101172. function rotl (x, n) {
  101173. return (x << n) | (x >>> (32 - n))
  101174. }
  101175. function fn1 (a, b, c, d, e, m, k, s) {
  101176. return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
  101177. }
  101178. function fn2 (a, b, c, d, e, m, k, s) {
  101179. return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
  101180. }
  101181. function fn3 (a, b, c, d, e, m, k, s) {
  101182. return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
  101183. }
  101184. function fn4 (a, b, c, d, e, m, k, s) {
  101185. return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
  101186. }
  101187. function fn5 (a, b, c, d, e, m, k, s) {
  101188. return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
  101189. }
  101190. module.exports = RIPEMD160
  101191. },{"buffer":193,"hash-base":283,"inherits":320}],561:[function(require,module,exports){
  101192. /* eslint-disable node/no-deprecated-api */
  101193. var buffer = require('buffer')
  101194. var Buffer = buffer.Buffer
  101195. // alternative to using Object.keys for old browsers
  101196. function copyProps (src, dst) {
  101197. for (var key in src) {
  101198. dst[key] = src[key]
  101199. }
  101200. }
  101201. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  101202. module.exports = buffer
  101203. } else {
  101204. // Copy properties from require('buffer')
  101205. copyProps(buffer, exports)
  101206. exports.Buffer = SafeBuffer
  101207. }
  101208. function SafeBuffer (arg, encodingOrOffset, length) {
  101209. return Buffer(arg, encodingOrOffset, length)
  101210. }
  101211. // Copy static methods from Buffer
  101212. copyProps(Buffer, SafeBuffer)
  101213. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  101214. if (typeof arg === 'number') {
  101215. throw new TypeError('Argument must not be a number')
  101216. }
  101217. return Buffer(arg, encodingOrOffset, length)
  101218. }
  101219. SafeBuffer.alloc = function (size, fill, encoding) {
  101220. if (typeof size !== 'number') {
  101221. throw new TypeError('Argument must be a number')
  101222. }
  101223. var buf = Buffer(size)
  101224. if (fill !== undefined) {
  101225. if (typeof encoding === 'string') {
  101226. buf.fill(fill, encoding)
  101227. } else {
  101228. buf.fill(fill)
  101229. }
  101230. } else {
  101231. buf.fill(0)
  101232. }
  101233. return buf
  101234. }
  101235. SafeBuffer.allocUnsafe = function (size) {
  101236. if (typeof size !== 'number') {
  101237. throw new TypeError('Argument must be a number')
  101238. }
  101239. return Buffer(size)
  101240. }
  101241. SafeBuffer.allocUnsafeSlow = function (size) {
  101242. if (typeof size !== 'number') {
  101243. throw new TypeError('Argument must be a number')
  101244. }
  101245. return buffer.SlowBuffer(size)
  101246. }
  101247. },{"buffer":193}],562:[function(require,module,exports){
  101248. (function (process){(function (){
  101249. /* eslint-disable node/no-deprecated-api */
  101250. 'use strict'
  101251. var buffer = require('buffer')
  101252. var Buffer = buffer.Buffer
  101253. var safer = {}
  101254. var key
  101255. for (key in buffer) {
  101256. if (!buffer.hasOwnProperty(key)) continue
  101257. if (key === 'SlowBuffer' || key === 'Buffer') continue
  101258. safer[key] = buffer[key]
  101259. }
  101260. var Safer = safer.Buffer = {}
  101261. for (key in Buffer) {
  101262. if (!Buffer.hasOwnProperty(key)) continue
  101263. if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
  101264. Safer[key] = Buffer[key]
  101265. }
  101266. safer.Buffer.prototype = Buffer.prototype
  101267. if (!Safer.from || Safer.from === Uint8Array.from) {
  101268. Safer.from = function (value, encodingOrOffset, length) {
  101269. if (typeof value === 'number') {
  101270. throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
  101271. }
  101272. if (value && typeof value.length === 'undefined') {
  101273. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
  101274. }
  101275. return Buffer(value, encodingOrOffset, length)
  101276. }
  101277. }
  101278. if (!Safer.alloc) {
  101279. Safer.alloc = function (size, fill, encoding) {
  101280. if (typeof size !== 'number') {
  101281. throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
  101282. }
  101283. if (size < 0 || size >= 2 * (1 << 30)) {
  101284. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  101285. }
  101286. var buf = Buffer(size)
  101287. if (!fill || fill.length === 0) {
  101288. buf.fill(0)
  101289. } else if (typeof encoding === 'string') {
  101290. buf.fill(fill, encoding)
  101291. } else {
  101292. buf.fill(fill)
  101293. }
  101294. return buf
  101295. }
  101296. }
  101297. if (!safer.kStringMaxLength) {
  101298. try {
  101299. safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
  101300. } catch (e) {
  101301. // we can't determine kStringMaxLength in environments where process.binding
  101302. // is unsupported, so let's not set it
  101303. }
  101304. }
  101305. if (!safer.constants) {
  101306. safer.constants = {
  101307. MAX_LENGTH: safer.kMaxLength
  101308. }
  101309. if (safer.kStringMaxLength) {
  101310. safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
  101311. }
  101312. }
  101313. module.exports = safer
  101314. }).call(this)}).call(this,require('_process'))
  101315. },{"_process":525,"buffer":193}],563:[function(require,module,exports){
  101316. (function (Buffer){(function (){
  101317. ;(function (sax) { // wrapper for non-node envs
  101318. sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
  101319. sax.SAXParser = SAXParser
  101320. sax.SAXStream = SAXStream
  101321. sax.createStream = createStream
  101322. // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
  101323. // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
  101324. // since that's the earliest that a buffer overrun could occur. This way, checks are
  101325. // as rare as required, but as often as necessary to ensure never crossing this bound.
  101326. // Furthermore, buffers are only tested at most once per write(), so passing a very
  101327. // large string into write() might have undesirable effects, but this is manageable by
  101328. // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
  101329. // edge case, result in creating at most one complete copy of the string passed in.
  101330. // Set to Infinity to have unlimited buffers.
  101331. sax.MAX_BUFFER_LENGTH = 64 * 1024
  101332. var buffers = [
  101333. 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
  101334. 'procInstName', 'procInstBody', 'entity', 'attribName',
  101335. 'attribValue', 'cdata', 'script'
  101336. ]
  101337. sax.EVENTS = [
  101338. 'text',
  101339. 'processinginstruction',
  101340. 'sgmldeclaration',
  101341. 'doctype',
  101342. 'comment',
  101343. 'opentagstart',
  101344. 'attribute',
  101345. 'opentag',
  101346. 'closetag',
  101347. 'opencdata',
  101348. 'cdata',
  101349. 'closecdata',
  101350. 'error',
  101351. 'end',
  101352. 'ready',
  101353. 'script',
  101354. 'opennamespace',
  101355. 'closenamespace'
  101356. ]
  101357. function SAXParser (strict, opt) {
  101358. if (!(this instanceof SAXParser)) {
  101359. return new SAXParser(strict, opt)
  101360. }
  101361. var parser = this
  101362. clearBuffers(parser)
  101363. parser.q = parser.c = ''
  101364. parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
  101365. parser.opt = opt || {}
  101366. parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
  101367. parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
  101368. parser.tags = []
  101369. parser.closed = parser.closedRoot = parser.sawRoot = false
  101370. parser.tag = parser.error = null
  101371. parser.strict = !!strict
  101372. parser.noscript = !!(strict || parser.opt.noscript)
  101373. parser.state = S.BEGIN
  101374. parser.strictEntities = parser.opt.strictEntities
  101375. parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
  101376. parser.attribList = []
  101377. // namespaces form a prototype chain.
  101378. // it always points at the current tag,
  101379. // which protos to its parent tag.
  101380. if (parser.opt.xmlns) {
  101381. parser.ns = Object.create(rootNS)
  101382. }
  101383. // mostly just for error reporting
  101384. parser.trackPosition = parser.opt.position !== false
  101385. if (parser.trackPosition) {
  101386. parser.position = parser.line = parser.column = 0
  101387. }
  101388. emit(parser, 'onready')
  101389. }
  101390. if (!Object.create) {
  101391. Object.create = function (o) {
  101392. function F () {}
  101393. F.prototype = o
  101394. var newf = new F()
  101395. return newf
  101396. }
  101397. }
  101398. if (!Object.keys) {
  101399. Object.keys = function (o) {
  101400. var a = []
  101401. for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
  101402. return a
  101403. }
  101404. }
  101405. function checkBufferLength (parser) {
  101406. var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
  101407. var maxActual = 0
  101408. for (var i = 0, l = buffers.length; i < l; i++) {
  101409. var len = parser[buffers[i]].length
  101410. if (len > maxAllowed) {
  101411. // Text/cdata nodes can get big, and since they're buffered,
  101412. // we can get here under normal conditions.
  101413. // Avoid issues by emitting the text node now,
  101414. // so at least it won't get any bigger.
  101415. switch (buffers[i]) {
  101416. case 'textNode':
  101417. closeText(parser)
  101418. break
  101419. case 'cdata':
  101420. emitNode(parser, 'oncdata', parser.cdata)
  101421. parser.cdata = ''
  101422. break
  101423. case 'script':
  101424. emitNode(parser, 'onscript', parser.script)
  101425. parser.script = ''
  101426. break
  101427. default:
  101428. error(parser, 'Max buffer length exceeded: ' + buffers[i])
  101429. }
  101430. }
  101431. maxActual = Math.max(maxActual, len)
  101432. }
  101433. // schedule the next check for the earliest possible buffer overrun.
  101434. var m = sax.MAX_BUFFER_LENGTH - maxActual
  101435. parser.bufferCheckPosition = m + parser.position
  101436. }
  101437. function clearBuffers (parser) {
  101438. for (var i = 0, l = buffers.length; i < l; i++) {
  101439. parser[buffers[i]] = ''
  101440. }
  101441. }
  101442. function flushBuffers (parser) {
  101443. closeText(parser)
  101444. if (parser.cdata !== '') {
  101445. emitNode(parser, 'oncdata', parser.cdata)
  101446. parser.cdata = ''
  101447. }
  101448. if (parser.script !== '') {
  101449. emitNode(parser, 'onscript', parser.script)
  101450. parser.script = ''
  101451. }
  101452. }
  101453. SAXParser.prototype = {
  101454. end: function () { end(this) },
  101455. write: write,
  101456. resume: function () { this.error = null; return this },
  101457. close: function () { return this.write(null) },
  101458. flush: function () { flushBuffers(this) }
  101459. }
  101460. var Stream
  101461. try {
  101462. Stream = require('stream').Stream
  101463. } catch (ex) {
  101464. Stream = function () {}
  101465. }
  101466. var streamWraps = sax.EVENTS.filter(function (ev) {
  101467. return ev !== 'error' && ev !== 'end'
  101468. })
  101469. function createStream (strict, opt) {
  101470. return new SAXStream(strict, opt)
  101471. }
  101472. function SAXStream (strict, opt) {
  101473. if (!(this instanceof SAXStream)) {
  101474. return new SAXStream(strict, opt)
  101475. }
  101476. Stream.apply(this)
  101477. this._parser = new SAXParser(strict, opt)
  101478. this.writable = true
  101479. this.readable = true
  101480. var me = this
  101481. this._parser.onend = function () {
  101482. me.emit('end')
  101483. }
  101484. this._parser.onerror = function (er) {
  101485. me.emit('error', er)
  101486. // if didn't throw, then means error was handled.
  101487. // go ahead and clear error, so we can write again.
  101488. me._parser.error = null
  101489. }
  101490. this._decoder = null
  101491. streamWraps.forEach(function (ev) {
  101492. Object.defineProperty(me, 'on' + ev, {
  101493. get: function () {
  101494. return me._parser['on' + ev]
  101495. },
  101496. set: function (h) {
  101497. if (!h) {
  101498. me.removeAllListeners(ev)
  101499. me._parser['on' + ev] = h
  101500. return h
  101501. }
  101502. me.on(ev, h)
  101503. },
  101504. enumerable: true,
  101505. configurable: false
  101506. })
  101507. })
  101508. }
  101509. SAXStream.prototype = Object.create(Stream.prototype, {
  101510. constructor: {
  101511. value: SAXStream
  101512. }
  101513. })
  101514. SAXStream.prototype.write = function (data) {
  101515. if (typeof Buffer === 'function' &&
  101516. typeof Buffer.isBuffer === 'function' &&
  101517. Buffer.isBuffer(data)) {
  101518. if (!this._decoder) {
  101519. var SD = require('string_decoder').StringDecoder
  101520. this._decoder = new SD('utf8')
  101521. }
  101522. data = this._decoder.write(data)
  101523. }
  101524. this._parser.write(data.toString())
  101525. this.emit('data', data)
  101526. return true
  101527. }
  101528. SAXStream.prototype.end = function (chunk) {
  101529. if (chunk && chunk.length) {
  101530. this.write(chunk)
  101531. }
  101532. this._parser.end()
  101533. return true
  101534. }
  101535. SAXStream.prototype.on = function (ev, handler) {
  101536. var me = this
  101537. if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
  101538. me._parser['on' + ev] = function () {
  101539. var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
  101540. args.splice(0, 0, ev)
  101541. me.emit.apply(me, args)
  101542. }
  101543. }
  101544. return Stream.prototype.on.call(me, ev, handler)
  101545. }
  101546. // this really needs to be replaced with character classes.
  101547. // XML allows all manner of ridiculous numbers and digits.
  101548. var CDATA = '[CDATA['
  101549. var DOCTYPE = 'DOCTYPE'
  101550. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
  101551. var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
  101552. var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
  101553. // http://www.w3.org/TR/REC-xml/#NT-NameStartChar
  101554. // This implementation works on strings, a single character at a time
  101555. // as such, it cannot ever support astral-plane characters (10000-EFFFF)
  101556. // without a significant breaking change to either this parser, or the
  101557. // JavaScript language. Implementation of an emoji-capable xml parser
  101558. // is left as an exercise for the reader.
  101559. var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
  101560. var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/
  101561. var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
  101562. var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/
  101563. function isWhitespace (c) {
  101564. return c === ' ' || c === '\n' || c === '\r' || c === '\t'
  101565. }
  101566. function isQuote (c) {
  101567. return c === '"' || c === '\''
  101568. }
  101569. function isAttribEnd (c) {
  101570. return c === '>' || isWhitespace(c)
  101571. }
  101572. function isMatch (regex, c) {
  101573. return regex.test(c)
  101574. }
  101575. function notMatch (regex, c) {
  101576. return !isMatch(regex, c)
  101577. }
  101578. var S = 0
  101579. sax.STATE = {
  101580. BEGIN: S++, // leading byte order mark or whitespace
  101581. BEGIN_WHITESPACE: S++, // leading whitespace
  101582. TEXT: S++, // general stuff
  101583. TEXT_ENTITY: S++, // &amp and such.
  101584. OPEN_WAKA: S++, // <
  101585. SGML_DECL: S++, // <!BLARG
  101586. SGML_DECL_QUOTED: S++, // <!BLARG foo "bar
  101587. DOCTYPE: S++, // <!DOCTYPE
  101588. DOCTYPE_QUOTED: S++, // <!DOCTYPE "//blah
  101589. DOCTYPE_DTD: S++, // <!DOCTYPE "//blah" [ ...
  101590. DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE "//blah" [ "foo
  101591. COMMENT_STARTING: S++, // <!-
  101592. COMMENT: S++, // <!--
  101593. COMMENT_ENDING: S++, // <!-- blah -
  101594. COMMENT_ENDED: S++, // <!-- blah --
  101595. CDATA: S++, // <![CDATA[ something
  101596. CDATA_ENDING: S++, // ]
  101597. CDATA_ENDING_2: S++, // ]]
  101598. PROC_INST: S++, // <?hi
  101599. PROC_INST_BODY: S++, // <?hi there
  101600. PROC_INST_ENDING: S++, // <?hi "there" ?
  101601. OPEN_TAG: S++, // <strong
  101602. OPEN_TAG_SLASH: S++, // <strong /
  101603. ATTRIB: S++, // <a
  101604. ATTRIB_NAME: S++, // <a foo
  101605. ATTRIB_NAME_SAW_WHITE: S++, // <a foo _
  101606. ATTRIB_VALUE: S++, // <a foo=
  101607. ATTRIB_VALUE_QUOTED: S++, // <a foo="bar
  101608. ATTRIB_VALUE_CLOSED: S++, // <a foo="bar"
  101609. ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar
  101610. ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar="&quot;"
  101611. ATTRIB_VALUE_ENTITY_U: S++, // <foo bar=&quot
  101612. CLOSE_TAG: S++, // </a
  101613. CLOSE_TAG_SAW_WHITE: S++, // </a >
  101614. SCRIPT: S++, // <script> ...
  101615. SCRIPT_ENDING: S++ // <script> ... <
  101616. }
  101617. sax.XML_ENTITIES = {
  101618. 'amp': '&',
  101619. 'gt': '>',
  101620. 'lt': '<',
  101621. 'quot': '"',
  101622. 'apos': "'"
  101623. }
  101624. sax.ENTITIES = {
  101625. 'amp': '&',
  101626. 'gt': '>',
  101627. 'lt': '<',
  101628. 'quot': '"',
  101629. 'apos': "'",
  101630. 'AElig': 198,
  101631. 'Aacute': 193,
  101632. 'Acirc': 194,
  101633. 'Agrave': 192,
  101634. 'Aring': 197,
  101635. 'Atilde': 195,
  101636. 'Auml': 196,
  101637. 'Ccedil': 199,
  101638. 'ETH': 208,
  101639. 'Eacute': 201,
  101640. 'Ecirc': 202,
  101641. 'Egrave': 200,
  101642. 'Euml': 203,
  101643. 'Iacute': 205,
  101644. 'Icirc': 206,
  101645. 'Igrave': 204,
  101646. 'Iuml': 207,
  101647. 'Ntilde': 209,
  101648. 'Oacute': 211,
  101649. 'Ocirc': 212,
  101650. 'Ograve': 210,
  101651. 'Oslash': 216,
  101652. 'Otilde': 213,
  101653. 'Ouml': 214,
  101654. 'THORN': 222,
  101655. 'Uacute': 218,
  101656. 'Ucirc': 219,
  101657. 'Ugrave': 217,
  101658. 'Uuml': 220,
  101659. 'Yacute': 221,
  101660. 'aacute': 225,
  101661. 'acirc': 226,
  101662. 'aelig': 230,
  101663. 'agrave': 224,
  101664. 'aring': 229,
  101665. 'atilde': 227,
  101666. 'auml': 228,
  101667. 'ccedil': 231,
  101668. 'eacute': 233,
  101669. 'ecirc': 234,
  101670. 'egrave': 232,
  101671. 'eth': 240,
  101672. 'euml': 235,
  101673. 'iacute': 237,
  101674. 'icirc': 238,
  101675. 'igrave': 236,
  101676. 'iuml': 239,
  101677. 'ntilde': 241,
  101678. 'oacute': 243,
  101679. 'ocirc': 244,
  101680. 'ograve': 242,
  101681. 'oslash': 248,
  101682. 'otilde': 245,
  101683. 'ouml': 246,
  101684. 'szlig': 223,
  101685. 'thorn': 254,
  101686. 'uacute': 250,
  101687. 'ucirc': 251,
  101688. 'ugrave': 249,
  101689. 'uuml': 252,
  101690. 'yacute': 253,
  101691. 'yuml': 255,
  101692. 'copy': 169,
  101693. 'reg': 174,
  101694. 'nbsp': 160,
  101695. 'iexcl': 161,
  101696. 'cent': 162,
  101697. 'pound': 163,
  101698. 'curren': 164,
  101699. 'yen': 165,
  101700. 'brvbar': 166,
  101701. 'sect': 167,
  101702. 'uml': 168,
  101703. 'ordf': 170,
  101704. 'laquo': 171,
  101705. 'not': 172,
  101706. 'shy': 173,
  101707. 'macr': 175,
  101708. 'deg': 176,
  101709. 'plusmn': 177,
  101710. 'sup1': 185,
  101711. 'sup2': 178,
  101712. 'sup3': 179,
  101713. 'acute': 180,
  101714. 'micro': 181,
  101715. 'para': 182,
  101716. 'middot': 183,
  101717. 'cedil': 184,
  101718. 'ordm': 186,
  101719. 'raquo': 187,
  101720. 'frac14': 188,
  101721. 'frac12': 189,
  101722. 'frac34': 190,
  101723. 'iquest': 191,
  101724. 'times': 215,
  101725. 'divide': 247,
  101726. 'OElig': 338,
  101727. 'oelig': 339,
  101728. 'Scaron': 352,
  101729. 'scaron': 353,
  101730. 'Yuml': 376,
  101731. 'fnof': 402,
  101732. 'circ': 710,
  101733. 'tilde': 732,
  101734. 'Alpha': 913,
  101735. 'Beta': 914,
  101736. 'Gamma': 915,
  101737. 'Delta': 916,
  101738. 'Epsilon': 917,
  101739. 'Zeta': 918,
  101740. 'Eta': 919,
  101741. 'Theta': 920,
  101742. 'Iota': 921,
  101743. 'Kappa': 922,
  101744. 'Lambda': 923,
  101745. 'Mu': 924,
  101746. 'Nu': 925,
  101747. 'Xi': 926,
  101748. 'Omicron': 927,
  101749. 'Pi': 928,
  101750. 'Rho': 929,
  101751. 'Sigma': 931,
  101752. 'Tau': 932,
  101753. 'Upsilon': 933,
  101754. 'Phi': 934,
  101755. 'Chi': 935,
  101756. 'Psi': 936,
  101757. 'Omega': 937,
  101758. 'alpha': 945,
  101759. 'beta': 946,
  101760. 'gamma': 947,
  101761. 'delta': 948,
  101762. 'epsilon': 949,
  101763. 'zeta': 950,
  101764. 'eta': 951,
  101765. 'theta': 952,
  101766. 'iota': 953,
  101767. 'kappa': 954,
  101768. 'lambda': 955,
  101769. 'mu': 956,
  101770. 'nu': 957,
  101771. 'xi': 958,
  101772. 'omicron': 959,
  101773. 'pi': 960,
  101774. 'rho': 961,
  101775. 'sigmaf': 962,
  101776. 'sigma': 963,
  101777. 'tau': 964,
  101778. 'upsilon': 965,
  101779. 'phi': 966,
  101780. 'chi': 967,
  101781. 'psi': 968,
  101782. 'omega': 969,
  101783. 'thetasym': 977,
  101784. 'upsih': 978,
  101785. 'piv': 982,
  101786. 'ensp': 8194,
  101787. 'emsp': 8195,
  101788. 'thinsp': 8201,
  101789. 'zwnj': 8204,
  101790. 'zwj': 8205,
  101791. 'lrm': 8206,
  101792. 'rlm': 8207,
  101793. 'ndash': 8211,
  101794. 'mdash': 8212,
  101795. 'lsquo': 8216,
  101796. 'rsquo': 8217,
  101797. 'sbquo': 8218,
  101798. 'ldquo': 8220,
  101799. 'rdquo': 8221,
  101800. 'bdquo': 8222,
  101801. 'dagger': 8224,
  101802. 'Dagger': 8225,
  101803. 'bull': 8226,
  101804. 'hellip': 8230,
  101805. 'permil': 8240,
  101806. 'prime': 8242,
  101807. 'Prime': 8243,
  101808. 'lsaquo': 8249,
  101809. 'rsaquo': 8250,
  101810. 'oline': 8254,
  101811. 'frasl': 8260,
  101812. 'euro': 8364,
  101813. 'image': 8465,
  101814. 'weierp': 8472,
  101815. 'real': 8476,
  101816. 'trade': 8482,
  101817. 'alefsym': 8501,
  101818. 'larr': 8592,
  101819. 'uarr': 8593,
  101820. 'rarr': 8594,
  101821. 'darr': 8595,
  101822. 'harr': 8596,
  101823. 'crarr': 8629,
  101824. 'lArr': 8656,
  101825. 'uArr': 8657,
  101826. 'rArr': 8658,
  101827. 'dArr': 8659,
  101828. 'hArr': 8660,
  101829. 'forall': 8704,
  101830. 'part': 8706,
  101831. 'exist': 8707,
  101832. 'empty': 8709,
  101833. 'nabla': 8711,
  101834. 'isin': 8712,
  101835. 'notin': 8713,
  101836. 'ni': 8715,
  101837. 'prod': 8719,
  101838. 'sum': 8721,
  101839. 'minus': 8722,
  101840. 'lowast': 8727,
  101841. 'radic': 8730,
  101842. 'prop': 8733,
  101843. 'infin': 8734,
  101844. 'ang': 8736,
  101845. 'and': 8743,
  101846. 'or': 8744,
  101847. 'cap': 8745,
  101848. 'cup': 8746,
  101849. 'int': 8747,
  101850. 'there4': 8756,
  101851. 'sim': 8764,
  101852. 'cong': 8773,
  101853. 'asymp': 8776,
  101854. 'ne': 8800,
  101855. 'equiv': 8801,
  101856. 'le': 8804,
  101857. 'ge': 8805,
  101858. 'sub': 8834,
  101859. 'sup': 8835,
  101860. 'nsub': 8836,
  101861. 'sube': 8838,
  101862. 'supe': 8839,
  101863. 'oplus': 8853,
  101864. 'otimes': 8855,
  101865. 'perp': 8869,
  101866. 'sdot': 8901,
  101867. 'lceil': 8968,
  101868. 'rceil': 8969,
  101869. 'lfloor': 8970,
  101870. 'rfloor': 8971,
  101871. 'lang': 9001,
  101872. 'rang': 9002,
  101873. 'loz': 9674,
  101874. 'spades': 9824,
  101875. 'clubs': 9827,
  101876. 'hearts': 9829,
  101877. 'diams': 9830
  101878. }
  101879. Object.keys(sax.ENTITIES).forEach(function (key) {
  101880. var e = sax.ENTITIES[key]
  101881. var s = typeof e === 'number' ? String.fromCharCode(e) : e
  101882. sax.ENTITIES[key] = s
  101883. })
  101884. for (var s in sax.STATE) {
  101885. sax.STATE[sax.STATE[s]] = s
  101886. }
  101887. // shorthand
  101888. S = sax.STATE
  101889. function emit (parser, event, data) {
  101890. parser[event] && parser[event](data)
  101891. }
  101892. function emitNode (parser, nodeType, data) {
  101893. if (parser.textNode) closeText(parser)
  101894. emit(parser, nodeType, data)
  101895. }
  101896. function closeText (parser) {
  101897. parser.textNode = textopts(parser.opt, parser.textNode)
  101898. if (parser.textNode) emit(parser, 'ontext', parser.textNode)
  101899. parser.textNode = ''
  101900. }
  101901. function textopts (opt, text) {
  101902. if (opt.trim) text = text.trim()
  101903. if (opt.normalize) text = text.replace(/\s+/g, ' ')
  101904. return text
  101905. }
  101906. function error (parser, er) {
  101907. closeText(parser)
  101908. if (parser.trackPosition) {
  101909. er += '\nLine: ' + parser.line +
  101910. '\nColumn: ' + parser.column +
  101911. '\nChar: ' + parser.c
  101912. }
  101913. er = new Error(er)
  101914. parser.error = er
  101915. emit(parser, 'onerror', er)
  101916. return parser
  101917. }
  101918. function end (parser) {
  101919. if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag')
  101920. if ((parser.state !== S.BEGIN) &&
  101921. (parser.state !== S.BEGIN_WHITESPACE) &&
  101922. (parser.state !== S.TEXT)) {
  101923. error(parser, 'Unexpected end')
  101924. }
  101925. closeText(parser)
  101926. parser.c = ''
  101927. parser.closed = true
  101928. emit(parser, 'onend')
  101929. SAXParser.call(parser, parser.strict, parser.opt)
  101930. return parser
  101931. }
  101932. function strictFail (parser, message) {
  101933. if (typeof parser !== 'object' || !(parser instanceof SAXParser)) {
  101934. throw new Error('bad call to strictFail')
  101935. }
  101936. if (parser.strict) {
  101937. error(parser, message)
  101938. }
  101939. }
  101940. function newTag (parser) {
  101941. if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]()
  101942. var parent = parser.tags[parser.tags.length - 1] || parser
  101943. var tag = parser.tag = { name: parser.tagName, attributes: {} }
  101944. // will be overridden if tag contails an xmlns="foo" or xmlns:foo="bar"
  101945. if (parser.opt.xmlns) {
  101946. tag.ns = parent.ns
  101947. }
  101948. parser.attribList.length = 0
  101949. emitNode(parser, 'onopentagstart', tag)
  101950. }
  101951. function qname (name, attribute) {
  101952. var i = name.indexOf(':')
  101953. var qualName = i < 0 ? [ '', name ] : name.split(':')
  101954. var prefix = qualName[0]
  101955. var local = qualName[1]
  101956. // <x "xmlns"="http://foo">
  101957. if (attribute && name === 'xmlns') {
  101958. prefix = 'xmlns'
  101959. local = ''
  101960. }
  101961. return { prefix: prefix, local: local }
  101962. }
  101963. function attrib (parser) {
  101964. if (!parser.strict) {
  101965. parser.attribName = parser.attribName[parser.looseCase]()
  101966. }
  101967. if (parser.attribList.indexOf(parser.attribName) !== -1 ||
  101968. parser.tag.attributes.hasOwnProperty(parser.attribName)) {
  101969. parser.attribName = parser.attribValue = ''
  101970. return
  101971. }
  101972. if (parser.opt.xmlns) {
  101973. var qn = qname(parser.attribName, true)
  101974. var prefix = qn.prefix
  101975. var local = qn.local
  101976. if (prefix === 'xmlns') {
  101977. // namespace binding attribute. push the binding into scope
  101978. if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {
  101979. strictFail(parser,
  101980. 'xml: prefix must be bound to ' + XML_NAMESPACE + '\n' +
  101981. 'Actual: ' + parser.attribValue)
  101982. } else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {
  101983. strictFail(parser,
  101984. 'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\n' +
  101985. 'Actual: ' + parser.attribValue)
  101986. } else {
  101987. var tag = parser.tag
  101988. var parent = parser.tags[parser.tags.length - 1] || parser
  101989. if (tag.ns === parent.ns) {
  101990. tag.ns = Object.create(parent.ns)
  101991. }
  101992. tag.ns[local] = parser.attribValue
  101993. }
  101994. }
  101995. // defer onattribute events until all attributes have been seen
  101996. // so any new bindings can take effect. preserve attribute order
  101997. // so deferred events can be emitted in document order
  101998. parser.attribList.push([parser.attribName, parser.attribValue])
  101999. } else {
  102000. // in non-xmlns mode, we can emit the event right away
  102001. parser.tag.attributes[parser.attribName] = parser.attribValue
  102002. emitNode(parser, 'onattribute', {
  102003. name: parser.attribName,
  102004. value: parser.attribValue
  102005. })
  102006. }
  102007. parser.attribName = parser.attribValue = ''
  102008. }
  102009. function openTag (parser, selfClosing) {
  102010. if (parser.opt.xmlns) {
  102011. // emit namespace binding events
  102012. var tag = parser.tag
  102013. // add namespace info to tag
  102014. var qn = qname(parser.tagName)
  102015. tag.prefix = qn.prefix
  102016. tag.local = qn.local
  102017. tag.uri = tag.ns[qn.prefix] || ''
  102018. if (tag.prefix && !tag.uri) {
  102019. strictFail(parser, 'Unbound namespace prefix: ' +
  102020. JSON.stringify(parser.tagName))
  102021. tag.uri = qn.prefix
  102022. }
  102023. var parent = parser.tags[parser.tags.length - 1] || parser
  102024. if (tag.ns && parent.ns !== tag.ns) {
  102025. Object.keys(tag.ns).forEach(function (p) {
  102026. emitNode(parser, 'onopennamespace', {
  102027. prefix: p,
  102028. uri: tag.ns[p]
  102029. })
  102030. })
  102031. }
  102032. // handle deferred onattribute events
  102033. // Note: do not apply default ns to attributes:
  102034. // http://www.w3.org/TR/REC-xml-names/#defaulting
  102035. for (var i = 0, l = parser.attribList.length; i < l; i++) {
  102036. var nv = parser.attribList[i]
  102037. var name = nv[0]
  102038. var value = nv[1]
  102039. var qualName = qname(name, true)
  102040. var prefix = qualName.prefix
  102041. var local = qualName.local
  102042. var uri = prefix === '' ? '' : (tag.ns[prefix] || '')
  102043. var a = {
  102044. name: name,
  102045. value: value,
  102046. prefix: prefix,
  102047. local: local,
  102048. uri: uri
  102049. }
  102050. // if there's any attributes with an undefined namespace,
  102051. // then fail on them now.
  102052. if (prefix && prefix !== 'xmlns' && !uri) {
  102053. strictFail(parser, 'Unbound namespace prefix: ' +
  102054. JSON.stringify(prefix))
  102055. a.uri = prefix
  102056. }
  102057. parser.tag.attributes[name] = a
  102058. emitNode(parser, 'onattribute', a)
  102059. }
  102060. parser.attribList.length = 0
  102061. }
  102062. parser.tag.isSelfClosing = !!selfClosing
  102063. // process the tag
  102064. parser.sawRoot = true
  102065. parser.tags.push(parser.tag)
  102066. emitNode(parser, 'onopentag', parser.tag)
  102067. if (!selfClosing) {
  102068. // special case for <script> in non-strict mode.
  102069. if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {
  102070. parser.state = S.SCRIPT
  102071. } else {
  102072. parser.state = S.TEXT
  102073. }
  102074. parser.tag = null
  102075. parser.tagName = ''
  102076. }
  102077. parser.attribName = parser.attribValue = ''
  102078. parser.attribList.length = 0
  102079. }
  102080. function closeTag (parser) {
  102081. if (!parser.tagName) {
  102082. strictFail(parser, 'Weird empty close tag.')
  102083. parser.textNode += '</>'
  102084. parser.state = S.TEXT
  102085. return
  102086. }
  102087. if (parser.script) {
  102088. if (parser.tagName !== 'script') {
  102089. parser.script += '</' + parser.tagName + '>'
  102090. parser.tagName = ''
  102091. parser.state = S.SCRIPT
  102092. return
  102093. }
  102094. emitNode(parser, 'onscript', parser.script)
  102095. parser.script = ''
  102096. }
  102097. // first make sure that the closing tag actually exists.
  102098. // <a><b></c></b></a> will close everything, otherwise.
  102099. var t = parser.tags.length
  102100. var tagName = parser.tagName
  102101. if (!parser.strict) {
  102102. tagName = tagName[parser.looseCase]()
  102103. }
  102104. var closeTo = tagName
  102105. while (t--) {
  102106. var close = parser.tags[t]
  102107. if (close.name !== closeTo) {
  102108. // fail the first time in strict mode
  102109. strictFail(parser, 'Unexpected close tag')
  102110. } else {
  102111. break
  102112. }
  102113. }
  102114. // didn't find it. we already failed for strict, so just abort.
  102115. if (t < 0) {
  102116. strictFail(parser, 'Unmatched closing tag: ' + parser.tagName)
  102117. parser.textNode += '</' + parser.tagName + '>'
  102118. parser.state = S.TEXT
  102119. return
  102120. }
  102121. parser.tagName = tagName
  102122. var s = parser.tags.length
  102123. while (s-- > t) {
  102124. var tag = parser.tag = parser.tags.pop()
  102125. parser.tagName = parser.tag.name
  102126. emitNode(parser, 'onclosetag', parser.tagName)
  102127. var x = {}
  102128. for (var i in tag.ns) {
  102129. x[i] = tag.ns[i]
  102130. }
  102131. var parent = parser.tags[parser.tags.length - 1] || parser
  102132. if (parser.opt.xmlns && tag.ns !== parent.ns) {
  102133. // remove namespace bindings introduced by tag
  102134. Object.keys(tag.ns).forEach(function (p) {
  102135. var n = tag.ns[p]
  102136. emitNode(parser, 'onclosenamespace', { prefix: p, uri: n })
  102137. })
  102138. }
  102139. }
  102140. if (t === 0) parser.closedRoot = true
  102141. parser.tagName = parser.attribValue = parser.attribName = ''
  102142. parser.attribList.length = 0
  102143. parser.state = S.TEXT
  102144. }
  102145. function parseEntity (parser) {
  102146. var entity = parser.entity
  102147. var entityLC = entity.toLowerCase()
  102148. var num
  102149. var numStr = ''
  102150. if (parser.ENTITIES[entity]) {
  102151. return parser.ENTITIES[entity]
  102152. }
  102153. if (parser.ENTITIES[entityLC]) {
  102154. return parser.ENTITIES[entityLC]
  102155. }
  102156. entity = entityLC
  102157. if (entity.charAt(0) === '#') {
  102158. if (entity.charAt(1) === 'x') {
  102159. entity = entity.slice(2)
  102160. num = parseInt(entity, 16)
  102161. numStr = num.toString(16)
  102162. } else {
  102163. entity = entity.slice(1)
  102164. num = parseInt(entity, 10)
  102165. numStr = num.toString(10)
  102166. }
  102167. }
  102168. entity = entity.replace(/^0+/, '')
  102169. if (isNaN(num) || numStr.toLowerCase() !== entity) {
  102170. strictFail(parser, 'Invalid character entity')
  102171. return '&' + parser.entity + ';'
  102172. }
  102173. return String.fromCodePoint(num)
  102174. }
  102175. function beginWhiteSpace (parser, c) {
  102176. if (c === '<') {
  102177. parser.state = S.OPEN_WAKA
  102178. parser.startTagPosition = parser.position
  102179. } else if (!isWhitespace(c)) {
  102180. // have to process this as a text node.
  102181. // weird, but happens.
  102182. strictFail(parser, 'Non-whitespace before first tag.')
  102183. parser.textNode = c
  102184. parser.state = S.TEXT
  102185. }
  102186. }
  102187. function charAt (chunk, i) {
  102188. var result = ''
  102189. if (i < chunk.length) {
  102190. result = chunk.charAt(i)
  102191. }
  102192. return result
  102193. }
  102194. function write (chunk) {
  102195. var parser = this
  102196. if (this.error) {
  102197. throw this.error
  102198. }
  102199. if (parser.closed) {
  102200. return error(parser,
  102201. 'Cannot write after close. Assign an onready handler.')
  102202. }
  102203. if (chunk === null) {
  102204. return end(parser)
  102205. }
  102206. if (typeof chunk === 'object') {
  102207. chunk = chunk.toString()
  102208. }
  102209. var i = 0
  102210. var c = ''
  102211. while (true) {
  102212. c = charAt(chunk, i++)
  102213. parser.c = c
  102214. if (!c) {
  102215. break
  102216. }
  102217. if (parser.trackPosition) {
  102218. parser.position++
  102219. if (c === '\n') {
  102220. parser.line++
  102221. parser.column = 0
  102222. } else {
  102223. parser.column++
  102224. }
  102225. }
  102226. switch (parser.state) {
  102227. case S.BEGIN:
  102228. parser.state = S.BEGIN_WHITESPACE
  102229. if (c === '\uFEFF') {
  102230. continue
  102231. }
  102232. beginWhiteSpace(parser, c)
  102233. continue
  102234. case S.BEGIN_WHITESPACE:
  102235. beginWhiteSpace(parser, c)
  102236. continue
  102237. case S.TEXT:
  102238. if (parser.sawRoot && !parser.closedRoot) {
  102239. var starti = i - 1
  102240. while (c && c !== '<' && c !== '&') {
  102241. c = charAt(chunk, i++)
  102242. if (c && parser.trackPosition) {
  102243. parser.position++
  102244. if (c === '\n') {
  102245. parser.line++
  102246. parser.column = 0
  102247. } else {
  102248. parser.column++
  102249. }
  102250. }
  102251. }
  102252. parser.textNode += chunk.substring(starti, i - 1)
  102253. }
  102254. if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
  102255. parser.state = S.OPEN_WAKA
  102256. parser.startTagPosition = parser.position
  102257. } else {
  102258. if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) {
  102259. strictFail(parser, 'Text data outside of root node.')
  102260. }
  102261. if (c === '&') {
  102262. parser.state = S.TEXT_ENTITY
  102263. } else {
  102264. parser.textNode += c
  102265. }
  102266. }
  102267. continue
  102268. case S.SCRIPT:
  102269. // only non-strict
  102270. if (c === '<') {
  102271. parser.state = S.SCRIPT_ENDING
  102272. } else {
  102273. parser.script += c
  102274. }
  102275. continue
  102276. case S.SCRIPT_ENDING:
  102277. if (c === '/') {
  102278. parser.state = S.CLOSE_TAG
  102279. } else {
  102280. parser.script += '<' + c
  102281. parser.state = S.SCRIPT
  102282. }
  102283. continue
  102284. case S.OPEN_WAKA:
  102285. // either a /, ?, !, or text is coming next.
  102286. if (c === '!') {
  102287. parser.state = S.SGML_DECL
  102288. parser.sgmlDecl = ''
  102289. } else if (isWhitespace(c)) {
  102290. // wait for it...
  102291. } else if (isMatch(nameStart, c)) {
  102292. parser.state = S.OPEN_TAG
  102293. parser.tagName = c
  102294. } else if (c === '/') {
  102295. parser.state = S.CLOSE_TAG
  102296. parser.tagName = ''
  102297. } else if (c === '?') {
  102298. parser.state = S.PROC_INST
  102299. parser.procInstName = parser.procInstBody = ''
  102300. } else {
  102301. strictFail(parser, 'Unencoded <')
  102302. // if there was some whitespace, then add that in.
  102303. if (parser.startTagPosition + 1 < parser.position) {
  102304. var pad = parser.position - parser.startTagPosition
  102305. c = new Array(pad).join(' ') + c
  102306. }
  102307. parser.textNode += '<' + c
  102308. parser.state = S.TEXT
  102309. }
  102310. continue
  102311. case S.SGML_DECL:
  102312. if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
  102313. emitNode(parser, 'onopencdata')
  102314. parser.state = S.CDATA
  102315. parser.sgmlDecl = ''
  102316. parser.cdata = ''
  102317. } else if (parser.sgmlDecl + c === '--') {
  102318. parser.state = S.COMMENT
  102319. parser.comment = ''
  102320. parser.sgmlDecl = ''
  102321. } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
  102322. parser.state = S.DOCTYPE
  102323. if (parser.doctype || parser.sawRoot) {
  102324. strictFail(parser,
  102325. 'Inappropriately located doctype declaration')
  102326. }
  102327. parser.doctype = ''
  102328. parser.sgmlDecl = ''
  102329. } else if (c === '>') {
  102330. emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl)
  102331. parser.sgmlDecl = ''
  102332. parser.state = S.TEXT
  102333. } else if (isQuote(c)) {
  102334. parser.state = S.SGML_DECL_QUOTED
  102335. parser.sgmlDecl += c
  102336. } else {
  102337. parser.sgmlDecl += c
  102338. }
  102339. continue
  102340. case S.SGML_DECL_QUOTED:
  102341. if (c === parser.q) {
  102342. parser.state = S.SGML_DECL
  102343. parser.q = ''
  102344. }
  102345. parser.sgmlDecl += c
  102346. continue
  102347. case S.DOCTYPE:
  102348. if (c === '>') {
  102349. parser.state = S.TEXT
  102350. emitNode(parser, 'ondoctype', parser.doctype)
  102351. parser.doctype = true // just remember that we saw it.
  102352. } else {
  102353. parser.doctype += c
  102354. if (c === '[') {
  102355. parser.state = S.DOCTYPE_DTD
  102356. } else if (isQuote(c)) {
  102357. parser.state = S.DOCTYPE_QUOTED
  102358. parser.q = c
  102359. }
  102360. }
  102361. continue
  102362. case S.DOCTYPE_QUOTED:
  102363. parser.doctype += c
  102364. if (c === parser.q) {
  102365. parser.q = ''
  102366. parser.state = S.DOCTYPE
  102367. }
  102368. continue
  102369. case S.DOCTYPE_DTD:
  102370. parser.doctype += c
  102371. if (c === ']') {
  102372. parser.state = S.DOCTYPE
  102373. } else if (isQuote(c)) {
  102374. parser.state = S.DOCTYPE_DTD_QUOTED
  102375. parser.q = c
  102376. }
  102377. continue
  102378. case S.DOCTYPE_DTD_QUOTED:
  102379. parser.doctype += c
  102380. if (c === parser.q) {
  102381. parser.state = S.DOCTYPE_DTD
  102382. parser.q = ''
  102383. }
  102384. continue
  102385. case S.COMMENT:
  102386. if (c === '-') {
  102387. parser.state = S.COMMENT_ENDING
  102388. } else {
  102389. parser.comment += c
  102390. }
  102391. continue
  102392. case S.COMMENT_ENDING:
  102393. if (c === '-') {
  102394. parser.state = S.COMMENT_ENDED
  102395. parser.comment = textopts(parser.opt, parser.comment)
  102396. if (parser.comment) {
  102397. emitNode(parser, 'oncomment', parser.comment)
  102398. }
  102399. parser.comment = ''
  102400. } else {
  102401. parser.comment += '-' + c
  102402. parser.state = S.COMMENT
  102403. }
  102404. continue
  102405. case S.COMMENT_ENDED:
  102406. if (c !== '>') {
  102407. strictFail(parser, 'Malformed comment')
  102408. // allow <!-- blah -- bloo --> in non-strict mode,
  102409. // which is a comment of " blah -- bloo "
  102410. parser.comment += '--' + c
  102411. parser.state = S.COMMENT
  102412. } else {
  102413. parser.state = S.TEXT
  102414. }
  102415. continue
  102416. case S.CDATA:
  102417. if (c === ']') {
  102418. parser.state = S.CDATA_ENDING
  102419. } else {
  102420. parser.cdata += c
  102421. }
  102422. continue
  102423. case S.CDATA_ENDING:
  102424. if (c === ']') {
  102425. parser.state = S.CDATA_ENDING_2
  102426. } else {
  102427. parser.cdata += ']' + c
  102428. parser.state = S.CDATA
  102429. }
  102430. continue
  102431. case S.CDATA_ENDING_2:
  102432. if (c === '>') {
  102433. if (parser.cdata) {
  102434. emitNode(parser, 'oncdata', parser.cdata)
  102435. }
  102436. emitNode(parser, 'onclosecdata')
  102437. parser.cdata = ''
  102438. parser.state = S.TEXT
  102439. } else if (c === ']') {
  102440. parser.cdata += ']'
  102441. } else {
  102442. parser.cdata += ']]' + c
  102443. parser.state = S.CDATA
  102444. }
  102445. continue
  102446. case S.PROC_INST:
  102447. if (c === '?') {
  102448. parser.state = S.PROC_INST_ENDING
  102449. } else if (isWhitespace(c)) {
  102450. parser.state = S.PROC_INST_BODY
  102451. } else {
  102452. parser.procInstName += c
  102453. }
  102454. continue
  102455. case S.PROC_INST_BODY:
  102456. if (!parser.procInstBody && isWhitespace(c)) {
  102457. continue
  102458. } else if (c === '?') {
  102459. parser.state = S.PROC_INST_ENDING
  102460. } else {
  102461. parser.procInstBody += c
  102462. }
  102463. continue
  102464. case S.PROC_INST_ENDING:
  102465. if (c === '>') {
  102466. emitNode(parser, 'onprocessinginstruction', {
  102467. name: parser.procInstName,
  102468. body: parser.procInstBody
  102469. })
  102470. parser.procInstName = parser.procInstBody = ''
  102471. parser.state = S.TEXT
  102472. } else {
  102473. parser.procInstBody += '?' + c
  102474. parser.state = S.PROC_INST_BODY
  102475. }
  102476. continue
  102477. case S.OPEN_TAG:
  102478. if (isMatch(nameBody, c)) {
  102479. parser.tagName += c
  102480. } else {
  102481. newTag(parser)
  102482. if (c === '>') {
  102483. openTag(parser)
  102484. } else if (c === '/') {
  102485. parser.state = S.OPEN_TAG_SLASH
  102486. } else {
  102487. if (!isWhitespace(c)) {
  102488. strictFail(parser, 'Invalid character in tag name')
  102489. }
  102490. parser.state = S.ATTRIB
  102491. }
  102492. }
  102493. continue
  102494. case S.OPEN_TAG_SLASH:
  102495. if (c === '>') {
  102496. openTag(parser, true)
  102497. closeTag(parser)
  102498. } else {
  102499. strictFail(parser, 'Forward-slash in opening tag not followed by >')
  102500. parser.state = S.ATTRIB
  102501. }
  102502. continue
  102503. case S.ATTRIB:
  102504. // haven't read the attribute name yet.
  102505. if (isWhitespace(c)) {
  102506. continue
  102507. } else if (c === '>') {
  102508. openTag(parser)
  102509. } else if (c === '/') {
  102510. parser.state = S.OPEN_TAG_SLASH
  102511. } else if (isMatch(nameStart, c)) {
  102512. parser.attribName = c
  102513. parser.attribValue = ''
  102514. parser.state = S.ATTRIB_NAME
  102515. } else {
  102516. strictFail(parser, 'Invalid attribute name')
  102517. }
  102518. continue
  102519. case S.ATTRIB_NAME:
  102520. if (c === '=') {
  102521. parser.state = S.ATTRIB_VALUE
  102522. } else if (c === '>') {
  102523. strictFail(parser, 'Attribute without value')
  102524. parser.attribValue = parser.attribName
  102525. attrib(parser)
  102526. openTag(parser)
  102527. } else if (isWhitespace(c)) {
  102528. parser.state = S.ATTRIB_NAME_SAW_WHITE
  102529. } else if (isMatch(nameBody, c)) {
  102530. parser.attribName += c
  102531. } else {
  102532. strictFail(parser, 'Invalid attribute name')
  102533. }
  102534. continue
  102535. case S.ATTRIB_NAME_SAW_WHITE:
  102536. if (c === '=') {
  102537. parser.state = S.ATTRIB_VALUE
  102538. } else if (isWhitespace(c)) {
  102539. continue
  102540. } else {
  102541. strictFail(parser, 'Attribute without value')
  102542. parser.tag.attributes[parser.attribName] = ''
  102543. parser.attribValue = ''
  102544. emitNode(parser, 'onattribute', {
  102545. name: parser.attribName,
  102546. value: ''
  102547. })
  102548. parser.attribName = ''
  102549. if (c === '>') {
  102550. openTag(parser)
  102551. } else if (isMatch(nameStart, c)) {
  102552. parser.attribName = c
  102553. parser.state = S.ATTRIB_NAME
  102554. } else {
  102555. strictFail(parser, 'Invalid attribute name')
  102556. parser.state = S.ATTRIB
  102557. }
  102558. }
  102559. continue
  102560. case S.ATTRIB_VALUE:
  102561. if (isWhitespace(c)) {
  102562. continue
  102563. } else if (isQuote(c)) {
  102564. parser.q = c
  102565. parser.state = S.ATTRIB_VALUE_QUOTED
  102566. } else {
  102567. strictFail(parser, 'Unquoted attribute value')
  102568. parser.state = S.ATTRIB_VALUE_UNQUOTED
  102569. parser.attribValue = c
  102570. }
  102571. continue
  102572. case S.ATTRIB_VALUE_QUOTED:
  102573. if (c !== parser.q) {
  102574. if (c === '&') {
  102575. parser.state = S.ATTRIB_VALUE_ENTITY_Q
  102576. } else {
  102577. parser.attribValue += c
  102578. }
  102579. continue
  102580. }
  102581. attrib(parser)
  102582. parser.q = ''
  102583. parser.state = S.ATTRIB_VALUE_CLOSED
  102584. continue
  102585. case S.ATTRIB_VALUE_CLOSED:
  102586. if (isWhitespace(c)) {
  102587. parser.state = S.ATTRIB
  102588. } else if (c === '>') {
  102589. openTag(parser)
  102590. } else if (c === '/') {
  102591. parser.state = S.OPEN_TAG_SLASH
  102592. } else if (isMatch(nameStart, c)) {
  102593. strictFail(parser, 'No whitespace between attributes')
  102594. parser.attribName = c
  102595. parser.attribValue = ''
  102596. parser.state = S.ATTRIB_NAME
  102597. } else {
  102598. strictFail(parser, 'Invalid attribute name')
  102599. }
  102600. continue
  102601. case S.ATTRIB_VALUE_UNQUOTED:
  102602. if (!isAttribEnd(c)) {
  102603. if (c === '&') {
  102604. parser.state = S.ATTRIB_VALUE_ENTITY_U
  102605. } else {
  102606. parser.attribValue += c
  102607. }
  102608. continue
  102609. }
  102610. attrib(parser)
  102611. if (c === '>') {
  102612. openTag(parser)
  102613. } else {
  102614. parser.state = S.ATTRIB
  102615. }
  102616. continue
  102617. case S.CLOSE_TAG:
  102618. if (!parser.tagName) {
  102619. if (isWhitespace(c)) {
  102620. continue
  102621. } else if (notMatch(nameStart, c)) {
  102622. if (parser.script) {
  102623. parser.script += '</' + c
  102624. parser.state = S.SCRIPT
  102625. } else {
  102626. strictFail(parser, 'Invalid tagname in closing tag.')
  102627. }
  102628. } else {
  102629. parser.tagName = c
  102630. }
  102631. } else if (c === '>') {
  102632. closeTag(parser)
  102633. } else if (isMatch(nameBody, c)) {
  102634. parser.tagName += c
  102635. } else if (parser.script) {
  102636. parser.script += '</' + parser.tagName
  102637. parser.tagName = ''
  102638. parser.state = S.SCRIPT
  102639. } else {
  102640. if (!isWhitespace(c)) {
  102641. strictFail(parser, 'Invalid tagname in closing tag')
  102642. }
  102643. parser.state = S.CLOSE_TAG_SAW_WHITE
  102644. }
  102645. continue
  102646. case S.CLOSE_TAG_SAW_WHITE:
  102647. if (isWhitespace(c)) {
  102648. continue
  102649. }
  102650. if (c === '>') {
  102651. closeTag(parser)
  102652. } else {
  102653. strictFail(parser, 'Invalid characters in closing tag')
  102654. }
  102655. continue
  102656. case S.TEXT_ENTITY:
  102657. case S.ATTRIB_VALUE_ENTITY_Q:
  102658. case S.ATTRIB_VALUE_ENTITY_U:
  102659. var returnState
  102660. var buffer
  102661. switch (parser.state) {
  102662. case S.TEXT_ENTITY:
  102663. returnState = S.TEXT
  102664. buffer = 'textNode'
  102665. break
  102666. case S.ATTRIB_VALUE_ENTITY_Q:
  102667. returnState = S.ATTRIB_VALUE_QUOTED
  102668. buffer = 'attribValue'
  102669. break
  102670. case S.ATTRIB_VALUE_ENTITY_U:
  102671. returnState = S.ATTRIB_VALUE_UNQUOTED
  102672. buffer = 'attribValue'
  102673. break
  102674. }
  102675. if (c === ';') {
  102676. parser[buffer] += parseEntity(parser)
  102677. parser.entity = ''
  102678. parser.state = returnState
  102679. } else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) {
  102680. parser.entity += c
  102681. } else {
  102682. strictFail(parser, 'Invalid character in entity name')
  102683. parser[buffer] += '&' + parser.entity + c
  102684. parser.entity = ''
  102685. parser.state = returnState
  102686. }
  102687. continue
  102688. default:
  102689. throw new Error(parser, 'Unknown state: ' + parser.state)
  102690. }
  102691. } // while
  102692. if (parser.position >= parser.bufferCheckPosition) {
  102693. checkBufferLength(parser)
  102694. }
  102695. return parser
  102696. }
  102697. /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
  102698. /* istanbul ignore next */
  102699. if (!String.fromCodePoint) {
  102700. (function () {
  102701. var stringFromCharCode = String.fromCharCode
  102702. var floor = Math.floor
  102703. var fromCodePoint = function () {
  102704. var MAX_SIZE = 0x4000
  102705. var codeUnits = []
  102706. var highSurrogate
  102707. var lowSurrogate
  102708. var index = -1
  102709. var length = arguments.length
  102710. if (!length) {
  102711. return ''
  102712. }
  102713. var result = ''
  102714. while (++index < length) {
  102715. var codePoint = Number(arguments[index])
  102716. if (
  102717. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  102718. codePoint < 0 || // not a valid Unicode code point
  102719. codePoint > 0x10FFFF || // not a valid Unicode code point
  102720. floor(codePoint) !== codePoint // not an integer
  102721. ) {
  102722. throw RangeError('Invalid code point: ' + codePoint)
  102723. }
  102724. if (codePoint <= 0xFFFF) { // BMP code point
  102725. codeUnits.push(codePoint)
  102726. } else { // Astral code point; split in surrogate halves
  102727. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  102728. codePoint -= 0x10000
  102729. highSurrogate = (codePoint >> 10) + 0xD800
  102730. lowSurrogate = (codePoint % 0x400) + 0xDC00
  102731. codeUnits.push(highSurrogate, lowSurrogate)
  102732. }
  102733. if (index + 1 === length || codeUnits.length > MAX_SIZE) {
  102734. result += stringFromCharCode.apply(null, codeUnits)
  102735. codeUnits.length = 0
  102736. }
  102737. }
  102738. return result
  102739. }
  102740. /* istanbul ignore next */
  102741. if (Object.defineProperty) {
  102742. Object.defineProperty(String, 'fromCodePoint', {
  102743. value: fromCodePoint,
  102744. configurable: true,
  102745. writable: true
  102746. })
  102747. } else {
  102748. String.fromCodePoint = fromCodePoint
  102749. }
  102750. }())
  102751. }
  102752. })(typeof exports === 'undefined' ? this.sax = {} : exports)
  102753. }).call(this)}).call(this,require("buffer").Buffer)
  102754. },{"buffer":193,"stream":597,"string_decoder":631}],564:[function(require,module,exports){
  102755. var Buffer = require('safe-buffer').Buffer
  102756. // prototype class for hash functions
  102757. function Hash (blockSize, finalSize) {
  102758. this._block = Buffer.alloc(blockSize)
  102759. this._finalSize = finalSize
  102760. this._blockSize = blockSize
  102761. this._len = 0
  102762. }
  102763. Hash.prototype.update = function (data, enc) {
  102764. if (typeof data === 'string') {
  102765. enc = enc || 'utf8'
  102766. data = Buffer.from(data, enc)
  102767. }
  102768. var block = this._block
  102769. var blockSize = this._blockSize
  102770. var length = data.length
  102771. var accum = this._len
  102772. for (var offset = 0; offset < length;) {
  102773. var assigned = accum % blockSize
  102774. var remainder = Math.min(length - offset, blockSize - assigned)
  102775. for (var i = 0; i < remainder; i++) {
  102776. block[assigned + i] = data[offset + i]
  102777. }
  102778. accum += remainder
  102779. offset += remainder
  102780. if ((accum % blockSize) === 0) {
  102781. this._update(block)
  102782. }
  102783. }
  102784. this._len += length
  102785. return this
  102786. }
  102787. Hash.prototype.digest = function (enc) {
  102788. var rem = this._len % this._blockSize
  102789. this._block[rem] = 0x80
  102790. // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
  102791. // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
  102792. this._block.fill(0, rem + 1)
  102793. if (rem >= this._finalSize) {
  102794. this._update(this._block)
  102795. this._block.fill(0)
  102796. }
  102797. var bits = this._len * 8
  102798. // uint32
  102799. if (bits <= 0xffffffff) {
  102800. this._block.writeUInt32BE(bits, this._blockSize - 4)
  102801. // uint64
  102802. } else {
  102803. var lowBits = (bits & 0xffffffff) >>> 0
  102804. var highBits = (bits - lowBits) / 0x100000000
  102805. this._block.writeUInt32BE(highBits, this._blockSize - 8)
  102806. this._block.writeUInt32BE(lowBits, this._blockSize - 4)
  102807. }
  102808. this._update(this._block)
  102809. var hash = this._hash()
  102810. return enc ? hash.toString(enc) : hash
  102811. }
  102812. Hash.prototype._update = function () {
  102813. throw new Error('_update must be implemented by subclass')
  102814. }
  102815. module.exports = Hash
  102816. },{"safe-buffer":561}],565:[function(require,module,exports){
  102817. var exports = module.exports = function SHA (algorithm) {
  102818. algorithm = algorithm.toLowerCase()
  102819. var Algorithm = exports[algorithm]
  102820. if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
  102821. return new Algorithm()
  102822. }
  102823. exports.sha = require('./sha')
  102824. exports.sha1 = require('./sha1')
  102825. exports.sha224 = require('./sha224')
  102826. exports.sha256 = require('./sha256')
  102827. exports.sha384 = require('./sha384')
  102828. exports.sha512 = require('./sha512')
  102829. },{"./sha":566,"./sha1":567,"./sha224":568,"./sha256":569,"./sha384":570,"./sha512":571}],566:[function(require,module,exports){
  102830. /*
  102831. * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
  102832. * in FIPS PUB 180-1
  102833. * This source code is derived from sha1.js of the same repository.
  102834. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
  102835. * operation was added.
  102836. */
  102837. var inherits = require('inherits')
  102838. var Hash = require('./hash')
  102839. var Buffer = require('safe-buffer').Buffer
  102840. var K = [
  102841. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  102842. ]
  102843. var W = new Array(80)
  102844. function Sha () {
  102845. this.init()
  102846. this._w = W
  102847. Hash.call(this, 64, 56)
  102848. }
  102849. inherits(Sha, Hash)
  102850. Sha.prototype.init = function () {
  102851. this._a = 0x67452301
  102852. this._b = 0xefcdab89
  102853. this._c = 0x98badcfe
  102854. this._d = 0x10325476
  102855. this._e = 0xc3d2e1f0
  102856. return this
  102857. }
  102858. function rotl5 (num) {
  102859. return (num << 5) | (num >>> 27)
  102860. }
  102861. function rotl30 (num) {
  102862. return (num << 30) | (num >>> 2)
  102863. }
  102864. function ft (s, b, c, d) {
  102865. if (s === 0) return (b & c) | ((~b) & d)
  102866. if (s === 2) return (b & c) | (b & d) | (c & d)
  102867. return b ^ c ^ d
  102868. }
  102869. Sha.prototype._update = function (M) {
  102870. var W = this._w
  102871. var a = this._a | 0
  102872. var b = this._b | 0
  102873. var c = this._c | 0
  102874. var d = this._d | 0
  102875. var e = this._e | 0
  102876. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  102877. for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
  102878. for (var j = 0; j < 80; ++j) {
  102879. var s = ~~(j / 20)
  102880. var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
  102881. e = d
  102882. d = c
  102883. c = rotl30(b)
  102884. b = a
  102885. a = t
  102886. }
  102887. this._a = (a + this._a) | 0
  102888. this._b = (b + this._b) | 0
  102889. this._c = (c + this._c) | 0
  102890. this._d = (d + this._d) | 0
  102891. this._e = (e + this._e) | 0
  102892. }
  102893. Sha.prototype._hash = function () {
  102894. var H = Buffer.allocUnsafe(20)
  102895. H.writeInt32BE(this._a | 0, 0)
  102896. H.writeInt32BE(this._b | 0, 4)
  102897. H.writeInt32BE(this._c | 0, 8)
  102898. H.writeInt32BE(this._d | 0, 12)
  102899. H.writeInt32BE(this._e | 0, 16)
  102900. return H
  102901. }
  102902. module.exports = Sha
  102903. },{"./hash":564,"inherits":320,"safe-buffer":561}],567:[function(require,module,exports){
  102904. /*
  102905. * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
  102906. * in FIPS PUB 180-1
  102907. * Version 2.1a Copyright Paul Johnston 2000 - 2002.
  102908. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  102909. * Distributed under the BSD License
  102910. * See http://pajhome.org.uk/crypt/md5 for details.
  102911. */
  102912. var inherits = require('inherits')
  102913. var Hash = require('./hash')
  102914. var Buffer = require('safe-buffer').Buffer
  102915. var K = [
  102916. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  102917. ]
  102918. var W = new Array(80)
  102919. function Sha1 () {
  102920. this.init()
  102921. this._w = W
  102922. Hash.call(this, 64, 56)
  102923. }
  102924. inherits(Sha1, Hash)
  102925. Sha1.prototype.init = function () {
  102926. this._a = 0x67452301
  102927. this._b = 0xefcdab89
  102928. this._c = 0x98badcfe
  102929. this._d = 0x10325476
  102930. this._e = 0xc3d2e1f0
  102931. return this
  102932. }
  102933. function rotl1 (num) {
  102934. return (num << 1) | (num >>> 31)
  102935. }
  102936. function rotl5 (num) {
  102937. return (num << 5) | (num >>> 27)
  102938. }
  102939. function rotl30 (num) {
  102940. return (num << 30) | (num >>> 2)
  102941. }
  102942. function ft (s, b, c, d) {
  102943. if (s === 0) return (b & c) | ((~b) & d)
  102944. if (s === 2) return (b & c) | (b & d) | (c & d)
  102945. return b ^ c ^ d
  102946. }
  102947. Sha1.prototype._update = function (M) {
  102948. var W = this._w
  102949. var a = this._a | 0
  102950. var b = this._b | 0
  102951. var c = this._c | 0
  102952. var d = this._d | 0
  102953. var e = this._e | 0
  102954. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  102955. for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
  102956. for (var j = 0; j < 80; ++j) {
  102957. var s = ~~(j / 20)
  102958. var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
  102959. e = d
  102960. d = c
  102961. c = rotl30(b)
  102962. b = a
  102963. a = t
  102964. }
  102965. this._a = (a + this._a) | 0
  102966. this._b = (b + this._b) | 0
  102967. this._c = (c + this._c) | 0
  102968. this._d = (d + this._d) | 0
  102969. this._e = (e + this._e) | 0
  102970. }
  102971. Sha1.prototype._hash = function () {
  102972. var H = Buffer.allocUnsafe(20)
  102973. H.writeInt32BE(this._a | 0, 0)
  102974. H.writeInt32BE(this._b | 0, 4)
  102975. H.writeInt32BE(this._c | 0, 8)
  102976. H.writeInt32BE(this._d | 0, 12)
  102977. H.writeInt32BE(this._e | 0, 16)
  102978. return H
  102979. }
  102980. module.exports = Sha1
  102981. },{"./hash":564,"inherits":320,"safe-buffer":561}],568:[function(require,module,exports){
  102982. /**
  102983. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  102984. * in FIPS 180-2
  102985. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  102986. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  102987. *
  102988. */
  102989. var inherits = require('inherits')
  102990. var Sha256 = require('./sha256')
  102991. var Hash = require('./hash')
  102992. var Buffer = require('safe-buffer').Buffer
  102993. var W = new Array(64)
  102994. function Sha224 () {
  102995. this.init()
  102996. this._w = W // new Array(64)
  102997. Hash.call(this, 64, 56)
  102998. }
  102999. inherits(Sha224, Sha256)
  103000. Sha224.prototype.init = function () {
  103001. this._a = 0xc1059ed8
  103002. this._b = 0x367cd507
  103003. this._c = 0x3070dd17
  103004. this._d = 0xf70e5939
  103005. this._e = 0xffc00b31
  103006. this._f = 0x68581511
  103007. this._g = 0x64f98fa7
  103008. this._h = 0xbefa4fa4
  103009. return this
  103010. }
  103011. Sha224.prototype._hash = function () {
  103012. var H = Buffer.allocUnsafe(28)
  103013. H.writeInt32BE(this._a, 0)
  103014. H.writeInt32BE(this._b, 4)
  103015. H.writeInt32BE(this._c, 8)
  103016. H.writeInt32BE(this._d, 12)
  103017. H.writeInt32BE(this._e, 16)
  103018. H.writeInt32BE(this._f, 20)
  103019. H.writeInt32BE(this._g, 24)
  103020. return H
  103021. }
  103022. module.exports = Sha224
  103023. },{"./hash":564,"./sha256":569,"inherits":320,"safe-buffer":561}],569:[function(require,module,exports){
  103024. /**
  103025. * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  103026. * in FIPS 180-2
  103027. * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
  103028. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  103029. *
  103030. */
  103031. var inherits = require('inherits')
  103032. var Hash = require('./hash')
  103033. var Buffer = require('safe-buffer').Buffer
  103034. var K = [
  103035. 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
  103036. 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
  103037. 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
  103038. 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
  103039. 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
  103040. 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
  103041. 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
  103042. 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
  103043. 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
  103044. 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
  103045. 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
  103046. 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
  103047. 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
  103048. 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
  103049. 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
  103050. 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
  103051. ]
  103052. var W = new Array(64)
  103053. function Sha256 () {
  103054. this.init()
  103055. this._w = W // new Array(64)
  103056. Hash.call(this, 64, 56)
  103057. }
  103058. inherits(Sha256, Hash)
  103059. Sha256.prototype.init = function () {
  103060. this._a = 0x6a09e667
  103061. this._b = 0xbb67ae85
  103062. this._c = 0x3c6ef372
  103063. this._d = 0xa54ff53a
  103064. this._e = 0x510e527f
  103065. this._f = 0x9b05688c
  103066. this._g = 0x1f83d9ab
  103067. this._h = 0x5be0cd19
  103068. return this
  103069. }
  103070. function ch (x, y, z) {
  103071. return z ^ (x & (y ^ z))
  103072. }
  103073. function maj (x, y, z) {
  103074. return (x & y) | (z & (x | y))
  103075. }
  103076. function sigma0 (x) {
  103077. return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
  103078. }
  103079. function sigma1 (x) {
  103080. return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
  103081. }
  103082. function gamma0 (x) {
  103083. return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
  103084. }
  103085. function gamma1 (x) {
  103086. return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
  103087. }
  103088. Sha256.prototype._update = function (M) {
  103089. var W = this._w
  103090. var a = this._a | 0
  103091. var b = this._b | 0
  103092. var c = this._c | 0
  103093. var d = this._d | 0
  103094. var e = this._e | 0
  103095. var f = this._f | 0
  103096. var g = this._g | 0
  103097. var h = this._h | 0
  103098. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  103099. for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
  103100. for (var j = 0; j < 64; ++j) {
  103101. var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
  103102. var T2 = (sigma0(a) + maj(a, b, c)) | 0
  103103. h = g
  103104. g = f
  103105. f = e
  103106. e = (d + T1) | 0
  103107. d = c
  103108. c = b
  103109. b = a
  103110. a = (T1 + T2) | 0
  103111. }
  103112. this._a = (a + this._a) | 0
  103113. this._b = (b + this._b) | 0
  103114. this._c = (c + this._c) | 0
  103115. this._d = (d + this._d) | 0
  103116. this._e = (e + this._e) | 0
  103117. this._f = (f + this._f) | 0
  103118. this._g = (g + this._g) | 0
  103119. this._h = (h + this._h) | 0
  103120. }
  103121. Sha256.prototype._hash = function () {
  103122. var H = Buffer.allocUnsafe(32)
  103123. H.writeInt32BE(this._a, 0)
  103124. H.writeInt32BE(this._b, 4)
  103125. H.writeInt32BE(this._c, 8)
  103126. H.writeInt32BE(this._d, 12)
  103127. H.writeInt32BE(this._e, 16)
  103128. H.writeInt32BE(this._f, 20)
  103129. H.writeInt32BE(this._g, 24)
  103130. H.writeInt32BE(this._h, 28)
  103131. return H
  103132. }
  103133. module.exports = Sha256
  103134. },{"./hash":564,"inherits":320,"safe-buffer":561}],570:[function(require,module,exports){
  103135. var inherits = require('inherits')
  103136. var SHA512 = require('./sha512')
  103137. var Hash = require('./hash')
  103138. var Buffer = require('safe-buffer').Buffer
  103139. var W = new Array(160)
  103140. function Sha384 () {
  103141. this.init()
  103142. this._w = W
  103143. Hash.call(this, 128, 112)
  103144. }
  103145. inherits(Sha384, SHA512)
  103146. Sha384.prototype.init = function () {
  103147. this._ah = 0xcbbb9d5d
  103148. this._bh = 0x629a292a
  103149. this._ch = 0x9159015a
  103150. this._dh = 0x152fecd8
  103151. this._eh = 0x67332667
  103152. this._fh = 0x8eb44a87
  103153. this._gh = 0xdb0c2e0d
  103154. this._hh = 0x47b5481d
  103155. this._al = 0xc1059ed8
  103156. this._bl = 0x367cd507
  103157. this._cl = 0x3070dd17
  103158. this._dl = 0xf70e5939
  103159. this._el = 0xffc00b31
  103160. this._fl = 0x68581511
  103161. this._gl = 0x64f98fa7
  103162. this._hl = 0xbefa4fa4
  103163. return this
  103164. }
  103165. Sha384.prototype._hash = function () {
  103166. var H = Buffer.allocUnsafe(48)
  103167. function writeInt64BE (h, l, offset) {
  103168. H.writeInt32BE(h, offset)
  103169. H.writeInt32BE(l, offset + 4)
  103170. }
  103171. writeInt64BE(this._ah, this._al, 0)
  103172. writeInt64BE(this._bh, this._bl, 8)
  103173. writeInt64BE(this._ch, this._cl, 16)
  103174. writeInt64BE(this._dh, this._dl, 24)
  103175. writeInt64BE(this._eh, this._el, 32)
  103176. writeInt64BE(this._fh, this._fl, 40)
  103177. return H
  103178. }
  103179. module.exports = Sha384
  103180. },{"./hash":564,"./sha512":571,"inherits":320,"safe-buffer":561}],571:[function(require,module,exports){
  103181. var inherits = require('inherits')
  103182. var Hash = require('./hash')
  103183. var Buffer = require('safe-buffer').Buffer
  103184. var K = [
  103185. 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  103186. 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  103187. 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  103188. 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  103189. 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  103190. 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  103191. 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  103192. 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  103193. 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  103194. 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  103195. 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  103196. 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  103197. 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  103198. 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  103199. 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  103200. 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  103201. 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  103202. 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  103203. 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  103204. 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  103205. 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  103206. 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  103207. 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  103208. 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  103209. 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  103210. 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  103211. 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  103212. 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  103213. 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  103214. 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  103215. 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  103216. 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  103217. 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  103218. 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  103219. 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  103220. 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  103221. 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  103222. 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  103223. 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  103224. 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  103225. ]
  103226. var W = new Array(160)
  103227. function Sha512 () {
  103228. this.init()
  103229. this._w = W
  103230. Hash.call(this, 128, 112)
  103231. }
  103232. inherits(Sha512, Hash)
  103233. Sha512.prototype.init = function () {
  103234. this._ah = 0x6a09e667
  103235. this._bh = 0xbb67ae85
  103236. this._ch = 0x3c6ef372
  103237. this._dh = 0xa54ff53a
  103238. this._eh = 0x510e527f
  103239. this._fh = 0x9b05688c
  103240. this._gh = 0x1f83d9ab
  103241. this._hh = 0x5be0cd19
  103242. this._al = 0xf3bcc908
  103243. this._bl = 0x84caa73b
  103244. this._cl = 0xfe94f82b
  103245. this._dl = 0x5f1d36f1
  103246. this._el = 0xade682d1
  103247. this._fl = 0x2b3e6c1f
  103248. this._gl = 0xfb41bd6b
  103249. this._hl = 0x137e2179
  103250. return this
  103251. }
  103252. function Ch (x, y, z) {
  103253. return z ^ (x & (y ^ z))
  103254. }
  103255. function maj (x, y, z) {
  103256. return (x & y) | (z & (x | y))
  103257. }
  103258. function sigma0 (x, xl) {
  103259. return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
  103260. }
  103261. function sigma1 (x, xl) {
  103262. return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
  103263. }
  103264. function Gamma0 (x, xl) {
  103265. return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
  103266. }
  103267. function Gamma0l (x, xl) {
  103268. return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
  103269. }
  103270. function Gamma1 (x, xl) {
  103271. return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
  103272. }
  103273. function Gamma1l (x, xl) {
  103274. return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
  103275. }
  103276. function getCarry (a, b) {
  103277. return (a >>> 0) < (b >>> 0) ? 1 : 0
  103278. }
  103279. Sha512.prototype._update = function (M) {
  103280. var W = this._w
  103281. var ah = this._ah | 0
  103282. var bh = this._bh | 0
  103283. var ch = this._ch | 0
  103284. var dh = this._dh | 0
  103285. var eh = this._eh | 0
  103286. var fh = this._fh | 0
  103287. var gh = this._gh | 0
  103288. var hh = this._hh | 0
  103289. var al = this._al | 0
  103290. var bl = this._bl | 0
  103291. var cl = this._cl | 0
  103292. var dl = this._dl | 0
  103293. var el = this._el | 0
  103294. var fl = this._fl | 0
  103295. var gl = this._gl | 0
  103296. var hl = this._hl | 0
  103297. for (var i = 0; i < 32; i += 2) {
  103298. W[i] = M.readInt32BE(i * 4)
  103299. W[i + 1] = M.readInt32BE(i * 4 + 4)
  103300. }
  103301. for (; i < 160; i += 2) {
  103302. var xh = W[i - 15 * 2]
  103303. var xl = W[i - 15 * 2 + 1]
  103304. var gamma0 = Gamma0(xh, xl)
  103305. var gamma0l = Gamma0l(xl, xh)
  103306. xh = W[i - 2 * 2]
  103307. xl = W[i - 2 * 2 + 1]
  103308. var gamma1 = Gamma1(xh, xl)
  103309. var gamma1l = Gamma1l(xl, xh)
  103310. // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
  103311. var Wi7h = W[i - 7 * 2]
  103312. var Wi7l = W[i - 7 * 2 + 1]
  103313. var Wi16h = W[i - 16 * 2]
  103314. var Wi16l = W[i - 16 * 2 + 1]
  103315. var Wil = (gamma0l + Wi7l) | 0
  103316. var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
  103317. Wil = (Wil + gamma1l) | 0
  103318. Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
  103319. Wil = (Wil + Wi16l) | 0
  103320. Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
  103321. W[i] = Wih
  103322. W[i + 1] = Wil
  103323. }
  103324. for (var j = 0; j < 160; j += 2) {
  103325. Wih = W[j]
  103326. Wil = W[j + 1]
  103327. var majh = maj(ah, bh, ch)
  103328. var majl = maj(al, bl, cl)
  103329. var sigma0h = sigma0(ah, al)
  103330. var sigma0l = sigma0(al, ah)
  103331. var sigma1h = sigma1(eh, el)
  103332. var sigma1l = sigma1(el, eh)
  103333. // t1 = h + sigma1 + ch + K[j] + W[j]
  103334. var Kih = K[j]
  103335. var Kil = K[j + 1]
  103336. var chh = Ch(eh, fh, gh)
  103337. var chl = Ch(el, fl, gl)
  103338. var t1l = (hl + sigma1l) | 0
  103339. var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
  103340. t1l = (t1l + chl) | 0
  103341. t1h = (t1h + chh + getCarry(t1l, chl)) | 0
  103342. t1l = (t1l + Kil) | 0
  103343. t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
  103344. t1l = (t1l + Wil) | 0
  103345. t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
  103346. // t2 = sigma0 + maj
  103347. var t2l = (sigma0l + majl) | 0
  103348. var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
  103349. hh = gh
  103350. hl = gl
  103351. gh = fh
  103352. gl = fl
  103353. fh = eh
  103354. fl = el
  103355. el = (dl + t1l) | 0
  103356. eh = (dh + t1h + getCarry(el, dl)) | 0
  103357. dh = ch
  103358. dl = cl
  103359. ch = bh
  103360. cl = bl
  103361. bh = ah
  103362. bl = al
  103363. al = (t1l + t2l) | 0
  103364. ah = (t1h + t2h + getCarry(al, t1l)) | 0
  103365. }
  103366. this._al = (this._al + al) | 0
  103367. this._bl = (this._bl + bl) | 0
  103368. this._cl = (this._cl + cl) | 0
  103369. this._dl = (this._dl + dl) | 0
  103370. this._el = (this._el + el) | 0
  103371. this._fl = (this._fl + fl) | 0
  103372. this._gl = (this._gl + gl) | 0
  103373. this._hl = (this._hl + hl) | 0
  103374. this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
  103375. this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
  103376. this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
  103377. this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
  103378. this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
  103379. this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
  103380. this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
  103381. this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
  103382. }
  103383. Sha512.prototype._hash = function () {
  103384. var H = Buffer.allocUnsafe(64)
  103385. function writeInt64BE (h, l, offset) {
  103386. H.writeInt32BE(h, offset)
  103387. H.writeInt32BE(l, offset + 4)
  103388. }
  103389. writeInt64BE(this._ah, this._al, 0)
  103390. writeInt64BE(this._bh, this._bl, 8)
  103391. writeInt64BE(this._ch, this._cl, 16)
  103392. writeInt64BE(this._dh, this._dl, 24)
  103393. writeInt64BE(this._eh, this._el, 32)
  103394. writeInt64BE(this._fh, this._fl, 40)
  103395. writeInt64BE(this._gh, this._gl, 48)
  103396. writeInt64BE(this._hh, this._hl, 56)
  103397. return H
  103398. }
  103399. module.exports = Sha512
  103400. },{"./hash":564,"inherits":320,"safe-buffer":561}],572:[function(require,module,exports){
  103401. // Copyright 2015 Joyent, Inc.
  103402. var Buffer = require('safer-buffer').Buffer;
  103403. var algInfo = {
  103404. 'dsa': {
  103405. parts: ['p', 'q', 'g', 'y'],
  103406. sizePart: 'p'
  103407. },
  103408. 'rsa': {
  103409. parts: ['e', 'n'],
  103410. sizePart: 'n'
  103411. },
  103412. 'ecdsa': {
  103413. parts: ['curve', 'Q'],
  103414. sizePart: 'Q'
  103415. },
  103416. 'ed25519': {
  103417. parts: ['A'],
  103418. sizePart: 'A'
  103419. }
  103420. };
  103421. algInfo['curve25519'] = algInfo['ed25519'];
  103422. var algPrivInfo = {
  103423. 'dsa': {
  103424. parts: ['p', 'q', 'g', 'y', 'x']
  103425. },
  103426. 'rsa': {
  103427. parts: ['n', 'e', 'd', 'iqmp', 'p', 'q']
  103428. },
  103429. 'ecdsa': {
  103430. parts: ['curve', 'Q', 'd']
  103431. },
  103432. 'ed25519': {
  103433. parts: ['A', 'k']
  103434. }
  103435. };
  103436. algPrivInfo['curve25519'] = algPrivInfo['ed25519'];
  103437. var hashAlgs = {
  103438. 'md5': true,
  103439. 'sha1': true,
  103440. 'sha256': true,
  103441. 'sha384': true,
  103442. 'sha512': true
  103443. };
  103444. /*
  103445. * Taken from
  103446. * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf
  103447. */
  103448. var curves = {
  103449. 'nistp256': {
  103450. size: 256,
  103451. pkcs8oid: '1.2.840.10045.3.1.7',
  103452. p: Buffer.from(('00' +
  103453. 'ffffffff 00000001 00000000 00000000' +
  103454. '00000000 ffffffff ffffffff ffffffff').
  103455. replace(/ /g, ''), 'hex'),
  103456. a: Buffer.from(('00' +
  103457. 'FFFFFFFF 00000001 00000000 00000000' +
  103458. '00000000 FFFFFFFF FFFFFFFF FFFFFFFC').
  103459. replace(/ /g, ''), 'hex'),
  103460. b: Buffer.from((
  103461. '5ac635d8 aa3a93e7 b3ebbd55 769886bc' +
  103462. '651d06b0 cc53b0f6 3bce3c3e 27d2604b').
  103463. replace(/ /g, ''), 'hex'),
  103464. s: Buffer.from(('00' +
  103465. 'c49d3608 86e70493 6a6678e1 139d26b7' +
  103466. '819f7e90').
  103467. replace(/ /g, ''), 'hex'),
  103468. n: Buffer.from(('00' +
  103469. 'ffffffff 00000000 ffffffff ffffffff' +
  103470. 'bce6faad a7179e84 f3b9cac2 fc632551').
  103471. replace(/ /g, ''), 'hex'),
  103472. G: Buffer.from(('04' +
  103473. '6b17d1f2 e12c4247 f8bce6e5 63a440f2' +
  103474. '77037d81 2deb33a0 f4a13945 d898c296' +
  103475. '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' +
  103476. '2bce3357 6b315ece cbb64068 37bf51f5').
  103477. replace(/ /g, ''), 'hex')
  103478. },
  103479. 'nistp384': {
  103480. size: 384,
  103481. pkcs8oid: '1.3.132.0.34',
  103482. p: Buffer.from(('00' +
  103483. 'ffffffff ffffffff ffffffff ffffffff' +
  103484. 'ffffffff ffffffff ffffffff fffffffe' +
  103485. 'ffffffff 00000000 00000000 ffffffff').
  103486. replace(/ /g, ''), 'hex'),
  103487. a: Buffer.from(('00' +
  103488. 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
  103489. 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' +
  103490. 'FFFFFFFF 00000000 00000000 FFFFFFFC').
  103491. replace(/ /g, ''), 'hex'),
  103492. b: Buffer.from((
  103493. 'b3312fa7 e23ee7e4 988e056b e3f82d19' +
  103494. '181d9c6e fe814112 0314088f 5013875a' +
  103495. 'c656398d 8a2ed19d 2a85c8ed d3ec2aef').
  103496. replace(/ /g, ''), 'hex'),
  103497. s: Buffer.from(('00' +
  103498. 'a335926a a319a27a 1d00896a 6773a482' +
  103499. '7acdac73').
  103500. replace(/ /g, ''), 'hex'),
  103501. n: Buffer.from(('00' +
  103502. 'ffffffff ffffffff ffffffff ffffffff' +
  103503. 'ffffffff ffffffff c7634d81 f4372ddf' +
  103504. '581a0db2 48b0a77a ecec196a ccc52973').
  103505. replace(/ /g, ''), 'hex'),
  103506. G: Buffer.from(('04' +
  103507. 'aa87ca22 be8b0537 8eb1c71e f320ad74' +
  103508. '6e1d3b62 8ba79b98 59f741e0 82542a38' +
  103509. '5502f25d bf55296c 3a545e38 72760ab7' +
  103510. '3617de4a 96262c6f 5d9e98bf 9292dc29' +
  103511. 'f8f41dbd 289a147c e9da3113 b5f0b8c0' +
  103512. '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f').
  103513. replace(/ /g, ''), 'hex')
  103514. },
  103515. 'nistp521': {
  103516. size: 521,
  103517. pkcs8oid: '1.3.132.0.35',
  103518. p: Buffer.from((
  103519. '01ffffff ffffffff ffffffff ffffffff' +
  103520. 'ffffffff ffffffff ffffffff ffffffff' +
  103521. 'ffffffff ffffffff ffffffff ffffffff' +
  103522. 'ffffffff ffffffff ffffffff ffffffff' +
  103523. 'ffff').replace(/ /g, ''), 'hex'),
  103524. a: Buffer.from(('01FF' +
  103525. 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
  103526. 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
  103527. 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
  103528. 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC').
  103529. replace(/ /g, ''), 'hex'),
  103530. b: Buffer.from(('51' +
  103531. '953eb961 8e1c9a1f 929a21a0 b68540ee' +
  103532. 'a2da725b 99b315f3 b8b48991 8ef109e1' +
  103533. '56193951 ec7e937b 1652c0bd 3bb1bf07' +
  103534. '3573df88 3d2c34f1 ef451fd4 6b503f00').
  103535. replace(/ /g, ''), 'hex'),
  103536. s: Buffer.from(('00' +
  103537. 'd09e8800 291cb853 96cc6717 393284aa' +
  103538. 'a0da64ba').replace(/ /g, ''), 'hex'),
  103539. n: Buffer.from(('01ff' +
  103540. 'ffffffff ffffffff ffffffff ffffffff' +
  103541. 'ffffffff ffffffff ffffffff fffffffa' +
  103542. '51868783 bf2f966b 7fcc0148 f709a5d0' +
  103543. '3bb5c9b8 899c47ae bb6fb71e 91386409').
  103544. replace(/ /g, ''), 'hex'),
  103545. G: Buffer.from(('04' +
  103546. '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' +
  103547. '9c648139 053fb521 f828af60 6b4d3dba' +
  103548. 'a14b5e77 efe75928 fe1dc127 a2ffa8de' +
  103549. '3348b3c1 856a429b f97e7e31 c2e5bd66' +
  103550. '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' +
  103551. '98f54449 579b4468 17afbd17 273e662c' +
  103552. '97ee7299 5ef42640 c550b901 3fad0761' +
  103553. '353c7086 a272c240 88be9476 9fd16650').
  103554. replace(/ /g, ''), 'hex')
  103555. }
  103556. };
  103557. module.exports = {
  103558. info: algInfo,
  103559. privInfo: algPrivInfo,
  103560. hashAlgs: hashAlgs,
  103561. curves: curves
  103562. };
  103563. },{"safer-buffer":562}],573:[function(require,module,exports){
  103564. // Copyright 2016 Joyent, Inc.
  103565. module.exports = Certificate;
  103566. var assert = require('assert-plus');
  103567. var Buffer = require('safer-buffer').Buffer;
  103568. var algs = require('./algs');
  103569. var crypto = require('crypto');
  103570. var Fingerprint = require('./fingerprint');
  103571. var Signature = require('./signature');
  103572. var errs = require('./errors');
  103573. var util = require('util');
  103574. var utils = require('./utils');
  103575. var Key = require('./key');
  103576. var PrivateKey = require('./private-key');
  103577. var Identity = require('./identity');
  103578. var formats = {};
  103579. formats['openssh'] = require('./formats/openssh-cert');
  103580. formats['x509'] = require('./formats/x509');
  103581. formats['pem'] = require('./formats/x509-pem');
  103582. var CertificateParseError = errs.CertificateParseError;
  103583. var InvalidAlgorithmError = errs.InvalidAlgorithmError;
  103584. function Certificate(opts) {
  103585. assert.object(opts, 'options');
  103586. assert.arrayOfObject(opts.subjects, 'options.subjects');
  103587. utils.assertCompatible(opts.subjects[0], Identity, [1, 0],
  103588. 'options.subjects');
  103589. utils.assertCompatible(opts.subjectKey, Key, [1, 0],
  103590. 'options.subjectKey');
  103591. utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer');
  103592. if (opts.issuerKey !== undefined) {
  103593. utils.assertCompatible(opts.issuerKey, Key, [1, 0],
  103594. 'options.issuerKey');
  103595. }
  103596. assert.object(opts.signatures, 'options.signatures');
  103597. assert.buffer(opts.serial, 'options.serial');
  103598. assert.date(opts.validFrom, 'options.validFrom');
  103599. assert.date(opts.validUntil, 'optons.validUntil');
  103600. assert.optionalArrayOfString(opts.purposes, 'options.purposes');
  103601. this._hashCache = {};
  103602. this.subjects = opts.subjects;
  103603. this.issuer = opts.issuer;
  103604. this.subjectKey = opts.subjectKey;
  103605. this.issuerKey = opts.issuerKey;
  103606. this.signatures = opts.signatures;
  103607. this.serial = opts.serial;
  103608. this.validFrom = opts.validFrom;
  103609. this.validUntil = opts.validUntil;
  103610. this.purposes = opts.purposes;
  103611. }
  103612. Certificate.formats = formats;
  103613. Certificate.prototype.toBuffer = function (format, options) {
  103614. if (format === undefined)
  103615. format = 'x509';
  103616. assert.string(format, 'format');
  103617. assert.object(formats[format], 'formats[format]');
  103618. assert.optionalObject(options, 'options');
  103619. return (formats[format].write(this, options));
  103620. };
  103621. Certificate.prototype.toString = function (format, options) {
  103622. if (format === undefined)
  103623. format = 'pem';
  103624. return (this.toBuffer(format, options).toString());
  103625. };
  103626. Certificate.prototype.fingerprint = function (algo) {
  103627. if (algo === undefined)
  103628. algo = 'sha256';
  103629. assert.string(algo, 'algorithm');
  103630. var opts = {
  103631. type: 'certificate',
  103632. hash: this.hash(algo),
  103633. algorithm: algo
  103634. };
  103635. return (new Fingerprint(opts));
  103636. };
  103637. Certificate.prototype.hash = function (algo) {
  103638. assert.string(algo, 'algorithm');
  103639. algo = algo.toLowerCase();
  103640. if (algs.hashAlgs[algo] === undefined)
  103641. throw (new InvalidAlgorithmError(algo));
  103642. if (this._hashCache[algo])
  103643. return (this._hashCache[algo]);
  103644. var hash = crypto.createHash(algo).
  103645. update(this.toBuffer('x509')).digest();
  103646. this._hashCache[algo] = hash;
  103647. return (hash);
  103648. };
  103649. Certificate.prototype.isExpired = function (when) {
  103650. if (when === undefined)
  103651. when = new Date();
  103652. return (!((when.getTime() >= this.validFrom.getTime()) &&
  103653. (when.getTime() < this.validUntil.getTime())));
  103654. };
  103655. Certificate.prototype.isSignedBy = function (issuerCert) {
  103656. utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer');
  103657. if (!this.issuer.equals(issuerCert.subjects[0]))
  103658. return (false);
  103659. if (this.issuer.purposes && this.issuer.purposes.length > 0 &&
  103660. this.issuer.purposes.indexOf('ca') === -1) {
  103661. return (false);
  103662. }
  103663. return (this.isSignedByKey(issuerCert.subjectKey));
  103664. };
  103665. Certificate.prototype.getExtension = function (keyOrOid) {
  103666. assert.string(keyOrOid, 'keyOrOid');
  103667. var ext = this.getExtensions().filter(function (maybeExt) {
  103668. if (maybeExt.format === 'x509')
  103669. return (maybeExt.oid === keyOrOid);
  103670. if (maybeExt.format === 'openssh')
  103671. return (maybeExt.name === keyOrOid);
  103672. return (false);
  103673. })[0];
  103674. return (ext);
  103675. };
  103676. Certificate.prototype.getExtensions = function () {
  103677. var exts = [];
  103678. var x509 = this.signatures.x509;
  103679. if (x509 && x509.extras && x509.extras.exts) {
  103680. x509.extras.exts.forEach(function (ext) {
  103681. ext.format = 'x509';
  103682. exts.push(ext);
  103683. });
  103684. }
  103685. var openssh = this.signatures.openssh;
  103686. if (openssh && openssh.exts) {
  103687. openssh.exts.forEach(function (ext) {
  103688. ext.format = 'openssh';
  103689. exts.push(ext);
  103690. });
  103691. }
  103692. return (exts);
  103693. };
  103694. Certificate.prototype.isSignedByKey = function (issuerKey) {
  103695. utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey');
  103696. if (this.issuerKey !== undefined) {
  103697. return (this.issuerKey.
  103698. fingerprint('sha512').matches(issuerKey));
  103699. }
  103700. var fmt = Object.keys(this.signatures)[0];
  103701. var valid = formats[fmt].verify(this, issuerKey);
  103702. if (valid)
  103703. this.issuerKey = issuerKey;
  103704. return (valid);
  103705. };
  103706. Certificate.prototype.signWith = function (key) {
  103707. utils.assertCompatible(key, PrivateKey, [1, 2], 'key');
  103708. var fmts = Object.keys(formats);
  103709. var didOne = false;
  103710. for (var i = 0; i < fmts.length; ++i) {
  103711. if (fmts[i] !== 'pem') {
  103712. var ret = formats[fmts[i]].sign(this, key);
  103713. if (ret === true)
  103714. didOne = true;
  103715. }
  103716. }
  103717. if (!didOne) {
  103718. throw (new Error('Failed to sign the certificate for any ' +
  103719. 'available certificate formats'));
  103720. }
  103721. };
  103722. Certificate.createSelfSigned = function (subjectOrSubjects, key, options) {
  103723. var subjects;
  103724. if (Array.isArray(subjectOrSubjects))
  103725. subjects = subjectOrSubjects;
  103726. else
  103727. subjects = [subjectOrSubjects];
  103728. assert.arrayOfObject(subjects);
  103729. subjects.forEach(function (subject) {
  103730. utils.assertCompatible(subject, Identity, [1, 0], 'subject');
  103731. });
  103732. utils.assertCompatible(key, PrivateKey, [1, 2], 'private key');
  103733. assert.optionalObject(options, 'options');
  103734. if (options === undefined)
  103735. options = {};
  103736. assert.optionalObject(options.validFrom, 'options.validFrom');
  103737. assert.optionalObject(options.validUntil, 'options.validUntil');
  103738. var validFrom = options.validFrom;
  103739. var validUntil = options.validUntil;
  103740. if (validFrom === undefined)
  103741. validFrom = new Date();
  103742. if (validUntil === undefined) {
  103743. assert.optionalNumber(options.lifetime, 'options.lifetime');
  103744. var lifetime = options.lifetime;
  103745. if (lifetime === undefined)
  103746. lifetime = 10*365*24*3600;
  103747. validUntil = new Date();
  103748. validUntil.setTime(validUntil.getTime() + lifetime*1000);
  103749. }
  103750. assert.optionalBuffer(options.serial, 'options.serial');
  103751. var serial = options.serial;
  103752. if (serial === undefined)
  103753. serial = Buffer.from('0000000000000001', 'hex');
  103754. var purposes = options.purposes;
  103755. if (purposes === undefined)
  103756. purposes = [];
  103757. if (purposes.indexOf('signature') === -1)
  103758. purposes.push('signature');
  103759. /* Self-signed certs are always CAs. */
  103760. if (purposes.indexOf('ca') === -1)
  103761. purposes.push('ca');
  103762. if (purposes.indexOf('crl') === -1)
  103763. purposes.push('crl');
  103764. /*
  103765. * If we weren't explicitly given any other purposes, do the sensible
  103766. * thing and add some basic ones depending on the subject type.
  103767. */
  103768. if (purposes.length <= 3) {
  103769. var hostSubjects = subjects.filter(function (subject) {
  103770. return (subject.type === 'host');
  103771. });
  103772. var userSubjects = subjects.filter(function (subject) {
  103773. return (subject.type === 'user');
  103774. });
  103775. if (hostSubjects.length > 0) {
  103776. if (purposes.indexOf('serverAuth') === -1)
  103777. purposes.push('serverAuth');
  103778. }
  103779. if (userSubjects.length > 0) {
  103780. if (purposes.indexOf('clientAuth') === -1)
  103781. purposes.push('clientAuth');
  103782. }
  103783. if (userSubjects.length > 0 || hostSubjects.length > 0) {
  103784. if (purposes.indexOf('keyAgreement') === -1)
  103785. purposes.push('keyAgreement');
  103786. if (key.type === 'rsa' &&
  103787. purposes.indexOf('encryption') === -1)
  103788. purposes.push('encryption');
  103789. }
  103790. }
  103791. var cert = new Certificate({
  103792. subjects: subjects,
  103793. issuer: subjects[0],
  103794. subjectKey: key.toPublic(),
  103795. issuerKey: key.toPublic(),
  103796. signatures: {},
  103797. serial: serial,
  103798. validFrom: validFrom,
  103799. validUntil: validUntil,
  103800. purposes: purposes
  103801. });
  103802. cert.signWith(key);
  103803. return (cert);
  103804. };
  103805. Certificate.create =
  103806. function (subjectOrSubjects, key, issuer, issuerKey, options) {
  103807. var subjects;
  103808. if (Array.isArray(subjectOrSubjects))
  103809. subjects = subjectOrSubjects;
  103810. else
  103811. subjects = [subjectOrSubjects];
  103812. assert.arrayOfObject(subjects);
  103813. subjects.forEach(function (subject) {
  103814. utils.assertCompatible(subject, Identity, [1, 0], 'subject');
  103815. });
  103816. utils.assertCompatible(key, Key, [1, 0], 'key');
  103817. if (PrivateKey.isPrivateKey(key))
  103818. key = key.toPublic();
  103819. utils.assertCompatible(issuer, Identity, [1, 0], 'issuer');
  103820. utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key');
  103821. assert.optionalObject(options, 'options');
  103822. if (options === undefined)
  103823. options = {};
  103824. assert.optionalObject(options.validFrom, 'options.validFrom');
  103825. assert.optionalObject(options.validUntil, 'options.validUntil');
  103826. var validFrom = options.validFrom;
  103827. var validUntil = options.validUntil;
  103828. if (validFrom === undefined)
  103829. validFrom = new Date();
  103830. if (validUntil === undefined) {
  103831. assert.optionalNumber(options.lifetime, 'options.lifetime');
  103832. var lifetime = options.lifetime;
  103833. if (lifetime === undefined)
  103834. lifetime = 10*365*24*3600;
  103835. validUntil = new Date();
  103836. validUntil.setTime(validUntil.getTime() + lifetime*1000);
  103837. }
  103838. assert.optionalBuffer(options.serial, 'options.serial');
  103839. var serial = options.serial;
  103840. if (serial === undefined)
  103841. serial = Buffer.from('0000000000000001', 'hex');
  103842. var purposes = options.purposes;
  103843. if (purposes === undefined)
  103844. purposes = [];
  103845. if (purposes.indexOf('signature') === -1)
  103846. purposes.push('signature');
  103847. if (options.ca === true) {
  103848. if (purposes.indexOf('ca') === -1)
  103849. purposes.push('ca');
  103850. if (purposes.indexOf('crl') === -1)
  103851. purposes.push('crl');
  103852. }
  103853. var hostSubjects = subjects.filter(function (subject) {
  103854. return (subject.type === 'host');
  103855. });
  103856. var userSubjects = subjects.filter(function (subject) {
  103857. return (subject.type === 'user');
  103858. });
  103859. if (hostSubjects.length > 0) {
  103860. if (purposes.indexOf('serverAuth') === -1)
  103861. purposes.push('serverAuth');
  103862. }
  103863. if (userSubjects.length > 0) {
  103864. if (purposes.indexOf('clientAuth') === -1)
  103865. purposes.push('clientAuth');
  103866. }
  103867. if (userSubjects.length > 0 || hostSubjects.length > 0) {
  103868. if (purposes.indexOf('keyAgreement') === -1)
  103869. purposes.push('keyAgreement');
  103870. if (key.type === 'rsa' &&
  103871. purposes.indexOf('encryption') === -1)
  103872. purposes.push('encryption');
  103873. }
  103874. var cert = new Certificate({
  103875. subjects: subjects,
  103876. issuer: issuer,
  103877. subjectKey: key,
  103878. issuerKey: issuerKey.toPublic(),
  103879. signatures: {},
  103880. serial: serial,
  103881. validFrom: validFrom,
  103882. validUntil: validUntil,
  103883. purposes: purposes
  103884. });
  103885. cert.signWith(issuerKey);
  103886. return (cert);
  103887. };
  103888. Certificate.parse = function (data, format, options) {
  103889. if (typeof (data) !== 'string')
  103890. assert.buffer(data, 'data');
  103891. if (format === undefined)
  103892. format = 'auto';
  103893. assert.string(format, 'format');
  103894. if (typeof (options) === 'string')
  103895. options = { filename: options };
  103896. assert.optionalObject(options, 'options');
  103897. if (options === undefined)
  103898. options = {};
  103899. assert.optionalString(options.filename, 'options.filename');
  103900. if (options.filename === undefined)
  103901. options.filename = '(unnamed)';
  103902. assert.object(formats[format], 'formats[format]');
  103903. try {
  103904. var k = formats[format].read(data, options);
  103905. return (k);
  103906. } catch (e) {
  103907. throw (new CertificateParseError(options.filename, format, e));
  103908. }
  103909. };
  103910. Certificate.isCertificate = function (obj, ver) {
  103911. return (utils.isCompatible(obj, Certificate, ver));
  103912. };
  103913. /*
  103914. * API versions for Certificate:
  103915. * [1,0] -- initial ver
  103916. * [1,1] -- openssh format now unpacks extensions
  103917. */
  103918. Certificate.prototype._sshpkApiVersion = [1, 1];
  103919. Certificate._oldVersionDetect = function (obj) {
  103920. return ([1, 0]);
  103921. };
  103922. },{"./algs":572,"./errors":576,"./fingerprint":577,"./formats/openssh-cert":580,"./formats/x509":589,"./formats/x509-pem":588,"./identity":590,"./key":592,"./private-key":593,"./signature":594,"./utils":596,"assert-plus":104,"crypto":208,"safer-buffer":562,"util":658}],574:[function(require,module,exports){
  103923. // Copyright 2017 Joyent, Inc.
  103924. module.exports = {
  103925. DiffieHellman: DiffieHellman,
  103926. generateECDSA: generateECDSA,
  103927. generateED25519: generateED25519
  103928. };
  103929. var assert = require('assert-plus');
  103930. var crypto = require('crypto');
  103931. var Buffer = require('safer-buffer').Buffer;
  103932. var algs = require('./algs');
  103933. var utils = require('./utils');
  103934. var nacl = require('tweetnacl');
  103935. var Key = require('./key');
  103936. var PrivateKey = require('./private-key');
  103937. var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined);
  103938. var ecdh = require('ecc-jsbn');
  103939. var ec = require('ecc-jsbn/lib/ec');
  103940. var jsbn = require('jsbn').BigInteger;
  103941. function DiffieHellman(key) {
  103942. utils.assertCompatible(key, Key, [1, 4], 'key');
  103943. this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]);
  103944. this._algo = key.type;
  103945. this._curve = key.curve;
  103946. this._key = key;
  103947. if (key.type === 'dsa') {
  103948. if (!CRYPTO_HAVE_ECDH) {
  103949. throw (new Error('Due to bugs in the node 0.10 ' +
  103950. 'crypto API, node 0.12.x or later is required ' +
  103951. 'to use DH'));
  103952. }
  103953. this._dh = crypto.createDiffieHellman(
  103954. key.part.p.data, undefined,
  103955. key.part.g.data, undefined);
  103956. this._p = key.part.p;
  103957. this._g = key.part.g;
  103958. if (this._isPriv)
  103959. this._dh.setPrivateKey(key.part.x.data);
  103960. this._dh.setPublicKey(key.part.y.data);
  103961. } else if (key.type === 'ecdsa') {
  103962. if (!CRYPTO_HAVE_ECDH) {
  103963. this._ecParams = new X9ECParameters(this._curve);
  103964. if (this._isPriv) {
  103965. this._priv = new ECPrivate(
  103966. this._ecParams, key.part.d.data);
  103967. }
  103968. return;
  103969. }
  103970. var curve = {
  103971. 'nistp256': 'prime256v1',
  103972. 'nistp384': 'secp384r1',
  103973. 'nistp521': 'secp521r1'
  103974. }[key.curve];
  103975. this._dh = crypto.createECDH(curve);
  103976. if (typeof (this._dh) !== 'object' ||
  103977. typeof (this._dh.setPrivateKey) !== 'function') {
  103978. CRYPTO_HAVE_ECDH = false;
  103979. DiffieHellman.call(this, key);
  103980. return;
  103981. }
  103982. if (this._isPriv)
  103983. this._dh.setPrivateKey(key.part.d.data);
  103984. this._dh.setPublicKey(key.part.Q.data);
  103985. } else if (key.type === 'curve25519') {
  103986. if (this._isPriv) {
  103987. utils.assertCompatible(key, PrivateKey, [1, 5], 'key');
  103988. this._priv = key.part.k.data;
  103989. }
  103990. } else {
  103991. throw (new Error('DH not supported for ' + key.type + ' keys'));
  103992. }
  103993. }
  103994. DiffieHellman.prototype.getPublicKey = function () {
  103995. if (this._isPriv)
  103996. return (this._key.toPublic());
  103997. return (this._key);
  103998. };
  103999. DiffieHellman.prototype.getPrivateKey = function () {
  104000. if (this._isPriv)
  104001. return (this._key);
  104002. else
  104003. return (undefined);
  104004. };
  104005. DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey;
  104006. DiffieHellman.prototype._keyCheck = function (pk, isPub) {
  104007. assert.object(pk, 'key');
  104008. if (!isPub)
  104009. utils.assertCompatible(pk, PrivateKey, [1, 3], 'key');
  104010. utils.assertCompatible(pk, Key, [1, 4], 'key');
  104011. if (pk.type !== this._algo) {
  104012. throw (new Error('A ' + pk.type + ' key cannot be used in ' +
  104013. this._algo + ' Diffie-Hellman'));
  104014. }
  104015. if (pk.curve !== this._curve) {
  104016. throw (new Error('A key from the ' + pk.curve + ' curve ' +
  104017. 'cannot be used with a ' + this._curve +
  104018. ' Diffie-Hellman'));
  104019. }
  104020. if (pk.type === 'dsa') {
  104021. assert.deepEqual(pk.part.p, this._p,
  104022. 'DSA key prime does not match');
  104023. assert.deepEqual(pk.part.g, this._g,
  104024. 'DSA key generator does not match');
  104025. }
  104026. };
  104027. DiffieHellman.prototype.setKey = function (pk) {
  104028. this._keyCheck(pk);
  104029. if (pk.type === 'dsa') {
  104030. this._dh.setPrivateKey(pk.part.x.data);
  104031. this._dh.setPublicKey(pk.part.y.data);
  104032. } else if (pk.type === 'ecdsa') {
  104033. if (CRYPTO_HAVE_ECDH) {
  104034. this._dh.setPrivateKey(pk.part.d.data);
  104035. this._dh.setPublicKey(pk.part.Q.data);
  104036. } else {
  104037. this._priv = new ECPrivate(
  104038. this._ecParams, pk.part.d.data);
  104039. }
  104040. } else if (pk.type === 'curve25519') {
  104041. var k = pk.part.k;
  104042. if (!pk.part.k)
  104043. k = pk.part.r;
  104044. this._priv = k.data;
  104045. if (this._priv[0] === 0x00)
  104046. this._priv = this._priv.slice(1);
  104047. this._priv = this._priv.slice(0, 32);
  104048. }
  104049. this._key = pk;
  104050. this._isPriv = true;
  104051. };
  104052. DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey;
  104053. DiffieHellman.prototype.computeSecret = function (otherpk) {
  104054. this._keyCheck(otherpk, true);
  104055. if (!this._isPriv)
  104056. throw (new Error('DH exchange has not been initialized with ' +
  104057. 'a private key yet'));
  104058. var pub;
  104059. if (this._algo === 'dsa') {
  104060. return (this._dh.computeSecret(
  104061. otherpk.part.y.data));
  104062. } else if (this._algo === 'ecdsa') {
  104063. if (CRYPTO_HAVE_ECDH) {
  104064. return (this._dh.computeSecret(
  104065. otherpk.part.Q.data));
  104066. } else {
  104067. pub = new ECPublic(
  104068. this._ecParams, otherpk.part.Q.data);
  104069. return (this._priv.deriveSharedSecret(pub));
  104070. }
  104071. } else if (this._algo === 'curve25519') {
  104072. pub = otherpk.part.A.data;
  104073. while (pub[0] === 0x00 && pub.length > 32)
  104074. pub = pub.slice(1);
  104075. var priv = this._priv;
  104076. assert.strictEqual(pub.length, 32);
  104077. assert.strictEqual(priv.length, 32);
  104078. var secret = nacl.box.before(new Uint8Array(pub),
  104079. new Uint8Array(priv));
  104080. return (Buffer.from(secret));
  104081. }
  104082. throw (new Error('Invalid algorithm: ' + this._algo));
  104083. };
  104084. DiffieHellman.prototype.generateKey = function () {
  104085. var parts = [];
  104086. var priv, pub;
  104087. if (this._algo === 'dsa') {
  104088. this._dh.generateKeys();
  104089. parts.push({name: 'p', data: this._p.data});
  104090. parts.push({name: 'q', data: this._key.part.q.data});
  104091. parts.push({name: 'g', data: this._g.data});
  104092. parts.push({name: 'y', data: this._dh.getPublicKey()});
  104093. parts.push({name: 'x', data: this._dh.getPrivateKey()});
  104094. this._key = new PrivateKey({
  104095. type: 'dsa',
  104096. parts: parts
  104097. });
  104098. this._isPriv = true;
  104099. return (this._key);
  104100. } else if (this._algo === 'ecdsa') {
  104101. if (CRYPTO_HAVE_ECDH) {
  104102. this._dh.generateKeys();
  104103. parts.push({name: 'curve',
  104104. data: Buffer.from(this._curve)});
  104105. parts.push({name: 'Q', data: this._dh.getPublicKey()});
  104106. parts.push({name: 'd', data: this._dh.getPrivateKey()});
  104107. this._key = new PrivateKey({
  104108. type: 'ecdsa',
  104109. curve: this._curve,
  104110. parts: parts
  104111. });
  104112. this._isPriv = true;
  104113. return (this._key);
  104114. } else {
  104115. var n = this._ecParams.getN();
  104116. var r = new jsbn(crypto.randomBytes(n.bitLength()));
  104117. var n1 = n.subtract(jsbn.ONE);
  104118. priv = r.mod(n1).add(jsbn.ONE);
  104119. pub = this._ecParams.getG().multiply(priv);
  104120. priv = Buffer.from(priv.toByteArray());
  104121. pub = Buffer.from(this._ecParams.getCurve().
  104122. encodePointHex(pub), 'hex');
  104123. this._priv = new ECPrivate(this._ecParams, priv);
  104124. parts.push({name: 'curve',
  104125. data: Buffer.from(this._curve)});
  104126. parts.push({name: 'Q', data: pub});
  104127. parts.push({name: 'd', data: priv});
  104128. this._key = new PrivateKey({
  104129. type: 'ecdsa',
  104130. curve: this._curve,
  104131. parts: parts
  104132. });
  104133. this._isPriv = true;
  104134. return (this._key);
  104135. }
  104136. } else if (this._algo === 'curve25519') {
  104137. var pair = nacl.box.keyPair();
  104138. priv = Buffer.from(pair.secretKey);
  104139. pub = Buffer.from(pair.publicKey);
  104140. priv = Buffer.concat([priv, pub]);
  104141. assert.strictEqual(priv.length, 64);
  104142. assert.strictEqual(pub.length, 32);
  104143. parts.push({name: 'A', data: pub});
  104144. parts.push({name: 'k', data: priv});
  104145. this._key = new PrivateKey({
  104146. type: 'curve25519',
  104147. parts: parts
  104148. });
  104149. this._isPriv = true;
  104150. return (this._key);
  104151. }
  104152. throw (new Error('Invalid algorithm: ' + this._algo));
  104153. };
  104154. DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey;
  104155. /* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */
  104156. function X9ECParameters(name) {
  104157. var params = algs.curves[name];
  104158. assert.object(params);
  104159. var p = new jsbn(params.p);
  104160. var a = new jsbn(params.a);
  104161. var b = new jsbn(params.b);
  104162. var n = new jsbn(params.n);
  104163. var h = jsbn.ONE;
  104164. var curve = new ec.ECCurveFp(p, a, b);
  104165. var G = curve.decodePointHex(params.G.toString('hex'));
  104166. this.curve = curve;
  104167. this.g = G;
  104168. this.n = n;
  104169. this.h = h;
  104170. }
  104171. X9ECParameters.prototype.getCurve = function () { return (this.curve); };
  104172. X9ECParameters.prototype.getG = function () { return (this.g); };
  104173. X9ECParameters.prototype.getN = function () { return (this.n); };
  104174. X9ECParameters.prototype.getH = function () { return (this.h); };
  104175. function ECPublic(params, buffer) {
  104176. this._params = params;
  104177. if (buffer[0] === 0x00)
  104178. buffer = buffer.slice(1);
  104179. this._pub = params.getCurve().decodePointHex(buffer.toString('hex'));
  104180. }
  104181. function ECPrivate(params, buffer) {
  104182. this._params = params;
  104183. this._priv = new jsbn(utils.mpNormalize(buffer));
  104184. }
  104185. ECPrivate.prototype.deriveSharedSecret = function (pubKey) {
  104186. assert.ok(pubKey instanceof ECPublic);
  104187. var S = pubKey._pub.multiply(this._priv);
  104188. return (Buffer.from(S.getX().toBigInteger().toByteArray()));
  104189. };
  104190. function generateED25519() {
  104191. var pair = nacl.sign.keyPair();
  104192. var priv = Buffer.from(pair.secretKey);
  104193. var pub = Buffer.from(pair.publicKey);
  104194. assert.strictEqual(priv.length, 64);
  104195. assert.strictEqual(pub.length, 32);
  104196. var parts = [];
  104197. parts.push({name: 'A', data: pub});
  104198. parts.push({name: 'k', data: priv.slice(0, 32)});
  104199. var key = new PrivateKey({
  104200. type: 'ed25519',
  104201. parts: parts
  104202. });
  104203. return (key);
  104204. }
  104205. /* Generates a new ECDSA private key on a given curve. */
  104206. function generateECDSA(curve) {
  104207. var parts = [];
  104208. var key;
  104209. if (CRYPTO_HAVE_ECDH) {
  104210. /*
  104211. * Node crypto doesn't expose key generation directly, but the
  104212. * ECDH instances can generate keys. It turns out this just
  104213. * calls into the OpenSSL generic key generator, and we can
  104214. * read its output happily without doing an actual DH. So we
  104215. * use that here.
  104216. */
  104217. var osCurve = {
  104218. 'nistp256': 'prime256v1',
  104219. 'nistp384': 'secp384r1',
  104220. 'nistp521': 'secp521r1'
  104221. }[curve];
  104222. var dh = crypto.createECDH(osCurve);
  104223. dh.generateKeys();
  104224. parts.push({name: 'curve',
  104225. data: Buffer.from(curve)});
  104226. parts.push({name: 'Q', data: dh.getPublicKey()});
  104227. parts.push({name: 'd', data: dh.getPrivateKey()});
  104228. key = new PrivateKey({
  104229. type: 'ecdsa',
  104230. curve: curve,
  104231. parts: parts
  104232. });
  104233. return (key);
  104234. } else {
  104235. var ecParams = new X9ECParameters(curve);
  104236. /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */
  104237. var n = ecParams.getN();
  104238. /*
  104239. * The crypto.randomBytes() function can only give us whole
  104240. * bytes, so taking a nod from X9.62, we round up.
  104241. */
  104242. var cByteLen = Math.ceil((n.bitLength() + 64) / 8);
  104243. var c = new jsbn(crypto.randomBytes(cByteLen));
  104244. var n1 = n.subtract(jsbn.ONE);
  104245. var priv = c.mod(n1).add(jsbn.ONE);
  104246. var pub = ecParams.getG().multiply(priv);
  104247. priv = Buffer.from(priv.toByteArray());
  104248. pub = Buffer.from(ecParams.getCurve().
  104249. encodePointHex(pub), 'hex');
  104250. parts.push({name: 'curve', data: Buffer.from(curve)});
  104251. parts.push({name: 'Q', data: pub});
  104252. parts.push({name: 'd', data: priv});
  104253. key = new PrivateKey({
  104254. type: 'ecdsa',
  104255. curve: curve,
  104256. parts: parts
  104257. });
  104258. return (key);
  104259. }
  104260. }
  104261. },{"./algs":572,"./key":592,"./private-key":593,"./utils":596,"assert-plus":104,"crypto":208,"ecc-jsbn":223,"ecc-jsbn/lib/ec":224,"jsbn":328,"safer-buffer":562,"tweetnacl":650}],575:[function(require,module,exports){
  104262. // Copyright 2015 Joyent, Inc.
  104263. module.exports = {
  104264. Verifier: Verifier,
  104265. Signer: Signer
  104266. };
  104267. var nacl = require('tweetnacl');
  104268. var stream = require('stream');
  104269. var util = require('util');
  104270. var assert = require('assert-plus');
  104271. var Buffer = require('safer-buffer').Buffer;
  104272. var Signature = require('./signature');
  104273. function Verifier(key, hashAlgo) {
  104274. if (hashAlgo.toLowerCase() !== 'sha512')
  104275. throw (new Error('ED25519 only supports the use of ' +
  104276. 'SHA-512 hashes'));
  104277. this.key = key;
  104278. this.chunks = [];
  104279. stream.Writable.call(this, {});
  104280. }
  104281. util.inherits(Verifier, stream.Writable);
  104282. Verifier.prototype._write = function (chunk, enc, cb) {
  104283. this.chunks.push(chunk);
  104284. cb();
  104285. };
  104286. Verifier.prototype.update = function (chunk) {
  104287. if (typeof (chunk) === 'string')
  104288. chunk = Buffer.from(chunk, 'binary');
  104289. this.chunks.push(chunk);
  104290. };
  104291. Verifier.prototype.verify = function (signature, fmt) {
  104292. var sig;
  104293. if (Signature.isSignature(signature, [2, 0])) {
  104294. if (signature.type !== 'ed25519')
  104295. return (false);
  104296. sig = signature.toBuffer('raw');
  104297. } else if (typeof (signature) === 'string') {
  104298. sig = Buffer.from(signature, 'base64');
  104299. } else if (Signature.isSignature(signature, [1, 0])) {
  104300. throw (new Error('signature was created by too old ' +
  104301. 'a version of sshpk and cannot be verified'));
  104302. }
  104303. assert.buffer(sig);
  104304. return (nacl.sign.detached.verify(
  104305. new Uint8Array(Buffer.concat(this.chunks)),
  104306. new Uint8Array(sig),
  104307. new Uint8Array(this.key.part.A.data)));
  104308. };
  104309. function Signer(key, hashAlgo) {
  104310. if (hashAlgo.toLowerCase() !== 'sha512')
  104311. throw (new Error('ED25519 only supports the use of ' +
  104312. 'SHA-512 hashes'));
  104313. this.key = key;
  104314. this.chunks = [];
  104315. stream.Writable.call(this, {});
  104316. }
  104317. util.inherits(Signer, stream.Writable);
  104318. Signer.prototype._write = function (chunk, enc, cb) {
  104319. this.chunks.push(chunk);
  104320. cb();
  104321. };
  104322. Signer.prototype.update = function (chunk) {
  104323. if (typeof (chunk) === 'string')
  104324. chunk = Buffer.from(chunk, 'binary');
  104325. this.chunks.push(chunk);
  104326. };
  104327. Signer.prototype.sign = function () {
  104328. var sig = nacl.sign.detached(
  104329. new Uint8Array(Buffer.concat(this.chunks)),
  104330. new Uint8Array(Buffer.concat([
  104331. this.key.part.k.data, this.key.part.A.data])));
  104332. var sigBuf = Buffer.from(sig);
  104333. var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw');
  104334. sigObj.hashAlgorithm = 'sha512';
  104335. return (sigObj);
  104336. };
  104337. },{"./signature":594,"assert-plus":104,"safer-buffer":562,"stream":597,"tweetnacl":650,"util":658}],576:[function(require,module,exports){
  104338. // Copyright 2015 Joyent, Inc.
  104339. var assert = require('assert-plus');
  104340. var util = require('util');
  104341. function FingerprintFormatError(fp, format) {
  104342. if (Error.captureStackTrace)
  104343. Error.captureStackTrace(this, FingerprintFormatError);
  104344. this.name = 'FingerprintFormatError';
  104345. this.fingerprint = fp;
  104346. this.format = format;
  104347. this.message = 'Fingerprint format is not supported, or is invalid: ';
  104348. if (fp !== undefined)
  104349. this.message += ' fingerprint = ' + fp;
  104350. if (format !== undefined)
  104351. this.message += ' format = ' + format;
  104352. }
  104353. util.inherits(FingerprintFormatError, Error);
  104354. function InvalidAlgorithmError(alg) {
  104355. if (Error.captureStackTrace)
  104356. Error.captureStackTrace(this, InvalidAlgorithmError);
  104357. this.name = 'InvalidAlgorithmError';
  104358. this.algorithm = alg;
  104359. this.message = 'Algorithm "' + alg + '" is not supported';
  104360. }
  104361. util.inherits(InvalidAlgorithmError, Error);
  104362. function KeyParseError(name, format, innerErr) {
  104363. if (Error.captureStackTrace)
  104364. Error.captureStackTrace(this, KeyParseError);
  104365. this.name = 'KeyParseError';
  104366. this.format = format;
  104367. this.keyName = name;
  104368. this.innerErr = innerErr;
  104369. this.message = 'Failed to parse ' + name + ' as a valid ' + format +
  104370. ' format key: ' + innerErr.message;
  104371. }
  104372. util.inherits(KeyParseError, Error);
  104373. function SignatureParseError(type, format, innerErr) {
  104374. if (Error.captureStackTrace)
  104375. Error.captureStackTrace(this, SignatureParseError);
  104376. this.name = 'SignatureParseError';
  104377. this.type = type;
  104378. this.format = format;
  104379. this.innerErr = innerErr;
  104380. this.message = 'Failed to parse the given data as a ' + type +
  104381. ' signature in ' + format + ' format: ' + innerErr.message;
  104382. }
  104383. util.inherits(SignatureParseError, Error);
  104384. function CertificateParseError(name, format, innerErr) {
  104385. if (Error.captureStackTrace)
  104386. Error.captureStackTrace(this, CertificateParseError);
  104387. this.name = 'CertificateParseError';
  104388. this.format = format;
  104389. this.certName = name;
  104390. this.innerErr = innerErr;
  104391. this.message = 'Failed to parse ' + name + ' as a valid ' + format +
  104392. ' format certificate: ' + innerErr.message;
  104393. }
  104394. util.inherits(CertificateParseError, Error);
  104395. function KeyEncryptedError(name, format) {
  104396. if (Error.captureStackTrace)
  104397. Error.captureStackTrace(this, KeyEncryptedError);
  104398. this.name = 'KeyEncryptedError';
  104399. this.format = format;
  104400. this.keyName = name;
  104401. this.message = 'The ' + format + ' format key ' + name + ' is ' +
  104402. 'encrypted (password-protected), and no passphrase was ' +
  104403. 'provided in `options`';
  104404. }
  104405. util.inherits(KeyEncryptedError, Error);
  104406. module.exports = {
  104407. FingerprintFormatError: FingerprintFormatError,
  104408. InvalidAlgorithmError: InvalidAlgorithmError,
  104409. KeyParseError: KeyParseError,
  104410. SignatureParseError: SignatureParseError,
  104411. KeyEncryptedError: KeyEncryptedError,
  104412. CertificateParseError: CertificateParseError
  104413. };
  104414. },{"assert-plus":104,"util":658}],577:[function(require,module,exports){
  104415. // Copyright 2018 Joyent, Inc.
  104416. module.exports = Fingerprint;
  104417. var assert = require('assert-plus');
  104418. var Buffer = require('safer-buffer').Buffer;
  104419. var algs = require('./algs');
  104420. var crypto = require('crypto');
  104421. var errs = require('./errors');
  104422. var Key = require('./key');
  104423. var PrivateKey = require('./private-key');
  104424. var Certificate = require('./certificate');
  104425. var utils = require('./utils');
  104426. var FingerprintFormatError = errs.FingerprintFormatError;
  104427. var InvalidAlgorithmError = errs.InvalidAlgorithmError;
  104428. function Fingerprint(opts) {
  104429. assert.object(opts, 'options');
  104430. assert.string(opts.type, 'options.type');
  104431. assert.buffer(opts.hash, 'options.hash');
  104432. assert.string(opts.algorithm, 'options.algorithm');
  104433. this.algorithm = opts.algorithm.toLowerCase();
  104434. if (algs.hashAlgs[this.algorithm] !== true)
  104435. throw (new InvalidAlgorithmError(this.algorithm));
  104436. this.hash = opts.hash;
  104437. this.type = opts.type;
  104438. this.hashType = opts.hashType;
  104439. }
  104440. Fingerprint.prototype.toString = function (format) {
  104441. if (format === undefined) {
  104442. if (this.algorithm === 'md5' || this.hashType === 'spki')
  104443. format = 'hex';
  104444. else
  104445. format = 'base64';
  104446. }
  104447. assert.string(format);
  104448. switch (format) {
  104449. case 'hex':
  104450. if (this.hashType === 'spki')
  104451. return (this.hash.toString('hex'));
  104452. return (addColons(this.hash.toString('hex')));
  104453. case 'base64':
  104454. if (this.hashType === 'spki')
  104455. return (this.hash.toString('base64'));
  104456. return (sshBase64Format(this.algorithm,
  104457. this.hash.toString('base64')));
  104458. default:
  104459. throw (new FingerprintFormatError(undefined, format));
  104460. }
  104461. };
  104462. Fingerprint.prototype.matches = function (other) {
  104463. assert.object(other, 'key or certificate');
  104464. if (this.type === 'key' && this.hashType !== 'ssh') {
  104465. utils.assertCompatible(other, Key, [1, 7], 'key with spki');
  104466. if (PrivateKey.isPrivateKey(other)) {
  104467. utils.assertCompatible(other, PrivateKey, [1, 6],
  104468. 'privatekey with spki support');
  104469. }
  104470. } else if (this.type === 'key') {
  104471. utils.assertCompatible(other, Key, [1, 0], 'key');
  104472. } else {
  104473. utils.assertCompatible(other, Certificate, [1, 0],
  104474. 'certificate');
  104475. }
  104476. var theirHash = other.hash(this.algorithm, this.hashType);
  104477. var theirHash2 = crypto.createHash(this.algorithm).
  104478. update(theirHash).digest('base64');
  104479. if (this.hash2 === undefined)
  104480. this.hash2 = crypto.createHash(this.algorithm).
  104481. update(this.hash).digest('base64');
  104482. return (this.hash2 === theirHash2);
  104483. };
  104484. /*JSSTYLED*/
  104485. var base64RE = /^[A-Za-z0-9+\/=]+$/;
  104486. /*JSSTYLED*/
  104487. var hexRE = /^[a-fA-F0-9]+$/;
  104488. Fingerprint.parse = function (fp, options) {
  104489. assert.string(fp, 'fingerprint');
  104490. var alg, hash, enAlgs;
  104491. if (Array.isArray(options)) {
  104492. enAlgs = options;
  104493. options = {};
  104494. }
  104495. assert.optionalObject(options, 'options');
  104496. if (options === undefined)
  104497. options = {};
  104498. if (options.enAlgs !== undefined)
  104499. enAlgs = options.enAlgs;
  104500. if (options.algorithms !== undefined)
  104501. enAlgs = options.algorithms;
  104502. assert.optionalArrayOfString(enAlgs, 'algorithms');
  104503. var hashType = 'ssh';
  104504. if (options.hashType !== undefined)
  104505. hashType = options.hashType;
  104506. assert.string(hashType, 'options.hashType');
  104507. var parts = fp.split(':');
  104508. if (parts.length == 2) {
  104509. alg = parts[0].toLowerCase();
  104510. if (!base64RE.test(parts[1]))
  104511. throw (new FingerprintFormatError(fp));
  104512. try {
  104513. hash = Buffer.from(parts[1], 'base64');
  104514. } catch (e) {
  104515. throw (new FingerprintFormatError(fp));
  104516. }
  104517. } else if (parts.length > 2) {
  104518. alg = 'md5';
  104519. if (parts[0].toLowerCase() === 'md5')
  104520. parts = parts.slice(1);
  104521. parts = parts.map(function (p) {
  104522. while (p.length < 2)
  104523. p = '0' + p;
  104524. if (p.length > 2)
  104525. throw (new FingerprintFormatError(fp));
  104526. return (p);
  104527. });
  104528. parts = parts.join('');
  104529. if (!hexRE.test(parts) || parts.length % 2 !== 0)
  104530. throw (new FingerprintFormatError(fp));
  104531. try {
  104532. hash = Buffer.from(parts, 'hex');
  104533. } catch (e) {
  104534. throw (new FingerprintFormatError(fp));
  104535. }
  104536. } else {
  104537. if (hexRE.test(fp)) {
  104538. hash = Buffer.from(fp, 'hex');
  104539. } else if (base64RE.test(fp)) {
  104540. hash = Buffer.from(fp, 'base64');
  104541. } else {
  104542. throw (new FingerprintFormatError(fp));
  104543. }
  104544. switch (hash.length) {
  104545. case 32:
  104546. alg = 'sha256';
  104547. break;
  104548. case 16:
  104549. alg = 'md5';
  104550. break;
  104551. case 20:
  104552. alg = 'sha1';
  104553. break;
  104554. case 64:
  104555. alg = 'sha512';
  104556. break;
  104557. default:
  104558. throw (new FingerprintFormatError(fp));
  104559. }
  104560. /* Plain hex/base64: guess it's probably SPKI unless told. */
  104561. if (options.hashType === undefined)
  104562. hashType = 'spki';
  104563. }
  104564. if (alg === undefined)
  104565. throw (new FingerprintFormatError(fp));
  104566. if (algs.hashAlgs[alg] === undefined)
  104567. throw (new InvalidAlgorithmError(alg));
  104568. if (enAlgs !== undefined) {
  104569. enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); });
  104570. if (enAlgs.indexOf(alg) === -1)
  104571. throw (new InvalidAlgorithmError(alg));
  104572. }
  104573. return (new Fingerprint({
  104574. algorithm: alg,
  104575. hash: hash,
  104576. type: options.type || 'key',
  104577. hashType: hashType
  104578. }));
  104579. };
  104580. function addColons(s) {
  104581. /*JSSTYLED*/
  104582. return (s.replace(/(.{2})(?=.)/g, '$1:'));
  104583. }
  104584. function base64Strip(s) {
  104585. /*JSSTYLED*/
  104586. return (s.replace(/=*$/, ''));
  104587. }
  104588. function sshBase64Format(alg, h) {
  104589. return (alg.toUpperCase() + ':' + base64Strip(h));
  104590. }
  104591. Fingerprint.isFingerprint = function (obj, ver) {
  104592. return (utils.isCompatible(obj, Fingerprint, ver));
  104593. };
  104594. /*
  104595. * API versions for Fingerprint:
  104596. * [1,0] -- initial ver
  104597. * [1,1] -- first tagged ver
  104598. * [1,2] -- hashType and spki support
  104599. */
  104600. Fingerprint.prototype._sshpkApiVersion = [1, 2];
  104601. Fingerprint._oldVersionDetect = function (obj) {
  104602. assert.func(obj.toString);
  104603. assert.func(obj.matches);
  104604. return ([1, 0]);
  104605. };
  104606. },{"./algs":572,"./certificate":573,"./errors":576,"./key":592,"./private-key":593,"./utils":596,"assert-plus":104,"crypto":208,"safer-buffer":562}],578:[function(require,module,exports){
  104607. // Copyright 2018 Joyent, Inc.
  104608. module.exports = {
  104609. read: read,
  104610. write: write
  104611. };
  104612. var assert = require('assert-plus');
  104613. var Buffer = require('safer-buffer').Buffer;
  104614. var utils = require('../utils');
  104615. var Key = require('../key');
  104616. var PrivateKey = require('../private-key');
  104617. var pem = require('./pem');
  104618. var ssh = require('./ssh');
  104619. var rfc4253 = require('./rfc4253');
  104620. var dnssec = require('./dnssec');
  104621. var putty = require('./putty');
  104622. var DNSSEC_PRIVKEY_HEADER_PREFIX = 'Private-key-format: v1';
  104623. function read(buf, options) {
  104624. if (typeof (buf) === 'string') {
  104625. if (buf.trim().match(/^[-]+[ ]*BEGIN/))
  104626. return (pem.read(buf, options));
  104627. if (buf.match(/^\s*ssh-[a-z]/))
  104628. return (ssh.read(buf, options));
  104629. if (buf.match(/^\s*ecdsa-/))
  104630. return (ssh.read(buf, options));
  104631. if (buf.match(/^putty-user-key-file-2:/i))
  104632. return (putty.read(buf, options));
  104633. if (findDNSSECHeader(buf))
  104634. return (dnssec.read(buf, options));
  104635. buf = Buffer.from(buf, 'binary');
  104636. } else {
  104637. assert.buffer(buf);
  104638. if (findPEMHeader(buf))
  104639. return (pem.read(buf, options));
  104640. if (findSSHHeader(buf))
  104641. return (ssh.read(buf, options));
  104642. if (findPuTTYHeader(buf))
  104643. return (putty.read(buf, options));
  104644. if (findDNSSECHeader(buf))
  104645. return (dnssec.read(buf, options));
  104646. }
  104647. if (buf.readUInt32BE(0) < buf.length)
  104648. return (rfc4253.read(buf, options));
  104649. throw (new Error('Failed to auto-detect format of key'));
  104650. }
  104651. function findPuTTYHeader(buf) {
  104652. var offset = 0;
  104653. while (offset < buf.length &&
  104654. (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
  104655. ++offset;
  104656. if (offset + 22 <= buf.length &&
  104657. buf.slice(offset, offset + 22).toString('ascii').toLowerCase() ===
  104658. 'putty-user-key-file-2:')
  104659. return (true);
  104660. return (false);
  104661. }
  104662. function findSSHHeader(buf) {
  104663. var offset = 0;
  104664. while (offset < buf.length &&
  104665. (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
  104666. ++offset;
  104667. if (offset + 4 <= buf.length &&
  104668. buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
  104669. return (true);
  104670. if (offset + 6 <= buf.length &&
  104671. buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
  104672. return (true);
  104673. return (false);
  104674. }
  104675. function findPEMHeader(buf) {
  104676. var offset = 0;
  104677. while (offset < buf.length &&
  104678. (buf[offset] === 32 || buf[offset] === 10))
  104679. ++offset;
  104680. if (buf[offset] !== 45)
  104681. return (false);
  104682. while (offset < buf.length &&
  104683. (buf[offset] === 45))
  104684. ++offset;
  104685. while (offset < buf.length &&
  104686. (buf[offset] === 32))
  104687. ++offset;
  104688. if (offset + 5 > buf.length ||
  104689. buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
  104690. return (false);
  104691. return (true);
  104692. }
  104693. function findDNSSECHeader(buf) {
  104694. // private case first
  104695. if (buf.length <= DNSSEC_PRIVKEY_HEADER_PREFIX.length)
  104696. return (false);
  104697. var headerCheck = buf.slice(0, DNSSEC_PRIVKEY_HEADER_PREFIX.length);
  104698. if (headerCheck.toString('ascii') === DNSSEC_PRIVKEY_HEADER_PREFIX)
  104699. return (true);
  104700. // public-key RFC3110 ?
  104701. // 'domain.com. IN KEY ...' or 'domain.com. IN DNSKEY ...'
  104702. // skip any comment-lines
  104703. if (typeof (buf) !== 'string') {
  104704. buf = buf.toString('ascii');
  104705. }
  104706. var lines = buf.split('\n');
  104707. var line = 0;
  104708. /* JSSTYLED */
  104709. while (lines[line].match(/^\;/))
  104710. line++;
  104711. if (lines[line].toString('ascii').match(/\. IN KEY /))
  104712. return (true);
  104713. if (lines[line].toString('ascii').match(/\. IN DNSKEY /))
  104714. return (true);
  104715. return (false);
  104716. }
  104717. function write(key, options) {
  104718. throw (new Error('"auto" format cannot be used for writing'));
  104719. }
  104720. },{"../key":592,"../private-key":593,"../utils":596,"./dnssec":579,"./pem":581,"./putty":584,"./rfc4253":585,"./ssh":587,"assert-plus":104,"safer-buffer":562}],579:[function(require,module,exports){
  104721. // Copyright 2017 Joyent, Inc.
  104722. module.exports = {
  104723. read: read,
  104724. write: write
  104725. };
  104726. var assert = require('assert-plus');
  104727. var Buffer = require('safer-buffer').Buffer;
  104728. var Key = require('../key');
  104729. var PrivateKey = require('../private-key');
  104730. var utils = require('../utils');
  104731. var SSHBuffer = require('../ssh-buffer');
  104732. var Dhe = require('../dhe');
  104733. var supportedAlgos = {
  104734. 'rsa-sha1' : 5,
  104735. 'rsa-sha256' : 8,
  104736. 'rsa-sha512' : 10,
  104737. 'ecdsa-p256-sha256' : 13,
  104738. 'ecdsa-p384-sha384' : 14
  104739. /*
  104740. * ed25519 is hypothetically supported with id 15
  104741. * but the common tools available don't appear to be
  104742. * capable of generating/using ed25519 keys
  104743. */
  104744. };
  104745. var supportedAlgosById = {};
  104746. Object.keys(supportedAlgos).forEach(function (k) {
  104747. supportedAlgosById[supportedAlgos[k]] = k.toUpperCase();
  104748. });
  104749. function read(buf, options) {
  104750. if (typeof (buf) !== 'string') {
  104751. assert.buffer(buf, 'buf');
  104752. buf = buf.toString('ascii');
  104753. }
  104754. var lines = buf.split('\n');
  104755. if (lines[0].match(/^Private-key-format\: v1/)) {
  104756. var algElems = lines[1].split(' ');
  104757. var algoNum = parseInt(algElems[1], 10);
  104758. var algoName = algElems[2];
  104759. if (!supportedAlgosById[algoNum])
  104760. throw (new Error('Unsupported algorithm: ' + algoName));
  104761. return (readDNSSECPrivateKey(algoNum, lines.slice(2)));
  104762. }
  104763. // skip any comment-lines
  104764. var line = 0;
  104765. /* JSSTYLED */
  104766. while (lines[line].match(/^\;/))
  104767. line++;
  104768. // we should now have *one single* line left with our KEY on it.
  104769. if ((lines[line].match(/\. IN KEY /) ||
  104770. lines[line].match(/\. IN DNSKEY /)) && lines[line+1].length === 0) {
  104771. return (readRFC3110(lines[line]));
  104772. }
  104773. throw (new Error('Cannot parse dnssec key'));
  104774. }
  104775. function readRFC3110(keyString) {
  104776. var elems = keyString.split(' ');
  104777. //unused var flags = parseInt(elems[3], 10);
  104778. //unused var protocol = parseInt(elems[4], 10);
  104779. var algorithm = parseInt(elems[5], 10);
  104780. if (!supportedAlgosById[algorithm])
  104781. throw (new Error('Unsupported algorithm: ' + algorithm));
  104782. var base64key = elems.slice(6, elems.length).join();
  104783. var keyBuffer = Buffer.from(base64key, 'base64');
  104784. if (supportedAlgosById[algorithm].match(/^RSA-/)) {
  104785. // join the rest of the body into a single base64-blob
  104786. var publicExponentLen = keyBuffer.readUInt8(0);
  104787. if (publicExponentLen != 3 && publicExponentLen != 1)
  104788. throw (new Error('Cannot parse dnssec key: ' +
  104789. 'unsupported exponent length'));
  104790. var publicExponent = keyBuffer.slice(1, publicExponentLen+1);
  104791. publicExponent = utils.mpNormalize(publicExponent);
  104792. var modulus = keyBuffer.slice(1+publicExponentLen);
  104793. modulus = utils.mpNormalize(modulus);
  104794. // now, make the key
  104795. var rsaKey = {
  104796. type: 'rsa',
  104797. parts: []
  104798. };
  104799. rsaKey.parts.push({ name: 'e', data: publicExponent});
  104800. rsaKey.parts.push({ name: 'n', data: modulus});
  104801. return (new Key(rsaKey));
  104802. }
  104803. if (supportedAlgosById[algorithm] === 'ECDSA-P384-SHA384' ||
  104804. supportedAlgosById[algorithm] === 'ECDSA-P256-SHA256') {
  104805. var curve = 'nistp384';
  104806. var size = 384;
  104807. if (supportedAlgosById[algorithm].match(/^ECDSA-P256-SHA256/)) {
  104808. curve = 'nistp256';
  104809. size = 256;
  104810. }
  104811. var ecdsaKey = {
  104812. type: 'ecdsa',
  104813. curve: curve,
  104814. size: size,
  104815. parts: [
  104816. {name: 'curve', data: Buffer.from(curve) },
  104817. {name: 'Q', data: utils.ecNormalize(keyBuffer) }
  104818. ]
  104819. };
  104820. return (new Key(ecdsaKey));
  104821. }
  104822. throw (new Error('Unsupported algorithm: ' +
  104823. supportedAlgosById[algorithm]));
  104824. }
  104825. function elementToBuf(e) {
  104826. return (Buffer.from(e.split(' ')[1], 'base64'));
  104827. }
  104828. function readDNSSECRSAPrivateKey(elements) {
  104829. var rsaParams = {};
  104830. elements.forEach(function (element) {
  104831. if (element.split(' ')[0] === 'Modulus:')
  104832. rsaParams['n'] = elementToBuf(element);
  104833. else if (element.split(' ')[0] === 'PublicExponent:')
  104834. rsaParams['e'] = elementToBuf(element);
  104835. else if (element.split(' ')[0] === 'PrivateExponent:')
  104836. rsaParams['d'] = elementToBuf(element);
  104837. else if (element.split(' ')[0] === 'Prime1:')
  104838. rsaParams['p'] = elementToBuf(element);
  104839. else if (element.split(' ')[0] === 'Prime2:')
  104840. rsaParams['q'] = elementToBuf(element);
  104841. else if (element.split(' ')[0] === 'Exponent1:')
  104842. rsaParams['dmodp'] = elementToBuf(element);
  104843. else if (element.split(' ')[0] === 'Exponent2:')
  104844. rsaParams['dmodq'] = elementToBuf(element);
  104845. else if (element.split(' ')[0] === 'Coefficient:')
  104846. rsaParams['iqmp'] = elementToBuf(element);
  104847. });
  104848. // now, make the key
  104849. var key = {
  104850. type: 'rsa',
  104851. parts: [
  104852. { name: 'e', data: utils.mpNormalize(rsaParams['e'])},
  104853. { name: 'n', data: utils.mpNormalize(rsaParams['n'])},
  104854. { name: 'd', data: utils.mpNormalize(rsaParams['d'])},
  104855. { name: 'p', data: utils.mpNormalize(rsaParams['p'])},
  104856. { name: 'q', data: utils.mpNormalize(rsaParams['q'])},
  104857. { name: 'dmodp',
  104858. data: utils.mpNormalize(rsaParams['dmodp'])},
  104859. { name: 'dmodq',
  104860. data: utils.mpNormalize(rsaParams['dmodq'])},
  104861. { name: 'iqmp',
  104862. data: utils.mpNormalize(rsaParams['iqmp'])}
  104863. ]
  104864. };
  104865. return (new PrivateKey(key));
  104866. }
  104867. function readDNSSECPrivateKey(alg, elements) {
  104868. if (supportedAlgosById[alg].match(/^RSA-/)) {
  104869. return (readDNSSECRSAPrivateKey(elements));
  104870. }
  104871. if (supportedAlgosById[alg] === 'ECDSA-P384-SHA384' ||
  104872. supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
  104873. var d = Buffer.from(elements[0].split(' ')[1], 'base64');
  104874. var curve = 'nistp384';
  104875. var size = 384;
  104876. if (supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
  104877. curve = 'nistp256';
  104878. size = 256;
  104879. }
  104880. // DNSSEC generates the public-key on the fly (go calculate it)
  104881. var publicKey = utils.publicFromPrivateECDSA(curve, d);
  104882. var Q = publicKey.part['Q'].data;
  104883. var ecdsaKey = {
  104884. type: 'ecdsa',
  104885. curve: curve,
  104886. size: size,
  104887. parts: [
  104888. {name: 'curve', data: Buffer.from(curve) },
  104889. {name: 'd', data: d },
  104890. {name: 'Q', data: Q }
  104891. ]
  104892. };
  104893. return (new PrivateKey(ecdsaKey));
  104894. }
  104895. throw (new Error('Unsupported algorithm: ' + supportedAlgosById[alg]));
  104896. }
  104897. function dnssecTimestamp(date) {
  104898. var year = date.getFullYear() + ''; //stringify
  104899. var month = (date.getMonth() + 1);
  104900. var timestampStr = year + month + date.getUTCDate();
  104901. timestampStr += '' + date.getUTCHours() + date.getUTCMinutes();
  104902. timestampStr += date.getUTCSeconds();
  104903. return (timestampStr);
  104904. }
  104905. function rsaAlgFromOptions(opts) {
  104906. if (!opts || !opts.hashAlgo || opts.hashAlgo === 'sha1')
  104907. return ('5 (RSASHA1)');
  104908. else if (opts.hashAlgo === 'sha256')
  104909. return ('8 (RSASHA256)');
  104910. else if (opts.hashAlgo === 'sha512')
  104911. return ('10 (RSASHA512)');
  104912. else
  104913. throw (new Error('Unknown or unsupported hash: ' +
  104914. opts.hashAlgo));
  104915. }
  104916. function writeRSA(key, options) {
  104917. // if we're missing parts, add them.
  104918. if (!key.part.dmodp || !key.part.dmodq) {
  104919. utils.addRSAMissing(key);
  104920. }
  104921. var out = '';
  104922. out += 'Private-key-format: v1.3\n';
  104923. out += 'Algorithm: ' + rsaAlgFromOptions(options) + '\n';
  104924. var n = utils.mpDenormalize(key.part['n'].data);
  104925. out += 'Modulus: ' + n.toString('base64') + '\n';
  104926. var e = utils.mpDenormalize(key.part['e'].data);
  104927. out += 'PublicExponent: ' + e.toString('base64') + '\n';
  104928. var d = utils.mpDenormalize(key.part['d'].data);
  104929. out += 'PrivateExponent: ' + d.toString('base64') + '\n';
  104930. var p = utils.mpDenormalize(key.part['p'].data);
  104931. out += 'Prime1: ' + p.toString('base64') + '\n';
  104932. var q = utils.mpDenormalize(key.part['q'].data);
  104933. out += 'Prime2: ' + q.toString('base64') + '\n';
  104934. var dmodp = utils.mpDenormalize(key.part['dmodp'].data);
  104935. out += 'Exponent1: ' + dmodp.toString('base64') + '\n';
  104936. var dmodq = utils.mpDenormalize(key.part['dmodq'].data);
  104937. out += 'Exponent2: ' + dmodq.toString('base64') + '\n';
  104938. var iqmp = utils.mpDenormalize(key.part['iqmp'].data);
  104939. out += 'Coefficient: ' + iqmp.toString('base64') + '\n';
  104940. // Assume that we're valid as-of now
  104941. var timestamp = new Date();
  104942. out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
  104943. out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
  104944. out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
  104945. return (Buffer.from(out, 'ascii'));
  104946. }
  104947. function writeECDSA(key, options) {
  104948. var out = '';
  104949. out += 'Private-key-format: v1.3\n';
  104950. if (key.curve === 'nistp256') {
  104951. out += 'Algorithm: 13 (ECDSAP256SHA256)\n';
  104952. } else if (key.curve === 'nistp384') {
  104953. out += 'Algorithm: 14 (ECDSAP384SHA384)\n';
  104954. } else {
  104955. throw (new Error('Unsupported curve'));
  104956. }
  104957. var base64Key = key.part['d'].data.toString('base64');
  104958. out += 'PrivateKey: ' + base64Key + '\n';
  104959. // Assume that we're valid as-of now
  104960. var timestamp = new Date();
  104961. out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
  104962. out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
  104963. out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
  104964. return (Buffer.from(out, 'ascii'));
  104965. }
  104966. function write(key, options) {
  104967. if (PrivateKey.isPrivateKey(key)) {
  104968. if (key.type === 'rsa') {
  104969. return (writeRSA(key, options));
  104970. } else if (key.type === 'ecdsa') {
  104971. return (writeECDSA(key, options));
  104972. } else {
  104973. throw (new Error('Unsupported algorithm: ' + key.type));
  104974. }
  104975. } else if (Key.isKey(key)) {
  104976. /*
  104977. * RFC3110 requires a keyname, and a keytype, which we
  104978. * don't really have a mechanism for specifying such
  104979. * additional metadata.
  104980. */
  104981. throw (new Error('Format "dnssec" only supports ' +
  104982. 'writing private keys'));
  104983. } else {
  104984. throw (new Error('key is not a Key or PrivateKey'));
  104985. }
  104986. }
  104987. },{"../dhe":574,"../key":592,"../private-key":593,"../ssh-buffer":595,"../utils":596,"assert-plus":104,"safer-buffer":562}],580:[function(require,module,exports){
  104988. // Copyright 2017 Joyent, Inc.
  104989. module.exports = {
  104990. read: read,
  104991. verify: verify,
  104992. sign: sign,
  104993. signAsync: signAsync,
  104994. write: write,
  104995. /* Internal private API */
  104996. fromBuffer: fromBuffer,
  104997. toBuffer: toBuffer
  104998. };
  104999. var assert = require('assert-plus');
  105000. var SSHBuffer = require('../ssh-buffer');
  105001. var crypto = require('crypto');
  105002. var Buffer = require('safer-buffer').Buffer;
  105003. var algs = require('../algs');
  105004. var Key = require('../key');
  105005. var PrivateKey = require('../private-key');
  105006. var Identity = require('../identity');
  105007. var rfc4253 = require('./rfc4253');
  105008. var Signature = require('../signature');
  105009. var utils = require('../utils');
  105010. var Certificate = require('../certificate');
  105011. function verify(cert, key) {
  105012. /*
  105013. * We always give an issuerKey, so if our verify() is being called then
  105014. * there was no signature. Return false.
  105015. */
  105016. return (false);
  105017. }
  105018. var TYPES = {
  105019. 'user': 1,
  105020. 'host': 2
  105021. };
  105022. Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; });
  105023. var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/;
  105024. function read(buf, options) {
  105025. if (Buffer.isBuffer(buf))
  105026. buf = buf.toString('ascii');
  105027. var parts = buf.trim().split(/[ \t\n]+/g);
  105028. if (parts.length < 2 || parts.length > 3)
  105029. throw (new Error('Not a valid SSH certificate line'));
  105030. var algo = parts[0];
  105031. var data = parts[1];
  105032. data = Buffer.from(data, 'base64');
  105033. return (fromBuffer(data, algo));
  105034. }
  105035. function fromBuffer(data, algo, partial) {
  105036. var sshbuf = new SSHBuffer({ buffer: data });
  105037. var innerAlgo = sshbuf.readString();
  105038. if (algo !== undefined && innerAlgo !== algo)
  105039. throw (new Error('SSH certificate algorithm mismatch'));
  105040. if (algo === undefined)
  105041. algo = innerAlgo;
  105042. var cert = {};
  105043. cert.signatures = {};
  105044. cert.signatures.openssh = {};
  105045. cert.signatures.openssh.nonce = sshbuf.readBuffer();
  105046. var key = {};
  105047. var parts = (key.parts = []);
  105048. key.type = getAlg(algo);
  105049. var partCount = algs.info[key.type].parts.length;
  105050. while (parts.length < partCount)
  105051. parts.push(sshbuf.readPart());
  105052. assert.ok(parts.length >= 1, 'key must have at least one part');
  105053. var algInfo = algs.info[key.type];
  105054. if (key.type === 'ecdsa') {
  105055. var res = ECDSA_ALGO.exec(algo);
  105056. assert.ok(res !== null);
  105057. assert.strictEqual(res[1], parts[0].data.toString());
  105058. }
  105059. for (var i = 0; i < algInfo.parts.length; ++i) {
  105060. parts[i].name = algInfo.parts[i];
  105061. if (parts[i].name !== 'curve' &&
  105062. algInfo.normalize !== false) {
  105063. var p = parts[i];
  105064. p.data = utils.mpNormalize(p.data);
  105065. }
  105066. }
  105067. cert.subjectKey = new Key(key);
  105068. cert.serial = sshbuf.readInt64();
  105069. var type = TYPES[sshbuf.readInt()];
  105070. assert.string(type, 'valid cert type');
  105071. cert.signatures.openssh.keyId = sshbuf.readString();
  105072. var principals = [];
  105073. var pbuf = sshbuf.readBuffer();
  105074. var psshbuf = new SSHBuffer({ buffer: pbuf });
  105075. while (!psshbuf.atEnd())
  105076. principals.push(psshbuf.readString());
  105077. if (principals.length === 0)
  105078. principals = ['*'];
  105079. cert.subjects = principals.map(function (pr) {
  105080. if (type === 'user')
  105081. return (Identity.forUser(pr));
  105082. else if (type === 'host')
  105083. return (Identity.forHost(pr));
  105084. throw (new Error('Unknown identity type ' + type));
  105085. });
  105086. cert.validFrom = int64ToDate(sshbuf.readInt64());
  105087. cert.validUntil = int64ToDate(sshbuf.readInt64());
  105088. var exts = [];
  105089. var extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() });
  105090. var ext;
  105091. while (!extbuf.atEnd()) {
  105092. ext = { critical: true };
  105093. ext.name = extbuf.readString();
  105094. ext.data = extbuf.readBuffer();
  105095. exts.push(ext);
  105096. }
  105097. extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() });
  105098. while (!extbuf.atEnd()) {
  105099. ext = { critical: false };
  105100. ext.name = extbuf.readString();
  105101. ext.data = extbuf.readBuffer();
  105102. exts.push(ext);
  105103. }
  105104. cert.signatures.openssh.exts = exts;
  105105. /* reserved */
  105106. sshbuf.readBuffer();
  105107. var signingKeyBuf = sshbuf.readBuffer();
  105108. cert.issuerKey = rfc4253.read(signingKeyBuf);
  105109. /*
  105110. * OpenSSH certs don't give the identity of the issuer, just their
  105111. * public key. So, we use an Identity that matches anything. The
  105112. * isSignedBy() function will later tell you if the key matches.
  105113. */
  105114. cert.issuer = Identity.forHost('**');
  105115. var sigBuf = sshbuf.readBuffer();
  105116. cert.signatures.openssh.signature =
  105117. Signature.parse(sigBuf, cert.issuerKey.type, 'ssh');
  105118. if (partial !== undefined) {
  105119. partial.remainder = sshbuf.remainder();
  105120. partial.consumed = sshbuf._offset;
  105121. }
  105122. return (new Certificate(cert));
  105123. }
  105124. function int64ToDate(buf) {
  105125. var i = buf.readUInt32BE(0) * 4294967296;
  105126. i += buf.readUInt32BE(4);
  105127. var d = new Date();
  105128. d.setTime(i * 1000);
  105129. d.sourceInt64 = buf;
  105130. return (d);
  105131. }
  105132. function dateToInt64(date) {
  105133. if (date.sourceInt64 !== undefined)
  105134. return (date.sourceInt64);
  105135. var i = Math.round(date.getTime() / 1000);
  105136. var upper = Math.floor(i / 4294967296);
  105137. var lower = Math.floor(i % 4294967296);
  105138. var buf = Buffer.alloc(8);
  105139. buf.writeUInt32BE(upper, 0);
  105140. buf.writeUInt32BE(lower, 4);
  105141. return (buf);
  105142. }
  105143. function sign(cert, key) {
  105144. if (cert.signatures.openssh === undefined)
  105145. cert.signatures.openssh = {};
  105146. try {
  105147. var blob = toBuffer(cert, true);
  105148. } catch (e) {
  105149. delete (cert.signatures.openssh);
  105150. return (false);
  105151. }
  105152. var sig = cert.signatures.openssh;
  105153. var hashAlgo = undefined;
  105154. if (key.type === 'rsa' || key.type === 'dsa')
  105155. hashAlgo = 'sha1';
  105156. var signer = key.createSign(hashAlgo);
  105157. signer.write(blob);
  105158. sig.signature = signer.sign();
  105159. return (true);
  105160. }
  105161. function signAsync(cert, signer, done) {
  105162. if (cert.signatures.openssh === undefined)
  105163. cert.signatures.openssh = {};
  105164. try {
  105165. var blob = toBuffer(cert, true);
  105166. } catch (e) {
  105167. delete (cert.signatures.openssh);
  105168. done(e);
  105169. return;
  105170. }
  105171. var sig = cert.signatures.openssh;
  105172. signer(blob, function (err, signature) {
  105173. if (err) {
  105174. done(err);
  105175. return;
  105176. }
  105177. try {
  105178. /*
  105179. * This will throw if the signature isn't of a
  105180. * type/algo that can be used for SSH.
  105181. */
  105182. signature.toBuffer('ssh');
  105183. } catch (e) {
  105184. done(e);
  105185. return;
  105186. }
  105187. sig.signature = signature;
  105188. done();
  105189. });
  105190. }
  105191. function write(cert, options) {
  105192. if (options === undefined)
  105193. options = {};
  105194. var blob = toBuffer(cert);
  105195. var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64');
  105196. if (options.comment)
  105197. out = out + ' ' + options.comment;
  105198. return (out);
  105199. }
  105200. function toBuffer(cert, noSig) {
  105201. assert.object(cert.signatures.openssh, 'signature for openssh format');
  105202. var sig = cert.signatures.openssh;
  105203. if (sig.nonce === undefined)
  105204. sig.nonce = crypto.randomBytes(16);
  105205. var buf = new SSHBuffer({});
  105206. buf.writeString(getCertType(cert.subjectKey));
  105207. buf.writeBuffer(sig.nonce);
  105208. var key = cert.subjectKey;
  105209. var algInfo = algs.info[key.type];
  105210. algInfo.parts.forEach(function (part) {
  105211. buf.writePart(key.part[part]);
  105212. });
  105213. buf.writeInt64(cert.serial);
  105214. var type = cert.subjects[0].type;
  105215. assert.notStrictEqual(type, 'unknown');
  105216. cert.subjects.forEach(function (id) {
  105217. assert.strictEqual(id.type, type);
  105218. });
  105219. type = TYPES[type];
  105220. buf.writeInt(type);
  105221. if (sig.keyId === undefined) {
  105222. sig.keyId = cert.subjects[0].type + '_' +
  105223. (cert.subjects[0].uid || cert.subjects[0].hostname);
  105224. }
  105225. buf.writeString(sig.keyId);
  105226. var sub = new SSHBuffer({});
  105227. cert.subjects.forEach(function (id) {
  105228. if (type === TYPES.host)
  105229. sub.writeString(id.hostname);
  105230. else if (type === TYPES.user)
  105231. sub.writeString(id.uid);
  105232. });
  105233. buf.writeBuffer(sub.toBuffer());
  105234. buf.writeInt64(dateToInt64(cert.validFrom));
  105235. buf.writeInt64(dateToInt64(cert.validUntil));
  105236. var exts = sig.exts;
  105237. if (exts === undefined)
  105238. exts = [];
  105239. var extbuf = new SSHBuffer({});
  105240. exts.forEach(function (ext) {
  105241. if (ext.critical !== true)
  105242. return;
  105243. extbuf.writeString(ext.name);
  105244. extbuf.writeBuffer(ext.data);
  105245. });
  105246. buf.writeBuffer(extbuf.toBuffer());
  105247. extbuf = new SSHBuffer({});
  105248. exts.forEach(function (ext) {
  105249. if (ext.critical === true)
  105250. return;
  105251. extbuf.writeString(ext.name);
  105252. extbuf.writeBuffer(ext.data);
  105253. });
  105254. buf.writeBuffer(extbuf.toBuffer());
  105255. /* reserved */
  105256. buf.writeBuffer(Buffer.alloc(0));
  105257. sub = rfc4253.write(cert.issuerKey);
  105258. buf.writeBuffer(sub);
  105259. if (!noSig)
  105260. buf.writeBuffer(sig.signature.toBuffer('ssh'));
  105261. return (buf.toBuffer());
  105262. }
  105263. function getAlg(certType) {
  105264. if (certType === 'ssh-rsa-cert-v01@openssh.com')
  105265. return ('rsa');
  105266. if (certType === 'ssh-dss-cert-v01@openssh.com')
  105267. return ('dsa');
  105268. if (certType.match(ECDSA_ALGO))
  105269. return ('ecdsa');
  105270. if (certType === 'ssh-ed25519-cert-v01@openssh.com')
  105271. return ('ed25519');
  105272. throw (new Error('Unsupported cert type ' + certType));
  105273. }
  105274. function getCertType(key) {
  105275. if (key.type === 'rsa')
  105276. return ('ssh-rsa-cert-v01@openssh.com');
  105277. if (key.type === 'dsa')
  105278. return ('ssh-dss-cert-v01@openssh.com');
  105279. if (key.type === 'ecdsa')
  105280. return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com');
  105281. if (key.type === 'ed25519')
  105282. return ('ssh-ed25519-cert-v01@openssh.com');
  105283. throw (new Error('Unsupported key type ' + key.type));
  105284. }
  105285. },{"../algs":572,"../certificate":573,"../identity":590,"../key":592,"../private-key":593,"../signature":594,"../ssh-buffer":595,"../utils":596,"./rfc4253":585,"assert-plus":104,"crypto":208,"safer-buffer":562}],581:[function(require,module,exports){
  105286. // Copyright 2018 Joyent, Inc.
  105287. module.exports = {
  105288. read: read,
  105289. write: write
  105290. };
  105291. var assert = require('assert-plus');
  105292. var asn1 = require('asn1');
  105293. var crypto = require('crypto');
  105294. var Buffer = require('safer-buffer').Buffer;
  105295. var algs = require('../algs');
  105296. var utils = require('../utils');
  105297. var Key = require('../key');
  105298. var PrivateKey = require('../private-key');
  105299. var pkcs1 = require('./pkcs1');
  105300. var pkcs8 = require('./pkcs8');
  105301. var sshpriv = require('./ssh-private');
  105302. var rfc4253 = require('./rfc4253');
  105303. var errors = require('../errors');
  105304. var OID_PBES2 = '1.2.840.113549.1.5.13';
  105305. var OID_PBKDF2 = '1.2.840.113549.1.5.12';
  105306. var OID_TO_CIPHER = {
  105307. '1.2.840.113549.3.7': '3des-cbc',
  105308. '2.16.840.1.101.3.4.1.2': 'aes128-cbc',
  105309. '2.16.840.1.101.3.4.1.42': 'aes256-cbc'
  105310. };
  105311. var CIPHER_TO_OID = {};
  105312. Object.keys(OID_TO_CIPHER).forEach(function (k) {
  105313. CIPHER_TO_OID[OID_TO_CIPHER[k]] = k;
  105314. });
  105315. var OID_TO_HASH = {
  105316. '1.2.840.113549.2.7': 'sha1',
  105317. '1.2.840.113549.2.9': 'sha256',
  105318. '1.2.840.113549.2.11': 'sha512'
  105319. };
  105320. var HASH_TO_OID = {};
  105321. Object.keys(OID_TO_HASH).forEach(function (k) {
  105322. HASH_TO_OID[OID_TO_HASH[k]] = k;
  105323. });
  105324. /*
  105325. * For reading we support both PKCS#1 and PKCS#8. If we find a private key,
  105326. * we just take the public component of it and use that.
  105327. */
  105328. function read(buf, options, forceType) {
  105329. var input = buf;
  105330. if (typeof (buf) !== 'string') {
  105331. assert.buffer(buf, 'buf');
  105332. buf = buf.toString('ascii');
  105333. }
  105334. var lines = buf.trim().split(/[\r\n]+/g);
  105335. var m;
  105336. var si = -1;
  105337. while (!m && si < lines.length) {
  105338. m = lines[++si].match(/*JSSTYLED*/
  105339. /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
  105340. }
  105341. assert.ok(m, 'invalid PEM header');
  105342. var m2;
  105343. var ei = lines.length;
  105344. while (!m2 && ei > 0) {
  105345. m2 = lines[--ei].match(/*JSSTYLED*/
  105346. /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
  105347. }
  105348. assert.ok(m2, 'invalid PEM footer');
  105349. /* Begin and end banners must match key type */
  105350. assert.equal(m[2], m2[2]);
  105351. var type = m[2].toLowerCase();
  105352. var alg;
  105353. if (m[1]) {
  105354. /* They also must match algorithms, if given */
  105355. assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
  105356. alg = m[1].trim();
  105357. }
  105358. lines = lines.slice(si, ei + 1);
  105359. var headers = {};
  105360. while (true) {
  105361. lines = lines.slice(1);
  105362. m = lines[0].match(/*JSSTYLED*/
  105363. /^([A-Za-z0-9-]+): (.+)$/);
  105364. if (!m)
  105365. break;
  105366. headers[m[1].toLowerCase()] = m[2];
  105367. }
  105368. /* Chop off the first and last lines */
  105369. lines = lines.slice(0, -1).join('');
  105370. buf = Buffer.from(lines, 'base64');
  105371. var cipher, key, iv;
  105372. if (headers['proc-type']) {
  105373. var parts = headers['proc-type'].split(',');
  105374. if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
  105375. if (typeof (options.passphrase) === 'string') {
  105376. options.passphrase = Buffer.from(
  105377. options.passphrase, 'utf-8');
  105378. }
  105379. if (!Buffer.isBuffer(options.passphrase)) {
  105380. throw (new errors.KeyEncryptedError(
  105381. options.filename, 'PEM'));
  105382. } else {
  105383. parts = headers['dek-info'].split(',');
  105384. assert.ok(parts.length === 2);
  105385. cipher = parts[0].toLowerCase();
  105386. iv = Buffer.from(parts[1], 'hex');
  105387. key = utils.opensslKeyDeriv(cipher, iv,
  105388. options.passphrase, 1).key;
  105389. }
  105390. }
  105391. }
  105392. if (alg && alg.toLowerCase() === 'encrypted') {
  105393. var eder = new asn1.BerReader(buf);
  105394. var pbesEnd;
  105395. eder.readSequence();
  105396. eder.readSequence();
  105397. pbesEnd = eder.offset + eder.length;
  105398. var method = eder.readOID();
  105399. if (method !== OID_PBES2) {
  105400. throw (new Error('Unsupported PEM/PKCS8 encryption ' +
  105401. 'scheme: ' + method));
  105402. }
  105403. eder.readSequence(); /* PBES2-params */
  105404. eder.readSequence(); /* keyDerivationFunc */
  105405. var kdfEnd = eder.offset + eder.length;
  105406. var kdfOid = eder.readOID();
  105407. if (kdfOid !== OID_PBKDF2)
  105408. throw (new Error('Unsupported PBES2 KDF: ' + kdfOid));
  105409. eder.readSequence();
  105410. var salt = eder.readString(asn1.Ber.OctetString, true);
  105411. var iterations = eder.readInt();
  105412. var hashAlg = 'sha1';
  105413. if (eder.offset < kdfEnd) {
  105414. eder.readSequence();
  105415. var hashAlgOid = eder.readOID();
  105416. hashAlg = OID_TO_HASH[hashAlgOid];
  105417. if (hashAlg === undefined) {
  105418. throw (new Error('Unsupported PBKDF2 hash: ' +
  105419. hashAlgOid));
  105420. }
  105421. }
  105422. eder._offset = kdfEnd;
  105423. eder.readSequence(); /* encryptionScheme */
  105424. var cipherOid = eder.readOID();
  105425. cipher = OID_TO_CIPHER[cipherOid];
  105426. if (cipher === undefined) {
  105427. throw (new Error('Unsupported PBES2 cipher: ' +
  105428. cipherOid));
  105429. }
  105430. iv = eder.readString(asn1.Ber.OctetString, true);
  105431. eder._offset = pbesEnd;
  105432. buf = eder.readString(asn1.Ber.OctetString, true);
  105433. if (typeof (options.passphrase) === 'string') {
  105434. options.passphrase = Buffer.from(
  105435. options.passphrase, 'utf-8');
  105436. }
  105437. if (!Buffer.isBuffer(options.passphrase)) {
  105438. throw (new errors.KeyEncryptedError(
  105439. options.filename, 'PEM'));
  105440. }
  105441. var cinfo = utils.opensshCipherInfo(cipher);
  105442. cipher = cinfo.opensslName;
  105443. key = utils.pbkdf2(hashAlg, salt, iterations, cinfo.keySize,
  105444. options.passphrase);
  105445. alg = undefined;
  105446. }
  105447. if (cipher && key && iv) {
  105448. var cipherStream = crypto.createDecipheriv(cipher, key, iv);
  105449. var chunk, chunks = [];
  105450. cipherStream.once('error', function (e) {
  105451. if (e.toString().indexOf('bad decrypt') !== -1) {
  105452. throw (new Error('Incorrect passphrase ' +
  105453. 'supplied, could not decrypt key'));
  105454. }
  105455. throw (e);
  105456. });
  105457. cipherStream.write(buf);
  105458. cipherStream.end();
  105459. while ((chunk = cipherStream.read()) !== null)
  105460. chunks.push(chunk);
  105461. buf = Buffer.concat(chunks);
  105462. }
  105463. /* The new OpenSSH internal format abuses PEM headers */
  105464. if (alg && alg.toLowerCase() === 'openssh')
  105465. return (sshpriv.readSSHPrivate(type, buf, options));
  105466. if (alg && alg.toLowerCase() === 'ssh2')
  105467. return (rfc4253.readType(type, buf, options));
  105468. var der = new asn1.BerReader(buf);
  105469. der.originalInput = input;
  105470. /*
  105471. * All of the PEM file types start with a sequence tag, so chop it
  105472. * off here
  105473. */
  105474. der.readSequence();
  105475. /* PKCS#1 type keys name an algorithm in the banner explicitly */
  105476. if (alg) {
  105477. if (forceType)
  105478. assert.strictEqual(forceType, 'pkcs1');
  105479. return (pkcs1.readPkcs1(alg, type, der));
  105480. } else {
  105481. if (forceType)
  105482. assert.strictEqual(forceType, 'pkcs8');
  105483. return (pkcs8.readPkcs8(alg, type, der));
  105484. }
  105485. }
  105486. function write(key, options, type) {
  105487. assert.object(key);
  105488. var alg = {
  105489. 'ecdsa': 'EC',
  105490. 'rsa': 'RSA',
  105491. 'dsa': 'DSA',
  105492. 'ed25519': 'EdDSA'
  105493. }[key.type];
  105494. var header;
  105495. var der = new asn1.BerWriter();
  105496. if (PrivateKey.isPrivateKey(key)) {
  105497. if (type && type === 'pkcs8') {
  105498. header = 'PRIVATE KEY';
  105499. pkcs8.writePkcs8(der, key);
  105500. } else {
  105501. if (type)
  105502. assert.strictEqual(type, 'pkcs1');
  105503. header = alg + ' PRIVATE KEY';
  105504. pkcs1.writePkcs1(der, key);
  105505. }
  105506. } else if (Key.isKey(key)) {
  105507. if (type && type === 'pkcs1') {
  105508. header = alg + ' PUBLIC KEY';
  105509. pkcs1.writePkcs1(der, key);
  105510. } else {
  105511. if (type)
  105512. assert.strictEqual(type, 'pkcs8');
  105513. header = 'PUBLIC KEY';
  105514. pkcs8.writePkcs8(der, key);
  105515. }
  105516. } else {
  105517. throw (new Error('key is not a Key or PrivateKey'));
  105518. }
  105519. var tmp = der.buffer.toString('base64');
  105520. var len = tmp.length + (tmp.length / 64) +
  105521. 18 + 16 + header.length*2 + 10;
  105522. var buf = Buffer.alloc(len);
  105523. var o = 0;
  105524. o += buf.write('-----BEGIN ' + header + '-----\n', o);
  105525. for (var i = 0; i < tmp.length; ) {
  105526. var limit = i + 64;
  105527. if (limit > tmp.length)
  105528. limit = tmp.length;
  105529. o += buf.write(tmp.slice(i, limit), o);
  105530. buf[o++] = 10;
  105531. i = limit;
  105532. }
  105533. o += buf.write('-----END ' + header + '-----\n', o);
  105534. return (buf.slice(0, o));
  105535. }
  105536. },{"../algs":572,"../errors":576,"../key":592,"../private-key":593,"../utils":596,"./pkcs1":582,"./pkcs8":583,"./rfc4253":585,"./ssh-private":586,"asn1":103,"assert-plus":104,"crypto":208,"safer-buffer":562}],582:[function(require,module,exports){
  105537. // Copyright 2015 Joyent, Inc.
  105538. module.exports = {
  105539. read: read,
  105540. readPkcs1: readPkcs1,
  105541. write: write,
  105542. writePkcs1: writePkcs1
  105543. };
  105544. var assert = require('assert-plus');
  105545. var asn1 = require('asn1');
  105546. var Buffer = require('safer-buffer').Buffer;
  105547. var algs = require('../algs');
  105548. var utils = require('../utils');
  105549. var Key = require('../key');
  105550. var PrivateKey = require('../private-key');
  105551. var pem = require('./pem');
  105552. var pkcs8 = require('./pkcs8');
  105553. var readECDSACurve = pkcs8.readECDSACurve;
  105554. function read(buf, options) {
  105555. return (pem.read(buf, options, 'pkcs1'));
  105556. }
  105557. function write(key, options) {
  105558. return (pem.write(key, options, 'pkcs1'));
  105559. }
  105560. /* Helper to read in a single mpint */
  105561. function readMPInt(der, nm) {
  105562. assert.strictEqual(der.peek(), asn1.Ber.Integer,
  105563. nm + ' is not an Integer');
  105564. return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
  105565. }
  105566. function readPkcs1(alg, type, der) {
  105567. switch (alg) {
  105568. case 'RSA':
  105569. if (type === 'public')
  105570. return (readPkcs1RSAPublic(der));
  105571. else if (type === 'private')
  105572. return (readPkcs1RSAPrivate(der));
  105573. throw (new Error('Unknown key type: ' + type));
  105574. case 'DSA':
  105575. if (type === 'public')
  105576. return (readPkcs1DSAPublic(der));
  105577. else if (type === 'private')
  105578. return (readPkcs1DSAPrivate(der));
  105579. throw (new Error('Unknown key type: ' + type));
  105580. case 'EC':
  105581. case 'ECDSA':
  105582. if (type === 'private')
  105583. return (readPkcs1ECDSAPrivate(der));
  105584. else if (type === 'public')
  105585. return (readPkcs1ECDSAPublic(der));
  105586. throw (new Error('Unknown key type: ' + type));
  105587. case 'EDDSA':
  105588. case 'EdDSA':
  105589. if (type === 'private')
  105590. return (readPkcs1EdDSAPrivate(der));
  105591. throw (new Error(type + ' keys not supported with EdDSA'));
  105592. default:
  105593. throw (new Error('Unknown key algo: ' + alg));
  105594. }
  105595. }
  105596. function readPkcs1RSAPublic(der) {
  105597. // modulus and exponent
  105598. var n = readMPInt(der, 'modulus');
  105599. var e = readMPInt(der, 'exponent');
  105600. // now, make the key
  105601. var key = {
  105602. type: 'rsa',
  105603. parts: [
  105604. { name: 'e', data: e },
  105605. { name: 'n', data: n }
  105606. ]
  105607. };
  105608. return (new Key(key));
  105609. }
  105610. function readPkcs1RSAPrivate(der) {
  105611. var version = readMPInt(der, 'version');
  105612. assert.strictEqual(version[0], 0);
  105613. // modulus then public exponent
  105614. var n = readMPInt(der, 'modulus');
  105615. var e = readMPInt(der, 'public exponent');
  105616. var d = readMPInt(der, 'private exponent');
  105617. var p = readMPInt(der, 'prime1');
  105618. var q = readMPInt(der, 'prime2');
  105619. var dmodp = readMPInt(der, 'exponent1');
  105620. var dmodq = readMPInt(der, 'exponent2');
  105621. var iqmp = readMPInt(der, 'iqmp');
  105622. // now, make the key
  105623. var key = {
  105624. type: 'rsa',
  105625. parts: [
  105626. { name: 'n', data: n },
  105627. { name: 'e', data: e },
  105628. { name: 'd', data: d },
  105629. { name: 'iqmp', data: iqmp },
  105630. { name: 'p', data: p },
  105631. { name: 'q', data: q },
  105632. { name: 'dmodp', data: dmodp },
  105633. { name: 'dmodq', data: dmodq }
  105634. ]
  105635. };
  105636. return (new PrivateKey(key));
  105637. }
  105638. function readPkcs1DSAPrivate(der) {
  105639. var version = readMPInt(der, 'version');
  105640. assert.strictEqual(version.readUInt8(0), 0);
  105641. var p = readMPInt(der, 'p');
  105642. var q = readMPInt(der, 'q');
  105643. var g = readMPInt(der, 'g');
  105644. var y = readMPInt(der, 'y');
  105645. var x = readMPInt(der, 'x');
  105646. // now, make the key
  105647. var key = {
  105648. type: 'dsa',
  105649. parts: [
  105650. { name: 'p', data: p },
  105651. { name: 'q', data: q },
  105652. { name: 'g', data: g },
  105653. { name: 'y', data: y },
  105654. { name: 'x', data: x }
  105655. ]
  105656. };
  105657. return (new PrivateKey(key));
  105658. }
  105659. function readPkcs1EdDSAPrivate(der) {
  105660. var version = readMPInt(der, 'version');
  105661. assert.strictEqual(version.readUInt8(0), 1);
  105662. // private key
  105663. var k = der.readString(asn1.Ber.OctetString, true);
  105664. der.readSequence(0xa0);
  105665. var oid = der.readOID();
  105666. assert.strictEqual(oid, '1.3.101.112', 'the ed25519 curve identifier');
  105667. der.readSequence(0xa1);
  105668. var A = utils.readBitString(der);
  105669. var key = {
  105670. type: 'ed25519',
  105671. parts: [
  105672. { name: 'A', data: utils.zeroPadToLength(A, 32) },
  105673. { name: 'k', data: k }
  105674. ]
  105675. };
  105676. return (new PrivateKey(key));
  105677. }
  105678. function readPkcs1DSAPublic(der) {
  105679. var y = readMPInt(der, 'y');
  105680. var p = readMPInt(der, 'p');
  105681. var q = readMPInt(der, 'q');
  105682. var g = readMPInt(der, 'g');
  105683. var key = {
  105684. type: 'dsa',
  105685. parts: [
  105686. { name: 'y', data: y },
  105687. { name: 'p', data: p },
  105688. { name: 'q', data: q },
  105689. { name: 'g', data: g }
  105690. ]
  105691. };
  105692. return (new Key(key));
  105693. }
  105694. function readPkcs1ECDSAPublic(der) {
  105695. der.readSequence();
  105696. var oid = der.readOID();
  105697. assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey');
  105698. var curveOid = der.readOID();
  105699. var curve;
  105700. var curves = Object.keys(algs.curves);
  105701. for (var j = 0; j < curves.length; ++j) {
  105702. var c = curves[j];
  105703. var cd = algs.curves[c];
  105704. if (cd.pkcs8oid === curveOid) {
  105705. curve = c;
  105706. break;
  105707. }
  105708. }
  105709. assert.string(curve, 'a known ECDSA named curve');
  105710. var Q = der.readString(asn1.Ber.BitString, true);
  105711. Q = utils.ecNormalize(Q);
  105712. var key = {
  105713. type: 'ecdsa',
  105714. parts: [
  105715. { name: 'curve', data: Buffer.from(curve) },
  105716. { name: 'Q', data: Q }
  105717. ]
  105718. };
  105719. return (new Key(key));
  105720. }
  105721. function readPkcs1ECDSAPrivate(der) {
  105722. var version = readMPInt(der, 'version');
  105723. assert.strictEqual(version.readUInt8(0), 1);
  105724. // private key
  105725. var d = der.readString(asn1.Ber.OctetString, true);
  105726. der.readSequence(0xa0);
  105727. var curve = readECDSACurve(der);
  105728. assert.string(curve, 'a known elliptic curve');
  105729. der.readSequence(0xa1);
  105730. var Q = der.readString(asn1.Ber.BitString, true);
  105731. Q = utils.ecNormalize(Q);
  105732. var key = {
  105733. type: 'ecdsa',
  105734. parts: [
  105735. { name: 'curve', data: Buffer.from(curve) },
  105736. { name: 'Q', data: Q },
  105737. { name: 'd', data: d }
  105738. ]
  105739. };
  105740. return (new PrivateKey(key));
  105741. }
  105742. function writePkcs1(der, key) {
  105743. der.startSequence();
  105744. switch (key.type) {
  105745. case 'rsa':
  105746. if (PrivateKey.isPrivateKey(key))
  105747. writePkcs1RSAPrivate(der, key);
  105748. else
  105749. writePkcs1RSAPublic(der, key);
  105750. break;
  105751. case 'dsa':
  105752. if (PrivateKey.isPrivateKey(key))
  105753. writePkcs1DSAPrivate(der, key);
  105754. else
  105755. writePkcs1DSAPublic(der, key);
  105756. break;
  105757. case 'ecdsa':
  105758. if (PrivateKey.isPrivateKey(key))
  105759. writePkcs1ECDSAPrivate(der, key);
  105760. else
  105761. writePkcs1ECDSAPublic(der, key);
  105762. break;
  105763. case 'ed25519':
  105764. if (PrivateKey.isPrivateKey(key))
  105765. writePkcs1EdDSAPrivate(der, key);
  105766. else
  105767. writePkcs1EdDSAPublic(der, key);
  105768. break;
  105769. default:
  105770. throw (new Error('Unknown key algo: ' + key.type));
  105771. }
  105772. der.endSequence();
  105773. }
  105774. function writePkcs1RSAPublic(der, key) {
  105775. der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
  105776. der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
  105777. }
  105778. function writePkcs1RSAPrivate(der, key) {
  105779. var ver = Buffer.from([0]);
  105780. der.writeBuffer(ver, asn1.Ber.Integer);
  105781. der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
  105782. der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
  105783. der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
  105784. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  105785. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  105786. if (!key.part.dmodp || !key.part.dmodq)
  105787. utils.addRSAMissing(key);
  105788. der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
  105789. der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
  105790. der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
  105791. }
  105792. function writePkcs1DSAPrivate(der, key) {
  105793. var ver = Buffer.from([0]);
  105794. der.writeBuffer(ver, asn1.Ber.Integer);
  105795. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  105796. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  105797. der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
  105798. der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
  105799. der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
  105800. }
  105801. function writePkcs1DSAPublic(der, key) {
  105802. der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
  105803. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  105804. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  105805. der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
  105806. }
  105807. function writePkcs1ECDSAPublic(der, key) {
  105808. der.startSequence();
  105809. der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */
  105810. var curve = key.part.curve.data.toString();
  105811. var curveOid = algs.curves[curve].pkcs8oid;
  105812. assert.string(curveOid, 'a known ECDSA named curve');
  105813. der.writeOID(curveOid);
  105814. der.endSequence();
  105815. var Q = utils.ecNormalize(key.part.Q.data, true);
  105816. der.writeBuffer(Q, asn1.Ber.BitString);
  105817. }
  105818. function writePkcs1ECDSAPrivate(der, key) {
  105819. var ver = Buffer.from([1]);
  105820. der.writeBuffer(ver, asn1.Ber.Integer);
  105821. der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
  105822. der.startSequence(0xa0);
  105823. var curve = key.part.curve.data.toString();
  105824. var curveOid = algs.curves[curve].pkcs8oid;
  105825. assert.string(curveOid, 'a known ECDSA named curve');
  105826. der.writeOID(curveOid);
  105827. der.endSequence();
  105828. der.startSequence(0xa1);
  105829. var Q = utils.ecNormalize(key.part.Q.data, true);
  105830. der.writeBuffer(Q, asn1.Ber.BitString);
  105831. der.endSequence();
  105832. }
  105833. function writePkcs1EdDSAPrivate(der, key) {
  105834. var ver = Buffer.from([1]);
  105835. der.writeBuffer(ver, asn1.Ber.Integer);
  105836. der.writeBuffer(key.part.k.data, asn1.Ber.OctetString);
  105837. der.startSequence(0xa0);
  105838. der.writeOID('1.3.101.112');
  105839. der.endSequence();
  105840. der.startSequence(0xa1);
  105841. utils.writeBitString(der, key.part.A.data);
  105842. der.endSequence();
  105843. }
  105844. function writePkcs1EdDSAPublic(der, key) {
  105845. throw (new Error('Public keys are not supported for EdDSA PKCS#1'));
  105846. }
  105847. },{"../algs":572,"../key":592,"../private-key":593,"../utils":596,"./pem":581,"./pkcs8":583,"asn1":103,"assert-plus":104,"safer-buffer":562}],583:[function(require,module,exports){
  105848. // Copyright 2018 Joyent, Inc.
  105849. module.exports = {
  105850. read: read,
  105851. readPkcs8: readPkcs8,
  105852. write: write,
  105853. writePkcs8: writePkcs8,
  105854. pkcs8ToBuffer: pkcs8ToBuffer,
  105855. readECDSACurve: readECDSACurve,
  105856. writeECDSACurve: writeECDSACurve
  105857. };
  105858. var assert = require('assert-plus');
  105859. var asn1 = require('asn1');
  105860. var Buffer = require('safer-buffer').Buffer;
  105861. var algs = require('../algs');
  105862. var utils = require('../utils');
  105863. var Key = require('../key');
  105864. var PrivateKey = require('../private-key');
  105865. var pem = require('./pem');
  105866. function read(buf, options) {
  105867. return (pem.read(buf, options, 'pkcs8'));
  105868. }
  105869. function write(key, options) {
  105870. return (pem.write(key, options, 'pkcs8'));
  105871. }
  105872. /* Helper to read in a single mpint */
  105873. function readMPInt(der, nm) {
  105874. assert.strictEqual(der.peek(), asn1.Ber.Integer,
  105875. nm + ' is not an Integer');
  105876. return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
  105877. }
  105878. function readPkcs8(alg, type, der) {
  105879. /* Private keys in pkcs#8 format have a weird extra int */
  105880. if (der.peek() === asn1.Ber.Integer) {
  105881. assert.strictEqual(type, 'private',
  105882. 'unexpected Integer at start of public key');
  105883. der.readString(asn1.Ber.Integer, true);
  105884. }
  105885. der.readSequence();
  105886. var next = der.offset + der.length;
  105887. var oid = der.readOID();
  105888. switch (oid) {
  105889. case '1.2.840.113549.1.1.1':
  105890. der._offset = next;
  105891. if (type === 'public')
  105892. return (readPkcs8RSAPublic(der));
  105893. else
  105894. return (readPkcs8RSAPrivate(der));
  105895. case '1.2.840.10040.4.1':
  105896. if (type === 'public')
  105897. return (readPkcs8DSAPublic(der));
  105898. else
  105899. return (readPkcs8DSAPrivate(der));
  105900. case '1.2.840.10045.2.1':
  105901. if (type === 'public')
  105902. return (readPkcs8ECDSAPublic(der));
  105903. else
  105904. return (readPkcs8ECDSAPrivate(der));
  105905. case '1.3.101.112':
  105906. if (type === 'public') {
  105907. return (readPkcs8EdDSAPublic(der));
  105908. } else {
  105909. return (readPkcs8EdDSAPrivate(der));
  105910. }
  105911. case '1.3.101.110':
  105912. if (type === 'public') {
  105913. return (readPkcs8X25519Public(der));
  105914. } else {
  105915. return (readPkcs8X25519Private(der));
  105916. }
  105917. default:
  105918. throw (new Error('Unknown key type OID ' + oid));
  105919. }
  105920. }
  105921. function readPkcs8RSAPublic(der) {
  105922. // bit string sequence
  105923. der.readSequence(asn1.Ber.BitString);
  105924. der.readByte();
  105925. der.readSequence();
  105926. // modulus
  105927. var n = readMPInt(der, 'modulus');
  105928. var e = readMPInt(der, 'exponent');
  105929. // now, make the key
  105930. var key = {
  105931. type: 'rsa',
  105932. source: der.originalInput,
  105933. parts: [
  105934. { name: 'e', data: e },
  105935. { name: 'n', data: n }
  105936. ]
  105937. };
  105938. return (new Key(key));
  105939. }
  105940. function readPkcs8RSAPrivate(der) {
  105941. der.readSequence(asn1.Ber.OctetString);
  105942. der.readSequence();
  105943. var ver = readMPInt(der, 'version');
  105944. assert.equal(ver[0], 0x0, 'unknown RSA private key version');
  105945. // modulus then public exponent
  105946. var n = readMPInt(der, 'modulus');
  105947. var e = readMPInt(der, 'public exponent');
  105948. var d = readMPInt(der, 'private exponent');
  105949. var p = readMPInt(der, 'prime1');
  105950. var q = readMPInt(der, 'prime2');
  105951. var dmodp = readMPInt(der, 'exponent1');
  105952. var dmodq = readMPInt(der, 'exponent2');
  105953. var iqmp = readMPInt(der, 'iqmp');
  105954. // now, make the key
  105955. var key = {
  105956. type: 'rsa',
  105957. parts: [
  105958. { name: 'n', data: n },
  105959. { name: 'e', data: e },
  105960. { name: 'd', data: d },
  105961. { name: 'iqmp', data: iqmp },
  105962. { name: 'p', data: p },
  105963. { name: 'q', data: q },
  105964. { name: 'dmodp', data: dmodp },
  105965. { name: 'dmodq', data: dmodq }
  105966. ]
  105967. };
  105968. return (new PrivateKey(key));
  105969. }
  105970. function readPkcs8DSAPublic(der) {
  105971. der.readSequence();
  105972. var p = readMPInt(der, 'p');
  105973. var q = readMPInt(der, 'q');
  105974. var g = readMPInt(der, 'g');
  105975. // bit string sequence
  105976. der.readSequence(asn1.Ber.BitString);
  105977. der.readByte();
  105978. var y = readMPInt(der, 'y');
  105979. // now, make the key
  105980. var key = {
  105981. type: 'dsa',
  105982. parts: [
  105983. { name: 'p', data: p },
  105984. { name: 'q', data: q },
  105985. { name: 'g', data: g },
  105986. { name: 'y', data: y }
  105987. ]
  105988. };
  105989. return (new Key(key));
  105990. }
  105991. function readPkcs8DSAPrivate(der) {
  105992. der.readSequence();
  105993. var p = readMPInt(der, 'p');
  105994. var q = readMPInt(der, 'q');
  105995. var g = readMPInt(der, 'g');
  105996. der.readSequence(asn1.Ber.OctetString);
  105997. var x = readMPInt(der, 'x');
  105998. /* The pkcs#8 format does not include the public key */
  105999. var y = utils.calculateDSAPublic(g, p, x);
  106000. var key = {
  106001. type: 'dsa',
  106002. parts: [
  106003. { name: 'p', data: p },
  106004. { name: 'q', data: q },
  106005. { name: 'g', data: g },
  106006. { name: 'y', data: y },
  106007. { name: 'x', data: x }
  106008. ]
  106009. };
  106010. return (new PrivateKey(key));
  106011. }
  106012. function readECDSACurve(der) {
  106013. var curveName, curveNames;
  106014. var j, c, cd;
  106015. if (der.peek() === asn1.Ber.OID) {
  106016. var oid = der.readOID();
  106017. curveNames = Object.keys(algs.curves);
  106018. for (j = 0; j < curveNames.length; ++j) {
  106019. c = curveNames[j];
  106020. cd = algs.curves[c];
  106021. if (cd.pkcs8oid === oid) {
  106022. curveName = c;
  106023. break;
  106024. }
  106025. }
  106026. } else {
  106027. // ECParameters sequence
  106028. der.readSequence();
  106029. var version = der.readString(asn1.Ber.Integer, true);
  106030. assert.strictEqual(version[0], 1, 'ECDSA key not version 1');
  106031. var curve = {};
  106032. // FieldID sequence
  106033. der.readSequence();
  106034. var fieldTypeOid = der.readOID();
  106035. assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1',
  106036. 'ECDSA key is not from a prime-field');
  106037. var p = curve.p = utils.mpNormalize(
  106038. der.readString(asn1.Ber.Integer, true));
  106039. /*
  106040. * p always starts with a 1 bit, so count the zeros to get its
  106041. * real size.
  106042. */
  106043. curve.size = p.length * 8 - utils.countZeros(p);
  106044. // Curve sequence
  106045. der.readSequence();
  106046. curve.a = utils.mpNormalize(
  106047. der.readString(asn1.Ber.OctetString, true));
  106048. curve.b = utils.mpNormalize(
  106049. der.readString(asn1.Ber.OctetString, true));
  106050. if (der.peek() === asn1.Ber.BitString)
  106051. curve.s = der.readString(asn1.Ber.BitString, true);
  106052. // Combined Gx and Gy
  106053. curve.G = der.readString(asn1.Ber.OctetString, true);
  106054. assert.strictEqual(curve.G[0], 0x4,
  106055. 'uncompressed G is required');
  106056. curve.n = utils.mpNormalize(
  106057. der.readString(asn1.Ber.Integer, true));
  106058. curve.h = utils.mpNormalize(
  106059. der.readString(asn1.Ber.Integer, true));
  106060. assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' +
  106061. 'required');
  106062. curveNames = Object.keys(algs.curves);
  106063. var ks = Object.keys(curve);
  106064. for (j = 0; j < curveNames.length; ++j) {
  106065. c = curveNames[j];
  106066. cd = algs.curves[c];
  106067. var equal = true;
  106068. for (var i = 0; i < ks.length; ++i) {
  106069. var k = ks[i];
  106070. if (cd[k] === undefined)
  106071. continue;
  106072. if (typeof (cd[k]) === 'object' &&
  106073. cd[k].equals !== undefined) {
  106074. if (!cd[k].equals(curve[k])) {
  106075. equal = false;
  106076. break;
  106077. }
  106078. } else if (Buffer.isBuffer(cd[k])) {
  106079. if (cd[k].toString('binary')
  106080. !== curve[k].toString('binary')) {
  106081. equal = false;
  106082. break;
  106083. }
  106084. } else {
  106085. if (cd[k] !== curve[k]) {
  106086. equal = false;
  106087. break;
  106088. }
  106089. }
  106090. }
  106091. if (equal) {
  106092. curveName = c;
  106093. break;
  106094. }
  106095. }
  106096. }
  106097. return (curveName);
  106098. }
  106099. function readPkcs8ECDSAPrivate(der) {
  106100. var curveName = readECDSACurve(der);
  106101. assert.string(curveName, 'a known elliptic curve');
  106102. der.readSequence(asn1.Ber.OctetString);
  106103. der.readSequence();
  106104. var version = readMPInt(der, 'version');
  106105. assert.equal(version[0], 1, 'unknown version of ECDSA key');
  106106. var d = der.readString(asn1.Ber.OctetString, true);
  106107. var Q;
  106108. if (der.peek() == 0xa0) {
  106109. der.readSequence(0xa0);
  106110. der._offset += der.length;
  106111. }
  106112. if (der.peek() == 0xa1) {
  106113. der.readSequence(0xa1);
  106114. Q = der.readString(asn1.Ber.BitString, true);
  106115. Q = utils.ecNormalize(Q);
  106116. }
  106117. if (Q === undefined) {
  106118. var pub = utils.publicFromPrivateECDSA(curveName, d);
  106119. Q = pub.part.Q.data;
  106120. }
  106121. var key = {
  106122. type: 'ecdsa',
  106123. parts: [
  106124. { name: 'curve', data: Buffer.from(curveName) },
  106125. { name: 'Q', data: Q },
  106126. { name: 'd', data: d }
  106127. ]
  106128. };
  106129. return (new PrivateKey(key));
  106130. }
  106131. function readPkcs8ECDSAPublic(der) {
  106132. var curveName = readECDSACurve(der);
  106133. assert.string(curveName, 'a known elliptic curve');
  106134. var Q = der.readString(asn1.Ber.BitString, true);
  106135. Q = utils.ecNormalize(Q);
  106136. var key = {
  106137. type: 'ecdsa',
  106138. parts: [
  106139. { name: 'curve', data: Buffer.from(curveName) },
  106140. { name: 'Q', data: Q }
  106141. ]
  106142. };
  106143. return (new Key(key));
  106144. }
  106145. function readPkcs8EdDSAPublic(der) {
  106146. if (der.peek() === 0x00)
  106147. der.readByte();
  106148. var A = utils.readBitString(der);
  106149. var key = {
  106150. type: 'ed25519',
  106151. parts: [
  106152. { name: 'A', data: utils.zeroPadToLength(A, 32) }
  106153. ]
  106154. };
  106155. return (new Key(key));
  106156. }
  106157. function readPkcs8X25519Public(der) {
  106158. var A = utils.readBitString(der);
  106159. var key = {
  106160. type: 'curve25519',
  106161. parts: [
  106162. { name: 'A', data: utils.zeroPadToLength(A, 32) }
  106163. ]
  106164. };
  106165. return (new Key(key));
  106166. }
  106167. function readPkcs8EdDSAPrivate(der) {
  106168. if (der.peek() === 0x00)
  106169. der.readByte();
  106170. der.readSequence(asn1.Ber.OctetString);
  106171. var k = der.readString(asn1.Ber.OctetString, true);
  106172. k = utils.zeroPadToLength(k, 32);
  106173. var A;
  106174. if (der.peek() === asn1.Ber.BitString) {
  106175. A = utils.readBitString(der);
  106176. A = utils.zeroPadToLength(A, 32);
  106177. } else {
  106178. A = utils.calculateED25519Public(k);
  106179. }
  106180. var key = {
  106181. type: 'ed25519',
  106182. parts: [
  106183. { name: 'A', data: utils.zeroPadToLength(A, 32) },
  106184. { name: 'k', data: utils.zeroPadToLength(k, 32) }
  106185. ]
  106186. };
  106187. return (new PrivateKey(key));
  106188. }
  106189. function readPkcs8X25519Private(der) {
  106190. if (der.peek() === 0x00)
  106191. der.readByte();
  106192. der.readSequence(asn1.Ber.OctetString);
  106193. var k = der.readString(asn1.Ber.OctetString, true);
  106194. k = utils.zeroPadToLength(k, 32);
  106195. var A = utils.calculateX25519Public(k);
  106196. var key = {
  106197. type: 'curve25519',
  106198. parts: [
  106199. { name: 'A', data: utils.zeroPadToLength(A, 32) },
  106200. { name: 'k', data: utils.zeroPadToLength(k, 32) }
  106201. ]
  106202. };
  106203. return (new PrivateKey(key));
  106204. }
  106205. function pkcs8ToBuffer(key) {
  106206. var der = new asn1.BerWriter();
  106207. writePkcs8(der, key);
  106208. return (der.buffer);
  106209. }
  106210. function writePkcs8(der, key) {
  106211. der.startSequence();
  106212. if (PrivateKey.isPrivateKey(key)) {
  106213. var sillyInt = Buffer.from([0]);
  106214. der.writeBuffer(sillyInt, asn1.Ber.Integer);
  106215. }
  106216. der.startSequence();
  106217. switch (key.type) {
  106218. case 'rsa':
  106219. der.writeOID('1.2.840.113549.1.1.1');
  106220. if (PrivateKey.isPrivateKey(key))
  106221. writePkcs8RSAPrivate(key, der);
  106222. else
  106223. writePkcs8RSAPublic(key, der);
  106224. break;
  106225. case 'dsa':
  106226. der.writeOID('1.2.840.10040.4.1');
  106227. if (PrivateKey.isPrivateKey(key))
  106228. writePkcs8DSAPrivate(key, der);
  106229. else
  106230. writePkcs8DSAPublic(key, der);
  106231. break;
  106232. case 'ecdsa':
  106233. der.writeOID('1.2.840.10045.2.1');
  106234. if (PrivateKey.isPrivateKey(key))
  106235. writePkcs8ECDSAPrivate(key, der);
  106236. else
  106237. writePkcs8ECDSAPublic(key, der);
  106238. break;
  106239. case 'ed25519':
  106240. der.writeOID('1.3.101.112');
  106241. if (PrivateKey.isPrivateKey(key))
  106242. throw (new Error('Ed25519 private keys in pkcs8 ' +
  106243. 'format are not supported'));
  106244. writePkcs8EdDSAPublic(key, der);
  106245. break;
  106246. default:
  106247. throw (new Error('Unsupported key type: ' + key.type));
  106248. }
  106249. der.endSequence();
  106250. }
  106251. function writePkcs8RSAPrivate(key, der) {
  106252. der.writeNull();
  106253. der.endSequence();
  106254. der.startSequence(asn1.Ber.OctetString);
  106255. der.startSequence();
  106256. var version = Buffer.from([0]);
  106257. der.writeBuffer(version, asn1.Ber.Integer);
  106258. der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
  106259. der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
  106260. der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
  106261. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  106262. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  106263. if (!key.part.dmodp || !key.part.dmodq)
  106264. utils.addRSAMissing(key);
  106265. der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
  106266. der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
  106267. der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
  106268. der.endSequence();
  106269. der.endSequence();
  106270. }
  106271. function writePkcs8RSAPublic(key, der) {
  106272. der.writeNull();
  106273. der.endSequence();
  106274. der.startSequence(asn1.Ber.BitString);
  106275. der.writeByte(0x00);
  106276. der.startSequence();
  106277. der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
  106278. der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
  106279. der.endSequence();
  106280. der.endSequence();
  106281. }
  106282. function writePkcs8DSAPrivate(key, der) {
  106283. der.startSequence();
  106284. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  106285. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  106286. der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
  106287. der.endSequence();
  106288. der.endSequence();
  106289. der.startSequence(asn1.Ber.OctetString);
  106290. der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
  106291. der.endSequence();
  106292. }
  106293. function writePkcs8DSAPublic(key, der) {
  106294. der.startSequence();
  106295. der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
  106296. der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
  106297. der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
  106298. der.endSequence();
  106299. der.endSequence();
  106300. der.startSequence(asn1.Ber.BitString);
  106301. der.writeByte(0x00);
  106302. der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
  106303. der.endSequence();
  106304. }
  106305. function writeECDSACurve(key, der) {
  106306. var curve = algs.curves[key.curve];
  106307. if (curve.pkcs8oid) {
  106308. /* This one has a name in pkcs#8, so just write the oid */
  106309. der.writeOID(curve.pkcs8oid);
  106310. } else {
  106311. // ECParameters sequence
  106312. der.startSequence();
  106313. var version = Buffer.from([1]);
  106314. der.writeBuffer(version, asn1.Ber.Integer);
  106315. // FieldID sequence
  106316. der.startSequence();
  106317. der.writeOID('1.2.840.10045.1.1'); // prime-field
  106318. der.writeBuffer(curve.p, asn1.Ber.Integer);
  106319. der.endSequence();
  106320. // Curve sequence
  106321. der.startSequence();
  106322. var a = curve.p;
  106323. if (a[0] === 0x0)
  106324. a = a.slice(1);
  106325. der.writeBuffer(a, asn1.Ber.OctetString);
  106326. der.writeBuffer(curve.b, asn1.Ber.OctetString);
  106327. der.writeBuffer(curve.s, asn1.Ber.BitString);
  106328. der.endSequence();
  106329. der.writeBuffer(curve.G, asn1.Ber.OctetString);
  106330. der.writeBuffer(curve.n, asn1.Ber.Integer);
  106331. var h = curve.h;
  106332. if (!h) {
  106333. h = Buffer.from([1]);
  106334. }
  106335. der.writeBuffer(h, asn1.Ber.Integer);
  106336. // ECParameters
  106337. der.endSequence();
  106338. }
  106339. }
  106340. function writePkcs8ECDSAPublic(key, der) {
  106341. writeECDSACurve(key, der);
  106342. der.endSequence();
  106343. var Q = utils.ecNormalize(key.part.Q.data, true);
  106344. der.writeBuffer(Q, asn1.Ber.BitString);
  106345. }
  106346. function writePkcs8ECDSAPrivate(key, der) {
  106347. writeECDSACurve(key, der);
  106348. der.endSequence();
  106349. der.startSequence(asn1.Ber.OctetString);
  106350. der.startSequence();
  106351. var version = Buffer.from([1]);
  106352. der.writeBuffer(version, asn1.Ber.Integer);
  106353. der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
  106354. der.startSequence(0xa1);
  106355. var Q = utils.ecNormalize(key.part.Q.data, true);
  106356. der.writeBuffer(Q, asn1.Ber.BitString);
  106357. der.endSequence();
  106358. der.endSequence();
  106359. der.endSequence();
  106360. }
  106361. function writePkcs8EdDSAPublic(key, der) {
  106362. der.endSequence();
  106363. utils.writeBitString(der, key.part.A.data);
  106364. }
  106365. function writePkcs8EdDSAPrivate(key, der) {
  106366. der.endSequence();
  106367. var k = utils.mpNormalize(key.part.k.data, true);
  106368. der.startSequence(asn1.Ber.OctetString);
  106369. der.writeBuffer(k, asn1.Ber.OctetString);
  106370. der.endSequence();
  106371. }
  106372. },{"../algs":572,"../key":592,"../private-key":593,"../utils":596,"./pem":581,"asn1":103,"assert-plus":104,"safer-buffer":562}],584:[function(require,module,exports){
  106373. // Copyright 2018 Joyent, Inc.
  106374. module.exports = {
  106375. read: read,
  106376. write: write
  106377. };
  106378. var assert = require('assert-plus');
  106379. var Buffer = require('safer-buffer').Buffer;
  106380. var rfc4253 = require('./rfc4253');
  106381. var Key = require('../key');
  106382. var errors = require('../errors');
  106383. function read(buf, options) {
  106384. var lines = buf.toString('ascii').split(/[\r\n]+/);
  106385. var found = false;
  106386. var parts;
  106387. var si = 0;
  106388. while (si < lines.length) {
  106389. parts = splitHeader(lines[si++]);
  106390. if (parts &&
  106391. parts[0].toLowerCase() === 'putty-user-key-file-2') {
  106392. found = true;
  106393. break;
  106394. }
  106395. }
  106396. if (!found) {
  106397. throw (new Error('No PuTTY format first line found'));
  106398. }
  106399. var alg = parts[1];
  106400. parts = splitHeader(lines[si++]);
  106401. assert.equal(parts[0].toLowerCase(), 'encryption');
  106402. parts = splitHeader(lines[si++]);
  106403. assert.equal(parts[0].toLowerCase(), 'comment');
  106404. var comment = parts[1];
  106405. parts = splitHeader(lines[si++]);
  106406. assert.equal(parts[0].toLowerCase(), 'public-lines');
  106407. var publicLines = parseInt(parts[1], 10);
  106408. if (!isFinite(publicLines) || publicLines < 0 ||
  106409. publicLines > lines.length) {
  106410. throw (new Error('Invalid public-lines count'));
  106411. }
  106412. var publicBuf = Buffer.from(
  106413. lines.slice(si, si + publicLines).join(''), 'base64');
  106414. var keyType = rfc4253.algToKeyType(alg);
  106415. var key = rfc4253.read(publicBuf);
  106416. if (key.type !== keyType) {
  106417. throw (new Error('Outer key algorithm mismatch'));
  106418. }
  106419. key.comment = comment;
  106420. return (key);
  106421. }
  106422. function splitHeader(line) {
  106423. var idx = line.indexOf(':');
  106424. if (idx === -1)
  106425. return (null);
  106426. var header = line.slice(0, idx);
  106427. ++idx;
  106428. while (line[idx] === ' ')
  106429. ++idx;
  106430. var rest = line.slice(idx);
  106431. return ([header, rest]);
  106432. }
  106433. function write(key, options) {
  106434. assert.object(key);
  106435. if (!Key.isKey(key))
  106436. throw (new Error('Must be a public key'));
  106437. var alg = rfc4253.keyTypeToAlg(key);
  106438. var buf = rfc4253.write(key);
  106439. var comment = key.comment || '';
  106440. var b64 = buf.toString('base64');
  106441. var lines = wrap(b64, 64);
  106442. lines.unshift('Public-Lines: ' + lines.length);
  106443. lines.unshift('Comment: ' + comment);
  106444. lines.unshift('Encryption: none');
  106445. lines.unshift('PuTTY-User-Key-File-2: ' + alg);
  106446. return (Buffer.from(lines.join('\n') + '\n'));
  106447. }
  106448. function wrap(txt, len) {
  106449. var lines = [];
  106450. var pos = 0;
  106451. while (pos < txt.length) {
  106452. lines.push(txt.slice(pos, pos + 64));
  106453. pos += 64;
  106454. }
  106455. return (lines);
  106456. }
  106457. },{"../errors":576,"../key":592,"./rfc4253":585,"assert-plus":104,"safer-buffer":562}],585:[function(require,module,exports){
  106458. // Copyright 2015 Joyent, Inc.
  106459. module.exports = {
  106460. read: read.bind(undefined, false, undefined),
  106461. readType: read.bind(undefined, false),
  106462. write: write,
  106463. /* semi-private api, used by sshpk-agent */
  106464. readPartial: read.bind(undefined, true),
  106465. /* shared with ssh format */
  106466. readInternal: read,
  106467. keyTypeToAlg: keyTypeToAlg,
  106468. algToKeyType: algToKeyType
  106469. };
  106470. var assert = require('assert-plus');
  106471. var Buffer = require('safer-buffer').Buffer;
  106472. var algs = require('../algs');
  106473. var utils = require('../utils');
  106474. var Key = require('../key');
  106475. var PrivateKey = require('../private-key');
  106476. var SSHBuffer = require('../ssh-buffer');
  106477. function algToKeyType(alg) {
  106478. assert.string(alg);
  106479. if (alg === 'ssh-dss')
  106480. return ('dsa');
  106481. else if (alg === 'ssh-rsa')
  106482. return ('rsa');
  106483. else if (alg === 'ssh-ed25519')
  106484. return ('ed25519');
  106485. else if (alg === 'ssh-curve25519')
  106486. return ('curve25519');
  106487. else if (alg.match(/^ecdsa-sha2-/))
  106488. return ('ecdsa');
  106489. else
  106490. throw (new Error('Unknown algorithm ' + alg));
  106491. }
  106492. function keyTypeToAlg(key) {
  106493. assert.object(key);
  106494. if (key.type === 'dsa')
  106495. return ('ssh-dss');
  106496. else if (key.type === 'rsa')
  106497. return ('ssh-rsa');
  106498. else if (key.type === 'ed25519')
  106499. return ('ssh-ed25519');
  106500. else if (key.type === 'curve25519')
  106501. return ('ssh-curve25519');
  106502. else if (key.type === 'ecdsa')
  106503. return ('ecdsa-sha2-' + key.part.curve.data.toString());
  106504. else
  106505. throw (new Error('Unknown key type ' + key.type));
  106506. }
  106507. function read(partial, type, buf, options) {
  106508. if (typeof (buf) === 'string')
  106509. buf = Buffer.from(buf);
  106510. assert.buffer(buf, 'buf');
  106511. var key = {};
  106512. var parts = key.parts = [];
  106513. var sshbuf = new SSHBuffer({buffer: buf});
  106514. var alg = sshbuf.readString();
  106515. assert.ok(!sshbuf.atEnd(), 'key must have at least one part');
  106516. key.type = algToKeyType(alg);
  106517. var partCount = algs.info[key.type].parts.length;
  106518. if (type && type === 'private')
  106519. partCount = algs.privInfo[key.type].parts.length;
  106520. while (!sshbuf.atEnd() && parts.length < partCount)
  106521. parts.push(sshbuf.readPart());
  106522. while (!partial && !sshbuf.atEnd())
  106523. parts.push(sshbuf.readPart());
  106524. assert.ok(parts.length >= 1,
  106525. 'key must have at least one part');
  106526. assert.ok(partial || sshbuf.atEnd(),
  106527. 'leftover bytes at end of key');
  106528. var Constructor = Key;
  106529. var algInfo = algs.info[key.type];
  106530. if (type === 'private' || algInfo.parts.length !== parts.length) {
  106531. algInfo = algs.privInfo[key.type];
  106532. Constructor = PrivateKey;
  106533. }
  106534. assert.strictEqual(algInfo.parts.length, parts.length);
  106535. if (key.type === 'ecdsa') {
  106536. var res = /^ecdsa-sha2-(.+)$/.exec(alg);
  106537. assert.ok(res !== null);
  106538. assert.strictEqual(res[1], parts[0].data.toString());
  106539. }
  106540. var normalized = true;
  106541. for (var i = 0; i < algInfo.parts.length; ++i) {
  106542. var p = parts[i];
  106543. p.name = algInfo.parts[i];
  106544. /*
  106545. * OpenSSH stores ed25519 "private" keys as seed + public key
  106546. * concat'd together (k followed by A). We want to keep them
  106547. * separate for other formats that don't do this.
  106548. */
  106549. if (key.type === 'ed25519' && p.name === 'k')
  106550. p.data = p.data.slice(0, 32);
  106551. if (p.name !== 'curve' && algInfo.normalize !== false) {
  106552. var nd;
  106553. if (key.type === 'ed25519') {
  106554. nd = utils.zeroPadToLength(p.data, 32);
  106555. } else {
  106556. nd = utils.mpNormalize(p.data);
  106557. }
  106558. if (nd.toString('binary') !==
  106559. p.data.toString('binary')) {
  106560. p.data = nd;
  106561. normalized = false;
  106562. }
  106563. }
  106564. }
  106565. if (normalized)
  106566. key._rfc4253Cache = sshbuf.toBuffer();
  106567. if (partial && typeof (partial) === 'object') {
  106568. partial.remainder = sshbuf.remainder();
  106569. partial.consumed = sshbuf._offset;
  106570. }
  106571. return (new Constructor(key));
  106572. }
  106573. function write(key, options) {
  106574. assert.object(key);
  106575. var alg = keyTypeToAlg(key);
  106576. var i;
  106577. var algInfo = algs.info[key.type];
  106578. if (PrivateKey.isPrivateKey(key))
  106579. algInfo = algs.privInfo[key.type];
  106580. var parts = algInfo.parts;
  106581. var buf = new SSHBuffer({});
  106582. buf.writeString(alg);
  106583. for (i = 0; i < parts.length; ++i) {
  106584. var data = key.part[parts[i]].data;
  106585. if (algInfo.normalize !== false) {
  106586. if (key.type === 'ed25519')
  106587. data = utils.zeroPadToLength(data, 32);
  106588. else
  106589. data = utils.mpNormalize(data);
  106590. }
  106591. if (key.type === 'ed25519' && parts[i] === 'k')
  106592. data = Buffer.concat([data, key.part.A.data]);
  106593. buf.writeBuffer(data);
  106594. }
  106595. return (buf.toBuffer());
  106596. }
  106597. },{"../algs":572,"../key":592,"../private-key":593,"../ssh-buffer":595,"../utils":596,"assert-plus":104,"safer-buffer":562}],586:[function(require,module,exports){
  106598. // Copyright 2015 Joyent, Inc.
  106599. module.exports = {
  106600. read: read,
  106601. readSSHPrivate: readSSHPrivate,
  106602. write: write
  106603. };
  106604. var assert = require('assert-plus');
  106605. var asn1 = require('asn1');
  106606. var Buffer = require('safer-buffer').Buffer;
  106607. var algs = require('../algs');
  106608. var utils = require('../utils');
  106609. var crypto = require('crypto');
  106610. var Key = require('../key');
  106611. var PrivateKey = require('../private-key');
  106612. var pem = require('./pem');
  106613. var rfc4253 = require('./rfc4253');
  106614. var SSHBuffer = require('../ssh-buffer');
  106615. var errors = require('../errors');
  106616. var bcrypt;
  106617. function read(buf, options) {
  106618. return (pem.read(buf, options));
  106619. }
  106620. var MAGIC = 'openssh-key-v1';
  106621. function readSSHPrivate(type, buf, options) {
  106622. buf = new SSHBuffer({buffer: buf});
  106623. var magic = buf.readCString();
  106624. assert.strictEqual(magic, MAGIC, 'bad magic string');
  106625. var cipher = buf.readString();
  106626. var kdf = buf.readString();
  106627. var kdfOpts = buf.readBuffer();
  106628. var nkeys = buf.readInt();
  106629. if (nkeys !== 1) {
  106630. throw (new Error('OpenSSH-format key file contains ' +
  106631. 'multiple keys: this is unsupported.'));
  106632. }
  106633. var pubKey = buf.readBuffer();
  106634. if (type === 'public') {
  106635. assert.ok(buf.atEnd(), 'excess bytes left after key');
  106636. return (rfc4253.read(pubKey));
  106637. }
  106638. var privKeyBlob = buf.readBuffer();
  106639. assert.ok(buf.atEnd(), 'excess bytes left after key');
  106640. var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts });
  106641. switch (kdf) {
  106642. case 'none':
  106643. if (cipher !== 'none') {
  106644. throw (new Error('OpenSSH-format key uses KDF "none" ' +
  106645. 'but specifies a cipher other than "none"'));
  106646. }
  106647. break;
  106648. case 'bcrypt':
  106649. var salt = kdfOptsBuf.readBuffer();
  106650. var rounds = kdfOptsBuf.readInt();
  106651. var cinf = utils.opensshCipherInfo(cipher);
  106652. if (bcrypt === undefined) {
  106653. bcrypt = require('bcrypt-pbkdf');
  106654. }
  106655. if (typeof (options.passphrase) === 'string') {
  106656. options.passphrase = Buffer.from(options.passphrase,
  106657. 'utf-8');
  106658. }
  106659. if (!Buffer.isBuffer(options.passphrase)) {
  106660. throw (new errors.KeyEncryptedError(
  106661. options.filename, 'OpenSSH'));
  106662. }
  106663. var pass = new Uint8Array(options.passphrase);
  106664. var salti = new Uint8Array(salt);
  106665. /* Use the pbkdf to derive both the key and the IV. */
  106666. var out = new Uint8Array(cinf.keySize + cinf.blockSize);
  106667. var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
  106668. out, out.length, rounds);
  106669. if (res !== 0) {
  106670. throw (new Error('bcrypt_pbkdf function returned ' +
  106671. 'failure, parameters invalid'));
  106672. }
  106673. out = Buffer.from(out);
  106674. var ckey = out.slice(0, cinf.keySize);
  106675. var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
  106676. var cipherStream = crypto.createDecipheriv(cinf.opensslName,
  106677. ckey, iv);
  106678. cipherStream.setAutoPadding(false);
  106679. var chunk, chunks = [];
  106680. cipherStream.once('error', function (e) {
  106681. if (e.toString().indexOf('bad decrypt') !== -1) {
  106682. throw (new Error('Incorrect passphrase ' +
  106683. 'supplied, could not decrypt key'));
  106684. }
  106685. throw (e);
  106686. });
  106687. cipherStream.write(privKeyBlob);
  106688. cipherStream.end();
  106689. while ((chunk = cipherStream.read()) !== null)
  106690. chunks.push(chunk);
  106691. privKeyBlob = Buffer.concat(chunks);
  106692. break;
  106693. default:
  106694. throw (new Error(
  106695. 'OpenSSH-format key uses unknown KDF "' + kdf + '"'));
  106696. }
  106697. buf = new SSHBuffer({buffer: privKeyBlob});
  106698. var checkInt1 = buf.readInt();
  106699. var checkInt2 = buf.readInt();
  106700. if (checkInt1 !== checkInt2) {
  106701. throw (new Error('Incorrect passphrase supplied, could not ' +
  106702. 'decrypt key'));
  106703. }
  106704. var ret = {};
  106705. var key = rfc4253.readInternal(ret, 'private', buf.remainder());
  106706. buf.skip(ret.consumed);
  106707. var comment = buf.readString();
  106708. key.comment = comment;
  106709. return (key);
  106710. }
  106711. function write(key, options) {
  106712. var pubKey;
  106713. if (PrivateKey.isPrivateKey(key))
  106714. pubKey = key.toPublic();
  106715. else
  106716. pubKey = key;
  106717. var cipher = 'none';
  106718. var kdf = 'none';
  106719. var kdfopts = Buffer.alloc(0);
  106720. var cinf = { blockSize: 8 };
  106721. var passphrase;
  106722. if (options !== undefined) {
  106723. passphrase = options.passphrase;
  106724. if (typeof (passphrase) === 'string')
  106725. passphrase = Buffer.from(passphrase, 'utf-8');
  106726. if (passphrase !== undefined) {
  106727. assert.buffer(passphrase, 'options.passphrase');
  106728. assert.optionalString(options.cipher, 'options.cipher');
  106729. cipher = options.cipher;
  106730. if (cipher === undefined)
  106731. cipher = 'aes128-ctr';
  106732. cinf = utils.opensshCipherInfo(cipher);
  106733. kdf = 'bcrypt';
  106734. }
  106735. }
  106736. var privBuf;
  106737. if (PrivateKey.isPrivateKey(key)) {
  106738. privBuf = new SSHBuffer({});
  106739. var checkInt = crypto.randomBytes(4).readUInt32BE(0);
  106740. privBuf.writeInt(checkInt);
  106741. privBuf.writeInt(checkInt);
  106742. privBuf.write(key.toBuffer('rfc4253'));
  106743. privBuf.writeString(key.comment || '');
  106744. var n = 1;
  106745. while (privBuf._offset % cinf.blockSize !== 0)
  106746. privBuf.writeChar(n++);
  106747. privBuf = privBuf.toBuffer();
  106748. }
  106749. switch (kdf) {
  106750. case 'none':
  106751. break;
  106752. case 'bcrypt':
  106753. var salt = crypto.randomBytes(16);
  106754. var rounds = 16;
  106755. var kdfssh = new SSHBuffer({});
  106756. kdfssh.writeBuffer(salt);
  106757. kdfssh.writeInt(rounds);
  106758. kdfopts = kdfssh.toBuffer();
  106759. if (bcrypt === undefined) {
  106760. bcrypt = require('bcrypt-pbkdf');
  106761. }
  106762. var pass = new Uint8Array(passphrase);
  106763. var salti = new Uint8Array(salt);
  106764. /* Use the pbkdf to derive both the key and the IV. */
  106765. var out = new Uint8Array(cinf.keySize + cinf.blockSize);
  106766. var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
  106767. out, out.length, rounds);
  106768. if (res !== 0) {
  106769. throw (new Error('bcrypt_pbkdf function returned ' +
  106770. 'failure, parameters invalid'));
  106771. }
  106772. out = Buffer.from(out);
  106773. var ckey = out.slice(0, cinf.keySize);
  106774. var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
  106775. var cipherStream = crypto.createCipheriv(cinf.opensslName,
  106776. ckey, iv);
  106777. cipherStream.setAutoPadding(false);
  106778. var chunk, chunks = [];
  106779. cipherStream.once('error', function (e) {
  106780. throw (e);
  106781. });
  106782. cipherStream.write(privBuf);
  106783. cipherStream.end();
  106784. while ((chunk = cipherStream.read()) !== null)
  106785. chunks.push(chunk);
  106786. privBuf = Buffer.concat(chunks);
  106787. break;
  106788. default:
  106789. throw (new Error('Unsupported kdf ' + kdf));
  106790. }
  106791. var buf = new SSHBuffer({});
  106792. buf.writeCString(MAGIC);
  106793. buf.writeString(cipher); /* cipher */
  106794. buf.writeString(kdf); /* kdf */
  106795. buf.writeBuffer(kdfopts); /* kdfoptions */
  106796. buf.writeInt(1); /* nkeys */
  106797. buf.writeBuffer(pubKey.toBuffer('rfc4253'));
  106798. if (privBuf)
  106799. buf.writeBuffer(privBuf);
  106800. buf = buf.toBuffer();
  106801. var header;
  106802. if (PrivateKey.isPrivateKey(key))
  106803. header = 'OPENSSH PRIVATE KEY';
  106804. else
  106805. header = 'OPENSSH PUBLIC KEY';
  106806. var tmp = buf.toString('base64');
  106807. var len = tmp.length + (tmp.length / 70) +
  106808. 18 + 16 + header.length*2 + 10;
  106809. buf = Buffer.alloc(len);
  106810. var o = 0;
  106811. o += buf.write('-----BEGIN ' + header + '-----\n', o);
  106812. for (var i = 0; i < tmp.length; ) {
  106813. var limit = i + 70;
  106814. if (limit > tmp.length)
  106815. limit = tmp.length;
  106816. o += buf.write(tmp.slice(i, limit), o);
  106817. buf[o++] = 10;
  106818. i = limit;
  106819. }
  106820. o += buf.write('-----END ' + header + '-----\n', o);
  106821. return (buf.slice(0, o));
  106822. }
  106823. },{"../algs":572,"../errors":576,"../key":592,"../private-key":593,"../ssh-buffer":595,"../utils":596,"./pem":581,"./rfc4253":585,"asn1":103,"assert-plus":104,"bcrypt-pbkdf":141,"crypto":208,"safer-buffer":562}],587:[function(require,module,exports){
  106824. // Copyright 2015 Joyent, Inc.
  106825. module.exports = {
  106826. read: read,
  106827. write: write
  106828. };
  106829. var assert = require('assert-plus');
  106830. var Buffer = require('safer-buffer').Buffer;
  106831. var rfc4253 = require('./rfc4253');
  106832. var utils = require('../utils');
  106833. var Key = require('../key');
  106834. var PrivateKey = require('../private-key');
  106835. var sshpriv = require('./ssh-private');
  106836. /*JSSTYLED*/
  106837. var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/;
  106838. /*JSSTYLED*/
  106839. var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/;
  106840. function read(buf, options) {
  106841. if (typeof (buf) !== 'string') {
  106842. assert.buffer(buf, 'buf');
  106843. buf = buf.toString('ascii');
  106844. }
  106845. var trimmed = buf.trim().replace(/[\\\r]/g, '');
  106846. var m = trimmed.match(SSHKEY_RE);
  106847. if (!m)
  106848. m = trimmed.match(SSHKEY_RE2);
  106849. assert.ok(m, 'key must match regex');
  106850. var type = rfc4253.algToKeyType(m[1]);
  106851. var kbuf = Buffer.from(m[2], 'base64');
  106852. /*
  106853. * This is a bit tricky. If we managed to parse the key and locate the
  106854. * key comment with the regex, then do a non-partial read and assert
  106855. * that we have consumed all bytes. If we couldn't locate the key
  106856. * comment, though, there may be whitespace shenanigans going on that
  106857. * have conjoined the comment to the rest of the key. We do a partial
  106858. * read in this case to try to make the best out of a sorry situation.
  106859. */
  106860. var key;
  106861. var ret = {};
  106862. if (m[4]) {
  106863. try {
  106864. key = rfc4253.read(kbuf);
  106865. } catch (e) {
  106866. m = trimmed.match(SSHKEY_RE2);
  106867. assert.ok(m, 'key must match regex');
  106868. kbuf = Buffer.from(m[2], 'base64');
  106869. key = rfc4253.readInternal(ret, 'public', kbuf);
  106870. }
  106871. } else {
  106872. key = rfc4253.readInternal(ret, 'public', kbuf);
  106873. }
  106874. assert.strictEqual(type, key.type);
  106875. if (m[4] && m[4].length > 0) {
  106876. key.comment = m[4];
  106877. } else if (ret.consumed) {
  106878. /*
  106879. * Now the magic: trying to recover the key comment when it's
  106880. * gotten conjoined to the key or otherwise shenanigan'd.
  106881. *
  106882. * Work out how much base64 we used, then drop all non-base64
  106883. * chars from the beginning up to this point in the the string.
  106884. * Then offset in this and try to make up for missing = chars.
  106885. */
  106886. var data = m[2] + (m[3] ? m[3] : '');
  106887. var realOffset = Math.ceil(ret.consumed / 3) * 4;
  106888. data = data.slice(0, realOffset - 2). /*JSSTYLED*/
  106889. replace(/[^a-zA-Z0-9+\/=]/g, '') +
  106890. data.slice(realOffset - 2);
  106891. var padding = ret.consumed % 3;
  106892. if (padding > 0 &&
  106893. data.slice(realOffset - 1, realOffset) !== '=')
  106894. realOffset--;
  106895. while (data.slice(realOffset, realOffset + 1) === '=')
  106896. realOffset++;
  106897. /* Finally, grab what we think is the comment & clean it up. */
  106898. var trailer = data.slice(realOffset);
  106899. trailer = trailer.replace(/[\r\n]/g, ' ').
  106900. replace(/^\s+/, '');
  106901. if (trailer.match(/^[a-zA-Z0-9]/))
  106902. key.comment = trailer;
  106903. }
  106904. return (key);
  106905. }
  106906. function write(key, options) {
  106907. assert.object(key);
  106908. if (!Key.isKey(key))
  106909. throw (new Error('Must be a public key'));
  106910. var parts = [];
  106911. var alg = rfc4253.keyTypeToAlg(key);
  106912. parts.push(alg);
  106913. var buf = rfc4253.write(key);
  106914. parts.push(buf.toString('base64'));
  106915. if (key.comment)
  106916. parts.push(key.comment);
  106917. return (Buffer.from(parts.join(' ')));
  106918. }
  106919. },{"../key":592,"../private-key":593,"../utils":596,"./rfc4253":585,"./ssh-private":586,"assert-plus":104,"safer-buffer":562}],588:[function(require,module,exports){
  106920. // Copyright 2016 Joyent, Inc.
  106921. var x509 = require('./x509');
  106922. module.exports = {
  106923. read: read,
  106924. verify: x509.verify,
  106925. sign: x509.sign,
  106926. write: write
  106927. };
  106928. var assert = require('assert-plus');
  106929. var asn1 = require('asn1');
  106930. var Buffer = require('safer-buffer').Buffer;
  106931. var algs = require('../algs');
  106932. var utils = require('../utils');
  106933. var Key = require('../key');
  106934. var PrivateKey = require('../private-key');
  106935. var pem = require('./pem');
  106936. var Identity = require('../identity');
  106937. var Signature = require('../signature');
  106938. var Certificate = require('../certificate');
  106939. function read(buf, options) {
  106940. if (typeof (buf) !== 'string') {
  106941. assert.buffer(buf, 'buf');
  106942. buf = buf.toString('ascii');
  106943. }
  106944. var lines = buf.trim().split(/[\r\n]+/g);
  106945. var m;
  106946. var si = -1;
  106947. while (!m && si < lines.length) {
  106948. m = lines[++si].match(/*JSSTYLED*/
  106949. /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);
  106950. }
  106951. assert.ok(m, 'invalid PEM header');
  106952. var m2;
  106953. var ei = lines.length;
  106954. while (!m2 && ei > 0) {
  106955. m2 = lines[--ei].match(/*JSSTYLED*/
  106956. /[-]+[ ]*END CERTIFICATE[ ]*[-]+/);
  106957. }
  106958. assert.ok(m2, 'invalid PEM footer');
  106959. lines = lines.slice(si, ei + 1);
  106960. var headers = {};
  106961. while (true) {
  106962. lines = lines.slice(1);
  106963. m = lines[0].match(/*JSSTYLED*/
  106964. /^([A-Za-z0-9-]+): (.+)$/);
  106965. if (!m)
  106966. break;
  106967. headers[m[1].toLowerCase()] = m[2];
  106968. }
  106969. /* Chop off the first and last lines */
  106970. lines = lines.slice(0, -1).join('');
  106971. buf = Buffer.from(lines, 'base64');
  106972. return (x509.read(buf, options));
  106973. }
  106974. function write(cert, options) {
  106975. var dbuf = x509.write(cert, options);
  106976. var header = 'CERTIFICATE';
  106977. var tmp = dbuf.toString('base64');
  106978. var len = tmp.length + (tmp.length / 64) +
  106979. 18 + 16 + header.length*2 + 10;
  106980. var buf = Buffer.alloc(len);
  106981. var o = 0;
  106982. o += buf.write('-----BEGIN ' + header + '-----\n', o);
  106983. for (var i = 0; i < tmp.length; ) {
  106984. var limit = i + 64;
  106985. if (limit > tmp.length)
  106986. limit = tmp.length;
  106987. o += buf.write(tmp.slice(i, limit), o);
  106988. buf[o++] = 10;
  106989. i = limit;
  106990. }
  106991. o += buf.write('-----END ' + header + '-----\n', o);
  106992. return (buf.slice(0, o));
  106993. }
  106994. },{"../algs":572,"../certificate":573,"../identity":590,"../key":592,"../private-key":593,"../signature":594,"../utils":596,"./pem":581,"./x509":589,"asn1":103,"assert-plus":104,"safer-buffer":562}],589:[function(require,module,exports){
  106995. // Copyright 2017 Joyent, Inc.
  106996. module.exports = {
  106997. read: read,
  106998. verify: verify,
  106999. sign: sign,
  107000. signAsync: signAsync,
  107001. write: write
  107002. };
  107003. var assert = require('assert-plus');
  107004. var asn1 = require('asn1');
  107005. var Buffer = require('safer-buffer').Buffer;
  107006. var algs = require('../algs');
  107007. var utils = require('../utils');
  107008. var Key = require('../key');
  107009. var PrivateKey = require('../private-key');
  107010. var pem = require('./pem');
  107011. var Identity = require('../identity');
  107012. var Signature = require('../signature');
  107013. var Certificate = require('../certificate');
  107014. var pkcs8 = require('./pkcs8');
  107015. /*
  107016. * This file is based on RFC5280 (X.509).
  107017. */
  107018. /* Helper to read in a single mpint */
  107019. function readMPInt(der, nm) {
  107020. assert.strictEqual(der.peek(), asn1.Ber.Integer,
  107021. nm + ' is not an Integer');
  107022. return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
  107023. }
  107024. function verify(cert, key) {
  107025. var sig = cert.signatures.x509;
  107026. assert.object(sig, 'x509 signature');
  107027. var algParts = sig.algo.split('-');
  107028. if (algParts[0] !== key.type)
  107029. return (false);
  107030. var blob = sig.cache;
  107031. if (blob === undefined) {
  107032. var der = new asn1.BerWriter();
  107033. writeTBSCert(cert, der);
  107034. blob = der.buffer;
  107035. }
  107036. var verifier = key.createVerify(algParts[1]);
  107037. verifier.write(blob);
  107038. return (verifier.verify(sig.signature));
  107039. }
  107040. function Local(i) {
  107041. return (asn1.Ber.Context | asn1.Ber.Constructor | i);
  107042. }
  107043. function Context(i) {
  107044. return (asn1.Ber.Context | i);
  107045. }
  107046. var SIGN_ALGS = {
  107047. 'rsa-md5': '1.2.840.113549.1.1.4',
  107048. 'rsa-sha1': '1.2.840.113549.1.1.5',
  107049. 'rsa-sha256': '1.2.840.113549.1.1.11',
  107050. 'rsa-sha384': '1.2.840.113549.1.1.12',
  107051. 'rsa-sha512': '1.2.840.113549.1.1.13',
  107052. 'dsa-sha1': '1.2.840.10040.4.3',
  107053. 'dsa-sha256': '2.16.840.1.101.3.4.3.2',
  107054. 'ecdsa-sha1': '1.2.840.10045.4.1',
  107055. 'ecdsa-sha256': '1.2.840.10045.4.3.2',
  107056. 'ecdsa-sha384': '1.2.840.10045.4.3.3',
  107057. 'ecdsa-sha512': '1.2.840.10045.4.3.4',
  107058. 'ed25519-sha512': '1.3.101.112'
  107059. };
  107060. Object.keys(SIGN_ALGS).forEach(function (k) {
  107061. SIGN_ALGS[SIGN_ALGS[k]] = k;
  107062. });
  107063. SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5';
  107064. SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1';
  107065. var EXTS = {
  107066. 'issuerKeyId': '2.5.29.35',
  107067. 'altName': '2.5.29.17',
  107068. 'basicConstraints': '2.5.29.19',
  107069. 'keyUsage': '2.5.29.15',
  107070. 'extKeyUsage': '2.5.29.37'
  107071. };
  107072. function read(buf, options) {
  107073. if (typeof (buf) === 'string') {
  107074. buf = Buffer.from(buf, 'binary');
  107075. }
  107076. assert.buffer(buf, 'buf');
  107077. var der = new asn1.BerReader(buf);
  107078. der.readSequence();
  107079. if (Math.abs(der.length - der.remain) > 1) {
  107080. throw (new Error('DER sequence does not contain whole byte ' +
  107081. 'stream'));
  107082. }
  107083. var tbsStart = der.offset;
  107084. der.readSequence();
  107085. var sigOffset = der.offset + der.length;
  107086. var tbsEnd = sigOffset;
  107087. if (der.peek() === Local(0)) {
  107088. der.readSequence(Local(0));
  107089. var version = der.readInt();
  107090. assert.ok(version <= 3,
  107091. 'only x.509 versions up to v3 supported');
  107092. }
  107093. var cert = {};
  107094. cert.signatures = {};
  107095. var sig = (cert.signatures.x509 = {});
  107096. sig.extras = {};
  107097. cert.serial = readMPInt(der, 'serial');
  107098. der.readSequence();
  107099. var after = der.offset + der.length;
  107100. var certAlgOid = der.readOID();
  107101. var certAlg = SIGN_ALGS[certAlgOid];
  107102. if (certAlg === undefined)
  107103. throw (new Error('unknown signature algorithm ' + certAlgOid));
  107104. der._offset = after;
  107105. cert.issuer = Identity.parseAsn1(der);
  107106. der.readSequence();
  107107. cert.validFrom = readDate(der);
  107108. cert.validUntil = readDate(der);
  107109. cert.subjects = [Identity.parseAsn1(der)];
  107110. der.readSequence();
  107111. after = der.offset + der.length;
  107112. cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der);
  107113. der._offset = after;
  107114. /* issuerUniqueID */
  107115. if (der.peek() === Local(1)) {
  107116. der.readSequence(Local(1));
  107117. sig.extras.issuerUniqueID =
  107118. buf.slice(der.offset, der.offset + der.length);
  107119. der._offset += der.length;
  107120. }
  107121. /* subjectUniqueID */
  107122. if (der.peek() === Local(2)) {
  107123. der.readSequence(Local(2));
  107124. sig.extras.subjectUniqueID =
  107125. buf.slice(der.offset, der.offset + der.length);
  107126. der._offset += der.length;
  107127. }
  107128. /* extensions */
  107129. if (der.peek() === Local(3)) {
  107130. der.readSequence(Local(3));
  107131. var extEnd = der.offset + der.length;
  107132. der.readSequence();
  107133. while (der.offset < extEnd)
  107134. readExtension(cert, buf, der);
  107135. assert.strictEqual(der.offset, extEnd);
  107136. }
  107137. assert.strictEqual(der.offset, sigOffset);
  107138. der.readSequence();
  107139. after = der.offset + der.length;
  107140. var sigAlgOid = der.readOID();
  107141. var sigAlg = SIGN_ALGS[sigAlgOid];
  107142. if (sigAlg === undefined)
  107143. throw (new Error('unknown signature algorithm ' + sigAlgOid));
  107144. der._offset = after;
  107145. var sigData = der.readString(asn1.Ber.BitString, true);
  107146. if (sigData[0] === 0)
  107147. sigData = sigData.slice(1);
  107148. var algParts = sigAlg.split('-');
  107149. sig.signature = Signature.parse(sigData, algParts[0], 'asn1');
  107150. sig.signature.hashAlgorithm = algParts[1];
  107151. sig.algo = sigAlg;
  107152. sig.cache = buf.slice(tbsStart, tbsEnd);
  107153. return (new Certificate(cert));
  107154. }
  107155. function readDate(der) {
  107156. if (der.peek() === asn1.Ber.UTCTime) {
  107157. return (utcTimeToDate(der.readString(asn1.Ber.UTCTime)));
  107158. } else if (der.peek() === asn1.Ber.GeneralizedTime) {
  107159. return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime)));
  107160. } else {
  107161. throw (new Error('Unsupported date format'));
  107162. }
  107163. }
  107164. function writeDate(der, date) {
  107165. if (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) {
  107166. der.writeString(dateToGTime(date), asn1.Ber.GeneralizedTime);
  107167. } else {
  107168. der.writeString(dateToUTCTime(date), asn1.Ber.UTCTime);
  107169. }
  107170. }
  107171. /* RFC5280, section 4.2.1.6 (GeneralName type) */
  107172. var ALTNAME = {
  107173. OtherName: Local(0),
  107174. RFC822Name: Context(1),
  107175. DNSName: Context(2),
  107176. X400Address: Local(3),
  107177. DirectoryName: Local(4),
  107178. EDIPartyName: Local(5),
  107179. URI: Context(6),
  107180. IPAddress: Context(7),
  107181. OID: Context(8)
  107182. };
  107183. /* RFC5280, section 4.2.1.12 (KeyPurposeId) */
  107184. var EXTPURPOSE = {
  107185. 'serverAuth': '1.3.6.1.5.5.7.3.1',
  107186. 'clientAuth': '1.3.6.1.5.5.7.3.2',
  107187. 'codeSigning': '1.3.6.1.5.5.7.3.3',
  107188. /* See https://github.com/joyent/oid-docs/blob/master/root.md */
  107189. 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1',
  107190. 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2'
  107191. };
  107192. var EXTPURPOSE_REV = {};
  107193. Object.keys(EXTPURPOSE).forEach(function (k) {
  107194. EXTPURPOSE_REV[EXTPURPOSE[k]] = k;
  107195. });
  107196. var KEYUSEBITS = [
  107197. 'signature', 'identity', 'keyEncryption',
  107198. 'encryption', 'keyAgreement', 'ca', 'crl'
  107199. ];
  107200. function readExtension(cert, buf, der) {
  107201. der.readSequence();
  107202. var after = der.offset + der.length;
  107203. var extId = der.readOID();
  107204. var id;
  107205. var sig = cert.signatures.x509;
  107206. if (!sig.extras.exts)
  107207. sig.extras.exts = [];
  107208. var critical;
  107209. if (der.peek() === asn1.Ber.Boolean)
  107210. critical = der.readBoolean();
  107211. switch (extId) {
  107212. case (EXTS.basicConstraints):
  107213. der.readSequence(asn1.Ber.OctetString);
  107214. der.readSequence();
  107215. var bcEnd = der.offset + der.length;
  107216. var ca = false;
  107217. if (der.peek() === asn1.Ber.Boolean)
  107218. ca = der.readBoolean();
  107219. if (cert.purposes === undefined)
  107220. cert.purposes = [];
  107221. if (ca === true)
  107222. cert.purposes.push('ca');
  107223. var bc = { oid: extId, critical: critical };
  107224. if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer)
  107225. bc.pathLen = der.readInt();
  107226. sig.extras.exts.push(bc);
  107227. break;
  107228. case (EXTS.extKeyUsage):
  107229. der.readSequence(asn1.Ber.OctetString);
  107230. der.readSequence();
  107231. if (cert.purposes === undefined)
  107232. cert.purposes = [];
  107233. var ekEnd = der.offset + der.length;
  107234. while (der.offset < ekEnd) {
  107235. var oid = der.readOID();
  107236. cert.purposes.push(EXTPURPOSE_REV[oid] || oid);
  107237. }
  107238. /*
  107239. * This is a bit of a hack: in the case where we have a cert
  107240. * that's only allowed to do serverAuth or clientAuth (and not
  107241. * the other), we want to make sure all our Subjects are of
  107242. * the right type. But we already parsed our Subjects and
  107243. * decided if they were hosts or users earlier (since it appears
  107244. * first in the cert).
  107245. *
  107246. * So we go through and mutate them into the right kind here if
  107247. * it doesn't match. This might not be hugely beneficial, as it
  107248. * seems that single-purpose certs are not often seen in the
  107249. * wild.
  107250. */
  107251. if (cert.purposes.indexOf('serverAuth') !== -1 &&
  107252. cert.purposes.indexOf('clientAuth') === -1) {
  107253. cert.subjects.forEach(function (ide) {
  107254. if (ide.type !== 'host') {
  107255. ide.type = 'host';
  107256. ide.hostname = ide.uid ||
  107257. ide.email ||
  107258. ide.components[0].value;
  107259. }
  107260. });
  107261. } else if (cert.purposes.indexOf('clientAuth') !== -1 &&
  107262. cert.purposes.indexOf('serverAuth') === -1) {
  107263. cert.subjects.forEach(function (ide) {
  107264. if (ide.type !== 'user') {
  107265. ide.type = 'user';
  107266. ide.uid = ide.hostname ||
  107267. ide.email ||
  107268. ide.components[0].value;
  107269. }
  107270. });
  107271. }
  107272. sig.extras.exts.push({ oid: extId, critical: critical });
  107273. break;
  107274. case (EXTS.keyUsage):
  107275. der.readSequence(asn1.Ber.OctetString);
  107276. var bits = der.readString(asn1.Ber.BitString, true);
  107277. var setBits = readBitField(bits, KEYUSEBITS);
  107278. setBits.forEach(function (bit) {
  107279. if (cert.purposes === undefined)
  107280. cert.purposes = [];
  107281. if (cert.purposes.indexOf(bit) === -1)
  107282. cert.purposes.push(bit);
  107283. });
  107284. sig.extras.exts.push({ oid: extId, critical: critical,
  107285. bits: bits });
  107286. break;
  107287. case (EXTS.altName):
  107288. der.readSequence(asn1.Ber.OctetString);
  107289. der.readSequence();
  107290. var aeEnd = der.offset + der.length;
  107291. while (der.offset < aeEnd) {
  107292. switch (der.peek()) {
  107293. case ALTNAME.OtherName:
  107294. case ALTNAME.EDIPartyName:
  107295. der.readSequence();
  107296. der._offset += der.length;
  107297. break;
  107298. case ALTNAME.OID:
  107299. der.readOID(ALTNAME.OID);
  107300. break;
  107301. case ALTNAME.RFC822Name:
  107302. /* RFC822 specifies email addresses */
  107303. var email = der.readString(ALTNAME.RFC822Name);
  107304. id = Identity.forEmail(email);
  107305. if (!cert.subjects[0].equals(id))
  107306. cert.subjects.push(id);
  107307. break;
  107308. case ALTNAME.DirectoryName:
  107309. der.readSequence(ALTNAME.DirectoryName);
  107310. id = Identity.parseAsn1(der);
  107311. if (!cert.subjects[0].equals(id))
  107312. cert.subjects.push(id);
  107313. break;
  107314. case ALTNAME.DNSName:
  107315. var host = der.readString(
  107316. ALTNAME.DNSName);
  107317. id = Identity.forHost(host);
  107318. if (!cert.subjects[0].equals(id))
  107319. cert.subjects.push(id);
  107320. break;
  107321. default:
  107322. der.readString(der.peek());
  107323. break;
  107324. }
  107325. }
  107326. sig.extras.exts.push({ oid: extId, critical: critical });
  107327. break;
  107328. default:
  107329. sig.extras.exts.push({
  107330. oid: extId,
  107331. critical: critical,
  107332. data: der.readString(asn1.Ber.OctetString, true)
  107333. });
  107334. break;
  107335. }
  107336. der._offset = after;
  107337. }
  107338. var UTCTIME_RE =
  107339. /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
  107340. function utcTimeToDate(t) {
  107341. var m = t.match(UTCTIME_RE);
  107342. assert.ok(m, 'timestamps must be in UTC');
  107343. var d = new Date();
  107344. var thisYear = d.getUTCFullYear();
  107345. var century = Math.floor(thisYear / 100) * 100;
  107346. var year = parseInt(m[1], 10);
  107347. if (thisYear % 100 < 50 && year >= 60)
  107348. year += (century - 1);
  107349. else
  107350. year += century;
  107351. d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10));
  107352. d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
  107353. if (m[6] && m[6].length > 0)
  107354. d.setUTCSeconds(parseInt(m[6], 10));
  107355. return (d);
  107356. }
  107357. var GTIME_RE =
  107358. /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
  107359. function gTimeToDate(t) {
  107360. var m = t.match(GTIME_RE);
  107361. assert.ok(m);
  107362. var d = new Date();
  107363. d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1,
  107364. parseInt(m[3], 10));
  107365. d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
  107366. if (m[6] && m[6].length > 0)
  107367. d.setUTCSeconds(parseInt(m[6], 10));
  107368. return (d);
  107369. }
  107370. function zeroPad(n, m) {
  107371. if (m === undefined)
  107372. m = 2;
  107373. var s = '' + n;
  107374. while (s.length < m)
  107375. s = '0' + s;
  107376. return (s);
  107377. }
  107378. function dateToUTCTime(d) {
  107379. var s = '';
  107380. s += zeroPad(d.getUTCFullYear() % 100);
  107381. s += zeroPad(d.getUTCMonth() + 1);
  107382. s += zeroPad(d.getUTCDate());
  107383. s += zeroPad(d.getUTCHours());
  107384. s += zeroPad(d.getUTCMinutes());
  107385. s += zeroPad(d.getUTCSeconds());
  107386. s += 'Z';
  107387. return (s);
  107388. }
  107389. function dateToGTime(d) {
  107390. var s = '';
  107391. s += zeroPad(d.getUTCFullYear(), 4);
  107392. s += zeroPad(d.getUTCMonth() + 1);
  107393. s += zeroPad(d.getUTCDate());
  107394. s += zeroPad(d.getUTCHours());
  107395. s += zeroPad(d.getUTCMinutes());
  107396. s += zeroPad(d.getUTCSeconds());
  107397. s += 'Z';
  107398. return (s);
  107399. }
  107400. function sign(cert, key) {
  107401. if (cert.signatures.x509 === undefined)
  107402. cert.signatures.x509 = {};
  107403. var sig = cert.signatures.x509;
  107404. sig.algo = key.type + '-' + key.defaultHashAlgorithm();
  107405. if (SIGN_ALGS[sig.algo] === undefined)
  107406. return (false);
  107407. var der = new asn1.BerWriter();
  107408. writeTBSCert(cert, der);
  107409. var blob = der.buffer;
  107410. sig.cache = blob;
  107411. var signer = key.createSign();
  107412. signer.write(blob);
  107413. cert.signatures.x509.signature = signer.sign();
  107414. return (true);
  107415. }
  107416. function signAsync(cert, signer, done) {
  107417. if (cert.signatures.x509 === undefined)
  107418. cert.signatures.x509 = {};
  107419. var sig = cert.signatures.x509;
  107420. var der = new asn1.BerWriter();
  107421. writeTBSCert(cert, der);
  107422. var blob = der.buffer;
  107423. sig.cache = blob;
  107424. signer(blob, function (err, signature) {
  107425. if (err) {
  107426. done(err);
  107427. return;
  107428. }
  107429. sig.algo = signature.type + '-' + signature.hashAlgorithm;
  107430. if (SIGN_ALGS[sig.algo] === undefined) {
  107431. done(new Error('Invalid signing algorithm "' +
  107432. sig.algo + '"'));
  107433. return;
  107434. }
  107435. sig.signature = signature;
  107436. done();
  107437. });
  107438. }
  107439. function write(cert, options) {
  107440. var sig = cert.signatures.x509;
  107441. assert.object(sig, 'x509 signature');
  107442. var der = new asn1.BerWriter();
  107443. der.startSequence();
  107444. if (sig.cache) {
  107445. der._ensure(sig.cache.length);
  107446. sig.cache.copy(der._buf, der._offset);
  107447. der._offset += sig.cache.length;
  107448. } else {
  107449. writeTBSCert(cert, der);
  107450. }
  107451. der.startSequence();
  107452. der.writeOID(SIGN_ALGS[sig.algo]);
  107453. if (sig.algo.match(/^rsa-/))
  107454. der.writeNull();
  107455. der.endSequence();
  107456. var sigData = sig.signature.toBuffer('asn1');
  107457. var data = Buffer.alloc(sigData.length + 1);
  107458. data[0] = 0;
  107459. sigData.copy(data, 1);
  107460. der.writeBuffer(data, asn1.Ber.BitString);
  107461. der.endSequence();
  107462. return (der.buffer);
  107463. }
  107464. function writeTBSCert(cert, der) {
  107465. var sig = cert.signatures.x509;
  107466. assert.object(sig, 'x509 signature');
  107467. der.startSequence();
  107468. der.startSequence(Local(0));
  107469. der.writeInt(2);
  107470. der.endSequence();
  107471. der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer);
  107472. der.startSequence();
  107473. der.writeOID(SIGN_ALGS[sig.algo]);
  107474. if (sig.algo.match(/^rsa-/))
  107475. der.writeNull();
  107476. der.endSequence();
  107477. cert.issuer.toAsn1(der);
  107478. der.startSequence();
  107479. writeDate(der, cert.validFrom);
  107480. writeDate(der, cert.validUntil);
  107481. der.endSequence();
  107482. var subject = cert.subjects[0];
  107483. var altNames = cert.subjects.slice(1);
  107484. subject.toAsn1(der);
  107485. pkcs8.writePkcs8(der, cert.subjectKey);
  107486. if (sig.extras && sig.extras.issuerUniqueID) {
  107487. der.writeBuffer(sig.extras.issuerUniqueID, Local(1));
  107488. }
  107489. if (sig.extras && sig.extras.subjectUniqueID) {
  107490. der.writeBuffer(sig.extras.subjectUniqueID, Local(2));
  107491. }
  107492. if (altNames.length > 0 || subject.type === 'host' ||
  107493. (cert.purposes !== undefined && cert.purposes.length > 0) ||
  107494. (sig.extras && sig.extras.exts)) {
  107495. der.startSequence(Local(3));
  107496. der.startSequence();
  107497. var exts = [];
  107498. if (cert.purposes !== undefined && cert.purposes.length > 0) {
  107499. exts.push({
  107500. oid: EXTS.basicConstraints,
  107501. critical: true
  107502. });
  107503. exts.push({
  107504. oid: EXTS.keyUsage,
  107505. critical: true
  107506. });
  107507. exts.push({
  107508. oid: EXTS.extKeyUsage,
  107509. critical: true
  107510. });
  107511. }
  107512. exts.push({ oid: EXTS.altName });
  107513. if (sig.extras && sig.extras.exts)
  107514. exts = sig.extras.exts;
  107515. for (var i = 0; i < exts.length; ++i) {
  107516. der.startSequence();
  107517. der.writeOID(exts[i].oid);
  107518. if (exts[i].critical !== undefined)
  107519. der.writeBoolean(exts[i].critical);
  107520. if (exts[i].oid === EXTS.altName) {
  107521. der.startSequence(asn1.Ber.OctetString);
  107522. der.startSequence();
  107523. if (subject.type === 'host') {
  107524. der.writeString(subject.hostname,
  107525. Context(2));
  107526. }
  107527. for (var j = 0; j < altNames.length; ++j) {
  107528. if (altNames[j].type === 'host') {
  107529. der.writeString(
  107530. altNames[j].hostname,
  107531. ALTNAME.DNSName);
  107532. } else if (altNames[j].type ===
  107533. 'email') {
  107534. der.writeString(
  107535. altNames[j].email,
  107536. ALTNAME.RFC822Name);
  107537. } else {
  107538. /*
  107539. * Encode anything else as a
  107540. * DN style name for now.
  107541. */
  107542. der.startSequence(
  107543. ALTNAME.DirectoryName);
  107544. altNames[j].toAsn1(der);
  107545. der.endSequence();
  107546. }
  107547. }
  107548. der.endSequence();
  107549. der.endSequence();
  107550. } else if (exts[i].oid === EXTS.basicConstraints) {
  107551. der.startSequence(asn1.Ber.OctetString);
  107552. der.startSequence();
  107553. var ca = (cert.purposes.indexOf('ca') !== -1);
  107554. var pathLen = exts[i].pathLen;
  107555. der.writeBoolean(ca);
  107556. if (pathLen !== undefined)
  107557. der.writeInt(pathLen);
  107558. der.endSequence();
  107559. der.endSequence();
  107560. } else if (exts[i].oid === EXTS.extKeyUsage) {
  107561. der.startSequence(asn1.Ber.OctetString);
  107562. der.startSequence();
  107563. cert.purposes.forEach(function (purpose) {
  107564. if (purpose === 'ca')
  107565. return;
  107566. if (KEYUSEBITS.indexOf(purpose) !== -1)
  107567. return;
  107568. var oid = purpose;
  107569. if (EXTPURPOSE[purpose] !== undefined)
  107570. oid = EXTPURPOSE[purpose];
  107571. der.writeOID(oid);
  107572. });
  107573. der.endSequence();
  107574. der.endSequence();
  107575. } else if (exts[i].oid === EXTS.keyUsage) {
  107576. der.startSequence(asn1.Ber.OctetString);
  107577. /*
  107578. * If we parsed this certificate from a byte
  107579. * stream (i.e. we didn't generate it in sshpk)
  107580. * then we'll have a ".bits" property on the
  107581. * ext with the original raw byte contents.
  107582. *
  107583. * If we have this, use it here instead of
  107584. * regenerating it. This guarantees we output
  107585. * the same data we parsed, so signatures still
  107586. * validate.
  107587. */
  107588. if (exts[i].bits !== undefined) {
  107589. der.writeBuffer(exts[i].bits,
  107590. asn1.Ber.BitString);
  107591. } else {
  107592. var bits = writeBitField(cert.purposes,
  107593. KEYUSEBITS);
  107594. der.writeBuffer(bits,
  107595. asn1.Ber.BitString);
  107596. }
  107597. der.endSequence();
  107598. } else {
  107599. der.writeBuffer(exts[i].data,
  107600. asn1.Ber.OctetString);
  107601. }
  107602. der.endSequence();
  107603. }
  107604. der.endSequence();
  107605. der.endSequence();
  107606. }
  107607. der.endSequence();
  107608. }
  107609. /*
  107610. * Reads an ASN.1 BER bitfield out of the Buffer produced by doing
  107611. * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw
  107612. * contents of the BitString tag, which is a count of unused bits followed by
  107613. * the bits as a right-padded byte string.
  107614. *
  107615. * `bits` is the Buffer, `bitIndex` should contain an array of string names
  107616. * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec.
  107617. *
  107618. * Returns an array of Strings, the names of the bits that were set to 1.
  107619. */
  107620. function readBitField(bits, bitIndex) {
  107621. var bitLen = 8 * (bits.length - 1) - bits[0];
  107622. var setBits = {};
  107623. for (var i = 0; i < bitLen; ++i) {
  107624. var byteN = 1 + Math.floor(i / 8);
  107625. var bit = 7 - (i % 8);
  107626. var mask = 1 << bit;
  107627. var bitVal = ((bits[byteN] & mask) !== 0);
  107628. var name = bitIndex[i];
  107629. if (bitVal && typeof (name) === 'string') {
  107630. setBits[name] = true;
  107631. }
  107632. }
  107633. return (Object.keys(setBits));
  107634. }
  107635. /*
  107636. * `setBits` is an array of strings, containing the names for each bit that
  107637. * sould be set to 1. `bitIndex` is same as in `readBitField()`.
  107638. *
  107639. * Returns a Buffer, ready to be written out with `BerWriter#writeString()`.
  107640. */
  107641. function writeBitField(setBits, bitIndex) {
  107642. var bitLen = bitIndex.length;
  107643. var blen = Math.ceil(bitLen / 8);
  107644. var unused = blen * 8 - bitLen;
  107645. var bits = Buffer.alloc(1 + blen); // zero-filled
  107646. bits[0] = unused;
  107647. for (var i = 0; i < bitLen; ++i) {
  107648. var byteN = 1 + Math.floor(i / 8);
  107649. var bit = 7 - (i % 8);
  107650. var mask = 1 << bit;
  107651. var name = bitIndex[i];
  107652. if (name === undefined)
  107653. continue;
  107654. var bitVal = (setBits.indexOf(name) !== -1);
  107655. if (bitVal) {
  107656. bits[byteN] |= mask;
  107657. }
  107658. }
  107659. return (bits);
  107660. }
  107661. },{"../algs":572,"../certificate":573,"../identity":590,"../key":592,"../private-key":593,"../signature":594,"../utils":596,"./pem":581,"./pkcs8":583,"asn1":103,"assert-plus":104,"safer-buffer":562}],590:[function(require,module,exports){
  107662. // Copyright 2017 Joyent, Inc.
  107663. module.exports = Identity;
  107664. var assert = require('assert-plus');
  107665. var algs = require('./algs');
  107666. var crypto = require('crypto');
  107667. var Fingerprint = require('./fingerprint');
  107668. var Signature = require('./signature');
  107669. var errs = require('./errors');
  107670. var util = require('util');
  107671. var utils = require('./utils');
  107672. var asn1 = require('asn1');
  107673. var Buffer = require('safer-buffer').Buffer;
  107674. /*JSSTYLED*/
  107675. var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i;
  107676. var oids = {};
  107677. oids.cn = '2.5.4.3';
  107678. oids.o = '2.5.4.10';
  107679. oids.ou = '2.5.4.11';
  107680. oids.l = '2.5.4.7';
  107681. oids.s = '2.5.4.8';
  107682. oids.c = '2.5.4.6';
  107683. oids.sn = '2.5.4.4';
  107684. oids.postalCode = '2.5.4.17';
  107685. oids.serialNumber = '2.5.4.5';
  107686. oids.street = '2.5.4.9';
  107687. oids.x500UniqueIdentifier = '2.5.4.45';
  107688. oids.role = '2.5.4.72';
  107689. oids.telephoneNumber = '2.5.4.20';
  107690. oids.description = '2.5.4.13';
  107691. oids.dc = '0.9.2342.19200300.100.1.25';
  107692. oids.uid = '0.9.2342.19200300.100.1.1';
  107693. oids.mail = '0.9.2342.19200300.100.1.3';
  107694. oids.title = '2.5.4.12';
  107695. oids.gn = '2.5.4.42';
  107696. oids.initials = '2.5.4.43';
  107697. oids.pseudonym = '2.5.4.65';
  107698. oids.emailAddress = '1.2.840.113549.1.9.1';
  107699. var unoids = {};
  107700. Object.keys(oids).forEach(function (k) {
  107701. unoids[oids[k]] = k;
  107702. });
  107703. function Identity(opts) {
  107704. var self = this;
  107705. assert.object(opts, 'options');
  107706. assert.arrayOfObject(opts.components, 'options.components');
  107707. this.components = opts.components;
  107708. this.componentLookup = {};
  107709. this.components.forEach(function (c) {
  107710. if (c.name && !c.oid)
  107711. c.oid = oids[c.name];
  107712. if (c.oid && !c.name)
  107713. c.name = unoids[c.oid];
  107714. if (self.componentLookup[c.name] === undefined)
  107715. self.componentLookup[c.name] = [];
  107716. self.componentLookup[c.name].push(c);
  107717. });
  107718. if (this.componentLookup.cn && this.componentLookup.cn.length > 0) {
  107719. this.cn = this.componentLookup.cn[0].value;
  107720. }
  107721. assert.optionalString(opts.type, 'options.type');
  107722. if (opts.type === undefined) {
  107723. if (this.components.length === 1 &&
  107724. this.componentLookup.cn &&
  107725. this.componentLookup.cn.length === 1 &&
  107726. this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
  107727. this.type = 'host';
  107728. this.hostname = this.componentLookup.cn[0].value;
  107729. } else if (this.componentLookup.dc &&
  107730. this.components.length === this.componentLookup.dc.length) {
  107731. this.type = 'host';
  107732. this.hostname = this.componentLookup.dc.map(
  107733. function (c) {
  107734. return (c.value);
  107735. }).join('.');
  107736. } else if (this.componentLookup.uid &&
  107737. this.components.length ===
  107738. this.componentLookup.uid.length) {
  107739. this.type = 'user';
  107740. this.uid = this.componentLookup.uid[0].value;
  107741. } else if (this.componentLookup.cn &&
  107742. this.componentLookup.cn.length === 1 &&
  107743. this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
  107744. this.type = 'host';
  107745. this.hostname = this.componentLookup.cn[0].value;
  107746. } else if (this.componentLookup.uid &&
  107747. this.componentLookup.uid.length === 1) {
  107748. this.type = 'user';
  107749. this.uid = this.componentLookup.uid[0].value;
  107750. } else if (this.componentLookup.mail &&
  107751. this.componentLookup.mail.length === 1) {
  107752. this.type = 'email';
  107753. this.email = this.componentLookup.mail[0].value;
  107754. } else if (this.componentLookup.cn &&
  107755. this.componentLookup.cn.length === 1) {
  107756. this.type = 'user';
  107757. this.uid = this.componentLookup.cn[0].value;
  107758. } else {
  107759. this.type = 'unknown';
  107760. }
  107761. } else {
  107762. this.type = opts.type;
  107763. if (this.type === 'host')
  107764. this.hostname = opts.hostname;
  107765. else if (this.type === 'user')
  107766. this.uid = opts.uid;
  107767. else if (this.type === 'email')
  107768. this.email = opts.email;
  107769. else
  107770. throw (new Error('Unknown type ' + this.type));
  107771. }
  107772. }
  107773. Identity.prototype.toString = function () {
  107774. return (this.components.map(function (c) {
  107775. var n = c.name.toUpperCase();
  107776. /*JSSTYLED*/
  107777. n = n.replace(/=/g, '\\=');
  107778. var v = c.value;
  107779. /*JSSTYLED*/
  107780. v = v.replace(/,/g, '\\,');
  107781. return (n + '=' + v);
  107782. }).join(', '));
  107783. };
  107784. Identity.prototype.get = function (name, asArray) {
  107785. assert.string(name, 'name');
  107786. var arr = this.componentLookup[name];
  107787. if (arr === undefined || arr.length === 0)
  107788. return (undefined);
  107789. if (!asArray && arr.length > 1)
  107790. throw (new Error('Multiple values for attribute ' + name));
  107791. if (!asArray)
  107792. return (arr[0].value);
  107793. return (arr.map(function (c) {
  107794. return (c.value);
  107795. }));
  107796. };
  107797. Identity.prototype.toArray = function (idx) {
  107798. return (this.components.map(function (c) {
  107799. return ({
  107800. name: c.name,
  107801. value: c.value
  107802. });
  107803. }));
  107804. };
  107805. /*
  107806. * These are from X.680 -- PrintableString allowed chars are in section 37.4
  107807. * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to
  107808. * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006
  107809. * (the basic ASCII character set).
  107810. */
  107811. /* JSSTYLED */
  107812. var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/;
  107813. /* JSSTYLED */
  107814. var NOT_IA5 = /[^\x00-\x7f]/;
  107815. Identity.prototype.toAsn1 = function (der, tag) {
  107816. der.startSequence(tag);
  107817. this.components.forEach(function (c) {
  107818. der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set);
  107819. der.startSequence();
  107820. der.writeOID(c.oid);
  107821. /*
  107822. * If we fit in a PrintableString, use that. Otherwise use an
  107823. * IA5String or UTF8String.
  107824. *
  107825. * If this identity was parsed from a DN, use the ASN.1 types
  107826. * from the original representation (otherwise this might not
  107827. * be a full match for the original in some validators).
  107828. */
  107829. if (c.asn1type === asn1.Ber.Utf8String ||
  107830. c.value.match(NOT_IA5)) {
  107831. var v = Buffer.from(c.value, 'utf8');
  107832. der.writeBuffer(v, asn1.Ber.Utf8String);
  107833. } else if (c.asn1type === asn1.Ber.IA5String ||
  107834. c.value.match(NOT_PRINTABLE)) {
  107835. der.writeString(c.value, asn1.Ber.IA5String);
  107836. } else {
  107837. var type = asn1.Ber.PrintableString;
  107838. if (c.asn1type !== undefined)
  107839. type = c.asn1type;
  107840. der.writeString(c.value, type);
  107841. }
  107842. der.endSequence();
  107843. der.endSequence();
  107844. });
  107845. der.endSequence();
  107846. };
  107847. function globMatch(a, b) {
  107848. if (a === '**' || b === '**')
  107849. return (true);
  107850. var aParts = a.split('.');
  107851. var bParts = b.split('.');
  107852. if (aParts.length !== bParts.length)
  107853. return (false);
  107854. for (var i = 0; i < aParts.length; ++i) {
  107855. if (aParts[i] === '*' || bParts[i] === '*')
  107856. continue;
  107857. if (aParts[i] !== bParts[i])
  107858. return (false);
  107859. }
  107860. return (true);
  107861. }
  107862. Identity.prototype.equals = function (other) {
  107863. if (!Identity.isIdentity(other, [1, 0]))
  107864. return (false);
  107865. if (other.components.length !== this.components.length)
  107866. return (false);
  107867. for (var i = 0; i < this.components.length; ++i) {
  107868. if (this.components[i].oid !== other.components[i].oid)
  107869. return (false);
  107870. if (!globMatch(this.components[i].value,
  107871. other.components[i].value)) {
  107872. return (false);
  107873. }
  107874. }
  107875. return (true);
  107876. };
  107877. Identity.forHost = function (hostname) {
  107878. assert.string(hostname, 'hostname');
  107879. return (new Identity({
  107880. type: 'host',
  107881. hostname: hostname,
  107882. components: [ { name: 'cn', value: hostname } ]
  107883. }));
  107884. };
  107885. Identity.forUser = function (uid) {
  107886. assert.string(uid, 'uid');
  107887. return (new Identity({
  107888. type: 'user',
  107889. uid: uid,
  107890. components: [ { name: 'uid', value: uid } ]
  107891. }));
  107892. };
  107893. Identity.forEmail = function (email) {
  107894. assert.string(email, 'email');
  107895. return (new Identity({
  107896. type: 'email',
  107897. email: email,
  107898. components: [ { name: 'mail', value: email } ]
  107899. }));
  107900. };
  107901. Identity.parseDN = function (dn) {
  107902. assert.string(dn, 'dn');
  107903. var parts = [''];
  107904. var idx = 0;
  107905. var rem = dn;
  107906. while (rem.length > 0) {
  107907. var m;
  107908. /*JSSTYLED*/
  107909. if ((m = /^,/.exec(rem)) !== null) {
  107910. parts[++idx] = '';
  107911. rem = rem.slice(m[0].length);
  107912. /*JSSTYLED*/
  107913. } else if ((m = /^\\,/.exec(rem)) !== null) {
  107914. parts[idx] += ',';
  107915. rem = rem.slice(m[0].length);
  107916. /*JSSTYLED*/
  107917. } else if ((m = /^\\./.exec(rem)) !== null) {
  107918. parts[idx] += m[0];
  107919. rem = rem.slice(m[0].length);
  107920. /*JSSTYLED*/
  107921. } else if ((m = /^[^\\,]+/.exec(rem)) !== null) {
  107922. parts[idx] += m[0];
  107923. rem = rem.slice(m[0].length);
  107924. } else {
  107925. throw (new Error('Failed to parse DN'));
  107926. }
  107927. }
  107928. var cmps = parts.map(function (c) {
  107929. c = c.trim();
  107930. var eqPos = c.indexOf('=');
  107931. while (eqPos > 0 && c.charAt(eqPos - 1) === '\\')
  107932. eqPos = c.indexOf('=', eqPos + 1);
  107933. if (eqPos === -1) {
  107934. throw (new Error('Failed to parse DN'));
  107935. }
  107936. /*JSSTYLED*/
  107937. var name = c.slice(0, eqPos).toLowerCase().replace(/\\=/g, '=');
  107938. var value = c.slice(eqPos + 1);
  107939. return ({ name: name, value: value });
  107940. });
  107941. return (new Identity({ components: cmps }));
  107942. };
  107943. Identity.fromArray = function (components) {
  107944. assert.arrayOfObject(components, 'components');
  107945. components.forEach(function (cmp) {
  107946. assert.object(cmp, 'component');
  107947. assert.string(cmp.name, 'component.name');
  107948. if (!Buffer.isBuffer(cmp.value) &&
  107949. !(typeof (cmp.value) === 'string')) {
  107950. throw (new Error('Invalid component value'));
  107951. }
  107952. });
  107953. return (new Identity({ components: components }));
  107954. };
  107955. Identity.parseAsn1 = function (der, top) {
  107956. var components = [];
  107957. der.readSequence(top);
  107958. var end = der.offset + der.length;
  107959. while (der.offset < end) {
  107960. der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set);
  107961. var after = der.offset + der.length;
  107962. der.readSequence();
  107963. var oid = der.readOID();
  107964. var type = der.peek();
  107965. var value;
  107966. switch (type) {
  107967. case asn1.Ber.PrintableString:
  107968. case asn1.Ber.IA5String:
  107969. case asn1.Ber.OctetString:
  107970. case asn1.Ber.T61String:
  107971. value = der.readString(type);
  107972. break;
  107973. case asn1.Ber.Utf8String:
  107974. value = der.readString(type, true);
  107975. value = value.toString('utf8');
  107976. break;
  107977. case asn1.Ber.CharacterString:
  107978. case asn1.Ber.BMPString:
  107979. value = der.readString(type, true);
  107980. value = value.toString('utf16le');
  107981. break;
  107982. default:
  107983. throw (new Error('Unknown asn1 type ' + type));
  107984. }
  107985. components.push({ oid: oid, asn1type: type, value: value });
  107986. der._offset = after;
  107987. }
  107988. der._offset = end;
  107989. return (new Identity({
  107990. components: components
  107991. }));
  107992. };
  107993. Identity.isIdentity = function (obj, ver) {
  107994. return (utils.isCompatible(obj, Identity, ver));
  107995. };
  107996. /*
  107997. * API versions for Identity:
  107998. * [1,0] -- initial ver
  107999. */
  108000. Identity.prototype._sshpkApiVersion = [1, 0];
  108001. Identity._oldVersionDetect = function (obj) {
  108002. return ([1, 0]);
  108003. };
  108004. },{"./algs":572,"./errors":576,"./fingerprint":577,"./signature":594,"./utils":596,"asn1":103,"assert-plus":104,"crypto":208,"safer-buffer":562,"util":658}],591:[function(require,module,exports){
  108005. // Copyright 2015 Joyent, Inc.
  108006. var Key = require('./key');
  108007. var Fingerprint = require('./fingerprint');
  108008. var Signature = require('./signature');
  108009. var PrivateKey = require('./private-key');
  108010. var Certificate = require('./certificate');
  108011. var Identity = require('./identity');
  108012. var errs = require('./errors');
  108013. module.exports = {
  108014. /* top-level classes */
  108015. Key: Key,
  108016. parseKey: Key.parse,
  108017. Fingerprint: Fingerprint,
  108018. parseFingerprint: Fingerprint.parse,
  108019. Signature: Signature,
  108020. parseSignature: Signature.parse,
  108021. PrivateKey: PrivateKey,
  108022. parsePrivateKey: PrivateKey.parse,
  108023. generatePrivateKey: PrivateKey.generate,
  108024. Certificate: Certificate,
  108025. parseCertificate: Certificate.parse,
  108026. createSelfSignedCertificate: Certificate.createSelfSigned,
  108027. createCertificate: Certificate.create,
  108028. Identity: Identity,
  108029. identityFromDN: Identity.parseDN,
  108030. identityForHost: Identity.forHost,
  108031. identityForUser: Identity.forUser,
  108032. identityForEmail: Identity.forEmail,
  108033. identityFromArray: Identity.fromArray,
  108034. /* errors */
  108035. FingerprintFormatError: errs.FingerprintFormatError,
  108036. InvalidAlgorithmError: errs.InvalidAlgorithmError,
  108037. KeyParseError: errs.KeyParseError,
  108038. SignatureParseError: errs.SignatureParseError,
  108039. KeyEncryptedError: errs.KeyEncryptedError,
  108040. CertificateParseError: errs.CertificateParseError
  108041. };
  108042. },{"./certificate":573,"./errors":576,"./fingerprint":577,"./identity":590,"./key":592,"./private-key":593,"./signature":594}],592:[function(require,module,exports){
  108043. (function (Buffer){(function (){
  108044. // Copyright 2018 Joyent, Inc.
  108045. module.exports = Key;
  108046. var assert = require('assert-plus');
  108047. var algs = require('./algs');
  108048. var crypto = require('crypto');
  108049. var Fingerprint = require('./fingerprint');
  108050. var Signature = require('./signature');
  108051. var DiffieHellman = require('./dhe').DiffieHellman;
  108052. var errs = require('./errors');
  108053. var utils = require('./utils');
  108054. var PrivateKey = require('./private-key');
  108055. var edCompat;
  108056. try {
  108057. edCompat = require('./ed-compat');
  108058. } catch (e) {
  108059. /* Just continue through, and bail out if we try to use it. */
  108060. }
  108061. var InvalidAlgorithmError = errs.InvalidAlgorithmError;
  108062. var KeyParseError = errs.KeyParseError;
  108063. var formats = {};
  108064. formats['auto'] = require('./formats/auto');
  108065. formats['pem'] = require('./formats/pem');
  108066. formats['pkcs1'] = require('./formats/pkcs1');
  108067. formats['pkcs8'] = require('./formats/pkcs8');
  108068. formats['rfc4253'] = require('./formats/rfc4253');
  108069. formats['ssh'] = require('./formats/ssh');
  108070. formats['ssh-private'] = require('./formats/ssh-private');
  108071. formats['openssh'] = formats['ssh-private'];
  108072. formats['dnssec'] = require('./formats/dnssec');
  108073. formats['putty'] = require('./formats/putty');
  108074. formats['ppk'] = formats['putty'];
  108075. function Key(opts) {
  108076. assert.object(opts, 'options');
  108077. assert.arrayOfObject(opts.parts, 'options.parts');
  108078. assert.string(opts.type, 'options.type');
  108079. assert.optionalString(opts.comment, 'options.comment');
  108080. var algInfo = algs.info[opts.type];
  108081. if (typeof (algInfo) !== 'object')
  108082. throw (new InvalidAlgorithmError(opts.type));
  108083. var partLookup = {};
  108084. for (var i = 0; i < opts.parts.length; ++i) {
  108085. var part = opts.parts[i];
  108086. partLookup[part.name] = part;
  108087. }
  108088. this.type = opts.type;
  108089. this.parts = opts.parts;
  108090. this.part = partLookup;
  108091. this.comment = undefined;
  108092. this.source = opts.source;
  108093. /* for speeding up hashing/fingerprint operations */
  108094. this._rfc4253Cache = opts._rfc4253Cache;
  108095. this._hashCache = {};
  108096. var sz;
  108097. this.curve = undefined;
  108098. if (this.type === 'ecdsa') {
  108099. var curve = this.part.curve.data.toString();
  108100. this.curve = curve;
  108101. sz = algs.curves[curve].size;
  108102. } else if (this.type === 'ed25519' || this.type === 'curve25519') {
  108103. sz = 256;
  108104. this.curve = 'curve25519';
  108105. } else {
  108106. var szPart = this.part[algInfo.sizePart];
  108107. sz = szPart.data.length;
  108108. sz = sz * 8 - utils.countZeros(szPart.data);
  108109. }
  108110. this.size = sz;
  108111. }
  108112. Key.formats = formats;
  108113. Key.prototype.toBuffer = function (format, options) {
  108114. if (format === undefined)
  108115. format = 'ssh';
  108116. assert.string(format, 'format');
  108117. assert.object(formats[format], 'formats[format]');
  108118. assert.optionalObject(options, 'options');
  108119. if (format === 'rfc4253') {
  108120. if (this._rfc4253Cache === undefined)
  108121. this._rfc4253Cache = formats['rfc4253'].write(this);
  108122. return (this._rfc4253Cache);
  108123. }
  108124. return (formats[format].write(this, options));
  108125. };
  108126. Key.prototype.toString = function (format, options) {
  108127. return (this.toBuffer(format, options).toString());
  108128. };
  108129. Key.prototype.hash = function (algo, type) {
  108130. assert.string(algo, 'algorithm');
  108131. assert.optionalString(type, 'type');
  108132. if (type === undefined)
  108133. type = 'ssh';
  108134. algo = algo.toLowerCase();
  108135. if (algs.hashAlgs[algo] === undefined)
  108136. throw (new InvalidAlgorithmError(algo));
  108137. var cacheKey = algo + '||' + type;
  108138. if (this._hashCache[cacheKey])
  108139. return (this._hashCache[cacheKey]);
  108140. var buf;
  108141. if (type === 'ssh') {
  108142. buf = this.toBuffer('rfc4253');
  108143. } else if (type === 'spki') {
  108144. buf = formats.pkcs8.pkcs8ToBuffer(this);
  108145. } else {
  108146. throw (new Error('Hash type ' + type + ' not supported'));
  108147. }
  108148. var hash = crypto.createHash(algo).update(buf).digest();
  108149. this._hashCache[cacheKey] = hash;
  108150. return (hash);
  108151. };
  108152. Key.prototype.fingerprint = function (algo, type) {
  108153. if (algo === undefined)
  108154. algo = 'sha256';
  108155. if (type === undefined)
  108156. type = 'ssh';
  108157. assert.string(algo, 'algorithm');
  108158. assert.string(type, 'type');
  108159. var opts = {
  108160. type: 'key',
  108161. hash: this.hash(algo, type),
  108162. algorithm: algo,
  108163. hashType: type
  108164. };
  108165. return (new Fingerprint(opts));
  108166. };
  108167. Key.prototype.defaultHashAlgorithm = function () {
  108168. var hashAlgo = 'sha1';
  108169. if (this.type === 'rsa')
  108170. hashAlgo = 'sha256';
  108171. if (this.type === 'dsa' && this.size > 1024)
  108172. hashAlgo = 'sha256';
  108173. if (this.type === 'ed25519')
  108174. hashAlgo = 'sha512';
  108175. if (this.type === 'ecdsa') {
  108176. if (this.size <= 256)
  108177. hashAlgo = 'sha256';
  108178. else if (this.size <= 384)
  108179. hashAlgo = 'sha384';
  108180. else
  108181. hashAlgo = 'sha512';
  108182. }
  108183. return (hashAlgo);
  108184. };
  108185. Key.prototype.createVerify = function (hashAlgo) {
  108186. if (hashAlgo === undefined)
  108187. hashAlgo = this.defaultHashAlgorithm();
  108188. assert.string(hashAlgo, 'hash algorithm');
  108189. /* ED25519 is not supported by OpenSSL, use a javascript impl. */
  108190. if (this.type === 'ed25519' && edCompat !== undefined)
  108191. return (new edCompat.Verifier(this, hashAlgo));
  108192. if (this.type === 'curve25519')
  108193. throw (new Error('Curve25519 keys are not suitable for ' +
  108194. 'signing or verification'));
  108195. var v, nm, err;
  108196. try {
  108197. nm = hashAlgo.toUpperCase();
  108198. v = crypto.createVerify(nm);
  108199. } catch (e) {
  108200. err = e;
  108201. }
  108202. if (v === undefined || (err instanceof Error &&
  108203. err.message.match(/Unknown message digest/))) {
  108204. nm = 'RSA-';
  108205. nm += hashAlgo.toUpperCase();
  108206. v = crypto.createVerify(nm);
  108207. }
  108208. assert.ok(v, 'failed to create verifier');
  108209. var oldVerify = v.verify.bind(v);
  108210. var key = this.toBuffer('pkcs8');
  108211. var curve = this.curve;
  108212. var self = this;
  108213. v.verify = function (signature, fmt) {
  108214. if (Signature.isSignature(signature, [2, 0])) {
  108215. if (signature.type !== self.type)
  108216. return (false);
  108217. if (signature.hashAlgorithm &&
  108218. signature.hashAlgorithm !== hashAlgo)
  108219. return (false);
  108220. if (signature.curve && self.type === 'ecdsa' &&
  108221. signature.curve !== curve)
  108222. return (false);
  108223. return (oldVerify(key, signature.toBuffer('asn1')));
  108224. } else if (typeof (signature) === 'string' ||
  108225. Buffer.isBuffer(signature)) {
  108226. return (oldVerify(key, signature, fmt));
  108227. /*
  108228. * Avoid doing this on valid arguments, walking the prototype
  108229. * chain can be quite slow.
  108230. */
  108231. } else if (Signature.isSignature(signature, [1, 0])) {
  108232. throw (new Error('signature was created by too old ' +
  108233. 'a version of sshpk and cannot be verified'));
  108234. } else {
  108235. throw (new TypeError('signature must be a string, ' +
  108236. 'Buffer, or Signature object'));
  108237. }
  108238. };
  108239. return (v);
  108240. };
  108241. Key.prototype.createDiffieHellman = function () {
  108242. if (this.type === 'rsa')
  108243. throw (new Error('RSA keys do not support Diffie-Hellman'));
  108244. return (new DiffieHellman(this));
  108245. };
  108246. Key.prototype.createDH = Key.prototype.createDiffieHellman;
  108247. Key.parse = function (data, format, options) {
  108248. if (typeof (data) !== 'string')
  108249. assert.buffer(data, 'data');
  108250. if (format === undefined)
  108251. format = 'auto';
  108252. assert.string(format, 'format');
  108253. if (typeof (options) === 'string')
  108254. options = { filename: options };
  108255. assert.optionalObject(options, 'options');
  108256. if (options === undefined)
  108257. options = {};
  108258. assert.optionalString(options.filename, 'options.filename');
  108259. if (options.filename === undefined)
  108260. options.filename = '(unnamed)';
  108261. assert.object(formats[format], 'formats[format]');
  108262. try {
  108263. var k = formats[format].read(data, options);
  108264. if (k instanceof PrivateKey)
  108265. k = k.toPublic();
  108266. if (!k.comment)
  108267. k.comment = options.filename;
  108268. return (k);
  108269. } catch (e) {
  108270. if (e.name === 'KeyEncryptedError')
  108271. throw (e);
  108272. throw (new KeyParseError(options.filename, format, e));
  108273. }
  108274. };
  108275. Key.isKey = function (obj, ver) {
  108276. return (utils.isCompatible(obj, Key, ver));
  108277. };
  108278. /*
  108279. * API versions for Key:
  108280. * [1,0] -- initial ver, may take Signature for createVerify or may not
  108281. * [1,1] -- added pkcs1, pkcs8 formats
  108282. * [1,2] -- added auto, ssh-private, openssh formats
  108283. * [1,3] -- added defaultHashAlgorithm
  108284. * [1,4] -- added ed support, createDH
  108285. * [1,5] -- first explicitly tagged version
  108286. * [1,6] -- changed ed25519 part names
  108287. * [1,7] -- spki hash types
  108288. */
  108289. Key.prototype._sshpkApiVersion = [1, 7];
  108290. Key._oldVersionDetect = function (obj) {
  108291. assert.func(obj.toBuffer);
  108292. assert.func(obj.fingerprint);
  108293. if (obj.createDH)
  108294. return ([1, 4]);
  108295. if (obj.defaultHashAlgorithm)
  108296. return ([1, 3]);
  108297. if (obj.formats['auto'])
  108298. return ([1, 2]);
  108299. if (obj.formats['pkcs1'])
  108300. return ([1, 1]);
  108301. return ([1, 0]);
  108302. };
  108303. }).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  108304. },{"../../is-buffer/index.js":322,"./algs":572,"./dhe":574,"./ed-compat":575,"./errors":576,"./fingerprint":577,"./formats/auto":578,"./formats/dnssec":579,"./formats/pem":581,"./formats/pkcs1":582,"./formats/pkcs8":583,"./formats/putty":584,"./formats/rfc4253":585,"./formats/ssh":587,"./formats/ssh-private":586,"./private-key":593,"./signature":594,"./utils":596,"assert-plus":104,"crypto":208}],593:[function(require,module,exports){
  108305. // Copyright 2017 Joyent, Inc.
  108306. module.exports = PrivateKey;
  108307. var assert = require('assert-plus');
  108308. var Buffer = require('safer-buffer').Buffer;
  108309. var algs = require('./algs');
  108310. var crypto = require('crypto');
  108311. var Fingerprint = require('./fingerprint');
  108312. var Signature = require('./signature');
  108313. var errs = require('./errors');
  108314. var util = require('util');
  108315. var utils = require('./utils');
  108316. var dhe = require('./dhe');
  108317. var generateECDSA = dhe.generateECDSA;
  108318. var generateED25519 = dhe.generateED25519;
  108319. var edCompat = require('./ed-compat');
  108320. var nacl = require('tweetnacl');
  108321. var Key = require('./key');
  108322. var InvalidAlgorithmError = errs.InvalidAlgorithmError;
  108323. var KeyParseError = errs.KeyParseError;
  108324. var KeyEncryptedError = errs.KeyEncryptedError;
  108325. var formats = {};
  108326. formats['auto'] = require('./formats/auto');
  108327. formats['pem'] = require('./formats/pem');
  108328. formats['pkcs1'] = require('./formats/pkcs1');
  108329. formats['pkcs8'] = require('./formats/pkcs8');
  108330. formats['rfc4253'] = require('./formats/rfc4253');
  108331. formats['ssh-private'] = require('./formats/ssh-private');
  108332. formats['openssh'] = formats['ssh-private'];
  108333. formats['ssh'] = formats['ssh-private'];
  108334. formats['dnssec'] = require('./formats/dnssec');
  108335. function PrivateKey(opts) {
  108336. assert.object(opts, 'options');
  108337. Key.call(this, opts);
  108338. this._pubCache = undefined;
  108339. }
  108340. util.inherits(PrivateKey, Key);
  108341. PrivateKey.formats = formats;
  108342. PrivateKey.prototype.toBuffer = function (format, options) {
  108343. if (format === undefined)
  108344. format = 'pkcs1';
  108345. assert.string(format, 'format');
  108346. assert.object(formats[format], 'formats[format]');
  108347. assert.optionalObject(options, 'options');
  108348. return (formats[format].write(this, options));
  108349. };
  108350. PrivateKey.prototype.hash = function (algo, type) {
  108351. return (this.toPublic().hash(algo, type));
  108352. };
  108353. PrivateKey.prototype.fingerprint = function (algo, type) {
  108354. return (this.toPublic().fingerprint(algo, type));
  108355. };
  108356. PrivateKey.prototype.toPublic = function () {
  108357. if (this._pubCache)
  108358. return (this._pubCache);
  108359. var algInfo = algs.info[this.type];
  108360. var pubParts = [];
  108361. for (var i = 0; i < algInfo.parts.length; ++i) {
  108362. var p = algInfo.parts[i];
  108363. pubParts.push(this.part[p]);
  108364. }
  108365. this._pubCache = new Key({
  108366. type: this.type,
  108367. source: this,
  108368. parts: pubParts
  108369. });
  108370. if (this.comment)
  108371. this._pubCache.comment = this.comment;
  108372. return (this._pubCache);
  108373. };
  108374. PrivateKey.prototype.derive = function (newType) {
  108375. assert.string(newType, 'type');
  108376. var priv, pub, pair;
  108377. if (this.type === 'ed25519' && newType === 'curve25519') {
  108378. priv = this.part.k.data;
  108379. if (priv[0] === 0x00)
  108380. priv = priv.slice(1);
  108381. pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv));
  108382. pub = Buffer.from(pair.publicKey);
  108383. return (new PrivateKey({
  108384. type: 'curve25519',
  108385. parts: [
  108386. { name: 'A', data: utils.mpNormalize(pub) },
  108387. { name: 'k', data: utils.mpNormalize(priv) }
  108388. ]
  108389. }));
  108390. } else if (this.type === 'curve25519' && newType === 'ed25519') {
  108391. priv = this.part.k.data;
  108392. if (priv[0] === 0x00)
  108393. priv = priv.slice(1);
  108394. pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv));
  108395. pub = Buffer.from(pair.publicKey);
  108396. return (new PrivateKey({
  108397. type: 'ed25519',
  108398. parts: [
  108399. { name: 'A', data: utils.mpNormalize(pub) },
  108400. { name: 'k', data: utils.mpNormalize(priv) }
  108401. ]
  108402. }));
  108403. }
  108404. throw (new Error('Key derivation not supported from ' + this.type +
  108405. ' to ' + newType));
  108406. };
  108407. PrivateKey.prototype.createVerify = function (hashAlgo) {
  108408. return (this.toPublic().createVerify(hashAlgo));
  108409. };
  108410. PrivateKey.prototype.createSign = function (hashAlgo) {
  108411. if (hashAlgo === undefined)
  108412. hashAlgo = this.defaultHashAlgorithm();
  108413. assert.string(hashAlgo, 'hash algorithm');
  108414. /* ED25519 is not supported by OpenSSL, use a javascript impl. */
  108415. if (this.type === 'ed25519' && edCompat !== undefined)
  108416. return (new edCompat.Signer(this, hashAlgo));
  108417. if (this.type === 'curve25519')
  108418. throw (new Error('Curve25519 keys are not suitable for ' +
  108419. 'signing or verification'));
  108420. var v, nm, err;
  108421. try {
  108422. nm = hashAlgo.toUpperCase();
  108423. v = crypto.createSign(nm);
  108424. } catch (e) {
  108425. err = e;
  108426. }
  108427. if (v === undefined || (err instanceof Error &&
  108428. err.message.match(/Unknown message digest/))) {
  108429. nm = 'RSA-';
  108430. nm += hashAlgo.toUpperCase();
  108431. v = crypto.createSign(nm);
  108432. }
  108433. assert.ok(v, 'failed to create verifier');
  108434. var oldSign = v.sign.bind(v);
  108435. var key = this.toBuffer('pkcs1');
  108436. var type = this.type;
  108437. var curve = this.curve;
  108438. v.sign = function () {
  108439. var sig = oldSign(key);
  108440. if (typeof (sig) === 'string')
  108441. sig = Buffer.from(sig, 'binary');
  108442. sig = Signature.parse(sig, type, 'asn1');
  108443. sig.hashAlgorithm = hashAlgo;
  108444. sig.curve = curve;
  108445. return (sig);
  108446. };
  108447. return (v);
  108448. };
  108449. PrivateKey.parse = function (data, format, options) {
  108450. if (typeof (data) !== 'string')
  108451. assert.buffer(data, 'data');
  108452. if (format === undefined)
  108453. format = 'auto';
  108454. assert.string(format, 'format');
  108455. if (typeof (options) === 'string')
  108456. options = { filename: options };
  108457. assert.optionalObject(options, 'options');
  108458. if (options === undefined)
  108459. options = {};
  108460. assert.optionalString(options.filename, 'options.filename');
  108461. if (options.filename === undefined)
  108462. options.filename = '(unnamed)';
  108463. assert.object(formats[format], 'formats[format]');
  108464. try {
  108465. var k = formats[format].read(data, options);
  108466. assert.ok(k instanceof PrivateKey, 'key is not a private key');
  108467. if (!k.comment)
  108468. k.comment = options.filename;
  108469. return (k);
  108470. } catch (e) {
  108471. if (e.name === 'KeyEncryptedError')
  108472. throw (e);
  108473. throw (new KeyParseError(options.filename, format, e));
  108474. }
  108475. };
  108476. PrivateKey.isPrivateKey = function (obj, ver) {
  108477. return (utils.isCompatible(obj, PrivateKey, ver));
  108478. };
  108479. PrivateKey.generate = function (type, options) {
  108480. if (options === undefined)
  108481. options = {};
  108482. assert.object(options, 'options');
  108483. switch (type) {
  108484. case 'ecdsa':
  108485. if (options.curve === undefined)
  108486. options.curve = 'nistp256';
  108487. assert.string(options.curve, 'options.curve');
  108488. return (generateECDSA(options.curve));
  108489. case 'ed25519':
  108490. return (generateED25519());
  108491. default:
  108492. throw (new Error('Key generation not supported with key ' +
  108493. 'type "' + type + '"'));
  108494. }
  108495. };
  108496. /*
  108497. * API versions for PrivateKey:
  108498. * [1,0] -- initial ver
  108499. * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats
  108500. * [1,2] -- added defaultHashAlgorithm
  108501. * [1,3] -- added derive, ed, createDH
  108502. * [1,4] -- first tagged version
  108503. * [1,5] -- changed ed25519 part names and format
  108504. * [1,6] -- type arguments for hash() and fingerprint()
  108505. */
  108506. PrivateKey.prototype._sshpkApiVersion = [1, 6];
  108507. PrivateKey._oldVersionDetect = function (obj) {
  108508. assert.func(obj.toPublic);
  108509. assert.func(obj.createSign);
  108510. if (obj.derive)
  108511. return ([1, 3]);
  108512. if (obj.defaultHashAlgorithm)
  108513. return ([1, 2]);
  108514. if (obj.formats['auto'])
  108515. return ([1, 1]);
  108516. return ([1, 0]);
  108517. };
  108518. },{"./algs":572,"./dhe":574,"./ed-compat":575,"./errors":576,"./fingerprint":577,"./formats/auto":578,"./formats/dnssec":579,"./formats/pem":581,"./formats/pkcs1":582,"./formats/pkcs8":583,"./formats/rfc4253":585,"./formats/ssh-private":586,"./key":592,"./signature":594,"./utils":596,"assert-plus":104,"crypto":208,"safer-buffer":562,"tweetnacl":650,"util":658}],594:[function(require,module,exports){
  108519. // Copyright 2015 Joyent, Inc.
  108520. module.exports = Signature;
  108521. var assert = require('assert-plus');
  108522. var Buffer = require('safer-buffer').Buffer;
  108523. var algs = require('./algs');
  108524. var crypto = require('crypto');
  108525. var errs = require('./errors');
  108526. var utils = require('./utils');
  108527. var asn1 = require('asn1');
  108528. var SSHBuffer = require('./ssh-buffer');
  108529. var InvalidAlgorithmError = errs.InvalidAlgorithmError;
  108530. var SignatureParseError = errs.SignatureParseError;
  108531. function Signature(opts) {
  108532. assert.object(opts, 'options');
  108533. assert.arrayOfObject(opts.parts, 'options.parts');
  108534. assert.string(opts.type, 'options.type');
  108535. var partLookup = {};
  108536. for (var i = 0; i < opts.parts.length; ++i) {
  108537. var part = opts.parts[i];
  108538. partLookup[part.name] = part;
  108539. }
  108540. this.type = opts.type;
  108541. this.hashAlgorithm = opts.hashAlgo;
  108542. this.curve = opts.curve;
  108543. this.parts = opts.parts;
  108544. this.part = partLookup;
  108545. }
  108546. Signature.prototype.toBuffer = function (format) {
  108547. if (format === undefined)
  108548. format = 'asn1';
  108549. assert.string(format, 'format');
  108550. var buf;
  108551. var stype = 'ssh-' + this.type;
  108552. switch (this.type) {
  108553. case 'rsa':
  108554. switch (this.hashAlgorithm) {
  108555. case 'sha256':
  108556. stype = 'rsa-sha2-256';
  108557. break;
  108558. case 'sha512':
  108559. stype = 'rsa-sha2-512';
  108560. break;
  108561. case 'sha1':
  108562. case undefined:
  108563. break;
  108564. default:
  108565. throw (new Error('SSH signature ' +
  108566. 'format does not support hash ' +
  108567. 'algorithm ' + this.hashAlgorithm));
  108568. }
  108569. if (format === 'ssh') {
  108570. buf = new SSHBuffer({});
  108571. buf.writeString(stype);
  108572. buf.writePart(this.part.sig);
  108573. return (buf.toBuffer());
  108574. } else {
  108575. return (this.part.sig.data);
  108576. }
  108577. break;
  108578. case 'ed25519':
  108579. if (format === 'ssh') {
  108580. buf = new SSHBuffer({});
  108581. buf.writeString(stype);
  108582. buf.writePart(this.part.sig);
  108583. return (buf.toBuffer());
  108584. } else {
  108585. return (this.part.sig.data);
  108586. }
  108587. break;
  108588. case 'dsa':
  108589. case 'ecdsa':
  108590. var r, s;
  108591. if (format === 'asn1') {
  108592. var der = new asn1.BerWriter();
  108593. der.startSequence();
  108594. r = utils.mpNormalize(this.part.r.data);
  108595. s = utils.mpNormalize(this.part.s.data);
  108596. der.writeBuffer(r, asn1.Ber.Integer);
  108597. der.writeBuffer(s, asn1.Ber.Integer);
  108598. der.endSequence();
  108599. return (der.buffer);
  108600. } else if (format === 'ssh' && this.type === 'dsa') {
  108601. buf = new SSHBuffer({});
  108602. buf.writeString('ssh-dss');
  108603. r = this.part.r.data;
  108604. if (r.length > 20 && r[0] === 0x00)
  108605. r = r.slice(1);
  108606. s = this.part.s.data;
  108607. if (s.length > 20 && s[0] === 0x00)
  108608. s = s.slice(1);
  108609. if ((this.hashAlgorithm &&
  108610. this.hashAlgorithm !== 'sha1') ||
  108611. r.length + s.length !== 40) {
  108612. throw (new Error('OpenSSH only supports ' +
  108613. 'DSA signatures with SHA1 hash'));
  108614. }
  108615. buf.writeBuffer(Buffer.concat([r, s]));
  108616. return (buf.toBuffer());
  108617. } else if (format === 'ssh' && this.type === 'ecdsa') {
  108618. var inner = new SSHBuffer({});
  108619. r = this.part.r.data;
  108620. inner.writeBuffer(r);
  108621. inner.writePart(this.part.s);
  108622. buf = new SSHBuffer({});
  108623. /* XXX: find a more proper way to do this? */
  108624. var curve;
  108625. if (r[0] === 0x00)
  108626. r = r.slice(1);
  108627. var sz = r.length * 8;
  108628. if (sz === 256)
  108629. curve = 'nistp256';
  108630. else if (sz === 384)
  108631. curve = 'nistp384';
  108632. else if (sz === 528)
  108633. curve = 'nistp521';
  108634. buf.writeString('ecdsa-sha2-' + curve);
  108635. buf.writeBuffer(inner.toBuffer());
  108636. return (buf.toBuffer());
  108637. }
  108638. throw (new Error('Invalid signature format'));
  108639. default:
  108640. throw (new Error('Invalid signature data'));
  108641. }
  108642. };
  108643. Signature.prototype.toString = function (format) {
  108644. assert.optionalString(format, 'format');
  108645. return (this.toBuffer(format).toString('base64'));
  108646. };
  108647. Signature.parse = function (data, type, format) {
  108648. if (typeof (data) === 'string')
  108649. data = Buffer.from(data, 'base64');
  108650. assert.buffer(data, 'data');
  108651. assert.string(format, 'format');
  108652. assert.string(type, 'type');
  108653. var opts = {};
  108654. opts.type = type.toLowerCase();
  108655. opts.parts = [];
  108656. try {
  108657. assert.ok(data.length > 0, 'signature must not be empty');
  108658. switch (opts.type) {
  108659. case 'rsa':
  108660. return (parseOneNum(data, type, format, opts));
  108661. case 'ed25519':
  108662. return (parseOneNum(data, type, format, opts));
  108663. case 'dsa':
  108664. case 'ecdsa':
  108665. if (format === 'asn1')
  108666. return (parseDSAasn1(data, type, format, opts));
  108667. else if (opts.type === 'dsa')
  108668. return (parseDSA(data, type, format, opts));
  108669. else
  108670. return (parseECDSA(data, type, format, opts));
  108671. default:
  108672. throw (new InvalidAlgorithmError(type));
  108673. }
  108674. } catch (e) {
  108675. if (e instanceof InvalidAlgorithmError)
  108676. throw (e);
  108677. throw (new SignatureParseError(type, format, e));
  108678. }
  108679. };
  108680. function parseOneNum(data, type, format, opts) {
  108681. if (format === 'ssh') {
  108682. try {
  108683. var buf = new SSHBuffer({buffer: data});
  108684. var head = buf.readString();
  108685. } catch (e) {
  108686. /* fall through */
  108687. }
  108688. if (buf !== undefined) {
  108689. var msg = 'SSH signature does not match expected ' +
  108690. 'type (expected ' + type + ', got ' + head + ')';
  108691. switch (head) {
  108692. case 'ssh-rsa':
  108693. assert.strictEqual(type, 'rsa', msg);
  108694. opts.hashAlgo = 'sha1';
  108695. break;
  108696. case 'rsa-sha2-256':
  108697. assert.strictEqual(type, 'rsa', msg);
  108698. opts.hashAlgo = 'sha256';
  108699. break;
  108700. case 'rsa-sha2-512':
  108701. assert.strictEqual(type, 'rsa', msg);
  108702. opts.hashAlgo = 'sha512';
  108703. break;
  108704. case 'ssh-ed25519':
  108705. assert.strictEqual(type, 'ed25519', msg);
  108706. opts.hashAlgo = 'sha512';
  108707. break;
  108708. default:
  108709. throw (new Error('Unknown SSH signature ' +
  108710. 'type: ' + head));
  108711. }
  108712. var sig = buf.readPart();
  108713. assert.ok(buf.atEnd(), 'extra trailing bytes');
  108714. sig.name = 'sig';
  108715. opts.parts.push(sig);
  108716. return (new Signature(opts));
  108717. }
  108718. }
  108719. opts.parts.push({name: 'sig', data: data});
  108720. return (new Signature(opts));
  108721. }
  108722. function parseDSAasn1(data, type, format, opts) {
  108723. var der = new asn1.BerReader(data);
  108724. der.readSequence();
  108725. var r = der.readString(asn1.Ber.Integer, true);
  108726. var s = der.readString(asn1.Ber.Integer, true);
  108727. opts.parts.push({name: 'r', data: utils.mpNormalize(r)});
  108728. opts.parts.push({name: 's', data: utils.mpNormalize(s)});
  108729. return (new Signature(opts));
  108730. }
  108731. function parseDSA(data, type, format, opts) {
  108732. if (data.length != 40) {
  108733. var buf = new SSHBuffer({buffer: data});
  108734. var d = buf.readBuffer();
  108735. if (d.toString('ascii') === 'ssh-dss')
  108736. d = buf.readBuffer();
  108737. assert.ok(buf.atEnd(), 'extra trailing bytes');
  108738. assert.strictEqual(d.length, 40, 'invalid inner length');
  108739. data = d;
  108740. }
  108741. opts.parts.push({name: 'r', data: data.slice(0, 20)});
  108742. opts.parts.push({name: 's', data: data.slice(20, 40)});
  108743. return (new Signature(opts));
  108744. }
  108745. function parseECDSA(data, type, format, opts) {
  108746. var buf = new SSHBuffer({buffer: data});
  108747. var r, s;
  108748. var inner = buf.readBuffer();
  108749. var stype = inner.toString('ascii');
  108750. if (stype.slice(0, 6) === 'ecdsa-') {
  108751. var parts = stype.split('-');
  108752. assert.strictEqual(parts[0], 'ecdsa');
  108753. assert.strictEqual(parts[1], 'sha2');
  108754. opts.curve = parts[2];
  108755. switch (opts.curve) {
  108756. case 'nistp256':
  108757. opts.hashAlgo = 'sha256';
  108758. break;
  108759. case 'nistp384':
  108760. opts.hashAlgo = 'sha384';
  108761. break;
  108762. case 'nistp521':
  108763. opts.hashAlgo = 'sha512';
  108764. break;
  108765. default:
  108766. throw (new Error('Unsupported ECDSA curve: ' +
  108767. opts.curve));
  108768. }
  108769. inner = buf.readBuffer();
  108770. assert.ok(buf.atEnd(), 'extra trailing bytes on outer');
  108771. buf = new SSHBuffer({buffer: inner});
  108772. r = buf.readPart();
  108773. } else {
  108774. r = {data: inner};
  108775. }
  108776. s = buf.readPart();
  108777. assert.ok(buf.atEnd(), 'extra trailing bytes');
  108778. r.name = 'r';
  108779. s.name = 's';
  108780. opts.parts.push(r);
  108781. opts.parts.push(s);
  108782. return (new Signature(opts));
  108783. }
  108784. Signature.isSignature = function (obj, ver) {
  108785. return (utils.isCompatible(obj, Signature, ver));
  108786. };
  108787. /*
  108788. * API versions for Signature:
  108789. * [1,0] -- initial ver
  108790. * [2,0] -- support for rsa in full ssh format, compat with sshpk-agent
  108791. * hashAlgorithm property
  108792. * [2,1] -- first tagged version
  108793. */
  108794. Signature.prototype._sshpkApiVersion = [2, 1];
  108795. Signature._oldVersionDetect = function (obj) {
  108796. assert.func(obj.toBuffer);
  108797. if (obj.hasOwnProperty('hashAlgorithm'))
  108798. return ([2, 0]);
  108799. return ([1, 0]);
  108800. };
  108801. },{"./algs":572,"./errors":576,"./ssh-buffer":595,"./utils":596,"asn1":103,"assert-plus":104,"crypto":208,"safer-buffer":562}],595:[function(require,module,exports){
  108802. // Copyright 2015 Joyent, Inc.
  108803. module.exports = SSHBuffer;
  108804. var assert = require('assert-plus');
  108805. var Buffer = require('safer-buffer').Buffer;
  108806. function SSHBuffer(opts) {
  108807. assert.object(opts, 'options');
  108808. if (opts.buffer !== undefined)
  108809. assert.buffer(opts.buffer, 'options.buffer');
  108810. this._size = opts.buffer ? opts.buffer.length : 1024;
  108811. this._buffer = opts.buffer || Buffer.alloc(this._size);
  108812. this._offset = 0;
  108813. }
  108814. SSHBuffer.prototype.toBuffer = function () {
  108815. return (this._buffer.slice(0, this._offset));
  108816. };
  108817. SSHBuffer.prototype.atEnd = function () {
  108818. return (this._offset >= this._buffer.length);
  108819. };
  108820. SSHBuffer.prototype.remainder = function () {
  108821. return (this._buffer.slice(this._offset));
  108822. };
  108823. SSHBuffer.prototype.skip = function (n) {
  108824. this._offset += n;
  108825. };
  108826. SSHBuffer.prototype.expand = function () {
  108827. this._size *= 2;
  108828. var buf = Buffer.alloc(this._size);
  108829. this._buffer.copy(buf, 0);
  108830. this._buffer = buf;
  108831. };
  108832. SSHBuffer.prototype.readPart = function () {
  108833. return ({data: this.readBuffer()});
  108834. };
  108835. SSHBuffer.prototype.readBuffer = function () {
  108836. var len = this._buffer.readUInt32BE(this._offset);
  108837. this._offset += 4;
  108838. assert.ok(this._offset + len <= this._buffer.length,
  108839. 'length out of bounds at +0x' + this._offset.toString(16) +
  108840. ' (data truncated?)');
  108841. var buf = this._buffer.slice(this._offset, this._offset + len);
  108842. this._offset += len;
  108843. return (buf);
  108844. };
  108845. SSHBuffer.prototype.readString = function () {
  108846. return (this.readBuffer().toString());
  108847. };
  108848. SSHBuffer.prototype.readCString = function () {
  108849. var offset = this._offset;
  108850. while (offset < this._buffer.length &&
  108851. this._buffer[offset] !== 0x00)
  108852. offset++;
  108853. assert.ok(offset < this._buffer.length, 'c string does not terminate');
  108854. var str = this._buffer.slice(this._offset, offset).toString();
  108855. this._offset = offset + 1;
  108856. return (str);
  108857. };
  108858. SSHBuffer.prototype.readInt = function () {
  108859. var v = this._buffer.readUInt32BE(this._offset);
  108860. this._offset += 4;
  108861. return (v);
  108862. };
  108863. SSHBuffer.prototype.readInt64 = function () {
  108864. assert.ok(this._offset + 8 < this._buffer.length,
  108865. 'buffer not long enough to read Int64');
  108866. var v = this._buffer.slice(this._offset, this._offset + 8);
  108867. this._offset += 8;
  108868. return (v);
  108869. };
  108870. SSHBuffer.prototype.readChar = function () {
  108871. var v = this._buffer[this._offset++];
  108872. return (v);
  108873. };
  108874. SSHBuffer.prototype.writeBuffer = function (buf) {
  108875. while (this._offset + 4 + buf.length > this._size)
  108876. this.expand();
  108877. this._buffer.writeUInt32BE(buf.length, this._offset);
  108878. this._offset += 4;
  108879. buf.copy(this._buffer, this._offset);
  108880. this._offset += buf.length;
  108881. };
  108882. SSHBuffer.prototype.writeString = function (str) {
  108883. this.writeBuffer(Buffer.from(str, 'utf8'));
  108884. };
  108885. SSHBuffer.prototype.writeCString = function (str) {
  108886. while (this._offset + 1 + str.length > this._size)
  108887. this.expand();
  108888. this._buffer.write(str, this._offset);
  108889. this._offset += str.length;
  108890. this._buffer[this._offset++] = 0;
  108891. };
  108892. SSHBuffer.prototype.writeInt = function (v) {
  108893. while (this._offset + 4 > this._size)
  108894. this.expand();
  108895. this._buffer.writeUInt32BE(v, this._offset);
  108896. this._offset += 4;
  108897. };
  108898. SSHBuffer.prototype.writeInt64 = function (v) {
  108899. assert.buffer(v, 'value');
  108900. if (v.length > 8) {
  108901. var lead = v.slice(0, v.length - 8);
  108902. for (var i = 0; i < lead.length; ++i) {
  108903. assert.strictEqual(lead[i], 0,
  108904. 'must fit in 64 bits of precision');
  108905. }
  108906. v = v.slice(v.length - 8, v.length);
  108907. }
  108908. while (this._offset + 8 > this._size)
  108909. this.expand();
  108910. v.copy(this._buffer, this._offset);
  108911. this._offset += 8;
  108912. };
  108913. SSHBuffer.prototype.writeChar = function (v) {
  108914. while (this._offset + 1 > this._size)
  108915. this.expand();
  108916. this._buffer[this._offset++] = v;
  108917. };
  108918. SSHBuffer.prototype.writePart = function (p) {
  108919. this.writeBuffer(p.data);
  108920. };
  108921. SSHBuffer.prototype.write = function (buf) {
  108922. while (this._offset + buf.length > this._size)
  108923. this.expand();
  108924. buf.copy(this._buffer, this._offset);
  108925. this._offset += buf.length;
  108926. };
  108927. },{"assert-plus":104,"safer-buffer":562}],596:[function(require,module,exports){
  108928. // Copyright 2015 Joyent, Inc.
  108929. module.exports = {
  108930. bufferSplit: bufferSplit,
  108931. addRSAMissing: addRSAMissing,
  108932. calculateDSAPublic: calculateDSAPublic,
  108933. calculateED25519Public: calculateED25519Public,
  108934. calculateX25519Public: calculateX25519Public,
  108935. mpNormalize: mpNormalize,
  108936. mpDenormalize: mpDenormalize,
  108937. ecNormalize: ecNormalize,
  108938. countZeros: countZeros,
  108939. assertCompatible: assertCompatible,
  108940. isCompatible: isCompatible,
  108941. opensslKeyDeriv: opensslKeyDeriv,
  108942. opensshCipherInfo: opensshCipherInfo,
  108943. publicFromPrivateECDSA: publicFromPrivateECDSA,
  108944. zeroPadToLength: zeroPadToLength,
  108945. writeBitString: writeBitString,
  108946. readBitString: readBitString,
  108947. pbkdf2: pbkdf2
  108948. };
  108949. var assert = require('assert-plus');
  108950. var Buffer = require('safer-buffer').Buffer;
  108951. var PrivateKey = require('./private-key');
  108952. var Key = require('./key');
  108953. var crypto = require('crypto');
  108954. var algs = require('./algs');
  108955. var asn1 = require('asn1');
  108956. var ec = require('ecc-jsbn/lib/ec');
  108957. var jsbn = require('jsbn').BigInteger;
  108958. var nacl = require('tweetnacl');
  108959. var MAX_CLASS_DEPTH = 3;
  108960. function isCompatible(obj, klass, needVer) {
  108961. if (obj === null || typeof (obj) !== 'object')
  108962. return (false);
  108963. if (needVer === undefined)
  108964. needVer = klass.prototype._sshpkApiVersion;
  108965. if (obj instanceof klass &&
  108966. klass.prototype._sshpkApiVersion[0] == needVer[0])
  108967. return (true);
  108968. var proto = Object.getPrototypeOf(obj);
  108969. var depth = 0;
  108970. while (proto.constructor.name !== klass.name) {
  108971. proto = Object.getPrototypeOf(proto);
  108972. if (!proto || ++depth > MAX_CLASS_DEPTH)
  108973. return (false);
  108974. }
  108975. if (proto.constructor.name !== klass.name)
  108976. return (false);
  108977. var ver = proto._sshpkApiVersion;
  108978. if (ver === undefined)
  108979. ver = klass._oldVersionDetect(obj);
  108980. if (ver[0] != needVer[0] || ver[1] < needVer[1])
  108981. return (false);
  108982. return (true);
  108983. }
  108984. function assertCompatible(obj, klass, needVer, name) {
  108985. if (name === undefined)
  108986. name = 'object';
  108987. assert.ok(obj, name + ' must not be null');
  108988. assert.object(obj, name + ' must be an object');
  108989. if (needVer === undefined)
  108990. needVer = klass.prototype._sshpkApiVersion;
  108991. if (obj instanceof klass &&
  108992. klass.prototype._sshpkApiVersion[0] == needVer[0])
  108993. return;
  108994. var proto = Object.getPrototypeOf(obj);
  108995. var depth = 0;
  108996. while (proto.constructor.name !== klass.name) {
  108997. proto = Object.getPrototypeOf(proto);
  108998. assert.ok(proto && ++depth <= MAX_CLASS_DEPTH,
  108999. name + ' must be a ' + klass.name + ' instance');
  109000. }
  109001. assert.strictEqual(proto.constructor.name, klass.name,
  109002. name + ' must be a ' + klass.name + ' instance');
  109003. var ver = proto._sshpkApiVersion;
  109004. if (ver === undefined)
  109005. ver = klass._oldVersionDetect(obj);
  109006. assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1],
  109007. name + ' must be compatible with ' + klass.name + ' klass ' +
  109008. 'version ' + needVer[0] + '.' + needVer[1]);
  109009. }
  109010. var CIPHER_LEN = {
  109011. 'des-ede3-cbc': { key: 24, iv: 8 },
  109012. 'aes-128-cbc': { key: 16, iv: 16 },
  109013. 'aes-256-cbc': { key: 32, iv: 16 }
  109014. };
  109015. var PKCS5_SALT_LEN = 8;
  109016. function opensslKeyDeriv(cipher, salt, passphrase, count) {
  109017. assert.buffer(salt, 'salt');
  109018. assert.buffer(passphrase, 'passphrase');
  109019. assert.number(count, 'iteration count');
  109020. var clen = CIPHER_LEN[cipher];
  109021. assert.object(clen, 'supported cipher');
  109022. salt = salt.slice(0, PKCS5_SALT_LEN);
  109023. var D, D_prev, bufs;
  109024. var material = Buffer.alloc(0);
  109025. while (material.length < clen.key + clen.iv) {
  109026. bufs = [];
  109027. if (D_prev)
  109028. bufs.push(D_prev);
  109029. bufs.push(passphrase);
  109030. bufs.push(salt);
  109031. D = Buffer.concat(bufs);
  109032. for (var j = 0; j < count; ++j)
  109033. D = crypto.createHash('md5').update(D).digest();
  109034. material = Buffer.concat([material, D]);
  109035. D_prev = D;
  109036. }
  109037. return ({
  109038. key: material.slice(0, clen.key),
  109039. iv: material.slice(clen.key, clen.key + clen.iv)
  109040. });
  109041. }
  109042. /* See: RFC2898 */
  109043. function pbkdf2(hashAlg, salt, iterations, size, passphrase) {
  109044. var hkey = Buffer.alloc(salt.length + 4);
  109045. salt.copy(hkey);
  109046. var gen = 0, ts = [];
  109047. var i = 1;
  109048. while (gen < size) {
  109049. var t = T(i++);
  109050. gen += t.length;
  109051. ts.push(t);
  109052. }
  109053. return (Buffer.concat(ts).slice(0, size));
  109054. function T(I) {
  109055. hkey.writeUInt32BE(I, hkey.length - 4);
  109056. var hmac = crypto.createHmac(hashAlg, passphrase);
  109057. hmac.update(hkey);
  109058. var Ti = hmac.digest();
  109059. var Uc = Ti;
  109060. var c = 1;
  109061. while (c++ < iterations) {
  109062. hmac = crypto.createHmac(hashAlg, passphrase);
  109063. hmac.update(Uc);
  109064. Uc = hmac.digest();
  109065. for (var x = 0; x < Ti.length; ++x)
  109066. Ti[x] ^= Uc[x];
  109067. }
  109068. return (Ti);
  109069. }
  109070. }
  109071. /* Count leading zero bits on a buffer */
  109072. function countZeros(buf) {
  109073. var o = 0, obit = 8;
  109074. while (o < buf.length) {
  109075. var mask = (1 << obit);
  109076. if ((buf[o] & mask) === mask)
  109077. break;
  109078. obit--;
  109079. if (obit < 0) {
  109080. o++;
  109081. obit = 8;
  109082. }
  109083. }
  109084. return (o*8 + (8 - obit) - 1);
  109085. }
  109086. function bufferSplit(buf, chr) {
  109087. assert.buffer(buf);
  109088. assert.string(chr);
  109089. var parts = [];
  109090. var lastPart = 0;
  109091. var matches = 0;
  109092. for (var i = 0; i < buf.length; ++i) {
  109093. if (buf[i] === chr.charCodeAt(matches))
  109094. ++matches;
  109095. else if (buf[i] === chr.charCodeAt(0))
  109096. matches = 1;
  109097. else
  109098. matches = 0;
  109099. if (matches >= chr.length) {
  109100. var newPart = i + 1;
  109101. parts.push(buf.slice(lastPart, newPart - matches));
  109102. lastPart = newPart;
  109103. matches = 0;
  109104. }
  109105. }
  109106. if (lastPart <= buf.length)
  109107. parts.push(buf.slice(lastPart, buf.length));
  109108. return (parts);
  109109. }
  109110. function ecNormalize(buf, addZero) {
  109111. assert.buffer(buf);
  109112. if (buf[0] === 0x00 && buf[1] === 0x04) {
  109113. if (addZero)
  109114. return (buf);
  109115. return (buf.slice(1));
  109116. } else if (buf[0] === 0x04) {
  109117. if (!addZero)
  109118. return (buf);
  109119. } else {
  109120. while (buf[0] === 0x00)
  109121. buf = buf.slice(1);
  109122. if (buf[0] === 0x02 || buf[0] === 0x03)
  109123. throw (new Error('Compressed elliptic curve points ' +
  109124. 'are not supported'));
  109125. if (buf[0] !== 0x04)
  109126. throw (new Error('Not a valid elliptic curve point'));
  109127. if (!addZero)
  109128. return (buf);
  109129. }
  109130. var b = Buffer.alloc(buf.length + 1);
  109131. b[0] = 0x0;
  109132. buf.copy(b, 1);
  109133. return (b);
  109134. }
  109135. function readBitString(der, tag) {
  109136. if (tag === undefined)
  109137. tag = asn1.Ber.BitString;
  109138. var buf = der.readString(tag, true);
  109139. assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' +
  109140. 'not supported (0x' + buf[0].toString(16) + ')');
  109141. return (buf.slice(1));
  109142. }
  109143. function writeBitString(der, buf, tag) {
  109144. if (tag === undefined)
  109145. tag = asn1.Ber.BitString;
  109146. var b = Buffer.alloc(buf.length + 1);
  109147. b[0] = 0x00;
  109148. buf.copy(b, 1);
  109149. der.writeBuffer(b, tag);
  109150. }
  109151. function mpNormalize(buf) {
  109152. assert.buffer(buf);
  109153. while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00)
  109154. buf = buf.slice(1);
  109155. if ((buf[0] & 0x80) === 0x80) {
  109156. var b = Buffer.alloc(buf.length + 1);
  109157. b[0] = 0x00;
  109158. buf.copy(b, 1);
  109159. buf = b;
  109160. }
  109161. return (buf);
  109162. }
  109163. function mpDenormalize(buf) {
  109164. assert.buffer(buf);
  109165. while (buf.length > 1 && buf[0] === 0x00)
  109166. buf = buf.slice(1);
  109167. return (buf);
  109168. }
  109169. function zeroPadToLength(buf, len) {
  109170. assert.buffer(buf);
  109171. assert.number(len);
  109172. while (buf.length > len) {
  109173. assert.equal(buf[0], 0x00);
  109174. buf = buf.slice(1);
  109175. }
  109176. while (buf.length < len) {
  109177. var b = Buffer.alloc(buf.length + 1);
  109178. b[0] = 0x00;
  109179. buf.copy(b, 1);
  109180. buf = b;
  109181. }
  109182. return (buf);
  109183. }
  109184. function bigintToMpBuf(bigint) {
  109185. var buf = Buffer.from(bigint.toByteArray());
  109186. buf = mpNormalize(buf);
  109187. return (buf);
  109188. }
  109189. function calculateDSAPublic(g, p, x) {
  109190. assert.buffer(g);
  109191. assert.buffer(p);
  109192. assert.buffer(x);
  109193. g = new jsbn(g);
  109194. p = new jsbn(p);
  109195. x = new jsbn(x);
  109196. var y = g.modPow(x, p);
  109197. var ybuf = bigintToMpBuf(y);
  109198. return (ybuf);
  109199. }
  109200. function calculateED25519Public(k) {
  109201. assert.buffer(k);
  109202. var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k));
  109203. return (Buffer.from(kp.publicKey));
  109204. }
  109205. function calculateX25519Public(k) {
  109206. assert.buffer(k);
  109207. var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k));
  109208. return (Buffer.from(kp.publicKey));
  109209. }
  109210. function addRSAMissing(key) {
  109211. assert.object(key);
  109212. assertCompatible(key, PrivateKey, [1, 1]);
  109213. var d = new jsbn(key.part.d.data);
  109214. var buf;
  109215. if (!key.part.dmodp) {
  109216. var p = new jsbn(key.part.p.data);
  109217. var dmodp = d.mod(p.subtract(1));
  109218. buf = bigintToMpBuf(dmodp);
  109219. key.part.dmodp = {name: 'dmodp', data: buf};
  109220. key.parts.push(key.part.dmodp);
  109221. }
  109222. if (!key.part.dmodq) {
  109223. var q = new jsbn(key.part.q.data);
  109224. var dmodq = d.mod(q.subtract(1));
  109225. buf = bigintToMpBuf(dmodq);
  109226. key.part.dmodq = {name: 'dmodq', data: buf};
  109227. key.parts.push(key.part.dmodq);
  109228. }
  109229. }
  109230. function publicFromPrivateECDSA(curveName, priv) {
  109231. assert.string(curveName, 'curveName');
  109232. assert.buffer(priv);
  109233. var params = algs.curves[curveName];
  109234. var p = new jsbn(params.p);
  109235. var a = new jsbn(params.a);
  109236. var b = new jsbn(params.b);
  109237. var curve = new ec.ECCurveFp(p, a, b);
  109238. var G = curve.decodePointHex(params.G.toString('hex'));
  109239. var d = new jsbn(mpNormalize(priv));
  109240. var pub = G.multiply(d);
  109241. pub = Buffer.from(curve.encodePointHex(pub), 'hex');
  109242. var parts = [];
  109243. parts.push({name: 'curve', data: Buffer.from(curveName)});
  109244. parts.push({name: 'Q', data: pub});
  109245. var key = new Key({type: 'ecdsa', curve: curve, parts: parts});
  109246. return (key);
  109247. }
  109248. function opensshCipherInfo(cipher) {
  109249. var inf = {};
  109250. switch (cipher) {
  109251. case '3des-cbc':
  109252. inf.keySize = 24;
  109253. inf.blockSize = 8;
  109254. inf.opensslName = 'des-ede3-cbc';
  109255. break;
  109256. case 'blowfish-cbc':
  109257. inf.keySize = 16;
  109258. inf.blockSize = 8;
  109259. inf.opensslName = 'bf-cbc';
  109260. break;
  109261. case 'aes128-cbc':
  109262. case 'aes128-ctr':
  109263. case 'aes128-gcm@openssh.com':
  109264. inf.keySize = 16;
  109265. inf.blockSize = 16;
  109266. inf.opensslName = 'aes-128-' + cipher.slice(7, 10);
  109267. break;
  109268. case 'aes192-cbc':
  109269. case 'aes192-ctr':
  109270. case 'aes192-gcm@openssh.com':
  109271. inf.keySize = 24;
  109272. inf.blockSize = 16;
  109273. inf.opensslName = 'aes-192-' + cipher.slice(7, 10);
  109274. break;
  109275. case 'aes256-cbc':
  109276. case 'aes256-ctr':
  109277. case 'aes256-gcm@openssh.com':
  109278. inf.keySize = 32;
  109279. inf.blockSize = 16;
  109280. inf.opensslName = 'aes-256-' + cipher.slice(7, 10);
  109281. break;
  109282. default:
  109283. throw (new Error(
  109284. 'Unsupported openssl cipher "' + cipher + '"'));
  109285. }
  109286. return (inf);
  109287. }
  109288. },{"./algs":572,"./key":592,"./private-key":593,"asn1":103,"assert-plus":104,"crypto":208,"ecc-jsbn/lib/ec":224,"jsbn":328,"safer-buffer":562,"tweetnacl":650}],597:[function(require,module,exports){
  109289. // Copyright Joyent, Inc. and other Node contributors.
  109290. //
  109291. // Permission is hereby granted, free of charge, to any person obtaining a
  109292. // copy of this software and associated documentation files (the
  109293. // "Software"), to deal in the Software without restriction, including
  109294. // without limitation the rights to use, copy, modify, merge, publish,
  109295. // distribute, sublicense, and/or sell copies of the Software, and to permit
  109296. // persons to whom the Software is furnished to do so, subject to the
  109297. // following conditions:
  109298. //
  109299. // The above copyright notice and this permission notice shall be included
  109300. // in all copies or substantial portions of the Software.
  109301. //
  109302. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  109303. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  109304. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  109305. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  109306. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  109307. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  109308. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  109309. module.exports = Stream;
  109310. var EE = require('events').EventEmitter;
  109311. var inherits = require('inherits');
  109312. inherits(Stream, EE);
  109313. Stream.Readable = require('readable-stream/lib/_stream_readable.js');
  109314. Stream.Writable = require('readable-stream/lib/_stream_writable.js');
  109315. Stream.Duplex = require('readable-stream/lib/_stream_duplex.js');
  109316. Stream.Transform = require('readable-stream/lib/_stream_transform.js');
  109317. Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js');
  109318. Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js')
  109319. Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js')
  109320. // Backwards-compat with node 0.4.x
  109321. Stream.Stream = Stream;
  109322. // old-style streams. Note that the pipe method (the only relevant
  109323. // part of this class) is overridden in the Readable class.
  109324. function Stream() {
  109325. EE.call(this);
  109326. }
  109327. Stream.prototype.pipe = function(dest, options) {
  109328. var source = this;
  109329. function ondata(chunk) {
  109330. if (dest.writable) {
  109331. if (false === dest.write(chunk) && source.pause) {
  109332. source.pause();
  109333. }
  109334. }
  109335. }
  109336. source.on('data', ondata);
  109337. function ondrain() {
  109338. if (source.readable && source.resume) {
  109339. source.resume();
  109340. }
  109341. }
  109342. dest.on('drain', ondrain);
  109343. // If the 'end' option is not supplied, dest.end() will be called when
  109344. // source gets the 'end' or 'close' events. Only dest.end() once.
  109345. if (!dest._isStdio && (!options || options.end !== false)) {
  109346. source.on('end', onend);
  109347. source.on('close', onclose);
  109348. }
  109349. var didOnEnd = false;
  109350. function onend() {
  109351. if (didOnEnd) return;
  109352. didOnEnd = true;
  109353. dest.end();
  109354. }
  109355. function onclose() {
  109356. if (didOnEnd) return;
  109357. didOnEnd = true;
  109358. if (typeof dest.destroy === 'function') dest.destroy();
  109359. }
  109360. // don't leave dangling pipes when there are errors.
  109361. function onerror(er) {
  109362. cleanup();
  109363. if (EE.listenerCount(this, 'error') === 0) {
  109364. throw er; // Unhandled stream error in pipe.
  109365. }
  109366. }
  109367. source.on('error', onerror);
  109368. dest.on('error', onerror);
  109369. // remove all the event listeners that were added.
  109370. function cleanup() {
  109371. source.removeListener('data', ondata);
  109372. dest.removeListener('drain', ondrain);
  109373. source.removeListener('end', onend);
  109374. source.removeListener('close', onclose);
  109375. source.removeListener('error', onerror);
  109376. dest.removeListener('error', onerror);
  109377. source.removeListener('end', cleanup);
  109378. source.removeListener('close', cleanup);
  109379. dest.removeListener('close', cleanup);
  109380. }
  109381. source.on('end', cleanup);
  109382. source.on('close', cleanup);
  109383. dest.on('close', cleanup);
  109384. dest.emit('pipe', source);
  109385. // Allow for unix-like usage: A.pipe(B).pipe(C)
  109386. return dest;
  109387. };
  109388. },{"events":247,"inherits":320,"readable-stream/lib/_stream_duplex.js":599,"readable-stream/lib/_stream_passthrough.js":600,"readable-stream/lib/_stream_readable.js":601,"readable-stream/lib/_stream_transform.js":602,"readable-stream/lib/_stream_writable.js":603,"readable-stream/lib/internal/streams/end-of-stream.js":607,"readable-stream/lib/internal/streams/pipeline.js":609}],598:[function(require,module,exports){
  109389. arguments[4][172][0].apply(exports,arguments)
  109390. },{"dup":172}],599:[function(require,module,exports){
  109391. arguments[4][173][0].apply(exports,arguments)
  109392. },{"./_stream_readable":601,"./_stream_writable":603,"_process":525,"dup":173,"inherits":320}],600:[function(require,module,exports){
  109393. arguments[4][174][0].apply(exports,arguments)
  109394. },{"./_stream_transform":602,"dup":174,"inherits":320}],601:[function(require,module,exports){
  109395. arguments[4][175][0].apply(exports,arguments)
  109396. },{"../errors":598,"./_stream_duplex":599,"./internal/streams/async_iterator":604,"./internal/streams/buffer_list":605,"./internal/streams/destroy":606,"./internal/streams/from":608,"./internal/streams/state":610,"./internal/streams/stream":611,"_process":525,"buffer":193,"dup":175,"events":247,"inherits":320,"string_decoder/":631,"util":144}],602:[function(require,module,exports){
  109397. arguments[4][176][0].apply(exports,arguments)
  109398. },{"../errors":598,"./_stream_duplex":599,"dup":176,"inherits":320}],603:[function(require,module,exports){
  109399. arguments[4][177][0].apply(exports,arguments)
  109400. },{"../errors":598,"./_stream_duplex":599,"./internal/streams/destroy":606,"./internal/streams/state":610,"./internal/streams/stream":611,"_process":525,"buffer":193,"dup":177,"inherits":320,"util-deprecate":655}],604:[function(require,module,exports){
  109401. arguments[4][178][0].apply(exports,arguments)
  109402. },{"./end-of-stream":607,"_process":525,"dup":178}],605:[function(require,module,exports){
  109403. arguments[4][179][0].apply(exports,arguments)
  109404. },{"buffer":193,"dup":179,"util":144}],606:[function(require,module,exports){
  109405. arguments[4][180][0].apply(exports,arguments)
  109406. },{"_process":525,"dup":180}],607:[function(require,module,exports){
  109407. arguments[4][181][0].apply(exports,arguments)
  109408. },{"../../../errors":598,"dup":181}],608:[function(require,module,exports){
  109409. arguments[4][182][0].apply(exports,arguments)
  109410. },{"dup":182}],609:[function(require,module,exports){
  109411. arguments[4][183][0].apply(exports,arguments)
  109412. },{"../../../errors":598,"./end-of-stream":607,"dup":183}],610:[function(require,module,exports){
  109413. arguments[4][184][0].apply(exports,arguments)
  109414. },{"../../../errors":598,"dup":184}],611:[function(require,module,exports){
  109415. arguments[4][185][0].apply(exports,arguments)
  109416. },{"dup":185,"events":247}],612:[function(require,module,exports){
  109417. (function (global){(function (){
  109418. var ClientRequest = require('./lib/request')
  109419. var response = require('./lib/response')
  109420. var extend = require('xtend')
  109421. var statusCodes = require('builtin-status-codes')
  109422. var url = require('url')
  109423. var http = exports
  109424. http.request = function (opts, cb) {
  109425. if (typeof opts === 'string')
  109426. opts = url.parse(opts)
  109427. else
  109428. opts = extend(opts)
  109429. // Normally, the page is loaded from http or https, so not specifying a protocol
  109430. // will result in a (valid) protocol-relative url. However, this won't work if
  109431. // the protocol is something else, like 'file:'
  109432. var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
  109433. var protocol = opts.protocol || defaultProtocol
  109434. var host = opts.hostname || opts.host
  109435. var port = opts.port
  109436. var path = opts.path || '/'
  109437. // Necessary for IPv6 addresses
  109438. if (host && host.indexOf(':') !== -1)
  109439. host = '[' + host + ']'
  109440. // This may be a relative url. The browser should always be able to interpret it correctly.
  109441. opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
  109442. opts.method = (opts.method || 'GET').toUpperCase()
  109443. opts.headers = opts.headers || {}
  109444. // Also valid opts.auth, opts.mode
  109445. var req = new ClientRequest(opts)
  109446. if (cb)
  109447. req.on('response', cb)
  109448. return req
  109449. }
  109450. http.get = function get (opts, cb) {
  109451. var req = http.request(opts, cb)
  109452. req.end()
  109453. return req
  109454. }
  109455. http.ClientRequest = ClientRequest
  109456. http.IncomingMessage = response.IncomingMessage
  109457. http.Agent = function () {}
  109458. http.Agent.defaultMaxSockets = 4
  109459. http.globalAgent = new http.Agent()
  109460. http.STATUS_CODES = statusCodes
  109461. http.METHODS = [
  109462. 'CHECKOUT',
  109463. 'CONNECT',
  109464. 'COPY',
  109465. 'DELETE',
  109466. 'GET',
  109467. 'HEAD',
  109468. 'LOCK',
  109469. 'M-SEARCH',
  109470. 'MERGE',
  109471. 'MKACTIVITY',
  109472. 'MKCOL',
  109473. 'MOVE',
  109474. 'NOTIFY',
  109475. 'OPTIONS',
  109476. 'PATCH',
  109477. 'POST',
  109478. 'PROPFIND',
  109479. 'PROPPATCH',
  109480. 'PURGE',
  109481. 'PUT',
  109482. 'REPORT',
  109483. 'SEARCH',
  109484. 'SUBSCRIBE',
  109485. 'TRACE',
  109486. 'UNLOCK',
  109487. 'UNSUBSCRIBE'
  109488. ]
  109489. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  109490. },{"./lib/request":614,"./lib/response":615,"builtin-status-codes":194,"url":653,"xtend":710}],613:[function(require,module,exports){
  109491. (function (global){(function (){
  109492. exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
  109493. exports.writableStream = isFunction(global.WritableStream)
  109494. exports.abortController = isFunction(global.AbortController)
  109495. // The xhr request to example.com may violate some restrictive CSP configurations,
  109496. // so if we're running in a browser that supports `fetch`, avoid calling getXHR()
  109497. // and assume support for certain features below.
  109498. var xhr
  109499. function getXHR () {
  109500. // Cache the xhr value
  109501. if (xhr !== undefined) return xhr
  109502. if (global.XMLHttpRequest) {
  109503. xhr = new global.XMLHttpRequest()
  109504. // If XDomainRequest is available (ie only, where xhr might not work
  109505. // cross domain), use the page location. Otherwise use example.com
  109506. // Note: this doesn't actually make an http request.
  109507. try {
  109508. xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
  109509. } catch(e) {
  109510. xhr = null
  109511. }
  109512. } else {
  109513. // Service workers don't have XHR
  109514. xhr = null
  109515. }
  109516. return xhr
  109517. }
  109518. function checkTypeSupport (type) {
  109519. var xhr = getXHR()
  109520. if (!xhr) return false
  109521. try {
  109522. xhr.responseType = type
  109523. return xhr.responseType === type
  109524. } catch (e) {}
  109525. return false
  109526. }
  109527. // If fetch is supported, then arraybuffer will be supported too. Skip calling
  109528. // checkTypeSupport(), since that calls getXHR().
  109529. exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer')
  109530. // These next two tests unavoidably show warnings in Chrome. Since fetch will always
  109531. // be used if it's available, just return false for these to avoid the warnings.
  109532. exports.msstream = !exports.fetch && checkTypeSupport('ms-stream')
  109533. exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer')
  109534. // If fetch is supported, then overrideMimeType will be supported too. Skip calling
  109535. // getXHR().
  109536. exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
  109537. function isFunction (value) {
  109538. return typeof value === 'function'
  109539. }
  109540. xhr = null // Help gc
  109541. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  109542. },{}],614:[function(require,module,exports){
  109543. (function (process,global,Buffer){(function (){
  109544. var capability = require('./capability')
  109545. var inherits = require('inherits')
  109546. var response = require('./response')
  109547. var stream = require('readable-stream')
  109548. var IncomingMessage = response.IncomingMessage
  109549. var rStates = response.readyStates
  109550. function decideMode (preferBinary, useFetch) {
  109551. if (capability.fetch && useFetch) {
  109552. return 'fetch'
  109553. } else if (capability.mozchunkedarraybuffer) {
  109554. return 'moz-chunked-arraybuffer'
  109555. } else if (capability.msstream) {
  109556. return 'ms-stream'
  109557. } else if (capability.arraybuffer && preferBinary) {
  109558. return 'arraybuffer'
  109559. } else {
  109560. return 'text'
  109561. }
  109562. }
  109563. var ClientRequest = module.exports = function (opts) {
  109564. var self = this
  109565. stream.Writable.call(self)
  109566. self._opts = opts
  109567. self._body = []
  109568. self._headers = {}
  109569. if (opts.auth)
  109570. self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
  109571. Object.keys(opts.headers).forEach(function (name) {
  109572. self.setHeader(name, opts.headers[name])
  109573. })
  109574. var preferBinary
  109575. var useFetch = true
  109576. if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
  109577. // If the use of XHR should be preferred. Not typically needed.
  109578. useFetch = false
  109579. preferBinary = true
  109580. } else if (opts.mode === 'prefer-streaming') {
  109581. // If streaming is a high priority but binary compatibility and
  109582. // the accuracy of the 'content-type' header aren't
  109583. preferBinary = false
  109584. } else if (opts.mode === 'allow-wrong-content-type') {
  109585. // If streaming is more important than preserving the 'content-type' header
  109586. preferBinary = !capability.overrideMimeType
  109587. } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
  109588. // Use binary if text streaming may corrupt data or the content-type header, or for speed
  109589. preferBinary = true
  109590. } else {
  109591. throw new Error('Invalid value for opts.mode')
  109592. }
  109593. self._mode = decideMode(preferBinary, useFetch)
  109594. self._fetchTimer = null
  109595. self.on('finish', function () {
  109596. self._onFinish()
  109597. })
  109598. }
  109599. inherits(ClientRequest, stream.Writable)
  109600. ClientRequest.prototype.setHeader = function (name, value) {
  109601. var self = this
  109602. var lowerName = name.toLowerCase()
  109603. // This check is not necessary, but it prevents warnings from browsers about setting unsafe
  109604. // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
  109605. // http-browserify did it, so I will too.
  109606. if (unsafeHeaders.indexOf(lowerName) !== -1)
  109607. return
  109608. self._headers[lowerName] = {
  109609. name: name,
  109610. value: value
  109611. }
  109612. }
  109613. ClientRequest.prototype.getHeader = function (name) {
  109614. var header = this._headers[name.toLowerCase()]
  109615. if (header)
  109616. return header.value
  109617. return null
  109618. }
  109619. ClientRequest.prototype.removeHeader = function (name) {
  109620. var self = this
  109621. delete self._headers[name.toLowerCase()]
  109622. }
  109623. ClientRequest.prototype._onFinish = function () {
  109624. var self = this
  109625. if (self._destroyed)
  109626. return
  109627. var opts = self._opts
  109628. var headersObj = self._headers
  109629. var body = null
  109630. if (opts.method !== 'GET' && opts.method !== 'HEAD') {
  109631. body = new Blob(self._body, {
  109632. type: (headersObj['content-type'] || {}).value || ''
  109633. });
  109634. }
  109635. // create flattened list of headers
  109636. var headersList = []
  109637. Object.keys(headersObj).forEach(function (keyName) {
  109638. var name = headersObj[keyName].name
  109639. var value = headersObj[keyName].value
  109640. if (Array.isArray(value)) {
  109641. value.forEach(function (v) {
  109642. headersList.push([name, v])
  109643. })
  109644. } else {
  109645. headersList.push([name, value])
  109646. }
  109647. })
  109648. if (self._mode === 'fetch') {
  109649. var signal = null
  109650. if (capability.abortController) {
  109651. var controller = new AbortController()
  109652. signal = controller.signal
  109653. self._fetchAbortController = controller
  109654. if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
  109655. self._fetchTimer = global.setTimeout(function () {
  109656. self.emit('requestTimeout')
  109657. if (self._fetchAbortController)
  109658. self._fetchAbortController.abort()
  109659. }, opts.requestTimeout)
  109660. }
  109661. }
  109662. global.fetch(self._opts.url, {
  109663. method: self._opts.method,
  109664. headers: headersList,
  109665. body: body || undefined,
  109666. mode: 'cors',
  109667. credentials: opts.withCredentials ? 'include' : 'same-origin',
  109668. signal: signal
  109669. }).then(function (response) {
  109670. self._fetchResponse = response
  109671. self._connect()
  109672. }, function (reason) {
  109673. global.clearTimeout(self._fetchTimer)
  109674. if (!self._destroyed)
  109675. self.emit('error', reason)
  109676. })
  109677. } else {
  109678. var xhr = self._xhr = new global.XMLHttpRequest()
  109679. try {
  109680. xhr.open(self._opts.method, self._opts.url, true)
  109681. } catch (err) {
  109682. process.nextTick(function () {
  109683. self.emit('error', err)
  109684. })
  109685. return
  109686. }
  109687. // Can't set responseType on really old browsers
  109688. if ('responseType' in xhr)
  109689. xhr.responseType = self._mode
  109690. if ('withCredentials' in xhr)
  109691. xhr.withCredentials = !!opts.withCredentials
  109692. if (self._mode === 'text' && 'overrideMimeType' in xhr)
  109693. xhr.overrideMimeType('text/plain; charset=x-user-defined')
  109694. if ('requestTimeout' in opts) {
  109695. xhr.timeout = opts.requestTimeout
  109696. xhr.ontimeout = function () {
  109697. self.emit('requestTimeout')
  109698. }
  109699. }
  109700. headersList.forEach(function (header) {
  109701. xhr.setRequestHeader(header[0], header[1])
  109702. })
  109703. self._response = null
  109704. xhr.onreadystatechange = function () {
  109705. switch (xhr.readyState) {
  109706. case rStates.LOADING:
  109707. case rStates.DONE:
  109708. self._onXHRProgress()
  109709. break
  109710. }
  109711. }
  109712. // Necessary for streaming in Firefox, since xhr.response is ONLY defined
  109713. // in onprogress, not in onreadystatechange with xhr.readyState = 3
  109714. if (self._mode === 'moz-chunked-arraybuffer') {
  109715. xhr.onprogress = function () {
  109716. self._onXHRProgress()
  109717. }
  109718. }
  109719. xhr.onerror = function () {
  109720. if (self._destroyed)
  109721. return
  109722. self.emit('error', new Error('XHR error'))
  109723. }
  109724. try {
  109725. xhr.send(body)
  109726. } catch (err) {
  109727. process.nextTick(function () {
  109728. self.emit('error', err)
  109729. })
  109730. return
  109731. }
  109732. }
  109733. }
  109734. /**
  109735. * Checks if xhr.status is readable and non-zero, indicating no error.
  109736. * Even though the spec says it should be available in readyState 3,
  109737. * accessing it throws an exception in IE8
  109738. */
  109739. function statusValid (xhr) {
  109740. try {
  109741. var status = xhr.status
  109742. return (status !== null && status !== 0)
  109743. } catch (e) {
  109744. return false
  109745. }
  109746. }
  109747. ClientRequest.prototype._onXHRProgress = function () {
  109748. var self = this
  109749. if (!statusValid(self._xhr) || self._destroyed)
  109750. return
  109751. if (!self._response)
  109752. self._connect()
  109753. self._response._onXHRProgress()
  109754. }
  109755. ClientRequest.prototype._connect = function () {
  109756. var self = this
  109757. if (self._destroyed)
  109758. return
  109759. self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
  109760. self._response.on('error', function(err) {
  109761. self.emit('error', err)
  109762. })
  109763. self.emit('response', self._response)
  109764. }
  109765. ClientRequest.prototype._write = function (chunk, encoding, cb) {
  109766. var self = this
  109767. self._body.push(chunk)
  109768. cb()
  109769. }
  109770. ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
  109771. var self = this
  109772. self._destroyed = true
  109773. global.clearTimeout(self._fetchTimer)
  109774. if (self._response)
  109775. self._response._destroyed = true
  109776. if (self._xhr)
  109777. self._xhr.abort()
  109778. else if (self._fetchAbortController)
  109779. self._fetchAbortController.abort()
  109780. }
  109781. ClientRequest.prototype.end = function (data, encoding, cb) {
  109782. var self = this
  109783. if (typeof data === 'function') {
  109784. cb = data
  109785. data = undefined
  109786. }
  109787. stream.Writable.prototype.end.call(self, data, encoding, cb)
  109788. }
  109789. ClientRequest.prototype.flushHeaders = function () {}
  109790. ClientRequest.prototype.setTimeout = function () {}
  109791. ClientRequest.prototype.setNoDelay = function () {}
  109792. ClientRequest.prototype.setSocketKeepAlive = function () {}
  109793. // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
  109794. var unsafeHeaders = [
  109795. 'accept-charset',
  109796. 'accept-encoding',
  109797. 'access-control-request-headers',
  109798. 'access-control-request-method',
  109799. 'connection',
  109800. 'content-length',
  109801. 'cookie',
  109802. 'cookie2',
  109803. 'date',
  109804. 'dnt',
  109805. 'expect',
  109806. 'host',
  109807. 'keep-alive',
  109808. 'origin',
  109809. 'referer',
  109810. 'te',
  109811. 'trailer',
  109812. 'transfer-encoding',
  109813. 'upgrade',
  109814. 'via'
  109815. ]
  109816. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  109817. },{"./capability":613,"./response":615,"_process":525,"buffer":193,"inherits":320,"readable-stream":630}],615:[function(require,module,exports){
  109818. (function (process,global,Buffer){(function (){
  109819. var capability = require('./capability')
  109820. var inherits = require('inherits')
  109821. var stream = require('readable-stream')
  109822. var rStates = exports.readyStates = {
  109823. UNSENT: 0,
  109824. OPENED: 1,
  109825. HEADERS_RECEIVED: 2,
  109826. LOADING: 3,
  109827. DONE: 4
  109828. }
  109829. var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
  109830. var self = this
  109831. stream.Readable.call(self)
  109832. self._mode = mode
  109833. self.headers = {}
  109834. self.rawHeaders = []
  109835. self.trailers = {}
  109836. self.rawTrailers = []
  109837. // Fake the 'close' event, but only once 'end' fires
  109838. self.on('end', function () {
  109839. // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
  109840. process.nextTick(function () {
  109841. self.emit('close')
  109842. })
  109843. })
  109844. if (mode === 'fetch') {
  109845. self._fetchResponse = response
  109846. self.url = response.url
  109847. self.statusCode = response.status
  109848. self.statusMessage = response.statusText
  109849. response.headers.forEach(function (header, key){
  109850. self.headers[key.toLowerCase()] = header
  109851. self.rawHeaders.push(key, header)
  109852. })
  109853. if (capability.writableStream) {
  109854. var writable = new WritableStream({
  109855. write: function (chunk) {
  109856. return new Promise(function (resolve, reject) {
  109857. if (self._destroyed) {
  109858. reject()
  109859. } else if(self.push(Buffer.from(chunk))) {
  109860. resolve()
  109861. } else {
  109862. self._resumeFetch = resolve
  109863. }
  109864. })
  109865. },
  109866. close: function () {
  109867. global.clearTimeout(fetchTimer)
  109868. if (!self._destroyed)
  109869. self.push(null)
  109870. },
  109871. abort: function (err) {
  109872. if (!self._destroyed)
  109873. self.emit('error', err)
  109874. }
  109875. })
  109876. try {
  109877. response.body.pipeTo(writable).catch(function (err) {
  109878. global.clearTimeout(fetchTimer)
  109879. if (!self._destroyed)
  109880. self.emit('error', err)
  109881. })
  109882. return
  109883. } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
  109884. }
  109885. // fallback for when writableStream or pipeTo aren't available
  109886. var reader = response.body.getReader()
  109887. function read () {
  109888. reader.read().then(function (result) {
  109889. if (self._destroyed)
  109890. return
  109891. if (result.done) {
  109892. global.clearTimeout(fetchTimer)
  109893. self.push(null)
  109894. return
  109895. }
  109896. self.push(Buffer.from(result.value))
  109897. read()
  109898. }).catch(function (err) {
  109899. global.clearTimeout(fetchTimer)
  109900. if (!self._destroyed)
  109901. self.emit('error', err)
  109902. })
  109903. }
  109904. read()
  109905. } else {
  109906. self._xhr = xhr
  109907. self._pos = 0
  109908. self.url = xhr.responseURL
  109909. self.statusCode = xhr.status
  109910. self.statusMessage = xhr.statusText
  109911. var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
  109912. headers.forEach(function (header) {
  109913. var matches = header.match(/^([^:]+):\s*(.*)/)
  109914. if (matches) {
  109915. var key = matches[1].toLowerCase()
  109916. if (key === 'set-cookie') {
  109917. if (self.headers[key] === undefined) {
  109918. self.headers[key] = []
  109919. }
  109920. self.headers[key].push(matches[2])
  109921. } else if (self.headers[key] !== undefined) {
  109922. self.headers[key] += ', ' + matches[2]
  109923. } else {
  109924. self.headers[key] = matches[2]
  109925. }
  109926. self.rawHeaders.push(matches[1], matches[2])
  109927. }
  109928. })
  109929. self._charset = 'x-user-defined'
  109930. if (!capability.overrideMimeType) {
  109931. var mimeType = self.rawHeaders['mime-type']
  109932. if (mimeType) {
  109933. var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
  109934. if (charsetMatch) {
  109935. self._charset = charsetMatch[1].toLowerCase()
  109936. }
  109937. }
  109938. if (!self._charset)
  109939. self._charset = 'utf-8' // best guess
  109940. }
  109941. }
  109942. }
  109943. inherits(IncomingMessage, stream.Readable)
  109944. IncomingMessage.prototype._read = function () {
  109945. var self = this
  109946. var resolve = self._resumeFetch
  109947. if (resolve) {
  109948. self._resumeFetch = null
  109949. resolve()
  109950. }
  109951. }
  109952. IncomingMessage.prototype._onXHRProgress = function () {
  109953. var self = this
  109954. var xhr = self._xhr
  109955. var response = null
  109956. switch (self._mode) {
  109957. case 'text':
  109958. response = xhr.responseText
  109959. if (response.length > self._pos) {
  109960. var newData = response.substr(self._pos)
  109961. if (self._charset === 'x-user-defined') {
  109962. var buffer = Buffer.alloc(newData.length)
  109963. for (var i = 0; i < newData.length; i++)
  109964. buffer[i] = newData.charCodeAt(i) & 0xff
  109965. self.push(buffer)
  109966. } else {
  109967. self.push(newData, self._charset)
  109968. }
  109969. self._pos = response.length
  109970. }
  109971. break
  109972. case 'arraybuffer':
  109973. if (xhr.readyState !== rStates.DONE || !xhr.response)
  109974. break
  109975. response = xhr.response
  109976. self.push(Buffer.from(new Uint8Array(response)))
  109977. break
  109978. case 'moz-chunked-arraybuffer': // take whole
  109979. response = xhr.response
  109980. if (xhr.readyState !== rStates.LOADING || !response)
  109981. break
  109982. self.push(Buffer.from(new Uint8Array(response)))
  109983. break
  109984. case 'ms-stream':
  109985. response = xhr.response
  109986. if (xhr.readyState !== rStates.LOADING)
  109987. break
  109988. var reader = new global.MSStreamReader()
  109989. reader.onprogress = function () {
  109990. if (reader.result.byteLength > self._pos) {
  109991. self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos))))
  109992. self._pos = reader.result.byteLength
  109993. }
  109994. }
  109995. reader.onload = function () {
  109996. self.push(null)
  109997. }
  109998. // reader.onerror = ??? // TODO: this
  109999. reader.readAsArrayBuffer(response)
  110000. break
  110001. }
  110002. // The ms-stream case handles end separately in reader.onload()
  110003. if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
  110004. self.push(null)
  110005. }
  110006. }
  110007. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
  110008. },{"./capability":613,"_process":525,"buffer":193,"inherits":320,"readable-stream":630}],616:[function(require,module,exports){
  110009. arguments[4][172][0].apply(exports,arguments)
  110010. },{"dup":172}],617:[function(require,module,exports){
  110011. arguments[4][173][0].apply(exports,arguments)
  110012. },{"./_stream_readable":619,"./_stream_writable":621,"_process":525,"dup":173,"inherits":320}],618:[function(require,module,exports){
  110013. arguments[4][174][0].apply(exports,arguments)
  110014. },{"./_stream_transform":620,"dup":174,"inherits":320}],619:[function(require,module,exports){
  110015. arguments[4][175][0].apply(exports,arguments)
  110016. },{"../errors":616,"./_stream_duplex":617,"./internal/streams/async_iterator":622,"./internal/streams/buffer_list":623,"./internal/streams/destroy":624,"./internal/streams/from":626,"./internal/streams/state":628,"./internal/streams/stream":629,"_process":525,"buffer":193,"dup":175,"events":247,"inherits":320,"string_decoder/":631,"util":144}],620:[function(require,module,exports){
  110017. arguments[4][176][0].apply(exports,arguments)
  110018. },{"../errors":616,"./_stream_duplex":617,"dup":176,"inherits":320}],621:[function(require,module,exports){
  110019. arguments[4][177][0].apply(exports,arguments)
  110020. },{"../errors":616,"./_stream_duplex":617,"./internal/streams/destroy":624,"./internal/streams/state":628,"./internal/streams/stream":629,"_process":525,"buffer":193,"dup":177,"inherits":320,"util-deprecate":655}],622:[function(require,module,exports){
  110021. arguments[4][178][0].apply(exports,arguments)
  110022. },{"./end-of-stream":625,"_process":525,"dup":178}],623:[function(require,module,exports){
  110023. arguments[4][179][0].apply(exports,arguments)
  110024. },{"buffer":193,"dup":179,"util":144}],624:[function(require,module,exports){
  110025. arguments[4][180][0].apply(exports,arguments)
  110026. },{"_process":525,"dup":180}],625:[function(require,module,exports){
  110027. arguments[4][181][0].apply(exports,arguments)
  110028. },{"../../../errors":616,"dup":181}],626:[function(require,module,exports){
  110029. arguments[4][182][0].apply(exports,arguments)
  110030. },{"dup":182}],627:[function(require,module,exports){
  110031. arguments[4][183][0].apply(exports,arguments)
  110032. },{"../../../errors":616,"./end-of-stream":625,"dup":183}],628:[function(require,module,exports){
  110033. arguments[4][184][0].apply(exports,arguments)
  110034. },{"../../../errors":616,"dup":184}],629:[function(require,module,exports){
  110035. arguments[4][185][0].apply(exports,arguments)
  110036. },{"dup":185,"events":247}],630:[function(require,module,exports){
  110037. arguments[4][186][0].apply(exports,arguments)
  110038. },{"./lib/_stream_duplex.js":617,"./lib/_stream_passthrough.js":618,"./lib/_stream_readable.js":619,"./lib/_stream_transform.js":620,"./lib/_stream_writable.js":621,"./lib/internal/streams/end-of-stream.js":625,"./lib/internal/streams/pipeline.js":627,"dup":186}],631:[function(require,module,exports){
  110039. // Copyright Joyent, Inc. and other Node contributors.
  110040. //
  110041. // Permission is hereby granted, free of charge, to any person obtaining a
  110042. // copy of this software and associated documentation files (the
  110043. // "Software"), to deal in the Software without restriction, including
  110044. // without limitation the rights to use, copy, modify, merge, publish,
  110045. // distribute, sublicense, and/or sell copies of the Software, and to permit
  110046. // persons to whom the Software is furnished to do so, subject to the
  110047. // following conditions:
  110048. //
  110049. // The above copyright notice and this permission notice shall be included
  110050. // in all copies or substantial portions of the Software.
  110051. //
  110052. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  110053. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  110054. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  110055. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  110056. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  110057. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  110058. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  110059. 'use strict';
  110060. /*<replacement>*/
  110061. var Buffer = require('safe-buffer').Buffer;
  110062. /*</replacement>*/
  110063. var isEncoding = Buffer.isEncoding || function (encoding) {
  110064. encoding = '' + encoding;
  110065. switch (encoding && encoding.toLowerCase()) {
  110066. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  110067. return true;
  110068. default:
  110069. return false;
  110070. }
  110071. };
  110072. function _normalizeEncoding(enc) {
  110073. if (!enc) return 'utf8';
  110074. var retried;
  110075. while (true) {
  110076. switch (enc) {
  110077. case 'utf8':
  110078. case 'utf-8':
  110079. return 'utf8';
  110080. case 'ucs2':
  110081. case 'ucs-2':
  110082. case 'utf16le':
  110083. case 'utf-16le':
  110084. return 'utf16le';
  110085. case 'latin1':
  110086. case 'binary':
  110087. return 'latin1';
  110088. case 'base64':
  110089. case 'ascii':
  110090. case 'hex':
  110091. return enc;
  110092. default:
  110093. if (retried) return; // undefined
  110094. enc = ('' + enc).toLowerCase();
  110095. retried = true;
  110096. }
  110097. }
  110098. };
  110099. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  110100. // modules monkey-patch it to support additional encodings
  110101. function normalizeEncoding(enc) {
  110102. var nenc = _normalizeEncoding(enc);
  110103. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  110104. return nenc || enc;
  110105. }
  110106. // StringDecoder provides an interface for efficiently splitting a series of
  110107. // buffers into a series of JS strings without breaking apart multi-byte
  110108. // characters.
  110109. exports.StringDecoder = StringDecoder;
  110110. function StringDecoder(encoding) {
  110111. this.encoding = normalizeEncoding(encoding);
  110112. var nb;
  110113. switch (this.encoding) {
  110114. case 'utf16le':
  110115. this.text = utf16Text;
  110116. this.end = utf16End;
  110117. nb = 4;
  110118. break;
  110119. case 'utf8':
  110120. this.fillLast = utf8FillLast;
  110121. nb = 4;
  110122. break;
  110123. case 'base64':
  110124. this.text = base64Text;
  110125. this.end = base64End;
  110126. nb = 3;
  110127. break;
  110128. default:
  110129. this.write = simpleWrite;
  110130. this.end = simpleEnd;
  110131. return;
  110132. }
  110133. this.lastNeed = 0;
  110134. this.lastTotal = 0;
  110135. this.lastChar = Buffer.allocUnsafe(nb);
  110136. }
  110137. StringDecoder.prototype.write = function (buf) {
  110138. if (buf.length === 0) return '';
  110139. var r;
  110140. var i;
  110141. if (this.lastNeed) {
  110142. r = this.fillLast(buf);
  110143. if (r === undefined) return '';
  110144. i = this.lastNeed;
  110145. this.lastNeed = 0;
  110146. } else {
  110147. i = 0;
  110148. }
  110149. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  110150. return r || '';
  110151. };
  110152. StringDecoder.prototype.end = utf8End;
  110153. // Returns only complete characters in a Buffer
  110154. StringDecoder.prototype.text = utf8Text;
  110155. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  110156. StringDecoder.prototype.fillLast = function (buf) {
  110157. if (this.lastNeed <= buf.length) {
  110158. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  110159. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  110160. }
  110161. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  110162. this.lastNeed -= buf.length;
  110163. };
  110164. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  110165. // continuation byte. If an invalid byte is detected, -2 is returned.
  110166. function utf8CheckByte(byte) {
  110167. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  110168. return byte >> 6 === 0x02 ? -1 : -2;
  110169. }
  110170. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  110171. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  110172. // needed to complete the UTF-8 character (if applicable) are returned.
  110173. function utf8CheckIncomplete(self, buf, i) {
  110174. var j = buf.length - 1;
  110175. if (j < i) return 0;
  110176. var nb = utf8CheckByte(buf[j]);
  110177. if (nb >= 0) {
  110178. if (nb > 0) self.lastNeed = nb - 1;
  110179. return nb;
  110180. }
  110181. if (--j < i || nb === -2) return 0;
  110182. nb = utf8CheckByte(buf[j]);
  110183. if (nb >= 0) {
  110184. if (nb > 0) self.lastNeed = nb - 2;
  110185. return nb;
  110186. }
  110187. if (--j < i || nb === -2) return 0;
  110188. nb = utf8CheckByte(buf[j]);
  110189. if (nb >= 0) {
  110190. if (nb > 0) {
  110191. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  110192. }
  110193. return nb;
  110194. }
  110195. return 0;
  110196. }
  110197. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  110198. // needed or are available. If we see a non-continuation byte where we expect
  110199. // one, we "replace" the validated continuation bytes we've seen so far with
  110200. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  110201. // behavior. The continuation byte check is included three times in the case
  110202. // where all of the continuation bytes for a character exist in the same buffer.
  110203. // It is also done this way as a slight performance increase instead of using a
  110204. // loop.
  110205. function utf8CheckExtraBytes(self, buf, p) {
  110206. if ((buf[0] & 0xC0) !== 0x80) {
  110207. self.lastNeed = 0;
  110208. return '\ufffd';
  110209. }
  110210. if (self.lastNeed > 1 && buf.length > 1) {
  110211. if ((buf[1] & 0xC0) !== 0x80) {
  110212. self.lastNeed = 1;
  110213. return '\ufffd';
  110214. }
  110215. if (self.lastNeed > 2 && buf.length > 2) {
  110216. if ((buf[2] & 0xC0) !== 0x80) {
  110217. self.lastNeed = 2;
  110218. return '\ufffd';
  110219. }
  110220. }
  110221. }
  110222. }
  110223. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  110224. function utf8FillLast(buf) {
  110225. var p = this.lastTotal - this.lastNeed;
  110226. var r = utf8CheckExtraBytes(this, buf, p);
  110227. if (r !== undefined) return r;
  110228. if (this.lastNeed <= buf.length) {
  110229. buf.copy(this.lastChar, p, 0, this.lastNeed);
  110230. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  110231. }
  110232. buf.copy(this.lastChar, p, 0, buf.length);
  110233. this.lastNeed -= buf.length;
  110234. }
  110235. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  110236. // partial character, the character's bytes are buffered until the required
  110237. // number of bytes are available.
  110238. function utf8Text(buf, i) {
  110239. var total = utf8CheckIncomplete(this, buf, i);
  110240. if (!this.lastNeed) return buf.toString('utf8', i);
  110241. this.lastTotal = total;
  110242. var end = buf.length - (total - this.lastNeed);
  110243. buf.copy(this.lastChar, 0, end);
  110244. return buf.toString('utf8', i, end);
  110245. }
  110246. // For UTF-8, a replacement character is added when ending on a partial
  110247. // character.
  110248. function utf8End(buf) {
  110249. var r = buf && buf.length ? this.write(buf) : '';
  110250. if (this.lastNeed) return r + '\ufffd';
  110251. return r;
  110252. }
  110253. // UTF-16LE typically needs two bytes per character, but even if we have an even
  110254. // number of bytes available, we need to check if we end on a leading/high
  110255. // surrogate. In that case, we need to wait for the next two bytes in order to
  110256. // decode the last character properly.
  110257. function utf16Text(buf, i) {
  110258. if ((buf.length - i) % 2 === 0) {
  110259. var r = buf.toString('utf16le', i);
  110260. if (r) {
  110261. var c = r.charCodeAt(r.length - 1);
  110262. if (c >= 0xD800 && c <= 0xDBFF) {
  110263. this.lastNeed = 2;
  110264. this.lastTotal = 4;
  110265. this.lastChar[0] = buf[buf.length - 2];
  110266. this.lastChar[1] = buf[buf.length - 1];
  110267. return r.slice(0, -1);
  110268. }
  110269. }
  110270. return r;
  110271. }
  110272. this.lastNeed = 1;
  110273. this.lastTotal = 2;
  110274. this.lastChar[0] = buf[buf.length - 1];
  110275. return buf.toString('utf16le', i, buf.length - 1);
  110276. }
  110277. // For UTF-16LE we do not explicitly append special replacement characters if we
  110278. // end on a partial character, we simply let v8 handle that.
  110279. function utf16End(buf) {
  110280. var r = buf && buf.length ? this.write(buf) : '';
  110281. if (this.lastNeed) {
  110282. var end = this.lastTotal - this.lastNeed;
  110283. return r + this.lastChar.toString('utf16le', 0, end);
  110284. }
  110285. return r;
  110286. }
  110287. function base64Text(buf, i) {
  110288. var n = (buf.length - i) % 3;
  110289. if (n === 0) return buf.toString('base64', i);
  110290. this.lastNeed = 3 - n;
  110291. this.lastTotal = 3;
  110292. if (n === 1) {
  110293. this.lastChar[0] = buf[buf.length - 1];
  110294. } else {
  110295. this.lastChar[0] = buf[buf.length - 2];
  110296. this.lastChar[1] = buf[buf.length - 1];
  110297. }
  110298. return buf.toString('base64', i, buf.length - n);
  110299. }
  110300. function base64End(buf) {
  110301. var r = buf && buf.length ? this.write(buf) : '';
  110302. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  110303. return r;
  110304. }
  110305. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  110306. function simpleWrite(buf) {
  110307. return buf.toString(this.encoding);
  110308. }
  110309. function simpleEnd(buf) {
  110310. return buf && buf.length ? this.write(buf) : '';
  110311. }
  110312. },{"safe-buffer":561}],632:[function(require,module,exports){
  110313. "use strict";
  110314. Object.defineProperty(exports, "__esModule", { value: true });
  110315. const TimeoutError_1 = require("./TimeoutError");
  110316. const utils_1 = require("./utils");
  110317. class PendingOperation {
  110318. constructor(timeoutMillis) {
  110319. this.timeoutMillis = timeoutMillis;
  110320. this.deferred = utils_1.defer();
  110321. this.possibleTimeoutCause = null;
  110322. this.promise = timeout(this.deferred.promise, timeoutMillis).catch(err => {
  110323. if (err instanceof TimeoutError_1.TimeoutError) {
  110324. if (this.possibleTimeoutCause) {
  110325. err = new TimeoutError_1.TimeoutError(this.possibleTimeoutCause.message);
  110326. }
  110327. else {
  110328. err = new TimeoutError_1.TimeoutError('operation timed out for an unknown reason');
  110329. }
  110330. }
  110331. return Promise.reject(err);
  110332. });
  110333. }
  110334. abort() {
  110335. this.reject(new Error('aborted'));
  110336. }
  110337. reject(err) {
  110338. this.deferred.reject(err);
  110339. }
  110340. resolve(value) {
  110341. this.deferred.resolve(value);
  110342. }
  110343. }
  110344. exports.PendingOperation = PendingOperation;
  110345. function timeout(promise, time) {
  110346. return new Promise((resolve, reject) => {
  110347. const timeoutHandle = setTimeout(() => reject(new TimeoutError_1.TimeoutError()), time);
  110348. promise
  110349. .then(result => {
  110350. clearTimeout(timeoutHandle);
  110351. resolve(result);
  110352. })
  110353. .catch(err => {
  110354. clearTimeout(timeoutHandle);
  110355. reject(err);
  110356. });
  110357. });
  110358. }
  110359. },{"./TimeoutError":636,"./utils":638}],633:[function(require,module,exports){
  110360. "use strict";
  110361. Object.defineProperty(exports, "__esModule", { value: true });
  110362. const PendingOperation_1 = require("./PendingOperation");
  110363. const Resource_1 = require("./Resource");
  110364. const utils_1 = require("./utils");
  110365. class Pool {
  110366. constructor(opt) {
  110367. this.destroyed = false;
  110368. opt = opt || {};
  110369. if (!opt.create) {
  110370. throw new Error('Tarn: opt.create function most be provided');
  110371. }
  110372. if (!opt.destroy) {
  110373. throw new Error('Tarn: opt.destroy function most be provided');
  110374. }
  110375. if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) {
  110376. throw new Error('Tarn: opt.min must be an integer >= 0');
  110377. }
  110378. if (typeof opt.max !== 'number' || opt.max <= 0 || opt.max !== Math.round(opt.max)) {
  110379. throw new Error('Tarn: opt.max must be an integer > 0');
  110380. }
  110381. if (opt.min > opt.max) {
  110382. throw new Error('Tarn: opt.max is smaller than opt.min');
  110383. }
  110384. if (!utils_1.checkOptionalTime(opt.acquireTimeoutMillis)) {
  110385. throw new Error('Tarn: invalid opt.acquireTimeoutMillis ' + JSON.stringify(opt.acquireTimeoutMillis));
  110386. }
  110387. if (!utils_1.checkOptionalTime(opt.createTimeoutMillis)) {
  110388. throw new Error('Tarn: invalid opt.createTimeoutMillis ' + JSON.stringify(opt.createTimeoutMillis));
  110389. }
  110390. if (!utils_1.checkOptionalTime(opt.destroyTimeoutMillis)) {
  110391. throw new Error('Tarn: invalid opt.destroyTimeoutMillis ' + JSON.stringify(opt.destroyTimeoutMillis));
  110392. }
  110393. if (!utils_1.checkOptionalTime(opt.idleTimeoutMillis)) {
  110394. throw new Error('Tarn: invalid opt.idleTimeoutMillis ' + JSON.stringify(opt.idleTimeoutMillis));
  110395. }
  110396. if (!utils_1.checkOptionalTime(opt.reapIntervalMillis)) {
  110397. throw new Error('Tarn: invalid opt.reapIntervalMillis ' + JSON.stringify(opt.reapIntervalMillis));
  110398. }
  110399. if (!utils_1.checkOptionalTime(opt.createRetryIntervalMillis)) {
  110400. throw new Error('Tarn: invalid opt.createRetryIntervalMillis ' +
  110401. JSON.stringify(opt.createRetryIntervalMillis));
  110402. }
  110403. this.creator = opt.create;
  110404. this.destroyer = opt.destroy;
  110405. this.validate = typeof opt.validate === 'function' ? opt.validate : () => true;
  110406. this.log = opt.log || (() => { });
  110407. this.acquireTimeoutMillis = opt.acquireTimeoutMillis || 30000;
  110408. this.createTimeoutMillis = opt.createTimeoutMillis || 30000;
  110409. this.destroyTimeoutMillis = opt.destroyTimeoutMillis || 5000;
  110410. this.idleTimeoutMillis = opt.idleTimeoutMillis || 30000;
  110411. this.reapIntervalMillis = opt.reapIntervalMillis || 1000;
  110412. this.createRetryIntervalMillis = opt.createRetryIntervalMillis || 200;
  110413. this.propagateCreateError = !!opt.propagateCreateError;
  110414. this.min = opt.min;
  110415. this.max = opt.max;
  110416. this.used = [];
  110417. this.free = [];
  110418. this.pendingCreates = [];
  110419. this.pendingAcquires = [];
  110420. this.destroyed = false;
  110421. this.interval = null;
  110422. }
  110423. numUsed() {
  110424. return this.used.length;
  110425. }
  110426. numFree() {
  110427. return this.free.length;
  110428. }
  110429. numPendingAcquires() {
  110430. return this.pendingAcquires.length;
  110431. }
  110432. numPendingCreates() {
  110433. return this.pendingCreates.length;
  110434. }
  110435. acquire() {
  110436. const pendingAcquire = new PendingOperation_1.PendingOperation(this.acquireTimeoutMillis);
  110437. this.pendingAcquires.push(pendingAcquire);
  110438. // If the acquire fails for whatever reason
  110439. // remove it from the pending queue.
  110440. pendingAcquire.promise = pendingAcquire.promise.catch(err => {
  110441. remove(this.pendingAcquires, pendingAcquire);
  110442. return Promise.reject(err);
  110443. });
  110444. this._tryAcquireOrCreate();
  110445. return pendingAcquire;
  110446. }
  110447. release(resource) {
  110448. for (let i = 0, l = this.used.length; i < l; ++i) {
  110449. const used = this.used[i];
  110450. if (used.resource === resource) {
  110451. this.used.splice(i, 1);
  110452. this.free.push(used.resolve());
  110453. this._tryAcquireOrCreate();
  110454. return true;
  110455. }
  110456. }
  110457. return false;
  110458. }
  110459. isEmpty() {
  110460. return ([this.numFree(), this.numUsed(), this.numPendingAcquires(), this.numPendingCreates()].reduce((total, value) => total + value) === 0);
  110461. }
  110462. check() {
  110463. const timestamp = utils_1.now();
  110464. const newFree = [];
  110465. const minKeep = this.min - this.used.length;
  110466. const maxDestroy = this.free.length - minKeep;
  110467. let numDestroyed = 0;
  110468. this.free.forEach(free => {
  110469. if (utils_1.duration(timestamp, free.timestamp) > this.idleTimeoutMillis &&
  110470. numDestroyed < maxDestroy) {
  110471. numDestroyed++;
  110472. this._destroy(free.resource);
  110473. }
  110474. else {
  110475. newFree.push(free);
  110476. }
  110477. });
  110478. this.free = newFree;
  110479. // Pool is completely empty, stop reaping.
  110480. // Next .acquire will start reaping interval again.
  110481. if (this.isEmpty()) {
  110482. this._stopReaping();
  110483. }
  110484. }
  110485. destroy() {
  110486. this._stopReaping();
  110487. this.destroyed = true;
  110488. // First wait for all the pending creates get ready.
  110489. return utils_1.reflect(Promise.all(this.pendingCreates.map(create => utils_1.reflect(create.promise)))
  110490. .then(() => {
  110491. // Wait for all the used resources to be freed.
  110492. return Promise.all(this.used.map(used => utils_1.reflect(used.promise)));
  110493. })
  110494. .then(() => {
  110495. // Abort all pending acquires.
  110496. return Promise.all(this.pendingAcquires.map(acquire => {
  110497. acquire.abort();
  110498. return utils_1.reflect(acquire.promise);
  110499. }));
  110500. })
  110501. .then(() => {
  110502. // Now we can destroy all the freed resources.
  110503. return Promise.all(this.free.map(free => utils_1.reflect(this._destroy(free.resource))));
  110504. })
  110505. .then(() => {
  110506. this.free = [];
  110507. this.pendingAcquires = [];
  110508. }));
  110509. }
  110510. _tryAcquireOrCreate() {
  110511. if (this.destroyed) {
  110512. return;
  110513. }
  110514. if (this._hasFreeResources()) {
  110515. this._doAcquire();
  110516. }
  110517. else if (this._shouldCreateMoreResources()) {
  110518. this._doCreate();
  110519. }
  110520. }
  110521. _hasFreeResources() {
  110522. return this.free.length > 0;
  110523. }
  110524. _doAcquire() {
  110525. let didDestroyResources = false;
  110526. while (this._canAcquire()) {
  110527. const pendingAcquire = this.pendingAcquires[0];
  110528. const free = this.free[this.free.length - 1];
  110529. if (!this._validateResource(free.resource)) {
  110530. this.free.pop();
  110531. this._destroy(free.resource);
  110532. didDestroyResources = true;
  110533. continue;
  110534. }
  110535. this.pendingAcquires.shift();
  110536. this.free.pop();
  110537. this.used.push(free.resolve());
  110538. //At least one active resource, start reaping
  110539. this._startReaping();
  110540. pendingAcquire.resolve(free.resource);
  110541. }
  110542. // If we destroyed invalid resources, we may need to create new ones.
  110543. if (didDestroyResources) {
  110544. this._tryAcquireOrCreate();
  110545. }
  110546. }
  110547. _canAcquire() {
  110548. return this.free.length > 0 && this.pendingAcquires.length > 0;
  110549. }
  110550. _validateResource(resource) {
  110551. try {
  110552. return !!this.validate(resource);
  110553. }
  110554. catch (err) {
  110555. // There's nothing we can do here but log the error. This would otherwise
  110556. // leak out as an unhandled exception.
  110557. this.log('Tarn: resource validator threw an exception ' + err.stack, 'warn');
  110558. return false;
  110559. }
  110560. }
  110561. _shouldCreateMoreResources() {
  110562. return (this.used.length + this.pendingCreates.length < this.max &&
  110563. this.pendingCreates.length < this.pendingAcquires.length);
  110564. }
  110565. _doCreate() {
  110566. const pendingAcquiresBeforeCreate = this.pendingAcquires.slice();
  110567. const pendingCreate = this._create();
  110568. pendingCreate.promise
  110569. .then(() => {
  110570. // Not returned on purpose.
  110571. this._tryAcquireOrCreate();
  110572. return null;
  110573. })
  110574. .catch(err => {
  110575. if (this.propagateCreateError && this.pendingAcquires.length !== 0) {
  110576. // If propagateCreateError is true, we don't retry the create
  110577. // but reject the first pending acquire immediately. Intentionally
  110578. // use `this.pendingAcquires` instead of `pendingAcquiresBeforeCreate`
  110579. // in case some acquires in pendingAcquiresBeforeCreate have already
  110580. // been resolved.
  110581. this.pendingAcquires[0].reject(err);
  110582. }
  110583. // Save the create error to all pending acquires so that we can use it
  110584. // as the error to reject the acquire if it times out.
  110585. pendingAcquiresBeforeCreate.forEach(pendingAcquire => {
  110586. pendingAcquire.possibleTimeoutCause = err;
  110587. });
  110588. // Not returned on purpose.
  110589. utils_1.delay(this.createRetryIntervalMillis).then(() => this._tryAcquireOrCreate());
  110590. });
  110591. }
  110592. _create() {
  110593. const pendingCreate = new PendingOperation_1.PendingOperation(this.createTimeoutMillis);
  110594. this.pendingCreates.push(pendingCreate);
  110595. callbackOrPromise(this.creator)
  110596. .then(resource => {
  110597. remove(this.pendingCreates, pendingCreate);
  110598. this.free.push(new Resource_1.Resource(resource));
  110599. // Not returned on purpose.
  110600. pendingCreate.resolve(resource);
  110601. return null;
  110602. })
  110603. .catch(err => {
  110604. remove(this.pendingCreates, pendingCreate);
  110605. // Not returned on purpose.
  110606. pendingCreate.reject(err);
  110607. return null;
  110608. });
  110609. return pendingCreate;
  110610. }
  110611. _destroy(resource) {
  110612. try {
  110613. // this.destroyer can be both synchronous and asynchronous.
  110614. // When it's synchronous, errors are handled by the try/catch
  110615. // When it's asynchronous, errors are handled by .catch()
  110616. const retVal = this.destroyer(resource);
  110617. if (retVal && retVal.then && retVal.catch) {
  110618. const pendingDestroy = new PendingOperation_1.PendingOperation(this.destroyTimeoutMillis);
  110619. retVal
  110620. .then(() => {
  110621. pendingDestroy.resolve(resource);
  110622. })
  110623. .catch((err) => {
  110624. pendingDestroy.reject(err);
  110625. });
  110626. // In case of an error there's nothing we can do here but log it.
  110627. return pendingDestroy.promise.catch(err => this._logError(err));
  110628. }
  110629. return Promise.resolve(retVal);
  110630. }
  110631. catch (err) {
  110632. // There's nothing we can do here but log the error. This would otherwise
  110633. // leak out as an unhandled exception.
  110634. this._logError(err);
  110635. return Promise.resolve();
  110636. }
  110637. }
  110638. _logError(err) {
  110639. this.log('Tarn: resource destroyer threw an exception ' + err.stack, 'warn');
  110640. }
  110641. _startReaping() {
  110642. if (!this.interval) {
  110643. this.interval = setInterval(() => this.check(), this.reapIntervalMillis);
  110644. }
  110645. }
  110646. _stopReaping() {
  110647. if (this.interval !== null) {
  110648. clearInterval(this.interval);
  110649. }
  110650. this.interval = null;
  110651. }
  110652. }
  110653. exports.Pool = Pool;
  110654. function remove(arr, item) {
  110655. var idx = arr.indexOf(item);
  110656. if (idx === -1) {
  110657. return false;
  110658. }
  110659. else {
  110660. arr.splice(idx, 1);
  110661. return true;
  110662. }
  110663. }
  110664. function callbackOrPromise(func) {
  110665. return new Promise((resolve, reject) => {
  110666. const callback = (err, resource) => {
  110667. if (err) {
  110668. reject(err);
  110669. }
  110670. else {
  110671. resolve(resource);
  110672. }
  110673. };
  110674. utils_1.tryPromise(() => func(callback))
  110675. .then(res => {
  110676. // If the result is falsy, we assume that the callback will
  110677. // be called instead of interpreting the falsy value as a
  110678. // result value.
  110679. if (res) {
  110680. resolve(res);
  110681. }
  110682. })
  110683. .catch(err => {
  110684. reject(err);
  110685. });
  110686. });
  110687. }
  110688. },{"./PendingOperation":632,"./Resource":635,"./utils":638}],634:[function(require,module,exports){
  110689. "use strict";
  110690. Object.defineProperty(exports, "__esModule", { value: true });
  110691. class PromiseInspection {
  110692. constructor(args) {
  110693. this._value = args.value;
  110694. this._error = args.error;
  110695. }
  110696. value() {
  110697. return this._value;
  110698. }
  110699. reason() {
  110700. return this._error;
  110701. }
  110702. isRejected() {
  110703. return !!this._error;
  110704. }
  110705. isFulfilled() {
  110706. return !!this._value;
  110707. }
  110708. }
  110709. exports.PromiseInspection = PromiseInspection;
  110710. },{}],635:[function(require,module,exports){
  110711. "use strict";
  110712. Object.defineProperty(exports, "__esModule", { value: true });
  110713. const utils_1 = require("./utils");
  110714. class Resource {
  110715. constructor(resource) {
  110716. this.resource = resource;
  110717. this.resource = resource;
  110718. this.timestamp = utils_1.now();
  110719. this.deferred = utils_1.defer();
  110720. }
  110721. get promise() {
  110722. return this.deferred.promise;
  110723. }
  110724. resolve() {
  110725. this.deferred.resolve(undefined);
  110726. return new Resource(this.resource);
  110727. }
  110728. }
  110729. exports.Resource = Resource;
  110730. },{"./utils":638}],636:[function(require,module,exports){
  110731. "use strict";
  110732. Object.defineProperty(exports, "__esModule", { value: true });
  110733. class TimeoutError extends Error {
  110734. }
  110735. exports.TimeoutError = TimeoutError;
  110736. },{}],637:[function(require,module,exports){
  110737. "use strict";
  110738. Object.defineProperty(exports, "__esModule", { value: true });
  110739. const Pool_1 = require("./Pool");
  110740. exports.Pool = Pool_1.Pool;
  110741. const TimeoutError_1 = require("./TimeoutError");
  110742. exports.TimeoutError = TimeoutError_1.TimeoutError;
  110743. module.exports = {
  110744. Pool: Pool_1.Pool,
  110745. TimeoutError: TimeoutError_1.TimeoutError
  110746. };
  110747. },{"./Pool":633,"./TimeoutError":636}],638:[function(require,module,exports){
  110748. "use strict";
  110749. Object.defineProperty(exports, "__esModule", { value: true });
  110750. const PromiseInspection_1 = require("./PromiseInspection");
  110751. function defer() {
  110752. let resolve = null;
  110753. let reject = null;
  110754. const promise = new Promise((resolver, rejecter) => {
  110755. resolve = resolver;
  110756. reject = rejecter;
  110757. });
  110758. return {
  110759. promise,
  110760. resolve,
  110761. reject
  110762. };
  110763. }
  110764. exports.defer = defer;
  110765. function now() {
  110766. return Date.now();
  110767. }
  110768. exports.now = now;
  110769. function duration(t1, t2) {
  110770. return Math.abs(t2 - t1);
  110771. }
  110772. exports.duration = duration;
  110773. function checkOptionalTime(time) {
  110774. if (typeof time === 'undefined') {
  110775. return true;
  110776. }
  110777. return checkRequiredTime(time);
  110778. }
  110779. exports.checkOptionalTime = checkOptionalTime;
  110780. function checkRequiredTime(time) {
  110781. return typeof time === 'number' && time === Math.round(time) && time > 0;
  110782. }
  110783. exports.checkRequiredTime = checkRequiredTime;
  110784. function delay(millis) {
  110785. return new Promise(resolve => setTimeout(resolve, millis));
  110786. }
  110787. exports.delay = delay;
  110788. function reflect(promise) {
  110789. return promise
  110790. .then(value => {
  110791. return new PromiseInspection_1.PromiseInspection({ value });
  110792. })
  110793. .catch(error => {
  110794. return new PromiseInspection_1.PromiseInspection({ error });
  110795. });
  110796. }
  110797. exports.reflect = reflect;
  110798. function tryPromise(cb) {
  110799. try {
  110800. const result = cb();
  110801. return Promise.resolve(result);
  110802. }
  110803. catch (err) {
  110804. return Promise.reject(err);
  110805. }
  110806. }
  110807. exports.tryPromise = tryPromise;
  110808. },{"./PromiseInspection":634}],639:[function(require,module,exports){
  110809. (function (setImmediate,clearImmediate){(function (){
  110810. var nextTick = require('process/browser.js').nextTick;
  110811. var apply = Function.prototype.apply;
  110812. var slice = Array.prototype.slice;
  110813. var immediateIds = {};
  110814. var nextImmediateId = 0;
  110815. // DOM APIs, for completeness
  110816. exports.setTimeout = function() {
  110817. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  110818. };
  110819. exports.setInterval = function() {
  110820. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  110821. };
  110822. exports.clearTimeout =
  110823. exports.clearInterval = function(timeout) { timeout.close(); };
  110824. function Timeout(id, clearFn) {
  110825. this._id = id;
  110826. this._clearFn = clearFn;
  110827. }
  110828. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  110829. Timeout.prototype.close = function() {
  110830. this._clearFn.call(window, this._id);
  110831. };
  110832. // Does not start the time, just sets up the members needed.
  110833. exports.enroll = function(item, msecs) {
  110834. clearTimeout(item._idleTimeoutId);
  110835. item._idleTimeout = msecs;
  110836. };
  110837. exports.unenroll = function(item) {
  110838. clearTimeout(item._idleTimeoutId);
  110839. item._idleTimeout = -1;
  110840. };
  110841. exports._unrefActive = exports.active = function(item) {
  110842. clearTimeout(item._idleTimeoutId);
  110843. var msecs = item._idleTimeout;
  110844. if (msecs >= 0) {
  110845. item._idleTimeoutId = setTimeout(function onTimeout() {
  110846. if (item._onTimeout)
  110847. item._onTimeout();
  110848. }, msecs);
  110849. }
  110850. };
  110851. // That's not how node.js implements it but the exposed api is the same.
  110852. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  110853. var id = nextImmediateId++;
  110854. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  110855. immediateIds[id] = true;
  110856. nextTick(function onNextTick() {
  110857. if (immediateIds[id]) {
  110858. // fn.call() is faster so we optimize for the common use-case
  110859. // @see http://jsperf.com/call-apply-segu
  110860. if (args) {
  110861. fn.apply(null, args);
  110862. } else {
  110863. fn.call(null);
  110864. }
  110865. // Prevent ids from leaking
  110866. exports.clearImmediate(id);
  110867. }
  110868. });
  110869. return id;
  110870. };
  110871. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  110872. delete immediateIds[id];
  110873. };
  110874. }).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  110875. },{"process/browser.js":525,"timers":639}],640:[function(require,module,exports){
  110876. /*!
  110877. * Copyright (c) 2015, Salesforce.com, Inc.
  110878. * All rights reserved.
  110879. *
  110880. * Redistribution and use in source and binary forms, with or without
  110881. * modification, are permitted provided that the following conditions are met:
  110882. *
  110883. * 1. Redistributions of source code must retain the above copyright notice,
  110884. * this list of conditions and the following disclaimer.
  110885. *
  110886. * 2. Redistributions in binary form must reproduce the above copyright notice,
  110887. * this list of conditions and the following disclaimer in the documentation
  110888. * and/or other materials provided with the distribution.
  110889. *
  110890. * 3. Neither the name of Salesforce.com nor the names of its contributors may
  110891. * be used to endorse or promote products derived from this software without
  110892. * specific prior written permission.
  110893. *
  110894. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  110895. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  110896. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  110897. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  110898. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  110899. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  110900. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  110901. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  110902. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  110903. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  110904. * POSSIBILITY OF SUCH DAMAGE.
  110905. */
  110906. 'use strict';
  110907. var net = require('net');
  110908. var urlParse = require('url').parse;
  110909. var util = require('util');
  110910. var pubsuffix = require('./pubsuffix-psl');
  110911. var Store = require('./store').Store;
  110912. var MemoryCookieStore = require('./memstore').MemoryCookieStore;
  110913. var pathMatch = require('./pathMatch').pathMatch;
  110914. var VERSION = require('./version');
  110915. var punycode;
  110916. try {
  110917. punycode = require('punycode');
  110918. } catch(e) {
  110919. console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization");
  110920. }
  110921. // From RFC6265 S4.1.1
  110922. // note that it excludes \x3B ";"
  110923. var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
  110924. var CONTROL_CHARS = /[\x00-\x1F]/;
  110925. // From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
  110926. // the "relaxed" mode, see:
  110927. // https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
  110928. var TERMINATORS = ['\n', '\r', '\0'];
  110929. // RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
  110930. // Note ';' is \x3B
  110931. var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
  110932. // date-time parsing constants (RFC6265 S5.1.1)
  110933. var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
  110934. var MONTH_TO_NUM = {
  110935. jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
  110936. jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
  110937. };
  110938. var NUM_TO_MONTH = [
  110939. 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
  110940. ];
  110941. var NUM_TO_DAY = [
  110942. 'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
  110943. ];
  110944. var MAX_TIME = 2147483647000; // 31-bit max
  110945. var MIN_TIME = 0; // 31-bit min
  110946. /*
  110947. * Parses a Natural number (i.e., non-negative integer) with either the
  110948. * <min>*<max>DIGIT ( non-digit *OCTET )
  110949. * or
  110950. * <min>*<max>DIGIT
  110951. * grammar (RFC6265 S5.1.1).
  110952. *
  110953. * The "trailingOK" boolean controls if the grammar accepts a
  110954. * "( non-digit *OCTET )" trailer.
  110955. */
  110956. function parseDigits(token, minDigits, maxDigits, trailingOK) {
  110957. var count = 0;
  110958. while (count < token.length) {
  110959. var c = token.charCodeAt(count);
  110960. // "non-digit = %x00-2F / %x3A-FF"
  110961. if (c <= 0x2F || c >= 0x3A) {
  110962. break;
  110963. }
  110964. count++;
  110965. }
  110966. // constrain to a minimum and maximum number of digits.
  110967. if (count < minDigits || count > maxDigits) {
  110968. return null;
  110969. }
  110970. if (!trailingOK && count != token.length) {
  110971. return null;
  110972. }
  110973. return parseInt(token.substr(0,count), 10);
  110974. }
  110975. function parseTime(token) {
  110976. var parts = token.split(':');
  110977. var result = [0,0,0];
  110978. /* RF6256 S5.1.1:
  110979. * time = hms-time ( non-digit *OCTET )
  110980. * hms-time = time-field ":" time-field ":" time-field
  110981. * time-field = 1*2DIGIT
  110982. */
  110983. if (parts.length !== 3) {
  110984. return null;
  110985. }
  110986. for (var i = 0; i < 3; i++) {
  110987. // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
  110988. // followed by "( non-digit *OCTET )" so therefore the last time-field can
  110989. // have a trailer
  110990. var trailingOK = (i == 2);
  110991. var num = parseDigits(parts[i], 1, 2, trailingOK);
  110992. if (num === null) {
  110993. return null;
  110994. }
  110995. result[i] = num;
  110996. }
  110997. return result;
  110998. }
  110999. function parseMonth(token) {
  111000. token = String(token).substr(0,3).toLowerCase();
  111001. var num = MONTH_TO_NUM[token];
  111002. return num >= 0 ? num : null;
  111003. }
  111004. /*
  111005. * RFC6265 S5.1.1 date parser (see RFC for full grammar)
  111006. */
  111007. function parseDate(str) {
  111008. if (!str) {
  111009. return;
  111010. }
  111011. /* RFC6265 S5.1.1:
  111012. * 2. Process each date-token sequentially in the order the date-tokens
  111013. * appear in the cookie-date
  111014. */
  111015. var tokens = str.split(DATE_DELIM);
  111016. if (!tokens) {
  111017. return;
  111018. }
  111019. var hour = null;
  111020. var minute = null;
  111021. var second = null;
  111022. var dayOfMonth = null;
  111023. var month = null;
  111024. var year = null;
  111025. for (var i=0; i<tokens.length; i++) {
  111026. var token = tokens[i].trim();
  111027. if (!token.length) {
  111028. continue;
  111029. }
  111030. var result;
  111031. /* 2.1. If the found-time flag is not set and the token matches the time
  111032. * production, set the found-time flag and set the hour- value,
  111033. * minute-value, and second-value to the numbers denoted by the digits in
  111034. * the date-token, respectively. Skip the remaining sub-steps and continue
  111035. * to the next date-token.
  111036. */
  111037. if (second === null) {
  111038. result = parseTime(token);
  111039. if (result) {
  111040. hour = result[0];
  111041. minute = result[1];
  111042. second = result[2];
  111043. continue;
  111044. }
  111045. }
  111046. /* 2.2. If the found-day-of-month flag is not set and the date-token matches
  111047. * the day-of-month production, set the found-day-of- month flag and set
  111048. * the day-of-month-value to the number denoted by the date-token. Skip
  111049. * the remaining sub-steps and continue to the next date-token.
  111050. */
  111051. if (dayOfMonth === null) {
  111052. // "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
  111053. result = parseDigits(token, 1, 2, true);
  111054. if (result !== null) {
  111055. dayOfMonth = result;
  111056. continue;
  111057. }
  111058. }
  111059. /* 2.3. If the found-month flag is not set and the date-token matches the
  111060. * month production, set the found-month flag and set the month-value to
  111061. * the month denoted by the date-token. Skip the remaining sub-steps and
  111062. * continue to the next date-token.
  111063. */
  111064. if (month === null) {
  111065. result = parseMonth(token);
  111066. if (result !== null) {
  111067. month = result;
  111068. continue;
  111069. }
  111070. }
  111071. /* 2.4. If the found-year flag is not set and the date-token matches the
  111072. * year production, set the found-year flag and set the year-value to the
  111073. * number denoted by the date-token. Skip the remaining sub-steps and
  111074. * continue to the next date-token.
  111075. */
  111076. if (year === null) {
  111077. // "year = 2*4DIGIT ( non-digit *OCTET )"
  111078. result = parseDigits(token, 2, 4, true);
  111079. if (result !== null) {
  111080. year = result;
  111081. /* From S5.1.1:
  111082. * 3. If the year-value is greater than or equal to 70 and less
  111083. * than or equal to 99, increment the year-value by 1900.
  111084. * 4. If the year-value is greater than or equal to 0 and less
  111085. * than or equal to 69, increment the year-value by 2000.
  111086. */
  111087. if (year >= 70 && year <= 99) {
  111088. year += 1900;
  111089. } else if (year >= 0 && year <= 69) {
  111090. year += 2000;
  111091. }
  111092. }
  111093. }
  111094. }
  111095. /* RFC 6265 S5.1.1
  111096. * "5. Abort these steps and fail to parse the cookie-date if:
  111097. * * at least one of the found-day-of-month, found-month, found-
  111098. * year, or found-time flags is not set,
  111099. * * the day-of-month-value is less than 1 or greater than 31,
  111100. * * the year-value is less than 1601,
  111101. * * the hour-value is greater than 23,
  111102. * * the minute-value is greater than 59, or
  111103. * * the second-value is greater than 59.
  111104. * (Note that leap seconds cannot be represented in this syntax.)"
  111105. *
  111106. * So, in order as above:
  111107. */
  111108. if (
  111109. dayOfMonth === null || month === null || year === null || second === null ||
  111110. dayOfMonth < 1 || dayOfMonth > 31 ||
  111111. year < 1601 ||
  111112. hour > 23 ||
  111113. minute > 59 ||
  111114. second > 59
  111115. ) {
  111116. return;
  111117. }
  111118. return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
  111119. }
  111120. function formatDate(date) {
  111121. var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
  111122. var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
  111123. var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
  111124. var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
  111125. return NUM_TO_DAY[date.getUTCDay()] + ', ' +
  111126. d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
  111127. h+':'+m+':'+s+' GMT';
  111128. }
  111129. // S5.1.2 Canonicalized Host Names
  111130. function canonicalDomain(str) {
  111131. if (str == null) {
  111132. return null;
  111133. }
  111134. str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
  111135. // convert to IDN if any non-ASCII characters
  111136. if (punycode && /[^\u0001-\u007f]/.test(str)) {
  111137. str = punycode.toASCII(str);
  111138. }
  111139. return str.toLowerCase();
  111140. }
  111141. // S5.1.3 Domain Matching
  111142. function domainMatch(str, domStr, canonicalize) {
  111143. if (str == null || domStr == null) {
  111144. return null;
  111145. }
  111146. if (canonicalize !== false) {
  111147. str = canonicalDomain(str);
  111148. domStr = canonicalDomain(domStr);
  111149. }
  111150. /*
  111151. * "The domain string and the string are identical. (Note that both the
  111152. * domain string and the string will have been canonicalized to lower case at
  111153. * this point)"
  111154. */
  111155. if (str == domStr) {
  111156. return true;
  111157. }
  111158. /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
  111159. /* "* The string is a host name (i.e., not an IP address)." */
  111160. if (net.isIP(str)) {
  111161. return false;
  111162. }
  111163. /* "* The domain string is a suffix of the string" */
  111164. var idx = str.indexOf(domStr);
  111165. if (idx <= 0) {
  111166. return false; // it's a non-match (-1) or prefix (0)
  111167. }
  111168. // e.g "a.b.c".indexOf("b.c") === 2
  111169. // 5 === 3+2
  111170. if (str.length !== domStr.length + idx) { // it's not a suffix
  111171. return false;
  111172. }
  111173. /* "* The last character of the string that is not included in the domain
  111174. * string is a %x2E (".") character." */
  111175. if (str.substr(idx-1,1) !== '.') {
  111176. return false;
  111177. }
  111178. return true;
  111179. }
  111180. // RFC6265 S5.1.4 Paths and Path-Match
  111181. /*
  111182. * "The user agent MUST use an algorithm equivalent to the following algorithm
  111183. * to compute the default-path of a cookie:"
  111184. *
  111185. * Assumption: the path (and not query part or absolute uri) is passed in.
  111186. */
  111187. function defaultPath(path) {
  111188. // "2. If the uri-path is empty or if the first character of the uri-path is not
  111189. // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
  111190. if (!path || path.substr(0,1) !== "/") {
  111191. return "/";
  111192. }
  111193. // "3. If the uri-path contains no more than one %x2F ("/") character, output
  111194. // %x2F ("/") and skip the remaining step."
  111195. if (path === "/") {
  111196. return path;
  111197. }
  111198. var rightSlash = path.lastIndexOf("/");
  111199. if (rightSlash === 0) {
  111200. return "/";
  111201. }
  111202. // "4. Output the characters of the uri-path from the first character up to,
  111203. // but not including, the right-most %x2F ("/")."
  111204. return path.slice(0, rightSlash);
  111205. }
  111206. function trimTerminator(str) {
  111207. for (var t = 0; t < TERMINATORS.length; t++) {
  111208. var terminatorIdx = str.indexOf(TERMINATORS[t]);
  111209. if (terminatorIdx !== -1) {
  111210. str = str.substr(0,terminatorIdx);
  111211. }
  111212. }
  111213. return str;
  111214. }
  111215. function parseCookiePair(cookiePair, looseMode) {
  111216. cookiePair = trimTerminator(cookiePair);
  111217. var firstEq = cookiePair.indexOf('=');
  111218. if (looseMode) {
  111219. if (firstEq === 0) { // '=' is immediately at start
  111220. cookiePair = cookiePair.substr(1);
  111221. firstEq = cookiePair.indexOf('='); // might still need to split on '='
  111222. }
  111223. } else { // non-loose mode
  111224. if (firstEq <= 0) { // no '=' or is at start
  111225. return; // needs to have non-empty "cookie-name"
  111226. }
  111227. }
  111228. var cookieName, cookieValue;
  111229. if (firstEq <= 0) {
  111230. cookieName = "";
  111231. cookieValue = cookiePair.trim();
  111232. } else {
  111233. cookieName = cookiePair.substr(0, firstEq).trim();
  111234. cookieValue = cookiePair.substr(firstEq+1).trim();
  111235. }
  111236. if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
  111237. return;
  111238. }
  111239. var c = new Cookie();
  111240. c.key = cookieName;
  111241. c.value = cookieValue;
  111242. return c;
  111243. }
  111244. function parse(str, options) {
  111245. if (!options || typeof options !== 'object') {
  111246. options = {};
  111247. }
  111248. str = str.trim();
  111249. // We use a regex to parse the "name-value-pair" part of S5.2
  111250. var firstSemi = str.indexOf(';'); // S5.2 step 1
  111251. var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi);
  111252. var c = parseCookiePair(cookiePair, !!options.loose);
  111253. if (!c) {
  111254. return;
  111255. }
  111256. if (firstSemi === -1) {
  111257. return c;
  111258. }
  111259. // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
  111260. // (including the %x3B (";") in question)." plus later on in the same section
  111261. // "discard the first ";" and trim".
  111262. var unparsed = str.slice(firstSemi + 1).trim();
  111263. // "If the unparsed-attributes string is empty, skip the rest of these
  111264. // steps."
  111265. if (unparsed.length === 0) {
  111266. return c;
  111267. }
  111268. /*
  111269. * S5.2 says that when looping over the items "[p]rocess the attribute-name
  111270. * and attribute-value according to the requirements in the following
  111271. * subsections" for every item. Plus, for many of the individual attributes
  111272. * in S5.3 it says to use the "attribute-value of the last attribute in the
  111273. * cookie-attribute-list". Therefore, in this implementation, we overwrite
  111274. * the previous value.
  111275. */
  111276. var cookie_avs = unparsed.split(';');
  111277. while (cookie_avs.length) {
  111278. var av = cookie_avs.shift().trim();
  111279. if (av.length === 0) { // happens if ";;" appears
  111280. continue;
  111281. }
  111282. var av_sep = av.indexOf('=');
  111283. var av_key, av_value;
  111284. if (av_sep === -1) {
  111285. av_key = av;
  111286. av_value = null;
  111287. } else {
  111288. av_key = av.substr(0,av_sep);
  111289. av_value = av.substr(av_sep+1);
  111290. }
  111291. av_key = av_key.trim().toLowerCase();
  111292. if (av_value) {
  111293. av_value = av_value.trim();
  111294. }
  111295. switch(av_key) {
  111296. case 'expires': // S5.2.1
  111297. if (av_value) {
  111298. var exp = parseDate(av_value);
  111299. // "If the attribute-value failed to parse as a cookie date, ignore the
  111300. // cookie-av."
  111301. if (exp) {
  111302. // over and underflow not realistically a concern: V8's getTime() seems to
  111303. // store something larger than a 32-bit time_t (even with 32-bit node)
  111304. c.expires = exp;
  111305. }
  111306. }
  111307. break;
  111308. case 'max-age': // S5.2.2
  111309. if (av_value) {
  111310. // "If the first character of the attribute-value is not a DIGIT or a "-"
  111311. // character ...[or]... If the remainder of attribute-value contains a
  111312. // non-DIGIT character, ignore the cookie-av."
  111313. if (/^-?[0-9]+$/.test(av_value)) {
  111314. var delta = parseInt(av_value, 10);
  111315. // "If delta-seconds is less than or equal to zero (0), let expiry-time
  111316. // be the earliest representable date and time."
  111317. c.setMaxAge(delta);
  111318. }
  111319. }
  111320. break;
  111321. case 'domain': // S5.2.3
  111322. // "If the attribute-value is empty, the behavior is undefined. However,
  111323. // the user agent SHOULD ignore the cookie-av entirely."
  111324. if (av_value) {
  111325. // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
  111326. // (".") character."
  111327. var domain = av_value.trim().replace(/^\./, '');
  111328. if (domain) {
  111329. // "Convert the cookie-domain to lower case."
  111330. c.domain = domain.toLowerCase();
  111331. }
  111332. }
  111333. break;
  111334. case 'path': // S5.2.4
  111335. /*
  111336. * "If the attribute-value is empty or if the first character of the
  111337. * attribute-value is not %x2F ("/"):
  111338. * Let cookie-path be the default-path.
  111339. * Otherwise:
  111340. * Let cookie-path be the attribute-value."
  111341. *
  111342. * We'll represent the default-path as null since it depends on the
  111343. * context of the parsing.
  111344. */
  111345. c.path = av_value && av_value[0] === "/" ? av_value : null;
  111346. break;
  111347. case 'secure': // S5.2.5
  111348. /*
  111349. * "If the attribute-name case-insensitively matches the string "Secure",
  111350. * the user agent MUST append an attribute to the cookie-attribute-list
  111351. * with an attribute-name of Secure and an empty attribute-value."
  111352. */
  111353. c.secure = true;
  111354. break;
  111355. case 'httponly': // S5.2.6 -- effectively the same as 'secure'
  111356. c.httpOnly = true;
  111357. break;
  111358. default:
  111359. c.extensions = c.extensions || [];
  111360. c.extensions.push(av);
  111361. break;
  111362. }
  111363. }
  111364. return c;
  111365. }
  111366. // avoid the V8 deoptimization monster!
  111367. function jsonParse(str) {
  111368. var obj;
  111369. try {
  111370. obj = JSON.parse(str);
  111371. } catch (e) {
  111372. return e;
  111373. }
  111374. return obj;
  111375. }
  111376. function fromJSON(str) {
  111377. if (!str) {
  111378. return null;
  111379. }
  111380. var obj;
  111381. if (typeof str === 'string') {
  111382. obj = jsonParse(str);
  111383. if (obj instanceof Error) {
  111384. return null;
  111385. }
  111386. } else {
  111387. // assume it's an Object
  111388. obj = str;
  111389. }
  111390. var c = new Cookie();
  111391. for (var i=0; i<Cookie.serializableProperties.length; i++) {
  111392. var prop = Cookie.serializableProperties[i];
  111393. if (obj[prop] === undefined ||
  111394. obj[prop] === Cookie.prototype[prop])
  111395. {
  111396. continue; // leave as prototype default
  111397. }
  111398. if (prop === 'expires' ||
  111399. prop === 'creation' ||
  111400. prop === 'lastAccessed')
  111401. {
  111402. if (obj[prop] === null) {
  111403. c[prop] = null;
  111404. } else {
  111405. c[prop] = obj[prop] == "Infinity" ?
  111406. "Infinity" : new Date(obj[prop]);
  111407. }
  111408. } else {
  111409. c[prop] = obj[prop];
  111410. }
  111411. }
  111412. return c;
  111413. }
  111414. /* Section 5.4 part 2:
  111415. * "* Cookies with longer paths are listed before cookies with
  111416. * shorter paths.
  111417. *
  111418. * * Among cookies that have equal-length path fields, cookies with
  111419. * earlier creation-times are listed before cookies with later
  111420. * creation-times."
  111421. */
  111422. function cookieCompare(a,b) {
  111423. var cmp = 0;
  111424. // descending for length: b CMP a
  111425. var aPathLen = a.path ? a.path.length : 0;
  111426. var bPathLen = b.path ? b.path.length : 0;
  111427. cmp = bPathLen - aPathLen;
  111428. if (cmp !== 0) {
  111429. return cmp;
  111430. }
  111431. // ascending for time: a CMP b
  111432. var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
  111433. var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
  111434. cmp = aTime - bTime;
  111435. if (cmp !== 0) {
  111436. return cmp;
  111437. }
  111438. // break ties for the same millisecond (precision of JavaScript's clock)
  111439. cmp = a.creationIndex - b.creationIndex;
  111440. return cmp;
  111441. }
  111442. // Gives the permutation of all possible pathMatch()es of a given path. The
  111443. // array is in longest-to-shortest order. Handy for indexing.
  111444. function permutePath(path) {
  111445. if (path === '/') {
  111446. return ['/'];
  111447. }
  111448. if (path.lastIndexOf('/') === path.length-1) {
  111449. path = path.substr(0,path.length-1);
  111450. }
  111451. var permutations = [path];
  111452. while (path.length > 1) {
  111453. var lindex = path.lastIndexOf('/');
  111454. if (lindex === 0) {
  111455. break;
  111456. }
  111457. path = path.substr(0,lindex);
  111458. permutations.push(path);
  111459. }
  111460. permutations.push('/');
  111461. return permutations;
  111462. }
  111463. function getCookieContext(url) {
  111464. if (url instanceof Object) {
  111465. return url;
  111466. }
  111467. // NOTE: decodeURI will throw on malformed URIs (see GH-32).
  111468. // Therefore, we will just skip decoding for such URIs.
  111469. try {
  111470. url = decodeURI(url);
  111471. }
  111472. catch(err) {
  111473. // Silently swallow error
  111474. }
  111475. return urlParse(url);
  111476. }
  111477. function Cookie(options) {
  111478. options = options || {};
  111479. Object.keys(options).forEach(function(prop) {
  111480. if (Cookie.prototype.hasOwnProperty(prop) &&
  111481. Cookie.prototype[prop] !== options[prop] &&
  111482. prop.substr(0,1) !== '_')
  111483. {
  111484. this[prop] = options[prop];
  111485. }
  111486. }, this);
  111487. this.creation = this.creation || new Date();
  111488. // used to break creation ties in cookieCompare():
  111489. Object.defineProperty(this, 'creationIndex', {
  111490. configurable: false,
  111491. enumerable: false, // important for assert.deepEqual checks
  111492. writable: true,
  111493. value: ++Cookie.cookiesCreated
  111494. });
  111495. }
  111496. Cookie.cookiesCreated = 0; // incremented each time a cookie is created
  111497. Cookie.parse = parse;
  111498. Cookie.fromJSON = fromJSON;
  111499. Cookie.prototype.key = "";
  111500. Cookie.prototype.value = "";
  111501. // the order in which the RFC has them:
  111502. Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
  111503. Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
  111504. Cookie.prototype.domain = null;
  111505. Cookie.prototype.path = null;
  111506. Cookie.prototype.secure = false;
  111507. Cookie.prototype.httpOnly = false;
  111508. Cookie.prototype.extensions = null;
  111509. // set by the CookieJar:
  111510. Cookie.prototype.hostOnly = null; // boolean when set
  111511. Cookie.prototype.pathIsDefault = null; // boolean when set
  111512. Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
  111513. Cookie.prototype.lastAccessed = null; // Date when set
  111514. Object.defineProperty(Cookie.prototype, 'creationIndex', {
  111515. configurable: true,
  111516. enumerable: false,
  111517. writable: true,
  111518. value: 0
  111519. });
  111520. Cookie.serializableProperties = Object.keys(Cookie.prototype)
  111521. .filter(function(prop) {
  111522. return !(
  111523. Cookie.prototype[prop] instanceof Function ||
  111524. prop === 'creationIndex' ||
  111525. prop.substr(0,1) === '_'
  111526. );
  111527. });
  111528. Cookie.prototype.inspect = function inspect() {
  111529. var now = Date.now();
  111530. return 'Cookie="'+this.toString() +
  111531. '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
  111532. '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
  111533. '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
  111534. '"';
  111535. };
  111536. // Use the new custom inspection symbol to add the custom inspect function if
  111537. // available.
  111538. if (util.inspect.custom) {
  111539. Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
  111540. }
  111541. Cookie.prototype.toJSON = function() {
  111542. var obj = {};
  111543. var props = Cookie.serializableProperties;
  111544. for (var i=0; i<props.length; i++) {
  111545. var prop = props[i];
  111546. if (this[prop] === Cookie.prototype[prop]) {
  111547. continue; // leave as prototype default
  111548. }
  111549. if (prop === 'expires' ||
  111550. prop === 'creation' ||
  111551. prop === 'lastAccessed')
  111552. {
  111553. if (this[prop] === null) {
  111554. obj[prop] = null;
  111555. } else {
  111556. obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
  111557. "Infinity" : this[prop].toISOString();
  111558. }
  111559. } else if (prop === 'maxAge') {
  111560. if (this[prop] !== null) {
  111561. // again, intentionally not ===
  111562. obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
  111563. this[prop].toString() : this[prop];
  111564. }
  111565. } else {
  111566. if (this[prop] !== Cookie.prototype[prop]) {
  111567. obj[prop] = this[prop];
  111568. }
  111569. }
  111570. }
  111571. return obj;
  111572. };
  111573. Cookie.prototype.clone = function() {
  111574. return fromJSON(this.toJSON());
  111575. };
  111576. Cookie.prototype.validate = function validate() {
  111577. if (!COOKIE_OCTETS.test(this.value)) {
  111578. return false;
  111579. }
  111580. if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
  111581. return false;
  111582. }
  111583. if (this.maxAge != null && this.maxAge <= 0) {
  111584. return false; // "Max-Age=" non-zero-digit *DIGIT
  111585. }
  111586. if (this.path != null && !PATH_VALUE.test(this.path)) {
  111587. return false;
  111588. }
  111589. var cdomain = this.cdomain();
  111590. if (cdomain) {
  111591. if (cdomain.match(/\.$/)) {
  111592. return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
  111593. }
  111594. var suffix = pubsuffix.getPublicSuffix(cdomain);
  111595. if (suffix == null) { // it's a public suffix
  111596. return false;
  111597. }
  111598. }
  111599. return true;
  111600. };
  111601. Cookie.prototype.setExpires = function setExpires(exp) {
  111602. if (exp instanceof Date) {
  111603. this.expires = exp;
  111604. } else {
  111605. this.expires = parseDate(exp) || "Infinity";
  111606. }
  111607. };
  111608. Cookie.prototype.setMaxAge = function setMaxAge(age) {
  111609. if (age === Infinity || age === -Infinity) {
  111610. this.maxAge = age.toString(); // so JSON.stringify() works
  111611. } else {
  111612. this.maxAge = age;
  111613. }
  111614. };
  111615. // gives Cookie header format
  111616. Cookie.prototype.cookieString = function cookieString() {
  111617. var val = this.value;
  111618. if (val == null) {
  111619. val = '';
  111620. }
  111621. if (this.key === '') {
  111622. return val;
  111623. }
  111624. return this.key+'='+val;
  111625. };
  111626. // gives Set-Cookie header format
  111627. Cookie.prototype.toString = function toString() {
  111628. var str = this.cookieString();
  111629. if (this.expires != Infinity) {
  111630. if (this.expires instanceof Date) {
  111631. str += '; Expires='+formatDate(this.expires);
  111632. } else {
  111633. str += '; Expires='+this.expires;
  111634. }
  111635. }
  111636. if (this.maxAge != null && this.maxAge != Infinity) {
  111637. str += '; Max-Age='+this.maxAge;
  111638. }
  111639. if (this.domain && !this.hostOnly) {
  111640. str += '; Domain='+this.domain;
  111641. }
  111642. if (this.path) {
  111643. str += '; Path='+this.path;
  111644. }
  111645. if (this.secure) {
  111646. str += '; Secure';
  111647. }
  111648. if (this.httpOnly) {
  111649. str += '; HttpOnly';
  111650. }
  111651. if (this.extensions) {
  111652. this.extensions.forEach(function(ext) {
  111653. str += '; '+ext;
  111654. });
  111655. }
  111656. return str;
  111657. };
  111658. // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
  111659. // elsewhere)
  111660. // S5.3 says to give the "latest representable date" for which we use Infinity
  111661. // For "expired" we use 0
  111662. Cookie.prototype.TTL = function TTL(now) {
  111663. /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
  111664. * attribute, the Max-Age attribute has precedence and controls the
  111665. * expiration date of the cookie.
  111666. * (Concurs with S5.3 step 3)
  111667. */
  111668. if (this.maxAge != null) {
  111669. return this.maxAge<=0 ? 0 : this.maxAge*1000;
  111670. }
  111671. var expires = this.expires;
  111672. if (expires != Infinity) {
  111673. if (!(expires instanceof Date)) {
  111674. expires = parseDate(expires) || Infinity;
  111675. }
  111676. if (expires == Infinity) {
  111677. return Infinity;
  111678. }
  111679. return expires.getTime() - (now || Date.now());
  111680. }
  111681. return Infinity;
  111682. };
  111683. // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
  111684. // elsewhere)
  111685. Cookie.prototype.expiryTime = function expiryTime(now) {
  111686. if (this.maxAge != null) {
  111687. var relativeTo = now || this.creation || new Date();
  111688. var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
  111689. return relativeTo.getTime() + age;
  111690. }
  111691. if (this.expires == Infinity) {
  111692. return Infinity;
  111693. }
  111694. return this.expires.getTime();
  111695. };
  111696. // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
  111697. // elsewhere), except it returns a Date
  111698. Cookie.prototype.expiryDate = function expiryDate(now) {
  111699. var millisec = this.expiryTime(now);
  111700. if (millisec == Infinity) {
  111701. return new Date(MAX_TIME);
  111702. } else if (millisec == -Infinity) {
  111703. return new Date(MIN_TIME);
  111704. } else {
  111705. return new Date(millisec);
  111706. }
  111707. };
  111708. // This replaces the "persistent-flag" parts of S5.3 step 3
  111709. Cookie.prototype.isPersistent = function isPersistent() {
  111710. return (this.maxAge != null || this.expires != Infinity);
  111711. };
  111712. // Mostly S5.1.2 and S5.2.3:
  111713. Cookie.prototype.cdomain =
  111714. Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
  111715. if (this.domain == null) {
  111716. return null;
  111717. }
  111718. return canonicalDomain(this.domain);
  111719. };
  111720. function CookieJar(store, options) {
  111721. if (typeof options === "boolean") {
  111722. options = {rejectPublicSuffixes: options};
  111723. } else if (options == null) {
  111724. options = {};
  111725. }
  111726. if (options.rejectPublicSuffixes != null) {
  111727. this.rejectPublicSuffixes = options.rejectPublicSuffixes;
  111728. }
  111729. if (options.looseMode != null) {
  111730. this.enableLooseMode = options.looseMode;
  111731. }
  111732. if (!store) {
  111733. store = new MemoryCookieStore();
  111734. }
  111735. this.store = store;
  111736. }
  111737. CookieJar.prototype.store = null;
  111738. CookieJar.prototype.rejectPublicSuffixes = true;
  111739. CookieJar.prototype.enableLooseMode = false;
  111740. var CAN_BE_SYNC = [];
  111741. CAN_BE_SYNC.push('setCookie');
  111742. CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
  111743. var err;
  111744. var context = getCookieContext(url);
  111745. if (options instanceof Function) {
  111746. cb = options;
  111747. options = {};
  111748. }
  111749. var host = canonicalDomain(context.hostname);
  111750. var loose = this.enableLooseMode;
  111751. if (options.loose != null) {
  111752. loose = options.loose;
  111753. }
  111754. // S5.3 step 1
  111755. if (!(cookie instanceof Cookie)) {
  111756. cookie = Cookie.parse(cookie, { loose: loose });
  111757. }
  111758. if (!cookie) {
  111759. err = new Error("Cookie failed to parse");
  111760. return cb(options.ignoreError ? null : err);
  111761. }
  111762. // S5.3 step 2
  111763. var now = options.now || new Date(); // will assign later to save effort in the face of errors
  111764. // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
  111765. // S5.3 step 4: NOOP; domain is null by default
  111766. // S5.3 step 5: public suffixes
  111767. if (this.rejectPublicSuffixes && cookie.domain) {
  111768. var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
  111769. if (suffix == null) { // e.g. "com"
  111770. err = new Error("Cookie has domain set to a public suffix");
  111771. return cb(options.ignoreError ? null : err);
  111772. }
  111773. }
  111774. // S5.3 step 6:
  111775. if (cookie.domain) {
  111776. if (!domainMatch(host, cookie.cdomain(), false)) {
  111777. err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
  111778. return cb(options.ignoreError ? null : err);
  111779. }
  111780. if (cookie.hostOnly == null) { // don't reset if already set
  111781. cookie.hostOnly = false;
  111782. }
  111783. } else {
  111784. cookie.hostOnly = true;
  111785. cookie.domain = host;
  111786. }
  111787. //S5.2.4 If the attribute-value is empty or if the first character of the
  111788. //attribute-value is not %x2F ("/"):
  111789. //Let cookie-path be the default-path.
  111790. if (!cookie.path || cookie.path[0] !== '/') {
  111791. cookie.path = defaultPath(context.pathname);
  111792. cookie.pathIsDefault = true;
  111793. }
  111794. // S5.3 step 8: NOOP; secure attribute
  111795. // S5.3 step 9: NOOP; httpOnly attribute
  111796. // S5.3 step 10
  111797. if (options.http === false && cookie.httpOnly) {
  111798. err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
  111799. return cb(options.ignoreError ? null : err);
  111800. }
  111801. var store = this.store;
  111802. if (!store.updateCookie) {
  111803. store.updateCookie = function(oldCookie, newCookie, cb) {
  111804. this.putCookie(newCookie, cb);
  111805. };
  111806. }
  111807. function withCookie(err, oldCookie) {
  111808. if (err) {
  111809. return cb(err);
  111810. }
  111811. var next = function(err) {
  111812. if (err) {
  111813. return cb(err);
  111814. } else {
  111815. cb(null, cookie);
  111816. }
  111817. };
  111818. if (oldCookie) {
  111819. // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
  111820. // domain, and path as the newly created cookie:"
  111821. if (options.http === false && oldCookie.httpOnly) { // step 11.2
  111822. err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
  111823. return cb(options.ignoreError ? null : err);
  111824. }
  111825. cookie.creation = oldCookie.creation; // step 11.3
  111826. cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
  111827. cookie.lastAccessed = now;
  111828. // Step 11.4 (delete cookie) is implied by just setting the new one:
  111829. store.updateCookie(oldCookie, cookie, next); // step 12
  111830. } else {
  111831. cookie.creation = cookie.lastAccessed = now;
  111832. store.putCookie(cookie, next); // step 12
  111833. }
  111834. }
  111835. store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
  111836. };
  111837. // RFC6365 S5.4
  111838. CAN_BE_SYNC.push('getCookies');
  111839. CookieJar.prototype.getCookies = function(url, options, cb) {
  111840. var context = getCookieContext(url);
  111841. if (options instanceof Function) {
  111842. cb = options;
  111843. options = {};
  111844. }
  111845. var host = canonicalDomain(context.hostname);
  111846. var path = context.pathname || '/';
  111847. var secure = options.secure;
  111848. if (secure == null && context.protocol &&
  111849. (context.protocol == 'https:' || context.protocol == 'wss:'))
  111850. {
  111851. secure = true;
  111852. }
  111853. var http = options.http;
  111854. if (http == null) {
  111855. http = true;
  111856. }
  111857. var now = options.now || Date.now();
  111858. var expireCheck = options.expire !== false;
  111859. var allPaths = !!options.allPaths;
  111860. var store = this.store;
  111861. function matchingCookie(c) {
  111862. // "Either:
  111863. // The cookie's host-only-flag is true and the canonicalized
  111864. // request-host is identical to the cookie's domain.
  111865. // Or:
  111866. // The cookie's host-only-flag is false and the canonicalized
  111867. // request-host domain-matches the cookie's domain."
  111868. if (c.hostOnly) {
  111869. if (c.domain != host) {
  111870. return false;
  111871. }
  111872. } else {
  111873. if (!domainMatch(host, c.domain, false)) {
  111874. return false;
  111875. }
  111876. }
  111877. // "The request-uri's path path-matches the cookie's path."
  111878. if (!allPaths && !pathMatch(path, c.path)) {
  111879. return false;
  111880. }
  111881. // "If the cookie's secure-only-flag is true, then the request-uri's
  111882. // scheme must denote a "secure" protocol"
  111883. if (c.secure && !secure) {
  111884. return false;
  111885. }
  111886. // "If the cookie's http-only-flag is true, then exclude the cookie if the
  111887. // cookie-string is being generated for a "non-HTTP" API"
  111888. if (c.httpOnly && !http) {
  111889. return false;
  111890. }
  111891. // deferred from S5.3
  111892. // non-RFC: allow retention of expired cookies by choice
  111893. if (expireCheck && c.expiryTime() <= now) {
  111894. store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
  111895. return false;
  111896. }
  111897. return true;
  111898. }
  111899. store.findCookies(host, allPaths ? null : path, function(err,cookies) {
  111900. if (err) {
  111901. return cb(err);
  111902. }
  111903. cookies = cookies.filter(matchingCookie);
  111904. // sorting of S5.4 part 2
  111905. if (options.sort !== false) {
  111906. cookies = cookies.sort(cookieCompare);
  111907. }
  111908. // S5.4 part 3
  111909. var now = new Date();
  111910. cookies.forEach(function(c) {
  111911. c.lastAccessed = now;
  111912. });
  111913. // TODO persist lastAccessed
  111914. cb(null,cookies);
  111915. });
  111916. };
  111917. CAN_BE_SYNC.push('getCookieString');
  111918. CookieJar.prototype.getCookieString = function(/*..., cb*/) {
  111919. var args = Array.prototype.slice.call(arguments,0);
  111920. var cb = args.pop();
  111921. var next = function(err,cookies) {
  111922. if (err) {
  111923. cb(err);
  111924. } else {
  111925. cb(null, cookies
  111926. .sort(cookieCompare)
  111927. .map(function(c){
  111928. return c.cookieString();
  111929. })
  111930. .join('; '));
  111931. }
  111932. };
  111933. args.push(next);
  111934. this.getCookies.apply(this,args);
  111935. };
  111936. CAN_BE_SYNC.push('getSetCookieStrings');
  111937. CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
  111938. var args = Array.prototype.slice.call(arguments,0);
  111939. var cb = args.pop();
  111940. var next = function(err,cookies) {
  111941. if (err) {
  111942. cb(err);
  111943. } else {
  111944. cb(null, cookies.map(function(c){
  111945. return c.toString();
  111946. }));
  111947. }
  111948. };
  111949. args.push(next);
  111950. this.getCookies.apply(this,args);
  111951. };
  111952. CAN_BE_SYNC.push('serialize');
  111953. CookieJar.prototype.serialize = function(cb) {
  111954. var type = this.store.constructor.name;
  111955. if (type === 'Object') {
  111956. type = null;
  111957. }
  111958. // update README.md "Serialization Format" if you change this, please!
  111959. var serialized = {
  111960. // The version of tough-cookie that serialized this jar. Generally a good
  111961. // practice since future versions can make data import decisions based on
  111962. // known past behavior. When/if this matters, use `semver`.
  111963. version: 'tough-cookie@'+VERSION,
  111964. // add the store type, to make humans happy:
  111965. storeType: type,
  111966. // CookieJar configuration:
  111967. rejectPublicSuffixes: !!this.rejectPublicSuffixes,
  111968. // this gets filled from getAllCookies:
  111969. cookies: []
  111970. };
  111971. if (!(this.store.getAllCookies &&
  111972. typeof this.store.getAllCookies === 'function'))
  111973. {
  111974. return cb(new Error('store does not support getAllCookies and cannot be serialized'));
  111975. }
  111976. this.store.getAllCookies(function(err,cookies) {
  111977. if (err) {
  111978. return cb(err);
  111979. }
  111980. serialized.cookies = cookies.map(function(cookie) {
  111981. // convert to serialized 'raw' cookies
  111982. cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
  111983. // Remove the index so new ones get assigned during deserialization
  111984. delete cookie.creationIndex;
  111985. return cookie;
  111986. });
  111987. return cb(null, serialized);
  111988. });
  111989. };
  111990. // well-known name that JSON.stringify calls
  111991. CookieJar.prototype.toJSON = function() {
  111992. return this.serializeSync();
  111993. };
  111994. // use the class method CookieJar.deserialize instead of calling this directly
  111995. CAN_BE_SYNC.push('_importCookies');
  111996. CookieJar.prototype._importCookies = function(serialized, cb) {
  111997. var jar = this;
  111998. var cookies = serialized.cookies;
  111999. if (!cookies || !Array.isArray(cookies)) {
  112000. return cb(new Error('serialized jar has no cookies array'));
  112001. }
  112002. cookies = cookies.slice(); // do not modify the original
  112003. function putNext(err) {
  112004. if (err) {
  112005. return cb(err);
  112006. }
  112007. if (!cookies.length) {
  112008. return cb(err, jar);
  112009. }
  112010. var cookie;
  112011. try {
  112012. cookie = fromJSON(cookies.shift());
  112013. } catch (e) {
  112014. return cb(e);
  112015. }
  112016. if (cookie === null) {
  112017. return putNext(null); // skip this cookie
  112018. }
  112019. jar.store.putCookie(cookie, putNext);
  112020. }
  112021. putNext();
  112022. };
  112023. CookieJar.deserialize = function(strOrObj, store, cb) {
  112024. if (arguments.length !== 3) {
  112025. // store is optional
  112026. cb = store;
  112027. store = null;
  112028. }
  112029. var serialized;
  112030. if (typeof strOrObj === 'string') {
  112031. serialized = jsonParse(strOrObj);
  112032. if (serialized instanceof Error) {
  112033. return cb(serialized);
  112034. }
  112035. } else {
  112036. serialized = strOrObj;
  112037. }
  112038. var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
  112039. jar._importCookies(serialized, function(err) {
  112040. if (err) {
  112041. return cb(err);
  112042. }
  112043. cb(null, jar);
  112044. });
  112045. };
  112046. CookieJar.deserializeSync = function(strOrObj, store) {
  112047. var serialized = typeof strOrObj === 'string' ?
  112048. JSON.parse(strOrObj) : strOrObj;
  112049. var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
  112050. // catch this mistake early:
  112051. if (!jar.store.synchronous) {
  112052. throw new Error('CookieJar store is not synchronous; use async API instead.');
  112053. }
  112054. jar._importCookiesSync(serialized);
  112055. return jar;
  112056. };
  112057. CookieJar.fromJSON = CookieJar.deserializeSync;
  112058. CookieJar.prototype.clone = function(newStore, cb) {
  112059. if (arguments.length === 1) {
  112060. cb = newStore;
  112061. newStore = null;
  112062. }
  112063. this.serialize(function(err,serialized) {
  112064. if (err) {
  112065. return cb(err);
  112066. }
  112067. CookieJar.deserialize(serialized, newStore, cb);
  112068. });
  112069. };
  112070. CAN_BE_SYNC.push('removeAllCookies');
  112071. CookieJar.prototype.removeAllCookies = function(cb) {
  112072. var store = this.store;
  112073. // Check that the store implements its own removeAllCookies(). The default
  112074. // implementation in Store will immediately call the callback with a "not
  112075. // implemented" Error.
  112076. if (store.removeAllCookies instanceof Function &&
  112077. store.removeAllCookies !== Store.prototype.removeAllCookies)
  112078. {
  112079. return store.removeAllCookies(cb);
  112080. }
  112081. store.getAllCookies(function(err, cookies) {
  112082. if (err) {
  112083. return cb(err);
  112084. }
  112085. if (cookies.length === 0) {
  112086. return cb(null);
  112087. }
  112088. var completedCount = 0;
  112089. var removeErrors = [];
  112090. function removeCookieCb(removeErr) {
  112091. if (removeErr) {
  112092. removeErrors.push(removeErr);
  112093. }
  112094. completedCount++;
  112095. if (completedCount === cookies.length) {
  112096. return cb(removeErrors.length ? removeErrors[0] : null);
  112097. }
  112098. }
  112099. cookies.forEach(function(cookie) {
  112100. store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb);
  112101. });
  112102. });
  112103. };
  112104. CookieJar.prototype._cloneSync = syncWrap('clone');
  112105. CookieJar.prototype.cloneSync = function(newStore) {
  112106. if (!newStore.synchronous) {
  112107. throw new Error('CookieJar clone destination store is not synchronous; use async API instead.');
  112108. }
  112109. return this._cloneSync(newStore);
  112110. };
  112111. // Use a closure to provide a true imperative API for synchronous stores.
  112112. function syncWrap(method) {
  112113. return function() {
  112114. if (!this.store.synchronous) {
  112115. throw new Error('CookieJar store is not synchronous; use async API instead.');
  112116. }
  112117. var args = Array.prototype.slice.call(arguments);
  112118. var syncErr, syncResult;
  112119. args.push(function syncCb(err, result) {
  112120. syncErr = err;
  112121. syncResult = result;
  112122. });
  112123. this[method].apply(this, args);
  112124. if (syncErr) {
  112125. throw syncErr;
  112126. }
  112127. return syncResult;
  112128. };
  112129. }
  112130. // wrap all declared CAN_BE_SYNC methods in the sync wrapper
  112131. CAN_BE_SYNC.forEach(function(method) {
  112132. CookieJar.prototype[method+'Sync'] = syncWrap(method);
  112133. });
  112134. exports.version = VERSION;
  112135. exports.CookieJar = CookieJar;
  112136. exports.Cookie = Cookie;
  112137. exports.Store = Store;
  112138. exports.MemoryCookieStore = MemoryCookieStore;
  112139. exports.parseDate = parseDate;
  112140. exports.formatDate = formatDate;
  112141. exports.parse = parse;
  112142. exports.fromJSON = fromJSON;
  112143. exports.domainMatch = domainMatch;
  112144. exports.defaultPath = defaultPath;
  112145. exports.pathMatch = pathMatch;
  112146. exports.getPublicSuffix = pubsuffix.getPublicSuffix;
  112147. exports.cookieCompare = cookieCompare;
  112148. exports.permuteDomain = require('./permuteDomain').permuteDomain;
  112149. exports.permutePath = permutePath;
  112150. exports.canonicalDomain = canonicalDomain;
  112151. },{"./memstore":641,"./pathMatch":642,"./permuteDomain":643,"./pubsuffix-psl":644,"./store":645,"./version":646,"net":190,"punycode":535,"url":653,"util":658}],641:[function(require,module,exports){
  112152. /*!
  112153. * Copyright (c) 2015, Salesforce.com, Inc.
  112154. * All rights reserved.
  112155. *
  112156. * Redistribution and use in source and binary forms, with or without
  112157. * modification, are permitted provided that the following conditions are met:
  112158. *
  112159. * 1. Redistributions of source code must retain the above copyright notice,
  112160. * this list of conditions and the following disclaimer.
  112161. *
  112162. * 2. Redistributions in binary form must reproduce the above copyright notice,
  112163. * this list of conditions and the following disclaimer in the documentation
  112164. * and/or other materials provided with the distribution.
  112165. *
  112166. * 3. Neither the name of Salesforce.com nor the names of its contributors may
  112167. * be used to endorse or promote products derived from this software without
  112168. * specific prior written permission.
  112169. *
  112170. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  112171. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  112172. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  112173. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  112174. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  112175. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  112176. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  112177. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  112178. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  112179. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  112180. * POSSIBILITY OF SUCH DAMAGE.
  112181. */
  112182. 'use strict';
  112183. var Store = require('./store').Store;
  112184. var permuteDomain = require('./permuteDomain').permuteDomain;
  112185. var pathMatch = require('./pathMatch').pathMatch;
  112186. var util = require('util');
  112187. function MemoryCookieStore() {
  112188. Store.call(this);
  112189. this.idx = {};
  112190. }
  112191. util.inherits(MemoryCookieStore, Store);
  112192. exports.MemoryCookieStore = MemoryCookieStore;
  112193. MemoryCookieStore.prototype.idx = null;
  112194. // Since it's just a struct in RAM, this Store is synchronous
  112195. MemoryCookieStore.prototype.synchronous = true;
  112196. // force a default depth:
  112197. MemoryCookieStore.prototype.inspect = function() {
  112198. return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
  112199. };
  112200. // Use the new custom inspection symbol to add the custom inspect function if
  112201. // available.
  112202. if (util.inspect.custom) {
  112203. MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect;
  112204. }
  112205. MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
  112206. if (!this.idx[domain]) {
  112207. return cb(null,undefined);
  112208. }
  112209. if (!this.idx[domain][path]) {
  112210. return cb(null,undefined);
  112211. }
  112212. return cb(null,this.idx[domain][path][key]||null);
  112213. };
  112214. MemoryCookieStore.prototype.findCookies = function(domain, path, cb) {
  112215. var results = [];
  112216. if (!domain) {
  112217. return cb(null,[]);
  112218. }
  112219. var pathMatcher;
  112220. if (!path) {
  112221. // null means "all paths"
  112222. pathMatcher = function matchAll(domainIndex) {
  112223. for (var curPath in domainIndex) {
  112224. var pathIndex = domainIndex[curPath];
  112225. for (var key in pathIndex) {
  112226. results.push(pathIndex[key]);
  112227. }
  112228. }
  112229. };
  112230. } else {
  112231. pathMatcher = function matchRFC(domainIndex) {
  112232. //NOTE: we should use path-match algorithm from S5.1.4 here
  112233. //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
  112234. Object.keys(domainIndex).forEach(function (cookiePath) {
  112235. if (pathMatch(path, cookiePath)) {
  112236. var pathIndex = domainIndex[cookiePath];
  112237. for (var key in pathIndex) {
  112238. results.push(pathIndex[key]);
  112239. }
  112240. }
  112241. });
  112242. };
  112243. }
  112244. var domains = permuteDomain(domain) || [domain];
  112245. var idx = this.idx;
  112246. domains.forEach(function(curDomain) {
  112247. var domainIndex = idx[curDomain];
  112248. if (!domainIndex) {
  112249. return;
  112250. }
  112251. pathMatcher(domainIndex);
  112252. });
  112253. cb(null,results);
  112254. };
  112255. MemoryCookieStore.prototype.putCookie = function(cookie, cb) {
  112256. if (!this.idx[cookie.domain]) {
  112257. this.idx[cookie.domain] = {};
  112258. }
  112259. if (!this.idx[cookie.domain][cookie.path]) {
  112260. this.idx[cookie.domain][cookie.path] = {};
  112261. }
  112262. this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
  112263. cb(null);
  112264. };
  112265. MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) {
  112266. // updateCookie() may avoid updating cookies that are identical. For example,
  112267. // lastAccessed may not be important to some stores and an equality
  112268. // comparison could exclude that field.
  112269. this.putCookie(newCookie,cb);
  112270. };
  112271. MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) {
  112272. if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
  112273. delete this.idx[domain][path][key];
  112274. }
  112275. cb(null);
  112276. };
  112277. MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
  112278. if (this.idx[domain]) {
  112279. if (path) {
  112280. delete this.idx[domain][path];
  112281. } else {
  112282. delete this.idx[domain];
  112283. }
  112284. }
  112285. return cb(null);
  112286. };
  112287. MemoryCookieStore.prototype.removeAllCookies = function(cb) {
  112288. this.idx = {};
  112289. return cb(null);
  112290. }
  112291. MemoryCookieStore.prototype.getAllCookies = function(cb) {
  112292. var cookies = [];
  112293. var idx = this.idx;
  112294. var domains = Object.keys(idx);
  112295. domains.forEach(function(domain) {
  112296. var paths = Object.keys(idx[domain]);
  112297. paths.forEach(function(path) {
  112298. var keys = Object.keys(idx[domain][path]);
  112299. keys.forEach(function(key) {
  112300. if (key !== null) {
  112301. cookies.push(idx[domain][path][key]);
  112302. }
  112303. });
  112304. });
  112305. });
  112306. // Sort by creationIndex so deserializing retains the creation order.
  112307. // When implementing your own store, this SHOULD retain the order too
  112308. cookies.sort(function(a,b) {
  112309. return (a.creationIndex||0) - (b.creationIndex||0);
  112310. });
  112311. cb(null, cookies);
  112312. };
  112313. },{"./pathMatch":642,"./permuteDomain":643,"./store":645,"util":658}],642:[function(require,module,exports){
  112314. /*!
  112315. * Copyright (c) 2015, Salesforce.com, Inc.
  112316. * All rights reserved.
  112317. *
  112318. * Redistribution and use in source and binary forms, with or without
  112319. * modification, are permitted provided that the following conditions are met:
  112320. *
  112321. * 1. Redistributions of source code must retain the above copyright notice,
  112322. * this list of conditions and the following disclaimer.
  112323. *
  112324. * 2. Redistributions in binary form must reproduce the above copyright notice,
  112325. * this list of conditions and the following disclaimer in the documentation
  112326. * and/or other materials provided with the distribution.
  112327. *
  112328. * 3. Neither the name of Salesforce.com nor the names of its contributors may
  112329. * be used to endorse or promote products derived from this software without
  112330. * specific prior written permission.
  112331. *
  112332. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  112333. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  112334. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  112335. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  112336. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  112337. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  112338. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  112339. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  112340. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  112341. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  112342. * POSSIBILITY OF SUCH DAMAGE.
  112343. */
  112344. "use strict";
  112345. /*
  112346. * "A request-path path-matches a given cookie-path if at least one of the
  112347. * following conditions holds:"
  112348. */
  112349. function pathMatch (reqPath, cookiePath) {
  112350. // "o The cookie-path and the request-path are identical."
  112351. if (cookiePath === reqPath) {
  112352. return true;
  112353. }
  112354. var idx = reqPath.indexOf(cookiePath);
  112355. if (idx === 0) {
  112356. // "o The cookie-path is a prefix of the request-path, and the last
  112357. // character of the cookie-path is %x2F ("/")."
  112358. if (cookiePath.substr(-1) === "/") {
  112359. return true;
  112360. }
  112361. // " o The cookie-path is a prefix of the request-path, and the first
  112362. // character of the request-path that is not included in the cookie- path
  112363. // is a %x2F ("/") character."
  112364. if (reqPath.substr(cookiePath.length, 1) === "/") {
  112365. return true;
  112366. }
  112367. }
  112368. return false;
  112369. }
  112370. exports.pathMatch = pathMatch;
  112371. },{}],643:[function(require,module,exports){
  112372. /*!
  112373. * Copyright (c) 2015, Salesforce.com, Inc.
  112374. * All rights reserved.
  112375. *
  112376. * Redistribution and use in source and binary forms, with or without
  112377. * modification, are permitted provided that the following conditions are met:
  112378. *
  112379. * 1. Redistributions of source code must retain the above copyright notice,
  112380. * this list of conditions and the following disclaimer.
  112381. *
  112382. * 2. Redistributions in binary form must reproduce the above copyright notice,
  112383. * this list of conditions and the following disclaimer in the documentation
  112384. * and/or other materials provided with the distribution.
  112385. *
  112386. * 3. Neither the name of Salesforce.com nor the names of its contributors may
  112387. * be used to endorse or promote products derived from this software without
  112388. * specific prior written permission.
  112389. *
  112390. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  112391. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  112392. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  112393. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  112394. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  112395. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  112396. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  112397. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  112398. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  112399. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  112400. * POSSIBILITY OF SUCH DAMAGE.
  112401. */
  112402. "use strict";
  112403. var pubsuffix = require('./pubsuffix-psl');
  112404. // Gives the permutation of all possible domainMatch()es of a given domain. The
  112405. // array is in shortest-to-longest order. Handy for indexing.
  112406. function permuteDomain (domain) {
  112407. var pubSuf = pubsuffix.getPublicSuffix(domain);
  112408. if (!pubSuf) {
  112409. return null;
  112410. }
  112411. if (pubSuf == domain) {
  112412. return [domain];
  112413. }
  112414. var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
  112415. var parts = prefix.split('.').reverse();
  112416. var cur = pubSuf;
  112417. var permutations = [cur];
  112418. while (parts.length) {
  112419. cur = parts.shift() + '.' + cur;
  112420. permutations.push(cur);
  112421. }
  112422. return permutations;
  112423. }
  112424. exports.permuteDomain = permuteDomain;
  112425. },{"./pubsuffix-psl":644}],644:[function(require,module,exports){
  112426. /*!
  112427. * Copyright (c) 2018, Salesforce.com, Inc.
  112428. * All rights reserved.
  112429. *
  112430. * Redistribution and use in source and binary forms, with or without
  112431. * modification, are permitted provided that the following conditions are met:
  112432. *
  112433. * 1. Redistributions of source code must retain the above copyright notice,
  112434. * this list of conditions and the following disclaimer.
  112435. *
  112436. * 2. Redistributions in binary form must reproduce the above copyright notice,
  112437. * this list of conditions and the following disclaimer in the documentation
  112438. * and/or other materials provided with the distribution.
  112439. *
  112440. * 3. Neither the name of Salesforce.com nor the names of its contributors may
  112441. * be used to endorse or promote products derived from this software without
  112442. * specific prior written permission.
  112443. *
  112444. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  112445. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  112446. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  112447. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  112448. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  112449. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  112450. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  112451. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  112452. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  112453. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  112454. * POSSIBILITY OF SUCH DAMAGE.
  112455. */
  112456. 'use strict';
  112457. var psl = require('psl');
  112458. function getPublicSuffix(domain) {
  112459. return psl.get(domain);
  112460. }
  112461. exports.getPublicSuffix = getPublicSuffix;
  112462. },{"psl":527}],645:[function(require,module,exports){
  112463. /*!
  112464. * Copyright (c) 2015, Salesforce.com, Inc.
  112465. * All rights reserved.
  112466. *
  112467. * Redistribution and use in source and binary forms, with or without
  112468. * modification, are permitted provided that the following conditions are met:
  112469. *
  112470. * 1. Redistributions of source code must retain the above copyright notice,
  112471. * this list of conditions and the following disclaimer.
  112472. *
  112473. * 2. Redistributions in binary form must reproduce the above copyright notice,
  112474. * this list of conditions and the following disclaimer in the documentation
  112475. * and/or other materials provided with the distribution.
  112476. *
  112477. * 3. Neither the name of Salesforce.com nor the names of its contributors may
  112478. * be used to endorse or promote products derived from this software without
  112479. * specific prior written permission.
  112480. *
  112481. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  112482. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  112483. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  112484. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  112485. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  112486. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  112487. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  112488. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  112489. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  112490. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  112491. * POSSIBILITY OF SUCH DAMAGE.
  112492. */
  112493. 'use strict';
  112494. /*jshint unused:false */
  112495. function Store() {
  112496. }
  112497. exports.Store = Store;
  112498. // Stores may be synchronous, but are still required to use a
  112499. // Continuation-Passing Style API. The CookieJar itself will expose a "*Sync"
  112500. // API that converts from synchronous-callbacks to imperative style.
  112501. Store.prototype.synchronous = false;
  112502. Store.prototype.findCookie = function(domain, path, key, cb) {
  112503. throw new Error('findCookie is not implemented');
  112504. };
  112505. Store.prototype.findCookies = function(domain, path, cb) {
  112506. throw new Error('findCookies is not implemented');
  112507. };
  112508. Store.prototype.putCookie = function(cookie, cb) {
  112509. throw new Error('putCookie is not implemented');
  112510. };
  112511. Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
  112512. // recommended default implementation:
  112513. // return this.putCookie(newCookie, cb);
  112514. throw new Error('updateCookie is not implemented');
  112515. };
  112516. Store.prototype.removeCookie = function(domain, path, key, cb) {
  112517. throw new Error('removeCookie is not implemented');
  112518. };
  112519. Store.prototype.removeCookies = function(domain, path, cb) {
  112520. throw new Error('removeCookies is not implemented');
  112521. };
  112522. Store.prototype.removeAllCookies = function(cb) {
  112523. throw new Error('removeAllCookies is not implemented');
  112524. }
  112525. Store.prototype.getAllCookies = function(cb) {
  112526. throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
  112527. };
  112528. },{}],646:[function(require,module,exports){
  112529. // generated by genversion
  112530. module.exports = '2.5.0'
  112531. },{}],647:[function(require,module,exports){
  112532. (function (process){(function (){
  112533. 'use strict'
  112534. var net = require('net')
  112535. , tls = require('tls')
  112536. , http = require('http')
  112537. , https = require('https')
  112538. , events = require('events')
  112539. , assert = require('assert')
  112540. , util = require('util')
  112541. , Buffer = require('safe-buffer').Buffer
  112542. ;
  112543. exports.httpOverHttp = httpOverHttp
  112544. exports.httpsOverHttp = httpsOverHttp
  112545. exports.httpOverHttps = httpOverHttps
  112546. exports.httpsOverHttps = httpsOverHttps
  112547. function httpOverHttp(options) {
  112548. var agent = new TunnelingAgent(options)
  112549. agent.request = http.request
  112550. return agent
  112551. }
  112552. function httpsOverHttp(options) {
  112553. var agent = new TunnelingAgent(options)
  112554. agent.request = http.request
  112555. agent.createSocket = createSecureSocket
  112556. agent.defaultPort = 443
  112557. return agent
  112558. }
  112559. function httpOverHttps(options) {
  112560. var agent = new TunnelingAgent(options)
  112561. agent.request = https.request
  112562. return agent
  112563. }
  112564. function httpsOverHttps(options) {
  112565. var agent = new TunnelingAgent(options)
  112566. agent.request = https.request
  112567. agent.createSocket = createSecureSocket
  112568. agent.defaultPort = 443
  112569. return agent
  112570. }
  112571. function TunnelingAgent(options) {
  112572. var self = this
  112573. self.options = options || {}
  112574. self.proxyOptions = self.options.proxy || {}
  112575. self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets
  112576. self.requests = []
  112577. self.sockets = []
  112578. self.on('free', function onFree(socket, host, port) {
  112579. for (var i = 0, len = self.requests.length; i < len; ++i) {
  112580. var pending = self.requests[i]
  112581. if (pending.host === host && pending.port === port) {
  112582. // Detect the request to connect same origin server,
  112583. // reuse the connection.
  112584. self.requests.splice(i, 1)
  112585. pending.request.onSocket(socket)
  112586. return
  112587. }
  112588. }
  112589. socket.destroy()
  112590. self.removeSocket(socket)
  112591. })
  112592. }
  112593. util.inherits(TunnelingAgent, events.EventEmitter)
  112594. TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
  112595. var self = this
  112596. // Legacy API: addRequest(req, host, port, path)
  112597. if (typeof options === 'string') {
  112598. options = {
  112599. host: options,
  112600. port: arguments[2],
  112601. path: arguments[3]
  112602. };
  112603. }
  112604. if (self.sockets.length >= this.maxSockets) {
  112605. // We are over limit so we'll add it to the queue.
  112606. self.requests.push({host: options.host, port: options.port, request: req})
  112607. return
  112608. }
  112609. // If we are under maxSockets create a new one.
  112610. self.createConnection({host: options.host, port: options.port, request: req})
  112611. }
  112612. TunnelingAgent.prototype.createConnection = function createConnection(pending) {
  112613. var self = this
  112614. self.createSocket(pending, function(socket) {
  112615. socket.on('free', onFree)
  112616. socket.on('close', onCloseOrRemove)
  112617. socket.on('agentRemove', onCloseOrRemove)
  112618. pending.request.onSocket(socket)
  112619. function onFree() {
  112620. self.emit('free', socket, pending.host, pending.port)
  112621. }
  112622. function onCloseOrRemove(err) {
  112623. self.removeSocket(socket)
  112624. socket.removeListener('free', onFree)
  112625. socket.removeListener('close', onCloseOrRemove)
  112626. socket.removeListener('agentRemove', onCloseOrRemove)
  112627. }
  112628. })
  112629. }
  112630. TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
  112631. var self = this
  112632. var placeholder = {}
  112633. self.sockets.push(placeholder)
  112634. var connectOptions = mergeOptions({}, self.proxyOptions,
  112635. { method: 'CONNECT'
  112636. , path: options.host + ':' + options.port
  112637. , agent: false
  112638. }
  112639. )
  112640. if (connectOptions.proxyAuth) {
  112641. connectOptions.headers = connectOptions.headers || {}
  112642. connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
  112643. Buffer.from(connectOptions.proxyAuth).toString('base64')
  112644. }
  112645. debug('making CONNECT request')
  112646. var connectReq = self.request(connectOptions)
  112647. connectReq.useChunkedEncodingByDefault = false // for v0.6
  112648. connectReq.once('response', onResponse) // for v0.6
  112649. connectReq.once('upgrade', onUpgrade) // for v0.6
  112650. connectReq.once('connect', onConnect) // for v0.7 or later
  112651. connectReq.once('error', onError)
  112652. connectReq.end()
  112653. function onResponse(res) {
  112654. // Very hacky. This is necessary to avoid http-parser leaks.
  112655. res.upgrade = true
  112656. }
  112657. function onUpgrade(res, socket, head) {
  112658. // Hacky.
  112659. process.nextTick(function() {
  112660. onConnect(res, socket, head)
  112661. })
  112662. }
  112663. function onConnect(res, socket, head) {
  112664. connectReq.removeAllListeners()
  112665. socket.removeAllListeners()
  112666. if (res.statusCode === 200) {
  112667. assert.equal(head.length, 0)
  112668. debug('tunneling connection has established')
  112669. self.sockets[self.sockets.indexOf(placeholder)] = socket
  112670. cb(socket)
  112671. } else {
  112672. debug('tunneling socket could not be established, statusCode=%d', res.statusCode)
  112673. var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)
  112674. error.code = 'ECONNRESET'
  112675. options.request.emit('error', error)
  112676. self.removeSocket(placeholder)
  112677. }
  112678. }
  112679. function onError(cause) {
  112680. connectReq.removeAllListeners()
  112681. debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack)
  112682. var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)
  112683. error.code = 'ECONNRESET'
  112684. options.request.emit('error', error)
  112685. self.removeSocket(placeholder)
  112686. }
  112687. }
  112688. TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
  112689. var pos = this.sockets.indexOf(socket)
  112690. if (pos === -1) return
  112691. this.sockets.splice(pos, 1)
  112692. var pending = this.requests.shift()
  112693. if (pending) {
  112694. // If we have pending requests and a socket gets closed a new one
  112695. // needs to be created to take over in the pool for the one that closed.
  112696. this.createConnection(pending)
  112697. }
  112698. }
  112699. function createSecureSocket(options, cb) {
  112700. var self = this
  112701. TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
  112702. // 0 is dummy port for v0.6
  112703. var secureSocket = tls.connect(0, mergeOptions({}, self.options,
  112704. { servername: options.host
  112705. , socket: socket
  112706. }
  112707. ))
  112708. self.sockets[self.sockets.indexOf(socket)] = secureSocket
  112709. cb(secureSocket)
  112710. })
  112711. }
  112712. function mergeOptions(target) {
  112713. for (var i = 1, len = arguments.length; i < len; ++i) {
  112714. var overrides = arguments[i]
  112715. if (typeof overrides === 'object') {
  112716. var keys = Object.keys(overrides)
  112717. for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
  112718. var k = keys[j]
  112719. if (overrides[k] !== undefined) {
  112720. target[k] = overrides[k]
  112721. }
  112722. }
  112723. }
  112724. }
  112725. return target
  112726. }
  112727. var debug
  112728. if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
  112729. debug = function() {
  112730. var args = Array.prototype.slice.call(arguments)
  112731. if (typeof args[0] === 'string') {
  112732. args[0] = 'TUNNEL: ' + args[0]
  112733. } else {
  112734. args.unshift('TUNNEL:')
  112735. }
  112736. console.error.apply(console, args)
  112737. }
  112738. } else {
  112739. debug = function() {}
  112740. }
  112741. exports.debug = debug // for test
  112742. }).call(this)}).call(this,require('_process'))
  112743. },{"_process":525,"assert":105,"events":247,"http":612,"https":318,"net":190,"safe-buffer":561,"tls":190,"util":658}],648:[function(require,module,exports){
  112744. module.exports = require('./lib/tunnel');
  112745. },{"./lib/tunnel":649}],649:[function(require,module,exports){
  112746. (function (process,Buffer){(function (){
  112747. 'use strict';
  112748. var net = require('net');
  112749. var tls = require('tls');
  112750. var http = require('http');
  112751. var https = require('https');
  112752. var events = require('events');
  112753. var assert = require('assert');
  112754. var util = require('util');
  112755. exports.httpOverHttp = httpOverHttp;
  112756. exports.httpsOverHttp = httpsOverHttp;
  112757. exports.httpOverHttps = httpOverHttps;
  112758. exports.httpsOverHttps = httpsOverHttps;
  112759. function httpOverHttp(options) {
  112760. var agent = new TunnelingAgent(options);
  112761. agent.request = http.request;
  112762. return agent;
  112763. }
  112764. function httpsOverHttp(options) {
  112765. var agent = new TunnelingAgent(options);
  112766. agent.request = http.request;
  112767. agent.createSocket = createSecureSocket;
  112768. agent.defaultPort = 443;
  112769. return agent;
  112770. }
  112771. function httpOverHttps(options) {
  112772. var agent = new TunnelingAgent(options);
  112773. agent.request = https.request;
  112774. return agent;
  112775. }
  112776. function httpsOverHttps(options) {
  112777. var agent = new TunnelingAgent(options);
  112778. agent.request = https.request;
  112779. agent.createSocket = createSecureSocket;
  112780. agent.defaultPort = 443;
  112781. return agent;
  112782. }
  112783. function TunnelingAgent(options) {
  112784. var self = this;
  112785. self.options = options || {};
  112786. self.proxyOptions = self.options.proxy || {};
  112787. self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
  112788. self.requests = [];
  112789. self.sockets = [];
  112790. self.on('free', function onFree(socket, host, port, localAddress) {
  112791. var options = toOptions(host, port, localAddress);
  112792. for (var i = 0, len = self.requests.length; i < len; ++i) {
  112793. var pending = self.requests[i];
  112794. if (pending.host === options.host && pending.port === options.port) {
  112795. // Detect the request to connect same origin server,
  112796. // reuse the connection.
  112797. self.requests.splice(i, 1);
  112798. pending.request.onSocket(socket);
  112799. return;
  112800. }
  112801. }
  112802. socket.destroy();
  112803. self.removeSocket(socket);
  112804. });
  112805. }
  112806. util.inherits(TunnelingAgent, events.EventEmitter);
  112807. TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
  112808. var self = this;
  112809. var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
  112810. if (self.sockets.length >= this.maxSockets) {
  112811. // We are over limit so we'll add it to the queue.
  112812. self.requests.push(options);
  112813. return;
  112814. }
  112815. // If we are under maxSockets create a new one.
  112816. self.createSocket(options, function(socket) {
  112817. socket.on('free', onFree);
  112818. socket.on('close', onCloseOrRemove);
  112819. socket.on('agentRemove', onCloseOrRemove);
  112820. req.onSocket(socket);
  112821. function onFree() {
  112822. self.emit('free', socket, options);
  112823. }
  112824. function onCloseOrRemove(err) {
  112825. self.removeSocket(socket);
  112826. socket.removeListener('free', onFree);
  112827. socket.removeListener('close', onCloseOrRemove);
  112828. socket.removeListener('agentRemove', onCloseOrRemove);
  112829. }
  112830. });
  112831. };
  112832. TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
  112833. var self = this;
  112834. var placeholder = {};
  112835. self.sockets.push(placeholder);
  112836. var connectOptions = mergeOptions({}, self.proxyOptions, {
  112837. method: 'CONNECT',
  112838. path: options.host + ':' + options.port,
  112839. agent: false,
  112840. headers: {
  112841. host: options.host + ':' + options.port
  112842. }
  112843. });
  112844. if (options.localAddress) {
  112845. connectOptions.localAddress = options.localAddress;
  112846. }
  112847. if (connectOptions.proxyAuth) {
  112848. connectOptions.headers = connectOptions.headers || {};
  112849. connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
  112850. new Buffer(connectOptions.proxyAuth).toString('base64');
  112851. }
  112852. debug('making CONNECT request');
  112853. var connectReq = self.request(connectOptions);
  112854. connectReq.useChunkedEncodingByDefault = false; // for v0.6
  112855. connectReq.once('response', onResponse); // for v0.6
  112856. connectReq.once('upgrade', onUpgrade); // for v0.6
  112857. connectReq.once('connect', onConnect); // for v0.7 or later
  112858. connectReq.once('error', onError);
  112859. connectReq.end();
  112860. function onResponse(res) {
  112861. // Very hacky. This is necessary to avoid http-parser leaks.
  112862. res.upgrade = true;
  112863. }
  112864. function onUpgrade(res, socket, head) {
  112865. // Hacky.
  112866. process.nextTick(function() {
  112867. onConnect(res, socket, head);
  112868. });
  112869. }
  112870. function onConnect(res, socket, head) {
  112871. connectReq.removeAllListeners();
  112872. socket.removeAllListeners();
  112873. if (res.statusCode !== 200) {
  112874. debug('tunneling socket could not be established, statusCode=%d',
  112875. res.statusCode);
  112876. socket.destroy();
  112877. var error = new Error('tunneling socket could not be established, ' +
  112878. 'statusCode=' + res.statusCode);
  112879. error.code = 'ECONNRESET';
  112880. options.request.emit('error', error);
  112881. self.removeSocket(placeholder);
  112882. return;
  112883. }
  112884. if (head.length > 0) {
  112885. debug('got illegal response body from proxy');
  112886. socket.destroy();
  112887. var error = new Error('got illegal response body from proxy');
  112888. error.code = 'ECONNRESET';
  112889. options.request.emit('error', error);
  112890. self.removeSocket(placeholder);
  112891. return;
  112892. }
  112893. debug('tunneling connection has established');
  112894. self.sockets[self.sockets.indexOf(placeholder)] = socket;
  112895. return cb(socket);
  112896. }
  112897. function onError(cause) {
  112898. connectReq.removeAllListeners();
  112899. debug('tunneling socket could not be established, cause=%s\n',
  112900. cause.message, cause.stack);
  112901. var error = new Error('tunneling socket could not be established, ' +
  112902. 'cause=' + cause.message);
  112903. error.code = 'ECONNRESET';
  112904. options.request.emit('error', error);
  112905. self.removeSocket(placeholder);
  112906. }
  112907. };
  112908. TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
  112909. var pos = this.sockets.indexOf(socket)
  112910. if (pos === -1) {
  112911. return;
  112912. }
  112913. this.sockets.splice(pos, 1);
  112914. var pending = this.requests.shift();
  112915. if (pending) {
  112916. // If we have pending requests and a socket gets closed a new one
  112917. // needs to be created to take over in the pool for the one that closed.
  112918. this.createSocket(pending, function(socket) {
  112919. pending.request.onSocket(socket);
  112920. });
  112921. }
  112922. };
  112923. function createSecureSocket(options, cb) {
  112924. var self = this;
  112925. TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
  112926. var hostHeader = options.request.getHeader('host');
  112927. var tlsOptions = mergeOptions({}, self.options, {
  112928. socket: socket,
  112929. servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
  112930. });
  112931. // 0 is dummy port for v0.6
  112932. var secureSocket = tls.connect(0, tlsOptions);
  112933. self.sockets[self.sockets.indexOf(socket)] = secureSocket;
  112934. cb(secureSocket);
  112935. });
  112936. }
  112937. function toOptions(host, port, localAddress) {
  112938. if (typeof host === 'string') { // since v0.10
  112939. return {
  112940. host: host,
  112941. port: port,
  112942. localAddress: localAddress
  112943. };
  112944. }
  112945. return host; // for v0.11 or later
  112946. }
  112947. function mergeOptions(target) {
  112948. for (var i = 1, len = arguments.length; i < len; ++i) {
  112949. var overrides = arguments[i];
  112950. if (typeof overrides === 'object') {
  112951. var keys = Object.keys(overrides);
  112952. for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
  112953. var k = keys[j];
  112954. if (overrides[k] !== undefined) {
  112955. target[k] = overrides[k];
  112956. }
  112957. }
  112958. }
  112959. }
  112960. return target;
  112961. }
  112962. var debug;
  112963. if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
  112964. debug = function() {
  112965. var args = Array.prototype.slice.call(arguments);
  112966. if (typeof args[0] === 'string') {
  112967. args[0] = 'TUNNEL: ' + args[0];
  112968. } else {
  112969. args.unshift('TUNNEL:');
  112970. }
  112971. console.error.apply(console, args);
  112972. }
  112973. } else {
  112974. debug = function() {};
  112975. }
  112976. exports.debug = debug; // for test
  112977. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  112978. },{"_process":525,"assert":105,"buffer":193,"events":247,"http":612,"https":318,"net":190,"tls":190,"util":658}],650:[function(require,module,exports){
  112979. (function(nacl) {
  112980. 'use strict';
  112981. // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
  112982. // Public domain.
  112983. //
  112984. // Implementation derived from TweetNaCl version 20140427.
  112985. // See for details: http://tweetnacl.cr.yp.to/
  112986. var gf = function(init) {
  112987. var i, r = new Float64Array(16);
  112988. if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
  112989. return r;
  112990. };
  112991. // Pluggable, initialized in high-level API below.
  112992. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
  112993. var _0 = new Uint8Array(16);
  112994. var _9 = new Uint8Array(32); _9[0] = 9;
  112995. var gf0 = gf(),
  112996. gf1 = gf([1]),
  112997. _121665 = gf([0xdb41, 1]),
  112998. D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
  112999. D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
  113000. X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
  113001. Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
  113002. I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
  113003. function ts64(x, i, h, l) {
  113004. x[i] = (h >> 24) & 0xff;
  113005. x[i+1] = (h >> 16) & 0xff;
  113006. x[i+2] = (h >> 8) & 0xff;
  113007. x[i+3] = h & 0xff;
  113008. x[i+4] = (l >> 24) & 0xff;
  113009. x[i+5] = (l >> 16) & 0xff;
  113010. x[i+6] = (l >> 8) & 0xff;
  113011. x[i+7] = l & 0xff;
  113012. }
  113013. function vn(x, xi, y, yi, n) {
  113014. var i,d = 0;
  113015. for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
  113016. return (1 & ((d - 1) >>> 8)) - 1;
  113017. }
  113018. function crypto_verify_16(x, xi, y, yi) {
  113019. return vn(x,xi,y,yi,16);
  113020. }
  113021. function crypto_verify_32(x, xi, y, yi) {
  113022. return vn(x,xi,y,yi,32);
  113023. }
  113024. function core_salsa20(o, p, k, c) {
  113025. var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
  113026. j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
  113027. j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
  113028. j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
  113029. j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
  113030. j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
  113031. j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
  113032. j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
  113033. j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
  113034. j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
  113035. j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
  113036. j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
  113037. j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
  113038. j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
  113039. j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
  113040. j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
  113041. var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
  113042. x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
  113043. x15 = j15, u;
  113044. for (var i = 0; i < 20; i += 2) {
  113045. u = x0 + x12 | 0;
  113046. x4 ^= u<<7 | u>>>(32-7);
  113047. u = x4 + x0 | 0;
  113048. x8 ^= u<<9 | u>>>(32-9);
  113049. u = x8 + x4 | 0;
  113050. x12 ^= u<<13 | u>>>(32-13);
  113051. u = x12 + x8 | 0;
  113052. x0 ^= u<<18 | u>>>(32-18);
  113053. u = x5 + x1 | 0;
  113054. x9 ^= u<<7 | u>>>(32-7);
  113055. u = x9 + x5 | 0;
  113056. x13 ^= u<<9 | u>>>(32-9);
  113057. u = x13 + x9 | 0;
  113058. x1 ^= u<<13 | u>>>(32-13);
  113059. u = x1 + x13 | 0;
  113060. x5 ^= u<<18 | u>>>(32-18);
  113061. u = x10 + x6 | 0;
  113062. x14 ^= u<<7 | u>>>(32-7);
  113063. u = x14 + x10 | 0;
  113064. x2 ^= u<<9 | u>>>(32-9);
  113065. u = x2 + x14 | 0;
  113066. x6 ^= u<<13 | u>>>(32-13);
  113067. u = x6 + x2 | 0;
  113068. x10 ^= u<<18 | u>>>(32-18);
  113069. u = x15 + x11 | 0;
  113070. x3 ^= u<<7 | u>>>(32-7);
  113071. u = x3 + x15 | 0;
  113072. x7 ^= u<<9 | u>>>(32-9);
  113073. u = x7 + x3 | 0;
  113074. x11 ^= u<<13 | u>>>(32-13);
  113075. u = x11 + x7 | 0;
  113076. x15 ^= u<<18 | u>>>(32-18);
  113077. u = x0 + x3 | 0;
  113078. x1 ^= u<<7 | u>>>(32-7);
  113079. u = x1 + x0 | 0;
  113080. x2 ^= u<<9 | u>>>(32-9);
  113081. u = x2 + x1 | 0;
  113082. x3 ^= u<<13 | u>>>(32-13);
  113083. u = x3 + x2 | 0;
  113084. x0 ^= u<<18 | u>>>(32-18);
  113085. u = x5 + x4 | 0;
  113086. x6 ^= u<<7 | u>>>(32-7);
  113087. u = x6 + x5 | 0;
  113088. x7 ^= u<<9 | u>>>(32-9);
  113089. u = x7 + x6 | 0;
  113090. x4 ^= u<<13 | u>>>(32-13);
  113091. u = x4 + x7 | 0;
  113092. x5 ^= u<<18 | u>>>(32-18);
  113093. u = x10 + x9 | 0;
  113094. x11 ^= u<<7 | u>>>(32-7);
  113095. u = x11 + x10 | 0;
  113096. x8 ^= u<<9 | u>>>(32-9);
  113097. u = x8 + x11 | 0;
  113098. x9 ^= u<<13 | u>>>(32-13);
  113099. u = x9 + x8 | 0;
  113100. x10 ^= u<<18 | u>>>(32-18);
  113101. u = x15 + x14 | 0;
  113102. x12 ^= u<<7 | u>>>(32-7);
  113103. u = x12 + x15 | 0;
  113104. x13 ^= u<<9 | u>>>(32-9);
  113105. u = x13 + x12 | 0;
  113106. x14 ^= u<<13 | u>>>(32-13);
  113107. u = x14 + x13 | 0;
  113108. x15 ^= u<<18 | u>>>(32-18);
  113109. }
  113110. x0 = x0 + j0 | 0;
  113111. x1 = x1 + j1 | 0;
  113112. x2 = x2 + j2 | 0;
  113113. x3 = x3 + j3 | 0;
  113114. x4 = x4 + j4 | 0;
  113115. x5 = x5 + j5 | 0;
  113116. x6 = x6 + j6 | 0;
  113117. x7 = x7 + j7 | 0;
  113118. x8 = x8 + j8 | 0;
  113119. x9 = x9 + j9 | 0;
  113120. x10 = x10 + j10 | 0;
  113121. x11 = x11 + j11 | 0;
  113122. x12 = x12 + j12 | 0;
  113123. x13 = x13 + j13 | 0;
  113124. x14 = x14 + j14 | 0;
  113125. x15 = x15 + j15 | 0;
  113126. o[ 0] = x0 >>> 0 & 0xff;
  113127. o[ 1] = x0 >>> 8 & 0xff;
  113128. o[ 2] = x0 >>> 16 & 0xff;
  113129. o[ 3] = x0 >>> 24 & 0xff;
  113130. o[ 4] = x1 >>> 0 & 0xff;
  113131. o[ 5] = x1 >>> 8 & 0xff;
  113132. o[ 6] = x1 >>> 16 & 0xff;
  113133. o[ 7] = x1 >>> 24 & 0xff;
  113134. o[ 8] = x2 >>> 0 & 0xff;
  113135. o[ 9] = x2 >>> 8 & 0xff;
  113136. o[10] = x2 >>> 16 & 0xff;
  113137. o[11] = x2 >>> 24 & 0xff;
  113138. o[12] = x3 >>> 0 & 0xff;
  113139. o[13] = x3 >>> 8 & 0xff;
  113140. o[14] = x3 >>> 16 & 0xff;
  113141. o[15] = x3 >>> 24 & 0xff;
  113142. o[16] = x4 >>> 0 & 0xff;
  113143. o[17] = x4 >>> 8 & 0xff;
  113144. o[18] = x4 >>> 16 & 0xff;
  113145. o[19] = x4 >>> 24 & 0xff;
  113146. o[20] = x5 >>> 0 & 0xff;
  113147. o[21] = x5 >>> 8 & 0xff;
  113148. o[22] = x5 >>> 16 & 0xff;
  113149. o[23] = x5 >>> 24 & 0xff;
  113150. o[24] = x6 >>> 0 & 0xff;
  113151. o[25] = x6 >>> 8 & 0xff;
  113152. o[26] = x6 >>> 16 & 0xff;
  113153. o[27] = x6 >>> 24 & 0xff;
  113154. o[28] = x7 >>> 0 & 0xff;
  113155. o[29] = x7 >>> 8 & 0xff;
  113156. o[30] = x7 >>> 16 & 0xff;
  113157. o[31] = x7 >>> 24 & 0xff;
  113158. o[32] = x8 >>> 0 & 0xff;
  113159. o[33] = x8 >>> 8 & 0xff;
  113160. o[34] = x8 >>> 16 & 0xff;
  113161. o[35] = x8 >>> 24 & 0xff;
  113162. o[36] = x9 >>> 0 & 0xff;
  113163. o[37] = x9 >>> 8 & 0xff;
  113164. o[38] = x9 >>> 16 & 0xff;
  113165. o[39] = x9 >>> 24 & 0xff;
  113166. o[40] = x10 >>> 0 & 0xff;
  113167. o[41] = x10 >>> 8 & 0xff;
  113168. o[42] = x10 >>> 16 & 0xff;
  113169. o[43] = x10 >>> 24 & 0xff;
  113170. o[44] = x11 >>> 0 & 0xff;
  113171. o[45] = x11 >>> 8 & 0xff;
  113172. o[46] = x11 >>> 16 & 0xff;
  113173. o[47] = x11 >>> 24 & 0xff;
  113174. o[48] = x12 >>> 0 & 0xff;
  113175. o[49] = x12 >>> 8 & 0xff;
  113176. o[50] = x12 >>> 16 & 0xff;
  113177. o[51] = x12 >>> 24 & 0xff;
  113178. o[52] = x13 >>> 0 & 0xff;
  113179. o[53] = x13 >>> 8 & 0xff;
  113180. o[54] = x13 >>> 16 & 0xff;
  113181. o[55] = x13 >>> 24 & 0xff;
  113182. o[56] = x14 >>> 0 & 0xff;
  113183. o[57] = x14 >>> 8 & 0xff;
  113184. o[58] = x14 >>> 16 & 0xff;
  113185. o[59] = x14 >>> 24 & 0xff;
  113186. o[60] = x15 >>> 0 & 0xff;
  113187. o[61] = x15 >>> 8 & 0xff;
  113188. o[62] = x15 >>> 16 & 0xff;
  113189. o[63] = x15 >>> 24 & 0xff;
  113190. }
  113191. function core_hsalsa20(o,p,k,c) {
  113192. var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
  113193. j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
  113194. j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
  113195. j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
  113196. j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
  113197. j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
  113198. j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
  113199. j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
  113200. j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
  113201. j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
  113202. j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
  113203. j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
  113204. j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
  113205. j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
  113206. j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
  113207. j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
  113208. var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
  113209. x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
  113210. x15 = j15, u;
  113211. for (var i = 0; i < 20; i += 2) {
  113212. u = x0 + x12 | 0;
  113213. x4 ^= u<<7 | u>>>(32-7);
  113214. u = x4 + x0 | 0;
  113215. x8 ^= u<<9 | u>>>(32-9);
  113216. u = x8 + x4 | 0;
  113217. x12 ^= u<<13 | u>>>(32-13);
  113218. u = x12 + x8 | 0;
  113219. x0 ^= u<<18 | u>>>(32-18);
  113220. u = x5 + x1 | 0;
  113221. x9 ^= u<<7 | u>>>(32-7);
  113222. u = x9 + x5 | 0;
  113223. x13 ^= u<<9 | u>>>(32-9);
  113224. u = x13 + x9 | 0;
  113225. x1 ^= u<<13 | u>>>(32-13);
  113226. u = x1 + x13 | 0;
  113227. x5 ^= u<<18 | u>>>(32-18);
  113228. u = x10 + x6 | 0;
  113229. x14 ^= u<<7 | u>>>(32-7);
  113230. u = x14 + x10 | 0;
  113231. x2 ^= u<<9 | u>>>(32-9);
  113232. u = x2 + x14 | 0;
  113233. x6 ^= u<<13 | u>>>(32-13);
  113234. u = x6 + x2 | 0;
  113235. x10 ^= u<<18 | u>>>(32-18);
  113236. u = x15 + x11 | 0;
  113237. x3 ^= u<<7 | u>>>(32-7);
  113238. u = x3 + x15 | 0;
  113239. x7 ^= u<<9 | u>>>(32-9);
  113240. u = x7 + x3 | 0;
  113241. x11 ^= u<<13 | u>>>(32-13);
  113242. u = x11 + x7 | 0;
  113243. x15 ^= u<<18 | u>>>(32-18);
  113244. u = x0 + x3 | 0;
  113245. x1 ^= u<<7 | u>>>(32-7);
  113246. u = x1 + x0 | 0;
  113247. x2 ^= u<<9 | u>>>(32-9);
  113248. u = x2 + x1 | 0;
  113249. x3 ^= u<<13 | u>>>(32-13);
  113250. u = x3 + x2 | 0;
  113251. x0 ^= u<<18 | u>>>(32-18);
  113252. u = x5 + x4 | 0;
  113253. x6 ^= u<<7 | u>>>(32-7);
  113254. u = x6 + x5 | 0;
  113255. x7 ^= u<<9 | u>>>(32-9);
  113256. u = x7 + x6 | 0;
  113257. x4 ^= u<<13 | u>>>(32-13);
  113258. u = x4 + x7 | 0;
  113259. x5 ^= u<<18 | u>>>(32-18);
  113260. u = x10 + x9 | 0;
  113261. x11 ^= u<<7 | u>>>(32-7);
  113262. u = x11 + x10 | 0;
  113263. x8 ^= u<<9 | u>>>(32-9);
  113264. u = x8 + x11 | 0;
  113265. x9 ^= u<<13 | u>>>(32-13);
  113266. u = x9 + x8 | 0;
  113267. x10 ^= u<<18 | u>>>(32-18);
  113268. u = x15 + x14 | 0;
  113269. x12 ^= u<<7 | u>>>(32-7);
  113270. u = x12 + x15 | 0;
  113271. x13 ^= u<<9 | u>>>(32-9);
  113272. u = x13 + x12 | 0;
  113273. x14 ^= u<<13 | u>>>(32-13);
  113274. u = x14 + x13 | 0;
  113275. x15 ^= u<<18 | u>>>(32-18);
  113276. }
  113277. o[ 0] = x0 >>> 0 & 0xff;
  113278. o[ 1] = x0 >>> 8 & 0xff;
  113279. o[ 2] = x0 >>> 16 & 0xff;
  113280. o[ 3] = x0 >>> 24 & 0xff;
  113281. o[ 4] = x5 >>> 0 & 0xff;
  113282. o[ 5] = x5 >>> 8 & 0xff;
  113283. o[ 6] = x5 >>> 16 & 0xff;
  113284. o[ 7] = x5 >>> 24 & 0xff;
  113285. o[ 8] = x10 >>> 0 & 0xff;
  113286. o[ 9] = x10 >>> 8 & 0xff;
  113287. o[10] = x10 >>> 16 & 0xff;
  113288. o[11] = x10 >>> 24 & 0xff;
  113289. o[12] = x15 >>> 0 & 0xff;
  113290. o[13] = x15 >>> 8 & 0xff;
  113291. o[14] = x15 >>> 16 & 0xff;
  113292. o[15] = x15 >>> 24 & 0xff;
  113293. o[16] = x6 >>> 0 & 0xff;
  113294. o[17] = x6 >>> 8 & 0xff;
  113295. o[18] = x6 >>> 16 & 0xff;
  113296. o[19] = x6 >>> 24 & 0xff;
  113297. o[20] = x7 >>> 0 & 0xff;
  113298. o[21] = x7 >>> 8 & 0xff;
  113299. o[22] = x7 >>> 16 & 0xff;
  113300. o[23] = x7 >>> 24 & 0xff;
  113301. o[24] = x8 >>> 0 & 0xff;
  113302. o[25] = x8 >>> 8 & 0xff;
  113303. o[26] = x8 >>> 16 & 0xff;
  113304. o[27] = x8 >>> 24 & 0xff;
  113305. o[28] = x9 >>> 0 & 0xff;
  113306. o[29] = x9 >>> 8 & 0xff;
  113307. o[30] = x9 >>> 16 & 0xff;
  113308. o[31] = x9 >>> 24 & 0xff;
  113309. }
  113310. function crypto_core_salsa20(out,inp,k,c) {
  113311. core_salsa20(out,inp,k,c);
  113312. }
  113313. function crypto_core_hsalsa20(out,inp,k,c) {
  113314. core_hsalsa20(out,inp,k,c);
  113315. }
  113316. var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
  113317. // "expand 32-byte k"
  113318. function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
  113319. var z = new Uint8Array(16), x = new Uint8Array(64);
  113320. var u, i;
  113321. for (i = 0; i < 16; i++) z[i] = 0;
  113322. for (i = 0; i < 8; i++) z[i] = n[i];
  113323. while (b >= 64) {
  113324. crypto_core_salsa20(x,z,k,sigma);
  113325. for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
  113326. u = 1;
  113327. for (i = 8; i < 16; i++) {
  113328. u = u + (z[i] & 0xff) | 0;
  113329. z[i] = u & 0xff;
  113330. u >>>= 8;
  113331. }
  113332. b -= 64;
  113333. cpos += 64;
  113334. mpos += 64;
  113335. }
  113336. if (b > 0) {
  113337. crypto_core_salsa20(x,z,k,sigma);
  113338. for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
  113339. }
  113340. return 0;
  113341. }
  113342. function crypto_stream_salsa20(c,cpos,b,n,k) {
  113343. var z = new Uint8Array(16), x = new Uint8Array(64);
  113344. var u, i;
  113345. for (i = 0; i < 16; i++) z[i] = 0;
  113346. for (i = 0; i < 8; i++) z[i] = n[i];
  113347. while (b >= 64) {
  113348. crypto_core_salsa20(x,z,k,sigma);
  113349. for (i = 0; i < 64; i++) c[cpos+i] = x[i];
  113350. u = 1;
  113351. for (i = 8; i < 16; i++) {
  113352. u = u + (z[i] & 0xff) | 0;
  113353. z[i] = u & 0xff;
  113354. u >>>= 8;
  113355. }
  113356. b -= 64;
  113357. cpos += 64;
  113358. }
  113359. if (b > 0) {
  113360. crypto_core_salsa20(x,z,k,sigma);
  113361. for (i = 0; i < b; i++) c[cpos+i] = x[i];
  113362. }
  113363. return 0;
  113364. }
  113365. function crypto_stream(c,cpos,d,n,k) {
  113366. var s = new Uint8Array(32);
  113367. crypto_core_hsalsa20(s,n,k,sigma);
  113368. var sn = new Uint8Array(8);
  113369. for (var i = 0; i < 8; i++) sn[i] = n[i+16];
  113370. return crypto_stream_salsa20(c,cpos,d,sn,s);
  113371. }
  113372. function crypto_stream_xor(c,cpos,m,mpos,d,n,k) {
  113373. var s = new Uint8Array(32);
  113374. crypto_core_hsalsa20(s,n,k,sigma);
  113375. var sn = new Uint8Array(8);
  113376. for (var i = 0; i < 8; i++) sn[i] = n[i+16];
  113377. return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
  113378. }
  113379. /*
  113380. * Port of Andrew Moon's Poly1305-donna-16. Public domain.
  113381. * https://github.com/floodyberry/poly1305-donna
  113382. */
  113383. var poly1305 = function(key) {
  113384. this.buffer = new Uint8Array(16);
  113385. this.r = new Uint16Array(10);
  113386. this.h = new Uint16Array(10);
  113387. this.pad = new Uint16Array(8);
  113388. this.leftover = 0;
  113389. this.fin = 0;
  113390. var t0, t1, t2, t3, t4, t5, t6, t7;
  113391. t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
  113392. t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
  113393. t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
  113394. t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
  113395. t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
  113396. this.r[5] = ((t4 >>> 1)) & 0x1ffe;
  113397. t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
  113398. t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
  113399. t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
  113400. this.r[9] = ((t7 >>> 5)) & 0x007f;
  113401. this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
  113402. this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
  113403. this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
  113404. this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
  113405. this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
  113406. this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
  113407. this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
  113408. this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
  113409. };
  113410. poly1305.prototype.blocks = function(m, mpos, bytes) {
  113411. var hibit = this.fin ? 0 : (1 << 11);
  113412. var t0, t1, t2, t3, t4, t5, t6, t7, c;
  113413. var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
  113414. var h0 = this.h[0],
  113415. h1 = this.h[1],
  113416. h2 = this.h[2],
  113417. h3 = this.h[3],
  113418. h4 = this.h[4],
  113419. h5 = this.h[5],
  113420. h6 = this.h[6],
  113421. h7 = this.h[7],
  113422. h8 = this.h[8],
  113423. h9 = this.h[9];
  113424. var r0 = this.r[0],
  113425. r1 = this.r[1],
  113426. r2 = this.r[2],
  113427. r3 = this.r[3],
  113428. r4 = this.r[4],
  113429. r5 = this.r[5],
  113430. r6 = this.r[6],
  113431. r7 = this.r[7],
  113432. r8 = this.r[8],
  113433. r9 = this.r[9];
  113434. while (bytes >= 16) {
  113435. t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
  113436. t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
  113437. t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
  113438. t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
  113439. t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
  113440. h5 += ((t4 >>> 1)) & 0x1fff;
  113441. t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
  113442. t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
  113443. t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
  113444. h9 += ((t7 >>> 5)) | hibit;
  113445. c = 0;
  113446. d0 = c;
  113447. d0 += h0 * r0;
  113448. d0 += h1 * (5 * r9);
  113449. d0 += h2 * (5 * r8);
  113450. d0 += h3 * (5 * r7);
  113451. d0 += h4 * (5 * r6);
  113452. c = (d0 >>> 13); d0 &= 0x1fff;
  113453. d0 += h5 * (5 * r5);
  113454. d0 += h6 * (5 * r4);
  113455. d0 += h7 * (5 * r3);
  113456. d0 += h8 * (5 * r2);
  113457. d0 += h9 * (5 * r1);
  113458. c += (d0 >>> 13); d0 &= 0x1fff;
  113459. d1 = c;
  113460. d1 += h0 * r1;
  113461. d1 += h1 * r0;
  113462. d1 += h2 * (5 * r9);
  113463. d1 += h3 * (5 * r8);
  113464. d1 += h4 * (5 * r7);
  113465. c = (d1 >>> 13); d1 &= 0x1fff;
  113466. d1 += h5 * (5 * r6);
  113467. d1 += h6 * (5 * r5);
  113468. d1 += h7 * (5 * r4);
  113469. d1 += h8 * (5 * r3);
  113470. d1 += h9 * (5 * r2);
  113471. c += (d1 >>> 13); d1 &= 0x1fff;
  113472. d2 = c;
  113473. d2 += h0 * r2;
  113474. d2 += h1 * r1;
  113475. d2 += h2 * r0;
  113476. d2 += h3 * (5 * r9);
  113477. d2 += h4 * (5 * r8);
  113478. c = (d2 >>> 13); d2 &= 0x1fff;
  113479. d2 += h5 * (5 * r7);
  113480. d2 += h6 * (5 * r6);
  113481. d2 += h7 * (5 * r5);
  113482. d2 += h8 * (5 * r4);
  113483. d2 += h9 * (5 * r3);
  113484. c += (d2 >>> 13); d2 &= 0x1fff;
  113485. d3 = c;
  113486. d3 += h0 * r3;
  113487. d3 += h1 * r2;
  113488. d3 += h2 * r1;
  113489. d3 += h3 * r0;
  113490. d3 += h4 * (5 * r9);
  113491. c = (d3 >>> 13); d3 &= 0x1fff;
  113492. d3 += h5 * (5 * r8);
  113493. d3 += h6 * (5 * r7);
  113494. d3 += h7 * (5 * r6);
  113495. d3 += h8 * (5 * r5);
  113496. d3 += h9 * (5 * r4);
  113497. c += (d3 >>> 13); d3 &= 0x1fff;
  113498. d4 = c;
  113499. d4 += h0 * r4;
  113500. d4 += h1 * r3;
  113501. d4 += h2 * r2;
  113502. d4 += h3 * r1;
  113503. d4 += h4 * r0;
  113504. c = (d4 >>> 13); d4 &= 0x1fff;
  113505. d4 += h5 * (5 * r9);
  113506. d4 += h6 * (5 * r8);
  113507. d4 += h7 * (5 * r7);
  113508. d4 += h8 * (5 * r6);
  113509. d4 += h9 * (5 * r5);
  113510. c += (d4 >>> 13); d4 &= 0x1fff;
  113511. d5 = c;
  113512. d5 += h0 * r5;
  113513. d5 += h1 * r4;
  113514. d5 += h2 * r3;
  113515. d5 += h3 * r2;
  113516. d5 += h4 * r1;
  113517. c = (d5 >>> 13); d5 &= 0x1fff;
  113518. d5 += h5 * r0;
  113519. d5 += h6 * (5 * r9);
  113520. d5 += h7 * (5 * r8);
  113521. d5 += h8 * (5 * r7);
  113522. d5 += h9 * (5 * r6);
  113523. c += (d5 >>> 13); d5 &= 0x1fff;
  113524. d6 = c;
  113525. d6 += h0 * r6;
  113526. d6 += h1 * r5;
  113527. d6 += h2 * r4;
  113528. d6 += h3 * r3;
  113529. d6 += h4 * r2;
  113530. c = (d6 >>> 13); d6 &= 0x1fff;
  113531. d6 += h5 * r1;
  113532. d6 += h6 * r0;
  113533. d6 += h7 * (5 * r9);
  113534. d6 += h8 * (5 * r8);
  113535. d6 += h9 * (5 * r7);
  113536. c += (d6 >>> 13); d6 &= 0x1fff;
  113537. d7 = c;
  113538. d7 += h0 * r7;
  113539. d7 += h1 * r6;
  113540. d7 += h2 * r5;
  113541. d7 += h3 * r4;
  113542. d7 += h4 * r3;
  113543. c = (d7 >>> 13); d7 &= 0x1fff;
  113544. d7 += h5 * r2;
  113545. d7 += h6 * r1;
  113546. d7 += h7 * r0;
  113547. d7 += h8 * (5 * r9);
  113548. d7 += h9 * (5 * r8);
  113549. c += (d7 >>> 13); d7 &= 0x1fff;
  113550. d8 = c;
  113551. d8 += h0 * r8;
  113552. d8 += h1 * r7;
  113553. d8 += h2 * r6;
  113554. d8 += h3 * r5;
  113555. d8 += h4 * r4;
  113556. c = (d8 >>> 13); d8 &= 0x1fff;
  113557. d8 += h5 * r3;
  113558. d8 += h6 * r2;
  113559. d8 += h7 * r1;
  113560. d8 += h8 * r0;
  113561. d8 += h9 * (5 * r9);
  113562. c += (d8 >>> 13); d8 &= 0x1fff;
  113563. d9 = c;
  113564. d9 += h0 * r9;
  113565. d9 += h1 * r8;
  113566. d9 += h2 * r7;
  113567. d9 += h3 * r6;
  113568. d9 += h4 * r5;
  113569. c = (d9 >>> 13); d9 &= 0x1fff;
  113570. d9 += h5 * r4;
  113571. d9 += h6 * r3;
  113572. d9 += h7 * r2;
  113573. d9 += h8 * r1;
  113574. d9 += h9 * r0;
  113575. c += (d9 >>> 13); d9 &= 0x1fff;
  113576. c = (((c << 2) + c)) | 0;
  113577. c = (c + d0) | 0;
  113578. d0 = c & 0x1fff;
  113579. c = (c >>> 13);
  113580. d1 += c;
  113581. h0 = d0;
  113582. h1 = d1;
  113583. h2 = d2;
  113584. h3 = d3;
  113585. h4 = d4;
  113586. h5 = d5;
  113587. h6 = d6;
  113588. h7 = d7;
  113589. h8 = d8;
  113590. h9 = d9;
  113591. mpos += 16;
  113592. bytes -= 16;
  113593. }
  113594. this.h[0] = h0;
  113595. this.h[1] = h1;
  113596. this.h[2] = h2;
  113597. this.h[3] = h3;
  113598. this.h[4] = h4;
  113599. this.h[5] = h5;
  113600. this.h[6] = h6;
  113601. this.h[7] = h7;
  113602. this.h[8] = h8;
  113603. this.h[9] = h9;
  113604. };
  113605. poly1305.prototype.finish = function(mac, macpos) {
  113606. var g = new Uint16Array(10);
  113607. var c, mask, f, i;
  113608. if (this.leftover) {
  113609. i = this.leftover;
  113610. this.buffer[i++] = 1;
  113611. for (; i < 16; i++) this.buffer[i] = 0;
  113612. this.fin = 1;
  113613. this.blocks(this.buffer, 0, 16);
  113614. }
  113615. c = this.h[1] >>> 13;
  113616. this.h[1] &= 0x1fff;
  113617. for (i = 2; i < 10; i++) {
  113618. this.h[i] += c;
  113619. c = this.h[i] >>> 13;
  113620. this.h[i] &= 0x1fff;
  113621. }
  113622. this.h[0] += (c * 5);
  113623. c = this.h[0] >>> 13;
  113624. this.h[0] &= 0x1fff;
  113625. this.h[1] += c;
  113626. c = this.h[1] >>> 13;
  113627. this.h[1] &= 0x1fff;
  113628. this.h[2] += c;
  113629. g[0] = this.h[0] + 5;
  113630. c = g[0] >>> 13;
  113631. g[0] &= 0x1fff;
  113632. for (i = 1; i < 10; i++) {
  113633. g[i] = this.h[i] + c;
  113634. c = g[i] >>> 13;
  113635. g[i] &= 0x1fff;
  113636. }
  113637. g[9] -= (1 << 13);
  113638. mask = (c ^ 1) - 1;
  113639. for (i = 0; i < 10; i++) g[i] &= mask;
  113640. mask = ~mask;
  113641. for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
  113642. this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
  113643. this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
  113644. this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
  113645. this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
  113646. this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
  113647. this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
  113648. this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
  113649. this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
  113650. f = this.h[0] + this.pad[0];
  113651. this.h[0] = f & 0xffff;
  113652. for (i = 1; i < 8; i++) {
  113653. f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
  113654. this.h[i] = f & 0xffff;
  113655. }
  113656. mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;
  113657. mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;
  113658. mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;
  113659. mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;
  113660. mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;
  113661. mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;
  113662. mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;
  113663. mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;
  113664. mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;
  113665. mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;
  113666. mac[macpos+10] = (this.h[5] >>> 0) & 0xff;
  113667. mac[macpos+11] = (this.h[5] >>> 8) & 0xff;
  113668. mac[macpos+12] = (this.h[6] >>> 0) & 0xff;
  113669. mac[macpos+13] = (this.h[6] >>> 8) & 0xff;
  113670. mac[macpos+14] = (this.h[7] >>> 0) & 0xff;
  113671. mac[macpos+15] = (this.h[7] >>> 8) & 0xff;
  113672. };
  113673. poly1305.prototype.update = function(m, mpos, bytes) {
  113674. var i, want;
  113675. if (this.leftover) {
  113676. want = (16 - this.leftover);
  113677. if (want > bytes)
  113678. want = bytes;
  113679. for (i = 0; i < want; i++)
  113680. this.buffer[this.leftover + i] = m[mpos+i];
  113681. bytes -= want;
  113682. mpos += want;
  113683. this.leftover += want;
  113684. if (this.leftover < 16)
  113685. return;
  113686. this.blocks(this.buffer, 0, 16);
  113687. this.leftover = 0;
  113688. }
  113689. if (bytes >= 16) {
  113690. want = bytes - (bytes % 16);
  113691. this.blocks(m, mpos, want);
  113692. mpos += want;
  113693. bytes -= want;
  113694. }
  113695. if (bytes) {
  113696. for (i = 0; i < bytes; i++)
  113697. this.buffer[this.leftover + i] = m[mpos+i];
  113698. this.leftover += bytes;
  113699. }
  113700. };
  113701. function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
  113702. var s = new poly1305(k);
  113703. s.update(m, mpos, n);
  113704. s.finish(out, outpos);
  113705. return 0;
  113706. }
  113707. function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
  113708. var x = new Uint8Array(16);
  113709. crypto_onetimeauth(x,0,m,mpos,n,k);
  113710. return crypto_verify_16(h,hpos,x,0);
  113711. }
  113712. function crypto_secretbox(c,m,d,n,k) {
  113713. var i;
  113714. if (d < 32) return -1;
  113715. crypto_stream_xor(c,0,m,0,d,n,k);
  113716. crypto_onetimeauth(c, 16, c, 32, d - 32, c);
  113717. for (i = 0; i < 16; i++) c[i] = 0;
  113718. return 0;
  113719. }
  113720. function crypto_secretbox_open(m,c,d,n,k) {
  113721. var i;
  113722. var x = new Uint8Array(32);
  113723. if (d < 32) return -1;
  113724. crypto_stream(x,0,32,n,k);
  113725. if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;
  113726. crypto_stream_xor(m,0,c,0,d,n,k);
  113727. for (i = 0; i < 32; i++) m[i] = 0;
  113728. return 0;
  113729. }
  113730. function set25519(r, a) {
  113731. var i;
  113732. for (i = 0; i < 16; i++) r[i] = a[i]|0;
  113733. }
  113734. function car25519(o) {
  113735. var i, v, c = 1;
  113736. for (i = 0; i < 16; i++) {
  113737. v = o[i] + c + 65535;
  113738. c = Math.floor(v / 65536);
  113739. o[i] = v - c * 65536;
  113740. }
  113741. o[0] += c-1 + 37 * (c-1);
  113742. }
  113743. function sel25519(p, q, b) {
  113744. var t, c = ~(b-1);
  113745. for (var i = 0; i < 16; i++) {
  113746. t = c & (p[i] ^ q[i]);
  113747. p[i] ^= t;
  113748. q[i] ^= t;
  113749. }
  113750. }
  113751. function pack25519(o, n) {
  113752. var i, j, b;
  113753. var m = gf(), t = gf();
  113754. for (i = 0; i < 16; i++) t[i] = n[i];
  113755. car25519(t);
  113756. car25519(t);
  113757. car25519(t);
  113758. for (j = 0; j < 2; j++) {
  113759. m[0] = t[0] - 0xffed;
  113760. for (i = 1; i < 15; i++) {
  113761. m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
  113762. m[i-1] &= 0xffff;
  113763. }
  113764. m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
  113765. b = (m[15]>>16) & 1;
  113766. m[14] &= 0xffff;
  113767. sel25519(t, m, 1-b);
  113768. }
  113769. for (i = 0; i < 16; i++) {
  113770. o[2*i] = t[i] & 0xff;
  113771. o[2*i+1] = t[i]>>8;
  113772. }
  113773. }
  113774. function neq25519(a, b) {
  113775. var c = new Uint8Array(32), d = new Uint8Array(32);
  113776. pack25519(c, a);
  113777. pack25519(d, b);
  113778. return crypto_verify_32(c, 0, d, 0);
  113779. }
  113780. function par25519(a) {
  113781. var d = new Uint8Array(32);
  113782. pack25519(d, a);
  113783. return d[0] & 1;
  113784. }
  113785. function unpack25519(o, n) {
  113786. var i;
  113787. for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
  113788. o[15] &= 0x7fff;
  113789. }
  113790. function A(o, a, b) {
  113791. for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
  113792. }
  113793. function Z(o, a, b) {
  113794. for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
  113795. }
  113796. function M(o, a, b) {
  113797. var v, c,
  113798. t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
  113799. t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
  113800. t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
  113801. t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
  113802. b0 = b[0],
  113803. b1 = b[1],
  113804. b2 = b[2],
  113805. b3 = b[3],
  113806. b4 = b[4],
  113807. b5 = b[5],
  113808. b6 = b[6],
  113809. b7 = b[7],
  113810. b8 = b[8],
  113811. b9 = b[9],
  113812. b10 = b[10],
  113813. b11 = b[11],
  113814. b12 = b[12],
  113815. b13 = b[13],
  113816. b14 = b[14],
  113817. b15 = b[15];
  113818. v = a[0];
  113819. t0 += v * b0;
  113820. t1 += v * b1;
  113821. t2 += v * b2;
  113822. t3 += v * b3;
  113823. t4 += v * b4;
  113824. t5 += v * b5;
  113825. t6 += v * b6;
  113826. t7 += v * b7;
  113827. t8 += v * b8;
  113828. t9 += v * b9;
  113829. t10 += v * b10;
  113830. t11 += v * b11;
  113831. t12 += v * b12;
  113832. t13 += v * b13;
  113833. t14 += v * b14;
  113834. t15 += v * b15;
  113835. v = a[1];
  113836. t1 += v * b0;
  113837. t2 += v * b1;
  113838. t3 += v * b2;
  113839. t4 += v * b3;
  113840. t5 += v * b4;
  113841. t6 += v * b5;
  113842. t7 += v * b6;
  113843. t8 += v * b7;
  113844. t9 += v * b8;
  113845. t10 += v * b9;
  113846. t11 += v * b10;
  113847. t12 += v * b11;
  113848. t13 += v * b12;
  113849. t14 += v * b13;
  113850. t15 += v * b14;
  113851. t16 += v * b15;
  113852. v = a[2];
  113853. t2 += v * b0;
  113854. t3 += v * b1;
  113855. t4 += v * b2;
  113856. t5 += v * b3;
  113857. t6 += v * b4;
  113858. t7 += v * b5;
  113859. t8 += v * b6;
  113860. t9 += v * b7;
  113861. t10 += v * b8;
  113862. t11 += v * b9;
  113863. t12 += v * b10;
  113864. t13 += v * b11;
  113865. t14 += v * b12;
  113866. t15 += v * b13;
  113867. t16 += v * b14;
  113868. t17 += v * b15;
  113869. v = a[3];
  113870. t3 += v * b0;
  113871. t4 += v * b1;
  113872. t5 += v * b2;
  113873. t6 += v * b3;
  113874. t7 += v * b4;
  113875. t8 += v * b5;
  113876. t9 += v * b6;
  113877. t10 += v * b7;
  113878. t11 += v * b8;
  113879. t12 += v * b9;
  113880. t13 += v * b10;
  113881. t14 += v * b11;
  113882. t15 += v * b12;
  113883. t16 += v * b13;
  113884. t17 += v * b14;
  113885. t18 += v * b15;
  113886. v = a[4];
  113887. t4 += v * b0;
  113888. t5 += v * b1;
  113889. t6 += v * b2;
  113890. t7 += v * b3;
  113891. t8 += v * b4;
  113892. t9 += v * b5;
  113893. t10 += v * b6;
  113894. t11 += v * b7;
  113895. t12 += v * b8;
  113896. t13 += v * b9;
  113897. t14 += v * b10;
  113898. t15 += v * b11;
  113899. t16 += v * b12;
  113900. t17 += v * b13;
  113901. t18 += v * b14;
  113902. t19 += v * b15;
  113903. v = a[5];
  113904. t5 += v * b0;
  113905. t6 += v * b1;
  113906. t7 += v * b2;
  113907. t8 += v * b3;
  113908. t9 += v * b4;
  113909. t10 += v * b5;
  113910. t11 += v * b6;
  113911. t12 += v * b7;
  113912. t13 += v * b8;
  113913. t14 += v * b9;
  113914. t15 += v * b10;
  113915. t16 += v * b11;
  113916. t17 += v * b12;
  113917. t18 += v * b13;
  113918. t19 += v * b14;
  113919. t20 += v * b15;
  113920. v = a[6];
  113921. t6 += v * b0;
  113922. t7 += v * b1;
  113923. t8 += v * b2;
  113924. t9 += v * b3;
  113925. t10 += v * b4;
  113926. t11 += v * b5;
  113927. t12 += v * b6;
  113928. t13 += v * b7;
  113929. t14 += v * b8;
  113930. t15 += v * b9;
  113931. t16 += v * b10;
  113932. t17 += v * b11;
  113933. t18 += v * b12;
  113934. t19 += v * b13;
  113935. t20 += v * b14;
  113936. t21 += v * b15;
  113937. v = a[7];
  113938. t7 += v * b0;
  113939. t8 += v * b1;
  113940. t9 += v * b2;
  113941. t10 += v * b3;
  113942. t11 += v * b4;
  113943. t12 += v * b5;
  113944. t13 += v * b6;
  113945. t14 += v * b7;
  113946. t15 += v * b8;
  113947. t16 += v * b9;
  113948. t17 += v * b10;
  113949. t18 += v * b11;
  113950. t19 += v * b12;
  113951. t20 += v * b13;
  113952. t21 += v * b14;
  113953. t22 += v * b15;
  113954. v = a[8];
  113955. t8 += v * b0;
  113956. t9 += v * b1;
  113957. t10 += v * b2;
  113958. t11 += v * b3;
  113959. t12 += v * b4;
  113960. t13 += v * b5;
  113961. t14 += v * b6;
  113962. t15 += v * b7;
  113963. t16 += v * b8;
  113964. t17 += v * b9;
  113965. t18 += v * b10;
  113966. t19 += v * b11;
  113967. t20 += v * b12;
  113968. t21 += v * b13;
  113969. t22 += v * b14;
  113970. t23 += v * b15;
  113971. v = a[9];
  113972. t9 += v * b0;
  113973. t10 += v * b1;
  113974. t11 += v * b2;
  113975. t12 += v * b3;
  113976. t13 += v * b4;
  113977. t14 += v * b5;
  113978. t15 += v * b6;
  113979. t16 += v * b7;
  113980. t17 += v * b8;
  113981. t18 += v * b9;
  113982. t19 += v * b10;
  113983. t20 += v * b11;
  113984. t21 += v * b12;
  113985. t22 += v * b13;
  113986. t23 += v * b14;
  113987. t24 += v * b15;
  113988. v = a[10];
  113989. t10 += v * b0;
  113990. t11 += v * b1;
  113991. t12 += v * b2;
  113992. t13 += v * b3;
  113993. t14 += v * b4;
  113994. t15 += v * b5;
  113995. t16 += v * b6;
  113996. t17 += v * b7;
  113997. t18 += v * b8;
  113998. t19 += v * b9;
  113999. t20 += v * b10;
  114000. t21 += v * b11;
  114001. t22 += v * b12;
  114002. t23 += v * b13;
  114003. t24 += v * b14;
  114004. t25 += v * b15;
  114005. v = a[11];
  114006. t11 += v * b0;
  114007. t12 += v * b1;
  114008. t13 += v * b2;
  114009. t14 += v * b3;
  114010. t15 += v * b4;
  114011. t16 += v * b5;
  114012. t17 += v * b6;
  114013. t18 += v * b7;
  114014. t19 += v * b8;
  114015. t20 += v * b9;
  114016. t21 += v * b10;
  114017. t22 += v * b11;
  114018. t23 += v * b12;
  114019. t24 += v * b13;
  114020. t25 += v * b14;
  114021. t26 += v * b15;
  114022. v = a[12];
  114023. t12 += v * b0;
  114024. t13 += v * b1;
  114025. t14 += v * b2;
  114026. t15 += v * b3;
  114027. t16 += v * b4;
  114028. t17 += v * b5;
  114029. t18 += v * b6;
  114030. t19 += v * b7;
  114031. t20 += v * b8;
  114032. t21 += v * b9;
  114033. t22 += v * b10;
  114034. t23 += v * b11;
  114035. t24 += v * b12;
  114036. t25 += v * b13;
  114037. t26 += v * b14;
  114038. t27 += v * b15;
  114039. v = a[13];
  114040. t13 += v * b0;
  114041. t14 += v * b1;
  114042. t15 += v * b2;
  114043. t16 += v * b3;
  114044. t17 += v * b4;
  114045. t18 += v * b5;
  114046. t19 += v * b6;
  114047. t20 += v * b7;
  114048. t21 += v * b8;
  114049. t22 += v * b9;
  114050. t23 += v * b10;
  114051. t24 += v * b11;
  114052. t25 += v * b12;
  114053. t26 += v * b13;
  114054. t27 += v * b14;
  114055. t28 += v * b15;
  114056. v = a[14];
  114057. t14 += v * b0;
  114058. t15 += v * b1;
  114059. t16 += v * b2;
  114060. t17 += v * b3;
  114061. t18 += v * b4;
  114062. t19 += v * b5;
  114063. t20 += v * b6;
  114064. t21 += v * b7;
  114065. t22 += v * b8;
  114066. t23 += v * b9;
  114067. t24 += v * b10;
  114068. t25 += v * b11;
  114069. t26 += v * b12;
  114070. t27 += v * b13;
  114071. t28 += v * b14;
  114072. t29 += v * b15;
  114073. v = a[15];
  114074. t15 += v * b0;
  114075. t16 += v * b1;
  114076. t17 += v * b2;
  114077. t18 += v * b3;
  114078. t19 += v * b4;
  114079. t20 += v * b5;
  114080. t21 += v * b6;
  114081. t22 += v * b7;
  114082. t23 += v * b8;
  114083. t24 += v * b9;
  114084. t25 += v * b10;
  114085. t26 += v * b11;
  114086. t27 += v * b12;
  114087. t28 += v * b13;
  114088. t29 += v * b14;
  114089. t30 += v * b15;
  114090. t0 += 38 * t16;
  114091. t1 += 38 * t17;
  114092. t2 += 38 * t18;
  114093. t3 += 38 * t19;
  114094. t4 += 38 * t20;
  114095. t5 += 38 * t21;
  114096. t6 += 38 * t22;
  114097. t7 += 38 * t23;
  114098. t8 += 38 * t24;
  114099. t9 += 38 * t25;
  114100. t10 += 38 * t26;
  114101. t11 += 38 * t27;
  114102. t12 += 38 * t28;
  114103. t13 += 38 * t29;
  114104. t14 += 38 * t30;
  114105. // t15 left as is
  114106. // first car
  114107. c = 1;
  114108. v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
  114109. v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
  114110. v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
  114111. v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
  114112. v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
  114113. v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
  114114. v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
  114115. v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
  114116. v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
  114117. v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
  114118. v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  114119. v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  114120. v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  114121. v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  114122. v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  114123. v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  114124. t0 += c-1 + 37 * (c-1);
  114125. // second car
  114126. c = 1;
  114127. v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
  114128. v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
  114129. v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
  114130. v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
  114131. v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
  114132. v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
  114133. v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
  114134. v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
  114135. v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
  114136. v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
  114137. v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  114138. v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  114139. v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  114140. v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  114141. v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  114142. v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  114143. t0 += c-1 + 37 * (c-1);
  114144. o[ 0] = t0;
  114145. o[ 1] = t1;
  114146. o[ 2] = t2;
  114147. o[ 3] = t3;
  114148. o[ 4] = t4;
  114149. o[ 5] = t5;
  114150. o[ 6] = t6;
  114151. o[ 7] = t7;
  114152. o[ 8] = t8;
  114153. o[ 9] = t9;
  114154. o[10] = t10;
  114155. o[11] = t11;
  114156. o[12] = t12;
  114157. o[13] = t13;
  114158. o[14] = t14;
  114159. o[15] = t15;
  114160. }
  114161. function S(o, a) {
  114162. M(o, a, a);
  114163. }
  114164. function inv25519(o, i) {
  114165. var c = gf();
  114166. var a;
  114167. for (a = 0; a < 16; a++) c[a] = i[a];
  114168. for (a = 253; a >= 0; a--) {
  114169. S(c, c);
  114170. if(a !== 2 && a !== 4) M(c, c, i);
  114171. }
  114172. for (a = 0; a < 16; a++) o[a] = c[a];
  114173. }
  114174. function pow2523(o, i) {
  114175. var c = gf();
  114176. var a;
  114177. for (a = 0; a < 16; a++) c[a] = i[a];
  114178. for (a = 250; a >= 0; a--) {
  114179. S(c, c);
  114180. if(a !== 1) M(c, c, i);
  114181. }
  114182. for (a = 0; a < 16; a++) o[a] = c[a];
  114183. }
  114184. function crypto_scalarmult(q, n, p) {
  114185. var z = new Uint8Array(32);
  114186. var x = new Float64Array(80), r, i;
  114187. var a = gf(), b = gf(), c = gf(),
  114188. d = gf(), e = gf(), f = gf();
  114189. for (i = 0; i < 31; i++) z[i] = n[i];
  114190. z[31]=(n[31]&127)|64;
  114191. z[0]&=248;
  114192. unpack25519(x,p);
  114193. for (i = 0; i < 16; i++) {
  114194. b[i]=x[i];
  114195. d[i]=a[i]=c[i]=0;
  114196. }
  114197. a[0]=d[0]=1;
  114198. for (i=254; i>=0; --i) {
  114199. r=(z[i>>>3]>>>(i&7))&1;
  114200. sel25519(a,b,r);
  114201. sel25519(c,d,r);
  114202. A(e,a,c);
  114203. Z(a,a,c);
  114204. A(c,b,d);
  114205. Z(b,b,d);
  114206. S(d,e);
  114207. S(f,a);
  114208. M(a,c,a);
  114209. M(c,b,e);
  114210. A(e,a,c);
  114211. Z(a,a,c);
  114212. S(b,a);
  114213. Z(c,d,f);
  114214. M(a,c,_121665);
  114215. A(a,a,d);
  114216. M(c,c,a);
  114217. M(a,d,f);
  114218. M(d,b,x);
  114219. S(b,e);
  114220. sel25519(a,b,r);
  114221. sel25519(c,d,r);
  114222. }
  114223. for (i = 0; i < 16; i++) {
  114224. x[i+16]=a[i];
  114225. x[i+32]=c[i];
  114226. x[i+48]=b[i];
  114227. x[i+64]=d[i];
  114228. }
  114229. var x32 = x.subarray(32);
  114230. var x16 = x.subarray(16);
  114231. inv25519(x32,x32);
  114232. M(x16,x16,x32);
  114233. pack25519(q,x16);
  114234. return 0;
  114235. }
  114236. function crypto_scalarmult_base(q, n) {
  114237. return crypto_scalarmult(q, n, _9);
  114238. }
  114239. function crypto_box_keypair(y, x) {
  114240. randombytes(x, 32);
  114241. return crypto_scalarmult_base(y, x);
  114242. }
  114243. function crypto_box_beforenm(k, y, x) {
  114244. var s = new Uint8Array(32);
  114245. crypto_scalarmult(s, x, y);
  114246. return crypto_core_hsalsa20(k, _0, s, sigma);
  114247. }
  114248. var crypto_box_afternm = crypto_secretbox;
  114249. var crypto_box_open_afternm = crypto_secretbox_open;
  114250. function crypto_box(c, m, d, n, y, x) {
  114251. var k = new Uint8Array(32);
  114252. crypto_box_beforenm(k, y, x);
  114253. return crypto_box_afternm(c, m, d, n, k);
  114254. }
  114255. function crypto_box_open(m, c, d, n, y, x) {
  114256. var k = new Uint8Array(32);
  114257. crypto_box_beforenm(k, y, x);
  114258. return crypto_box_open_afternm(m, c, d, n, k);
  114259. }
  114260. var K = [
  114261. 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  114262. 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  114263. 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  114264. 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  114265. 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  114266. 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  114267. 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  114268. 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  114269. 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  114270. 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  114271. 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  114272. 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  114273. 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  114274. 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  114275. 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  114276. 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  114277. 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  114278. 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  114279. 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  114280. 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  114281. 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  114282. 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  114283. 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  114284. 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  114285. 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  114286. 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  114287. 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  114288. 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  114289. 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  114290. 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  114291. 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  114292. 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  114293. 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  114294. 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  114295. 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  114296. 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  114297. 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  114298. 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  114299. 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  114300. 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  114301. ];
  114302. function crypto_hashblocks_hl(hh, hl, m, n) {
  114303. var wh = new Int32Array(16), wl = new Int32Array(16),
  114304. bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
  114305. bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
  114306. th, tl, i, j, h, l, a, b, c, d;
  114307. var ah0 = hh[0],
  114308. ah1 = hh[1],
  114309. ah2 = hh[2],
  114310. ah3 = hh[3],
  114311. ah4 = hh[4],
  114312. ah5 = hh[5],
  114313. ah6 = hh[6],
  114314. ah7 = hh[7],
  114315. al0 = hl[0],
  114316. al1 = hl[1],
  114317. al2 = hl[2],
  114318. al3 = hl[3],
  114319. al4 = hl[4],
  114320. al5 = hl[5],
  114321. al6 = hl[6],
  114322. al7 = hl[7];
  114323. var pos = 0;
  114324. while (n >= 128) {
  114325. for (i = 0; i < 16; i++) {
  114326. j = 8 * i + pos;
  114327. wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
  114328. wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
  114329. }
  114330. for (i = 0; i < 80; i++) {
  114331. bh0 = ah0;
  114332. bh1 = ah1;
  114333. bh2 = ah2;
  114334. bh3 = ah3;
  114335. bh4 = ah4;
  114336. bh5 = ah5;
  114337. bh6 = ah6;
  114338. bh7 = ah7;
  114339. bl0 = al0;
  114340. bl1 = al1;
  114341. bl2 = al2;
  114342. bl3 = al3;
  114343. bl4 = al4;
  114344. bl5 = al5;
  114345. bl6 = al6;
  114346. bl7 = al7;
  114347. // add
  114348. h = ah7;
  114349. l = al7;
  114350. a = l & 0xffff; b = l >>> 16;
  114351. c = h & 0xffff; d = h >>> 16;
  114352. // Sigma1
  114353. h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
  114354. l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
  114355. a += l & 0xffff; b += l >>> 16;
  114356. c += h & 0xffff; d += h >>> 16;
  114357. // Ch
  114358. h = (ah4 & ah5) ^ (~ah4 & ah6);
  114359. l = (al4 & al5) ^ (~al4 & al6);
  114360. a += l & 0xffff; b += l >>> 16;
  114361. c += h & 0xffff; d += h >>> 16;
  114362. // K
  114363. h = K[i*2];
  114364. l = K[i*2+1];
  114365. a += l & 0xffff; b += l >>> 16;
  114366. c += h & 0xffff; d += h >>> 16;
  114367. // w
  114368. h = wh[i%16];
  114369. l = wl[i%16];
  114370. a += l & 0xffff; b += l >>> 16;
  114371. c += h & 0xffff; d += h >>> 16;
  114372. b += a >>> 16;
  114373. c += b >>> 16;
  114374. d += c >>> 16;
  114375. th = c & 0xffff | d << 16;
  114376. tl = a & 0xffff | b << 16;
  114377. // add
  114378. h = th;
  114379. l = tl;
  114380. a = l & 0xffff; b = l >>> 16;
  114381. c = h & 0xffff; d = h >>> 16;
  114382. // Sigma0
  114383. h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
  114384. l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
  114385. a += l & 0xffff; b += l >>> 16;
  114386. c += h & 0xffff; d += h >>> 16;
  114387. // Maj
  114388. h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
  114389. l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
  114390. a += l & 0xffff; b += l >>> 16;
  114391. c += h & 0xffff; d += h >>> 16;
  114392. b += a >>> 16;
  114393. c += b >>> 16;
  114394. d += c >>> 16;
  114395. bh7 = (c & 0xffff) | (d << 16);
  114396. bl7 = (a & 0xffff) | (b << 16);
  114397. // add
  114398. h = bh3;
  114399. l = bl3;
  114400. a = l & 0xffff; b = l >>> 16;
  114401. c = h & 0xffff; d = h >>> 16;
  114402. h = th;
  114403. l = tl;
  114404. a += l & 0xffff; b += l >>> 16;
  114405. c += h & 0xffff; d += h >>> 16;
  114406. b += a >>> 16;
  114407. c += b >>> 16;
  114408. d += c >>> 16;
  114409. bh3 = (c & 0xffff) | (d << 16);
  114410. bl3 = (a & 0xffff) | (b << 16);
  114411. ah1 = bh0;
  114412. ah2 = bh1;
  114413. ah3 = bh2;
  114414. ah4 = bh3;
  114415. ah5 = bh4;
  114416. ah6 = bh5;
  114417. ah7 = bh6;
  114418. ah0 = bh7;
  114419. al1 = bl0;
  114420. al2 = bl1;
  114421. al3 = bl2;
  114422. al4 = bl3;
  114423. al5 = bl4;
  114424. al6 = bl5;
  114425. al7 = bl6;
  114426. al0 = bl7;
  114427. if (i%16 === 15) {
  114428. for (j = 0; j < 16; j++) {
  114429. // add
  114430. h = wh[j];
  114431. l = wl[j];
  114432. a = l & 0xffff; b = l >>> 16;
  114433. c = h & 0xffff; d = h >>> 16;
  114434. h = wh[(j+9)%16];
  114435. l = wl[(j+9)%16];
  114436. a += l & 0xffff; b += l >>> 16;
  114437. c += h & 0xffff; d += h >>> 16;
  114438. // sigma0
  114439. th = wh[(j+1)%16];
  114440. tl = wl[(j+1)%16];
  114441. h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
  114442. l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
  114443. a += l & 0xffff; b += l >>> 16;
  114444. c += h & 0xffff; d += h >>> 16;
  114445. // sigma1
  114446. th = wh[(j+14)%16];
  114447. tl = wl[(j+14)%16];
  114448. h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
  114449. l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
  114450. a += l & 0xffff; b += l >>> 16;
  114451. c += h & 0xffff; d += h >>> 16;
  114452. b += a >>> 16;
  114453. c += b >>> 16;
  114454. d += c >>> 16;
  114455. wh[j] = (c & 0xffff) | (d << 16);
  114456. wl[j] = (a & 0xffff) | (b << 16);
  114457. }
  114458. }
  114459. }
  114460. // add
  114461. h = ah0;
  114462. l = al0;
  114463. a = l & 0xffff; b = l >>> 16;
  114464. c = h & 0xffff; d = h >>> 16;
  114465. h = hh[0];
  114466. l = hl[0];
  114467. a += l & 0xffff; b += l >>> 16;
  114468. c += h & 0xffff; d += h >>> 16;
  114469. b += a >>> 16;
  114470. c += b >>> 16;
  114471. d += c >>> 16;
  114472. hh[0] = ah0 = (c & 0xffff) | (d << 16);
  114473. hl[0] = al0 = (a & 0xffff) | (b << 16);
  114474. h = ah1;
  114475. l = al1;
  114476. a = l & 0xffff; b = l >>> 16;
  114477. c = h & 0xffff; d = h >>> 16;
  114478. h = hh[1];
  114479. l = hl[1];
  114480. a += l & 0xffff; b += l >>> 16;
  114481. c += h & 0xffff; d += h >>> 16;
  114482. b += a >>> 16;
  114483. c += b >>> 16;
  114484. d += c >>> 16;
  114485. hh[1] = ah1 = (c & 0xffff) | (d << 16);
  114486. hl[1] = al1 = (a & 0xffff) | (b << 16);
  114487. h = ah2;
  114488. l = al2;
  114489. a = l & 0xffff; b = l >>> 16;
  114490. c = h & 0xffff; d = h >>> 16;
  114491. h = hh[2];
  114492. l = hl[2];
  114493. a += l & 0xffff; b += l >>> 16;
  114494. c += h & 0xffff; d += h >>> 16;
  114495. b += a >>> 16;
  114496. c += b >>> 16;
  114497. d += c >>> 16;
  114498. hh[2] = ah2 = (c & 0xffff) | (d << 16);
  114499. hl[2] = al2 = (a & 0xffff) | (b << 16);
  114500. h = ah3;
  114501. l = al3;
  114502. a = l & 0xffff; b = l >>> 16;
  114503. c = h & 0xffff; d = h >>> 16;
  114504. h = hh[3];
  114505. l = hl[3];
  114506. a += l & 0xffff; b += l >>> 16;
  114507. c += h & 0xffff; d += h >>> 16;
  114508. b += a >>> 16;
  114509. c += b >>> 16;
  114510. d += c >>> 16;
  114511. hh[3] = ah3 = (c & 0xffff) | (d << 16);
  114512. hl[3] = al3 = (a & 0xffff) | (b << 16);
  114513. h = ah4;
  114514. l = al4;
  114515. a = l & 0xffff; b = l >>> 16;
  114516. c = h & 0xffff; d = h >>> 16;
  114517. h = hh[4];
  114518. l = hl[4];
  114519. a += l & 0xffff; b += l >>> 16;
  114520. c += h & 0xffff; d += h >>> 16;
  114521. b += a >>> 16;
  114522. c += b >>> 16;
  114523. d += c >>> 16;
  114524. hh[4] = ah4 = (c & 0xffff) | (d << 16);
  114525. hl[4] = al4 = (a & 0xffff) | (b << 16);
  114526. h = ah5;
  114527. l = al5;
  114528. a = l & 0xffff; b = l >>> 16;
  114529. c = h & 0xffff; d = h >>> 16;
  114530. h = hh[5];
  114531. l = hl[5];
  114532. a += l & 0xffff; b += l >>> 16;
  114533. c += h & 0xffff; d += h >>> 16;
  114534. b += a >>> 16;
  114535. c += b >>> 16;
  114536. d += c >>> 16;
  114537. hh[5] = ah5 = (c & 0xffff) | (d << 16);
  114538. hl[5] = al5 = (a & 0xffff) | (b << 16);
  114539. h = ah6;
  114540. l = al6;
  114541. a = l & 0xffff; b = l >>> 16;
  114542. c = h & 0xffff; d = h >>> 16;
  114543. h = hh[6];
  114544. l = hl[6];
  114545. a += l & 0xffff; b += l >>> 16;
  114546. c += h & 0xffff; d += h >>> 16;
  114547. b += a >>> 16;
  114548. c += b >>> 16;
  114549. d += c >>> 16;
  114550. hh[6] = ah6 = (c & 0xffff) | (d << 16);
  114551. hl[6] = al6 = (a & 0xffff) | (b << 16);
  114552. h = ah7;
  114553. l = al7;
  114554. a = l & 0xffff; b = l >>> 16;
  114555. c = h & 0xffff; d = h >>> 16;
  114556. h = hh[7];
  114557. l = hl[7];
  114558. a += l & 0xffff; b += l >>> 16;
  114559. c += h & 0xffff; d += h >>> 16;
  114560. b += a >>> 16;
  114561. c += b >>> 16;
  114562. d += c >>> 16;
  114563. hh[7] = ah7 = (c & 0xffff) | (d << 16);
  114564. hl[7] = al7 = (a & 0xffff) | (b << 16);
  114565. pos += 128;
  114566. n -= 128;
  114567. }
  114568. return n;
  114569. }
  114570. function crypto_hash(out, m, n) {
  114571. var hh = new Int32Array(8),
  114572. hl = new Int32Array(8),
  114573. x = new Uint8Array(256),
  114574. i, b = n;
  114575. hh[0] = 0x6a09e667;
  114576. hh[1] = 0xbb67ae85;
  114577. hh[2] = 0x3c6ef372;
  114578. hh[3] = 0xa54ff53a;
  114579. hh[4] = 0x510e527f;
  114580. hh[5] = 0x9b05688c;
  114581. hh[6] = 0x1f83d9ab;
  114582. hh[7] = 0x5be0cd19;
  114583. hl[0] = 0xf3bcc908;
  114584. hl[1] = 0x84caa73b;
  114585. hl[2] = 0xfe94f82b;
  114586. hl[3] = 0x5f1d36f1;
  114587. hl[4] = 0xade682d1;
  114588. hl[5] = 0x2b3e6c1f;
  114589. hl[6] = 0xfb41bd6b;
  114590. hl[7] = 0x137e2179;
  114591. crypto_hashblocks_hl(hh, hl, m, n);
  114592. n %= 128;
  114593. for (i = 0; i < n; i++) x[i] = m[b-n+i];
  114594. x[n] = 128;
  114595. n = 256-128*(n<112?1:0);
  114596. x[n-9] = 0;
  114597. ts64(x, n-8, (b / 0x20000000) | 0, b << 3);
  114598. crypto_hashblocks_hl(hh, hl, x, n);
  114599. for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);
  114600. return 0;
  114601. }
  114602. function add(p, q) {
  114603. var a = gf(), b = gf(), c = gf(),
  114604. d = gf(), e = gf(), f = gf(),
  114605. g = gf(), h = gf(), t = gf();
  114606. Z(a, p[1], p[0]);
  114607. Z(t, q[1], q[0]);
  114608. M(a, a, t);
  114609. A(b, p[0], p[1]);
  114610. A(t, q[0], q[1]);
  114611. M(b, b, t);
  114612. M(c, p[3], q[3]);
  114613. M(c, c, D2);
  114614. M(d, p[2], q[2]);
  114615. A(d, d, d);
  114616. Z(e, b, a);
  114617. Z(f, d, c);
  114618. A(g, d, c);
  114619. A(h, b, a);
  114620. M(p[0], e, f);
  114621. M(p[1], h, g);
  114622. M(p[2], g, f);
  114623. M(p[3], e, h);
  114624. }
  114625. function cswap(p, q, b) {
  114626. var i;
  114627. for (i = 0; i < 4; i++) {
  114628. sel25519(p[i], q[i], b);
  114629. }
  114630. }
  114631. function pack(r, p) {
  114632. var tx = gf(), ty = gf(), zi = gf();
  114633. inv25519(zi, p[2]);
  114634. M(tx, p[0], zi);
  114635. M(ty, p[1], zi);
  114636. pack25519(r, ty);
  114637. r[31] ^= par25519(tx) << 7;
  114638. }
  114639. function scalarmult(p, q, s) {
  114640. var b, i;
  114641. set25519(p[0], gf0);
  114642. set25519(p[1], gf1);
  114643. set25519(p[2], gf1);
  114644. set25519(p[3], gf0);
  114645. for (i = 255; i >= 0; --i) {
  114646. b = (s[(i/8)|0] >> (i&7)) & 1;
  114647. cswap(p, q, b);
  114648. add(q, p);
  114649. add(p, p);
  114650. cswap(p, q, b);
  114651. }
  114652. }
  114653. function scalarbase(p, s) {
  114654. var q = [gf(), gf(), gf(), gf()];
  114655. set25519(q[0], X);
  114656. set25519(q[1], Y);
  114657. set25519(q[2], gf1);
  114658. M(q[3], X, Y);
  114659. scalarmult(p, q, s);
  114660. }
  114661. function crypto_sign_keypair(pk, sk, seeded) {
  114662. var d = new Uint8Array(64);
  114663. var p = [gf(), gf(), gf(), gf()];
  114664. var i;
  114665. if (!seeded) randombytes(sk, 32);
  114666. crypto_hash(d, sk, 32);
  114667. d[0] &= 248;
  114668. d[31] &= 127;
  114669. d[31] |= 64;
  114670. scalarbase(p, d);
  114671. pack(pk, p);
  114672. for (i = 0; i < 32; i++) sk[i+32] = pk[i];
  114673. return 0;
  114674. }
  114675. var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
  114676. function modL(r, x) {
  114677. var carry, i, j, k;
  114678. for (i = 63; i >= 32; --i) {
  114679. carry = 0;
  114680. for (j = i - 32, k = i - 12; j < k; ++j) {
  114681. x[j] += carry - 16 * x[i] * L[j - (i - 32)];
  114682. carry = (x[j] + 128) >> 8;
  114683. x[j] -= carry * 256;
  114684. }
  114685. x[j] += carry;
  114686. x[i] = 0;
  114687. }
  114688. carry = 0;
  114689. for (j = 0; j < 32; j++) {
  114690. x[j] += carry - (x[31] >> 4) * L[j];
  114691. carry = x[j] >> 8;
  114692. x[j] &= 255;
  114693. }
  114694. for (j = 0; j < 32; j++) x[j] -= carry * L[j];
  114695. for (i = 0; i < 32; i++) {
  114696. x[i+1] += x[i] >> 8;
  114697. r[i] = x[i] & 255;
  114698. }
  114699. }
  114700. function reduce(r) {
  114701. var x = new Float64Array(64), i;
  114702. for (i = 0; i < 64; i++) x[i] = r[i];
  114703. for (i = 0; i < 64; i++) r[i] = 0;
  114704. modL(r, x);
  114705. }
  114706. // Note: difference from C - smlen returned, not passed as argument.
  114707. function crypto_sign(sm, m, n, sk) {
  114708. var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
  114709. var i, j, x = new Float64Array(64);
  114710. var p = [gf(), gf(), gf(), gf()];
  114711. crypto_hash(d, sk, 32);
  114712. d[0] &= 248;
  114713. d[31] &= 127;
  114714. d[31] |= 64;
  114715. var smlen = n + 64;
  114716. for (i = 0; i < n; i++) sm[64 + i] = m[i];
  114717. for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
  114718. crypto_hash(r, sm.subarray(32), n+32);
  114719. reduce(r);
  114720. scalarbase(p, r);
  114721. pack(sm, p);
  114722. for (i = 32; i < 64; i++) sm[i] = sk[i];
  114723. crypto_hash(h, sm, n + 64);
  114724. reduce(h);
  114725. for (i = 0; i < 64; i++) x[i] = 0;
  114726. for (i = 0; i < 32; i++) x[i] = r[i];
  114727. for (i = 0; i < 32; i++) {
  114728. for (j = 0; j < 32; j++) {
  114729. x[i+j] += h[i] * d[j];
  114730. }
  114731. }
  114732. modL(sm.subarray(32), x);
  114733. return smlen;
  114734. }
  114735. function unpackneg(r, p) {
  114736. var t = gf(), chk = gf(), num = gf(),
  114737. den = gf(), den2 = gf(), den4 = gf(),
  114738. den6 = gf();
  114739. set25519(r[2], gf1);
  114740. unpack25519(r[1], p);
  114741. S(num, r[1]);
  114742. M(den, num, D);
  114743. Z(num, num, r[2]);
  114744. A(den, r[2], den);
  114745. S(den2, den);
  114746. S(den4, den2);
  114747. M(den6, den4, den2);
  114748. M(t, den6, num);
  114749. M(t, t, den);
  114750. pow2523(t, t);
  114751. M(t, t, num);
  114752. M(t, t, den);
  114753. M(t, t, den);
  114754. M(r[0], t, den);
  114755. S(chk, r[0]);
  114756. M(chk, chk, den);
  114757. if (neq25519(chk, num)) M(r[0], r[0], I);
  114758. S(chk, r[0]);
  114759. M(chk, chk, den);
  114760. if (neq25519(chk, num)) return -1;
  114761. if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
  114762. M(r[3], r[0], r[1]);
  114763. return 0;
  114764. }
  114765. function crypto_sign_open(m, sm, n, pk) {
  114766. var i, mlen;
  114767. var t = new Uint8Array(32), h = new Uint8Array(64);
  114768. var p = [gf(), gf(), gf(), gf()],
  114769. q = [gf(), gf(), gf(), gf()];
  114770. mlen = -1;
  114771. if (n < 64) return -1;
  114772. if (unpackneg(q, pk)) return -1;
  114773. for (i = 0; i < n; i++) m[i] = sm[i];
  114774. for (i = 0; i < 32; i++) m[i+32] = pk[i];
  114775. crypto_hash(h, m, n);
  114776. reduce(h);
  114777. scalarmult(p, q, h);
  114778. scalarbase(q, sm.subarray(32));
  114779. add(p, q);
  114780. pack(t, p);
  114781. n -= 64;
  114782. if (crypto_verify_32(sm, 0, t, 0)) {
  114783. for (i = 0; i < n; i++) m[i] = 0;
  114784. return -1;
  114785. }
  114786. for (i = 0; i < n; i++) m[i] = sm[i + 64];
  114787. mlen = n;
  114788. return mlen;
  114789. }
  114790. var crypto_secretbox_KEYBYTES = 32,
  114791. crypto_secretbox_NONCEBYTES = 24,
  114792. crypto_secretbox_ZEROBYTES = 32,
  114793. crypto_secretbox_BOXZEROBYTES = 16,
  114794. crypto_scalarmult_BYTES = 32,
  114795. crypto_scalarmult_SCALARBYTES = 32,
  114796. crypto_box_PUBLICKEYBYTES = 32,
  114797. crypto_box_SECRETKEYBYTES = 32,
  114798. crypto_box_BEFORENMBYTES = 32,
  114799. crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
  114800. crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
  114801. crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
  114802. crypto_sign_BYTES = 64,
  114803. crypto_sign_PUBLICKEYBYTES = 32,
  114804. crypto_sign_SECRETKEYBYTES = 64,
  114805. crypto_sign_SEEDBYTES = 32,
  114806. crypto_hash_BYTES = 64;
  114807. nacl.lowlevel = {
  114808. crypto_core_hsalsa20: crypto_core_hsalsa20,
  114809. crypto_stream_xor: crypto_stream_xor,
  114810. crypto_stream: crypto_stream,
  114811. crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
  114812. crypto_stream_salsa20: crypto_stream_salsa20,
  114813. crypto_onetimeauth: crypto_onetimeauth,
  114814. crypto_onetimeauth_verify: crypto_onetimeauth_verify,
  114815. crypto_verify_16: crypto_verify_16,
  114816. crypto_verify_32: crypto_verify_32,
  114817. crypto_secretbox: crypto_secretbox,
  114818. crypto_secretbox_open: crypto_secretbox_open,
  114819. crypto_scalarmult: crypto_scalarmult,
  114820. crypto_scalarmult_base: crypto_scalarmult_base,
  114821. crypto_box_beforenm: crypto_box_beforenm,
  114822. crypto_box_afternm: crypto_box_afternm,
  114823. crypto_box: crypto_box,
  114824. crypto_box_open: crypto_box_open,
  114825. crypto_box_keypair: crypto_box_keypair,
  114826. crypto_hash: crypto_hash,
  114827. crypto_sign: crypto_sign,
  114828. crypto_sign_keypair: crypto_sign_keypair,
  114829. crypto_sign_open: crypto_sign_open,
  114830. crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
  114831. crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
  114832. crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
  114833. crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
  114834. crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
  114835. crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
  114836. crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
  114837. crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
  114838. crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
  114839. crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
  114840. crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
  114841. crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
  114842. crypto_sign_BYTES: crypto_sign_BYTES,
  114843. crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
  114844. crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
  114845. crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
  114846. crypto_hash_BYTES: crypto_hash_BYTES
  114847. };
  114848. /* High-level API */
  114849. function checkLengths(k, n) {
  114850. if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
  114851. if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
  114852. }
  114853. function checkBoxLengths(pk, sk) {
  114854. if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');
  114855. if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');
  114856. }
  114857. function checkArrayTypes() {
  114858. var t, i;
  114859. for (i = 0; i < arguments.length; i++) {
  114860. if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')
  114861. throw new TypeError('unexpected type ' + t + ', use Uint8Array');
  114862. }
  114863. }
  114864. function cleanup(arr) {
  114865. for (var i = 0; i < arr.length; i++) arr[i] = 0;
  114866. }
  114867. // TODO: Completely remove this in v0.15.
  114868. if (!nacl.util) {
  114869. nacl.util = {};
  114870. nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {
  114871. throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');
  114872. };
  114873. }
  114874. nacl.randomBytes = function(n) {
  114875. var b = new Uint8Array(n);
  114876. randombytes(b, n);
  114877. return b;
  114878. };
  114879. nacl.secretbox = function(msg, nonce, key) {
  114880. checkArrayTypes(msg, nonce, key);
  114881. checkLengths(key, nonce);
  114882. var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
  114883. var c = new Uint8Array(m.length);
  114884. for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];
  114885. crypto_secretbox(c, m, m.length, nonce, key);
  114886. return c.subarray(crypto_secretbox_BOXZEROBYTES);
  114887. };
  114888. nacl.secretbox.open = function(box, nonce, key) {
  114889. checkArrayTypes(box, nonce, key);
  114890. checkLengths(key, nonce);
  114891. var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
  114892. var m = new Uint8Array(c.length);
  114893. for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];
  114894. if (c.length < 32) return false;
  114895. if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;
  114896. return m.subarray(crypto_secretbox_ZEROBYTES);
  114897. };
  114898. nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
  114899. nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
  114900. nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
  114901. nacl.scalarMult = function(n, p) {
  114902. checkArrayTypes(n, p);
  114903. if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
  114904. if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
  114905. var q = new Uint8Array(crypto_scalarmult_BYTES);
  114906. crypto_scalarmult(q, n, p);
  114907. return q;
  114908. };
  114909. nacl.scalarMult.base = function(n) {
  114910. checkArrayTypes(n);
  114911. if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
  114912. var q = new Uint8Array(crypto_scalarmult_BYTES);
  114913. crypto_scalarmult_base(q, n);
  114914. return q;
  114915. };
  114916. nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
  114917. nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
  114918. nacl.box = function(msg, nonce, publicKey, secretKey) {
  114919. var k = nacl.box.before(publicKey, secretKey);
  114920. return nacl.secretbox(msg, nonce, k);
  114921. };
  114922. nacl.box.before = function(publicKey, secretKey) {
  114923. checkArrayTypes(publicKey, secretKey);
  114924. checkBoxLengths(publicKey, secretKey);
  114925. var k = new Uint8Array(crypto_box_BEFORENMBYTES);
  114926. crypto_box_beforenm(k, publicKey, secretKey);
  114927. return k;
  114928. };
  114929. nacl.box.after = nacl.secretbox;
  114930. nacl.box.open = function(msg, nonce, publicKey, secretKey) {
  114931. var k = nacl.box.before(publicKey, secretKey);
  114932. return nacl.secretbox.open(msg, nonce, k);
  114933. };
  114934. nacl.box.open.after = nacl.secretbox.open;
  114935. nacl.box.keyPair = function() {
  114936. var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  114937. var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
  114938. crypto_box_keypair(pk, sk);
  114939. return {publicKey: pk, secretKey: sk};
  114940. };
  114941. nacl.box.keyPair.fromSecretKey = function(secretKey) {
  114942. checkArrayTypes(secretKey);
  114943. if (secretKey.length !== crypto_box_SECRETKEYBYTES)
  114944. throw new Error('bad secret key size');
  114945. var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  114946. crypto_scalarmult_base(pk, secretKey);
  114947. return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
  114948. };
  114949. nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
  114950. nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
  114951. nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
  114952. nacl.box.nonceLength = crypto_box_NONCEBYTES;
  114953. nacl.box.overheadLength = nacl.secretbox.overheadLength;
  114954. nacl.sign = function(msg, secretKey) {
  114955. checkArrayTypes(msg, secretKey);
  114956. if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
  114957. throw new Error('bad secret key size');
  114958. var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
  114959. crypto_sign(signedMsg, msg, msg.length, secretKey);
  114960. return signedMsg;
  114961. };
  114962. nacl.sign.open = function(signedMsg, publicKey) {
  114963. if (arguments.length !== 2)
  114964. throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');
  114965. checkArrayTypes(signedMsg, publicKey);
  114966. if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
  114967. throw new Error('bad public key size');
  114968. var tmp = new Uint8Array(signedMsg.length);
  114969. var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
  114970. if (mlen < 0) return null;
  114971. var m = new Uint8Array(mlen);
  114972. for (var i = 0; i < m.length; i++) m[i] = tmp[i];
  114973. return m;
  114974. };
  114975. nacl.sign.detached = function(msg, secretKey) {
  114976. var signedMsg = nacl.sign(msg, secretKey);
  114977. var sig = new Uint8Array(crypto_sign_BYTES);
  114978. for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
  114979. return sig;
  114980. };
  114981. nacl.sign.detached.verify = function(msg, sig, publicKey) {
  114982. checkArrayTypes(msg, sig, publicKey);
  114983. if (sig.length !== crypto_sign_BYTES)
  114984. throw new Error('bad signature size');
  114985. if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
  114986. throw new Error('bad public key size');
  114987. var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
  114988. var m = new Uint8Array(crypto_sign_BYTES + msg.length);
  114989. var i;
  114990. for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
  114991. for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
  114992. return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
  114993. };
  114994. nacl.sign.keyPair = function() {
  114995. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  114996. var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  114997. crypto_sign_keypair(pk, sk);
  114998. return {publicKey: pk, secretKey: sk};
  114999. };
  115000. nacl.sign.keyPair.fromSecretKey = function(secretKey) {
  115001. checkArrayTypes(secretKey);
  115002. if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
  115003. throw new Error('bad secret key size');
  115004. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  115005. for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
  115006. return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
  115007. };
  115008. nacl.sign.keyPair.fromSeed = function(seed) {
  115009. checkArrayTypes(seed);
  115010. if (seed.length !== crypto_sign_SEEDBYTES)
  115011. throw new Error('bad seed size');
  115012. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  115013. var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  115014. for (var i = 0; i < 32; i++) sk[i] = seed[i];
  115015. crypto_sign_keypair(pk, sk, true);
  115016. return {publicKey: pk, secretKey: sk};
  115017. };
  115018. nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
  115019. nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
  115020. nacl.sign.seedLength = crypto_sign_SEEDBYTES;
  115021. nacl.sign.signatureLength = crypto_sign_BYTES;
  115022. nacl.hash = function(msg) {
  115023. checkArrayTypes(msg);
  115024. var h = new Uint8Array(crypto_hash_BYTES);
  115025. crypto_hash(h, msg, msg.length);
  115026. return h;
  115027. };
  115028. nacl.hash.hashLength = crypto_hash_BYTES;
  115029. nacl.verify = function(x, y) {
  115030. checkArrayTypes(x, y);
  115031. // Zero length arguments are considered not equal.
  115032. if (x.length === 0 || y.length === 0) return false;
  115033. if (x.length !== y.length) return false;
  115034. return (vn(x, 0, y, 0, x.length) === 0) ? true : false;
  115035. };
  115036. nacl.setPRNG = function(fn) {
  115037. randombytes = fn;
  115038. };
  115039. (function() {
  115040. // Initialize PRNG if environment provides CSPRNG.
  115041. // If not, methods calling randombytes will throw.
  115042. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
  115043. if (crypto && crypto.getRandomValues) {
  115044. // Browsers.
  115045. var QUOTA = 65536;
  115046. nacl.setPRNG(function(x, n) {
  115047. var i, v = new Uint8Array(n);
  115048. for (i = 0; i < n; i += QUOTA) {
  115049. crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
  115050. }
  115051. for (i = 0; i < n; i++) x[i] = v[i];
  115052. cleanup(v);
  115053. });
  115054. } else if (typeof require !== 'undefined') {
  115055. // Node.js.
  115056. crypto = require('crypto');
  115057. if (crypto && crypto.randomBytes) {
  115058. nacl.setPRNG(function(x, n) {
  115059. var i, v = crypto.randomBytes(n);
  115060. for (i = 0; i < n; i++) x[i] = v[i];
  115061. cleanup(v);
  115062. });
  115063. }
  115064. }
  115065. })();
  115066. })(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
  115067. },{"crypto":144}],651:[function(require,module,exports){
  115068. (function (global){(function (){
  115069. (function (global, factory) {
  115070. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  115071. typeof define === 'function' && define.amd ? define('underscore', factory) :
  115072. (global = global || self, (function () {
  115073. var current = global._;
  115074. var exports = global._ = factory();
  115075. exports.noConflict = function () { global._ = current; return exports; };
  115076. }()));
  115077. }(this, (function () {
  115078. // Underscore.js 1.12.0
  115079. // https://underscorejs.org
  115080. // (c) 2009-2020 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  115081. // Underscore may be freely distributed under the MIT license.
  115082. // Current version.
  115083. var VERSION = '1.12.0';
  115084. // Establish the root object, `window` (`self`) in the browser, `global`
  115085. // on the server, or `this` in some virtual machines. We use `self`
  115086. // instead of `window` for `WebWorker` support.
  115087. var root = typeof self == 'object' && self.self === self && self ||
  115088. typeof global == 'object' && global.global === global && global ||
  115089. Function('return this')() ||
  115090. {};
  115091. // Save bytes in the minified (but not gzipped) version:
  115092. var ArrayProto = Array.prototype, ObjProto = Object.prototype;
  115093. var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
  115094. // Create quick reference variables for speed access to core prototypes.
  115095. var push = ArrayProto.push,
  115096. slice = ArrayProto.slice,
  115097. toString = ObjProto.toString,
  115098. hasOwnProperty = ObjProto.hasOwnProperty;
  115099. // Modern feature detection.
  115100. var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
  115101. supportsDataView = typeof DataView !== 'undefined';
  115102. // All **ECMAScript 5+** native function implementations that we hope to use
  115103. // are declared here.
  115104. var nativeIsArray = Array.isArray,
  115105. nativeKeys = Object.keys,
  115106. nativeCreate = Object.create,
  115107. nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;
  115108. // Create references to these builtin functions because we override them.
  115109. var _isNaN = isNaN,
  115110. _isFinite = isFinite;
  115111. // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  115112. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  115113. var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
  115114. 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
  115115. // The largest integer that can be represented exactly.
  115116. var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  115117. // Some functions take a variable number of arguments, or a few expected
  115118. // arguments at the beginning and then a variable number of values to operate
  115119. // on. This helper accumulates all remaining arguments past the function’s
  115120. // argument length (or an explicit `startIndex`), into an array that becomes
  115121. // the last argument. Similar to ES6’s "rest parameter".
  115122. function restArguments(func, startIndex) {
  115123. startIndex = startIndex == null ? func.length - 1 : +startIndex;
  115124. return function() {
  115125. var length = Math.max(arguments.length - startIndex, 0),
  115126. rest = Array(length),
  115127. index = 0;
  115128. for (; index < length; index++) {
  115129. rest[index] = arguments[index + startIndex];
  115130. }
  115131. switch (startIndex) {
  115132. case 0: return func.call(this, rest);
  115133. case 1: return func.call(this, arguments[0], rest);
  115134. case 2: return func.call(this, arguments[0], arguments[1], rest);
  115135. }
  115136. var args = Array(startIndex + 1);
  115137. for (index = 0; index < startIndex; index++) {
  115138. args[index] = arguments[index];
  115139. }
  115140. args[startIndex] = rest;
  115141. return func.apply(this, args);
  115142. };
  115143. }
  115144. // Is a given variable an object?
  115145. function isObject(obj) {
  115146. var type = typeof obj;
  115147. return type === 'function' || type === 'object' && !!obj;
  115148. }
  115149. // Is a given value equal to null?
  115150. function isNull(obj) {
  115151. return obj === null;
  115152. }
  115153. // Is a given variable undefined?
  115154. function isUndefined(obj) {
  115155. return obj === void 0;
  115156. }
  115157. // Is a given value a boolean?
  115158. function isBoolean(obj) {
  115159. return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  115160. }
  115161. // Is a given value a DOM element?
  115162. function isElement(obj) {
  115163. return !!(obj && obj.nodeType === 1);
  115164. }
  115165. // Internal function for creating a `toString`-based type tester.
  115166. function tagTester(name) {
  115167. var tag = '[object ' + name + ']';
  115168. return function(obj) {
  115169. return toString.call(obj) === tag;
  115170. };
  115171. }
  115172. var isString = tagTester('String');
  115173. var isNumber = tagTester('Number');
  115174. var isDate = tagTester('Date');
  115175. var isRegExp = tagTester('RegExp');
  115176. var isError = tagTester('Error');
  115177. var isSymbol = tagTester('Symbol');
  115178. var isArrayBuffer = tagTester('ArrayBuffer');
  115179. var isFunction = tagTester('Function');
  115180. // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
  115181. // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
  115182. var nodelist = root.document && root.document.childNodes;
  115183. if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
  115184. isFunction = function(obj) {
  115185. return typeof obj == 'function' || false;
  115186. };
  115187. }
  115188. var isFunction$1 = isFunction;
  115189. var hasObjectTag = tagTester('Object');
  115190. // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
  115191. // In IE 11, the most common among them, this problem also applies to
  115192. // `Map`, `WeakMap` and `Set`.
  115193. var hasStringTagBug = (
  115194. supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8)))
  115195. ),
  115196. isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map));
  115197. var isDataView = tagTester('DataView');
  115198. // In IE 10 - Edge 13, we need a different heuristic
  115199. // to determine whether an object is a `DataView`.
  115200. function ie10IsDataView(obj) {
  115201. return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer);
  115202. }
  115203. var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView);
  115204. // Is a given value an array?
  115205. // Delegates to ECMA5's native `Array.isArray`.
  115206. var isArray = nativeIsArray || tagTester('Array');
  115207. // Internal function to check whether `key` is an own property name of `obj`.
  115208. function has(obj, key) {
  115209. return obj != null && hasOwnProperty.call(obj, key);
  115210. }
  115211. var isArguments = tagTester('Arguments');
  115212. // Define a fallback version of the method in browsers (ahem, IE < 9), where
  115213. // there isn't any inspectable "Arguments" type.
  115214. (function() {
  115215. if (!isArguments(arguments)) {
  115216. isArguments = function(obj) {
  115217. return has(obj, 'callee');
  115218. };
  115219. }
  115220. }());
  115221. var isArguments$1 = isArguments;
  115222. // Is a given object a finite number?
  115223. function isFinite$1(obj) {
  115224. return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
  115225. }
  115226. // Is the given value `NaN`?
  115227. function isNaN$1(obj) {
  115228. return isNumber(obj) && _isNaN(obj);
  115229. }
  115230. // Predicate-generating function. Often useful outside of Underscore.
  115231. function constant(value) {
  115232. return function() {
  115233. return value;
  115234. };
  115235. }
  115236. // Common internal logic for `isArrayLike` and `isBufferLike`.
  115237. function createSizePropertyCheck(getSizeProperty) {
  115238. return function(collection) {
  115239. var sizeProperty = getSizeProperty(collection);
  115240. return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
  115241. }
  115242. }
  115243. // Internal helper to generate a function to obtain property `key` from `obj`.
  115244. function shallowProperty(key) {
  115245. return function(obj) {
  115246. return obj == null ? void 0 : obj[key];
  115247. };
  115248. }
  115249. // Internal helper to obtain the `byteLength` property of an object.
  115250. var getByteLength = shallowProperty('byteLength');
  115251. // Internal helper to determine whether we should spend extensive checks against
  115252. // `ArrayBuffer` et al.
  115253. var isBufferLike = createSizePropertyCheck(getByteLength);
  115254. // Is a given value a typed array?
  115255. var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
  115256. function isTypedArray(obj) {
  115257. // `ArrayBuffer.isView` is the most future-proof, so use it when available.
  115258. // Otherwise, fall back on the above regular expression.
  115259. return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) :
  115260. isBufferLike(obj) && typedArrayPattern.test(toString.call(obj));
  115261. }
  115262. var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false);
  115263. // Internal helper to obtain the `length` property of an object.
  115264. var getLength = shallowProperty('length');
  115265. // Internal helper to create a simple lookup structure.
  115266. // `collectNonEnumProps` used to depend on `_.contains`, but this led to
  115267. // circular imports. `emulatedSet` is a one-off solution that only works for
  115268. // arrays of strings.
  115269. function emulatedSet(keys) {
  115270. var hash = {};
  115271. for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
  115272. return {
  115273. contains: function(key) { return hash[key]; },
  115274. push: function(key) {
  115275. hash[key] = true;
  115276. return keys.push(key);
  115277. }
  115278. };
  115279. }
  115280. // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
  115281. // be iterated by `for key in ...` and thus missed. Extends `keys` in place if
  115282. // needed.
  115283. function collectNonEnumProps(obj, keys) {
  115284. keys = emulatedSet(keys);
  115285. var nonEnumIdx = nonEnumerableProps.length;
  115286. var constructor = obj.constructor;
  115287. var proto = isFunction$1(constructor) && constructor.prototype || ObjProto;
  115288. // Constructor is a special case.
  115289. var prop = 'constructor';
  115290. if (has(obj, prop) && !keys.contains(prop)) keys.push(prop);
  115291. while (nonEnumIdx--) {
  115292. prop = nonEnumerableProps[nonEnumIdx];
  115293. if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
  115294. keys.push(prop);
  115295. }
  115296. }
  115297. }
  115298. // Retrieve the names of an object's own properties.
  115299. // Delegates to **ECMAScript 5**'s native `Object.keys`.
  115300. function keys(obj) {
  115301. if (!isObject(obj)) return [];
  115302. if (nativeKeys) return nativeKeys(obj);
  115303. var keys = [];
  115304. for (var key in obj) if (has(obj, key)) keys.push(key);
  115305. // Ahem, IE < 9.
  115306. if (hasEnumBug) collectNonEnumProps(obj, keys);
  115307. return keys;
  115308. }
  115309. // Is a given array, string, or object empty?
  115310. // An "empty" object has no enumerable own-properties.
  115311. function isEmpty(obj) {
  115312. if (obj == null) return true;
  115313. // Skip the more expensive `toString`-based type checks if `obj` has no
  115314. // `.length`.
  115315. var length = getLength(obj);
  115316. if (typeof length == 'number' && (
  115317. isArray(obj) || isString(obj) || isArguments$1(obj)
  115318. )) return length === 0;
  115319. return getLength(keys(obj)) === 0;
  115320. }
  115321. // Returns whether an object has a given set of `key:value` pairs.
  115322. function isMatch(object, attrs) {
  115323. var _keys = keys(attrs), length = _keys.length;
  115324. if (object == null) return !length;
  115325. var obj = Object(object);
  115326. for (var i = 0; i < length; i++) {
  115327. var key = _keys[i];
  115328. if (attrs[key] !== obj[key] || !(key in obj)) return false;
  115329. }
  115330. return true;
  115331. }
  115332. // If Underscore is called as a function, it returns a wrapped object that can
  115333. // be used OO-style. This wrapper holds altered versions of all functions added
  115334. // through `_.mixin`. Wrapped objects may be chained.
  115335. function _(obj) {
  115336. if (obj instanceof _) return obj;
  115337. if (!(this instanceof _)) return new _(obj);
  115338. this._wrapped = obj;
  115339. }
  115340. _.VERSION = VERSION;
  115341. // Extracts the result from a wrapped and chained object.
  115342. _.prototype.value = function() {
  115343. return this._wrapped;
  115344. };
  115345. // Provide unwrapping proxies for some methods used in engine operations
  115346. // such as arithmetic and JSON stringification.
  115347. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
  115348. _.prototype.toString = function() {
  115349. return String(this._wrapped);
  115350. };
  115351. // Internal function to wrap or shallow-copy an ArrayBuffer,
  115352. // typed array or DataView to a new view, reusing the buffer.
  115353. function toBufferView(bufferSource) {
  115354. return new Uint8Array(
  115355. bufferSource.buffer || bufferSource,
  115356. bufferSource.byteOffset || 0,
  115357. getByteLength(bufferSource)
  115358. );
  115359. }
  115360. // We use this string twice, so give it a name for minification.
  115361. var tagDataView = '[object DataView]';
  115362. // Internal recursive comparison function for `_.isEqual`.
  115363. function eq(a, b, aStack, bStack) {
  115364. // Identical objects are equal. `0 === -0`, but they aren't identical.
  115365. // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
  115366. if (a === b) return a !== 0 || 1 / a === 1 / b;
  115367. // `null` or `undefined` only equal to itself (strict comparison).
  115368. if (a == null || b == null) return false;
  115369. // `NaN`s are equivalent, but non-reflexive.
  115370. if (a !== a) return b !== b;
  115371. // Exhaust primitive checks
  115372. var type = typeof a;
  115373. if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
  115374. return deepEq(a, b, aStack, bStack);
  115375. }
  115376. // Internal recursive comparison function for `_.isEqual`.
  115377. function deepEq(a, b, aStack, bStack) {
  115378. // Unwrap any wrapped objects.
  115379. if (a instanceof _) a = a._wrapped;
  115380. if (b instanceof _) b = b._wrapped;
  115381. // Compare `[[Class]]` names.
  115382. var className = toString.call(a);
  115383. if (className !== toString.call(b)) return false;
  115384. // Work around a bug in IE 10 - Edge 13.
  115385. if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) {
  115386. if (!isDataView$1(b)) return false;
  115387. className = tagDataView;
  115388. }
  115389. switch (className) {
  115390. // These types are compared by value.
  115391. case '[object RegExp]':
  115392. // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
  115393. case '[object String]':
  115394. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  115395. // equivalent to `new String("5")`.
  115396. return '' + a === '' + b;
  115397. case '[object Number]':
  115398. // `NaN`s are equivalent, but non-reflexive.
  115399. // Object(NaN) is equivalent to NaN.
  115400. if (+a !== +a) return +b !== +b;
  115401. // An `egal` comparison is performed for other numeric values.
  115402. return +a === 0 ? 1 / +a === 1 / b : +a === +b;
  115403. case '[object Date]':
  115404. case '[object Boolean]':
  115405. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  115406. // millisecond representations. Note that invalid dates with millisecond representations
  115407. // of `NaN` are not equivalent.
  115408. return +a === +b;
  115409. case '[object Symbol]':
  115410. return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
  115411. case '[object ArrayBuffer]':
  115412. case tagDataView:
  115413. // Coerce to typed array so we can fall through.
  115414. return deepEq(toBufferView(a), toBufferView(b), aStack, bStack);
  115415. }
  115416. var areArrays = className === '[object Array]';
  115417. if (!areArrays && isTypedArray$1(a)) {
  115418. var byteLength = getByteLength(a);
  115419. if (byteLength !== getByteLength(b)) return false;
  115420. if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
  115421. areArrays = true;
  115422. }
  115423. if (!areArrays) {
  115424. if (typeof a != 'object' || typeof b != 'object') return false;
  115425. // Objects with different constructors are not equivalent, but `Object`s or `Array`s
  115426. // from different frames are.
  115427. var aCtor = a.constructor, bCtor = b.constructor;
  115428. if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor &&
  115429. isFunction$1(bCtor) && bCtor instanceof bCtor)
  115430. && ('constructor' in a && 'constructor' in b)) {
  115431. return false;
  115432. }
  115433. }
  115434. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  115435. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  115436. // Initializing stack of traversed objects.
  115437. // It's done here since we only need them for objects and arrays comparison.
  115438. aStack = aStack || [];
  115439. bStack = bStack || [];
  115440. var length = aStack.length;
  115441. while (length--) {
  115442. // Linear search. Performance is inversely proportional to the number of
  115443. // unique nested structures.
  115444. if (aStack[length] === a) return bStack[length] === b;
  115445. }
  115446. // Add the first object to the stack of traversed objects.
  115447. aStack.push(a);
  115448. bStack.push(b);
  115449. // Recursively compare objects and arrays.
  115450. if (areArrays) {
  115451. // Compare array lengths to determine if a deep comparison is necessary.
  115452. length = a.length;
  115453. if (length !== b.length) return false;
  115454. // Deep compare the contents, ignoring non-numeric properties.
  115455. while (length--) {
  115456. if (!eq(a[length], b[length], aStack, bStack)) return false;
  115457. }
  115458. } else {
  115459. // Deep compare objects.
  115460. var _keys = keys(a), key;
  115461. length = _keys.length;
  115462. // Ensure that both objects contain the same number of properties before comparing deep equality.
  115463. if (keys(b).length !== length) return false;
  115464. while (length--) {
  115465. // Deep compare each member
  115466. key = _keys[length];
  115467. if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
  115468. }
  115469. }
  115470. // Remove the first object from the stack of traversed objects.
  115471. aStack.pop();
  115472. bStack.pop();
  115473. return true;
  115474. }
  115475. // Perform a deep comparison to check if two objects are equal.
  115476. function isEqual(a, b) {
  115477. return eq(a, b);
  115478. }
  115479. // Retrieve all the enumerable property names of an object.
  115480. function allKeys(obj) {
  115481. if (!isObject(obj)) return [];
  115482. var keys = [];
  115483. for (var key in obj) keys.push(key);
  115484. // Ahem, IE < 9.
  115485. if (hasEnumBug) collectNonEnumProps(obj, keys);
  115486. return keys;
  115487. }
  115488. // Since the regular `Object.prototype.toString` type tests don't work for
  115489. // some types in IE 11, we use a fingerprinting heuristic instead, based
  115490. // on the methods. It's not great, but it's the best we got.
  115491. // The fingerprint method lists are defined below.
  115492. function ie11fingerprint(methods) {
  115493. var length = getLength(methods);
  115494. return function(obj) {
  115495. if (obj == null) return false;
  115496. // `Map`, `WeakMap` and `Set` have no enumerable keys.
  115497. var keys = allKeys(obj);
  115498. if (getLength(keys)) return false;
  115499. for (var i = 0; i < length; i++) {
  115500. if (!isFunction$1(obj[methods[i]])) return false;
  115501. }
  115502. // If we are testing against `WeakMap`, we need to ensure that
  115503. // `obj` doesn't have a `forEach` method in order to distinguish
  115504. // it from a regular `Map`.
  115505. return methods !== weakMapMethods || !isFunction$1(obj[forEachName]);
  115506. };
  115507. }
  115508. // In the interest of compact minification, we write
  115509. // each string in the fingerprints only once.
  115510. var forEachName = 'forEach',
  115511. hasName = 'has',
  115512. commonInit = ['clear', 'delete'],
  115513. mapTail = ['get', hasName, 'set'];
  115514. // `Map`, `WeakMap` and `Set` each have slightly different
  115515. // combinations of the above sublists.
  115516. var mapMethods = commonInit.concat(forEachName, mapTail),
  115517. weakMapMethods = commonInit.concat(mapTail),
  115518. setMethods = ['add'].concat(commonInit, forEachName, hasName);
  115519. var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map');
  115520. var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap');
  115521. var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set');
  115522. var isWeakSet = tagTester('WeakSet');
  115523. // Retrieve the values of an object's properties.
  115524. function values(obj) {
  115525. var _keys = keys(obj);
  115526. var length = _keys.length;
  115527. var values = Array(length);
  115528. for (var i = 0; i < length; i++) {
  115529. values[i] = obj[_keys[i]];
  115530. }
  115531. return values;
  115532. }
  115533. // Convert an object into a list of `[key, value]` pairs.
  115534. // The opposite of `_.object` with one argument.
  115535. function pairs(obj) {
  115536. var _keys = keys(obj);
  115537. var length = _keys.length;
  115538. var pairs = Array(length);
  115539. for (var i = 0; i < length; i++) {
  115540. pairs[i] = [_keys[i], obj[_keys[i]]];
  115541. }
  115542. return pairs;
  115543. }
  115544. // Invert the keys and values of an object. The values must be serializable.
  115545. function invert(obj) {
  115546. var result = {};
  115547. var _keys = keys(obj);
  115548. for (var i = 0, length = _keys.length; i < length; i++) {
  115549. result[obj[_keys[i]]] = _keys[i];
  115550. }
  115551. return result;
  115552. }
  115553. // Return a sorted list of the function names available on the object.
  115554. function functions(obj) {
  115555. var names = [];
  115556. for (var key in obj) {
  115557. if (isFunction$1(obj[key])) names.push(key);
  115558. }
  115559. return names.sort();
  115560. }
  115561. // An internal function for creating assigner functions.
  115562. function createAssigner(keysFunc, defaults) {
  115563. return function(obj) {
  115564. var length = arguments.length;
  115565. if (defaults) obj = Object(obj);
  115566. if (length < 2 || obj == null) return obj;
  115567. for (var index = 1; index < length; index++) {
  115568. var source = arguments[index],
  115569. keys = keysFunc(source),
  115570. l = keys.length;
  115571. for (var i = 0; i < l; i++) {
  115572. var key = keys[i];
  115573. if (!defaults || obj[key] === void 0) obj[key] = source[key];
  115574. }
  115575. }
  115576. return obj;
  115577. };
  115578. }
  115579. // Extend a given object with all the properties in passed-in object(s).
  115580. var extend = createAssigner(allKeys);
  115581. // Assigns a given object with all the own properties in the passed-in
  115582. // object(s).
  115583. // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  115584. var extendOwn = createAssigner(keys);
  115585. // Fill in a given object with default properties.
  115586. var defaults = createAssigner(allKeys, true);
  115587. // Create a naked function reference for surrogate-prototype-swapping.
  115588. function ctor() {
  115589. return function(){};
  115590. }
  115591. // An internal function for creating a new object that inherits from another.
  115592. function baseCreate(prototype) {
  115593. if (!isObject(prototype)) return {};
  115594. if (nativeCreate) return nativeCreate(prototype);
  115595. var Ctor = ctor();
  115596. Ctor.prototype = prototype;
  115597. var result = new Ctor;
  115598. Ctor.prototype = null;
  115599. return result;
  115600. }
  115601. // Creates an object that inherits from the given prototype object.
  115602. // If additional properties are provided then they will be added to the
  115603. // created object.
  115604. function create(prototype, props) {
  115605. var result = baseCreate(prototype);
  115606. if (props) extendOwn(result, props);
  115607. return result;
  115608. }
  115609. // Create a (shallow-cloned) duplicate of an object.
  115610. function clone(obj) {
  115611. if (!isObject(obj)) return obj;
  115612. return isArray(obj) ? obj.slice() : extend({}, obj);
  115613. }
  115614. // Invokes `interceptor` with the `obj` and then returns `obj`.
  115615. // The primary purpose of this method is to "tap into" a method chain, in
  115616. // order to perform operations on intermediate results within the chain.
  115617. function tap(obj, interceptor) {
  115618. interceptor(obj);
  115619. return obj;
  115620. }
  115621. // Normalize a (deep) property `path` to array.
  115622. // Like `_.iteratee`, this function can be customized.
  115623. function toPath(path) {
  115624. return isArray(path) ? path : [path];
  115625. }
  115626. _.toPath = toPath;
  115627. // Internal wrapper for `_.toPath` to enable minification.
  115628. // Similar to `cb` for `_.iteratee`.
  115629. function toPath$1(path) {
  115630. return _.toPath(path);
  115631. }
  115632. // Internal function to obtain a nested property in `obj` along `path`.
  115633. function deepGet(obj, path) {
  115634. var length = path.length;
  115635. for (var i = 0; i < length; i++) {
  115636. if (obj == null) return void 0;
  115637. obj = obj[path[i]];
  115638. }
  115639. return length ? obj : void 0;
  115640. }
  115641. // Get the value of the (deep) property on `path` from `object`.
  115642. // If any property in `path` does not exist or if the value is
  115643. // `undefined`, return `defaultValue` instead.
  115644. // The `path` is normalized through `_.toPath`.
  115645. function get(object, path, defaultValue) {
  115646. var value = deepGet(object, toPath$1(path));
  115647. return isUndefined(value) ? defaultValue : value;
  115648. }
  115649. // Shortcut function for checking if an object has a given property directly on
  115650. // itself (in other words, not on a prototype). Unlike the internal `has`
  115651. // function, this public version can also traverse nested properties.
  115652. function has$1(obj, path) {
  115653. path = toPath$1(path);
  115654. var length = path.length;
  115655. for (var i = 0; i < length; i++) {
  115656. var key = path[i];
  115657. if (!has(obj, key)) return false;
  115658. obj = obj[key];
  115659. }
  115660. return !!length;
  115661. }
  115662. // Keep the identity function around for default iteratees.
  115663. function identity(value) {
  115664. return value;
  115665. }
  115666. // Returns a predicate for checking whether an object has a given set of
  115667. // `key:value` pairs.
  115668. function matcher(attrs) {
  115669. attrs = extendOwn({}, attrs);
  115670. return function(obj) {
  115671. return isMatch(obj, attrs);
  115672. };
  115673. }
  115674. // Creates a function that, when passed an object, will traverse that object’s
  115675. // properties down the given `path`, specified as an array of keys or indices.
  115676. function property(path) {
  115677. path = toPath$1(path);
  115678. return function(obj) {
  115679. return deepGet(obj, path);
  115680. };
  115681. }
  115682. // Internal function that returns an efficient (for current engines) version
  115683. // of the passed-in callback, to be repeatedly applied in other Underscore
  115684. // functions.
  115685. function optimizeCb(func, context, argCount) {
  115686. if (context === void 0) return func;
  115687. switch (argCount == null ? 3 : argCount) {
  115688. case 1: return function(value) {
  115689. return func.call(context, value);
  115690. };
  115691. // The 2-argument case is omitted because we’re not using it.
  115692. case 3: return function(value, index, collection) {
  115693. return func.call(context, value, index, collection);
  115694. };
  115695. case 4: return function(accumulator, value, index, collection) {
  115696. return func.call(context, accumulator, value, index, collection);
  115697. };
  115698. }
  115699. return function() {
  115700. return func.apply(context, arguments);
  115701. };
  115702. }
  115703. // An internal function to generate callbacks that can be applied to each
  115704. // element in a collection, returning the desired result — either `_.identity`,
  115705. // an arbitrary callback, a property matcher, or a property accessor.
  115706. function baseIteratee(value, context, argCount) {
  115707. if (value == null) return identity;
  115708. if (isFunction$1(value)) return optimizeCb(value, context, argCount);
  115709. if (isObject(value) && !isArray(value)) return matcher(value);
  115710. return property(value);
  115711. }
  115712. // External wrapper for our callback generator. Users may customize
  115713. // `_.iteratee` if they want additional predicate/iteratee shorthand styles.
  115714. // This abstraction hides the internal-only `argCount` argument.
  115715. function iteratee(value, context) {
  115716. return baseIteratee(value, context, Infinity);
  115717. }
  115718. _.iteratee = iteratee;
  115719. // The function we call internally to generate a callback. It invokes
  115720. // `_.iteratee` if overridden, otherwise `baseIteratee`.
  115721. function cb(value, context, argCount) {
  115722. if (_.iteratee !== iteratee) return _.iteratee(value, context);
  115723. return baseIteratee(value, context, argCount);
  115724. }
  115725. // Returns the results of applying the `iteratee` to each element of `obj`.
  115726. // In contrast to `_.map` it returns an object.
  115727. function mapObject(obj, iteratee, context) {
  115728. iteratee = cb(iteratee, context);
  115729. var _keys = keys(obj),
  115730. length = _keys.length,
  115731. results = {};
  115732. for (var index = 0; index < length; index++) {
  115733. var currentKey = _keys[index];
  115734. results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
  115735. }
  115736. return results;
  115737. }
  115738. // Predicate-generating function. Often useful outside of Underscore.
  115739. function noop(){}
  115740. // Generates a function for a given object that returns a given property.
  115741. function propertyOf(obj) {
  115742. if (obj == null) return noop;
  115743. return function(path) {
  115744. return get(obj, path);
  115745. };
  115746. }
  115747. // Run a function **n** times.
  115748. function times(n, iteratee, context) {
  115749. var accum = Array(Math.max(0, n));
  115750. iteratee = optimizeCb(iteratee, context, 1);
  115751. for (var i = 0; i < n; i++) accum[i] = iteratee(i);
  115752. return accum;
  115753. }
  115754. // Return a random integer between `min` and `max` (inclusive).
  115755. function random(min, max) {
  115756. if (max == null) {
  115757. max = min;
  115758. min = 0;
  115759. }
  115760. return min + Math.floor(Math.random() * (max - min + 1));
  115761. }
  115762. // A (possibly faster) way to get the current timestamp as an integer.
  115763. var now = Date.now || function() {
  115764. return new Date().getTime();
  115765. };
  115766. // Internal helper to generate functions for escaping and unescaping strings
  115767. // to/from HTML interpolation.
  115768. function createEscaper(map) {
  115769. var escaper = function(match) {
  115770. return map[match];
  115771. };
  115772. // Regexes for identifying a key that needs to be escaped.
  115773. var source = '(?:' + keys(map).join('|') + ')';
  115774. var testRegexp = RegExp(source);
  115775. var replaceRegexp = RegExp(source, 'g');
  115776. return function(string) {
  115777. string = string == null ? '' : '' + string;
  115778. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  115779. };
  115780. }
  115781. // Internal list of HTML entities for escaping.
  115782. var escapeMap = {
  115783. '&': '&amp;',
  115784. '<': '&lt;',
  115785. '>': '&gt;',
  115786. '"': '&quot;',
  115787. "'": '&#x27;',
  115788. '`': '&#x60;'
  115789. };
  115790. // Function for escaping strings to HTML interpolation.
  115791. var _escape = createEscaper(escapeMap);
  115792. // Internal list of HTML entities for unescaping.
  115793. var unescapeMap = invert(escapeMap);
  115794. // Function for unescaping strings from HTML interpolation.
  115795. var _unescape = createEscaper(unescapeMap);
  115796. // By default, Underscore uses ERB-style template delimiters. Change the
  115797. // following template settings to use alternative delimiters.
  115798. var templateSettings = _.templateSettings = {
  115799. evaluate: /<%([\s\S]+?)%>/g,
  115800. interpolate: /<%=([\s\S]+?)%>/g,
  115801. escape: /<%-([\s\S]+?)%>/g
  115802. };
  115803. // When customizing `_.templateSettings`, if you don't want to define an
  115804. // interpolation, evaluation or escaping regex, we need one that is
  115805. // guaranteed not to match.
  115806. var noMatch = /(.)^/;
  115807. // Certain characters need to be escaped so that they can be put into a
  115808. // string literal.
  115809. var escapes = {
  115810. "'": "'",
  115811. '\\': '\\',
  115812. '\r': 'r',
  115813. '\n': 'n',
  115814. '\u2028': 'u2028',
  115815. '\u2029': 'u2029'
  115816. };
  115817. var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
  115818. function escapeChar(match) {
  115819. return '\\' + escapes[match];
  115820. }
  115821. // JavaScript micro-templating, similar to John Resig's implementation.
  115822. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  115823. // and correctly escapes quotes within interpolated code.
  115824. // NB: `oldSettings` only exists for backwards compatibility.
  115825. function template(text, settings, oldSettings) {
  115826. if (!settings && oldSettings) settings = oldSettings;
  115827. settings = defaults({}, settings, _.templateSettings);
  115828. // Combine delimiters into one regular expression via alternation.
  115829. var matcher = RegExp([
  115830. (settings.escape || noMatch).source,
  115831. (settings.interpolate || noMatch).source,
  115832. (settings.evaluate || noMatch).source
  115833. ].join('|') + '|$', 'g');
  115834. // Compile the template source, escaping string literals appropriately.
  115835. var index = 0;
  115836. var source = "__p+='";
  115837. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  115838. source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
  115839. index = offset + match.length;
  115840. if (escape) {
  115841. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  115842. } else if (interpolate) {
  115843. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  115844. } else if (evaluate) {
  115845. source += "';\n" + evaluate + "\n__p+='";
  115846. }
  115847. // Adobe VMs need the match returned to produce the correct offset.
  115848. return match;
  115849. });
  115850. source += "';\n";
  115851. // If a variable is not specified, place data values in local scope.
  115852. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  115853. source = "var __t,__p='',__j=Array.prototype.join," +
  115854. "print=function(){__p+=__j.call(arguments,'');};\n" +
  115855. source + 'return __p;\n';
  115856. var render;
  115857. try {
  115858. render = new Function(settings.variable || 'obj', '_', source);
  115859. } catch (e) {
  115860. e.source = source;
  115861. throw e;
  115862. }
  115863. var template = function(data) {
  115864. return render.call(this, data, _);
  115865. };
  115866. // Provide the compiled source as a convenience for precompilation.
  115867. var argument = settings.variable || 'obj';
  115868. template.source = 'function(' + argument + '){\n' + source + '}';
  115869. return template;
  115870. }
  115871. // Traverses the children of `obj` along `path`. If a child is a function, it
  115872. // is invoked with its parent as context. Returns the value of the final
  115873. // child, or `fallback` if any child is undefined.
  115874. function result(obj, path, fallback) {
  115875. path = toPath$1(path);
  115876. var length = path.length;
  115877. if (!length) {
  115878. return isFunction$1(fallback) ? fallback.call(obj) : fallback;
  115879. }
  115880. for (var i = 0; i < length; i++) {
  115881. var prop = obj == null ? void 0 : obj[path[i]];
  115882. if (prop === void 0) {
  115883. prop = fallback;
  115884. i = length; // Ensure we don't continue iterating.
  115885. }
  115886. obj = isFunction$1(prop) ? prop.call(obj) : prop;
  115887. }
  115888. return obj;
  115889. }
  115890. // Generate a unique integer id (unique within the entire client session).
  115891. // Useful for temporary DOM ids.
  115892. var idCounter = 0;
  115893. function uniqueId(prefix) {
  115894. var id = ++idCounter + '';
  115895. return prefix ? prefix + id : id;
  115896. }
  115897. // Start chaining a wrapped Underscore object.
  115898. function chain(obj) {
  115899. var instance = _(obj);
  115900. instance._chain = true;
  115901. return instance;
  115902. }
  115903. // Internal function to execute `sourceFunc` bound to `context` with optional
  115904. // `args`. Determines whether to execute a function as a constructor or as a
  115905. // normal function.
  115906. function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
  115907. if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
  115908. var self = baseCreate(sourceFunc.prototype);
  115909. var result = sourceFunc.apply(self, args);
  115910. if (isObject(result)) return result;
  115911. return self;
  115912. }
  115913. // Partially apply a function by creating a version that has had some of its
  115914. // arguments pre-filled, without changing its dynamic `this` context. `_` acts
  115915. // as a placeholder by default, allowing any combination of arguments to be
  115916. // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
  115917. var partial = restArguments(function(func, boundArgs) {
  115918. var placeholder = partial.placeholder;
  115919. var bound = function() {
  115920. var position = 0, length = boundArgs.length;
  115921. var args = Array(length);
  115922. for (var i = 0; i < length; i++) {
  115923. args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
  115924. }
  115925. while (position < arguments.length) args.push(arguments[position++]);
  115926. return executeBound(func, bound, this, this, args);
  115927. };
  115928. return bound;
  115929. });
  115930. partial.placeholder = _;
  115931. // Create a function bound to a given object (assigning `this`, and arguments,
  115932. // optionally).
  115933. var bind = restArguments(function(func, context, args) {
  115934. if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function');
  115935. var bound = restArguments(function(callArgs) {
  115936. return executeBound(func, bound, context, this, args.concat(callArgs));
  115937. });
  115938. return bound;
  115939. });
  115940. // Internal helper for collection methods to determine whether a collection
  115941. // should be iterated as an array or as an object.
  115942. // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  115943. // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  115944. var isArrayLike = createSizePropertyCheck(getLength);
  115945. // Internal implementation of a recursive `flatten` function.
  115946. function flatten(input, depth, strict, output) {
  115947. output = output || [];
  115948. if (!depth && depth !== 0) {
  115949. depth = Infinity;
  115950. } else if (depth <= 0) {
  115951. return output.concat(input);
  115952. }
  115953. var idx = output.length;
  115954. for (var i = 0, length = getLength(input); i < length; i++) {
  115955. var value = input[i];
  115956. if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) {
  115957. // Flatten current level of array or arguments object.
  115958. if (depth > 1) {
  115959. flatten(value, depth - 1, strict, output);
  115960. idx = output.length;
  115961. } else {
  115962. var j = 0, len = value.length;
  115963. while (j < len) output[idx++] = value[j++];
  115964. }
  115965. } else if (!strict) {
  115966. output[idx++] = value;
  115967. }
  115968. }
  115969. return output;
  115970. }
  115971. // Bind a number of an object's methods to that object. Remaining arguments
  115972. // are the method names to be bound. Useful for ensuring that all callbacks
  115973. // defined on an object belong to it.
  115974. var bindAll = restArguments(function(obj, keys) {
  115975. keys = flatten(keys, false, false);
  115976. var index = keys.length;
  115977. if (index < 1) throw new Error('bindAll must be passed function names');
  115978. while (index--) {
  115979. var key = keys[index];
  115980. obj[key] = bind(obj[key], obj);
  115981. }
  115982. return obj;
  115983. });
  115984. // Memoize an expensive function by storing its results.
  115985. function memoize(func, hasher) {
  115986. var memoize = function(key) {
  115987. var cache = memoize.cache;
  115988. var address = '' + (hasher ? hasher.apply(this, arguments) : key);
  115989. if (!has(cache, address)) cache[address] = func.apply(this, arguments);
  115990. return cache[address];
  115991. };
  115992. memoize.cache = {};
  115993. return memoize;
  115994. }
  115995. // Delays a function for the given number of milliseconds, and then calls
  115996. // it with the arguments supplied.
  115997. var delay = restArguments(function(func, wait, args) {
  115998. return setTimeout(function() {
  115999. return func.apply(null, args);
  116000. }, wait);
  116001. });
  116002. // Defers a function, scheduling it to run after the current call stack has
  116003. // cleared.
  116004. var defer = partial(delay, _, 1);
  116005. // Returns a function, that, when invoked, will only be triggered at most once
  116006. // during a given window of time. Normally, the throttled function will run
  116007. // as much as it can, without ever going more than once per `wait` duration;
  116008. // but if you'd like to disable the execution on the leading edge, pass
  116009. // `{leading: false}`. To disable execution on the trailing edge, ditto.
  116010. function throttle(func, wait, options) {
  116011. var timeout, context, args, result;
  116012. var previous = 0;
  116013. if (!options) options = {};
  116014. var later = function() {
  116015. previous = options.leading === false ? 0 : now();
  116016. timeout = null;
  116017. result = func.apply(context, args);
  116018. if (!timeout) context = args = null;
  116019. };
  116020. var throttled = function() {
  116021. var _now = now();
  116022. if (!previous && options.leading === false) previous = _now;
  116023. var remaining = wait - (_now - previous);
  116024. context = this;
  116025. args = arguments;
  116026. if (remaining <= 0 || remaining > wait) {
  116027. if (timeout) {
  116028. clearTimeout(timeout);
  116029. timeout = null;
  116030. }
  116031. previous = _now;
  116032. result = func.apply(context, args);
  116033. if (!timeout) context = args = null;
  116034. } else if (!timeout && options.trailing !== false) {
  116035. timeout = setTimeout(later, remaining);
  116036. }
  116037. return result;
  116038. };
  116039. throttled.cancel = function() {
  116040. clearTimeout(timeout);
  116041. previous = 0;
  116042. timeout = context = args = null;
  116043. };
  116044. return throttled;
  116045. }
  116046. // When a sequence of calls of the returned function ends, the argument
  116047. // function is triggered. The end of a sequence is defined by the `wait`
  116048. // parameter. If `immediate` is passed, the argument function will be
  116049. // triggered at the beginning of the sequence instead of at the end.
  116050. function debounce(func, wait, immediate) {
  116051. var timeout, result;
  116052. var later = function(context, args) {
  116053. timeout = null;
  116054. if (args) result = func.apply(context, args);
  116055. };
  116056. var debounced = restArguments(function(args) {
  116057. if (timeout) clearTimeout(timeout);
  116058. if (immediate) {
  116059. var callNow = !timeout;
  116060. timeout = setTimeout(later, wait);
  116061. if (callNow) result = func.apply(this, args);
  116062. } else {
  116063. timeout = delay(later, wait, this, args);
  116064. }
  116065. return result;
  116066. });
  116067. debounced.cancel = function() {
  116068. clearTimeout(timeout);
  116069. timeout = null;
  116070. };
  116071. return debounced;
  116072. }
  116073. // Returns the first function passed as an argument to the second,
  116074. // allowing you to adjust arguments, run code before and after, and
  116075. // conditionally execute the original function.
  116076. function wrap(func, wrapper) {
  116077. return partial(wrapper, func);
  116078. }
  116079. // Returns a negated version of the passed-in predicate.
  116080. function negate(predicate) {
  116081. return function() {
  116082. return !predicate.apply(this, arguments);
  116083. };
  116084. }
  116085. // Returns a function that is the composition of a list of functions, each
  116086. // consuming the return value of the function that follows.
  116087. function compose() {
  116088. var args = arguments;
  116089. var start = args.length - 1;
  116090. return function() {
  116091. var i = start;
  116092. var result = args[start].apply(this, arguments);
  116093. while (i--) result = args[i].call(this, result);
  116094. return result;
  116095. };
  116096. }
  116097. // Returns a function that will only be executed on and after the Nth call.
  116098. function after(times, func) {
  116099. return function() {
  116100. if (--times < 1) {
  116101. return func.apply(this, arguments);
  116102. }
  116103. };
  116104. }
  116105. // Returns a function that will only be executed up to (but not including) the
  116106. // Nth call.
  116107. function before(times, func) {
  116108. var memo;
  116109. return function() {
  116110. if (--times > 0) {
  116111. memo = func.apply(this, arguments);
  116112. }
  116113. if (times <= 1) func = null;
  116114. return memo;
  116115. };
  116116. }
  116117. // Returns a function that will be executed at most one time, no matter how
  116118. // often you call it. Useful for lazy initialization.
  116119. var once = partial(before, 2);
  116120. // Returns the first key on an object that passes a truth test.
  116121. function findKey(obj, predicate, context) {
  116122. predicate = cb(predicate, context);
  116123. var _keys = keys(obj), key;
  116124. for (var i = 0, length = _keys.length; i < length; i++) {
  116125. key = _keys[i];
  116126. if (predicate(obj[key], key, obj)) return key;
  116127. }
  116128. }
  116129. // Internal function to generate `_.findIndex` and `_.findLastIndex`.
  116130. function createPredicateIndexFinder(dir) {
  116131. return function(array, predicate, context) {
  116132. predicate = cb(predicate, context);
  116133. var length = getLength(array);
  116134. var index = dir > 0 ? 0 : length - 1;
  116135. for (; index >= 0 && index < length; index += dir) {
  116136. if (predicate(array[index], index, array)) return index;
  116137. }
  116138. return -1;
  116139. };
  116140. }
  116141. // Returns the first index on an array-like that passes a truth test.
  116142. var findIndex = createPredicateIndexFinder(1);
  116143. // Returns the last index on an array-like that passes a truth test.
  116144. var findLastIndex = createPredicateIndexFinder(-1);
  116145. // Use a comparator function to figure out the smallest index at which
  116146. // an object should be inserted so as to maintain order. Uses binary search.
  116147. function sortedIndex(array, obj, iteratee, context) {
  116148. iteratee = cb(iteratee, context, 1);
  116149. var value = iteratee(obj);
  116150. var low = 0, high = getLength(array);
  116151. while (low < high) {
  116152. var mid = Math.floor((low + high) / 2);
  116153. if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
  116154. }
  116155. return low;
  116156. }
  116157. // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
  116158. function createIndexFinder(dir, predicateFind, sortedIndex) {
  116159. return function(array, item, idx) {
  116160. var i = 0, length = getLength(array);
  116161. if (typeof idx == 'number') {
  116162. if (dir > 0) {
  116163. i = idx >= 0 ? idx : Math.max(idx + length, i);
  116164. } else {
  116165. length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
  116166. }
  116167. } else if (sortedIndex && idx && length) {
  116168. idx = sortedIndex(array, item);
  116169. return array[idx] === item ? idx : -1;
  116170. }
  116171. if (item !== item) {
  116172. idx = predicateFind(slice.call(array, i, length), isNaN$1);
  116173. return idx >= 0 ? idx + i : -1;
  116174. }
  116175. for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
  116176. if (array[idx] === item) return idx;
  116177. }
  116178. return -1;
  116179. };
  116180. }
  116181. // Return the position of the first occurrence of an item in an array,
  116182. // or -1 if the item is not included in the array.
  116183. // If the array is large and already in sort order, pass `true`
  116184. // for **isSorted** to use binary search.
  116185. var indexOf = createIndexFinder(1, findIndex, sortedIndex);
  116186. // Return the position of the last occurrence of an item in an array,
  116187. // or -1 if the item is not included in the array.
  116188. var lastIndexOf = createIndexFinder(-1, findLastIndex);
  116189. // Return the first value which passes a truth test.
  116190. function find(obj, predicate, context) {
  116191. var keyFinder = isArrayLike(obj) ? findIndex : findKey;
  116192. var key = keyFinder(obj, predicate, context);
  116193. if (key !== void 0 && key !== -1) return obj[key];
  116194. }
  116195. // Convenience version of a common use case of `_.find`: getting the first
  116196. // object containing specific `key:value` pairs.
  116197. function findWhere(obj, attrs) {
  116198. return find(obj, matcher(attrs));
  116199. }
  116200. // The cornerstone for collection functions, an `each`
  116201. // implementation, aka `forEach`.
  116202. // Handles raw objects in addition to array-likes. Treats all
  116203. // sparse array-likes as if they were dense.
  116204. function each(obj, iteratee, context) {
  116205. iteratee = optimizeCb(iteratee, context);
  116206. var i, length;
  116207. if (isArrayLike(obj)) {
  116208. for (i = 0, length = obj.length; i < length; i++) {
  116209. iteratee(obj[i], i, obj);
  116210. }
  116211. } else {
  116212. var _keys = keys(obj);
  116213. for (i = 0, length = _keys.length; i < length; i++) {
  116214. iteratee(obj[_keys[i]], _keys[i], obj);
  116215. }
  116216. }
  116217. return obj;
  116218. }
  116219. // Return the results of applying the iteratee to each element.
  116220. function map(obj, iteratee, context) {
  116221. iteratee = cb(iteratee, context);
  116222. var _keys = !isArrayLike(obj) && keys(obj),
  116223. length = (_keys || obj).length,
  116224. results = Array(length);
  116225. for (var index = 0; index < length; index++) {
  116226. var currentKey = _keys ? _keys[index] : index;
  116227. results[index] = iteratee(obj[currentKey], currentKey, obj);
  116228. }
  116229. return results;
  116230. }
  116231. // Internal helper to create a reducing function, iterating left or right.
  116232. function createReduce(dir) {
  116233. // Wrap code that reassigns argument variables in a separate function than
  116234. // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
  116235. var reducer = function(obj, iteratee, memo, initial) {
  116236. var _keys = !isArrayLike(obj) && keys(obj),
  116237. length = (_keys || obj).length,
  116238. index = dir > 0 ? 0 : length - 1;
  116239. if (!initial) {
  116240. memo = obj[_keys ? _keys[index] : index];
  116241. index += dir;
  116242. }
  116243. for (; index >= 0 && index < length; index += dir) {
  116244. var currentKey = _keys ? _keys[index] : index;
  116245. memo = iteratee(memo, obj[currentKey], currentKey, obj);
  116246. }
  116247. return memo;
  116248. };
  116249. return function(obj, iteratee, memo, context) {
  116250. var initial = arguments.length >= 3;
  116251. return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
  116252. };
  116253. }
  116254. // **Reduce** builds up a single result from a list of values, aka `inject`,
  116255. // or `foldl`.
  116256. var reduce = createReduce(1);
  116257. // The right-associative version of reduce, also known as `foldr`.
  116258. var reduceRight = createReduce(-1);
  116259. // Return all the elements that pass a truth test.
  116260. function filter(obj, predicate, context) {
  116261. var results = [];
  116262. predicate = cb(predicate, context);
  116263. each(obj, function(value, index, list) {
  116264. if (predicate(value, index, list)) results.push(value);
  116265. });
  116266. return results;
  116267. }
  116268. // Return all the elements for which a truth test fails.
  116269. function reject(obj, predicate, context) {
  116270. return filter(obj, negate(cb(predicate)), context);
  116271. }
  116272. // Determine whether all of the elements pass a truth test.
  116273. function every(obj, predicate, context) {
  116274. predicate = cb(predicate, context);
  116275. var _keys = !isArrayLike(obj) && keys(obj),
  116276. length = (_keys || obj).length;
  116277. for (var index = 0; index < length; index++) {
  116278. var currentKey = _keys ? _keys[index] : index;
  116279. if (!predicate(obj[currentKey], currentKey, obj)) return false;
  116280. }
  116281. return true;
  116282. }
  116283. // Determine if at least one element in the object passes a truth test.
  116284. function some(obj, predicate, context) {
  116285. predicate = cb(predicate, context);
  116286. var _keys = !isArrayLike(obj) && keys(obj),
  116287. length = (_keys || obj).length;
  116288. for (var index = 0; index < length; index++) {
  116289. var currentKey = _keys ? _keys[index] : index;
  116290. if (predicate(obj[currentKey], currentKey, obj)) return true;
  116291. }
  116292. return false;
  116293. }
  116294. // Determine if the array or object contains a given item (using `===`).
  116295. function contains(obj, item, fromIndex, guard) {
  116296. if (!isArrayLike(obj)) obj = values(obj);
  116297. if (typeof fromIndex != 'number' || guard) fromIndex = 0;
  116298. return indexOf(obj, item, fromIndex) >= 0;
  116299. }
  116300. // Invoke a method (with arguments) on every item in a collection.
  116301. var invoke = restArguments(function(obj, path, args) {
  116302. var contextPath, func;
  116303. if (isFunction$1(path)) {
  116304. func = path;
  116305. } else {
  116306. path = toPath$1(path);
  116307. contextPath = path.slice(0, -1);
  116308. path = path[path.length - 1];
  116309. }
  116310. return map(obj, function(context) {
  116311. var method = func;
  116312. if (!method) {
  116313. if (contextPath && contextPath.length) {
  116314. context = deepGet(context, contextPath);
  116315. }
  116316. if (context == null) return void 0;
  116317. method = context[path];
  116318. }
  116319. return method == null ? method : method.apply(context, args);
  116320. });
  116321. });
  116322. // Convenience version of a common use case of `_.map`: fetching a property.
  116323. function pluck(obj, key) {
  116324. return map(obj, property(key));
  116325. }
  116326. // Convenience version of a common use case of `_.filter`: selecting only
  116327. // objects containing specific `key:value` pairs.
  116328. function where(obj, attrs) {
  116329. return filter(obj, matcher(attrs));
  116330. }
  116331. // Return the maximum element (or element-based computation).
  116332. function max(obj, iteratee, context) {
  116333. var result = -Infinity, lastComputed = -Infinity,
  116334. value, computed;
  116335. if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
  116336. obj = isArrayLike(obj) ? obj : values(obj);
  116337. for (var i = 0, length = obj.length; i < length; i++) {
  116338. value = obj[i];
  116339. if (value != null && value > result) {
  116340. result = value;
  116341. }
  116342. }
  116343. } else {
  116344. iteratee = cb(iteratee, context);
  116345. each(obj, function(v, index, list) {
  116346. computed = iteratee(v, index, list);
  116347. if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
  116348. result = v;
  116349. lastComputed = computed;
  116350. }
  116351. });
  116352. }
  116353. return result;
  116354. }
  116355. // Return the minimum element (or element-based computation).
  116356. function min(obj, iteratee, context) {
  116357. var result = Infinity, lastComputed = Infinity,
  116358. value, computed;
  116359. if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
  116360. obj = isArrayLike(obj) ? obj : values(obj);
  116361. for (var i = 0, length = obj.length; i < length; i++) {
  116362. value = obj[i];
  116363. if (value != null && value < result) {
  116364. result = value;
  116365. }
  116366. }
  116367. } else {
  116368. iteratee = cb(iteratee, context);
  116369. each(obj, function(v, index, list) {
  116370. computed = iteratee(v, index, list);
  116371. if (computed < lastComputed || computed === Infinity && result === Infinity) {
  116372. result = v;
  116373. lastComputed = computed;
  116374. }
  116375. });
  116376. }
  116377. return result;
  116378. }
  116379. // Sample **n** random values from a collection using the modern version of the
  116380. // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  116381. // If **n** is not specified, returns a single random element.
  116382. // The internal `guard` argument allows it to work with `_.map`.
  116383. function sample(obj, n, guard) {
  116384. if (n == null || guard) {
  116385. if (!isArrayLike(obj)) obj = values(obj);
  116386. return obj[random(obj.length - 1)];
  116387. }
  116388. var sample = isArrayLike(obj) ? clone(obj) : values(obj);
  116389. var length = getLength(sample);
  116390. n = Math.max(Math.min(n, length), 0);
  116391. var last = length - 1;
  116392. for (var index = 0; index < n; index++) {
  116393. var rand = random(index, last);
  116394. var temp = sample[index];
  116395. sample[index] = sample[rand];
  116396. sample[rand] = temp;
  116397. }
  116398. return sample.slice(0, n);
  116399. }
  116400. // Shuffle a collection.
  116401. function shuffle(obj) {
  116402. return sample(obj, Infinity);
  116403. }
  116404. // Sort the object's values by a criterion produced by an iteratee.
  116405. function sortBy(obj, iteratee, context) {
  116406. var index = 0;
  116407. iteratee = cb(iteratee, context);
  116408. return pluck(map(obj, function(value, key, list) {
  116409. return {
  116410. value: value,
  116411. index: index++,
  116412. criteria: iteratee(value, key, list)
  116413. };
  116414. }).sort(function(left, right) {
  116415. var a = left.criteria;
  116416. var b = right.criteria;
  116417. if (a !== b) {
  116418. if (a > b || a === void 0) return 1;
  116419. if (a < b || b === void 0) return -1;
  116420. }
  116421. return left.index - right.index;
  116422. }), 'value');
  116423. }
  116424. // An internal function used for aggregate "group by" operations.
  116425. function group(behavior, partition) {
  116426. return function(obj, iteratee, context) {
  116427. var result = partition ? [[], []] : {};
  116428. iteratee = cb(iteratee, context);
  116429. each(obj, function(value, index) {
  116430. var key = iteratee(value, index, obj);
  116431. behavior(result, value, key);
  116432. });
  116433. return result;
  116434. };
  116435. }
  116436. // Groups the object's values by a criterion. Pass either a string attribute
  116437. // to group by, or a function that returns the criterion.
  116438. var groupBy = group(function(result, value, key) {
  116439. if (has(result, key)) result[key].push(value); else result[key] = [value];
  116440. });
  116441. // Indexes the object's values by a criterion, similar to `_.groupBy`, but for
  116442. // when you know that your index values will be unique.
  116443. var indexBy = group(function(result, value, key) {
  116444. result[key] = value;
  116445. });
  116446. // Counts instances of an object that group by a certain criterion. Pass
  116447. // either a string attribute to count by, or a function that returns the
  116448. // criterion.
  116449. var countBy = group(function(result, value, key) {
  116450. if (has(result, key)) result[key]++; else result[key] = 1;
  116451. });
  116452. // Split a collection into two arrays: one whose elements all pass the given
  116453. // truth test, and one whose elements all do not pass the truth test.
  116454. var partition = group(function(result, value, pass) {
  116455. result[pass ? 0 : 1].push(value);
  116456. }, true);
  116457. // Safely create a real, live array from anything iterable.
  116458. var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
  116459. function toArray(obj) {
  116460. if (!obj) return [];
  116461. if (isArray(obj)) return slice.call(obj);
  116462. if (isString(obj)) {
  116463. // Keep surrogate pair characters together.
  116464. return obj.match(reStrSymbol);
  116465. }
  116466. if (isArrayLike(obj)) return map(obj, identity);
  116467. return values(obj);
  116468. }
  116469. // Return the number of elements in a collection.
  116470. function size(obj) {
  116471. if (obj == null) return 0;
  116472. return isArrayLike(obj) ? obj.length : keys(obj).length;
  116473. }
  116474. // Internal `_.pick` helper function to determine whether `key` is an enumerable
  116475. // property name of `obj`.
  116476. function keyInObj(value, key, obj) {
  116477. return key in obj;
  116478. }
  116479. // Return a copy of the object only containing the allowed properties.
  116480. var pick = restArguments(function(obj, keys) {
  116481. var result = {}, iteratee = keys[0];
  116482. if (obj == null) return result;
  116483. if (isFunction$1(iteratee)) {
  116484. if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
  116485. keys = allKeys(obj);
  116486. } else {
  116487. iteratee = keyInObj;
  116488. keys = flatten(keys, false, false);
  116489. obj = Object(obj);
  116490. }
  116491. for (var i = 0, length = keys.length; i < length; i++) {
  116492. var key = keys[i];
  116493. var value = obj[key];
  116494. if (iteratee(value, key, obj)) result[key] = value;
  116495. }
  116496. return result;
  116497. });
  116498. // Return a copy of the object without the disallowed properties.
  116499. var omit = restArguments(function(obj, keys) {
  116500. var iteratee = keys[0], context;
  116501. if (isFunction$1(iteratee)) {
  116502. iteratee = negate(iteratee);
  116503. if (keys.length > 1) context = keys[1];
  116504. } else {
  116505. keys = map(flatten(keys, false, false), String);
  116506. iteratee = function(value, key) {
  116507. return !contains(keys, key);
  116508. };
  116509. }
  116510. return pick(obj, iteratee, context);
  116511. });
  116512. // Returns everything but the last entry of the array. Especially useful on
  116513. // the arguments object. Passing **n** will return all the values in
  116514. // the array, excluding the last N.
  116515. function initial(array, n, guard) {
  116516. return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  116517. }
  116518. // Get the first element of an array. Passing **n** will return the first N
  116519. // values in the array. The **guard** check allows it to work with `_.map`.
  116520. function first(array, n, guard) {
  116521. if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  116522. if (n == null || guard) return array[0];
  116523. return initial(array, array.length - n);
  116524. }
  116525. // Returns everything but the first entry of the `array`. Especially useful on
  116526. // the `arguments` object. Passing an **n** will return the rest N values in the
  116527. // `array`.
  116528. function rest(array, n, guard) {
  116529. return slice.call(array, n == null || guard ? 1 : n);
  116530. }
  116531. // Get the last element of an array. Passing **n** will return the last N
  116532. // values in the array.
  116533. function last(array, n, guard) {
  116534. if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  116535. if (n == null || guard) return array[array.length - 1];
  116536. return rest(array, Math.max(0, array.length - n));
  116537. }
  116538. // Trim out all falsy values from an array.
  116539. function compact(array) {
  116540. return filter(array, Boolean);
  116541. }
  116542. // Flatten out an array, either recursively (by default), or up to `depth`.
  116543. // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
  116544. function flatten$1(array, depth) {
  116545. return flatten(array, depth, false);
  116546. }
  116547. // Take the difference between one array and a number of other arrays.
  116548. // Only the elements present in just the first array will remain.
  116549. var difference = restArguments(function(array, rest) {
  116550. rest = flatten(rest, true, true);
  116551. return filter(array, function(value){
  116552. return !contains(rest, value);
  116553. });
  116554. });
  116555. // Return a version of the array that does not contain the specified value(s).
  116556. var without = restArguments(function(array, otherArrays) {
  116557. return difference(array, otherArrays);
  116558. });
  116559. // Produce a duplicate-free version of the array. If the array has already
  116560. // been sorted, you have the option of using a faster algorithm.
  116561. // The faster algorithm will not work with an iteratee if the iteratee
  116562. // is not a one-to-one function, so providing an iteratee will disable
  116563. // the faster algorithm.
  116564. function uniq(array, isSorted, iteratee, context) {
  116565. if (!isBoolean(isSorted)) {
  116566. context = iteratee;
  116567. iteratee = isSorted;
  116568. isSorted = false;
  116569. }
  116570. if (iteratee != null) iteratee = cb(iteratee, context);
  116571. var result = [];
  116572. var seen = [];
  116573. for (var i = 0, length = getLength(array); i < length; i++) {
  116574. var value = array[i],
  116575. computed = iteratee ? iteratee(value, i, array) : value;
  116576. if (isSorted && !iteratee) {
  116577. if (!i || seen !== computed) result.push(value);
  116578. seen = computed;
  116579. } else if (iteratee) {
  116580. if (!contains(seen, computed)) {
  116581. seen.push(computed);
  116582. result.push(value);
  116583. }
  116584. } else if (!contains(result, value)) {
  116585. result.push(value);
  116586. }
  116587. }
  116588. return result;
  116589. }
  116590. // Produce an array that contains the union: each distinct element from all of
  116591. // the passed-in arrays.
  116592. var union = restArguments(function(arrays) {
  116593. return uniq(flatten(arrays, true, true));
  116594. });
  116595. // Produce an array that contains every item shared between all the
  116596. // passed-in arrays.
  116597. function intersection(array) {
  116598. var result = [];
  116599. var argsLength = arguments.length;
  116600. for (var i = 0, length = getLength(array); i < length; i++) {
  116601. var item = array[i];
  116602. if (contains(result, item)) continue;
  116603. var j;
  116604. for (j = 1; j < argsLength; j++) {
  116605. if (!contains(arguments[j], item)) break;
  116606. }
  116607. if (j === argsLength) result.push(item);
  116608. }
  116609. return result;
  116610. }
  116611. // Complement of zip. Unzip accepts an array of arrays and groups
  116612. // each array's elements on shared indices.
  116613. function unzip(array) {
  116614. var length = array && max(array, getLength).length || 0;
  116615. var result = Array(length);
  116616. for (var index = 0; index < length; index++) {
  116617. result[index] = pluck(array, index);
  116618. }
  116619. return result;
  116620. }
  116621. // Zip together multiple lists into a single array -- elements that share
  116622. // an index go together.
  116623. var zip = restArguments(unzip);
  116624. // Converts lists into objects. Pass either a single array of `[key, value]`
  116625. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  116626. // the corresponding values. Passing by pairs is the reverse of `_.pairs`.
  116627. function object(list, values) {
  116628. var result = {};
  116629. for (var i = 0, length = getLength(list); i < length; i++) {
  116630. if (values) {
  116631. result[list[i]] = values[i];
  116632. } else {
  116633. result[list[i][0]] = list[i][1];
  116634. }
  116635. }
  116636. return result;
  116637. }
  116638. // Generate an integer Array containing an arithmetic progression. A port of
  116639. // the native Python `range()` function. See
  116640. // [the Python documentation](https://docs.python.org/library/functions.html#range).
  116641. function range(start, stop, step) {
  116642. if (stop == null) {
  116643. stop = start || 0;
  116644. start = 0;
  116645. }
  116646. if (!step) {
  116647. step = stop < start ? -1 : 1;
  116648. }
  116649. var length = Math.max(Math.ceil((stop - start) / step), 0);
  116650. var range = Array(length);
  116651. for (var idx = 0; idx < length; idx++, start += step) {
  116652. range[idx] = start;
  116653. }
  116654. return range;
  116655. }
  116656. // Chunk a single array into multiple arrays, each containing `count` or fewer
  116657. // items.
  116658. function chunk(array, count) {
  116659. if (count == null || count < 1) return [];
  116660. var result = [];
  116661. var i = 0, length = array.length;
  116662. while (i < length) {
  116663. result.push(slice.call(array, i, i += count));
  116664. }
  116665. return result;
  116666. }
  116667. // Helper function to continue chaining intermediate results.
  116668. function chainResult(instance, obj) {
  116669. return instance._chain ? _(obj).chain() : obj;
  116670. }
  116671. // Add your own custom functions to the Underscore object.
  116672. function mixin(obj) {
  116673. each(functions(obj), function(name) {
  116674. var func = _[name] = obj[name];
  116675. _.prototype[name] = function() {
  116676. var args = [this._wrapped];
  116677. push.apply(args, arguments);
  116678. return chainResult(this, func.apply(_, args));
  116679. };
  116680. });
  116681. return _;
  116682. }
  116683. // Add all mutator `Array` functions to the wrapper.
  116684. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  116685. var method = ArrayProto[name];
  116686. _.prototype[name] = function() {
  116687. var obj = this._wrapped;
  116688. if (obj != null) {
  116689. method.apply(obj, arguments);
  116690. if ((name === 'shift' || name === 'splice') && obj.length === 0) {
  116691. delete obj[0];
  116692. }
  116693. }
  116694. return chainResult(this, obj);
  116695. };
  116696. });
  116697. // Add all accessor `Array` functions to the wrapper.
  116698. each(['concat', 'join', 'slice'], function(name) {
  116699. var method = ArrayProto[name];
  116700. _.prototype[name] = function() {
  116701. var obj = this._wrapped;
  116702. if (obj != null) obj = method.apply(obj, arguments);
  116703. return chainResult(this, obj);
  116704. };
  116705. });
  116706. // Named Exports
  116707. var allExports = {
  116708. __proto__: null,
  116709. VERSION: VERSION,
  116710. restArguments: restArguments,
  116711. isObject: isObject,
  116712. isNull: isNull,
  116713. isUndefined: isUndefined,
  116714. isBoolean: isBoolean,
  116715. isElement: isElement,
  116716. isString: isString,
  116717. isNumber: isNumber,
  116718. isDate: isDate,
  116719. isRegExp: isRegExp,
  116720. isError: isError,
  116721. isSymbol: isSymbol,
  116722. isArrayBuffer: isArrayBuffer,
  116723. isDataView: isDataView$1,
  116724. isArray: isArray,
  116725. isFunction: isFunction$1,
  116726. isArguments: isArguments$1,
  116727. isFinite: isFinite$1,
  116728. isNaN: isNaN$1,
  116729. isTypedArray: isTypedArray$1,
  116730. isEmpty: isEmpty,
  116731. isMatch: isMatch,
  116732. isEqual: isEqual,
  116733. isMap: isMap,
  116734. isWeakMap: isWeakMap,
  116735. isSet: isSet,
  116736. isWeakSet: isWeakSet,
  116737. keys: keys,
  116738. allKeys: allKeys,
  116739. values: values,
  116740. pairs: pairs,
  116741. invert: invert,
  116742. functions: functions,
  116743. methods: functions,
  116744. extend: extend,
  116745. extendOwn: extendOwn,
  116746. assign: extendOwn,
  116747. defaults: defaults,
  116748. create: create,
  116749. clone: clone,
  116750. tap: tap,
  116751. get: get,
  116752. has: has$1,
  116753. mapObject: mapObject,
  116754. identity: identity,
  116755. constant: constant,
  116756. noop: noop,
  116757. toPath: toPath,
  116758. property: property,
  116759. propertyOf: propertyOf,
  116760. matcher: matcher,
  116761. matches: matcher,
  116762. times: times,
  116763. random: random,
  116764. now: now,
  116765. escape: _escape,
  116766. unescape: _unescape,
  116767. templateSettings: templateSettings,
  116768. template: template,
  116769. result: result,
  116770. uniqueId: uniqueId,
  116771. chain: chain,
  116772. iteratee: iteratee,
  116773. partial: partial,
  116774. bind: bind,
  116775. bindAll: bindAll,
  116776. memoize: memoize,
  116777. delay: delay,
  116778. defer: defer,
  116779. throttle: throttle,
  116780. debounce: debounce,
  116781. wrap: wrap,
  116782. negate: negate,
  116783. compose: compose,
  116784. after: after,
  116785. before: before,
  116786. once: once,
  116787. findKey: findKey,
  116788. findIndex: findIndex,
  116789. findLastIndex: findLastIndex,
  116790. sortedIndex: sortedIndex,
  116791. indexOf: indexOf,
  116792. lastIndexOf: lastIndexOf,
  116793. find: find,
  116794. detect: find,
  116795. findWhere: findWhere,
  116796. each: each,
  116797. forEach: each,
  116798. map: map,
  116799. collect: map,
  116800. reduce: reduce,
  116801. foldl: reduce,
  116802. inject: reduce,
  116803. reduceRight: reduceRight,
  116804. foldr: reduceRight,
  116805. filter: filter,
  116806. select: filter,
  116807. reject: reject,
  116808. every: every,
  116809. all: every,
  116810. some: some,
  116811. any: some,
  116812. contains: contains,
  116813. includes: contains,
  116814. include: contains,
  116815. invoke: invoke,
  116816. pluck: pluck,
  116817. where: where,
  116818. max: max,
  116819. min: min,
  116820. shuffle: shuffle,
  116821. sample: sample,
  116822. sortBy: sortBy,
  116823. groupBy: groupBy,
  116824. indexBy: indexBy,
  116825. countBy: countBy,
  116826. partition: partition,
  116827. toArray: toArray,
  116828. size: size,
  116829. pick: pick,
  116830. omit: omit,
  116831. first: first,
  116832. head: first,
  116833. take: first,
  116834. initial: initial,
  116835. last: last,
  116836. rest: rest,
  116837. tail: rest,
  116838. drop: rest,
  116839. compact: compact,
  116840. flatten: flatten$1,
  116841. without: without,
  116842. uniq: uniq,
  116843. unique: uniq,
  116844. union: union,
  116845. intersection: intersection,
  116846. difference: difference,
  116847. unzip: unzip,
  116848. transpose: unzip,
  116849. zip: zip,
  116850. object: object,
  116851. range: range,
  116852. chunk: chunk,
  116853. mixin: mixin,
  116854. 'default': _
  116855. };
  116856. // Default Export
  116857. // Add all of the Underscore functions to the wrapper object.
  116858. var _$1 = mixin(allExports);
  116859. // Legacy Node.js API.
  116860. _$1._ = _$1;
  116861. return _$1;
  116862. })));
  116863. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  116864. },{}],652:[function(require,module,exports){
  116865. /** @license URI.js v4.4.0 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
  116866. (function (global, factory) {
  116867. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  116868. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  116869. (factory((global.URI = global.URI || {})));
  116870. }(this, (function (exports) { 'use strict';
  116871. function merge() {
  116872. for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
  116873. sets[_key] = arguments[_key];
  116874. }
  116875. if (sets.length > 1) {
  116876. sets[0] = sets[0].slice(0, -1);
  116877. var xl = sets.length - 1;
  116878. for (var x = 1; x < xl; ++x) {
  116879. sets[x] = sets[x].slice(1, -1);
  116880. }
  116881. sets[xl] = sets[xl].slice(1);
  116882. return sets.join('');
  116883. } else {
  116884. return sets[0];
  116885. }
  116886. }
  116887. function subexp(str) {
  116888. return "(?:" + str + ")";
  116889. }
  116890. function typeOf(o) {
  116891. return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
  116892. }
  116893. function toUpperCase(str) {
  116894. return str.toUpperCase();
  116895. }
  116896. function toArray(obj) {
  116897. return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
  116898. }
  116899. function assign(target, source) {
  116900. var obj = target;
  116901. if (source) {
  116902. for (var key in source) {
  116903. obj[key] = source[key];
  116904. }
  116905. }
  116906. return obj;
  116907. }
  116908. function buildExps(isIRI) {
  116909. var ALPHA$$ = "[A-Za-z]",
  116910. CR$ = "[\\x0D]",
  116911. DIGIT$$ = "[0-9]",
  116912. DQUOTE$$ = "[\\x22]",
  116913. HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"),
  116914. //case-insensitive
  116915. LF$$ = "[\\x0A]",
  116916. SP$$ = "[\\x20]",
  116917. PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)),
  116918. //expanded
  116919. GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
  116920. SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
  116921. RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),
  116922. UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]",
  116923. //subset, excludes bidi control characters
  116924. IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]",
  116925. //subset
  116926. UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$),
  116927. SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
  116928. USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
  116929. DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
  116930. DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$),
  116931. //relaxed parsing rules
  116932. IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$),
  116933. H16$ = subexp(HEXDIG$$ + "{1,4}"),
  116934. LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
  116935. IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$),
  116936. // 6( h16 ":" ) ls32
  116937. IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$),
  116938. // "::" 5( h16 ":" ) ls32
  116939. IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$),
  116940. //[ h16 ] "::" 4( h16 ":" ) ls32
  116941. IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$),
  116942. //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
  116943. IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$),
  116944. //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
  116945. IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$),
  116946. //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
  116947. IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$),
  116948. //[ *4( h16 ":" ) h16 ] "::" ls32
  116949. IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$),
  116950. //[ *5( h16 ":" ) h16 ] "::" h16
  116951. IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"),
  116952. //[ *6( h16 ":" ) h16 ] "::"
  116953. IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")),
  116954. ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"),
  116955. //RFC 6874
  116956. IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$),
  116957. //RFC 6874
  116958. IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$),
  116959. //RFC 6874, with relaxed parsing rules
  116960. IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
  116961. IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
  116962. //RFC 6874
  116963. REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
  116964. HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$),
  116965. PORT$ = subexp(DIGIT$$ + "*"),
  116966. AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
  116967. PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
  116968. SEGMENT$ = subexp(PCHAR$ + "*"),
  116969. SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
  116970. SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
  116971. PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
  116972. PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),
  116973. //simplified
  116974. PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),
  116975. //simplified
  116976. PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),
  116977. //simplified
  116978. PATH_EMPTY$ = "(?!" + PCHAR$ + ")",
  116979. PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
  116980. QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"),
  116981. FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
  116982. HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
  116983. URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
  116984. RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
  116985. RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
  116986. URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$),
  116987. ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
  116988. GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
  116989. RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
  116990. ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$",
  116991. SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
  116992. AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
  116993. return {
  116994. NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
  116995. NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
  116996. NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
  116997. NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
  116998. NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
  116999. NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
  117000. NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
  117001. ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
  117002. UNRESERVED: new RegExp(UNRESERVED$$, "g"),
  117003. OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
  117004. PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
  117005. IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
  117006. IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules
  117007. };
  117008. }
  117009. var URI_PROTOCOL = buildExps(false);
  117010. var IRI_PROTOCOL = buildExps(true);
  117011. var slicedToArray = function () {
  117012. function sliceIterator(arr, i) {
  117013. var _arr = [];
  117014. var _n = true;
  117015. var _d = false;
  117016. var _e = undefined;
  117017. try {
  117018. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  117019. _arr.push(_s.value);
  117020. if (i && _arr.length === i) break;
  117021. }
  117022. } catch (err) {
  117023. _d = true;
  117024. _e = err;
  117025. } finally {
  117026. try {
  117027. if (!_n && _i["return"]) _i["return"]();
  117028. } finally {
  117029. if (_d) throw _e;
  117030. }
  117031. }
  117032. return _arr;
  117033. }
  117034. return function (arr, i) {
  117035. if (Array.isArray(arr)) {
  117036. return arr;
  117037. } else if (Symbol.iterator in Object(arr)) {
  117038. return sliceIterator(arr, i);
  117039. } else {
  117040. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  117041. }
  117042. };
  117043. }();
  117044. var toConsumableArray = function (arr) {
  117045. if (Array.isArray(arr)) {
  117046. for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  117047. return arr2;
  117048. } else {
  117049. return Array.from(arr);
  117050. }
  117051. };
  117052. /** Highest positive signed 32-bit float value */
  117053. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  117054. /** Bootstring parameters */
  117055. var base = 36;
  117056. var tMin = 1;
  117057. var tMax = 26;
  117058. var skew = 38;
  117059. var damp = 700;
  117060. var initialBias = 72;
  117061. var initialN = 128; // 0x80
  117062. var delimiter = '-'; // '\x2D'
  117063. /** Regular expressions */
  117064. var regexPunycode = /^xn--/;
  117065. var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
  117066. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  117067. /** Error messages */
  117068. var errors = {
  117069. 'overflow': 'Overflow: input needs wider integers to process',
  117070. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  117071. 'invalid-input': 'Invalid input'
  117072. };
  117073. /** Convenience shortcuts */
  117074. var baseMinusTMin = base - tMin;
  117075. var floor = Math.floor;
  117076. var stringFromCharCode = String.fromCharCode;
  117077. /*--------------------------------------------------------------------------*/
  117078. /**
  117079. * A generic error utility function.
  117080. * @private
  117081. * @param {String} type The error type.
  117082. * @returns {Error} Throws a `RangeError` with the applicable error message.
  117083. */
  117084. function error$1(type) {
  117085. throw new RangeError(errors[type]);
  117086. }
  117087. /**
  117088. * A generic `Array#map` utility function.
  117089. * @private
  117090. * @param {Array} array The array to iterate over.
  117091. * @param {Function} callback The function that gets called for every array
  117092. * item.
  117093. * @returns {Array} A new array of values returned by the callback function.
  117094. */
  117095. function map(array, fn) {
  117096. var result = [];
  117097. var length = array.length;
  117098. while (length--) {
  117099. result[length] = fn(array[length]);
  117100. }
  117101. return result;
  117102. }
  117103. /**
  117104. * A simple `Array#map`-like wrapper to work with domain name strings or email
  117105. * addresses.
  117106. * @private
  117107. * @param {String} domain The domain name or email address.
  117108. * @param {Function} callback The function that gets called for every
  117109. * character.
  117110. * @returns {Array} A new string of characters returned by the callback
  117111. * function.
  117112. */
  117113. function mapDomain(string, fn) {
  117114. var parts = string.split('@');
  117115. var result = '';
  117116. if (parts.length > 1) {
  117117. // In email addresses, only the domain name should be punycoded. Leave
  117118. // the local part (i.e. everything up to `@`) intact.
  117119. result = parts[0] + '@';
  117120. string = parts[1];
  117121. }
  117122. // Avoid `split(regex)` for IE8 compatibility. See #17.
  117123. string = string.replace(regexSeparators, '\x2E');
  117124. var labels = string.split('.');
  117125. var encoded = map(labels, fn).join('.');
  117126. return result + encoded;
  117127. }
  117128. /**
  117129. * Creates an array containing the numeric code points of each Unicode
  117130. * character in the string. While JavaScript uses UCS-2 internally,
  117131. * this function will convert a pair of surrogate halves (each of which
  117132. * UCS-2 exposes as separate characters) into a single code point,
  117133. * matching UTF-16.
  117134. * @see `punycode.ucs2.encode`
  117135. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  117136. * @memberOf punycode.ucs2
  117137. * @name decode
  117138. * @param {String} string The Unicode input string (UCS-2).
  117139. * @returns {Array} The new array of code points.
  117140. */
  117141. function ucs2decode(string) {
  117142. var output = [];
  117143. var counter = 0;
  117144. var length = string.length;
  117145. while (counter < length) {
  117146. var value = string.charCodeAt(counter++);
  117147. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  117148. // It's a high surrogate, and there is a next character.
  117149. var extra = string.charCodeAt(counter++);
  117150. if ((extra & 0xFC00) == 0xDC00) {
  117151. // Low surrogate.
  117152. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  117153. } else {
  117154. // It's an unmatched surrogate; only append this code unit, in case the
  117155. // next code unit is the high surrogate of a surrogate pair.
  117156. output.push(value);
  117157. counter--;
  117158. }
  117159. } else {
  117160. output.push(value);
  117161. }
  117162. }
  117163. return output;
  117164. }
  117165. /**
  117166. * Creates a string based on an array of numeric code points.
  117167. * @see `punycode.ucs2.decode`
  117168. * @memberOf punycode.ucs2
  117169. * @name encode
  117170. * @param {Array} codePoints The array of numeric code points.
  117171. * @returns {String} The new Unicode string (UCS-2).
  117172. */
  117173. var ucs2encode = function ucs2encode(array) {
  117174. return String.fromCodePoint.apply(String, toConsumableArray(array));
  117175. };
  117176. /**
  117177. * Converts a basic code point into a digit/integer.
  117178. * @see `digitToBasic()`
  117179. * @private
  117180. * @param {Number} codePoint The basic numeric code point value.
  117181. * @returns {Number} The numeric value of a basic code point (for use in
  117182. * representing integers) in the range `0` to `base - 1`, or `base` if
  117183. * the code point does not represent a value.
  117184. */
  117185. var basicToDigit = function basicToDigit(codePoint) {
  117186. if (codePoint - 0x30 < 0x0A) {
  117187. return codePoint - 0x16;
  117188. }
  117189. if (codePoint - 0x41 < 0x1A) {
  117190. return codePoint - 0x41;
  117191. }
  117192. if (codePoint - 0x61 < 0x1A) {
  117193. return codePoint - 0x61;
  117194. }
  117195. return base;
  117196. };
  117197. /**
  117198. * Converts a digit/integer into a basic code point.
  117199. * @see `basicToDigit()`
  117200. * @private
  117201. * @param {Number} digit The numeric value of a basic code point.
  117202. * @returns {Number} The basic code point whose value (when used for
  117203. * representing integers) is `digit`, which needs to be in the range
  117204. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  117205. * used; else, the lowercase form is used. The behavior is undefined
  117206. * if `flag` is non-zero and `digit` has no uppercase form.
  117207. */
  117208. var digitToBasic = function digitToBasic(digit, flag) {
  117209. // 0..25 map to ASCII a..z or A..Z
  117210. // 26..35 map to ASCII 0..9
  117211. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  117212. };
  117213. /**
  117214. * Bias adaptation function as per section 3.4 of RFC 3492.
  117215. * https://tools.ietf.org/html/rfc3492#section-3.4
  117216. * @private
  117217. */
  117218. var adapt = function adapt(delta, numPoints, firstTime) {
  117219. var k = 0;
  117220. delta = firstTime ? floor(delta / damp) : delta >> 1;
  117221. delta += floor(delta / numPoints);
  117222. for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
  117223. delta = floor(delta / baseMinusTMin);
  117224. }
  117225. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  117226. };
  117227. /**
  117228. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  117229. * symbols.
  117230. * @memberOf punycode
  117231. * @param {String} input The Punycode string of ASCII-only symbols.
  117232. * @returns {String} The resulting string of Unicode symbols.
  117233. */
  117234. var decode = function decode(input) {
  117235. // Don't use UCS-2.
  117236. var output = [];
  117237. var inputLength = input.length;
  117238. var i = 0;
  117239. var n = initialN;
  117240. var bias = initialBias;
  117241. // Handle the basic code points: let `basic` be the number of input code
  117242. // points before the last delimiter, or `0` if there is none, then copy
  117243. // the first basic code points to the output.
  117244. var basic = input.lastIndexOf(delimiter);
  117245. if (basic < 0) {
  117246. basic = 0;
  117247. }
  117248. for (var j = 0; j < basic; ++j) {
  117249. // if it's not a basic code point
  117250. if (input.charCodeAt(j) >= 0x80) {
  117251. error$1('not-basic');
  117252. }
  117253. output.push(input.charCodeAt(j));
  117254. }
  117255. // Main decoding loop: start just after the last delimiter if any basic code
  117256. // points were copied; start at the beginning otherwise.
  117257. for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{
  117258. // `index` is the index of the next character to be consumed.
  117259. // Decode a generalized variable-length integer into `delta`,
  117260. // which gets added to `i`. The overflow checking is easier
  117261. // if we increase `i` as we go, then subtract off its starting
  117262. // value at the end to obtain `delta`.
  117263. var oldi = i;
  117264. for (var w = 1, k = base;; /* no condition */k += base) {
  117265. if (index >= inputLength) {
  117266. error$1('invalid-input');
  117267. }
  117268. var digit = basicToDigit(input.charCodeAt(index++));
  117269. if (digit >= base || digit > floor((maxInt - i) / w)) {
  117270. error$1('overflow');
  117271. }
  117272. i += digit * w;
  117273. var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
  117274. if (digit < t) {
  117275. break;
  117276. }
  117277. var baseMinusT = base - t;
  117278. if (w > floor(maxInt / baseMinusT)) {
  117279. error$1('overflow');
  117280. }
  117281. w *= baseMinusT;
  117282. }
  117283. var out = output.length + 1;
  117284. bias = adapt(i - oldi, out, oldi == 0);
  117285. // `i` was supposed to wrap around from `out` to `0`,
  117286. // incrementing `n` each time, so we'll fix that now:
  117287. if (floor(i / out) > maxInt - n) {
  117288. error$1('overflow');
  117289. }
  117290. n += floor(i / out);
  117291. i %= out;
  117292. // Insert `n` at position `i` of the output.
  117293. output.splice(i++, 0, n);
  117294. }
  117295. return String.fromCodePoint.apply(String, output);
  117296. };
  117297. /**
  117298. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  117299. * Punycode string of ASCII-only symbols.
  117300. * @memberOf punycode
  117301. * @param {String} input The string of Unicode symbols.
  117302. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  117303. */
  117304. var encode = function encode(input) {
  117305. var output = [];
  117306. // Convert the input in UCS-2 to an array of Unicode code points.
  117307. input = ucs2decode(input);
  117308. // Cache the length.
  117309. var inputLength = input.length;
  117310. // Initialize the state.
  117311. var n = initialN;
  117312. var delta = 0;
  117313. var bias = initialBias;
  117314. // Handle the basic code points.
  117315. var _iteratorNormalCompletion = true;
  117316. var _didIteratorError = false;
  117317. var _iteratorError = undefined;
  117318. try {
  117319. for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  117320. var _currentValue2 = _step.value;
  117321. if (_currentValue2 < 0x80) {
  117322. output.push(stringFromCharCode(_currentValue2));
  117323. }
  117324. }
  117325. } catch (err) {
  117326. _didIteratorError = true;
  117327. _iteratorError = err;
  117328. } finally {
  117329. try {
  117330. if (!_iteratorNormalCompletion && _iterator.return) {
  117331. _iterator.return();
  117332. }
  117333. } finally {
  117334. if (_didIteratorError) {
  117335. throw _iteratorError;
  117336. }
  117337. }
  117338. }
  117339. var basicLength = output.length;
  117340. var handledCPCount = basicLength;
  117341. // `handledCPCount` is the number of code points that have been handled;
  117342. // `basicLength` is the number of basic code points.
  117343. // Finish the basic string with a delimiter unless it's empty.
  117344. if (basicLength) {
  117345. output.push(delimiter);
  117346. }
  117347. // Main encoding loop:
  117348. while (handledCPCount < inputLength) {
  117349. // All non-basic code points < n have been handled already. Find the next
  117350. // larger one:
  117351. var m = maxInt;
  117352. var _iteratorNormalCompletion2 = true;
  117353. var _didIteratorError2 = false;
  117354. var _iteratorError2 = undefined;
  117355. try {
  117356. for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  117357. var currentValue = _step2.value;
  117358. if (currentValue >= n && currentValue < m) {
  117359. m = currentValue;
  117360. }
  117361. }
  117362. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  117363. // but guard against overflow.
  117364. } catch (err) {
  117365. _didIteratorError2 = true;
  117366. _iteratorError2 = err;
  117367. } finally {
  117368. try {
  117369. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  117370. _iterator2.return();
  117371. }
  117372. } finally {
  117373. if (_didIteratorError2) {
  117374. throw _iteratorError2;
  117375. }
  117376. }
  117377. }
  117378. var handledCPCountPlusOne = handledCPCount + 1;
  117379. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  117380. error$1('overflow');
  117381. }
  117382. delta += (m - n) * handledCPCountPlusOne;
  117383. n = m;
  117384. var _iteratorNormalCompletion3 = true;
  117385. var _didIteratorError3 = false;
  117386. var _iteratorError3 = undefined;
  117387. try {
  117388. for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  117389. var _currentValue = _step3.value;
  117390. if (_currentValue < n && ++delta > maxInt) {
  117391. error$1('overflow');
  117392. }
  117393. if (_currentValue == n) {
  117394. // Represent delta as a generalized variable-length integer.
  117395. var q = delta;
  117396. for (var k = base;; /* no condition */k += base) {
  117397. var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
  117398. if (q < t) {
  117399. break;
  117400. }
  117401. var qMinusT = q - t;
  117402. var baseMinusT = base - t;
  117403. output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
  117404. q = floor(qMinusT / baseMinusT);
  117405. }
  117406. output.push(stringFromCharCode(digitToBasic(q, 0)));
  117407. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  117408. delta = 0;
  117409. ++handledCPCount;
  117410. }
  117411. }
  117412. } catch (err) {
  117413. _didIteratorError3 = true;
  117414. _iteratorError3 = err;
  117415. } finally {
  117416. try {
  117417. if (!_iteratorNormalCompletion3 && _iterator3.return) {
  117418. _iterator3.return();
  117419. }
  117420. } finally {
  117421. if (_didIteratorError3) {
  117422. throw _iteratorError3;
  117423. }
  117424. }
  117425. }
  117426. ++delta;
  117427. ++n;
  117428. }
  117429. return output.join('');
  117430. };
  117431. /**
  117432. * Converts a Punycode string representing a domain name or an email address
  117433. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  117434. * it doesn't matter if you call it on a string that has already been
  117435. * converted to Unicode.
  117436. * @memberOf punycode
  117437. * @param {String} input The Punycoded domain name or email address to
  117438. * convert to Unicode.
  117439. * @returns {String} The Unicode representation of the given Punycode
  117440. * string.
  117441. */
  117442. var toUnicode = function toUnicode(input) {
  117443. return mapDomain(input, function (string) {
  117444. return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
  117445. });
  117446. };
  117447. /**
  117448. * Converts a Unicode string representing a domain name or an email address to
  117449. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  117450. * i.e. it doesn't matter if you call it with a domain that's already in
  117451. * ASCII.
  117452. * @memberOf punycode
  117453. * @param {String} input The domain name or email address to convert, as a
  117454. * Unicode string.
  117455. * @returns {String} The Punycode representation of the given domain name or
  117456. * email address.
  117457. */
  117458. var toASCII = function toASCII(input) {
  117459. return mapDomain(input, function (string) {
  117460. return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
  117461. });
  117462. };
  117463. /*--------------------------------------------------------------------------*/
  117464. /** Define the public API */
  117465. var punycode = {
  117466. /**
  117467. * A string representing the current Punycode.js version number.
  117468. * @memberOf punycode
  117469. * @type String
  117470. */
  117471. 'version': '2.1.0',
  117472. /**
  117473. * An object of methods to convert from JavaScript's internal character
  117474. * representation (UCS-2) to Unicode code points, and back.
  117475. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  117476. * @memberOf punycode
  117477. * @type Object
  117478. */
  117479. 'ucs2': {
  117480. 'decode': ucs2decode,
  117481. 'encode': ucs2encode
  117482. },
  117483. 'decode': decode,
  117484. 'encode': encode,
  117485. 'toASCII': toASCII,
  117486. 'toUnicode': toUnicode
  117487. };
  117488. /**
  117489. * URI.js
  117490. *
  117491. * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
  117492. * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
  117493. * @see http://github.com/garycourt/uri-js
  117494. */
  117495. /**
  117496. * Copyright 2011 Gary Court. All rights reserved.
  117497. *
  117498. * Redistribution and use in source and binary forms, with or without modification, are
  117499. * permitted provided that the following conditions are met:
  117500. *
  117501. * 1. Redistributions of source code must retain the above copyright notice, this list of
  117502. * conditions and the following disclaimer.
  117503. *
  117504. * 2. Redistributions in binary form must reproduce the above copyright notice, this list
  117505. * of conditions and the following disclaimer in the documentation and/or other materials
  117506. * provided with the distribution.
  117507. *
  117508. * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
  117509. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  117510. * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
  117511. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  117512. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  117513. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  117514. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  117515. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  117516. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  117517. *
  117518. * The views and conclusions contained in the software and documentation are those of the
  117519. * authors and should not be interpreted as representing official policies, either expressed
  117520. * or implied, of Gary Court.
  117521. */
  117522. var SCHEMES = {};
  117523. function pctEncChar(chr) {
  117524. var c = chr.charCodeAt(0);
  117525. var e = void 0;
  117526. if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
  117527. return e;
  117528. }
  117529. function pctDecChars(str) {
  117530. var newStr = "";
  117531. var i = 0;
  117532. var il = str.length;
  117533. while (i < il) {
  117534. var c = parseInt(str.substr(i + 1, 2), 16);
  117535. if (c < 128) {
  117536. newStr += String.fromCharCode(c);
  117537. i += 3;
  117538. } else if (c >= 194 && c < 224) {
  117539. if (il - i >= 6) {
  117540. var c2 = parseInt(str.substr(i + 4, 2), 16);
  117541. newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
  117542. } else {
  117543. newStr += str.substr(i, 6);
  117544. }
  117545. i += 6;
  117546. } else if (c >= 224) {
  117547. if (il - i >= 9) {
  117548. var _c = parseInt(str.substr(i + 4, 2), 16);
  117549. var c3 = parseInt(str.substr(i + 7, 2), 16);
  117550. newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
  117551. } else {
  117552. newStr += str.substr(i, 9);
  117553. }
  117554. i += 9;
  117555. } else {
  117556. newStr += str.substr(i, 3);
  117557. i += 3;
  117558. }
  117559. }
  117560. return newStr;
  117561. }
  117562. function _normalizeComponentEncoding(components, protocol) {
  117563. function decodeUnreserved(str) {
  117564. var decStr = pctDecChars(str);
  117565. return !decStr.match(protocol.UNRESERVED) ? str : decStr;
  117566. }
  117567. if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
  117568. if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
  117569. if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
  117570. if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
  117571. if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
  117572. if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
  117573. return components;
  117574. }
  117575. function _stripLeadingZeros(str) {
  117576. return str.replace(/^0*(.*)/, "$1") || "0";
  117577. }
  117578. function _normalizeIPv4(host, protocol) {
  117579. var matches = host.match(protocol.IPV4ADDRESS) || [];
  117580. var _matches = slicedToArray(matches, 2),
  117581. address = _matches[1];
  117582. if (address) {
  117583. return address.split(".").map(_stripLeadingZeros).join(".");
  117584. } else {
  117585. return host;
  117586. }
  117587. }
  117588. function _normalizeIPv6(host, protocol) {
  117589. var matches = host.match(protocol.IPV6ADDRESS) || [];
  117590. var _matches2 = slicedToArray(matches, 3),
  117591. address = _matches2[1],
  117592. zone = _matches2[2];
  117593. if (address) {
  117594. var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(),
  117595. _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2),
  117596. last = _address$toLowerCase$2[0],
  117597. first = _address$toLowerCase$2[1];
  117598. var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
  117599. var lastFields = last.split(":").map(_stripLeadingZeros);
  117600. var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
  117601. var fieldCount = isLastFieldIPv4Address ? 7 : 8;
  117602. var lastFieldsStart = lastFields.length - fieldCount;
  117603. var fields = Array(fieldCount);
  117604. for (var x = 0; x < fieldCount; ++x) {
  117605. fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
  117606. }
  117607. if (isLastFieldIPv4Address) {
  117608. fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
  117609. }
  117610. var allZeroFields = fields.reduce(function (acc, field, index) {
  117611. if (!field || field === "0") {
  117612. var lastLongest = acc[acc.length - 1];
  117613. if (lastLongest && lastLongest.index + lastLongest.length === index) {
  117614. lastLongest.length++;
  117615. } else {
  117616. acc.push({ index: index, length: 1 });
  117617. }
  117618. }
  117619. return acc;
  117620. }, []);
  117621. var longestZeroFields = allZeroFields.sort(function (a, b) {
  117622. return b.length - a.length;
  117623. })[0];
  117624. var newHost = void 0;
  117625. if (longestZeroFields && longestZeroFields.length > 1) {
  117626. var newFirst = fields.slice(0, longestZeroFields.index);
  117627. var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
  117628. newHost = newFirst.join(":") + "::" + newLast.join(":");
  117629. } else {
  117630. newHost = fields.join(":");
  117631. }
  117632. if (zone) {
  117633. newHost += "%" + zone;
  117634. }
  117635. return newHost;
  117636. } else {
  117637. return host;
  117638. }
  117639. }
  117640. var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
  117641. var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
  117642. function parse(uriString) {
  117643. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  117644. var components = {};
  117645. var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
  117646. if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
  117647. var matches = uriString.match(URI_PARSE);
  117648. if (matches) {
  117649. if (NO_MATCH_IS_UNDEFINED) {
  117650. //store each component
  117651. components.scheme = matches[1];
  117652. components.userinfo = matches[3];
  117653. components.host = matches[4];
  117654. components.port = parseInt(matches[5], 10);
  117655. components.path = matches[6] || "";
  117656. components.query = matches[7];
  117657. components.fragment = matches[8];
  117658. //fix port number
  117659. if (isNaN(components.port)) {
  117660. components.port = matches[5];
  117661. }
  117662. } else {
  117663. //IE FIX for improper RegExp matching
  117664. //store each component
  117665. components.scheme = matches[1] || undefined;
  117666. components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined;
  117667. components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined;
  117668. components.port = parseInt(matches[5], 10);
  117669. components.path = matches[6] || "";
  117670. components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined;
  117671. components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined;
  117672. //fix port number
  117673. if (isNaN(components.port)) {
  117674. components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined;
  117675. }
  117676. }
  117677. if (components.host) {
  117678. //normalize IP hosts
  117679. components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
  117680. }
  117681. //determine reference type
  117682. if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {
  117683. components.reference = "same-document";
  117684. } else if (components.scheme === undefined) {
  117685. components.reference = "relative";
  117686. } else if (components.fragment === undefined) {
  117687. components.reference = "absolute";
  117688. } else {
  117689. components.reference = "uri";
  117690. }
  117691. //check for reference errors
  117692. if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
  117693. components.error = components.error || "URI is not a " + options.reference + " reference.";
  117694. }
  117695. //find scheme handler
  117696. var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
  117697. //check if scheme can't handle IRIs
  117698. if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
  117699. //if host component is a domain name
  117700. if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
  117701. //convert Unicode IDN -> ASCII IDN
  117702. try {
  117703. components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
  117704. } catch (e) {
  117705. components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
  117706. }
  117707. }
  117708. //convert IRI -> URI
  117709. _normalizeComponentEncoding(components, URI_PROTOCOL);
  117710. } else {
  117711. //normalize encodings
  117712. _normalizeComponentEncoding(components, protocol);
  117713. }
  117714. //perform scheme specific parsing
  117715. if (schemeHandler && schemeHandler.parse) {
  117716. schemeHandler.parse(components, options);
  117717. }
  117718. } else {
  117719. components.error = components.error || "URI can not be parsed.";
  117720. }
  117721. return components;
  117722. }
  117723. function _recomposeAuthority(components, options) {
  117724. var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
  117725. var uriTokens = [];
  117726. if (components.userinfo !== undefined) {
  117727. uriTokens.push(components.userinfo);
  117728. uriTokens.push("@");
  117729. }
  117730. if (components.host !== undefined) {
  117731. //normalize IP hosts, add brackets and escape zone separator for IPv6
  117732. uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) {
  117733. return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
  117734. }));
  117735. }
  117736. if (typeof components.port === "number" || typeof components.port === "string") {
  117737. uriTokens.push(":");
  117738. uriTokens.push(String(components.port));
  117739. }
  117740. return uriTokens.length ? uriTokens.join("") : undefined;
  117741. }
  117742. var RDS1 = /^\.\.?\//;
  117743. var RDS2 = /^\/\.(\/|$)/;
  117744. var RDS3 = /^\/\.\.(\/|$)/;
  117745. var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
  117746. function removeDotSegments(input) {
  117747. var output = [];
  117748. while (input.length) {
  117749. if (input.match(RDS1)) {
  117750. input = input.replace(RDS1, "");
  117751. } else if (input.match(RDS2)) {
  117752. input = input.replace(RDS2, "/");
  117753. } else if (input.match(RDS3)) {
  117754. input = input.replace(RDS3, "/");
  117755. output.pop();
  117756. } else if (input === "." || input === "..") {
  117757. input = "";
  117758. } else {
  117759. var im = input.match(RDS5);
  117760. if (im) {
  117761. var s = im[0];
  117762. input = input.slice(s.length);
  117763. output.push(s);
  117764. } else {
  117765. throw new Error("Unexpected dot segment condition");
  117766. }
  117767. }
  117768. }
  117769. return output.join("");
  117770. }
  117771. function serialize(components) {
  117772. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  117773. var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
  117774. var uriTokens = [];
  117775. //find scheme handler
  117776. var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
  117777. //perform scheme specific serialization
  117778. if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
  117779. if (components.host) {
  117780. //if host component is an IPv6 address
  117781. if (protocol.IPV6ADDRESS.test(components.host)) {}
  117782. //TODO: normalize IPv6 address as per RFC 5952
  117783. //if host component is a domain name
  117784. else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
  117785. //convert IDN via punycode
  117786. try {
  117787. components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
  117788. } catch (e) {
  117789. components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
  117790. }
  117791. }
  117792. }
  117793. //normalize encoding
  117794. _normalizeComponentEncoding(components, protocol);
  117795. if (options.reference !== "suffix" && components.scheme) {
  117796. uriTokens.push(components.scheme);
  117797. uriTokens.push(":");
  117798. }
  117799. var authority = _recomposeAuthority(components, options);
  117800. if (authority !== undefined) {
  117801. if (options.reference !== "suffix") {
  117802. uriTokens.push("//");
  117803. }
  117804. uriTokens.push(authority);
  117805. if (components.path && components.path.charAt(0) !== "/") {
  117806. uriTokens.push("/");
  117807. }
  117808. }
  117809. if (components.path !== undefined) {
  117810. var s = components.path;
  117811. if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
  117812. s = removeDotSegments(s);
  117813. }
  117814. if (authority === undefined) {
  117815. s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//"
  117816. }
  117817. uriTokens.push(s);
  117818. }
  117819. if (components.query !== undefined) {
  117820. uriTokens.push("?");
  117821. uriTokens.push(components.query);
  117822. }
  117823. if (components.fragment !== undefined) {
  117824. uriTokens.push("#");
  117825. uriTokens.push(components.fragment);
  117826. }
  117827. return uriTokens.join(""); //merge tokens into a string
  117828. }
  117829. function resolveComponents(base, relative) {
  117830. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  117831. var skipNormalization = arguments[3];
  117832. var target = {};
  117833. if (!skipNormalization) {
  117834. base = parse(serialize(base, options), options); //normalize base components
  117835. relative = parse(serialize(relative, options), options); //normalize relative components
  117836. }
  117837. options = options || {};
  117838. if (!options.tolerant && relative.scheme) {
  117839. target.scheme = relative.scheme;
  117840. //target.authority = relative.authority;
  117841. target.userinfo = relative.userinfo;
  117842. target.host = relative.host;
  117843. target.port = relative.port;
  117844. target.path = removeDotSegments(relative.path || "");
  117845. target.query = relative.query;
  117846. } else {
  117847. if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
  117848. //target.authority = relative.authority;
  117849. target.userinfo = relative.userinfo;
  117850. target.host = relative.host;
  117851. target.port = relative.port;
  117852. target.path = removeDotSegments(relative.path || "");
  117853. target.query = relative.query;
  117854. } else {
  117855. if (!relative.path) {
  117856. target.path = base.path;
  117857. if (relative.query !== undefined) {
  117858. target.query = relative.query;
  117859. } else {
  117860. target.query = base.query;
  117861. }
  117862. } else {
  117863. if (relative.path.charAt(0) === "/") {
  117864. target.path = removeDotSegments(relative.path);
  117865. } else {
  117866. if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
  117867. target.path = "/" + relative.path;
  117868. } else if (!base.path) {
  117869. target.path = relative.path;
  117870. } else {
  117871. target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
  117872. }
  117873. target.path = removeDotSegments(target.path);
  117874. }
  117875. target.query = relative.query;
  117876. }
  117877. //target.authority = base.authority;
  117878. target.userinfo = base.userinfo;
  117879. target.host = base.host;
  117880. target.port = base.port;
  117881. }
  117882. target.scheme = base.scheme;
  117883. }
  117884. target.fragment = relative.fragment;
  117885. return target;
  117886. }
  117887. function resolve(baseURI, relativeURI, options) {
  117888. var schemelessOptions = assign({ scheme: 'null' }, options);
  117889. return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
  117890. }
  117891. function normalize(uri, options) {
  117892. if (typeof uri === "string") {
  117893. uri = serialize(parse(uri, options), options);
  117894. } else if (typeOf(uri) === "object") {
  117895. uri = parse(serialize(uri, options), options);
  117896. }
  117897. return uri;
  117898. }
  117899. function equal(uriA, uriB, options) {
  117900. if (typeof uriA === "string") {
  117901. uriA = serialize(parse(uriA, options), options);
  117902. } else if (typeOf(uriA) === "object") {
  117903. uriA = serialize(uriA, options);
  117904. }
  117905. if (typeof uriB === "string") {
  117906. uriB = serialize(parse(uriB, options), options);
  117907. } else if (typeOf(uriB) === "object") {
  117908. uriB = serialize(uriB, options);
  117909. }
  117910. return uriA === uriB;
  117911. }
  117912. function escapeComponent(str, options) {
  117913. return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
  117914. }
  117915. function unescapeComponent(str, options) {
  117916. return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
  117917. }
  117918. var handler = {
  117919. scheme: "http",
  117920. domainHost: true,
  117921. parse: function parse(components, options) {
  117922. //report missing host
  117923. if (!components.host) {
  117924. components.error = components.error || "HTTP URIs must have a host.";
  117925. }
  117926. return components;
  117927. },
  117928. serialize: function serialize(components, options) {
  117929. var secure = String(components.scheme).toLowerCase() === "https";
  117930. //normalize the default port
  117931. if (components.port === (secure ? 443 : 80) || components.port === "") {
  117932. components.port = undefined;
  117933. }
  117934. //normalize the empty path
  117935. if (!components.path) {
  117936. components.path = "/";
  117937. }
  117938. //NOTE: We do not parse query strings for HTTP URIs
  117939. //as WWW Form Url Encoded query strings are part of the HTML4+ spec,
  117940. //and not the HTTP spec.
  117941. return components;
  117942. }
  117943. };
  117944. var handler$1 = {
  117945. scheme: "https",
  117946. domainHost: handler.domainHost,
  117947. parse: handler.parse,
  117948. serialize: handler.serialize
  117949. };
  117950. function isSecure(wsComponents) {
  117951. return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
  117952. }
  117953. //RFC 6455
  117954. var handler$2 = {
  117955. scheme: "ws",
  117956. domainHost: true,
  117957. parse: function parse(components, options) {
  117958. var wsComponents = components;
  117959. //indicate if the secure flag is set
  117960. wsComponents.secure = isSecure(wsComponents);
  117961. //construct resouce name
  117962. wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');
  117963. wsComponents.path = undefined;
  117964. wsComponents.query = undefined;
  117965. return wsComponents;
  117966. },
  117967. serialize: function serialize(wsComponents, options) {
  117968. //normalize the default port
  117969. if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
  117970. wsComponents.port = undefined;
  117971. }
  117972. //ensure scheme matches secure flag
  117973. if (typeof wsComponents.secure === 'boolean') {
  117974. wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws';
  117975. wsComponents.secure = undefined;
  117976. }
  117977. //reconstruct path from resource name
  117978. if (wsComponents.resourceName) {
  117979. var _wsComponents$resourc = wsComponents.resourceName.split('?'),
  117980. _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2),
  117981. path = _wsComponents$resourc2[0],
  117982. query = _wsComponents$resourc2[1];
  117983. wsComponents.path = path && path !== '/' ? path : undefined;
  117984. wsComponents.query = query;
  117985. wsComponents.resourceName = undefined;
  117986. }
  117987. //forbid fragment component
  117988. wsComponents.fragment = undefined;
  117989. return wsComponents;
  117990. }
  117991. };
  117992. var handler$3 = {
  117993. scheme: "wss",
  117994. domainHost: handler$2.domainHost,
  117995. parse: handler$2.parse,
  117996. serialize: handler$2.serialize
  117997. };
  117998. var O = {};
  117999. var isIRI = true;
  118000. //RFC 3986
  118001. var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
  118002. var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
  118003. var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
  118004. //RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
  118005. //const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
  118006. //const WSP$$ = "[\\x20\\x09]";
  118007. //const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127)
  118008. //const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext
  118009. //const VCHAR$$ = "[\\x21-\\x7E]";
  118010. //const WSP$$ = "[\\x20\\x09]";
  118011. //const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext
  118012. //const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
  118013. //const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
  118014. //const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
  118015. var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
  118016. var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
  118017. var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
  118018. var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
  118019. var UNRESERVED = new RegExp(UNRESERVED$$, "g");
  118020. var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
  118021. var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
  118022. var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
  118023. var NOT_HFVALUE = NOT_HFNAME;
  118024. function decodeUnreserved(str) {
  118025. var decStr = pctDecChars(str);
  118026. return !decStr.match(UNRESERVED) ? str : decStr;
  118027. }
  118028. var handler$4 = {
  118029. scheme: "mailto",
  118030. parse: function parse$$1(components, options) {
  118031. var mailtoComponents = components;
  118032. var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
  118033. mailtoComponents.path = undefined;
  118034. if (mailtoComponents.query) {
  118035. var unknownHeaders = false;
  118036. var headers = {};
  118037. var hfields = mailtoComponents.query.split("&");
  118038. for (var x = 0, xl = hfields.length; x < xl; ++x) {
  118039. var hfield = hfields[x].split("=");
  118040. switch (hfield[0]) {
  118041. case "to":
  118042. var toAddrs = hfield[1].split(",");
  118043. for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
  118044. to.push(toAddrs[_x]);
  118045. }
  118046. break;
  118047. case "subject":
  118048. mailtoComponents.subject = unescapeComponent(hfield[1], options);
  118049. break;
  118050. case "body":
  118051. mailtoComponents.body = unescapeComponent(hfield[1], options);
  118052. break;
  118053. default:
  118054. unknownHeaders = true;
  118055. headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
  118056. break;
  118057. }
  118058. }
  118059. if (unknownHeaders) mailtoComponents.headers = headers;
  118060. }
  118061. mailtoComponents.query = undefined;
  118062. for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
  118063. var addr = to[_x2].split("@");
  118064. addr[0] = unescapeComponent(addr[0]);
  118065. if (!options.unicodeSupport) {
  118066. //convert Unicode IDN -> ASCII IDN
  118067. try {
  118068. addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
  118069. } catch (e) {
  118070. mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
  118071. }
  118072. } else {
  118073. addr[1] = unescapeComponent(addr[1], options).toLowerCase();
  118074. }
  118075. to[_x2] = addr.join("@");
  118076. }
  118077. return mailtoComponents;
  118078. },
  118079. serialize: function serialize$$1(mailtoComponents, options) {
  118080. var components = mailtoComponents;
  118081. var to = toArray(mailtoComponents.to);
  118082. if (to) {
  118083. for (var x = 0, xl = to.length; x < xl; ++x) {
  118084. var toAddr = String(to[x]);
  118085. var atIdx = toAddr.lastIndexOf("@");
  118086. var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
  118087. var domain = toAddr.slice(atIdx + 1);
  118088. //convert IDN via punycode
  118089. try {
  118090. domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
  118091. } catch (e) {
  118092. components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
  118093. }
  118094. to[x] = localPart + "@" + domain;
  118095. }
  118096. components.path = to.join(",");
  118097. }
  118098. var headers = mailtoComponents.headers = mailtoComponents.headers || {};
  118099. if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
  118100. if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
  118101. var fields = [];
  118102. for (var name in headers) {
  118103. if (headers[name] !== O[name]) {
  118104. fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
  118105. }
  118106. }
  118107. if (fields.length) {
  118108. components.query = fields.join("&");
  118109. }
  118110. return components;
  118111. }
  118112. };
  118113. var URN_PARSE = /^([^\:]+)\:(.*)/;
  118114. //RFC 2141
  118115. var handler$5 = {
  118116. scheme: "urn",
  118117. parse: function parse$$1(components, options) {
  118118. var matches = components.path && components.path.match(URN_PARSE);
  118119. var urnComponents = components;
  118120. if (matches) {
  118121. var scheme = options.scheme || urnComponents.scheme || "urn";
  118122. var nid = matches[1].toLowerCase();
  118123. var nss = matches[2];
  118124. var urnScheme = scheme + ":" + (options.nid || nid);
  118125. var schemeHandler = SCHEMES[urnScheme];
  118126. urnComponents.nid = nid;
  118127. urnComponents.nss = nss;
  118128. urnComponents.path = undefined;
  118129. if (schemeHandler) {
  118130. urnComponents = schemeHandler.parse(urnComponents, options);
  118131. }
  118132. } else {
  118133. urnComponents.error = urnComponents.error || "URN can not be parsed.";
  118134. }
  118135. return urnComponents;
  118136. },
  118137. serialize: function serialize$$1(urnComponents, options) {
  118138. var scheme = options.scheme || urnComponents.scheme || "urn";
  118139. var nid = urnComponents.nid;
  118140. var urnScheme = scheme + ":" + (options.nid || nid);
  118141. var schemeHandler = SCHEMES[urnScheme];
  118142. if (schemeHandler) {
  118143. urnComponents = schemeHandler.serialize(urnComponents, options);
  118144. }
  118145. var uriComponents = urnComponents;
  118146. var nss = urnComponents.nss;
  118147. uriComponents.path = (nid || options.nid) + ":" + nss;
  118148. return uriComponents;
  118149. }
  118150. };
  118151. var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
  118152. //RFC 4122
  118153. var handler$6 = {
  118154. scheme: "urn:uuid",
  118155. parse: function parse(urnComponents, options) {
  118156. var uuidComponents = urnComponents;
  118157. uuidComponents.uuid = uuidComponents.nss;
  118158. uuidComponents.nss = undefined;
  118159. if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
  118160. uuidComponents.error = uuidComponents.error || "UUID is not valid.";
  118161. }
  118162. return uuidComponents;
  118163. },
  118164. serialize: function serialize(uuidComponents, options) {
  118165. var urnComponents = uuidComponents;
  118166. //normalize UUID
  118167. urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
  118168. return urnComponents;
  118169. }
  118170. };
  118171. SCHEMES[handler.scheme] = handler;
  118172. SCHEMES[handler$1.scheme] = handler$1;
  118173. SCHEMES[handler$2.scheme] = handler$2;
  118174. SCHEMES[handler$3.scheme] = handler$3;
  118175. SCHEMES[handler$4.scheme] = handler$4;
  118176. SCHEMES[handler$5.scheme] = handler$5;
  118177. SCHEMES[handler$6.scheme] = handler$6;
  118178. exports.SCHEMES = SCHEMES;
  118179. exports.pctEncChar = pctEncChar;
  118180. exports.pctDecChars = pctDecChars;
  118181. exports.parse = parse;
  118182. exports.removeDotSegments = removeDotSegments;
  118183. exports.serialize = serialize;
  118184. exports.resolveComponents = resolveComponents;
  118185. exports.resolve = resolve;
  118186. exports.normalize = normalize;
  118187. exports.equal = equal;
  118188. exports.escapeComponent = escapeComponent;
  118189. exports.unescapeComponent = unescapeComponent;
  118190. Object.defineProperty(exports, '__esModule', { value: true });
  118191. })));
  118192. },{}],653:[function(require,module,exports){
  118193. // Copyright Joyent, Inc. and other Node contributors.
  118194. //
  118195. // Permission is hereby granted, free of charge, to any person obtaining a
  118196. // copy of this software and associated documentation files (the
  118197. // "Software"), to deal in the Software without restriction, including
  118198. // without limitation the rights to use, copy, modify, merge, publish,
  118199. // distribute, sublicense, and/or sell copies of the Software, and to permit
  118200. // persons to whom the Software is furnished to do so, subject to the
  118201. // following conditions:
  118202. //
  118203. // The above copyright notice and this permission notice shall be included
  118204. // in all copies or substantial portions of the Software.
  118205. //
  118206. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  118207. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  118208. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  118209. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  118210. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  118211. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  118212. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  118213. 'use strict';
  118214. var punycode = require('punycode');
  118215. var util = require('./util');
  118216. exports.parse = urlParse;
  118217. exports.resolve = urlResolve;
  118218. exports.resolveObject = urlResolveObject;
  118219. exports.format = urlFormat;
  118220. exports.Url = Url;
  118221. function Url() {
  118222. this.protocol = null;
  118223. this.slashes = null;
  118224. this.auth = null;
  118225. this.host = null;
  118226. this.port = null;
  118227. this.hostname = null;
  118228. this.hash = null;
  118229. this.search = null;
  118230. this.query = null;
  118231. this.pathname = null;
  118232. this.path = null;
  118233. this.href = null;
  118234. }
  118235. // Reference: RFC 3986, RFC 1808, RFC 2396
  118236. // define these here so at least they only have to be
  118237. // compiled once on the first module load.
  118238. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  118239. portPattern = /:[0-9]*$/,
  118240. // Special case for a simple path URL
  118241. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  118242. // RFC 2396: characters reserved for delimiting URLs.
  118243. // We actually just auto-escape these.
  118244. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  118245. // RFC 2396: characters not allowed for various reasons.
  118246. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  118247. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  118248. autoEscape = ['\''].concat(unwise),
  118249. // Characters that are never ever allowed in a hostname.
  118250. // Note that any invalid chars are also handled, but these
  118251. // are the ones that are *expected* to be seen, so we fast-path
  118252. // them.
  118253. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  118254. hostEndingChars = ['/', '?', '#'],
  118255. hostnameMaxLen = 255,
  118256. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  118257. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  118258. // protocols that can allow "unsafe" and "unwise" chars.
  118259. unsafeProtocol = {
  118260. 'javascript': true,
  118261. 'javascript:': true
  118262. },
  118263. // protocols that never have a hostname.
  118264. hostlessProtocol = {
  118265. 'javascript': true,
  118266. 'javascript:': true
  118267. },
  118268. // protocols that always contain a // bit.
  118269. slashedProtocol = {
  118270. 'http': true,
  118271. 'https': true,
  118272. 'ftp': true,
  118273. 'gopher': true,
  118274. 'file': true,
  118275. 'http:': true,
  118276. 'https:': true,
  118277. 'ftp:': true,
  118278. 'gopher:': true,
  118279. 'file:': true
  118280. },
  118281. querystring = require('querystring');
  118282. function urlParse(url, parseQueryString, slashesDenoteHost) {
  118283. if (url && util.isObject(url) && url instanceof Url) return url;
  118284. var u = new Url;
  118285. u.parse(url, parseQueryString, slashesDenoteHost);
  118286. return u;
  118287. }
  118288. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  118289. if (!util.isString(url)) {
  118290. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  118291. }
  118292. // Copy chrome, IE, opera backslash-handling behavior.
  118293. // Back slashes before the query string get converted to forward slashes
  118294. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  118295. var queryIndex = url.indexOf('?'),
  118296. splitter =
  118297. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  118298. uSplit = url.split(splitter),
  118299. slashRegex = /\\/g;
  118300. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  118301. url = uSplit.join(splitter);
  118302. var rest = url;
  118303. // trim before proceeding.
  118304. // This is to support parse stuff like " http://foo.com \n"
  118305. rest = rest.trim();
  118306. if (!slashesDenoteHost && url.split('#').length === 1) {
  118307. // Try fast path regexp
  118308. var simplePath = simplePathPattern.exec(rest);
  118309. if (simplePath) {
  118310. this.path = rest;
  118311. this.href = rest;
  118312. this.pathname = simplePath[1];
  118313. if (simplePath[2]) {
  118314. this.search = simplePath[2];
  118315. if (parseQueryString) {
  118316. this.query = querystring.parse(this.search.substr(1));
  118317. } else {
  118318. this.query = this.search.substr(1);
  118319. }
  118320. } else if (parseQueryString) {
  118321. this.search = '';
  118322. this.query = {};
  118323. }
  118324. return this;
  118325. }
  118326. }
  118327. var proto = protocolPattern.exec(rest);
  118328. if (proto) {
  118329. proto = proto[0];
  118330. var lowerProto = proto.toLowerCase();
  118331. this.protocol = lowerProto;
  118332. rest = rest.substr(proto.length);
  118333. }
  118334. // figure out if it's got a host
  118335. // user@server is *always* interpreted as a hostname, and url
  118336. // resolution will treat //foo/bar as host=foo,path=bar because that's
  118337. // how the browser resolves relative URLs.
  118338. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  118339. var slashes = rest.substr(0, 2) === '//';
  118340. if (slashes && !(proto && hostlessProtocol[proto])) {
  118341. rest = rest.substr(2);
  118342. this.slashes = true;
  118343. }
  118344. }
  118345. if (!hostlessProtocol[proto] &&
  118346. (slashes || (proto && !slashedProtocol[proto]))) {
  118347. // there's a hostname.
  118348. // the first instance of /, ?, ;, or # ends the host.
  118349. //
  118350. // If there is an @ in the hostname, then non-host chars *are* allowed
  118351. // to the left of the last @ sign, unless some host-ending character
  118352. // comes *before* the @-sign.
  118353. // URLs are obnoxious.
  118354. //
  118355. // ex:
  118356. // http://a@b@c/ => user:a@b host:c
  118357. // http://a@b?@c => user:a host:c path:/?@c
  118358. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  118359. // Review our test case against browsers more comprehensively.
  118360. // find the first instance of any hostEndingChars
  118361. var hostEnd = -1;
  118362. for (var i = 0; i < hostEndingChars.length; i++) {
  118363. var hec = rest.indexOf(hostEndingChars[i]);
  118364. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  118365. hostEnd = hec;
  118366. }
  118367. // at this point, either we have an explicit point where the
  118368. // auth portion cannot go past, or the last @ char is the decider.
  118369. var auth, atSign;
  118370. if (hostEnd === -1) {
  118371. // atSign can be anywhere.
  118372. atSign = rest.lastIndexOf('@');
  118373. } else {
  118374. // atSign must be in auth portion.
  118375. // http://a@b/c@d => host:b auth:a path:/c@d
  118376. atSign = rest.lastIndexOf('@', hostEnd);
  118377. }
  118378. // Now we have a portion which is definitely the auth.
  118379. // Pull that off.
  118380. if (atSign !== -1) {
  118381. auth = rest.slice(0, atSign);
  118382. rest = rest.slice(atSign + 1);
  118383. this.auth = decodeURIComponent(auth);
  118384. }
  118385. // the host is the remaining to the left of the first non-host char
  118386. hostEnd = -1;
  118387. for (var i = 0; i < nonHostChars.length; i++) {
  118388. var hec = rest.indexOf(nonHostChars[i]);
  118389. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  118390. hostEnd = hec;
  118391. }
  118392. // if we still have not hit it, then the entire thing is a host.
  118393. if (hostEnd === -1)
  118394. hostEnd = rest.length;
  118395. this.host = rest.slice(0, hostEnd);
  118396. rest = rest.slice(hostEnd);
  118397. // pull out port.
  118398. this.parseHost();
  118399. // we've indicated that there is a hostname,
  118400. // so even if it's empty, it has to be present.
  118401. this.hostname = this.hostname || '';
  118402. // if hostname begins with [ and ends with ]
  118403. // assume that it's an IPv6 address.
  118404. var ipv6Hostname = this.hostname[0] === '[' &&
  118405. this.hostname[this.hostname.length - 1] === ']';
  118406. // validate a little.
  118407. if (!ipv6Hostname) {
  118408. var hostparts = this.hostname.split(/\./);
  118409. for (var i = 0, l = hostparts.length; i < l; i++) {
  118410. var part = hostparts[i];
  118411. if (!part) continue;
  118412. if (!part.match(hostnamePartPattern)) {
  118413. var newpart = '';
  118414. for (var j = 0, k = part.length; j < k; j++) {
  118415. if (part.charCodeAt(j) > 127) {
  118416. // we replace non-ASCII char with a temporary placeholder
  118417. // we need this to make sure size of hostname is not
  118418. // broken by replacing non-ASCII by nothing
  118419. newpart += 'x';
  118420. } else {
  118421. newpart += part[j];
  118422. }
  118423. }
  118424. // we test again with ASCII char only
  118425. if (!newpart.match(hostnamePartPattern)) {
  118426. var validParts = hostparts.slice(0, i);
  118427. var notHost = hostparts.slice(i + 1);
  118428. var bit = part.match(hostnamePartStart);
  118429. if (bit) {
  118430. validParts.push(bit[1]);
  118431. notHost.unshift(bit[2]);
  118432. }
  118433. if (notHost.length) {
  118434. rest = '/' + notHost.join('.') + rest;
  118435. }
  118436. this.hostname = validParts.join('.');
  118437. break;
  118438. }
  118439. }
  118440. }
  118441. }
  118442. if (this.hostname.length > hostnameMaxLen) {
  118443. this.hostname = '';
  118444. } else {
  118445. // hostnames are always lower case.
  118446. this.hostname = this.hostname.toLowerCase();
  118447. }
  118448. if (!ipv6Hostname) {
  118449. // IDNA Support: Returns a punycoded representation of "domain".
  118450. // It only converts parts of the domain name that
  118451. // have non-ASCII characters, i.e. it doesn't matter if
  118452. // you call it with a domain that already is ASCII-only.
  118453. this.hostname = punycode.toASCII(this.hostname);
  118454. }
  118455. var p = this.port ? ':' + this.port : '';
  118456. var h = this.hostname || '';
  118457. this.host = h + p;
  118458. this.href += this.host;
  118459. // strip [ and ] from the hostname
  118460. // the host field still retains them, though
  118461. if (ipv6Hostname) {
  118462. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  118463. if (rest[0] !== '/') {
  118464. rest = '/' + rest;
  118465. }
  118466. }
  118467. }
  118468. // now rest is set to the post-host stuff.
  118469. // chop off any delim chars.
  118470. if (!unsafeProtocol[lowerProto]) {
  118471. // First, make 100% sure that any "autoEscape" chars get
  118472. // escaped, even if encodeURIComponent doesn't think they
  118473. // need to be.
  118474. for (var i = 0, l = autoEscape.length; i < l; i++) {
  118475. var ae = autoEscape[i];
  118476. if (rest.indexOf(ae) === -1)
  118477. continue;
  118478. var esc = encodeURIComponent(ae);
  118479. if (esc === ae) {
  118480. esc = escape(ae);
  118481. }
  118482. rest = rest.split(ae).join(esc);
  118483. }
  118484. }
  118485. // chop off from the tail first.
  118486. var hash = rest.indexOf('#');
  118487. if (hash !== -1) {
  118488. // got a fragment string.
  118489. this.hash = rest.substr(hash);
  118490. rest = rest.slice(0, hash);
  118491. }
  118492. var qm = rest.indexOf('?');
  118493. if (qm !== -1) {
  118494. this.search = rest.substr(qm);
  118495. this.query = rest.substr(qm + 1);
  118496. if (parseQueryString) {
  118497. this.query = querystring.parse(this.query);
  118498. }
  118499. rest = rest.slice(0, qm);
  118500. } else if (parseQueryString) {
  118501. // no query string, but parseQueryString still requested
  118502. this.search = '';
  118503. this.query = {};
  118504. }
  118505. if (rest) this.pathname = rest;
  118506. if (slashedProtocol[lowerProto] &&
  118507. this.hostname && !this.pathname) {
  118508. this.pathname = '/';
  118509. }
  118510. //to support http.request
  118511. if (this.pathname || this.search) {
  118512. var p = this.pathname || '';
  118513. var s = this.search || '';
  118514. this.path = p + s;
  118515. }
  118516. // finally, reconstruct the href based on what has been validated.
  118517. this.href = this.format();
  118518. return this;
  118519. };
  118520. // format a parsed object into a url string
  118521. function urlFormat(obj) {
  118522. // ensure it's an object, and not a string url.
  118523. // If it's an obj, this is a no-op.
  118524. // this way, you can call url_format() on strings
  118525. // to clean up potentially wonky urls.
  118526. if (util.isString(obj)) obj = urlParse(obj);
  118527. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  118528. return obj.format();
  118529. }
  118530. Url.prototype.format = function() {
  118531. var auth = this.auth || '';
  118532. if (auth) {
  118533. auth = encodeURIComponent(auth);
  118534. auth = auth.replace(/%3A/i, ':');
  118535. auth += '@';
  118536. }
  118537. var protocol = this.protocol || '',
  118538. pathname = this.pathname || '',
  118539. hash = this.hash || '',
  118540. host = false,
  118541. query = '';
  118542. if (this.host) {
  118543. host = auth + this.host;
  118544. } else if (this.hostname) {
  118545. host = auth + (this.hostname.indexOf(':') === -1 ?
  118546. this.hostname :
  118547. '[' + this.hostname + ']');
  118548. if (this.port) {
  118549. host += ':' + this.port;
  118550. }
  118551. }
  118552. if (this.query &&
  118553. util.isObject(this.query) &&
  118554. Object.keys(this.query).length) {
  118555. query = querystring.stringify(this.query);
  118556. }
  118557. var search = this.search || (query && ('?' + query)) || '';
  118558. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  118559. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  118560. // unless they had them to begin with.
  118561. if (this.slashes ||
  118562. (!protocol || slashedProtocol[protocol]) && host !== false) {
  118563. host = '//' + (host || '');
  118564. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  118565. } else if (!host) {
  118566. host = '';
  118567. }
  118568. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  118569. if (search && search.charAt(0) !== '?') search = '?' + search;
  118570. pathname = pathname.replace(/[?#]/g, function(match) {
  118571. return encodeURIComponent(match);
  118572. });
  118573. search = search.replace('#', '%23');
  118574. return protocol + host + pathname + search + hash;
  118575. };
  118576. function urlResolve(source, relative) {
  118577. return urlParse(source, false, true).resolve(relative);
  118578. }
  118579. Url.prototype.resolve = function(relative) {
  118580. return this.resolveObject(urlParse(relative, false, true)).format();
  118581. };
  118582. function urlResolveObject(source, relative) {
  118583. if (!source) return relative;
  118584. return urlParse(source, false, true).resolveObject(relative);
  118585. }
  118586. Url.prototype.resolveObject = function(relative) {
  118587. if (util.isString(relative)) {
  118588. var rel = new Url();
  118589. rel.parse(relative, false, true);
  118590. relative = rel;
  118591. }
  118592. var result = new Url();
  118593. var tkeys = Object.keys(this);
  118594. for (var tk = 0; tk < tkeys.length; tk++) {
  118595. var tkey = tkeys[tk];
  118596. result[tkey] = this[tkey];
  118597. }
  118598. // hash is always overridden, no matter what.
  118599. // even href="" will remove it.
  118600. result.hash = relative.hash;
  118601. // if the relative url is empty, then there's nothing left to do here.
  118602. if (relative.href === '') {
  118603. result.href = result.format();
  118604. return result;
  118605. }
  118606. // hrefs like //foo/bar always cut to the protocol.
  118607. if (relative.slashes && !relative.protocol) {
  118608. // take everything except the protocol from relative
  118609. var rkeys = Object.keys(relative);
  118610. for (var rk = 0; rk < rkeys.length; rk++) {
  118611. var rkey = rkeys[rk];
  118612. if (rkey !== 'protocol')
  118613. result[rkey] = relative[rkey];
  118614. }
  118615. //urlParse appends trailing / to urls like http://www.example.com
  118616. if (slashedProtocol[result.protocol] &&
  118617. result.hostname && !result.pathname) {
  118618. result.path = result.pathname = '/';
  118619. }
  118620. result.href = result.format();
  118621. return result;
  118622. }
  118623. if (relative.protocol && relative.protocol !== result.protocol) {
  118624. // if it's a known url protocol, then changing
  118625. // the protocol does weird things
  118626. // first, if it's not file:, then we MUST have a host,
  118627. // and if there was a path
  118628. // to begin with, then we MUST have a path.
  118629. // if it is file:, then the host is dropped,
  118630. // because that's known to be hostless.
  118631. // anything else is assumed to be absolute.
  118632. if (!slashedProtocol[relative.protocol]) {
  118633. var keys = Object.keys(relative);
  118634. for (var v = 0; v < keys.length; v++) {
  118635. var k = keys[v];
  118636. result[k] = relative[k];
  118637. }
  118638. result.href = result.format();
  118639. return result;
  118640. }
  118641. result.protocol = relative.protocol;
  118642. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  118643. var relPath = (relative.pathname || '').split('/');
  118644. while (relPath.length && !(relative.host = relPath.shift()));
  118645. if (!relative.host) relative.host = '';
  118646. if (!relative.hostname) relative.hostname = '';
  118647. if (relPath[0] !== '') relPath.unshift('');
  118648. if (relPath.length < 2) relPath.unshift('');
  118649. result.pathname = relPath.join('/');
  118650. } else {
  118651. result.pathname = relative.pathname;
  118652. }
  118653. result.search = relative.search;
  118654. result.query = relative.query;
  118655. result.host = relative.host || '';
  118656. result.auth = relative.auth;
  118657. result.hostname = relative.hostname || relative.host;
  118658. result.port = relative.port;
  118659. // to support http.request
  118660. if (result.pathname || result.search) {
  118661. var p = result.pathname || '';
  118662. var s = result.search || '';
  118663. result.path = p + s;
  118664. }
  118665. result.slashes = result.slashes || relative.slashes;
  118666. result.href = result.format();
  118667. return result;
  118668. }
  118669. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  118670. isRelAbs = (
  118671. relative.host ||
  118672. relative.pathname && relative.pathname.charAt(0) === '/'
  118673. ),
  118674. mustEndAbs = (isRelAbs || isSourceAbs ||
  118675. (result.host && relative.pathname)),
  118676. removeAllDots = mustEndAbs,
  118677. srcPath = result.pathname && result.pathname.split('/') || [],
  118678. relPath = relative.pathname && relative.pathname.split('/') || [],
  118679. psychotic = result.protocol && !slashedProtocol[result.protocol];
  118680. // if the url is a non-slashed url, then relative
  118681. // links like ../.. should be able
  118682. // to crawl up to the hostname, as well. This is strange.
  118683. // result.protocol has already been set by now.
  118684. // Later on, put the first path part into the host field.
  118685. if (psychotic) {
  118686. result.hostname = '';
  118687. result.port = null;
  118688. if (result.host) {
  118689. if (srcPath[0] === '') srcPath[0] = result.host;
  118690. else srcPath.unshift(result.host);
  118691. }
  118692. result.host = '';
  118693. if (relative.protocol) {
  118694. relative.hostname = null;
  118695. relative.port = null;
  118696. if (relative.host) {
  118697. if (relPath[0] === '') relPath[0] = relative.host;
  118698. else relPath.unshift(relative.host);
  118699. }
  118700. relative.host = null;
  118701. }
  118702. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  118703. }
  118704. if (isRelAbs) {
  118705. // it's absolute.
  118706. result.host = (relative.host || relative.host === '') ?
  118707. relative.host : result.host;
  118708. result.hostname = (relative.hostname || relative.hostname === '') ?
  118709. relative.hostname : result.hostname;
  118710. result.search = relative.search;
  118711. result.query = relative.query;
  118712. srcPath = relPath;
  118713. // fall through to the dot-handling below.
  118714. } else if (relPath.length) {
  118715. // it's relative
  118716. // throw away the existing file, and take the new path instead.
  118717. if (!srcPath) srcPath = [];
  118718. srcPath.pop();
  118719. srcPath = srcPath.concat(relPath);
  118720. result.search = relative.search;
  118721. result.query = relative.query;
  118722. } else if (!util.isNullOrUndefined(relative.search)) {
  118723. // just pull out the search.
  118724. // like href='?foo'.
  118725. // Put this after the other two cases because it simplifies the booleans
  118726. if (psychotic) {
  118727. result.hostname = result.host = srcPath.shift();
  118728. //occationaly the auth can get stuck only in host
  118729. //this especially happens in cases like
  118730. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  118731. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  118732. result.host.split('@') : false;
  118733. if (authInHost) {
  118734. result.auth = authInHost.shift();
  118735. result.host = result.hostname = authInHost.shift();
  118736. }
  118737. }
  118738. result.search = relative.search;
  118739. result.query = relative.query;
  118740. //to support http.request
  118741. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  118742. result.path = (result.pathname ? result.pathname : '') +
  118743. (result.search ? result.search : '');
  118744. }
  118745. result.href = result.format();
  118746. return result;
  118747. }
  118748. if (!srcPath.length) {
  118749. // no path at all. easy.
  118750. // we've already handled the other stuff above.
  118751. result.pathname = null;
  118752. //to support http.request
  118753. if (result.search) {
  118754. result.path = '/' + result.search;
  118755. } else {
  118756. result.path = null;
  118757. }
  118758. result.href = result.format();
  118759. return result;
  118760. }
  118761. // if a url ENDs in . or .., then it must get a trailing slash.
  118762. // however, if it ends in anything else non-slashy,
  118763. // then it must NOT get a trailing slash.
  118764. var last = srcPath.slice(-1)[0];
  118765. var hasTrailingSlash = (
  118766. (result.host || relative.host || srcPath.length > 1) &&
  118767. (last === '.' || last === '..') || last === '');
  118768. // strip single dots, resolve double dots to parent dir
  118769. // if the path tries to go above the root, `up` ends up > 0
  118770. var up = 0;
  118771. for (var i = srcPath.length; i >= 0; i--) {
  118772. last = srcPath[i];
  118773. if (last === '.') {
  118774. srcPath.splice(i, 1);
  118775. } else if (last === '..') {
  118776. srcPath.splice(i, 1);
  118777. up++;
  118778. } else if (up) {
  118779. srcPath.splice(i, 1);
  118780. up--;
  118781. }
  118782. }
  118783. // if the path is allowed to go above the root, restore leading ..s
  118784. if (!mustEndAbs && !removeAllDots) {
  118785. for (; up--; up) {
  118786. srcPath.unshift('..');
  118787. }
  118788. }
  118789. if (mustEndAbs && srcPath[0] !== '' &&
  118790. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  118791. srcPath.unshift('');
  118792. }
  118793. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  118794. srcPath.push('');
  118795. }
  118796. var isAbsolute = srcPath[0] === '' ||
  118797. (srcPath[0] && srcPath[0].charAt(0) === '/');
  118798. // put the host back
  118799. if (psychotic) {
  118800. result.hostname = result.host = isAbsolute ? '' :
  118801. srcPath.length ? srcPath.shift() : '';
  118802. //occationaly the auth can get stuck only in host
  118803. //this especially happens in cases like
  118804. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  118805. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  118806. result.host.split('@') : false;
  118807. if (authInHost) {
  118808. result.auth = authInHost.shift();
  118809. result.host = result.hostname = authInHost.shift();
  118810. }
  118811. }
  118812. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  118813. if (mustEndAbs && !isAbsolute) {
  118814. srcPath.unshift('');
  118815. }
  118816. if (!srcPath.length) {
  118817. result.pathname = null;
  118818. result.path = null;
  118819. } else {
  118820. result.pathname = srcPath.join('/');
  118821. }
  118822. //to support request.http
  118823. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  118824. result.path = (result.pathname ? result.pathname : '') +
  118825. (result.search ? result.search : '');
  118826. }
  118827. result.auth = relative.auth || result.auth;
  118828. result.slashes = result.slashes || relative.slashes;
  118829. result.href = result.format();
  118830. return result;
  118831. };
  118832. Url.prototype.parseHost = function() {
  118833. var host = this.host;
  118834. var port = portPattern.exec(host);
  118835. if (port) {
  118836. port = port[0];
  118837. if (port !== ':') {
  118838. this.port = port.substr(1);
  118839. }
  118840. host = host.substr(0, host.length - port.length);
  118841. }
  118842. if (host) this.hostname = host;
  118843. };
  118844. },{"./util":654,"punycode":535,"querystring":543}],654:[function(require,module,exports){
  118845. 'use strict';
  118846. module.exports = {
  118847. isString: function(arg) {
  118848. return typeof(arg) === 'string';
  118849. },
  118850. isObject: function(arg) {
  118851. return typeof(arg) === 'object' && arg !== null;
  118852. },
  118853. isNull: function(arg) {
  118854. return arg === null;
  118855. },
  118856. isNullOrUndefined: function(arg) {
  118857. return arg == null;
  118858. }
  118859. };
  118860. },{}],655:[function(require,module,exports){
  118861. (function (global){(function (){
  118862. /**
  118863. * Module exports.
  118864. */
  118865. module.exports = deprecate;
  118866. /**
  118867. * Mark that a method should not be used.
  118868. * Returns a modified function which warns once by default.
  118869. *
  118870. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  118871. *
  118872. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  118873. * will throw an Error when invoked.
  118874. *
  118875. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  118876. * will invoke `console.trace()` instead of `console.error()`.
  118877. *
  118878. * @param {Function} fn - the function to deprecate
  118879. * @param {String} msg - the string to print to the console when `fn` is invoked
  118880. * @returns {Function} a new "deprecated" version of `fn`
  118881. * @api public
  118882. */
  118883. function deprecate (fn, msg) {
  118884. if (config('noDeprecation')) {
  118885. return fn;
  118886. }
  118887. var warned = false;
  118888. function deprecated() {
  118889. if (!warned) {
  118890. if (config('throwDeprecation')) {
  118891. throw new Error(msg);
  118892. } else if (config('traceDeprecation')) {
  118893. console.trace(msg);
  118894. } else {
  118895. console.warn(msg);
  118896. }
  118897. warned = true;
  118898. }
  118899. return fn.apply(this, arguments);
  118900. }
  118901. return deprecated;
  118902. }
  118903. /**
  118904. * Checks `localStorage` for boolean values for the given `name`.
  118905. *
  118906. * @param {String} name
  118907. * @returns {Boolean}
  118908. * @api private
  118909. */
  118910. function config (name) {
  118911. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  118912. try {
  118913. if (!global.localStorage) return false;
  118914. } catch (_) {
  118915. return false;
  118916. }
  118917. var val = global.localStorage[name];
  118918. if (null == val) return false;
  118919. return String(val).toLowerCase() === 'true';
  118920. }
  118921. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  118922. },{}],656:[function(require,module,exports){
  118923. arguments[4][107][0].apply(exports,arguments)
  118924. },{"dup":107}],657:[function(require,module,exports){
  118925. // Currently in sync with Node.js lib/internal/util/types.js
  118926. // https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9
  118927. 'use strict';
  118928. var isArgumentsObject = require('is-arguments');
  118929. var isGeneratorFunction = require('is-generator-function');
  118930. var whichTypedArray = require('which-typed-array');
  118931. var isTypedArray = require('is-typed-array');
  118932. function uncurryThis(f) {
  118933. return f.call.bind(f);
  118934. }
  118935. var BigIntSupported = typeof BigInt !== 'undefined';
  118936. var SymbolSupported = typeof Symbol !== 'undefined';
  118937. var ObjectToString = uncurryThis(Object.prototype.toString);
  118938. var numberValue = uncurryThis(Number.prototype.valueOf);
  118939. var stringValue = uncurryThis(String.prototype.valueOf);
  118940. var booleanValue = uncurryThis(Boolean.prototype.valueOf);
  118941. if (BigIntSupported) {
  118942. var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
  118943. }
  118944. if (SymbolSupported) {
  118945. var symbolValue = uncurryThis(Symbol.prototype.valueOf);
  118946. }
  118947. function checkBoxedPrimitive(value, prototypeValueOf) {
  118948. if (typeof value !== 'object') {
  118949. return false;
  118950. }
  118951. try {
  118952. prototypeValueOf(value);
  118953. return true;
  118954. } catch(e) {
  118955. return false;
  118956. }
  118957. }
  118958. exports.isArgumentsObject = isArgumentsObject;
  118959. exports.isGeneratorFunction = isGeneratorFunction;
  118960. exports.isTypedArray = isTypedArray;
  118961. // Taken from here and modified for better browser support
  118962. // https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
  118963. function isPromise(input) {
  118964. return (
  118965. (
  118966. typeof Promise !== 'undefined' &&
  118967. input instanceof Promise
  118968. ) ||
  118969. (
  118970. input !== null &&
  118971. typeof input === 'object' &&
  118972. typeof input.then === 'function' &&
  118973. typeof input.catch === 'function'
  118974. )
  118975. );
  118976. }
  118977. exports.isPromise = isPromise;
  118978. function isArrayBufferView(value) {
  118979. if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
  118980. return ArrayBuffer.isView(value);
  118981. }
  118982. return (
  118983. isTypedArray(value) ||
  118984. isDataView(value)
  118985. );
  118986. }
  118987. exports.isArrayBufferView = isArrayBufferView;
  118988. function isUint8Array(value) {
  118989. return whichTypedArray(value) === 'Uint8Array';
  118990. }
  118991. exports.isUint8Array = isUint8Array;
  118992. function isUint8ClampedArray(value) {
  118993. return whichTypedArray(value) === 'Uint8ClampedArray';
  118994. }
  118995. exports.isUint8ClampedArray = isUint8ClampedArray;
  118996. function isUint16Array(value) {
  118997. return whichTypedArray(value) === 'Uint16Array';
  118998. }
  118999. exports.isUint16Array = isUint16Array;
  119000. function isUint32Array(value) {
  119001. return whichTypedArray(value) === 'Uint32Array';
  119002. }
  119003. exports.isUint32Array = isUint32Array;
  119004. function isInt8Array(value) {
  119005. return whichTypedArray(value) === 'Int8Array';
  119006. }
  119007. exports.isInt8Array = isInt8Array;
  119008. function isInt16Array(value) {
  119009. return whichTypedArray(value) === 'Int16Array';
  119010. }
  119011. exports.isInt16Array = isInt16Array;
  119012. function isInt32Array(value) {
  119013. return whichTypedArray(value) === 'Int32Array';
  119014. }
  119015. exports.isInt32Array = isInt32Array;
  119016. function isFloat32Array(value) {
  119017. return whichTypedArray(value) === 'Float32Array';
  119018. }
  119019. exports.isFloat32Array = isFloat32Array;
  119020. function isFloat64Array(value) {
  119021. return whichTypedArray(value) === 'Float64Array';
  119022. }
  119023. exports.isFloat64Array = isFloat64Array;
  119024. function isBigInt64Array(value) {
  119025. return whichTypedArray(value) === 'BigInt64Array';
  119026. }
  119027. exports.isBigInt64Array = isBigInt64Array;
  119028. function isBigUint64Array(value) {
  119029. return whichTypedArray(value) === 'BigUint64Array';
  119030. }
  119031. exports.isBigUint64Array = isBigUint64Array;
  119032. function isMapToString(value) {
  119033. return ObjectToString(value) === '[object Map]';
  119034. }
  119035. isMapToString.working = (
  119036. typeof Map !== 'undefined' &&
  119037. isMapToString(new Map())
  119038. );
  119039. function isMap(value) {
  119040. if (typeof Map === 'undefined') {
  119041. return false;
  119042. }
  119043. return isMapToString.working
  119044. ? isMapToString(value)
  119045. : value instanceof Map;
  119046. }
  119047. exports.isMap = isMap;
  119048. function isSetToString(value) {
  119049. return ObjectToString(value) === '[object Set]';
  119050. }
  119051. isSetToString.working = (
  119052. typeof Set !== 'undefined' &&
  119053. isSetToString(new Set())
  119054. );
  119055. function isSet(value) {
  119056. if (typeof Set === 'undefined') {
  119057. return false;
  119058. }
  119059. return isSetToString.working
  119060. ? isSetToString(value)
  119061. : value instanceof Set;
  119062. }
  119063. exports.isSet = isSet;
  119064. function isWeakMapToString(value) {
  119065. return ObjectToString(value) === '[object WeakMap]';
  119066. }
  119067. isWeakMapToString.working = (
  119068. typeof WeakMap !== 'undefined' &&
  119069. isWeakMapToString(new WeakMap())
  119070. );
  119071. function isWeakMap(value) {
  119072. if (typeof WeakMap === 'undefined') {
  119073. return false;
  119074. }
  119075. return isWeakMapToString.working
  119076. ? isWeakMapToString(value)
  119077. : value instanceof WeakMap;
  119078. }
  119079. exports.isWeakMap = isWeakMap;
  119080. function isWeakSetToString(value) {
  119081. return ObjectToString(value) === '[object WeakSet]';
  119082. }
  119083. isWeakSetToString.working = (
  119084. typeof WeakSet !== 'undefined' &&
  119085. isWeakSetToString(new WeakSet())
  119086. );
  119087. function isWeakSet(value) {
  119088. return isWeakSetToString(value);
  119089. }
  119090. exports.isWeakSet = isWeakSet;
  119091. function isArrayBufferToString(value) {
  119092. return ObjectToString(value) === '[object ArrayBuffer]';
  119093. }
  119094. isArrayBufferToString.working = (
  119095. typeof ArrayBuffer !== 'undefined' &&
  119096. isArrayBufferToString(new ArrayBuffer())
  119097. );
  119098. function isArrayBuffer(value) {
  119099. if (typeof ArrayBuffer === 'undefined') {
  119100. return false;
  119101. }
  119102. return isArrayBufferToString.working
  119103. ? isArrayBufferToString(value)
  119104. : value instanceof ArrayBuffer;
  119105. }
  119106. exports.isArrayBuffer = isArrayBuffer;
  119107. function isDataViewToString(value) {
  119108. return ObjectToString(value) === '[object DataView]';
  119109. }
  119110. isDataViewToString.working = (
  119111. typeof ArrayBuffer !== 'undefined' &&
  119112. typeof DataView !== 'undefined' &&
  119113. isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
  119114. );
  119115. function isDataView(value) {
  119116. if (typeof DataView === 'undefined') {
  119117. return false;
  119118. }
  119119. return isDataViewToString.working
  119120. ? isDataViewToString(value)
  119121. : value instanceof DataView;
  119122. }
  119123. exports.isDataView = isDataView;
  119124. function isSharedArrayBufferToString(value) {
  119125. return ObjectToString(value) === '[object SharedArrayBuffer]';
  119126. }
  119127. isSharedArrayBufferToString.working = (
  119128. typeof SharedArrayBuffer !== 'undefined' &&
  119129. isSharedArrayBufferToString(new SharedArrayBuffer())
  119130. );
  119131. function isSharedArrayBuffer(value) {
  119132. if (typeof SharedArrayBuffer === 'undefined') {
  119133. return false;
  119134. }
  119135. return isSharedArrayBufferToString.working
  119136. ? isSharedArrayBufferToString(value)
  119137. : value instanceof SharedArrayBuffer;
  119138. }
  119139. exports.isSharedArrayBuffer = isSharedArrayBuffer;
  119140. function isAsyncFunction(value) {
  119141. return ObjectToString(value) === '[object AsyncFunction]';
  119142. }
  119143. exports.isAsyncFunction = isAsyncFunction;
  119144. function isMapIterator(value) {
  119145. return ObjectToString(value) === '[object Map Iterator]';
  119146. }
  119147. exports.isMapIterator = isMapIterator;
  119148. function isSetIterator(value) {
  119149. return ObjectToString(value) === '[object Set Iterator]';
  119150. }
  119151. exports.isSetIterator = isSetIterator;
  119152. function isGeneratorObject(value) {
  119153. return ObjectToString(value) === '[object Generator]';
  119154. }
  119155. exports.isGeneratorObject = isGeneratorObject;
  119156. function isWebAssemblyCompiledModule(value) {
  119157. return ObjectToString(value) === '[object WebAssembly.Module]';
  119158. }
  119159. exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;
  119160. function isNumberObject(value) {
  119161. return checkBoxedPrimitive(value, numberValue);
  119162. }
  119163. exports.isNumberObject = isNumberObject;
  119164. function isStringObject(value) {
  119165. return checkBoxedPrimitive(value, stringValue);
  119166. }
  119167. exports.isStringObject = isStringObject;
  119168. function isBooleanObject(value) {
  119169. return checkBoxedPrimitive(value, booleanValue);
  119170. }
  119171. exports.isBooleanObject = isBooleanObject;
  119172. function isBigIntObject(value) {
  119173. return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
  119174. }
  119175. exports.isBigIntObject = isBigIntObject;
  119176. function isSymbolObject(value) {
  119177. return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
  119178. }
  119179. exports.isSymbolObject = isSymbolObject;
  119180. function isBoxedPrimitive(value) {
  119181. return (
  119182. isNumberObject(value) ||
  119183. isStringObject(value) ||
  119184. isBooleanObject(value) ||
  119185. isBigIntObject(value) ||
  119186. isSymbolObject(value)
  119187. );
  119188. }
  119189. exports.isBoxedPrimitive = isBoxedPrimitive;
  119190. function isAnyArrayBuffer(value) {
  119191. return typeof Uint8Array !== 'undefined' && (
  119192. isArrayBuffer(value) ||
  119193. isSharedArrayBuffer(value)
  119194. );
  119195. }
  119196. exports.isAnyArrayBuffer = isAnyArrayBuffer;
  119197. ['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {
  119198. Object.defineProperty(exports, method, {
  119199. enumerable: false,
  119200. value: function() {
  119201. throw new Error(method + ' is not supported in userland');
  119202. }
  119203. });
  119204. });
  119205. },{"is-arguments":321,"is-generator-function":323,"is-typed-array":324,"which-typed-array":665}],658:[function(require,module,exports){
  119206. (function (process){(function (){
  119207. // Copyright Joyent, Inc. and other Node contributors.
  119208. //
  119209. // Permission is hereby granted, free of charge, to any person obtaining a
  119210. // copy of this software and associated documentation files (the
  119211. // "Software"), to deal in the Software without restriction, including
  119212. // without limitation the rights to use, copy, modify, merge, publish,
  119213. // distribute, sublicense, and/or sell copies of the Software, and to permit
  119214. // persons to whom the Software is furnished to do so, subject to the
  119215. // following conditions:
  119216. //
  119217. // The above copyright notice and this permission notice shall be included
  119218. // in all copies or substantial portions of the Software.
  119219. //
  119220. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  119221. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  119222. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  119223. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  119224. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  119225. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  119226. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  119227. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
  119228. function getOwnPropertyDescriptors(obj) {
  119229. var keys = Object.keys(obj);
  119230. var descriptors = {};
  119231. for (var i = 0; i < keys.length; i++) {
  119232. descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
  119233. }
  119234. return descriptors;
  119235. };
  119236. var formatRegExp = /%[sdj%]/g;
  119237. exports.format = function(f) {
  119238. if (!isString(f)) {
  119239. var objects = [];
  119240. for (var i = 0; i < arguments.length; i++) {
  119241. objects.push(inspect(arguments[i]));
  119242. }
  119243. return objects.join(' ');
  119244. }
  119245. var i = 1;
  119246. var args = arguments;
  119247. var len = args.length;
  119248. var str = String(f).replace(formatRegExp, function(x) {
  119249. if (x === '%%') return '%';
  119250. if (i >= len) return x;
  119251. switch (x) {
  119252. case '%s': return String(args[i++]);
  119253. case '%d': return Number(args[i++]);
  119254. case '%j':
  119255. try {
  119256. return JSON.stringify(args[i++]);
  119257. } catch (_) {
  119258. return '[Circular]';
  119259. }
  119260. default:
  119261. return x;
  119262. }
  119263. });
  119264. for (var x = args[i]; i < len; x = args[++i]) {
  119265. if (isNull(x) || !isObject(x)) {
  119266. str += ' ' + x;
  119267. } else {
  119268. str += ' ' + inspect(x);
  119269. }
  119270. }
  119271. return str;
  119272. };
  119273. // Mark that a method should not be used.
  119274. // Returns a modified function which warns once by default.
  119275. // If --no-deprecation is set, then it is a no-op.
  119276. exports.deprecate = function(fn, msg) {
  119277. if (typeof process !== 'undefined' && process.noDeprecation === true) {
  119278. return fn;
  119279. }
  119280. // Allow for deprecating things in the process of starting up.
  119281. if (typeof process === 'undefined') {
  119282. return function() {
  119283. return exports.deprecate(fn, msg).apply(this, arguments);
  119284. };
  119285. }
  119286. var warned = false;
  119287. function deprecated() {
  119288. if (!warned) {
  119289. if (process.throwDeprecation) {
  119290. throw new Error(msg);
  119291. } else if (process.traceDeprecation) {
  119292. console.trace(msg);
  119293. } else {
  119294. console.error(msg);
  119295. }
  119296. warned = true;
  119297. }
  119298. return fn.apply(this, arguments);
  119299. }
  119300. return deprecated;
  119301. };
  119302. var debugs = {};
  119303. var debugEnvRegex = /^$/;
  119304. if (process.env.NODE_DEBUG) {
  119305. var debugEnv = process.env.NODE_DEBUG;
  119306. debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
  119307. .replace(/\*/g, '.*')
  119308. .replace(/,/g, '$|^')
  119309. .toUpperCase();
  119310. debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
  119311. }
  119312. exports.debuglog = function(set) {
  119313. set = set.toUpperCase();
  119314. if (!debugs[set]) {
  119315. if (debugEnvRegex.test(set)) {
  119316. var pid = process.pid;
  119317. debugs[set] = function() {
  119318. var msg = exports.format.apply(exports, arguments);
  119319. console.error('%s %d: %s', set, pid, msg);
  119320. };
  119321. } else {
  119322. debugs[set] = function() {};
  119323. }
  119324. }
  119325. return debugs[set];
  119326. };
  119327. /**
  119328. * Echos the value of a value. Trys to print the value out
  119329. * in the best way possible given the different types.
  119330. *
  119331. * @param {Object} obj The object to print out.
  119332. * @param {Object} opts Optional options object that alters the output.
  119333. */
  119334. /* legacy: obj, showHidden, depth, colors*/
  119335. function inspect(obj, opts) {
  119336. // default options
  119337. var ctx = {
  119338. seen: [],
  119339. stylize: stylizeNoColor
  119340. };
  119341. // legacy...
  119342. if (arguments.length >= 3) ctx.depth = arguments[2];
  119343. if (arguments.length >= 4) ctx.colors = arguments[3];
  119344. if (isBoolean(opts)) {
  119345. // legacy...
  119346. ctx.showHidden = opts;
  119347. } else if (opts) {
  119348. // got an "options" object
  119349. exports._extend(ctx, opts);
  119350. }
  119351. // set default options
  119352. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  119353. if (isUndefined(ctx.depth)) ctx.depth = 2;
  119354. if (isUndefined(ctx.colors)) ctx.colors = false;
  119355. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  119356. if (ctx.colors) ctx.stylize = stylizeWithColor;
  119357. return formatValue(ctx, obj, ctx.depth);
  119358. }
  119359. exports.inspect = inspect;
  119360. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  119361. inspect.colors = {
  119362. 'bold' : [1, 22],
  119363. 'italic' : [3, 23],
  119364. 'underline' : [4, 24],
  119365. 'inverse' : [7, 27],
  119366. 'white' : [37, 39],
  119367. 'grey' : [90, 39],
  119368. 'black' : [30, 39],
  119369. 'blue' : [34, 39],
  119370. 'cyan' : [36, 39],
  119371. 'green' : [32, 39],
  119372. 'magenta' : [35, 39],
  119373. 'red' : [31, 39],
  119374. 'yellow' : [33, 39]
  119375. };
  119376. // Don't use 'blue' not visible on cmd.exe
  119377. inspect.styles = {
  119378. 'special': 'cyan',
  119379. 'number': 'yellow',
  119380. 'boolean': 'yellow',
  119381. 'undefined': 'grey',
  119382. 'null': 'bold',
  119383. 'string': 'green',
  119384. 'date': 'magenta',
  119385. // "name": intentionally not styling
  119386. 'regexp': 'red'
  119387. };
  119388. function stylizeWithColor(str, styleType) {
  119389. var style = inspect.styles[styleType];
  119390. if (style) {
  119391. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  119392. '\u001b[' + inspect.colors[style][1] + 'm';
  119393. } else {
  119394. return str;
  119395. }
  119396. }
  119397. function stylizeNoColor(str, styleType) {
  119398. return str;
  119399. }
  119400. function arrayToHash(array) {
  119401. var hash = {};
  119402. array.forEach(function(val, idx) {
  119403. hash[val] = true;
  119404. });
  119405. return hash;
  119406. }
  119407. function formatValue(ctx, value, recurseTimes) {
  119408. // Provide a hook for user-specified inspect functions.
  119409. // Check that value is an object with an inspect function on it
  119410. if (ctx.customInspect &&
  119411. value &&
  119412. isFunction(value.inspect) &&
  119413. // Filter out the util module, it's inspect function is special
  119414. value.inspect !== exports.inspect &&
  119415. // Also filter out any prototype objects using the circular check.
  119416. !(value.constructor && value.constructor.prototype === value)) {
  119417. var ret = value.inspect(recurseTimes, ctx);
  119418. if (!isString(ret)) {
  119419. ret = formatValue(ctx, ret, recurseTimes);
  119420. }
  119421. return ret;
  119422. }
  119423. // Primitive types cannot have properties
  119424. var primitive = formatPrimitive(ctx, value);
  119425. if (primitive) {
  119426. return primitive;
  119427. }
  119428. // Look up the keys of the object.
  119429. var keys = Object.keys(value);
  119430. var visibleKeys = arrayToHash(keys);
  119431. if (ctx.showHidden) {
  119432. keys = Object.getOwnPropertyNames(value);
  119433. }
  119434. // IE doesn't make error fields non-enumerable
  119435. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  119436. if (isError(value)
  119437. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  119438. return formatError(value);
  119439. }
  119440. // Some type of object without properties can be shortcutted.
  119441. if (keys.length === 0) {
  119442. if (isFunction(value)) {
  119443. var name = value.name ? ': ' + value.name : '';
  119444. return ctx.stylize('[Function' + name + ']', 'special');
  119445. }
  119446. if (isRegExp(value)) {
  119447. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  119448. }
  119449. if (isDate(value)) {
  119450. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  119451. }
  119452. if (isError(value)) {
  119453. return formatError(value);
  119454. }
  119455. }
  119456. var base = '', array = false, braces = ['{', '}'];
  119457. // Make Array say that they are Array
  119458. if (isArray(value)) {
  119459. array = true;
  119460. braces = ['[', ']'];
  119461. }
  119462. // Make functions say that they are functions
  119463. if (isFunction(value)) {
  119464. var n = value.name ? ': ' + value.name : '';
  119465. base = ' [Function' + n + ']';
  119466. }
  119467. // Make RegExps say that they are RegExps
  119468. if (isRegExp(value)) {
  119469. base = ' ' + RegExp.prototype.toString.call(value);
  119470. }
  119471. // Make dates with properties first say the date
  119472. if (isDate(value)) {
  119473. base = ' ' + Date.prototype.toUTCString.call(value);
  119474. }
  119475. // Make error with message first say the error
  119476. if (isError(value)) {
  119477. base = ' ' + formatError(value);
  119478. }
  119479. if (keys.length === 0 && (!array || value.length == 0)) {
  119480. return braces[0] + base + braces[1];
  119481. }
  119482. if (recurseTimes < 0) {
  119483. if (isRegExp(value)) {
  119484. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  119485. } else {
  119486. return ctx.stylize('[Object]', 'special');
  119487. }
  119488. }
  119489. ctx.seen.push(value);
  119490. var output;
  119491. if (array) {
  119492. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  119493. } else {
  119494. output = keys.map(function(key) {
  119495. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  119496. });
  119497. }
  119498. ctx.seen.pop();
  119499. return reduceToSingleString(output, base, braces);
  119500. }
  119501. function formatPrimitive(ctx, value) {
  119502. if (isUndefined(value))
  119503. return ctx.stylize('undefined', 'undefined');
  119504. if (isString(value)) {
  119505. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  119506. .replace(/'/g, "\\'")
  119507. .replace(/\\"/g, '"') + '\'';
  119508. return ctx.stylize(simple, 'string');
  119509. }
  119510. if (isNumber(value))
  119511. return ctx.stylize('' + value, 'number');
  119512. if (isBoolean(value))
  119513. return ctx.stylize('' + value, 'boolean');
  119514. // For some reason typeof null is "object", so special case here.
  119515. if (isNull(value))
  119516. return ctx.stylize('null', 'null');
  119517. }
  119518. function formatError(value) {
  119519. return '[' + Error.prototype.toString.call(value) + ']';
  119520. }
  119521. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  119522. var output = [];
  119523. for (var i = 0, l = value.length; i < l; ++i) {
  119524. if (hasOwnProperty(value, String(i))) {
  119525. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  119526. String(i), true));
  119527. } else {
  119528. output.push('');
  119529. }
  119530. }
  119531. keys.forEach(function(key) {
  119532. if (!key.match(/^\d+$/)) {
  119533. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  119534. key, true));
  119535. }
  119536. });
  119537. return output;
  119538. }
  119539. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  119540. var name, str, desc;
  119541. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  119542. if (desc.get) {
  119543. if (desc.set) {
  119544. str = ctx.stylize('[Getter/Setter]', 'special');
  119545. } else {
  119546. str = ctx.stylize('[Getter]', 'special');
  119547. }
  119548. } else {
  119549. if (desc.set) {
  119550. str = ctx.stylize('[Setter]', 'special');
  119551. }
  119552. }
  119553. if (!hasOwnProperty(visibleKeys, key)) {
  119554. name = '[' + key + ']';
  119555. }
  119556. if (!str) {
  119557. if (ctx.seen.indexOf(desc.value) < 0) {
  119558. if (isNull(recurseTimes)) {
  119559. str = formatValue(ctx, desc.value, null);
  119560. } else {
  119561. str = formatValue(ctx, desc.value, recurseTimes - 1);
  119562. }
  119563. if (str.indexOf('\n') > -1) {
  119564. if (array) {
  119565. str = str.split('\n').map(function(line) {
  119566. return ' ' + line;
  119567. }).join('\n').substr(2);
  119568. } else {
  119569. str = '\n' + str.split('\n').map(function(line) {
  119570. return ' ' + line;
  119571. }).join('\n');
  119572. }
  119573. }
  119574. } else {
  119575. str = ctx.stylize('[Circular]', 'special');
  119576. }
  119577. }
  119578. if (isUndefined(name)) {
  119579. if (array && key.match(/^\d+$/)) {
  119580. return str;
  119581. }
  119582. name = JSON.stringify('' + key);
  119583. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  119584. name = name.substr(1, name.length - 2);
  119585. name = ctx.stylize(name, 'name');
  119586. } else {
  119587. name = name.replace(/'/g, "\\'")
  119588. .replace(/\\"/g, '"')
  119589. .replace(/(^"|"$)/g, "'");
  119590. name = ctx.stylize(name, 'string');
  119591. }
  119592. }
  119593. return name + ': ' + str;
  119594. }
  119595. function reduceToSingleString(output, base, braces) {
  119596. var numLinesEst = 0;
  119597. var length = output.reduce(function(prev, cur) {
  119598. numLinesEst++;
  119599. if (cur.indexOf('\n') >= 0) numLinesEst++;
  119600. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  119601. }, 0);
  119602. if (length > 60) {
  119603. return braces[0] +
  119604. (base === '' ? '' : base + '\n ') +
  119605. ' ' +
  119606. output.join(',\n ') +
  119607. ' ' +
  119608. braces[1];
  119609. }
  119610. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  119611. }
  119612. // NOTE: These type checking functions intentionally don't use `instanceof`
  119613. // because it is fragile and can be easily faked with `Object.create()`.
  119614. exports.types = require('./support/types');
  119615. function isArray(ar) {
  119616. return Array.isArray(ar);
  119617. }
  119618. exports.isArray = isArray;
  119619. function isBoolean(arg) {
  119620. return typeof arg === 'boolean';
  119621. }
  119622. exports.isBoolean = isBoolean;
  119623. function isNull(arg) {
  119624. return arg === null;
  119625. }
  119626. exports.isNull = isNull;
  119627. function isNullOrUndefined(arg) {
  119628. return arg == null;
  119629. }
  119630. exports.isNullOrUndefined = isNullOrUndefined;
  119631. function isNumber(arg) {
  119632. return typeof arg === 'number';
  119633. }
  119634. exports.isNumber = isNumber;
  119635. function isString(arg) {
  119636. return typeof arg === 'string';
  119637. }
  119638. exports.isString = isString;
  119639. function isSymbol(arg) {
  119640. return typeof arg === 'symbol';
  119641. }
  119642. exports.isSymbol = isSymbol;
  119643. function isUndefined(arg) {
  119644. return arg === void 0;
  119645. }
  119646. exports.isUndefined = isUndefined;
  119647. function isRegExp(re) {
  119648. return isObject(re) && objectToString(re) === '[object RegExp]';
  119649. }
  119650. exports.isRegExp = isRegExp;
  119651. exports.types.isRegExp = isRegExp;
  119652. function isObject(arg) {
  119653. return typeof arg === 'object' && arg !== null;
  119654. }
  119655. exports.isObject = isObject;
  119656. function isDate(d) {
  119657. return isObject(d) && objectToString(d) === '[object Date]';
  119658. }
  119659. exports.isDate = isDate;
  119660. exports.types.isDate = isDate;
  119661. function isError(e) {
  119662. return isObject(e) &&
  119663. (objectToString(e) === '[object Error]' || e instanceof Error);
  119664. }
  119665. exports.isError = isError;
  119666. exports.types.isNativeError = isError;
  119667. function isFunction(arg) {
  119668. return typeof arg === 'function';
  119669. }
  119670. exports.isFunction = isFunction;
  119671. function isPrimitive(arg) {
  119672. return arg === null ||
  119673. typeof arg === 'boolean' ||
  119674. typeof arg === 'number' ||
  119675. typeof arg === 'string' ||
  119676. typeof arg === 'symbol' || // ES6 symbol
  119677. typeof arg === 'undefined';
  119678. }
  119679. exports.isPrimitive = isPrimitive;
  119680. exports.isBuffer = require('./support/isBuffer');
  119681. function objectToString(o) {
  119682. return Object.prototype.toString.call(o);
  119683. }
  119684. function pad(n) {
  119685. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  119686. }
  119687. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  119688. 'Oct', 'Nov', 'Dec'];
  119689. // 26 Feb 16:19:34
  119690. function timestamp() {
  119691. var d = new Date();
  119692. var time = [pad(d.getHours()),
  119693. pad(d.getMinutes()),
  119694. pad(d.getSeconds())].join(':');
  119695. return [d.getDate(), months[d.getMonth()], time].join(' ');
  119696. }
  119697. // log is just a thin wrapper to console.log that prepends a timestamp
  119698. exports.log = function() {
  119699. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  119700. };
  119701. /**
  119702. * Inherit the prototype methods from one constructor into another.
  119703. *
  119704. * The Function.prototype.inherits from lang.js rewritten as a standalone
  119705. * function (not on Function.prototype). NOTE: If this file is to be loaded
  119706. * during bootstrapping this function needs to be rewritten using some native
  119707. * functions as prototype setup using normal JavaScript does not work as
  119708. * expected during bootstrapping (see mirror.js in r114903).
  119709. *
  119710. * @param {function} ctor Constructor function which needs to inherit the
  119711. * prototype.
  119712. * @param {function} superCtor Constructor function to inherit prototype from.
  119713. */
  119714. exports.inherits = require('inherits');
  119715. exports._extend = function(origin, add) {
  119716. // Don't do anything if add isn't an object
  119717. if (!add || !isObject(add)) return origin;
  119718. var keys = Object.keys(add);
  119719. var i = keys.length;
  119720. while (i--) {
  119721. origin[keys[i]] = add[keys[i]];
  119722. }
  119723. return origin;
  119724. };
  119725. function hasOwnProperty(obj, prop) {
  119726. return Object.prototype.hasOwnProperty.call(obj, prop);
  119727. }
  119728. var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
  119729. exports.promisify = function promisify(original) {
  119730. if (typeof original !== 'function')
  119731. throw new TypeError('The "original" argument must be of type Function');
  119732. if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
  119733. var fn = original[kCustomPromisifiedSymbol];
  119734. if (typeof fn !== 'function') {
  119735. throw new TypeError('The "util.promisify.custom" argument must be of type Function');
  119736. }
  119737. Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  119738. value: fn, enumerable: false, writable: false, configurable: true
  119739. });
  119740. return fn;
  119741. }
  119742. function fn() {
  119743. var promiseResolve, promiseReject;
  119744. var promise = new Promise(function (resolve, reject) {
  119745. promiseResolve = resolve;
  119746. promiseReject = reject;
  119747. });
  119748. var args = [];
  119749. for (var i = 0; i < arguments.length; i++) {
  119750. args.push(arguments[i]);
  119751. }
  119752. args.push(function (err, value) {
  119753. if (err) {
  119754. promiseReject(err);
  119755. } else {
  119756. promiseResolve(value);
  119757. }
  119758. });
  119759. try {
  119760. original.apply(this, args);
  119761. } catch (err) {
  119762. promiseReject(err);
  119763. }
  119764. return promise;
  119765. }
  119766. Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
  119767. if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  119768. value: fn, enumerable: false, writable: false, configurable: true
  119769. });
  119770. return Object.defineProperties(
  119771. fn,
  119772. getOwnPropertyDescriptors(original)
  119773. );
  119774. }
  119775. exports.promisify.custom = kCustomPromisifiedSymbol
  119776. function callbackifyOnRejected(reason, cb) {
  119777. // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
  119778. // Because `null` is a special error value in callbacks which means "no error
  119779. // occurred", we error-wrap so the callback consumer can distinguish between
  119780. // "the promise rejected with null" or "the promise fulfilled with undefined".
  119781. if (!reason) {
  119782. var newReason = new Error('Promise was rejected with a falsy value');
  119783. newReason.reason = reason;
  119784. reason = newReason;
  119785. }
  119786. return cb(reason);
  119787. }
  119788. function callbackify(original) {
  119789. if (typeof original !== 'function') {
  119790. throw new TypeError('The "original" argument must be of type Function');
  119791. }
  119792. // We DO NOT return the promise as it gives the user a false sense that
  119793. // the promise is actually somehow related to the callback's execution
  119794. // and that the callback throwing will reject the promise.
  119795. function callbackified() {
  119796. var args = [];
  119797. for (var i = 0; i < arguments.length; i++) {
  119798. args.push(arguments[i]);
  119799. }
  119800. var maybeCb = args.pop();
  119801. if (typeof maybeCb !== 'function') {
  119802. throw new TypeError('The last argument must be of type Function');
  119803. }
  119804. var self = this;
  119805. var cb = function() {
  119806. return maybeCb.apply(self, arguments);
  119807. };
  119808. // In true node style we process the callback on `nextTick` with all the
  119809. // implications (stack, `uncaughtException`, `async_hooks`)
  119810. original.apply(this, args)
  119811. .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },
  119812. function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });
  119813. }
  119814. Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  119815. Object.defineProperties(callbackified,
  119816. getOwnPropertyDescriptors(original));
  119817. return callbackified;
  119818. }
  119819. exports.callbackify = callbackify;
  119820. }).call(this)}).call(this,require('_process'))
  119821. },{"./support/isBuffer":656,"./support/types":657,"_process":525,"inherits":320}],659:[function(require,module,exports){
  119822. var v1 = require('./v1');
  119823. var v4 = require('./v4');
  119824. var uuid = v4;
  119825. uuid.v1 = v1;
  119826. uuid.v4 = v4;
  119827. module.exports = uuid;
  119828. },{"./v1":662,"./v4":663}],660:[function(require,module,exports){
  119829. /**
  119830. * Convert array of 16 byte values to UUID string format of the form:
  119831. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  119832. */
  119833. var byteToHex = [];
  119834. for (var i = 0; i < 256; ++i) {
  119835. byteToHex[i] = (i + 0x100).toString(16).substr(1);
  119836. }
  119837. function bytesToUuid(buf, offset) {
  119838. var i = offset || 0;
  119839. var bth = byteToHex;
  119840. // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  119841. return ([
  119842. bth[buf[i++]], bth[buf[i++]],
  119843. bth[buf[i++]], bth[buf[i++]], '-',
  119844. bth[buf[i++]], bth[buf[i++]], '-',
  119845. bth[buf[i++]], bth[buf[i++]], '-',
  119846. bth[buf[i++]], bth[buf[i++]], '-',
  119847. bth[buf[i++]], bth[buf[i++]],
  119848. bth[buf[i++]], bth[buf[i++]],
  119849. bth[buf[i++]], bth[buf[i++]]
  119850. ]).join('');
  119851. }
  119852. module.exports = bytesToUuid;
  119853. },{}],661:[function(require,module,exports){
  119854. // Unique ID creation requires a high quality random # generator. In the
  119855. // browser this is a little complicated due to unknown quality of Math.random()
  119856. // and inconsistent support for the `crypto` API. We do the best we can via
  119857. // feature-detection
  119858. // getRandomValues needs to be invoked in a context where "this" is a Crypto
  119859. // implementation. Also, find the complete implementation of crypto on IE11.
  119860. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
  119861. (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
  119862. if (getRandomValues) {
  119863. // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  119864. var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
  119865. module.exports = function whatwgRNG() {
  119866. getRandomValues(rnds8);
  119867. return rnds8;
  119868. };
  119869. } else {
  119870. // Math.random()-based (RNG)
  119871. //
  119872. // If all else fails, use Math.random(). It's fast, but is of unspecified
  119873. // quality.
  119874. var rnds = new Array(16);
  119875. module.exports = function mathRNG() {
  119876. for (var i = 0, r; i < 16; i++) {
  119877. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  119878. rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  119879. }
  119880. return rnds;
  119881. };
  119882. }
  119883. },{}],662:[function(require,module,exports){
  119884. var rng = require('./lib/rng');
  119885. var bytesToUuid = require('./lib/bytesToUuid');
  119886. // **`v1()` - Generate time-based UUID**
  119887. //
  119888. // Inspired by https://github.com/LiosK/UUID.js
  119889. // and http://docs.python.org/library/uuid.html
  119890. var _nodeId;
  119891. var _clockseq;
  119892. // Previous uuid creation time
  119893. var _lastMSecs = 0;
  119894. var _lastNSecs = 0;
  119895. // See https://github.com/uuidjs/uuid for API details
  119896. function v1(options, buf, offset) {
  119897. var i = buf && offset || 0;
  119898. var b = buf || [];
  119899. options = options || {};
  119900. var node = options.node || _nodeId;
  119901. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
  119902. // node and clockseq need to be initialized to random values if they're not
  119903. // specified. We do this lazily to minimize issues related to insufficient
  119904. // system entropy. See #189
  119905. if (node == null || clockseq == null) {
  119906. var seedBytes = rng();
  119907. if (node == null) {
  119908. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  119909. node = _nodeId = [
  119910. seedBytes[0] | 0x01,
  119911. seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
  119912. ];
  119913. }
  119914. if (clockseq == null) {
  119915. // Per 4.2.2, randomize (14 bit) clockseq
  119916. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  119917. }
  119918. }
  119919. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  119920. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  119921. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  119922. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  119923. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
  119924. // Per 4.2.1.2, use count of uuid's generated during the current clock
  119925. // cycle to simulate higher resolution clock
  119926. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
  119927. // Time since last uuid creation (in msecs)
  119928. var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
  119929. // Per 4.2.1.2, Bump clockseq on clock regression
  119930. if (dt < 0 && options.clockseq === undefined) {
  119931. clockseq = clockseq + 1 & 0x3fff;
  119932. }
  119933. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  119934. // time interval
  119935. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  119936. nsecs = 0;
  119937. }
  119938. // Per 4.2.1.2 Throw error if too many uuids are requested
  119939. if (nsecs >= 10000) {
  119940. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  119941. }
  119942. _lastMSecs = msecs;
  119943. _lastNSecs = nsecs;
  119944. _clockseq = clockseq;
  119945. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  119946. msecs += 12219292800000;
  119947. // `time_low`
  119948. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  119949. b[i++] = tl >>> 24 & 0xff;
  119950. b[i++] = tl >>> 16 & 0xff;
  119951. b[i++] = tl >>> 8 & 0xff;
  119952. b[i++] = tl & 0xff;
  119953. // `time_mid`
  119954. var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  119955. b[i++] = tmh >>> 8 & 0xff;
  119956. b[i++] = tmh & 0xff;
  119957. // `time_high_and_version`
  119958. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  119959. b[i++] = tmh >>> 16 & 0xff;
  119960. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  119961. b[i++] = clockseq >>> 8 | 0x80;
  119962. // `clock_seq_low`
  119963. b[i++] = clockseq & 0xff;
  119964. // `node`
  119965. for (var n = 0; n < 6; ++n) {
  119966. b[i + n] = node[n];
  119967. }
  119968. return buf ? buf : bytesToUuid(b);
  119969. }
  119970. module.exports = v1;
  119971. },{"./lib/bytesToUuid":660,"./lib/rng":661}],663:[function(require,module,exports){
  119972. var rng = require('./lib/rng');
  119973. var bytesToUuid = require('./lib/bytesToUuid');
  119974. function v4(options, buf, offset) {
  119975. var i = buf && offset || 0;
  119976. if (typeof(options) == 'string') {
  119977. buf = options === 'binary' ? new Array(16) : null;
  119978. options = null;
  119979. }
  119980. options = options || {};
  119981. var rnds = options.random || (options.rng || rng)();
  119982. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  119983. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  119984. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  119985. // Copy bytes to buffer, if provided
  119986. if (buf) {
  119987. for (var ii = 0; ii < 16; ++ii) {
  119988. buf[i + ii] = rnds[ii];
  119989. }
  119990. }
  119991. return buf || bytesToUuid(rnds);
  119992. }
  119993. module.exports = v4;
  119994. },{"./lib/bytesToUuid":660,"./lib/rng":661}],664:[function(require,module,exports){
  119995. /*
  119996. * verror.js: richer JavaScript errors
  119997. */
  119998. var mod_assertplus = require('assert-plus');
  119999. var mod_util = require('util');
  120000. var mod_extsprintf = require('extsprintf');
  120001. var mod_isError = require('core-util-is').isError;
  120002. var sprintf = mod_extsprintf.sprintf;
  120003. /*
  120004. * Public interface
  120005. */
  120006. /* So you can 'var VError = require('verror')' */
  120007. module.exports = VError;
  120008. /* For compatibility */
  120009. VError.VError = VError;
  120010. /* Other exported classes */
  120011. VError.SError = SError;
  120012. VError.WError = WError;
  120013. VError.MultiError = MultiError;
  120014. /*
  120015. * Common function used to parse constructor arguments for VError, WError, and
  120016. * SError. Named arguments to this function:
  120017. *
  120018. * strict force strict interpretation of sprintf arguments, even
  120019. * if the options in "argv" don't say so
  120020. *
  120021. * argv error's constructor arguments, which are to be
  120022. * interpreted as described in README.md. For quick
  120023. * reference, "argv" has one of the following forms:
  120024. *
  120025. * [ sprintf_args... ] (argv[0] is a string)
  120026. * [ cause, sprintf_args... ] (argv[0] is an Error)
  120027. * [ options, sprintf_args... ] (argv[0] is an object)
  120028. *
  120029. * This function normalizes these forms, producing an object with the following
  120030. * properties:
  120031. *
  120032. * options equivalent to "options" in third form. This will never
  120033. * be a direct reference to what the caller passed in
  120034. * (i.e., it may be a shallow copy), so it can be freely
  120035. * modified.
  120036. *
  120037. * shortmessage result of sprintf(sprintf_args), taking options.strict
  120038. * into account as described in README.md.
  120039. */
  120040. function parseConstructorArguments(args)
  120041. {
  120042. var argv, options, sprintf_args, shortmessage, k;
  120043. mod_assertplus.object(args, 'args');
  120044. mod_assertplus.bool(args.strict, 'args.strict');
  120045. mod_assertplus.array(args.argv, 'args.argv');
  120046. argv = args.argv;
  120047. /*
  120048. * First, figure out which form of invocation we've been given.
  120049. */
  120050. if (argv.length === 0) {
  120051. options = {};
  120052. sprintf_args = [];
  120053. } else if (mod_isError(argv[0])) {
  120054. options = { 'cause': argv[0] };
  120055. sprintf_args = argv.slice(1);
  120056. } else if (typeof (argv[0]) === 'object') {
  120057. options = {};
  120058. for (k in argv[0]) {
  120059. options[k] = argv[0][k];
  120060. }
  120061. sprintf_args = argv.slice(1);
  120062. } else {
  120063. mod_assertplus.string(argv[0],
  120064. 'first argument to VError, SError, or WError ' +
  120065. 'constructor must be a string, object, or Error');
  120066. options = {};
  120067. sprintf_args = argv;
  120068. }
  120069. /*
  120070. * Now construct the error's message.
  120071. *
  120072. * extsprintf (which we invoke here with our caller's arguments in order
  120073. * to construct this Error's message) is strict in its interpretation of
  120074. * values to be processed by the "%s" specifier. The value passed to
  120075. * extsprintf must actually be a string or something convertible to a
  120076. * String using .toString(). Passing other values (notably "null" and
  120077. * "undefined") is considered a programmer error. The assumption is
  120078. * that if you actually want to print the string "null" or "undefined",
  120079. * then that's easy to do that when you're calling extsprintf; on the
  120080. * other hand, if you did NOT want that (i.e., there's actually a bug
  120081. * where the program assumes some variable is non-null and tries to
  120082. * print it, which might happen when constructing a packet or file in
  120083. * some specific format), then it's better to stop immediately than
  120084. * produce bogus output.
  120085. *
  120086. * However, sometimes the bug is only in the code calling VError, and a
  120087. * programmer might prefer to have the error message contain "null" or
  120088. * "undefined" rather than have the bug in the error path crash the
  120089. * program (making the first bug harder to identify). For that reason,
  120090. * by default VError converts "null" or "undefined" arguments to their
  120091. * string representations and passes those to extsprintf. Programmers
  120092. * desiring the strict behavior can use the SError class or pass the
  120093. * "strict" option to the VError constructor.
  120094. */
  120095. mod_assertplus.object(options);
  120096. if (!options.strict && !args.strict) {
  120097. sprintf_args = sprintf_args.map(function (a) {
  120098. return (a === null ? 'null' :
  120099. a === undefined ? 'undefined' : a);
  120100. });
  120101. }
  120102. if (sprintf_args.length === 0) {
  120103. shortmessage = '';
  120104. } else {
  120105. shortmessage = sprintf.apply(null, sprintf_args);
  120106. }
  120107. return ({
  120108. 'options': options,
  120109. 'shortmessage': shortmessage
  120110. });
  120111. }
  120112. /*
  120113. * See README.md for reference documentation.
  120114. */
  120115. function VError()
  120116. {
  120117. var args, obj, parsed, cause, ctor, message, k;
  120118. args = Array.prototype.slice.call(arguments, 0);
  120119. /*
  120120. * This is a regrettable pattern, but JavaScript's built-in Error class
  120121. * is defined to work this way, so we allow the constructor to be called
  120122. * without "new".
  120123. */
  120124. if (!(this instanceof VError)) {
  120125. obj = Object.create(VError.prototype);
  120126. VError.apply(obj, arguments);
  120127. return (obj);
  120128. }
  120129. /*
  120130. * For convenience and backwards compatibility, we support several
  120131. * different calling forms. Normalize them here.
  120132. */
  120133. parsed = parseConstructorArguments({
  120134. 'argv': args,
  120135. 'strict': false
  120136. });
  120137. /*
  120138. * If we've been given a name, apply it now.
  120139. */
  120140. if (parsed.options.name) {
  120141. mod_assertplus.string(parsed.options.name,
  120142. 'error\'s "name" must be a string');
  120143. this.name = parsed.options.name;
  120144. }
  120145. /*
  120146. * For debugging, we keep track of the original short message (attached
  120147. * this Error particularly) separately from the complete message (which
  120148. * includes the messages of our cause chain).
  120149. */
  120150. this.jse_shortmsg = parsed.shortmessage;
  120151. message = parsed.shortmessage;
  120152. /*
  120153. * If we've been given a cause, record a reference to it and update our
  120154. * message appropriately.
  120155. */
  120156. cause = parsed.options.cause;
  120157. if (cause) {
  120158. mod_assertplus.ok(mod_isError(cause), 'cause is not an Error');
  120159. this.jse_cause = cause;
  120160. if (!parsed.options.skipCauseMessage) {
  120161. message += ': ' + cause.message;
  120162. }
  120163. }
  120164. /*
  120165. * If we've been given an object with properties, shallow-copy that
  120166. * here. We don't want to use a deep copy in case there are non-plain
  120167. * objects here, but we don't want to use the original object in case
  120168. * the caller modifies it later.
  120169. */
  120170. this.jse_info = {};
  120171. if (parsed.options.info) {
  120172. for (k in parsed.options.info) {
  120173. this.jse_info[k] = parsed.options.info[k];
  120174. }
  120175. }
  120176. this.message = message;
  120177. Error.call(this, message);
  120178. if (Error.captureStackTrace) {
  120179. ctor = parsed.options.constructorOpt || this.constructor;
  120180. Error.captureStackTrace(this, ctor);
  120181. }
  120182. return (this);
  120183. }
  120184. mod_util.inherits(VError, Error);
  120185. VError.prototype.name = 'VError';
  120186. VError.prototype.toString = function ve_toString()
  120187. {
  120188. var str = (this.hasOwnProperty('name') && this.name ||
  120189. this.constructor.name || this.constructor.prototype.name);
  120190. if (this.message)
  120191. str += ': ' + this.message;
  120192. return (str);
  120193. };
  120194. /*
  120195. * This method is provided for compatibility. New callers should use
  120196. * VError.cause() instead. That method also uses the saner `null` return value
  120197. * when there is no cause.
  120198. */
  120199. VError.prototype.cause = function ve_cause()
  120200. {
  120201. var cause = VError.cause(this);
  120202. return (cause === null ? undefined : cause);
  120203. };
  120204. /*
  120205. * Static methods
  120206. *
  120207. * These class-level methods are provided so that callers can use them on
  120208. * instances of Errors that are not VErrors. New interfaces should be provided
  120209. * only using static methods to eliminate the class of programming mistake where
  120210. * people fail to check whether the Error object has the corresponding methods.
  120211. */
  120212. VError.cause = function (err)
  120213. {
  120214. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  120215. return (mod_isError(err.jse_cause) ? err.jse_cause : null);
  120216. };
  120217. VError.info = function (err)
  120218. {
  120219. var rv, cause, k;
  120220. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  120221. cause = VError.cause(err);
  120222. if (cause !== null) {
  120223. rv = VError.info(cause);
  120224. } else {
  120225. rv = {};
  120226. }
  120227. if (typeof (err.jse_info) == 'object' && err.jse_info !== null) {
  120228. for (k in err.jse_info) {
  120229. rv[k] = err.jse_info[k];
  120230. }
  120231. }
  120232. return (rv);
  120233. };
  120234. VError.findCauseByName = function (err, name)
  120235. {
  120236. var cause;
  120237. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  120238. mod_assertplus.string(name, 'name');
  120239. mod_assertplus.ok(name.length > 0, 'name cannot be empty');
  120240. for (cause = err; cause !== null; cause = VError.cause(cause)) {
  120241. mod_assertplus.ok(mod_isError(cause));
  120242. if (cause.name == name) {
  120243. return (cause);
  120244. }
  120245. }
  120246. return (null);
  120247. };
  120248. VError.hasCauseWithName = function (err, name)
  120249. {
  120250. return (VError.findCauseByName(err, name) !== null);
  120251. };
  120252. VError.fullStack = function (err)
  120253. {
  120254. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  120255. var cause = VError.cause(err);
  120256. if (cause) {
  120257. return (err.stack + '\ncaused by: ' + VError.fullStack(cause));
  120258. }
  120259. return (err.stack);
  120260. };
  120261. VError.errorFromList = function (errors)
  120262. {
  120263. mod_assertplus.arrayOfObject(errors, 'errors');
  120264. if (errors.length === 0) {
  120265. return (null);
  120266. }
  120267. errors.forEach(function (e) {
  120268. mod_assertplus.ok(mod_isError(e));
  120269. });
  120270. if (errors.length == 1) {
  120271. return (errors[0]);
  120272. }
  120273. return (new MultiError(errors));
  120274. };
  120275. VError.errorForEach = function (err, func)
  120276. {
  120277. mod_assertplus.ok(mod_isError(err), 'err must be an Error');
  120278. mod_assertplus.func(func, 'func');
  120279. if (err instanceof MultiError) {
  120280. err.errors().forEach(function iterError(e) { func(e); });
  120281. } else {
  120282. func(err);
  120283. }
  120284. };
  120285. /*
  120286. * SError is like VError, but stricter about types. You cannot pass "null" or
  120287. * "undefined" as string arguments to the formatter.
  120288. */
  120289. function SError()
  120290. {
  120291. var args, obj, parsed, options;
  120292. args = Array.prototype.slice.call(arguments, 0);
  120293. if (!(this instanceof SError)) {
  120294. obj = Object.create(SError.prototype);
  120295. SError.apply(obj, arguments);
  120296. return (obj);
  120297. }
  120298. parsed = parseConstructorArguments({
  120299. 'argv': args,
  120300. 'strict': true
  120301. });
  120302. options = parsed.options;
  120303. VError.call(this, options, '%s', parsed.shortmessage);
  120304. return (this);
  120305. }
  120306. /*
  120307. * We don't bother setting SError.prototype.name because once constructed,
  120308. * SErrors are just like VErrors.
  120309. */
  120310. mod_util.inherits(SError, VError);
  120311. /*
  120312. * Represents a collection of errors for the purpose of consumers that generally
  120313. * only deal with one error. Callers can extract the individual errors
  120314. * contained in this object, but may also just treat it as a normal single
  120315. * error, in which case a summary message will be printed.
  120316. */
  120317. function MultiError(errors)
  120318. {
  120319. mod_assertplus.array(errors, 'list of errors');
  120320. mod_assertplus.ok(errors.length > 0, 'must be at least one error');
  120321. this.ase_errors = errors;
  120322. VError.call(this, {
  120323. 'cause': errors[0]
  120324. }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');
  120325. }
  120326. mod_util.inherits(MultiError, VError);
  120327. MultiError.prototype.name = 'MultiError';
  120328. MultiError.prototype.errors = function me_errors()
  120329. {
  120330. return (this.ase_errors.slice(0));
  120331. };
  120332. /*
  120333. * See README.md for reference details.
  120334. */
  120335. function WError()
  120336. {
  120337. var args, obj, parsed, options;
  120338. args = Array.prototype.slice.call(arguments, 0);
  120339. if (!(this instanceof WError)) {
  120340. obj = Object.create(WError.prototype);
  120341. WError.apply(obj, args);
  120342. return (obj);
  120343. }
  120344. parsed = parseConstructorArguments({
  120345. 'argv': args,
  120346. 'strict': false
  120347. });
  120348. options = parsed.options;
  120349. options['skipCauseMessage'] = true;
  120350. VError.call(this, options, '%s', parsed.shortmessage);
  120351. return (this);
  120352. }
  120353. mod_util.inherits(WError, VError);
  120354. WError.prototype.name = 'WError';
  120355. WError.prototype.toString = function we_toString()
  120356. {
  120357. var str = (this.hasOwnProperty('name') && this.name ||
  120358. this.constructor.name || this.constructor.prototype.name);
  120359. if (this.message)
  120360. str += ': ' + this.message;
  120361. if (this.jse_cause && this.jse_cause.message)
  120362. str += '; caused by ' + this.jse_cause.toString();
  120363. return (str);
  120364. };
  120365. /*
  120366. * For purely historical reasons, WError's cause() function allows you to set
  120367. * the cause.
  120368. */
  120369. WError.prototype.cause = function we_cause(c)
  120370. {
  120371. if (mod_isError(c))
  120372. this.jse_cause = c;
  120373. return (this.jse_cause);
  120374. };
  120375. },{"assert-plus":104,"core-util-is":201,"extsprintf":250,"util":658}],665:[function(require,module,exports){
  120376. (function (global){(function (){
  120377. 'use strict';
  120378. var forEach = require('foreach');
  120379. var availableTypedArrays = require('available-typed-arrays');
  120380. var callBound = require('call-bind/callBound');
  120381. var $toString = callBound('Object.prototype.toString');
  120382. var hasSymbols = require('has-symbols')();
  120383. var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol';
  120384. var typedArrays = availableTypedArrays();
  120385. var $slice = callBound('String.prototype.slice');
  120386. var toStrTags = {};
  120387. var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');
  120388. var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
  120389. if (hasToStringTag && gOPD && getPrototypeOf) {
  120390. forEach(typedArrays, function (typedArray) {
  120391. if (typeof global[typedArray] === 'function') {
  120392. var arr = new global[typedArray]();
  120393. if (!(Symbol.toStringTag in arr)) {
  120394. throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.');
  120395. }
  120396. var proto = getPrototypeOf(arr);
  120397. var descriptor = gOPD(proto, Symbol.toStringTag);
  120398. if (!descriptor) {
  120399. var superProto = getPrototypeOf(proto);
  120400. descriptor = gOPD(superProto, Symbol.toStringTag);
  120401. }
  120402. toStrTags[typedArray] = descriptor.get;
  120403. }
  120404. });
  120405. }
  120406. var tryTypedArrays = function tryAllTypedArrays(value) {
  120407. var foundName = false;
  120408. forEach(toStrTags, function (getter, typedArray) {
  120409. if (!foundName) {
  120410. try {
  120411. var name = getter.call(value);
  120412. if (name === typedArray) {
  120413. foundName = name;
  120414. }
  120415. } catch (e) {}
  120416. }
  120417. });
  120418. return foundName;
  120419. };
  120420. var isTypedArray = require('is-typed-array');
  120421. module.exports = function whichTypedArray(value) {
  120422. if (!isTypedArray(value)) { return false; }
  120423. if (!hasToStringTag) { return $slice($toString(value), 8, -1); }
  120424. return tryTypedArrays(value);
  120425. };
  120426. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  120427. },{"available-typed-arrays":110,"call-bind/callBound":195,"es-abstract/helpers/getOwnPropertyDescriptor":246,"foreach":253,"has-symbols":280,"is-typed-array":324}],666:[function(require,module,exports){
  120428. // Generated by CoffeeScript 1.12.7
  120429. (function() {
  120430. "use strict";
  120431. exports.stripBOM = function(str) {
  120432. if (str[0] === '\uFEFF') {
  120433. return str.substring(1);
  120434. } else {
  120435. return str;
  120436. }
  120437. };
  120438. }).call(this);
  120439. },{}],667:[function(require,module,exports){
  120440. // Generated by CoffeeScript 1.12.7
  120441. (function() {
  120442. "use strict";
  120443. var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA,
  120444. hasProp = {}.hasOwnProperty;
  120445. builder = require('xmlbuilder');
  120446. defaults = require('./defaults').defaults;
  120447. requiresCDATA = function(entry) {
  120448. return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0);
  120449. };
  120450. wrapCDATA = function(entry) {
  120451. return "<![CDATA[" + (escapeCDATA(entry)) + "]]>";
  120452. };
  120453. escapeCDATA = function(entry) {
  120454. return entry.replace(']]>', ']]]]><![CDATA[>');
  120455. };
  120456. exports.Builder = (function() {
  120457. function Builder(opts) {
  120458. var key, ref, value;
  120459. this.options = {};
  120460. ref = defaults["0.2"];
  120461. for (key in ref) {
  120462. if (!hasProp.call(ref, key)) continue;
  120463. value = ref[key];
  120464. this.options[key] = value;
  120465. }
  120466. for (key in opts) {
  120467. if (!hasProp.call(opts, key)) continue;
  120468. value = opts[key];
  120469. this.options[key] = value;
  120470. }
  120471. }
  120472. Builder.prototype.buildObject = function(rootObj) {
  120473. var attrkey, charkey, render, rootElement, rootName;
  120474. attrkey = this.options.attrkey;
  120475. charkey = this.options.charkey;
  120476. if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) {
  120477. rootName = Object.keys(rootObj)[0];
  120478. rootObj = rootObj[rootName];
  120479. } else {
  120480. rootName = this.options.rootName;
  120481. }
  120482. render = (function(_this) {
  120483. return function(element, obj) {
  120484. var attr, child, entry, index, key, value;
  120485. if (typeof obj !== 'object') {
  120486. if (_this.options.cdata && requiresCDATA(obj)) {
  120487. element.raw(wrapCDATA(obj));
  120488. } else {
  120489. element.txt(obj);
  120490. }
  120491. } else if (Array.isArray(obj)) {
  120492. for (index in obj) {
  120493. if (!hasProp.call(obj, index)) continue;
  120494. child = obj[index];
  120495. for (key in child) {
  120496. entry = child[key];
  120497. element = render(element.ele(key), entry).up();
  120498. }
  120499. }
  120500. } else {
  120501. for (key in obj) {
  120502. if (!hasProp.call(obj, key)) continue;
  120503. child = obj[key];
  120504. if (key === attrkey) {
  120505. if (typeof child === "object") {
  120506. for (attr in child) {
  120507. value = child[attr];
  120508. element = element.att(attr, value);
  120509. }
  120510. }
  120511. } else if (key === charkey) {
  120512. if (_this.options.cdata && requiresCDATA(child)) {
  120513. element = element.raw(wrapCDATA(child));
  120514. } else {
  120515. element = element.txt(child);
  120516. }
  120517. } else if (Array.isArray(child)) {
  120518. for (index in child) {
  120519. if (!hasProp.call(child, index)) continue;
  120520. entry = child[index];
  120521. if (typeof entry === 'string') {
  120522. if (_this.options.cdata && requiresCDATA(entry)) {
  120523. element = element.ele(key).raw(wrapCDATA(entry)).up();
  120524. } else {
  120525. element = element.ele(key, entry).up();
  120526. }
  120527. } else {
  120528. element = render(element.ele(key), entry).up();
  120529. }
  120530. }
  120531. } else if (typeof child === "object") {
  120532. element = render(element.ele(key), child).up();
  120533. } else {
  120534. if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) {
  120535. element = element.ele(key).raw(wrapCDATA(child)).up();
  120536. } else {
  120537. if (child == null) {
  120538. child = '';
  120539. }
  120540. element = element.ele(key, child.toString()).up();
  120541. }
  120542. }
  120543. }
  120544. }
  120545. return element;
  120546. };
  120547. })(this);
  120548. rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, {
  120549. headless: this.options.headless,
  120550. allowSurrogateChars: this.options.allowSurrogateChars
  120551. });
  120552. return render(rootElement, rootObj).end(this.options.renderOpts);
  120553. };
  120554. return Builder;
  120555. })();
  120556. }).call(this);
  120557. },{"./defaults":668,"xmlbuilder":704}],668:[function(require,module,exports){
  120558. // Generated by CoffeeScript 1.12.7
  120559. (function() {
  120560. exports.defaults = {
  120561. "0.1": {
  120562. explicitCharkey: false,
  120563. trim: true,
  120564. normalize: true,
  120565. normalizeTags: false,
  120566. attrkey: "@",
  120567. charkey: "#",
  120568. explicitArray: false,
  120569. ignoreAttrs: false,
  120570. mergeAttrs: false,
  120571. explicitRoot: false,
  120572. validator: null,
  120573. xmlns: false,
  120574. explicitChildren: false,
  120575. childkey: '@@',
  120576. charsAsChildren: false,
  120577. includeWhiteChars: false,
  120578. async: false,
  120579. strict: true,
  120580. attrNameProcessors: null,
  120581. attrValueProcessors: null,
  120582. tagNameProcessors: null,
  120583. valueProcessors: null,
  120584. emptyTag: ''
  120585. },
  120586. "0.2": {
  120587. explicitCharkey: false,
  120588. trim: false,
  120589. normalize: false,
  120590. normalizeTags: false,
  120591. attrkey: "$",
  120592. charkey: "_",
  120593. explicitArray: true,
  120594. ignoreAttrs: false,
  120595. mergeAttrs: false,
  120596. explicitRoot: true,
  120597. validator: null,
  120598. xmlns: false,
  120599. explicitChildren: false,
  120600. preserveChildrenOrder: false,
  120601. childkey: '$$',
  120602. charsAsChildren: false,
  120603. includeWhiteChars: false,
  120604. async: false,
  120605. strict: true,
  120606. attrNameProcessors: null,
  120607. attrValueProcessors: null,
  120608. tagNameProcessors: null,
  120609. valueProcessors: null,
  120610. rootName: 'root',
  120611. xmldec: {
  120612. 'version': '1.0',
  120613. 'encoding': 'UTF-8',
  120614. 'standalone': true
  120615. },
  120616. doctype: null,
  120617. renderOpts: {
  120618. 'pretty': true,
  120619. 'indent': ' ',
  120620. 'newline': '\n'
  120621. },
  120622. headless: false,
  120623. chunkSize: 10000,
  120624. emptyTag: '',
  120625. cdata: false
  120626. }
  120627. };
  120628. }).call(this);
  120629. },{}],669:[function(require,module,exports){
  120630. // Generated by CoffeeScript 1.12.7
  120631. (function() {
  120632. "use strict";
  120633. var bom, defaults, events, isEmpty, processItem, processors, sax, setImmediate,
  120634. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  120635. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  120636. hasProp = {}.hasOwnProperty;
  120637. sax = require('sax');
  120638. events = require('events');
  120639. bom = require('./bom');
  120640. processors = require('./processors');
  120641. setImmediate = require('timers').setImmediate;
  120642. defaults = require('./defaults').defaults;
  120643. isEmpty = function(thing) {
  120644. return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0;
  120645. };
  120646. processItem = function(processors, item, key) {
  120647. var i, len, process;
  120648. for (i = 0, len = processors.length; i < len; i++) {
  120649. process = processors[i];
  120650. item = process(item, key);
  120651. }
  120652. return item;
  120653. };
  120654. exports.Parser = (function(superClass) {
  120655. extend(Parser, superClass);
  120656. function Parser(opts) {
  120657. this.parseStringPromise = bind(this.parseStringPromise, this);
  120658. this.parseString = bind(this.parseString, this);
  120659. this.reset = bind(this.reset, this);
  120660. this.assignOrPush = bind(this.assignOrPush, this);
  120661. this.processAsync = bind(this.processAsync, this);
  120662. var key, ref, value;
  120663. if (!(this instanceof exports.Parser)) {
  120664. return new exports.Parser(opts);
  120665. }
  120666. this.options = {};
  120667. ref = defaults["0.2"];
  120668. for (key in ref) {
  120669. if (!hasProp.call(ref, key)) continue;
  120670. value = ref[key];
  120671. this.options[key] = value;
  120672. }
  120673. for (key in opts) {
  120674. if (!hasProp.call(opts, key)) continue;
  120675. value = opts[key];
  120676. this.options[key] = value;
  120677. }
  120678. if (this.options.xmlns) {
  120679. this.options.xmlnskey = this.options.attrkey + "ns";
  120680. }
  120681. if (this.options.normalizeTags) {
  120682. if (!this.options.tagNameProcessors) {
  120683. this.options.tagNameProcessors = [];
  120684. }
  120685. this.options.tagNameProcessors.unshift(processors.normalize);
  120686. }
  120687. this.reset();
  120688. }
  120689. Parser.prototype.processAsync = function() {
  120690. var chunk, err;
  120691. try {
  120692. if (this.remaining.length <= this.options.chunkSize) {
  120693. chunk = this.remaining;
  120694. this.remaining = '';
  120695. this.saxParser = this.saxParser.write(chunk);
  120696. return this.saxParser.close();
  120697. } else {
  120698. chunk = this.remaining.substr(0, this.options.chunkSize);
  120699. this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length);
  120700. this.saxParser = this.saxParser.write(chunk);
  120701. return setImmediate(this.processAsync);
  120702. }
  120703. } catch (error1) {
  120704. err = error1;
  120705. if (!this.saxParser.errThrown) {
  120706. this.saxParser.errThrown = true;
  120707. return this.emit(err);
  120708. }
  120709. }
  120710. };
  120711. Parser.prototype.assignOrPush = function(obj, key, newValue) {
  120712. if (!(key in obj)) {
  120713. if (!this.options.explicitArray) {
  120714. return obj[key] = newValue;
  120715. } else {
  120716. return obj[key] = [newValue];
  120717. }
  120718. } else {
  120719. if (!(obj[key] instanceof Array)) {
  120720. obj[key] = [obj[key]];
  120721. }
  120722. return obj[key].push(newValue);
  120723. }
  120724. };
  120725. Parser.prototype.reset = function() {
  120726. var attrkey, charkey, ontext, stack;
  120727. this.removeAllListeners();
  120728. this.saxParser = sax.parser(this.options.strict, {
  120729. trim: false,
  120730. normalize: false,
  120731. xmlns: this.options.xmlns
  120732. });
  120733. this.saxParser.errThrown = false;
  120734. this.saxParser.onerror = (function(_this) {
  120735. return function(error) {
  120736. _this.saxParser.resume();
  120737. if (!_this.saxParser.errThrown) {
  120738. _this.saxParser.errThrown = true;
  120739. return _this.emit("error", error);
  120740. }
  120741. };
  120742. })(this);
  120743. this.saxParser.onend = (function(_this) {
  120744. return function() {
  120745. if (!_this.saxParser.ended) {
  120746. _this.saxParser.ended = true;
  120747. return _this.emit("end", _this.resultObject);
  120748. }
  120749. };
  120750. })(this);
  120751. this.saxParser.ended = false;
  120752. this.EXPLICIT_CHARKEY = this.options.explicitCharkey;
  120753. this.resultObject = null;
  120754. stack = [];
  120755. attrkey = this.options.attrkey;
  120756. charkey = this.options.charkey;
  120757. this.saxParser.onopentag = (function(_this) {
  120758. return function(node) {
  120759. var key, newValue, obj, processedKey, ref;
  120760. obj = {};
  120761. obj[charkey] = "";
  120762. if (!_this.options.ignoreAttrs) {
  120763. ref = node.attributes;
  120764. for (key in ref) {
  120765. if (!hasProp.call(ref, key)) continue;
  120766. if (!(attrkey in obj) && !_this.options.mergeAttrs) {
  120767. obj[attrkey] = {};
  120768. }
  120769. newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key];
  120770. processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key;
  120771. if (_this.options.mergeAttrs) {
  120772. _this.assignOrPush(obj, processedKey, newValue);
  120773. } else {
  120774. obj[attrkey][processedKey] = newValue;
  120775. }
  120776. }
  120777. }
  120778. obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name;
  120779. if (_this.options.xmlns) {
  120780. obj[_this.options.xmlnskey] = {
  120781. uri: node.uri,
  120782. local: node.local
  120783. };
  120784. }
  120785. return stack.push(obj);
  120786. };
  120787. })(this);
  120788. this.saxParser.onclosetag = (function(_this) {
  120789. return function() {
  120790. var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath;
  120791. obj = stack.pop();
  120792. nodeName = obj["#name"];
  120793. if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) {
  120794. delete obj["#name"];
  120795. }
  120796. if (obj.cdata === true) {
  120797. cdata = obj.cdata;
  120798. delete obj.cdata;
  120799. }
  120800. s = stack[stack.length - 1];
  120801. if (obj[charkey].match(/^\s*$/) && !cdata) {
  120802. emptyStr = obj[charkey];
  120803. delete obj[charkey];
  120804. } else {
  120805. if (_this.options.trim) {
  120806. obj[charkey] = obj[charkey].trim();
  120807. }
  120808. if (_this.options.normalize) {
  120809. obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim();
  120810. }
  120811. obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey];
  120812. if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) {
  120813. obj = obj[charkey];
  120814. }
  120815. }
  120816. if (isEmpty(obj)) {
  120817. obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr;
  120818. }
  120819. if (_this.options.validator != null) {
  120820. xpath = "/" + ((function() {
  120821. var i, len, results;
  120822. results = [];
  120823. for (i = 0, len = stack.length; i < len; i++) {
  120824. node = stack[i];
  120825. results.push(node["#name"]);
  120826. }
  120827. return results;
  120828. })()).concat(nodeName).join("/");
  120829. (function() {
  120830. var err;
  120831. try {
  120832. return obj = _this.options.validator(xpath, s && s[nodeName], obj);
  120833. } catch (error1) {
  120834. err = error1;
  120835. return _this.emit("error", err);
  120836. }
  120837. })();
  120838. }
  120839. if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') {
  120840. if (!_this.options.preserveChildrenOrder) {
  120841. node = {};
  120842. if (_this.options.attrkey in obj) {
  120843. node[_this.options.attrkey] = obj[_this.options.attrkey];
  120844. delete obj[_this.options.attrkey];
  120845. }
  120846. if (!_this.options.charsAsChildren && _this.options.charkey in obj) {
  120847. node[_this.options.charkey] = obj[_this.options.charkey];
  120848. delete obj[_this.options.charkey];
  120849. }
  120850. if (Object.getOwnPropertyNames(obj).length > 0) {
  120851. node[_this.options.childkey] = obj;
  120852. }
  120853. obj = node;
  120854. } else if (s) {
  120855. s[_this.options.childkey] = s[_this.options.childkey] || [];
  120856. objClone = {};
  120857. for (key in obj) {
  120858. if (!hasProp.call(obj, key)) continue;
  120859. objClone[key] = obj[key];
  120860. }
  120861. s[_this.options.childkey].push(objClone);
  120862. delete obj["#name"];
  120863. if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) {
  120864. obj = obj[charkey];
  120865. }
  120866. }
  120867. }
  120868. if (stack.length > 0) {
  120869. return _this.assignOrPush(s, nodeName, obj);
  120870. } else {
  120871. if (_this.options.explicitRoot) {
  120872. old = obj;
  120873. obj = {};
  120874. obj[nodeName] = old;
  120875. }
  120876. _this.resultObject = obj;
  120877. _this.saxParser.ended = true;
  120878. return _this.emit("end", _this.resultObject);
  120879. }
  120880. };
  120881. })(this);
  120882. ontext = (function(_this) {
  120883. return function(text) {
  120884. var charChild, s;
  120885. s = stack[stack.length - 1];
  120886. if (s) {
  120887. s[charkey] += text;
  120888. if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) {
  120889. s[_this.options.childkey] = s[_this.options.childkey] || [];
  120890. charChild = {
  120891. '#name': '__text__'
  120892. };
  120893. charChild[charkey] = text;
  120894. if (_this.options.normalize) {
  120895. charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim();
  120896. }
  120897. s[_this.options.childkey].push(charChild);
  120898. }
  120899. return s;
  120900. }
  120901. };
  120902. })(this);
  120903. this.saxParser.ontext = ontext;
  120904. return this.saxParser.oncdata = (function(_this) {
  120905. return function(text) {
  120906. var s;
  120907. s = ontext(text);
  120908. if (s) {
  120909. return s.cdata = true;
  120910. }
  120911. };
  120912. })(this);
  120913. };
  120914. Parser.prototype.parseString = function(str, cb) {
  120915. var err;
  120916. if ((cb != null) && typeof cb === "function") {
  120917. this.on("end", function(result) {
  120918. this.reset();
  120919. return cb(null, result);
  120920. });
  120921. this.on("error", function(err) {
  120922. this.reset();
  120923. return cb(err);
  120924. });
  120925. }
  120926. try {
  120927. str = str.toString();
  120928. if (str.trim() === '') {
  120929. this.emit("end", null);
  120930. return true;
  120931. }
  120932. str = bom.stripBOM(str);
  120933. if (this.options.async) {
  120934. this.remaining = str;
  120935. setImmediate(this.processAsync);
  120936. return this.saxParser;
  120937. }
  120938. return this.saxParser.write(str).close();
  120939. } catch (error1) {
  120940. err = error1;
  120941. if (!(this.saxParser.errThrown || this.saxParser.ended)) {
  120942. this.emit('error', err);
  120943. return this.saxParser.errThrown = true;
  120944. } else if (this.saxParser.ended) {
  120945. throw err;
  120946. }
  120947. }
  120948. };
  120949. Parser.prototype.parseStringPromise = function(str) {
  120950. return new Promise((function(_this) {
  120951. return function(resolve, reject) {
  120952. return _this.parseString(str, function(err, value) {
  120953. if (err) {
  120954. return reject(err);
  120955. } else {
  120956. return resolve(value);
  120957. }
  120958. });
  120959. };
  120960. })(this));
  120961. };
  120962. return Parser;
  120963. })(events);
  120964. exports.parseString = function(str, a, b) {
  120965. var cb, options, parser;
  120966. if (b != null) {
  120967. if (typeof b === 'function') {
  120968. cb = b;
  120969. }
  120970. if (typeof a === 'object') {
  120971. options = a;
  120972. }
  120973. } else {
  120974. if (typeof a === 'function') {
  120975. cb = a;
  120976. }
  120977. options = {};
  120978. }
  120979. parser = new exports.Parser(options);
  120980. return parser.parseString(str, cb);
  120981. };
  120982. exports.parseStringPromise = function(str, a) {
  120983. var options, parser;
  120984. if (typeof a === 'object') {
  120985. options = a;
  120986. }
  120987. parser = new exports.Parser(options);
  120988. return parser.parseStringPromise(str);
  120989. };
  120990. }).call(this);
  120991. },{"./bom":666,"./defaults":668,"./processors":670,"events":247,"sax":563,"timers":639}],670:[function(require,module,exports){
  120992. // Generated by CoffeeScript 1.12.7
  120993. (function() {
  120994. "use strict";
  120995. var prefixMatch;
  120996. prefixMatch = new RegExp(/(?!xmlns)^.*:/);
  120997. exports.normalize = function(str) {
  120998. return str.toLowerCase();
  120999. };
  121000. exports.firstCharLowerCase = function(str) {
  121001. return str.charAt(0).toLowerCase() + str.slice(1);
  121002. };
  121003. exports.stripPrefix = function(str) {
  121004. return str.replace(prefixMatch, '');
  121005. };
  121006. exports.parseNumbers = function(str) {
  121007. if (!isNaN(str)) {
  121008. str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str);
  121009. }
  121010. return str;
  121011. };
  121012. exports.parseBooleans = function(str) {
  121013. if (/^(?:true|false)$/i.test(str)) {
  121014. str = str.toLowerCase() === 'true';
  121015. }
  121016. return str;
  121017. };
  121018. }).call(this);
  121019. },{}],671:[function(require,module,exports){
  121020. // Generated by CoffeeScript 1.12.7
  121021. (function() {
  121022. "use strict";
  121023. var builder, defaults, parser, processors,
  121024. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121025. hasProp = {}.hasOwnProperty;
  121026. defaults = require('./defaults');
  121027. builder = require('./builder');
  121028. parser = require('./parser');
  121029. processors = require('./processors');
  121030. exports.defaults = defaults.defaults;
  121031. exports.processors = processors;
  121032. exports.ValidationError = (function(superClass) {
  121033. extend(ValidationError, superClass);
  121034. function ValidationError(message) {
  121035. this.message = message;
  121036. }
  121037. return ValidationError;
  121038. })(Error);
  121039. exports.Builder = builder.Builder;
  121040. exports.Parser = parser.Parser;
  121041. exports.parseString = parser.parseString;
  121042. exports.parseStringPromise = parser.parseStringPromise;
  121043. }).call(this);
  121044. },{"./builder":667,"./defaults":668,"./parser":669,"./processors":670}],672:[function(require,module,exports){
  121045. // Generated by CoffeeScript 1.12.7
  121046. (function() {
  121047. module.exports = {
  121048. Disconnected: 1,
  121049. Preceding: 2,
  121050. Following: 4,
  121051. Contains: 8,
  121052. ContainedBy: 16,
  121053. ImplementationSpecific: 32
  121054. };
  121055. }).call(this);
  121056. },{}],673:[function(require,module,exports){
  121057. // Generated by CoffeeScript 1.12.7
  121058. (function() {
  121059. module.exports = {
  121060. Element: 1,
  121061. Attribute: 2,
  121062. Text: 3,
  121063. CData: 4,
  121064. EntityReference: 5,
  121065. EntityDeclaration: 6,
  121066. ProcessingInstruction: 7,
  121067. Comment: 8,
  121068. Document: 9,
  121069. DocType: 10,
  121070. DocumentFragment: 11,
  121071. NotationDeclaration: 12,
  121072. Declaration: 201,
  121073. Raw: 202,
  121074. AttributeDeclaration: 203,
  121075. ElementDeclaration: 204,
  121076. Dummy: 205
  121077. };
  121078. }).call(this);
  121079. },{}],674:[function(require,module,exports){
  121080. // Generated by CoffeeScript 1.12.7
  121081. (function() {
  121082. var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject,
  121083. slice = [].slice,
  121084. hasProp = {}.hasOwnProperty;
  121085. assign = function() {
  121086. var i, key, len, source, sources, target;
  121087. target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  121088. if (isFunction(Object.assign)) {
  121089. Object.assign.apply(null, arguments);
  121090. } else {
  121091. for (i = 0, len = sources.length; i < len; i++) {
  121092. source = sources[i];
  121093. if (source != null) {
  121094. for (key in source) {
  121095. if (!hasProp.call(source, key)) continue;
  121096. target[key] = source[key];
  121097. }
  121098. }
  121099. }
  121100. }
  121101. return target;
  121102. };
  121103. isFunction = function(val) {
  121104. return !!val && Object.prototype.toString.call(val) === '[object Function]';
  121105. };
  121106. isObject = function(val) {
  121107. var ref;
  121108. return !!val && ((ref = typeof val) === 'function' || ref === 'object');
  121109. };
  121110. isArray = function(val) {
  121111. if (isFunction(Array.isArray)) {
  121112. return Array.isArray(val);
  121113. } else {
  121114. return Object.prototype.toString.call(val) === '[object Array]';
  121115. }
  121116. };
  121117. isEmpty = function(val) {
  121118. var key;
  121119. if (isArray(val)) {
  121120. return !val.length;
  121121. } else {
  121122. for (key in val) {
  121123. if (!hasProp.call(val, key)) continue;
  121124. return false;
  121125. }
  121126. return true;
  121127. }
  121128. };
  121129. isPlainObject = function(val) {
  121130. var ctor, proto;
  121131. return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && (typeof ctor === 'function') && (ctor instanceof ctor) && (Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object));
  121132. };
  121133. getValue = function(obj) {
  121134. if (isFunction(obj.valueOf)) {
  121135. return obj.valueOf();
  121136. } else {
  121137. return obj;
  121138. }
  121139. };
  121140. module.exports.assign = assign;
  121141. module.exports.isFunction = isFunction;
  121142. module.exports.isObject = isObject;
  121143. module.exports.isArray = isArray;
  121144. module.exports.isEmpty = isEmpty;
  121145. module.exports.isPlainObject = isPlainObject;
  121146. module.exports.getValue = getValue;
  121147. }).call(this);
  121148. },{}],675:[function(require,module,exports){
  121149. // Generated by CoffeeScript 1.12.7
  121150. (function() {
  121151. module.exports = {
  121152. None: 0,
  121153. OpenTag: 1,
  121154. InsideTag: 2,
  121155. CloseTag: 3
  121156. };
  121157. }).call(this);
  121158. },{}],676:[function(require,module,exports){
  121159. // Generated by CoffeeScript 1.12.7
  121160. (function() {
  121161. var NodeType, XMLAttribute, XMLNode;
  121162. NodeType = require('./NodeType');
  121163. XMLNode = require('./XMLNode');
  121164. module.exports = XMLAttribute = (function() {
  121165. function XMLAttribute(parent, name, value) {
  121166. this.parent = parent;
  121167. if (this.parent) {
  121168. this.options = this.parent.options;
  121169. this.stringify = this.parent.stringify;
  121170. }
  121171. if (name == null) {
  121172. throw new Error("Missing attribute name. " + this.debugInfo(name));
  121173. }
  121174. this.name = this.stringify.name(name);
  121175. this.value = this.stringify.attValue(value);
  121176. this.type = NodeType.Attribute;
  121177. this.isId = false;
  121178. this.schemaTypeInfo = null;
  121179. }
  121180. Object.defineProperty(XMLAttribute.prototype, 'nodeType', {
  121181. get: function() {
  121182. return this.type;
  121183. }
  121184. });
  121185. Object.defineProperty(XMLAttribute.prototype, 'ownerElement', {
  121186. get: function() {
  121187. return this.parent;
  121188. }
  121189. });
  121190. Object.defineProperty(XMLAttribute.prototype, 'textContent', {
  121191. get: function() {
  121192. return this.value;
  121193. },
  121194. set: function(value) {
  121195. return this.value = value || '';
  121196. }
  121197. });
  121198. Object.defineProperty(XMLAttribute.prototype, 'namespaceURI', {
  121199. get: function() {
  121200. return '';
  121201. }
  121202. });
  121203. Object.defineProperty(XMLAttribute.prototype, 'prefix', {
  121204. get: function() {
  121205. return '';
  121206. }
  121207. });
  121208. Object.defineProperty(XMLAttribute.prototype, 'localName', {
  121209. get: function() {
  121210. return this.name;
  121211. }
  121212. });
  121213. Object.defineProperty(XMLAttribute.prototype, 'specified', {
  121214. get: function() {
  121215. return true;
  121216. }
  121217. });
  121218. XMLAttribute.prototype.clone = function() {
  121219. return Object.create(this);
  121220. };
  121221. XMLAttribute.prototype.toString = function(options) {
  121222. return this.options.writer.attribute(this, this.options.writer.filterOptions(options));
  121223. };
  121224. XMLAttribute.prototype.debugInfo = function(name) {
  121225. name = name || this.name;
  121226. if (name == null) {
  121227. return "parent: <" + this.parent.name + ">";
  121228. } else {
  121229. return "attribute: {" + name + "}, parent: <" + this.parent.name + ">";
  121230. }
  121231. };
  121232. XMLAttribute.prototype.isEqualNode = function(node) {
  121233. if (node.namespaceURI !== this.namespaceURI) {
  121234. return false;
  121235. }
  121236. if (node.prefix !== this.prefix) {
  121237. return false;
  121238. }
  121239. if (node.localName !== this.localName) {
  121240. return false;
  121241. }
  121242. if (node.value !== this.value) {
  121243. return false;
  121244. }
  121245. return true;
  121246. };
  121247. return XMLAttribute;
  121248. })();
  121249. }).call(this);
  121250. },{"./NodeType":673,"./XMLNode":695}],677:[function(require,module,exports){
  121251. // Generated by CoffeeScript 1.12.7
  121252. (function() {
  121253. var NodeType, XMLCData, XMLCharacterData,
  121254. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121255. hasProp = {}.hasOwnProperty;
  121256. NodeType = require('./NodeType');
  121257. XMLCharacterData = require('./XMLCharacterData');
  121258. module.exports = XMLCData = (function(superClass) {
  121259. extend(XMLCData, superClass);
  121260. function XMLCData(parent, text) {
  121261. XMLCData.__super__.constructor.call(this, parent);
  121262. if (text == null) {
  121263. throw new Error("Missing CDATA text. " + this.debugInfo());
  121264. }
  121265. this.name = "#cdata-section";
  121266. this.type = NodeType.CData;
  121267. this.value = this.stringify.cdata(text);
  121268. }
  121269. XMLCData.prototype.clone = function() {
  121270. return Object.create(this);
  121271. };
  121272. XMLCData.prototype.toString = function(options) {
  121273. return this.options.writer.cdata(this, this.options.writer.filterOptions(options));
  121274. };
  121275. return XMLCData;
  121276. })(XMLCharacterData);
  121277. }).call(this);
  121278. },{"./NodeType":673,"./XMLCharacterData":678}],678:[function(require,module,exports){
  121279. // Generated by CoffeeScript 1.12.7
  121280. (function() {
  121281. var XMLCharacterData, XMLNode,
  121282. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121283. hasProp = {}.hasOwnProperty;
  121284. XMLNode = require('./XMLNode');
  121285. module.exports = XMLCharacterData = (function(superClass) {
  121286. extend(XMLCharacterData, superClass);
  121287. function XMLCharacterData(parent) {
  121288. XMLCharacterData.__super__.constructor.call(this, parent);
  121289. this.value = '';
  121290. }
  121291. Object.defineProperty(XMLCharacterData.prototype, 'data', {
  121292. get: function() {
  121293. return this.value;
  121294. },
  121295. set: function(value) {
  121296. return this.value = value || '';
  121297. }
  121298. });
  121299. Object.defineProperty(XMLCharacterData.prototype, 'length', {
  121300. get: function() {
  121301. return this.value.length;
  121302. }
  121303. });
  121304. Object.defineProperty(XMLCharacterData.prototype, 'textContent', {
  121305. get: function() {
  121306. return this.value;
  121307. },
  121308. set: function(value) {
  121309. return this.value = value || '';
  121310. }
  121311. });
  121312. XMLCharacterData.prototype.clone = function() {
  121313. return Object.create(this);
  121314. };
  121315. XMLCharacterData.prototype.substringData = function(offset, count) {
  121316. throw new Error("This DOM method is not implemented." + this.debugInfo());
  121317. };
  121318. XMLCharacterData.prototype.appendData = function(arg) {
  121319. throw new Error("This DOM method is not implemented." + this.debugInfo());
  121320. };
  121321. XMLCharacterData.prototype.insertData = function(offset, arg) {
  121322. throw new Error("This DOM method is not implemented." + this.debugInfo());
  121323. };
  121324. XMLCharacterData.prototype.deleteData = function(offset, count) {
  121325. throw new Error("This DOM method is not implemented." + this.debugInfo());
  121326. };
  121327. XMLCharacterData.prototype.replaceData = function(offset, count, arg) {
  121328. throw new Error("This DOM method is not implemented." + this.debugInfo());
  121329. };
  121330. XMLCharacterData.prototype.isEqualNode = function(node) {
  121331. if (!XMLCharacterData.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
  121332. return false;
  121333. }
  121334. if (node.data !== this.data) {
  121335. return false;
  121336. }
  121337. return true;
  121338. };
  121339. return XMLCharacterData;
  121340. })(XMLNode);
  121341. }).call(this);
  121342. },{"./XMLNode":695}],679:[function(require,module,exports){
  121343. // Generated by CoffeeScript 1.12.7
  121344. (function() {
  121345. var NodeType, XMLCharacterData, XMLComment,
  121346. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121347. hasProp = {}.hasOwnProperty;
  121348. NodeType = require('./NodeType');
  121349. XMLCharacterData = require('./XMLCharacterData');
  121350. module.exports = XMLComment = (function(superClass) {
  121351. extend(XMLComment, superClass);
  121352. function XMLComment(parent, text) {
  121353. XMLComment.__super__.constructor.call(this, parent);
  121354. if (text == null) {
  121355. throw new Error("Missing comment text. " + this.debugInfo());
  121356. }
  121357. this.name = "#comment";
  121358. this.type = NodeType.Comment;
  121359. this.value = this.stringify.comment(text);
  121360. }
  121361. XMLComment.prototype.clone = function() {
  121362. return Object.create(this);
  121363. };
  121364. XMLComment.prototype.toString = function(options) {
  121365. return this.options.writer.comment(this, this.options.writer.filterOptions(options));
  121366. };
  121367. return XMLComment;
  121368. })(XMLCharacterData);
  121369. }).call(this);
  121370. },{"./NodeType":673,"./XMLCharacterData":678}],680:[function(require,module,exports){
  121371. // Generated by CoffeeScript 1.12.7
  121372. (function() {
  121373. var XMLDOMConfiguration, XMLDOMErrorHandler, XMLDOMStringList;
  121374. XMLDOMErrorHandler = require('./XMLDOMErrorHandler');
  121375. XMLDOMStringList = require('./XMLDOMStringList');
  121376. module.exports = XMLDOMConfiguration = (function() {
  121377. function XMLDOMConfiguration() {
  121378. var clonedSelf;
  121379. this.defaultParams = {
  121380. "canonical-form": false,
  121381. "cdata-sections": false,
  121382. "comments": false,
  121383. "datatype-normalization": false,
  121384. "element-content-whitespace": true,
  121385. "entities": true,
  121386. "error-handler": new XMLDOMErrorHandler(),
  121387. "infoset": true,
  121388. "validate-if-schema": false,
  121389. "namespaces": true,
  121390. "namespace-declarations": true,
  121391. "normalize-characters": false,
  121392. "schema-location": '',
  121393. "schema-type": '',
  121394. "split-cdata-sections": true,
  121395. "validate": false,
  121396. "well-formed": true
  121397. };
  121398. this.params = clonedSelf = Object.create(this.defaultParams);
  121399. }
  121400. Object.defineProperty(XMLDOMConfiguration.prototype, 'parameterNames', {
  121401. get: function() {
  121402. return new XMLDOMStringList(Object.keys(this.defaultParams));
  121403. }
  121404. });
  121405. XMLDOMConfiguration.prototype.getParameter = function(name) {
  121406. if (this.params.hasOwnProperty(name)) {
  121407. return this.params[name];
  121408. } else {
  121409. return null;
  121410. }
  121411. };
  121412. XMLDOMConfiguration.prototype.canSetParameter = function(name, value) {
  121413. return true;
  121414. };
  121415. XMLDOMConfiguration.prototype.setParameter = function(name, value) {
  121416. if (value != null) {
  121417. return this.params[name] = value;
  121418. } else {
  121419. return delete this.params[name];
  121420. }
  121421. };
  121422. return XMLDOMConfiguration;
  121423. })();
  121424. }).call(this);
  121425. },{"./XMLDOMErrorHandler":681,"./XMLDOMStringList":683}],681:[function(require,module,exports){
  121426. // Generated by CoffeeScript 1.12.7
  121427. (function() {
  121428. var XMLDOMErrorHandler;
  121429. module.exports = XMLDOMErrorHandler = (function() {
  121430. function XMLDOMErrorHandler() {}
  121431. XMLDOMErrorHandler.prototype.handleError = function(error) {
  121432. throw new Error(error);
  121433. };
  121434. return XMLDOMErrorHandler;
  121435. })();
  121436. }).call(this);
  121437. },{}],682:[function(require,module,exports){
  121438. // Generated by CoffeeScript 1.12.7
  121439. (function() {
  121440. var XMLDOMImplementation;
  121441. module.exports = XMLDOMImplementation = (function() {
  121442. function XMLDOMImplementation() {}
  121443. XMLDOMImplementation.prototype.hasFeature = function(feature, version) {
  121444. return true;
  121445. };
  121446. XMLDOMImplementation.prototype.createDocumentType = function(qualifiedName, publicId, systemId) {
  121447. throw new Error("This DOM method is not implemented.");
  121448. };
  121449. XMLDOMImplementation.prototype.createDocument = function(namespaceURI, qualifiedName, doctype) {
  121450. throw new Error("This DOM method is not implemented.");
  121451. };
  121452. XMLDOMImplementation.prototype.createHTMLDocument = function(title) {
  121453. throw new Error("This DOM method is not implemented.");
  121454. };
  121455. XMLDOMImplementation.prototype.getFeature = function(feature, version) {
  121456. throw new Error("This DOM method is not implemented.");
  121457. };
  121458. return XMLDOMImplementation;
  121459. })();
  121460. }).call(this);
  121461. },{}],683:[function(require,module,exports){
  121462. // Generated by CoffeeScript 1.12.7
  121463. (function() {
  121464. var XMLDOMStringList;
  121465. module.exports = XMLDOMStringList = (function() {
  121466. function XMLDOMStringList(arr) {
  121467. this.arr = arr || [];
  121468. }
  121469. Object.defineProperty(XMLDOMStringList.prototype, 'length', {
  121470. get: function() {
  121471. return this.arr.length;
  121472. }
  121473. });
  121474. XMLDOMStringList.prototype.item = function(index) {
  121475. return this.arr[index] || null;
  121476. };
  121477. XMLDOMStringList.prototype.contains = function(str) {
  121478. return this.arr.indexOf(str) !== -1;
  121479. };
  121480. return XMLDOMStringList;
  121481. })();
  121482. }).call(this);
  121483. },{}],684:[function(require,module,exports){
  121484. // Generated by CoffeeScript 1.12.7
  121485. (function() {
  121486. var NodeType, XMLDTDAttList, XMLNode,
  121487. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121488. hasProp = {}.hasOwnProperty;
  121489. XMLNode = require('./XMLNode');
  121490. NodeType = require('./NodeType');
  121491. module.exports = XMLDTDAttList = (function(superClass) {
  121492. extend(XMLDTDAttList, superClass);
  121493. function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  121494. XMLDTDAttList.__super__.constructor.call(this, parent);
  121495. if (elementName == null) {
  121496. throw new Error("Missing DTD element name. " + this.debugInfo());
  121497. }
  121498. if (attributeName == null) {
  121499. throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName));
  121500. }
  121501. if (!attributeType) {
  121502. throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName));
  121503. }
  121504. if (!defaultValueType) {
  121505. throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName));
  121506. }
  121507. if (defaultValueType.indexOf('#') !== 0) {
  121508. defaultValueType = '#' + defaultValueType;
  121509. }
  121510. if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
  121511. throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName));
  121512. }
  121513. if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
  121514. throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName));
  121515. }
  121516. this.elementName = this.stringify.name(elementName);
  121517. this.type = NodeType.AttributeDeclaration;
  121518. this.attributeName = this.stringify.name(attributeName);
  121519. this.attributeType = this.stringify.dtdAttType(attributeType);
  121520. if (defaultValue) {
  121521. this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
  121522. }
  121523. this.defaultValueType = defaultValueType;
  121524. }
  121525. XMLDTDAttList.prototype.toString = function(options) {
  121526. return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options));
  121527. };
  121528. return XMLDTDAttList;
  121529. })(XMLNode);
  121530. }).call(this);
  121531. },{"./NodeType":673,"./XMLNode":695}],685:[function(require,module,exports){
  121532. // Generated by CoffeeScript 1.12.7
  121533. (function() {
  121534. var NodeType, XMLDTDElement, XMLNode,
  121535. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121536. hasProp = {}.hasOwnProperty;
  121537. XMLNode = require('./XMLNode');
  121538. NodeType = require('./NodeType');
  121539. module.exports = XMLDTDElement = (function(superClass) {
  121540. extend(XMLDTDElement, superClass);
  121541. function XMLDTDElement(parent, name, value) {
  121542. XMLDTDElement.__super__.constructor.call(this, parent);
  121543. if (name == null) {
  121544. throw new Error("Missing DTD element name. " + this.debugInfo());
  121545. }
  121546. if (!value) {
  121547. value = '(#PCDATA)';
  121548. }
  121549. if (Array.isArray(value)) {
  121550. value = '(' + value.join(',') + ')';
  121551. }
  121552. this.name = this.stringify.name(name);
  121553. this.type = NodeType.ElementDeclaration;
  121554. this.value = this.stringify.dtdElementValue(value);
  121555. }
  121556. XMLDTDElement.prototype.toString = function(options) {
  121557. return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options));
  121558. };
  121559. return XMLDTDElement;
  121560. })(XMLNode);
  121561. }).call(this);
  121562. },{"./NodeType":673,"./XMLNode":695}],686:[function(require,module,exports){
  121563. // Generated by CoffeeScript 1.12.7
  121564. (function() {
  121565. var NodeType, XMLDTDEntity, XMLNode, isObject,
  121566. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121567. hasProp = {}.hasOwnProperty;
  121568. isObject = require('./Utility').isObject;
  121569. XMLNode = require('./XMLNode');
  121570. NodeType = require('./NodeType');
  121571. module.exports = XMLDTDEntity = (function(superClass) {
  121572. extend(XMLDTDEntity, superClass);
  121573. function XMLDTDEntity(parent, pe, name, value) {
  121574. XMLDTDEntity.__super__.constructor.call(this, parent);
  121575. if (name == null) {
  121576. throw new Error("Missing DTD entity name. " + this.debugInfo(name));
  121577. }
  121578. if (value == null) {
  121579. throw new Error("Missing DTD entity value. " + this.debugInfo(name));
  121580. }
  121581. this.pe = !!pe;
  121582. this.name = this.stringify.name(name);
  121583. this.type = NodeType.EntityDeclaration;
  121584. if (!isObject(value)) {
  121585. this.value = this.stringify.dtdEntityValue(value);
  121586. this.internal = true;
  121587. } else {
  121588. if (!value.pubID && !value.sysID) {
  121589. throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name));
  121590. }
  121591. if (value.pubID && !value.sysID) {
  121592. throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name));
  121593. }
  121594. this.internal = false;
  121595. if (value.pubID != null) {
  121596. this.pubID = this.stringify.dtdPubID(value.pubID);
  121597. }
  121598. if (value.sysID != null) {
  121599. this.sysID = this.stringify.dtdSysID(value.sysID);
  121600. }
  121601. if (value.nData != null) {
  121602. this.nData = this.stringify.dtdNData(value.nData);
  121603. }
  121604. if (this.pe && this.nData) {
  121605. throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name));
  121606. }
  121607. }
  121608. }
  121609. Object.defineProperty(XMLDTDEntity.prototype, 'publicId', {
  121610. get: function() {
  121611. return this.pubID;
  121612. }
  121613. });
  121614. Object.defineProperty(XMLDTDEntity.prototype, 'systemId', {
  121615. get: function() {
  121616. return this.sysID;
  121617. }
  121618. });
  121619. Object.defineProperty(XMLDTDEntity.prototype, 'notationName', {
  121620. get: function() {
  121621. return this.nData || null;
  121622. }
  121623. });
  121624. Object.defineProperty(XMLDTDEntity.prototype, 'inputEncoding', {
  121625. get: function() {
  121626. return null;
  121627. }
  121628. });
  121629. Object.defineProperty(XMLDTDEntity.prototype, 'xmlEncoding', {
  121630. get: function() {
  121631. return null;
  121632. }
  121633. });
  121634. Object.defineProperty(XMLDTDEntity.prototype, 'xmlVersion', {
  121635. get: function() {
  121636. return null;
  121637. }
  121638. });
  121639. XMLDTDEntity.prototype.toString = function(options) {
  121640. return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options));
  121641. };
  121642. return XMLDTDEntity;
  121643. })(XMLNode);
  121644. }).call(this);
  121645. },{"./NodeType":673,"./Utility":674,"./XMLNode":695}],687:[function(require,module,exports){
  121646. // Generated by CoffeeScript 1.12.7
  121647. (function() {
  121648. var NodeType, XMLDTDNotation, XMLNode,
  121649. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121650. hasProp = {}.hasOwnProperty;
  121651. XMLNode = require('./XMLNode');
  121652. NodeType = require('./NodeType');
  121653. module.exports = XMLDTDNotation = (function(superClass) {
  121654. extend(XMLDTDNotation, superClass);
  121655. function XMLDTDNotation(parent, name, value) {
  121656. XMLDTDNotation.__super__.constructor.call(this, parent);
  121657. if (name == null) {
  121658. throw new Error("Missing DTD notation name. " + this.debugInfo(name));
  121659. }
  121660. if (!value.pubID && !value.sysID) {
  121661. throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name));
  121662. }
  121663. this.name = this.stringify.name(name);
  121664. this.type = NodeType.NotationDeclaration;
  121665. if (value.pubID != null) {
  121666. this.pubID = this.stringify.dtdPubID(value.pubID);
  121667. }
  121668. if (value.sysID != null) {
  121669. this.sysID = this.stringify.dtdSysID(value.sysID);
  121670. }
  121671. }
  121672. Object.defineProperty(XMLDTDNotation.prototype, 'publicId', {
  121673. get: function() {
  121674. return this.pubID;
  121675. }
  121676. });
  121677. Object.defineProperty(XMLDTDNotation.prototype, 'systemId', {
  121678. get: function() {
  121679. return this.sysID;
  121680. }
  121681. });
  121682. XMLDTDNotation.prototype.toString = function(options) {
  121683. return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options));
  121684. };
  121685. return XMLDTDNotation;
  121686. })(XMLNode);
  121687. }).call(this);
  121688. },{"./NodeType":673,"./XMLNode":695}],688:[function(require,module,exports){
  121689. // Generated by CoffeeScript 1.12.7
  121690. (function() {
  121691. var NodeType, XMLDeclaration, XMLNode, isObject,
  121692. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121693. hasProp = {}.hasOwnProperty;
  121694. isObject = require('./Utility').isObject;
  121695. XMLNode = require('./XMLNode');
  121696. NodeType = require('./NodeType');
  121697. module.exports = XMLDeclaration = (function(superClass) {
  121698. extend(XMLDeclaration, superClass);
  121699. function XMLDeclaration(parent, version, encoding, standalone) {
  121700. var ref;
  121701. XMLDeclaration.__super__.constructor.call(this, parent);
  121702. if (isObject(version)) {
  121703. ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
  121704. }
  121705. if (!version) {
  121706. version = '1.0';
  121707. }
  121708. this.type = NodeType.Declaration;
  121709. this.version = this.stringify.xmlVersion(version);
  121710. if (encoding != null) {
  121711. this.encoding = this.stringify.xmlEncoding(encoding);
  121712. }
  121713. if (standalone != null) {
  121714. this.standalone = this.stringify.xmlStandalone(standalone);
  121715. }
  121716. }
  121717. XMLDeclaration.prototype.toString = function(options) {
  121718. return this.options.writer.declaration(this, this.options.writer.filterOptions(options));
  121719. };
  121720. return XMLDeclaration;
  121721. })(XMLNode);
  121722. }).call(this);
  121723. },{"./NodeType":673,"./Utility":674,"./XMLNode":695}],689:[function(require,module,exports){
  121724. // Generated by CoffeeScript 1.12.7
  121725. (function() {
  121726. var NodeType, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNamedNodeMap, XMLNode, isObject,
  121727. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121728. hasProp = {}.hasOwnProperty;
  121729. isObject = require('./Utility').isObject;
  121730. XMLNode = require('./XMLNode');
  121731. NodeType = require('./NodeType');
  121732. XMLDTDAttList = require('./XMLDTDAttList');
  121733. XMLDTDEntity = require('./XMLDTDEntity');
  121734. XMLDTDElement = require('./XMLDTDElement');
  121735. XMLDTDNotation = require('./XMLDTDNotation');
  121736. XMLNamedNodeMap = require('./XMLNamedNodeMap');
  121737. module.exports = XMLDocType = (function(superClass) {
  121738. extend(XMLDocType, superClass);
  121739. function XMLDocType(parent, pubID, sysID) {
  121740. var child, i, len, ref, ref1, ref2;
  121741. XMLDocType.__super__.constructor.call(this, parent);
  121742. this.type = NodeType.DocType;
  121743. if (parent.children) {
  121744. ref = parent.children;
  121745. for (i = 0, len = ref.length; i < len; i++) {
  121746. child = ref[i];
  121747. if (child.type === NodeType.Element) {
  121748. this.name = child.name;
  121749. break;
  121750. }
  121751. }
  121752. }
  121753. this.documentObject = parent;
  121754. if (isObject(pubID)) {
  121755. ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID;
  121756. }
  121757. if (sysID == null) {
  121758. ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1];
  121759. }
  121760. if (pubID != null) {
  121761. this.pubID = this.stringify.dtdPubID(pubID);
  121762. }
  121763. if (sysID != null) {
  121764. this.sysID = this.stringify.dtdSysID(sysID);
  121765. }
  121766. }
  121767. Object.defineProperty(XMLDocType.prototype, 'entities', {
  121768. get: function() {
  121769. var child, i, len, nodes, ref;
  121770. nodes = {};
  121771. ref = this.children;
  121772. for (i = 0, len = ref.length; i < len; i++) {
  121773. child = ref[i];
  121774. if ((child.type === NodeType.EntityDeclaration) && !child.pe) {
  121775. nodes[child.name] = child;
  121776. }
  121777. }
  121778. return new XMLNamedNodeMap(nodes);
  121779. }
  121780. });
  121781. Object.defineProperty(XMLDocType.prototype, 'notations', {
  121782. get: function() {
  121783. var child, i, len, nodes, ref;
  121784. nodes = {};
  121785. ref = this.children;
  121786. for (i = 0, len = ref.length; i < len; i++) {
  121787. child = ref[i];
  121788. if (child.type === NodeType.NotationDeclaration) {
  121789. nodes[child.name] = child;
  121790. }
  121791. }
  121792. return new XMLNamedNodeMap(nodes);
  121793. }
  121794. });
  121795. Object.defineProperty(XMLDocType.prototype, 'publicId', {
  121796. get: function() {
  121797. return this.pubID;
  121798. }
  121799. });
  121800. Object.defineProperty(XMLDocType.prototype, 'systemId', {
  121801. get: function() {
  121802. return this.sysID;
  121803. }
  121804. });
  121805. Object.defineProperty(XMLDocType.prototype, 'internalSubset', {
  121806. get: function() {
  121807. throw new Error("This DOM method is not implemented." + this.debugInfo());
  121808. }
  121809. });
  121810. XMLDocType.prototype.element = function(name, value) {
  121811. var child;
  121812. child = new XMLDTDElement(this, name, value);
  121813. this.children.push(child);
  121814. return this;
  121815. };
  121816. XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  121817. var child;
  121818. child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
  121819. this.children.push(child);
  121820. return this;
  121821. };
  121822. XMLDocType.prototype.entity = function(name, value) {
  121823. var child;
  121824. child = new XMLDTDEntity(this, false, name, value);
  121825. this.children.push(child);
  121826. return this;
  121827. };
  121828. XMLDocType.prototype.pEntity = function(name, value) {
  121829. var child;
  121830. child = new XMLDTDEntity(this, true, name, value);
  121831. this.children.push(child);
  121832. return this;
  121833. };
  121834. XMLDocType.prototype.notation = function(name, value) {
  121835. var child;
  121836. child = new XMLDTDNotation(this, name, value);
  121837. this.children.push(child);
  121838. return this;
  121839. };
  121840. XMLDocType.prototype.toString = function(options) {
  121841. return this.options.writer.docType(this, this.options.writer.filterOptions(options));
  121842. };
  121843. XMLDocType.prototype.ele = function(name, value) {
  121844. return this.element(name, value);
  121845. };
  121846. XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  121847. return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
  121848. };
  121849. XMLDocType.prototype.ent = function(name, value) {
  121850. return this.entity(name, value);
  121851. };
  121852. XMLDocType.prototype.pent = function(name, value) {
  121853. return this.pEntity(name, value);
  121854. };
  121855. XMLDocType.prototype.not = function(name, value) {
  121856. return this.notation(name, value);
  121857. };
  121858. XMLDocType.prototype.up = function() {
  121859. return this.root() || this.documentObject;
  121860. };
  121861. XMLDocType.prototype.isEqualNode = function(node) {
  121862. if (!XMLDocType.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
  121863. return false;
  121864. }
  121865. if (node.name !== this.name) {
  121866. return false;
  121867. }
  121868. if (node.publicId !== this.publicId) {
  121869. return false;
  121870. }
  121871. if (node.systemId !== this.systemId) {
  121872. return false;
  121873. }
  121874. return true;
  121875. };
  121876. return XMLDocType;
  121877. })(XMLNode);
  121878. }).call(this);
  121879. },{"./NodeType":673,"./Utility":674,"./XMLDTDAttList":684,"./XMLDTDElement":685,"./XMLDTDEntity":686,"./XMLDTDNotation":687,"./XMLNamedNodeMap":694,"./XMLNode":695}],690:[function(require,module,exports){
  121880. // Generated by CoffeeScript 1.12.7
  121881. (function() {
  121882. var NodeType, XMLDOMConfiguration, XMLDOMImplementation, XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject,
  121883. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  121884. hasProp = {}.hasOwnProperty;
  121885. isPlainObject = require('./Utility').isPlainObject;
  121886. XMLDOMImplementation = require('./XMLDOMImplementation');
  121887. XMLDOMConfiguration = require('./XMLDOMConfiguration');
  121888. XMLNode = require('./XMLNode');
  121889. NodeType = require('./NodeType');
  121890. XMLStringifier = require('./XMLStringifier');
  121891. XMLStringWriter = require('./XMLStringWriter');
  121892. module.exports = XMLDocument = (function(superClass) {
  121893. extend(XMLDocument, superClass);
  121894. function XMLDocument(options) {
  121895. XMLDocument.__super__.constructor.call(this, null);
  121896. this.name = "#document";
  121897. this.type = NodeType.Document;
  121898. this.documentURI = null;
  121899. this.domConfig = new XMLDOMConfiguration();
  121900. options || (options = {});
  121901. if (!options.writer) {
  121902. options.writer = new XMLStringWriter();
  121903. }
  121904. this.options = options;
  121905. this.stringify = new XMLStringifier(options);
  121906. }
  121907. Object.defineProperty(XMLDocument.prototype, 'implementation', {
  121908. value: new XMLDOMImplementation()
  121909. });
  121910. Object.defineProperty(XMLDocument.prototype, 'doctype', {
  121911. get: function() {
  121912. var child, i, len, ref;
  121913. ref = this.children;
  121914. for (i = 0, len = ref.length; i < len; i++) {
  121915. child = ref[i];
  121916. if (child.type === NodeType.DocType) {
  121917. return child;
  121918. }
  121919. }
  121920. return null;
  121921. }
  121922. });
  121923. Object.defineProperty(XMLDocument.prototype, 'documentElement', {
  121924. get: function() {
  121925. return this.rootObject || null;
  121926. }
  121927. });
  121928. Object.defineProperty(XMLDocument.prototype, 'inputEncoding', {
  121929. get: function() {
  121930. return null;
  121931. }
  121932. });
  121933. Object.defineProperty(XMLDocument.prototype, 'strictErrorChecking', {
  121934. get: function() {
  121935. return false;
  121936. }
  121937. });
  121938. Object.defineProperty(XMLDocument.prototype, 'xmlEncoding', {
  121939. get: function() {
  121940. if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {
  121941. return this.children[0].encoding;
  121942. } else {
  121943. return null;
  121944. }
  121945. }
  121946. });
  121947. Object.defineProperty(XMLDocument.prototype, 'xmlStandalone', {
  121948. get: function() {
  121949. if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {
  121950. return this.children[0].standalone === 'yes';
  121951. } else {
  121952. return false;
  121953. }
  121954. }
  121955. });
  121956. Object.defineProperty(XMLDocument.prototype, 'xmlVersion', {
  121957. get: function() {
  121958. if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {
  121959. return this.children[0].version;
  121960. } else {
  121961. return "1.0";
  121962. }
  121963. }
  121964. });
  121965. Object.defineProperty(XMLDocument.prototype, 'URL', {
  121966. get: function() {
  121967. return this.documentURI;
  121968. }
  121969. });
  121970. Object.defineProperty(XMLDocument.prototype, 'origin', {
  121971. get: function() {
  121972. return null;
  121973. }
  121974. });
  121975. Object.defineProperty(XMLDocument.prototype, 'compatMode', {
  121976. get: function() {
  121977. return null;
  121978. }
  121979. });
  121980. Object.defineProperty(XMLDocument.prototype, 'characterSet', {
  121981. get: function() {
  121982. return null;
  121983. }
  121984. });
  121985. Object.defineProperty(XMLDocument.prototype, 'contentType', {
  121986. get: function() {
  121987. return null;
  121988. }
  121989. });
  121990. XMLDocument.prototype.end = function(writer) {
  121991. var writerOptions;
  121992. writerOptions = {};
  121993. if (!writer) {
  121994. writer = this.options.writer;
  121995. } else if (isPlainObject(writer)) {
  121996. writerOptions = writer;
  121997. writer = this.options.writer;
  121998. }
  121999. return writer.document(this, writer.filterOptions(writerOptions));
  122000. };
  122001. XMLDocument.prototype.toString = function(options) {
  122002. return this.options.writer.document(this, this.options.writer.filterOptions(options));
  122003. };
  122004. XMLDocument.prototype.createElement = function(tagName) {
  122005. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122006. };
  122007. XMLDocument.prototype.createDocumentFragment = function() {
  122008. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122009. };
  122010. XMLDocument.prototype.createTextNode = function(data) {
  122011. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122012. };
  122013. XMLDocument.prototype.createComment = function(data) {
  122014. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122015. };
  122016. XMLDocument.prototype.createCDATASection = function(data) {
  122017. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122018. };
  122019. XMLDocument.prototype.createProcessingInstruction = function(target, data) {
  122020. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122021. };
  122022. XMLDocument.prototype.createAttribute = function(name) {
  122023. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122024. };
  122025. XMLDocument.prototype.createEntityReference = function(name) {
  122026. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122027. };
  122028. XMLDocument.prototype.getElementsByTagName = function(tagname) {
  122029. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122030. };
  122031. XMLDocument.prototype.importNode = function(importedNode, deep) {
  122032. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122033. };
  122034. XMLDocument.prototype.createElementNS = function(namespaceURI, qualifiedName) {
  122035. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122036. };
  122037. XMLDocument.prototype.createAttributeNS = function(namespaceURI, qualifiedName) {
  122038. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122039. };
  122040. XMLDocument.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {
  122041. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122042. };
  122043. XMLDocument.prototype.getElementById = function(elementId) {
  122044. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122045. };
  122046. XMLDocument.prototype.adoptNode = function(source) {
  122047. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122048. };
  122049. XMLDocument.prototype.normalizeDocument = function() {
  122050. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122051. };
  122052. XMLDocument.prototype.renameNode = function(node, namespaceURI, qualifiedName) {
  122053. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122054. };
  122055. XMLDocument.prototype.getElementsByClassName = function(classNames) {
  122056. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122057. };
  122058. XMLDocument.prototype.createEvent = function(eventInterface) {
  122059. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122060. };
  122061. XMLDocument.prototype.createRange = function() {
  122062. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122063. };
  122064. XMLDocument.prototype.createNodeIterator = function(root, whatToShow, filter) {
  122065. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122066. };
  122067. XMLDocument.prototype.createTreeWalker = function(root, whatToShow, filter) {
  122068. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122069. };
  122070. return XMLDocument;
  122071. })(XMLNode);
  122072. }).call(this);
  122073. },{"./NodeType":673,"./Utility":674,"./XMLDOMConfiguration":680,"./XMLDOMImplementation":682,"./XMLNode":695,"./XMLStringWriter":700,"./XMLStringifier":701}],691:[function(require,module,exports){
  122074. // Generated by CoffeeScript 1.12.7
  122075. (function() {
  122076. var NodeType, WriterState, XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocument, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref,
  122077. hasProp = {}.hasOwnProperty;
  122078. ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue;
  122079. NodeType = require('./NodeType');
  122080. XMLDocument = require('./XMLDocument');
  122081. XMLElement = require('./XMLElement');
  122082. XMLCData = require('./XMLCData');
  122083. XMLComment = require('./XMLComment');
  122084. XMLRaw = require('./XMLRaw');
  122085. XMLText = require('./XMLText');
  122086. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  122087. XMLDeclaration = require('./XMLDeclaration');
  122088. XMLDocType = require('./XMLDocType');
  122089. XMLDTDAttList = require('./XMLDTDAttList');
  122090. XMLDTDEntity = require('./XMLDTDEntity');
  122091. XMLDTDElement = require('./XMLDTDElement');
  122092. XMLDTDNotation = require('./XMLDTDNotation');
  122093. XMLAttribute = require('./XMLAttribute');
  122094. XMLStringifier = require('./XMLStringifier');
  122095. XMLStringWriter = require('./XMLStringWriter');
  122096. WriterState = require('./WriterState');
  122097. module.exports = XMLDocumentCB = (function() {
  122098. function XMLDocumentCB(options, onData, onEnd) {
  122099. var writerOptions;
  122100. this.name = "?xml";
  122101. this.type = NodeType.Document;
  122102. options || (options = {});
  122103. writerOptions = {};
  122104. if (!options.writer) {
  122105. options.writer = new XMLStringWriter();
  122106. } else if (isPlainObject(options.writer)) {
  122107. writerOptions = options.writer;
  122108. options.writer = new XMLStringWriter();
  122109. }
  122110. this.options = options;
  122111. this.writer = options.writer;
  122112. this.writerOptions = this.writer.filterOptions(writerOptions);
  122113. this.stringify = new XMLStringifier(options);
  122114. this.onDataCallback = onData || function() {};
  122115. this.onEndCallback = onEnd || function() {};
  122116. this.currentNode = null;
  122117. this.currentLevel = -1;
  122118. this.openTags = {};
  122119. this.documentStarted = false;
  122120. this.documentCompleted = false;
  122121. this.root = null;
  122122. }
  122123. XMLDocumentCB.prototype.createChildNode = function(node) {
  122124. var att, attName, attributes, child, i, len, ref1, ref2;
  122125. switch (node.type) {
  122126. case NodeType.CData:
  122127. this.cdata(node.value);
  122128. break;
  122129. case NodeType.Comment:
  122130. this.comment(node.value);
  122131. break;
  122132. case NodeType.Element:
  122133. attributes = {};
  122134. ref1 = node.attribs;
  122135. for (attName in ref1) {
  122136. if (!hasProp.call(ref1, attName)) continue;
  122137. att = ref1[attName];
  122138. attributes[attName] = att.value;
  122139. }
  122140. this.node(node.name, attributes);
  122141. break;
  122142. case NodeType.Dummy:
  122143. this.dummy();
  122144. break;
  122145. case NodeType.Raw:
  122146. this.raw(node.value);
  122147. break;
  122148. case NodeType.Text:
  122149. this.text(node.value);
  122150. break;
  122151. case NodeType.ProcessingInstruction:
  122152. this.instruction(node.target, node.value);
  122153. break;
  122154. default:
  122155. throw new Error("This XML node type is not supported in a JS object: " + node.constructor.name);
  122156. }
  122157. ref2 = node.children;
  122158. for (i = 0, len = ref2.length; i < len; i++) {
  122159. child = ref2[i];
  122160. this.createChildNode(child);
  122161. if (child.type === NodeType.Element) {
  122162. this.up();
  122163. }
  122164. }
  122165. return this;
  122166. };
  122167. XMLDocumentCB.prototype.dummy = function() {
  122168. return this;
  122169. };
  122170. XMLDocumentCB.prototype.node = function(name, attributes, text) {
  122171. var ref1;
  122172. if (name == null) {
  122173. throw new Error("Missing node name.");
  122174. }
  122175. if (this.root && this.currentLevel === -1) {
  122176. throw new Error("Document can only have one root node. " + this.debugInfo(name));
  122177. }
  122178. this.openCurrent();
  122179. name = getValue(name);
  122180. if (attributes == null) {
  122181. attributes = {};
  122182. }
  122183. attributes = getValue(attributes);
  122184. if (!isObject(attributes)) {
  122185. ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
  122186. }
  122187. this.currentNode = new XMLElement(this, name, attributes);
  122188. this.currentNode.children = false;
  122189. this.currentLevel++;
  122190. this.openTags[this.currentLevel] = this.currentNode;
  122191. if (text != null) {
  122192. this.text(text);
  122193. }
  122194. return this;
  122195. };
  122196. XMLDocumentCB.prototype.element = function(name, attributes, text) {
  122197. var child, i, len, oldValidationFlag, ref1, root;
  122198. if (this.currentNode && this.currentNode.type === NodeType.DocType) {
  122199. this.dtdElement.apply(this, arguments);
  122200. } else {
  122201. if (Array.isArray(name) || isObject(name) || isFunction(name)) {
  122202. oldValidationFlag = this.options.noValidation;
  122203. this.options.noValidation = true;
  122204. root = new XMLDocument(this.options).element('TEMP_ROOT');
  122205. root.element(name);
  122206. this.options.noValidation = oldValidationFlag;
  122207. ref1 = root.children;
  122208. for (i = 0, len = ref1.length; i < len; i++) {
  122209. child = ref1[i];
  122210. this.createChildNode(child);
  122211. if (child.type === NodeType.Element) {
  122212. this.up();
  122213. }
  122214. }
  122215. } else {
  122216. this.node(name, attributes, text);
  122217. }
  122218. }
  122219. return this;
  122220. };
  122221. XMLDocumentCB.prototype.attribute = function(name, value) {
  122222. var attName, attValue;
  122223. if (!this.currentNode || this.currentNode.children) {
  122224. throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name));
  122225. }
  122226. if (name != null) {
  122227. name = getValue(name);
  122228. }
  122229. if (isObject(name)) {
  122230. for (attName in name) {
  122231. if (!hasProp.call(name, attName)) continue;
  122232. attValue = name[attName];
  122233. this.attribute(attName, attValue);
  122234. }
  122235. } else {
  122236. if (isFunction(value)) {
  122237. value = value.apply();
  122238. }
  122239. if (this.options.keepNullAttributes && (value == null)) {
  122240. this.currentNode.attribs[name] = new XMLAttribute(this, name, "");
  122241. } else if (value != null) {
  122242. this.currentNode.attribs[name] = new XMLAttribute(this, name, value);
  122243. }
  122244. }
  122245. return this;
  122246. };
  122247. XMLDocumentCB.prototype.text = function(value) {
  122248. var node;
  122249. this.openCurrent();
  122250. node = new XMLText(this, value);
  122251. this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122252. return this;
  122253. };
  122254. XMLDocumentCB.prototype.cdata = function(value) {
  122255. var node;
  122256. this.openCurrent();
  122257. node = new XMLCData(this, value);
  122258. this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122259. return this;
  122260. };
  122261. XMLDocumentCB.prototype.comment = function(value) {
  122262. var node;
  122263. this.openCurrent();
  122264. node = new XMLComment(this, value);
  122265. this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122266. return this;
  122267. };
  122268. XMLDocumentCB.prototype.raw = function(value) {
  122269. var node;
  122270. this.openCurrent();
  122271. node = new XMLRaw(this, value);
  122272. this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122273. return this;
  122274. };
  122275. XMLDocumentCB.prototype.instruction = function(target, value) {
  122276. var i, insTarget, insValue, len, node;
  122277. this.openCurrent();
  122278. if (target != null) {
  122279. target = getValue(target);
  122280. }
  122281. if (value != null) {
  122282. value = getValue(value);
  122283. }
  122284. if (Array.isArray(target)) {
  122285. for (i = 0, len = target.length; i < len; i++) {
  122286. insTarget = target[i];
  122287. this.instruction(insTarget);
  122288. }
  122289. } else if (isObject(target)) {
  122290. for (insTarget in target) {
  122291. if (!hasProp.call(target, insTarget)) continue;
  122292. insValue = target[insTarget];
  122293. this.instruction(insTarget, insValue);
  122294. }
  122295. } else {
  122296. if (isFunction(value)) {
  122297. value = value.apply();
  122298. }
  122299. node = new XMLProcessingInstruction(this, target, value);
  122300. this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122301. }
  122302. return this;
  122303. };
  122304. XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) {
  122305. var node;
  122306. this.openCurrent();
  122307. if (this.documentStarted) {
  122308. throw new Error("declaration() must be the first node.");
  122309. }
  122310. node = new XMLDeclaration(this, version, encoding, standalone);
  122311. this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122312. return this;
  122313. };
  122314. XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) {
  122315. this.openCurrent();
  122316. if (root == null) {
  122317. throw new Error("Missing root node name.");
  122318. }
  122319. if (this.root) {
  122320. throw new Error("dtd() must come before the root node.");
  122321. }
  122322. this.currentNode = new XMLDocType(this, pubID, sysID);
  122323. this.currentNode.rootNodeName = root;
  122324. this.currentNode.children = false;
  122325. this.currentLevel++;
  122326. this.openTags[this.currentLevel] = this.currentNode;
  122327. return this;
  122328. };
  122329. XMLDocumentCB.prototype.dtdElement = function(name, value) {
  122330. var node;
  122331. this.openCurrent();
  122332. node = new XMLDTDElement(this, name, value);
  122333. this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122334. return this;
  122335. };
  122336. XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  122337. var node;
  122338. this.openCurrent();
  122339. node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
  122340. this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122341. return this;
  122342. };
  122343. XMLDocumentCB.prototype.entity = function(name, value) {
  122344. var node;
  122345. this.openCurrent();
  122346. node = new XMLDTDEntity(this, false, name, value);
  122347. this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122348. return this;
  122349. };
  122350. XMLDocumentCB.prototype.pEntity = function(name, value) {
  122351. var node;
  122352. this.openCurrent();
  122353. node = new XMLDTDEntity(this, true, name, value);
  122354. this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122355. return this;
  122356. };
  122357. XMLDocumentCB.prototype.notation = function(name, value) {
  122358. var node;
  122359. this.openCurrent();
  122360. node = new XMLDTDNotation(this, name, value);
  122361. this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
  122362. return this;
  122363. };
  122364. XMLDocumentCB.prototype.up = function() {
  122365. if (this.currentLevel < 0) {
  122366. throw new Error("The document node has no parent.");
  122367. }
  122368. if (this.currentNode) {
  122369. if (this.currentNode.children) {
  122370. this.closeNode(this.currentNode);
  122371. } else {
  122372. this.openNode(this.currentNode);
  122373. }
  122374. this.currentNode = null;
  122375. } else {
  122376. this.closeNode(this.openTags[this.currentLevel]);
  122377. }
  122378. delete this.openTags[this.currentLevel];
  122379. this.currentLevel--;
  122380. return this;
  122381. };
  122382. XMLDocumentCB.prototype.end = function() {
  122383. while (this.currentLevel >= 0) {
  122384. this.up();
  122385. }
  122386. return this.onEnd();
  122387. };
  122388. XMLDocumentCB.prototype.openCurrent = function() {
  122389. if (this.currentNode) {
  122390. this.currentNode.children = true;
  122391. return this.openNode(this.currentNode);
  122392. }
  122393. };
  122394. XMLDocumentCB.prototype.openNode = function(node) {
  122395. var att, chunk, name, ref1;
  122396. if (!node.isOpen) {
  122397. if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) {
  122398. this.root = node;
  122399. }
  122400. chunk = '';
  122401. if (node.type === NodeType.Element) {
  122402. this.writerOptions.state = WriterState.OpenTag;
  122403. chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<' + node.name;
  122404. ref1 = node.attribs;
  122405. for (name in ref1) {
  122406. if (!hasProp.call(ref1, name)) continue;
  122407. att = ref1[name];
  122408. chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel);
  122409. }
  122410. chunk += (node.children ? '>' : '/>') + this.writer.endline(node, this.writerOptions, this.currentLevel);
  122411. this.writerOptions.state = WriterState.InsideTag;
  122412. } else {
  122413. this.writerOptions.state = WriterState.OpenTag;
  122414. chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<!DOCTYPE ' + node.rootNodeName;
  122415. if (node.pubID && node.sysID) {
  122416. chunk += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  122417. } else if (node.sysID) {
  122418. chunk += ' SYSTEM "' + node.sysID + '"';
  122419. }
  122420. if (node.children) {
  122421. chunk += ' [';
  122422. this.writerOptions.state = WriterState.InsideTag;
  122423. } else {
  122424. this.writerOptions.state = WriterState.CloseTag;
  122425. chunk += '>';
  122426. }
  122427. chunk += this.writer.endline(node, this.writerOptions, this.currentLevel);
  122428. }
  122429. this.onData(chunk, this.currentLevel);
  122430. return node.isOpen = true;
  122431. }
  122432. };
  122433. XMLDocumentCB.prototype.closeNode = function(node) {
  122434. var chunk;
  122435. if (!node.isClosed) {
  122436. chunk = '';
  122437. this.writerOptions.state = WriterState.CloseTag;
  122438. if (node.type === NodeType.Element) {
  122439. chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '</' + node.name + '>' + this.writer.endline(node, this.writerOptions, this.currentLevel);
  122440. } else {
  122441. chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ']>' + this.writer.endline(node, this.writerOptions, this.currentLevel);
  122442. }
  122443. this.writerOptions.state = WriterState.None;
  122444. this.onData(chunk, this.currentLevel);
  122445. return node.isClosed = true;
  122446. }
  122447. };
  122448. XMLDocumentCB.prototype.onData = function(chunk, level) {
  122449. this.documentStarted = true;
  122450. return this.onDataCallback(chunk, level + 1);
  122451. };
  122452. XMLDocumentCB.prototype.onEnd = function() {
  122453. this.documentCompleted = true;
  122454. return this.onEndCallback();
  122455. };
  122456. XMLDocumentCB.prototype.debugInfo = function(name) {
  122457. if (name == null) {
  122458. return "";
  122459. } else {
  122460. return "node: <" + name + ">";
  122461. }
  122462. };
  122463. XMLDocumentCB.prototype.ele = function() {
  122464. return this.element.apply(this, arguments);
  122465. };
  122466. XMLDocumentCB.prototype.nod = function(name, attributes, text) {
  122467. return this.node(name, attributes, text);
  122468. };
  122469. XMLDocumentCB.prototype.txt = function(value) {
  122470. return this.text(value);
  122471. };
  122472. XMLDocumentCB.prototype.dat = function(value) {
  122473. return this.cdata(value);
  122474. };
  122475. XMLDocumentCB.prototype.com = function(value) {
  122476. return this.comment(value);
  122477. };
  122478. XMLDocumentCB.prototype.ins = function(target, value) {
  122479. return this.instruction(target, value);
  122480. };
  122481. XMLDocumentCB.prototype.dec = function(version, encoding, standalone) {
  122482. return this.declaration(version, encoding, standalone);
  122483. };
  122484. XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) {
  122485. return this.doctype(root, pubID, sysID);
  122486. };
  122487. XMLDocumentCB.prototype.e = function(name, attributes, text) {
  122488. return this.element(name, attributes, text);
  122489. };
  122490. XMLDocumentCB.prototype.n = function(name, attributes, text) {
  122491. return this.node(name, attributes, text);
  122492. };
  122493. XMLDocumentCB.prototype.t = function(value) {
  122494. return this.text(value);
  122495. };
  122496. XMLDocumentCB.prototype.d = function(value) {
  122497. return this.cdata(value);
  122498. };
  122499. XMLDocumentCB.prototype.c = function(value) {
  122500. return this.comment(value);
  122501. };
  122502. XMLDocumentCB.prototype.r = function(value) {
  122503. return this.raw(value);
  122504. };
  122505. XMLDocumentCB.prototype.i = function(target, value) {
  122506. return this.instruction(target, value);
  122507. };
  122508. XMLDocumentCB.prototype.att = function() {
  122509. if (this.currentNode && this.currentNode.type === NodeType.DocType) {
  122510. return this.attList.apply(this, arguments);
  122511. } else {
  122512. return this.attribute.apply(this, arguments);
  122513. }
  122514. };
  122515. XMLDocumentCB.prototype.a = function() {
  122516. if (this.currentNode && this.currentNode.type === NodeType.DocType) {
  122517. return this.attList.apply(this, arguments);
  122518. } else {
  122519. return this.attribute.apply(this, arguments);
  122520. }
  122521. };
  122522. XMLDocumentCB.prototype.ent = function(name, value) {
  122523. return this.entity(name, value);
  122524. };
  122525. XMLDocumentCB.prototype.pent = function(name, value) {
  122526. return this.pEntity(name, value);
  122527. };
  122528. XMLDocumentCB.prototype.not = function(name, value) {
  122529. return this.notation(name, value);
  122530. };
  122531. return XMLDocumentCB;
  122532. })();
  122533. }).call(this);
  122534. },{"./NodeType":673,"./Utility":674,"./WriterState":675,"./XMLAttribute":676,"./XMLCData":677,"./XMLComment":679,"./XMLDTDAttList":684,"./XMLDTDElement":685,"./XMLDTDEntity":686,"./XMLDTDNotation":687,"./XMLDeclaration":688,"./XMLDocType":689,"./XMLDocument":690,"./XMLElement":693,"./XMLProcessingInstruction":697,"./XMLRaw":698,"./XMLStringWriter":700,"./XMLStringifier":701,"./XMLText":702}],692:[function(require,module,exports){
  122535. // Generated by CoffeeScript 1.12.7
  122536. (function() {
  122537. var NodeType, XMLDummy, XMLNode,
  122538. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  122539. hasProp = {}.hasOwnProperty;
  122540. XMLNode = require('./XMLNode');
  122541. NodeType = require('./NodeType');
  122542. module.exports = XMLDummy = (function(superClass) {
  122543. extend(XMLDummy, superClass);
  122544. function XMLDummy(parent) {
  122545. XMLDummy.__super__.constructor.call(this, parent);
  122546. this.type = NodeType.Dummy;
  122547. }
  122548. XMLDummy.prototype.clone = function() {
  122549. return Object.create(this);
  122550. };
  122551. XMLDummy.prototype.toString = function(options) {
  122552. return '';
  122553. };
  122554. return XMLDummy;
  122555. })(XMLNode);
  122556. }).call(this);
  122557. },{"./NodeType":673,"./XMLNode":695}],693:[function(require,module,exports){
  122558. // Generated by CoffeeScript 1.12.7
  122559. (function() {
  122560. var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref,
  122561. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  122562. hasProp = {}.hasOwnProperty;
  122563. ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue;
  122564. XMLNode = require('./XMLNode');
  122565. NodeType = require('./NodeType');
  122566. XMLAttribute = require('./XMLAttribute');
  122567. XMLNamedNodeMap = require('./XMLNamedNodeMap');
  122568. module.exports = XMLElement = (function(superClass) {
  122569. extend(XMLElement, superClass);
  122570. function XMLElement(parent, name, attributes) {
  122571. var child, j, len, ref1;
  122572. XMLElement.__super__.constructor.call(this, parent);
  122573. if (name == null) {
  122574. throw new Error("Missing element name. " + this.debugInfo());
  122575. }
  122576. this.name = this.stringify.name(name);
  122577. this.type = NodeType.Element;
  122578. this.attribs = {};
  122579. this.schemaTypeInfo = null;
  122580. if (attributes != null) {
  122581. this.attribute(attributes);
  122582. }
  122583. if (parent.type === NodeType.Document) {
  122584. this.isRoot = true;
  122585. this.documentObject = parent;
  122586. parent.rootObject = this;
  122587. if (parent.children) {
  122588. ref1 = parent.children;
  122589. for (j = 0, len = ref1.length; j < len; j++) {
  122590. child = ref1[j];
  122591. if (child.type === NodeType.DocType) {
  122592. child.name = this.name;
  122593. break;
  122594. }
  122595. }
  122596. }
  122597. }
  122598. }
  122599. Object.defineProperty(XMLElement.prototype, 'tagName', {
  122600. get: function() {
  122601. return this.name;
  122602. }
  122603. });
  122604. Object.defineProperty(XMLElement.prototype, 'namespaceURI', {
  122605. get: function() {
  122606. return '';
  122607. }
  122608. });
  122609. Object.defineProperty(XMLElement.prototype, 'prefix', {
  122610. get: function() {
  122611. return '';
  122612. }
  122613. });
  122614. Object.defineProperty(XMLElement.prototype, 'localName', {
  122615. get: function() {
  122616. return this.name;
  122617. }
  122618. });
  122619. Object.defineProperty(XMLElement.prototype, 'id', {
  122620. get: function() {
  122621. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122622. }
  122623. });
  122624. Object.defineProperty(XMLElement.prototype, 'className', {
  122625. get: function() {
  122626. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122627. }
  122628. });
  122629. Object.defineProperty(XMLElement.prototype, 'classList', {
  122630. get: function() {
  122631. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122632. }
  122633. });
  122634. Object.defineProperty(XMLElement.prototype, 'attributes', {
  122635. get: function() {
  122636. if (!this.attributeMap || !this.attributeMap.nodes) {
  122637. this.attributeMap = new XMLNamedNodeMap(this.attribs);
  122638. }
  122639. return this.attributeMap;
  122640. }
  122641. });
  122642. XMLElement.prototype.clone = function() {
  122643. var att, attName, clonedSelf, ref1;
  122644. clonedSelf = Object.create(this);
  122645. if (clonedSelf.isRoot) {
  122646. clonedSelf.documentObject = null;
  122647. }
  122648. clonedSelf.attribs = {};
  122649. ref1 = this.attribs;
  122650. for (attName in ref1) {
  122651. if (!hasProp.call(ref1, attName)) continue;
  122652. att = ref1[attName];
  122653. clonedSelf.attribs[attName] = att.clone();
  122654. }
  122655. clonedSelf.children = [];
  122656. this.children.forEach(function(child) {
  122657. var clonedChild;
  122658. clonedChild = child.clone();
  122659. clonedChild.parent = clonedSelf;
  122660. return clonedSelf.children.push(clonedChild);
  122661. });
  122662. return clonedSelf;
  122663. };
  122664. XMLElement.prototype.attribute = function(name, value) {
  122665. var attName, attValue;
  122666. if (name != null) {
  122667. name = getValue(name);
  122668. }
  122669. if (isObject(name)) {
  122670. for (attName in name) {
  122671. if (!hasProp.call(name, attName)) continue;
  122672. attValue = name[attName];
  122673. this.attribute(attName, attValue);
  122674. }
  122675. } else {
  122676. if (isFunction(value)) {
  122677. value = value.apply();
  122678. }
  122679. if (this.options.keepNullAttributes && (value == null)) {
  122680. this.attribs[name] = new XMLAttribute(this, name, "");
  122681. } else if (value != null) {
  122682. this.attribs[name] = new XMLAttribute(this, name, value);
  122683. }
  122684. }
  122685. return this;
  122686. };
  122687. XMLElement.prototype.removeAttribute = function(name) {
  122688. var attName, j, len;
  122689. if (name == null) {
  122690. throw new Error("Missing attribute name. " + this.debugInfo());
  122691. }
  122692. name = getValue(name);
  122693. if (Array.isArray(name)) {
  122694. for (j = 0, len = name.length; j < len; j++) {
  122695. attName = name[j];
  122696. delete this.attribs[attName];
  122697. }
  122698. } else {
  122699. delete this.attribs[name];
  122700. }
  122701. return this;
  122702. };
  122703. XMLElement.prototype.toString = function(options) {
  122704. return this.options.writer.element(this, this.options.writer.filterOptions(options));
  122705. };
  122706. XMLElement.prototype.att = function(name, value) {
  122707. return this.attribute(name, value);
  122708. };
  122709. XMLElement.prototype.a = function(name, value) {
  122710. return this.attribute(name, value);
  122711. };
  122712. XMLElement.prototype.getAttribute = function(name) {
  122713. if (this.attribs.hasOwnProperty(name)) {
  122714. return this.attribs[name].value;
  122715. } else {
  122716. return null;
  122717. }
  122718. };
  122719. XMLElement.prototype.setAttribute = function(name, value) {
  122720. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122721. };
  122722. XMLElement.prototype.getAttributeNode = function(name) {
  122723. if (this.attribs.hasOwnProperty(name)) {
  122724. return this.attribs[name];
  122725. } else {
  122726. return null;
  122727. }
  122728. };
  122729. XMLElement.prototype.setAttributeNode = function(newAttr) {
  122730. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122731. };
  122732. XMLElement.prototype.removeAttributeNode = function(oldAttr) {
  122733. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122734. };
  122735. XMLElement.prototype.getElementsByTagName = function(name) {
  122736. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122737. };
  122738. XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) {
  122739. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122740. };
  122741. XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) {
  122742. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122743. };
  122744. XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) {
  122745. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122746. };
  122747. XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) {
  122748. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122749. };
  122750. XMLElement.prototype.setAttributeNodeNS = function(newAttr) {
  122751. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122752. };
  122753. XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {
  122754. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122755. };
  122756. XMLElement.prototype.hasAttribute = function(name) {
  122757. return this.attribs.hasOwnProperty(name);
  122758. };
  122759. XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) {
  122760. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122761. };
  122762. XMLElement.prototype.setIdAttribute = function(name, isId) {
  122763. if (this.attribs.hasOwnProperty(name)) {
  122764. return this.attribs[name].isId;
  122765. } else {
  122766. return isId;
  122767. }
  122768. };
  122769. XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) {
  122770. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122771. };
  122772. XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) {
  122773. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122774. };
  122775. XMLElement.prototype.getElementsByTagName = function(tagname) {
  122776. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122777. };
  122778. XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {
  122779. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122780. };
  122781. XMLElement.prototype.getElementsByClassName = function(classNames) {
  122782. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122783. };
  122784. XMLElement.prototype.isEqualNode = function(node) {
  122785. var i, j, ref1;
  122786. if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
  122787. return false;
  122788. }
  122789. if (node.namespaceURI !== this.namespaceURI) {
  122790. return false;
  122791. }
  122792. if (node.prefix !== this.prefix) {
  122793. return false;
  122794. }
  122795. if (node.localName !== this.localName) {
  122796. return false;
  122797. }
  122798. if (node.attribs.length !== this.attribs.length) {
  122799. return false;
  122800. }
  122801. for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) {
  122802. if (!this.attribs[i].isEqualNode(node.attribs[i])) {
  122803. return false;
  122804. }
  122805. }
  122806. return true;
  122807. };
  122808. return XMLElement;
  122809. })(XMLNode);
  122810. }).call(this);
  122811. },{"./NodeType":673,"./Utility":674,"./XMLAttribute":676,"./XMLNamedNodeMap":694,"./XMLNode":695}],694:[function(require,module,exports){
  122812. // Generated by CoffeeScript 1.12.7
  122813. (function() {
  122814. var XMLNamedNodeMap;
  122815. module.exports = XMLNamedNodeMap = (function() {
  122816. function XMLNamedNodeMap(nodes) {
  122817. this.nodes = nodes;
  122818. }
  122819. Object.defineProperty(XMLNamedNodeMap.prototype, 'length', {
  122820. get: function() {
  122821. return Object.keys(this.nodes).length || 0;
  122822. }
  122823. });
  122824. XMLNamedNodeMap.prototype.clone = function() {
  122825. return this.nodes = null;
  122826. };
  122827. XMLNamedNodeMap.prototype.getNamedItem = function(name) {
  122828. return this.nodes[name];
  122829. };
  122830. XMLNamedNodeMap.prototype.setNamedItem = function(node) {
  122831. var oldNode;
  122832. oldNode = this.nodes[node.nodeName];
  122833. this.nodes[node.nodeName] = node;
  122834. return oldNode || null;
  122835. };
  122836. XMLNamedNodeMap.prototype.removeNamedItem = function(name) {
  122837. var oldNode;
  122838. oldNode = this.nodes[name];
  122839. delete this.nodes[name];
  122840. return oldNode || null;
  122841. };
  122842. XMLNamedNodeMap.prototype.item = function(index) {
  122843. return this.nodes[Object.keys(this.nodes)[index]] || null;
  122844. };
  122845. XMLNamedNodeMap.prototype.getNamedItemNS = function(namespaceURI, localName) {
  122846. throw new Error("This DOM method is not implemented.");
  122847. };
  122848. XMLNamedNodeMap.prototype.setNamedItemNS = function(node) {
  122849. throw new Error("This DOM method is not implemented.");
  122850. };
  122851. XMLNamedNodeMap.prototype.removeNamedItemNS = function(namespaceURI, localName) {
  122852. throw new Error("This DOM method is not implemented.");
  122853. };
  122854. return XMLNamedNodeMap;
  122855. })();
  122856. }).call(this);
  122857. },{}],695:[function(require,module,exports){
  122858. // Generated by CoffeeScript 1.12.7
  122859. (function() {
  122860. var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNamedNodeMap, XMLNode, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref1,
  122861. hasProp = {}.hasOwnProperty;
  122862. ref1 = require('./Utility'), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue;
  122863. XMLElement = null;
  122864. XMLCData = null;
  122865. XMLComment = null;
  122866. XMLDeclaration = null;
  122867. XMLDocType = null;
  122868. XMLRaw = null;
  122869. XMLText = null;
  122870. XMLProcessingInstruction = null;
  122871. XMLDummy = null;
  122872. NodeType = null;
  122873. XMLNodeList = null;
  122874. XMLNamedNodeMap = null;
  122875. DocumentPosition = null;
  122876. module.exports = XMLNode = (function() {
  122877. function XMLNode(parent1) {
  122878. this.parent = parent1;
  122879. if (this.parent) {
  122880. this.options = this.parent.options;
  122881. this.stringify = this.parent.stringify;
  122882. }
  122883. this.value = null;
  122884. this.children = [];
  122885. this.baseURI = null;
  122886. if (!XMLElement) {
  122887. XMLElement = require('./XMLElement');
  122888. XMLCData = require('./XMLCData');
  122889. XMLComment = require('./XMLComment');
  122890. XMLDeclaration = require('./XMLDeclaration');
  122891. XMLDocType = require('./XMLDocType');
  122892. XMLRaw = require('./XMLRaw');
  122893. XMLText = require('./XMLText');
  122894. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  122895. XMLDummy = require('./XMLDummy');
  122896. NodeType = require('./NodeType');
  122897. XMLNodeList = require('./XMLNodeList');
  122898. XMLNamedNodeMap = require('./XMLNamedNodeMap');
  122899. DocumentPosition = require('./DocumentPosition');
  122900. }
  122901. }
  122902. Object.defineProperty(XMLNode.prototype, 'nodeName', {
  122903. get: function() {
  122904. return this.name;
  122905. }
  122906. });
  122907. Object.defineProperty(XMLNode.prototype, 'nodeType', {
  122908. get: function() {
  122909. return this.type;
  122910. }
  122911. });
  122912. Object.defineProperty(XMLNode.prototype, 'nodeValue', {
  122913. get: function() {
  122914. return this.value;
  122915. }
  122916. });
  122917. Object.defineProperty(XMLNode.prototype, 'parentNode', {
  122918. get: function() {
  122919. return this.parent;
  122920. }
  122921. });
  122922. Object.defineProperty(XMLNode.prototype, 'childNodes', {
  122923. get: function() {
  122924. if (!this.childNodeList || !this.childNodeList.nodes) {
  122925. this.childNodeList = new XMLNodeList(this.children);
  122926. }
  122927. return this.childNodeList;
  122928. }
  122929. });
  122930. Object.defineProperty(XMLNode.prototype, 'firstChild', {
  122931. get: function() {
  122932. return this.children[0] || null;
  122933. }
  122934. });
  122935. Object.defineProperty(XMLNode.prototype, 'lastChild', {
  122936. get: function() {
  122937. return this.children[this.children.length - 1] || null;
  122938. }
  122939. });
  122940. Object.defineProperty(XMLNode.prototype, 'previousSibling', {
  122941. get: function() {
  122942. var i;
  122943. i = this.parent.children.indexOf(this);
  122944. return this.parent.children[i - 1] || null;
  122945. }
  122946. });
  122947. Object.defineProperty(XMLNode.prototype, 'nextSibling', {
  122948. get: function() {
  122949. var i;
  122950. i = this.parent.children.indexOf(this);
  122951. return this.parent.children[i + 1] || null;
  122952. }
  122953. });
  122954. Object.defineProperty(XMLNode.prototype, 'ownerDocument', {
  122955. get: function() {
  122956. return this.document() || null;
  122957. }
  122958. });
  122959. Object.defineProperty(XMLNode.prototype, 'textContent', {
  122960. get: function() {
  122961. var child, j, len, ref2, str;
  122962. if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) {
  122963. str = '';
  122964. ref2 = this.children;
  122965. for (j = 0, len = ref2.length; j < len; j++) {
  122966. child = ref2[j];
  122967. if (child.textContent) {
  122968. str += child.textContent;
  122969. }
  122970. }
  122971. return str;
  122972. } else {
  122973. return null;
  122974. }
  122975. },
  122976. set: function(value) {
  122977. throw new Error("This DOM method is not implemented." + this.debugInfo());
  122978. }
  122979. });
  122980. XMLNode.prototype.setParent = function(parent) {
  122981. var child, j, len, ref2, results;
  122982. this.parent = parent;
  122983. if (parent) {
  122984. this.options = parent.options;
  122985. this.stringify = parent.stringify;
  122986. }
  122987. ref2 = this.children;
  122988. results = [];
  122989. for (j = 0, len = ref2.length; j < len; j++) {
  122990. child = ref2[j];
  122991. results.push(child.setParent(this));
  122992. }
  122993. return results;
  122994. };
  122995. XMLNode.prototype.element = function(name, attributes, text) {
  122996. var childNode, item, j, k, key, lastChild, len, len1, ref2, ref3, val;
  122997. lastChild = null;
  122998. if (attributes === null && (text == null)) {
  122999. ref2 = [{}, null], attributes = ref2[0], text = ref2[1];
  123000. }
  123001. if (attributes == null) {
  123002. attributes = {};
  123003. }
  123004. attributes = getValue(attributes);
  123005. if (!isObject(attributes)) {
  123006. ref3 = [attributes, text], text = ref3[0], attributes = ref3[1];
  123007. }
  123008. if (name != null) {
  123009. name = getValue(name);
  123010. }
  123011. if (Array.isArray(name)) {
  123012. for (j = 0, len = name.length; j < len; j++) {
  123013. item = name[j];
  123014. lastChild = this.element(item);
  123015. }
  123016. } else if (isFunction(name)) {
  123017. lastChild = this.element(name.apply());
  123018. } else if (isObject(name)) {
  123019. for (key in name) {
  123020. if (!hasProp.call(name, key)) continue;
  123021. val = name[key];
  123022. if (isFunction(val)) {
  123023. val = val.apply();
  123024. }
  123025. if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
  123026. lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
  123027. } else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) {
  123028. lastChild = this.dummy();
  123029. } else if (isObject(val) && isEmpty(val)) {
  123030. lastChild = this.element(key);
  123031. } else if (!this.options.keepNullNodes && (val == null)) {
  123032. lastChild = this.dummy();
  123033. } else if (!this.options.separateArrayItems && Array.isArray(val)) {
  123034. for (k = 0, len1 = val.length; k < len1; k++) {
  123035. item = val[k];
  123036. childNode = {};
  123037. childNode[key] = item;
  123038. lastChild = this.element(childNode);
  123039. }
  123040. } else if (isObject(val)) {
  123041. if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) {
  123042. lastChild = this.element(val);
  123043. } else {
  123044. lastChild = this.element(key);
  123045. lastChild.element(val);
  123046. }
  123047. } else {
  123048. lastChild = this.element(key, val);
  123049. }
  123050. }
  123051. } else if (!this.options.keepNullNodes && text === null) {
  123052. lastChild = this.dummy();
  123053. } else {
  123054. if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
  123055. lastChild = this.text(text);
  123056. } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
  123057. lastChild = this.cdata(text);
  123058. } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
  123059. lastChild = this.comment(text);
  123060. } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
  123061. lastChild = this.raw(text);
  123062. } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) {
  123063. lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text);
  123064. } else {
  123065. lastChild = this.node(name, attributes, text);
  123066. }
  123067. }
  123068. if (lastChild == null) {
  123069. throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo());
  123070. }
  123071. return lastChild;
  123072. };
  123073. XMLNode.prototype.insertBefore = function(name, attributes, text) {
  123074. var child, i, newChild, refChild, removed;
  123075. if (name != null ? name.type : void 0) {
  123076. newChild = name;
  123077. refChild = attributes;
  123078. newChild.setParent(this);
  123079. if (refChild) {
  123080. i = children.indexOf(refChild);
  123081. removed = children.splice(i);
  123082. children.push(newChild);
  123083. Array.prototype.push.apply(children, removed);
  123084. } else {
  123085. children.push(newChild);
  123086. }
  123087. return newChild;
  123088. } else {
  123089. if (this.isRoot) {
  123090. throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
  123091. }
  123092. i = this.parent.children.indexOf(this);
  123093. removed = this.parent.children.splice(i);
  123094. child = this.parent.element(name, attributes, text);
  123095. Array.prototype.push.apply(this.parent.children, removed);
  123096. return child;
  123097. }
  123098. };
  123099. XMLNode.prototype.insertAfter = function(name, attributes, text) {
  123100. var child, i, removed;
  123101. if (this.isRoot) {
  123102. throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
  123103. }
  123104. i = this.parent.children.indexOf(this);
  123105. removed = this.parent.children.splice(i + 1);
  123106. child = this.parent.element(name, attributes, text);
  123107. Array.prototype.push.apply(this.parent.children, removed);
  123108. return child;
  123109. };
  123110. XMLNode.prototype.remove = function() {
  123111. var i, ref2;
  123112. if (this.isRoot) {
  123113. throw new Error("Cannot remove the root element. " + this.debugInfo());
  123114. }
  123115. i = this.parent.children.indexOf(this);
  123116. [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref2 = [])), ref2;
  123117. return this.parent;
  123118. };
  123119. XMLNode.prototype.node = function(name, attributes, text) {
  123120. var child, ref2;
  123121. if (name != null) {
  123122. name = getValue(name);
  123123. }
  123124. attributes || (attributes = {});
  123125. attributes = getValue(attributes);
  123126. if (!isObject(attributes)) {
  123127. ref2 = [attributes, text], text = ref2[0], attributes = ref2[1];
  123128. }
  123129. child = new XMLElement(this, name, attributes);
  123130. if (text != null) {
  123131. child.text(text);
  123132. }
  123133. this.children.push(child);
  123134. return child;
  123135. };
  123136. XMLNode.prototype.text = function(value) {
  123137. var child;
  123138. if (isObject(value)) {
  123139. this.element(value);
  123140. }
  123141. child = new XMLText(this, value);
  123142. this.children.push(child);
  123143. return this;
  123144. };
  123145. XMLNode.prototype.cdata = function(value) {
  123146. var child;
  123147. child = new XMLCData(this, value);
  123148. this.children.push(child);
  123149. return this;
  123150. };
  123151. XMLNode.prototype.comment = function(value) {
  123152. var child;
  123153. child = new XMLComment(this, value);
  123154. this.children.push(child);
  123155. return this;
  123156. };
  123157. XMLNode.prototype.commentBefore = function(value) {
  123158. var child, i, removed;
  123159. i = this.parent.children.indexOf(this);
  123160. removed = this.parent.children.splice(i);
  123161. child = this.parent.comment(value);
  123162. Array.prototype.push.apply(this.parent.children, removed);
  123163. return this;
  123164. };
  123165. XMLNode.prototype.commentAfter = function(value) {
  123166. var child, i, removed;
  123167. i = this.parent.children.indexOf(this);
  123168. removed = this.parent.children.splice(i + 1);
  123169. child = this.parent.comment(value);
  123170. Array.prototype.push.apply(this.parent.children, removed);
  123171. return this;
  123172. };
  123173. XMLNode.prototype.raw = function(value) {
  123174. var child;
  123175. child = new XMLRaw(this, value);
  123176. this.children.push(child);
  123177. return this;
  123178. };
  123179. XMLNode.prototype.dummy = function() {
  123180. var child;
  123181. child = new XMLDummy(this);
  123182. return child;
  123183. };
  123184. XMLNode.prototype.instruction = function(target, value) {
  123185. var insTarget, insValue, instruction, j, len;
  123186. if (target != null) {
  123187. target = getValue(target);
  123188. }
  123189. if (value != null) {
  123190. value = getValue(value);
  123191. }
  123192. if (Array.isArray(target)) {
  123193. for (j = 0, len = target.length; j < len; j++) {
  123194. insTarget = target[j];
  123195. this.instruction(insTarget);
  123196. }
  123197. } else if (isObject(target)) {
  123198. for (insTarget in target) {
  123199. if (!hasProp.call(target, insTarget)) continue;
  123200. insValue = target[insTarget];
  123201. this.instruction(insTarget, insValue);
  123202. }
  123203. } else {
  123204. if (isFunction(value)) {
  123205. value = value.apply();
  123206. }
  123207. instruction = new XMLProcessingInstruction(this, target, value);
  123208. this.children.push(instruction);
  123209. }
  123210. return this;
  123211. };
  123212. XMLNode.prototype.instructionBefore = function(target, value) {
  123213. var child, i, removed;
  123214. i = this.parent.children.indexOf(this);
  123215. removed = this.parent.children.splice(i);
  123216. child = this.parent.instruction(target, value);
  123217. Array.prototype.push.apply(this.parent.children, removed);
  123218. return this;
  123219. };
  123220. XMLNode.prototype.instructionAfter = function(target, value) {
  123221. var child, i, removed;
  123222. i = this.parent.children.indexOf(this);
  123223. removed = this.parent.children.splice(i + 1);
  123224. child = this.parent.instruction(target, value);
  123225. Array.prototype.push.apply(this.parent.children, removed);
  123226. return this;
  123227. };
  123228. XMLNode.prototype.declaration = function(version, encoding, standalone) {
  123229. var doc, xmldec;
  123230. doc = this.document();
  123231. xmldec = new XMLDeclaration(doc, version, encoding, standalone);
  123232. if (doc.children.length === 0) {
  123233. doc.children.unshift(xmldec);
  123234. } else if (doc.children[0].type === NodeType.Declaration) {
  123235. doc.children[0] = xmldec;
  123236. } else {
  123237. doc.children.unshift(xmldec);
  123238. }
  123239. return doc.root() || doc;
  123240. };
  123241. XMLNode.prototype.dtd = function(pubID, sysID) {
  123242. var child, doc, doctype, i, j, k, len, len1, ref2, ref3;
  123243. doc = this.document();
  123244. doctype = new XMLDocType(doc, pubID, sysID);
  123245. ref2 = doc.children;
  123246. for (i = j = 0, len = ref2.length; j < len; i = ++j) {
  123247. child = ref2[i];
  123248. if (child.type === NodeType.DocType) {
  123249. doc.children[i] = doctype;
  123250. return doctype;
  123251. }
  123252. }
  123253. ref3 = doc.children;
  123254. for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) {
  123255. child = ref3[i];
  123256. if (child.isRoot) {
  123257. doc.children.splice(i, 0, doctype);
  123258. return doctype;
  123259. }
  123260. }
  123261. doc.children.push(doctype);
  123262. return doctype;
  123263. };
  123264. XMLNode.prototype.up = function() {
  123265. if (this.isRoot) {
  123266. throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
  123267. }
  123268. return this.parent;
  123269. };
  123270. XMLNode.prototype.root = function() {
  123271. var node;
  123272. node = this;
  123273. while (node) {
  123274. if (node.type === NodeType.Document) {
  123275. return node.rootObject;
  123276. } else if (node.isRoot) {
  123277. return node;
  123278. } else {
  123279. node = node.parent;
  123280. }
  123281. }
  123282. };
  123283. XMLNode.prototype.document = function() {
  123284. var node;
  123285. node = this;
  123286. while (node) {
  123287. if (node.type === NodeType.Document) {
  123288. return node;
  123289. } else {
  123290. node = node.parent;
  123291. }
  123292. }
  123293. };
  123294. XMLNode.prototype.end = function(options) {
  123295. return this.document().end(options);
  123296. };
  123297. XMLNode.prototype.prev = function() {
  123298. var i;
  123299. i = this.parent.children.indexOf(this);
  123300. if (i < 1) {
  123301. throw new Error("Already at the first node. " + this.debugInfo());
  123302. }
  123303. return this.parent.children[i - 1];
  123304. };
  123305. XMLNode.prototype.next = function() {
  123306. var i;
  123307. i = this.parent.children.indexOf(this);
  123308. if (i === -1 || i === this.parent.children.length - 1) {
  123309. throw new Error("Already at the last node. " + this.debugInfo());
  123310. }
  123311. return this.parent.children[i + 1];
  123312. };
  123313. XMLNode.prototype.importDocument = function(doc) {
  123314. var clonedRoot;
  123315. clonedRoot = doc.root().clone();
  123316. clonedRoot.parent = this;
  123317. clonedRoot.isRoot = false;
  123318. this.children.push(clonedRoot);
  123319. return this;
  123320. };
  123321. XMLNode.prototype.debugInfo = function(name) {
  123322. var ref2, ref3;
  123323. name = name || this.name;
  123324. if ((name == null) && !((ref2 = this.parent) != null ? ref2.name : void 0)) {
  123325. return "";
  123326. } else if (name == null) {
  123327. return "parent: <" + this.parent.name + ">";
  123328. } else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) {
  123329. return "node: <" + name + ">";
  123330. } else {
  123331. return "node: <" + name + ">, parent: <" + this.parent.name + ">";
  123332. }
  123333. };
  123334. XMLNode.prototype.ele = function(name, attributes, text) {
  123335. return this.element(name, attributes, text);
  123336. };
  123337. XMLNode.prototype.nod = function(name, attributes, text) {
  123338. return this.node(name, attributes, text);
  123339. };
  123340. XMLNode.prototype.txt = function(value) {
  123341. return this.text(value);
  123342. };
  123343. XMLNode.prototype.dat = function(value) {
  123344. return this.cdata(value);
  123345. };
  123346. XMLNode.prototype.com = function(value) {
  123347. return this.comment(value);
  123348. };
  123349. XMLNode.prototype.ins = function(target, value) {
  123350. return this.instruction(target, value);
  123351. };
  123352. XMLNode.prototype.doc = function() {
  123353. return this.document();
  123354. };
  123355. XMLNode.prototype.dec = function(version, encoding, standalone) {
  123356. return this.declaration(version, encoding, standalone);
  123357. };
  123358. XMLNode.prototype.e = function(name, attributes, text) {
  123359. return this.element(name, attributes, text);
  123360. };
  123361. XMLNode.prototype.n = function(name, attributes, text) {
  123362. return this.node(name, attributes, text);
  123363. };
  123364. XMLNode.prototype.t = function(value) {
  123365. return this.text(value);
  123366. };
  123367. XMLNode.prototype.d = function(value) {
  123368. return this.cdata(value);
  123369. };
  123370. XMLNode.prototype.c = function(value) {
  123371. return this.comment(value);
  123372. };
  123373. XMLNode.prototype.r = function(value) {
  123374. return this.raw(value);
  123375. };
  123376. XMLNode.prototype.i = function(target, value) {
  123377. return this.instruction(target, value);
  123378. };
  123379. XMLNode.prototype.u = function() {
  123380. return this.up();
  123381. };
  123382. XMLNode.prototype.importXMLBuilder = function(doc) {
  123383. return this.importDocument(doc);
  123384. };
  123385. XMLNode.prototype.replaceChild = function(newChild, oldChild) {
  123386. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123387. };
  123388. XMLNode.prototype.removeChild = function(oldChild) {
  123389. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123390. };
  123391. XMLNode.prototype.appendChild = function(newChild) {
  123392. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123393. };
  123394. XMLNode.prototype.hasChildNodes = function() {
  123395. return this.children.length !== 0;
  123396. };
  123397. XMLNode.prototype.cloneNode = function(deep) {
  123398. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123399. };
  123400. XMLNode.prototype.normalize = function() {
  123401. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123402. };
  123403. XMLNode.prototype.isSupported = function(feature, version) {
  123404. return true;
  123405. };
  123406. XMLNode.prototype.hasAttributes = function() {
  123407. return this.attribs.length !== 0;
  123408. };
  123409. XMLNode.prototype.compareDocumentPosition = function(other) {
  123410. var ref, res;
  123411. ref = this;
  123412. if (ref === other) {
  123413. return 0;
  123414. } else if (this.document() !== other.document()) {
  123415. res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific;
  123416. if (Math.random() < 0.5) {
  123417. res |= DocumentPosition.Preceding;
  123418. } else {
  123419. res |= DocumentPosition.Following;
  123420. }
  123421. return res;
  123422. } else if (ref.isAncestor(other)) {
  123423. return DocumentPosition.Contains | DocumentPosition.Preceding;
  123424. } else if (ref.isDescendant(other)) {
  123425. return DocumentPosition.Contains | DocumentPosition.Following;
  123426. } else if (ref.isPreceding(other)) {
  123427. return DocumentPosition.Preceding;
  123428. } else {
  123429. return DocumentPosition.Following;
  123430. }
  123431. };
  123432. XMLNode.prototype.isSameNode = function(other) {
  123433. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123434. };
  123435. XMLNode.prototype.lookupPrefix = function(namespaceURI) {
  123436. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123437. };
  123438. XMLNode.prototype.isDefaultNamespace = function(namespaceURI) {
  123439. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123440. };
  123441. XMLNode.prototype.lookupNamespaceURI = function(prefix) {
  123442. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123443. };
  123444. XMLNode.prototype.isEqualNode = function(node) {
  123445. var i, j, ref2;
  123446. if (node.nodeType !== this.nodeType) {
  123447. return false;
  123448. }
  123449. if (node.children.length !== this.children.length) {
  123450. return false;
  123451. }
  123452. for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) {
  123453. if (!this.children[i].isEqualNode(node.children[i])) {
  123454. return false;
  123455. }
  123456. }
  123457. return true;
  123458. };
  123459. XMLNode.prototype.getFeature = function(feature, version) {
  123460. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123461. };
  123462. XMLNode.prototype.setUserData = function(key, data, handler) {
  123463. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123464. };
  123465. XMLNode.prototype.getUserData = function(key) {
  123466. throw new Error("This DOM method is not implemented." + this.debugInfo());
  123467. };
  123468. XMLNode.prototype.contains = function(other) {
  123469. if (!other) {
  123470. return false;
  123471. }
  123472. return other === this || this.isDescendant(other);
  123473. };
  123474. XMLNode.prototype.isDescendant = function(node) {
  123475. var child, isDescendantChild, j, len, ref2;
  123476. ref2 = this.children;
  123477. for (j = 0, len = ref2.length; j < len; j++) {
  123478. child = ref2[j];
  123479. if (node === child) {
  123480. return true;
  123481. }
  123482. isDescendantChild = child.isDescendant(node);
  123483. if (isDescendantChild) {
  123484. return true;
  123485. }
  123486. }
  123487. return false;
  123488. };
  123489. XMLNode.prototype.isAncestor = function(node) {
  123490. return node.isDescendant(this);
  123491. };
  123492. XMLNode.prototype.isPreceding = function(node) {
  123493. var nodePos, thisPos;
  123494. nodePos = this.treePosition(node);
  123495. thisPos = this.treePosition(this);
  123496. if (nodePos === -1 || thisPos === -1) {
  123497. return false;
  123498. } else {
  123499. return nodePos < thisPos;
  123500. }
  123501. };
  123502. XMLNode.prototype.isFollowing = function(node) {
  123503. var nodePos, thisPos;
  123504. nodePos = this.treePosition(node);
  123505. thisPos = this.treePosition(this);
  123506. if (nodePos === -1 || thisPos === -1) {
  123507. return false;
  123508. } else {
  123509. return nodePos > thisPos;
  123510. }
  123511. };
  123512. XMLNode.prototype.treePosition = function(node) {
  123513. var found, pos;
  123514. pos = 0;
  123515. found = false;
  123516. this.foreachTreeNode(this.document(), function(childNode) {
  123517. pos++;
  123518. if (!found && childNode === node) {
  123519. return found = true;
  123520. }
  123521. });
  123522. if (found) {
  123523. return pos;
  123524. } else {
  123525. return -1;
  123526. }
  123527. };
  123528. XMLNode.prototype.foreachTreeNode = function(node, func) {
  123529. var child, j, len, ref2, res;
  123530. node || (node = this.document());
  123531. ref2 = node.children;
  123532. for (j = 0, len = ref2.length; j < len; j++) {
  123533. child = ref2[j];
  123534. if (res = func(child)) {
  123535. return res;
  123536. } else {
  123537. res = this.foreachTreeNode(child, func);
  123538. if (res) {
  123539. return res;
  123540. }
  123541. }
  123542. }
  123543. };
  123544. return XMLNode;
  123545. })();
  123546. }).call(this);
  123547. },{"./DocumentPosition":672,"./NodeType":673,"./Utility":674,"./XMLCData":677,"./XMLComment":679,"./XMLDeclaration":688,"./XMLDocType":689,"./XMLDummy":692,"./XMLElement":693,"./XMLNamedNodeMap":694,"./XMLNodeList":696,"./XMLProcessingInstruction":697,"./XMLRaw":698,"./XMLText":702}],696:[function(require,module,exports){
  123548. // Generated by CoffeeScript 1.12.7
  123549. (function() {
  123550. var XMLNodeList;
  123551. module.exports = XMLNodeList = (function() {
  123552. function XMLNodeList(nodes) {
  123553. this.nodes = nodes;
  123554. }
  123555. Object.defineProperty(XMLNodeList.prototype, 'length', {
  123556. get: function() {
  123557. return this.nodes.length || 0;
  123558. }
  123559. });
  123560. XMLNodeList.prototype.clone = function() {
  123561. return this.nodes = null;
  123562. };
  123563. XMLNodeList.prototype.item = function(index) {
  123564. return this.nodes[index] || null;
  123565. };
  123566. return XMLNodeList;
  123567. })();
  123568. }).call(this);
  123569. },{}],697:[function(require,module,exports){
  123570. // Generated by CoffeeScript 1.12.7
  123571. (function() {
  123572. var NodeType, XMLCharacterData, XMLProcessingInstruction,
  123573. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  123574. hasProp = {}.hasOwnProperty;
  123575. NodeType = require('./NodeType');
  123576. XMLCharacterData = require('./XMLCharacterData');
  123577. module.exports = XMLProcessingInstruction = (function(superClass) {
  123578. extend(XMLProcessingInstruction, superClass);
  123579. function XMLProcessingInstruction(parent, target, value) {
  123580. XMLProcessingInstruction.__super__.constructor.call(this, parent);
  123581. if (target == null) {
  123582. throw new Error("Missing instruction target. " + this.debugInfo());
  123583. }
  123584. this.type = NodeType.ProcessingInstruction;
  123585. this.target = this.stringify.insTarget(target);
  123586. this.name = this.target;
  123587. if (value) {
  123588. this.value = this.stringify.insValue(value);
  123589. }
  123590. }
  123591. XMLProcessingInstruction.prototype.clone = function() {
  123592. return Object.create(this);
  123593. };
  123594. XMLProcessingInstruction.prototype.toString = function(options) {
  123595. return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options));
  123596. };
  123597. XMLProcessingInstruction.prototype.isEqualNode = function(node) {
  123598. if (!XMLProcessingInstruction.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
  123599. return false;
  123600. }
  123601. if (node.target !== this.target) {
  123602. return false;
  123603. }
  123604. return true;
  123605. };
  123606. return XMLProcessingInstruction;
  123607. })(XMLCharacterData);
  123608. }).call(this);
  123609. },{"./NodeType":673,"./XMLCharacterData":678}],698:[function(require,module,exports){
  123610. // Generated by CoffeeScript 1.12.7
  123611. (function() {
  123612. var NodeType, XMLNode, XMLRaw,
  123613. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  123614. hasProp = {}.hasOwnProperty;
  123615. NodeType = require('./NodeType');
  123616. XMLNode = require('./XMLNode');
  123617. module.exports = XMLRaw = (function(superClass) {
  123618. extend(XMLRaw, superClass);
  123619. function XMLRaw(parent, text) {
  123620. XMLRaw.__super__.constructor.call(this, parent);
  123621. if (text == null) {
  123622. throw new Error("Missing raw text. " + this.debugInfo());
  123623. }
  123624. this.type = NodeType.Raw;
  123625. this.value = this.stringify.raw(text);
  123626. }
  123627. XMLRaw.prototype.clone = function() {
  123628. return Object.create(this);
  123629. };
  123630. XMLRaw.prototype.toString = function(options) {
  123631. return this.options.writer.raw(this, this.options.writer.filterOptions(options));
  123632. };
  123633. return XMLRaw;
  123634. })(XMLNode);
  123635. }).call(this);
  123636. },{"./NodeType":673,"./XMLNode":695}],699:[function(require,module,exports){
  123637. // Generated by CoffeeScript 1.12.7
  123638. (function() {
  123639. var NodeType, WriterState, XMLStreamWriter, XMLWriterBase,
  123640. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  123641. hasProp = {}.hasOwnProperty;
  123642. NodeType = require('./NodeType');
  123643. XMLWriterBase = require('./XMLWriterBase');
  123644. WriterState = require('./WriterState');
  123645. module.exports = XMLStreamWriter = (function(superClass) {
  123646. extend(XMLStreamWriter, superClass);
  123647. function XMLStreamWriter(stream, options) {
  123648. this.stream = stream;
  123649. XMLStreamWriter.__super__.constructor.call(this, options);
  123650. }
  123651. XMLStreamWriter.prototype.endline = function(node, options, level) {
  123652. if (node.isLastRootNode && options.state === WriterState.CloseTag) {
  123653. return '';
  123654. } else {
  123655. return XMLStreamWriter.__super__.endline.call(this, node, options, level);
  123656. }
  123657. };
  123658. XMLStreamWriter.prototype.document = function(doc, options) {
  123659. var child, i, j, k, len, len1, ref, ref1, results;
  123660. ref = doc.children;
  123661. for (i = j = 0, len = ref.length; j < len; i = ++j) {
  123662. child = ref[i];
  123663. child.isLastRootNode = i === doc.children.length - 1;
  123664. }
  123665. options = this.filterOptions(options);
  123666. ref1 = doc.children;
  123667. results = [];
  123668. for (k = 0, len1 = ref1.length; k < len1; k++) {
  123669. child = ref1[k];
  123670. results.push(this.writeChildNode(child, options, 0));
  123671. }
  123672. return results;
  123673. };
  123674. XMLStreamWriter.prototype.attribute = function(att, options, level) {
  123675. return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level));
  123676. };
  123677. XMLStreamWriter.prototype.cdata = function(node, options, level) {
  123678. return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level));
  123679. };
  123680. XMLStreamWriter.prototype.comment = function(node, options, level) {
  123681. return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level));
  123682. };
  123683. XMLStreamWriter.prototype.declaration = function(node, options, level) {
  123684. return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level));
  123685. };
  123686. XMLStreamWriter.prototype.docType = function(node, options, level) {
  123687. var child, j, len, ref;
  123688. level || (level = 0);
  123689. this.openNode(node, options, level);
  123690. options.state = WriterState.OpenTag;
  123691. this.stream.write(this.indent(node, options, level));
  123692. this.stream.write('<!DOCTYPE ' + node.root().name);
  123693. if (node.pubID && node.sysID) {
  123694. this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
  123695. } else if (node.sysID) {
  123696. this.stream.write(' SYSTEM "' + node.sysID + '"');
  123697. }
  123698. if (node.children.length > 0) {
  123699. this.stream.write(' [');
  123700. this.stream.write(this.endline(node, options, level));
  123701. options.state = WriterState.InsideTag;
  123702. ref = node.children;
  123703. for (j = 0, len = ref.length; j < len; j++) {
  123704. child = ref[j];
  123705. this.writeChildNode(child, options, level + 1);
  123706. }
  123707. options.state = WriterState.CloseTag;
  123708. this.stream.write(']');
  123709. }
  123710. options.state = WriterState.CloseTag;
  123711. this.stream.write(options.spaceBeforeSlash + '>');
  123712. this.stream.write(this.endline(node, options, level));
  123713. options.state = WriterState.None;
  123714. return this.closeNode(node, options, level);
  123715. };
  123716. XMLStreamWriter.prototype.element = function(node, options, level) {
  123717. var att, child, childNodeCount, firstChildNode, j, len, name, prettySuppressed, ref, ref1;
  123718. level || (level = 0);
  123719. this.openNode(node, options, level);
  123720. options.state = WriterState.OpenTag;
  123721. this.stream.write(this.indent(node, options, level) + '<' + node.name);
  123722. ref = node.attribs;
  123723. for (name in ref) {
  123724. if (!hasProp.call(ref, name)) continue;
  123725. att = ref[name];
  123726. this.attribute(att, options, level);
  123727. }
  123728. childNodeCount = node.children.length;
  123729. firstChildNode = childNodeCount === 0 ? null : node.children[0];
  123730. if (childNodeCount === 0 || node.children.every(function(e) {
  123731. return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === '';
  123732. })) {
  123733. if (options.allowEmpty) {
  123734. this.stream.write('>');
  123735. options.state = WriterState.CloseTag;
  123736. this.stream.write('</' + node.name + '>');
  123737. } else {
  123738. options.state = WriterState.CloseTag;
  123739. this.stream.write(options.spaceBeforeSlash + '/>');
  123740. }
  123741. } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) {
  123742. this.stream.write('>');
  123743. options.state = WriterState.InsideTag;
  123744. options.suppressPrettyCount++;
  123745. prettySuppressed = true;
  123746. this.writeChildNode(firstChildNode, options, level + 1);
  123747. options.suppressPrettyCount--;
  123748. prettySuppressed = false;
  123749. options.state = WriterState.CloseTag;
  123750. this.stream.write('</' + node.name + '>');
  123751. } else {
  123752. this.stream.write('>' + this.endline(node, options, level));
  123753. options.state = WriterState.InsideTag;
  123754. ref1 = node.children;
  123755. for (j = 0, len = ref1.length; j < len; j++) {
  123756. child = ref1[j];
  123757. this.writeChildNode(child, options, level + 1);
  123758. }
  123759. options.state = WriterState.CloseTag;
  123760. this.stream.write(this.indent(node, options, level) + '</' + node.name + '>');
  123761. }
  123762. this.stream.write(this.endline(node, options, level));
  123763. options.state = WriterState.None;
  123764. return this.closeNode(node, options, level);
  123765. };
  123766. XMLStreamWriter.prototype.processingInstruction = function(node, options, level) {
  123767. return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level));
  123768. };
  123769. XMLStreamWriter.prototype.raw = function(node, options, level) {
  123770. return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level));
  123771. };
  123772. XMLStreamWriter.prototype.text = function(node, options, level) {
  123773. return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level));
  123774. };
  123775. XMLStreamWriter.prototype.dtdAttList = function(node, options, level) {
  123776. return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level));
  123777. };
  123778. XMLStreamWriter.prototype.dtdElement = function(node, options, level) {
  123779. return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level));
  123780. };
  123781. XMLStreamWriter.prototype.dtdEntity = function(node, options, level) {
  123782. return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level));
  123783. };
  123784. XMLStreamWriter.prototype.dtdNotation = function(node, options, level) {
  123785. return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level));
  123786. };
  123787. return XMLStreamWriter;
  123788. })(XMLWriterBase);
  123789. }).call(this);
  123790. },{"./NodeType":673,"./WriterState":675,"./XMLWriterBase":703}],700:[function(require,module,exports){
  123791. // Generated by CoffeeScript 1.12.7
  123792. (function() {
  123793. var XMLStringWriter, XMLWriterBase,
  123794. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  123795. hasProp = {}.hasOwnProperty;
  123796. XMLWriterBase = require('./XMLWriterBase');
  123797. module.exports = XMLStringWriter = (function(superClass) {
  123798. extend(XMLStringWriter, superClass);
  123799. function XMLStringWriter(options) {
  123800. XMLStringWriter.__super__.constructor.call(this, options);
  123801. }
  123802. XMLStringWriter.prototype.document = function(doc, options) {
  123803. var child, i, len, r, ref;
  123804. options = this.filterOptions(options);
  123805. r = '';
  123806. ref = doc.children;
  123807. for (i = 0, len = ref.length; i < len; i++) {
  123808. child = ref[i];
  123809. r += this.writeChildNode(child, options, 0);
  123810. }
  123811. if (options.pretty && r.slice(-options.newline.length) === options.newline) {
  123812. r = r.slice(0, -options.newline.length);
  123813. }
  123814. return r;
  123815. };
  123816. return XMLStringWriter;
  123817. })(XMLWriterBase);
  123818. }).call(this);
  123819. },{"./XMLWriterBase":703}],701:[function(require,module,exports){
  123820. // Generated by CoffeeScript 1.12.7
  123821. (function() {
  123822. var XMLStringifier,
  123823. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  123824. hasProp = {}.hasOwnProperty;
  123825. module.exports = XMLStringifier = (function() {
  123826. function XMLStringifier(options) {
  123827. this.assertLegalName = bind(this.assertLegalName, this);
  123828. this.assertLegalChar = bind(this.assertLegalChar, this);
  123829. var key, ref, value;
  123830. options || (options = {});
  123831. this.options = options;
  123832. if (!this.options.version) {
  123833. this.options.version = '1.0';
  123834. }
  123835. ref = options.stringify || {};
  123836. for (key in ref) {
  123837. if (!hasProp.call(ref, key)) continue;
  123838. value = ref[key];
  123839. this[key] = value;
  123840. }
  123841. }
  123842. XMLStringifier.prototype.name = function(val) {
  123843. if (this.options.noValidation) {
  123844. return val;
  123845. }
  123846. return this.assertLegalName('' + val || '');
  123847. };
  123848. XMLStringifier.prototype.text = function(val) {
  123849. if (this.options.noValidation) {
  123850. return val;
  123851. }
  123852. return this.assertLegalChar(this.textEscape('' + val || ''));
  123853. };
  123854. XMLStringifier.prototype.cdata = function(val) {
  123855. if (this.options.noValidation) {
  123856. return val;
  123857. }
  123858. val = '' + val || '';
  123859. val = val.replace(']]>', ']]]]><![CDATA[>');
  123860. return this.assertLegalChar(val);
  123861. };
  123862. XMLStringifier.prototype.comment = function(val) {
  123863. if (this.options.noValidation) {
  123864. return val;
  123865. }
  123866. val = '' + val || '';
  123867. if (val.match(/--/)) {
  123868. throw new Error("Comment text cannot contain double-hypen: " + val);
  123869. }
  123870. return this.assertLegalChar(val);
  123871. };
  123872. XMLStringifier.prototype.raw = function(val) {
  123873. if (this.options.noValidation) {
  123874. return val;
  123875. }
  123876. return '' + val || '';
  123877. };
  123878. XMLStringifier.prototype.attValue = function(val) {
  123879. if (this.options.noValidation) {
  123880. return val;
  123881. }
  123882. return this.assertLegalChar(this.attEscape(val = '' + val || ''));
  123883. };
  123884. XMLStringifier.prototype.insTarget = function(val) {
  123885. if (this.options.noValidation) {
  123886. return val;
  123887. }
  123888. return this.assertLegalChar('' + val || '');
  123889. };
  123890. XMLStringifier.prototype.insValue = function(val) {
  123891. if (this.options.noValidation) {
  123892. return val;
  123893. }
  123894. val = '' + val || '';
  123895. if (val.match(/\?>/)) {
  123896. throw new Error("Invalid processing instruction value: " + val);
  123897. }
  123898. return this.assertLegalChar(val);
  123899. };
  123900. XMLStringifier.prototype.xmlVersion = function(val) {
  123901. if (this.options.noValidation) {
  123902. return val;
  123903. }
  123904. val = '' + val || '';
  123905. if (!val.match(/1\.[0-9]+/)) {
  123906. throw new Error("Invalid version number: " + val);
  123907. }
  123908. return val;
  123909. };
  123910. XMLStringifier.prototype.xmlEncoding = function(val) {
  123911. if (this.options.noValidation) {
  123912. return val;
  123913. }
  123914. val = '' + val || '';
  123915. if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) {
  123916. throw new Error("Invalid encoding: " + val);
  123917. }
  123918. return this.assertLegalChar(val);
  123919. };
  123920. XMLStringifier.prototype.xmlStandalone = function(val) {
  123921. if (this.options.noValidation) {
  123922. return val;
  123923. }
  123924. if (val) {
  123925. return "yes";
  123926. } else {
  123927. return "no";
  123928. }
  123929. };
  123930. XMLStringifier.prototype.dtdPubID = function(val) {
  123931. if (this.options.noValidation) {
  123932. return val;
  123933. }
  123934. return this.assertLegalChar('' + val || '');
  123935. };
  123936. XMLStringifier.prototype.dtdSysID = function(val) {
  123937. if (this.options.noValidation) {
  123938. return val;
  123939. }
  123940. return this.assertLegalChar('' + val || '');
  123941. };
  123942. XMLStringifier.prototype.dtdElementValue = function(val) {
  123943. if (this.options.noValidation) {
  123944. return val;
  123945. }
  123946. return this.assertLegalChar('' + val || '');
  123947. };
  123948. XMLStringifier.prototype.dtdAttType = function(val) {
  123949. if (this.options.noValidation) {
  123950. return val;
  123951. }
  123952. return this.assertLegalChar('' + val || '');
  123953. };
  123954. XMLStringifier.prototype.dtdAttDefault = function(val) {
  123955. if (this.options.noValidation) {
  123956. return val;
  123957. }
  123958. return this.assertLegalChar('' + val || '');
  123959. };
  123960. XMLStringifier.prototype.dtdEntityValue = function(val) {
  123961. if (this.options.noValidation) {
  123962. return val;
  123963. }
  123964. return this.assertLegalChar('' + val || '');
  123965. };
  123966. XMLStringifier.prototype.dtdNData = function(val) {
  123967. if (this.options.noValidation) {
  123968. return val;
  123969. }
  123970. return this.assertLegalChar('' + val || '');
  123971. };
  123972. XMLStringifier.prototype.convertAttKey = '@';
  123973. XMLStringifier.prototype.convertPIKey = '?';
  123974. XMLStringifier.prototype.convertTextKey = '#text';
  123975. XMLStringifier.prototype.convertCDataKey = '#cdata';
  123976. XMLStringifier.prototype.convertCommentKey = '#comment';
  123977. XMLStringifier.prototype.convertRawKey = '#raw';
  123978. XMLStringifier.prototype.assertLegalChar = function(str) {
  123979. var regex, res;
  123980. if (this.options.noValidation) {
  123981. return str;
  123982. }
  123983. regex = '';
  123984. if (this.options.version === '1.0') {
  123985. regex = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  123986. if (res = str.match(regex)) {
  123987. throw new Error("Invalid character in string: " + str + " at index " + res.index);
  123988. }
  123989. } else if (this.options.version === '1.1') {
  123990. regex = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
  123991. if (res = str.match(regex)) {
  123992. throw new Error("Invalid character in string: " + str + " at index " + res.index);
  123993. }
  123994. }
  123995. return str;
  123996. };
  123997. XMLStringifier.prototype.assertLegalName = function(str) {
  123998. var regex;
  123999. if (this.options.noValidation) {
  124000. return str;
  124001. }
  124002. this.assertLegalChar(str);
  124003. regex = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/;
  124004. if (!str.match(regex)) {
  124005. throw new Error("Invalid character in name");
  124006. }
  124007. return str;
  124008. };
  124009. XMLStringifier.prototype.textEscape = function(str) {
  124010. var ampregex;
  124011. if (this.options.noValidation) {
  124012. return str;
  124013. }
  124014. ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
  124015. return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
  124016. };
  124017. XMLStringifier.prototype.attEscape = function(str) {
  124018. var ampregex;
  124019. if (this.options.noValidation) {
  124020. return str;
  124021. }
  124022. ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
  124023. return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
  124024. };
  124025. return XMLStringifier;
  124026. })();
  124027. }).call(this);
  124028. },{}],702:[function(require,module,exports){
  124029. // Generated by CoffeeScript 1.12.7
  124030. (function() {
  124031. var NodeType, XMLCharacterData, XMLText,
  124032. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  124033. hasProp = {}.hasOwnProperty;
  124034. NodeType = require('./NodeType');
  124035. XMLCharacterData = require('./XMLCharacterData');
  124036. module.exports = XMLText = (function(superClass) {
  124037. extend(XMLText, superClass);
  124038. function XMLText(parent, text) {
  124039. XMLText.__super__.constructor.call(this, parent);
  124040. if (text == null) {
  124041. throw new Error("Missing element text. " + this.debugInfo());
  124042. }
  124043. this.name = "#text";
  124044. this.type = NodeType.Text;
  124045. this.value = this.stringify.text(text);
  124046. }
  124047. Object.defineProperty(XMLText.prototype, 'isElementContentWhitespace', {
  124048. get: function() {
  124049. throw new Error("This DOM method is not implemented." + this.debugInfo());
  124050. }
  124051. });
  124052. Object.defineProperty(XMLText.prototype, 'wholeText', {
  124053. get: function() {
  124054. var next, prev, str;
  124055. str = '';
  124056. prev = this.previousSibling;
  124057. while (prev) {
  124058. str = prev.data + str;
  124059. prev = prev.previousSibling;
  124060. }
  124061. str += this.data;
  124062. next = this.nextSibling;
  124063. while (next) {
  124064. str = str + next.data;
  124065. next = next.nextSibling;
  124066. }
  124067. return str;
  124068. }
  124069. });
  124070. XMLText.prototype.clone = function() {
  124071. return Object.create(this);
  124072. };
  124073. XMLText.prototype.toString = function(options) {
  124074. return this.options.writer.text(this, this.options.writer.filterOptions(options));
  124075. };
  124076. XMLText.prototype.splitText = function(offset) {
  124077. throw new Error("This DOM method is not implemented." + this.debugInfo());
  124078. };
  124079. XMLText.prototype.replaceWholeText = function(content) {
  124080. throw new Error("This DOM method is not implemented." + this.debugInfo());
  124081. };
  124082. return XMLText;
  124083. })(XMLCharacterData);
  124084. }).call(this);
  124085. },{"./NodeType":673,"./XMLCharacterData":678}],703:[function(require,module,exports){
  124086. // Generated by CoffeeScript 1.12.7
  124087. (function() {
  124088. var NodeType, WriterState, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLProcessingInstruction, XMLRaw, XMLText, XMLWriterBase, assign,
  124089. hasProp = {}.hasOwnProperty;
  124090. assign = require('./Utility').assign;
  124091. NodeType = require('./NodeType');
  124092. XMLDeclaration = require('./XMLDeclaration');
  124093. XMLDocType = require('./XMLDocType');
  124094. XMLCData = require('./XMLCData');
  124095. XMLComment = require('./XMLComment');
  124096. XMLElement = require('./XMLElement');
  124097. XMLRaw = require('./XMLRaw');
  124098. XMLText = require('./XMLText');
  124099. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  124100. XMLDummy = require('./XMLDummy');
  124101. XMLDTDAttList = require('./XMLDTDAttList');
  124102. XMLDTDElement = require('./XMLDTDElement');
  124103. XMLDTDEntity = require('./XMLDTDEntity');
  124104. XMLDTDNotation = require('./XMLDTDNotation');
  124105. WriterState = require('./WriterState');
  124106. module.exports = XMLWriterBase = (function() {
  124107. function XMLWriterBase(options) {
  124108. var key, ref, value;
  124109. options || (options = {});
  124110. this.options = options;
  124111. ref = options.writer || {};
  124112. for (key in ref) {
  124113. if (!hasProp.call(ref, key)) continue;
  124114. value = ref[key];
  124115. this["_" + key] = this[key];
  124116. this[key] = value;
  124117. }
  124118. }
  124119. XMLWriterBase.prototype.filterOptions = function(options) {
  124120. var filteredOptions, ref, ref1, ref2, ref3, ref4, ref5, ref6;
  124121. options || (options = {});
  124122. options = assign({}, this.options, options);
  124123. filteredOptions = {
  124124. writer: this
  124125. };
  124126. filteredOptions.pretty = options.pretty || false;
  124127. filteredOptions.allowEmpty = options.allowEmpty || false;
  124128. filteredOptions.indent = (ref = options.indent) != null ? ref : ' ';
  124129. filteredOptions.newline = (ref1 = options.newline) != null ? ref1 : '\n';
  124130. filteredOptions.offset = (ref2 = options.offset) != null ? ref2 : 0;
  124131. filteredOptions.dontPrettyTextNodes = (ref3 = (ref4 = options.dontPrettyTextNodes) != null ? ref4 : options.dontprettytextnodes) != null ? ref3 : 0;
  124132. filteredOptions.spaceBeforeSlash = (ref5 = (ref6 = options.spaceBeforeSlash) != null ? ref6 : options.spacebeforeslash) != null ? ref5 : '';
  124133. if (filteredOptions.spaceBeforeSlash === true) {
  124134. filteredOptions.spaceBeforeSlash = ' ';
  124135. }
  124136. filteredOptions.suppressPrettyCount = 0;
  124137. filteredOptions.user = {};
  124138. filteredOptions.state = WriterState.None;
  124139. return filteredOptions;
  124140. };
  124141. XMLWriterBase.prototype.indent = function(node, options, level) {
  124142. var indentLevel;
  124143. if (!options.pretty || options.suppressPrettyCount) {
  124144. return '';
  124145. } else if (options.pretty) {
  124146. indentLevel = (level || 0) + options.offset + 1;
  124147. if (indentLevel > 0) {
  124148. return new Array(indentLevel).join(options.indent);
  124149. }
  124150. }
  124151. return '';
  124152. };
  124153. XMLWriterBase.prototype.endline = function(node, options, level) {
  124154. if (!options.pretty || options.suppressPrettyCount) {
  124155. return '';
  124156. } else {
  124157. return options.newline;
  124158. }
  124159. };
  124160. XMLWriterBase.prototype.attribute = function(att, options, level) {
  124161. var r;
  124162. this.openAttribute(att, options, level);
  124163. r = ' ' + att.name + '="' + att.value + '"';
  124164. this.closeAttribute(att, options, level);
  124165. return r;
  124166. };
  124167. XMLWriterBase.prototype.cdata = function(node, options, level) {
  124168. var r;
  124169. this.openNode(node, options, level);
  124170. options.state = WriterState.OpenTag;
  124171. r = this.indent(node, options, level) + '<![CDATA[';
  124172. options.state = WriterState.InsideTag;
  124173. r += node.value;
  124174. options.state = WriterState.CloseTag;
  124175. r += ']]>' + this.endline(node, options, level);
  124176. options.state = WriterState.None;
  124177. this.closeNode(node, options, level);
  124178. return r;
  124179. };
  124180. XMLWriterBase.prototype.comment = function(node, options, level) {
  124181. var r;
  124182. this.openNode(node, options, level);
  124183. options.state = WriterState.OpenTag;
  124184. r = this.indent(node, options, level) + '<!-- ';
  124185. options.state = WriterState.InsideTag;
  124186. r += node.value;
  124187. options.state = WriterState.CloseTag;
  124188. r += ' -->' + this.endline(node, options, level);
  124189. options.state = WriterState.None;
  124190. this.closeNode(node, options, level);
  124191. return r;
  124192. };
  124193. XMLWriterBase.prototype.declaration = function(node, options, level) {
  124194. var r;
  124195. this.openNode(node, options, level);
  124196. options.state = WriterState.OpenTag;
  124197. r = this.indent(node, options, level) + '<?xml';
  124198. options.state = WriterState.InsideTag;
  124199. r += ' version="' + node.version + '"';
  124200. if (node.encoding != null) {
  124201. r += ' encoding="' + node.encoding + '"';
  124202. }
  124203. if (node.standalone != null) {
  124204. r += ' standalone="' + node.standalone + '"';
  124205. }
  124206. options.state = WriterState.CloseTag;
  124207. r += options.spaceBeforeSlash + '?>';
  124208. r += this.endline(node, options, level);
  124209. options.state = WriterState.None;
  124210. this.closeNode(node, options, level);
  124211. return r;
  124212. };
  124213. XMLWriterBase.prototype.docType = function(node, options, level) {
  124214. var child, i, len, r, ref;
  124215. level || (level = 0);
  124216. this.openNode(node, options, level);
  124217. options.state = WriterState.OpenTag;
  124218. r = this.indent(node, options, level);
  124219. r += '<!DOCTYPE ' + node.root().name;
  124220. if (node.pubID && node.sysID) {
  124221. r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  124222. } else if (node.sysID) {
  124223. r += ' SYSTEM "' + node.sysID + '"';
  124224. }
  124225. if (node.children.length > 0) {
  124226. r += ' [';
  124227. r += this.endline(node, options, level);
  124228. options.state = WriterState.InsideTag;
  124229. ref = node.children;
  124230. for (i = 0, len = ref.length; i < len; i++) {
  124231. child = ref[i];
  124232. r += this.writeChildNode(child, options, level + 1);
  124233. }
  124234. options.state = WriterState.CloseTag;
  124235. r += ']';
  124236. }
  124237. options.state = WriterState.CloseTag;
  124238. r += options.spaceBeforeSlash + '>';
  124239. r += this.endline(node, options, level);
  124240. options.state = WriterState.None;
  124241. this.closeNode(node, options, level);
  124242. return r;
  124243. };
  124244. XMLWriterBase.prototype.element = function(node, options, level) {
  124245. var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2;
  124246. level || (level = 0);
  124247. prettySuppressed = false;
  124248. r = '';
  124249. this.openNode(node, options, level);
  124250. options.state = WriterState.OpenTag;
  124251. r += this.indent(node, options, level) + '<' + node.name;
  124252. ref = node.attribs;
  124253. for (name in ref) {
  124254. if (!hasProp.call(ref, name)) continue;
  124255. att = ref[name];
  124256. r += this.attribute(att, options, level);
  124257. }
  124258. childNodeCount = node.children.length;
  124259. firstChildNode = childNodeCount === 0 ? null : node.children[0];
  124260. if (childNodeCount === 0 || node.children.every(function(e) {
  124261. return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === '';
  124262. })) {
  124263. if (options.allowEmpty) {
  124264. r += '>';
  124265. options.state = WriterState.CloseTag;
  124266. r += '</' + node.name + '>' + this.endline(node, options, level);
  124267. } else {
  124268. options.state = WriterState.CloseTag;
  124269. r += options.spaceBeforeSlash + '/>' + this.endline(node, options, level);
  124270. }
  124271. } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) {
  124272. r += '>';
  124273. options.state = WriterState.InsideTag;
  124274. options.suppressPrettyCount++;
  124275. prettySuppressed = true;
  124276. r += this.writeChildNode(firstChildNode, options, level + 1);
  124277. options.suppressPrettyCount--;
  124278. prettySuppressed = false;
  124279. options.state = WriterState.CloseTag;
  124280. r += '</' + node.name + '>' + this.endline(node, options, level);
  124281. } else {
  124282. if (options.dontPrettyTextNodes) {
  124283. ref1 = node.children;
  124284. for (i = 0, len = ref1.length; i < len; i++) {
  124285. child = ref1[i];
  124286. if ((child.type === NodeType.Text || child.type === NodeType.Raw) && (child.value != null)) {
  124287. options.suppressPrettyCount++;
  124288. prettySuppressed = true;
  124289. break;
  124290. }
  124291. }
  124292. }
  124293. r += '>' + this.endline(node, options, level);
  124294. options.state = WriterState.InsideTag;
  124295. ref2 = node.children;
  124296. for (j = 0, len1 = ref2.length; j < len1; j++) {
  124297. child = ref2[j];
  124298. r += this.writeChildNode(child, options, level + 1);
  124299. }
  124300. options.state = WriterState.CloseTag;
  124301. r += this.indent(node, options, level) + '</' + node.name + '>';
  124302. if (prettySuppressed) {
  124303. options.suppressPrettyCount--;
  124304. }
  124305. r += this.endline(node, options, level);
  124306. options.state = WriterState.None;
  124307. }
  124308. this.closeNode(node, options, level);
  124309. return r;
  124310. };
  124311. XMLWriterBase.prototype.writeChildNode = function(node, options, level) {
  124312. switch (node.type) {
  124313. case NodeType.CData:
  124314. return this.cdata(node, options, level);
  124315. case NodeType.Comment:
  124316. return this.comment(node, options, level);
  124317. case NodeType.Element:
  124318. return this.element(node, options, level);
  124319. case NodeType.Raw:
  124320. return this.raw(node, options, level);
  124321. case NodeType.Text:
  124322. return this.text(node, options, level);
  124323. case NodeType.ProcessingInstruction:
  124324. return this.processingInstruction(node, options, level);
  124325. case NodeType.Dummy:
  124326. return '';
  124327. case NodeType.Declaration:
  124328. return this.declaration(node, options, level);
  124329. case NodeType.DocType:
  124330. return this.docType(node, options, level);
  124331. case NodeType.AttributeDeclaration:
  124332. return this.dtdAttList(node, options, level);
  124333. case NodeType.ElementDeclaration:
  124334. return this.dtdElement(node, options, level);
  124335. case NodeType.EntityDeclaration:
  124336. return this.dtdEntity(node, options, level);
  124337. case NodeType.NotationDeclaration:
  124338. return this.dtdNotation(node, options, level);
  124339. default:
  124340. throw new Error("Unknown XML node type: " + node.constructor.name);
  124341. }
  124342. };
  124343. XMLWriterBase.prototype.processingInstruction = function(node, options, level) {
  124344. var r;
  124345. this.openNode(node, options, level);
  124346. options.state = WriterState.OpenTag;
  124347. r = this.indent(node, options, level) + '<?';
  124348. options.state = WriterState.InsideTag;
  124349. r += node.target;
  124350. if (node.value) {
  124351. r += ' ' + node.value;
  124352. }
  124353. options.state = WriterState.CloseTag;
  124354. r += options.spaceBeforeSlash + '?>';
  124355. r += this.endline(node, options, level);
  124356. options.state = WriterState.None;
  124357. this.closeNode(node, options, level);
  124358. return r;
  124359. };
  124360. XMLWriterBase.prototype.raw = function(node, options, level) {
  124361. var r;
  124362. this.openNode(node, options, level);
  124363. options.state = WriterState.OpenTag;
  124364. r = this.indent(node, options, level);
  124365. options.state = WriterState.InsideTag;
  124366. r += node.value;
  124367. options.state = WriterState.CloseTag;
  124368. r += this.endline(node, options, level);
  124369. options.state = WriterState.None;
  124370. this.closeNode(node, options, level);
  124371. return r;
  124372. };
  124373. XMLWriterBase.prototype.text = function(node, options, level) {
  124374. var r;
  124375. this.openNode(node, options, level);
  124376. options.state = WriterState.OpenTag;
  124377. r = this.indent(node, options, level);
  124378. options.state = WriterState.InsideTag;
  124379. r += node.value;
  124380. options.state = WriterState.CloseTag;
  124381. r += this.endline(node, options, level);
  124382. options.state = WriterState.None;
  124383. this.closeNode(node, options, level);
  124384. return r;
  124385. };
  124386. XMLWriterBase.prototype.dtdAttList = function(node, options, level) {
  124387. var r;
  124388. this.openNode(node, options, level);
  124389. options.state = WriterState.OpenTag;
  124390. r = this.indent(node, options, level) + '<!ATTLIST';
  124391. options.state = WriterState.InsideTag;
  124392. r += ' ' + node.elementName + ' ' + node.attributeName + ' ' + node.attributeType;
  124393. if (node.defaultValueType !== '#DEFAULT') {
  124394. r += ' ' + node.defaultValueType;
  124395. }
  124396. if (node.defaultValue) {
  124397. r += ' "' + node.defaultValue + '"';
  124398. }
  124399. options.state = WriterState.CloseTag;
  124400. r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
  124401. options.state = WriterState.None;
  124402. this.closeNode(node, options, level);
  124403. return r;
  124404. };
  124405. XMLWriterBase.prototype.dtdElement = function(node, options, level) {
  124406. var r;
  124407. this.openNode(node, options, level);
  124408. options.state = WriterState.OpenTag;
  124409. r = this.indent(node, options, level) + '<!ELEMENT';
  124410. options.state = WriterState.InsideTag;
  124411. r += ' ' + node.name + ' ' + node.value;
  124412. options.state = WriterState.CloseTag;
  124413. r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
  124414. options.state = WriterState.None;
  124415. this.closeNode(node, options, level);
  124416. return r;
  124417. };
  124418. XMLWriterBase.prototype.dtdEntity = function(node, options, level) {
  124419. var r;
  124420. this.openNode(node, options, level);
  124421. options.state = WriterState.OpenTag;
  124422. r = this.indent(node, options, level) + '<!ENTITY';
  124423. options.state = WriterState.InsideTag;
  124424. if (node.pe) {
  124425. r += ' %';
  124426. }
  124427. r += ' ' + node.name;
  124428. if (node.value) {
  124429. r += ' "' + node.value + '"';
  124430. } else {
  124431. if (node.pubID && node.sysID) {
  124432. r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  124433. } else if (node.sysID) {
  124434. r += ' SYSTEM "' + node.sysID + '"';
  124435. }
  124436. if (node.nData) {
  124437. r += ' NDATA ' + node.nData;
  124438. }
  124439. }
  124440. options.state = WriterState.CloseTag;
  124441. r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
  124442. options.state = WriterState.None;
  124443. this.closeNode(node, options, level);
  124444. return r;
  124445. };
  124446. XMLWriterBase.prototype.dtdNotation = function(node, options, level) {
  124447. var r;
  124448. this.openNode(node, options, level);
  124449. options.state = WriterState.OpenTag;
  124450. r = this.indent(node, options, level) + '<!NOTATION';
  124451. options.state = WriterState.InsideTag;
  124452. r += ' ' + node.name;
  124453. if (node.pubID && node.sysID) {
  124454. r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  124455. } else if (node.pubID) {
  124456. r += ' PUBLIC "' + node.pubID + '"';
  124457. } else if (node.sysID) {
  124458. r += ' SYSTEM "' + node.sysID + '"';
  124459. }
  124460. options.state = WriterState.CloseTag;
  124461. r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
  124462. options.state = WriterState.None;
  124463. this.closeNode(node, options, level);
  124464. return r;
  124465. };
  124466. XMLWriterBase.prototype.openNode = function(node, options, level) {};
  124467. XMLWriterBase.prototype.closeNode = function(node, options, level) {};
  124468. XMLWriterBase.prototype.openAttribute = function(att, options, level) {};
  124469. XMLWriterBase.prototype.closeAttribute = function(att, options, level) {};
  124470. return XMLWriterBase;
  124471. })();
  124472. }).call(this);
  124473. },{"./NodeType":673,"./Utility":674,"./WriterState":675,"./XMLCData":677,"./XMLComment":679,"./XMLDTDAttList":684,"./XMLDTDElement":685,"./XMLDTDEntity":686,"./XMLDTDNotation":687,"./XMLDeclaration":688,"./XMLDocType":689,"./XMLDummy":692,"./XMLElement":693,"./XMLProcessingInstruction":697,"./XMLRaw":698,"./XMLText":702}],704:[function(require,module,exports){
  124474. // Generated by CoffeeScript 1.12.7
  124475. (function() {
  124476. var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref;
  124477. ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction;
  124478. XMLDOMImplementation = require('./XMLDOMImplementation');
  124479. XMLDocument = require('./XMLDocument');
  124480. XMLDocumentCB = require('./XMLDocumentCB');
  124481. XMLStringWriter = require('./XMLStringWriter');
  124482. XMLStreamWriter = require('./XMLStreamWriter');
  124483. NodeType = require('./NodeType');
  124484. WriterState = require('./WriterState');
  124485. module.exports.create = function(name, xmldec, doctype, options) {
  124486. var doc, root;
  124487. if (name == null) {
  124488. throw new Error("Root element needs a name.");
  124489. }
  124490. options = assign({}, xmldec, doctype, options);
  124491. doc = new XMLDocument(options);
  124492. root = doc.element(name);
  124493. if (!options.headless) {
  124494. doc.declaration(options);
  124495. if ((options.pubID != null) || (options.sysID != null)) {
  124496. doc.dtd(options);
  124497. }
  124498. }
  124499. return root;
  124500. };
  124501. module.exports.begin = function(options, onData, onEnd) {
  124502. var ref1;
  124503. if (isFunction(options)) {
  124504. ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];
  124505. options = {};
  124506. }
  124507. if (onData) {
  124508. return new XMLDocumentCB(options, onData, onEnd);
  124509. } else {
  124510. return new XMLDocument(options);
  124511. }
  124512. };
  124513. module.exports.stringWriter = function(options) {
  124514. return new XMLStringWriter(options);
  124515. };
  124516. module.exports.streamWriter = function(stream, options) {
  124517. return new XMLStreamWriter(stream, options);
  124518. };
  124519. module.exports.implementation = new XMLDOMImplementation();
  124520. module.exports.nodeType = NodeType;
  124521. module.exports.writerState = WriterState;
  124522. }).call(this);
  124523. },{"./NodeType":673,"./Utility":674,"./WriterState":675,"./XMLDOMImplementation":682,"./XMLDocument":690,"./XMLDocumentCB":691,"./XMLStreamWriter":699,"./XMLStringWriter":700}],705:[function(require,module,exports){
  124524. function DOMParser(options){
  124525. this.options = options ||{locator:{}};
  124526. }
  124527. DOMParser.prototype.parseFromString = function(source,mimeType){
  124528. var options = this.options;
  124529. var sax = new XMLReader();
  124530. var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
  124531. var errorHandler = options.errorHandler;
  124532. var locator = options.locator;
  124533. var defaultNSMap = options.xmlns||{};
  124534. var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
  124535. var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
  124536. if(locator){
  124537. domBuilder.setDocumentLocator(locator)
  124538. }
  124539. sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
  124540. sax.domBuilder = options.domBuilder || domBuilder;
  124541. if(isHTML){
  124542. defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
  124543. }
  124544. defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
  124545. if(source && typeof source === 'string'){
  124546. sax.parse(source,defaultNSMap,entityMap);
  124547. }else{
  124548. sax.errorHandler.error("invalid doc source");
  124549. }
  124550. return domBuilder.doc;
  124551. }
  124552. function buildErrorHandler(errorImpl,domBuilder,locator){
  124553. if(!errorImpl){
  124554. if(domBuilder instanceof DOMHandler){
  124555. return domBuilder;
  124556. }
  124557. errorImpl = domBuilder ;
  124558. }
  124559. var errorHandler = {}
  124560. var isCallback = errorImpl instanceof Function;
  124561. locator = locator||{}
  124562. function build(key){
  124563. var fn = errorImpl[key];
  124564. if(!fn && isCallback){
  124565. fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
  124566. }
  124567. errorHandler[key] = fn && function(msg){
  124568. fn('[xmldom '+key+']\t'+msg+_locator(locator));
  124569. }||function(){};
  124570. }
  124571. build('warning');
  124572. build('error');
  124573. build('fatalError');
  124574. return errorHandler;
  124575. }
  124576. //console.log('#\n\n\n\n\n\n\n####')
  124577. /**
  124578. * +ContentHandler+ErrorHandler
  124579. * +LexicalHandler+EntityResolver2
  124580. * -DeclHandler-DTDHandler
  124581. *
  124582. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  124583. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  124584. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  124585. */
  124586. function DOMHandler() {
  124587. this.cdata = false;
  124588. }
  124589. function position(locator,node){
  124590. node.lineNumber = locator.lineNumber;
  124591. node.columnNumber = locator.columnNumber;
  124592. }
  124593. /**
  124594. * @see org.xml.sax.ContentHandler#startDocument
  124595. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  124596. */
  124597. DOMHandler.prototype = {
  124598. startDocument : function() {
  124599. this.doc = new DOMImplementation().createDocument(null, null, null);
  124600. if (this.locator) {
  124601. this.doc.documentURI = this.locator.systemId;
  124602. }
  124603. },
  124604. startElement:function(namespaceURI, localName, qName, attrs) {
  124605. var doc = this.doc;
  124606. var el = doc.createElementNS(namespaceURI, qName||localName);
  124607. var len = attrs.length;
  124608. appendElement(this, el);
  124609. this.currentElement = el;
  124610. this.locator && position(this.locator,el)
  124611. for (var i = 0 ; i < len; i++) {
  124612. var namespaceURI = attrs.getURI(i);
  124613. var value = attrs.getValue(i);
  124614. var qName = attrs.getQName(i);
  124615. var attr = doc.createAttributeNS(namespaceURI, qName);
  124616. this.locator &&position(attrs.getLocator(i),attr);
  124617. attr.value = attr.nodeValue = value;
  124618. el.setAttributeNode(attr)
  124619. }
  124620. },
  124621. endElement:function(namespaceURI, localName, qName) {
  124622. var current = this.currentElement
  124623. var tagName = current.tagName;
  124624. this.currentElement = current.parentNode;
  124625. },
  124626. startPrefixMapping:function(prefix, uri) {
  124627. },
  124628. endPrefixMapping:function(prefix) {
  124629. },
  124630. processingInstruction:function(target, data) {
  124631. var ins = this.doc.createProcessingInstruction(target, data);
  124632. this.locator && position(this.locator,ins)
  124633. appendElement(this, ins);
  124634. },
  124635. ignorableWhitespace:function(ch, start, length) {
  124636. },
  124637. characters:function(chars, start, length) {
  124638. chars = _toString.apply(this,arguments)
  124639. //console.log(chars)
  124640. if(chars){
  124641. if (this.cdata) {
  124642. var charNode = this.doc.createCDATASection(chars);
  124643. } else {
  124644. var charNode = this.doc.createTextNode(chars);
  124645. }
  124646. if(this.currentElement){
  124647. this.currentElement.appendChild(charNode);
  124648. }else if(/^\s*$/.test(chars)){
  124649. this.doc.appendChild(charNode);
  124650. //process xml
  124651. }
  124652. this.locator && position(this.locator,charNode)
  124653. }
  124654. },
  124655. skippedEntity:function(name) {
  124656. },
  124657. endDocument:function() {
  124658. this.doc.normalize();
  124659. },
  124660. setDocumentLocator:function (locator) {
  124661. if(this.locator = locator){// && !('lineNumber' in locator)){
  124662. locator.lineNumber = 0;
  124663. }
  124664. },
  124665. //LexicalHandler
  124666. comment:function(chars, start, length) {
  124667. chars = _toString.apply(this,arguments)
  124668. var comm = this.doc.createComment(chars);
  124669. this.locator && position(this.locator,comm)
  124670. appendElement(this, comm);
  124671. },
  124672. startCDATA:function() {
  124673. //used in characters() methods
  124674. this.cdata = true;
  124675. },
  124676. endCDATA:function() {
  124677. this.cdata = false;
  124678. },
  124679. startDTD:function(name, publicId, systemId) {
  124680. var impl = this.doc.implementation;
  124681. if (impl && impl.createDocumentType) {
  124682. var dt = impl.createDocumentType(name, publicId, systemId);
  124683. this.locator && position(this.locator,dt)
  124684. appendElement(this, dt);
  124685. }
  124686. },
  124687. /**
  124688. * @see org.xml.sax.ErrorHandler
  124689. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  124690. */
  124691. warning:function(error) {
  124692. console.warn('[xmldom warning]\t'+error,_locator(this.locator));
  124693. },
  124694. error:function(error) {
  124695. console.error('[xmldom error]\t'+error,_locator(this.locator));
  124696. },
  124697. fatalError:function(error) {
  124698. console.error('[xmldom fatalError]\t'+error,_locator(this.locator));
  124699. throw error;
  124700. }
  124701. }
  124702. function _locator(l){
  124703. if(l){
  124704. return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
  124705. }
  124706. }
  124707. function _toString(chars,start,length){
  124708. if(typeof chars == 'string'){
  124709. return chars.substr(start,length)
  124710. }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  124711. if(chars.length >= start+length || start){
  124712. return new java.lang.String(chars,start,length)+'';
  124713. }
  124714. return chars;
  124715. }
  124716. }
  124717. /*
  124718. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  124719. * used method of org.xml.sax.ext.LexicalHandler:
  124720. * #comment(chars, start, length)
  124721. * #startCDATA()
  124722. * #endCDATA()
  124723. * #startDTD(name, publicId, systemId)
  124724. *
  124725. *
  124726. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  124727. * #endDTD()
  124728. * #startEntity(name)
  124729. * #endEntity(name)
  124730. *
  124731. *
  124732. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  124733. * IGNORED method of org.xml.sax.ext.DeclHandler
  124734. * #attributeDecl(eName, aName, type, mode, value)
  124735. * #elementDecl(name, model)
  124736. * #externalEntityDecl(name, publicId, systemId)
  124737. * #internalEntityDecl(name, value)
  124738. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  124739. * IGNORED method of org.xml.sax.EntityResolver2
  124740. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  124741. * #resolveEntity(publicId, systemId)
  124742. * #getExternalSubset(name, baseURI)
  124743. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  124744. * IGNORED method of org.xml.sax.DTDHandler
  124745. * #notationDecl(name, publicId, systemId) {};
  124746. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  124747. */
  124748. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
  124749. DOMHandler.prototype[key] = function(){return null}
  124750. })
  124751. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  124752. function appendElement (hander,node) {
  124753. if (!hander.currentElement) {
  124754. hander.doc.appendChild(node);
  124755. } else {
  124756. hander.currentElement.appendChild(node);
  124757. }
  124758. }//appendChild and setAttributeNS are preformance key
  124759. //if(typeof require == 'function'){
  124760. var htmlEntity = require('./entities');
  124761. var XMLReader = require('./sax').XMLReader;
  124762. var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
  124763. exports.XMLSerializer = require('./dom').XMLSerializer ;
  124764. exports.DOMParser = DOMParser;
  124765. //}
  124766. },{"./dom":706,"./entities":707,"./sax":708}],706:[function(require,module,exports){
  124767. /*
  124768. * DOM Level 2
  124769. * Object DOMException
  124770. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  124771. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  124772. */
  124773. function copy(src,dest){
  124774. for(var p in src){
  124775. dest[p] = src[p];
  124776. }
  124777. }
  124778. /**
  124779. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  124780. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  124781. */
  124782. function _extends(Class,Super){
  124783. var pt = Class.prototype;
  124784. if(!(pt instanceof Super)){
  124785. function t(){};
  124786. t.prototype = Super.prototype;
  124787. t = new t();
  124788. copy(pt,t);
  124789. Class.prototype = pt = t;
  124790. }
  124791. if(pt.constructor != Class){
  124792. if(typeof Class != 'function'){
  124793. console.error("unknow Class:"+Class)
  124794. }
  124795. pt.constructor = Class
  124796. }
  124797. }
  124798. var htmlns = 'http://www.w3.org/1999/xhtml' ;
  124799. // Node Types
  124800. var NodeType = {}
  124801. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  124802. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  124803. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  124804. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  124805. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  124806. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  124807. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  124808. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  124809. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  124810. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  124811. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  124812. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  124813. // ExceptionCode
  124814. var ExceptionCode = {}
  124815. var ExceptionMessage = {};
  124816. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  124817. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  124818. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  124819. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  124820. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  124821. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  124822. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  124823. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  124824. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  124825. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  124826. //level2
  124827. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  124828. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  124829. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  124830. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  124831. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  124832. function DOMException(code, message) {
  124833. if(message instanceof Error){
  124834. var error = message;
  124835. }else{
  124836. error = this;
  124837. Error.call(this, ExceptionMessage[code]);
  124838. this.message = ExceptionMessage[code];
  124839. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  124840. }
  124841. error.code = code;
  124842. if(message) this.message = this.message + ": " + message;
  124843. return error;
  124844. };
  124845. DOMException.prototype = Error.prototype;
  124846. copy(ExceptionCode,DOMException)
  124847. /**
  124848. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  124849. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  124850. * The items in the NodeList are accessible via an integral index, starting from 0.
  124851. */
  124852. function NodeList() {
  124853. };
  124854. NodeList.prototype = {
  124855. /**
  124856. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  124857. * @standard level1
  124858. */
  124859. length:0,
  124860. /**
  124861. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  124862. * @standard level1
  124863. * @param index unsigned long
  124864. * Index into the collection.
  124865. * @return Node
  124866. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  124867. */
  124868. item: function(index) {
  124869. return this[index] || null;
  124870. },
  124871. toString:function(isHTML,nodeFilter){
  124872. for(var buf = [], i = 0;i<this.length;i++){
  124873. serializeToString(this[i],buf,isHTML,nodeFilter);
  124874. }
  124875. return buf.join('');
  124876. }
  124877. };
  124878. function LiveNodeList(node,refresh){
  124879. this._node = node;
  124880. this._refresh = refresh
  124881. _updateLiveList(this);
  124882. }
  124883. function _updateLiveList(list){
  124884. var inc = list._node._inc || list._node.ownerDocument._inc;
  124885. if(list._inc != inc){
  124886. var ls = list._refresh(list._node);
  124887. //console.log(ls.length)
  124888. __set__(list,'length',ls.length);
  124889. copy(ls,list);
  124890. list._inc = inc;
  124891. }
  124892. }
  124893. LiveNodeList.prototype.item = function(i){
  124894. _updateLiveList(this);
  124895. return this[i];
  124896. }
  124897. _extends(LiveNodeList,NodeList);
  124898. /**
  124899. *
  124900. * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
  124901. * NamedNodeMap objects in the DOM are live.
  124902. * used for attributes or DocumentType entities
  124903. */
  124904. function NamedNodeMap() {
  124905. };
  124906. function _findNodeIndex(list,node){
  124907. var i = list.length;
  124908. while(i--){
  124909. if(list[i] === node){return i}
  124910. }
  124911. }
  124912. function _addNamedNode(el,list,newAttr,oldAttr){
  124913. if(oldAttr){
  124914. list[_findNodeIndex(list,oldAttr)] = newAttr;
  124915. }else{
  124916. list[list.length++] = newAttr;
  124917. }
  124918. if(el){
  124919. newAttr.ownerElement = el;
  124920. var doc = el.ownerDocument;
  124921. if(doc){
  124922. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  124923. _onAddAttribute(doc,el,newAttr);
  124924. }
  124925. }
  124926. }
  124927. function _removeNamedNode(el,list,attr){
  124928. //console.log('remove attr:'+attr)
  124929. var i = _findNodeIndex(list,attr);
  124930. if(i>=0){
  124931. var lastIndex = list.length-1
  124932. while(i<lastIndex){
  124933. list[i] = list[++i]
  124934. }
  124935. list.length = lastIndex;
  124936. if(el){
  124937. var doc = el.ownerDocument;
  124938. if(doc){
  124939. _onRemoveAttribute(doc,el,attr);
  124940. attr.ownerElement = null;
  124941. }
  124942. }
  124943. }else{
  124944. throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
  124945. }
  124946. }
  124947. NamedNodeMap.prototype = {
  124948. length:0,
  124949. item:NodeList.prototype.item,
  124950. getNamedItem: function(key) {
  124951. // if(key.indexOf(':')>0 || key == 'xmlns'){
  124952. // return null;
  124953. // }
  124954. //console.log()
  124955. var i = this.length;
  124956. while(i--){
  124957. var attr = this[i];
  124958. //console.log(attr.nodeName,key)
  124959. if(attr.nodeName == key){
  124960. return attr;
  124961. }
  124962. }
  124963. },
  124964. setNamedItem: function(attr) {
  124965. var el = attr.ownerElement;
  124966. if(el && el!=this._ownerElement){
  124967. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  124968. }
  124969. var oldAttr = this.getNamedItem(attr.nodeName);
  124970. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  124971. return oldAttr;
  124972. },
  124973. /* returns Node */
  124974. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  124975. var el = attr.ownerElement, oldAttr;
  124976. if(el && el!=this._ownerElement){
  124977. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  124978. }
  124979. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  124980. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  124981. return oldAttr;
  124982. },
  124983. /* returns Node */
  124984. removeNamedItem: function(key) {
  124985. var attr = this.getNamedItem(key);
  124986. _removeNamedNode(this._ownerElement,this,attr);
  124987. return attr;
  124988. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  124989. //for level2
  124990. removeNamedItemNS:function(namespaceURI,localName){
  124991. var attr = this.getNamedItemNS(namespaceURI,localName);
  124992. _removeNamedNode(this._ownerElement,this,attr);
  124993. return attr;
  124994. },
  124995. getNamedItemNS: function(namespaceURI, localName) {
  124996. var i = this.length;
  124997. while(i--){
  124998. var node = this[i];
  124999. if(node.localName == localName && node.namespaceURI == namespaceURI){
  125000. return node;
  125001. }
  125002. }
  125003. return null;
  125004. }
  125005. };
  125006. /**
  125007. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  125008. */
  125009. function DOMImplementation(/* Object */ features) {
  125010. this._features = {};
  125011. if (features) {
  125012. for (var feature in features) {
  125013. this._features = features[feature];
  125014. }
  125015. }
  125016. };
  125017. DOMImplementation.prototype = {
  125018. hasFeature: function(/* string */ feature, /* string */ version) {
  125019. var versions = this._features[feature.toLowerCase()];
  125020. if (versions && (!version || version in versions)) {
  125021. return true;
  125022. } else {
  125023. return false;
  125024. }
  125025. },
  125026. // Introduced in DOM Level 2:
  125027. createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  125028. var doc = new Document();
  125029. doc.implementation = this;
  125030. doc.childNodes = new NodeList();
  125031. doc.doctype = doctype;
  125032. if(doctype){
  125033. doc.appendChild(doctype);
  125034. }
  125035. if(qualifiedName){
  125036. var root = doc.createElementNS(namespaceURI,qualifiedName);
  125037. doc.appendChild(root);
  125038. }
  125039. return doc;
  125040. },
  125041. // Introduced in DOM Level 2:
  125042. createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  125043. var node = new DocumentType();
  125044. node.name = qualifiedName;
  125045. node.nodeName = qualifiedName;
  125046. node.publicId = publicId;
  125047. node.systemId = systemId;
  125048. // Introduced in DOM Level 2:
  125049. //readonly attribute DOMString internalSubset;
  125050. //TODO:..
  125051. // readonly attribute NamedNodeMap entities;
  125052. // readonly attribute NamedNodeMap notations;
  125053. return node;
  125054. }
  125055. };
  125056. /**
  125057. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  125058. */
  125059. function Node() {
  125060. };
  125061. Node.prototype = {
  125062. firstChild : null,
  125063. lastChild : null,
  125064. previousSibling : null,
  125065. nextSibling : null,
  125066. attributes : null,
  125067. parentNode : null,
  125068. childNodes : null,
  125069. ownerDocument : null,
  125070. nodeValue : null,
  125071. namespaceURI : null,
  125072. prefix : null,
  125073. localName : null,
  125074. // Modified in DOM Level 2:
  125075. insertBefore:function(newChild, refChild){//raises
  125076. return _insertBefore(this,newChild,refChild);
  125077. },
  125078. replaceChild:function(newChild, oldChild){//raises
  125079. this.insertBefore(newChild,oldChild);
  125080. if(oldChild){
  125081. this.removeChild(oldChild);
  125082. }
  125083. },
  125084. removeChild:function(oldChild){
  125085. return _removeChild(this,oldChild);
  125086. },
  125087. appendChild:function(newChild){
  125088. return this.insertBefore(newChild,null);
  125089. },
  125090. hasChildNodes:function(){
  125091. return this.firstChild != null;
  125092. },
  125093. cloneNode:function(deep){
  125094. return cloneNode(this.ownerDocument||this,this,deep);
  125095. },
  125096. // Modified in DOM Level 2:
  125097. normalize:function(){
  125098. var child = this.firstChild;
  125099. while(child){
  125100. var next = child.nextSibling;
  125101. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  125102. this.removeChild(next);
  125103. child.appendData(next.data);
  125104. }else{
  125105. child.normalize();
  125106. child = next;
  125107. }
  125108. }
  125109. },
  125110. // Introduced in DOM Level 2:
  125111. isSupported:function(feature, version){
  125112. return this.ownerDocument.implementation.hasFeature(feature,version);
  125113. },
  125114. // Introduced in DOM Level 2:
  125115. hasAttributes:function(){
  125116. return this.attributes.length>0;
  125117. },
  125118. lookupPrefix:function(namespaceURI){
  125119. var el = this;
  125120. while(el){
  125121. var map = el._nsMap;
  125122. //console.dir(map)
  125123. if(map){
  125124. for(var n in map){
  125125. if(map[n] == namespaceURI){
  125126. return n;
  125127. }
  125128. }
  125129. }
  125130. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  125131. }
  125132. return null;
  125133. },
  125134. // Introduced in DOM Level 3:
  125135. lookupNamespaceURI:function(prefix){
  125136. var el = this;
  125137. while(el){
  125138. var map = el._nsMap;
  125139. //console.dir(map)
  125140. if(map){
  125141. if(prefix in map){
  125142. return map[prefix] ;
  125143. }
  125144. }
  125145. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  125146. }
  125147. return null;
  125148. },
  125149. // Introduced in DOM Level 3:
  125150. isDefaultNamespace:function(namespaceURI){
  125151. var prefix = this.lookupPrefix(namespaceURI);
  125152. return prefix == null;
  125153. }
  125154. };
  125155. function _xmlEncoder(c){
  125156. return c == '<' && '&lt;' ||
  125157. c == '>' && '&gt;' ||
  125158. c == '&' && '&amp;' ||
  125159. c == '"' && '&quot;' ||
  125160. '&#'+c.charCodeAt()+';'
  125161. }
  125162. copy(NodeType,Node);
  125163. copy(NodeType,Node.prototype);
  125164. /**
  125165. * @param callback return true for continue,false for break
  125166. * @return boolean true: break visit;
  125167. */
  125168. function _visitNode(node,callback){
  125169. if(callback(node)){
  125170. return true;
  125171. }
  125172. if(node = node.firstChild){
  125173. do{
  125174. if(_visitNode(node,callback)){return true}
  125175. }while(node=node.nextSibling)
  125176. }
  125177. }
  125178. function Document(){
  125179. }
  125180. function _onAddAttribute(doc,el,newAttr){
  125181. doc && doc._inc++;
  125182. var ns = newAttr.namespaceURI ;
  125183. if(ns == 'http://www.w3.org/2000/xmlns/'){
  125184. //update namespace
  125185. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  125186. }
  125187. }
  125188. function _onRemoveAttribute(doc,el,newAttr,remove){
  125189. doc && doc._inc++;
  125190. var ns = newAttr.namespaceURI ;
  125191. if(ns == 'http://www.w3.org/2000/xmlns/'){
  125192. //update namespace
  125193. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  125194. }
  125195. }
  125196. function _onUpdateChild(doc,el,newChild){
  125197. if(doc && doc._inc){
  125198. doc._inc++;
  125199. //update childNodes
  125200. var cs = el.childNodes;
  125201. if(newChild){
  125202. cs[cs.length++] = newChild;
  125203. }else{
  125204. //console.log(1)
  125205. var child = el.firstChild;
  125206. var i = 0;
  125207. while(child){
  125208. cs[i++] = child;
  125209. child =child.nextSibling;
  125210. }
  125211. cs.length = i;
  125212. }
  125213. }
  125214. }
  125215. /**
  125216. * attributes;
  125217. * children;
  125218. *
  125219. * writeable properties:
  125220. * nodeValue,Attr:value,CharacterData:data
  125221. * prefix
  125222. */
  125223. function _removeChild(parentNode,child){
  125224. var previous = child.previousSibling;
  125225. var next = child.nextSibling;
  125226. if(previous){
  125227. previous.nextSibling = next;
  125228. }else{
  125229. parentNode.firstChild = next
  125230. }
  125231. if(next){
  125232. next.previousSibling = previous;
  125233. }else{
  125234. parentNode.lastChild = previous;
  125235. }
  125236. _onUpdateChild(parentNode.ownerDocument,parentNode);
  125237. return child;
  125238. }
  125239. /**
  125240. * preformance key(refChild == null)
  125241. */
  125242. function _insertBefore(parentNode,newChild,nextChild){
  125243. var cp = newChild.parentNode;
  125244. if(cp){
  125245. cp.removeChild(newChild);//remove and update
  125246. }
  125247. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  125248. var newFirst = newChild.firstChild;
  125249. if (newFirst == null) {
  125250. return newChild;
  125251. }
  125252. var newLast = newChild.lastChild;
  125253. }else{
  125254. newFirst = newLast = newChild;
  125255. }
  125256. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  125257. newFirst.previousSibling = pre;
  125258. newLast.nextSibling = nextChild;
  125259. if(pre){
  125260. pre.nextSibling = newFirst;
  125261. }else{
  125262. parentNode.firstChild = newFirst;
  125263. }
  125264. if(nextChild == null){
  125265. parentNode.lastChild = newLast;
  125266. }else{
  125267. nextChild.previousSibling = newLast;
  125268. }
  125269. do{
  125270. newFirst.parentNode = parentNode;
  125271. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  125272. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  125273. //console.log(parentNode.lastChild.nextSibling == null)
  125274. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  125275. newChild.firstChild = newChild.lastChild = null;
  125276. }
  125277. return newChild;
  125278. }
  125279. function _appendSingleChild(parentNode,newChild){
  125280. var cp = newChild.parentNode;
  125281. if(cp){
  125282. var pre = parentNode.lastChild;
  125283. cp.removeChild(newChild);//remove and update
  125284. var pre = parentNode.lastChild;
  125285. }
  125286. var pre = parentNode.lastChild;
  125287. newChild.parentNode = parentNode;
  125288. newChild.previousSibling = pre;
  125289. newChild.nextSibling = null;
  125290. if(pre){
  125291. pre.nextSibling = newChild;
  125292. }else{
  125293. parentNode.firstChild = newChild;
  125294. }
  125295. parentNode.lastChild = newChild;
  125296. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  125297. return newChild;
  125298. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  125299. }
  125300. Document.prototype = {
  125301. //implementation : null,
  125302. nodeName : '#document',
  125303. nodeType : DOCUMENT_NODE,
  125304. doctype : null,
  125305. documentElement : null,
  125306. _inc : 1,
  125307. insertBefore : function(newChild, refChild){//raises
  125308. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  125309. var child = newChild.firstChild;
  125310. while(child){
  125311. var next = child.nextSibling;
  125312. this.insertBefore(child,refChild);
  125313. child = next;
  125314. }
  125315. return newChild;
  125316. }
  125317. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  125318. this.documentElement = newChild;
  125319. }
  125320. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  125321. },
  125322. removeChild : function(oldChild){
  125323. if(this.documentElement == oldChild){
  125324. this.documentElement = null;
  125325. }
  125326. return _removeChild(this,oldChild);
  125327. },
  125328. // Introduced in DOM Level 2:
  125329. importNode : function(importedNode,deep){
  125330. return importNode(this,importedNode,deep);
  125331. },
  125332. // Introduced in DOM Level 2:
  125333. getElementById : function(id){
  125334. var rtv = null;
  125335. _visitNode(this.documentElement,function(node){
  125336. if(node.nodeType == ELEMENT_NODE){
  125337. if(node.getAttribute('id') == id){
  125338. rtv = node;
  125339. return true;
  125340. }
  125341. }
  125342. })
  125343. return rtv;
  125344. },
  125345. getElementsByClassName: function(className) {
  125346. var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
  125347. return new LiveNodeList(this, function(base) {
  125348. var ls = [];
  125349. _visitNode(base.documentElement, function(node) {
  125350. if(node !== base && node.nodeType == ELEMENT_NODE) {
  125351. if(pattern.test(node.getAttribute('class'))) {
  125352. ls.push(node);
  125353. }
  125354. }
  125355. });
  125356. return ls;
  125357. });
  125358. },
  125359. //document factory method:
  125360. createElement : function(tagName){
  125361. var node = new Element();
  125362. node.ownerDocument = this;
  125363. node.nodeName = tagName;
  125364. node.tagName = tagName;
  125365. node.childNodes = new NodeList();
  125366. var attrs = node.attributes = new NamedNodeMap();
  125367. attrs._ownerElement = node;
  125368. return node;
  125369. },
  125370. createDocumentFragment : function(){
  125371. var node = new DocumentFragment();
  125372. node.ownerDocument = this;
  125373. node.childNodes = new NodeList();
  125374. return node;
  125375. },
  125376. createTextNode : function(data){
  125377. var node = new Text();
  125378. node.ownerDocument = this;
  125379. node.appendData(data)
  125380. return node;
  125381. },
  125382. createComment : function(data){
  125383. var node = new Comment();
  125384. node.ownerDocument = this;
  125385. node.appendData(data)
  125386. return node;
  125387. },
  125388. createCDATASection : function(data){
  125389. var node = new CDATASection();
  125390. node.ownerDocument = this;
  125391. node.appendData(data)
  125392. return node;
  125393. },
  125394. createProcessingInstruction : function(target,data){
  125395. var node = new ProcessingInstruction();
  125396. node.ownerDocument = this;
  125397. node.tagName = node.target = target;
  125398. node.nodeValue= node.data = data;
  125399. return node;
  125400. },
  125401. createAttribute : function(name){
  125402. var node = new Attr();
  125403. node.ownerDocument = this;
  125404. node.name = name;
  125405. node.nodeName = name;
  125406. node.localName = name;
  125407. node.specified = true;
  125408. return node;
  125409. },
  125410. createEntityReference : function(name){
  125411. var node = new EntityReference();
  125412. node.ownerDocument = this;
  125413. node.nodeName = name;
  125414. return node;
  125415. },
  125416. // Introduced in DOM Level 2:
  125417. createElementNS : function(namespaceURI,qualifiedName){
  125418. var node = new Element();
  125419. var pl = qualifiedName.split(':');
  125420. var attrs = node.attributes = new NamedNodeMap();
  125421. node.childNodes = new NodeList();
  125422. node.ownerDocument = this;
  125423. node.nodeName = qualifiedName;
  125424. node.tagName = qualifiedName;
  125425. node.namespaceURI = namespaceURI;
  125426. if(pl.length == 2){
  125427. node.prefix = pl[0];
  125428. node.localName = pl[1];
  125429. }else{
  125430. //el.prefix = null;
  125431. node.localName = qualifiedName;
  125432. }
  125433. attrs._ownerElement = node;
  125434. return node;
  125435. },
  125436. // Introduced in DOM Level 2:
  125437. createAttributeNS : function(namespaceURI,qualifiedName){
  125438. var node = new Attr();
  125439. var pl = qualifiedName.split(':');
  125440. node.ownerDocument = this;
  125441. node.nodeName = qualifiedName;
  125442. node.name = qualifiedName;
  125443. node.namespaceURI = namespaceURI;
  125444. node.specified = true;
  125445. if(pl.length == 2){
  125446. node.prefix = pl[0];
  125447. node.localName = pl[1];
  125448. }else{
  125449. //el.prefix = null;
  125450. node.localName = qualifiedName;
  125451. }
  125452. return node;
  125453. }
  125454. };
  125455. _extends(Document,Node);
  125456. function Element() {
  125457. this._nsMap = {};
  125458. };
  125459. Element.prototype = {
  125460. nodeType : ELEMENT_NODE,
  125461. hasAttribute : function(name){
  125462. return this.getAttributeNode(name)!=null;
  125463. },
  125464. getAttribute : function(name){
  125465. var attr = this.getAttributeNode(name);
  125466. return attr && attr.value || '';
  125467. },
  125468. getAttributeNode : function(name){
  125469. return this.attributes.getNamedItem(name);
  125470. },
  125471. setAttribute : function(name, value){
  125472. var attr = this.ownerDocument.createAttribute(name);
  125473. attr.value = attr.nodeValue = "" + value;
  125474. this.setAttributeNode(attr)
  125475. },
  125476. removeAttribute : function(name){
  125477. var attr = this.getAttributeNode(name)
  125478. attr && this.removeAttributeNode(attr);
  125479. },
  125480. //four real opeartion method
  125481. appendChild:function(newChild){
  125482. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  125483. return this.insertBefore(newChild,null);
  125484. }else{
  125485. return _appendSingleChild(this,newChild);
  125486. }
  125487. },
  125488. setAttributeNode : function(newAttr){
  125489. return this.attributes.setNamedItem(newAttr);
  125490. },
  125491. setAttributeNodeNS : function(newAttr){
  125492. return this.attributes.setNamedItemNS(newAttr);
  125493. },
  125494. removeAttributeNode : function(oldAttr){
  125495. //console.log(this == oldAttr.ownerElement)
  125496. return this.attributes.removeNamedItem(oldAttr.nodeName);
  125497. },
  125498. //get real attribute name,and remove it by removeAttributeNode
  125499. removeAttributeNS : function(namespaceURI, localName){
  125500. var old = this.getAttributeNodeNS(namespaceURI, localName);
  125501. old && this.removeAttributeNode(old);
  125502. },
  125503. hasAttributeNS : function(namespaceURI, localName){
  125504. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  125505. },
  125506. getAttributeNS : function(namespaceURI, localName){
  125507. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  125508. return attr && attr.value || '';
  125509. },
  125510. setAttributeNS : function(namespaceURI, qualifiedName, value){
  125511. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  125512. attr.value = attr.nodeValue = "" + value;
  125513. this.setAttributeNode(attr)
  125514. },
  125515. getAttributeNodeNS : function(namespaceURI, localName){
  125516. return this.attributes.getNamedItemNS(namespaceURI, localName);
  125517. },
  125518. getElementsByTagName : function(tagName){
  125519. return new LiveNodeList(this,function(base){
  125520. var ls = [];
  125521. _visitNode(base,function(node){
  125522. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  125523. ls.push(node);
  125524. }
  125525. });
  125526. return ls;
  125527. });
  125528. },
  125529. getElementsByTagNameNS : function(namespaceURI, localName){
  125530. return new LiveNodeList(this,function(base){
  125531. var ls = [];
  125532. _visitNode(base,function(node){
  125533. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  125534. ls.push(node);
  125535. }
  125536. });
  125537. return ls;
  125538. });
  125539. }
  125540. };
  125541. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  125542. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  125543. _extends(Element,Node);
  125544. function Attr() {
  125545. };
  125546. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  125547. _extends(Attr,Node);
  125548. function CharacterData() {
  125549. };
  125550. CharacterData.prototype = {
  125551. data : '',
  125552. substringData : function(offset, count) {
  125553. return this.data.substring(offset, offset+count);
  125554. },
  125555. appendData: function(text) {
  125556. text = this.data+text;
  125557. this.nodeValue = this.data = text;
  125558. this.length = text.length;
  125559. },
  125560. insertData: function(offset,text) {
  125561. this.replaceData(offset,0,text);
  125562. },
  125563. appendChild:function(newChild){
  125564. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  125565. },
  125566. deleteData: function(offset, count) {
  125567. this.replaceData(offset,count,"");
  125568. },
  125569. replaceData: function(offset, count, text) {
  125570. var start = this.data.substring(0,offset);
  125571. var end = this.data.substring(offset+count);
  125572. text = start + text + end;
  125573. this.nodeValue = this.data = text;
  125574. this.length = text.length;
  125575. }
  125576. }
  125577. _extends(CharacterData,Node);
  125578. function Text() {
  125579. };
  125580. Text.prototype = {
  125581. nodeName : "#text",
  125582. nodeType : TEXT_NODE,
  125583. splitText : function(offset) {
  125584. var text = this.data;
  125585. var newText = text.substring(offset);
  125586. text = text.substring(0, offset);
  125587. this.data = this.nodeValue = text;
  125588. this.length = text.length;
  125589. var newNode = this.ownerDocument.createTextNode(newText);
  125590. if(this.parentNode){
  125591. this.parentNode.insertBefore(newNode, this.nextSibling);
  125592. }
  125593. return newNode;
  125594. }
  125595. }
  125596. _extends(Text,CharacterData);
  125597. function Comment() {
  125598. };
  125599. Comment.prototype = {
  125600. nodeName : "#comment",
  125601. nodeType : COMMENT_NODE
  125602. }
  125603. _extends(Comment,CharacterData);
  125604. function CDATASection() {
  125605. };
  125606. CDATASection.prototype = {
  125607. nodeName : "#cdata-section",
  125608. nodeType : CDATA_SECTION_NODE
  125609. }
  125610. _extends(CDATASection,CharacterData);
  125611. function DocumentType() {
  125612. };
  125613. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  125614. _extends(DocumentType,Node);
  125615. function Notation() {
  125616. };
  125617. Notation.prototype.nodeType = NOTATION_NODE;
  125618. _extends(Notation,Node);
  125619. function Entity() {
  125620. };
  125621. Entity.prototype.nodeType = ENTITY_NODE;
  125622. _extends(Entity,Node);
  125623. function EntityReference() {
  125624. };
  125625. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  125626. _extends(EntityReference,Node);
  125627. function DocumentFragment() {
  125628. };
  125629. DocumentFragment.prototype.nodeName = "#document-fragment";
  125630. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  125631. _extends(DocumentFragment,Node);
  125632. function ProcessingInstruction() {
  125633. }
  125634. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  125635. _extends(ProcessingInstruction,Node);
  125636. function XMLSerializer(){}
  125637. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  125638. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  125639. }
  125640. Node.prototype.toString = nodeSerializeToString;
  125641. function nodeSerializeToString(isHtml,nodeFilter){
  125642. var buf = [];
  125643. var refNode = this.nodeType == 9 && this.documentElement || this;
  125644. var prefix = refNode.prefix;
  125645. var uri = refNode.namespaceURI;
  125646. if(uri && prefix == null){
  125647. //console.log(prefix)
  125648. var prefix = refNode.lookupPrefix(uri);
  125649. if(prefix == null){
  125650. //isHTML = true;
  125651. var visibleNamespaces=[
  125652. {namespace:uri,prefix:null}
  125653. //{namespace:uri,prefix:''}
  125654. ]
  125655. }
  125656. }
  125657. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  125658. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  125659. return buf.join('');
  125660. }
  125661. function needNamespaceDefine(node,isHTML, visibleNamespaces) {
  125662. var prefix = node.prefix||'';
  125663. var uri = node.namespaceURI;
  125664. if (!prefix && !uri){
  125665. return false;
  125666. }
  125667. if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
  125668. || uri == 'http://www.w3.org/2000/xmlns/'){
  125669. return false;
  125670. }
  125671. var i = visibleNamespaces.length
  125672. //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
  125673. while (i--) {
  125674. var ns = visibleNamespaces[i];
  125675. // get namespace prefix
  125676. //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
  125677. if (ns.prefix == prefix){
  125678. return ns.namespace != uri;
  125679. }
  125680. }
  125681. //console.log(isHTML,uri,prefix=='')
  125682. //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  125683. // return false;
  125684. //}
  125685. //node.flag = '11111'
  125686. //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
  125687. return true;
  125688. }
  125689. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  125690. if(nodeFilter){
  125691. node = nodeFilter(node);
  125692. if(node){
  125693. if(typeof node == 'string'){
  125694. buf.push(node);
  125695. return;
  125696. }
  125697. }else{
  125698. return;
  125699. }
  125700. //buf.sort.apply(attrs, attributeSorter);
  125701. }
  125702. switch(node.nodeType){
  125703. case ELEMENT_NODE:
  125704. if (!visibleNamespaces) visibleNamespaces = [];
  125705. var startVisibleNamespaces = visibleNamespaces.length;
  125706. var attrs = node.attributes;
  125707. var len = attrs.length;
  125708. var child = node.firstChild;
  125709. var nodeName = node.tagName;
  125710. isHTML = (htmlns === node.namespaceURI) ||isHTML
  125711. buf.push('<',nodeName);
  125712. for(var i=0;i<len;i++){
  125713. // add namespaces for attributes
  125714. var attr = attrs.item(i);
  125715. if (attr.prefix == 'xmlns') {
  125716. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  125717. }else if(attr.nodeName == 'xmlns'){
  125718. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  125719. }
  125720. }
  125721. for(var i=0;i<len;i++){
  125722. var attr = attrs.item(i);
  125723. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  125724. var prefix = attr.prefix||'';
  125725. var uri = attr.namespaceURI;
  125726. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  125727. buf.push(ns, '="' , uri , '"');
  125728. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  125729. }
  125730. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  125731. }
  125732. // add namespace for current node
  125733. if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
  125734. var prefix = node.prefix||'';
  125735. var uri = node.namespaceURI;
  125736. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  125737. buf.push(ns, '="' , uri , '"');
  125738. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  125739. }
  125740. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  125741. buf.push('>');
  125742. //if is cdata child node
  125743. if(isHTML && /^script$/i.test(nodeName)){
  125744. while(child){
  125745. if(child.data){
  125746. buf.push(child.data);
  125747. }else{
  125748. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  125749. }
  125750. child = child.nextSibling;
  125751. }
  125752. }else
  125753. {
  125754. while(child){
  125755. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  125756. child = child.nextSibling;
  125757. }
  125758. }
  125759. buf.push('</',nodeName,'>');
  125760. }else{
  125761. buf.push('/>');
  125762. }
  125763. // remove added visible namespaces
  125764. //visibleNamespaces.length = startVisibleNamespaces;
  125765. return;
  125766. case DOCUMENT_NODE:
  125767. case DOCUMENT_FRAGMENT_NODE:
  125768. var child = node.firstChild;
  125769. while(child){
  125770. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  125771. child = child.nextSibling;
  125772. }
  125773. return;
  125774. case ATTRIBUTE_NODE:
  125775. return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
  125776. case TEXT_NODE:
  125777. return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
  125778. case CDATA_SECTION_NODE:
  125779. return buf.push( '<![CDATA[',node.data,']]>');
  125780. case COMMENT_NODE:
  125781. return buf.push( "<!--",node.data,"-->");
  125782. case DOCUMENT_TYPE_NODE:
  125783. var pubid = node.publicId;
  125784. var sysid = node.systemId;
  125785. buf.push('<!DOCTYPE ',node.name);
  125786. if(pubid){
  125787. buf.push(' PUBLIC "',pubid);
  125788. if (sysid && sysid!='.') {
  125789. buf.push( '" "',sysid);
  125790. }
  125791. buf.push('">');
  125792. }else if(sysid && sysid!='.'){
  125793. buf.push(' SYSTEM "',sysid,'">');
  125794. }else{
  125795. var sub = node.internalSubset;
  125796. if(sub){
  125797. buf.push(" [",sub,"]");
  125798. }
  125799. buf.push(">");
  125800. }
  125801. return;
  125802. case PROCESSING_INSTRUCTION_NODE:
  125803. return buf.push( "<?",node.target," ",node.data,"?>");
  125804. case ENTITY_REFERENCE_NODE:
  125805. return buf.push( '&',node.nodeName,';');
  125806. //case ENTITY_NODE:
  125807. //case NOTATION_NODE:
  125808. default:
  125809. buf.push('??',node.nodeName);
  125810. }
  125811. }
  125812. function importNode(doc,node,deep){
  125813. var node2;
  125814. switch (node.nodeType) {
  125815. case ELEMENT_NODE:
  125816. node2 = node.cloneNode(false);
  125817. node2.ownerDocument = doc;
  125818. //var attrs = node2.attributes;
  125819. //var len = attrs.length;
  125820. //for(var i=0;i<len;i++){
  125821. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  125822. //}
  125823. case DOCUMENT_FRAGMENT_NODE:
  125824. break;
  125825. case ATTRIBUTE_NODE:
  125826. deep = true;
  125827. break;
  125828. //case ENTITY_REFERENCE_NODE:
  125829. //case PROCESSING_INSTRUCTION_NODE:
  125830. ////case TEXT_NODE:
  125831. //case CDATA_SECTION_NODE:
  125832. //case COMMENT_NODE:
  125833. // deep = false;
  125834. // break;
  125835. //case DOCUMENT_NODE:
  125836. //case DOCUMENT_TYPE_NODE:
  125837. //cannot be imported.
  125838. //case ENTITY_NODE:
  125839. //case NOTATION_NODE:
  125840. //can not hit in level3
  125841. //default:throw e;
  125842. }
  125843. if(!node2){
  125844. node2 = node.cloneNode(false);//false
  125845. }
  125846. node2.ownerDocument = doc;
  125847. node2.parentNode = null;
  125848. if(deep){
  125849. var child = node.firstChild;
  125850. while(child){
  125851. node2.appendChild(importNode(doc,child,deep));
  125852. child = child.nextSibling;
  125853. }
  125854. }
  125855. return node2;
  125856. }
  125857. //
  125858. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  125859. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  125860. function cloneNode(doc,node,deep){
  125861. var node2 = new node.constructor();
  125862. for(var n in node){
  125863. var v = node[n];
  125864. if(typeof v != 'object' ){
  125865. if(v != node2[n]){
  125866. node2[n] = v;
  125867. }
  125868. }
  125869. }
  125870. if(node.childNodes){
  125871. node2.childNodes = new NodeList();
  125872. }
  125873. node2.ownerDocument = doc;
  125874. switch (node2.nodeType) {
  125875. case ELEMENT_NODE:
  125876. var attrs = node.attributes;
  125877. var attrs2 = node2.attributes = new NamedNodeMap();
  125878. var len = attrs.length
  125879. attrs2._ownerElement = node2;
  125880. for(var i=0;i<len;i++){
  125881. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  125882. }
  125883. break;;
  125884. case ATTRIBUTE_NODE:
  125885. deep = true;
  125886. }
  125887. if(deep){
  125888. var child = node.firstChild;
  125889. while(child){
  125890. node2.appendChild(cloneNode(doc,child,deep));
  125891. child = child.nextSibling;
  125892. }
  125893. }
  125894. return node2;
  125895. }
  125896. function __set__(object,key,value){
  125897. object[key] = value
  125898. }
  125899. //do dynamic
  125900. try{
  125901. if(Object.defineProperty){
  125902. Object.defineProperty(LiveNodeList.prototype,'length',{
  125903. get:function(){
  125904. _updateLiveList(this);
  125905. return this.$$length;
  125906. }
  125907. });
  125908. Object.defineProperty(Node.prototype,'textContent',{
  125909. get:function(){
  125910. return getTextContent(this);
  125911. },
  125912. set:function(data){
  125913. switch(this.nodeType){
  125914. case ELEMENT_NODE:
  125915. case DOCUMENT_FRAGMENT_NODE:
  125916. while(this.firstChild){
  125917. this.removeChild(this.firstChild);
  125918. }
  125919. if(data || String(data)){
  125920. this.appendChild(this.ownerDocument.createTextNode(data));
  125921. }
  125922. break;
  125923. default:
  125924. //TODO:
  125925. this.data = data;
  125926. this.value = data;
  125927. this.nodeValue = data;
  125928. }
  125929. }
  125930. })
  125931. function getTextContent(node){
  125932. switch(node.nodeType){
  125933. case ELEMENT_NODE:
  125934. case DOCUMENT_FRAGMENT_NODE:
  125935. var buf = [];
  125936. node = node.firstChild;
  125937. while(node){
  125938. if(node.nodeType!==7 && node.nodeType !==8){
  125939. buf.push(getTextContent(node));
  125940. }
  125941. node = node.nextSibling;
  125942. }
  125943. return buf.join('');
  125944. default:
  125945. return node.nodeValue;
  125946. }
  125947. }
  125948. __set__ = function(object,key,value){
  125949. //console.log(value)
  125950. object['$$'+key] = value
  125951. }
  125952. }
  125953. }catch(e){//ie8
  125954. }
  125955. //if(typeof require == 'function'){
  125956. exports.Node = Node;
  125957. exports.DOMImplementation = DOMImplementation;
  125958. exports.XMLSerializer = XMLSerializer;
  125959. //}
  125960. },{}],707:[function(require,module,exports){
  125961. exports.entityMap = {
  125962. lt: '<',
  125963. gt: '>',
  125964. amp: '&',
  125965. quot: '"',
  125966. apos: "'",
  125967. Agrave: "À",
  125968. Aacute: "Á",
  125969. Acirc: "Â",
  125970. Atilde: "Ã",
  125971. Auml: "Ä",
  125972. Aring: "Å",
  125973. AElig: "Æ",
  125974. Ccedil: "Ç",
  125975. Egrave: "È",
  125976. Eacute: "É",
  125977. Ecirc: "Ê",
  125978. Euml: "Ë",
  125979. Igrave: "Ì",
  125980. Iacute: "Í",
  125981. Icirc: "Î",
  125982. Iuml: "Ï",
  125983. ETH: "Ð",
  125984. Ntilde: "Ñ",
  125985. Ograve: "Ò",
  125986. Oacute: "Ó",
  125987. Ocirc: "Ô",
  125988. Otilde: "Õ",
  125989. Ouml: "Ö",
  125990. Oslash: "Ø",
  125991. Ugrave: "Ù",
  125992. Uacute: "Ú",
  125993. Ucirc: "Û",
  125994. Uuml: "Ü",
  125995. Yacute: "Ý",
  125996. THORN: "Þ",
  125997. szlig: "ß",
  125998. agrave: "à",
  125999. aacute: "á",
  126000. acirc: "â",
  126001. atilde: "ã",
  126002. auml: "ä",
  126003. aring: "å",
  126004. aelig: "æ",
  126005. ccedil: "ç",
  126006. egrave: "è",
  126007. eacute: "é",
  126008. ecirc: "ê",
  126009. euml: "ë",
  126010. igrave: "ì",
  126011. iacute: "í",
  126012. icirc: "î",
  126013. iuml: "ï",
  126014. eth: "ð",
  126015. ntilde: "ñ",
  126016. ograve: "ò",
  126017. oacute: "ó",
  126018. ocirc: "ô",
  126019. otilde: "õ",
  126020. ouml: "ö",
  126021. oslash: "ø",
  126022. ugrave: "ù",
  126023. uacute: "ú",
  126024. ucirc: "û",
  126025. uuml: "ü",
  126026. yacute: "ý",
  126027. thorn: "þ",
  126028. yuml: "ÿ",
  126029. nbsp: "\u00a0",
  126030. iexcl: "¡",
  126031. cent: "¢",
  126032. pound: "£",
  126033. curren: "¤",
  126034. yen: "¥",
  126035. brvbar: "¦",
  126036. sect: "§",
  126037. uml: "¨",
  126038. copy: "©",
  126039. ordf: "ª",
  126040. laquo: "«",
  126041. not: "¬",
  126042. shy: "­­",
  126043. reg: "®",
  126044. macr: "¯",
  126045. deg: "°",
  126046. plusmn: "±",
  126047. sup2: "²",
  126048. sup3: "³",
  126049. acute: "´",
  126050. micro: "µ",
  126051. para: "¶",
  126052. middot: "·",
  126053. cedil: "¸",
  126054. sup1: "¹",
  126055. ordm: "º",
  126056. raquo: "»",
  126057. frac14: "¼",
  126058. frac12: "½",
  126059. frac34: "¾",
  126060. iquest: "¿",
  126061. times: "×",
  126062. divide: "÷",
  126063. forall: "∀",
  126064. part: "∂",
  126065. exist: "∃",
  126066. empty: "∅",
  126067. nabla: "∇",
  126068. isin: "∈",
  126069. notin: "∉",
  126070. ni: "∋",
  126071. prod: "∏",
  126072. sum: "∑",
  126073. minus: "−",
  126074. lowast: "∗",
  126075. radic: "√",
  126076. prop: "∝",
  126077. infin: "∞",
  126078. ang: "∠",
  126079. and: "∧",
  126080. or: "∨",
  126081. cap: "∩",
  126082. cup: "∪",
  126083. 'int': "∫",
  126084. there4: "∴",
  126085. sim: "∼",
  126086. cong: "≅",
  126087. asymp: "≈",
  126088. ne: "≠",
  126089. equiv: "≡",
  126090. le: "≤",
  126091. ge: "≥",
  126092. sub: "⊂",
  126093. sup: "⊃",
  126094. nsub: "⊄",
  126095. sube: "⊆",
  126096. supe: "⊇",
  126097. oplus: "⊕",
  126098. otimes: "⊗",
  126099. perp: "⊥",
  126100. sdot: "⋅",
  126101. Alpha: "Α",
  126102. Beta: "Β",
  126103. Gamma: "Γ",
  126104. Delta: "Δ",
  126105. Epsilon: "Ε",
  126106. Zeta: "Ζ",
  126107. Eta: "Η",
  126108. Theta: "Θ",
  126109. Iota: "Ι",
  126110. Kappa: "Κ",
  126111. Lambda: "Λ",
  126112. Mu: "Μ",
  126113. Nu: "Ν",
  126114. Xi: "Ξ",
  126115. Omicron: "Ο",
  126116. Pi: "Π",
  126117. Rho: "Ρ",
  126118. Sigma: "Σ",
  126119. Tau: "Τ",
  126120. Upsilon: "Υ",
  126121. Phi: "Φ",
  126122. Chi: "Χ",
  126123. Psi: "Ψ",
  126124. Omega: "Ω",
  126125. alpha: "α",
  126126. beta: "β",
  126127. gamma: "γ",
  126128. delta: "δ",
  126129. epsilon: "ε",
  126130. zeta: "ζ",
  126131. eta: "η",
  126132. theta: "θ",
  126133. iota: "ι",
  126134. kappa: "κ",
  126135. lambda: "λ",
  126136. mu: "μ",
  126137. nu: "ν",
  126138. xi: "ξ",
  126139. omicron: "ο",
  126140. pi: "π",
  126141. rho: "ρ",
  126142. sigmaf: "ς",
  126143. sigma: "σ",
  126144. tau: "τ",
  126145. upsilon: "υ",
  126146. phi: "φ",
  126147. chi: "χ",
  126148. psi: "ψ",
  126149. omega: "ω",
  126150. thetasym: "ϑ",
  126151. upsih: "ϒ",
  126152. piv: "ϖ",
  126153. OElig: "Œ",
  126154. oelig: "œ",
  126155. Scaron: "Š",
  126156. scaron: "š",
  126157. Yuml: "Ÿ",
  126158. fnof: "ƒ",
  126159. circ: "ˆ",
  126160. tilde: "˜",
  126161. ensp: " ",
  126162. emsp: " ",
  126163. thinsp: " ",
  126164. zwnj: "‌",
  126165. zwj: "‍",
  126166. lrm: "‎",
  126167. rlm: "‏",
  126168. ndash: "–",
  126169. mdash: "—",
  126170. lsquo: "‘",
  126171. rsquo: "’",
  126172. sbquo: "‚",
  126173. ldquo: "“",
  126174. rdquo: "”",
  126175. bdquo: "„",
  126176. dagger: "†",
  126177. Dagger: "‡",
  126178. bull: "•",
  126179. hellip: "…",
  126180. permil: "‰",
  126181. prime: "′",
  126182. Prime: "″",
  126183. lsaquo: "‹",
  126184. rsaquo: "›",
  126185. oline: "‾",
  126186. euro: "€",
  126187. trade: "™",
  126188. larr: "←",
  126189. uarr: "↑",
  126190. rarr: "→",
  126191. darr: "↓",
  126192. harr: "↔",
  126193. crarr: "↵",
  126194. lceil: "⌈",
  126195. rceil: "⌉",
  126196. lfloor: "⌊",
  126197. rfloor: "⌋",
  126198. loz: "◊",
  126199. spades: "♠",
  126200. clubs: "♣",
  126201. hearts: "♥",
  126202. diams: "♦"
  126203. };
  126204. },{}],708:[function(require,module,exports){
  126205. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  126206. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  126207. //[5] Name ::= NameStartChar (NameChar)*
  126208. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
  126209. var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  126210. var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
  126211. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  126212. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  126213. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  126214. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  126215. var S_TAG = 0;//tag name offerring
  126216. var S_ATTR = 1;//attr name offerring
  126217. var S_ATTR_SPACE=2;//attr name end and space offer
  126218. var S_EQ = 3;//=space?
  126219. var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
  126220. var S_ATTR_END = 5;//attr value end and no space(quot end)
  126221. var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
  126222. var S_TAG_CLOSE = 7;//closed el<el />
  126223. function XMLReader(){
  126224. }
  126225. XMLReader.prototype = {
  126226. parse:function(source,defaultNSMap,entityMap){
  126227. var domBuilder = this.domBuilder;
  126228. domBuilder.startDocument();
  126229. _copy(defaultNSMap ,defaultNSMap = {})
  126230. parse(source,defaultNSMap,entityMap,
  126231. domBuilder,this.errorHandler);
  126232. domBuilder.endDocument();
  126233. }
  126234. }
  126235. function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
  126236. function fixedFromCharCode(code) {
  126237. // String.prototype.fromCharCode does not supports
  126238. // > 2 bytes unicode chars directly
  126239. if (code > 0xffff) {
  126240. code -= 0x10000;
  126241. var surrogate1 = 0xd800 + (code >> 10)
  126242. , surrogate2 = 0xdc00 + (code & 0x3ff);
  126243. return String.fromCharCode(surrogate1, surrogate2);
  126244. } else {
  126245. return String.fromCharCode(code);
  126246. }
  126247. }
  126248. function entityReplacer(a){
  126249. var k = a.slice(1,-1);
  126250. if(k in entityMap){
  126251. return entityMap[k];
  126252. }else if(k.charAt(0) === '#'){
  126253. return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
  126254. }else{
  126255. errorHandler.error('entity not found:'+a);
  126256. return a;
  126257. }
  126258. }
  126259. function appendText(end){//has some bugs
  126260. if(end>start){
  126261. var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
  126262. locator&&position(start);
  126263. domBuilder.characters(xt,0,end-start);
  126264. start = end
  126265. }
  126266. }
  126267. function position(p,m){
  126268. while(p>=lineEnd && (m = linePattern.exec(source))){
  126269. lineStart = m.index;
  126270. lineEnd = lineStart + m[0].length;
  126271. locator.lineNumber++;
  126272. //console.log('line++:',locator,startPos,endPos)
  126273. }
  126274. locator.columnNumber = p-lineStart+1;
  126275. }
  126276. var lineStart = 0;
  126277. var lineEnd = 0;
  126278. var linePattern = /.*(?:\r\n?|\n)|.*$/g
  126279. var locator = domBuilder.locator;
  126280. var parseStack = [{currentNSMap:defaultNSMapCopy}]
  126281. var closeMap = {};
  126282. var start = 0;
  126283. while(true){
  126284. try{
  126285. var tagStart = source.indexOf('<',start);
  126286. if(tagStart<0){
  126287. if(!source.substr(start).match(/^\s*$/)){
  126288. var doc = domBuilder.doc;
  126289. var text = doc.createTextNode(source.substr(start));
  126290. doc.appendChild(text);
  126291. domBuilder.currentElement = text;
  126292. }
  126293. return;
  126294. }
  126295. if(tagStart>start){
  126296. appendText(tagStart);
  126297. }
  126298. switch(source.charAt(tagStart+1)){
  126299. case '/':
  126300. var end = source.indexOf('>',tagStart+3);
  126301. var tagName = source.substring(tagStart+2,end);
  126302. var config = parseStack.pop();
  126303. if(end<0){
  126304. tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
  126305. //console.error('#@@@@@@'+tagName)
  126306. errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
  126307. end = tagStart+1+tagName.length;
  126308. }else if(tagName.match(/\s</)){
  126309. tagName = tagName.replace(/[\s<].*/,'');
  126310. errorHandler.error("end tag name: "+tagName+' maybe not complete');
  126311. end = tagStart+1+tagName.length;
  126312. }
  126313. //console.error(parseStack.length,parseStack)
  126314. //console.error(config);
  126315. var localNSMap = config.localNSMap;
  126316. var endMatch = config.tagName == tagName;
  126317. var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
  126318. if(endIgnoreCaseMach){
  126319. domBuilder.endElement(config.uri,config.localName,tagName);
  126320. if(localNSMap){
  126321. for(var prefix in localNSMap){
  126322. domBuilder.endPrefixMapping(prefix) ;
  126323. }
  126324. }
  126325. if(!endMatch){
  126326. errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
  126327. }
  126328. }else{
  126329. parseStack.push(config)
  126330. }
  126331. end++;
  126332. break;
  126333. // end elment
  126334. case '?':// <?...?>
  126335. locator&&position(tagStart);
  126336. end = parseInstruction(source,tagStart,domBuilder);
  126337. break;
  126338. case '!':// <!doctype,<![CDATA,<!--
  126339. locator&&position(tagStart);
  126340. end = parseDCC(source,tagStart,domBuilder,errorHandler);
  126341. break;
  126342. default:
  126343. locator&&position(tagStart);
  126344. var el = new ElementAttributes();
  126345. var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  126346. //elStartEnd
  126347. var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
  126348. var len = el.length;
  126349. if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
  126350. el.closed = true;
  126351. if(!entityMap.nbsp){
  126352. errorHandler.warning('unclosed xml attribute');
  126353. }
  126354. }
  126355. if(locator && len){
  126356. var locator2 = copyLocator(locator,{});
  126357. //try{//attribute position fixed
  126358. for(var i = 0;i<len;i++){
  126359. var a = el[i];
  126360. position(a.offset);
  126361. a.locator = copyLocator(locator,{});
  126362. }
  126363. //}catch(e){console.error('@@@@@'+e)}
  126364. domBuilder.locator = locator2
  126365. if(appendElement(el,domBuilder,currentNSMap)){
  126366. parseStack.push(el)
  126367. }
  126368. domBuilder.locator = locator;
  126369. }else{
  126370. if(appendElement(el,domBuilder,currentNSMap)){
  126371. parseStack.push(el)
  126372. }
  126373. }
  126374. if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
  126375. end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
  126376. }else{
  126377. end++;
  126378. }
  126379. }
  126380. }catch(e){
  126381. errorHandler.error('element parse error: '+e)
  126382. //errorHandler.error('element parse error: '+e);
  126383. end = -1;
  126384. //throw e;
  126385. }
  126386. if(end>start){
  126387. start = end;
  126388. }else{
  126389. //TODO: 这里有可能sax回退,有位置错误风险
  126390. appendText(Math.max(tagStart,start)+1);
  126391. }
  126392. }
  126393. }
  126394. function copyLocator(f,t){
  126395. t.lineNumber = f.lineNumber;
  126396. t.columnNumber = f.columnNumber;
  126397. return t;
  126398. }
  126399. /**
  126400. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  126401. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  126402. */
  126403. function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
  126404. var attrName;
  126405. var value;
  126406. var p = ++start;
  126407. var s = S_TAG;//status
  126408. while(true){
  126409. var c = source.charAt(p);
  126410. switch(c){
  126411. case '=':
  126412. if(s === S_ATTR){//attrName
  126413. attrName = source.slice(start,p);
  126414. s = S_EQ;
  126415. }else if(s === S_ATTR_SPACE){
  126416. s = S_EQ;
  126417. }else{
  126418. //fatalError: equal must after attrName or space after attrName
  126419. throw new Error('attribute equal must after attrName');
  126420. }
  126421. break;
  126422. case '\'':
  126423. case '"':
  126424. if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  126425. ){//equal
  126426. if(s === S_ATTR){
  126427. errorHandler.warning('attribute value must after "="')
  126428. attrName = source.slice(start,p)
  126429. }
  126430. start = p+1;
  126431. p = source.indexOf(c,start)
  126432. if(p>0){
  126433. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  126434. el.add(attrName,value,start-1);
  126435. s = S_ATTR_END;
  126436. }else{
  126437. //fatalError: no end quot match
  126438. throw new Error('attribute value no end \''+c+'\' match');
  126439. }
  126440. }else if(s == S_ATTR_NOQUOT_VALUE){
  126441. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  126442. //console.log(attrName,value,start,p)
  126443. el.add(attrName,value,start);
  126444. //console.dir(el)
  126445. errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
  126446. start = p+1;
  126447. s = S_ATTR_END
  126448. }else{
  126449. //fatalError: no equal before
  126450. throw new Error('attribute value must after "="');
  126451. }
  126452. break;
  126453. case '/':
  126454. switch(s){
  126455. case S_TAG:
  126456. el.setTagName(source.slice(start,p));
  126457. case S_ATTR_END:
  126458. case S_TAG_SPACE:
  126459. case S_TAG_CLOSE:
  126460. s =S_TAG_CLOSE;
  126461. el.closed = true;
  126462. case S_ATTR_NOQUOT_VALUE:
  126463. case S_ATTR:
  126464. case S_ATTR_SPACE:
  126465. break;
  126466. //case S_EQ:
  126467. default:
  126468. throw new Error("attribute invalid close char('/')")
  126469. }
  126470. break;
  126471. case ''://end document
  126472. //throw new Error('unexpected end of input')
  126473. errorHandler.error('unexpected end of input');
  126474. if(s == S_TAG){
  126475. el.setTagName(source.slice(start,p));
  126476. }
  126477. return p;
  126478. case '>':
  126479. switch(s){
  126480. case S_TAG:
  126481. el.setTagName(source.slice(start,p));
  126482. case S_ATTR_END:
  126483. case S_TAG_SPACE:
  126484. case S_TAG_CLOSE:
  126485. break;//normal
  126486. case S_ATTR_NOQUOT_VALUE://Compatible state
  126487. case S_ATTR:
  126488. value = source.slice(start,p);
  126489. if(value.slice(-1) === '/'){
  126490. el.closed = true;
  126491. value = value.slice(0,-1)
  126492. }
  126493. case S_ATTR_SPACE:
  126494. if(s === S_ATTR_SPACE){
  126495. value = attrName;
  126496. }
  126497. if(s == S_ATTR_NOQUOT_VALUE){
  126498. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  126499. el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
  126500. }else{
  126501. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
  126502. errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
  126503. }
  126504. el.add(value,value,start)
  126505. }
  126506. break;
  126507. case S_EQ:
  126508. throw new Error('attribute value missed!!');
  126509. }
  126510. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  126511. return p;
  126512. /*xml space '\x20' | #x9 | #xD | #xA; */
  126513. case '\u0080':
  126514. c = ' ';
  126515. default:
  126516. if(c<= ' '){//space
  126517. switch(s){
  126518. case S_TAG:
  126519. el.setTagName(source.slice(start,p));//tagName
  126520. s = S_TAG_SPACE;
  126521. break;
  126522. case S_ATTR:
  126523. attrName = source.slice(start,p)
  126524. s = S_ATTR_SPACE;
  126525. break;
  126526. case S_ATTR_NOQUOT_VALUE:
  126527. var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  126528. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  126529. el.add(attrName,value,start)
  126530. case S_ATTR_END:
  126531. s = S_TAG_SPACE;
  126532. break;
  126533. //case S_TAG_SPACE:
  126534. //case S_EQ:
  126535. //case S_ATTR_SPACE:
  126536. // void();break;
  126537. //case S_TAG_CLOSE:
  126538. //ignore warning
  126539. }
  126540. }else{//not space
  126541. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  126542. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  126543. switch(s){
  126544. //case S_TAG:void();break;
  126545. //case S_ATTR:void();break;
  126546. //case S_ATTR_NOQUOT_VALUE:void();break;
  126547. case S_ATTR_SPACE:
  126548. var tagName = el.tagName;
  126549. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
  126550. errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
  126551. }
  126552. el.add(attrName,attrName,start);
  126553. start = p;
  126554. s = S_ATTR;
  126555. break;
  126556. case S_ATTR_END:
  126557. errorHandler.warning('attribute space is required"'+attrName+'"!!')
  126558. case S_TAG_SPACE:
  126559. s = S_ATTR;
  126560. start = p;
  126561. break;
  126562. case S_EQ:
  126563. s = S_ATTR_NOQUOT_VALUE;
  126564. start = p;
  126565. break;
  126566. case S_TAG_CLOSE:
  126567. throw new Error("elements closed character '/' and '>' must be connected to");
  126568. }
  126569. }
  126570. }//end outer switch
  126571. //console.log('p++',p)
  126572. p++;
  126573. }
  126574. }
  126575. /**
  126576. * @return true if has new namespace define
  126577. */
  126578. function appendElement(el,domBuilder,currentNSMap){
  126579. var tagName = el.tagName;
  126580. var localNSMap = null;
  126581. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  126582. var i = el.length;
  126583. while(i--){
  126584. var a = el[i];
  126585. var qName = a.qName;
  126586. var value = a.value;
  126587. var nsp = qName.indexOf(':');
  126588. if(nsp>0){
  126589. var prefix = a.prefix = qName.slice(0,nsp);
  126590. var localName = qName.slice(nsp+1);
  126591. var nsPrefix = prefix === 'xmlns' && localName
  126592. }else{
  126593. localName = qName;
  126594. prefix = null
  126595. nsPrefix = qName === 'xmlns' && ''
  126596. }
  126597. //can not set prefix,because prefix !== ''
  126598. a.localName = localName ;
  126599. //prefix == null for no ns prefix attribute
  126600. if(nsPrefix !== false){//hack!!
  126601. if(localNSMap == null){
  126602. localNSMap = {}
  126603. //console.log(currentNSMap,0)
  126604. _copy(currentNSMap,currentNSMap={})
  126605. //console.log(currentNSMap,1)
  126606. }
  126607. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  126608. a.uri = 'http://www.w3.org/2000/xmlns/'
  126609. domBuilder.startPrefixMapping(nsPrefix, value)
  126610. }
  126611. }
  126612. var i = el.length;
  126613. while(i--){
  126614. a = el[i];
  126615. var prefix = a.prefix;
  126616. if(prefix){//no prefix attribute has no namespace
  126617. if(prefix === 'xml'){
  126618. a.uri = 'http://www.w3.org/XML/1998/namespace';
  126619. }if(prefix !== 'xmlns'){
  126620. a.uri = currentNSMap[prefix || '']
  126621. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  126622. }
  126623. }
  126624. }
  126625. var nsp = tagName.indexOf(':');
  126626. if(nsp>0){
  126627. prefix = el.prefix = tagName.slice(0,nsp);
  126628. localName = el.localName = tagName.slice(nsp+1);
  126629. }else{
  126630. prefix = null;//important!!
  126631. localName = el.localName = tagName;
  126632. }
  126633. //no prefix element has default namespace
  126634. var ns = el.uri = currentNSMap[prefix || ''];
  126635. domBuilder.startElement(ns,localName,tagName,el);
  126636. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  126637. //localNSMap = null
  126638. if(el.closed){
  126639. domBuilder.endElement(ns,localName,tagName);
  126640. if(localNSMap){
  126641. for(prefix in localNSMap){
  126642. domBuilder.endPrefixMapping(prefix)
  126643. }
  126644. }
  126645. }else{
  126646. el.currentNSMap = currentNSMap;
  126647. el.localNSMap = localNSMap;
  126648. //parseStack.push(el);
  126649. return true;
  126650. }
  126651. }
  126652. function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
  126653. if(/^(?:script|textarea)$/i.test(tagName)){
  126654. var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
  126655. var text = source.substring(elStartEnd+1,elEndStart);
  126656. if(/[&<]/.test(text)){
  126657. if(/^script$/i.test(tagName)){
  126658. //if(!/\]\]>/.test(text)){
  126659. //lexHandler.startCDATA();
  126660. domBuilder.characters(text,0,text.length);
  126661. //lexHandler.endCDATA();
  126662. return elEndStart;
  126663. //}
  126664. }//}else{//text area
  126665. text = text.replace(/&#?\w+;/g,entityReplacer);
  126666. domBuilder.characters(text,0,text.length);
  126667. return elEndStart;
  126668. //}
  126669. }
  126670. }
  126671. return elStartEnd+1;
  126672. }
  126673. function fixSelfClosed(source,elStartEnd,tagName,closeMap){
  126674. //if(tagName in closeMap){
  126675. var pos = closeMap[tagName];
  126676. if(pos == null){
  126677. //console.log(tagName)
  126678. pos = source.lastIndexOf('</'+tagName+'>')
  126679. if(pos<elStartEnd){//忘记闭合
  126680. pos = source.lastIndexOf('</'+tagName)
  126681. }
  126682. closeMap[tagName] =pos
  126683. }
  126684. return pos<elStartEnd;
  126685. //}
  126686. }
  126687. function _copy(source,target){
  126688. for(var n in source){target[n] = source[n]}
  126689. }
  126690. function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
  126691. var next= source.charAt(start+2)
  126692. switch(next){
  126693. case '-':
  126694. if(source.charAt(start + 3) === '-'){
  126695. var end = source.indexOf('-->',start+4);
  126696. //append comment source.substring(4,end)//<!--
  126697. if(end>start){
  126698. domBuilder.comment(source,start+4,end-start-4);
  126699. return end+3;
  126700. }else{
  126701. errorHandler.error("Unclosed comment");
  126702. return -1;
  126703. }
  126704. }else{
  126705. //error
  126706. return -1;
  126707. }
  126708. default:
  126709. if(source.substr(start+3,6) == 'CDATA['){
  126710. var end = source.indexOf(']]>',start+9);
  126711. domBuilder.startCDATA();
  126712. domBuilder.characters(source,start+9,end-start-9);
  126713. domBuilder.endCDATA()
  126714. return end+3;
  126715. }
  126716. //<!DOCTYPE
  126717. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  126718. var matchs = split(source,start);
  126719. var len = matchs.length;
  126720. if(len>1 && /!doctype/i.test(matchs[0][0])){
  126721. var name = matchs[1][0];
  126722. var pubid = false;
  126723. var sysid = false;
  126724. if(len>3){
  126725. if(/^public$/i.test(matchs[2][0])){
  126726. pubid = matchs[3][0];
  126727. sysid = len>4 && matchs[4][0];
  126728. }else if(/^system$/i.test(matchs[2][0])){
  126729. sysid = matchs[3][0];
  126730. }
  126731. }
  126732. var lastMatch = matchs[len-1]
  126733. domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
  126734. sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
  126735. domBuilder.endDTD();
  126736. return lastMatch.index+lastMatch[0].length
  126737. }
  126738. }
  126739. return -1;
  126740. }
  126741. function parseInstruction(source,start,domBuilder){
  126742. var end = source.indexOf('?>',start);
  126743. if(end){
  126744. var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  126745. if(match){
  126746. var len = match[0].length;
  126747. domBuilder.processingInstruction(match[1], match[2]) ;
  126748. return end+2;
  126749. }else{//error
  126750. return -1;
  126751. }
  126752. }
  126753. return -1;
  126754. }
  126755. /**
  126756. * @param source
  126757. */
  126758. function ElementAttributes(source){
  126759. }
  126760. ElementAttributes.prototype = {
  126761. setTagName:function(tagName){
  126762. if(!tagNamePattern.test(tagName)){
  126763. throw new Error('invalid tagName:'+tagName)
  126764. }
  126765. this.tagName = tagName
  126766. },
  126767. add:function(qName,value,offset){
  126768. if(!tagNamePattern.test(qName)){
  126769. throw new Error('invalid attribute:'+qName)
  126770. }
  126771. this[this.length++] = {qName:qName,value:value,offset:offset}
  126772. },
  126773. length:0,
  126774. getLocalName:function(i){return this[i].localName},
  126775. getLocator:function(i){return this[i].locator},
  126776. getQName:function(i){return this[i].qName},
  126777. getURI:function(i){return this[i].uri},
  126778. getValue:function(i){return this[i].value}
  126779. // ,getIndex:function(uri, localName)){
  126780. // if(localName){
  126781. //
  126782. // }else{
  126783. // var qName = uri
  126784. // }
  126785. // },
  126786. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  126787. // getType:function(uri,localName){}
  126788. // getType:function(i){},
  126789. }
  126790. function split(source,start){
  126791. var match;
  126792. var buf = [];
  126793. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  126794. reg.lastIndex = start;
  126795. reg.exec(source);//skip <
  126796. while(match = reg.exec(source)){
  126797. buf.push(match);
  126798. if(match[1])return buf;
  126799. }
  126800. }
  126801. exports.XMLReader = XMLReader;
  126802. },{}],709:[function(require,module,exports){
  126803. /*
  126804. * xpath.js
  126805. *
  126806. * An XPath 1.0 library for JavaScript.
  126807. *
  126808. * Cameron McCormack <cam (at) mcc.id.au>
  126809. *
  126810. *
  126811. * Revision 20: April 26, 2011
  126812. * Fixed a typo resulting in FIRST_ORDERED_NODE_TYPE results being wrong,
  126813. * thanks to <shi_a009 (at) hotmail.com>.
  126814. *
  126815. * Revision 19: November 29, 2005
  126816. * Nodesets now store their nodes in a height balanced tree, increasing
  126817. * performance for the common case of selecting nodes in document order,
  126818. * thanks to Sébastien Cramatte <contact (at) zeninteractif.com>.
  126819. * AVL tree code adapted from Raimund Neumann <rnova (at) gmx.net>.
  126820. *
  126821. * Revision 18: October 27, 2005
  126822. * DOM 3 XPath support. Caveats:
  126823. * - namespace prefixes aren't resolved in XPathEvaluator.createExpression,
  126824. * but in XPathExpression.evaluate.
  126825. * - XPathResult.invalidIteratorState is not implemented.
  126826. *
  126827. * Revision 17: October 25, 2005
  126828. * Some core XPath function fixes and a patch to avoid crashing certain
  126829. * versions of MSXML in PathExpr.prototype.getOwnerElement, thanks to
  126830. * Sébastien Cramatte <contact (at) zeninteractif.com>.
  126831. *
  126832. * Revision 16: September 22, 2005
  126833. * Workarounds for some IE 5.5 deficiencies.
  126834. * Fixed problem with prefix node tests on attribute nodes.
  126835. *
  126836. * Revision 15: May 21, 2005
  126837. * Fixed problem with QName node tests on elements with an xmlns="...".
  126838. *
  126839. * Revision 14: May 19, 2005
  126840. * Fixed QName node tests on attribute node regression.
  126841. *
  126842. * Revision 13: May 3, 2005
  126843. * Node tests are case insensitive now if working in an HTML DOM.
  126844. *
  126845. * Revision 12: April 26, 2005
  126846. * Updated licence. Slight code changes to enable use of Dean
  126847. * Edwards' script compression, http://dean.edwards.name/packer/ .
  126848. *
  126849. * Revision 11: April 23, 2005
  126850. * Fixed bug with 'and' and 'or' operators, fix thanks to
  126851. * Sandy McArthur <sandy (at) mcarthur.org>.
  126852. *
  126853. * Revision 10: April 15, 2005
  126854. * Added support for a virtual root node, supposedly helpful for
  126855. * implementing XForms. Fixed problem with QName node tests and
  126856. * the parent axis.
  126857. *
  126858. * Revision 9: March 17, 2005
  126859. * Namespace resolver tweaked so using the document node as the context
  126860. * for namespace lookups is equivalent to using the document element.
  126861. *
  126862. * Revision 8: February 13, 2005
  126863. * Handle implicit declaration of 'xmlns' namespace prefix.
  126864. * Fixed bug when comparing nodesets.
  126865. * Instance data can now be associated with a FunctionResolver, and
  126866. * workaround for MSXML not supporting 'localName' and 'getElementById',
  126867. * thanks to Grant Gongaware.
  126868. * Fix a few problems when the context node is the root node.
  126869. *
  126870. * Revision 7: February 11, 2005
  126871. * Default namespace resolver fix from Grant Gongaware
  126872. * <grant (at) gongaware.com>.
  126873. *
  126874. * Revision 6: February 10, 2005
  126875. * Fixed bug in 'number' function.
  126876. *
  126877. * Revision 5: February 9, 2005
  126878. * Fixed bug where text nodes not getting converted to string values.
  126879. *
  126880. * Revision 4: January 21, 2005
  126881. * Bug in 'name' function, fix thanks to Bill Edney.
  126882. * Fixed incorrect processing of namespace nodes.
  126883. * Fixed NamespaceResolver to resolve 'xml' namespace.
  126884. * Implemented union '|' operator.
  126885. *
  126886. * Revision 3: January 14, 2005
  126887. * Fixed bug with nodeset comparisons, bug lexing < and >.
  126888. *
  126889. * Revision 2: October 26, 2004
  126890. * QName node test namespace handling fixed. Few other bug fixes.
  126891. *
  126892. * Revision 1: August 13, 2004
  126893. * Bug fixes from William J. Edney <bedney (at) technicalpursuit.com>.
  126894. * Added minimal licence.
  126895. *
  126896. * Initial version: June 14, 2004
  126897. */
  126898. // XPathParser ///////////////////////////////////////////////////////////////
  126899. XPathParser.prototype = new Object();
  126900. XPathParser.prototype.constructor = XPathParser;
  126901. XPathParser.superclass = Object.prototype;
  126902. function XPathParser() {
  126903. this.init();
  126904. }
  126905. XPathParser.prototype.init = function() {
  126906. this.reduceActions = [];
  126907. this.reduceActions[3] = function(rhs) {
  126908. return new OrOperation(rhs[0], rhs[2]);
  126909. };
  126910. this.reduceActions[5] = function(rhs) {
  126911. return new AndOperation(rhs[0], rhs[2]);
  126912. };
  126913. this.reduceActions[7] = function(rhs) {
  126914. return new EqualsOperation(rhs[0], rhs[2]);
  126915. };
  126916. this.reduceActions[8] = function(rhs) {
  126917. return new NotEqualOperation(rhs[0], rhs[2]);
  126918. };
  126919. this.reduceActions[10] = function(rhs) {
  126920. return new LessThanOperation(rhs[0], rhs[2]);
  126921. };
  126922. this.reduceActions[11] = function(rhs) {
  126923. return new GreaterThanOperation(rhs[0], rhs[2]);
  126924. };
  126925. this.reduceActions[12] = function(rhs) {
  126926. return new LessThanOrEqualOperation(rhs[0], rhs[2]);
  126927. };
  126928. this.reduceActions[13] = function(rhs) {
  126929. return new GreaterThanOrEqualOperation(rhs[0], rhs[2]);
  126930. };
  126931. this.reduceActions[15] = function(rhs) {
  126932. return new PlusOperation(rhs[0], rhs[2]);
  126933. };
  126934. this.reduceActions[16] = function(rhs) {
  126935. return new MinusOperation(rhs[0], rhs[2]);
  126936. };
  126937. this.reduceActions[18] = function(rhs) {
  126938. return new MultiplyOperation(rhs[0], rhs[2]);
  126939. };
  126940. this.reduceActions[19] = function(rhs) {
  126941. return new DivOperation(rhs[0], rhs[2]);
  126942. };
  126943. this.reduceActions[20] = function(rhs) {
  126944. return new ModOperation(rhs[0], rhs[2]);
  126945. };
  126946. this.reduceActions[22] = function(rhs) {
  126947. return new UnaryMinusOperation(rhs[1]);
  126948. };
  126949. this.reduceActions[24] = function(rhs) {
  126950. return new BarOperation(rhs[0], rhs[2]);
  126951. };
  126952. this.reduceActions[25] = function(rhs) {
  126953. return new PathExpr(undefined, undefined, rhs[0]);
  126954. };
  126955. this.reduceActions[27] = function(rhs) {
  126956. rhs[0].locationPath = rhs[2];
  126957. return rhs[0];
  126958. };
  126959. this.reduceActions[28] = function(rhs) {
  126960. rhs[0].locationPath = rhs[2];
  126961. rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), []));
  126962. return rhs[0];
  126963. };
  126964. this.reduceActions[29] = function(rhs) {
  126965. return new PathExpr(rhs[0], [], undefined);
  126966. };
  126967. this.reduceActions[30] = function(rhs) {
  126968. if (Utilities.instance_of(rhs[0], PathExpr)) {
  126969. if (rhs[0].filterPredicates == undefined) {
  126970. rhs[0].filterPredicates = [];
  126971. }
  126972. rhs[0].filterPredicates.push(rhs[1]);
  126973. return rhs[0];
  126974. } else {
  126975. return new PathExpr(rhs[0], [rhs[1]], undefined);
  126976. }
  126977. };
  126978. this.reduceActions[32] = function(rhs) {
  126979. return rhs[1];
  126980. };
  126981. this.reduceActions[33] = function(rhs) {
  126982. return new XString(rhs[0]);
  126983. };
  126984. this.reduceActions[34] = function(rhs) {
  126985. return new XNumber(rhs[0]);
  126986. };
  126987. this.reduceActions[36] = function(rhs) {
  126988. return new FunctionCall(rhs[0], []);
  126989. };
  126990. this.reduceActions[37] = function(rhs) {
  126991. return new FunctionCall(rhs[0], rhs[2]);
  126992. };
  126993. this.reduceActions[38] = function(rhs) {
  126994. return [ rhs[0] ];
  126995. };
  126996. this.reduceActions[39] = function(rhs) {
  126997. rhs[2].unshift(rhs[0]);
  126998. return rhs[2];
  126999. };
  127000. this.reduceActions[43] = function(rhs) {
  127001. return new LocationPath(true, []);
  127002. };
  127003. this.reduceActions[44] = function(rhs) {
  127004. rhs[1].absolute = true;
  127005. return rhs[1];
  127006. };
  127007. this.reduceActions[46] = function(rhs) {
  127008. return new LocationPath(false, [ rhs[0] ]);
  127009. };
  127010. this.reduceActions[47] = function(rhs) {
  127011. rhs[0].steps.push(rhs[2]);
  127012. return rhs[0];
  127013. };
  127014. this.reduceActions[49] = function(rhs) {
  127015. return new Step(rhs[0], rhs[1], []);
  127016. };
  127017. this.reduceActions[50] = function(rhs) {
  127018. return new Step(Step.CHILD, rhs[0], []);
  127019. };
  127020. this.reduceActions[51] = function(rhs) {
  127021. return new Step(rhs[0], rhs[1], rhs[2]);
  127022. };
  127023. this.reduceActions[52] = function(rhs) {
  127024. return new Step(Step.CHILD, rhs[0], rhs[1]);
  127025. };
  127026. this.reduceActions[54] = function(rhs) {
  127027. return [ rhs[0] ];
  127028. };
  127029. this.reduceActions[55] = function(rhs) {
  127030. rhs[1].unshift(rhs[0]);
  127031. return rhs[1];
  127032. };
  127033. this.reduceActions[56] = function(rhs) {
  127034. if (rhs[0] == "ancestor") {
  127035. return Step.ANCESTOR;
  127036. } else if (rhs[0] == "ancestor-or-self") {
  127037. return Step.ANCESTORORSELF;
  127038. } else if (rhs[0] == "attribute") {
  127039. return Step.ATTRIBUTE;
  127040. } else if (rhs[0] == "child") {
  127041. return Step.CHILD;
  127042. } else if (rhs[0] == "descendant") {
  127043. return Step.DESCENDANT;
  127044. } else if (rhs[0] == "descendant-or-self") {
  127045. return Step.DESCENDANTORSELF;
  127046. } else if (rhs[0] == "following") {
  127047. return Step.FOLLOWING;
  127048. } else if (rhs[0] == "following-sibling") {
  127049. return Step.FOLLOWINGSIBLING;
  127050. } else if (rhs[0] == "namespace") {
  127051. return Step.NAMESPACE;
  127052. } else if (rhs[0] == "parent") {
  127053. return Step.PARENT;
  127054. } else if (rhs[0] == "preceding") {
  127055. return Step.PRECEDING;
  127056. } else if (rhs[0] == "preceding-sibling") {
  127057. return Step.PRECEDINGSIBLING;
  127058. } else if (rhs[0] == "self") {
  127059. return Step.SELF;
  127060. }
  127061. return -1;
  127062. };
  127063. this.reduceActions[57] = function(rhs) {
  127064. return Step.ATTRIBUTE;
  127065. };
  127066. this.reduceActions[59] = function(rhs) {
  127067. if (rhs[0] == "comment") {
  127068. return new NodeTest(NodeTest.COMMENT, undefined);
  127069. } else if (rhs[0] == "text") {
  127070. return new NodeTest(NodeTest.TEXT, undefined);
  127071. } else if (rhs[0] == "processing-instruction") {
  127072. return new NodeTest(NodeTest.PI, undefined);
  127073. } else if (rhs[0] == "node") {
  127074. return new NodeTest(NodeTest.NODE, undefined);
  127075. }
  127076. return new NodeTest(-1, undefined);
  127077. };
  127078. this.reduceActions[60] = function(rhs) {
  127079. return new NodeTest(NodeTest.PI, rhs[2]);
  127080. };
  127081. this.reduceActions[61] = function(rhs) {
  127082. return rhs[1];
  127083. };
  127084. this.reduceActions[63] = function(rhs) {
  127085. rhs[1].absolute = true;
  127086. rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), []));
  127087. return rhs[1];
  127088. };
  127089. this.reduceActions[64] = function(rhs) {
  127090. rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), []));
  127091. rhs[0].steps.push(rhs[2]);
  127092. return rhs[0];
  127093. };
  127094. this.reduceActions[65] = function(rhs) {
  127095. return new Step(Step.SELF, new NodeTest(NodeTest.NODE, undefined), []);
  127096. };
  127097. this.reduceActions[66] = function(rhs) {
  127098. return new Step(Step.PARENT, new NodeTest(NodeTest.NODE, undefined), []);
  127099. };
  127100. this.reduceActions[67] = function(rhs) {
  127101. return new VariableReference(rhs[1]);
  127102. };
  127103. this.reduceActions[68] = function(rhs) {
  127104. return new NodeTest(NodeTest.NAMETESTANY, undefined);
  127105. };
  127106. this.reduceActions[69] = function(rhs) {
  127107. var prefix = rhs[0].substring(0, rhs[0].indexOf(":"));
  127108. return new NodeTest(NodeTest.NAMETESTPREFIXANY, prefix);
  127109. };
  127110. this.reduceActions[70] = function(rhs) {
  127111. return new NodeTest(NodeTest.NAMETESTQNAME, rhs[0]);
  127112. };
  127113. };
  127114. XPathParser.actionTable = [
  127115. " s s sssssssss s ss s ss",
  127116. " s ",
  127117. "r rrrrrrrrr rrrrrrr rr r ",
  127118. " rrrrr ",
  127119. " s s sssssssss s ss s ss",
  127120. "rs rrrrrrrr s sssssrrrrrr rrs rs ",
  127121. " s s sssssssss s ss s ss",
  127122. " s ",
  127123. " s ",
  127124. "r rrrrrrrrr rrrrrrr rr rr ",
  127125. "r rrrrrrrrr rrrrrrr rr rr ",
  127126. "r rrrrrrrrr rrrrrrr rr rr ",
  127127. "r rrrrrrrrr rrrrrrr rr rr ",
  127128. "r rrrrrrrrr rrrrrrr rr rr ",
  127129. " s ",
  127130. " s ",
  127131. " s s sssss s s ",
  127132. "r rrrrrrrrr rrrrrrr rr r ",
  127133. "a ",
  127134. "r s rr r ",
  127135. "r sr rr r ",
  127136. "r s rr s rr r ",
  127137. "r rssrr rss rr r ",
  127138. "r rrrrr rrrss rr r ",
  127139. "r rrrrrsss rrrrr rr r ",
  127140. "r rrrrrrrr rrrrr rr r ",
  127141. "r rrrrrrrr rrrrrs rr r ",
  127142. "r rrrrrrrr rrrrrr rr r ",
  127143. "r rrrrrrrr rrrrrr rr r ",
  127144. "r srrrrrrrr rrrrrrs rr sr ",
  127145. "r srrrrrrrr rrrrrrs rr r ",
  127146. "r rrrrrrrrr rrrrrrr rr rr ",
  127147. "r rrrrrrrrr rrrrrrr rr rr ",
  127148. "r rrrrrrrrr rrrrrrr rr rr ",
  127149. "r rrrrrrrr rrrrrr rr r ",
  127150. "r rrrrrrrr rrrrrr rr r ",
  127151. "r rrrrrrrrr rrrrrrr rr r ",
  127152. "r rrrrrrrrr rrrrrrr rr r ",
  127153. " sssss ",
  127154. "r rrrrrrrrr rrrrrrr rr sr ",
  127155. "r rrrrrrrrr rrrrrrr rr r ",
  127156. "r rrrrrrrrr rrrrrrr rr rr ",
  127157. "r rrrrrrrrr rrrrrrr rr rr ",
  127158. " s ",
  127159. "r srrrrrrrr rrrrrrs rr r ",
  127160. "r rrrrrrrr rrrrr rr r ",
  127161. " s ",
  127162. " s ",
  127163. " rrrrr ",
  127164. " s s sssssssss s sss s ss",
  127165. "r srrrrrrrr rrrrrrs rr r ",
  127166. " s s sssssssss s ss s ss",
  127167. " s s sssssssss s ss s ss",
  127168. " s s sssssssss s ss s ss",
  127169. " s s sssssssss s ss s ss",
  127170. " s s sssssssss s ss s ss",
  127171. " s s sssssssss s ss s ss",
  127172. " s s sssssssss s ss s ss",
  127173. " s s sssssssss s ss s ss",
  127174. " s s sssssssss s ss s ss",
  127175. " s s sssssssss s ss s ss",
  127176. " s s sssssssss s ss s ss",
  127177. " s s sssssssss s ss s ss",
  127178. " s s sssssssss s ss s ss",
  127179. " s s sssssssss ss s ss",
  127180. " s s sssssssss s ss s ss",
  127181. " s s sssss s s ",
  127182. " s s sssss s s ",
  127183. "r rrrrrrrrr rrrrrrr rr rr ",
  127184. " s s sssss s s ",
  127185. " s s sssss s s ",
  127186. "r rrrrrrrrr rrrrrrr rr sr ",
  127187. "r rrrrrrrrr rrrrrrr rr sr ",
  127188. "r rrrrrrrrr rrrrrrr rr r ",
  127189. "r rrrrrrrrr rrrrrrr rr rr ",
  127190. " s ",
  127191. "r rrrrrrrrr rrrrrrr rr rr ",
  127192. "r rrrrrrrrr rrrrrrr rr rr ",
  127193. " rr ",
  127194. " s ",
  127195. " rs ",
  127196. "r sr rr r ",
  127197. "r s rr s rr r ",
  127198. "r rssrr rss rr r ",
  127199. "r rssrr rss rr r ",
  127200. "r rrrrr rrrss rr r ",
  127201. "r rrrrr rrrss rr r ",
  127202. "r rrrrr rrrss rr r ",
  127203. "r rrrrr rrrss rr r ",
  127204. "r rrrrrsss rrrrr rr r ",
  127205. "r rrrrrsss rrrrr rr r ",
  127206. "r rrrrrrrr rrrrr rr r ",
  127207. "r rrrrrrrr rrrrr rr r ",
  127208. "r rrrrrrrr rrrrr rr r ",
  127209. "r rrrrrrrr rrrrrr rr r ",
  127210. " r ",
  127211. " s ",
  127212. "r srrrrrrrr rrrrrrs rr r ",
  127213. "r srrrrrrrr rrrrrrs rr r ",
  127214. "r rrrrrrrrr rrrrrrr rr r ",
  127215. "r rrrrrrrrr rrrrrrr rr r ",
  127216. "r rrrrrrrrr rrrrrrr rr r ",
  127217. "r rrrrrrrrr rrrrrrr rr r ",
  127218. "r rrrrrrrrr rrrrrrr rr rr ",
  127219. "r rrrrrrrrr rrrrrrr rr rr ",
  127220. " s s sssssssss s ss s ss",
  127221. "r rrrrrrrrr rrrrrrr rr rr ",
  127222. " r "
  127223. ];
  127224. XPathParser.actionTableNumber = [
  127225. " 1 0 /.-,+*)(' & %$ # \"!",
  127226. " J ",
  127227. "a aaaaaaaaa aaaaaaa aa a ",
  127228. " YYYYY ",
  127229. " 1 0 /.-,+*)(' & %$ # \"!",
  127230. "K1 KKKKKKKK . +*)('KKKKKK KK# K\" ",
  127231. " 1 0 /.-,+*)(' & %$ # \"!",
  127232. " N ",
  127233. " O ",
  127234. "e eeeeeeeee eeeeeee ee ee ",
  127235. "f fffffffff fffffff ff ff ",
  127236. "d ddddddddd ddddddd dd dd ",
  127237. "B BBBBBBBBB BBBBBBB BB BB ",
  127238. "A AAAAAAAAA AAAAAAA AA AA ",
  127239. " P ",
  127240. " Q ",
  127241. " 1 . +*)(' # \" ",
  127242. "b bbbbbbbbb bbbbbbb bb b ",
  127243. " ",
  127244. "! S !! ! ",
  127245. "\" T\" \"\" \" ",
  127246. "$ V $$ U $$ $ ",
  127247. "& &ZY&& &XW && & ",
  127248. ") ))))) )))\\[ )) ) ",
  127249. ". ....._^] ..... .. . ",
  127250. "1 11111111 11111 11 1 ",
  127251. "5 55555555 55555` 55 5 ",
  127252. "7 77777777 777777 77 7 ",
  127253. "9 99999999 999999 99 9 ",
  127254. ": c:::::::: ::::::b :: a: ",
  127255. "I fIIIIIIII IIIIIIe II I ",
  127256. "= ========= ======= == == ",
  127257. "? ????????? ??????? ?? ?? ",
  127258. "C CCCCCCCCC CCCCCCC CC CC ",
  127259. "J JJJJJJJJ JJJJJJ JJ J ",
  127260. "M MMMMMMMM MMMMMM MM M ",
  127261. "N NNNNNNNNN NNNNNNN NN N ",
  127262. "P PPPPPPPPP PPPPPPP PP P ",
  127263. " +*)(' ",
  127264. "R RRRRRRRRR RRRRRRR RR aR ",
  127265. "U UUUUUUUUU UUUUUUU UU U ",
  127266. "Z ZZZZZZZZZ ZZZZZZZ ZZ ZZ ",
  127267. "c ccccccccc ccccccc cc cc ",
  127268. " j ",
  127269. "L fLLLLLLLL LLLLLLe LL L ",
  127270. "6 66666666 66666 66 6 ",
  127271. " k ",
  127272. " l ",
  127273. " XXXXX ",
  127274. " 1 0 /.-,+*)(' & %$m # \"!",
  127275. "_ f________ ______e __ _ ",
  127276. " 1 0 /.-,+*)(' & %$ # \"!",
  127277. " 1 0 /.-,+*)(' & %$ # \"!",
  127278. " 1 0 /.-,+*)(' & %$ # \"!",
  127279. " 1 0 /.-,+*)(' & %$ # \"!",
  127280. " 1 0 /.-,+*)(' & %$ # \"!",
  127281. " 1 0 /.-,+*)(' & %$ # \"!",
  127282. " 1 0 /.-,+*)(' & %$ # \"!",
  127283. " 1 0 /.-,+*)(' & %$ # \"!",
  127284. " 1 0 /.-,+*)(' & %$ # \"!",
  127285. " 1 0 /.-,+*)(' & %$ # \"!",
  127286. " 1 0 /.-,+*)(' & %$ # \"!",
  127287. " 1 0 /.-,+*)(' & %$ # \"!",
  127288. " 1 0 /.-,+*)(' & %$ # \"!",
  127289. " 1 0 /.-,+*)(' %$ # \"!",
  127290. " 1 0 /.-,+*)(' & %$ # \"!",
  127291. " 1 . +*)(' # \" ",
  127292. " 1 . +*)(' # \" ",
  127293. "> >>>>>>>>> >>>>>>> >> >> ",
  127294. " 1 . +*)(' # \" ",
  127295. " 1 . +*)(' # \" ",
  127296. "Q QQQQQQQQQ QQQQQQQ QQ aQ ",
  127297. "V VVVVVVVVV VVVVVVV VV aV ",
  127298. "T TTTTTTTTT TTTTTTT TT T ",
  127299. "@ @@@@@@@@@ @@@@@@@ @@ @@ ",
  127300. " \x87 ",
  127301. "[ [[[[[[[[[ [[[[[[[ [[ [[ ",
  127302. "D DDDDDDDDD DDDDDDD DD DD ",
  127303. " HH ",
  127304. " \x88 ",
  127305. " F\x89 ",
  127306. "# T# ## # ",
  127307. "% V %% U %% % ",
  127308. "' 'ZY'' 'XW '' ' ",
  127309. "( (ZY(( (XW (( ( ",
  127310. "+ +++++ +++\\[ ++ + ",
  127311. "* ***** ***\\[ ** * ",
  127312. "- ----- ---\\[ -- - ",
  127313. ", ,,,,, ,,,\\[ ,, , ",
  127314. "0 00000_^] 00000 00 0 ",
  127315. "/ /////_^] ///// // / ",
  127316. "2 22222222 22222 22 2 ",
  127317. "3 33333333 33333 33 3 ",
  127318. "4 44444444 44444 44 4 ",
  127319. "8 88888888 888888 88 8 ",
  127320. " ^ ",
  127321. " \x8a ",
  127322. "; f;;;;;;;; ;;;;;;e ;; ; ",
  127323. "< f<<<<<<<< <<<<<<e << < ",
  127324. "O OOOOOOOOO OOOOOOO OO O ",
  127325. "` ````````` ``````` `` ` ",
  127326. "S SSSSSSSSS SSSSSSS SS S ",
  127327. "W WWWWWWWWW WWWWWWW WW W ",
  127328. "\\ \\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\ \\\\ \\\\ ",
  127329. "E EEEEEEEEE EEEEEEE EE EE ",
  127330. " 1 0 /.-,+*)(' & %$ # \"!",
  127331. "] ]]]]]]]]] ]]]]]]] ]] ]] ",
  127332. " G "
  127333. ];
  127334. XPathParser.gotoTable = [
  127335. "3456789:;<=>?@ AB CDEFGH IJ ",
  127336. " ",
  127337. " ",
  127338. " ",
  127339. "L456789:;<=>?@ AB CDEFGH IJ ",
  127340. " M EFGH IJ ",
  127341. " N;<=>?@ AB CDEFGH IJ ",
  127342. " ",
  127343. " ",
  127344. " ",
  127345. " ",
  127346. " ",
  127347. " ",
  127348. " ",
  127349. " ",
  127350. " ",
  127351. " S EFGH IJ ",
  127352. " ",
  127353. " ",
  127354. " ",
  127355. " ",
  127356. " ",
  127357. " ",
  127358. " ",
  127359. " ",
  127360. " ",
  127361. " ",
  127362. " ",
  127363. " ",
  127364. " e ",
  127365. " ",
  127366. " ",
  127367. " ",
  127368. " ",
  127369. " ",
  127370. " ",
  127371. " ",
  127372. " ",
  127373. " h J ",
  127374. " i j ",
  127375. " ",
  127376. " ",
  127377. " ",
  127378. " ",
  127379. " ",
  127380. " ",
  127381. " ",
  127382. " ",
  127383. " ",
  127384. "o456789:;<=>?@ ABpqCDEFGH IJ ",
  127385. " ",
  127386. " r6789:;<=>?@ AB CDEFGH IJ ",
  127387. " s789:;<=>?@ AB CDEFGH IJ ",
  127388. " t89:;<=>?@ AB CDEFGH IJ ",
  127389. " u89:;<=>?@ AB CDEFGH IJ ",
  127390. " v9:;<=>?@ AB CDEFGH IJ ",
  127391. " w9:;<=>?@ AB CDEFGH IJ ",
  127392. " x9:;<=>?@ AB CDEFGH IJ ",
  127393. " y9:;<=>?@ AB CDEFGH IJ ",
  127394. " z:;<=>?@ AB CDEFGH IJ ",
  127395. " {:;<=>?@ AB CDEFGH IJ ",
  127396. " |;<=>?@ AB CDEFGH IJ ",
  127397. " };<=>?@ AB CDEFGH IJ ",
  127398. " ~;<=>?@ AB CDEFGH IJ ",
  127399. " \x7f=>?@ AB CDEFGH IJ ",
  127400. "\x80456789:;<=>?@ AB CDEFGH IJ\x81",
  127401. " \x82 EFGH IJ ",
  127402. " \x83 EFGH IJ ",
  127403. " ",
  127404. " \x84 GH IJ ",
  127405. " \x85 GH IJ ",
  127406. " i \x86 ",
  127407. " i \x87 ",
  127408. " ",
  127409. " ",
  127410. " ",
  127411. " ",
  127412. " ",
  127413. " ",
  127414. " ",
  127415. " ",
  127416. " ",
  127417. " ",
  127418. " ",
  127419. " ",
  127420. " ",
  127421. " ",
  127422. " ",
  127423. " ",
  127424. " ",
  127425. " ",
  127426. " ",
  127427. " ",
  127428. " ",
  127429. " ",
  127430. " ",
  127431. " ",
  127432. " ",
  127433. " ",
  127434. " ",
  127435. " ",
  127436. " ",
  127437. " ",
  127438. " ",
  127439. " ",
  127440. "o456789:;<=>?@ AB\x8cqCDEFGH IJ ",
  127441. " ",
  127442. " "
  127443. ];
  127444. XPathParser.productions = [
  127445. [1, 1, 2],
  127446. [2, 1, 3],
  127447. [3, 1, 4],
  127448. [3, 3, 3, -9, 4],
  127449. [4, 1, 5],
  127450. [4, 3, 4, -8, 5],
  127451. [5, 1, 6],
  127452. [5, 3, 5, -22, 6],
  127453. [5, 3, 5, -5, 6],
  127454. [6, 1, 7],
  127455. [6, 3, 6, -23, 7],
  127456. [6, 3, 6, -24, 7],
  127457. [6, 3, 6, -6, 7],
  127458. [6, 3, 6, -7, 7],
  127459. [7, 1, 8],
  127460. [7, 3, 7, -25, 8],
  127461. [7, 3, 7, -26, 8],
  127462. [8, 1, 9],
  127463. [8, 3, 8, -12, 9],
  127464. [8, 3, 8, -11, 9],
  127465. [8, 3, 8, -10, 9],
  127466. [9, 1, 10],
  127467. [9, 2, -26, 9],
  127468. [10, 1, 11],
  127469. [10, 3, 10, -27, 11],
  127470. [11, 1, 12],
  127471. [11, 1, 13],
  127472. [11, 3, 13, -28, 14],
  127473. [11, 3, 13, -4, 14],
  127474. [13, 1, 15],
  127475. [13, 2, 13, 16],
  127476. [15, 1, 17],
  127477. [15, 3, -29, 2, -30],
  127478. [15, 1, -15],
  127479. [15, 1, -16],
  127480. [15, 1, 18],
  127481. [18, 3, -13, -29, -30],
  127482. [18, 4, -13, -29, 19, -30],
  127483. [19, 1, 20],
  127484. [19, 3, 20, -31, 19],
  127485. [20, 1, 2],
  127486. [12, 1, 14],
  127487. [12, 1, 21],
  127488. [21, 1, -28],
  127489. [21, 2, -28, 14],
  127490. [21, 1, 22],
  127491. [14, 1, 23],
  127492. [14, 3, 14, -28, 23],
  127493. [14, 1, 24],
  127494. [23, 2, 25, 26],
  127495. [23, 1, 26],
  127496. [23, 3, 25, 26, 27],
  127497. [23, 2, 26, 27],
  127498. [23, 1, 28],
  127499. [27, 1, 16],
  127500. [27, 2, 16, 27],
  127501. [25, 2, -14, -3],
  127502. [25, 1, -32],
  127503. [26, 1, 29],
  127504. [26, 3, -20, -29, -30],
  127505. [26, 4, -21, -29, -15, -30],
  127506. [16, 3, -33, 30, -34],
  127507. [30, 1, 2],
  127508. [22, 2, -4, 14],
  127509. [24, 3, 14, -4, 23],
  127510. [28, 1, -35],
  127511. [28, 1, -2],
  127512. [17, 2, -36, -18],
  127513. [29, 1, -17],
  127514. [29, 1, -19],
  127515. [29, 1, -18]
  127516. ];
  127517. XPathParser.DOUBLEDOT = 2;
  127518. XPathParser.DOUBLECOLON = 3;
  127519. XPathParser.DOUBLESLASH = 4;
  127520. XPathParser.NOTEQUAL = 5;
  127521. XPathParser.LESSTHANOREQUAL = 6;
  127522. XPathParser.GREATERTHANOREQUAL = 7;
  127523. XPathParser.AND = 8;
  127524. XPathParser.OR = 9;
  127525. XPathParser.MOD = 10;
  127526. XPathParser.DIV = 11;
  127527. XPathParser.MULTIPLYOPERATOR = 12;
  127528. XPathParser.FUNCTIONNAME = 13;
  127529. XPathParser.AXISNAME = 14;
  127530. XPathParser.LITERAL = 15;
  127531. XPathParser.NUMBER = 16;
  127532. XPathParser.ASTERISKNAMETEST = 17;
  127533. XPathParser.QNAME = 18;
  127534. XPathParser.NCNAMECOLONASTERISK = 19;
  127535. XPathParser.NODETYPE = 20;
  127536. XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21;
  127537. XPathParser.EQUALS = 22;
  127538. XPathParser.LESSTHAN = 23;
  127539. XPathParser.GREATERTHAN = 24;
  127540. XPathParser.PLUS = 25;
  127541. XPathParser.MINUS = 26;
  127542. XPathParser.BAR = 27;
  127543. XPathParser.SLASH = 28;
  127544. XPathParser.LEFTPARENTHESIS = 29;
  127545. XPathParser.RIGHTPARENTHESIS = 30;
  127546. XPathParser.COMMA = 31;
  127547. XPathParser.AT = 32;
  127548. XPathParser.LEFTBRACKET = 33;
  127549. XPathParser.RIGHTBRACKET = 34;
  127550. XPathParser.DOT = 35;
  127551. XPathParser.DOLLAR = 36;
  127552. XPathParser.prototype.tokenize = function(s1) {
  127553. var types = [];
  127554. var values = [];
  127555. var s = s1 + '\0';
  127556. var pos = 0;
  127557. var c = s.charAt(pos++);
  127558. while (1) {
  127559. while (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
  127560. c = s.charAt(pos++);
  127561. }
  127562. if (c == '\0' || pos >= s.length) {
  127563. break;
  127564. }
  127565. if (c == '(') {
  127566. types.push(XPathParser.LEFTPARENTHESIS);
  127567. values.push(c);
  127568. c = s.charAt(pos++);
  127569. continue;
  127570. }
  127571. if (c == ')') {
  127572. types.push(XPathParser.RIGHTPARENTHESIS);
  127573. values.push(c);
  127574. c = s.charAt(pos++);
  127575. continue;
  127576. }
  127577. if (c == '[') {
  127578. types.push(XPathParser.LEFTBRACKET);
  127579. values.push(c);
  127580. c = s.charAt(pos++);
  127581. continue;
  127582. }
  127583. if (c == ']') {
  127584. types.push(XPathParser.RIGHTBRACKET);
  127585. values.push(c);
  127586. c = s.charAt(pos++);
  127587. continue;
  127588. }
  127589. if (c == '@') {
  127590. types.push(XPathParser.AT);
  127591. values.push(c);
  127592. c = s.charAt(pos++);
  127593. continue;
  127594. }
  127595. if (c == ',') {
  127596. types.push(XPathParser.COMMA);
  127597. values.push(c);
  127598. c = s.charAt(pos++);
  127599. continue;
  127600. }
  127601. if (c == '|') {
  127602. types.push(XPathParser.BAR);
  127603. values.push(c);
  127604. c = s.charAt(pos++);
  127605. continue;
  127606. }
  127607. if (c == '+') {
  127608. types.push(XPathParser.PLUS);
  127609. values.push(c);
  127610. c = s.charAt(pos++);
  127611. continue;
  127612. }
  127613. if (c == '-') {
  127614. types.push(XPathParser.MINUS);
  127615. values.push(c);
  127616. c = s.charAt(pos++);
  127617. continue;
  127618. }
  127619. if (c == '=') {
  127620. types.push(XPathParser.EQUALS);
  127621. values.push(c);
  127622. c = s.charAt(pos++);
  127623. continue;
  127624. }
  127625. if (c == '$') {
  127626. types.push(XPathParser.DOLLAR);
  127627. values.push(c);
  127628. c = s.charAt(pos++);
  127629. continue;
  127630. }
  127631. if (c == '.') {
  127632. c = s.charAt(pos++);
  127633. if (c == '.') {
  127634. types.push(XPathParser.DOUBLEDOT);
  127635. values.push("..");
  127636. c = s.charAt(pos++);
  127637. continue;
  127638. }
  127639. if (c >= '0' && c <= '9') {
  127640. var number = "." + c;
  127641. c = s.charAt(pos++);
  127642. while (c >= '0' && c <= '9') {
  127643. number += c;
  127644. c = s.charAt(pos++);
  127645. }
  127646. types.push(XPathParser.NUMBER);
  127647. values.push(number);
  127648. continue;
  127649. }
  127650. types.push(XPathParser.DOT);
  127651. values.push('.');
  127652. continue;
  127653. }
  127654. if (c == '\'' || c == '"') {
  127655. var delimiter = c;
  127656. var literal = "";
  127657. while ((c = s.charAt(pos++)) != delimiter) {
  127658. literal += c;
  127659. }
  127660. types.push(XPathParser.LITERAL);
  127661. values.push(literal);
  127662. c = s.charAt(pos++);
  127663. continue;
  127664. }
  127665. if (c >= '0' && c <= '9') {
  127666. var number = c;
  127667. c = s.charAt(pos++);
  127668. while (c >= '0' && c <= '9') {
  127669. number += c;
  127670. c = s.charAt(pos++);
  127671. }
  127672. if (c == '.') {
  127673. if (s.charAt(pos) >= '0' && s.charAt(pos) <= '9') {
  127674. number += c;
  127675. number += s.charAt(pos++);
  127676. c = s.charAt(pos++);
  127677. while (c >= '0' && c <= '9') {
  127678. number += c;
  127679. c = s.charAt(pos++);
  127680. }
  127681. }
  127682. }
  127683. types.push(XPathParser.NUMBER);
  127684. values.push(number);
  127685. continue;
  127686. }
  127687. if (c == '*') {
  127688. if (types.length > 0) {
  127689. var last = types[types.length - 1];
  127690. if (last != XPathParser.AT
  127691. && last != XPathParser.DOUBLECOLON
  127692. && last != XPathParser.LEFTPARENTHESIS
  127693. && last != XPathParser.LEFTBRACKET
  127694. && last != XPathParser.AND
  127695. && last != XPathParser.OR
  127696. && last != XPathParser.MOD
  127697. && last != XPathParser.DIV
  127698. && last != XPathParser.MULTIPLYOPERATOR
  127699. && last != XPathParser.SLASH
  127700. && last != XPathParser.DOUBLESLASH
  127701. && last != XPathParser.BAR
  127702. && last != XPathParser.PLUS
  127703. && last != XPathParser.MINUS
  127704. && last != XPathParser.EQUALS
  127705. && last != XPathParser.NOTEQUAL
  127706. && last != XPathParser.LESSTHAN
  127707. && last != XPathParser.LESSTHANOREQUAL
  127708. && last != XPathParser.GREATERTHAN
  127709. && last != XPathParser.GREATERTHANOREQUAL) {
  127710. types.push(XPathParser.MULTIPLYOPERATOR);
  127711. values.push(c);
  127712. c = s.charAt(pos++);
  127713. continue;
  127714. }
  127715. }
  127716. types.push(XPathParser.ASTERISKNAMETEST);
  127717. values.push(c);
  127718. c = s.charAt(pos++);
  127719. continue;
  127720. }
  127721. if (c == ':') {
  127722. if (s.charAt(pos) == ':') {
  127723. types.push(XPathParser.DOUBLECOLON);
  127724. values.push("::");
  127725. pos++;
  127726. c = s.charAt(pos++);
  127727. continue;
  127728. }
  127729. }
  127730. if (c == '/') {
  127731. c = s.charAt(pos++);
  127732. if (c == '/') {
  127733. types.push(XPathParser.DOUBLESLASH);
  127734. values.push("//");
  127735. c = s.charAt(pos++);
  127736. continue;
  127737. }
  127738. types.push(XPathParser.SLASH);
  127739. values.push('/');
  127740. continue;
  127741. }
  127742. if (c == '!') {
  127743. if (s.charAt(pos) == '=') {
  127744. types.push(XPathParser.NOTEQUAL);
  127745. values.push("!=");
  127746. pos++;
  127747. c = s.charAt(pos++);
  127748. continue;
  127749. }
  127750. }
  127751. if (c == '<') {
  127752. if (s.charAt(pos) == '=') {
  127753. types.push(XPathParser.LESSTHANOREQUAL);
  127754. values.push("<=");
  127755. pos++;
  127756. c = s.charAt(pos++);
  127757. continue;
  127758. }
  127759. types.push(XPathParser.LESSTHAN);
  127760. values.push('<');
  127761. c = s.charAt(pos++);
  127762. continue;
  127763. }
  127764. if (c == '>') {
  127765. if (s.charAt(pos) == '=') {
  127766. types.push(XPathParser.GREATERTHANOREQUAL);
  127767. values.push(">=");
  127768. pos++;
  127769. c = s.charAt(pos++);
  127770. continue;
  127771. }
  127772. types.push(XPathParser.GREATERTHAN);
  127773. values.push('>');
  127774. c = s.charAt(pos++);
  127775. continue;
  127776. }
  127777. if (c == '_' || Utilities.isLetter(c.charCodeAt(0))) {
  127778. var name = c;
  127779. c = s.charAt(pos++);
  127780. while (Utilities.isNCNameChar(c.charCodeAt(0))) {
  127781. name += c;
  127782. c = s.charAt(pos++);
  127783. }
  127784. if (types.length > 0) {
  127785. var last = types[types.length - 1];
  127786. if (last != XPathParser.AT
  127787. && last != XPathParser.DOUBLECOLON
  127788. && last != XPathParser.LEFTPARENTHESIS
  127789. && last != XPathParser.LEFTBRACKET
  127790. && last != XPathParser.AND
  127791. && last != XPathParser.OR
  127792. && last != XPathParser.MOD
  127793. && last != XPathParser.DIV
  127794. && last != XPathParser.MULTIPLYOPERATOR
  127795. && last != XPathParser.SLASH
  127796. && last != XPathParser.DOUBLESLASH
  127797. && last != XPathParser.BAR
  127798. && last != XPathParser.PLUS
  127799. && last != XPathParser.MINUS
  127800. && last != XPathParser.EQUALS
  127801. && last != XPathParser.NOTEQUAL
  127802. && last != XPathParser.LESSTHAN
  127803. && last != XPathParser.LESSTHANOREQUAL
  127804. && last != XPathParser.GREATERTHAN
  127805. && last != XPathParser.GREATERTHANOREQUAL) {
  127806. if (name == "and") {
  127807. types.push(XPathParser.AND);
  127808. values.push(name);
  127809. continue;
  127810. }
  127811. if (name == "or") {
  127812. types.push(XPathParser.OR);
  127813. values.push(name);
  127814. continue;
  127815. }
  127816. if (name == "mod") {
  127817. types.push(XPathParser.MOD);
  127818. values.push(name);
  127819. continue;
  127820. }
  127821. if (name == "div") {
  127822. types.push(XPathParser.DIV);
  127823. values.push(name);
  127824. continue;
  127825. }
  127826. }
  127827. }
  127828. if (c == ':') {
  127829. if (s.charAt(pos) == '*') {
  127830. types.push(XPathParser.NCNAMECOLONASTERISK);
  127831. values.push(name + ":*");
  127832. pos++;
  127833. c = s.charAt(pos++);
  127834. continue;
  127835. }
  127836. if (s.charAt(pos) == '_' || Utilities.isLetter(s.charCodeAt(pos))) {
  127837. name += ':';
  127838. c = s.charAt(pos++);
  127839. while (Utilities.isNCNameChar(c.charCodeAt(0))) {
  127840. name += c;
  127841. c = s.charAt(pos++);
  127842. }
  127843. if (c == '(') {
  127844. types.push(XPathParser.FUNCTIONNAME);
  127845. values.push(name);
  127846. continue;
  127847. }
  127848. types.push(XPathParser.QNAME);
  127849. values.push(name);
  127850. continue;
  127851. }
  127852. if (s.charAt(pos) == ':') {
  127853. types.push(XPathParser.AXISNAME);
  127854. values.push(name);
  127855. continue;
  127856. }
  127857. }
  127858. if (c == '(') {
  127859. if (name == "comment" || name == "text" || name == "node") {
  127860. types.push(XPathParser.NODETYPE);
  127861. values.push(name);
  127862. continue;
  127863. }
  127864. if (name == "processing-instruction") {
  127865. if (s.charAt(pos) == ')') {
  127866. types.push(XPathParser.NODETYPE);
  127867. } else {
  127868. types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL);
  127869. }
  127870. values.push(name);
  127871. continue;
  127872. }
  127873. types.push(XPathParser.FUNCTIONNAME);
  127874. values.push(name);
  127875. continue;
  127876. }
  127877. types.push(XPathParser.QNAME);
  127878. values.push(name);
  127879. continue;
  127880. }
  127881. throw new Error("Unexpected character " + c);
  127882. }
  127883. types.push(1);
  127884. values.push("[EOF]");
  127885. return [types, values];
  127886. };
  127887. XPathParser.SHIFT = 's';
  127888. XPathParser.REDUCE = 'r';
  127889. XPathParser.ACCEPT = 'a';
  127890. XPathParser.prototype.parse = function(s) {
  127891. var types;
  127892. var values;
  127893. var res = this.tokenize(s);
  127894. if (res == undefined) {
  127895. return undefined;
  127896. }
  127897. types = res[0];
  127898. values = res[1];
  127899. var tokenPos = 0;
  127900. var state = [];
  127901. var tokenType = [];
  127902. var tokenValue = [];
  127903. var s;
  127904. var a;
  127905. var t;
  127906. state.push(0);
  127907. tokenType.push(1);
  127908. tokenValue.push("_S");
  127909. a = types[tokenPos];
  127910. t = values[tokenPos++];
  127911. while (1) {
  127912. s = state[state.length - 1];
  127913. switch (XPathParser.actionTable[s].charAt(a - 1)) {
  127914. case XPathParser.SHIFT:
  127915. tokenType.push(-a);
  127916. tokenValue.push(t);
  127917. state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32);
  127918. a = types[tokenPos];
  127919. t = values[tokenPos++];
  127920. break;
  127921. case XPathParser.REDUCE:
  127922. var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1];
  127923. var rhs = [];
  127924. for (var i = 0; i < num; i++) {
  127925. tokenType.pop();
  127926. rhs.unshift(tokenValue.pop());
  127927. state.pop();
  127928. }
  127929. var s_ = state[state.length - 1];
  127930. tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]);
  127931. if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == undefined) {
  127932. tokenValue.push(rhs[0]);
  127933. } else {
  127934. tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs));
  127935. }
  127936. state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33);
  127937. break;
  127938. case XPathParser.ACCEPT:
  127939. return new XPath(tokenValue.pop());
  127940. default:
  127941. throw new Error("XPath parse error");
  127942. }
  127943. }
  127944. };
  127945. // XPath /////////////////////////////////////////////////////////////////////
  127946. XPath.prototype = new Object();
  127947. XPath.prototype.constructor = XPath;
  127948. XPath.superclass = Object.prototype;
  127949. function XPath(e) {
  127950. this.expression = e;
  127951. }
  127952. XPath.prototype.toString = function() {
  127953. return this.expression.toString();
  127954. };
  127955. XPath.prototype.evaluate = function(c) {
  127956. c.contextNode = c.expressionContextNode;
  127957. c.contextSize = 1;
  127958. c.contextPosition = 1;
  127959. c.caseInsensitive = false;
  127960. if (c.contextNode != null) {
  127961. var doc = c.contextNode;
  127962. if (doc.nodeType != 9 /*Node.DOCUMENT_NODE*/) {
  127963. doc = doc.ownerDocument;
  127964. }
  127965. try {
  127966. c.caseInsensitive = doc.implementation.hasFeature("HTML", "2.0");
  127967. } catch (e) {
  127968. c.caseInsensitive = true;
  127969. }
  127970. }
  127971. return this.expression.evaluate(c);
  127972. };
  127973. XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace";
  127974. XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/";
  127975. // Expression ////////////////////////////////////////////////////////////////
  127976. Expression.prototype = new Object();
  127977. Expression.prototype.constructor = Expression;
  127978. Expression.superclass = Object.prototype;
  127979. function Expression() {
  127980. }
  127981. Expression.prototype.init = function() {
  127982. };
  127983. Expression.prototype.toString = function() {
  127984. return "<Expression>";
  127985. };
  127986. Expression.prototype.evaluate = function(c) {
  127987. throw new Error("Could not evaluate expression.");
  127988. };
  127989. // UnaryOperation ////////////////////////////////////////////////////////////
  127990. UnaryOperation.prototype = new Expression();
  127991. UnaryOperation.prototype.constructor = UnaryOperation;
  127992. UnaryOperation.superclass = Expression.prototype;
  127993. function UnaryOperation(rhs) {
  127994. if (arguments.length > 0) {
  127995. this.init(rhs);
  127996. }
  127997. }
  127998. UnaryOperation.prototype.init = function(rhs) {
  127999. this.rhs = rhs;
  128000. };
  128001. // UnaryMinusOperation ///////////////////////////////////////////////////////
  128002. UnaryMinusOperation.prototype = new UnaryOperation();
  128003. UnaryMinusOperation.prototype.constructor = UnaryMinusOperation;
  128004. UnaryMinusOperation.superclass = UnaryOperation.prototype;
  128005. function UnaryMinusOperation(rhs) {
  128006. if (arguments.length > 0) {
  128007. this.init(rhs);
  128008. }
  128009. }
  128010. UnaryMinusOperation.prototype.init = function(rhs) {
  128011. UnaryMinusOperation.superclass.init.call(this, rhs);
  128012. };
  128013. UnaryMinusOperation.prototype.evaluate = function(c) {
  128014. return this.rhs.evaluate(c).number().negate();
  128015. };
  128016. UnaryMinusOperation.prototype.toString = function() {
  128017. return "-" + this.rhs.toString();
  128018. };
  128019. // BinaryOperation ///////////////////////////////////////////////////////////
  128020. BinaryOperation.prototype = new Expression();
  128021. BinaryOperation.prototype.constructor = BinaryOperation;
  128022. BinaryOperation.superclass = Expression.prototype;
  128023. function BinaryOperation(lhs, rhs) {
  128024. if (arguments.length > 0) {
  128025. this.init(lhs, rhs);
  128026. }
  128027. }
  128028. BinaryOperation.prototype.init = function(lhs, rhs) {
  128029. this.lhs = lhs;
  128030. this.rhs = rhs;
  128031. };
  128032. // OrOperation ///////////////////////////////////////////////////////////////
  128033. OrOperation.prototype = new BinaryOperation();
  128034. OrOperation.prototype.constructor = OrOperation;
  128035. OrOperation.superclass = BinaryOperation.prototype;
  128036. function OrOperation(lhs, rhs) {
  128037. if (arguments.length > 0) {
  128038. this.init(lhs, rhs);
  128039. }
  128040. }
  128041. OrOperation.prototype.init = function(lhs, rhs) {
  128042. OrOperation.superclass.init.call(this, lhs, rhs);
  128043. };
  128044. OrOperation.prototype.toString = function() {
  128045. return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")";
  128046. };
  128047. OrOperation.prototype.evaluate = function(c) {
  128048. var b = this.lhs.evaluate(c).bool();
  128049. if (b.booleanValue()) {
  128050. return b;
  128051. }
  128052. return this.rhs.evaluate(c).bool();
  128053. };
  128054. // AndOperation //////////////////////////////////////////////////////////////
  128055. AndOperation.prototype = new BinaryOperation();
  128056. AndOperation.prototype.constructor = AndOperation;
  128057. AndOperation.superclass = BinaryOperation.prototype;
  128058. function AndOperation(lhs, rhs) {
  128059. if (arguments.length > 0) {
  128060. this.init(lhs, rhs);
  128061. }
  128062. }
  128063. AndOperation.prototype.init = function(lhs, rhs) {
  128064. AndOperation.superclass.init.call(this, lhs, rhs);
  128065. };
  128066. AndOperation.prototype.toString = function() {
  128067. return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")";
  128068. };
  128069. AndOperation.prototype.evaluate = function(c) {
  128070. var b = this.lhs.evaluate(c).bool();
  128071. if (!b.booleanValue()) {
  128072. return b;
  128073. }
  128074. return this.rhs.evaluate(c).bool();
  128075. };
  128076. // EqualsOperation ///////////////////////////////////////////////////////////
  128077. EqualsOperation.prototype = new BinaryOperation();
  128078. EqualsOperation.prototype.constructor = EqualsOperation;
  128079. EqualsOperation.superclass = BinaryOperation.prototype;
  128080. function EqualsOperation(lhs, rhs) {
  128081. if (arguments.length > 0) {
  128082. this.init(lhs, rhs);
  128083. }
  128084. }
  128085. EqualsOperation.prototype.init = function(lhs, rhs) {
  128086. EqualsOperation.superclass.init.call(this, lhs, rhs);
  128087. };
  128088. EqualsOperation.prototype.toString = function() {
  128089. return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")";
  128090. };
  128091. EqualsOperation.prototype.evaluate = function(c) {
  128092. return this.lhs.evaluate(c).equals(this.rhs.evaluate(c));
  128093. };
  128094. // NotEqualOperation /////////////////////////////////////////////////////////
  128095. NotEqualOperation.prototype = new BinaryOperation();
  128096. NotEqualOperation.prototype.constructor = NotEqualOperation;
  128097. NotEqualOperation.superclass = BinaryOperation.prototype;
  128098. function NotEqualOperation(lhs, rhs) {
  128099. if (arguments.length > 0) {
  128100. this.init(lhs, rhs);
  128101. }
  128102. }
  128103. NotEqualOperation.prototype.init = function(lhs, rhs) {
  128104. NotEqualOperation.superclass.init.call(this, lhs, rhs);
  128105. };
  128106. NotEqualOperation.prototype.toString = function() {
  128107. return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")";
  128108. };
  128109. NotEqualOperation.prototype.evaluate = function(c) {
  128110. return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c));
  128111. };
  128112. // LessThanOperation /////////////////////////////////////////////////////////
  128113. LessThanOperation.prototype = new BinaryOperation();
  128114. LessThanOperation.prototype.constructor = LessThanOperation;
  128115. LessThanOperation.superclass = BinaryOperation.prototype;
  128116. function LessThanOperation(lhs, rhs) {
  128117. if (arguments.length > 0) {
  128118. this.init(lhs, rhs);
  128119. }
  128120. }
  128121. LessThanOperation.prototype.init = function(lhs, rhs) {
  128122. LessThanOperation.superclass.init.call(this, lhs, rhs);
  128123. };
  128124. LessThanOperation.prototype.evaluate = function(c) {
  128125. return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c));
  128126. };
  128127. LessThanOperation.prototype.toString = function() {
  128128. return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")";
  128129. };
  128130. // GreaterThanOperation //////////////////////////////////////////////////////
  128131. GreaterThanOperation.prototype = new BinaryOperation();
  128132. GreaterThanOperation.prototype.constructor = GreaterThanOperation;
  128133. GreaterThanOperation.superclass = BinaryOperation.prototype;
  128134. function GreaterThanOperation(lhs, rhs) {
  128135. if (arguments.length > 0) {
  128136. this.init(lhs, rhs);
  128137. }
  128138. }
  128139. GreaterThanOperation.prototype.init = function(lhs, rhs) {
  128140. GreaterThanOperation.superclass.init.call(this, lhs, rhs);
  128141. };
  128142. GreaterThanOperation.prototype.evaluate = function(c) {
  128143. return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c));
  128144. };
  128145. GreaterThanOperation.prototype.toString = function() {
  128146. return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")";
  128147. };
  128148. // LessThanOrEqualOperation //////////////////////////////////////////////////
  128149. LessThanOrEqualOperation.prototype = new BinaryOperation();
  128150. LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation;
  128151. LessThanOrEqualOperation.superclass = BinaryOperation.prototype;
  128152. function LessThanOrEqualOperation(lhs, rhs) {
  128153. if (arguments.length > 0) {
  128154. this.init(lhs, rhs);
  128155. }
  128156. }
  128157. LessThanOrEqualOperation.prototype.init = function(lhs, rhs) {
  128158. LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs);
  128159. };
  128160. LessThanOrEqualOperation.prototype.evaluate = function(c) {
  128161. return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c));
  128162. };
  128163. LessThanOrEqualOperation.prototype.toString = function() {
  128164. return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")";
  128165. };
  128166. // GreaterThanOrEqualOperation ///////////////////////////////////////////////
  128167. GreaterThanOrEqualOperation.prototype = new BinaryOperation();
  128168. GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation;
  128169. GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype;
  128170. function GreaterThanOrEqualOperation(lhs, rhs) {
  128171. if (arguments.length > 0) {
  128172. this.init(lhs, rhs);
  128173. }
  128174. }
  128175. GreaterThanOrEqualOperation.prototype.init = function(lhs, rhs) {
  128176. GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs);
  128177. };
  128178. GreaterThanOrEqualOperation.prototype.evaluate = function(c) {
  128179. return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c));
  128180. };
  128181. GreaterThanOrEqualOperation.prototype.toString = function() {
  128182. return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")";
  128183. };
  128184. // PlusOperation /////////////////////////////////////////////////////////////
  128185. PlusOperation.prototype = new BinaryOperation();
  128186. PlusOperation.prototype.constructor = PlusOperation;
  128187. PlusOperation.superclass = BinaryOperation.prototype;
  128188. function PlusOperation(lhs, rhs) {
  128189. if (arguments.length > 0) {
  128190. this.init(lhs, rhs);
  128191. }
  128192. }
  128193. PlusOperation.prototype.init = function(lhs, rhs) {
  128194. PlusOperation.superclass.init.call(this, lhs, rhs);
  128195. };
  128196. PlusOperation.prototype.evaluate = function(c) {
  128197. return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number());
  128198. };
  128199. PlusOperation.prototype.toString = function() {
  128200. return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")";
  128201. };
  128202. // MinusOperation ////////////////////////////////////////////////////////////
  128203. MinusOperation.prototype = new BinaryOperation();
  128204. MinusOperation.prototype.constructor = MinusOperation;
  128205. MinusOperation.superclass = BinaryOperation.prototype;
  128206. function MinusOperation(lhs, rhs) {
  128207. if (arguments.length > 0) {
  128208. this.init(lhs, rhs);
  128209. }
  128210. }
  128211. MinusOperation.prototype.init = function(lhs, rhs) {
  128212. MinusOperation.superclass.init.call(this, lhs, rhs);
  128213. };
  128214. MinusOperation.prototype.evaluate = function(c) {
  128215. return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number());
  128216. };
  128217. MinusOperation.prototype.toString = function() {
  128218. return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")";
  128219. };
  128220. // MultiplyOperation /////////////////////////////////////////////////////////
  128221. MultiplyOperation.prototype = new BinaryOperation();
  128222. MultiplyOperation.prototype.constructor = MultiplyOperation;
  128223. MultiplyOperation.superclass = BinaryOperation.prototype;
  128224. function MultiplyOperation(lhs, rhs) {
  128225. if (arguments.length > 0) {
  128226. this.init(lhs, rhs);
  128227. }
  128228. }
  128229. MultiplyOperation.prototype.init = function(lhs, rhs) {
  128230. MultiplyOperation.superclass.init.call(this, lhs, rhs);
  128231. };
  128232. MultiplyOperation.prototype.evaluate = function(c) {
  128233. return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number());
  128234. };
  128235. MultiplyOperation.prototype.toString = function() {
  128236. return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")";
  128237. };
  128238. // DivOperation //////////////////////////////////////////////////////////////
  128239. DivOperation.prototype = new BinaryOperation();
  128240. DivOperation.prototype.constructor = DivOperation;
  128241. DivOperation.superclass = BinaryOperation.prototype;
  128242. function DivOperation(lhs, rhs) {
  128243. if (arguments.length > 0) {
  128244. this.init(lhs, rhs);
  128245. }
  128246. }
  128247. DivOperation.prototype.init = function(lhs, rhs) {
  128248. DivOperation.superclass.init.call(this, lhs, rhs);
  128249. };
  128250. DivOperation.prototype.evaluate = function(c) {
  128251. return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number());
  128252. };
  128253. DivOperation.prototype.toString = function() {
  128254. return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")";
  128255. };
  128256. // ModOperation //////////////////////////////////////////////////////////////
  128257. ModOperation.prototype = new BinaryOperation();
  128258. ModOperation.prototype.constructor = ModOperation;
  128259. ModOperation.superclass = BinaryOperation.prototype;
  128260. function ModOperation(lhs, rhs) {
  128261. if (arguments.length > 0) {
  128262. this.init(lhs, rhs);
  128263. }
  128264. }
  128265. ModOperation.prototype.init = function(lhs, rhs) {
  128266. ModOperation.superclass.init.call(this, lhs, rhs);
  128267. };
  128268. ModOperation.prototype.evaluate = function(c) {
  128269. return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number());
  128270. };
  128271. ModOperation.prototype.toString = function() {
  128272. return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")";
  128273. };
  128274. // BarOperation //////////////////////////////////////////////////////////////
  128275. BarOperation.prototype = new BinaryOperation();
  128276. BarOperation.prototype.constructor = BarOperation;
  128277. BarOperation.superclass = BinaryOperation.prototype;
  128278. function BarOperation(lhs, rhs) {
  128279. if (arguments.length > 0) {
  128280. this.init(lhs, rhs);
  128281. }
  128282. }
  128283. BarOperation.prototype.init = function(lhs, rhs) {
  128284. BarOperation.superclass.init.call(this, lhs, rhs);
  128285. };
  128286. BarOperation.prototype.evaluate = function(c) {
  128287. return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset());
  128288. };
  128289. BarOperation.prototype.toString = function() {
  128290. return this.lhs.toString() + " | " + this.rhs.toString();
  128291. };
  128292. // PathExpr //////////////////////////////////////////////////////////////////
  128293. PathExpr.prototype = new Expression();
  128294. PathExpr.prototype.constructor = PathExpr;
  128295. PathExpr.superclass = Expression.prototype;
  128296. function PathExpr(filter, filterPreds, locpath) {
  128297. if (arguments.length > 0) {
  128298. this.init(filter, filterPreds, locpath);
  128299. }
  128300. }
  128301. PathExpr.prototype.init = function(filter, filterPreds, locpath) {
  128302. PathExpr.superclass.init.call(this);
  128303. this.filter = filter;
  128304. this.filterPredicates = filterPreds;
  128305. this.locationPath = locpath;
  128306. };
  128307. PathExpr.prototype.evaluate = function(c) {
  128308. var nodes;
  128309. var xpc = new XPathContext();
  128310. xpc.variableResolver = c.variableResolver;
  128311. xpc.functionResolver = c.functionResolver;
  128312. xpc.namespaceResolver = c.namespaceResolver;
  128313. xpc.expressionContextNode = c.expressionContextNode;
  128314. xpc.virtualRoot = c.virtualRoot;
  128315. xpc.caseInsensitive = c.caseInsensitive;
  128316. if (this.filter == null) {
  128317. nodes = [ c.contextNode ];
  128318. } else {
  128319. var ns = this.filter.evaluate(c);
  128320. if (!Utilities.instance_of(ns, XNodeSet)) {
  128321. if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) {
  128322. throw new Error("Path expression filter must evaluate to a nodset if predicates or location path are used");
  128323. }
  128324. return ns;
  128325. }
  128326. nodes = ns.toArray();
  128327. if (this.filterPredicates != null) {
  128328. // apply each of the predicates in turn
  128329. for (var j = 0; j < this.filterPredicates.length; j++) {
  128330. var pred = this.filterPredicates[j];
  128331. var newNodes = [];
  128332. xpc.contextSize = nodes.length;
  128333. for (xpc.contextPosition = 1; xpc.contextPosition <= xpc.contextSize; xpc.contextPosition++) {
  128334. xpc.contextNode = nodes[xpc.contextPosition - 1];
  128335. if (this.predicateMatches(pred, xpc)) {
  128336. newNodes.push(xpc.contextNode);
  128337. }
  128338. }
  128339. nodes = newNodes;
  128340. }
  128341. }
  128342. }
  128343. if (this.locationPath != null) {
  128344. if (this.locationPath.absolute) {
  128345. if (nodes[0].nodeType != 9 /*Node.DOCUMENT_NODE*/) {
  128346. if (xpc.virtualRoot != null) {
  128347. nodes = [ xpc.virtualRoot ];
  128348. } else {
  128349. if (nodes[0].ownerDocument == null) {
  128350. // IE 5.5 doesn't have ownerDocument?
  128351. var n = nodes[0];
  128352. while (n.parentNode != null) {
  128353. n = n.parentNode;
  128354. }
  128355. nodes = [ n ];
  128356. } else {
  128357. nodes = [ nodes[0].ownerDocument ];
  128358. }
  128359. }
  128360. } else {
  128361. nodes = [ nodes[0] ];
  128362. }
  128363. }
  128364. for (var i = 0; i < this.locationPath.steps.length; i++) {
  128365. var step = this.locationPath.steps[i];
  128366. var newNodes = [];
  128367. var newLocalContext = [];
  128368. for (var j = 0; j < nodes.length; j++) {
  128369. xpc.contextNode = nodes[j];
  128370. switch (step.axis) {
  128371. case Step.ANCESTOR:
  128372. // look at all the ancestor nodes
  128373. if (xpc.contextNode === xpc.virtualRoot) {
  128374. break;
  128375. }
  128376. var m;
  128377. if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
  128378. m = this.getOwnerElement(xpc.contextNode);
  128379. } else {
  128380. m = xpc.contextNode.parentNode;
  128381. }
  128382. while (m != null) {
  128383. if (step.nodeTest.matches(m, xpc)) {
  128384. newNodes.push(m);
  128385. }
  128386. if (m === xpc.virtualRoot) {
  128387. break;
  128388. }
  128389. m = m.parentNode;
  128390. }
  128391. break;
  128392. case Step.ANCESTORORSELF:
  128393. // look at all the ancestor nodes and the current node
  128394. for (var m = xpc.contextNode; m != null; m = m.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ ? this.getOwnerElement(m) : m.parentNode) {
  128395. if (step.nodeTest.matches(m, xpc)) {
  128396. newNodes.push(m);
  128397. }
  128398. if (m === xpc.virtualRoot) {
  128399. break;
  128400. }
  128401. }
  128402. break;
  128403. case Step.ATTRIBUTE:
  128404. // look at the attributes
  128405. var nnm = xpc.contextNode.attributes;
  128406. if (nnm != null) {
  128407. for (var k = 0; k < nnm.length; k++) {
  128408. var m = nnm.item(k);
  128409. if (step.nodeTest.matches(m, xpc)) {
  128410. newNodes.push(m);
  128411. }
  128412. }
  128413. }
  128414. break;
  128415. case Step.CHILD:
  128416. // look at all child elements
  128417. var pos = 0
  128418. var tmpContext = []
  128419. for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) {
  128420. if (step.nodeTest.matches(m, xpc)) {
  128421. newNodes.push(m);
  128422. //keep track of the element position between other matching siblings
  128423. tmpContext.push({contextPosition: ++pos});
  128424. }
  128425. }
  128426. for (var k=0; k<tmpContext.length; k++) {
  128427. //track size of matching siblings
  128428. tmpContext[k].contextSize = pos
  128429. newLocalContext.push(tmpContext[k])
  128430. }
  128431. break;
  128432. case Step.DESCENDANT:
  128433. // look at all descendant nodes
  128434. var st = [ xpc.contextNode.firstChild ];
  128435. while (st.length > 0) {
  128436. for (var m = st.pop(); m != null; ) {
  128437. if (step.nodeTest.matches(m, xpc)) {
  128438. newNodes.push(m);
  128439. }
  128440. if (m.firstChild != null) {
  128441. st.push(m.nextSibling);
  128442. m = m.firstChild;
  128443. } else {
  128444. m = m.nextSibling;
  128445. }
  128446. }
  128447. }
  128448. break;
  128449. case Step.DESCENDANTORSELF:
  128450. // look at self
  128451. if (step.nodeTest.matches(xpc.contextNode, xpc)) {
  128452. newNodes.push(xpc.contextNode);
  128453. }
  128454. // look at all descendant nodes
  128455. var st = [ xpc.contextNode.firstChild ];
  128456. while (st.length > 0) {
  128457. for (var m = st.pop(); m != null; ) {
  128458. if (step.nodeTest.matches(m, xpc)) {
  128459. newNodes.push(m);
  128460. }
  128461. if (m.firstChild != null) {
  128462. st.push(m.nextSibling);
  128463. m = m.firstChild;
  128464. } else {
  128465. m = m.nextSibling;
  128466. }
  128467. }
  128468. }
  128469. break;
  128470. case Step.FOLLOWING:
  128471. if (xpc.contextNode === xpc.virtualRoot) {
  128472. break;
  128473. }
  128474. var st = [];
  128475. if (xpc.contextNode.firstChild != null) {
  128476. st.unshift(xpc.contextNode.firstChild);
  128477. } else {
  128478. st.unshift(xpc.contextNode.nextSibling);
  128479. }
  128480. for (var m = xpc.contextNode; m != null && m.nodeType != 9 /*Node.DOCUMENT_NODE*/ && m !== xpc.virtualRoot; m = m.parentNode) {
  128481. st.unshift(m.nextSibling);
  128482. }
  128483. do {
  128484. for (var m = st.pop(); m != null; ) {
  128485. if (step.nodeTest.matches(m, xpc)) {
  128486. newNodes.push(m);
  128487. }
  128488. if (m.firstChild != null) {
  128489. st.push(m.nextSibling);
  128490. m = m.firstChild;
  128491. } else {
  128492. m = m.nextSibling;
  128493. }
  128494. }
  128495. } while (st.length > 0);
  128496. break;
  128497. case Step.FOLLOWINGSIBLING:
  128498. if (xpc.contextNode === xpc.virtualRoot) {
  128499. break;
  128500. }
  128501. for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) {
  128502. if (step.nodeTest.matches(m, xpc)) {
  128503. newNodes.push(m);
  128504. }
  128505. }
  128506. break;
  128507. case Step.NAMESPACE:
  128508. var n = {};
  128509. if (xpc.contextNode.nodeType == 1 /*Node.ELEMENT_NODE*/) {
  128510. n["xml"] = XPath.XML_NAMESPACE_URI;
  128511. n["xmlns"] = XPath.XMLNS_NAMESPACE_URI;
  128512. for (var m = xpc.contextNode; m != null && m.nodeType == 1 /*Node.ELEMENT_NODE*/; m = m.parentNode) {
  128513. for (var k = 0; k < m.attributes.length; k++) {
  128514. var attr = m.attributes.item(k);
  128515. var nm = String(attr.name);
  128516. if (nm == "xmlns") {
  128517. if (n[""] == undefined) {
  128518. n[""] = attr.value;
  128519. }
  128520. } else if (nm.length > 6 && nm.substring(0, 6) == "xmlns:") {
  128521. var pre = nm.substring(6, nm.length);
  128522. if (n[pre] == undefined) {
  128523. n[pre] = attr.value;
  128524. }
  128525. }
  128526. }
  128527. }
  128528. for (var pre in n) {
  128529. var nsn = new NamespaceNode(pre, n[pre], xpc.contextNode);
  128530. if (step.nodeTest.matches(nsn, xpc)) {
  128531. newNodes.push(nsn);
  128532. }
  128533. }
  128534. }
  128535. break;
  128536. case Step.PARENT:
  128537. m = null;
  128538. if (xpc.contextNode !== xpc.virtualRoot) {
  128539. if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
  128540. m = this.getOwnerElement(xpc.contextNode);
  128541. } else {
  128542. m = xpc.contextNode.parentNode;
  128543. }
  128544. }
  128545. if (m != null && step.nodeTest.matches(m, xpc)) {
  128546. newNodes.push(m);
  128547. }
  128548. break;
  128549. case Step.PRECEDING:
  128550. var st;
  128551. if (xpc.virtualRoot != null) {
  128552. st = [ xpc.virtualRoot ];
  128553. } else {
  128554. st = xpc.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/
  128555. ? [ xpc.contextNode ]
  128556. : [ xpc.contextNode.ownerDocument ];
  128557. }
  128558. outer: while (st.length > 0) {
  128559. for (var m = st.pop(); m != null; ) {
  128560. if (m == xpc.contextNode) {
  128561. break outer;
  128562. }
  128563. if (step.nodeTest.matches(m, xpc)) {
  128564. newNodes.unshift(m);
  128565. }
  128566. if (m.firstChild != null) {
  128567. st.push(m.nextSibling);
  128568. m = m.firstChild;
  128569. } else {
  128570. m = m.nextSibling;
  128571. }
  128572. }
  128573. }
  128574. break;
  128575. case Step.PRECEDINGSIBLING:
  128576. if (xpc.contextNode === xpc.virtualRoot) {
  128577. break;
  128578. }
  128579. for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) {
  128580. if (step.nodeTest.matches(m, xpc)) {
  128581. newNodes.push(m);
  128582. }
  128583. }
  128584. break;
  128585. case Step.SELF:
  128586. if (step.nodeTest.matches(xpc.contextNode, xpc)) {
  128587. newNodes.push(xpc.contextNode);
  128588. }
  128589. break;
  128590. default:
  128591. }
  128592. }
  128593. nodes = newNodes;
  128594. // apply each of the predicates in turn
  128595. for (var j = 0; j < step.predicates.length; j++) {
  128596. var pred = step.predicates[j];
  128597. var newNodes = [];
  128598. xpc.contextSize = nodes.length;
  128599. for (xpc.contextPosition = 1; xpc.contextPosition <= xpc.contextSize; xpc.contextPosition++) {
  128600. xpc.contextNode = nodes[xpc.contextPosition - 1];
  128601. //if we keep track of the node original context then use it
  128602. //end goal is to always use original cotnext, now implemented just for CHILD axis
  128603. var localCtx = newLocalContext.length>0?this.getLocalCtx(xpc, newLocalContext[xpc.contextPosition-1]):xpc
  128604. if (this.predicateMatches(pred, localCtx)) {
  128605. newNodes.push(xpc.contextNode);
  128606. } else {
  128607. }
  128608. }
  128609. nodes = newNodes;
  128610. //console.log(nodes.length)
  128611. }
  128612. }
  128613. }
  128614. var ns = new XNodeSet();
  128615. ns.addArray(nodes);
  128616. return ns;
  128617. };
  128618. PathExpr.prototype.getLocalCtx = function(xpc, localCtx, length) {
  128619. var res = new XPathContext();
  128620. res.variableResolver = xpc.variableResolver;
  128621. res.functionResolver = xpc.functionResolver;
  128622. res.namespaceResolver = xpc.namespaceResolver;
  128623. res.expressionContextNode = xpc.expressionContextNode;
  128624. res.virtualRoot = xpc.virtualRoot;
  128625. res.caseInsensitive = xpc.caseInsensitive;
  128626. res.contextNode = xpc.contextNode;
  128627. res.contextPosition = localCtx.contextPosition;
  128628. res.contextSize = localCtx.contextSize;
  128629. return res;
  128630. };
  128631. PathExpr.prototype.predicateMatches = function(pred, c) {
  128632. var res = pred.evaluate(c);
  128633. if (Utilities.instance_of(res, XNumber)) {
  128634. var val = c.contextPosition == res.numberValue()
  128635. return val;
  128636. }
  128637. return res.booleanValue();
  128638. };
  128639. PathExpr.prototype.toString = function() {
  128640. if (this.filter != undefined) {
  128641. var s = this.filter.toString();
  128642. if (Utilities.instance_of(this.filter, XString)) {
  128643. s = "'" + s + "'";
  128644. }
  128645. if (this.filterPredicates != undefined) {
  128646. for (var i = 0; i < this.filterPredicates.length; i++) {
  128647. s = s + "[" + this.filterPredicates[i].toString() + "]";
  128648. }
  128649. }
  128650. if (this.locationPath != undefined) {
  128651. if (!this.locationPath.absolute) {
  128652. s += "/";
  128653. }
  128654. s += this.locationPath.toString();
  128655. }
  128656. return s;
  128657. }
  128658. return this.locationPath.toString();
  128659. };
  128660. PathExpr.prototype.getOwnerElement = function(n) {
  128661. // DOM 2 has ownerElement
  128662. if (n.ownerElement) {
  128663. return n.ownerElement;
  128664. }
  128665. // DOM 1 Internet Explorer can use selectSingleNode (ironically)
  128666. try {
  128667. if (n.selectSingleNode) {
  128668. return n.selectSingleNode("..");
  128669. }
  128670. } catch (e) {
  128671. }
  128672. // Other DOM 1 implementations must use this egregious search
  128673. var doc = n.nodeType == 9 /*Node.DOCUMENT_NODE*/
  128674. ? n
  128675. : n.ownerDocument;
  128676. var elts = doc.getElementsByTagName("*");
  128677. for (var i = 0; i < elts.length; i++) {
  128678. var elt = elts.item(i);
  128679. var nnm = elt.attributes;
  128680. for (var j = 0; j < nnm.length; j++) {
  128681. var an = nnm.item(j);
  128682. if (an === n) {
  128683. return elt;
  128684. }
  128685. }
  128686. }
  128687. return null;
  128688. };
  128689. // LocationPath //////////////////////////////////////////////////////////////
  128690. LocationPath.prototype = new Object();
  128691. LocationPath.prototype.constructor = LocationPath;
  128692. LocationPath.superclass = Object.prototype;
  128693. function LocationPath(abs, steps) {
  128694. if (arguments.length > 0) {
  128695. this.init(abs, steps);
  128696. }
  128697. }
  128698. LocationPath.prototype.init = function(abs, steps) {
  128699. this.absolute = abs;
  128700. this.steps = steps;
  128701. };
  128702. LocationPath.prototype.toString = function() {
  128703. var s;
  128704. if (this.absolute) {
  128705. s = "/";
  128706. } else {
  128707. s = "";
  128708. }
  128709. for (var i = 0; i < this.steps.length; i++) {
  128710. if (i != 0) {
  128711. s += "/";
  128712. }
  128713. s += this.steps[i].toString();
  128714. }
  128715. return s;
  128716. };
  128717. // Step //////////////////////////////////////////////////////////////////////
  128718. Step.prototype = new Object();
  128719. Step.prototype.constructor = Step;
  128720. Step.superclass = Object.prototype;
  128721. function Step(axis, nodetest, preds) {
  128722. if (arguments.length > 0) {
  128723. this.init(axis, nodetest, preds);
  128724. }
  128725. }
  128726. Step.prototype.init = function(axis, nodetest, preds) {
  128727. this.axis = axis;
  128728. this.nodeTest = nodetest;
  128729. this.predicates = preds;
  128730. };
  128731. Step.prototype.toString = function() {
  128732. var s;
  128733. switch (this.axis) {
  128734. case Step.ANCESTOR:
  128735. s = "ancestor";
  128736. break;
  128737. case Step.ANCESTORORSELF:
  128738. s = "ancestor-or-self";
  128739. break;
  128740. case Step.ATTRIBUTE:
  128741. s = "attribute";
  128742. break;
  128743. case Step.CHILD:
  128744. s = "child";
  128745. break;
  128746. case Step.DESCENDANT:
  128747. s = "descendant";
  128748. break;
  128749. case Step.DESCENDANTORSELF:
  128750. s = "descendant-or-self";
  128751. break;
  128752. case Step.FOLLOWING:
  128753. s = "following";
  128754. break;
  128755. case Step.FOLLOWINGSIBLING:
  128756. s = "following-sibling";
  128757. break;
  128758. case Step.NAMESPACE:
  128759. s = "namespace";
  128760. break;
  128761. case Step.PARENT:
  128762. s = "parent";
  128763. break;
  128764. case Step.PRECEDING:
  128765. s = "preceding";
  128766. break;
  128767. case Step.PRECEDINGSIBLING:
  128768. s = "preceding-sibling";
  128769. break;
  128770. case Step.SELF:
  128771. s = "self";
  128772. break;
  128773. }
  128774. s += "::";
  128775. s += this.nodeTest.toString();
  128776. for (var i = 0; i < this.predicates.length; i++) {
  128777. s += "[" + this.predicates[i].toString() + "]";
  128778. }
  128779. return s;
  128780. };
  128781. Step.ANCESTOR = 0;
  128782. Step.ANCESTORORSELF = 1;
  128783. Step.ATTRIBUTE = 2;
  128784. Step.CHILD = 3;
  128785. Step.DESCENDANT = 4;
  128786. Step.DESCENDANTORSELF = 5;
  128787. Step.FOLLOWING = 6;
  128788. Step.FOLLOWINGSIBLING = 7;
  128789. Step.NAMESPACE = 8;
  128790. Step.PARENT = 9;
  128791. Step.PRECEDING = 10;
  128792. Step.PRECEDINGSIBLING = 11;
  128793. Step.SELF = 12;
  128794. // NodeTest //////////////////////////////////////////////////////////////////
  128795. NodeTest.prototype = new Object();
  128796. NodeTest.prototype.constructor = NodeTest;
  128797. NodeTest.superclass = Object.prototype;
  128798. function NodeTest(type, value) {
  128799. if (arguments.length > 0) {
  128800. this.init(type, value);
  128801. }
  128802. }
  128803. NodeTest.prototype.init = function(type, value) {
  128804. this.type = type;
  128805. this.value = value;
  128806. };
  128807. NodeTest.prototype.toString = function() {
  128808. switch (this.type) {
  128809. case NodeTest.NAMETESTANY:
  128810. return "*";
  128811. case NodeTest.NAMETESTPREFIXANY:
  128812. return this.value + ":*";
  128813. case NodeTest.NAMETESTRESOLVEDANY:
  128814. return "{" + this.value + "}*";
  128815. case NodeTest.NAMETESTQNAME:
  128816. return this.value;
  128817. case NodeTest.NAMETESTRESOLVEDNAME:
  128818. return "{" + this.namespaceURI + "}" + this.value;
  128819. case NodeTest.COMMENT:
  128820. return "comment()";
  128821. case NodeTest.TEXT:
  128822. return "text()";
  128823. case NodeTest.PI:
  128824. if (this.value != undefined) {
  128825. return "processing-instruction(\"" + this.value + "\")";
  128826. }
  128827. return "processing-instruction()";
  128828. case NodeTest.NODE:
  128829. return "node()";
  128830. }
  128831. return "<unknown nodetest type>";
  128832. };
  128833. NodeTest.prototype.matches = function(n, xpc) {
  128834. switch (this.type) {
  128835. case NodeTest.NAMETESTANY:
  128836. if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/
  128837. || n.nodeType == 1 /*Node.ELEMENT_NODE*/
  128838. || n.nodeType == XPathNamespace.XPATH_NAMESPACE_NODE) {
  128839. return true;
  128840. }
  128841. return false;
  128842. case NodeTest.NAMETESTPREFIXANY:
  128843. if ((n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ || n.nodeType == 1 /*Node.ELEMENT_NODE*/)) {
  128844. var ns = xpc.namespaceResolver.getNamespace(this.value, xpc.expressionContextNode);
  128845. if (ns == null) {
  128846. throw new Error("Cannot resolve QName " + this.value);
  128847. }
  128848. return true;
  128849. }
  128850. return false;
  128851. case NodeTest.NAMETESTQNAME:
  128852. if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/
  128853. || n.nodeType == 1 /*Node.ELEMENT_NODE*/
  128854. || n.nodeType == XPathNamespace.XPATH_NAMESPACE_NODE) {
  128855. var test = Utilities.resolveQName(this.value, xpc.namespaceResolver, xpc.expressionContextNode, false);
  128856. if (test[0] == null) {
  128857. throw new Error("Cannot resolve QName " + this.value);
  128858. }
  128859. test[0] = String(test[0]);
  128860. test[1] = String(test[1]);
  128861. if (test[0] == "") {
  128862. test[0] = null;
  128863. }
  128864. var node = Utilities.resolveQName(n.nodeName, xpc.namespaceResolver, n, n.nodeType == 1 /*Node.ELEMENT_NODE*/);
  128865. node[0] = String(node[0]);
  128866. node[1] = String(node[1]);
  128867. if (node[0] == "") {
  128868. node[0] = null;
  128869. }
  128870. if (xpc.caseInsensitive) {
  128871. return test[0] == node[0] && String(test[1]).toLowerCase() == String(node[1]).toLowerCase();
  128872. }
  128873. return test[0] == node[0] && test[1] == node[1];
  128874. }
  128875. return false;
  128876. case NodeTest.COMMENT:
  128877. return n.nodeType == 8 /*Node.COMMENT_NODE*/;
  128878. case NodeTest.TEXT:
  128879. return n.nodeType == 3 /*Node.TEXT_NODE*/ || n.nodeType == 4 /*Node.CDATA_SECTION_NODE*/;
  128880. case NodeTest.PI:
  128881. return n.nodeType == 7 /*Node.PROCESSING_INSTRUCTION_NODE*/
  128882. && (this.value == null || n.nodeName == this.value);
  128883. case NodeTest.NODE:
  128884. return n.nodeType == 9 /*Node.DOCUMENT_NODE*/
  128885. || n.nodeType == 1 /*Node.ELEMENT_NODE*/
  128886. || n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/
  128887. || n.nodeType == 3 /*Node.TEXT_NODE*/
  128888. || n.nodeType == 4 /*Node.CDATA_SECTION_NODE*/
  128889. || n.nodeType == 8 /*Node.COMMENT_NODE*/
  128890. || n.nodeType == 7 /*Node.PROCESSING_INSTRUCTION_NODE*/;
  128891. }
  128892. return false;
  128893. };
  128894. NodeTest.NAMETESTANY = 0;
  128895. NodeTest.NAMETESTPREFIXANY = 1;
  128896. NodeTest.NAMETESTQNAME = 2;
  128897. NodeTest.COMMENT = 3;
  128898. NodeTest.TEXT = 4;
  128899. NodeTest.PI = 5;
  128900. NodeTest.NODE = 6;
  128901. // VariableReference /////////////////////////////////////////////////////////
  128902. VariableReference.prototype = new Expression();
  128903. VariableReference.prototype.constructor = VariableReference;
  128904. VariableReference.superclass = Expression.prototype;
  128905. function VariableReference(v) {
  128906. if (arguments.length > 0) {
  128907. this.init(v);
  128908. }
  128909. }
  128910. VariableReference.prototype.init = function(v) {
  128911. this.variable = v;
  128912. };
  128913. VariableReference.prototype.toString = function() {
  128914. return "$" + this.variable;
  128915. };
  128916. VariableReference.prototype.evaluate = function(c) {
  128917. return c.variableResolver.getVariable(this.variable, c);
  128918. };
  128919. // FunctionCall //////////////////////////////////////////////////////////////
  128920. FunctionCall.prototype = new Expression();
  128921. FunctionCall.prototype.constructor = FunctionCall;
  128922. FunctionCall.superclass = Expression.prototype;
  128923. function FunctionCall(fn, args) {
  128924. if (arguments.length > 0) {
  128925. this.init(fn, args);
  128926. }
  128927. }
  128928. FunctionCall.prototype.init = function(fn, args) {
  128929. this.functionName = fn;
  128930. this.arguments = args;
  128931. };
  128932. FunctionCall.prototype.toString = function() {
  128933. var s = this.functionName + "(";
  128934. for (var i = 0; i < this.arguments.length; i++) {
  128935. if (i > 0) {
  128936. s += ", ";
  128937. }
  128938. s += this.arguments[i].toString();
  128939. }
  128940. return s + ")";
  128941. };
  128942. FunctionCall.prototype.evaluate = function(c) {
  128943. var f = c.functionResolver.getFunction(this.functionName, c);
  128944. if (f == undefined) {
  128945. throw new Error("Unknown function " + this.functionName);
  128946. }
  128947. var a = [c].concat(this.arguments);
  128948. return f.apply(c.functionResolver.thisArg, a);
  128949. };
  128950. // XString ///////////////////////////////////////////////////////////////////
  128951. XString.prototype = new Expression();
  128952. XString.prototype.constructor = XString;
  128953. XString.superclass = Expression.prototype;
  128954. function XString(s) {
  128955. if (arguments.length > 0) {
  128956. this.init(s);
  128957. }
  128958. }
  128959. XString.prototype.init = function(s) {
  128960. this.str = s;
  128961. };
  128962. XString.prototype.toString = function() {
  128963. return this.str;
  128964. };
  128965. XString.prototype.evaluate = function(c) {
  128966. return this;
  128967. };
  128968. XString.prototype.string = function() {
  128969. return this;
  128970. };
  128971. XString.prototype.number = function() {
  128972. return new XNumber(this.str);
  128973. };
  128974. XString.prototype.bool = function() {
  128975. return new XBoolean(this.str);
  128976. };
  128977. XString.prototype.nodeset = function() {
  128978. throw new Error("Cannot convert string to nodeset");
  128979. };
  128980. XString.prototype.stringValue = function() {
  128981. return this.str;
  128982. };
  128983. XString.prototype.numberValue = function() {
  128984. return this.number().numberValue();
  128985. };
  128986. XString.prototype.booleanValue = function() {
  128987. return this.bool().booleanValue();
  128988. };
  128989. XString.prototype.equals = function(r) {
  128990. if (Utilities.instance_of(r, XBoolean)) {
  128991. return this.bool().equals(r);
  128992. }
  128993. if (Utilities.instance_of(r, XNumber)) {
  128994. return this.number().equals(r);
  128995. }
  128996. if (Utilities.instance_of(r, XNodeSet)) {
  128997. return r.compareWithString(this, Operators.equals);
  128998. }
  128999. return new XBoolean(this.str == r.str);
  129000. };
  129001. XString.prototype.notequal = function(r) {
  129002. if (Utilities.instance_of(r, XBoolean)) {
  129003. return this.bool().notequal(r);
  129004. }
  129005. if (Utilities.instance_of(r, XNumber)) {
  129006. return this.number().notequal(r);
  129007. }
  129008. if (Utilities.instance_of(r, XNodeSet)) {
  129009. return r.compareWithString(this, Operators.notequal);
  129010. }
  129011. return new XBoolean(this.str != r.str);
  129012. };
  129013. XString.prototype.lessthan = function(r) {
  129014. if (Utilities.instance_of(r, XNodeSet)) {
  129015. return r.compareWithNumber(this.number(), Operators.greaterthanorequal);
  129016. }
  129017. return this.number().lessthan(r.number());
  129018. };
  129019. XString.prototype.greaterthan = function(r) {
  129020. if (Utilities.instance_of(r, XNodeSet)) {
  129021. return r.compareWithNumber(this.number(), Operators.lessthanorequal);
  129022. }
  129023. return this.number().greaterthan(r.number());
  129024. };
  129025. XString.prototype.lessthanorequal = function(r) {
  129026. if (Utilities.instance_of(r, XNodeSet)) {
  129027. return r.compareWithNumber(this.number(), Operators.greaterthan);
  129028. }
  129029. return this.number().lessthanorequal(r.number());
  129030. };
  129031. XString.prototype.greaterthanorequal = function(r) {
  129032. if (Utilities.instance_of(r, XNodeSet)) {
  129033. return r.compareWithNumber(this.number(), Operators.lessthan);
  129034. }
  129035. return this.number().greaterthanorequal(r.number());
  129036. };
  129037. // XNumber ///////////////////////////////////////////////////////////////////
  129038. XNumber.prototype = new Expression();
  129039. XNumber.prototype.constructor = XNumber;
  129040. XNumber.superclass = Expression.prototype;
  129041. function XNumber(n) {
  129042. if (arguments.length > 0) {
  129043. this.init(n);
  129044. }
  129045. }
  129046. XNumber.prototype.init = function(n) {
  129047. this.num = Number(n);
  129048. };
  129049. XNumber.prototype.toString = function() {
  129050. return this.num;
  129051. };
  129052. XNumber.prototype.evaluate = function(c) {
  129053. return this;
  129054. };
  129055. XNumber.prototype.string = function() {
  129056. return new XString(this.num);
  129057. };
  129058. XNumber.prototype.number = function() {
  129059. return this;
  129060. };
  129061. XNumber.prototype.bool = function() {
  129062. return new XBoolean(this.num);
  129063. };
  129064. XNumber.prototype.nodeset = function() {
  129065. throw new Error("Cannot convert number to nodeset");
  129066. };
  129067. XNumber.prototype.stringValue = function() {
  129068. return this.string().stringValue();
  129069. };
  129070. XNumber.prototype.numberValue = function() {
  129071. return this.num;
  129072. };
  129073. XNumber.prototype.booleanValue = function() {
  129074. return this.bool().booleanValue();
  129075. };
  129076. XNumber.prototype.negate = function() {
  129077. return new XNumber(-this.num);
  129078. };
  129079. XNumber.prototype.equals = function(r) {
  129080. if (Utilities.instance_of(r, XBoolean)) {
  129081. return this.bool().equals(r);
  129082. }
  129083. if (Utilities.instance_of(r, XString)) {
  129084. return this.equals(r.number());
  129085. }
  129086. if (Utilities.instance_of(r, XNodeSet)) {
  129087. return r.compareWithNumber(this, Operators.equals);
  129088. }
  129089. return new XBoolean(this.num == r.num);
  129090. };
  129091. XNumber.prototype.notequal = function(r) {
  129092. if (Utilities.instance_of(r, XBoolean)) {
  129093. return this.bool().notequal(r);
  129094. }
  129095. if (Utilities.instance_of(r, XString)) {
  129096. return this.notequal(r.number());
  129097. }
  129098. if (Utilities.instance_of(r, XNodeSet)) {
  129099. return r.compareWithNumber(this, Operators.notequal);
  129100. }
  129101. return new XBoolean(this.num != r.num);
  129102. };
  129103. XNumber.prototype.lessthan = function(r) {
  129104. if (Utilities.instance_of(r, XNodeSet)) {
  129105. return r.compareWithNumber(this, Operators.greaterthanorequal);
  129106. }
  129107. if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
  129108. return this.lessthan(r.number());
  129109. }
  129110. return new XBoolean(this.num < r.num);
  129111. };
  129112. XNumber.prototype.greaterthan = function(r) {
  129113. if (Utilities.instance_of(r, XNodeSet)) {
  129114. return r.compareWithNumber(this, Operators.lessthanorequal);
  129115. }
  129116. if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
  129117. return this.greaterthan(r.number());
  129118. }
  129119. return new XBoolean(this.num > r.num);
  129120. };
  129121. XNumber.prototype.lessthanorequal = function(r) {
  129122. if (Utilities.instance_of(r, XNodeSet)) {
  129123. return r.compareWithNumber(this, Operators.greaterthan);
  129124. }
  129125. if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
  129126. return this.lessthanorequal(r.number());
  129127. }
  129128. return new XBoolean(this.num <= r.num);
  129129. };
  129130. XNumber.prototype.greaterthanorequal = function(r) {
  129131. if (Utilities.instance_of(r, XNodeSet)) {
  129132. return r.compareWithNumber(this, Operators.lessthan);
  129133. }
  129134. if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
  129135. return this.greaterthanorequal(r.number());
  129136. }
  129137. return new XBoolean(this.num >= r.num);
  129138. };
  129139. XNumber.prototype.plus = function(r) {
  129140. return new XNumber(this.num + r.num);
  129141. };
  129142. XNumber.prototype.minus = function(r) {
  129143. return new XNumber(this.num - r.num);
  129144. };
  129145. XNumber.prototype.multiply = function(r) {
  129146. return new XNumber(this.num * r.num);
  129147. };
  129148. XNumber.prototype.div = function(r) {
  129149. return new XNumber(this.num / r.num);
  129150. };
  129151. XNumber.prototype.mod = function(r) {
  129152. return new XNumber(this.num % r.num);
  129153. };
  129154. // XBoolean //////////////////////////////////////////////////////////////////
  129155. XBoolean.prototype = new Expression();
  129156. XBoolean.prototype.constructor = XBoolean;
  129157. XBoolean.superclass = Expression.prototype;
  129158. function XBoolean(b) {
  129159. if (arguments.length > 0) {
  129160. this.init(b);
  129161. }
  129162. }
  129163. XBoolean.prototype.init = function(b) {
  129164. this.b = Boolean(b);
  129165. };
  129166. XBoolean.prototype.toString = function() {
  129167. return this.b.toString();
  129168. };
  129169. XBoolean.prototype.evaluate = function(c) {
  129170. return this;
  129171. };
  129172. XBoolean.prototype.string = function() {
  129173. return new XString(this.b);
  129174. };
  129175. XBoolean.prototype.number = function() {
  129176. return new XNumber(this.b);
  129177. };
  129178. XBoolean.prototype.bool = function() {
  129179. return this;
  129180. };
  129181. XBoolean.prototype.nodeset = function() {
  129182. throw new Error("Cannot convert boolean to nodeset");
  129183. };
  129184. XBoolean.prototype.stringValue = function() {
  129185. return this.string().stringValue();
  129186. };
  129187. XBoolean.prototype.numberValue = function() {
  129188. return this.num().numberValue();
  129189. };
  129190. XBoolean.prototype.booleanValue = function() {
  129191. return this.b;
  129192. };
  129193. XBoolean.prototype.not = function() {
  129194. return new XBoolean(!this.b);
  129195. };
  129196. XBoolean.prototype.equals = function(r) {
  129197. if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {
  129198. return this.equals(r.bool());
  129199. }
  129200. if (Utilities.instance_of(r, XNodeSet)) {
  129201. return r.compareWithBoolean(this, Operators.equals);
  129202. }
  129203. return new XBoolean(this.b == r.b);
  129204. };
  129205. XBoolean.prototype.notequal = function(r) {
  129206. if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {
  129207. return this.notequal(r.bool());
  129208. }
  129209. if (Utilities.instance_of(r, XNodeSet)) {
  129210. return r.compareWithBoolean(this, Operators.notequal);
  129211. }
  129212. return new XBoolean(this.b != r.b);
  129213. };
  129214. XBoolean.prototype.lessthan = function(r) {
  129215. if (Utilities.instance_of(r, XNodeSet)) {
  129216. return r.compareWithNumber(this.number(), Operators.greaterthanorequal);
  129217. }
  129218. return this.number().lessthan(r.number());
  129219. };
  129220. XBoolean.prototype.greaterthan = function(r) {
  129221. if (Utilities.instance_of(r, XNodeSet)) {
  129222. return r.compareWithNumber(this.number(), Operators.lessthanorequal);
  129223. }
  129224. return this.number().greaterthan(r.number());
  129225. };
  129226. XBoolean.prototype.lessthanorequal = function(r) {
  129227. if (Utilities.instance_of(r, XNodeSet)) {
  129228. return r.compareWithNumber(this.number(), Operators.greaterthan);
  129229. }
  129230. return this.number().lessthanorequal(r.number());
  129231. };
  129232. XBoolean.prototype.greaterthanorequal = function(r) {
  129233. if (Utilities.instance_of(r, XNodeSet)) {
  129234. return r.compareWithNumber(this.number(), Operators.lessthan);
  129235. }
  129236. return this.number().greaterthanorequal(r.number());
  129237. };
  129238. // AVLTree ///////////////////////////////////////////////////////////////////
  129239. AVLTree.prototype = new Object();
  129240. AVLTree.prototype.constructor = AVLTree;
  129241. AVLTree.superclass = Object.prototype;
  129242. function AVLTree(n) {
  129243. this.init(n);
  129244. }
  129245. AVLTree.prototype.init = function(n) {
  129246. this.left = null;
  129247. this.right = null;
  129248. this.node = n;
  129249. this.depth = 1;
  129250. };
  129251. AVLTree.prototype.balance = function() {
  129252. var ldepth = this.left == null ? 0 : this.left.depth;
  129253. var rdepth = this.right == null ? 0 : this.right.depth;
  129254. if (ldepth > rdepth + 1) {
  129255. // LR or LL rotation
  129256. var lldepth = this.left.left == null ? 0 : this.left.left.depth;
  129257. var lrdepth = this.left.right == null ? 0 : this.left.right.depth;
  129258. if (lldepth < lrdepth) {
  129259. // LR rotation consists of a RR rotation of the left child
  129260. this.left.rotateRR();
  129261. // plus a LL rotation of this node, which happens anyway
  129262. }
  129263. this.rotateLL();
  129264. } else if (ldepth + 1 < rdepth) {
  129265. // RR or RL rorarion
  129266. var rrdepth = this.right.right == null ? 0 : this.right.right.depth;
  129267. var rldepth = this.right.left == null ? 0 : this.right.left.depth;
  129268. if (rldepth > rrdepth) {
  129269. // RR rotation consists of a LL rotation of the right child
  129270. this.right.rotateLL();
  129271. // plus a RR rotation of this node, which happens anyway
  129272. }
  129273. this.rotateRR();
  129274. }
  129275. };
  129276. AVLTree.prototype.rotateLL = function() {
  129277. // the left side is too long => rotate from the left (_not_ leftwards)
  129278. var nodeBefore = this.node;
  129279. var rightBefore = this.right;
  129280. this.node = this.left.node;
  129281. this.right = this.left;
  129282. this.left = this.left.left;
  129283. this.right.left = this.right.right;
  129284. this.right.right = rightBefore;
  129285. this.right.node = nodeBefore;
  129286. this.right.updateInNewLocation();
  129287. this.updateInNewLocation();
  129288. };
  129289. AVLTree.prototype.rotateRR = function() {
  129290. // the right side is too long => rotate from the right (_not_ rightwards)
  129291. var nodeBefore = this.node;
  129292. var leftBefore = this.left;
  129293. this.node = this.right.node;
  129294. this.left = this.right;
  129295. this.right = this.right.right;
  129296. this.left.right = this.left.left;
  129297. this.left.left = leftBefore;
  129298. this.left.node = nodeBefore;
  129299. this.left.updateInNewLocation();
  129300. this.updateInNewLocation();
  129301. };
  129302. AVLTree.prototype.updateInNewLocation = function() {
  129303. this.getDepthFromChildren();
  129304. };
  129305. AVLTree.prototype.getDepthFromChildren = function() {
  129306. this.depth = this.node == null ? 0 : 1;
  129307. if (this.left != null) {
  129308. this.depth = this.left.depth + 1;
  129309. }
  129310. if (this.right != null && this.depth <= this.right.depth) {
  129311. this.depth = this.right.depth + 1;
  129312. }
  129313. };
  129314. AVLTree.prototype.order = function(n1, n2) {
  129315. if (n1 === n2) {
  129316. return 0;
  129317. }
  129318. var d1 = 0;
  129319. var d2 = 0;
  129320. for (var m1 = n1; m1 != null; m1 = m1.parentNode) {
  129321. d1++;
  129322. }
  129323. for (var m2 = n2; m2 != null; m2 = m2.parentNode) {
  129324. d2++;
  129325. }
  129326. if (d1 > d2) {
  129327. while (d1 > d2) {
  129328. n1 = n1.parentNode;
  129329. d1--;
  129330. }
  129331. if (n1 == n2) {
  129332. return 1;
  129333. }
  129334. } else if (d2 > d1) {
  129335. while (d2 > d1) {
  129336. n2 = n2.parentNode;
  129337. d2--;
  129338. }
  129339. if (n1 == n2) {
  129340. return -1;
  129341. }
  129342. }
  129343. while (n1.parentNode != n2.parentNode) {
  129344. n1 = n1.parentNode;
  129345. n2 = n2.parentNode;
  129346. }
  129347. while (n1.previousSibling != null && n2.previousSibling != null) {
  129348. n1 = n1.previousSibling;
  129349. n2 = n2.previousSibling;
  129350. }
  129351. if (n1.previousSibling == null) {
  129352. return -1;
  129353. }
  129354. return 1;
  129355. };
  129356. AVLTree.prototype.add = function(n) {
  129357. if (n === this.node) {
  129358. return false;
  129359. }
  129360. var o = this.order(n, this.node);
  129361. var ret = false;
  129362. if (o == -1) {
  129363. if (this.left == null) {
  129364. this.left = new AVLTree(n);
  129365. ret = true;
  129366. } else {
  129367. ret = this.left.add(n);
  129368. if (ret) {
  129369. this.balance();
  129370. }
  129371. }
  129372. } else if (o == 1) {
  129373. if (this.right == null) {
  129374. this.right = new AVLTree(n);
  129375. ret = true;
  129376. } else {
  129377. ret = this.right.add(n);
  129378. if (ret) {
  129379. this.balance();
  129380. }
  129381. }
  129382. }
  129383. if (ret) {
  129384. this.getDepthFromChildren();
  129385. }
  129386. return ret;
  129387. };
  129388. // XNodeSet //////////////////////////////////////////////////////////////////
  129389. XNodeSet.prototype = new Expression();
  129390. XNodeSet.prototype.constructor = XNodeSet;
  129391. XNodeSet.superclass = Expression.prototype;
  129392. function XNodeSet() {
  129393. this.init();
  129394. }
  129395. XNodeSet.prototype.init = function() {
  129396. this.tree = null;
  129397. this.size = 0;
  129398. };
  129399. XNodeSet.prototype.toString = function() {
  129400. var p = this.first();
  129401. if (p == null) {
  129402. return "";
  129403. }
  129404. return this.stringForNode(p);
  129405. };
  129406. XNodeSet.prototype.evaluate = function(c) {
  129407. return this;
  129408. };
  129409. XNodeSet.prototype.string = function() {
  129410. return new XString(this.toString());
  129411. };
  129412. XNodeSet.prototype.stringValue = function() {
  129413. return this.toString();
  129414. };
  129415. XNodeSet.prototype.number = function() {
  129416. return new XNumber(this.string());
  129417. };
  129418. XNodeSet.prototype.numberValue = function() {
  129419. return Number(this.string());
  129420. };
  129421. XNodeSet.prototype.bool = function() {
  129422. return new XBoolean(this.tree != null);
  129423. };
  129424. XNodeSet.prototype.booleanValue = function() {
  129425. return this.tree != null;
  129426. };
  129427. XNodeSet.prototype.nodeset = function() {
  129428. return this;
  129429. };
  129430. XNodeSet.prototype.stringForNode = function(n) {
  129431. if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/) {
  129432. n = n.documentElement;
  129433. }
  129434. if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) {
  129435. return this.stringForNodeRec(n);
  129436. }
  129437. if (n.isNamespaceNode) {
  129438. return n.namespace;
  129439. }
  129440. return n.nodeValue;
  129441. };
  129442. XNodeSet.prototype.stringForNodeRec = function(n) {
  129443. var s = "";
  129444. for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) {
  129445. if (n2.nodeType == 3 /*Node.TEXT_NODE*/) {
  129446. s += n2.nodeValue;
  129447. } else if (n2.nodeType == 1 /*Node.ELEMENT_NODE*/) {
  129448. s += this.stringForNodeRec(n2);
  129449. }
  129450. }
  129451. return s;
  129452. };
  129453. XNodeSet.prototype.first = function() {
  129454. var p = this.tree;
  129455. if (p == null) {
  129456. return null;
  129457. }
  129458. while (p.left != null) {
  129459. p = p.left;
  129460. }
  129461. return p.node;
  129462. };
  129463. XNodeSet.prototype.add = function(n) {
  129464. var added;
  129465. if (this.tree == null) {
  129466. this.tree = new AVLTree(n);
  129467. added = true;
  129468. } else {
  129469. added = this.tree.add(n);
  129470. }
  129471. if (added) {
  129472. this.size++;
  129473. }
  129474. };
  129475. XNodeSet.prototype.addArray = function(ns) {
  129476. for (var i = 0; i < ns.length; i++) {
  129477. this.add(ns[i]);
  129478. }
  129479. };
  129480. XNodeSet.prototype.toArray = function() {
  129481. var a = [];
  129482. this.toArrayRec(this.tree, a);
  129483. return a;
  129484. };
  129485. XNodeSet.prototype.toArrayRec = function(t, a) {
  129486. if (t != null) {
  129487. this.toArrayRec(t.left, a);
  129488. a.push(t.node);
  129489. this.toArrayRec(t.right, a);
  129490. }
  129491. };
  129492. XNodeSet.prototype.compareWithString = function(r, o) {
  129493. var a = this.toArray();
  129494. for (var i = 0; i < a.length; i++) {
  129495. var n = a[i];
  129496. var l = new XString(this.stringForNode(n));
  129497. var res = o(l, r);
  129498. if (res.booleanValue()) {
  129499. return res;
  129500. }
  129501. }
  129502. return new XBoolean(false);
  129503. };
  129504. XNodeSet.prototype.compareWithNumber = function(r, o) {
  129505. var a = this.toArray();
  129506. for (var i = 0; i < a.length; i++) {
  129507. var n = a[i];
  129508. var l = new XNumber(this.stringForNode(n));
  129509. var res = o(l, r);
  129510. if (res.booleanValue()) {
  129511. return res;
  129512. }
  129513. }
  129514. return new XBoolean(false);
  129515. };
  129516. XNodeSet.prototype.compareWithBoolean = function(r, o) {
  129517. return o(this.bool(), r);
  129518. };
  129519. XNodeSet.prototype.compareWithNodeSet = function(r, o) {
  129520. var a = this.toArray();
  129521. for (var i = 0; i < a.length; i++) {
  129522. var n = a[i];
  129523. var l = new XString(this.stringForNode(n));
  129524. var b = r.toArray();
  129525. for (var j = 0; j < b.length; j++) {
  129526. var n2 = b[j];
  129527. var r = new XString(this.stringForNode(n2));
  129528. var res = o(l, r);
  129529. if (res.booleanValue()) {
  129530. return res;
  129531. }
  129532. }
  129533. }
  129534. return new XBoolean(false);
  129535. };
  129536. XNodeSet.prototype.equals = function(r) {
  129537. if (Utilities.instance_of(r, XString)) {
  129538. return this.compareWithString(r, Operators.equals);
  129539. }
  129540. if (Utilities.instance_of(r, XNumber)) {
  129541. return this.compareWithNumber(r, Operators.equals);
  129542. }
  129543. if (Utilities.instance_of(r, XBoolean)) {
  129544. return this.compareWithBoolean(r, Operators.equals);
  129545. }
  129546. return this.compareWithNodeSet(r, Operators.equals);
  129547. };
  129548. XNodeSet.prototype.notequal = function(r) {
  129549. if (Utilities.instance_of(r, XString)) {
  129550. return this.compareWithString(r, Operators.notequal);
  129551. }
  129552. if (Utilities.instance_of(r, XNumber)) {
  129553. return this.compareWithNumber(r, Operators.notequal);
  129554. }
  129555. if (Utilities.instance_of(r, XBoolean)) {
  129556. return this.compareWithBoolean(r, Operators.notequal);
  129557. }
  129558. return this.compareWithNodeSet(r, Operators.notequal);
  129559. };
  129560. XNodeSet.prototype.lessthan = function(r) {
  129561. if (Utilities.instance_of(r, XString)) {
  129562. return this.compareWithNumber(r.number(), Operators.lessthan);
  129563. }
  129564. if (Utilities.instance_of(r, XNumber)) {
  129565. return this.compareWithNumber(r, Operators.lessthan);
  129566. }
  129567. if (Utilities.instance_of(r, XBoolean)) {
  129568. return this.compareWithBoolean(r, Operators.lessthan);
  129569. }
  129570. return this.compareWithNodeSet(r, Operators.lessthan);
  129571. };
  129572. XNodeSet.prototype.greaterthan = function(r) {
  129573. if (Utilities.instance_of(r, XString)) {
  129574. return this.compareWithNumber(r.number(), Operators.greaterthan);
  129575. }
  129576. if (Utilities.instance_of(r, XNumber)) {
  129577. return this.compareWithNumber(r, Operators.greaterthan);
  129578. }
  129579. if (Utilities.instance_of(r, XBoolean)) {
  129580. return this.compareWithBoolean(r, Operators.greaterthan);
  129581. }
  129582. return this.compareWithNodeSet(r, Operators.greaterthan);
  129583. };
  129584. XNodeSet.prototype.lessthanorequal = function(r) {
  129585. if (Utilities.instance_of(r, XString)) {
  129586. return this.compareWithNumber(r.number(), Operators.lessthanorequal);
  129587. }
  129588. if (Utilities.instance_of(r, XNumber)) {
  129589. return this.compareWithNumber(r, Operators.lessthanorequal);
  129590. }
  129591. if (Utilities.instance_of(r, XBoolean)) {
  129592. return this.compareWithBoolean(r, Operators.lessthanorequal);
  129593. }
  129594. return this.compareWithNodeSet(r, Operators.lessthanorequal);
  129595. };
  129596. XNodeSet.prototype.greaterthanorequal = function(r) {
  129597. if (Utilities.instance_of(r, XString)) {
  129598. return this.compareWithNumber(r.number(), Operators.greaterthanorequal);
  129599. }
  129600. if (Utilities.instance_of(r, XNumber)) {
  129601. return this.compareWithNumber(r, Operators.greaterthanorequal);
  129602. }
  129603. if (Utilities.instance_of(r, XBoolean)) {
  129604. return this.compareWithBoolean(r, Operators.greaterthanorequal);
  129605. }
  129606. return this.compareWithNodeSet(r, Operators.greaterthanorequal);
  129607. };
  129608. XNodeSet.prototype.union = function(r) {
  129609. var ns = new XNodeSet();
  129610. ns.tree = this.tree;
  129611. ns.size = this.size;
  129612. ns.addArray(r.toArray());
  129613. return ns;
  129614. };
  129615. // XPathNamespace ////////////////////////////////////////////////////////////
  129616. XPathNamespace.prototype = new Object();
  129617. XPathNamespace.prototype.constructor = XPathNamespace;
  129618. XPathNamespace.superclass = Object.prototype;
  129619. function XPathNamespace(pre, ns, p) {
  129620. this.isXPathNamespace = true;
  129621. this.ownerDocument = p.ownerDocument;
  129622. this.nodeName = "#namespace";
  129623. this.prefix = pre;
  129624. this.localName = pre;
  129625. this.namespaceURI = ns;
  129626. this.nodeValue = ns;
  129627. this.ownerElement = p;
  129628. this.nodeType = XPathNamespace.XPATH_NAMESPACE_NODE;
  129629. }
  129630. XPathNamespace.prototype.toString = function() {
  129631. return "{ \"" + this.prefix + "\", \"" + this.namespaceURI + "\" }";
  129632. };
  129633. // Operators /////////////////////////////////////////////////////////////////
  129634. var Operators = new Object();
  129635. Operators.equals = function(l, r) {
  129636. return l.equals(r);
  129637. };
  129638. Operators.notequal = function(l, r) {
  129639. return l.notequal(r);
  129640. };
  129641. Operators.lessthan = function(l, r) {
  129642. return l.lessthan(r);
  129643. };
  129644. Operators.greaterthan = function(l, r) {
  129645. return l.greaterthan(r);
  129646. };
  129647. Operators.lessthanorequal = function(l, r) {
  129648. return l.lessthanorequal(r);
  129649. };
  129650. Operators.greaterthanorequal = function(l, r) {
  129651. return l.greaterthanorequal(r);
  129652. };
  129653. // XPathContext //////////////////////////////////////////////////////////////
  129654. XPathContext.prototype = new Object();
  129655. XPathContext.prototype.constructor = XPathContext;
  129656. XPathContext.superclass = Object.prototype;
  129657. function XPathContext(vr, nr, fr) {
  129658. this.variableResolver = vr != null ? vr : new VariableResolver();
  129659. this.namespaceResolver = nr != null ? nr : new NamespaceResolver();
  129660. this.functionResolver = fr != null ? fr : new FunctionResolver();
  129661. }
  129662. // VariableResolver //////////////////////////////////////////////////////////
  129663. VariableResolver.prototype = new Object();
  129664. VariableResolver.prototype.constructor = VariableResolver;
  129665. VariableResolver.superclass = Object.prototype;
  129666. function VariableResolver() {
  129667. }
  129668. VariableResolver.prototype.getVariable = function(vn, c) {
  129669. var parts = Utilities.splitQName(vn);
  129670. if (parts[0] != null) {
  129671. parts[0] = c.namespaceResolver.getNamespace(parts[0], c.expressionContextNode);
  129672. if (parts[0] == null) {
  129673. throw new Error("Cannot resolve QName " + fn);
  129674. }
  129675. }
  129676. return this.getVariableWithName(parts[0], parts[1], c.expressionContextNode);
  129677. };
  129678. VariableResolver.prototype.getVariableWithName = function(ns, ln, c) {
  129679. return null;
  129680. };
  129681. // FunctionResolver //////////////////////////////////////////////////////////
  129682. FunctionResolver.prototype = new Object();
  129683. FunctionResolver.prototype.constructor = FunctionResolver;
  129684. FunctionResolver.superclass = Object.prototype;
  129685. function FunctionResolver(thisArg) {
  129686. this.thisArg = thisArg != null ? thisArg : Functions;
  129687. this.functions = new Object();
  129688. this.addStandardFunctions();
  129689. }
  129690. FunctionResolver.prototype.addStandardFunctions = function() {
  129691. this.functions["{}last"] = Functions.last;
  129692. this.functions["{}position"] = Functions.position;
  129693. this.functions["{}count"] = Functions.count;
  129694. this.functions["{}id"] = Functions.id;
  129695. this.functions["{}local-name"] = Functions.localName;
  129696. this.functions["{}namespace-uri"] = Functions.namespaceURI;
  129697. this.functions["{}name"] = Functions.name;
  129698. this.functions["{}string"] = Functions.string;
  129699. this.functions["{}concat"] = Functions.concat;
  129700. this.functions["{}starts-with"] = Functions.startsWith;
  129701. this.functions["{}contains"] = Functions.contains;
  129702. this.functions["{}substring-before"] = Functions.substringBefore;
  129703. this.functions["{}substring-after"] = Functions.substringAfter;
  129704. this.functions["{}substring"] = Functions.substring;
  129705. this.functions["{}string-length"] = Functions.stringLength;
  129706. this.functions["{}normalize-space"] = Functions.normalizeSpace;
  129707. this.functions["{}translate"] = Functions.translate;
  129708. this.functions["{}boolean"] = Functions.boolean_;
  129709. this.functions["{}not"] = Functions.not;
  129710. this.functions["{}true"] = Functions.true_;
  129711. this.functions["{}false"] = Functions.false_;
  129712. this.functions["{}lang"] = Functions.lang;
  129713. this.functions["{}number"] = Functions.number;
  129714. this.functions["{}sum"] = Functions.sum;
  129715. this.functions["{}floor"] = Functions.floor;
  129716. this.functions["{}ceiling"] = Functions.ceiling;
  129717. this.functions["{}round"] = Functions.round;
  129718. };
  129719. FunctionResolver.prototype.addFunction = function(ns, ln, f) {
  129720. this.functions["{" + ns + "}" + ln] = f;
  129721. };
  129722. FunctionResolver.prototype.getFunction = function(fn, c) {
  129723. var parts = Utilities.resolveQName(fn, c.namespaceResolver, c.contextNode, false);
  129724. if (parts[0] == null) {
  129725. throw new Error("Cannot resolve QName " + fn);
  129726. }
  129727. return this.getFunctionWithName(parts[0], parts[1], c.contextNode);
  129728. };
  129729. FunctionResolver.prototype.getFunctionWithName = function(ns, ln, c) {
  129730. return this.functions["{" + ns + "}" + ln];
  129731. };
  129732. // NamespaceResolver /////////////////////////////////////////////////////////
  129733. NamespaceResolver.prototype = new Object();
  129734. NamespaceResolver.prototype.constructor = NamespaceResolver;
  129735. NamespaceResolver.superclass = Object.prototype;
  129736. function NamespaceResolver() {
  129737. }
  129738. NamespaceResolver.prototype.getNamespace = function(prefix, n) {
  129739. if (prefix == "xml") {
  129740. return XPath.XML_NAMESPACE_URI;
  129741. } else if (prefix == "xmlns") {
  129742. return XPath.XMLNS_NAMESPACE_URI;
  129743. }
  129744. if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/) {
  129745. n = n.documentElement;
  129746. } else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
  129747. n = PathExpr.prototype.getOwnerElement(n);
  129748. } else if (n.nodeType != 1 /*Node.ELEMENT_NODE*/) {
  129749. n = n.parentNode;
  129750. }
  129751. while (n != null && n.nodeType == 1 /*Node.ELEMENT_NODE*/) {
  129752. var nnm = n.attributes;
  129753. for (var i = 0; i < nnm.length; i++) {
  129754. var a = nnm.item(i);
  129755. var aname = a.nodeName;
  129756. if (aname == "xmlns" && prefix == ""
  129757. || aname == "xmlns:" + prefix) {
  129758. return String(a.nodeValue);
  129759. }
  129760. }
  129761. n = n.parentNode;
  129762. }
  129763. return null;
  129764. };
  129765. // Functions /////////////////////////////////////////////////////////////////
  129766. var Functions = new Object();
  129767. Functions.last = function() {
  129768. var c = arguments[0];
  129769. if (arguments.length != 1) {
  129770. throw new Error("Function last expects ()");
  129771. }
  129772. return new XNumber(c.contextSize);
  129773. };
  129774. Functions.position = function() {
  129775. var c = arguments[0];
  129776. if (arguments.length != 1) {
  129777. throw new Error("Function position expects ()");
  129778. }
  129779. return new XNumber(c.contextPosition);
  129780. };
  129781. Functions.count = function() {
  129782. var c = arguments[0];
  129783. var ns;
  129784. if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) {
  129785. throw new Error("Function count expects (node-set)");
  129786. }
  129787. return new XNumber(ns.size);
  129788. };
  129789. Functions.id = function() {
  129790. var c = arguments[0];
  129791. var id;
  129792. if (arguments.length != 2) {
  129793. throw new Error("Function id expects (object)");
  129794. }
  129795. id = arguments[1].evaluate(c);
  129796. if (Utilities.instance_of(id, XNodeSet)) {
  129797. id = id.toArray().join(" ");
  129798. } else {
  129799. id = id.stringValue();
  129800. }
  129801. var ids = id.split(/[\x0d\x0a\x09\x20]+/);
  129802. var count = 0;
  129803. var ns = new XNodeSet();
  129804. var doc = c.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/
  129805. ? c.contextNode
  129806. : c.contextNode.ownerDocument;
  129807. for (var i = 0; i < ids.length; i++) {
  129808. var n;
  129809. if (doc.getElementById) {
  129810. n = doc.getElementById(ids[i]);
  129811. } else {
  129812. n = Utilities.getElementById(doc, ids[i]);
  129813. }
  129814. if (n != null) {
  129815. ns.add(n);
  129816. count++;
  129817. }
  129818. }
  129819. return ns;
  129820. };
  129821. Functions.localName = function() {
  129822. var c = arguments[0];
  129823. var n;
  129824. if (arguments.length == 1) {
  129825. n = c.contextNode;
  129826. } else if (arguments.length == 2) {
  129827. n = arguments[1].evaluate(c).first();
  129828. } else {
  129829. throw new Error("Function local-name expects (node-set?)");
  129830. }
  129831. if (n == null) {
  129832. return new XString("");
  129833. }
  129834. return new XString(n.localName ? n.localName : n.baseName);
  129835. };
  129836. Functions.namespaceURI = function() {
  129837. var c = arguments[0];
  129838. var n;
  129839. if (arguments.length == 1) {
  129840. n = c.contextNode;
  129841. } else if (arguments.length == 2) {
  129842. n = arguments[1].evaluate(c).first();
  129843. } else {
  129844. throw new Error("Function namespace-uri expects (node-set?)");
  129845. }
  129846. if (n == null) {
  129847. return new XString("");
  129848. }
  129849. return new XString(n.namespaceURI);
  129850. };
  129851. Functions.name = function() {
  129852. var c = arguments[0];
  129853. var n;
  129854. if (arguments.length == 1) {
  129855. n = c.contextNode;
  129856. } else if (arguments.length == 2) {
  129857. n = arguments[1].evaluate(c).first();
  129858. } else {
  129859. throw new Error("Function name expects (node-set?)");
  129860. }
  129861. if (n == null) {
  129862. return new XString("");
  129863. }
  129864. if (n.nodeType == 1 /*Node.ELEMENT_NODE*/ || n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
  129865. return new XString(n.nodeName);
  129866. } else if (n.localName == null) {
  129867. return new XString("");
  129868. } else {
  129869. return new XString(n.localName);
  129870. }
  129871. };
  129872. Functions.string = function() {
  129873. var c = arguments[0];
  129874. if (arguments.length == 1) {
  129875. return XNodeSet.prototype.stringForNode(c.contextNode);
  129876. } else if (arguments.length == 2) {
  129877. return arguments[1].evaluate(c).string();
  129878. }
  129879. throw new Error("Function string expects (object?)");
  129880. };
  129881. Functions.concat = function() {
  129882. var c = arguments[0];
  129883. if (arguments.length < 3) {
  129884. throw new Error("Function concat expects (string, string, string*)");
  129885. }
  129886. var s = "";
  129887. for (var i = 1; i < arguments.length; i++) {
  129888. s += arguments[i].evaluate(c).stringValue();
  129889. }
  129890. return new XString(s);
  129891. };
  129892. Functions.startsWith = function() {
  129893. var c = arguments[0];
  129894. if (arguments.length != 3) {
  129895. throw new Error("Function startsWith expects (string, string)");
  129896. }
  129897. var s1 = arguments[1].evaluate(c).stringValue();
  129898. var s2 = arguments[2].evaluate(c).stringValue();
  129899. return new XBoolean(s1.substring(0, s2.length) == s2);
  129900. };
  129901. Functions.contains = function() {
  129902. var c = arguments[0];
  129903. if (arguments.length != 3) {
  129904. throw new Error("Function contains expects (string, string)");
  129905. }
  129906. var s1 = arguments[1].evaluate(c).stringValue();
  129907. var s2 = arguments[2].evaluate(c).stringValue();
  129908. return new XBoolean(s1.indexOf(s2) != -1);
  129909. };
  129910. Functions.substringBefore = function() {
  129911. var c = arguments[0];
  129912. if (arguments.length != 3) {
  129913. throw new Error("Function substring-before expects (string, string)");
  129914. }
  129915. var s1 = arguments[1].evaluate(c).stringValue();
  129916. var s2 = arguments[2].evaluate(c).stringValue();
  129917. return new XString(s1.substring(0, s1.indexOf(s2)));
  129918. };
  129919. Functions.substringAfter = function() {
  129920. var c = arguments[0];
  129921. if (arguments.length != 3) {
  129922. throw new Error("Function substring-after expects (string, string)");
  129923. }
  129924. var s1 = arguments[1].evaluate(c).stringValue();
  129925. var s2 = arguments[2].evaluate(c).stringValue();
  129926. if (s2.length == 0) {
  129927. return new XString(s1);
  129928. }
  129929. var i = s1.indexOf(s2);
  129930. if (i == -1) {
  129931. return new XString("");
  129932. }
  129933. return new XString(s1.substring(s1.indexOf(s2) + 1));
  129934. };
  129935. Functions.substring = function() {
  129936. var c = arguments[0];
  129937. if (!(arguments.length == 3 || arguments.length == 4)) {
  129938. throw new Error("Function substring expects (string, number, number?)");
  129939. }
  129940. var s = arguments[1].evaluate(c).stringValue();
  129941. var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1;
  129942. var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : undefined;
  129943. return new XString(s.substring(n1, n2));
  129944. };
  129945. Functions.stringLength = function() {
  129946. var c = arguments[0];
  129947. var s;
  129948. if (arguments.length == 1) {
  129949. s = XNodeSet.prototype.stringForNode(c.contextNode);
  129950. } else if (arguments.length == 2) {
  129951. s = arguments[1].evaluate(c).stringValue();
  129952. } else {
  129953. throw new Error("Function string-length expects (string?)");
  129954. }
  129955. return new XNumber(s.length);
  129956. };
  129957. Functions.normalizeSpace = function() {
  129958. var c = arguments[0];
  129959. var s;
  129960. if (arguments.length == 1) {
  129961. s = XNodeSet.prototype.stringForNode(c.contextNode);
  129962. } else if (arguments.length == 2) {
  129963. s = arguments[1].evaluate(c).stringValue();
  129964. } else {
  129965. throw new Error("Function normalize-space expects (string?)");
  129966. }
  129967. var i = 0;
  129968. var j = s.length - 1;
  129969. while (Utilities.isSpace(s.charCodeAt(j))) {
  129970. j--;
  129971. }
  129972. var t = "";
  129973. while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {
  129974. i++;
  129975. }
  129976. while (i <= j) {
  129977. if (Utilities.isSpace(s.charCodeAt(i))) {
  129978. t += " ";
  129979. while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {
  129980. i++;
  129981. }
  129982. } else {
  129983. t += s.charAt(i);
  129984. i++;
  129985. }
  129986. }
  129987. return new XString(t);
  129988. };
  129989. Functions.translate = function() {
  129990. var c = arguments[0];
  129991. if (arguments.length != 4) {
  129992. throw new Error("Function translate expects (string, string, string)");
  129993. }
  129994. var s1 = arguments[1].evaluate(c).stringValue();
  129995. var s2 = arguments[2].evaluate(c).stringValue();
  129996. var s3 = arguments[3].evaluate(c).stringValue();
  129997. var map = [];
  129998. for (var i = 0; i < s2.length; i++) {
  129999. var j = s2.charCodeAt(i);
  130000. if (map[j] == undefined) {
  130001. var k = i > s3.length ? "" : s3.charAt(i);
  130002. map[j] = k;
  130003. }
  130004. }
  130005. var t = "";
  130006. for (var i = 0; i < s1.length; i++) {
  130007. var c = s1.charCodeAt(i);
  130008. var r = map[c];
  130009. if (r == undefined) {
  130010. t += s1.charAt(i);
  130011. } else {
  130012. t += r;
  130013. }
  130014. }
  130015. return new XString(t);
  130016. };
  130017. Functions.boolean_ = function() {
  130018. var c = arguments[0];
  130019. if (arguments.length != 2) {
  130020. throw new Error("Function boolean expects (object)");
  130021. }
  130022. return arguments[1].evaluate(c).bool();
  130023. };
  130024. Functions.not = function() {
  130025. var c = arguments[0];
  130026. if (arguments.length != 2) {
  130027. throw new Error("Function not expects (object)");
  130028. }
  130029. return arguments[1].evaluate(c).bool().not();
  130030. };
  130031. Functions.true_ = function() {
  130032. if (arguments.length != 1) {
  130033. throw new Error("Function true expects ()");
  130034. }
  130035. return new XBoolean(true);
  130036. };
  130037. Functions.false_ = function() {
  130038. if (arguments.length != 1) {
  130039. throw new Error("Function false expects ()");
  130040. }
  130041. return new XBoolean(false);
  130042. };
  130043. Functions.lang = function() {
  130044. var c = arguments[0];
  130045. if (arguments.length != 2) {
  130046. throw new Error("Function lang expects (string)");
  130047. }
  130048. var lang;
  130049. for (var n = c.contextNode; n != null && n.nodeType != 9 /*Node.DOCUMENT_NODE*/; n = n.parentNode) {
  130050. var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang");
  130051. if (a != null) {
  130052. lang = String(a);
  130053. break;
  130054. }
  130055. }
  130056. if (lang == null) {
  130057. return new XBoolean(false);
  130058. }
  130059. var s = arguments[1].evaluate(c).stringValue();
  130060. return new XBoolean(lang.substring(0, s.length) == s
  130061. && (lang.length == s.length || lang.charAt(s.length) == '-'));
  130062. };
  130063. Functions.number = function() {
  130064. var c = arguments[0];
  130065. if (!(arguments.length == 1 || arguments.length == 2)) {
  130066. throw new Error("Function number expects (object?)");
  130067. }
  130068. if (arguments.length == 1) {
  130069. return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode));
  130070. }
  130071. return arguments[1].evaluate(c).number();
  130072. };
  130073. Functions.sum = function() {
  130074. var c = arguments[0];
  130075. var ns;
  130076. if (arguments.length != 2 || !Utilities.instance_of((ns = arguments[1].evaluate(c)), XNodeSet)) {
  130077. throw new Error("Function sum expects (node-set)");
  130078. }
  130079. ns = ns.toArray();
  130080. var n = 0;
  130081. for (var i = 0; i < ns.length; i++) {
  130082. n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue();
  130083. }
  130084. return new XNumber(n);
  130085. };
  130086. Functions.floor = function() {
  130087. var c = arguments[0];
  130088. if (arguments.length != 2) {
  130089. throw new Error("Function floor expects (number)");
  130090. }
  130091. return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue()));
  130092. };
  130093. Functions.ceiling = function() {
  130094. var c = arguments[0];
  130095. if (arguments.length != 2) {
  130096. throw new Error("Function ceiling expects (number)");
  130097. }
  130098. return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue()));
  130099. };
  130100. Functions.round = function() {
  130101. var c = arguments[0];
  130102. if (arguments.length != 2) {
  130103. throw new Error("Function round expects (number)");
  130104. }
  130105. return new XNumber(Math.round(arguments[1].evaluate(c).numberValue()));
  130106. };
  130107. // Utilities /////////////////////////////////////////////////////////////////
  130108. var Utilities = new Object();
  130109. Utilities.splitQName = function(qn) {
  130110. var i = qn.indexOf(":");
  130111. if (i == -1) {
  130112. return [ null, qn ];
  130113. }
  130114. return [ qn.substring(0, i), qn.substring(i + 1) ];
  130115. };
  130116. Utilities.resolveQName = function(qn, nr, n, useDefault) {
  130117. var parts = Utilities.splitQName(qn);
  130118. if (parts[0] != null) {
  130119. parts[0] = nr.getNamespace(parts[0], n);
  130120. } else {
  130121. if (useDefault) {
  130122. parts[0] = nr.getNamespace("", n);
  130123. if (parts[0] == null) {
  130124. parts[0] = "";
  130125. }
  130126. } else {
  130127. parts[0] = "";
  130128. }
  130129. }
  130130. return parts;
  130131. };
  130132. Utilities.isSpace = function(c) {
  130133. return c == 0x9 || c == 0xd || c == 0xa || c == 0x20;
  130134. };
  130135. Utilities.isLetter = function(c) {
  130136. return c >= 0x0041 && c <= 0x005A ||
  130137. c >= 0x0061 && c <= 0x007A ||
  130138. c >= 0x00C0 && c <= 0x00D6 ||
  130139. c >= 0x00D8 && c <= 0x00F6 ||
  130140. c >= 0x00F8 && c <= 0x00FF ||
  130141. c >= 0x0100 && c <= 0x0131 ||
  130142. c >= 0x0134 && c <= 0x013E ||
  130143. c >= 0x0141 && c <= 0x0148 ||
  130144. c >= 0x014A && c <= 0x017E ||
  130145. c >= 0x0180 && c <= 0x01C3 ||
  130146. c >= 0x01CD && c <= 0x01F0 ||
  130147. c >= 0x01F4 && c <= 0x01F5 ||
  130148. c >= 0x01FA && c <= 0x0217 ||
  130149. c >= 0x0250 && c <= 0x02A8 ||
  130150. c >= 0x02BB && c <= 0x02C1 ||
  130151. c == 0x0386 ||
  130152. c >= 0x0388 && c <= 0x038A ||
  130153. c == 0x038C ||
  130154. c >= 0x038E && c <= 0x03A1 ||
  130155. c >= 0x03A3 && c <= 0x03CE ||
  130156. c >= 0x03D0 && c <= 0x03D6 ||
  130157. c == 0x03DA ||
  130158. c == 0x03DC ||
  130159. c == 0x03DE ||
  130160. c == 0x03E0 ||
  130161. c >= 0x03E2 && c <= 0x03F3 ||
  130162. c >= 0x0401 && c <= 0x040C ||
  130163. c >= 0x040E && c <= 0x044F ||
  130164. c >= 0x0451 && c <= 0x045C ||
  130165. c >= 0x045E && c <= 0x0481 ||
  130166. c >= 0x0490 && c <= 0x04C4 ||
  130167. c >= 0x04C7 && c <= 0x04C8 ||
  130168. c >= 0x04CB && c <= 0x04CC ||
  130169. c >= 0x04D0 && c <= 0x04EB ||
  130170. c >= 0x04EE && c <= 0x04F5 ||
  130171. c >= 0x04F8 && c <= 0x04F9 ||
  130172. c >= 0x0531 && c <= 0x0556 ||
  130173. c == 0x0559 ||
  130174. c >= 0x0561 && c <= 0x0586 ||
  130175. c >= 0x05D0 && c <= 0x05EA ||
  130176. c >= 0x05F0 && c <= 0x05F2 ||
  130177. c >= 0x0621 && c <= 0x063A ||
  130178. c >= 0x0641 && c <= 0x064A ||
  130179. c >= 0x0671 && c <= 0x06B7 ||
  130180. c >= 0x06BA && c <= 0x06BE ||
  130181. c >= 0x06C0 && c <= 0x06CE ||
  130182. c >= 0x06D0 && c <= 0x06D3 ||
  130183. c == 0x06D5 ||
  130184. c >= 0x06E5 && c <= 0x06E6 ||
  130185. c >= 0x0905 && c <= 0x0939 ||
  130186. c == 0x093D ||
  130187. c >= 0x0958 && c <= 0x0961 ||
  130188. c >= 0x0985 && c <= 0x098C ||
  130189. c >= 0x098F && c <= 0x0990 ||
  130190. c >= 0x0993 && c <= 0x09A8 ||
  130191. c >= 0x09AA && c <= 0x09B0 ||
  130192. c == 0x09B2 ||
  130193. c >= 0x09B6 && c <= 0x09B9 ||
  130194. c >= 0x09DC && c <= 0x09DD ||
  130195. c >= 0x09DF && c <= 0x09E1 ||
  130196. c >= 0x09F0 && c <= 0x09F1 ||
  130197. c >= 0x0A05 && c <= 0x0A0A ||
  130198. c >= 0x0A0F && c <= 0x0A10 ||
  130199. c >= 0x0A13 && c <= 0x0A28 ||
  130200. c >= 0x0A2A && c <= 0x0A30 ||
  130201. c >= 0x0A32 && c <= 0x0A33 ||
  130202. c >= 0x0A35 && c <= 0x0A36 ||
  130203. c >= 0x0A38 && c <= 0x0A39 ||
  130204. c >= 0x0A59 && c <= 0x0A5C ||
  130205. c == 0x0A5E ||
  130206. c >= 0x0A72 && c <= 0x0A74 ||
  130207. c >= 0x0A85 && c <= 0x0A8B ||
  130208. c == 0x0A8D ||
  130209. c >= 0x0A8F && c <= 0x0A91 ||
  130210. c >= 0x0A93 && c <= 0x0AA8 ||
  130211. c >= 0x0AAA && c <= 0x0AB0 ||
  130212. c >= 0x0AB2 && c <= 0x0AB3 ||
  130213. c >= 0x0AB5 && c <= 0x0AB9 ||
  130214. c == 0x0ABD ||
  130215. c == 0x0AE0 ||
  130216. c >= 0x0B05 && c <= 0x0B0C ||
  130217. c >= 0x0B0F && c <= 0x0B10 ||
  130218. c >= 0x0B13 && c <= 0x0B28 ||
  130219. c >= 0x0B2A && c <= 0x0B30 ||
  130220. c >= 0x0B32 && c <= 0x0B33 ||
  130221. c >= 0x0B36 && c <= 0x0B39 ||
  130222. c == 0x0B3D ||
  130223. c >= 0x0B5C && c <= 0x0B5D ||
  130224. c >= 0x0B5F && c <= 0x0B61 ||
  130225. c >= 0x0B85 && c <= 0x0B8A ||
  130226. c >= 0x0B8E && c <= 0x0B90 ||
  130227. c >= 0x0B92 && c <= 0x0B95 ||
  130228. c >= 0x0B99 && c <= 0x0B9A ||
  130229. c == 0x0B9C ||
  130230. c >= 0x0B9E && c <= 0x0B9F ||
  130231. c >= 0x0BA3 && c <= 0x0BA4 ||
  130232. c >= 0x0BA8 && c <= 0x0BAA ||
  130233. c >= 0x0BAE && c <= 0x0BB5 ||
  130234. c >= 0x0BB7 && c <= 0x0BB9 ||
  130235. c >= 0x0C05 && c <= 0x0C0C ||
  130236. c >= 0x0C0E && c <= 0x0C10 ||
  130237. c >= 0x0C12 && c <= 0x0C28 ||
  130238. c >= 0x0C2A && c <= 0x0C33 ||
  130239. c >= 0x0C35 && c <= 0x0C39 ||
  130240. c >= 0x0C60 && c <= 0x0C61 ||
  130241. c >= 0x0C85 && c <= 0x0C8C ||
  130242. c >= 0x0C8E && c <= 0x0C90 ||
  130243. c >= 0x0C92 && c <= 0x0CA8 ||
  130244. c >= 0x0CAA && c <= 0x0CB3 ||
  130245. c >= 0x0CB5 && c <= 0x0CB9 ||
  130246. c == 0x0CDE ||
  130247. c >= 0x0CE0 && c <= 0x0CE1 ||
  130248. c >= 0x0D05 && c <= 0x0D0C ||
  130249. c >= 0x0D0E && c <= 0x0D10 ||
  130250. c >= 0x0D12 && c <= 0x0D28 ||
  130251. c >= 0x0D2A && c <= 0x0D39 ||
  130252. c >= 0x0D60 && c <= 0x0D61 ||
  130253. c >= 0x0E01 && c <= 0x0E2E ||
  130254. c == 0x0E30 ||
  130255. c >= 0x0E32 && c <= 0x0E33 ||
  130256. c >= 0x0E40 && c <= 0x0E45 ||
  130257. c >= 0x0E81 && c <= 0x0E82 ||
  130258. c == 0x0E84 ||
  130259. c >= 0x0E87 && c <= 0x0E88 ||
  130260. c == 0x0E8A ||
  130261. c == 0x0E8D ||
  130262. c >= 0x0E94 && c <= 0x0E97 ||
  130263. c >= 0x0E99 && c <= 0x0E9F ||
  130264. c >= 0x0EA1 && c <= 0x0EA3 ||
  130265. c == 0x0EA5 ||
  130266. c == 0x0EA7 ||
  130267. c >= 0x0EAA && c <= 0x0EAB ||
  130268. c >= 0x0EAD && c <= 0x0EAE ||
  130269. c == 0x0EB0 ||
  130270. c >= 0x0EB2 && c <= 0x0EB3 ||
  130271. c == 0x0EBD ||
  130272. c >= 0x0EC0 && c <= 0x0EC4 ||
  130273. c >= 0x0F40 && c <= 0x0F47 ||
  130274. c >= 0x0F49 && c <= 0x0F69 ||
  130275. c >= 0x10A0 && c <= 0x10C5 ||
  130276. c >= 0x10D0 && c <= 0x10F6 ||
  130277. c == 0x1100 ||
  130278. c >= 0x1102 && c <= 0x1103 ||
  130279. c >= 0x1105 && c <= 0x1107 ||
  130280. c == 0x1109 ||
  130281. c >= 0x110B && c <= 0x110C ||
  130282. c >= 0x110E && c <= 0x1112 ||
  130283. c == 0x113C ||
  130284. c == 0x113E ||
  130285. c == 0x1140 ||
  130286. c == 0x114C ||
  130287. c == 0x114E ||
  130288. c == 0x1150 ||
  130289. c >= 0x1154 && c <= 0x1155 ||
  130290. c == 0x1159 ||
  130291. c >= 0x115F && c <= 0x1161 ||
  130292. c == 0x1163 ||
  130293. c == 0x1165 ||
  130294. c == 0x1167 ||
  130295. c == 0x1169 ||
  130296. c >= 0x116D && c <= 0x116E ||
  130297. c >= 0x1172 && c <= 0x1173 ||
  130298. c == 0x1175 ||
  130299. c == 0x119E ||
  130300. c == 0x11A8 ||
  130301. c == 0x11AB ||
  130302. c >= 0x11AE && c <= 0x11AF ||
  130303. c >= 0x11B7 && c <= 0x11B8 ||
  130304. c == 0x11BA ||
  130305. c >= 0x11BC && c <= 0x11C2 ||
  130306. c == 0x11EB ||
  130307. c == 0x11F0 ||
  130308. c == 0x11F9 ||
  130309. c >= 0x1E00 && c <= 0x1E9B ||
  130310. c >= 0x1EA0 && c <= 0x1EF9 ||
  130311. c >= 0x1F00 && c <= 0x1F15 ||
  130312. c >= 0x1F18 && c <= 0x1F1D ||
  130313. c >= 0x1F20 && c <= 0x1F45 ||
  130314. c >= 0x1F48 && c <= 0x1F4D ||
  130315. c >= 0x1F50 && c <= 0x1F57 ||
  130316. c == 0x1F59 ||
  130317. c == 0x1F5B ||
  130318. c == 0x1F5D ||
  130319. c >= 0x1F5F && c <= 0x1F7D ||
  130320. c >= 0x1F80 && c <= 0x1FB4 ||
  130321. c >= 0x1FB6 && c <= 0x1FBC ||
  130322. c == 0x1FBE ||
  130323. c >= 0x1FC2 && c <= 0x1FC4 ||
  130324. c >= 0x1FC6 && c <= 0x1FCC ||
  130325. c >= 0x1FD0 && c <= 0x1FD3 ||
  130326. c >= 0x1FD6 && c <= 0x1FDB ||
  130327. c >= 0x1FE0 && c <= 0x1FEC ||
  130328. c >= 0x1FF2 && c <= 0x1FF4 ||
  130329. c >= 0x1FF6 && c <= 0x1FFC ||
  130330. c == 0x2126 ||
  130331. c >= 0x212A && c <= 0x212B ||
  130332. c == 0x212E ||
  130333. c >= 0x2180 && c <= 0x2182 ||
  130334. c >= 0x3041 && c <= 0x3094 ||
  130335. c >= 0x30A1 && c <= 0x30FA ||
  130336. c >= 0x3105 && c <= 0x312C ||
  130337. c >= 0xAC00 && c <= 0xD7A3 ||
  130338. c >= 0x4E00 && c <= 0x9FA5 ||
  130339. c == 0x3007 ||
  130340. c >= 0x3021 && c <= 0x3029;
  130341. };
  130342. Utilities.isNCNameChar = function(c) {
  130343. return c >= 0x0030 && c <= 0x0039
  130344. || c >= 0x0660 && c <= 0x0669
  130345. || c >= 0x06F0 && c <= 0x06F9
  130346. || c >= 0x0966 && c <= 0x096F
  130347. || c >= 0x09E6 && c <= 0x09EF
  130348. || c >= 0x0A66 && c <= 0x0A6F
  130349. || c >= 0x0AE6 && c <= 0x0AEF
  130350. || c >= 0x0B66 && c <= 0x0B6F
  130351. || c >= 0x0BE7 && c <= 0x0BEF
  130352. || c >= 0x0C66 && c <= 0x0C6F
  130353. || c >= 0x0CE6 && c <= 0x0CEF
  130354. || c >= 0x0D66 && c <= 0x0D6F
  130355. || c >= 0x0E50 && c <= 0x0E59
  130356. || c >= 0x0ED0 && c <= 0x0ED9
  130357. || c >= 0x0F20 && c <= 0x0F29
  130358. || c == 0x002E
  130359. || c == 0x002D
  130360. || c == 0x005F
  130361. || Utilities.isLetter(c)
  130362. || c >= 0x0300 && c <= 0x0345
  130363. || c >= 0x0360 && c <= 0x0361
  130364. || c >= 0x0483 && c <= 0x0486
  130365. || c >= 0x0591 && c <= 0x05A1
  130366. || c >= 0x05A3 && c <= 0x05B9
  130367. || c >= 0x05BB && c <= 0x05BD
  130368. || c == 0x05BF
  130369. || c >= 0x05C1 && c <= 0x05C2
  130370. || c == 0x05C4
  130371. || c >= 0x064B && c <= 0x0652
  130372. || c == 0x0670
  130373. || c >= 0x06D6 && c <= 0x06DC
  130374. || c >= 0x06DD && c <= 0x06DF
  130375. || c >= 0x06E0 && c <= 0x06E4
  130376. || c >= 0x06E7 && c <= 0x06E8
  130377. || c >= 0x06EA && c <= 0x06ED
  130378. || c >= 0x0901 && c <= 0x0903
  130379. || c == 0x093C
  130380. || c >= 0x093E && c <= 0x094C
  130381. || c == 0x094D
  130382. || c >= 0x0951 && c <= 0x0954
  130383. || c >= 0x0962 && c <= 0x0963
  130384. || c >= 0x0981 && c <= 0x0983
  130385. || c == 0x09BC
  130386. || c == 0x09BE
  130387. || c == 0x09BF
  130388. || c >= 0x09C0 && c <= 0x09C4
  130389. || c >= 0x09C7 && c <= 0x09C8
  130390. || c >= 0x09CB && c <= 0x09CD
  130391. || c == 0x09D7
  130392. || c >= 0x09E2 && c <= 0x09E3
  130393. || c == 0x0A02
  130394. || c == 0x0A3C
  130395. || c == 0x0A3E
  130396. || c == 0x0A3F
  130397. || c >= 0x0A40 && c <= 0x0A42
  130398. || c >= 0x0A47 && c <= 0x0A48
  130399. || c >= 0x0A4B && c <= 0x0A4D
  130400. || c >= 0x0A70 && c <= 0x0A71
  130401. || c >= 0x0A81 && c <= 0x0A83
  130402. || c == 0x0ABC
  130403. || c >= 0x0ABE && c <= 0x0AC5
  130404. || c >= 0x0AC7 && c <= 0x0AC9
  130405. || c >= 0x0ACB && c <= 0x0ACD
  130406. || c >= 0x0B01 && c <= 0x0B03
  130407. || c == 0x0B3C
  130408. || c >= 0x0B3E && c <= 0x0B43
  130409. || c >= 0x0B47 && c <= 0x0B48
  130410. || c >= 0x0B4B && c <= 0x0B4D
  130411. || c >= 0x0B56 && c <= 0x0B57
  130412. || c >= 0x0B82 && c <= 0x0B83
  130413. || c >= 0x0BBE && c <= 0x0BC2
  130414. || c >= 0x0BC6 && c <= 0x0BC8
  130415. || c >= 0x0BCA && c <= 0x0BCD
  130416. || c == 0x0BD7
  130417. || c >= 0x0C01 && c <= 0x0C03
  130418. || c >= 0x0C3E && c <= 0x0C44
  130419. || c >= 0x0C46 && c <= 0x0C48
  130420. || c >= 0x0C4A && c <= 0x0C4D
  130421. || c >= 0x0C55 && c <= 0x0C56
  130422. || c >= 0x0C82 && c <= 0x0C83
  130423. || c >= 0x0CBE && c <= 0x0CC4
  130424. || c >= 0x0CC6 && c <= 0x0CC8
  130425. || c >= 0x0CCA && c <= 0x0CCD
  130426. || c >= 0x0CD5 && c <= 0x0CD6
  130427. || c >= 0x0D02 && c <= 0x0D03
  130428. || c >= 0x0D3E && c <= 0x0D43
  130429. || c >= 0x0D46 && c <= 0x0D48
  130430. || c >= 0x0D4A && c <= 0x0D4D
  130431. || c == 0x0D57
  130432. || c == 0x0E31
  130433. || c >= 0x0E34 && c <= 0x0E3A
  130434. || c >= 0x0E47 && c <= 0x0E4E
  130435. || c == 0x0EB1
  130436. || c >= 0x0EB4 && c <= 0x0EB9
  130437. || c >= 0x0EBB && c <= 0x0EBC
  130438. || c >= 0x0EC8 && c <= 0x0ECD
  130439. || c >= 0x0F18 && c <= 0x0F19
  130440. || c == 0x0F35
  130441. || c == 0x0F37
  130442. || c == 0x0F39
  130443. || c == 0x0F3E
  130444. || c == 0x0F3F
  130445. || c >= 0x0F71 && c <= 0x0F84
  130446. || c >= 0x0F86 && c <= 0x0F8B
  130447. || c >= 0x0F90 && c <= 0x0F95
  130448. || c == 0x0F97
  130449. || c >= 0x0F99 && c <= 0x0FAD
  130450. || c >= 0x0FB1 && c <= 0x0FB7
  130451. || c == 0x0FB9
  130452. || c >= 0x20D0 && c <= 0x20DC
  130453. || c == 0x20E1
  130454. || c >= 0x302A && c <= 0x302F
  130455. || c == 0x3099
  130456. || c == 0x309A
  130457. || c == 0x00B7
  130458. || c == 0x02D0
  130459. || c == 0x02D1
  130460. || c == 0x0387
  130461. || c == 0x0640
  130462. || c == 0x0E46
  130463. || c == 0x0EC6
  130464. || c == 0x3005
  130465. || c >= 0x3031 && c <= 0x3035
  130466. || c >= 0x309D && c <= 0x309E
  130467. || c >= 0x30FC && c <= 0x30FE;
  130468. };
  130469. Utilities.coalesceText = function(n) {
  130470. for (var m = n.firstChild; m != null; m = m.nextSibling) {
  130471. if (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) {
  130472. var s = m.nodeValue;
  130473. var first = m;
  130474. m = m.nextSibling;
  130475. while (m != null && (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/)) {
  130476. s += m.nodeValue;
  130477. var del = m;
  130478. m = m.nextSibling;
  130479. del.parentNode.removeChild(del);
  130480. }
  130481. if (first.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) {
  130482. var p = first.parentNode;
  130483. if (first.nextSibling == null) {
  130484. p.removeChild(first);
  130485. p.appendChild(p.ownerDocument.createTextNode(s));
  130486. } else {
  130487. var next = first.nextSibling;
  130488. p.removeChild(first);
  130489. p.insertBefore(p.ownerDocument.createTextNode(s), next);
  130490. }
  130491. } else {
  130492. first.nodeValue = s;
  130493. }
  130494. if (m == null) {
  130495. break;
  130496. }
  130497. } else if (m.nodeType == 1 /*Node.ELEMENT_NODE*/) {
  130498. Utilities.coalesceText(m);
  130499. }
  130500. }
  130501. };
  130502. Utilities.instance_of = function(o, c) {
  130503. while (o != null) {
  130504. if (o.constructor === c) {
  130505. return true;
  130506. }
  130507. if (o === Object) {
  130508. return false;
  130509. }
  130510. o = o.constructor.superclass;
  130511. }
  130512. return false;
  130513. };
  130514. Utilities.getElementById = function(n, id) {
  130515. // Note that this does not check the DTD to check for actual
  130516. // attributes of type ID, so this may be a bit wrong.
  130517. if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) {
  130518. if (n.getAttribute("id") == id
  130519. || n.getAttributeNS(null, "id") == id) {
  130520. return n;
  130521. }
  130522. }
  130523. for (var m = n.firstChild; m != null; m = m.nextSibling) {
  130524. var res = Utilities.getElementById(m, id);
  130525. if (res != null) {
  130526. return res;
  130527. }
  130528. }
  130529. return null;
  130530. };
  130531. // XPathException ////////////////////////////////////////////////////////////
  130532. XPathException.prototype = {};
  130533. XPathException.prototype.constructor = XPathException;
  130534. XPathException.superclass = Object.prototype;
  130535. function XPathException(c, e) {
  130536. this.code = c;
  130537. this.exception = e;
  130538. }
  130539. XPathException.prototype.toString = function() {
  130540. var msg = this.exception ? ": " + this.exception.toString() : "";
  130541. switch (this.code) {
  130542. case XPathException.INVALID_EXPRESSION_ERR:
  130543. return "Invalid expression" + msg;
  130544. case XPathException.TYPE_ERR:
  130545. return "Type error" + msg;
  130546. }
  130547. };
  130548. XPathException.INVALID_EXPRESSION_ERR = 51;
  130549. XPathException.TYPE_ERR = 52;
  130550. // XPathExpression ///////////////////////////////////////////////////////////
  130551. XPathExpression.prototype = {};
  130552. XPathExpression.prototype.constructor = XPathExpression;
  130553. XPathExpression.superclass = Object.prototype;
  130554. function XPathExpression(e, r, p) {
  130555. this.xpath = p.parse(e);
  130556. this.context = new XPathContext();
  130557. this.context.namespaceResolver = new XPathNSResolverWrapper(r);
  130558. }
  130559. XPathExpression.prototype.evaluate = function(n, t, res) {
  130560. this.context.expressionContextNode = n;
  130561. var result = this.xpath.evaluate(this.context);
  130562. return new XPathResult(result, t);
  130563. }
  130564. // XPathNSResolverWrapper ////////////////////////////////////////////////////
  130565. XPathNSResolverWrapper.prototype = {};
  130566. XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper;
  130567. XPathNSResolverWrapper.superclass = Object.prototype;
  130568. function XPathNSResolverWrapper(r) {
  130569. this.xpathNSResolver = r;
  130570. }
  130571. XPathNSResolverWrapper.prototype.getNamespace = function(prefix, n) {
  130572. if (this.xpathNSResolver == null) {
  130573. return null;
  130574. }
  130575. return this.xpathNSResolver.lookupNamespaceURI(prefix);
  130576. };
  130577. // NodeXPathNSResolver ///////////////////////////////////////////////////////
  130578. NodeXPathNSResolver.prototype = {};
  130579. NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver;
  130580. NodeXPathNSResolver.superclass = Object.prototype;
  130581. function NodeXPathNSResolver(n) {
  130582. this.node = n;
  130583. this.namespaceResolver = new NamespaceResolver();
  130584. }
  130585. NodeXPathNSResolver.prototype.lookupNamespaceURI = function(prefix) {
  130586. return this.namespaceResolver.getNamespace(prefix, this.node);
  130587. };
  130588. // XPathResult ///////////////////////////////////////////////////////////////
  130589. XPathResult.prototype = {};
  130590. XPathResult.prototype.constructor = XPathResult;
  130591. XPathResult.superclass = Object.prototype;
  130592. function XPathResult(v, t) {
  130593. if (t == XPathResult.ANY_TYPE) {
  130594. if (v.constructor === XString) {
  130595. t = XPathResult.STRING_TYPE;
  130596. } else if (v.constructor === XNumber) {
  130597. t = XPathResult.NUMBER_TYPE;
  130598. } else if (v.constructor === XBoolean) {
  130599. t = XPathResult.BOOLEAN_TYPE;
  130600. } else if (v.constructor === XNodeSet) {
  130601. t = XPathResult.UNORDERED_NODE_ITERATOR_TYPE;
  130602. }
  130603. }
  130604. this.resultType = t;
  130605. switch (t) {
  130606. case XPathResult.NUMBER_TYPE:
  130607. this.numberValue = v.numberValue();
  130608. return;
  130609. case XPathResult.STRING_TYPE:
  130610. this.stringValue = v.stringValue();
  130611. return;
  130612. case XPathResult.BOOLEAN_TYPE:
  130613. this.booleanValue = v.booleanValue();
  130614. return;
  130615. case XPathResult.ANY_UNORDERED_NODE_TYPE:
  130616. case XPathResult.FIRST_ORDERED_NODE_TYPE:
  130617. if (v.constructor === XNodeSet) {
  130618. this.singleNodeValue = v.first();
  130619. return;
  130620. }
  130621. break;
  130622. case XPathResult.UNORDERED_NODE_ITERATOR_TYPE:
  130623. case XPathResult.ORDERED_NODE_ITERATOR_TYPE:
  130624. if (v.constructor === XNodeSet) {
  130625. this.invalidIteratorState = false;
  130626. this.nodes = v.toArray();
  130627. this.iteratorIndex = 0;
  130628. return;
  130629. }
  130630. break;
  130631. case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE:
  130632. case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE:
  130633. if (v.constructor === XNodeSet) {
  130634. this.nodes = v.toArray();
  130635. this.snapshotLength = this.nodes.length;
  130636. return;
  130637. }
  130638. break;
  130639. }
  130640. throw new XPathException(XPathException.TYPE_ERR);
  130641. };
  130642. XPathResult.prototype.iterateNext = function() {
  130643. if (this.resultType != XPathResult.UNORDERED_NODE_ITERATOR_TYPE
  130644. && this.resultType != XPathResult.ORDERED_NODE_ITERATOR_TYPE) {
  130645. throw new XPathException(XPathException.TYPE_ERR);
  130646. }
  130647. return this.nodes[this.iteratorIndex++];
  130648. };
  130649. XPathResult.prototype.snapshotItem = function(i) {
  130650. if (this.resultType != XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE
  130651. && this.resultType != XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) {
  130652. throw new XPathException(XPathException.TYPE_ERR);
  130653. }
  130654. return this.nodes[i];
  130655. };
  130656. XPathResult.ANY_TYPE = 0;
  130657. XPathResult.NUMBER_TYPE = 1;
  130658. XPathResult.STRING_TYPE = 2;
  130659. XPathResult.BOOLEAN_TYPE = 3;
  130660. XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4;
  130661. XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5;
  130662. XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6;
  130663. XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7;
  130664. XPathResult.ANY_UNORDERED_NODE_TYPE = 8;
  130665. XPathResult.FIRST_ORDERED_NODE_TYPE = 9;
  130666. // DOM 3 XPath support ///////////////////////////////////////////////////////
  130667. function installDOM3XPathSupport(doc, p) {
  130668. doc.createExpression = function(e, r) {
  130669. try {
  130670. return new XPathExpression(e, r, p);
  130671. } catch (e) {
  130672. throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e);
  130673. }
  130674. };
  130675. doc.createNSResolver = function(n) {
  130676. return new NodeXPathNSResolver(n);
  130677. };
  130678. doc.evaluate = function(e, cn, r, t, res) {
  130679. if (t < 0 || t > 9) {
  130680. throw { code: 0, toString: function() { return "Request type not supported"; } };
  130681. }
  130682. return doc.createExpression(e, r, p).evaluate(cn, t, res);
  130683. };
  130684. };
  130685. // ---------------------------------------------------------------------------
  130686. // Install DOM 3 XPath support for the current document.
  130687. try {
  130688. var shouldInstall = true;
  130689. try {
  130690. if (document.implementation
  130691. && document.implementation.hasFeature
  130692. && document.implementation.hasFeature("XPath", null)) {
  130693. shouldInstall = false;
  130694. }
  130695. } catch (e) {
  130696. }
  130697. if (shouldInstall) {
  130698. installDOM3XPathSupport(document, new XPathParser());
  130699. }
  130700. } catch (e) {
  130701. }
  130702. function SelectNodes(doc, xpath)
  130703. {
  130704. var parser = new XPathParser();
  130705. var xpath = parser.parse(xpath);
  130706. var context = new XPathContext();
  130707. if(doc.documentElement){
  130708. context.expressionContextNode = doc.documentElement;
  130709. } else {
  130710. context.expressionContextNode = doc;
  130711. }
  130712. var res = xpath.evaluate(context)
  130713. return res.toArray();
  130714. }
  130715. module.exports = SelectNodes;
  130716. },{}],710:[function(require,module,exports){
  130717. module.exports = extend
  130718. var hasOwnProperty = Object.prototype.hasOwnProperty;
  130719. function extend() {
  130720. var target = {}
  130721. for (var i = 0; i < arguments.length; i++) {
  130722. var source = arguments[i]
  130723. for (var key in source) {
  130724. if (hasOwnProperty.call(source, key)) {
  130725. target[key] = source[key]
  130726. }
  130727. }
  130728. }
  130729. return target
  130730. }
  130731. },{}],711:[function(require,module,exports){
  130732. window.mssql = require('mssql')
  130733. },{"mssql":347}]},{},[711]);