mammoth.browser.js 990 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625
  1. // Module: [email protected]
  2. // License: MIT
  3. //
  4. // Module: [email protected]
  5. // License: MIT
  6. //
  7. // Module: [email protected]
  8. // License: MIT
  9. //
  10. // Module: [email protected]
  11. // License: MIT
  12. //
  13. // Module: [email protected]
  14. // License: MIT
  15. //
  16. // Module: [email protected]
  17. // License: MIT
  18. //
  19. // Module: [email protected]
  20. // License: BSD-3-Clause
  21. //
  22. // Module: [email protected]
  23. // License: ISC
  24. //
  25. // Module: [email protected]
  26. // License: ISC
  27. //
  28. // Module: [email protected]
  29. // License: MIT
  30. //
  31. // Module: [email protected]
  32. // License: MIT or GPLv3
  33. //
  34. // Module: [email protected]
  35. // License: BSD
  36. //
  37. // Module: [email protected]
  38. // License: BSD-2-Clause
  39. //
  40. // Module: [email protected]
  41. // License: BSD
  42. //
  43. // Module: [email protected]
  44. // License: MIT
  45. //
  46. // Module: [email protected]
  47. // License: MIT
  48. //
  49. // Module: [email protected]
  50. // License: MIT
  51. //
  52. // Module: [email protected]
  53. // License: MIT
  54. //
  55. // Module: [email protected]
  56. // License: MIT
  57. //
  58. // Module: [email protected]
  59. // License: ISC
  60. //
  61. // Module: [email protected]
  62. // License: MIT
  63. //
  64. // Module: [email protected]
  65. // License: MIT
  66. //
  67. // Module: [email protected]
  68. // License: MIT
  69. //
  70. // Module: [email protected]
  71. // License: MIT
  72. //
  73. // Module: [email protected]
  74. // License: MIT
  75. //
  76. // Module: [email protected]
  77. // License: MIT
  78. //
  79. // Module: [email protected]
  80. // License: MIT
  81. //
  82. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mammoth = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  83. var promises = require("../../lib/promises");
  84. exports.Files = Files;
  85. function Files() {
  86. function read(uri) {
  87. return promises.reject(new Error("could not open external image: '" + uri + "'\ncannot open linked files from a web browser"));
  88. }
  89. return {
  90. read: read
  91. };
  92. }
  93. },{"../../lib/promises":23}],2:[function(require,module,exports){
  94. var promises = require("../lib/promises");
  95. var zipfile = require("../lib/zipfile");
  96. exports.openZip = openZip;
  97. function openZip(options) {
  98. if (options.arrayBuffer) {
  99. return promises.resolve(zipfile.openArrayBuffer(options.arrayBuffer));
  100. } else {
  101. return promises.reject(new Error("Could not find file in options"));
  102. }
  103. }
  104. },{"../lib/promises":23,"../lib/zipfile":38}],3:[function(require,module,exports){
  105. var _ = require("underscore");
  106. var promises = require("./promises");
  107. var documents = require("./documents");
  108. var htmlPaths = require("./styles/html-paths");
  109. var results = require("./results");
  110. var images = require("./images");
  111. var Html = require("./html");
  112. var writers = require("./writers");
  113. exports.DocumentConverter = DocumentConverter;
  114. function DocumentConverter(options) {
  115. return {
  116. convertToHtml: function(element) {
  117. var comments = _.indexBy(
  118. element.type === documents.types.document ? element.comments : [],
  119. "commentId"
  120. );
  121. var conversion = new DocumentConversion(options, comments);
  122. return conversion.convertToHtml(element);
  123. }
  124. };
  125. }
  126. function DocumentConversion(options, comments) {
  127. var noteNumber = 1;
  128. var noteReferences = [];
  129. var referencedComments = [];
  130. options = _.extend({ignoreEmptyParagraphs: true}, options);
  131. var idPrefix = options.idPrefix === undefined ? "" : options.idPrefix;
  132. var ignoreEmptyParagraphs = options.ignoreEmptyParagraphs;
  133. var defaultParagraphStyle = htmlPaths.topLevelElement("p");
  134. var styleMap = options.styleMap || [];
  135. function convertToHtml(document) {
  136. var messages = [];
  137. var html = elementToHtml(document, messages, {});
  138. var deferredNodes = [];
  139. walkHtml(html, function(node) {
  140. if (node.type === "deferred") {
  141. deferredNodes.push(node);
  142. }
  143. });
  144. var deferredValues = {};
  145. return promises.mapSeries(deferredNodes, function(deferred) {
  146. return deferred.value().then(function(value) {
  147. deferredValues[deferred.id] = value;
  148. });
  149. }).then(function() {
  150. function replaceDeferred(nodes) {
  151. return flatMap(nodes, function(node) {
  152. if (node.type === "deferred") {
  153. return deferredValues[node.id];
  154. } else if (node.children) {
  155. return [
  156. _.extend({}, node, {
  157. children: replaceDeferred(node.children)
  158. })
  159. ];
  160. } else {
  161. return [node];
  162. }
  163. });
  164. }
  165. var writer = writers.writer({
  166. prettyPrint: options.prettyPrint,
  167. outputFormat: options.outputFormat
  168. });
  169. Html.write(writer, Html.simplify(replaceDeferred(html)));
  170. return new results.Result(writer.asString(), messages);
  171. });
  172. }
  173. function convertElements(elements, messages, options) {
  174. return flatMap(elements, function(element) {
  175. return elementToHtml(element, messages, options);
  176. });
  177. }
  178. function elementToHtml(element, messages, options) {
  179. if (!options) {
  180. throw new Error("options not set");
  181. }
  182. var handler = elementConverters[element.type];
  183. if (handler) {
  184. return handler(element, messages, options);
  185. } else {
  186. return [];
  187. }
  188. }
  189. function convertParagraph(element, messages, options) {
  190. return htmlPathForParagraph(element, messages).wrap(function() {
  191. var content = convertElements(element.children, messages, options);
  192. if (ignoreEmptyParagraphs) {
  193. return content;
  194. } else {
  195. return [Html.forceWrite].concat(content);
  196. }
  197. });
  198. }
  199. function htmlPathForParagraph(element, messages) {
  200. var style = findStyle(element);
  201. if (style) {
  202. return style.to;
  203. } else {
  204. if (element.styleId) {
  205. messages.push(unrecognisedStyleWarning("paragraph", element));
  206. }
  207. return defaultParagraphStyle;
  208. }
  209. }
  210. function convertRun(run, messages, options) {
  211. var nodes = function() {
  212. return convertElements(run.children, messages, options);
  213. };
  214. var paths = [];
  215. if (run.isSmallCaps) {
  216. paths.push(findHtmlPathForRunProperty("smallCaps"));
  217. }
  218. if (run.isStrikethrough) {
  219. paths.push(findHtmlPathForRunProperty("strikethrough", "s"));
  220. }
  221. if (run.isUnderline) {
  222. paths.push(findHtmlPathForRunProperty("underline"));
  223. }
  224. if (run.verticalAlignment === documents.verticalAlignment.subscript) {
  225. paths.push(htmlPaths.element("sub", {}, {fresh: false}));
  226. }
  227. if (run.verticalAlignment === documents.verticalAlignment.superscript) {
  228. paths.push(htmlPaths.element("sup", {}, {fresh: false}));
  229. }
  230. if (run.isItalic) {
  231. paths.push(findHtmlPathForRunProperty("italic", "em"));
  232. }
  233. if (run.isBold) {
  234. paths.push(findHtmlPathForRunProperty("bold", "strong"));
  235. }
  236. var stylePath = htmlPaths.empty;
  237. var style = findStyle(run);
  238. if (style) {
  239. stylePath = style.to;
  240. } else if (run.styleId) {
  241. messages.push(unrecognisedStyleWarning("run", run));
  242. }
  243. paths.push(stylePath);
  244. paths.forEach(function(path) {
  245. nodes = path.wrap.bind(path, nodes);
  246. });
  247. return nodes();
  248. }
  249. function findHtmlPathForRunProperty(elementType, defaultTagName) {
  250. var path = findHtmlPath({type: elementType});
  251. if (path) {
  252. return path;
  253. } else if (defaultTagName) {
  254. return htmlPaths.element(defaultTagName, {}, {fresh: false});
  255. } else {
  256. return htmlPaths.empty;
  257. }
  258. }
  259. function findHtmlPath(element, defaultPath) {
  260. var style = findStyle(element);
  261. return style ? style.to : defaultPath;
  262. }
  263. function findStyle(element) {
  264. for (var i = 0; i < styleMap.length; i++) {
  265. if (styleMap[i].from.matches(element)) {
  266. return styleMap[i];
  267. }
  268. }
  269. }
  270. function recoveringConvertImage(convertImage) {
  271. return function(image, messages) {
  272. return promises.attempt(function() {
  273. return convertImage(image, messages);
  274. }).caught(function(error) {
  275. messages.push(results.error(error));
  276. return [];
  277. });
  278. };
  279. }
  280. function noteHtmlId(note) {
  281. return referentHtmlId(note.noteType, note.noteId);
  282. }
  283. function noteRefHtmlId(note) {
  284. return referenceHtmlId(note.noteType, note.noteId);
  285. }
  286. function referentHtmlId(referenceType, referenceId) {
  287. return htmlId(referenceType + "-" + referenceId);
  288. }
  289. function referenceHtmlId(referenceType, referenceId) {
  290. return htmlId(referenceType + "-ref-" + referenceId);
  291. }
  292. function htmlId(suffix) {
  293. return idPrefix + suffix;
  294. }
  295. var defaultTablePath = htmlPaths.elements([
  296. htmlPaths.element("table", {}, {fresh: true})
  297. ]);
  298. function convertTable(element, messages, options) {
  299. return findHtmlPath(element, defaultTablePath).wrap(function() {
  300. return convertTableChildren(element, messages, options);
  301. });
  302. }
  303. function convertTableChildren(element, messages, options) {
  304. var bodyIndex = _.findIndex(element.children, function(child) {
  305. return !child.type === documents.types.tableRow || !child.isHeader;
  306. });
  307. if (bodyIndex === -1) {
  308. bodyIndex = element.children.length;
  309. }
  310. var children;
  311. if (bodyIndex === 0) {
  312. children = convertElements(
  313. element.children,
  314. messages,
  315. _.extend({}, options, {isTableHeader: false})
  316. );
  317. } else {
  318. var headRows = convertElements(
  319. element.children.slice(0, bodyIndex),
  320. messages,
  321. _.extend({}, options, {isTableHeader: true})
  322. );
  323. var bodyRows = convertElements(
  324. element.children.slice(bodyIndex),
  325. messages,
  326. _.extend({}, options, {isTableHeader: false})
  327. );
  328. children = [
  329. Html.freshElement("thead", {}, headRows),
  330. Html.freshElement("tbody", {}, bodyRows)
  331. ];
  332. }
  333. return [Html.forceWrite].concat(children);
  334. }
  335. function convertTableRow(element, messages, options) {
  336. return wrapChildrenInFreshElement(element, "tr", messages, options);
  337. }
  338. function convertTableCell(element, messages, options) {
  339. var tagName = options.isTableHeader ? "th" : "td";
  340. var children = convertElements(element.children, messages, options);
  341. var attributes = {};
  342. if (element.colSpan !== 1) {
  343. attributes.colspan = element.colSpan.toString();
  344. }
  345. if (element.rowSpan !== 1) {
  346. attributes.rowspan = element.rowSpan.toString();
  347. }
  348. return [
  349. Html.freshElement(tagName, attributes, [Html.forceWrite].concat(children))
  350. ];
  351. }
  352. function convertCommentReference(reference, messages, options) {
  353. return findHtmlPath(reference, htmlPaths.ignore).wrap(function() {
  354. var comment = comments[reference.commentId];
  355. var count = referencedComments.length + 1;
  356. var label = "[" + commentAuthorLabel(comment) + count + "]";
  357. referencedComments.push({label: label, comment: comment});
  358. // TODO: remove duplication with note references
  359. return [
  360. Html.freshElement("a", {
  361. href: "#" + referentHtmlId("comment", reference.commentId),
  362. id: referenceHtmlId("comment", reference.commentId)
  363. }, [Html.text(label)])
  364. ];
  365. });
  366. }
  367. function convertComment(referencedComment, messages, options) {
  368. // TODO: remove duplication with note references
  369. var label = referencedComment.label;
  370. var comment = referencedComment.comment;
  371. var body = convertElements(comment.body, messages, options).concat([
  372. Html.nonFreshElement("p", {}, [
  373. Html.text(" "),
  374. Html.freshElement("a", {"href": "#" + referenceHtmlId("comment", comment.commentId)}, [
  375. Html.text("↑")
  376. ])
  377. ])
  378. ]);
  379. return [
  380. Html.freshElement(
  381. "dt",
  382. {"id": referentHtmlId("comment", comment.commentId)},
  383. [Html.text("Comment " + label)]
  384. ),
  385. Html.freshElement("dd", {}, body)
  386. ];
  387. }
  388. function convertBreak(element, messages, options) {
  389. return htmlPathForBreak(element).wrap(function() {
  390. return [];
  391. });
  392. }
  393. function htmlPathForBreak(element) {
  394. var style = findStyle(element);
  395. if (style) {
  396. return style.to;
  397. } else if (element.breakType === "line") {
  398. return htmlPaths.topLevelElement("br");
  399. } else {
  400. return htmlPaths.empty;
  401. }
  402. }
  403. function wrapChildrenInFreshElement(element, wrapElementName, messages, options) {
  404. var children = convertElements(element.children, messages, options);
  405. return [
  406. Html.freshElement(wrapElementName, {}, [Html.forceWrite].concat(children))
  407. ];
  408. }
  409. var elementConverters = {
  410. "document": function(document, messages, options) {
  411. var children = convertElements(document.children, messages, options);
  412. var notes = noteReferences.map(function(noteReference) {
  413. return document.notes.resolve(noteReference);
  414. });
  415. var notesNodes = convertElements(notes, messages, options);
  416. return children.concat([
  417. Html.freshElement("ol", {}, notesNodes),
  418. Html.freshElement("dl", {}, flatMap(referencedComments, function(referencedComment) {
  419. return convertComment(referencedComment, messages, options);
  420. }))
  421. ]);
  422. },
  423. "paragraph": convertParagraph,
  424. "run": convertRun,
  425. "text": function(element, messages, options) {
  426. return [Html.text(element.value)];
  427. },
  428. "tab": function(element, messages, options) {
  429. return [Html.text("\t")];
  430. },
  431. "hyperlink": function(element, messages, options) {
  432. var href = element.anchor ? "#" + htmlId(element.anchor) : element.href;
  433. var attributes = {href: href};
  434. if (element.targetFrame != null) {
  435. attributes.target = element.targetFrame;
  436. }
  437. var children = convertElements(element.children, messages, options);
  438. return [Html.freshElement("a", attributes, children)];
  439. },
  440. "bookmarkStart": function(element, messages, options) {
  441. var anchor = Html.freshElement("a", {
  442. id: htmlId(element.name)
  443. }, [Html.forceWrite]);
  444. return [anchor];
  445. },
  446. "noteReference": function(element, messages, options) {
  447. noteReferences.push(element);
  448. var anchor = Html.freshElement("a", {
  449. href: "#" + noteHtmlId(element),
  450. id: noteRefHtmlId(element)
  451. }, [Html.text("[" + (noteNumber++) + "]")]);
  452. return [Html.freshElement("sup", {}, [anchor])];
  453. },
  454. "note": function(element, messages, options) {
  455. var children = convertElements(element.body, messages, options);
  456. var backLink = Html.elementWithTag(htmlPaths.element("p", {}, {fresh: false}), [
  457. Html.text(" "),
  458. Html.freshElement("a", {href: "#" + noteRefHtmlId(element)}, [Html.text("↑")])
  459. ]);
  460. var body = children.concat([backLink]);
  461. return Html.freshElement("li", {id: noteHtmlId(element)}, body);
  462. },
  463. "commentReference": convertCommentReference,
  464. "comment": convertComment,
  465. "image": deferredConversion(recoveringConvertImage(options.convertImage || images.dataUri)),
  466. "table": convertTable,
  467. "tableRow": convertTableRow,
  468. "tableCell": convertTableCell,
  469. "break": convertBreak
  470. };
  471. return {
  472. convertToHtml: convertToHtml
  473. };
  474. }
  475. var deferredId = 1;
  476. function deferredConversion(func) {
  477. return function(element, messages, options) {
  478. return [
  479. {
  480. type: "deferred",
  481. id: deferredId++,
  482. value: function() {
  483. return func(element, messages, options);
  484. }
  485. }
  486. ];
  487. };
  488. }
  489. function unrecognisedStyleWarning(type, element) {
  490. return results.warning(
  491. "Unrecognised " + type + " style: '" + element.styleName + "'" +
  492. " (Style ID: " + element.styleId + ")"
  493. );
  494. }
  495. function flatMap(values, func) {
  496. return _.flatten(values.map(func), true);
  497. }
  498. function walkHtml(nodes, callback) {
  499. nodes.forEach(function(node) {
  500. callback(node);
  501. if (node.children) {
  502. walkHtml(node.children, callback);
  503. }
  504. });
  505. }
  506. var commentAuthorLabel = exports.commentAuthorLabel = function commentAuthorLabel(comment) {
  507. return comment.authorInitials || "";
  508. };
  509. },{"./documents":4,"./html":18,"./images":20,"./promises":23,"./results":24,"./styles/html-paths":27,"./writers":32,"underscore":153}],4:[function(require,module,exports){
  510. var _ = require("underscore");
  511. var types = exports.types = {
  512. document: "document",
  513. paragraph: "paragraph",
  514. run: "run",
  515. text: "text",
  516. tab: "tab",
  517. hyperlink: "hyperlink",
  518. noteReference: "noteReference",
  519. image: "image",
  520. note: "note",
  521. commentReference: "commentReference",
  522. comment: "comment",
  523. table: "table",
  524. tableRow: "tableRow",
  525. tableCell: "tableCell",
  526. "break": "break",
  527. bookmarkStart: "bookmarkStart"
  528. };
  529. function Document(children, options) {
  530. options = options || {};
  531. return {
  532. type: types.document,
  533. children: children,
  534. notes: options.notes || new Notes({}),
  535. comments: options.comments || []
  536. };
  537. }
  538. function Paragraph(children, properties) {
  539. properties = properties || {};
  540. var indent = properties.indent || {};
  541. return {
  542. type: types.paragraph,
  543. children: children,
  544. styleId: properties.styleId || null,
  545. styleName: properties.styleName || null,
  546. numbering: properties.numbering || null,
  547. alignment: properties.alignment || null,
  548. indent: {
  549. start: indent.start || null,
  550. end: indent.end || null,
  551. firstLine: indent.firstLine || null,
  552. hanging: indent.hanging || null
  553. }
  554. };
  555. }
  556. function Run(children, properties) {
  557. properties = properties || {};
  558. return {
  559. type: types.run,
  560. children: children,
  561. styleId: properties.styleId || null,
  562. styleName: properties.styleName || null,
  563. isBold: properties.isBold,
  564. isUnderline: properties.isUnderline,
  565. isItalic: properties.isItalic,
  566. isStrikethrough: properties.isStrikethrough,
  567. isSmallCaps: properties.isSmallCaps,
  568. verticalAlignment: properties.verticalAlignment || verticalAlignment.baseline,
  569. font: properties.font || null
  570. };
  571. }
  572. var verticalAlignment = {
  573. baseline: "baseline",
  574. superscript: "superscript",
  575. subscript: "subscript"
  576. };
  577. function Text(value) {
  578. return {
  579. type: types.text,
  580. value: value
  581. };
  582. }
  583. function Tab() {
  584. return {
  585. type: types.tab
  586. };
  587. }
  588. function Hyperlink(children, options) {
  589. return {
  590. type: types.hyperlink,
  591. children: children,
  592. href: options.href,
  593. anchor: options.anchor,
  594. targetFrame: options.targetFrame
  595. };
  596. }
  597. function NoteReference(options) {
  598. return {
  599. type: types.noteReference,
  600. noteType: options.noteType,
  601. noteId: options.noteId
  602. };
  603. }
  604. function Notes(notes) {
  605. this._notes = _.indexBy(notes, function(note) {
  606. return noteKey(note.noteType, note.noteId);
  607. });
  608. }
  609. Notes.prototype.resolve = function(reference) {
  610. return this.findNoteByKey(noteKey(reference.noteType, reference.noteId));
  611. };
  612. Notes.prototype.findNoteByKey = function(key) {
  613. return this._notes[key] || null;
  614. };
  615. function Note(options) {
  616. return {
  617. type: types.note,
  618. noteType: options.noteType,
  619. noteId: options.noteId,
  620. body: options.body
  621. };
  622. }
  623. function commentReference(options) {
  624. return {
  625. type: types.commentReference,
  626. commentId: options.commentId
  627. };
  628. }
  629. function comment(options) {
  630. return {
  631. type: types.comment,
  632. commentId: options.commentId,
  633. body: options.body,
  634. authorName: options.authorName,
  635. authorInitials: options.authorInitials
  636. };
  637. }
  638. function noteKey(noteType, id) {
  639. return noteType + "-" + id;
  640. }
  641. function Image(options) {
  642. return {
  643. type: types.image,
  644. read: options.readImage,
  645. altText: options.altText,
  646. contentType: options.contentType
  647. };
  648. }
  649. function Table(children, properties) {
  650. properties = properties || {};
  651. return {
  652. type: types.table,
  653. children: children,
  654. styleId: properties.styleId || null,
  655. styleName: properties.styleName || null
  656. };
  657. }
  658. function TableRow(children, options) {
  659. options = options || {};
  660. return {
  661. type: types.tableRow,
  662. children: children,
  663. isHeader: options.isHeader || false
  664. };
  665. }
  666. function TableCell(children, options) {
  667. options = options || {};
  668. return {
  669. type: types.tableCell,
  670. children: children,
  671. colSpan: options.colSpan == null ? 1 : options.colSpan,
  672. rowSpan: options.rowSpan == null ? 1 : options.rowSpan
  673. };
  674. }
  675. function Break(breakType) {
  676. return {
  677. type: types["break"],
  678. breakType: breakType
  679. };
  680. }
  681. function BookmarkStart(options) {
  682. return {
  683. type: types.bookmarkStart,
  684. name: options.name
  685. };
  686. }
  687. exports.document = exports.Document = Document;
  688. exports.paragraph = exports.Paragraph = Paragraph;
  689. exports.run = exports.Run = Run;
  690. exports.Text = Text;
  691. exports.tab = exports.Tab = Tab;
  692. exports.Hyperlink = Hyperlink;
  693. exports.noteReference = exports.NoteReference = NoteReference;
  694. exports.Notes = Notes;
  695. exports.Note = Note;
  696. exports.commentReference = commentReference;
  697. exports.comment = comment;
  698. exports.Image = Image;
  699. exports.Table = Table;
  700. exports.TableRow = TableRow;
  701. exports.TableCell = TableCell;
  702. exports.lineBreak = Break("line");
  703. exports.pageBreak = Break("page");
  704. exports.columnBreak = Break("column");
  705. exports.BookmarkStart = BookmarkStart;
  706. exports.verticalAlignment = verticalAlignment;
  707. },{"underscore":153}],5:[function(require,module,exports){
  708. exports.createBodyReader = createBodyReader;
  709. exports._readNumberingProperties = readNumberingProperties;
  710. var _ = require("underscore");
  711. var documents = require("../documents");
  712. var Result = require("../results").Result;
  713. var warning = require("../results").warning;
  714. var uris = require("./uris");
  715. function createBodyReader(options) {
  716. return {
  717. readXmlElement: function(element) {
  718. return new BodyReader(options).readXmlElement(element);
  719. },
  720. readXmlElements: function(elements) {
  721. return new BodyReader(options).readXmlElements(elements);
  722. }
  723. };
  724. }
  725. function BodyReader(options) {
  726. var complexFieldStack = [];
  727. var currentInstrText = [];
  728. var relationships = options.relationships;
  729. var contentTypes = options.contentTypes;
  730. var docxFile = options.docxFile;
  731. var files = options.files;
  732. var numbering = options.numbering;
  733. var styles = options.styles;
  734. function readXmlElements(elements) {
  735. var results = elements.map(readXmlElement);
  736. return combineResults(results);
  737. }
  738. function readXmlElement(element) {
  739. if (element.type === "element") {
  740. var handler = xmlElementReaders[element.name];
  741. if (handler) {
  742. return handler(element);
  743. } else if (!Object.prototype.hasOwnProperty.call(ignoreElements, element.name)) {
  744. var message = warning("An unrecognised element was ignored: " + element.name);
  745. return emptyResultWithMessages([message]);
  746. }
  747. }
  748. return emptyResult();
  749. }
  750. function readParagraphIndent(element) {
  751. return {
  752. start: element.attributes["w:start"] || element.attributes["w:left"],
  753. end: element.attributes["w:end"] || element.attributes["w:right"],
  754. firstLine: element.attributes["w:firstLine"],
  755. hanging: element.attributes["w:hanging"]
  756. };
  757. }
  758. function readRunProperties(element) {
  759. return readRunStyle(element).map(function(style) {
  760. return {
  761. type: "runProperties",
  762. styleId: style.styleId,
  763. styleName: style.name,
  764. verticalAlignment: element.firstOrEmpty("w:vertAlign").attributes["w:val"],
  765. font: element.firstOrEmpty("w:rFonts").attributes["w:ascii"],
  766. isBold: readBooleanElement(element.first("w:b")),
  767. isUnderline: readBooleanElement(element.first("w:u")),
  768. isItalic: readBooleanElement(element.first("w:i")),
  769. isStrikethrough: readBooleanElement(element.first("w:strike")),
  770. isSmallCaps: readBooleanElement(element.first("w:smallCaps"))
  771. };
  772. });
  773. }
  774. function readBooleanElement(element) {
  775. if (element) {
  776. var value = element.attributes["w:val"];
  777. return value !== "false" && value !== "0";
  778. } else {
  779. return false;
  780. }
  781. }
  782. function readParagraphStyle(element) {
  783. return readStyle(element, "w:pStyle", "Paragraph", styles.findParagraphStyleById);
  784. }
  785. function readRunStyle(element) {
  786. return readStyle(element, "w:rStyle", "Run", styles.findCharacterStyleById);
  787. }
  788. function readTableStyle(element) {
  789. return readStyle(element, "w:tblStyle", "Table", styles.findTableStyleById);
  790. }
  791. function readStyle(element, styleTagName, styleType, findStyleById) {
  792. var messages = [];
  793. var styleElement = element.first(styleTagName);
  794. var styleId = null;
  795. var name = null;
  796. if (styleElement) {
  797. styleId = styleElement.attributes["w:val"];
  798. if (styleId) {
  799. var style = findStyleById(styleId);
  800. if (style) {
  801. name = style.name;
  802. } else {
  803. messages.push(undefinedStyleWarning(styleType, styleId));
  804. }
  805. }
  806. }
  807. return elementResultWithMessages({styleId: styleId, name: name}, messages);
  808. }
  809. var unknownComplexField = {type: "unknown"};
  810. function readFldChar(element) {
  811. var type = element.attributes["w:fldCharType"];
  812. if (type === "begin") {
  813. complexFieldStack.push(unknownComplexField);
  814. currentInstrText = [];
  815. } else if (type === "end") {
  816. complexFieldStack.pop();
  817. } else if (type === "separate") {
  818. var href = parseHyperlinkFieldCode(currentInstrText.join(''));
  819. var complexField = href === null ? unknownComplexField : {type: "hyperlink", href: href};
  820. complexFieldStack.pop();
  821. complexFieldStack.push(complexField);
  822. }
  823. return emptyResult();
  824. }
  825. function currentHyperlinkHref() {
  826. var topHyperlink = _.last(complexFieldStack.filter(function(complexField) {
  827. return complexField.type === "hyperlink";
  828. }));
  829. return topHyperlink ? topHyperlink.href : null;
  830. }
  831. function parseHyperlinkFieldCode(code) {
  832. var result = /\s*HYPERLINK "(.*)"/.exec(code);
  833. if (result) {
  834. return result[1];
  835. } else {
  836. return null;
  837. }
  838. }
  839. function readInstrText(element) {
  840. currentInstrText.push(element.text());
  841. return emptyResult();
  842. }
  843. function noteReferenceReader(noteType) {
  844. return function(element) {
  845. var noteId = element.attributes["w:id"];
  846. return elementResult(new documents.NoteReference({
  847. noteType: noteType,
  848. noteId: noteId
  849. }));
  850. };
  851. }
  852. function readCommentReference(element) {
  853. return elementResult(documents.commentReference({
  854. commentId: element.attributes["w:id"]
  855. }));
  856. }
  857. function readChildElements(element) {
  858. return readXmlElements(element.children);
  859. }
  860. var xmlElementReaders = {
  861. "w:p": function(element) {
  862. return readXmlElements(element.children)
  863. .map(function(children) {
  864. var properties = _.find(children, isParagraphProperties);
  865. return new documents.Paragraph(
  866. children.filter(negate(isParagraphProperties)),
  867. properties
  868. );
  869. })
  870. .insertExtra();
  871. },
  872. "w:pPr": function(element) {
  873. return readParagraphStyle(element).map(function(style) {
  874. return {
  875. type: "paragraphProperties",
  876. styleId: style.styleId,
  877. styleName: style.name,
  878. alignment: element.firstOrEmpty("w:jc").attributes["w:val"],
  879. numbering: readNumberingProperties(element.firstOrEmpty("w:numPr"), numbering),
  880. indent: readParagraphIndent(element.firstOrEmpty("w:ind"))
  881. };
  882. });
  883. },
  884. "w:r": function(element) {
  885. return readXmlElements(element.children)
  886. .map(function(children) {
  887. var properties = _.find(children, isRunProperties);
  888. children = children.filter(negate(isRunProperties));
  889. var hyperlinkHref = currentHyperlinkHref();
  890. if (hyperlinkHref !== null) {
  891. children = [new documents.Hyperlink(children, {href: hyperlinkHref})];
  892. }
  893. return new documents.Run(children, properties);
  894. });
  895. },
  896. "w:rPr": readRunProperties,
  897. "w:fldChar": readFldChar,
  898. "w:instrText": readInstrText,
  899. "w:t": function(element) {
  900. return elementResult(new documents.Text(element.text()));
  901. },
  902. "w:tab": function(element) {
  903. return elementResult(new documents.Tab());
  904. },
  905. "w:noBreakHyphen": function() {
  906. return elementResult(new documents.Text("\u2011"));
  907. },
  908. "w:hyperlink": function(element) {
  909. var relationshipId = element.attributes["r:id"];
  910. var anchor = element.attributes["w:anchor"];
  911. return readXmlElements(element.children).map(function(children) {
  912. function create(options) {
  913. var targetFrame = element.attributes["w:tgtFrame"] || null;
  914. return new documents.Hyperlink(
  915. children,
  916. _.extend({targetFrame: targetFrame}, options)
  917. );
  918. }
  919. if (relationshipId) {
  920. var href = relationships.findTargetByRelationshipId(relationshipId);
  921. if (anchor) {
  922. href = uris.replaceFragment(href, anchor);
  923. }
  924. return create({href: href});
  925. } else if (anchor) {
  926. return create({anchor: anchor});
  927. } else {
  928. return children;
  929. }
  930. });
  931. },
  932. "w:tbl": readTable,
  933. "w:tr": readTableRow,
  934. "w:tc": readTableCell,
  935. "w:footnoteReference": noteReferenceReader("footnote"),
  936. "w:endnoteReference": noteReferenceReader("endnote"),
  937. "w:commentReference": readCommentReference,
  938. "w:br": function(element) {
  939. var breakType = element.attributes["w:type"];
  940. if (breakType == null || breakType === "textWrapping") {
  941. return elementResult(documents.lineBreak);
  942. } else if (breakType === "page") {
  943. return elementResult(documents.pageBreak);
  944. } else if (breakType === "column") {
  945. return elementResult(documents.columnBreak);
  946. } else {
  947. return emptyResultWithMessages([warning("Unsupported break type: " + breakType)]);
  948. }
  949. },
  950. "w:bookmarkStart": function(element){
  951. var name = element.attributes["w:name"];
  952. if (name === "_GoBack") {
  953. return emptyResult();
  954. } else {
  955. return elementResult(new documents.BookmarkStart({name: name}));
  956. }
  957. },
  958. "mc:AlternateContent": function(element) {
  959. return readChildElements(element.first("mc:Fallback"));
  960. },
  961. "w:sdt": function(element) {
  962. return readXmlElements(element.firstOrEmpty("w:sdtContent").children);
  963. },
  964. "w:ins": readChildElements,
  965. "w:object": readChildElements,
  966. "w:smartTag": readChildElements,
  967. "w:drawing": readChildElements,
  968. "w:pict": function(element) {
  969. return readChildElements(element).toExtra();
  970. },
  971. "v:roundrect": readChildElements,
  972. "v:shape": readChildElements,
  973. "v:textbox": readChildElements,
  974. "w:txbxContent": readChildElements,
  975. "wp:inline": readDrawingElement,
  976. "wp:anchor": readDrawingElement,
  977. "v:imagedata": readImageData,
  978. "v:group": readChildElements,
  979. "v:rect": readChildElements
  980. };
  981. return {
  982. readXmlElement: readXmlElement,
  983. readXmlElements: readXmlElements
  984. };
  985. function readTable(element) {
  986. var propertiesResult = readTableProperties(element.firstOrEmpty("w:tblPr"));
  987. return readXmlElements(element.children)
  988. .flatMap(calculateRowSpans)
  989. .flatMap(function(children) {
  990. return propertiesResult.map(function(properties) {
  991. return documents.Table(children, properties);
  992. });
  993. });
  994. }
  995. function readTableProperties(element) {
  996. return readTableStyle(element).map(function(style) {
  997. return {
  998. styleId: style.styleId,
  999. styleName: style.name
  1000. };
  1001. });
  1002. }
  1003. function readTableRow(element) {
  1004. var properties = element.firstOrEmpty("w:trPr");
  1005. var isHeader = !!properties.first("w:tblHeader");
  1006. return readXmlElements(element.children).map(function(children) {
  1007. return documents.TableRow(children, {isHeader: isHeader});
  1008. });
  1009. }
  1010. function readTableCell(element) {
  1011. return readXmlElements(element.children).map(function(children) {
  1012. var properties = element.firstOrEmpty("w:tcPr");
  1013. var gridSpan = properties.firstOrEmpty("w:gridSpan").attributes["w:val"];
  1014. var colSpan = gridSpan ? parseInt(gridSpan, 10) : 1;
  1015. var cell = documents.TableCell(children, {colSpan: colSpan});
  1016. cell._vMerge = readVMerge(properties);
  1017. return cell;
  1018. });
  1019. }
  1020. function readVMerge(properties) {
  1021. var element = properties.first("w:vMerge");
  1022. if (element) {
  1023. var val = element.attributes["w:val"];
  1024. return val === "continue" || !val;
  1025. } else {
  1026. return null;
  1027. }
  1028. }
  1029. function calculateRowSpans(rows) {
  1030. var unexpectedNonRows = _.any(rows, function(row) {
  1031. return row.type !== documents.types.tableRow;
  1032. });
  1033. if (unexpectedNonRows) {
  1034. return elementResultWithMessages(rows, [warning(
  1035. "unexpected non-row element in table, cell merging may be incorrect"
  1036. )]);
  1037. }
  1038. var unexpectedNonCells = _.any(rows, function(row) {
  1039. return _.any(row.children, function(cell) {
  1040. return cell.type !== documents.types.tableCell;
  1041. });
  1042. });
  1043. if (unexpectedNonCells) {
  1044. return elementResultWithMessages(rows, [warning(
  1045. "unexpected non-cell element in table row, cell merging may be incorrect"
  1046. )]);
  1047. }
  1048. var columns = {};
  1049. rows.forEach(function(row) {
  1050. var cellIndex = 0;
  1051. row.children.forEach(function(cell) {
  1052. if (cell._vMerge && columns[cellIndex]) {
  1053. columns[cellIndex].rowSpan++;
  1054. } else {
  1055. columns[cellIndex] = cell;
  1056. cell._vMerge = false;
  1057. }
  1058. cellIndex += cell.colSpan;
  1059. });
  1060. });
  1061. rows.forEach(function(row) {
  1062. row.children = row.children.filter(function(cell) {
  1063. return !cell._vMerge;
  1064. });
  1065. row.children.forEach(function(cell) {
  1066. delete cell._vMerge;
  1067. });
  1068. });
  1069. return elementResult(rows);
  1070. }
  1071. function readDrawingElement(element) {
  1072. var blips = element
  1073. .getElementsByTagName("a:graphic")
  1074. .getElementsByTagName("a:graphicData")
  1075. .getElementsByTagName("pic:pic")
  1076. .getElementsByTagName("pic:blipFill")
  1077. .getElementsByTagName("a:blip");
  1078. return combineResults(blips.map(readBlip.bind(null, element)));
  1079. }
  1080. function readBlip(element, blip) {
  1081. var properties = element.first("wp:docPr").attributes;
  1082. var altText = isBlank(properties.descr) ? properties.title : properties.descr;
  1083. return readImage(findBlipImageFile(blip), altText);
  1084. }
  1085. function isBlank(value) {
  1086. return value == null || /^\s*$/.test(value);
  1087. }
  1088. function findBlipImageFile(blip) {
  1089. var embedRelationshipId = blip.attributes["r:embed"];
  1090. var linkRelationshipId = blip.attributes["r:link"];
  1091. if (embedRelationshipId) {
  1092. return findEmbeddedImageFile(embedRelationshipId);
  1093. } else {
  1094. var imagePath = relationships.findTargetByRelationshipId(linkRelationshipId);
  1095. return {
  1096. path: imagePath,
  1097. read: files.read.bind(files, imagePath)
  1098. };
  1099. }
  1100. }
  1101. function readImageData(element) {
  1102. var relationshipId = element.attributes['r:id'];
  1103. if (relationshipId) {
  1104. return readImage(
  1105. findEmbeddedImageFile(relationshipId),
  1106. element.attributes["o:title"]);
  1107. } else {
  1108. return emptyResultWithMessages([warning("A v:imagedata element without a relationship ID was ignored")]);
  1109. }
  1110. }
  1111. function findEmbeddedImageFile(relationshipId) {
  1112. var path = uris.uriToZipEntryName("word", relationships.findTargetByRelationshipId(relationshipId));
  1113. return {
  1114. path: path,
  1115. read: docxFile.read.bind(docxFile, path)
  1116. };
  1117. }
  1118. function readImage(imageFile, altText) {
  1119. var contentType = contentTypes.findContentType(imageFile.path);
  1120. var image = documents.Image({
  1121. readImage: imageFile.read,
  1122. altText: altText,
  1123. contentType: contentType
  1124. });
  1125. var warnings = supportedImageTypes[contentType] ?
  1126. [] : warning("Image of type " + contentType + " is unlikely to display in web browsers");
  1127. return elementResultWithMessages(image, warnings);
  1128. }
  1129. function undefinedStyleWarning(type, styleId) {
  1130. return warning(
  1131. type + " style with ID " + styleId + " was referenced but not defined in the document");
  1132. }
  1133. }
  1134. function readNumberingProperties(element, numbering) {
  1135. var level = element.firstOrEmpty("w:ilvl").attributes["w:val"];
  1136. var numId = element.firstOrEmpty("w:numId").attributes["w:val"];
  1137. if (level === undefined || numId === undefined) {
  1138. return null;
  1139. } else {
  1140. return numbering.findLevel(numId, level);
  1141. }
  1142. }
  1143. var supportedImageTypes = {
  1144. "image/png": true,
  1145. "image/gif": true,
  1146. "image/jpeg": true,
  1147. "image/svg+xml": true,
  1148. "image/tiff": true
  1149. };
  1150. var ignoreElements = {
  1151. "office-word:wrap": true,
  1152. "v:shadow": true,
  1153. "v:shapetype": true,
  1154. "w:annotationRef": true,
  1155. "w:bookmarkEnd": true,
  1156. "w:sectPr": true,
  1157. "w:proofErr": true,
  1158. "w:lastRenderedPageBreak": true,
  1159. "w:commentRangeStart": true,
  1160. "w:commentRangeEnd": true,
  1161. "w:del": true,
  1162. "w:footnoteRef": true,
  1163. "w:endnoteRef": true,
  1164. "w:tblPr": true,
  1165. "w:tblGrid": true,
  1166. "w:trPr": true,
  1167. "w:tcPr": true
  1168. };
  1169. function isParagraphProperties(element) {
  1170. return element.type === "paragraphProperties";
  1171. }
  1172. function isRunProperties(element) {
  1173. return element.type === "runProperties";
  1174. }
  1175. function negate(predicate) {
  1176. return function(value) {
  1177. return !predicate(value);
  1178. };
  1179. }
  1180. function emptyResultWithMessages(messages) {
  1181. return new ReadResult(null, null, messages);
  1182. }
  1183. function emptyResult() {
  1184. return new ReadResult(null);
  1185. }
  1186. function elementResult(element) {
  1187. return new ReadResult(element);
  1188. }
  1189. function elementResultWithMessages(element, messages) {
  1190. return new ReadResult(element, null, messages);
  1191. }
  1192. function ReadResult(element, extra, messages) {
  1193. this.value = element || [];
  1194. this.extra = extra;
  1195. this._result = new Result({
  1196. element: this.value,
  1197. extra: extra
  1198. }, messages);
  1199. this.messages = this._result.messages;
  1200. }
  1201. ReadResult.prototype.toExtra = function() {
  1202. return new ReadResult(null, joinElements(this.extra, this.value), this.messages);
  1203. };
  1204. ReadResult.prototype.insertExtra = function() {
  1205. var extra = this.extra;
  1206. if (extra && extra.length) {
  1207. return new ReadResult(joinElements(this.value, extra), null, this.messages);
  1208. } else {
  1209. return this;
  1210. }
  1211. };
  1212. ReadResult.prototype.map = function(func) {
  1213. var result = this._result.map(function(value) {
  1214. return func(value.element);
  1215. });
  1216. return new ReadResult(result.value, this.extra, result.messages);
  1217. };
  1218. ReadResult.prototype.flatMap = function(func) {
  1219. var result = this._result.flatMap(function(value) {
  1220. return func(value.element)._result;
  1221. });
  1222. return new ReadResult(result.value.element, joinElements(this.extra, result.value.extra), result.messages);
  1223. };
  1224. function combineResults(results) {
  1225. var result = Result.combine(_.pluck(results, "_result"));
  1226. return new ReadResult(
  1227. _.flatten(_.pluck(result.value, "element")),
  1228. _.filter(_.flatten(_.pluck(result.value, "extra")), identity),
  1229. result.messages
  1230. );
  1231. }
  1232. function joinElements(first, second) {
  1233. return _.flatten([first, second]);
  1234. }
  1235. function identity(value) {
  1236. return value;
  1237. }
  1238. },{"../documents":4,"../results":24,"./uris":16,"underscore":153}],6:[function(require,module,exports){
  1239. var documents = require("../documents");
  1240. var Result = require("../results").Result;
  1241. function createCommentsReader(bodyReader) {
  1242. function readCommentsXml(element) {
  1243. return Result.combine(element.getElementsByTagName("w:comment")
  1244. .map(readCommentElement));
  1245. }
  1246. function readCommentElement(element) {
  1247. var id = element.attributes["w:id"];
  1248. function readOptionalAttribute(name) {
  1249. return (element.attributes[name] || "").trim() || null;
  1250. }
  1251. return bodyReader.readXmlElements(element.children)
  1252. .map(function(body) {
  1253. return documents.comment({
  1254. commentId: id,
  1255. body: body,
  1256. authorName: readOptionalAttribute("w:author"),
  1257. authorInitials: readOptionalAttribute("w:initials")
  1258. });
  1259. });
  1260. }
  1261. return readCommentsXml;
  1262. }
  1263. exports.createCommentsReader = createCommentsReader;
  1264. },{"../documents":4,"../results":24}],7:[function(require,module,exports){
  1265. exports.readContentTypesFromXml = readContentTypesFromXml;
  1266. var fallbackContentTypes = {
  1267. "png": "png",
  1268. "gif": "gif",
  1269. "jpeg": "jpeg",
  1270. "jpg": "jpeg",
  1271. "tif": "tiff",
  1272. "tiff": "tiff",
  1273. "bmp": "bmp"
  1274. };
  1275. exports.defaultContentTypes = contentTypes({}, {});
  1276. function readContentTypesFromXml(element) {
  1277. var extensionDefaults = {};
  1278. var overrides = {};
  1279. element.children.forEach(function(child) {
  1280. if (child.name === "content-types:Default") {
  1281. extensionDefaults[child.attributes.Extension] = child.attributes.ContentType;
  1282. }
  1283. if (child.name === "content-types:Override") {
  1284. var name = child.attributes.PartName;
  1285. if (name.charAt(0) === "/") {
  1286. name = name.substring(1);
  1287. }
  1288. overrides[name] = child.attributes.ContentType;
  1289. }
  1290. });
  1291. return contentTypes(overrides, extensionDefaults);
  1292. }
  1293. function contentTypes(overrides, extensionDefaults) {
  1294. return {
  1295. findContentType: function(path) {
  1296. var overrideContentType = overrides[path];
  1297. if (overrideContentType) {
  1298. return overrideContentType;
  1299. } else {
  1300. var pathParts = path.split(".");
  1301. var extension = pathParts[pathParts.length - 1];
  1302. if (extensionDefaults.hasOwnProperty(extension)) {
  1303. return extensionDefaults[extension];
  1304. } else {
  1305. var fallback = fallbackContentTypes[extension.toLowerCase()];
  1306. if (fallback) {
  1307. return "image/" + fallback;
  1308. } else {
  1309. return null;
  1310. }
  1311. }
  1312. }
  1313. }
  1314. };
  1315. }
  1316. },{}],8:[function(require,module,exports){
  1317. exports.DocumentXmlReader = DocumentXmlReader;
  1318. var documents = require("../documents");
  1319. var Result = require("../results").Result;
  1320. function DocumentXmlReader(options) {
  1321. var bodyReader = options.bodyReader;
  1322. function convertXmlToDocument(element) {
  1323. var body = element.first("w:body");
  1324. var result = bodyReader.readXmlElements(body.children)
  1325. .map(function(children) {
  1326. return new documents.Document(children, {
  1327. notes: options.notes,
  1328. comments: options.comments
  1329. });
  1330. });
  1331. return new Result(result.value, result.messages);
  1332. }
  1333. return {
  1334. convertXmlToDocument: convertXmlToDocument
  1335. };
  1336. }
  1337. },{"../documents":4,"../results":24}],9:[function(require,module,exports){
  1338. exports.read = read;
  1339. exports._findPartPaths = findPartPaths;
  1340. var path = require("path");
  1341. var promises = require("../promises");
  1342. var documents = require("../documents");
  1343. var Result = require("../results").Result;
  1344. var zipfile = require("../zipfile");
  1345. var readXmlFromZipFile = require("./office-xml-reader").readXmlFromZipFile;
  1346. var createBodyReader = require("./body-reader").createBodyReader;
  1347. var DocumentXmlReader = require("./document-xml-reader").DocumentXmlReader;
  1348. var relationshipsReader = require("./relationships-reader");
  1349. var contentTypesReader = require("./content-types-reader");
  1350. var numberingXml = require("./numbering-xml");
  1351. var stylesReader = require("./styles-reader");
  1352. var notesReader = require("./notes-reader");
  1353. var commentsReader = require("./comments-reader");
  1354. var Files = require("./files").Files;
  1355. function read(docxFile, input) {
  1356. input = input || {};
  1357. return promises.props({
  1358. contentTypes: readContentTypesFromZipFile(docxFile),
  1359. partPaths: findPartPaths(docxFile),
  1360. docxFile: docxFile,
  1361. files: new Files(input.path ? path.dirname(input.path) : null)
  1362. }).also(function(result) {
  1363. return {
  1364. numbering: readNumberingFromZipFile(docxFile, result.partPaths.numbering),
  1365. styles: readStylesFromZipFile(docxFile, result.partPaths.styles)
  1366. };
  1367. }).also(function(result) {
  1368. return {
  1369. footnotes: readXmlFileWithBody(result.partPaths.footnotes, result, function(bodyReader, xml) {
  1370. if (xml) {
  1371. return notesReader.createFootnotesReader(bodyReader)(xml);
  1372. } else {
  1373. return new Result([]);
  1374. }
  1375. }),
  1376. endnotes: readXmlFileWithBody(result.partPaths.endnotes, result, function(bodyReader, xml) {
  1377. if (xml) {
  1378. return notesReader.createEndnotesReader(bodyReader)(xml);
  1379. } else {
  1380. return new Result([]);
  1381. }
  1382. }),
  1383. comments: readXmlFileWithBody(result.partPaths.comments, result, function(bodyReader, xml) {
  1384. if (xml) {
  1385. return commentsReader.createCommentsReader(bodyReader)(xml);
  1386. } else {
  1387. return new Result([]);
  1388. }
  1389. })
  1390. };
  1391. }).also(function(result) {
  1392. return {
  1393. notes: result.footnotes.flatMap(function(footnotes) {
  1394. return result.endnotes.map(function(endnotes) {
  1395. return new documents.Notes(footnotes.concat(endnotes));
  1396. });
  1397. })
  1398. };
  1399. }).then(function(result) {
  1400. return readXmlFileWithBody(result.partPaths.mainDocument, result, function(bodyReader, xml) {
  1401. return result.notes.flatMap(function(notes) {
  1402. return result.comments.flatMap(function(comments) {
  1403. var reader = new DocumentXmlReader({
  1404. bodyReader: bodyReader,
  1405. notes: notes,
  1406. comments: comments
  1407. });
  1408. return reader.convertXmlToDocument(xml);
  1409. });
  1410. });
  1411. });
  1412. });
  1413. }
  1414. function findPartPaths(docxFile) {
  1415. return readPackageRelationships(docxFile).then(function(packageRelationships) {
  1416. var mainDocumentPath = findPartPath({
  1417. docxFile: docxFile,
  1418. relationships: packageRelationships,
  1419. relationshipType: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  1420. basePath: "",
  1421. fallbackPath: "word/document.xml"
  1422. });
  1423. if (!docxFile.exists(mainDocumentPath)) {
  1424. throw new Error("Could not find main document part. Are you sure this is a valid .docx file?");
  1425. }
  1426. return xmlFileReader({
  1427. filename: relationshipsFilename(mainDocumentPath),
  1428. readElement: relationshipsReader.readRelationships,
  1429. defaultValue: relationshipsReader.defaultValue
  1430. })(docxFile).then(function(documentRelationships) {
  1431. function findPartRelatedToMainDocument(name) {
  1432. return findPartPath({
  1433. docxFile: docxFile,
  1434. relationships: documentRelationships,
  1435. relationshipType: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/" + name,
  1436. basePath: zipfile.splitPath(mainDocumentPath).dirname,
  1437. fallbackPath: "word/" + name + ".xml"
  1438. });
  1439. }
  1440. return {
  1441. mainDocument: mainDocumentPath,
  1442. comments: findPartRelatedToMainDocument("comments"),
  1443. endnotes: findPartRelatedToMainDocument("endnotes"),
  1444. footnotes: findPartRelatedToMainDocument("footnotes"),
  1445. numbering: findPartRelatedToMainDocument("numbering"),
  1446. styles: findPartRelatedToMainDocument("styles")
  1447. };
  1448. });
  1449. });
  1450. }
  1451. function findPartPath(options) {
  1452. var docxFile = options.docxFile;
  1453. var relationships = options.relationships;
  1454. var relationshipType = options.relationshipType;
  1455. var basePath = options.basePath;
  1456. var fallbackPath = options.fallbackPath;
  1457. var targets = relationships.findTargetsByType(relationshipType);
  1458. var normalisedTargets = targets.map(function(target) {
  1459. return stripPrefix(zipfile.joinPath(basePath, target), "/");
  1460. });
  1461. var validTargets = normalisedTargets.filter(function(target) {
  1462. return docxFile.exists(target);
  1463. });
  1464. if (validTargets.length === 0) {
  1465. return fallbackPath;
  1466. } else {
  1467. return validTargets[0];
  1468. }
  1469. }
  1470. function stripPrefix(value, prefix) {
  1471. if (value.substring(0, prefix.length) === prefix) {
  1472. return value.substring(prefix.length);
  1473. } else {
  1474. return value;
  1475. }
  1476. }
  1477. function xmlFileReader(options) {
  1478. return function(zipFile) {
  1479. return readXmlFromZipFile(zipFile, options.filename)
  1480. .then(function(element) {
  1481. return element ? options.readElement(element) : options.defaultValue;
  1482. });
  1483. };
  1484. }
  1485. function readXmlFileWithBody(filename, options, func) {
  1486. var readRelationshipsFromZipFile = xmlFileReader({
  1487. filename: relationshipsFilename(filename),
  1488. readElement: relationshipsReader.readRelationships,
  1489. defaultValue: relationshipsReader.defaultValue
  1490. });
  1491. return readRelationshipsFromZipFile(options.docxFile).then(function(relationships) {
  1492. var bodyReader = new createBodyReader({
  1493. relationships: relationships,
  1494. contentTypes: options.contentTypes,
  1495. docxFile: options.docxFile,
  1496. numbering: options.numbering,
  1497. styles: options.styles,
  1498. files: options.files
  1499. });
  1500. return readXmlFromZipFile(options.docxFile, filename)
  1501. .then(function(xml) {
  1502. return func(bodyReader, xml);
  1503. });
  1504. });
  1505. }
  1506. function relationshipsFilename(filename) {
  1507. var split = zipfile.splitPath(filename);
  1508. return zipfile.joinPath(split.dirname, "_rels", split.basename + ".rels");
  1509. }
  1510. var readContentTypesFromZipFile = xmlFileReader({
  1511. filename: "[Content_Types].xml",
  1512. readElement: contentTypesReader.readContentTypesFromXml,
  1513. defaultValue: contentTypesReader.defaultContentTypes
  1514. });
  1515. function readNumberingFromZipFile(zipFile, path) {
  1516. return xmlFileReader({
  1517. filename: path,
  1518. readElement: numberingXml.readNumberingXml,
  1519. defaultValue: numberingXml.defaultNumbering
  1520. })(zipFile);
  1521. }
  1522. function readStylesFromZipFile(zipFile, path) {
  1523. return xmlFileReader({
  1524. filename: path,
  1525. readElement: stylesReader.readStylesXml,
  1526. defaultValue: stylesReader.defaultStyles
  1527. })(zipFile);
  1528. }
  1529. var readPackageRelationships = xmlFileReader({
  1530. filename: "_rels/.rels",
  1531. readElement: relationshipsReader.readRelationships,
  1532. defaultValue: relationshipsReader.defaultValue
  1533. });
  1534. },{"../documents":4,"../promises":23,"../results":24,"../zipfile":38,"./body-reader":5,"./comments-reader":6,"./content-types-reader":7,"./document-xml-reader":8,"./files":1,"./notes-reader":10,"./numbering-xml":11,"./office-xml-reader":12,"./relationships-reader":13,"./styles-reader":15,"path":136}],10:[function(require,module,exports){
  1535. var documents = require("../documents");
  1536. var Result = require("../results").Result;
  1537. exports.createFootnotesReader = createReader.bind(this, "footnote");
  1538. exports.createEndnotesReader = createReader.bind(this, "endnote");
  1539. function createReader(noteType, bodyReader) {
  1540. function readNotesXml(element) {
  1541. return Result.combine(element.getElementsByTagName("w:" + noteType)
  1542. .filter(isFootnoteElement)
  1543. .map(readFootnoteElement));
  1544. }
  1545. function isFootnoteElement(element) {
  1546. var type = element.attributes["w:type"];
  1547. return type !== "continuationSeparator" && type !== "separator";
  1548. }
  1549. function readFootnoteElement(footnoteElement) {
  1550. var id = footnoteElement.attributes["w:id"];
  1551. return bodyReader.readXmlElements(footnoteElement.children)
  1552. .map(function(body) {
  1553. return documents.Note({noteType: noteType, noteId: id, body: body});
  1554. });
  1555. }
  1556. return readNotesXml;
  1557. }
  1558. },{"../documents":4,"../results":24}],11:[function(require,module,exports){
  1559. exports.readNumberingXml = readNumberingXml;
  1560. exports.Numbering = Numbering;
  1561. exports.defaultNumbering = new Numbering({});
  1562. function Numbering(nums) {
  1563. return {
  1564. findLevel: function(numId, level) {
  1565. var num = nums[numId];
  1566. if (num) {
  1567. return num[level];
  1568. } else {
  1569. return null;
  1570. }
  1571. }
  1572. };
  1573. }
  1574. function readNumberingXml(root) {
  1575. var abstractNums = readAbstractNums(root);
  1576. var nums = readNums(root, abstractNums);
  1577. return new Numbering(nums);
  1578. }
  1579. function readAbstractNums(root) {
  1580. var abstractNums = {};
  1581. root.getElementsByTagName("w:abstractNum").forEach(function(element) {
  1582. var id = element.attributes["w:abstractNumId"];
  1583. abstractNums[id] = readAbstractNum(element);
  1584. });
  1585. return abstractNums;
  1586. }
  1587. function readAbstractNum(element) {
  1588. var levels = {};
  1589. element.getElementsByTagName("w:lvl").forEach(function(levelElement) {
  1590. var levelIndex = levelElement.attributes["w:ilvl"];
  1591. var numFmt = levelElement.first("w:numFmt").attributes["w:val"];
  1592. levels[levelIndex] = {
  1593. isOrdered: numFmt !== "bullet",
  1594. level: levelIndex
  1595. };
  1596. });
  1597. return levels;
  1598. }
  1599. function readNums(root, abstractNums) {
  1600. var nums = {};
  1601. root.getElementsByTagName("w:num").forEach(function(element) {
  1602. var id = element.attributes["w:numId"];
  1603. var abstractNumId = element.first("w:abstractNumId").attributes["w:val"];
  1604. nums[id] = abstractNums[abstractNumId];
  1605. });
  1606. return nums;
  1607. }
  1608. },{}],12:[function(require,module,exports){
  1609. var _ = require("underscore");
  1610. var promises = require("../promises");
  1611. var xml = require("../xml");
  1612. exports.read = read;
  1613. exports.readXmlFromZipFile = readXmlFromZipFile;
  1614. var xmlNamespaceMap = {
  1615. "http://schemas.openxmlformats.org/wordprocessingml/2006/main": "w",
  1616. "http://schemas.openxmlformats.org/officeDocument/2006/relationships": "r",
  1617. "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing": "wp",
  1618. "http://schemas.openxmlformats.org/drawingml/2006/main": "a",
  1619. "http://schemas.openxmlformats.org/drawingml/2006/picture": "pic",
  1620. "http://schemas.openxmlformats.org/package/2006/content-types": "content-types",
  1621. "urn:schemas-microsoft-com:vml": "v",
  1622. "http://schemas.openxmlformats.org/markup-compatibility/2006": "mc",
  1623. "urn:schemas-microsoft-com:office:word": "office-word"
  1624. };
  1625. function read(xmlString) {
  1626. return xml.readString(xmlString, xmlNamespaceMap)
  1627. .then(function(document) {
  1628. return collapseAlternateContent(document)[0];
  1629. });
  1630. }
  1631. function readXmlFromZipFile(docxFile, path) {
  1632. if (docxFile.exists(path)) {
  1633. return docxFile.read(path, "utf-8")
  1634. .then(stripUtf8Bom)
  1635. .then(read);
  1636. } else {
  1637. return promises.resolve(null);
  1638. }
  1639. }
  1640. function stripUtf8Bom(xmlString) {
  1641. return xmlString.replace(/^\uFEFF/g, '');
  1642. }
  1643. function collapseAlternateContent(node) {
  1644. if (node.type === "element") {
  1645. if (node.name === "mc:AlternateContent") {
  1646. return node.first("mc:Fallback").children;
  1647. } else {
  1648. node.children = _.flatten(node.children.map(collapseAlternateContent, true));
  1649. return [node];
  1650. }
  1651. } else {
  1652. return [node];
  1653. }
  1654. }
  1655. },{"../promises":23,"../xml":34,"underscore":153}],13:[function(require,module,exports){
  1656. exports.readRelationships = readRelationships;
  1657. exports.defaultValue = new Relationships([]);
  1658. exports.Relationships = Relationships;
  1659. function readRelationships(element) {
  1660. var relationships = [];
  1661. element.children.forEach(function(child) {
  1662. if (child.name === "{http://schemas.openxmlformats.org/package/2006/relationships}Relationship") {
  1663. var relationship = {
  1664. relationshipId: child.attributes.Id,
  1665. target: child.attributes.Target,
  1666. type: child.attributes.Type
  1667. };
  1668. relationships.push(relationship);
  1669. }
  1670. });
  1671. return new Relationships(relationships);
  1672. }
  1673. function Relationships(relationships) {
  1674. var targetsByRelationshipId = {};
  1675. relationships.forEach(function(relationship) {
  1676. targetsByRelationshipId[relationship.relationshipId] = relationship.target;
  1677. });
  1678. var targetsByType = {};
  1679. relationships.forEach(function(relationship) {
  1680. if (!targetsByType[relationship.type]) {
  1681. targetsByType[relationship.type] = [];
  1682. }
  1683. targetsByType[relationship.type].push(relationship.target);
  1684. });
  1685. return {
  1686. findTargetByRelationshipId: function(relationshipId) {
  1687. return targetsByRelationshipId[relationshipId];
  1688. },
  1689. findTargetsByType: function(type) {
  1690. return targetsByType[type] || [];
  1691. }
  1692. };
  1693. }
  1694. },{}],14:[function(require,module,exports){
  1695. var _ = require("underscore");
  1696. var promises = require("../promises");
  1697. var xml = require("../xml");
  1698. exports.writeStyleMap = writeStyleMap;
  1699. exports.readStyleMap = readStyleMap;
  1700. var schema = "http://schemas.zwobble.org/mammoth/style-map";
  1701. var styleMapPath = "mammoth/style-map";
  1702. var styleMapAbsolutePath = "/" + styleMapPath;
  1703. function writeStyleMap(docxFile, styleMap) {
  1704. docxFile.write(styleMapPath, styleMap);
  1705. return updateRelationships(docxFile).then(function() {
  1706. return updateContentTypes(docxFile);
  1707. });
  1708. }
  1709. function updateRelationships(docxFile) {
  1710. var path = "word/_rels/document.xml.rels";
  1711. var relationshipsUri = "http://schemas.openxmlformats.org/package/2006/relationships";
  1712. var relationshipElementName = "{" + relationshipsUri + "}Relationship";
  1713. return docxFile.read(path, "utf8")
  1714. .then(xml.readString)
  1715. .then(function(relationshipsContainer) {
  1716. var relationships = relationshipsContainer.children;
  1717. addOrUpdateElement(relationships, relationshipElementName, "Id", {
  1718. "Id": "rMammothStyleMap",
  1719. "Type": schema,
  1720. "Target": styleMapAbsolutePath
  1721. });
  1722. var namespaces = {"": relationshipsUri};
  1723. return docxFile.write(path, xml.writeString(relationshipsContainer, namespaces));
  1724. });
  1725. }
  1726. function updateContentTypes(docxFile) {
  1727. var path = "[Content_Types].xml";
  1728. var contentTypesUri = "http://schemas.openxmlformats.org/package/2006/content-types";
  1729. var overrideName = "{" + contentTypesUri + "}Override";
  1730. return docxFile.read(path, "utf8")
  1731. .then(xml.readString)
  1732. .then(function(typesElement) {
  1733. var children = typesElement.children;
  1734. addOrUpdateElement(children, overrideName, "PartName", {
  1735. "PartName": styleMapAbsolutePath,
  1736. "ContentType": "text/prs.mammoth.style-map"
  1737. });
  1738. var namespaces = {"": contentTypesUri};
  1739. return docxFile.write(path, xml.writeString(typesElement, namespaces));
  1740. });
  1741. }
  1742. function addOrUpdateElement(elements, name, identifyingAttribute, attributes) {
  1743. var existingElement = _.find(elements, function(element) {
  1744. return element.name === name &&
  1745. element.attributes[identifyingAttribute] === attributes[identifyingAttribute];
  1746. });
  1747. if (existingElement) {
  1748. existingElement.attributes = attributes;
  1749. } else {
  1750. elements.push(xml.element(name, attributes));
  1751. }
  1752. }
  1753. function readStyleMap(docxFile) {
  1754. if (docxFile.exists(styleMapPath)) {
  1755. return docxFile.read(styleMapPath, "utf8");
  1756. } else {
  1757. return promises.resolve(null);
  1758. }
  1759. }
  1760. },{"../promises":23,"../xml":34,"underscore":153}],15:[function(require,module,exports){
  1761. exports.readStylesXml = readStylesXml;
  1762. exports.Styles = Styles;
  1763. exports.defaultStyles = new Styles({}, {});
  1764. function Styles(paragraphStyles, characterStyles, tableStyles) {
  1765. return {
  1766. findParagraphStyleById: function(styleId) {
  1767. return paragraphStyles[styleId];
  1768. },
  1769. findCharacterStyleById: function(styleId) {
  1770. return characterStyles[styleId];
  1771. },
  1772. findTableStyleById: function(styleId) {
  1773. return tableStyles[styleId];
  1774. }
  1775. };
  1776. }
  1777. Styles.EMPTY = new Styles({}, {}, {});
  1778. function readStylesXml(root) {
  1779. var paragraphStyles = {};
  1780. var characterStyles = {};
  1781. var tableStyles = {};
  1782. var styles = {
  1783. "paragraph": paragraphStyles,
  1784. "character": characterStyles,
  1785. "table": tableStyles
  1786. };
  1787. root.getElementsByTagName("w:style").forEach(function(styleElement) {
  1788. var style = readStyleElement(styleElement);
  1789. var styleSet = styles[style.type];
  1790. if (styleSet) {
  1791. styleSet[style.styleId] = style;
  1792. }
  1793. });
  1794. return new Styles(paragraphStyles, characterStyles, tableStyles);
  1795. }
  1796. function readStyleElement(styleElement) {
  1797. var type = styleElement.attributes["w:type"];
  1798. var styleId = styleElement.attributes["w:styleId"];
  1799. var name = styleName(styleElement);
  1800. return {type: type, styleId: styleId, name: name};
  1801. }
  1802. function styleName(styleElement) {
  1803. var nameElement = styleElement.first("w:name");
  1804. return nameElement ? nameElement.attributes["w:val"] : null;
  1805. }
  1806. },{}],16:[function(require,module,exports){
  1807. exports.uriToZipEntryName = uriToZipEntryName;
  1808. exports.replaceFragment = replaceFragment;
  1809. function uriToZipEntryName(base, uri) {
  1810. if (uri.charAt(0) === "/") {
  1811. return uri.substr(1);
  1812. } else {
  1813. // In general, we should check first and second for trailing and leading slashes,
  1814. // but in our specific case this seems to be sufficient
  1815. return base + "/" + uri;
  1816. }
  1817. }
  1818. function replaceFragment(uri, fragment) {
  1819. var hashIndex = uri.indexOf("#");
  1820. if (hashIndex !== -1) {
  1821. uri = uri.substring(0, hashIndex);
  1822. }
  1823. return uri + "#" + fragment;
  1824. }
  1825. },{}],17:[function(require,module,exports){
  1826. var htmlPaths = require("../styles/html-paths");
  1827. function nonFreshElement(tagName, attributes, children) {
  1828. return elementWithTag(
  1829. htmlPaths.element(tagName, attributes, {fresh: false}),
  1830. children);
  1831. }
  1832. function freshElement(tagName, attributes, children) {
  1833. var tag = htmlPaths.element(tagName, attributes, {fresh: true});
  1834. return elementWithTag(tag, children);
  1835. }
  1836. function elementWithTag(tag, children) {
  1837. return {
  1838. type: "element",
  1839. tag: tag,
  1840. children: children || []
  1841. };
  1842. }
  1843. function text(value) {
  1844. return {
  1845. type: "text",
  1846. value: value
  1847. };
  1848. }
  1849. var forceWrite = {
  1850. type: "forceWrite"
  1851. };
  1852. exports.freshElement = freshElement;
  1853. exports.nonFreshElement = nonFreshElement;
  1854. exports.elementWithTag = elementWithTag;
  1855. exports.text = text;
  1856. exports.forceWrite = forceWrite;
  1857. var voidTagNames = {
  1858. "br": true,
  1859. "hr": true,
  1860. "img": true
  1861. };
  1862. function isVoidElement(node) {
  1863. return (node.children.length === 0) && voidTagNames[node.tag.tagName];
  1864. }
  1865. exports.isVoidElement = isVoidElement;
  1866. },{"../styles/html-paths":27}],18:[function(require,module,exports){
  1867. var ast = require("./ast");
  1868. exports.freshElement = ast.freshElement;
  1869. exports.nonFreshElement = ast.nonFreshElement;
  1870. exports.elementWithTag = ast.elementWithTag;
  1871. exports.text = ast.text;
  1872. exports.forceWrite = ast.forceWrite;
  1873. exports.simplify = require("./simplify");
  1874. function write(writer, nodes) {
  1875. nodes.forEach(function(node) {
  1876. writeNode(writer, node);
  1877. });
  1878. }
  1879. function writeNode(writer, node) {
  1880. toStrings[node.type](writer, node);
  1881. }
  1882. var toStrings = {
  1883. element: generateElementString,
  1884. text: generateTextString,
  1885. forceWrite: function() { }
  1886. };
  1887. function generateElementString(writer, node) {
  1888. if (ast.isVoidElement(node)) {
  1889. writer.selfClosing(node.tag.tagName, node.tag.attributes);
  1890. } else {
  1891. writer.open(node.tag.tagName, node.tag.attributes);
  1892. write(writer, node.children);
  1893. writer.close(node.tag.tagName);
  1894. }
  1895. }
  1896. function generateTextString(writer, node) {
  1897. writer.text(node.value);
  1898. }
  1899. exports.write = write;
  1900. },{"./ast":17,"./simplify":19}],19:[function(require,module,exports){
  1901. var _ = require("underscore");
  1902. var ast = require("./ast");
  1903. function simplify(nodes) {
  1904. return collapse(removeEmpty(nodes));
  1905. }
  1906. function collapse(nodes) {
  1907. var children = [];
  1908. nodes.map(collapseNode).forEach(function(child) {
  1909. appendChild(children, child);
  1910. });
  1911. return children;
  1912. }
  1913. function collapseNode(node) {
  1914. return collapsers[node.type](node);
  1915. }
  1916. var collapsers = {
  1917. element: collapseElement,
  1918. text: identity,
  1919. forceWrite: identity
  1920. };
  1921. function collapseElement(node) {
  1922. return ast.elementWithTag(node.tag, collapse(node.children));
  1923. }
  1924. function identity(value) {
  1925. return value;
  1926. }
  1927. function appendChild(children, child) {
  1928. var lastChild = children[children.length - 1];
  1929. if (child.type === "element" && !child.tag.fresh && lastChild && lastChild.type === "element" && child.tag.matchesElement(lastChild.tag)) {
  1930. if (child.tag.separator) {
  1931. appendChild(lastChild.children, ast.text(child.tag.separator));
  1932. }
  1933. child.children.forEach(function(grandChild) {
  1934. // Mutation is fine since simplifying elements create a copy of the children.
  1935. appendChild(lastChild.children, grandChild);
  1936. });
  1937. } else {
  1938. children.push(child);
  1939. }
  1940. }
  1941. function removeEmpty(nodes) {
  1942. return flatMap(nodes, function(node) {
  1943. return emptiers[node.type](node);
  1944. });
  1945. }
  1946. function flatMap(values, func) {
  1947. return _.flatten(_.map(values, func), true);
  1948. }
  1949. var emptiers = {
  1950. element: elementEmptier,
  1951. text: textEmptier,
  1952. forceWrite: neverEmpty
  1953. };
  1954. function neverEmpty(node) {
  1955. return [node];
  1956. }
  1957. function elementEmptier(element) {
  1958. var children = removeEmpty(element.children);
  1959. if (children.length === 0 && !ast.isVoidElement(element)) {
  1960. return [];
  1961. } else {
  1962. return [ast.elementWithTag(element.tag, children)];
  1963. }
  1964. }
  1965. function textEmptier(node) {
  1966. if (node.value.length === 0) {
  1967. return [];
  1968. } else {
  1969. return [node];
  1970. }
  1971. }
  1972. module.exports = simplify;
  1973. },{"./ast":17,"underscore":153}],20:[function(require,module,exports){
  1974. var _ = require("underscore");
  1975. var promises = require("./promises");
  1976. var Html = require("./html");
  1977. exports.imgElement = imgElement;
  1978. function imgElement(func) {
  1979. return function(element, messages) {
  1980. return promises.when(func(element)).then(function(result) {
  1981. var attributes = _.clone(result);
  1982. if (element.altText) {
  1983. attributes.alt = element.altText;
  1984. }
  1985. return [Html.freshElement("img", attributes)];
  1986. });
  1987. };
  1988. }
  1989. // Undocumented, but retained for backwards-compatibility with 0.3.x
  1990. exports.inline = exports.imgElement;
  1991. exports.dataUri = imgElement(function(element) {
  1992. return element.read("base64").then(function(imageBuffer) {
  1993. return {
  1994. src: "data:" + element.contentType + ";base64," + imageBuffer
  1995. };
  1996. });
  1997. });
  1998. },{"./html":18,"./promises":23,"underscore":153}],21:[function(require,module,exports){
  1999. var _ = require("underscore");
  2000. var docxReader = require("./docx/docx-reader");
  2001. var docxStyleMap = require("./docx/style-map");
  2002. var DocumentConverter = require("./document-to-html").DocumentConverter;
  2003. var readStyle = require("./style-reader").readStyle;
  2004. var readOptions = require("./options-reader").readOptions;
  2005. var unzip = require("./unzip");
  2006. var Result = require("./results").Result;
  2007. exports.convertToHtml = convertToHtml;
  2008. exports.convertToMarkdown = convertToMarkdown;
  2009. exports.convert = convert;
  2010. exports.extractRawText = extractRawText;
  2011. exports.images = require("./images");
  2012. exports.transforms = require("./transforms");
  2013. exports.underline = require("./underline");
  2014. exports.embedStyleMap = embedStyleMap;
  2015. exports.readEmbeddedStyleMap = readEmbeddedStyleMap;
  2016. function convertToHtml(input, options) {
  2017. return convert(input, options);
  2018. }
  2019. function convertToMarkdown(input, options) {
  2020. var markdownOptions = Object.create(options || {});
  2021. markdownOptions.outputFormat = "markdown";
  2022. return convert(input, markdownOptions);
  2023. }
  2024. function convert(input, options) {
  2025. options = readOptions(options);
  2026. return unzip.openZip(input)
  2027. .tap(function(docxFile) {
  2028. return docxStyleMap.readStyleMap(docxFile).then(function(styleMap) {
  2029. options.embeddedStyleMap = styleMap;
  2030. });
  2031. })
  2032. .then(function(docxFile) {
  2033. return docxReader.read(docxFile, input)
  2034. .then(function(documentResult) {
  2035. return documentResult.map(options.transformDocument);
  2036. })
  2037. .then(function(documentResult) {
  2038. return convertDocumentToHtml(documentResult, options);
  2039. });
  2040. });
  2041. }
  2042. function readEmbeddedStyleMap(input) {
  2043. return unzip.openZip(input)
  2044. .then(docxStyleMap.readStyleMap);
  2045. }
  2046. function convertDocumentToHtml(documentResult, options) {
  2047. var styleMapResult = parseStyleMap(options.readStyleMap());
  2048. var parsedOptions = _.extend({}, options, {
  2049. styleMap: styleMapResult.value
  2050. });
  2051. var documentConverter = new DocumentConverter(parsedOptions);
  2052. return documentResult.flatMapThen(function(document) {
  2053. return styleMapResult.flatMapThen(function(styleMap) {
  2054. return documentConverter.convertToHtml(document);
  2055. });
  2056. });
  2057. }
  2058. function parseStyleMap(styleMap) {
  2059. return Result.combine((styleMap || []).map(readStyle))
  2060. .map(function(styleMap) {
  2061. return styleMap.filter(function(styleMapping) {
  2062. return !!styleMapping;
  2063. });
  2064. });
  2065. }
  2066. function extractRawText(input) {
  2067. return unzip.openZip(input)
  2068. .then(docxReader.read)
  2069. .then(function(documentResult) {
  2070. return documentResult.map(convertElementToRawText);
  2071. });
  2072. }
  2073. function convertElementToRawText(element) {
  2074. if (element.type === "text") {
  2075. return element.value;
  2076. } else {
  2077. var tail = element.type === "paragraph" ? "\n\n" : "";
  2078. return (element.children || []).map(convertElementToRawText).join("") + tail;
  2079. }
  2080. }
  2081. function embedStyleMap(input, styleMap) {
  2082. return unzip.openZip(input)
  2083. .tap(function(docxFile) {
  2084. return docxStyleMap.writeStyleMap(docxFile, styleMap);
  2085. })
  2086. .then(function(docxFile) {
  2087. return {
  2088. toBuffer: docxFile.toBuffer
  2089. };
  2090. });
  2091. }
  2092. exports.styleMapping = function() {
  2093. throw new Error('Use a raw string instead of mammoth.styleMapping e.g. "p[style-name=\'Title\'] => h1" instead of mammoth.styleMapping("p[style-name=\'Title\'] => h1")');
  2094. };
  2095. },{"./document-to-html":3,"./docx/docx-reader":9,"./docx/style-map":14,"./images":20,"./options-reader":22,"./results":24,"./style-reader":25,"./transforms":29,"./underline":30,"./unzip":2,"underscore":153}],22:[function(require,module,exports){
  2096. exports.readOptions = readOptions;
  2097. var _ = require("underscore");
  2098. var defaultStyleMap = exports._defaultStyleMap = [
  2099. "p.Heading1 => h1:fresh",
  2100. "p.Heading2 => h2:fresh",
  2101. "p.Heading3 => h3:fresh",
  2102. "p.Heading4 => h4:fresh",
  2103. "p.Heading5 => h5:fresh",
  2104. "p.Heading6 => h6:fresh",
  2105. "p[style-name='Heading 1'] => h1:fresh",
  2106. "p[style-name='Heading 2'] => h2:fresh",
  2107. "p[style-name='Heading 3'] => h3:fresh",
  2108. "p[style-name='Heading 4'] => h4:fresh",
  2109. "p[style-name='Heading 5'] => h5:fresh",
  2110. "p[style-name='Heading 6'] => h6:fresh",
  2111. "p[style-name='heading 1'] => h1:fresh",
  2112. "p[style-name='heading 2'] => h2:fresh",
  2113. "p[style-name='heading 3'] => h3:fresh",
  2114. "p[style-name='heading 4'] => h4:fresh",
  2115. "p[style-name='heading 5'] => h5:fresh",
  2116. "p[style-name='heading 6'] => h6:fresh",
  2117. "r[style-name='Strong'] => strong",
  2118. "p[style-name='footnote text'] => p:fresh",
  2119. "r[style-name='footnote reference'] =>",
  2120. "p[style-name='endnote text'] => p:fresh",
  2121. "r[style-name='endnote reference'] =>",
  2122. "p[style-name='annotation text'] => p:fresh",
  2123. "r[style-name='annotation reference'] =>",
  2124. // LibreOffice
  2125. "p[style-name='Footnote'] => p:fresh",
  2126. "r[style-name='Footnote anchor'] =>",
  2127. "p[style-name='Endnote'] => p:fresh",
  2128. "r[style-name='Endnote anchor'] =>",
  2129. "p:unordered-list(1) => ul > li:fresh",
  2130. "p:unordered-list(2) => ul|ol > li > ul > li:fresh",
  2131. "p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh",
  2132. "p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
  2133. "p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
  2134. "p:ordered-list(1) => ol > li:fresh",
  2135. "p:ordered-list(2) => ul|ol > li > ol > li:fresh",
  2136. "p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh",
  2137. "p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
  2138. "p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
  2139. "r[style-name='Hyperlink'] =>",
  2140. "p[style-name='Normal'] => p:fresh"
  2141. ];
  2142. var standardOptions = exports._standardOptions = {
  2143. transformDocument: identity,
  2144. includeDefaultStyleMap: true,
  2145. includeEmbeddedStyleMap: true
  2146. };
  2147. function readOptions(options) {
  2148. options = options || {};
  2149. return _.extend({}, standardOptions, options, {
  2150. customStyleMap: readStyleMap(options.styleMap),
  2151. readStyleMap: function() {
  2152. var styleMap = this.customStyleMap;
  2153. if (this.includeEmbeddedStyleMap) {
  2154. styleMap = styleMap.concat(readStyleMap(this.embeddedStyleMap));
  2155. }
  2156. if (this.includeDefaultStyleMap) {
  2157. styleMap = styleMap.concat(defaultStyleMap);
  2158. }
  2159. return styleMap;
  2160. }
  2161. });
  2162. }
  2163. function readStyleMap(styleMap) {
  2164. if (!styleMap) {
  2165. return [];
  2166. } else if (_.isString(styleMap)) {
  2167. return styleMap.split("\n")
  2168. .map(function(line) {
  2169. return line.trim();
  2170. })
  2171. .filter(function(line) {
  2172. return line !== "" && line.charAt(0) !== "#";
  2173. });
  2174. } else {
  2175. return styleMap;
  2176. }
  2177. }
  2178. function identity(value) {
  2179. return value;
  2180. }
  2181. },{"underscore":153}],23:[function(require,module,exports){
  2182. var _ = require("underscore");
  2183. var bluebird = require("bluebird/js/release/promise")();
  2184. exports.defer = defer;
  2185. exports.when = bluebird.resolve;
  2186. exports.resolve = bluebird.resolve;
  2187. exports.all = bluebird.all;
  2188. exports.props = bluebird.props;
  2189. exports.reject = bluebird.reject;
  2190. exports.promisify = bluebird.promisify;
  2191. exports.mapSeries = bluebird.mapSeries;
  2192. exports.attempt = bluebird.attempt;
  2193. exports.nfcall = function(func) {
  2194. var args = Array.prototype.slice.call(arguments, 1);
  2195. var promisedFunc = bluebird.promisify(func);
  2196. return promisedFunc.apply(null, args);
  2197. };
  2198. bluebird.prototype.fail = bluebird.prototype.caught;
  2199. bluebird.prototype.also = function(func) {
  2200. return this.then(function(value) {
  2201. var returnValue = _.extend({}, value, func(value));
  2202. return bluebird.props(returnValue);
  2203. });
  2204. };
  2205. function defer() {
  2206. var resolve;
  2207. var reject;
  2208. var promise = new bluebird.Promise(function(resolveArg, rejectArg) {
  2209. resolve = resolveArg;
  2210. reject = rejectArg;
  2211. });
  2212. return {
  2213. resolve: resolve,
  2214. reject: reject,
  2215. promise: promise
  2216. };
  2217. }
  2218. },{"bluebird/js/release/promise":60,"underscore":153}],24:[function(require,module,exports){
  2219. var _ = require("underscore");
  2220. exports.Result = Result;
  2221. exports.success = success;
  2222. exports.warning = warning;
  2223. exports.error = error;
  2224. function Result(value, messages) {
  2225. this.value = value;
  2226. this.messages = messages || [];
  2227. }
  2228. Result.prototype.map = function(func) {
  2229. return new Result(func(this.value), this.messages);
  2230. };
  2231. Result.prototype.flatMap = function(func) {
  2232. var funcResult = func(this.value);
  2233. return new Result(funcResult.value, combineMessages([this, funcResult]));
  2234. };
  2235. Result.prototype.flatMapThen = function(func) {
  2236. var that = this;
  2237. return func(this.value).then(function(otherResult) {
  2238. return new Result(otherResult.value, combineMessages([that, otherResult]));
  2239. });
  2240. };
  2241. Result.combine = function(results) {
  2242. var values = _.flatten(_.pluck(results, "value"));
  2243. var messages = combineMessages(results);
  2244. return new Result(values, messages);
  2245. };
  2246. function success(value) {
  2247. return new Result(value, []);
  2248. }
  2249. function warning(message) {
  2250. return {
  2251. type: "warning",
  2252. message: message
  2253. };
  2254. }
  2255. function error(exception) {
  2256. return {
  2257. type: "error",
  2258. message: exception.message,
  2259. error: exception
  2260. };
  2261. }
  2262. function combineMessages(results) {
  2263. var messages = [];
  2264. _.flatten(_.pluck(results, "messages"), true).forEach(function(message) {
  2265. if (!containsMessage(messages, message)) {
  2266. messages.push(message);
  2267. }
  2268. });
  2269. return messages;
  2270. }
  2271. function containsMessage(messages, message) {
  2272. return _.find(messages, isSameMessage.bind(null, message)) !== undefined;
  2273. }
  2274. function isSameMessage(first, second) {
  2275. return first.type === second.type && first.message === second.message;
  2276. }
  2277. },{"underscore":153}],25:[function(require,module,exports){
  2278. var _ = require("underscore");
  2279. var lop = require("lop");
  2280. var documentMatchers = require("./styles/document-matchers");
  2281. var htmlPaths = require("./styles/html-paths");
  2282. var tokenise = require("./styles/parser/tokeniser").tokenise;
  2283. var results = require("./results");
  2284. exports.readHtmlPath = readHtmlPath;
  2285. exports.readDocumentMatcher = readDocumentMatcher;
  2286. exports.readStyle = readStyle;
  2287. function readStyle(string) {
  2288. return parseString(styleRule, string);
  2289. }
  2290. function createStyleRule() {
  2291. return lop.rules.sequence(
  2292. lop.rules.sequence.capture(documentMatcherRule()),
  2293. lop.rules.tokenOfType("whitespace"),
  2294. lop.rules.tokenOfType("arrow"),
  2295. lop.rules.sequence.capture(lop.rules.optional(lop.rules.sequence(
  2296. lop.rules.tokenOfType("whitespace"),
  2297. lop.rules.sequence.capture(htmlPathRule())
  2298. ).head())),
  2299. lop.rules.tokenOfType("end")
  2300. ).map(function(documentMatcher, htmlPath) {
  2301. return {
  2302. from: documentMatcher,
  2303. to: htmlPath.valueOrElse(htmlPaths.empty)
  2304. };
  2305. });
  2306. }
  2307. function readDocumentMatcher(string) {
  2308. return parseString(documentMatcherRule(), string);
  2309. }
  2310. function documentMatcherRule() {
  2311. var sequence = lop.rules.sequence;
  2312. var identifierToConstant = function(identifier, constant) {
  2313. return lop.rules.then(
  2314. lop.rules.token("identifier", identifier),
  2315. function() {
  2316. return constant;
  2317. }
  2318. );
  2319. };
  2320. var paragraphRule = identifierToConstant("p", documentMatchers.paragraph);
  2321. var runRule = identifierToConstant("r", documentMatchers.run);
  2322. var elementTypeRule = lop.rules.firstOf("p or r or table",
  2323. paragraphRule,
  2324. runRule
  2325. );
  2326. var styleIdRule = lop.rules.then(
  2327. classRule,
  2328. function(styleId) {
  2329. return {styleId: styleId};
  2330. }
  2331. );
  2332. var styleNameMatcherRule = lop.rules.firstOf("style name matcher",
  2333. lop.rules.then(
  2334. lop.rules.sequence(
  2335. lop.rules.tokenOfType("equals"),
  2336. lop.rules.sequence.cut(),
  2337. lop.rules.sequence.capture(stringRule)
  2338. ).head(),
  2339. function(styleName) {
  2340. return {styleName: documentMatchers.equalTo(styleName)};
  2341. }
  2342. ),
  2343. lop.rules.then(
  2344. lop.rules.sequence(
  2345. lop.rules.tokenOfType("startsWith"),
  2346. lop.rules.sequence.cut(),
  2347. lop.rules.sequence.capture(stringRule)
  2348. ).head(),
  2349. function(styleName) {
  2350. return {styleName: documentMatchers.startsWith(styleName)};
  2351. }
  2352. )
  2353. );
  2354. var styleNameRule = lop.rules.sequence(
  2355. lop.rules.tokenOfType("open-square-bracket"),
  2356. lop.rules.sequence.cut(),
  2357. lop.rules.token("identifier", "style-name"),
  2358. lop.rules.sequence.capture(styleNameMatcherRule),
  2359. lop.rules.tokenOfType("close-square-bracket")
  2360. ).head();
  2361. var listTypeRule = lop.rules.firstOf("list type",
  2362. identifierToConstant("ordered-list", {isOrdered: true}),
  2363. identifierToConstant("unordered-list", {isOrdered: false})
  2364. );
  2365. var listRule = sequence(
  2366. lop.rules.tokenOfType("colon"),
  2367. sequence.capture(listTypeRule),
  2368. sequence.cut(),
  2369. lop.rules.tokenOfType("open-paren"),
  2370. sequence.capture(integerRule),
  2371. lop.rules.tokenOfType("close-paren")
  2372. ).map(function(listType, levelNumber) {
  2373. return {
  2374. list: {
  2375. isOrdered: listType.isOrdered,
  2376. levelIndex: levelNumber - 1
  2377. }
  2378. };
  2379. });
  2380. function createMatcherSuffixesRule(rules) {
  2381. var matcherSuffix = lop.rules.firstOf.apply(
  2382. lop.rules.firstOf,
  2383. ["matcher suffix"].concat(rules)
  2384. );
  2385. var matcherSuffixes = lop.rules.zeroOrMore(matcherSuffix);
  2386. return lop.rules.then(matcherSuffixes, function(suffixes) {
  2387. var matcherOptions = {};
  2388. suffixes.forEach(function(suffix) {
  2389. _.extend(matcherOptions, suffix);
  2390. });
  2391. return matcherOptions;
  2392. });
  2393. }
  2394. var paragraphOrRun = sequence(
  2395. sequence.capture(elementTypeRule),
  2396. sequence.capture(createMatcherSuffixesRule([
  2397. styleIdRule,
  2398. styleNameRule,
  2399. listRule
  2400. ]))
  2401. ).map(function(createMatcher, matcherOptions) {
  2402. return createMatcher(matcherOptions);
  2403. });
  2404. var table = sequence(
  2405. lop.rules.token("identifier", "table"),
  2406. sequence.capture(createMatcherSuffixesRule([
  2407. styleIdRule,
  2408. styleNameRule
  2409. ]))
  2410. ).map(function(options) {
  2411. return documentMatchers.table(options);
  2412. });
  2413. var bold = identifierToConstant("b", documentMatchers.bold);
  2414. var italic = identifierToConstant("i", documentMatchers.italic);
  2415. var underline = identifierToConstant("u", documentMatchers.underline);
  2416. var strikethrough = identifierToConstant("strike", documentMatchers.strikethrough);
  2417. var smallCaps = identifierToConstant("small-caps", documentMatchers.smallCaps);
  2418. var commentReference = identifierToConstant("comment-reference", documentMatchers.commentReference);
  2419. var breakMatcher = sequence(
  2420. lop.rules.token("identifier", "br"),
  2421. sequence.cut(),
  2422. lop.rules.tokenOfType("open-square-bracket"),
  2423. lop.rules.token("identifier", "type"),
  2424. lop.rules.tokenOfType("equals"),
  2425. sequence.capture(stringRule),
  2426. lop.rules.tokenOfType("close-square-bracket")
  2427. ).map(function(breakType) {
  2428. switch (breakType) {
  2429. case "line":
  2430. return documentMatchers.lineBreak;
  2431. case "page":
  2432. return documentMatchers.pageBreak;
  2433. case "column":
  2434. return documentMatchers.columnBreak;
  2435. default:
  2436. // TODO: handle unknown document matchers
  2437. }
  2438. });
  2439. return lop.rules.firstOf("element type",
  2440. paragraphOrRun,
  2441. table,
  2442. bold,
  2443. italic,
  2444. underline,
  2445. strikethrough,
  2446. smallCaps,
  2447. commentReference,
  2448. breakMatcher
  2449. );
  2450. }
  2451. function readHtmlPath(string) {
  2452. return parseString(htmlPathRule(), string);
  2453. }
  2454. function htmlPathRule() {
  2455. var capture = lop.rules.sequence.capture;
  2456. var whitespaceRule = lop.rules.tokenOfType("whitespace");
  2457. var freshRule = lop.rules.then(
  2458. lop.rules.optional(lop.rules.sequence(
  2459. lop.rules.tokenOfType("colon"),
  2460. lop.rules.token("identifier", "fresh")
  2461. )),
  2462. function(option) {
  2463. return option.map(function() {
  2464. return true;
  2465. }).valueOrElse(false);
  2466. }
  2467. );
  2468. var separatorRule = lop.rules.then(
  2469. lop.rules.optional(lop.rules.sequence(
  2470. lop.rules.tokenOfType("colon"),
  2471. lop.rules.token("identifier", "separator"),
  2472. lop.rules.tokenOfType("open-paren"),
  2473. capture(stringRule),
  2474. lop.rules.tokenOfType("close-paren")
  2475. ).head()),
  2476. function(option) {
  2477. return option.valueOrElse("");
  2478. }
  2479. );
  2480. var tagNamesRule = lop.rules.oneOrMoreWithSeparator(
  2481. identifierRule,
  2482. lop.rules.tokenOfType("choice")
  2483. );
  2484. var styleElementRule = lop.rules.sequence(
  2485. capture(tagNamesRule),
  2486. capture(lop.rules.zeroOrMore(classRule)),
  2487. capture(freshRule),
  2488. capture(separatorRule)
  2489. ).map(function(tagName, classNames, fresh, separator) {
  2490. var attributes = {};
  2491. var options = {};
  2492. if (classNames.length > 0) {
  2493. attributes["class"] = classNames.join(" ");
  2494. }
  2495. if (fresh) {
  2496. options.fresh = true;
  2497. }
  2498. if (separator) {
  2499. options.separator = separator;
  2500. }
  2501. return htmlPaths.element(tagName, attributes, options);
  2502. });
  2503. return lop.rules.firstOf("html path",
  2504. lop.rules.then(lop.rules.tokenOfType("bang"), function() {
  2505. return htmlPaths.ignore;
  2506. }),
  2507. lop.rules.then(
  2508. lop.rules.zeroOrMoreWithSeparator(
  2509. styleElementRule,
  2510. lop.rules.sequence(
  2511. whitespaceRule,
  2512. lop.rules.tokenOfType("gt"),
  2513. whitespaceRule
  2514. )
  2515. ),
  2516. htmlPaths.elements
  2517. )
  2518. );
  2519. }
  2520. var identifierRule = lop.rules.then(
  2521. lop.rules.tokenOfType("identifier"),
  2522. decodeEscapeSequences
  2523. );
  2524. var integerRule = lop.rules.tokenOfType("integer");
  2525. var stringRule = lop.rules.then(
  2526. lop.rules.tokenOfType("string"),
  2527. decodeEscapeSequences
  2528. );
  2529. var escapeSequences = {
  2530. "n": "\n",
  2531. "r": "\r",
  2532. "t": "\t"
  2533. };
  2534. function decodeEscapeSequences(value) {
  2535. return value.replace(/\\(.)/g, function(match, code) {
  2536. return escapeSequences[code] || code;
  2537. });
  2538. }
  2539. var classRule = lop.rules.sequence(
  2540. lop.rules.tokenOfType("dot"),
  2541. lop.rules.sequence.cut(),
  2542. lop.rules.sequence.capture(identifierRule)
  2543. ).head();
  2544. function parseString(rule, string) {
  2545. var tokens = tokenise(string);
  2546. var parser = lop.Parser();
  2547. var parseResult = parser.parseTokens(rule, tokens);
  2548. if (parseResult.isSuccess()) {
  2549. return results.success(parseResult.value());
  2550. } else {
  2551. return new results.Result(null, [results.warning(describeFailure(string, parseResult))]);
  2552. }
  2553. }
  2554. function describeFailure(input, parseResult) {
  2555. return "Did not understand this style mapping, so ignored it: " + input + "\n" +
  2556. parseResult.errors().map(describeError).join("\n");
  2557. }
  2558. function describeError(error) {
  2559. return "Error was at character number " + error.characterNumber() + ": " +
  2560. "Expected " + error.expected + " but got " + error.actual;
  2561. }
  2562. var styleRule = createStyleRule();
  2563. },{"./results":24,"./styles/document-matchers":26,"./styles/html-paths":27,"./styles/parser/tokeniser":28,"lop":107,"underscore":153}],26:[function(require,module,exports){
  2564. exports.paragraph = paragraph;
  2565. exports.run = run;
  2566. exports.table = table;
  2567. exports.bold = new Matcher("bold");
  2568. exports.italic = new Matcher("italic");
  2569. exports.underline = new Matcher("underline");
  2570. exports.strikethrough = new Matcher("strikethrough");
  2571. exports.smallCaps = new Matcher("smallCaps");
  2572. exports.commentReference = new Matcher("commentReference");
  2573. exports.lineBreak = new Matcher("break", {breakType: "line"});
  2574. exports.pageBreak = new Matcher("break", {breakType: "page"});
  2575. exports.columnBreak = new Matcher("break", {breakType: "column"});
  2576. exports.equalTo = equalTo;
  2577. exports.startsWith = startsWith;
  2578. function paragraph(options) {
  2579. return new Matcher("paragraph", options);
  2580. }
  2581. function run(options) {
  2582. return new Matcher("run", options);
  2583. }
  2584. function table(options) {
  2585. return new Matcher("table", options);
  2586. }
  2587. function Matcher(elementType, options) {
  2588. options = options || {};
  2589. this._elementType = elementType;
  2590. this._styleId = options.styleId;
  2591. this._styleName = options.styleName;
  2592. if (options.list) {
  2593. this._listIndex = options.list.levelIndex;
  2594. this._listIsOrdered = options.list.isOrdered;
  2595. }
  2596. }
  2597. Matcher.prototype.matches = function(element) {
  2598. return element.type === this._elementType &&
  2599. (this._styleId === undefined || element.styleId === this._styleId) &&
  2600. (this._styleName === undefined || (element.styleName && this._styleName.operator(this._styleName.operand, element.styleName))) &&
  2601. (this._listIndex === undefined || isList(element, this._listIndex, this._listIsOrdered)) &&
  2602. (this._breakType === undefined || this._breakType === element.breakType);
  2603. };
  2604. function isList(element, levelIndex, isOrdered) {
  2605. return element.numbering &&
  2606. element.numbering.level == levelIndex &&
  2607. element.numbering.isOrdered == isOrdered;
  2608. }
  2609. function equalTo(value) {
  2610. return {
  2611. operator: operatorEqualTo,
  2612. operand: value
  2613. };
  2614. }
  2615. function startsWith(value) {
  2616. return {
  2617. operator: operatorStartsWith,
  2618. operand: value
  2619. };
  2620. }
  2621. function operatorEqualTo(first, second) {
  2622. return first.toUpperCase() === second.toUpperCase();
  2623. }
  2624. function operatorStartsWith(first, second) {
  2625. return second.toUpperCase().indexOf(first.toUpperCase()) === 0;
  2626. }
  2627. },{}],27:[function(require,module,exports){
  2628. var _ = require("underscore");
  2629. var html = require("../html");
  2630. exports.topLevelElement = topLevelElement;
  2631. exports.elements = elements;
  2632. exports.element = element;
  2633. function topLevelElement(tagName, attributes) {
  2634. return elements([element(tagName, attributes, {fresh: true})]);
  2635. }
  2636. function elements(elementStyles) {
  2637. return new HtmlPath(elementStyles.map(function(elementStyle) {
  2638. if (_.isString(elementStyle)) {
  2639. return element(elementStyle);
  2640. } else {
  2641. return elementStyle;
  2642. }
  2643. }));
  2644. }
  2645. function HtmlPath(elements) {
  2646. this._elements = elements;
  2647. }
  2648. HtmlPath.prototype.wrap = function wrap(children) {
  2649. var result = children();
  2650. for (var index = this._elements.length - 1; index >= 0; index--) {
  2651. result = this._elements[index].wrapNodes(result);
  2652. }
  2653. return result;
  2654. };
  2655. function element(tagName, attributes, options) {
  2656. options = options || {};
  2657. return new Element(tagName, attributes, options);
  2658. }
  2659. function Element(tagName, attributes, options) {
  2660. var tagNames = {};
  2661. if (_.isArray(tagName)) {
  2662. tagName.forEach(function(tagName) {
  2663. tagNames[tagName] = true;
  2664. });
  2665. tagName = tagName[0];
  2666. } else {
  2667. tagNames[tagName] = true;
  2668. }
  2669. this.tagName = tagName;
  2670. this.tagNames = tagNames;
  2671. this.attributes = attributes || {};
  2672. this.fresh = options.fresh;
  2673. this.separator = options.separator;
  2674. }
  2675. Element.prototype.matchesElement = function(element) {
  2676. return this.tagNames[element.tagName] && _.isEqual(this.attributes || {}, element.attributes || {});
  2677. };
  2678. Element.prototype.wrap = function wrap(generateNodes) {
  2679. return this.wrapNodes(generateNodes());
  2680. };
  2681. Element.prototype.wrapNodes = function wrapNodes(nodes) {
  2682. return [html.elementWithTag(this, nodes)];
  2683. };
  2684. exports.empty = elements([]);
  2685. exports.ignore = {
  2686. wrap: function() {
  2687. return [];
  2688. }
  2689. };
  2690. },{"../html":18,"underscore":153}],28:[function(require,module,exports){
  2691. var lop = require("lop");
  2692. var RegexTokeniser = lop.RegexTokeniser;
  2693. exports.tokenise = tokenise;
  2694. var stringPrefix = "'((?:\\\\.|[^'])*)";
  2695. function tokenise(string) {
  2696. var identifierCharacter = "(?:[a-zA-Z\\-_]|\\\\.)";
  2697. var tokeniser = new RegexTokeniser([
  2698. {name: "identifier", regex: new RegExp("(" + identifierCharacter + "(?:" + identifierCharacter + "|[0-9])*)")},
  2699. {name: "dot", regex: /\./},
  2700. {name: "colon", regex: /:/},
  2701. {name: "gt", regex: />/},
  2702. {name: "whitespace", regex: /\s+/},
  2703. {name: "arrow", regex: /=>/},
  2704. {name: "equals", regex: /=/},
  2705. {name: "startsWith", regex: /\^=/},
  2706. {name: "open-paren", regex: /\(/},
  2707. {name: "close-paren", regex: /\)/},
  2708. {name: "open-square-bracket", regex: /\[/},
  2709. {name: "close-square-bracket", regex: /\]/},
  2710. {name: "string", regex: new RegExp(stringPrefix + "'")},
  2711. {name: "unterminated-string", regex: new RegExp(stringPrefix)},
  2712. {name: "integer", regex: /([0-9]+)/},
  2713. {name: "choice", regex: /\|/},
  2714. {name: "bang", regex: /(!)/}
  2715. ]);
  2716. return tokeniser.tokenise(string);
  2717. }
  2718. },{"lop":107}],29:[function(require,module,exports){
  2719. var _ = require("underscore");
  2720. exports.paragraph = paragraph;
  2721. exports.run = run;
  2722. exports._elements = elements;
  2723. exports.getDescendantsOfType = getDescendantsOfType;
  2724. exports.getDescendants = getDescendants;
  2725. function paragraph(transform) {
  2726. return elementsOfType("paragraph", transform);
  2727. }
  2728. function run(transform) {
  2729. return elementsOfType("run", transform);
  2730. }
  2731. function elementsOfType(elementType, transform) {
  2732. return elements(function(element) {
  2733. if (element.type === elementType) {
  2734. return transform(element);
  2735. } else {
  2736. return element;
  2737. }
  2738. });
  2739. }
  2740. function elements(transform) {
  2741. return function transformElement(element) {
  2742. if (element.children) {
  2743. var children = _.map(element.children, transformElement);
  2744. element = _.extend(element, {children: children});
  2745. }
  2746. return transform(element);
  2747. };
  2748. }
  2749. function getDescendantsOfType(element, type) {
  2750. return getDescendants(element).filter(function(descendant) {
  2751. return descendant.type === type;
  2752. });
  2753. }
  2754. function getDescendants(element) {
  2755. var descendants = [];
  2756. visitDescendants(element, function(descendant) {
  2757. descendants.push(descendant);
  2758. });
  2759. return descendants;
  2760. }
  2761. function visitDescendants(element, visit) {
  2762. if (element.children) {
  2763. element.children.forEach(function(child) {
  2764. visitDescendants(child, visit);
  2765. visit(child);
  2766. });
  2767. }
  2768. }
  2769. },{"underscore":153}],30:[function(require,module,exports){
  2770. var htmlPaths = require("./styles/html-paths");
  2771. var Html = require("./html");
  2772. exports.element = element;
  2773. function element(name) {
  2774. return function(html) {
  2775. return Html.elementWithTag(htmlPaths.element(name), [html]);
  2776. };
  2777. }
  2778. },{"./html":18,"./styles/html-paths":27}],31:[function(require,module,exports){
  2779. var util = require("util");
  2780. var _ = require("underscore");
  2781. exports.writer = writer;
  2782. function writer(options) {
  2783. options = options || {};
  2784. if (options.prettyPrint) {
  2785. return prettyWriter();
  2786. } else {
  2787. return simpleWriter();
  2788. }
  2789. }
  2790. var indentedElements = {
  2791. div: true,
  2792. p: true,
  2793. ul: true,
  2794. li: true
  2795. };
  2796. function prettyWriter() {
  2797. var indentationLevel = 0;
  2798. var indentation = " ";
  2799. var stack = [];
  2800. var start = true;
  2801. var inText = false;
  2802. var writer = simpleWriter();
  2803. function open(tagName, attributes) {
  2804. if (indentedElements[tagName]) {
  2805. indent();
  2806. }
  2807. stack.push(tagName);
  2808. writer.open(tagName, attributes);
  2809. if (indentedElements[tagName]) {
  2810. indentationLevel++;
  2811. }
  2812. start = false;
  2813. }
  2814. function close(tagName) {
  2815. if (indentedElements[tagName]) {
  2816. indentationLevel--;
  2817. indent();
  2818. }
  2819. stack.pop();
  2820. writer.close(tagName);
  2821. }
  2822. function text(value) {
  2823. startText();
  2824. var text = isInPre() ? value : value.replace("\n", "\n" + indentation);
  2825. writer.text(text);
  2826. }
  2827. function selfClosing(tagName, attributes) {
  2828. indent();
  2829. writer.selfClosing(tagName, attributes);
  2830. }
  2831. function insideIndentedElement() {
  2832. return stack.length === 0 || indentedElements[stack[stack.length - 1]];
  2833. }
  2834. function startText() {
  2835. if (!inText) {
  2836. indent();
  2837. inText = true;
  2838. }
  2839. }
  2840. function indent() {
  2841. inText = false;
  2842. if (!start && insideIndentedElement() && !isInPre()) {
  2843. writer._append("\n");
  2844. for (var i = 0; i < indentationLevel; i++) {
  2845. writer._append(indentation);
  2846. }
  2847. }
  2848. }
  2849. function isInPre() {
  2850. return _.some(stack, function(tagName) {
  2851. return tagName === "pre";
  2852. });
  2853. }
  2854. return {
  2855. asString: writer.asString,
  2856. open: open,
  2857. close: close,
  2858. text: text,
  2859. selfClosing: selfClosing
  2860. };
  2861. }
  2862. function simpleWriter() {
  2863. var fragments = [];
  2864. function open(tagName, attributes) {
  2865. var attributeString = generateAttributeString(attributes);
  2866. fragments.push(util.format("<%s%s>", tagName, attributeString));
  2867. }
  2868. function close(tagName) {
  2869. fragments.push(util.format("</%s>", tagName));
  2870. }
  2871. function selfClosing(tagName, attributes) {
  2872. var attributeString = generateAttributeString(attributes);
  2873. fragments.push(util.format("<%s%s />", tagName, attributeString));
  2874. }
  2875. function generateAttributeString(attributes) {
  2876. return _.map(attributes, function(value, key) {
  2877. return util.format(' %s="%s"', key, escapeHtmlAttribute(value));
  2878. }).join("");
  2879. }
  2880. function text(value) {
  2881. fragments.push(escapeHtmlText(value));
  2882. }
  2883. function append(html) {
  2884. fragments.push(html);
  2885. }
  2886. function asString() {
  2887. return fragments.join("");
  2888. }
  2889. return {
  2890. asString: asString,
  2891. open: open,
  2892. close: close,
  2893. text: text,
  2894. selfClosing: selfClosing,
  2895. _append: append
  2896. };
  2897. }
  2898. function escapeHtmlText(value) {
  2899. return value
  2900. .replace(/&/g, '&amp;')
  2901. .replace(/</g, '&lt;')
  2902. .replace(/>/g, '&gt;');
  2903. }
  2904. function escapeHtmlAttribute(value) {
  2905. return value
  2906. .replace(/&/g, '&amp;')
  2907. .replace(/"/g, '&quot;')
  2908. .replace(/</g, '&lt;')
  2909. .replace(/>/g, '&gt;');
  2910. }
  2911. },{"underscore":153,"util":157}],32:[function(require,module,exports){
  2912. var htmlWriter = require("./html-writer");
  2913. var markdownWriter = require("./markdown-writer");
  2914. exports.writer = writer;
  2915. function writer(options) {
  2916. options = options || {};
  2917. if (options.outputFormat === "markdown") {
  2918. return markdownWriter.writer();
  2919. } else {
  2920. return htmlWriter.writer(options);
  2921. }
  2922. }
  2923. },{"./html-writer":31,"./markdown-writer":33}],33:[function(require,module,exports){
  2924. var _ = require("underscore");
  2925. function symmetricMarkdownElement(end) {
  2926. return markdownElement(end, end);
  2927. }
  2928. function markdownElement(start, end) {
  2929. return function() {
  2930. return {start: start, end: end};
  2931. };
  2932. }
  2933. function markdownLink(attributes) {
  2934. var href = attributes.href || "";
  2935. if (href) {
  2936. return {
  2937. start: "[",
  2938. end: "](" + href + ")",
  2939. anchorPosition: "before"
  2940. };
  2941. } else {
  2942. return {};
  2943. }
  2944. }
  2945. function markdownImage(attributes) {
  2946. var src = attributes.src || "";
  2947. var altText = attributes.alt || "";
  2948. if (src || altText) {
  2949. return {start: "![" + altText + "](" + src + ")"};
  2950. } else {
  2951. return {};
  2952. }
  2953. }
  2954. function markdownList(options) {
  2955. return function(attributes, list) {
  2956. return {
  2957. start: list ? "\n" : "",
  2958. end: list ? "" : "\n",
  2959. list: {
  2960. isOrdered: options.isOrdered,
  2961. indent: list ? list.indent + 1 : 0,
  2962. count: 0
  2963. }
  2964. };
  2965. };
  2966. }
  2967. function markdownListItem(attributes, list, listItem) {
  2968. list = list || {indent: 0, isOrdered: false, count: 0};
  2969. list.count++;
  2970. listItem.hasClosed = false;
  2971. var bullet = list.isOrdered ? list.count + "." : "-";
  2972. var start = repeatString("\t", list.indent) + bullet + " ";
  2973. return {
  2974. start: start,
  2975. end: function() {
  2976. if (!listItem.hasClosed) {
  2977. listItem.hasClosed = true;
  2978. return "\n";
  2979. }
  2980. }
  2981. };
  2982. }
  2983. var htmlToMarkdown = {
  2984. "p": markdownElement("", "\n\n"),
  2985. "br": markdownElement("", " \n"),
  2986. "ul": markdownList({isOrdered: false}),
  2987. "ol": markdownList({isOrdered: true}),
  2988. "li": markdownListItem,
  2989. "strong": symmetricMarkdownElement("__"),
  2990. "em": symmetricMarkdownElement("*"),
  2991. "a": markdownLink,
  2992. "img": markdownImage
  2993. };
  2994. (function() {
  2995. for (var i = 1; i <= 6; i++) {
  2996. htmlToMarkdown["h" + i] = markdownElement(repeatString("#", i) + " ", "\n\n");
  2997. }
  2998. })();
  2999. function repeatString(value, count) {
  3000. return new Array(count + 1).join(value);
  3001. }
  3002. function markdownWriter() {
  3003. var fragments = [];
  3004. var elementStack = [];
  3005. var list = null;
  3006. var listItem = {};
  3007. function open(tagName, attributes) {
  3008. attributes = attributes || {};
  3009. var createElement = htmlToMarkdown[tagName] || function() {
  3010. return {};
  3011. };
  3012. var element = createElement(attributes, list, listItem);
  3013. elementStack.push({end: element.end, list: list});
  3014. if (element.list) {
  3015. list = element.list;
  3016. }
  3017. var anchorBeforeStart = element.anchorPosition === "before";
  3018. if (anchorBeforeStart) {
  3019. writeAnchor(attributes);
  3020. }
  3021. fragments.push(element.start || "");
  3022. if (!anchorBeforeStart) {
  3023. writeAnchor(attributes);
  3024. }
  3025. }
  3026. function writeAnchor(attributes) {
  3027. if (attributes.id) {
  3028. fragments.push('<a id="' + attributes.id + '"></a>');
  3029. }
  3030. }
  3031. function close(tagName) {
  3032. var element = elementStack.pop();
  3033. list = element.list;
  3034. var end = _.isFunction(element.end) ? element.end() : element.end;
  3035. fragments.push(end || "");
  3036. }
  3037. function selfClosing(tagName, attributes) {
  3038. open(tagName, attributes);
  3039. close(tagName);
  3040. }
  3041. function text(value) {
  3042. fragments.push(escapeMarkdown(value));
  3043. }
  3044. function asString() {
  3045. return fragments.join("");
  3046. }
  3047. return {
  3048. asString: asString,
  3049. open: open,
  3050. close: close,
  3051. text: text,
  3052. selfClosing: selfClosing
  3053. };
  3054. }
  3055. exports.writer = markdownWriter;
  3056. function escapeMarkdown(value) {
  3057. return value
  3058. .replace(/\\/g, '\\\\')
  3059. .replace(/([\`\*_\{\}\[\]\(\)\#\+\-\.\!])/g, '\\$1');
  3060. }
  3061. },{"underscore":153}],34:[function(require,module,exports){
  3062. var nodes = require("./nodes");
  3063. exports.Element = nodes.Element;
  3064. exports.element = nodes.element;
  3065. exports.text = nodes.text;
  3066. exports.readString = require("./reader").readString;
  3067. exports.writeString = require("./writer").writeString;
  3068. },{"./nodes":35,"./reader":36,"./writer":37}],35:[function(require,module,exports){
  3069. var _ = require("underscore");
  3070. exports.Element = Element;
  3071. exports.element = function(name, attributes, children) {
  3072. return new Element(name, attributes, children);
  3073. };
  3074. exports.text = function(value) {
  3075. return {
  3076. type: "text",
  3077. value: value
  3078. };
  3079. };
  3080. var emptyElement = {
  3081. first: function() {
  3082. return null;
  3083. },
  3084. firstOrEmpty: function() {
  3085. return emptyElement;
  3086. },
  3087. attributes: {}
  3088. };
  3089. function Element(name, attributes, children) {
  3090. this.type = "element";
  3091. this.name = name;
  3092. this.attributes = attributes || {};
  3093. this.children = children || [];
  3094. }
  3095. Element.prototype.first = function(name) {
  3096. return _.find(this.children, function(child) {
  3097. return child.name === name;
  3098. });
  3099. };
  3100. Element.prototype.firstOrEmpty = function(name) {
  3101. return this.first(name) || emptyElement;
  3102. };
  3103. Element.prototype.getElementsByTagName = function(name) {
  3104. var elements = _.filter(this.children, function(child) {
  3105. return child.name === name;
  3106. });
  3107. return toElementList(elements);
  3108. };
  3109. Element.prototype.text = function() {
  3110. if (this.children.length === 0) {
  3111. return "";
  3112. } else if (this.children.length !== 1 || this.children[0].type !== "text") {
  3113. throw new Error("Not implemented");
  3114. }
  3115. return this.children[0].value;
  3116. };
  3117. var elementListPrototype = {
  3118. getElementsByTagName: function(name) {
  3119. return toElementList(_.flatten(this.map(function(element) {
  3120. return element.getElementsByTagName(name);
  3121. }, true)));
  3122. }
  3123. };
  3124. function toElementList(array) {
  3125. return _.extend(array, elementListPrototype);
  3126. }
  3127. },{"underscore":153}],36:[function(require,module,exports){
  3128. var promises = require("../promises");
  3129. var sax = require("sax");
  3130. var _ = require("underscore");
  3131. var nodes = require("./nodes");
  3132. var Element = nodes.Element;
  3133. exports.readString = readString;
  3134. function readString(xmlString, namespaceMap) {
  3135. namespaceMap = namespaceMap || {};
  3136. var finished = false;
  3137. var parser = sax.parser(true, {xmlns: true, position: false});
  3138. var rootElement = {children: []};
  3139. var currentElement = rootElement;
  3140. var stack = [];
  3141. var deferred = promises.defer();
  3142. parser.onopentag = function(node) {
  3143. var attributes = mapObject(node.attributes, function(attribute) {
  3144. return attribute.value;
  3145. }, mapName);
  3146. var element = new Element(mapName(node), attributes);
  3147. currentElement.children.push(element);
  3148. stack.push(currentElement);
  3149. currentElement = element;
  3150. };
  3151. function mapName(node) {
  3152. if (node.uri) {
  3153. var mappedPrefix = namespaceMap[node.uri];
  3154. var prefix;
  3155. if (mappedPrefix) {
  3156. prefix = mappedPrefix + ":";
  3157. } else {
  3158. prefix = "{" + node.uri + "}";
  3159. }
  3160. return prefix + node.local;
  3161. } else {
  3162. return node.local;
  3163. }
  3164. }
  3165. parser.onclosetag = function(node) {
  3166. currentElement = stack.pop();
  3167. };
  3168. parser.ontext = function(text) {
  3169. if (currentElement !== rootElement) {
  3170. currentElement.children.push(nodes.text(text));
  3171. }
  3172. };
  3173. parser.onend = function() {
  3174. if (!finished) {
  3175. finished = true;
  3176. deferred.resolve(rootElement.children[0]);
  3177. }
  3178. };
  3179. parser.onerror = function(error) {
  3180. if (!finished) {
  3181. finished = true;
  3182. deferred.reject(error);
  3183. }
  3184. };
  3185. parser.write(xmlString).close();
  3186. return deferred.promise;
  3187. }
  3188. function mapObject(input, valueFunc, keyFunc) {
  3189. return _.reduce(input, function(result, value, key) {
  3190. var mappedKey = keyFunc(value, key, input);
  3191. result[mappedKey] = valueFunc(value, key, input);
  3192. return result;
  3193. }, {});
  3194. }
  3195. },{"../promises":23,"./nodes":35,"sax":150,"underscore":153}],37:[function(require,module,exports){
  3196. var _ = require("underscore");
  3197. var xmlbuilder = require("xmlbuilder");
  3198. exports.writeString = writeString;
  3199. function writeString(root, namespaces) {
  3200. var uriToPrefix = _.invert(namespaces);
  3201. var nodeWriters = {
  3202. element: writeElement,
  3203. text: writeTextNode
  3204. };
  3205. function writeNode(builder, node) {
  3206. return nodeWriters[node.type](builder, node);
  3207. }
  3208. function writeElement(builder, element) {
  3209. var elementBuilder = builder.element(mapElementName(element.name), element.attributes);
  3210. element.children.forEach(function(child) {
  3211. writeNode(elementBuilder, child);
  3212. });
  3213. }
  3214. function mapElementName(name) {
  3215. var longFormMatch = /^\{(.*)\}(.*)$/.exec(name);
  3216. if (longFormMatch) {
  3217. var prefix = uriToPrefix[longFormMatch[1]];
  3218. return prefix + (prefix === "" ? "" : ":") + longFormMatch[2];
  3219. } else {
  3220. return name;
  3221. }
  3222. }
  3223. function writeDocument(root) {
  3224. var builder = xmlbuilder
  3225. .create(mapElementName(root.name), {
  3226. version: '1.0',
  3227. encoding: 'UTF-8',
  3228. standalone: true
  3229. });
  3230. _.forEach(namespaces, function(uri, prefix) {
  3231. var key = "xmlns" + (prefix === "" ? "" : ":" + prefix);
  3232. builder.attribute(key, uri);
  3233. });
  3234. root.children.forEach(function(child) {
  3235. writeNode(builder, child);
  3236. });
  3237. return builder.end();
  3238. }
  3239. return writeDocument(root);
  3240. }
  3241. function writeTextNode(builder, node) {
  3242. builder.text(node.value);
  3243. }
  3244. },{"underscore":153,"xmlbuilder":179}],38:[function(require,module,exports){
  3245. (function (Buffer){
  3246. var JSZip = require("jszip");
  3247. var promises = require("./promises");
  3248. exports.openArrayBuffer = openArrayBuffer;
  3249. exports.splitPath = splitPath;
  3250. exports.joinPath = joinPath;
  3251. function openArrayBuffer(arrayBuffer) {
  3252. var zipFile = new JSZip(arrayBuffer);
  3253. function exists(name) {
  3254. return zipFile.file(name) !== null;
  3255. }
  3256. function read(name, encoding) {
  3257. var array = zipFile.file(name).asUint8Array();
  3258. var buffer = new Buffer(array);
  3259. if (encoding) {
  3260. return promises.when(buffer.toString(encoding));
  3261. } else {
  3262. return promises.when(buffer);
  3263. }
  3264. }
  3265. function write(name, contents) {
  3266. zipFile.file(name, contents);
  3267. }
  3268. function toBuffer() {
  3269. return zipFile.generate({type: "nodebuffer"});
  3270. }
  3271. return {
  3272. exists: exists,
  3273. read: read,
  3274. write: write,
  3275. toBuffer: toBuffer
  3276. };
  3277. }
  3278. function splitPath(path) {
  3279. var lastIndex = path.lastIndexOf("/");
  3280. if (lastIndex === -1) {
  3281. return {dirname: "", basename: path};
  3282. } else {
  3283. return {
  3284. dirname: path.substring(0, lastIndex),
  3285. basename: path.substring(lastIndex + 1)
  3286. };
  3287. }
  3288. }
  3289. function joinPath() {
  3290. var nonEmptyPaths = Array.prototype.filter.call(arguments, function(path) {
  3291. return path;
  3292. });
  3293. var relevantPaths = [];
  3294. nonEmptyPaths.forEach(function(path) {
  3295. if (/^\//.test(path)) {
  3296. relevantPaths = [path];
  3297. } else {
  3298. relevantPaths.push(path);
  3299. }
  3300. });
  3301. return relevantPaths.join("/");
  3302. }
  3303. }).call(this,require("buffer").Buffer)
  3304. },{"./promises":23,"buffer":77,"jszip":92}],39:[function(require,module,exports){
  3305. 'use strict'
  3306. exports.byteLength = byteLength
  3307. exports.toByteArray = toByteArray
  3308. exports.fromByteArray = fromByteArray
  3309. var lookup = []
  3310. var revLookup = []
  3311. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  3312. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  3313. for (var i = 0, len = code.length; i < len; ++i) {
  3314. lookup[i] = code[i]
  3315. revLookup[code.charCodeAt(i)] = i
  3316. }
  3317. revLookup['-'.charCodeAt(0)] = 62
  3318. revLookup['_'.charCodeAt(0)] = 63
  3319. function placeHoldersCount (b64) {
  3320. var len = b64.length
  3321. if (len % 4 > 0) {
  3322. throw new Error('Invalid string. Length must be a multiple of 4')
  3323. }
  3324. // the number of equal signs (place holders)
  3325. // if there are two placeholders, than the two characters before it
  3326. // represent one byte
  3327. // if there is only one, then the three characters before it represent 2 bytes
  3328. // this is just a cheap hack to not do indexOf twice
  3329. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  3330. }
  3331. function byteLength (b64) {
  3332. // base64 is 4/3 + up to two characters of the original data
  3333. return b64.length * 3 / 4 - placeHoldersCount(b64)
  3334. }
  3335. function toByteArray (b64) {
  3336. var i, j, l, tmp, placeHolders, arr
  3337. var len = b64.length
  3338. placeHolders = placeHoldersCount(b64)
  3339. arr = new Arr(len * 3 / 4 - placeHolders)
  3340. // if there are placeholders, only get up to the last complete 4 chars
  3341. l = placeHolders > 0 ? len - 4 : len
  3342. var L = 0
  3343. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  3344. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  3345. arr[L++] = (tmp >> 16) & 0xFF
  3346. arr[L++] = (tmp >> 8) & 0xFF
  3347. arr[L++] = tmp & 0xFF
  3348. }
  3349. if (placeHolders === 2) {
  3350. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  3351. arr[L++] = tmp & 0xFF
  3352. } else if (placeHolders === 1) {
  3353. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  3354. arr[L++] = (tmp >> 8) & 0xFF
  3355. arr[L++] = tmp & 0xFF
  3356. }
  3357. return arr
  3358. }
  3359. function tripletToBase64 (num) {
  3360. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  3361. }
  3362. function encodeChunk (uint8, start, end) {
  3363. var tmp
  3364. var output = []
  3365. for (var i = start; i < end; i += 3) {
  3366. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  3367. output.push(tripletToBase64(tmp))
  3368. }
  3369. return output.join('')
  3370. }
  3371. function fromByteArray (uint8) {
  3372. var tmp
  3373. var len = uint8.length
  3374. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  3375. var output = ''
  3376. var parts = []
  3377. var maxChunkLength = 16383 // must be multiple of 3
  3378. // go through the array every three bytes, we'll deal with trailing stuff later
  3379. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  3380. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  3381. }
  3382. // pad the end with zeros, but make sure to not forget the extra bytes
  3383. if (extraBytes === 1) {
  3384. tmp = uint8[len - 1]
  3385. output += lookup[tmp >> 2]
  3386. output += lookup[(tmp << 4) & 0x3F]
  3387. output += '=='
  3388. } else if (extraBytes === 2) {
  3389. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  3390. output += lookup[tmp >> 10]
  3391. output += lookup[(tmp >> 4) & 0x3F]
  3392. output += lookup[(tmp << 2) & 0x3F]
  3393. output += '='
  3394. }
  3395. parts.push(output)
  3396. return parts.join('')
  3397. }
  3398. },{}],40:[function(require,module,exports){
  3399. "use strict";
  3400. module.exports = function(Promise) {
  3401. var SomePromiseArray = Promise._SomePromiseArray;
  3402. function any(promises) {
  3403. var ret = new SomePromiseArray(promises);
  3404. var promise = ret.promise();
  3405. ret.setHowMany(1);
  3406. ret.setUnwrap();
  3407. ret.init();
  3408. return promise;
  3409. }
  3410. Promise.any = function (promises) {
  3411. return any(promises);
  3412. };
  3413. Promise.prototype.any = function () {
  3414. return any(this);
  3415. };
  3416. };
  3417. },{}],41:[function(require,module,exports){
  3418. (function (process){
  3419. "use strict";
  3420. var firstLineError;
  3421. try {throw new Error(); } catch (e) {firstLineError = e;}
  3422. var schedule = require("./schedule");
  3423. var Queue = require("./queue");
  3424. var util = require("./util");
  3425. function Async() {
  3426. this._customScheduler = false;
  3427. this._isTickUsed = false;
  3428. this._lateQueue = new Queue(16);
  3429. this._normalQueue = new Queue(16);
  3430. this._haveDrainedQueues = false;
  3431. this._trampolineEnabled = true;
  3432. var self = this;
  3433. this.drainQueues = function () {
  3434. self._drainQueues();
  3435. };
  3436. this._schedule = schedule;
  3437. }
  3438. Async.prototype.setScheduler = function(fn) {
  3439. var prev = this._schedule;
  3440. this._schedule = fn;
  3441. this._customScheduler = true;
  3442. return prev;
  3443. };
  3444. Async.prototype.hasCustomScheduler = function() {
  3445. return this._customScheduler;
  3446. };
  3447. Async.prototype.enableTrampoline = function() {
  3448. this._trampolineEnabled = true;
  3449. };
  3450. Async.prototype.disableTrampolineIfNecessary = function() {
  3451. if (util.hasDevTools) {
  3452. this._trampolineEnabled = false;
  3453. }
  3454. };
  3455. Async.prototype.haveItemsQueued = function () {
  3456. return this._isTickUsed || this._haveDrainedQueues;
  3457. };
  3458. Async.prototype.fatalError = function(e, isNode) {
  3459. if (isNode) {
  3460. process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
  3461. "\n");
  3462. process.exit(2);
  3463. } else {
  3464. this.throwLater(e);
  3465. }
  3466. };
  3467. Async.prototype.throwLater = function(fn, arg) {
  3468. if (arguments.length === 1) {
  3469. arg = fn;
  3470. fn = function () { throw arg; };
  3471. }
  3472. if (typeof setTimeout !== "undefined") {
  3473. setTimeout(function() {
  3474. fn(arg);
  3475. }, 0);
  3476. } else try {
  3477. this._schedule(function() {
  3478. fn(arg);
  3479. });
  3480. } catch (e) {
  3481. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  3482. }
  3483. };
  3484. function AsyncInvokeLater(fn, receiver, arg) {
  3485. this._lateQueue.push(fn, receiver, arg);
  3486. this._queueTick();
  3487. }
  3488. function AsyncInvoke(fn, receiver, arg) {
  3489. this._normalQueue.push(fn, receiver, arg);
  3490. this._queueTick();
  3491. }
  3492. function AsyncSettlePromises(promise) {
  3493. this._normalQueue._pushOne(promise);
  3494. this._queueTick();
  3495. }
  3496. if (!util.hasDevTools) {
  3497. Async.prototype.invokeLater = AsyncInvokeLater;
  3498. Async.prototype.invoke = AsyncInvoke;
  3499. Async.prototype.settlePromises = AsyncSettlePromises;
  3500. } else {
  3501. Async.prototype.invokeLater = function (fn, receiver, arg) {
  3502. if (this._trampolineEnabled) {
  3503. AsyncInvokeLater.call(this, fn, receiver, arg);
  3504. } else {
  3505. this._schedule(function() {
  3506. setTimeout(function() {
  3507. fn.call(receiver, arg);
  3508. }, 100);
  3509. });
  3510. }
  3511. };
  3512. Async.prototype.invoke = function (fn, receiver, arg) {
  3513. if (this._trampolineEnabled) {
  3514. AsyncInvoke.call(this, fn, receiver, arg);
  3515. } else {
  3516. this._schedule(function() {
  3517. fn.call(receiver, arg);
  3518. });
  3519. }
  3520. };
  3521. Async.prototype.settlePromises = function(promise) {
  3522. if (this._trampolineEnabled) {
  3523. AsyncSettlePromises.call(this, promise);
  3524. } else {
  3525. this._schedule(function() {
  3526. promise._settlePromises();
  3527. });
  3528. }
  3529. };
  3530. }
  3531. Async.prototype._drainQueue = function(queue) {
  3532. while (queue.length() > 0) {
  3533. var fn = queue.shift();
  3534. if (typeof fn !== "function") {
  3535. fn._settlePromises();
  3536. continue;
  3537. }
  3538. var receiver = queue.shift();
  3539. var arg = queue.shift();
  3540. fn.call(receiver, arg);
  3541. }
  3542. };
  3543. Async.prototype._drainQueues = function () {
  3544. this._drainQueue(this._normalQueue);
  3545. this._reset();
  3546. this._haveDrainedQueues = true;
  3547. this._drainQueue(this._lateQueue);
  3548. };
  3549. Async.prototype._queueTick = function () {
  3550. if (!this._isTickUsed) {
  3551. this._isTickUsed = true;
  3552. this._schedule(this.drainQueues);
  3553. }
  3554. };
  3555. Async.prototype._reset = function () {
  3556. this._isTickUsed = false;
  3557. };
  3558. module.exports = Async;
  3559. module.exports.firstLineError = firstLineError;
  3560. }).call(this,require('_process'))
  3561. },{"./queue":64,"./schedule":67,"./util":74,"_process":138}],42:[function(require,module,exports){
  3562. "use strict";
  3563. module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
  3564. var calledBind = false;
  3565. var rejectThis = function(_, e) {
  3566. this._reject(e);
  3567. };
  3568. var targetRejected = function(e, context) {
  3569. context.promiseRejectionQueued = true;
  3570. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  3571. };
  3572. var bindingResolved = function(thisArg, context) {
  3573. if (((this._bitField & 50397184) === 0)) {
  3574. this._resolveCallback(context.target);
  3575. }
  3576. };
  3577. var bindingRejected = function(e, context) {
  3578. if (!context.promiseRejectionQueued) this._reject(e);
  3579. };
  3580. Promise.prototype.bind = function (thisArg) {
  3581. if (!calledBind) {
  3582. calledBind = true;
  3583. Promise.prototype._propagateFrom = debug.propagateFromFunction();
  3584. Promise.prototype._boundValue = debug.boundValueFunction();
  3585. }
  3586. var maybePromise = tryConvertToPromise(thisArg);
  3587. var ret = new Promise(INTERNAL);
  3588. ret._propagateFrom(this, 1);
  3589. var target = this._target();
  3590. ret._setBoundTo(maybePromise);
  3591. if (maybePromise instanceof Promise) {
  3592. var context = {
  3593. promiseRejectionQueued: false,
  3594. promise: ret,
  3595. target: target,
  3596. bindingPromise: maybePromise
  3597. };
  3598. target._then(INTERNAL, targetRejected, undefined, ret, context);
  3599. maybePromise._then(
  3600. bindingResolved, bindingRejected, undefined, ret, context);
  3601. ret._setOnCancel(maybePromise);
  3602. } else {
  3603. ret._resolveCallback(target);
  3604. }
  3605. return ret;
  3606. };
  3607. Promise.prototype._setBoundTo = function (obj) {
  3608. if (obj !== undefined) {
  3609. this._bitField = this._bitField | 2097152;
  3610. this._boundTo = obj;
  3611. } else {
  3612. this._bitField = this._bitField & (~2097152);
  3613. }
  3614. };
  3615. Promise.prototype._isBound = function () {
  3616. return (this._bitField & 2097152) === 2097152;
  3617. };
  3618. Promise.bind = function (thisArg, value) {
  3619. return Promise.resolve(value).bind(thisArg);
  3620. };
  3621. };
  3622. },{}],43:[function(require,module,exports){
  3623. "use strict";
  3624. var cr = Object.create;
  3625. if (cr) {
  3626. var callerCache = cr(null);
  3627. var getterCache = cr(null);
  3628. callerCache[" size"] = getterCache[" size"] = 0;
  3629. }
  3630. module.exports = function(Promise) {
  3631. var util = require("./util");
  3632. var canEvaluate = util.canEvaluate;
  3633. var isIdentifier = util.isIdentifier;
  3634. var getMethodCaller;
  3635. var getGetter;
  3636. if (!false) {
  3637. var makeMethodCaller = function (methodName) {
  3638. return new Function("ensureMethod", " \n\
  3639. return function(obj) { \n\
  3640. 'use strict' \n\
  3641. var len = this.length; \n\
  3642. ensureMethod(obj, 'methodName'); \n\
  3643. switch(len) { \n\
  3644. case 1: return obj.methodName(this[0]); \n\
  3645. case 2: return obj.methodName(this[0], this[1]); \n\
  3646. case 3: return obj.methodName(this[0], this[1], this[2]); \n\
  3647. case 0: return obj.methodName(); \n\
  3648. default: \n\
  3649. return obj.methodName.apply(obj, this); \n\
  3650. } \n\
  3651. }; \n\
  3652. ".replace(/methodName/g, methodName))(ensureMethod);
  3653. };
  3654. var makeGetter = function (propertyName) {
  3655. return new Function("obj", " \n\
  3656. 'use strict'; \n\
  3657. return obj.propertyName; \n\
  3658. ".replace("propertyName", propertyName));
  3659. };
  3660. var getCompiled = function(name, compiler, cache) {
  3661. var ret = cache[name];
  3662. if (typeof ret !== "function") {
  3663. if (!isIdentifier(name)) {
  3664. return null;
  3665. }
  3666. ret = compiler(name);
  3667. cache[name] = ret;
  3668. cache[" size"]++;
  3669. if (cache[" size"] > 512) {
  3670. var keys = Object.keys(cache);
  3671. for (var i = 0; i < 256; ++i) delete cache[keys[i]];
  3672. cache[" size"] = keys.length - 256;
  3673. }
  3674. }
  3675. return ret;
  3676. };
  3677. getMethodCaller = function(name) {
  3678. return getCompiled(name, makeMethodCaller, callerCache);
  3679. };
  3680. getGetter = function(name) {
  3681. return getCompiled(name, makeGetter, getterCache);
  3682. };
  3683. }
  3684. function ensureMethod(obj, methodName) {
  3685. var fn;
  3686. if (obj != null) fn = obj[methodName];
  3687. if (typeof fn !== "function") {
  3688. var message = "Object " + util.classString(obj) + " has no method '" +
  3689. util.toString(methodName) + "'";
  3690. throw new Promise.TypeError(message);
  3691. }
  3692. return fn;
  3693. }
  3694. function caller(obj) {
  3695. var methodName = this.pop();
  3696. var fn = ensureMethod(obj, methodName);
  3697. return fn.apply(obj, this);
  3698. }
  3699. Promise.prototype.call = function (methodName) {
  3700. var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
  3701. if (!false) {
  3702. if (canEvaluate) {
  3703. var maybeCaller = getMethodCaller(methodName);
  3704. if (maybeCaller !== null) {
  3705. return this._then(
  3706. maybeCaller, undefined, undefined, args, undefined);
  3707. }
  3708. }
  3709. }
  3710. args.push(methodName);
  3711. return this._then(caller, undefined, undefined, args, undefined);
  3712. };
  3713. function namedGetter(obj) {
  3714. return obj[this];
  3715. }
  3716. function indexedGetter(obj) {
  3717. var index = +this;
  3718. if (index < 0) index = Math.max(0, index + obj.length);
  3719. return obj[index];
  3720. }
  3721. Promise.prototype.get = function (propertyName) {
  3722. var isIndex = (typeof propertyName === "number");
  3723. var getter;
  3724. if (!isIndex) {
  3725. if (canEvaluate) {
  3726. var maybeGetter = getGetter(propertyName);
  3727. getter = maybeGetter !== null ? maybeGetter : namedGetter;
  3728. } else {
  3729. getter = namedGetter;
  3730. }
  3731. } else {
  3732. getter = indexedGetter;
  3733. }
  3734. return this._then(getter, undefined, undefined, propertyName, undefined);
  3735. };
  3736. };
  3737. },{"./util":74}],44:[function(require,module,exports){
  3738. "use strict";
  3739. module.exports = function(Promise, PromiseArray, apiRejection, debug) {
  3740. var util = require("./util");
  3741. var tryCatch = util.tryCatch;
  3742. var errorObj = util.errorObj;
  3743. var async = Promise._async;
  3744. Promise.prototype["break"] = Promise.prototype.cancel = function() {
  3745. if (!debug.cancellation()) return this._warn("cancellation is disabled");
  3746. var promise = this;
  3747. var child = promise;
  3748. while (promise._isCancellable()) {
  3749. if (!promise._cancelBy(child)) {
  3750. if (child._isFollowing()) {
  3751. child._followee().cancel();
  3752. } else {
  3753. child._cancelBranched();
  3754. }
  3755. break;
  3756. }
  3757. var parent = promise._cancellationParent;
  3758. if (parent == null || !parent._isCancellable()) {
  3759. if (promise._isFollowing()) {
  3760. promise._followee().cancel();
  3761. } else {
  3762. promise._cancelBranched();
  3763. }
  3764. break;
  3765. } else {
  3766. if (promise._isFollowing()) promise._followee().cancel();
  3767. promise._setWillBeCancelled();
  3768. child = promise;
  3769. promise = parent;
  3770. }
  3771. }
  3772. };
  3773. Promise.prototype._branchHasCancelled = function() {
  3774. this._branchesRemainingToCancel--;
  3775. };
  3776. Promise.prototype._enoughBranchesHaveCancelled = function() {
  3777. return this._branchesRemainingToCancel === undefined ||
  3778. this._branchesRemainingToCancel <= 0;
  3779. };
  3780. Promise.prototype._cancelBy = function(canceller) {
  3781. if (canceller === this) {
  3782. this._branchesRemainingToCancel = 0;
  3783. this._invokeOnCancel();
  3784. return true;
  3785. } else {
  3786. this._branchHasCancelled();
  3787. if (this._enoughBranchesHaveCancelled()) {
  3788. this._invokeOnCancel();
  3789. return true;
  3790. }
  3791. }
  3792. return false;
  3793. };
  3794. Promise.prototype._cancelBranched = function() {
  3795. if (this._enoughBranchesHaveCancelled()) {
  3796. this._cancel();
  3797. }
  3798. };
  3799. Promise.prototype._cancel = function() {
  3800. if (!this._isCancellable()) return;
  3801. this._setCancelled();
  3802. async.invoke(this._cancelPromises, this, undefined);
  3803. };
  3804. Promise.prototype._cancelPromises = function() {
  3805. if (this._length() > 0) this._settlePromises();
  3806. };
  3807. Promise.prototype._unsetOnCancel = function() {
  3808. this._onCancelField = undefined;
  3809. };
  3810. Promise.prototype._isCancellable = function() {
  3811. return this.isPending() && !this._isCancelled();
  3812. };
  3813. Promise.prototype.isCancellable = function() {
  3814. return this.isPending() && !this.isCancelled();
  3815. };
  3816. Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
  3817. if (util.isArray(onCancelCallback)) {
  3818. for (var i = 0; i < onCancelCallback.length; ++i) {
  3819. this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
  3820. }
  3821. } else if (onCancelCallback !== undefined) {
  3822. if (typeof onCancelCallback === "function") {
  3823. if (!internalOnly) {
  3824. var e = tryCatch(onCancelCallback).call(this._boundValue());
  3825. if (e === errorObj) {
  3826. this._attachExtraTrace(e.e);
  3827. async.throwLater(e.e);
  3828. }
  3829. }
  3830. } else {
  3831. onCancelCallback._resultCancelled(this);
  3832. }
  3833. }
  3834. };
  3835. Promise.prototype._invokeOnCancel = function() {
  3836. var onCancelCallback = this._onCancel();
  3837. this._unsetOnCancel();
  3838. async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
  3839. };
  3840. Promise.prototype._invokeInternalOnCancel = function() {
  3841. if (this._isCancellable()) {
  3842. this._doInvokeOnCancel(this._onCancel(), true);
  3843. this._unsetOnCancel();
  3844. }
  3845. };
  3846. Promise.prototype._resultCancelled = function() {
  3847. this.cancel();
  3848. };
  3849. };
  3850. },{"./util":74}],45:[function(require,module,exports){
  3851. "use strict";
  3852. module.exports = function(NEXT_FILTER) {
  3853. var util = require("./util");
  3854. var getKeys = require("./es5").keys;
  3855. var tryCatch = util.tryCatch;
  3856. var errorObj = util.errorObj;
  3857. function catchFilter(instances, cb, promise) {
  3858. return function(e) {
  3859. var boundTo = promise._boundValue();
  3860. predicateLoop: for (var i = 0; i < instances.length; ++i) {
  3861. var item = instances[i];
  3862. if (item === Error ||
  3863. (item != null && item.prototype instanceof Error)) {
  3864. if (e instanceof item) {
  3865. return tryCatch(cb).call(boundTo, e);
  3866. }
  3867. } else if (typeof item === "function") {
  3868. var matchesPredicate = tryCatch(item).call(boundTo, e);
  3869. if (matchesPredicate === errorObj) {
  3870. return matchesPredicate;
  3871. } else if (matchesPredicate) {
  3872. return tryCatch(cb).call(boundTo, e);
  3873. }
  3874. } else if (util.isObject(e)) {
  3875. var keys = getKeys(item);
  3876. for (var j = 0; j < keys.length; ++j) {
  3877. var key = keys[j];
  3878. if (item[key] != e[key]) {
  3879. continue predicateLoop;
  3880. }
  3881. }
  3882. return tryCatch(cb).call(boundTo, e);
  3883. }
  3884. }
  3885. return NEXT_FILTER;
  3886. };
  3887. }
  3888. return catchFilter;
  3889. };
  3890. },{"./es5":51,"./util":74}],46:[function(require,module,exports){
  3891. "use strict";
  3892. module.exports = function(Promise) {
  3893. var longStackTraces = false;
  3894. var contextStack = [];
  3895. Promise.prototype._promiseCreated = function() {};
  3896. Promise.prototype._pushContext = function() {};
  3897. Promise.prototype._popContext = function() {return null;};
  3898. Promise._peekContext = Promise.prototype._peekContext = function() {};
  3899. function Context() {
  3900. this._trace = new Context.CapturedTrace(peekContext());
  3901. }
  3902. Context.prototype._pushContext = function () {
  3903. if (this._trace !== undefined) {
  3904. this._trace._promiseCreated = null;
  3905. contextStack.push(this._trace);
  3906. }
  3907. };
  3908. Context.prototype._popContext = function () {
  3909. if (this._trace !== undefined) {
  3910. var trace = contextStack.pop();
  3911. var ret = trace._promiseCreated;
  3912. trace._promiseCreated = null;
  3913. return ret;
  3914. }
  3915. return null;
  3916. };
  3917. function createContext() {
  3918. if (longStackTraces) return new Context();
  3919. }
  3920. function peekContext() {
  3921. var lastIndex = contextStack.length - 1;
  3922. if (lastIndex >= 0) {
  3923. return contextStack[lastIndex];
  3924. }
  3925. return undefined;
  3926. }
  3927. Context.CapturedTrace = null;
  3928. Context.create = createContext;
  3929. Context.deactivateLongStackTraces = function() {};
  3930. Context.activateLongStackTraces = function() {
  3931. var Promise_pushContext = Promise.prototype._pushContext;
  3932. var Promise_popContext = Promise.prototype._popContext;
  3933. var Promise_PeekContext = Promise._peekContext;
  3934. var Promise_peekContext = Promise.prototype._peekContext;
  3935. var Promise_promiseCreated = Promise.prototype._promiseCreated;
  3936. Context.deactivateLongStackTraces = function() {
  3937. Promise.prototype._pushContext = Promise_pushContext;
  3938. Promise.prototype._popContext = Promise_popContext;
  3939. Promise._peekContext = Promise_PeekContext;
  3940. Promise.prototype._peekContext = Promise_peekContext;
  3941. Promise.prototype._promiseCreated = Promise_promiseCreated;
  3942. longStackTraces = false;
  3943. };
  3944. longStackTraces = true;
  3945. Promise.prototype._pushContext = Context.prototype._pushContext;
  3946. Promise.prototype._popContext = Context.prototype._popContext;
  3947. Promise._peekContext = Promise.prototype._peekContext = peekContext;
  3948. Promise.prototype._promiseCreated = function() {
  3949. var ctx = this._peekContext();
  3950. if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
  3951. };
  3952. };
  3953. return Context;
  3954. };
  3955. },{}],47:[function(require,module,exports){
  3956. (function (process){
  3957. "use strict";
  3958. module.exports = function(Promise, Context) {
  3959. var getDomain = Promise._getDomain;
  3960. var async = Promise._async;
  3961. var Warning = require("./errors").Warning;
  3962. var util = require("./util");
  3963. var canAttachTrace = util.canAttachTrace;
  3964. var unhandledRejectionHandled;
  3965. var possiblyUnhandledRejection;
  3966. var bluebirdFramePattern =
  3967. /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
  3968. var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
  3969. var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
  3970. var stackFramePattern = null;
  3971. var formatStack = null;
  3972. var indentStackFrames = false;
  3973. var printWarning;
  3974. var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
  3975. (false ||
  3976. util.env("BLUEBIRD_DEBUG") ||
  3977. util.env("NODE_ENV") === "development"));
  3978. var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
  3979. (debugging || util.env("BLUEBIRD_WARNINGS")));
  3980. var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
  3981. (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
  3982. var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
  3983. (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
  3984. Promise.prototype.suppressUnhandledRejections = function() {
  3985. var target = this._target();
  3986. target._bitField = ((target._bitField & (~1048576)) |
  3987. 524288);
  3988. };
  3989. Promise.prototype._ensurePossibleRejectionHandled = function () {
  3990. if ((this._bitField & 524288) !== 0) return;
  3991. this._setRejectionIsUnhandled();
  3992. async.invokeLater(this._notifyUnhandledRejection, this, undefined);
  3993. };
  3994. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  3995. fireRejectionEvent("rejectionHandled",
  3996. unhandledRejectionHandled, undefined, this);
  3997. };
  3998. Promise.prototype._setReturnedNonUndefined = function() {
  3999. this._bitField = this._bitField | 268435456;
  4000. };
  4001. Promise.prototype._returnedNonUndefined = function() {
  4002. return (this._bitField & 268435456) !== 0;
  4003. };
  4004. Promise.prototype._notifyUnhandledRejection = function () {
  4005. if (this._isRejectionUnhandled()) {
  4006. var reason = this._settledValue();
  4007. this._setUnhandledRejectionIsNotified();
  4008. fireRejectionEvent("unhandledRejection",
  4009. possiblyUnhandledRejection, reason, this);
  4010. }
  4011. };
  4012. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  4013. this._bitField = this._bitField | 262144;
  4014. };
  4015. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  4016. this._bitField = this._bitField & (~262144);
  4017. };
  4018. Promise.prototype._isUnhandledRejectionNotified = function () {
  4019. return (this._bitField & 262144) > 0;
  4020. };
  4021. Promise.prototype._setRejectionIsUnhandled = function () {
  4022. this._bitField = this._bitField | 1048576;
  4023. };
  4024. Promise.prototype._unsetRejectionIsUnhandled = function () {
  4025. this._bitField = this._bitField & (~1048576);
  4026. if (this._isUnhandledRejectionNotified()) {
  4027. this._unsetUnhandledRejectionIsNotified();
  4028. this._notifyUnhandledRejectionIsHandled();
  4029. }
  4030. };
  4031. Promise.prototype._isRejectionUnhandled = function () {
  4032. return (this._bitField & 1048576) > 0;
  4033. };
  4034. Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
  4035. return warn(message, shouldUseOwnTrace, promise || this);
  4036. };
  4037. Promise.onPossiblyUnhandledRejection = function (fn) {
  4038. var domain = getDomain();
  4039. possiblyUnhandledRejection =
  4040. typeof fn === "function" ? (domain === null ?
  4041. fn : util.domainBind(domain, fn))
  4042. : undefined;
  4043. };
  4044. Promise.onUnhandledRejectionHandled = function (fn) {
  4045. var domain = getDomain();
  4046. unhandledRejectionHandled =
  4047. typeof fn === "function" ? (domain === null ?
  4048. fn : util.domainBind(domain, fn))
  4049. : undefined;
  4050. };
  4051. var disableLongStackTraces = function() {};
  4052. Promise.longStackTraces = function () {
  4053. if (async.haveItemsQueued() && !config.longStackTraces) {
  4054. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4055. }
  4056. if (!config.longStackTraces && longStackTracesIsSupported()) {
  4057. var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
  4058. var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
  4059. config.longStackTraces = true;
  4060. disableLongStackTraces = function() {
  4061. if (async.haveItemsQueued() && !config.longStackTraces) {
  4062. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4063. }
  4064. Promise.prototype._captureStackTrace = Promise_captureStackTrace;
  4065. Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
  4066. Context.deactivateLongStackTraces();
  4067. async.enableTrampoline();
  4068. config.longStackTraces = false;
  4069. };
  4070. Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
  4071. Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
  4072. Context.activateLongStackTraces();
  4073. async.disableTrampolineIfNecessary();
  4074. }
  4075. };
  4076. Promise.hasLongStackTraces = function () {
  4077. return config.longStackTraces && longStackTracesIsSupported();
  4078. };
  4079. var fireDomEvent = (function() {
  4080. try {
  4081. if (typeof CustomEvent === "function") {
  4082. var event = new CustomEvent("CustomEvent");
  4083. util.global.dispatchEvent(event);
  4084. return function(name, event) {
  4085. var domEvent = new CustomEvent(name.toLowerCase(), {
  4086. detail: event,
  4087. cancelable: true
  4088. });
  4089. return !util.global.dispatchEvent(domEvent);
  4090. };
  4091. } else if (typeof Event === "function") {
  4092. var event = new Event("CustomEvent");
  4093. util.global.dispatchEvent(event);
  4094. return function(name, event) {
  4095. var domEvent = new Event(name.toLowerCase(), {
  4096. cancelable: true
  4097. });
  4098. domEvent.detail = event;
  4099. return !util.global.dispatchEvent(domEvent);
  4100. };
  4101. } else {
  4102. var event = document.createEvent("CustomEvent");
  4103. event.initCustomEvent("testingtheevent", false, true, {});
  4104. util.global.dispatchEvent(event);
  4105. return function(name, event) {
  4106. var domEvent = document.createEvent("CustomEvent");
  4107. domEvent.initCustomEvent(name.toLowerCase(), false, true,
  4108. event);
  4109. return !util.global.dispatchEvent(domEvent);
  4110. };
  4111. }
  4112. } catch (e) {}
  4113. return function() {
  4114. return false;
  4115. };
  4116. })();
  4117. var fireGlobalEvent = (function() {
  4118. if (util.isNode) {
  4119. return function() {
  4120. return process.emit.apply(process, arguments);
  4121. };
  4122. } else {
  4123. if (!util.global) {
  4124. return function() {
  4125. return false;
  4126. };
  4127. }
  4128. return function(name) {
  4129. var methodName = "on" + name.toLowerCase();
  4130. var method = util.global[methodName];
  4131. if (!method) return false;
  4132. method.apply(util.global, [].slice.call(arguments, 1));
  4133. return true;
  4134. };
  4135. }
  4136. })();
  4137. function generatePromiseLifecycleEventObject(name, promise) {
  4138. return {promise: promise};
  4139. }
  4140. var eventToObjectGenerator = {
  4141. promiseCreated: generatePromiseLifecycleEventObject,
  4142. promiseFulfilled: generatePromiseLifecycleEventObject,
  4143. promiseRejected: generatePromiseLifecycleEventObject,
  4144. promiseResolved: generatePromiseLifecycleEventObject,
  4145. promiseCancelled: generatePromiseLifecycleEventObject,
  4146. promiseChained: function(name, promise, child) {
  4147. return {promise: promise, child: child};
  4148. },
  4149. warning: function(name, warning) {
  4150. return {warning: warning};
  4151. },
  4152. unhandledRejection: function (name, reason, promise) {
  4153. return {reason: reason, promise: promise};
  4154. },
  4155. rejectionHandled: generatePromiseLifecycleEventObject
  4156. };
  4157. var activeFireEvent = function (name) {
  4158. var globalEventFired = false;
  4159. try {
  4160. globalEventFired = fireGlobalEvent.apply(null, arguments);
  4161. } catch (e) {
  4162. async.throwLater(e);
  4163. globalEventFired = true;
  4164. }
  4165. var domEventFired = false;
  4166. try {
  4167. domEventFired = fireDomEvent(name,
  4168. eventToObjectGenerator[name].apply(null, arguments));
  4169. } catch (e) {
  4170. async.throwLater(e);
  4171. domEventFired = true;
  4172. }
  4173. return domEventFired || globalEventFired;
  4174. };
  4175. Promise.config = function(opts) {
  4176. opts = Object(opts);
  4177. if ("longStackTraces" in opts) {
  4178. if (opts.longStackTraces) {
  4179. Promise.longStackTraces();
  4180. } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
  4181. disableLongStackTraces();
  4182. }
  4183. }
  4184. if ("warnings" in opts) {
  4185. var warningsOption = opts.warnings;
  4186. config.warnings = !!warningsOption;
  4187. wForgottenReturn = config.warnings;
  4188. if (util.isObject(warningsOption)) {
  4189. if ("wForgottenReturn" in warningsOption) {
  4190. wForgottenReturn = !!warningsOption.wForgottenReturn;
  4191. }
  4192. }
  4193. }
  4194. if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
  4195. if (async.haveItemsQueued()) {
  4196. throw new Error(
  4197. "cannot enable cancellation after promises are in use");
  4198. }
  4199. Promise.prototype._clearCancellationData =
  4200. cancellationClearCancellationData;
  4201. Promise.prototype._propagateFrom = cancellationPropagateFrom;
  4202. Promise.prototype._onCancel = cancellationOnCancel;
  4203. Promise.prototype._setOnCancel = cancellationSetOnCancel;
  4204. Promise.prototype._attachCancellationCallback =
  4205. cancellationAttachCancellationCallback;
  4206. Promise.prototype._execute = cancellationExecute;
  4207. propagateFromFunction = cancellationPropagateFrom;
  4208. config.cancellation = true;
  4209. }
  4210. if ("monitoring" in opts) {
  4211. if (opts.monitoring && !config.monitoring) {
  4212. config.monitoring = true;
  4213. Promise.prototype._fireEvent = activeFireEvent;
  4214. } else if (!opts.monitoring && config.monitoring) {
  4215. config.monitoring = false;
  4216. Promise.prototype._fireEvent = defaultFireEvent;
  4217. }
  4218. }
  4219. return Promise;
  4220. };
  4221. function defaultFireEvent() { return false; }
  4222. Promise.prototype._fireEvent = defaultFireEvent;
  4223. Promise.prototype._execute = function(executor, resolve, reject) {
  4224. try {
  4225. executor(resolve, reject);
  4226. } catch (e) {
  4227. return e;
  4228. }
  4229. };
  4230. Promise.prototype._onCancel = function () {};
  4231. Promise.prototype._setOnCancel = function (handler) { ; };
  4232. Promise.prototype._attachCancellationCallback = function(onCancel) {
  4233. ;
  4234. };
  4235. Promise.prototype._captureStackTrace = function () {};
  4236. Promise.prototype._attachExtraTrace = function () {};
  4237. Promise.prototype._clearCancellationData = function() {};
  4238. Promise.prototype._propagateFrom = function (parent, flags) {
  4239. ;
  4240. ;
  4241. };
  4242. function cancellationExecute(executor, resolve, reject) {
  4243. var promise = this;
  4244. try {
  4245. executor(resolve, reject, function(onCancel) {
  4246. if (typeof onCancel !== "function") {
  4247. throw new TypeError("onCancel must be a function, got: " +
  4248. util.toString(onCancel));
  4249. }
  4250. promise._attachCancellationCallback(onCancel);
  4251. });
  4252. } catch (e) {
  4253. return e;
  4254. }
  4255. }
  4256. function cancellationAttachCancellationCallback(onCancel) {
  4257. if (!this._isCancellable()) return this;
  4258. var previousOnCancel = this._onCancel();
  4259. if (previousOnCancel !== undefined) {
  4260. if (util.isArray(previousOnCancel)) {
  4261. previousOnCancel.push(onCancel);
  4262. } else {
  4263. this._setOnCancel([previousOnCancel, onCancel]);
  4264. }
  4265. } else {
  4266. this._setOnCancel(onCancel);
  4267. }
  4268. }
  4269. function cancellationOnCancel() {
  4270. return this._onCancelField;
  4271. }
  4272. function cancellationSetOnCancel(onCancel) {
  4273. this._onCancelField = onCancel;
  4274. }
  4275. function cancellationClearCancellationData() {
  4276. this._cancellationParent = undefined;
  4277. this._onCancelField = undefined;
  4278. }
  4279. function cancellationPropagateFrom(parent, flags) {
  4280. if ((flags & 1) !== 0) {
  4281. this._cancellationParent = parent;
  4282. var branchesRemainingToCancel = parent._branchesRemainingToCancel;
  4283. if (branchesRemainingToCancel === undefined) {
  4284. branchesRemainingToCancel = 0;
  4285. }
  4286. parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
  4287. }
  4288. if ((flags & 2) !== 0 && parent._isBound()) {
  4289. this._setBoundTo(parent._boundTo);
  4290. }
  4291. }
  4292. function bindingPropagateFrom(parent, flags) {
  4293. if ((flags & 2) !== 0 && parent._isBound()) {
  4294. this._setBoundTo(parent._boundTo);
  4295. }
  4296. }
  4297. var propagateFromFunction = bindingPropagateFrom;
  4298. function boundValueFunction() {
  4299. var ret = this._boundTo;
  4300. if (ret !== undefined) {
  4301. if (ret instanceof Promise) {
  4302. if (ret.isFulfilled()) {
  4303. return ret.value();
  4304. } else {
  4305. return undefined;
  4306. }
  4307. }
  4308. }
  4309. return ret;
  4310. }
  4311. function longStackTracesCaptureStackTrace() {
  4312. this._trace = new CapturedTrace(this._peekContext());
  4313. }
  4314. function longStackTracesAttachExtraTrace(error, ignoreSelf) {
  4315. if (canAttachTrace(error)) {
  4316. var trace = this._trace;
  4317. if (trace !== undefined) {
  4318. if (ignoreSelf) trace = trace._parent;
  4319. }
  4320. if (trace !== undefined) {
  4321. trace.attachExtraTrace(error);
  4322. } else if (!error.__stackCleaned__) {
  4323. var parsed = parseStackAndMessage(error);
  4324. util.notEnumerableProp(error, "stack",
  4325. parsed.message + "\n" + parsed.stack.join("\n"));
  4326. util.notEnumerableProp(error, "__stackCleaned__", true);
  4327. }
  4328. }
  4329. }
  4330. function checkForgottenReturns(returnValue, promiseCreated, name, promise,
  4331. parent) {
  4332. if (returnValue === undefined && promiseCreated !== null &&
  4333. wForgottenReturn) {
  4334. if (parent !== undefined && parent._returnedNonUndefined()) return;
  4335. if ((promise._bitField & 65535) === 0) return;
  4336. if (name) name = name + " ";
  4337. var handlerLine = "";
  4338. var creatorLine = "";
  4339. if (promiseCreated._trace) {
  4340. var traceLines = promiseCreated._trace.stack.split("\n");
  4341. var stack = cleanStack(traceLines);
  4342. for (var i = stack.length - 1; i >= 0; --i) {
  4343. var line = stack[i];
  4344. if (!nodeFramePattern.test(line)) {
  4345. var lineMatches = line.match(parseLinePattern);
  4346. if (lineMatches) {
  4347. handlerLine = "at " + lineMatches[1] +
  4348. ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
  4349. }
  4350. break;
  4351. }
  4352. }
  4353. if (stack.length > 0) {
  4354. var firstUserLine = stack[0];
  4355. for (var i = 0; i < traceLines.length; ++i) {
  4356. if (traceLines[i] === firstUserLine) {
  4357. if (i > 0) {
  4358. creatorLine = "\n" + traceLines[i - 1];
  4359. }
  4360. break;
  4361. }
  4362. }
  4363. }
  4364. }
  4365. var msg = "a promise was created in a " + name +
  4366. "handler " + handlerLine + "but was not returned from it, " +
  4367. "see http://goo.gl/rRqMUw" +
  4368. creatorLine;
  4369. promise._warn(msg, true, promiseCreated);
  4370. }
  4371. }
  4372. function deprecated(name, replacement) {
  4373. var message = name +
  4374. " is deprecated and will be removed in a future version.";
  4375. if (replacement) message += " Use " + replacement + " instead.";
  4376. return warn(message);
  4377. }
  4378. function warn(message, shouldUseOwnTrace, promise) {
  4379. if (!config.warnings) return;
  4380. var warning = new Warning(message);
  4381. var ctx;
  4382. if (shouldUseOwnTrace) {
  4383. promise._attachExtraTrace(warning);
  4384. } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
  4385. ctx.attachExtraTrace(warning);
  4386. } else {
  4387. var parsed = parseStackAndMessage(warning);
  4388. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  4389. }
  4390. if (!activeFireEvent("warning", warning)) {
  4391. formatAndLogError(warning, "", true);
  4392. }
  4393. }
  4394. function reconstructStack(message, stacks) {
  4395. for (var i = 0; i < stacks.length - 1; ++i) {
  4396. stacks[i].push("From previous event:");
  4397. stacks[i] = stacks[i].join("\n");
  4398. }
  4399. if (i < stacks.length) {
  4400. stacks[i] = stacks[i].join("\n");
  4401. }
  4402. return message + "\n" + stacks.join("\n");
  4403. }
  4404. function removeDuplicateOrEmptyJumps(stacks) {
  4405. for (var i = 0; i < stacks.length; ++i) {
  4406. if (stacks[i].length === 0 ||
  4407. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  4408. stacks.splice(i, 1);
  4409. i--;
  4410. }
  4411. }
  4412. }
  4413. function removeCommonRoots(stacks) {
  4414. var current = stacks[0];
  4415. for (var i = 1; i < stacks.length; ++i) {
  4416. var prev = stacks[i];
  4417. var currentLastIndex = current.length - 1;
  4418. var currentLastLine = current[currentLastIndex];
  4419. var commonRootMeetPoint = -1;
  4420. for (var j = prev.length - 1; j >= 0; --j) {
  4421. if (prev[j] === currentLastLine) {
  4422. commonRootMeetPoint = j;
  4423. break;
  4424. }
  4425. }
  4426. for (var j = commonRootMeetPoint; j >= 0; --j) {
  4427. var line = prev[j];
  4428. if (current[currentLastIndex] === line) {
  4429. current.pop();
  4430. currentLastIndex--;
  4431. } else {
  4432. break;
  4433. }
  4434. }
  4435. current = prev;
  4436. }
  4437. }
  4438. function cleanStack(stack) {
  4439. var ret = [];
  4440. for (var i = 0; i < stack.length; ++i) {
  4441. var line = stack[i];
  4442. var isTraceLine = " (No stack trace)" === line ||
  4443. stackFramePattern.test(line);
  4444. var isInternalFrame = isTraceLine && shouldIgnore(line);
  4445. if (isTraceLine && !isInternalFrame) {
  4446. if (indentStackFrames && line.charAt(0) !== " ") {
  4447. line = " " + line;
  4448. }
  4449. ret.push(line);
  4450. }
  4451. }
  4452. return ret;
  4453. }
  4454. function stackFramesAsArray(error) {
  4455. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  4456. for (var i = 0; i < stack.length; ++i) {
  4457. var line = stack[i];
  4458. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  4459. break;
  4460. }
  4461. }
  4462. if (i > 0 && error.name != "SyntaxError") {
  4463. stack = stack.slice(i);
  4464. }
  4465. return stack;
  4466. }
  4467. function parseStackAndMessage(error) {
  4468. var stack = error.stack;
  4469. var message = error.toString();
  4470. stack = typeof stack === "string" && stack.length > 0
  4471. ? stackFramesAsArray(error) : [" (No stack trace)"];
  4472. return {
  4473. message: message,
  4474. stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
  4475. };
  4476. }
  4477. function formatAndLogError(error, title, isSoft) {
  4478. if (typeof console !== "undefined") {
  4479. var message;
  4480. if (util.isObject(error)) {
  4481. var stack = error.stack;
  4482. message = title + formatStack(stack, error);
  4483. } else {
  4484. message = title + String(error);
  4485. }
  4486. if (typeof printWarning === "function") {
  4487. printWarning(message, isSoft);
  4488. } else if (typeof console.log === "function" ||
  4489. typeof console.log === "object") {
  4490. console.log(message);
  4491. }
  4492. }
  4493. }
  4494. function fireRejectionEvent(name, localHandler, reason, promise) {
  4495. var localEventFired = false;
  4496. try {
  4497. if (typeof localHandler === "function") {
  4498. localEventFired = true;
  4499. if (name === "rejectionHandled") {
  4500. localHandler(promise);
  4501. } else {
  4502. localHandler(reason, promise);
  4503. }
  4504. }
  4505. } catch (e) {
  4506. async.throwLater(e);
  4507. }
  4508. if (name === "unhandledRejection") {
  4509. if (!activeFireEvent(name, reason, promise) && !localEventFired) {
  4510. formatAndLogError(reason, "Unhandled rejection ");
  4511. }
  4512. } else {
  4513. activeFireEvent(name, promise);
  4514. }
  4515. }
  4516. function formatNonError(obj) {
  4517. var str;
  4518. if (typeof obj === "function") {
  4519. str = "[function " +
  4520. (obj.name || "anonymous") +
  4521. "]";
  4522. } else {
  4523. str = obj && typeof obj.toString === "function"
  4524. ? obj.toString() : util.toString(obj);
  4525. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  4526. if (ruselessToString.test(str)) {
  4527. try {
  4528. var newStr = JSON.stringify(obj);
  4529. str = newStr;
  4530. }
  4531. catch(e) {
  4532. }
  4533. }
  4534. if (str.length === 0) {
  4535. str = "(empty array)";
  4536. }
  4537. }
  4538. return ("(<" + snip(str) + ">, no stack trace)");
  4539. }
  4540. function snip(str) {
  4541. var maxChars = 41;
  4542. if (str.length < maxChars) {
  4543. return str;
  4544. }
  4545. return str.substr(0, maxChars - 3) + "...";
  4546. }
  4547. function longStackTracesIsSupported() {
  4548. return typeof captureStackTrace === "function";
  4549. }
  4550. var shouldIgnore = function() { return false; };
  4551. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  4552. function parseLineInfo(line) {
  4553. var matches = line.match(parseLineInfoRegex);
  4554. if (matches) {
  4555. return {
  4556. fileName: matches[1],
  4557. line: parseInt(matches[2], 10)
  4558. };
  4559. }
  4560. }
  4561. function setBounds(firstLineError, lastLineError) {
  4562. if (!longStackTracesIsSupported()) return;
  4563. var firstStackLines = firstLineError.stack.split("\n");
  4564. var lastStackLines = lastLineError.stack.split("\n");
  4565. var firstIndex = -1;
  4566. var lastIndex = -1;
  4567. var firstFileName;
  4568. var lastFileName;
  4569. for (var i = 0; i < firstStackLines.length; ++i) {
  4570. var result = parseLineInfo(firstStackLines[i]);
  4571. if (result) {
  4572. firstFileName = result.fileName;
  4573. firstIndex = result.line;
  4574. break;
  4575. }
  4576. }
  4577. for (var i = 0; i < lastStackLines.length; ++i) {
  4578. var result = parseLineInfo(lastStackLines[i]);
  4579. if (result) {
  4580. lastFileName = result.fileName;
  4581. lastIndex = result.line;
  4582. break;
  4583. }
  4584. }
  4585. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  4586. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  4587. return;
  4588. }
  4589. shouldIgnore = function(line) {
  4590. if (bluebirdFramePattern.test(line)) return true;
  4591. var info = parseLineInfo(line);
  4592. if (info) {
  4593. if (info.fileName === firstFileName &&
  4594. (firstIndex <= info.line && info.line <= lastIndex)) {
  4595. return true;
  4596. }
  4597. }
  4598. return false;
  4599. };
  4600. }
  4601. function CapturedTrace(parent) {
  4602. this._parent = parent;
  4603. this._promisesCreated = 0;
  4604. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  4605. captureStackTrace(this, CapturedTrace);
  4606. if (length > 32) this.uncycle();
  4607. }
  4608. util.inherits(CapturedTrace, Error);
  4609. Context.CapturedTrace = CapturedTrace;
  4610. CapturedTrace.prototype.uncycle = function() {
  4611. var length = this._length;
  4612. if (length < 2) return;
  4613. var nodes = [];
  4614. var stackToIndex = {};
  4615. for (var i = 0, node = this; node !== undefined; ++i) {
  4616. nodes.push(node);
  4617. node = node._parent;
  4618. }
  4619. length = this._length = i;
  4620. for (var i = length - 1; i >= 0; --i) {
  4621. var stack = nodes[i].stack;
  4622. if (stackToIndex[stack] === undefined) {
  4623. stackToIndex[stack] = i;
  4624. }
  4625. }
  4626. for (var i = 0; i < length; ++i) {
  4627. var currentStack = nodes[i].stack;
  4628. var index = stackToIndex[currentStack];
  4629. if (index !== undefined && index !== i) {
  4630. if (index > 0) {
  4631. nodes[index - 1]._parent = undefined;
  4632. nodes[index - 1]._length = 1;
  4633. }
  4634. nodes[i]._parent = undefined;
  4635. nodes[i]._length = 1;
  4636. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  4637. if (index < length - 1) {
  4638. cycleEdgeNode._parent = nodes[index + 1];
  4639. cycleEdgeNode._parent.uncycle();
  4640. cycleEdgeNode._length =
  4641. cycleEdgeNode._parent._length + 1;
  4642. } else {
  4643. cycleEdgeNode._parent = undefined;
  4644. cycleEdgeNode._length = 1;
  4645. }
  4646. var currentChildLength = cycleEdgeNode._length + 1;
  4647. for (var j = i - 2; j >= 0; --j) {
  4648. nodes[j]._length = currentChildLength;
  4649. currentChildLength++;
  4650. }
  4651. return;
  4652. }
  4653. }
  4654. };
  4655. CapturedTrace.prototype.attachExtraTrace = function(error) {
  4656. if (error.__stackCleaned__) return;
  4657. this.uncycle();
  4658. var parsed = parseStackAndMessage(error);
  4659. var message = parsed.message;
  4660. var stacks = [parsed.stack];
  4661. var trace = this;
  4662. while (trace !== undefined) {
  4663. stacks.push(cleanStack(trace.stack.split("\n")));
  4664. trace = trace._parent;
  4665. }
  4666. removeCommonRoots(stacks);
  4667. removeDuplicateOrEmptyJumps(stacks);
  4668. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  4669. util.notEnumerableProp(error, "__stackCleaned__", true);
  4670. };
  4671. var captureStackTrace = (function stackDetection() {
  4672. var v8stackFramePattern = /^\s*at\s*/;
  4673. var v8stackFormatter = function(stack, error) {
  4674. if (typeof stack === "string") return stack;
  4675. if (error.name !== undefined &&
  4676. error.message !== undefined) {
  4677. return error.toString();
  4678. }
  4679. return formatNonError(error);
  4680. };
  4681. if (typeof Error.stackTraceLimit === "number" &&
  4682. typeof Error.captureStackTrace === "function") {
  4683. Error.stackTraceLimit += 6;
  4684. stackFramePattern = v8stackFramePattern;
  4685. formatStack = v8stackFormatter;
  4686. var captureStackTrace = Error.captureStackTrace;
  4687. shouldIgnore = function(line) {
  4688. return bluebirdFramePattern.test(line);
  4689. };
  4690. return function(receiver, ignoreUntil) {
  4691. Error.stackTraceLimit += 6;
  4692. captureStackTrace(receiver, ignoreUntil);
  4693. Error.stackTraceLimit -= 6;
  4694. };
  4695. }
  4696. var err = new Error();
  4697. if (typeof err.stack === "string" &&
  4698. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  4699. stackFramePattern = /@/;
  4700. formatStack = v8stackFormatter;
  4701. indentStackFrames = true;
  4702. return function captureStackTrace(o) {
  4703. o.stack = new Error().stack;
  4704. };
  4705. }
  4706. var hasStackAfterThrow;
  4707. try { throw new Error(); }
  4708. catch(e) {
  4709. hasStackAfterThrow = ("stack" in e);
  4710. }
  4711. if (!("stack" in err) && hasStackAfterThrow &&
  4712. typeof Error.stackTraceLimit === "number") {
  4713. stackFramePattern = v8stackFramePattern;
  4714. formatStack = v8stackFormatter;
  4715. return function captureStackTrace(o) {
  4716. Error.stackTraceLimit += 6;
  4717. try { throw new Error(); }
  4718. catch(e) { o.stack = e.stack; }
  4719. Error.stackTraceLimit -= 6;
  4720. };
  4721. }
  4722. formatStack = function(stack, error) {
  4723. if (typeof stack === "string") return stack;
  4724. if ((typeof error === "object" ||
  4725. typeof error === "function") &&
  4726. error.name !== undefined &&
  4727. error.message !== undefined) {
  4728. return error.toString();
  4729. }
  4730. return formatNonError(error);
  4731. };
  4732. return null;
  4733. })([]);
  4734. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  4735. printWarning = function (message) {
  4736. console.warn(message);
  4737. };
  4738. if (util.isNode && process.stderr.isTTY) {
  4739. printWarning = function(message, isSoft) {
  4740. var color = isSoft ? "\u001b[33m" : "\u001b[31m";
  4741. console.warn(color + message + "\u001b[0m\n");
  4742. };
  4743. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  4744. printWarning = function(message, isSoft) {
  4745. console.warn("%c" + message,
  4746. isSoft ? "color: darkorange" : "color: red");
  4747. };
  4748. }
  4749. }
  4750. var config = {
  4751. warnings: warnings,
  4752. longStackTraces: false,
  4753. cancellation: false,
  4754. monitoring: false
  4755. };
  4756. if (longStackTraces) Promise.longStackTraces();
  4757. return {
  4758. longStackTraces: function() {
  4759. return config.longStackTraces;
  4760. },
  4761. warnings: function() {
  4762. return config.warnings;
  4763. },
  4764. cancellation: function() {
  4765. return config.cancellation;
  4766. },
  4767. monitoring: function() {
  4768. return config.monitoring;
  4769. },
  4770. propagateFromFunction: function() {
  4771. return propagateFromFunction;
  4772. },
  4773. boundValueFunction: function() {
  4774. return boundValueFunction;
  4775. },
  4776. checkForgottenReturns: checkForgottenReturns,
  4777. setBounds: setBounds,
  4778. warn: warn,
  4779. deprecated: deprecated,
  4780. CapturedTrace: CapturedTrace,
  4781. fireDomEvent: fireDomEvent,
  4782. fireGlobalEvent: fireGlobalEvent
  4783. };
  4784. };
  4785. }).call(this,require('_process'))
  4786. },{"./errors":50,"./util":74,"_process":138}],48:[function(require,module,exports){
  4787. "use strict";
  4788. module.exports = function(Promise) {
  4789. function returner() {
  4790. return this.value;
  4791. }
  4792. function thrower() {
  4793. throw this.reason;
  4794. }
  4795. Promise.prototype["return"] =
  4796. Promise.prototype.thenReturn = function (value) {
  4797. if (value instanceof Promise) value.suppressUnhandledRejections();
  4798. return this._then(
  4799. returner, undefined, undefined, {value: value}, undefined);
  4800. };
  4801. Promise.prototype["throw"] =
  4802. Promise.prototype.thenThrow = function (reason) {
  4803. return this._then(
  4804. thrower, undefined, undefined, {reason: reason}, undefined);
  4805. };
  4806. Promise.prototype.catchThrow = function (reason) {
  4807. if (arguments.length <= 1) {
  4808. return this._then(
  4809. undefined, thrower, undefined, {reason: reason}, undefined);
  4810. } else {
  4811. var _reason = arguments[1];
  4812. var handler = function() {throw _reason;};
  4813. return this.caught(reason, handler);
  4814. }
  4815. };
  4816. Promise.prototype.catchReturn = function (value) {
  4817. if (arguments.length <= 1) {
  4818. if (value instanceof Promise) value.suppressUnhandledRejections();
  4819. return this._then(
  4820. undefined, returner, undefined, {value: value}, undefined);
  4821. } else {
  4822. var _value = arguments[1];
  4823. if (_value instanceof Promise) _value.suppressUnhandledRejections();
  4824. var handler = function() {return _value;};
  4825. return this.caught(value, handler);
  4826. }
  4827. };
  4828. };
  4829. },{}],49:[function(require,module,exports){
  4830. "use strict";
  4831. module.exports = function(Promise, INTERNAL) {
  4832. var PromiseReduce = Promise.reduce;
  4833. var PromiseAll = Promise.all;
  4834. function promiseAllThis() {
  4835. return PromiseAll(this);
  4836. }
  4837. function PromiseMapSeries(promises, fn) {
  4838. return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
  4839. }
  4840. Promise.prototype.each = function (fn) {
  4841. return PromiseReduce(this, fn, INTERNAL, 0)
  4842. ._then(promiseAllThis, undefined, undefined, this, undefined);
  4843. };
  4844. Promise.prototype.mapSeries = function (fn) {
  4845. return PromiseReduce(this, fn, INTERNAL, INTERNAL);
  4846. };
  4847. Promise.each = function (promises, fn) {
  4848. return PromiseReduce(promises, fn, INTERNAL, 0)
  4849. ._then(promiseAllThis, undefined, undefined, promises, undefined);
  4850. };
  4851. Promise.mapSeries = PromiseMapSeries;
  4852. };
  4853. },{}],50:[function(require,module,exports){
  4854. "use strict";
  4855. var es5 = require("./es5");
  4856. var Objectfreeze = es5.freeze;
  4857. var util = require("./util");
  4858. var inherits = util.inherits;
  4859. var notEnumerableProp = util.notEnumerableProp;
  4860. function subError(nameProperty, defaultMessage) {
  4861. function SubError(message) {
  4862. if (!(this instanceof SubError)) return new SubError(message);
  4863. notEnumerableProp(this, "message",
  4864. typeof message === "string" ? message : defaultMessage);
  4865. notEnumerableProp(this, "name", nameProperty);
  4866. if (Error.captureStackTrace) {
  4867. Error.captureStackTrace(this, this.constructor);
  4868. } else {
  4869. Error.call(this);
  4870. }
  4871. }
  4872. inherits(SubError, Error);
  4873. return SubError;
  4874. }
  4875. var _TypeError, _RangeError;
  4876. var Warning = subError("Warning", "warning");
  4877. var CancellationError = subError("CancellationError", "cancellation error");
  4878. var TimeoutError = subError("TimeoutError", "timeout error");
  4879. var AggregateError = subError("AggregateError", "aggregate error");
  4880. try {
  4881. _TypeError = TypeError;
  4882. _RangeError = RangeError;
  4883. } catch(e) {
  4884. _TypeError = subError("TypeError", "type error");
  4885. _RangeError = subError("RangeError", "range error");
  4886. }
  4887. var methods = ("join pop push shift unshift slice filter forEach some " +
  4888. "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  4889. for (var i = 0; i < methods.length; ++i) {
  4890. if (typeof Array.prototype[methods[i]] === "function") {
  4891. AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
  4892. }
  4893. }
  4894. es5.defineProperty(AggregateError.prototype, "length", {
  4895. value: 0,
  4896. configurable: false,
  4897. writable: true,
  4898. enumerable: true
  4899. });
  4900. AggregateError.prototype["isOperational"] = true;
  4901. var level = 0;
  4902. AggregateError.prototype.toString = function() {
  4903. var indent = Array(level * 4 + 1).join(" ");
  4904. var ret = "\n" + indent + "AggregateError of:" + "\n";
  4905. level++;
  4906. indent = Array(level * 4 + 1).join(" ");
  4907. for (var i = 0; i < this.length; ++i) {
  4908. var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
  4909. var lines = str.split("\n");
  4910. for (var j = 0; j < lines.length; ++j) {
  4911. lines[j] = indent + lines[j];
  4912. }
  4913. str = lines.join("\n");
  4914. ret += str + "\n";
  4915. }
  4916. level--;
  4917. return ret;
  4918. };
  4919. function OperationalError(message) {
  4920. if (!(this instanceof OperationalError))
  4921. return new OperationalError(message);
  4922. notEnumerableProp(this, "name", "OperationalError");
  4923. notEnumerableProp(this, "message", message);
  4924. this.cause = message;
  4925. this["isOperational"] = true;
  4926. if (message instanceof Error) {
  4927. notEnumerableProp(this, "message", message.message);
  4928. notEnumerableProp(this, "stack", message.stack);
  4929. } else if (Error.captureStackTrace) {
  4930. Error.captureStackTrace(this, this.constructor);
  4931. }
  4932. }
  4933. inherits(OperationalError, Error);
  4934. var errorTypes = Error["__BluebirdErrorTypes__"];
  4935. if (!errorTypes) {
  4936. errorTypes = Objectfreeze({
  4937. CancellationError: CancellationError,
  4938. TimeoutError: TimeoutError,
  4939. OperationalError: OperationalError,
  4940. RejectionError: OperationalError,
  4941. AggregateError: AggregateError
  4942. });
  4943. es5.defineProperty(Error, "__BluebirdErrorTypes__", {
  4944. value: errorTypes,
  4945. writable: false,
  4946. enumerable: false,
  4947. configurable: false
  4948. });
  4949. }
  4950. module.exports = {
  4951. Error: Error,
  4952. TypeError: _TypeError,
  4953. RangeError: _RangeError,
  4954. CancellationError: errorTypes.CancellationError,
  4955. OperationalError: errorTypes.OperationalError,
  4956. TimeoutError: errorTypes.TimeoutError,
  4957. AggregateError: errorTypes.AggregateError,
  4958. Warning: Warning
  4959. };
  4960. },{"./es5":51,"./util":74}],51:[function(require,module,exports){
  4961. var isES5 = (function(){
  4962. "use strict";
  4963. return this === undefined;
  4964. })();
  4965. if (isES5) {
  4966. module.exports = {
  4967. freeze: Object.freeze,
  4968. defineProperty: Object.defineProperty,
  4969. getDescriptor: Object.getOwnPropertyDescriptor,
  4970. keys: Object.keys,
  4971. names: Object.getOwnPropertyNames,
  4972. getPrototypeOf: Object.getPrototypeOf,
  4973. isArray: Array.isArray,
  4974. isES5: isES5,
  4975. propertyIsWritable: function(obj, prop) {
  4976. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  4977. return !!(!descriptor || descriptor.writable || descriptor.set);
  4978. }
  4979. };
  4980. } else {
  4981. var has = {}.hasOwnProperty;
  4982. var str = {}.toString;
  4983. var proto = {}.constructor.prototype;
  4984. var ObjectKeys = function (o) {
  4985. var ret = [];
  4986. for (var key in o) {
  4987. if (has.call(o, key)) {
  4988. ret.push(key);
  4989. }
  4990. }
  4991. return ret;
  4992. };
  4993. var ObjectGetDescriptor = function(o, key) {
  4994. return {value: o[key]};
  4995. };
  4996. var ObjectDefineProperty = function (o, key, desc) {
  4997. o[key] = desc.value;
  4998. return o;
  4999. };
  5000. var ObjectFreeze = function (obj) {
  5001. return obj;
  5002. };
  5003. var ObjectGetPrototypeOf = function (obj) {
  5004. try {
  5005. return Object(obj).constructor.prototype;
  5006. }
  5007. catch (e) {
  5008. return proto;
  5009. }
  5010. };
  5011. var ArrayIsArray = function (obj) {
  5012. try {
  5013. return str.call(obj) === "[object Array]";
  5014. }
  5015. catch(e) {
  5016. return false;
  5017. }
  5018. };
  5019. module.exports = {
  5020. isArray: ArrayIsArray,
  5021. keys: ObjectKeys,
  5022. names: ObjectKeys,
  5023. defineProperty: ObjectDefineProperty,
  5024. getDescriptor: ObjectGetDescriptor,
  5025. freeze: ObjectFreeze,
  5026. getPrototypeOf: ObjectGetPrototypeOf,
  5027. isES5: isES5,
  5028. propertyIsWritable: function() {
  5029. return true;
  5030. }
  5031. };
  5032. }
  5033. },{}],52:[function(require,module,exports){
  5034. "use strict";
  5035. module.exports = function(Promise, INTERNAL) {
  5036. var PromiseMap = Promise.map;
  5037. Promise.prototype.filter = function (fn, options) {
  5038. return PromiseMap(this, fn, options, INTERNAL);
  5039. };
  5040. Promise.filter = function (promises, fn, options) {
  5041. return PromiseMap(promises, fn, options, INTERNAL);
  5042. };
  5043. };
  5044. },{}],53:[function(require,module,exports){
  5045. "use strict";
  5046. module.exports = function(Promise, tryConvertToPromise) {
  5047. var util = require("./util");
  5048. var CancellationError = Promise.CancellationError;
  5049. var errorObj = util.errorObj;
  5050. function PassThroughHandlerContext(promise, type, handler) {
  5051. this.promise = promise;
  5052. this.type = type;
  5053. this.handler = handler;
  5054. this.called = false;
  5055. this.cancelPromise = null;
  5056. }
  5057. PassThroughHandlerContext.prototype.isFinallyHandler = function() {
  5058. return this.type === 0;
  5059. };
  5060. function FinallyHandlerCancelReaction(finallyHandler) {
  5061. this.finallyHandler = finallyHandler;
  5062. }
  5063. FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
  5064. checkCancel(this.finallyHandler);
  5065. };
  5066. function checkCancel(ctx, reason) {
  5067. if (ctx.cancelPromise != null) {
  5068. if (arguments.length > 1) {
  5069. ctx.cancelPromise._reject(reason);
  5070. } else {
  5071. ctx.cancelPromise._cancel();
  5072. }
  5073. ctx.cancelPromise = null;
  5074. return true;
  5075. }
  5076. return false;
  5077. }
  5078. function succeed() {
  5079. return finallyHandler.call(this, this.promise._target()._settledValue());
  5080. }
  5081. function fail(reason) {
  5082. if (checkCancel(this, reason)) return;
  5083. errorObj.e = reason;
  5084. return errorObj;
  5085. }
  5086. function finallyHandler(reasonOrValue) {
  5087. var promise = this.promise;
  5088. var handler = this.handler;
  5089. if (!this.called) {
  5090. this.called = true;
  5091. var ret = this.isFinallyHandler()
  5092. ? handler.call(promise._boundValue())
  5093. : handler.call(promise._boundValue(), reasonOrValue);
  5094. if (ret !== undefined) {
  5095. promise._setReturnedNonUndefined();
  5096. var maybePromise = tryConvertToPromise(ret, promise);
  5097. if (maybePromise instanceof Promise) {
  5098. if (this.cancelPromise != null) {
  5099. if (maybePromise._isCancelled()) {
  5100. var reason =
  5101. new CancellationError("late cancellation observer");
  5102. promise._attachExtraTrace(reason);
  5103. errorObj.e = reason;
  5104. return errorObj;
  5105. } else if (maybePromise.isPending()) {
  5106. maybePromise._attachCancellationCallback(
  5107. new FinallyHandlerCancelReaction(this));
  5108. }
  5109. }
  5110. return maybePromise._then(
  5111. succeed, fail, undefined, this, undefined);
  5112. }
  5113. }
  5114. }
  5115. if (promise.isRejected()) {
  5116. checkCancel(this);
  5117. errorObj.e = reasonOrValue;
  5118. return errorObj;
  5119. } else {
  5120. checkCancel(this);
  5121. return reasonOrValue;
  5122. }
  5123. }
  5124. Promise.prototype._passThrough = function(handler, type, success, fail) {
  5125. if (typeof handler !== "function") return this.then();
  5126. return this._then(success,
  5127. fail,
  5128. undefined,
  5129. new PassThroughHandlerContext(this, type, handler),
  5130. undefined);
  5131. };
  5132. Promise.prototype.lastly =
  5133. Promise.prototype["finally"] = function (handler) {
  5134. return this._passThrough(handler,
  5135. 0,
  5136. finallyHandler,
  5137. finallyHandler);
  5138. };
  5139. Promise.prototype.tap = function (handler) {
  5140. return this._passThrough(handler, 1, finallyHandler);
  5141. };
  5142. return PassThroughHandlerContext;
  5143. };
  5144. },{"./util":74}],54:[function(require,module,exports){
  5145. "use strict";
  5146. module.exports = function(Promise,
  5147. apiRejection,
  5148. INTERNAL,
  5149. tryConvertToPromise,
  5150. Proxyable,
  5151. debug) {
  5152. var errors = require("./errors");
  5153. var TypeError = errors.TypeError;
  5154. var util = require("./util");
  5155. var errorObj = util.errorObj;
  5156. var tryCatch = util.tryCatch;
  5157. var yieldHandlers = [];
  5158. function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
  5159. for (var i = 0; i < yieldHandlers.length; ++i) {
  5160. traceParent._pushContext();
  5161. var result = tryCatch(yieldHandlers[i])(value);
  5162. traceParent._popContext();
  5163. if (result === errorObj) {
  5164. traceParent._pushContext();
  5165. var ret = Promise.reject(errorObj.e);
  5166. traceParent._popContext();
  5167. return ret;
  5168. }
  5169. var maybePromise = tryConvertToPromise(result, traceParent);
  5170. if (maybePromise instanceof Promise) return maybePromise;
  5171. }
  5172. return null;
  5173. }
  5174. function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
  5175. if (debug.cancellation()) {
  5176. var internal = new Promise(INTERNAL);
  5177. var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
  5178. this._promise = internal.lastly(function() {
  5179. return _finallyPromise;
  5180. });
  5181. internal._captureStackTrace();
  5182. internal._setOnCancel(this);
  5183. } else {
  5184. var promise = this._promise = new Promise(INTERNAL);
  5185. promise._captureStackTrace();
  5186. }
  5187. this._stack = stack;
  5188. this._generatorFunction = generatorFunction;
  5189. this._receiver = receiver;
  5190. this._generator = undefined;
  5191. this._yieldHandlers = typeof yieldHandler === "function"
  5192. ? [yieldHandler].concat(yieldHandlers)
  5193. : yieldHandlers;
  5194. this._yieldedPromise = null;
  5195. this._cancellationPhase = false;
  5196. }
  5197. util.inherits(PromiseSpawn, Proxyable);
  5198. PromiseSpawn.prototype._isResolved = function() {
  5199. return this._promise === null;
  5200. };
  5201. PromiseSpawn.prototype._cleanup = function() {
  5202. this._promise = this._generator = null;
  5203. if (debug.cancellation() && this._finallyPromise !== null) {
  5204. this._finallyPromise._fulfill();
  5205. this._finallyPromise = null;
  5206. }
  5207. };
  5208. PromiseSpawn.prototype._promiseCancelled = function() {
  5209. if (this._isResolved()) return;
  5210. var implementsReturn = typeof this._generator["return"] !== "undefined";
  5211. var result;
  5212. if (!implementsReturn) {
  5213. var reason = new Promise.CancellationError(
  5214. "generator .return() sentinel");
  5215. Promise.coroutine.returnSentinel = reason;
  5216. this._promise._attachExtraTrace(reason);
  5217. this._promise._pushContext();
  5218. result = tryCatch(this._generator["throw"]).call(this._generator,
  5219. reason);
  5220. this._promise._popContext();
  5221. } else {
  5222. this._promise._pushContext();
  5223. result = tryCatch(this._generator["return"]).call(this._generator,
  5224. undefined);
  5225. this._promise._popContext();
  5226. }
  5227. this._cancellationPhase = true;
  5228. this._yieldedPromise = null;
  5229. this._continue(result);
  5230. };
  5231. PromiseSpawn.prototype._promiseFulfilled = function(value) {
  5232. this._yieldedPromise = null;
  5233. this._promise._pushContext();
  5234. var result = tryCatch(this._generator.next).call(this._generator, value);
  5235. this._promise._popContext();
  5236. this._continue(result);
  5237. };
  5238. PromiseSpawn.prototype._promiseRejected = function(reason) {
  5239. this._yieldedPromise = null;
  5240. this._promise._attachExtraTrace(reason);
  5241. this._promise._pushContext();
  5242. var result = tryCatch(this._generator["throw"])
  5243. .call(this._generator, reason);
  5244. this._promise._popContext();
  5245. this._continue(result);
  5246. };
  5247. PromiseSpawn.prototype._resultCancelled = function() {
  5248. if (this._yieldedPromise instanceof Promise) {
  5249. var promise = this._yieldedPromise;
  5250. this._yieldedPromise = null;
  5251. promise.cancel();
  5252. }
  5253. };
  5254. PromiseSpawn.prototype.promise = function () {
  5255. return this._promise;
  5256. };
  5257. PromiseSpawn.prototype._run = function () {
  5258. this._generator = this._generatorFunction.call(this._receiver);
  5259. this._receiver =
  5260. this._generatorFunction = undefined;
  5261. this._promiseFulfilled(undefined);
  5262. };
  5263. PromiseSpawn.prototype._continue = function (result) {
  5264. var promise = this._promise;
  5265. if (result === errorObj) {
  5266. this._cleanup();
  5267. if (this._cancellationPhase) {
  5268. return promise.cancel();
  5269. } else {
  5270. return promise._rejectCallback(result.e, false);
  5271. }
  5272. }
  5273. var value = result.value;
  5274. if (result.done === true) {
  5275. this._cleanup();
  5276. if (this._cancellationPhase) {
  5277. return promise.cancel();
  5278. } else {
  5279. return promise._resolveCallback(value);
  5280. }
  5281. } else {
  5282. var maybePromise = tryConvertToPromise(value, this._promise);
  5283. if (!(maybePromise instanceof Promise)) {
  5284. maybePromise =
  5285. promiseFromYieldHandler(maybePromise,
  5286. this._yieldHandlers,
  5287. this._promise);
  5288. if (maybePromise === null) {
  5289. this._promiseRejected(
  5290. new TypeError(
  5291. "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
  5292. "From coroutine:\u000a" +
  5293. this._stack.split("\n").slice(1, -7).join("\n")
  5294. )
  5295. );
  5296. return;
  5297. }
  5298. }
  5299. maybePromise = maybePromise._target();
  5300. var bitField = maybePromise._bitField;
  5301. ;
  5302. if (((bitField & 50397184) === 0)) {
  5303. this._yieldedPromise = maybePromise;
  5304. maybePromise._proxy(this, null);
  5305. } else if (((bitField & 33554432) !== 0)) {
  5306. Promise._async.invoke(
  5307. this._promiseFulfilled, this, maybePromise._value()
  5308. );
  5309. } else if (((bitField & 16777216) !== 0)) {
  5310. Promise._async.invoke(
  5311. this._promiseRejected, this, maybePromise._reason()
  5312. );
  5313. } else {
  5314. this._promiseCancelled();
  5315. }
  5316. }
  5317. };
  5318. Promise.coroutine = function (generatorFunction, options) {
  5319. if (typeof generatorFunction !== "function") {
  5320. throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5321. }
  5322. var yieldHandler = Object(options).yieldHandler;
  5323. var PromiseSpawn$ = PromiseSpawn;
  5324. var stack = new Error().stack;
  5325. return function () {
  5326. var generator = generatorFunction.apply(this, arguments);
  5327. var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
  5328. stack);
  5329. var ret = spawn.promise();
  5330. spawn._generator = generator;
  5331. spawn._promiseFulfilled(undefined);
  5332. return ret;
  5333. };
  5334. };
  5335. Promise.coroutine.addYieldHandler = function(fn) {
  5336. if (typeof fn !== "function") {
  5337. throw new TypeError("expecting a function but got " + util.classString(fn));
  5338. }
  5339. yieldHandlers.push(fn);
  5340. };
  5341. Promise.spawn = function (generatorFunction) {
  5342. debug.deprecated("Promise.spawn()", "Promise.coroutine()");
  5343. if (typeof generatorFunction !== "function") {
  5344. return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5345. }
  5346. var spawn = new PromiseSpawn(generatorFunction, this);
  5347. var ret = spawn.promise();
  5348. spawn._run(Promise.spawn);
  5349. return ret;
  5350. };
  5351. };
  5352. },{"./errors":50,"./util":74}],55:[function(require,module,exports){
  5353. "use strict";
  5354. module.exports =
  5355. function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
  5356. getDomain) {
  5357. var util = require("./util");
  5358. var canEvaluate = util.canEvaluate;
  5359. var tryCatch = util.tryCatch;
  5360. var errorObj = util.errorObj;
  5361. var reject;
  5362. if (!false) {
  5363. if (canEvaluate) {
  5364. var thenCallback = function(i) {
  5365. return new Function("value", "holder", " \n\
  5366. 'use strict'; \n\
  5367. holder.pIndex = value; \n\
  5368. holder.checkFulfillment(this); \n\
  5369. ".replace(/Index/g, i));
  5370. };
  5371. var promiseSetter = function(i) {
  5372. return new Function("promise", "holder", " \n\
  5373. 'use strict'; \n\
  5374. holder.pIndex = promise; \n\
  5375. ".replace(/Index/g, i));
  5376. };
  5377. var generateHolderClass = function(total) {
  5378. var props = new Array(total);
  5379. for (var i = 0; i < props.length; ++i) {
  5380. props[i] = "this.p" + (i+1);
  5381. }
  5382. var assignment = props.join(" = ") + " = null;";
  5383. var cancellationCode= "var promise;\n" + props.map(function(prop) {
  5384. return " \n\
  5385. promise = " + prop + "; \n\
  5386. if (promise instanceof Promise) { \n\
  5387. promise.cancel(); \n\
  5388. } \n\
  5389. ";
  5390. }).join("\n");
  5391. var passedArguments = props.join(", ");
  5392. var name = "Holder$" + total;
  5393. var code = "return function(tryCatch, errorObj, Promise, async) { \n\
  5394. 'use strict'; \n\
  5395. function [TheName](fn) { \n\
  5396. [TheProperties] \n\
  5397. this.fn = fn; \n\
  5398. this.asyncNeeded = true; \n\
  5399. this.now = 0; \n\
  5400. } \n\
  5401. \n\
  5402. [TheName].prototype._callFunction = function(promise) { \n\
  5403. promise._pushContext(); \n\
  5404. var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
  5405. promise._popContext(); \n\
  5406. if (ret === errorObj) { \n\
  5407. promise._rejectCallback(ret.e, false); \n\
  5408. } else { \n\
  5409. promise._resolveCallback(ret); \n\
  5410. } \n\
  5411. }; \n\
  5412. \n\
  5413. [TheName].prototype.checkFulfillment = function(promise) { \n\
  5414. var now = ++this.now; \n\
  5415. if (now === [TheTotal]) { \n\
  5416. if (this.asyncNeeded) { \n\
  5417. async.invoke(this._callFunction, this, promise); \n\
  5418. } else { \n\
  5419. this._callFunction(promise); \n\
  5420. } \n\
  5421. \n\
  5422. } \n\
  5423. }; \n\
  5424. \n\
  5425. [TheName].prototype._resultCancelled = function() { \n\
  5426. [CancellationCode] \n\
  5427. }; \n\
  5428. \n\
  5429. return [TheName]; \n\
  5430. }(tryCatch, errorObj, Promise, async); \n\
  5431. ";
  5432. code = code.replace(/\[TheName\]/g, name)
  5433. .replace(/\[TheTotal\]/g, total)
  5434. .replace(/\[ThePassedArguments\]/g, passedArguments)
  5435. .replace(/\[TheProperties\]/g, assignment)
  5436. .replace(/\[CancellationCode\]/g, cancellationCode);
  5437. return new Function("tryCatch", "errorObj", "Promise", "async", code)
  5438. (tryCatch, errorObj, Promise, async);
  5439. };
  5440. var holderClasses = [];
  5441. var thenCallbacks = [];
  5442. var promiseSetters = [];
  5443. for (var i = 0; i < 8; ++i) {
  5444. holderClasses.push(generateHolderClass(i + 1));
  5445. thenCallbacks.push(thenCallback(i + 1));
  5446. promiseSetters.push(promiseSetter(i + 1));
  5447. }
  5448. reject = function (reason) {
  5449. this._reject(reason);
  5450. };
  5451. }}
  5452. Promise.join = function () {
  5453. var last = arguments.length - 1;
  5454. var fn;
  5455. if (last > 0 && typeof arguments[last] === "function") {
  5456. fn = arguments[last];
  5457. if (!false) {
  5458. if (last <= 8 && canEvaluate) {
  5459. var ret = new Promise(INTERNAL);
  5460. ret._captureStackTrace();
  5461. var HolderClass = holderClasses[last - 1];
  5462. var holder = new HolderClass(fn);
  5463. var callbacks = thenCallbacks;
  5464. for (var i = 0; i < last; ++i) {
  5465. var maybePromise = tryConvertToPromise(arguments[i], ret);
  5466. if (maybePromise instanceof Promise) {
  5467. maybePromise = maybePromise._target();
  5468. var bitField = maybePromise._bitField;
  5469. ;
  5470. if (((bitField & 50397184) === 0)) {
  5471. maybePromise._then(callbacks[i], reject,
  5472. undefined, ret, holder);
  5473. promiseSetters[i](maybePromise, holder);
  5474. holder.asyncNeeded = false;
  5475. } else if (((bitField & 33554432) !== 0)) {
  5476. callbacks[i].call(ret,
  5477. maybePromise._value(), holder);
  5478. } else if (((bitField & 16777216) !== 0)) {
  5479. ret._reject(maybePromise._reason());
  5480. } else {
  5481. ret._cancel();
  5482. }
  5483. } else {
  5484. callbacks[i].call(ret, maybePromise, holder);
  5485. }
  5486. }
  5487. if (!ret._isFateSealed()) {
  5488. if (holder.asyncNeeded) {
  5489. var domain = getDomain();
  5490. if (domain !== null) {
  5491. holder.fn = util.domainBind(domain, holder.fn);
  5492. }
  5493. }
  5494. ret._setAsyncGuaranteed();
  5495. ret._setOnCancel(holder);
  5496. }
  5497. return ret;
  5498. }
  5499. }
  5500. }
  5501. var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
  5502. if (fn) args.pop();
  5503. var ret = new PromiseArray(args).promise();
  5504. return fn !== undefined ? ret.spread(fn) : ret;
  5505. };
  5506. };
  5507. },{"./util":74}],56:[function(require,module,exports){
  5508. "use strict";
  5509. module.exports = function(Promise,
  5510. PromiseArray,
  5511. apiRejection,
  5512. tryConvertToPromise,
  5513. INTERNAL,
  5514. debug) {
  5515. var getDomain = Promise._getDomain;
  5516. var util = require("./util");
  5517. var tryCatch = util.tryCatch;
  5518. var errorObj = util.errorObj;
  5519. var async = Promise._async;
  5520. function MappingPromiseArray(promises, fn, limit, _filter) {
  5521. this.constructor$(promises);
  5522. this._promise._captureStackTrace();
  5523. var domain = getDomain();
  5524. this._callback = domain === null ? fn : util.domainBind(domain, fn);
  5525. this._preservedValues = _filter === INTERNAL
  5526. ? new Array(this.length())
  5527. : null;
  5528. this._limit = limit;
  5529. this._inFlight = 0;
  5530. this._queue = [];
  5531. async.invoke(this._asyncInit, this, undefined);
  5532. }
  5533. util.inherits(MappingPromiseArray, PromiseArray);
  5534. MappingPromiseArray.prototype._asyncInit = function() {
  5535. this._init$(undefined, -2);
  5536. };
  5537. MappingPromiseArray.prototype._init = function () {};
  5538. MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
  5539. var values = this._values;
  5540. var length = this.length();
  5541. var preservedValues = this._preservedValues;
  5542. var limit = this._limit;
  5543. if (index < 0) {
  5544. index = (index * -1) - 1;
  5545. values[index] = value;
  5546. if (limit >= 1) {
  5547. this._inFlight--;
  5548. this._drainQueue();
  5549. if (this._isResolved()) return true;
  5550. }
  5551. } else {
  5552. if (limit >= 1 && this._inFlight >= limit) {
  5553. values[index] = value;
  5554. this._queue.push(index);
  5555. return false;
  5556. }
  5557. if (preservedValues !== null) preservedValues[index] = value;
  5558. var promise = this._promise;
  5559. var callback = this._callback;
  5560. var receiver = promise._boundValue();
  5561. promise._pushContext();
  5562. var ret = tryCatch(callback).call(receiver, value, index, length);
  5563. var promiseCreated = promise._popContext();
  5564. debug.checkForgottenReturns(
  5565. ret,
  5566. promiseCreated,
  5567. preservedValues !== null ? "Promise.filter" : "Promise.map",
  5568. promise
  5569. );
  5570. if (ret === errorObj) {
  5571. this._reject(ret.e);
  5572. return true;
  5573. }
  5574. var maybePromise = tryConvertToPromise(ret, this._promise);
  5575. if (maybePromise instanceof Promise) {
  5576. maybePromise = maybePromise._target();
  5577. var bitField = maybePromise._bitField;
  5578. ;
  5579. if (((bitField & 50397184) === 0)) {
  5580. if (limit >= 1) this._inFlight++;
  5581. values[index] = maybePromise;
  5582. maybePromise._proxy(this, (index + 1) * -1);
  5583. return false;
  5584. } else if (((bitField & 33554432) !== 0)) {
  5585. ret = maybePromise._value();
  5586. } else if (((bitField & 16777216) !== 0)) {
  5587. this._reject(maybePromise._reason());
  5588. return true;
  5589. } else {
  5590. this._cancel();
  5591. return true;
  5592. }
  5593. }
  5594. values[index] = ret;
  5595. }
  5596. var totalResolved = ++this._totalResolved;
  5597. if (totalResolved >= length) {
  5598. if (preservedValues !== null) {
  5599. this._filter(values, preservedValues);
  5600. } else {
  5601. this._resolve(values);
  5602. }
  5603. return true;
  5604. }
  5605. return false;
  5606. };
  5607. MappingPromiseArray.prototype._drainQueue = function () {
  5608. var queue = this._queue;
  5609. var limit = this._limit;
  5610. var values = this._values;
  5611. while (queue.length > 0 && this._inFlight < limit) {
  5612. if (this._isResolved()) return;
  5613. var index = queue.pop();
  5614. this._promiseFulfilled(values[index], index);
  5615. }
  5616. };
  5617. MappingPromiseArray.prototype._filter = function (booleans, values) {
  5618. var len = values.length;
  5619. var ret = new Array(len);
  5620. var j = 0;
  5621. for (var i = 0; i < len; ++i) {
  5622. if (booleans[i]) ret[j++] = values[i];
  5623. }
  5624. ret.length = j;
  5625. this._resolve(ret);
  5626. };
  5627. MappingPromiseArray.prototype.preservedValues = function () {
  5628. return this._preservedValues;
  5629. };
  5630. function map(promises, fn, options, _filter) {
  5631. if (typeof fn !== "function") {
  5632. return apiRejection("expecting a function but got " + util.classString(fn));
  5633. }
  5634. var limit = 0;
  5635. if (options !== undefined) {
  5636. if (typeof options === "object" && options !== null) {
  5637. if (typeof options.concurrency !== "number") {
  5638. return Promise.reject(
  5639. new TypeError("'concurrency' must be a number but it is " +
  5640. util.classString(options.concurrency)));
  5641. }
  5642. limit = options.concurrency;
  5643. } else {
  5644. return Promise.reject(new TypeError(
  5645. "options argument must be an object but it is " +
  5646. util.classString(options)));
  5647. }
  5648. }
  5649. limit = typeof limit === "number" &&
  5650. isFinite(limit) && limit >= 1 ? limit : 0;
  5651. return new MappingPromiseArray(promises, fn, limit, _filter).promise();
  5652. }
  5653. Promise.prototype.map = function (fn, options) {
  5654. return map(this, fn, options, null);
  5655. };
  5656. Promise.map = function (promises, fn, options, _filter) {
  5657. return map(promises, fn, options, _filter);
  5658. };
  5659. };
  5660. },{"./util":74}],57:[function(require,module,exports){
  5661. "use strict";
  5662. module.exports =
  5663. function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
  5664. var util = require("./util");
  5665. var tryCatch = util.tryCatch;
  5666. Promise.method = function (fn) {
  5667. if (typeof fn !== "function") {
  5668. throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
  5669. }
  5670. return function () {
  5671. var ret = new Promise(INTERNAL);
  5672. ret._captureStackTrace();
  5673. ret._pushContext();
  5674. var value = tryCatch(fn).apply(this, arguments);
  5675. var promiseCreated = ret._popContext();
  5676. debug.checkForgottenReturns(
  5677. value, promiseCreated, "Promise.method", ret);
  5678. ret._resolveFromSyncValue(value);
  5679. return ret;
  5680. };
  5681. };
  5682. Promise.attempt = Promise["try"] = function (fn) {
  5683. if (typeof fn !== "function") {
  5684. return apiRejection("expecting a function but got " + util.classString(fn));
  5685. }
  5686. var ret = new Promise(INTERNAL);
  5687. ret._captureStackTrace();
  5688. ret._pushContext();
  5689. var value;
  5690. if (arguments.length > 1) {
  5691. debug.deprecated("calling Promise.try with more than 1 argument");
  5692. var arg = arguments[1];
  5693. var ctx = arguments[2];
  5694. value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
  5695. : tryCatch(fn).call(ctx, arg);
  5696. } else {
  5697. value = tryCatch(fn)();
  5698. }
  5699. var promiseCreated = ret._popContext();
  5700. debug.checkForgottenReturns(
  5701. value, promiseCreated, "Promise.try", ret);
  5702. ret._resolveFromSyncValue(value);
  5703. return ret;
  5704. };
  5705. Promise.prototype._resolveFromSyncValue = function (value) {
  5706. if (value === util.errorObj) {
  5707. this._rejectCallback(value.e, false);
  5708. } else {
  5709. this._resolveCallback(value, true);
  5710. }
  5711. };
  5712. };
  5713. },{"./util":74}],58:[function(require,module,exports){
  5714. "use strict";
  5715. var util = require("./util");
  5716. var maybeWrapAsError = util.maybeWrapAsError;
  5717. var errors = require("./errors");
  5718. var OperationalError = errors.OperationalError;
  5719. var es5 = require("./es5");
  5720. function isUntypedError(obj) {
  5721. return obj instanceof Error &&
  5722. es5.getPrototypeOf(obj) === Error.prototype;
  5723. }
  5724. var rErrorKey = /^(?:name|message|stack|cause)$/;
  5725. function wrapAsOperationalError(obj) {
  5726. var ret;
  5727. if (isUntypedError(obj)) {
  5728. ret = new OperationalError(obj);
  5729. ret.name = obj.name;
  5730. ret.message = obj.message;
  5731. ret.stack = obj.stack;
  5732. var keys = es5.keys(obj);
  5733. for (var i = 0; i < keys.length; ++i) {
  5734. var key = keys[i];
  5735. if (!rErrorKey.test(key)) {
  5736. ret[key] = obj[key];
  5737. }
  5738. }
  5739. return ret;
  5740. }
  5741. util.markAsOriginatingFromRejection(obj);
  5742. return obj;
  5743. }
  5744. function nodebackForPromise(promise, multiArgs) {
  5745. return function(err, value) {
  5746. if (promise === null) return;
  5747. if (err) {
  5748. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  5749. promise._attachExtraTrace(wrapped);
  5750. promise._reject(wrapped);
  5751. } else if (!multiArgs) {
  5752. promise._fulfill(value);
  5753. } else {
  5754. var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
  5755. promise._fulfill(args);
  5756. }
  5757. promise = null;
  5758. };
  5759. }
  5760. module.exports = nodebackForPromise;
  5761. },{"./errors":50,"./es5":51,"./util":74}],59:[function(require,module,exports){
  5762. "use strict";
  5763. module.exports = function(Promise) {
  5764. var util = require("./util");
  5765. var async = Promise._async;
  5766. var tryCatch = util.tryCatch;
  5767. var errorObj = util.errorObj;
  5768. function spreadAdapter(val, nodeback) {
  5769. var promise = this;
  5770. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  5771. var ret =
  5772. tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
  5773. if (ret === errorObj) {
  5774. async.throwLater(ret.e);
  5775. }
  5776. }
  5777. function successAdapter(val, nodeback) {
  5778. var promise = this;
  5779. var receiver = promise._boundValue();
  5780. var ret = val === undefined
  5781. ? tryCatch(nodeback).call(receiver, null)
  5782. : tryCatch(nodeback).call(receiver, null, val);
  5783. if (ret === errorObj) {
  5784. async.throwLater(ret.e);
  5785. }
  5786. }
  5787. function errorAdapter(reason, nodeback) {
  5788. var promise = this;
  5789. if (!reason) {
  5790. var newReason = new Error(reason + "");
  5791. newReason.cause = reason;
  5792. reason = newReason;
  5793. }
  5794. var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
  5795. if (ret === errorObj) {
  5796. async.throwLater(ret.e);
  5797. }
  5798. }
  5799. Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
  5800. options) {
  5801. if (typeof nodeback == "function") {
  5802. var adapter = successAdapter;
  5803. if (options !== undefined && Object(options).spread) {
  5804. adapter = spreadAdapter;
  5805. }
  5806. this._then(
  5807. adapter,
  5808. errorAdapter,
  5809. undefined,
  5810. this,
  5811. nodeback
  5812. );
  5813. }
  5814. return this;
  5815. };
  5816. };
  5817. },{"./util":74}],60:[function(require,module,exports){
  5818. (function (process){
  5819. "use strict";
  5820. module.exports = function() {
  5821. var makeSelfResolutionError = function () {
  5822. return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5823. };
  5824. var reflectHandler = function() {
  5825. return new Promise.PromiseInspection(this._target());
  5826. };
  5827. var apiRejection = function(msg) {
  5828. return Promise.reject(new TypeError(msg));
  5829. };
  5830. function Proxyable() {}
  5831. var UNDEFINED_BINDING = {};
  5832. var util = require("./util");
  5833. var getDomain;
  5834. if (util.isNode) {
  5835. getDomain = function() {
  5836. var ret = process.domain;
  5837. if (ret === undefined) ret = null;
  5838. return ret;
  5839. };
  5840. } else {
  5841. getDomain = function() {
  5842. return null;
  5843. };
  5844. }
  5845. util.notEnumerableProp(Promise, "_getDomain", getDomain);
  5846. var es5 = require("./es5");
  5847. var Async = require("./async");
  5848. var async = new Async();
  5849. es5.defineProperty(Promise, "_async", {value: async});
  5850. var errors = require("./errors");
  5851. var TypeError = Promise.TypeError = errors.TypeError;
  5852. Promise.RangeError = errors.RangeError;
  5853. var CancellationError = Promise.CancellationError = errors.CancellationError;
  5854. Promise.TimeoutError = errors.TimeoutError;
  5855. Promise.OperationalError = errors.OperationalError;
  5856. Promise.RejectionError = errors.OperationalError;
  5857. Promise.AggregateError = errors.AggregateError;
  5858. var INTERNAL = function(){};
  5859. var APPLY = {};
  5860. var NEXT_FILTER = {};
  5861. var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
  5862. var PromiseArray =
  5863. require("./promise_array")(Promise, INTERNAL,
  5864. tryConvertToPromise, apiRejection, Proxyable);
  5865. var Context = require("./context")(Promise);
  5866. /*jshint unused:false*/
  5867. var createContext = Context.create;
  5868. var debug = require("./debuggability")(Promise, Context);
  5869. var CapturedTrace = debug.CapturedTrace;
  5870. var PassThroughHandlerContext =
  5871. require("./finally")(Promise, tryConvertToPromise);
  5872. var catchFilter = require("./catch_filter")(NEXT_FILTER);
  5873. var nodebackForPromise = require("./nodeback");
  5874. var errorObj = util.errorObj;
  5875. var tryCatch = util.tryCatch;
  5876. function check(self, executor) {
  5877. if (typeof executor !== "function") {
  5878. throw new TypeError("expecting a function but got " + util.classString(executor));
  5879. }
  5880. if (self.constructor !== Promise) {
  5881. throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5882. }
  5883. }
  5884. function Promise(executor) {
  5885. this._bitField = 0;
  5886. this._fulfillmentHandler0 = undefined;
  5887. this._rejectionHandler0 = undefined;
  5888. this._promise0 = undefined;
  5889. this._receiver0 = undefined;
  5890. if (executor !== INTERNAL) {
  5891. check(this, executor);
  5892. this._resolveFromExecutor(executor);
  5893. }
  5894. this._promiseCreated();
  5895. this._fireEvent("promiseCreated", this);
  5896. }
  5897. Promise.prototype.toString = function () {
  5898. return "[object Promise]";
  5899. };
  5900. Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
  5901. var len = arguments.length;
  5902. if (len > 1) {
  5903. var catchInstances = new Array(len - 1),
  5904. j = 0, i;
  5905. for (i = 0; i < len - 1; ++i) {
  5906. var item = arguments[i];
  5907. if (util.isObject(item)) {
  5908. catchInstances[j++] = item;
  5909. } else {
  5910. return apiRejection("expecting an object but got " +
  5911. "A catch statement predicate " + util.classString(item));
  5912. }
  5913. }
  5914. catchInstances.length = j;
  5915. fn = arguments[i];
  5916. return this.then(undefined, catchFilter(catchInstances, fn, this));
  5917. }
  5918. return this.then(undefined, fn);
  5919. };
  5920. Promise.prototype.reflect = function () {
  5921. return this._then(reflectHandler,
  5922. reflectHandler, undefined, this, undefined);
  5923. };
  5924. Promise.prototype.then = function (didFulfill, didReject) {
  5925. if (debug.warnings() && arguments.length > 0 &&
  5926. typeof didFulfill !== "function" &&
  5927. typeof didReject !== "function") {
  5928. var msg = ".then() only accepts functions but was passed: " +
  5929. util.classString(didFulfill);
  5930. if (arguments.length > 1) {
  5931. msg += ", " + util.classString(didReject);
  5932. }
  5933. this._warn(msg);
  5934. }
  5935. return this._then(didFulfill, didReject, undefined, undefined, undefined);
  5936. };
  5937. Promise.prototype.done = function (didFulfill, didReject) {
  5938. var promise =
  5939. this._then(didFulfill, didReject, undefined, undefined, undefined);
  5940. promise._setIsFinal();
  5941. };
  5942. Promise.prototype.spread = function (fn) {
  5943. if (typeof fn !== "function") {
  5944. return apiRejection("expecting a function but got " + util.classString(fn));
  5945. }
  5946. return this.all()._then(fn, undefined, undefined, APPLY, undefined);
  5947. };
  5948. Promise.prototype.toJSON = function () {
  5949. var ret = {
  5950. isFulfilled: false,
  5951. isRejected: false,
  5952. fulfillmentValue: undefined,
  5953. rejectionReason: undefined
  5954. };
  5955. if (this.isFulfilled()) {
  5956. ret.fulfillmentValue = this.value();
  5957. ret.isFulfilled = true;
  5958. } else if (this.isRejected()) {
  5959. ret.rejectionReason = this.reason();
  5960. ret.isRejected = true;
  5961. }
  5962. return ret;
  5963. };
  5964. Promise.prototype.all = function () {
  5965. if (arguments.length > 0) {
  5966. this._warn(".all() was passed arguments but it does not take any");
  5967. }
  5968. return new PromiseArray(this).promise();
  5969. };
  5970. Promise.prototype.error = function (fn) {
  5971. return this.caught(util.originatesFromRejection, fn);
  5972. };
  5973. Promise.getNewLibraryCopy = module.exports;
  5974. Promise.is = function (val) {
  5975. return val instanceof Promise;
  5976. };
  5977. Promise.fromNode = Promise.fromCallback = function(fn) {
  5978. var ret = new Promise(INTERNAL);
  5979. ret._captureStackTrace();
  5980. var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
  5981. : false;
  5982. var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
  5983. if (result === errorObj) {
  5984. ret._rejectCallback(result.e, true);
  5985. }
  5986. if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
  5987. return ret;
  5988. };
  5989. Promise.all = function (promises) {
  5990. return new PromiseArray(promises).promise();
  5991. };
  5992. Promise.cast = function (obj) {
  5993. var ret = tryConvertToPromise(obj);
  5994. if (!(ret instanceof Promise)) {
  5995. ret = new Promise(INTERNAL);
  5996. ret._captureStackTrace();
  5997. ret._setFulfilled();
  5998. ret._rejectionHandler0 = obj;
  5999. }
  6000. return ret;
  6001. };
  6002. Promise.resolve = Promise.fulfilled = Promise.cast;
  6003. Promise.reject = Promise.rejected = function (reason) {
  6004. var ret = new Promise(INTERNAL);
  6005. ret._captureStackTrace();
  6006. ret._rejectCallback(reason, true);
  6007. return ret;
  6008. };
  6009. Promise.setScheduler = function(fn) {
  6010. if (typeof fn !== "function") {
  6011. throw new TypeError("expecting a function but got " + util.classString(fn));
  6012. }
  6013. return async.setScheduler(fn);
  6014. };
  6015. Promise.prototype._then = function (
  6016. didFulfill,
  6017. didReject,
  6018. _, receiver,
  6019. internalData
  6020. ) {
  6021. var haveInternalData = internalData !== undefined;
  6022. var promise = haveInternalData ? internalData : new Promise(INTERNAL);
  6023. var target = this._target();
  6024. var bitField = target._bitField;
  6025. if (!haveInternalData) {
  6026. promise._propagateFrom(this, 3);
  6027. promise._captureStackTrace();
  6028. if (receiver === undefined &&
  6029. ((this._bitField & 2097152) !== 0)) {
  6030. if (!((bitField & 50397184) === 0)) {
  6031. receiver = this._boundValue();
  6032. } else {
  6033. receiver = target === this ? undefined : this._boundTo;
  6034. }
  6035. }
  6036. this._fireEvent("promiseChained", this, promise);
  6037. }
  6038. var domain = getDomain();
  6039. if (!((bitField & 50397184) === 0)) {
  6040. var handler, value, settler = target._settlePromiseCtx;
  6041. if (((bitField & 33554432) !== 0)) {
  6042. value = target._rejectionHandler0;
  6043. handler = didFulfill;
  6044. } else if (((bitField & 16777216) !== 0)) {
  6045. value = target._fulfillmentHandler0;
  6046. handler = didReject;
  6047. target._unsetRejectionIsUnhandled();
  6048. } else {
  6049. settler = target._settlePromiseLateCancellationObserver;
  6050. value = new CancellationError("late cancellation observer");
  6051. target._attachExtraTrace(value);
  6052. handler = didReject;
  6053. }
  6054. async.invoke(settler, target, {
  6055. handler: domain === null ? handler
  6056. : (typeof handler === "function" &&
  6057. util.domainBind(domain, handler)),
  6058. promise: promise,
  6059. receiver: receiver,
  6060. value: value
  6061. });
  6062. } else {
  6063. target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
  6064. }
  6065. return promise;
  6066. };
  6067. Promise.prototype._length = function () {
  6068. return this._bitField & 65535;
  6069. };
  6070. Promise.prototype._isFateSealed = function () {
  6071. return (this._bitField & 117506048) !== 0;
  6072. };
  6073. Promise.prototype._isFollowing = function () {
  6074. return (this._bitField & 67108864) === 67108864;
  6075. };
  6076. Promise.prototype._setLength = function (len) {
  6077. this._bitField = (this._bitField & -65536) |
  6078. (len & 65535);
  6079. };
  6080. Promise.prototype._setFulfilled = function () {
  6081. this._bitField = this._bitField | 33554432;
  6082. this._fireEvent("promiseFulfilled", this);
  6083. };
  6084. Promise.prototype._setRejected = function () {
  6085. this._bitField = this._bitField | 16777216;
  6086. this._fireEvent("promiseRejected", this);
  6087. };
  6088. Promise.prototype._setFollowing = function () {
  6089. this._bitField = this._bitField | 67108864;
  6090. this._fireEvent("promiseResolved", this);
  6091. };
  6092. Promise.prototype._setIsFinal = function () {
  6093. this._bitField = this._bitField | 4194304;
  6094. };
  6095. Promise.prototype._isFinal = function () {
  6096. return (this._bitField & 4194304) > 0;
  6097. };
  6098. Promise.prototype._unsetCancelled = function() {
  6099. this._bitField = this._bitField & (~65536);
  6100. };
  6101. Promise.prototype._setCancelled = function() {
  6102. this._bitField = this._bitField | 65536;
  6103. this._fireEvent("promiseCancelled", this);
  6104. };
  6105. Promise.prototype._setWillBeCancelled = function() {
  6106. this._bitField = this._bitField | 8388608;
  6107. };
  6108. Promise.prototype._setAsyncGuaranteed = function() {
  6109. if (async.hasCustomScheduler()) return;
  6110. this._bitField = this._bitField | 134217728;
  6111. };
  6112. Promise.prototype._receiverAt = function (index) {
  6113. var ret = index === 0 ? this._receiver0 : this[
  6114. index * 4 - 4 + 3];
  6115. if (ret === UNDEFINED_BINDING) {
  6116. return undefined;
  6117. } else if (ret === undefined && this._isBound()) {
  6118. return this._boundValue();
  6119. }
  6120. return ret;
  6121. };
  6122. Promise.prototype._promiseAt = function (index) {
  6123. return this[
  6124. index * 4 - 4 + 2];
  6125. };
  6126. Promise.prototype._fulfillmentHandlerAt = function (index) {
  6127. return this[
  6128. index * 4 - 4 + 0];
  6129. };
  6130. Promise.prototype._rejectionHandlerAt = function (index) {
  6131. return this[
  6132. index * 4 - 4 + 1];
  6133. };
  6134. Promise.prototype._boundValue = function() {};
  6135. Promise.prototype._migrateCallback0 = function (follower) {
  6136. var bitField = follower._bitField;
  6137. var fulfill = follower._fulfillmentHandler0;
  6138. var reject = follower._rejectionHandler0;
  6139. var promise = follower._promise0;
  6140. var receiver = follower._receiverAt(0);
  6141. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  6142. this._addCallbacks(fulfill, reject, promise, receiver, null);
  6143. };
  6144. Promise.prototype._migrateCallbackAt = function (follower, index) {
  6145. var fulfill = follower._fulfillmentHandlerAt(index);
  6146. var reject = follower._rejectionHandlerAt(index);
  6147. var promise = follower._promiseAt(index);
  6148. var receiver = follower._receiverAt(index);
  6149. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  6150. this._addCallbacks(fulfill, reject, promise, receiver, null);
  6151. };
  6152. Promise.prototype._addCallbacks = function (
  6153. fulfill,
  6154. reject,
  6155. promise,
  6156. receiver,
  6157. domain
  6158. ) {
  6159. var index = this._length();
  6160. if (index >= 65535 - 4) {
  6161. index = 0;
  6162. this._setLength(0);
  6163. }
  6164. if (index === 0) {
  6165. this._promise0 = promise;
  6166. this._receiver0 = receiver;
  6167. if (typeof fulfill === "function") {
  6168. this._fulfillmentHandler0 =
  6169. domain === null ? fulfill : util.domainBind(domain, fulfill);
  6170. }
  6171. if (typeof reject === "function") {
  6172. this._rejectionHandler0 =
  6173. domain === null ? reject : util.domainBind(domain, reject);
  6174. }
  6175. } else {
  6176. var base = index * 4 - 4;
  6177. this[base + 2] = promise;
  6178. this[base + 3] = receiver;
  6179. if (typeof fulfill === "function") {
  6180. this[base + 0] =
  6181. domain === null ? fulfill : util.domainBind(domain, fulfill);
  6182. }
  6183. if (typeof reject === "function") {
  6184. this[base + 1] =
  6185. domain === null ? reject : util.domainBind(domain, reject);
  6186. }
  6187. }
  6188. this._setLength(index + 1);
  6189. return index;
  6190. };
  6191. Promise.prototype._proxy = function (proxyable, arg) {
  6192. this._addCallbacks(undefined, undefined, arg, proxyable, null);
  6193. };
  6194. Promise.prototype._resolveCallback = function(value, shouldBind) {
  6195. if (((this._bitField & 117506048) !== 0)) return;
  6196. if (value === this)
  6197. return this._rejectCallback(makeSelfResolutionError(), false);
  6198. var maybePromise = tryConvertToPromise(value, this);
  6199. if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  6200. if (shouldBind) this._propagateFrom(maybePromise, 2);
  6201. var promise = maybePromise._target();
  6202. if (promise === this) {
  6203. this._reject(makeSelfResolutionError());
  6204. return;
  6205. }
  6206. var bitField = promise._bitField;
  6207. if (((bitField & 50397184) === 0)) {
  6208. var len = this._length();
  6209. if (len > 0) promise._migrateCallback0(this);
  6210. for (var i = 1; i < len; ++i) {
  6211. promise._migrateCallbackAt(this, i);
  6212. }
  6213. this._setFollowing();
  6214. this._setLength(0);
  6215. this._setFollowee(promise);
  6216. } else if (((bitField & 33554432) !== 0)) {
  6217. this._fulfill(promise._value());
  6218. } else if (((bitField & 16777216) !== 0)) {
  6219. this._reject(promise._reason());
  6220. } else {
  6221. var reason = new CancellationError("late cancellation observer");
  6222. promise._attachExtraTrace(reason);
  6223. this._reject(reason);
  6224. }
  6225. };
  6226. Promise.prototype._rejectCallback =
  6227. function(reason, synchronous, ignoreNonErrorWarnings) {
  6228. var trace = util.ensureErrorObject(reason);
  6229. var hasStack = trace === reason;
  6230. if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
  6231. var message = "a promise was rejected with a non-error: " +
  6232. util.classString(reason);
  6233. this._warn(message, true);
  6234. }
  6235. this._attachExtraTrace(trace, synchronous ? hasStack : false);
  6236. this._reject(reason);
  6237. };
  6238. Promise.prototype._resolveFromExecutor = function (executor) {
  6239. var promise = this;
  6240. this._captureStackTrace();
  6241. this._pushContext();
  6242. var synchronous = true;
  6243. var r = this._execute(executor, function(value) {
  6244. promise._resolveCallback(value);
  6245. }, function (reason) {
  6246. promise._rejectCallback(reason, synchronous);
  6247. });
  6248. synchronous = false;
  6249. this._popContext();
  6250. if (r !== undefined) {
  6251. promise._rejectCallback(r, true);
  6252. }
  6253. };
  6254. Promise.prototype._settlePromiseFromHandler = function (
  6255. handler, receiver, value, promise
  6256. ) {
  6257. var bitField = promise._bitField;
  6258. if (((bitField & 65536) !== 0)) return;
  6259. promise._pushContext();
  6260. var x;
  6261. if (receiver === APPLY) {
  6262. if (!value || typeof value.length !== "number") {
  6263. x = errorObj;
  6264. x.e = new TypeError("cannot .spread() a non-array: " +
  6265. util.classString(value));
  6266. } else {
  6267. x = tryCatch(handler).apply(this._boundValue(), value);
  6268. }
  6269. } else {
  6270. x = tryCatch(handler).call(receiver, value);
  6271. }
  6272. var promiseCreated = promise._popContext();
  6273. bitField = promise._bitField;
  6274. if (((bitField & 65536) !== 0)) return;
  6275. if (x === NEXT_FILTER) {
  6276. promise._reject(value);
  6277. } else if (x === errorObj) {
  6278. promise._rejectCallback(x.e, false);
  6279. } else {
  6280. debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
  6281. promise._resolveCallback(x);
  6282. }
  6283. };
  6284. Promise.prototype._target = function() {
  6285. var ret = this;
  6286. while (ret._isFollowing()) ret = ret._followee();
  6287. return ret;
  6288. };
  6289. Promise.prototype._followee = function() {
  6290. return this._rejectionHandler0;
  6291. };
  6292. Promise.prototype._setFollowee = function(promise) {
  6293. this._rejectionHandler0 = promise;
  6294. };
  6295. Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
  6296. var isPromise = promise instanceof Promise;
  6297. var bitField = this._bitField;
  6298. var asyncGuaranteed = ((bitField & 134217728) !== 0);
  6299. if (((bitField & 65536) !== 0)) {
  6300. if (isPromise) promise._invokeInternalOnCancel();
  6301. if (receiver instanceof PassThroughHandlerContext &&
  6302. receiver.isFinallyHandler()) {
  6303. receiver.cancelPromise = promise;
  6304. if (tryCatch(handler).call(receiver, value) === errorObj) {
  6305. promise._reject(errorObj.e);
  6306. }
  6307. } else if (handler === reflectHandler) {
  6308. promise._fulfill(reflectHandler.call(receiver));
  6309. } else if (receiver instanceof Proxyable) {
  6310. receiver._promiseCancelled(promise);
  6311. } else if (isPromise || promise instanceof PromiseArray) {
  6312. promise._cancel();
  6313. } else {
  6314. receiver.cancel();
  6315. }
  6316. } else if (typeof handler === "function") {
  6317. if (!isPromise) {
  6318. handler.call(receiver, value, promise);
  6319. } else {
  6320. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  6321. this._settlePromiseFromHandler(handler, receiver, value, promise);
  6322. }
  6323. } else if (receiver instanceof Proxyable) {
  6324. if (!receiver._isResolved()) {
  6325. if (((bitField & 33554432) !== 0)) {
  6326. receiver._promiseFulfilled(value, promise);
  6327. } else {
  6328. receiver._promiseRejected(value, promise);
  6329. }
  6330. }
  6331. } else if (isPromise) {
  6332. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  6333. if (((bitField & 33554432) !== 0)) {
  6334. promise._fulfill(value);
  6335. } else {
  6336. promise._reject(value);
  6337. }
  6338. }
  6339. };
  6340. Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
  6341. var handler = ctx.handler;
  6342. var promise = ctx.promise;
  6343. var receiver = ctx.receiver;
  6344. var value = ctx.value;
  6345. if (typeof handler === "function") {
  6346. if (!(promise instanceof Promise)) {
  6347. handler.call(receiver, value, promise);
  6348. } else {
  6349. this._settlePromiseFromHandler(handler, receiver, value, promise);
  6350. }
  6351. } else if (promise instanceof Promise) {
  6352. promise._reject(value);
  6353. }
  6354. };
  6355. Promise.prototype._settlePromiseCtx = function(ctx) {
  6356. this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
  6357. };
  6358. Promise.prototype._settlePromise0 = function(handler, value, bitField) {
  6359. var promise = this._promise0;
  6360. var receiver = this._receiverAt(0);
  6361. this._promise0 = undefined;
  6362. this._receiver0 = undefined;
  6363. this._settlePromise(promise, handler, receiver, value);
  6364. };
  6365. Promise.prototype._clearCallbackDataAtIndex = function(index) {
  6366. var base = index * 4 - 4;
  6367. this[base + 2] =
  6368. this[base + 3] =
  6369. this[base + 0] =
  6370. this[base + 1] = undefined;
  6371. };
  6372. Promise.prototype._fulfill = function (value) {
  6373. var bitField = this._bitField;
  6374. if (((bitField & 117506048) >>> 16)) return;
  6375. if (value === this) {
  6376. var err = makeSelfResolutionError();
  6377. this._attachExtraTrace(err);
  6378. return this._reject(err);
  6379. }
  6380. this._setFulfilled();
  6381. this._rejectionHandler0 = value;
  6382. if ((bitField & 65535) > 0) {
  6383. if (((bitField & 134217728) !== 0)) {
  6384. this._settlePromises();
  6385. } else {
  6386. async.settlePromises(this);
  6387. }
  6388. }
  6389. };
  6390. Promise.prototype._reject = function (reason) {
  6391. var bitField = this._bitField;
  6392. if (((bitField & 117506048) >>> 16)) return;
  6393. this._setRejected();
  6394. this._fulfillmentHandler0 = reason;
  6395. if (this._isFinal()) {
  6396. return async.fatalError(reason, util.isNode);
  6397. }
  6398. if ((bitField & 65535) > 0) {
  6399. async.settlePromises(this);
  6400. } else {
  6401. this._ensurePossibleRejectionHandled();
  6402. }
  6403. };
  6404. Promise.prototype._fulfillPromises = function (len, value) {
  6405. for (var i = 1; i < len; i++) {
  6406. var handler = this._fulfillmentHandlerAt(i);
  6407. var promise = this._promiseAt(i);
  6408. var receiver = this._receiverAt(i);
  6409. this._clearCallbackDataAtIndex(i);
  6410. this._settlePromise(promise, handler, receiver, value);
  6411. }
  6412. };
  6413. Promise.prototype._rejectPromises = function (len, reason) {
  6414. for (var i = 1; i < len; i++) {
  6415. var handler = this._rejectionHandlerAt(i);
  6416. var promise = this._promiseAt(i);
  6417. var receiver = this._receiverAt(i);
  6418. this._clearCallbackDataAtIndex(i);
  6419. this._settlePromise(promise, handler, receiver, reason);
  6420. }
  6421. };
  6422. Promise.prototype._settlePromises = function () {
  6423. var bitField = this._bitField;
  6424. var len = (bitField & 65535);
  6425. if (len > 0) {
  6426. if (((bitField & 16842752) !== 0)) {
  6427. var reason = this._fulfillmentHandler0;
  6428. this._settlePromise0(this._rejectionHandler0, reason, bitField);
  6429. this._rejectPromises(len, reason);
  6430. } else {
  6431. var value = this._rejectionHandler0;
  6432. this._settlePromise0(this._fulfillmentHandler0, value, bitField);
  6433. this._fulfillPromises(len, value);
  6434. }
  6435. this._setLength(0);
  6436. }
  6437. this._clearCancellationData();
  6438. };
  6439. Promise.prototype._settledValue = function() {
  6440. var bitField = this._bitField;
  6441. if (((bitField & 33554432) !== 0)) {
  6442. return this._rejectionHandler0;
  6443. } else if (((bitField & 16777216) !== 0)) {
  6444. return this._fulfillmentHandler0;
  6445. }
  6446. };
  6447. function deferResolve(v) {this.promise._resolveCallback(v);}
  6448. function deferReject(v) {this.promise._rejectCallback(v, false);}
  6449. Promise.defer = Promise.pending = function() {
  6450. debug.deprecated("Promise.defer", "new Promise");
  6451. var promise = new Promise(INTERNAL);
  6452. return {
  6453. promise: promise,
  6454. resolve: deferResolve,
  6455. reject: deferReject
  6456. };
  6457. };
  6458. util.notEnumerableProp(Promise,
  6459. "_makeSelfResolutionError",
  6460. makeSelfResolutionError);
  6461. require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
  6462. debug);
  6463. require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
  6464. require("./cancel")(Promise, PromiseArray, apiRejection, debug);
  6465. require("./direct_resolve")(Promise);
  6466. require("./synchronous_inspection")(Promise);
  6467. require("./join")(
  6468. Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
  6469. Promise.Promise = Promise;
  6470. Promise.version = "3.4.7";
  6471. require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  6472. require('./call_get.js')(Promise);
  6473. require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
  6474. require('./timers.js')(Promise, INTERNAL, debug);
  6475. require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
  6476. require('./nodeify.js')(Promise);
  6477. require('./promisify.js')(Promise, INTERNAL);
  6478. require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  6479. require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  6480. require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  6481. require('./settle.js')(Promise, PromiseArray, debug);
  6482. require('./some.js')(Promise, PromiseArray, apiRejection);
  6483. require('./filter.js')(Promise, INTERNAL);
  6484. require('./each.js')(Promise, INTERNAL);
  6485. require('./any.js')(Promise);
  6486. util.toFastProperties(Promise);
  6487. util.toFastProperties(Promise.prototype);
  6488. function fillTypes(value) {
  6489. var p = new Promise(INTERNAL);
  6490. p._fulfillmentHandler0 = value;
  6491. p._rejectionHandler0 = value;
  6492. p._promise0 = value;
  6493. p._receiver0 = value;
  6494. }
  6495. // Complete slack tracking, opt out of field-type tracking and
  6496. // stabilize map
  6497. fillTypes({a: 1});
  6498. fillTypes({b: 2});
  6499. fillTypes({c: 3});
  6500. fillTypes(1);
  6501. fillTypes(function(){});
  6502. fillTypes(undefined);
  6503. fillTypes(false);
  6504. fillTypes(new Promise(INTERNAL));
  6505. debug.setBounds(Async.firstLineError, util.lastLineError);
  6506. return Promise;
  6507. };
  6508. }).call(this,require('_process'))
  6509. },{"./any.js":40,"./async":41,"./bind":42,"./call_get.js":43,"./cancel":44,"./catch_filter":45,"./context":46,"./debuggability":47,"./direct_resolve":48,"./each.js":49,"./errors":50,"./es5":51,"./filter.js":52,"./finally":53,"./generators.js":54,"./join":55,"./map.js":56,"./method":57,"./nodeback":58,"./nodeify.js":59,"./promise_array":61,"./promisify.js":62,"./props.js":63,"./race.js":65,"./reduce.js":66,"./settle.js":68,"./some.js":69,"./synchronous_inspection":70,"./thenables":71,"./timers.js":72,"./using.js":73,"./util":74,"_process":138}],61:[function(require,module,exports){
  6510. "use strict";
  6511. module.exports = function(Promise, INTERNAL, tryConvertToPromise,
  6512. apiRejection, Proxyable) {
  6513. var util = require("./util");
  6514. var isArray = util.isArray;
  6515. function toResolutionValue(val) {
  6516. switch(val) {
  6517. case -2: return [];
  6518. case -3: return {};
  6519. }
  6520. }
  6521. function PromiseArray(values) {
  6522. var promise = this._promise = new Promise(INTERNAL);
  6523. if (values instanceof Promise) {
  6524. promise._propagateFrom(values, 3);
  6525. }
  6526. promise._setOnCancel(this);
  6527. this._values = values;
  6528. this._length = 0;
  6529. this._totalResolved = 0;
  6530. this._init(undefined, -2);
  6531. }
  6532. util.inherits(PromiseArray, Proxyable);
  6533. PromiseArray.prototype.length = function () {
  6534. return this._length;
  6535. };
  6536. PromiseArray.prototype.promise = function () {
  6537. return this._promise;
  6538. };
  6539. PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
  6540. var values = tryConvertToPromise(this._values, this._promise);
  6541. if (values instanceof Promise) {
  6542. values = values._target();
  6543. var bitField = values._bitField;
  6544. ;
  6545. this._values = values;
  6546. if (((bitField & 50397184) === 0)) {
  6547. this._promise._setAsyncGuaranteed();
  6548. return values._then(
  6549. init,
  6550. this._reject,
  6551. undefined,
  6552. this,
  6553. resolveValueIfEmpty
  6554. );
  6555. } else if (((bitField & 33554432) !== 0)) {
  6556. values = values._value();
  6557. } else if (((bitField & 16777216) !== 0)) {
  6558. return this._reject(values._reason());
  6559. } else {
  6560. return this._cancel();
  6561. }
  6562. }
  6563. values = util.asArray(values);
  6564. if (values === null) {
  6565. var err = apiRejection(
  6566. "expecting an array or an iterable object but got " + util.classString(values)).reason();
  6567. this._promise._rejectCallback(err, false);
  6568. return;
  6569. }
  6570. if (values.length === 0) {
  6571. if (resolveValueIfEmpty === -5) {
  6572. this._resolveEmptyArray();
  6573. }
  6574. else {
  6575. this._resolve(toResolutionValue(resolveValueIfEmpty));
  6576. }
  6577. return;
  6578. }
  6579. this._iterate(values);
  6580. };
  6581. PromiseArray.prototype._iterate = function(values) {
  6582. var len = this.getActualLength(values.length);
  6583. this._length = len;
  6584. this._values = this.shouldCopyValues() ? new Array(len) : this._values;
  6585. var result = this._promise;
  6586. var isResolved = false;
  6587. var bitField = null;
  6588. for (var i = 0; i < len; ++i) {
  6589. var maybePromise = tryConvertToPromise(values[i], result);
  6590. if (maybePromise instanceof Promise) {
  6591. maybePromise = maybePromise._target();
  6592. bitField = maybePromise._bitField;
  6593. } else {
  6594. bitField = null;
  6595. }
  6596. if (isResolved) {
  6597. if (bitField !== null) {
  6598. maybePromise.suppressUnhandledRejections();
  6599. }
  6600. } else if (bitField !== null) {
  6601. if (((bitField & 50397184) === 0)) {
  6602. maybePromise._proxy(this, i);
  6603. this._values[i] = maybePromise;
  6604. } else if (((bitField & 33554432) !== 0)) {
  6605. isResolved = this._promiseFulfilled(maybePromise._value(), i);
  6606. } else if (((bitField & 16777216) !== 0)) {
  6607. isResolved = this._promiseRejected(maybePromise._reason(), i);
  6608. } else {
  6609. isResolved = this._promiseCancelled(i);
  6610. }
  6611. } else {
  6612. isResolved = this._promiseFulfilled(maybePromise, i);
  6613. }
  6614. }
  6615. if (!isResolved) result._setAsyncGuaranteed();
  6616. };
  6617. PromiseArray.prototype._isResolved = function () {
  6618. return this._values === null;
  6619. };
  6620. PromiseArray.prototype._resolve = function (value) {
  6621. this._values = null;
  6622. this._promise._fulfill(value);
  6623. };
  6624. PromiseArray.prototype._cancel = function() {
  6625. if (this._isResolved() || !this._promise._isCancellable()) return;
  6626. this._values = null;
  6627. this._promise._cancel();
  6628. };
  6629. PromiseArray.prototype._reject = function (reason) {
  6630. this._values = null;
  6631. this._promise._rejectCallback(reason, false);
  6632. };
  6633. PromiseArray.prototype._promiseFulfilled = function (value, index) {
  6634. this._values[index] = value;
  6635. var totalResolved = ++this._totalResolved;
  6636. if (totalResolved >= this._length) {
  6637. this._resolve(this._values);
  6638. return true;
  6639. }
  6640. return false;
  6641. };
  6642. PromiseArray.prototype._promiseCancelled = function() {
  6643. this._cancel();
  6644. return true;
  6645. };
  6646. PromiseArray.prototype._promiseRejected = function (reason) {
  6647. this._totalResolved++;
  6648. this._reject(reason);
  6649. return true;
  6650. };
  6651. PromiseArray.prototype._resultCancelled = function() {
  6652. if (this._isResolved()) return;
  6653. var values = this._values;
  6654. this._cancel();
  6655. if (values instanceof Promise) {
  6656. values.cancel();
  6657. } else {
  6658. for (var i = 0; i < values.length; ++i) {
  6659. if (values[i] instanceof Promise) {
  6660. values[i].cancel();
  6661. }
  6662. }
  6663. }
  6664. };
  6665. PromiseArray.prototype.shouldCopyValues = function () {
  6666. return true;
  6667. };
  6668. PromiseArray.prototype.getActualLength = function (len) {
  6669. return len;
  6670. };
  6671. return PromiseArray;
  6672. };
  6673. },{"./util":74}],62:[function(require,module,exports){
  6674. "use strict";
  6675. module.exports = function(Promise, INTERNAL) {
  6676. var THIS = {};
  6677. var util = require("./util");
  6678. var nodebackForPromise = require("./nodeback");
  6679. var withAppended = util.withAppended;
  6680. var maybeWrapAsError = util.maybeWrapAsError;
  6681. var canEvaluate = util.canEvaluate;
  6682. var TypeError = require("./errors").TypeError;
  6683. var defaultSuffix = "Async";
  6684. var defaultPromisified = {__isPromisified__: true};
  6685. var noCopyProps = [
  6686. "arity", "length",
  6687. "name",
  6688. "arguments",
  6689. "caller",
  6690. "callee",
  6691. "prototype",
  6692. "__isPromisified__"
  6693. ];
  6694. var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
  6695. var defaultFilter = function(name) {
  6696. return util.isIdentifier(name) &&
  6697. name.charAt(0) !== "_" &&
  6698. name !== "constructor";
  6699. };
  6700. function propsFilter(key) {
  6701. return !noCopyPropsPattern.test(key);
  6702. }
  6703. function isPromisified(fn) {
  6704. try {
  6705. return fn.__isPromisified__ === true;
  6706. }
  6707. catch (e) {
  6708. return false;
  6709. }
  6710. }
  6711. function hasPromisified(obj, key, suffix) {
  6712. var val = util.getDataPropertyOrDefault(obj, key + suffix,
  6713. defaultPromisified);
  6714. return val ? isPromisified(val) : false;
  6715. }
  6716. function checkValid(ret, suffix, suffixRegexp) {
  6717. for (var i = 0; i < ret.length; i += 2) {
  6718. var key = ret[i];
  6719. if (suffixRegexp.test(key)) {
  6720. var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
  6721. for (var j = 0; j < ret.length; j += 2) {
  6722. if (ret[j] === keyWithoutAsyncSuffix) {
  6723. throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
  6724. .replace("%s", suffix));
  6725. }
  6726. }
  6727. }
  6728. }
  6729. }
  6730. function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
  6731. var keys = util.inheritedDataKeys(obj);
  6732. var ret = [];
  6733. for (var i = 0; i < keys.length; ++i) {
  6734. var key = keys[i];
  6735. var value = obj[key];
  6736. var passesDefaultFilter = filter === defaultFilter
  6737. ? true : defaultFilter(key, value, obj);
  6738. if (typeof value === "function" &&
  6739. !isPromisified(value) &&
  6740. !hasPromisified(obj, key, suffix) &&
  6741. filter(key, value, obj, passesDefaultFilter)) {
  6742. ret.push(key, value);
  6743. }
  6744. }
  6745. checkValid(ret, suffix, suffixRegexp);
  6746. return ret;
  6747. }
  6748. var escapeIdentRegex = function(str) {
  6749. return str.replace(/([$])/, "\\$");
  6750. };
  6751. var makeNodePromisifiedEval;
  6752. if (!false) {
  6753. var switchCaseArgumentOrder = function(likelyArgumentCount) {
  6754. var ret = [likelyArgumentCount];
  6755. var min = Math.max(0, likelyArgumentCount - 1 - 3);
  6756. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  6757. ret.push(i);
  6758. }
  6759. for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
  6760. ret.push(i);
  6761. }
  6762. return ret;
  6763. };
  6764. var argumentSequence = function(argumentCount) {
  6765. return util.filledRange(argumentCount, "_arg", "");
  6766. };
  6767. var parameterDeclaration = function(parameterCount) {
  6768. return util.filledRange(
  6769. Math.max(parameterCount, 3), "_arg", "");
  6770. };
  6771. var parameterCount = function(fn) {
  6772. if (typeof fn.length === "number") {
  6773. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  6774. }
  6775. return 0;
  6776. };
  6777. makeNodePromisifiedEval =
  6778. function(callback, receiver, originalName, fn, _, multiArgs) {
  6779. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  6780. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  6781. var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  6782. function generateCallForArgumentCount(count) {
  6783. var args = argumentSequence(count).join(", ");
  6784. var comma = count > 0 ? ", " : "";
  6785. var ret;
  6786. if (shouldProxyThis) {
  6787. ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
  6788. } else {
  6789. ret = receiver === undefined
  6790. ? "ret = callback({{args}}, nodeback); break;\n"
  6791. : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
  6792. }
  6793. return ret.replace("{{args}}", args).replace(", ", comma);
  6794. }
  6795. function generateArgumentSwitchCase() {
  6796. var ret = "";
  6797. for (var i = 0; i < argumentOrder.length; ++i) {
  6798. ret += "case " + argumentOrder[i] +":" +
  6799. generateCallForArgumentCount(argumentOrder[i]);
  6800. }
  6801. ret += " \n\
  6802. default: \n\
  6803. var args = new Array(len + 1); \n\
  6804. var i = 0; \n\
  6805. for (var i = 0; i < len; ++i) { \n\
  6806. args[i] = arguments[i]; \n\
  6807. } \n\
  6808. args[i] = nodeback; \n\
  6809. [CodeForCall] \n\
  6810. break; \n\
  6811. ".replace("[CodeForCall]", (shouldProxyThis
  6812. ? "ret = callback.apply(this, args);\n"
  6813. : "ret = callback.apply(receiver, args);\n"));
  6814. return ret;
  6815. }
  6816. var getFunctionCode = typeof callback === "string"
  6817. ? ("this != null ? this['"+callback+"'] : fn")
  6818. : "fn";
  6819. var body = "'use strict'; \n\
  6820. var ret = function (Parameters) { \n\
  6821. 'use strict'; \n\
  6822. var len = arguments.length; \n\
  6823. var promise = new Promise(INTERNAL); \n\
  6824. promise._captureStackTrace(); \n\
  6825. var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
  6826. var ret; \n\
  6827. var callback = tryCatch([GetFunctionCode]); \n\
  6828. switch(len) { \n\
  6829. [CodeForSwitchCase] \n\
  6830. } \n\
  6831. if (ret === errorObj) { \n\
  6832. promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
  6833. } \n\
  6834. if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
  6835. return promise; \n\
  6836. }; \n\
  6837. notEnumerableProp(ret, '__isPromisified__', true); \n\
  6838. return ret; \n\
  6839. ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
  6840. .replace("[GetFunctionCode]", getFunctionCode);
  6841. body = body.replace("Parameters", parameterDeclaration(newParameterCount));
  6842. return new Function("Promise",
  6843. "fn",
  6844. "receiver",
  6845. "withAppended",
  6846. "maybeWrapAsError",
  6847. "nodebackForPromise",
  6848. "tryCatch",
  6849. "errorObj",
  6850. "notEnumerableProp",
  6851. "INTERNAL",
  6852. body)(
  6853. Promise,
  6854. fn,
  6855. receiver,
  6856. withAppended,
  6857. maybeWrapAsError,
  6858. nodebackForPromise,
  6859. util.tryCatch,
  6860. util.errorObj,
  6861. util.notEnumerableProp,
  6862. INTERNAL);
  6863. };
  6864. }
  6865. function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
  6866. var defaultThis = (function() {return this;})();
  6867. var method = callback;
  6868. if (typeof method === "string") {
  6869. callback = fn;
  6870. }
  6871. function promisified() {
  6872. var _receiver = receiver;
  6873. if (receiver === THIS) _receiver = this;
  6874. var promise = new Promise(INTERNAL);
  6875. promise._captureStackTrace();
  6876. var cb = typeof method === "string" && this !== defaultThis
  6877. ? this[method] : callback;
  6878. var fn = nodebackForPromise(promise, multiArgs);
  6879. try {
  6880. cb.apply(_receiver, withAppended(arguments, fn));
  6881. } catch(e) {
  6882. promise._rejectCallback(maybeWrapAsError(e), true, true);
  6883. }
  6884. if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
  6885. return promise;
  6886. }
  6887. util.notEnumerableProp(promisified, "__isPromisified__", true);
  6888. return promisified;
  6889. }
  6890. var makeNodePromisified = canEvaluate
  6891. ? makeNodePromisifiedEval
  6892. : makeNodePromisifiedClosure;
  6893. function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
  6894. var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
  6895. var methods =
  6896. promisifiableMethods(obj, suffix, suffixRegexp, filter);
  6897. for (var i = 0, len = methods.length; i < len; i+= 2) {
  6898. var key = methods[i];
  6899. var fn = methods[i+1];
  6900. var promisifiedKey = key + suffix;
  6901. if (promisifier === makeNodePromisified) {
  6902. obj[promisifiedKey] =
  6903. makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
  6904. } else {
  6905. var promisified = promisifier(fn, function() {
  6906. return makeNodePromisified(key, THIS, key,
  6907. fn, suffix, multiArgs);
  6908. });
  6909. util.notEnumerableProp(promisified, "__isPromisified__", true);
  6910. obj[promisifiedKey] = promisified;
  6911. }
  6912. }
  6913. util.toFastProperties(obj);
  6914. return obj;
  6915. }
  6916. function promisify(callback, receiver, multiArgs) {
  6917. return makeNodePromisified(callback, receiver, undefined,
  6918. callback, null, multiArgs);
  6919. }
  6920. Promise.promisify = function (fn, options) {
  6921. if (typeof fn !== "function") {
  6922. throw new TypeError("expecting a function but got " + util.classString(fn));
  6923. }
  6924. if (isPromisified(fn)) {
  6925. return fn;
  6926. }
  6927. options = Object(options);
  6928. var receiver = options.context === undefined ? THIS : options.context;
  6929. var multiArgs = !!options.multiArgs;
  6930. var ret = promisify(fn, receiver, multiArgs);
  6931. util.copyDescriptors(fn, ret, propsFilter);
  6932. return ret;
  6933. };
  6934. Promise.promisifyAll = function (target, options) {
  6935. if (typeof target !== "function" && typeof target !== "object") {
  6936. throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6937. }
  6938. options = Object(options);
  6939. var multiArgs = !!options.multiArgs;
  6940. var suffix = options.suffix;
  6941. if (typeof suffix !== "string") suffix = defaultSuffix;
  6942. var filter = options.filter;
  6943. if (typeof filter !== "function") filter = defaultFilter;
  6944. var promisifier = options.promisifier;
  6945. if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  6946. if (!util.isIdentifier(suffix)) {
  6947. throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6948. }
  6949. var keys = util.inheritedDataKeys(target);
  6950. for (var i = 0; i < keys.length; ++i) {
  6951. var value = target[keys[i]];
  6952. if (keys[i] !== "constructor" &&
  6953. util.isClass(value)) {
  6954. promisifyAll(value.prototype, suffix, filter, promisifier,
  6955. multiArgs);
  6956. promisifyAll(value, suffix, filter, promisifier, multiArgs);
  6957. }
  6958. }
  6959. return promisifyAll(target, suffix, filter, promisifier, multiArgs);
  6960. };
  6961. };
  6962. },{"./errors":50,"./nodeback":58,"./util":74}],63:[function(require,module,exports){
  6963. "use strict";
  6964. module.exports = function(
  6965. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  6966. var util = require("./util");
  6967. var isObject = util.isObject;
  6968. var es5 = require("./es5");
  6969. var Es6Map;
  6970. if (typeof Map === "function") Es6Map = Map;
  6971. var mapToEntries = (function() {
  6972. var index = 0;
  6973. var size = 0;
  6974. function extractEntry(value, key) {
  6975. this[index] = value;
  6976. this[index + size] = key;
  6977. index++;
  6978. }
  6979. return function mapToEntries(map) {
  6980. size = map.size;
  6981. index = 0;
  6982. var ret = new Array(map.size * 2);
  6983. map.forEach(extractEntry, ret);
  6984. return ret;
  6985. };
  6986. })();
  6987. var entriesToMap = function(entries) {
  6988. var ret = new Es6Map();
  6989. var length = entries.length / 2 | 0;
  6990. for (var i = 0; i < length; ++i) {
  6991. var key = entries[length + i];
  6992. var value = entries[i];
  6993. ret.set(key, value);
  6994. }
  6995. return ret;
  6996. };
  6997. function PropertiesPromiseArray(obj) {
  6998. var isMap = false;
  6999. var entries;
  7000. if (Es6Map !== undefined && obj instanceof Es6Map) {
  7001. entries = mapToEntries(obj);
  7002. isMap = true;
  7003. } else {
  7004. var keys = es5.keys(obj);
  7005. var len = keys.length;
  7006. entries = new Array(len * 2);
  7007. for (var i = 0; i < len; ++i) {
  7008. var key = keys[i];
  7009. entries[i] = obj[key];
  7010. entries[i + len] = key;
  7011. }
  7012. }
  7013. this.constructor$(entries);
  7014. this._isMap = isMap;
  7015. this._init$(undefined, -3);
  7016. }
  7017. util.inherits(PropertiesPromiseArray, PromiseArray);
  7018. PropertiesPromiseArray.prototype._init = function () {};
  7019. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  7020. this._values[index] = value;
  7021. var totalResolved = ++this._totalResolved;
  7022. if (totalResolved >= this._length) {
  7023. var val;
  7024. if (this._isMap) {
  7025. val = entriesToMap(this._values);
  7026. } else {
  7027. val = {};
  7028. var keyOffset = this.length();
  7029. for (var i = 0, len = this.length(); i < len; ++i) {
  7030. val[this._values[i + keyOffset]] = this._values[i];
  7031. }
  7032. }
  7033. this._resolve(val);
  7034. return true;
  7035. }
  7036. return false;
  7037. };
  7038. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  7039. return false;
  7040. };
  7041. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  7042. return len >> 1;
  7043. };
  7044. function props(promises) {
  7045. var ret;
  7046. var castValue = tryConvertToPromise(promises);
  7047. if (!isObject(castValue)) {
  7048. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7049. } else if (castValue instanceof Promise) {
  7050. ret = castValue._then(
  7051. Promise.props, undefined, undefined, undefined, undefined);
  7052. } else {
  7053. ret = new PropertiesPromiseArray(castValue).promise();
  7054. }
  7055. if (castValue instanceof Promise) {
  7056. ret._propagateFrom(castValue, 2);
  7057. }
  7058. return ret;
  7059. }
  7060. Promise.prototype.props = function () {
  7061. return props(this);
  7062. };
  7063. Promise.props = function (promises) {
  7064. return props(promises);
  7065. };
  7066. };
  7067. },{"./es5":51,"./util":74}],64:[function(require,module,exports){
  7068. "use strict";
  7069. function arrayMove(src, srcIndex, dst, dstIndex, len) {
  7070. for (var j = 0; j < len; ++j) {
  7071. dst[j + dstIndex] = src[j + srcIndex];
  7072. src[j + srcIndex] = void 0;
  7073. }
  7074. }
  7075. function Queue(capacity) {
  7076. this._capacity = capacity;
  7077. this._length = 0;
  7078. this._front = 0;
  7079. }
  7080. Queue.prototype._willBeOverCapacity = function (size) {
  7081. return this._capacity < size;
  7082. };
  7083. Queue.prototype._pushOne = function (arg) {
  7084. var length = this.length();
  7085. this._checkCapacity(length + 1);
  7086. var i = (this._front + length) & (this._capacity - 1);
  7087. this[i] = arg;
  7088. this._length = length + 1;
  7089. };
  7090. Queue.prototype.push = function (fn, receiver, arg) {
  7091. var length = this.length() + 3;
  7092. if (this._willBeOverCapacity(length)) {
  7093. this._pushOne(fn);
  7094. this._pushOne(receiver);
  7095. this._pushOne(arg);
  7096. return;
  7097. }
  7098. var j = this._front + length - 3;
  7099. this._checkCapacity(length);
  7100. var wrapMask = this._capacity - 1;
  7101. this[(j + 0) & wrapMask] = fn;
  7102. this[(j + 1) & wrapMask] = receiver;
  7103. this[(j + 2) & wrapMask] = arg;
  7104. this._length = length;
  7105. };
  7106. Queue.prototype.shift = function () {
  7107. var front = this._front,
  7108. ret = this[front];
  7109. this[front] = undefined;
  7110. this._front = (front + 1) & (this._capacity - 1);
  7111. this._length--;
  7112. return ret;
  7113. };
  7114. Queue.prototype.length = function () {
  7115. return this._length;
  7116. };
  7117. Queue.prototype._checkCapacity = function (size) {
  7118. if (this._capacity < size) {
  7119. this._resizeTo(this._capacity << 1);
  7120. }
  7121. };
  7122. Queue.prototype._resizeTo = function (capacity) {
  7123. var oldCapacity = this._capacity;
  7124. this._capacity = capacity;
  7125. var front = this._front;
  7126. var length = this._length;
  7127. var moveItemsCount = (front + length) & (oldCapacity - 1);
  7128. arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  7129. };
  7130. module.exports = Queue;
  7131. },{}],65:[function(require,module,exports){
  7132. "use strict";
  7133. module.exports = function(
  7134. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  7135. var util = require("./util");
  7136. var raceLater = function (promise) {
  7137. return promise.then(function(array) {
  7138. return race(array, promise);
  7139. });
  7140. };
  7141. function race(promises, parent) {
  7142. var maybePromise = tryConvertToPromise(promises);
  7143. if (maybePromise instanceof Promise) {
  7144. return raceLater(maybePromise);
  7145. } else {
  7146. promises = util.asArray(promises);
  7147. if (promises === null)
  7148. return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
  7149. }
  7150. var ret = new Promise(INTERNAL);
  7151. if (parent !== undefined) {
  7152. ret._propagateFrom(parent, 3);
  7153. }
  7154. var fulfill = ret._fulfill;
  7155. var reject = ret._reject;
  7156. for (var i = 0, len = promises.length; i < len; ++i) {
  7157. var val = promises[i];
  7158. if (val === undefined && !(i in promises)) {
  7159. continue;
  7160. }
  7161. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  7162. }
  7163. return ret;
  7164. }
  7165. Promise.race = function (promises) {
  7166. return race(promises, undefined);
  7167. };
  7168. Promise.prototype.race = function () {
  7169. return race(this, undefined);
  7170. };
  7171. };
  7172. },{"./util":74}],66:[function(require,module,exports){
  7173. "use strict";
  7174. module.exports = function(Promise,
  7175. PromiseArray,
  7176. apiRejection,
  7177. tryConvertToPromise,
  7178. INTERNAL,
  7179. debug) {
  7180. var getDomain = Promise._getDomain;
  7181. var util = require("./util");
  7182. var tryCatch = util.tryCatch;
  7183. function ReductionPromiseArray(promises, fn, initialValue, _each) {
  7184. this.constructor$(promises);
  7185. var domain = getDomain();
  7186. this._fn = domain === null ? fn : util.domainBind(domain, fn);
  7187. if (initialValue !== undefined) {
  7188. initialValue = Promise.resolve(initialValue);
  7189. initialValue._attachCancellationCallback(this);
  7190. }
  7191. this._initialValue = initialValue;
  7192. this._currentCancellable = null;
  7193. if(_each === INTERNAL) {
  7194. this._eachValues = Array(this._length);
  7195. } else if (_each === 0) {
  7196. this._eachValues = null;
  7197. } else {
  7198. this._eachValues = undefined;
  7199. }
  7200. this._promise._captureStackTrace();
  7201. this._init$(undefined, -5);
  7202. }
  7203. util.inherits(ReductionPromiseArray, PromiseArray);
  7204. ReductionPromiseArray.prototype._gotAccum = function(accum) {
  7205. if (this._eachValues !== undefined &&
  7206. this._eachValues !== null &&
  7207. accum !== INTERNAL) {
  7208. this._eachValues.push(accum);
  7209. }
  7210. };
  7211. ReductionPromiseArray.prototype._eachComplete = function(value) {
  7212. if (this._eachValues !== null) {
  7213. this._eachValues.push(value);
  7214. }
  7215. return this._eachValues;
  7216. };
  7217. ReductionPromiseArray.prototype._init = function() {};
  7218. ReductionPromiseArray.prototype._resolveEmptyArray = function() {
  7219. this._resolve(this._eachValues !== undefined ? this._eachValues
  7220. : this._initialValue);
  7221. };
  7222. ReductionPromiseArray.prototype.shouldCopyValues = function () {
  7223. return false;
  7224. };
  7225. ReductionPromiseArray.prototype._resolve = function(value) {
  7226. this._promise._resolveCallback(value);
  7227. this._values = null;
  7228. };
  7229. ReductionPromiseArray.prototype._resultCancelled = function(sender) {
  7230. if (sender === this._initialValue) return this._cancel();
  7231. if (this._isResolved()) return;
  7232. this._resultCancelled$();
  7233. if (this._currentCancellable instanceof Promise) {
  7234. this._currentCancellable.cancel();
  7235. }
  7236. if (this._initialValue instanceof Promise) {
  7237. this._initialValue.cancel();
  7238. }
  7239. };
  7240. ReductionPromiseArray.prototype._iterate = function (values) {
  7241. this._values = values;
  7242. var value;
  7243. var i;
  7244. var length = values.length;
  7245. if (this._initialValue !== undefined) {
  7246. value = this._initialValue;
  7247. i = 0;
  7248. } else {
  7249. value = Promise.resolve(values[0]);
  7250. i = 1;
  7251. }
  7252. this._currentCancellable = value;
  7253. if (!value.isRejected()) {
  7254. for (; i < length; ++i) {
  7255. var ctx = {
  7256. accum: null,
  7257. value: values[i],
  7258. index: i,
  7259. length: length,
  7260. array: this
  7261. };
  7262. value = value._then(gotAccum, undefined, undefined, ctx, undefined);
  7263. }
  7264. }
  7265. if (this._eachValues !== undefined) {
  7266. value = value
  7267. ._then(this._eachComplete, undefined, undefined, this, undefined);
  7268. }
  7269. value._then(completed, completed, undefined, value, this);
  7270. };
  7271. Promise.prototype.reduce = function (fn, initialValue) {
  7272. return reduce(this, fn, initialValue, null);
  7273. };
  7274. Promise.reduce = function (promises, fn, initialValue, _each) {
  7275. return reduce(promises, fn, initialValue, _each);
  7276. };
  7277. function completed(valueOrReason, array) {
  7278. if (this.isFulfilled()) {
  7279. array._resolve(valueOrReason);
  7280. } else {
  7281. array._reject(valueOrReason);
  7282. }
  7283. }
  7284. function reduce(promises, fn, initialValue, _each) {
  7285. if (typeof fn !== "function") {
  7286. return apiRejection("expecting a function but got " + util.classString(fn));
  7287. }
  7288. var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
  7289. return array.promise();
  7290. }
  7291. function gotAccum(accum) {
  7292. this.accum = accum;
  7293. this.array._gotAccum(accum);
  7294. var value = tryConvertToPromise(this.value, this.array._promise);
  7295. if (value instanceof Promise) {
  7296. this.array._currentCancellable = value;
  7297. return value._then(gotValue, undefined, undefined, this, undefined);
  7298. } else {
  7299. return gotValue.call(this, value);
  7300. }
  7301. }
  7302. function gotValue(value) {
  7303. var array = this.array;
  7304. var promise = array._promise;
  7305. var fn = tryCatch(array._fn);
  7306. promise._pushContext();
  7307. var ret;
  7308. if (array._eachValues !== undefined) {
  7309. ret = fn.call(promise._boundValue(), value, this.index, this.length);
  7310. } else {
  7311. ret = fn.call(promise._boundValue(),
  7312. this.accum, value, this.index, this.length);
  7313. }
  7314. if (ret instanceof Promise) {
  7315. array._currentCancellable = ret;
  7316. }
  7317. var promiseCreated = promise._popContext();
  7318. debug.checkForgottenReturns(
  7319. ret,
  7320. promiseCreated,
  7321. array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
  7322. promise
  7323. );
  7324. return ret;
  7325. }
  7326. };
  7327. },{"./util":74}],67:[function(require,module,exports){
  7328. (function (process,global){
  7329. "use strict";
  7330. var util = require("./util");
  7331. var schedule;
  7332. var noAsyncScheduler = function() {
  7333. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7334. };
  7335. var NativePromise = util.getNativePromise();
  7336. if (util.isNode && typeof MutationObserver === "undefined") {
  7337. var GlobalSetImmediate = global.setImmediate;
  7338. var ProcessNextTick = process.nextTick;
  7339. schedule = util.isRecentNode
  7340. ? function(fn) { GlobalSetImmediate.call(global, fn); }
  7341. : function(fn) { ProcessNextTick.call(process, fn); };
  7342. } else if (typeof NativePromise === "function" &&
  7343. typeof NativePromise.resolve === "function") {
  7344. var nativePromise = NativePromise.resolve();
  7345. schedule = function(fn) {
  7346. nativePromise.then(fn);
  7347. };
  7348. } else if ((typeof MutationObserver !== "undefined") &&
  7349. !(typeof window !== "undefined" &&
  7350. window.navigator &&
  7351. (window.navigator.standalone || window.cordova))) {
  7352. schedule = (function() {
  7353. var div = document.createElement("div");
  7354. var opts = {attributes: true};
  7355. var toggleScheduled = false;
  7356. var div2 = document.createElement("div");
  7357. var o2 = new MutationObserver(function() {
  7358. div.classList.toggle("foo");
  7359. toggleScheduled = false;
  7360. });
  7361. o2.observe(div2, opts);
  7362. var scheduleToggle = function() {
  7363. if (toggleScheduled) return;
  7364. toggleScheduled = true;
  7365. div2.classList.toggle("foo");
  7366. };
  7367. return function schedule(fn) {
  7368. var o = new MutationObserver(function() {
  7369. o.disconnect();
  7370. fn();
  7371. });
  7372. o.observe(div, opts);
  7373. scheduleToggle();
  7374. };
  7375. })();
  7376. } else if (typeof setImmediate !== "undefined") {
  7377. schedule = function (fn) {
  7378. setImmediate(fn);
  7379. };
  7380. } else if (typeof setTimeout !== "undefined") {
  7381. schedule = function (fn) {
  7382. setTimeout(fn, 0);
  7383. };
  7384. } else {
  7385. schedule = noAsyncScheduler;
  7386. }
  7387. module.exports = schedule;
  7388. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  7389. },{"./util":74,"_process":138}],68:[function(require,module,exports){
  7390. "use strict";
  7391. module.exports =
  7392. function(Promise, PromiseArray, debug) {
  7393. var PromiseInspection = Promise.PromiseInspection;
  7394. var util = require("./util");
  7395. function SettledPromiseArray(values) {
  7396. this.constructor$(values);
  7397. }
  7398. util.inherits(SettledPromiseArray, PromiseArray);
  7399. SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
  7400. this._values[index] = inspection;
  7401. var totalResolved = ++this._totalResolved;
  7402. if (totalResolved >= this._length) {
  7403. this._resolve(this._values);
  7404. return true;
  7405. }
  7406. return false;
  7407. };
  7408. SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
  7409. var ret = new PromiseInspection();
  7410. ret._bitField = 33554432;
  7411. ret._settledValueField = value;
  7412. return this._promiseResolved(index, ret);
  7413. };
  7414. SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
  7415. var ret = new PromiseInspection();
  7416. ret._bitField = 16777216;
  7417. ret._settledValueField = reason;
  7418. return this._promiseResolved(index, ret);
  7419. };
  7420. Promise.settle = function (promises) {
  7421. debug.deprecated(".settle()", ".reflect()");
  7422. return new SettledPromiseArray(promises).promise();
  7423. };
  7424. Promise.prototype.settle = function () {
  7425. return Promise.settle(this);
  7426. };
  7427. };
  7428. },{"./util":74}],69:[function(require,module,exports){
  7429. "use strict";
  7430. module.exports =
  7431. function(Promise, PromiseArray, apiRejection) {
  7432. var util = require("./util");
  7433. var RangeError = require("./errors").RangeError;
  7434. var AggregateError = require("./errors").AggregateError;
  7435. var isArray = util.isArray;
  7436. var CANCELLATION = {};
  7437. function SomePromiseArray(values) {
  7438. this.constructor$(values);
  7439. this._howMany = 0;
  7440. this._unwrap = false;
  7441. this._initialized = false;
  7442. }
  7443. util.inherits(SomePromiseArray, PromiseArray);
  7444. SomePromiseArray.prototype._init = function () {
  7445. if (!this._initialized) {
  7446. return;
  7447. }
  7448. if (this._howMany === 0) {
  7449. this._resolve([]);
  7450. return;
  7451. }
  7452. this._init$(undefined, -5);
  7453. var isArrayResolved = isArray(this._values);
  7454. if (!this._isResolved() &&
  7455. isArrayResolved &&
  7456. this._howMany > this._canPossiblyFulfill()) {
  7457. this._reject(this._getRangeError(this.length()));
  7458. }
  7459. };
  7460. SomePromiseArray.prototype.init = function () {
  7461. this._initialized = true;
  7462. this._init();
  7463. };
  7464. SomePromiseArray.prototype.setUnwrap = function () {
  7465. this._unwrap = true;
  7466. };
  7467. SomePromiseArray.prototype.howMany = function () {
  7468. return this._howMany;
  7469. };
  7470. SomePromiseArray.prototype.setHowMany = function (count) {
  7471. this._howMany = count;
  7472. };
  7473. SomePromiseArray.prototype._promiseFulfilled = function (value) {
  7474. this._addFulfilled(value);
  7475. if (this._fulfilled() === this.howMany()) {
  7476. this._values.length = this.howMany();
  7477. if (this.howMany() === 1 && this._unwrap) {
  7478. this._resolve(this._values[0]);
  7479. } else {
  7480. this._resolve(this._values);
  7481. }
  7482. return true;
  7483. }
  7484. return false;
  7485. };
  7486. SomePromiseArray.prototype._promiseRejected = function (reason) {
  7487. this._addRejected(reason);
  7488. return this._checkOutcome();
  7489. };
  7490. SomePromiseArray.prototype._promiseCancelled = function () {
  7491. if (this._values instanceof Promise || this._values == null) {
  7492. return this._cancel();
  7493. }
  7494. this._addRejected(CANCELLATION);
  7495. return this._checkOutcome();
  7496. };
  7497. SomePromiseArray.prototype._checkOutcome = function() {
  7498. if (this.howMany() > this._canPossiblyFulfill()) {
  7499. var e = new AggregateError();
  7500. for (var i = this.length(); i < this._values.length; ++i) {
  7501. if (this._values[i] !== CANCELLATION) {
  7502. e.push(this._values[i]);
  7503. }
  7504. }
  7505. if (e.length > 0) {
  7506. this._reject(e);
  7507. } else {
  7508. this._cancel();
  7509. }
  7510. return true;
  7511. }
  7512. return false;
  7513. };
  7514. SomePromiseArray.prototype._fulfilled = function () {
  7515. return this._totalResolved;
  7516. };
  7517. SomePromiseArray.prototype._rejected = function () {
  7518. return this._values.length - this.length();
  7519. };
  7520. SomePromiseArray.prototype._addRejected = function (reason) {
  7521. this._values.push(reason);
  7522. };
  7523. SomePromiseArray.prototype._addFulfilled = function (value) {
  7524. this._values[this._totalResolved++] = value;
  7525. };
  7526. SomePromiseArray.prototype._canPossiblyFulfill = function () {
  7527. return this.length() - this._rejected();
  7528. };
  7529. SomePromiseArray.prototype._getRangeError = function (count) {
  7530. var message = "Input array must contain at least " +
  7531. this._howMany + " items but contains only " + count + " items";
  7532. return new RangeError(message);
  7533. };
  7534. SomePromiseArray.prototype._resolveEmptyArray = function () {
  7535. this._reject(this._getRangeError(0));
  7536. };
  7537. function some(promises, howMany) {
  7538. if ((howMany | 0) !== howMany || howMany < 0) {
  7539. return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7540. }
  7541. var ret = new SomePromiseArray(promises);
  7542. var promise = ret.promise();
  7543. ret.setHowMany(howMany);
  7544. ret.init();
  7545. return promise;
  7546. }
  7547. Promise.some = function (promises, howMany) {
  7548. return some(promises, howMany);
  7549. };
  7550. Promise.prototype.some = function (howMany) {
  7551. return some(this, howMany);
  7552. };
  7553. Promise._SomePromiseArray = SomePromiseArray;
  7554. };
  7555. },{"./errors":50,"./util":74}],70:[function(require,module,exports){
  7556. "use strict";
  7557. module.exports = function(Promise) {
  7558. function PromiseInspection(promise) {
  7559. if (promise !== undefined) {
  7560. promise = promise._target();
  7561. this._bitField = promise._bitField;
  7562. this._settledValueField = promise._isFateSealed()
  7563. ? promise._settledValue() : undefined;
  7564. }
  7565. else {
  7566. this._bitField = 0;
  7567. this._settledValueField = undefined;
  7568. }
  7569. }
  7570. PromiseInspection.prototype._settledValue = function() {
  7571. return this._settledValueField;
  7572. };
  7573. var value = PromiseInspection.prototype.value = function () {
  7574. if (!this.isFulfilled()) {
  7575. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7576. }
  7577. return this._settledValue();
  7578. };
  7579. var reason = PromiseInspection.prototype.error =
  7580. PromiseInspection.prototype.reason = function () {
  7581. if (!this.isRejected()) {
  7582. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7583. }
  7584. return this._settledValue();
  7585. };
  7586. var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
  7587. return (this._bitField & 33554432) !== 0;
  7588. };
  7589. var isRejected = PromiseInspection.prototype.isRejected = function () {
  7590. return (this._bitField & 16777216) !== 0;
  7591. };
  7592. var isPending = PromiseInspection.prototype.isPending = function () {
  7593. return (this._bitField & 50397184) === 0;
  7594. };
  7595. var isResolved = PromiseInspection.prototype.isResolved = function () {
  7596. return (this._bitField & 50331648) !== 0;
  7597. };
  7598. PromiseInspection.prototype.isCancelled = function() {
  7599. return (this._bitField & 8454144) !== 0;
  7600. };
  7601. Promise.prototype.__isCancelled = function() {
  7602. return (this._bitField & 65536) === 65536;
  7603. };
  7604. Promise.prototype._isCancelled = function() {
  7605. return this._target().__isCancelled();
  7606. };
  7607. Promise.prototype.isCancelled = function() {
  7608. return (this._target()._bitField & 8454144) !== 0;
  7609. };
  7610. Promise.prototype.isPending = function() {
  7611. return isPending.call(this._target());
  7612. };
  7613. Promise.prototype.isRejected = function() {
  7614. return isRejected.call(this._target());
  7615. };
  7616. Promise.prototype.isFulfilled = function() {
  7617. return isFulfilled.call(this._target());
  7618. };
  7619. Promise.prototype.isResolved = function() {
  7620. return isResolved.call(this._target());
  7621. };
  7622. Promise.prototype.value = function() {
  7623. return value.call(this._target());
  7624. };
  7625. Promise.prototype.reason = function() {
  7626. var target = this._target();
  7627. target._unsetRejectionIsUnhandled();
  7628. return reason.call(target);
  7629. };
  7630. Promise.prototype._value = function() {
  7631. return this._settledValue();
  7632. };
  7633. Promise.prototype._reason = function() {
  7634. this._unsetRejectionIsUnhandled();
  7635. return this._settledValue();
  7636. };
  7637. Promise.PromiseInspection = PromiseInspection;
  7638. };
  7639. },{}],71:[function(require,module,exports){
  7640. "use strict";
  7641. module.exports = function(Promise, INTERNAL) {
  7642. var util = require("./util");
  7643. var errorObj = util.errorObj;
  7644. var isObject = util.isObject;
  7645. function tryConvertToPromise(obj, context) {
  7646. if (isObject(obj)) {
  7647. if (obj instanceof Promise) return obj;
  7648. var then = getThen(obj);
  7649. if (then === errorObj) {
  7650. if (context) context._pushContext();
  7651. var ret = Promise.reject(then.e);
  7652. if (context) context._popContext();
  7653. return ret;
  7654. } else if (typeof then === "function") {
  7655. if (isAnyBluebirdPromise(obj)) {
  7656. var ret = new Promise(INTERNAL);
  7657. obj._then(
  7658. ret._fulfill,
  7659. ret._reject,
  7660. undefined,
  7661. ret,
  7662. null
  7663. );
  7664. return ret;
  7665. }
  7666. return doThenable(obj, then, context);
  7667. }
  7668. }
  7669. return obj;
  7670. }
  7671. function doGetThen(obj) {
  7672. return obj.then;
  7673. }
  7674. function getThen(obj) {
  7675. try {
  7676. return doGetThen(obj);
  7677. } catch (e) {
  7678. errorObj.e = e;
  7679. return errorObj;
  7680. }
  7681. }
  7682. var hasProp = {}.hasOwnProperty;
  7683. function isAnyBluebirdPromise(obj) {
  7684. try {
  7685. return hasProp.call(obj, "_promise0");
  7686. } catch (e) {
  7687. return false;
  7688. }
  7689. }
  7690. function doThenable(x, then, context) {
  7691. var promise = new Promise(INTERNAL);
  7692. var ret = promise;
  7693. if (context) context._pushContext();
  7694. promise._captureStackTrace();
  7695. if (context) context._popContext();
  7696. var synchronous = true;
  7697. var result = util.tryCatch(then).call(x, resolve, reject);
  7698. synchronous = false;
  7699. if (promise && result === errorObj) {
  7700. promise._rejectCallback(result.e, true, true);
  7701. promise = null;
  7702. }
  7703. function resolve(value) {
  7704. if (!promise) return;
  7705. promise._resolveCallback(value);
  7706. promise = null;
  7707. }
  7708. function reject(reason) {
  7709. if (!promise) return;
  7710. promise._rejectCallback(reason, synchronous, true);
  7711. promise = null;
  7712. }
  7713. return ret;
  7714. }
  7715. return tryConvertToPromise;
  7716. };
  7717. },{"./util":74}],72:[function(require,module,exports){
  7718. "use strict";
  7719. module.exports = function(Promise, INTERNAL, debug) {
  7720. var util = require("./util");
  7721. var TimeoutError = Promise.TimeoutError;
  7722. function HandleWrapper(handle) {
  7723. this.handle = handle;
  7724. }
  7725. HandleWrapper.prototype._resultCancelled = function() {
  7726. clearTimeout(this.handle);
  7727. };
  7728. var afterValue = function(value) { return delay(+this).thenReturn(value); };
  7729. var delay = Promise.delay = function (ms, value) {
  7730. var ret;
  7731. var handle;
  7732. if (value !== undefined) {
  7733. ret = Promise.resolve(value)
  7734. ._then(afterValue, null, null, ms, undefined);
  7735. if (debug.cancellation() && value instanceof Promise) {
  7736. ret._setOnCancel(value);
  7737. }
  7738. } else {
  7739. ret = new Promise(INTERNAL);
  7740. handle = setTimeout(function() { ret._fulfill(); }, +ms);
  7741. if (debug.cancellation()) {
  7742. ret._setOnCancel(new HandleWrapper(handle));
  7743. }
  7744. ret._captureStackTrace();
  7745. }
  7746. ret._setAsyncGuaranteed();
  7747. return ret;
  7748. };
  7749. Promise.prototype.delay = function (ms) {
  7750. return delay(ms, this);
  7751. };
  7752. var afterTimeout = function (promise, message, parent) {
  7753. var err;
  7754. if (typeof message !== "string") {
  7755. if (message instanceof Error) {
  7756. err = message;
  7757. } else {
  7758. err = new TimeoutError("operation timed out");
  7759. }
  7760. } else {
  7761. err = new TimeoutError(message);
  7762. }
  7763. util.markAsOriginatingFromRejection(err);
  7764. promise._attachExtraTrace(err);
  7765. promise._reject(err);
  7766. if (parent != null) {
  7767. parent.cancel();
  7768. }
  7769. };
  7770. function successClear(value) {
  7771. clearTimeout(this.handle);
  7772. return value;
  7773. }
  7774. function failureClear(reason) {
  7775. clearTimeout(this.handle);
  7776. throw reason;
  7777. }
  7778. Promise.prototype.timeout = function (ms, message) {
  7779. ms = +ms;
  7780. var ret, parent;
  7781. var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
  7782. if (ret.isPending()) {
  7783. afterTimeout(ret, message, parent);
  7784. }
  7785. }, ms));
  7786. if (debug.cancellation()) {
  7787. parent = this.then();
  7788. ret = parent._then(successClear, failureClear,
  7789. undefined, handleWrapper, undefined);
  7790. ret._setOnCancel(handleWrapper);
  7791. } else {
  7792. ret = this._then(successClear, failureClear,
  7793. undefined, handleWrapper, undefined);
  7794. }
  7795. return ret;
  7796. };
  7797. };
  7798. },{"./util":74}],73:[function(require,module,exports){
  7799. "use strict";
  7800. module.exports = function (Promise, apiRejection, tryConvertToPromise,
  7801. createContext, INTERNAL, debug) {
  7802. var util = require("./util");
  7803. var TypeError = require("./errors").TypeError;
  7804. var inherits = require("./util").inherits;
  7805. var errorObj = util.errorObj;
  7806. var tryCatch = util.tryCatch;
  7807. var NULL = {};
  7808. function thrower(e) {
  7809. setTimeout(function(){throw e;}, 0);
  7810. }
  7811. function castPreservingDisposable(thenable) {
  7812. var maybePromise = tryConvertToPromise(thenable);
  7813. if (maybePromise !== thenable &&
  7814. typeof thenable._isDisposable === "function" &&
  7815. typeof thenable._getDisposer === "function" &&
  7816. thenable._isDisposable()) {
  7817. maybePromise._setDisposable(thenable._getDisposer());
  7818. }
  7819. return maybePromise;
  7820. }
  7821. function dispose(resources, inspection) {
  7822. var i = 0;
  7823. var len = resources.length;
  7824. var ret = new Promise(INTERNAL);
  7825. function iterator() {
  7826. if (i >= len) return ret._fulfill();
  7827. var maybePromise = castPreservingDisposable(resources[i++]);
  7828. if (maybePromise instanceof Promise &&
  7829. maybePromise._isDisposable()) {
  7830. try {
  7831. maybePromise = tryConvertToPromise(
  7832. maybePromise._getDisposer().tryDispose(inspection),
  7833. resources.promise);
  7834. } catch (e) {
  7835. return thrower(e);
  7836. }
  7837. if (maybePromise instanceof Promise) {
  7838. return maybePromise._then(iterator, thrower,
  7839. null, null, null);
  7840. }
  7841. }
  7842. iterator();
  7843. }
  7844. iterator();
  7845. return ret;
  7846. }
  7847. function Disposer(data, promise, context) {
  7848. this._data = data;
  7849. this._promise = promise;
  7850. this._context = context;
  7851. }
  7852. Disposer.prototype.data = function () {
  7853. return this._data;
  7854. };
  7855. Disposer.prototype.promise = function () {
  7856. return this._promise;
  7857. };
  7858. Disposer.prototype.resource = function () {
  7859. if (this.promise().isFulfilled()) {
  7860. return this.promise().value();
  7861. }
  7862. return NULL;
  7863. };
  7864. Disposer.prototype.tryDispose = function(inspection) {
  7865. var resource = this.resource();
  7866. var context = this._context;
  7867. if (context !== undefined) context._pushContext();
  7868. var ret = resource !== NULL
  7869. ? this.doDispose(resource, inspection) : null;
  7870. if (context !== undefined) context._popContext();
  7871. this._promise._unsetDisposable();
  7872. this._data = null;
  7873. return ret;
  7874. };
  7875. Disposer.isDisposer = function (d) {
  7876. return (d != null &&
  7877. typeof d.resource === "function" &&
  7878. typeof d.tryDispose === "function");
  7879. };
  7880. function FunctionDisposer(fn, promise, context) {
  7881. this.constructor$(fn, promise, context);
  7882. }
  7883. inherits(FunctionDisposer, Disposer);
  7884. FunctionDisposer.prototype.doDispose = function (resource, inspection) {
  7885. var fn = this.data();
  7886. return fn.call(resource, resource, inspection);
  7887. };
  7888. function maybeUnwrapDisposer(value) {
  7889. if (Disposer.isDisposer(value)) {
  7890. this.resources[this.index]._setDisposable(value);
  7891. return value.promise();
  7892. }
  7893. return value;
  7894. }
  7895. function ResourceList(length) {
  7896. this.length = length;
  7897. this.promise = null;
  7898. this[length-1] = null;
  7899. }
  7900. ResourceList.prototype._resultCancelled = function() {
  7901. var len = this.length;
  7902. for (var i = 0; i < len; ++i) {
  7903. var item = this[i];
  7904. if (item instanceof Promise) {
  7905. item.cancel();
  7906. }
  7907. }
  7908. };
  7909. Promise.using = function () {
  7910. var len = arguments.length;
  7911. if (len < 2) return apiRejection(
  7912. "you must pass at least 2 arguments to Promise.using");
  7913. var fn = arguments[len - 1];
  7914. if (typeof fn !== "function") {
  7915. return apiRejection("expecting a function but got " + util.classString(fn));
  7916. }
  7917. var input;
  7918. var spreadArgs = true;
  7919. if (len === 2 && Array.isArray(arguments[0])) {
  7920. input = arguments[0];
  7921. len = input.length;
  7922. spreadArgs = false;
  7923. } else {
  7924. input = arguments;
  7925. len--;
  7926. }
  7927. var resources = new ResourceList(len);
  7928. for (var i = 0; i < len; ++i) {
  7929. var resource = input[i];
  7930. if (Disposer.isDisposer(resource)) {
  7931. var disposer = resource;
  7932. resource = resource.promise();
  7933. resource._setDisposable(disposer);
  7934. } else {
  7935. var maybePromise = tryConvertToPromise(resource);
  7936. if (maybePromise instanceof Promise) {
  7937. resource =
  7938. maybePromise._then(maybeUnwrapDisposer, null, null, {
  7939. resources: resources,
  7940. index: i
  7941. }, undefined);
  7942. }
  7943. }
  7944. resources[i] = resource;
  7945. }
  7946. var reflectedResources = new Array(resources.length);
  7947. for (var i = 0; i < reflectedResources.length; ++i) {
  7948. reflectedResources[i] = Promise.resolve(resources[i]).reflect();
  7949. }
  7950. var resultPromise = Promise.all(reflectedResources)
  7951. .then(function(inspections) {
  7952. for (var i = 0; i < inspections.length; ++i) {
  7953. var inspection = inspections[i];
  7954. if (inspection.isRejected()) {
  7955. errorObj.e = inspection.error();
  7956. return errorObj;
  7957. } else if (!inspection.isFulfilled()) {
  7958. resultPromise.cancel();
  7959. return;
  7960. }
  7961. inspections[i] = inspection.value();
  7962. }
  7963. promise._pushContext();
  7964. fn = tryCatch(fn);
  7965. var ret = spreadArgs
  7966. ? fn.apply(undefined, inspections) : fn(inspections);
  7967. var promiseCreated = promise._popContext();
  7968. debug.checkForgottenReturns(
  7969. ret, promiseCreated, "Promise.using", promise);
  7970. return ret;
  7971. });
  7972. var promise = resultPromise.lastly(function() {
  7973. var inspection = new Promise.PromiseInspection(resultPromise);
  7974. return dispose(resources, inspection);
  7975. });
  7976. resources.promise = promise;
  7977. promise._setOnCancel(resources);
  7978. return promise;
  7979. };
  7980. Promise.prototype._setDisposable = function (disposer) {
  7981. this._bitField = this._bitField | 131072;
  7982. this._disposer = disposer;
  7983. };
  7984. Promise.prototype._isDisposable = function () {
  7985. return (this._bitField & 131072) > 0;
  7986. };
  7987. Promise.prototype._getDisposer = function () {
  7988. return this._disposer;
  7989. };
  7990. Promise.prototype._unsetDisposable = function () {
  7991. this._bitField = this._bitField & (~131072);
  7992. this._disposer = undefined;
  7993. };
  7994. Promise.prototype.disposer = function (fn) {
  7995. if (typeof fn === "function") {
  7996. return new FunctionDisposer(fn, this, createContext());
  7997. }
  7998. throw new TypeError();
  7999. };
  8000. };
  8001. },{"./errors":50,"./util":74}],74:[function(require,module,exports){
  8002. (function (process,global){
  8003. "use strict";
  8004. var es5 = require("./es5");
  8005. var canEvaluate = typeof navigator == "undefined";
  8006. var errorObj = {e: {}};
  8007. var tryCatchTarget;
  8008. var globalObject = typeof self !== "undefined" ? self :
  8009. typeof window !== "undefined" ? window :
  8010. typeof global !== "undefined" ? global :
  8011. this !== undefined ? this : null;
  8012. function tryCatcher() {
  8013. try {
  8014. var target = tryCatchTarget;
  8015. tryCatchTarget = null;
  8016. return target.apply(this, arguments);
  8017. } catch (e) {
  8018. errorObj.e = e;
  8019. return errorObj;
  8020. }
  8021. }
  8022. function tryCatch(fn) {
  8023. tryCatchTarget = fn;
  8024. return tryCatcher;
  8025. }
  8026. var inherits = function(Child, Parent) {
  8027. var hasProp = {}.hasOwnProperty;
  8028. function T() {
  8029. this.constructor = Child;
  8030. this.constructor$ = Parent;
  8031. for (var propertyName in Parent.prototype) {
  8032. if (hasProp.call(Parent.prototype, propertyName) &&
  8033. propertyName.charAt(propertyName.length-1) !== "$"
  8034. ) {
  8035. this[propertyName + "$"] = Parent.prototype[propertyName];
  8036. }
  8037. }
  8038. }
  8039. T.prototype = Parent.prototype;
  8040. Child.prototype = new T();
  8041. return Child.prototype;
  8042. };
  8043. function isPrimitive(val) {
  8044. return val == null || val === true || val === false ||
  8045. typeof val === "string" || typeof val === "number";
  8046. }
  8047. function isObject(value) {
  8048. return typeof value === "function" ||
  8049. typeof value === "object" && value !== null;
  8050. }
  8051. function maybeWrapAsError(maybeError) {
  8052. if (!isPrimitive(maybeError)) return maybeError;
  8053. return new Error(safeToString(maybeError));
  8054. }
  8055. function withAppended(target, appendee) {
  8056. var len = target.length;
  8057. var ret = new Array(len + 1);
  8058. var i;
  8059. for (i = 0; i < len; ++i) {
  8060. ret[i] = target[i];
  8061. }
  8062. ret[i] = appendee;
  8063. return ret;
  8064. }
  8065. function getDataPropertyOrDefault(obj, key, defaultValue) {
  8066. if (es5.isES5) {
  8067. var desc = Object.getOwnPropertyDescriptor(obj, key);
  8068. if (desc != null) {
  8069. return desc.get == null && desc.set == null
  8070. ? desc.value
  8071. : defaultValue;
  8072. }
  8073. } else {
  8074. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  8075. }
  8076. }
  8077. function notEnumerableProp(obj, name, value) {
  8078. if (isPrimitive(obj)) return obj;
  8079. var descriptor = {
  8080. value: value,
  8081. configurable: true,
  8082. enumerable: false,
  8083. writable: true
  8084. };
  8085. es5.defineProperty(obj, name, descriptor);
  8086. return obj;
  8087. }
  8088. function thrower(r) {
  8089. throw r;
  8090. }
  8091. var inheritedDataKeys = (function() {
  8092. var excludedPrototypes = [
  8093. Array.prototype,
  8094. Object.prototype,
  8095. Function.prototype
  8096. ];
  8097. var isExcludedProto = function(val) {
  8098. for (var i = 0; i < excludedPrototypes.length; ++i) {
  8099. if (excludedPrototypes[i] === val) {
  8100. return true;
  8101. }
  8102. }
  8103. return false;
  8104. };
  8105. if (es5.isES5) {
  8106. var getKeys = Object.getOwnPropertyNames;
  8107. return function(obj) {
  8108. var ret = [];
  8109. var visitedKeys = Object.create(null);
  8110. while (obj != null && !isExcludedProto(obj)) {
  8111. var keys;
  8112. try {
  8113. keys = getKeys(obj);
  8114. } catch (e) {
  8115. return ret;
  8116. }
  8117. for (var i = 0; i < keys.length; ++i) {
  8118. var key = keys[i];
  8119. if (visitedKeys[key]) continue;
  8120. visitedKeys[key] = true;
  8121. var desc = Object.getOwnPropertyDescriptor(obj, key);
  8122. if (desc != null && desc.get == null && desc.set == null) {
  8123. ret.push(key);
  8124. }
  8125. }
  8126. obj = es5.getPrototypeOf(obj);
  8127. }
  8128. return ret;
  8129. };
  8130. } else {
  8131. var hasProp = {}.hasOwnProperty;
  8132. return function(obj) {
  8133. if (isExcludedProto(obj)) return [];
  8134. var ret = [];
  8135. /*jshint forin:false */
  8136. enumeration: for (var key in obj) {
  8137. if (hasProp.call(obj, key)) {
  8138. ret.push(key);
  8139. } else {
  8140. for (var i = 0; i < excludedPrototypes.length; ++i) {
  8141. if (hasProp.call(excludedPrototypes[i], key)) {
  8142. continue enumeration;
  8143. }
  8144. }
  8145. ret.push(key);
  8146. }
  8147. }
  8148. return ret;
  8149. };
  8150. }
  8151. })();
  8152. var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  8153. function isClass(fn) {
  8154. try {
  8155. if (typeof fn === "function") {
  8156. var keys = es5.names(fn.prototype);
  8157. var hasMethods = es5.isES5 && keys.length > 1;
  8158. var hasMethodsOtherThanConstructor = keys.length > 0 &&
  8159. !(keys.length === 1 && keys[0] === "constructor");
  8160. var hasThisAssignmentAndStaticMethods =
  8161. thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  8162. if (hasMethods || hasMethodsOtherThanConstructor ||
  8163. hasThisAssignmentAndStaticMethods) {
  8164. return true;
  8165. }
  8166. }
  8167. return false;
  8168. } catch (e) {
  8169. return false;
  8170. }
  8171. }
  8172. function toFastProperties(obj) {
  8173. /*jshint -W027,-W055,-W031*/
  8174. function FakeConstructor() {}
  8175. FakeConstructor.prototype = obj;
  8176. var l = 8;
  8177. while (l--) new FakeConstructor();
  8178. return obj;
  8179. eval(obj);
  8180. }
  8181. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  8182. function isIdentifier(str) {
  8183. return rident.test(str);
  8184. }
  8185. function filledRange(count, prefix, suffix) {
  8186. var ret = new Array(count);
  8187. for(var i = 0; i < count; ++i) {
  8188. ret[i] = prefix + i + suffix;
  8189. }
  8190. return ret;
  8191. }
  8192. function safeToString(obj) {
  8193. try {
  8194. return obj + "";
  8195. } catch (e) {
  8196. return "[no string representation]";
  8197. }
  8198. }
  8199. function isError(obj) {
  8200. return obj !== null &&
  8201. typeof obj === "object" &&
  8202. typeof obj.message === "string" &&
  8203. typeof obj.name === "string";
  8204. }
  8205. function markAsOriginatingFromRejection(e) {
  8206. try {
  8207. notEnumerableProp(e, "isOperational", true);
  8208. }
  8209. catch(ignore) {}
  8210. }
  8211. function originatesFromRejection(e) {
  8212. if (e == null) return false;
  8213. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  8214. e["isOperational"] === true);
  8215. }
  8216. function canAttachTrace(obj) {
  8217. return isError(obj) && es5.propertyIsWritable(obj, "stack");
  8218. }
  8219. var ensureErrorObject = (function() {
  8220. if (!("stack" in new Error())) {
  8221. return function(value) {
  8222. if (canAttachTrace(value)) return value;
  8223. try {throw new Error(safeToString(value));}
  8224. catch(err) {return err;}
  8225. };
  8226. } else {
  8227. return function(value) {
  8228. if (canAttachTrace(value)) return value;
  8229. return new Error(safeToString(value));
  8230. };
  8231. }
  8232. })();
  8233. function classString(obj) {
  8234. return {}.toString.call(obj);
  8235. }
  8236. function copyDescriptors(from, to, filter) {
  8237. var keys = es5.names(from);
  8238. for (var i = 0; i < keys.length; ++i) {
  8239. var key = keys[i];
  8240. if (filter(key)) {
  8241. try {
  8242. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  8243. } catch (ignore) {}
  8244. }
  8245. }
  8246. }
  8247. var asArray = function(v) {
  8248. if (es5.isArray(v)) {
  8249. return v;
  8250. }
  8251. return null;
  8252. };
  8253. if (typeof Symbol !== "undefined" && Symbol.iterator) {
  8254. var ArrayFrom = typeof Array.from === "function" ? function(v) {
  8255. return Array.from(v);
  8256. } : function(v) {
  8257. var ret = [];
  8258. var it = v[Symbol.iterator]();
  8259. var itResult;
  8260. while (!((itResult = it.next()).done)) {
  8261. ret.push(itResult.value);
  8262. }
  8263. return ret;
  8264. };
  8265. asArray = function(v) {
  8266. if (es5.isArray(v)) {
  8267. return v;
  8268. } else if (v != null && typeof v[Symbol.iterator] === "function") {
  8269. return ArrayFrom(v);
  8270. }
  8271. return null;
  8272. };
  8273. }
  8274. var isNode = typeof process !== "undefined" &&
  8275. classString(process).toLowerCase() === "[object process]";
  8276. var hasEnvVariables = typeof process !== "undefined" &&
  8277. typeof process.env !== "undefined";
  8278. function env(key) {
  8279. return hasEnvVariables ? process.env[key] : undefined;
  8280. }
  8281. function getNativePromise() {
  8282. if (typeof Promise === "function") {
  8283. try {
  8284. var promise = new Promise(function(){});
  8285. if ({}.toString.call(promise) === "[object Promise]") {
  8286. return Promise;
  8287. }
  8288. } catch (e) {}
  8289. }
  8290. }
  8291. function domainBind(self, cb) {
  8292. return self.bind(cb);
  8293. }
  8294. var ret = {
  8295. isClass: isClass,
  8296. isIdentifier: isIdentifier,
  8297. inheritedDataKeys: inheritedDataKeys,
  8298. getDataPropertyOrDefault: getDataPropertyOrDefault,
  8299. thrower: thrower,
  8300. isArray: es5.isArray,
  8301. asArray: asArray,
  8302. notEnumerableProp: notEnumerableProp,
  8303. isPrimitive: isPrimitive,
  8304. isObject: isObject,
  8305. isError: isError,
  8306. canEvaluate: canEvaluate,
  8307. errorObj: errorObj,
  8308. tryCatch: tryCatch,
  8309. inherits: inherits,
  8310. withAppended: withAppended,
  8311. maybeWrapAsError: maybeWrapAsError,
  8312. toFastProperties: toFastProperties,
  8313. filledRange: filledRange,
  8314. toString: safeToString,
  8315. canAttachTrace: canAttachTrace,
  8316. ensureErrorObject: ensureErrorObject,
  8317. originatesFromRejection: originatesFromRejection,
  8318. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  8319. classString: classString,
  8320. copyDescriptors: copyDescriptors,
  8321. hasDevTools: typeof chrome !== "undefined" && chrome &&
  8322. typeof chrome.loadTimes === "function",
  8323. isNode: isNode,
  8324. hasEnvVariables: hasEnvVariables,
  8325. env: env,
  8326. global: globalObject,
  8327. getNativePromise: getNativePromise,
  8328. domainBind: domainBind
  8329. };
  8330. ret.isRecentNode = ret.isNode && (function() {
  8331. var version = process.versions.node.split(".").map(Number);
  8332. return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  8333. })();
  8334. if (ret.isNode) ret.toFastProperties(process);
  8335. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  8336. module.exports = ret;
  8337. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8338. },{"./es5":51,"_process":138}],75:[function(require,module,exports){
  8339. },{}],76:[function(require,module,exports){
  8340. (function (global){
  8341. 'use strict';
  8342. var buffer = require('buffer');
  8343. var Buffer = buffer.Buffer;
  8344. var SlowBuffer = buffer.SlowBuffer;
  8345. var MAX_LEN = buffer.kMaxLength || 2147483647;
  8346. exports.alloc = function alloc(size, fill, encoding) {
  8347. if (typeof Buffer.alloc === 'function') {
  8348. return Buffer.alloc(size, fill, encoding);
  8349. }
  8350. if (typeof encoding === 'number') {
  8351. throw new TypeError('encoding must not be number');
  8352. }
  8353. if (typeof size !== 'number') {
  8354. throw new TypeError('size must be a number');
  8355. }
  8356. if (size > MAX_LEN) {
  8357. throw new RangeError('size is too large');
  8358. }
  8359. var enc = encoding;
  8360. var _fill = fill;
  8361. if (_fill === undefined) {
  8362. enc = undefined;
  8363. _fill = 0;
  8364. }
  8365. var buf = new Buffer(size);
  8366. if (typeof _fill === 'string') {
  8367. var fillBuf = new Buffer(_fill, enc);
  8368. var flen = fillBuf.length;
  8369. var i = -1;
  8370. while (++i < size) {
  8371. buf[i] = fillBuf[i % flen];
  8372. }
  8373. } else {
  8374. buf.fill(_fill);
  8375. }
  8376. return buf;
  8377. }
  8378. exports.allocUnsafe = function allocUnsafe(size) {
  8379. if (typeof Buffer.allocUnsafe === 'function') {
  8380. return Buffer.allocUnsafe(size);
  8381. }
  8382. if (typeof size !== 'number') {
  8383. throw new TypeError('size must be a number');
  8384. }
  8385. if (size > MAX_LEN) {
  8386. throw new RangeError('size is too large');
  8387. }
  8388. return new Buffer(size);
  8389. }
  8390. exports.from = function from(value, encodingOrOffset, length) {
  8391. if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
  8392. return Buffer.from(value, encodingOrOffset, length);
  8393. }
  8394. if (typeof value === 'number') {
  8395. throw new TypeError('"value" argument must not be a number');
  8396. }
  8397. if (typeof value === 'string') {
  8398. return new Buffer(value, encodingOrOffset);
  8399. }
  8400. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  8401. var offset = encodingOrOffset;
  8402. if (arguments.length === 1) {
  8403. return new Buffer(value);
  8404. }
  8405. if (typeof offset === 'undefined') {
  8406. offset = 0;
  8407. }
  8408. var len = length;
  8409. if (typeof len === 'undefined') {
  8410. len = value.byteLength - offset;
  8411. }
  8412. if (offset >= value.byteLength) {
  8413. throw new RangeError('\'offset\' is out of bounds');
  8414. }
  8415. if (len > value.byteLength - offset) {
  8416. throw new RangeError('\'length\' is out of bounds');
  8417. }
  8418. return new Buffer(value.slice(offset, offset + len));
  8419. }
  8420. if (Buffer.isBuffer(value)) {
  8421. var out = new Buffer(value.length);
  8422. value.copy(out, 0, 0, value.length);
  8423. return out;
  8424. }
  8425. if (value) {
  8426. if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
  8427. return new Buffer(value);
  8428. }
  8429. if (value.type === 'Buffer' && Array.isArray(value.data)) {
  8430. return new Buffer(value.data);
  8431. }
  8432. }
  8433. throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
  8434. }
  8435. exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
  8436. if (typeof Buffer.allocUnsafeSlow === 'function') {
  8437. return Buffer.allocUnsafeSlow(size);
  8438. }
  8439. if (typeof size !== 'number') {
  8440. throw new TypeError('size must be a number');
  8441. }
  8442. if (size >= MAX_LEN) {
  8443. throw new RangeError('size is too large');
  8444. }
  8445. return new SlowBuffer(size);
  8446. }
  8447. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8448. },{"buffer":77}],77:[function(require,module,exports){
  8449. (function (global){
  8450. /*!
  8451. * The buffer module from node.js, for the browser.
  8452. *
  8453. * @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
  8454. * @license MIT
  8455. */
  8456. /* eslint-disable no-proto */
  8457. 'use strict'
  8458. var base64 = require('base64-js')
  8459. var ieee754 = require('ieee754')
  8460. var isArray = require('isarray')
  8461. exports.Buffer = Buffer
  8462. exports.SlowBuffer = SlowBuffer
  8463. exports.INSPECT_MAX_BYTES = 50
  8464. /**
  8465. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  8466. * === true Use Uint8Array implementation (fastest)
  8467. * === false Use Object implementation (most compatible, even IE6)
  8468. *
  8469. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  8470. * Opera 11.6+, iOS 4.2+.
  8471. *
  8472. * Due to various browser bugs, sometimes the Object implementation will be used even
  8473. * when the browser supports typed arrays.
  8474. *
  8475. * Note:
  8476. *
  8477. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  8478. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  8479. *
  8480. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  8481. *
  8482. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  8483. * incorrect length in some situations.
  8484. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  8485. * get the Object implementation, which is slower but behaves correctly.
  8486. */
  8487. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  8488. ? global.TYPED_ARRAY_SUPPORT
  8489. : typedArraySupport()
  8490. /*
  8491. * Export kMaxLength after typed array support is determined.
  8492. */
  8493. exports.kMaxLength = kMaxLength()
  8494. function typedArraySupport () {
  8495. try {
  8496. var arr = new Uint8Array(1)
  8497. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  8498. return arr.foo() === 42 && // typed array instances can be augmented
  8499. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  8500. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  8501. } catch (e) {
  8502. return false
  8503. }
  8504. }
  8505. function kMaxLength () {
  8506. return Buffer.TYPED_ARRAY_SUPPORT
  8507. ? 0x7fffffff
  8508. : 0x3fffffff
  8509. }
  8510. function createBuffer (that, length) {
  8511. if (kMaxLength() < length) {
  8512. throw new RangeError('Invalid typed array length')
  8513. }
  8514. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8515. // Return an augmented `Uint8Array` instance, for best performance
  8516. that = new Uint8Array(length)
  8517. that.__proto__ = Buffer.prototype
  8518. } else {
  8519. // Fallback: Return an object instance of the Buffer class
  8520. if (that === null) {
  8521. that = new Buffer(length)
  8522. }
  8523. that.length = length
  8524. }
  8525. return that
  8526. }
  8527. /**
  8528. * The Buffer constructor returns instances of `Uint8Array` that have their
  8529. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  8530. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  8531. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  8532. * returns a single octet.
  8533. *
  8534. * The `Uint8Array` prototype remains unmodified.
  8535. */
  8536. function Buffer (arg, encodingOrOffset, length) {
  8537. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  8538. return new Buffer(arg, encodingOrOffset, length)
  8539. }
  8540. // Common case.
  8541. if (typeof arg === 'number') {
  8542. if (typeof encodingOrOffset === 'string') {
  8543. throw new Error(
  8544. 'If encoding is specified then the first argument must be a string'
  8545. )
  8546. }
  8547. return allocUnsafe(this, arg)
  8548. }
  8549. return from(this, arg, encodingOrOffset, length)
  8550. }
  8551. Buffer.poolSize = 8192 // not used by this implementation
  8552. // TODO: Legacy, not needed anymore. Remove in next major version.
  8553. Buffer._augment = function (arr) {
  8554. arr.__proto__ = Buffer.prototype
  8555. return arr
  8556. }
  8557. function from (that, value, encodingOrOffset, length) {
  8558. if (typeof value === 'number') {
  8559. throw new TypeError('"value" argument must not be a number')
  8560. }
  8561. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  8562. return fromArrayBuffer(that, value, encodingOrOffset, length)
  8563. }
  8564. if (typeof value === 'string') {
  8565. return fromString(that, value, encodingOrOffset)
  8566. }
  8567. return fromObject(that, value)
  8568. }
  8569. /**
  8570. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  8571. * if value is a number.
  8572. * Buffer.from(str[, encoding])
  8573. * Buffer.from(array)
  8574. * Buffer.from(buffer)
  8575. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  8576. **/
  8577. Buffer.from = function (value, encodingOrOffset, length) {
  8578. return from(null, value, encodingOrOffset, length)
  8579. }
  8580. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8581. Buffer.prototype.__proto__ = Uint8Array.prototype
  8582. Buffer.__proto__ = Uint8Array
  8583. if (typeof Symbol !== 'undefined' && Symbol.species &&
  8584. Buffer[Symbol.species] === Buffer) {
  8585. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  8586. Object.defineProperty(Buffer, Symbol.species, {
  8587. value: null,
  8588. configurable: true
  8589. })
  8590. }
  8591. }
  8592. function assertSize (size) {
  8593. if (typeof size !== 'number') {
  8594. throw new TypeError('"size" argument must be a number')
  8595. } else if (size < 0) {
  8596. throw new RangeError('"size" argument must not be negative')
  8597. }
  8598. }
  8599. function alloc (that, size, fill, encoding) {
  8600. assertSize(size)
  8601. if (size <= 0) {
  8602. return createBuffer(that, size)
  8603. }
  8604. if (fill !== undefined) {
  8605. // Only pay attention to encoding if it's a string. This
  8606. // prevents accidentally sending in a number that would
  8607. // be interpretted as a start offset.
  8608. return typeof encoding === 'string'
  8609. ? createBuffer(that, size).fill(fill, encoding)
  8610. : createBuffer(that, size).fill(fill)
  8611. }
  8612. return createBuffer(that, size)
  8613. }
  8614. /**
  8615. * Creates a new filled Buffer instance.
  8616. * alloc(size[, fill[, encoding]])
  8617. **/
  8618. Buffer.alloc = function (size, fill, encoding) {
  8619. return alloc(null, size, fill, encoding)
  8620. }
  8621. function allocUnsafe (that, size) {
  8622. assertSize(size)
  8623. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  8624. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  8625. for (var i = 0; i < size; ++i) {
  8626. that[i] = 0
  8627. }
  8628. }
  8629. return that
  8630. }
  8631. /**
  8632. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  8633. * */
  8634. Buffer.allocUnsafe = function (size) {
  8635. return allocUnsafe(null, size)
  8636. }
  8637. /**
  8638. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  8639. */
  8640. Buffer.allocUnsafeSlow = function (size) {
  8641. return allocUnsafe(null, size)
  8642. }
  8643. function fromString (that, string, encoding) {
  8644. if (typeof encoding !== 'string' || encoding === '') {
  8645. encoding = 'utf8'
  8646. }
  8647. if (!Buffer.isEncoding(encoding)) {
  8648. throw new TypeError('"encoding" must be a valid string encoding')
  8649. }
  8650. var length = byteLength(string, encoding) | 0
  8651. that = createBuffer(that, length)
  8652. var actual = that.write(string, encoding)
  8653. if (actual !== length) {
  8654. // Writing a hex string, for example, that contains invalid characters will
  8655. // cause everything after the first invalid character to be ignored. (e.g.
  8656. // 'abxxcd' will be treated as 'ab')
  8657. that = that.slice(0, actual)
  8658. }
  8659. return that
  8660. }
  8661. function fromArrayLike (that, array) {
  8662. var length = array.length < 0 ? 0 : checked(array.length) | 0
  8663. that = createBuffer(that, length)
  8664. for (var i = 0; i < length; i += 1) {
  8665. that[i] = array[i] & 255
  8666. }
  8667. return that
  8668. }
  8669. function fromArrayBuffer (that, array, byteOffset, length) {
  8670. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  8671. if (byteOffset < 0 || array.byteLength < byteOffset) {
  8672. throw new RangeError('\'offset\' is out of bounds')
  8673. }
  8674. if (array.byteLength < byteOffset + (length || 0)) {
  8675. throw new RangeError('\'length\' is out of bounds')
  8676. }
  8677. if (byteOffset === undefined && length === undefined) {
  8678. array = new Uint8Array(array)
  8679. } else if (length === undefined) {
  8680. array = new Uint8Array(array, byteOffset)
  8681. } else {
  8682. array = new Uint8Array(array, byteOffset, length)
  8683. }
  8684. if (Buffer.TYPED_ARRAY_SUPPORT) {
  8685. // Return an augmented `Uint8Array` instance, for best performance
  8686. that = array
  8687. that.__proto__ = Buffer.prototype
  8688. } else {
  8689. // Fallback: Return an object instance of the Buffer class
  8690. that = fromArrayLike(that, array)
  8691. }
  8692. return that
  8693. }
  8694. function fromObject (that, obj) {
  8695. if (Buffer.isBuffer(obj)) {
  8696. var len = checked(obj.length) | 0
  8697. that = createBuffer(that, len)
  8698. if (that.length === 0) {
  8699. return that
  8700. }
  8701. obj.copy(that, 0, 0, len)
  8702. return that
  8703. }
  8704. if (obj) {
  8705. if ((typeof ArrayBuffer !== 'undefined' &&
  8706. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  8707. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  8708. return createBuffer(that, 0)
  8709. }
  8710. return fromArrayLike(that, obj)
  8711. }
  8712. if (obj.type === 'Buffer' && isArray(obj.data)) {
  8713. return fromArrayLike(that, obj.data)
  8714. }
  8715. }
  8716. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  8717. }
  8718. function checked (length) {
  8719. // Note: cannot use `length < kMaxLength()` here because that fails when
  8720. // length is NaN (which is otherwise coerced to zero.)
  8721. if (length >= kMaxLength()) {
  8722. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  8723. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  8724. }
  8725. return length | 0
  8726. }
  8727. function SlowBuffer (length) {
  8728. if (+length != length) { // eslint-disable-line eqeqeq
  8729. length = 0
  8730. }
  8731. return Buffer.alloc(+length)
  8732. }
  8733. Buffer.isBuffer = function isBuffer (b) {
  8734. return !!(b != null && b._isBuffer)
  8735. }
  8736. Buffer.compare = function compare (a, b) {
  8737. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  8738. throw new TypeError('Arguments must be Buffers')
  8739. }
  8740. if (a === b) return 0
  8741. var x = a.length
  8742. var y = b.length
  8743. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  8744. if (a[i] !== b[i]) {
  8745. x = a[i]
  8746. y = b[i]
  8747. break
  8748. }
  8749. }
  8750. if (x < y) return -1
  8751. if (y < x) return 1
  8752. return 0
  8753. }
  8754. Buffer.isEncoding = function isEncoding (encoding) {
  8755. switch (String(encoding).toLowerCase()) {
  8756. case 'hex':
  8757. case 'utf8':
  8758. case 'utf-8':
  8759. case 'ascii':
  8760. case 'latin1':
  8761. case 'binary':
  8762. case 'base64':
  8763. case 'ucs2':
  8764. case 'ucs-2':
  8765. case 'utf16le':
  8766. case 'utf-16le':
  8767. return true
  8768. default:
  8769. return false
  8770. }
  8771. }
  8772. Buffer.concat = function concat (list, length) {
  8773. if (!isArray(list)) {
  8774. throw new TypeError('"list" argument must be an Array of Buffers')
  8775. }
  8776. if (list.length === 0) {
  8777. return Buffer.alloc(0)
  8778. }
  8779. var i
  8780. if (length === undefined) {
  8781. length = 0
  8782. for (i = 0; i < list.length; ++i) {
  8783. length += list[i].length
  8784. }
  8785. }
  8786. var buffer = Buffer.allocUnsafe(length)
  8787. var pos = 0
  8788. for (i = 0; i < list.length; ++i) {
  8789. var buf = list[i]
  8790. if (!Buffer.isBuffer(buf)) {
  8791. throw new TypeError('"list" argument must be an Array of Buffers')
  8792. }
  8793. buf.copy(buffer, pos)
  8794. pos += buf.length
  8795. }
  8796. return buffer
  8797. }
  8798. function byteLength (string, encoding) {
  8799. if (Buffer.isBuffer(string)) {
  8800. return string.length
  8801. }
  8802. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  8803. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  8804. return string.byteLength
  8805. }
  8806. if (typeof string !== 'string') {
  8807. string = '' + string
  8808. }
  8809. var len = string.length
  8810. if (len === 0) return 0
  8811. // Use a for loop to avoid recursion
  8812. var loweredCase = false
  8813. for (;;) {
  8814. switch (encoding) {
  8815. case 'ascii':
  8816. case 'latin1':
  8817. case 'binary':
  8818. return len
  8819. case 'utf8':
  8820. case 'utf-8':
  8821. case undefined:
  8822. return utf8ToBytes(string).length
  8823. case 'ucs2':
  8824. case 'ucs-2':
  8825. case 'utf16le':
  8826. case 'utf-16le':
  8827. return len * 2
  8828. case 'hex':
  8829. return len >>> 1
  8830. case 'base64':
  8831. return base64ToBytes(string).length
  8832. default:
  8833. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  8834. encoding = ('' + encoding).toLowerCase()
  8835. loweredCase = true
  8836. }
  8837. }
  8838. }
  8839. Buffer.byteLength = byteLength
  8840. function slowToString (encoding, start, end) {
  8841. var loweredCase = false
  8842. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  8843. // property of a typed array.
  8844. // This behaves neither like String nor Uint8Array in that we set start/end
  8845. // to their upper/lower bounds if the value passed is out of range.
  8846. // undefined is handled specially as per ECMA-262 6th Edition,
  8847. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  8848. if (start === undefined || start < 0) {
  8849. start = 0
  8850. }
  8851. // Return early if start > this.length. Done here to prevent potential uint32
  8852. // coercion fail below.
  8853. if (start > this.length) {
  8854. return ''
  8855. }
  8856. if (end === undefined || end > this.length) {
  8857. end = this.length
  8858. }
  8859. if (end <= 0) {
  8860. return ''
  8861. }
  8862. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  8863. end >>>= 0
  8864. start >>>= 0
  8865. if (end <= start) {
  8866. return ''
  8867. }
  8868. if (!encoding) encoding = 'utf8'
  8869. while (true) {
  8870. switch (encoding) {
  8871. case 'hex':
  8872. return hexSlice(this, start, end)
  8873. case 'utf8':
  8874. case 'utf-8':
  8875. return utf8Slice(this, start, end)
  8876. case 'ascii':
  8877. return asciiSlice(this, start, end)
  8878. case 'latin1':
  8879. case 'binary':
  8880. return latin1Slice(this, start, end)
  8881. case 'base64':
  8882. return base64Slice(this, start, end)
  8883. case 'ucs2':
  8884. case 'ucs-2':
  8885. case 'utf16le':
  8886. case 'utf-16le':
  8887. return utf16leSlice(this, start, end)
  8888. default:
  8889. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  8890. encoding = (encoding + '').toLowerCase()
  8891. loweredCase = true
  8892. }
  8893. }
  8894. }
  8895. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  8896. // Buffer instances.
  8897. Buffer.prototype._isBuffer = true
  8898. function swap (b, n, m) {
  8899. var i = b[n]
  8900. b[n] = b[m]
  8901. b[m] = i
  8902. }
  8903. Buffer.prototype.swap16 = function swap16 () {
  8904. var len = this.length
  8905. if (len % 2 !== 0) {
  8906. throw new RangeError('Buffer size must be a multiple of 16-bits')
  8907. }
  8908. for (var i = 0; i < len; i += 2) {
  8909. swap(this, i, i + 1)
  8910. }
  8911. return this
  8912. }
  8913. Buffer.prototype.swap32 = function swap32 () {
  8914. var len = this.length
  8915. if (len % 4 !== 0) {
  8916. throw new RangeError('Buffer size must be a multiple of 32-bits')
  8917. }
  8918. for (var i = 0; i < len; i += 4) {
  8919. swap(this, i, i + 3)
  8920. swap(this, i + 1, i + 2)
  8921. }
  8922. return this
  8923. }
  8924. Buffer.prototype.swap64 = function swap64 () {
  8925. var len = this.length
  8926. if (len % 8 !== 0) {
  8927. throw new RangeError('Buffer size must be a multiple of 64-bits')
  8928. }
  8929. for (var i = 0; i < len; i += 8) {
  8930. swap(this, i, i + 7)
  8931. swap(this, i + 1, i + 6)
  8932. swap(this, i + 2, i + 5)
  8933. swap(this, i + 3, i + 4)
  8934. }
  8935. return this
  8936. }
  8937. Buffer.prototype.toString = function toString () {
  8938. var length = this.length | 0
  8939. if (length === 0) return ''
  8940. if (arguments.length === 0) return utf8Slice(this, 0, length)
  8941. return slowToString.apply(this, arguments)
  8942. }
  8943. Buffer.prototype.equals = function equals (b) {
  8944. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  8945. if (this === b) return true
  8946. return Buffer.compare(this, b) === 0
  8947. }
  8948. Buffer.prototype.inspect = function inspect () {
  8949. var str = ''
  8950. var max = exports.INSPECT_MAX_BYTES
  8951. if (this.length > 0) {
  8952. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  8953. if (this.length > max) str += ' ... '
  8954. }
  8955. return '<Buffer ' + str + '>'
  8956. }
  8957. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  8958. if (!Buffer.isBuffer(target)) {
  8959. throw new TypeError('Argument must be a Buffer')
  8960. }
  8961. if (start === undefined) {
  8962. start = 0
  8963. }
  8964. if (end === undefined) {
  8965. end = target ? target.length : 0
  8966. }
  8967. if (thisStart === undefined) {
  8968. thisStart = 0
  8969. }
  8970. if (thisEnd === undefined) {
  8971. thisEnd = this.length
  8972. }
  8973. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  8974. throw new RangeError('out of range index')
  8975. }
  8976. if (thisStart >= thisEnd && start >= end) {
  8977. return 0
  8978. }
  8979. if (thisStart >= thisEnd) {
  8980. return -1
  8981. }
  8982. if (start >= end) {
  8983. return 1
  8984. }
  8985. start >>>= 0
  8986. end >>>= 0
  8987. thisStart >>>= 0
  8988. thisEnd >>>= 0
  8989. if (this === target) return 0
  8990. var x = thisEnd - thisStart
  8991. var y = end - start
  8992. var len = Math.min(x, y)
  8993. var thisCopy = this.slice(thisStart, thisEnd)
  8994. var targetCopy = target.slice(start, end)
  8995. for (var i = 0; i < len; ++i) {
  8996. if (thisCopy[i] !== targetCopy[i]) {
  8997. x = thisCopy[i]
  8998. y = targetCopy[i]
  8999. break
  9000. }
  9001. }
  9002. if (x < y) return -1
  9003. if (y < x) return 1
  9004. return 0
  9005. }
  9006. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  9007. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  9008. //
  9009. // Arguments:
  9010. // - buffer - a Buffer to search
  9011. // - val - a string, Buffer, or number
  9012. // - byteOffset - an index into `buffer`; will be clamped to an int32
  9013. // - encoding - an optional encoding, relevant is val is a string
  9014. // - dir - true for indexOf, false for lastIndexOf
  9015. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  9016. // Empty buffer means no match
  9017. if (buffer.length === 0) return -1
  9018. // Normalize byteOffset
  9019. if (typeof byteOffset === 'string') {
  9020. encoding = byteOffset
  9021. byteOffset = 0
  9022. } else if (byteOffset > 0x7fffffff) {
  9023. byteOffset = 0x7fffffff
  9024. } else if (byteOffset < -0x80000000) {
  9025. byteOffset = -0x80000000
  9026. }
  9027. byteOffset = +byteOffset // Coerce to Number.
  9028. if (isNaN(byteOffset)) {
  9029. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  9030. byteOffset = dir ? 0 : (buffer.length - 1)
  9031. }
  9032. // Normalize byteOffset: negative offsets start from the end of the buffer
  9033. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  9034. if (byteOffset >= buffer.length) {
  9035. if (dir) return -1
  9036. else byteOffset = buffer.length - 1
  9037. } else if (byteOffset < 0) {
  9038. if (dir) byteOffset = 0
  9039. else return -1
  9040. }
  9041. // Normalize val
  9042. if (typeof val === 'string') {
  9043. val = Buffer.from(val, encoding)
  9044. }
  9045. // Finally, search either indexOf (if dir is true) or lastIndexOf
  9046. if (Buffer.isBuffer(val)) {
  9047. // Special case: looking for empty string/buffer always fails
  9048. if (val.length === 0) {
  9049. return -1
  9050. }
  9051. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  9052. } else if (typeof val === 'number') {
  9053. val = val & 0xFF // Search for a byte value [0-255]
  9054. if (Buffer.TYPED_ARRAY_SUPPORT &&
  9055. typeof Uint8Array.prototype.indexOf === 'function') {
  9056. if (dir) {
  9057. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  9058. } else {
  9059. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  9060. }
  9061. }
  9062. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  9063. }
  9064. throw new TypeError('val must be string, number or Buffer')
  9065. }
  9066. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  9067. var indexSize = 1
  9068. var arrLength = arr.length
  9069. var valLength = val.length
  9070. if (encoding !== undefined) {
  9071. encoding = String(encoding).toLowerCase()
  9072. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  9073. encoding === 'utf16le' || encoding === 'utf-16le') {
  9074. if (arr.length < 2 || val.length < 2) {
  9075. return -1
  9076. }
  9077. indexSize = 2
  9078. arrLength /= 2
  9079. valLength /= 2
  9080. byteOffset /= 2
  9081. }
  9082. }
  9083. function read (buf, i) {
  9084. if (indexSize === 1) {
  9085. return buf[i]
  9086. } else {
  9087. return buf.readUInt16BE(i * indexSize)
  9088. }
  9089. }
  9090. var i
  9091. if (dir) {
  9092. var foundIndex = -1
  9093. for (i = byteOffset; i < arrLength; i++) {
  9094. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  9095. if (foundIndex === -1) foundIndex = i
  9096. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  9097. } else {
  9098. if (foundIndex !== -1) i -= i - foundIndex
  9099. foundIndex = -1
  9100. }
  9101. }
  9102. } else {
  9103. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  9104. for (i = byteOffset; i >= 0; i--) {
  9105. var found = true
  9106. for (var j = 0; j < valLength; j++) {
  9107. if (read(arr, i + j) !== read(val, j)) {
  9108. found = false
  9109. break
  9110. }
  9111. }
  9112. if (found) return i
  9113. }
  9114. }
  9115. return -1
  9116. }
  9117. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  9118. return this.indexOf(val, byteOffset, encoding) !== -1
  9119. }
  9120. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  9121. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  9122. }
  9123. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  9124. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  9125. }
  9126. function hexWrite (buf, string, offset, length) {
  9127. offset = Number(offset) || 0
  9128. var remaining = buf.length - offset
  9129. if (!length) {
  9130. length = remaining
  9131. } else {
  9132. length = Number(length)
  9133. if (length > remaining) {
  9134. length = remaining
  9135. }
  9136. }
  9137. // must be an even number of digits
  9138. var strLen = string.length
  9139. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  9140. if (length > strLen / 2) {
  9141. length = strLen / 2
  9142. }
  9143. for (var i = 0; i < length; ++i) {
  9144. var parsed = parseInt(string.substr(i * 2, 2), 16)
  9145. if (isNaN(parsed)) return i
  9146. buf[offset + i] = parsed
  9147. }
  9148. return i
  9149. }
  9150. function utf8Write (buf, string, offset, length) {
  9151. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  9152. }
  9153. function asciiWrite (buf, string, offset, length) {
  9154. return blitBuffer(asciiToBytes(string), buf, offset, length)
  9155. }
  9156. function latin1Write (buf, string, offset, length) {
  9157. return asciiWrite(buf, string, offset, length)
  9158. }
  9159. function base64Write (buf, string, offset, length) {
  9160. return blitBuffer(base64ToBytes(string), buf, offset, length)
  9161. }
  9162. function ucs2Write (buf, string, offset, length) {
  9163. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  9164. }
  9165. Buffer.prototype.write = function write (string, offset, length, encoding) {
  9166. // Buffer#write(string)
  9167. if (offset === undefined) {
  9168. encoding = 'utf8'
  9169. length = this.length
  9170. offset = 0
  9171. // Buffer#write(string, encoding)
  9172. } else if (length === undefined && typeof offset === 'string') {
  9173. encoding = offset
  9174. length = this.length
  9175. offset = 0
  9176. // Buffer#write(string, offset[, length][, encoding])
  9177. } else if (isFinite(offset)) {
  9178. offset = offset | 0
  9179. if (isFinite(length)) {
  9180. length = length | 0
  9181. if (encoding === undefined) encoding = 'utf8'
  9182. } else {
  9183. encoding = length
  9184. length = undefined
  9185. }
  9186. // legacy write(string, encoding, offset, length) - remove in v0.13
  9187. } else {
  9188. throw new Error(
  9189. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  9190. )
  9191. }
  9192. var remaining = this.length - offset
  9193. if (length === undefined || length > remaining) length = remaining
  9194. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  9195. throw new RangeError('Attempt to write outside buffer bounds')
  9196. }
  9197. if (!encoding) encoding = 'utf8'
  9198. var loweredCase = false
  9199. for (;;) {
  9200. switch (encoding) {
  9201. case 'hex':
  9202. return hexWrite(this, string, offset, length)
  9203. case 'utf8':
  9204. case 'utf-8':
  9205. return utf8Write(this, string, offset, length)
  9206. case 'ascii':
  9207. return asciiWrite(this, string, offset, length)
  9208. case 'latin1':
  9209. case 'binary':
  9210. return latin1Write(this, string, offset, length)
  9211. case 'base64':
  9212. // Warning: maxLength not taken into account in base64Write
  9213. return base64Write(this, string, offset, length)
  9214. case 'ucs2':
  9215. case 'ucs-2':
  9216. case 'utf16le':
  9217. case 'utf-16le':
  9218. return ucs2Write(this, string, offset, length)
  9219. default:
  9220. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  9221. encoding = ('' + encoding).toLowerCase()
  9222. loweredCase = true
  9223. }
  9224. }
  9225. }
  9226. Buffer.prototype.toJSON = function toJSON () {
  9227. return {
  9228. type: 'Buffer',
  9229. data: Array.prototype.slice.call(this._arr || this, 0)
  9230. }
  9231. }
  9232. function base64Slice (buf, start, end) {
  9233. if (start === 0 && end === buf.length) {
  9234. return base64.fromByteArray(buf)
  9235. } else {
  9236. return base64.fromByteArray(buf.slice(start, end))
  9237. }
  9238. }
  9239. function utf8Slice (buf, start, end) {
  9240. end = Math.min(buf.length, end)
  9241. var res = []
  9242. var i = start
  9243. while (i < end) {
  9244. var firstByte = buf[i]
  9245. var codePoint = null
  9246. var bytesPerSequence = (firstByte > 0xEF) ? 4
  9247. : (firstByte > 0xDF) ? 3
  9248. : (firstByte > 0xBF) ? 2
  9249. : 1
  9250. if (i + bytesPerSequence <= end) {
  9251. var secondByte, thirdByte, fourthByte, tempCodePoint
  9252. switch (bytesPerSequence) {
  9253. case 1:
  9254. if (firstByte < 0x80) {
  9255. codePoint = firstByte
  9256. }
  9257. break
  9258. case 2:
  9259. secondByte = buf[i + 1]
  9260. if ((secondByte & 0xC0) === 0x80) {
  9261. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  9262. if (tempCodePoint > 0x7F) {
  9263. codePoint = tempCodePoint
  9264. }
  9265. }
  9266. break
  9267. case 3:
  9268. secondByte = buf[i + 1]
  9269. thirdByte = buf[i + 2]
  9270. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  9271. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  9272. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  9273. codePoint = tempCodePoint
  9274. }
  9275. }
  9276. break
  9277. case 4:
  9278. secondByte = buf[i + 1]
  9279. thirdByte = buf[i + 2]
  9280. fourthByte = buf[i + 3]
  9281. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  9282. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  9283. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  9284. codePoint = tempCodePoint
  9285. }
  9286. }
  9287. }
  9288. }
  9289. if (codePoint === null) {
  9290. // we did not generate a valid codePoint so insert a
  9291. // replacement char (U+FFFD) and advance only 1 byte
  9292. codePoint = 0xFFFD
  9293. bytesPerSequence = 1
  9294. } else if (codePoint > 0xFFFF) {
  9295. // encode to utf16 (surrogate pair dance)
  9296. codePoint -= 0x10000
  9297. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  9298. codePoint = 0xDC00 | codePoint & 0x3FF
  9299. }
  9300. res.push(codePoint)
  9301. i += bytesPerSequence
  9302. }
  9303. return decodeCodePointsArray(res)
  9304. }
  9305. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  9306. // the lowest limit is Chrome, with 0x10000 args.
  9307. // We go 1 magnitude less, for safety
  9308. var MAX_ARGUMENTS_LENGTH = 0x1000
  9309. function decodeCodePointsArray (codePoints) {
  9310. var len = codePoints.length
  9311. if (len <= MAX_ARGUMENTS_LENGTH) {
  9312. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  9313. }
  9314. // Decode in chunks to avoid "call stack size exceeded".
  9315. var res = ''
  9316. var i = 0
  9317. while (i < len) {
  9318. res += String.fromCharCode.apply(
  9319. String,
  9320. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  9321. )
  9322. }
  9323. return res
  9324. }
  9325. function asciiSlice (buf, start, end) {
  9326. var ret = ''
  9327. end = Math.min(buf.length, end)
  9328. for (var i = start; i < end; ++i) {
  9329. ret += String.fromCharCode(buf[i] & 0x7F)
  9330. }
  9331. return ret
  9332. }
  9333. function latin1Slice (buf, start, end) {
  9334. var ret = ''
  9335. end = Math.min(buf.length, end)
  9336. for (var i = start; i < end; ++i) {
  9337. ret += String.fromCharCode(buf[i])
  9338. }
  9339. return ret
  9340. }
  9341. function hexSlice (buf, start, end) {
  9342. var len = buf.length
  9343. if (!start || start < 0) start = 0
  9344. if (!end || end < 0 || end > len) end = len
  9345. var out = ''
  9346. for (var i = start; i < end; ++i) {
  9347. out += toHex(buf[i])
  9348. }
  9349. return out
  9350. }
  9351. function utf16leSlice (buf, start, end) {
  9352. var bytes = buf.slice(start, end)
  9353. var res = ''
  9354. for (var i = 0; i < bytes.length; i += 2) {
  9355. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  9356. }
  9357. return res
  9358. }
  9359. Buffer.prototype.slice = function slice (start, end) {
  9360. var len = this.length
  9361. start = ~~start
  9362. end = end === undefined ? len : ~~end
  9363. if (start < 0) {
  9364. start += len
  9365. if (start < 0) start = 0
  9366. } else if (start > len) {
  9367. start = len
  9368. }
  9369. if (end < 0) {
  9370. end += len
  9371. if (end < 0) end = 0
  9372. } else if (end > len) {
  9373. end = len
  9374. }
  9375. if (end < start) end = start
  9376. var newBuf
  9377. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9378. newBuf = this.subarray(start, end)
  9379. newBuf.__proto__ = Buffer.prototype
  9380. } else {
  9381. var sliceLen = end - start
  9382. newBuf = new Buffer(sliceLen, undefined)
  9383. for (var i = 0; i < sliceLen; ++i) {
  9384. newBuf[i] = this[i + start]
  9385. }
  9386. }
  9387. return newBuf
  9388. }
  9389. /*
  9390. * Need to make sure that buffer isn't trying to write out of bounds.
  9391. */
  9392. function checkOffset (offset, ext, length) {
  9393. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  9394. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  9395. }
  9396. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  9397. offset = offset | 0
  9398. byteLength = byteLength | 0
  9399. if (!noAssert) checkOffset(offset, byteLength, this.length)
  9400. var val = this[offset]
  9401. var mul = 1
  9402. var i = 0
  9403. while (++i < byteLength && (mul *= 0x100)) {
  9404. val += this[offset + i] * mul
  9405. }
  9406. return val
  9407. }
  9408. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  9409. offset = offset | 0
  9410. byteLength = byteLength | 0
  9411. if (!noAssert) {
  9412. checkOffset(offset, byteLength, this.length)
  9413. }
  9414. var val = this[offset + --byteLength]
  9415. var mul = 1
  9416. while (byteLength > 0 && (mul *= 0x100)) {
  9417. val += this[offset + --byteLength] * mul
  9418. }
  9419. return val
  9420. }
  9421. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  9422. if (!noAssert) checkOffset(offset, 1, this.length)
  9423. return this[offset]
  9424. }
  9425. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  9426. if (!noAssert) checkOffset(offset, 2, this.length)
  9427. return this[offset] | (this[offset + 1] << 8)
  9428. }
  9429. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  9430. if (!noAssert) checkOffset(offset, 2, this.length)
  9431. return (this[offset] << 8) | this[offset + 1]
  9432. }
  9433. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  9434. if (!noAssert) checkOffset(offset, 4, this.length)
  9435. return ((this[offset]) |
  9436. (this[offset + 1] << 8) |
  9437. (this[offset + 2] << 16)) +
  9438. (this[offset + 3] * 0x1000000)
  9439. }
  9440. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  9441. if (!noAssert) checkOffset(offset, 4, this.length)
  9442. return (this[offset] * 0x1000000) +
  9443. ((this[offset + 1] << 16) |
  9444. (this[offset + 2] << 8) |
  9445. this[offset + 3])
  9446. }
  9447. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  9448. offset = offset | 0
  9449. byteLength = byteLength | 0
  9450. if (!noAssert) checkOffset(offset, byteLength, this.length)
  9451. var val = this[offset]
  9452. var mul = 1
  9453. var i = 0
  9454. while (++i < byteLength && (mul *= 0x100)) {
  9455. val += this[offset + i] * mul
  9456. }
  9457. mul *= 0x80
  9458. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  9459. return val
  9460. }
  9461. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  9462. offset = offset | 0
  9463. byteLength = byteLength | 0
  9464. if (!noAssert) checkOffset(offset, byteLength, this.length)
  9465. var i = byteLength
  9466. var mul = 1
  9467. var val = this[offset + --i]
  9468. while (i > 0 && (mul *= 0x100)) {
  9469. val += this[offset + --i] * mul
  9470. }
  9471. mul *= 0x80
  9472. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  9473. return val
  9474. }
  9475. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  9476. if (!noAssert) checkOffset(offset, 1, this.length)
  9477. if (!(this[offset] & 0x80)) return (this[offset])
  9478. return ((0xff - this[offset] + 1) * -1)
  9479. }
  9480. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  9481. if (!noAssert) checkOffset(offset, 2, this.length)
  9482. var val = this[offset] | (this[offset + 1] << 8)
  9483. return (val & 0x8000) ? val | 0xFFFF0000 : val
  9484. }
  9485. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  9486. if (!noAssert) checkOffset(offset, 2, this.length)
  9487. var val = this[offset + 1] | (this[offset] << 8)
  9488. return (val & 0x8000) ? val | 0xFFFF0000 : val
  9489. }
  9490. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  9491. if (!noAssert) checkOffset(offset, 4, this.length)
  9492. return (this[offset]) |
  9493. (this[offset + 1] << 8) |
  9494. (this[offset + 2] << 16) |
  9495. (this[offset + 3] << 24)
  9496. }
  9497. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  9498. if (!noAssert) checkOffset(offset, 4, this.length)
  9499. return (this[offset] << 24) |
  9500. (this[offset + 1] << 16) |
  9501. (this[offset + 2] << 8) |
  9502. (this[offset + 3])
  9503. }
  9504. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  9505. if (!noAssert) checkOffset(offset, 4, this.length)
  9506. return ieee754.read(this, offset, true, 23, 4)
  9507. }
  9508. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  9509. if (!noAssert) checkOffset(offset, 4, this.length)
  9510. return ieee754.read(this, offset, false, 23, 4)
  9511. }
  9512. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  9513. if (!noAssert) checkOffset(offset, 8, this.length)
  9514. return ieee754.read(this, offset, true, 52, 8)
  9515. }
  9516. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  9517. if (!noAssert) checkOffset(offset, 8, this.length)
  9518. return ieee754.read(this, offset, false, 52, 8)
  9519. }
  9520. function checkInt (buf, value, offset, ext, max, min) {
  9521. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  9522. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  9523. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  9524. }
  9525. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  9526. value = +value
  9527. offset = offset | 0
  9528. byteLength = byteLength | 0
  9529. if (!noAssert) {
  9530. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  9531. checkInt(this, value, offset, byteLength, maxBytes, 0)
  9532. }
  9533. var mul = 1
  9534. var i = 0
  9535. this[offset] = value & 0xFF
  9536. while (++i < byteLength && (mul *= 0x100)) {
  9537. this[offset + i] = (value / mul) & 0xFF
  9538. }
  9539. return offset + byteLength
  9540. }
  9541. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  9542. value = +value
  9543. offset = offset | 0
  9544. byteLength = byteLength | 0
  9545. if (!noAssert) {
  9546. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  9547. checkInt(this, value, offset, byteLength, maxBytes, 0)
  9548. }
  9549. var i = byteLength - 1
  9550. var mul = 1
  9551. this[offset + i] = value & 0xFF
  9552. while (--i >= 0 && (mul *= 0x100)) {
  9553. this[offset + i] = (value / mul) & 0xFF
  9554. }
  9555. return offset + byteLength
  9556. }
  9557. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  9558. value = +value
  9559. offset = offset | 0
  9560. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  9561. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  9562. this[offset] = (value & 0xff)
  9563. return offset + 1
  9564. }
  9565. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  9566. if (value < 0) value = 0xffff + value + 1
  9567. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  9568. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  9569. (littleEndian ? i : 1 - i) * 8
  9570. }
  9571. }
  9572. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  9573. value = +value
  9574. offset = offset | 0
  9575. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  9576. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9577. this[offset] = (value & 0xff)
  9578. this[offset + 1] = (value >>> 8)
  9579. } else {
  9580. objectWriteUInt16(this, value, offset, true)
  9581. }
  9582. return offset + 2
  9583. }
  9584. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  9585. value = +value
  9586. offset = offset | 0
  9587. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  9588. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9589. this[offset] = (value >>> 8)
  9590. this[offset + 1] = (value & 0xff)
  9591. } else {
  9592. objectWriteUInt16(this, value, offset, false)
  9593. }
  9594. return offset + 2
  9595. }
  9596. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  9597. if (value < 0) value = 0xffffffff + value + 1
  9598. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  9599. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  9600. }
  9601. }
  9602. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  9603. value = +value
  9604. offset = offset | 0
  9605. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  9606. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9607. this[offset + 3] = (value >>> 24)
  9608. this[offset + 2] = (value >>> 16)
  9609. this[offset + 1] = (value >>> 8)
  9610. this[offset] = (value & 0xff)
  9611. } else {
  9612. objectWriteUInt32(this, value, offset, true)
  9613. }
  9614. return offset + 4
  9615. }
  9616. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  9617. value = +value
  9618. offset = offset | 0
  9619. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  9620. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9621. this[offset] = (value >>> 24)
  9622. this[offset + 1] = (value >>> 16)
  9623. this[offset + 2] = (value >>> 8)
  9624. this[offset + 3] = (value & 0xff)
  9625. } else {
  9626. objectWriteUInt32(this, value, offset, false)
  9627. }
  9628. return offset + 4
  9629. }
  9630. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  9631. value = +value
  9632. offset = offset | 0
  9633. if (!noAssert) {
  9634. var limit = Math.pow(2, 8 * byteLength - 1)
  9635. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  9636. }
  9637. var i = 0
  9638. var mul = 1
  9639. var sub = 0
  9640. this[offset] = value & 0xFF
  9641. while (++i < byteLength && (mul *= 0x100)) {
  9642. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  9643. sub = 1
  9644. }
  9645. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  9646. }
  9647. return offset + byteLength
  9648. }
  9649. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  9650. value = +value
  9651. offset = offset | 0
  9652. if (!noAssert) {
  9653. var limit = Math.pow(2, 8 * byteLength - 1)
  9654. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  9655. }
  9656. var i = byteLength - 1
  9657. var mul = 1
  9658. var sub = 0
  9659. this[offset + i] = value & 0xFF
  9660. while (--i >= 0 && (mul *= 0x100)) {
  9661. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  9662. sub = 1
  9663. }
  9664. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  9665. }
  9666. return offset + byteLength
  9667. }
  9668. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  9669. value = +value
  9670. offset = offset | 0
  9671. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  9672. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  9673. if (value < 0) value = 0xff + value + 1
  9674. this[offset] = (value & 0xff)
  9675. return offset + 1
  9676. }
  9677. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  9678. value = +value
  9679. offset = offset | 0
  9680. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  9681. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9682. this[offset] = (value & 0xff)
  9683. this[offset + 1] = (value >>> 8)
  9684. } else {
  9685. objectWriteUInt16(this, value, offset, true)
  9686. }
  9687. return offset + 2
  9688. }
  9689. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  9690. value = +value
  9691. offset = offset | 0
  9692. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  9693. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9694. this[offset] = (value >>> 8)
  9695. this[offset + 1] = (value & 0xff)
  9696. } else {
  9697. objectWriteUInt16(this, value, offset, false)
  9698. }
  9699. return offset + 2
  9700. }
  9701. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  9702. value = +value
  9703. offset = offset | 0
  9704. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  9705. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9706. this[offset] = (value & 0xff)
  9707. this[offset + 1] = (value >>> 8)
  9708. this[offset + 2] = (value >>> 16)
  9709. this[offset + 3] = (value >>> 24)
  9710. } else {
  9711. objectWriteUInt32(this, value, offset, true)
  9712. }
  9713. return offset + 4
  9714. }
  9715. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  9716. value = +value
  9717. offset = offset | 0
  9718. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  9719. if (value < 0) value = 0xffffffff + value + 1
  9720. if (Buffer.TYPED_ARRAY_SUPPORT) {
  9721. this[offset] = (value >>> 24)
  9722. this[offset + 1] = (value >>> 16)
  9723. this[offset + 2] = (value >>> 8)
  9724. this[offset + 3] = (value & 0xff)
  9725. } else {
  9726. objectWriteUInt32(this, value, offset, false)
  9727. }
  9728. return offset + 4
  9729. }
  9730. function checkIEEE754 (buf, value, offset, ext, max, min) {
  9731. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  9732. if (offset < 0) throw new RangeError('Index out of range')
  9733. }
  9734. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  9735. if (!noAssert) {
  9736. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  9737. }
  9738. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  9739. return offset + 4
  9740. }
  9741. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  9742. return writeFloat(this, value, offset, true, noAssert)
  9743. }
  9744. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  9745. return writeFloat(this, value, offset, false, noAssert)
  9746. }
  9747. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  9748. if (!noAssert) {
  9749. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  9750. }
  9751. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  9752. return offset + 8
  9753. }
  9754. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  9755. return writeDouble(this, value, offset, true, noAssert)
  9756. }
  9757. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  9758. return writeDouble(this, value, offset, false, noAssert)
  9759. }
  9760. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  9761. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  9762. if (!start) start = 0
  9763. if (!end && end !== 0) end = this.length
  9764. if (targetStart >= target.length) targetStart = target.length
  9765. if (!targetStart) targetStart = 0
  9766. if (end > 0 && end < start) end = start
  9767. // Copy 0 bytes; we're done
  9768. if (end === start) return 0
  9769. if (target.length === 0 || this.length === 0) return 0
  9770. // Fatal error conditions
  9771. if (targetStart < 0) {
  9772. throw new RangeError('targetStart out of bounds')
  9773. }
  9774. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  9775. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  9776. // Are we oob?
  9777. if (end > this.length) end = this.length
  9778. if (target.length - targetStart < end - start) {
  9779. end = target.length - targetStart + start
  9780. }
  9781. var len = end - start
  9782. var i
  9783. if (this === target && start < targetStart && targetStart < end) {
  9784. // descending copy from end
  9785. for (i = len - 1; i >= 0; --i) {
  9786. target[i + targetStart] = this[i + start]
  9787. }
  9788. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  9789. // ascending copy from start
  9790. for (i = 0; i < len; ++i) {
  9791. target[i + targetStart] = this[i + start]
  9792. }
  9793. } else {
  9794. Uint8Array.prototype.set.call(
  9795. target,
  9796. this.subarray(start, start + len),
  9797. targetStart
  9798. )
  9799. }
  9800. return len
  9801. }
  9802. // Usage:
  9803. // buffer.fill(number[, offset[, end]])
  9804. // buffer.fill(buffer[, offset[, end]])
  9805. // buffer.fill(string[, offset[, end]][, encoding])
  9806. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  9807. // Handle string cases:
  9808. if (typeof val === 'string') {
  9809. if (typeof start === 'string') {
  9810. encoding = start
  9811. start = 0
  9812. end = this.length
  9813. } else if (typeof end === 'string') {
  9814. encoding = end
  9815. end = this.length
  9816. }
  9817. if (val.length === 1) {
  9818. var code = val.charCodeAt(0)
  9819. if (code < 256) {
  9820. val = code
  9821. }
  9822. }
  9823. if (encoding !== undefined && typeof encoding !== 'string') {
  9824. throw new TypeError('encoding must be a string')
  9825. }
  9826. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  9827. throw new TypeError('Unknown encoding: ' + encoding)
  9828. }
  9829. } else if (typeof val === 'number') {
  9830. val = val & 255
  9831. }
  9832. // Invalid ranges are not set to a default, so can range check early.
  9833. if (start < 0 || this.length < start || this.length < end) {
  9834. throw new RangeError('Out of range index')
  9835. }
  9836. if (end <= start) {
  9837. return this
  9838. }
  9839. start = start >>> 0
  9840. end = end === undefined ? this.length : end >>> 0
  9841. if (!val) val = 0
  9842. var i
  9843. if (typeof val === 'number') {
  9844. for (i = start; i < end; ++i) {
  9845. this[i] = val
  9846. }
  9847. } else {
  9848. var bytes = Buffer.isBuffer(val)
  9849. ? val
  9850. : utf8ToBytes(new Buffer(val, encoding).toString())
  9851. var len = bytes.length
  9852. for (i = 0; i < end - start; ++i) {
  9853. this[i + start] = bytes[i % len]
  9854. }
  9855. }
  9856. return this
  9857. }
  9858. // HELPER FUNCTIONS
  9859. // ================
  9860. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  9861. function base64clean (str) {
  9862. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  9863. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  9864. // Node converts strings with length < 2 to ''
  9865. if (str.length < 2) return ''
  9866. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  9867. while (str.length % 4 !== 0) {
  9868. str = str + '='
  9869. }
  9870. return str
  9871. }
  9872. function stringtrim (str) {
  9873. if (str.trim) return str.trim()
  9874. return str.replace(/^\s+|\s+$/g, '')
  9875. }
  9876. function toHex (n) {
  9877. if (n < 16) return '0' + n.toString(16)
  9878. return n.toString(16)
  9879. }
  9880. function utf8ToBytes (string, units) {
  9881. units = units || Infinity
  9882. var codePoint
  9883. var length = string.length
  9884. var leadSurrogate = null
  9885. var bytes = []
  9886. for (var i = 0; i < length; ++i) {
  9887. codePoint = string.charCodeAt(i)
  9888. // is surrogate component
  9889. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  9890. // last char was a lead
  9891. if (!leadSurrogate) {
  9892. // no lead yet
  9893. if (codePoint > 0xDBFF) {
  9894. // unexpected trail
  9895. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9896. continue
  9897. } else if (i + 1 === length) {
  9898. // unpaired lead
  9899. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9900. continue
  9901. }
  9902. // valid lead
  9903. leadSurrogate = codePoint
  9904. continue
  9905. }
  9906. // 2 leads in a row
  9907. if (codePoint < 0xDC00) {
  9908. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9909. leadSurrogate = codePoint
  9910. continue
  9911. }
  9912. // valid surrogate pair
  9913. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  9914. } else if (leadSurrogate) {
  9915. // valid bmp char, but last char was a lead
  9916. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  9917. }
  9918. leadSurrogate = null
  9919. // encode utf8
  9920. if (codePoint < 0x80) {
  9921. if ((units -= 1) < 0) break
  9922. bytes.push(codePoint)
  9923. } else if (codePoint < 0x800) {
  9924. if ((units -= 2) < 0) break
  9925. bytes.push(
  9926. codePoint >> 0x6 | 0xC0,
  9927. codePoint & 0x3F | 0x80
  9928. )
  9929. } else if (codePoint < 0x10000) {
  9930. if ((units -= 3) < 0) break
  9931. bytes.push(
  9932. codePoint >> 0xC | 0xE0,
  9933. codePoint >> 0x6 & 0x3F | 0x80,
  9934. codePoint & 0x3F | 0x80
  9935. )
  9936. } else if (codePoint < 0x110000) {
  9937. if ((units -= 4) < 0) break
  9938. bytes.push(
  9939. codePoint >> 0x12 | 0xF0,
  9940. codePoint >> 0xC & 0x3F | 0x80,
  9941. codePoint >> 0x6 & 0x3F | 0x80,
  9942. codePoint & 0x3F | 0x80
  9943. )
  9944. } else {
  9945. throw new Error('Invalid code point')
  9946. }
  9947. }
  9948. return bytes
  9949. }
  9950. function asciiToBytes (str) {
  9951. var byteArray = []
  9952. for (var i = 0; i < str.length; ++i) {
  9953. // Node's code seems to be doing this and not & 0x7F..
  9954. byteArray.push(str.charCodeAt(i) & 0xFF)
  9955. }
  9956. return byteArray
  9957. }
  9958. function utf16leToBytes (str, units) {
  9959. var c, hi, lo
  9960. var byteArray = []
  9961. for (var i = 0; i < str.length; ++i) {
  9962. if ((units -= 2) < 0) break
  9963. c = str.charCodeAt(i)
  9964. hi = c >> 8
  9965. lo = c % 256
  9966. byteArray.push(lo)
  9967. byteArray.push(hi)
  9968. }
  9969. return byteArray
  9970. }
  9971. function base64ToBytes (str) {
  9972. return base64.toByteArray(base64clean(str))
  9973. }
  9974. function blitBuffer (src, dst, offset, length) {
  9975. for (var i = 0; i < length; ++i) {
  9976. if ((i + offset >= dst.length) || (i >= src.length)) break
  9977. dst[i + offset] = src[i]
  9978. }
  9979. return i
  9980. }
  9981. function isnan (val) {
  9982. return val !== val // eslint-disable-line no-self-compare
  9983. }
  9984. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9985. },{"base64-js":39,"ieee754":80,"isarray":83}],78:[function(require,module,exports){
  9986. (function (Buffer){
  9987. // Copyright Joyent, Inc. and other Node contributors.
  9988. //
  9989. // Permission is hereby granted, free of charge, to any person obtaining a
  9990. // copy of this software and associated documentation files (the
  9991. // "Software"), to deal in the Software without restriction, including
  9992. // without limitation the rights to use, copy, modify, merge, publish,
  9993. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9994. // persons to whom the Software is furnished to do so, subject to the
  9995. // following conditions:
  9996. //
  9997. // The above copyright notice and this permission notice shall be included
  9998. // in all copies or substantial portions of the Software.
  9999. //
  10000. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10001. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10002. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10003. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10004. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10005. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10006. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10007. // NOTE: These type checking functions intentionally don't use `instanceof`
  10008. // because it is fragile and can be easily faked with `Object.create()`.
  10009. function isArray(arg) {
  10010. if (Array.isArray) {
  10011. return Array.isArray(arg);
  10012. }
  10013. return objectToString(arg) === '[object Array]';
  10014. }
  10015. exports.isArray = isArray;
  10016. function isBoolean(arg) {
  10017. return typeof arg === 'boolean';
  10018. }
  10019. exports.isBoolean = isBoolean;
  10020. function isNull(arg) {
  10021. return arg === null;
  10022. }
  10023. exports.isNull = isNull;
  10024. function isNullOrUndefined(arg) {
  10025. return arg == null;
  10026. }
  10027. exports.isNullOrUndefined = isNullOrUndefined;
  10028. function isNumber(arg) {
  10029. return typeof arg === 'number';
  10030. }
  10031. exports.isNumber = isNumber;
  10032. function isString(arg) {
  10033. return typeof arg === 'string';
  10034. }
  10035. exports.isString = isString;
  10036. function isSymbol(arg) {
  10037. return typeof arg === 'symbol';
  10038. }
  10039. exports.isSymbol = isSymbol;
  10040. function isUndefined(arg) {
  10041. return arg === void 0;
  10042. }
  10043. exports.isUndefined = isUndefined;
  10044. function isRegExp(re) {
  10045. return objectToString(re) === '[object RegExp]';
  10046. }
  10047. exports.isRegExp = isRegExp;
  10048. function isObject(arg) {
  10049. return typeof arg === 'object' && arg !== null;
  10050. }
  10051. exports.isObject = isObject;
  10052. function isDate(d) {
  10053. return objectToString(d) === '[object Date]';
  10054. }
  10055. exports.isDate = isDate;
  10056. function isError(e) {
  10057. return (objectToString(e) === '[object Error]' || e instanceof Error);
  10058. }
  10059. exports.isError = isError;
  10060. function isFunction(arg) {
  10061. return typeof arg === 'function';
  10062. }
  10063. exports.isFunction = isFunction;
  10064. function isPrimitive(arg) {
  10065. return arg === null ||
  10066. typeof arg === 'boolean' ||
  10067. typeof arg === 'number' ||
  10068. typeof arg === 'string' ||
  10069. typeof arg === 'symbol' || // ES6 symbol
  10070. typeof arg === 'undefined';
  10071. }
  10072. exports.isPrimitive = isPrimitive;
  10073. exports.isBuffer = Buffer.isBuffer;
  10074. function objectToString(o) {
  10075. return Object.prototype.toString.call(o);
  10076. }
  10077. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  10078. },{"../../is-buffer/index.js":82}],79:[function(require,module,exports){
  10079. // Copyright Joyent, Inc. and other Node contributors.
  10080. //
  10081. // Permission is hereby granted, free of charge, to any person obtaining a
  10082. // copy of this software and associated documentation files (the
  10083. // "Software"), to deal in the Software without restriction, including
  10084. // without limitation the rights to use, copy, modify, merge, publish,
  10085. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10086. // persons to whom the Software is furnished to do so, subject to the
  10087. // following conditions:
  10088. //
  10089. // The above copyright notice and this permission notice shall be included
  10090. // in all copies or substantial portions of the Software.
  10091. //
  10092. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10093. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10094. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10095. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10096. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10097. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10098. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10099. function EventEmitter() {
  10100. this._events = this._events || {};
  10101. this._maxListeners = this._maxListeners || undefined;
  10102. }
  10103. module.exports = EventEmitter;
  10104. // Backwards-compat with node 0.10.x
  10105. EventEmitter.EventEmitter = EventEmitter;
  10106. EventEmitter.prototype._events = undefined;
  10107. EventEmitter.prototype._maxListeners = undefined;
  10108. // By default EventEmitters will print a warning if more than 10 listeners are
  10109. // added to it. This is a useful default which helps finding memory leaks.
  10110. EventEmitter.defaultMaxListeners = 10;
  10111. // Obviously not all Emitters should be limited to 10. This function allows
  10112. // that to be increased. Set to zero for unlimited.
  10113. EventEmitter.prototype.setMaxListeners = function(n) {
  10114. if (!isNumber(n) || n < 0 || isNaN(n))
  10115. throw TypeError('n must be a positive number');
  10116. this._maxListeners = n;
  10117. return this;
  10118. };
  10119. EventEmitter.prototype.emit = function(type) {
  10120. var er, handler, len, args, i, listeners;
  10121. if (!this._events)
  10122. this._events = {};
  10123. // If there is no 'error' event listener then throw.
  10124. if (type === 'error') {
  10125. if (!this._events.error ||
  10126. (isObject(this._events.error) && !this._events.error.length)) {
  10127. er = arguments[1];
  10128. if (er instanceof Error) {
  10129. throw er; // Unhandled 'error' event
  10130. } else {
  10131. // At least give some kind of context to the user
  10132. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  10133. err.context = er;
  10134. throw err;
  10135. }
  10136. }
  10137. }
  10138. handler = this._events[type];
  10139. if (isUndefined(handler))
  10140. return false;
  10141. if (isFunction(handler)) {
  10142. switch (arguments.length) {
  10143. // fast cases
  10144. case 1:
  10145. handler.call(this);
  10146. break;
  10147. case 2:
  10148. handler.call(this, arguments[1]);
  10149. break;
  10150. case 3:
  10151. handler.call(this, arguments[1], arguments[2]);
  10152. break;
  10153. // slower
  10154. default:
  10155. args = Array.prototype.slice.call(arguments, 1);
  10156. handler.apply(this, args);
  10157. }
  10158. } else if (isObject(handler)) {
  10159. args = Array.prototype.slice.call(arguments, 1);
  10160. listeners = handler.slice();
  10161. len = listeners.length;
  10162. for (i = 0; i < len; i++)
  10163. listeners[i].apply(this, args);
  10164. }
  10165. return true;
  10166. };
  10167. EventEmitter.prototype.addListener = function(type, listener) {
  10168. var m;
  10169. if (!isFunction(listener))
  10170. throw TypeError('listener must be a function');
  10171. if (!this._events)
  10172. this._events = {};
  10173. // To avoid recursion in the case that type === "newListener"! Before
  10174. // adding it to the listeners, first emit "newListener".
  10175. if (this._events.newListener)
  10176. this.emit('newListener', type,
  10177. isFunction(listener.listener) ?
  10178. listener.listener : listener);
  10179. if (!this._events[type])
  10180. // Optimize the case of one listener. Don't need the extra array object.
  10181. this._events[type] = listener;
  10182. else if (isObject(this._events[type]))
  10183. // If we've already got an array, just append.
  10184. this._events[type].push(listener);
  10185. else
  10186. // Adding the second element, need to change to array.
  10187. this._events[type] = [this._events[type], listener];
  10188. // Check for listener leak
  10189. if (isObject(this._events[type]) && !this._events[type].warned) {
  10190. if (!isUndefined(this._maxListeners)) {
  10191. m = this._maxListeners;
  10192. } else {
  10193. m = EventEmitter.defaultMaxListeners;
  10194. }
  10195. if (m && m > 0 && this._events[type].length > m) {
  10196. this._events[type].warned = true;
  10197. console.error('(node) warning: possible EventEmitter memory ' +
  10198. 'leak detected. %d listeners added. ' +
  10199. 'Use emitter.setMaxListeners() to increase limit.',
  10200. this._events[type].length);
  10201. if (typeof console.trace === 'function') {
  10202. // not supported in IE 10
  10203. console.trace();
  10204. }
  10205. }
  10206. }
  10207. return this;
  10208. };
  10209. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  10210. EventEmitter.prototype.once = function(type, listener) {
  10211. if (!isFunction(listener))
  10212. throw TypeError('listener must be a function');
  10213. var fired = false;
  10214. function g() {
  10215. this.removeListener(type, g);
  10216. if (!fired) {
  10217. fired = true;
  10218. listener.apply(this, arguments);
  10219. }
  10220. }
  10221. g.listener = listener;
  10222. this.on(type, g);
  10223. return this;
  10224. };
  10225. // emits a 'removeListener' event iff the listener was removed
  10226. EventEmitter.prototype.removeListener = function(type, listener) {
  10227. var list, position, length, i;
  10228. if (!isFunction(listener))
  10229. throw TypeError('listener must be a function');
  10230. if (!this._events || !this._events[type])
  10231. return this;
  10232. list = this._events[type];
  10233. length = list.length;
  10234. position = -1;
  10235. if (list === listener ||
  10236. (isFunction(list.listener) && list.listener === listener)) {
  10237. delete this._events[type];
  10238. if (this._events.removeListener)
  10239. this.emit('removeListener', type, listener);
  10240. } else if (isObject(list)) {
  10241. for (i = length; i-- > 0;) {
  10242. if (list[i] === listener ||
  10243. (list[i].listener && list[i].listener === listener)) {
  10244. position = i;
  10245. break;
  10246. }
  10247. }
  10248. if (position < 0)
  10249. return this;
  10250. if (list.length === 1) {
  10251. list.length = 0;
  10252. delete this._events[type];
  10253. } else {
  10254. list.splice(position, 1);
  10255. }
  10256. if (this._events.removeListener)
  10257. this.emit('removeListener', type, listener);
  10258. }
  10259. return this;
  10260. };
  10261. EventEmitter.prototype.removeAllListeners = function(type) {
  10262. var key, listeners;
  10263. if (!this._events)
  10264. return this;
  10265. // not listening for removeListener, no need to emit
  10266. if (!this._events.removeListener) {
  10267. if (arguments.length === 0)
  10268. this._events = {};
  10269. else if (this._events[type])
  10270. delete this._events[type];
  10271. return this;
  10272. }
  10273. // emit removeListener for all listeners on all events
  10274. if (arguments.length === 0) {
  10275. for (key in this._events) {
  10276. if (key === 'removeListener') continue;
  10277. this.removeAllListeners(key);
  10278. }
  10279. this.removeAllListeners('removeListener');
  10280. this._events = {};
  10281. return this;
  10282. }
  10283. listeners = this._events[type];
  10284. if (isFunction(listeners)) {
  10285. this.removeListener(type, listeners);
  10286. } else if (listeners) {
  10287. // LIFO order
  10288. while (listeners.length)
  10289. this.removeListener(type, listeners[listeners.length - 1]);
  10290. }
  10291. delete this._events[type];
  10292. return this;
  10293. };
  10294. EventEmitter.prototype.listeners = function(type) {
  10295. var ret;
  10296. if (!this._events || !this._events[type])
  10297. ret = [];
  10298. else if (isFunction(this._events[type]))
  10299. ret = [this._events[type]];
  10300. else
  10301. ret = this._events[type].slice();
  10302. return ret;
  10303. };
  10304. EventEmitter.prototype.listenerCount = function(type) {
  10305. if (this._events) {
  10306. var evlistener = this._events[type];
  10307. if (isFunction(evlistener))
  10308. return 1;
  10309. else if (evlistener)
  10310. return evlistener.length;
  10311. }
  10312. return 0;
  10313. };
  10314. EventEmitter.listenerCount = function(emitter, type) {
  10315. return emitter.listenerCount(type);
  10316. };
  10317. function isFunction(arg) {
  10318. return typeof arg === 'function';
  10319. }
  10320. function isNumber(arg) {
  10321. return typeof arg === 'number';
  10322. }
  10323. function isObject(arg) {
  10324. return typeof arg === 'object' && arg !== null;
  10325. }
  10326. function isUndefined(arg) {
  10327. return arg === void 0;
  10328. }
  10329. },{}],80:[function(require,module,exports){
  10330. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  10331. var e, m
  10332. var eLen = nBytes * 8 - mLen - 1
  10333. var eMax = (1 << eLen) - 1
  10334. var eBias = eMax >> 1
  10335. var nBits = -7
  10336. var i = isLE ? (nBytes - 1) : 0
  10337. var d = isLE ? -1 : 1
  10338. var s = buffer[offset + i]
  10339. i += d
  10340. e = s & ((1 << (-nBits)) - 1)
  10341. s >>= (-nBits)
  10342. nBits += eLen
  10343. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  10344. m = e & ((1 << (-nBits)) - 1)
  10345. e >>= (-nBits)
  10346. nBits += mLen
  10347. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  10348. if (e === 0) {
  10349. e = 1 - eBias
  10350. } else if (e === eMax) {
  10351. return m ? NaN : ((s ? -1 : 1) * Infinity)
  10352. } else {
  10353. m = m + Math.pow(2, mLen)
  10354. e = e - eBias
  10355. }
  10356. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  10357. }
  10358. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  10359. var e, m, c
  10360. var eLen = nBytes * 8 - mLen - 1
  10361. var eMax = (1 << eLen) - 1
  10362. var eBias = eMax >> 1
  10363. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  10364. var i = isLE ? 0 : (nBytes - 1)
  10365. var d = isLE ? 1 : -1
  10366. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  10367. value = Math.abs(value)
  10368. if (isNaN(value) || value === Infinity) {
  10369. m = isNaN(value) ? 1 : 0
  10370. e = eMax
  10371. } else {
  10372. e = Math.floor(Math.log(value) / Math.LN2)
  10373. if (value * (c = Math.pow(2, -e)) < 1) {
  10374. e--
  10375. c *= 2
  10376. }
  10377. if (e + eBias >= 1) {
  10378. value += rt / c
  10379. } else {
  10380. value += rt * Math.pow(2, 1 - eBias)
  10381. }
  10382. if (value * c >= 2) {
  10383. e++
  10384. c /= 2
  10385. }
  10386. if (e + eBias >= eMax) {
  10387. m = 0
  10388. e = eMax
  10389. } else if (e + eBias >= 1) {
  10390. m = (value * c - 1) * Math.pow(2, mLen)
  10391. e = e + eBias
  10392. } else {
  10393. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  10394. e = 0
  10395. }
  10396. }
  10397. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  10398. e = (e << mLen) | m
  10399. eLen += mLen
  10400. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  10401. buffer[offset + i - d] |= s * 128
  10402. }
  10403. },{}],81:[function(require,module,exports){
  10404. if (typeof Object.create === 'function') {
  10405. // implementation from standard node.js 'util' module
  10406. module.exports = function inherits(ctor, superCtor) {
  10407. ctor.super_ = superCtor
  10408. ctor.prototype = Object.create(superCtor.prototype, {
  10409. constructor: {
  10410. value: ctor,
  10411. enumerable: false,
  10412. writable: true,
  10413. configurable: true
  10414. }
  10415. });
  10416. };
  10417. } else {
  10418. // old school shim for old browsers
  10419. module.exports = function inherits(ctor, superCtor) {
  10420. ctor.super_ = superCtor
  10421. var TempCtor = function () {}
  10422. TempCtor.prototype = superCtor.prototype
  10423. ctor.prototype = new TempCtor()
  10424. ctor.prototype.constructor = ctor
  10425. }
  10426. }
  10427. },{}],82:[function(require,module,exports){
  10428. /*!
  10429. * Determine if an object is a Buffer
  10430. *
  10431. * @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
  10432. * @license MIT
  10433. */
  10434. // The _isBuffer check is for Safari 5-7 support, because it's missing
  10435. // Object.prototype.constructor. Remove this eventually
  10436. module.exports = function (obj) {
  10437. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  10438. }
  10439. function isBuffer (obj) {
  10440. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  10441. }
  10442. // For Node v0.10 support. Remove this eventually.
  10443. function isSlowBuffer (obj) {
  10444. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  10445. }
  10446. },{}],83:[function(require,module,exports){
  10447. var toString = {}.toString;
  10448. module.exports = Array.isArray || function (arr) {
  10449. return toString.call(arr) == '[object Array]';
  10450. };
  10451. },{}],84:[function(require,module,exports){
  10452. 'use strict';
  10453. // private property
  10454. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  10455. // public method for encoding
  10456. exports.encode = function(input, utf8) {
  10457. var output = "";
  10458. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  10459. var i = 0;
  10460. while (i < input.length) {
  10461. chr1 = input.charCodeAt(i++);
  10462. chr2 = input.charCodeAt(i++);
  10463. chr3 = input.charCodeAt(i++);
  10464. enc1 = chr1 >> 2;
  10465. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  10466. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  10467. enc4 = chr3 & 63;
  10468. if (isNaN(chr2)) {
  10469. enc3 = enc4 = 64;
  10470. }
  10471. else if (isNaN(chr3)) {
  10472. enc4 = 64;
  10473. }
  10474. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  10475. }
  10476. return output;
  10477. };
  10478. // public method for decoding
  10479. exports.decode = function(input, utf8) {
  10480. var output = "";
  10481. var chr1, chr2, chr3;
  10482. var enc1, enc2, enc3, enc4;
  10483. var i = 0;
  10484. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  10485. while (i < input.length) {
  10486. enc1 = _keyStr.indexOf(input.charAt(i++));
  10487. enc2 = _keyStr.indexOf(input.charAt(i++));
  10488. enc3 = _keyStr.indexOf(input.charAt(i++));
  10489. enc4 = _keyStr.indexOf(input.charAt(i++));
  10490. chr1 = (enc1 << 2) | (enc2 >> 4);
  10491. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  10492. chr3 = ((enc3 & 3) << 6) | enc4;
  10493. output = output + String.fromCharCode(chr1);
  10494. if (enc3 != 64) {
  10495. output = output + String.fromCharCode(chr2);
  10496. }
  10497. if (enc4 != 64) {
  10498. output = output + String.fromCharCode(chr3);
  10499. }
  10500. }
  10501. return output;
  10502. };
  10503. },{}],85:[function(require,module,exports){
  10504. 'use strict';
  10505. function CompressedObject() {
  10506. this.compressedSize = 0;
  10507. this.uncompressedSize = 0;
  10508. this.crc32 = 0;
  10509. this.compressionMethod = null;
  10510. this.compressedContent = null;
  10511. }
  10512. CompressedObject.prototype = {
  10513. /**
  10514. * Return the decompressed content in an unspecified format.
  10515. * The format will depend on the decompressor.
  10516. * @return {Object} the decompressed content.
  10517. */
  10518. getContent: function() {
  10519. return null; // see implementation
  10520. },
  10521. /**
  10522. * Return the compressed content in an unspecified format.
  10523. * The format will depend on the compressed conten source.
  10524. * @return {Object} the compressed content.
  10525. */
  10526. getCompressedContent: function() {
  10527. return null; // see implementation
  10528. }
  10529. };
  10530. module.exports = CompressedObject;
  10531. },{}],86:[function(require,module,exports){
  10532. 'use strict';
  10533. exports.STORE = {
  10534. magic: "\x00\x00",
  10535. compress: function(content, compressionOptions) {
  10536. return content; // no compression
  10537. },
  10538. uncompress: function(content) {
  10539. return content; // no compression
  10540. },
  10541. compressInputType: null,
  10542. uncompressInputType: null
  10543. };
  10544. exports.DEFLATE = require('./flate');
  10545. },{"./flate":91}],87:[function(require,module,exports){
  10546. 'use strict';
  10547. var utils = require('./utils');
  10548. var table = [
  10549. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  10550. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  10551. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  10552. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  10553. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  10554. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  10555. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  10556. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  10557. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  10558. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  10559. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  10560. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  10561. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  10562. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  10563. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  10564. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  10565. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  10566. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  10567. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  10568. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  10569. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  10570. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  10571. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  10572. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  10573. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  10574. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  10575. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  10576. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  10577. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  10578. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  10579. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  10580. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  10581. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  10582. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  10583. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  10584. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  10585. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  10586. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  10587. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  10588. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  10589. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  10590. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  10591. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  10592. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  10593. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  10594. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  10595. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  10596. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  10597. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  10598. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  10599. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  10600. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  10601. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  10602. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  10603. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  10604. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  10605. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  10606. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  10607. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  10608. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  10609. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  10610. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  10611. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  10612. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  10613. ];
  10614. /**
  10615. *
  10616. * Javascript crc32
  10617. * http://www.webtoolkit.info/
  10618. *
  10619. */
  10620. module.exports = function crc32(input, crc) {
  10621. if (typeof input === "undefined" || !input.length) {
  10622. return 0;
  10623. }
  10624. var isArray = utils.getTypeOf(input) !== "string";
  10625. if (typeof(crc) == "undefined") {
  10626. crc = 0;
  10627. }
  10628. var x = 0;
  10629. var y = 0;
  10630. var b = 0;
  10631. crc = crc ^ (-1);
  10632. for (var i = 0, iTop = input.length; i < iTop; i++) {
  10633. b = isArray ? input[i] : input.charCodeAt(i);
  10634. y = (crc ^ b) & 0xFF;
  10635. x = table[y];
  10636. crc = (crc >>> 8) ^ x;
  10637. }
  10638. return crc ^ (-1);
  10639. };
  10640. // vim: set shiftwidth=4 softtabstop=4:
  10641. },{"./utils":104}],88:[function(require,module,exports){
  10642. 'use strict';
  10643. var utils = require('./utils');
  10644. function DataReader(data) {
  10645. this.data = null; // type : see implementation
  10646. this.length = 0;
  10647. this.index = 0;
  10648. }
  10649. DataReader.prototype = {
  10650. /**
  10651. * Check that the offset will not go too far.
  10652. * @param {string} offset the additional offset to check.
  10653. * @throws {Error} an Error if the offset is out of bounds.
  10654. */
  10655. checkOffset: function(offset) {
  10656. this.checkIndex(this.index + offset);
  10657. },
  10658. /**
  10659. * Check that the specifed index will not be too far.
  10660. * @param {string} newIndex the index to check.
  10661. * @throws {Error} an Error if the index is out of bounds.
  10662. */
  10663. checkIndex: function(newIndex) {
  10664. if (this.length < newIndex || newIndex < 0) {
  10665. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  10666. }
  10667. },
  10668. /**
  10669. * Change the index.
  10670. * @param {number} newIndex The new index.
  10671. * @throws {Error} if the new index is out of the data.
  10672. */
  10673. setIndex: function(newIndex) {
  10674. this.checkIndex(newIndex);
  10675. this.index = newIndex;
  10676. },
  10677. /**
  10678. * Skip the next n bytes.
  10679. * @param {number} n the number of bytes to skip.
  10680. * @throws {Error} if the new index is out of the data.
  10681. */
  10682. skip: function(n) {
  10683. this.setIndex(this.index + n);
  10684. },
  10685. /**
  10686. * Get the byte at the specified index.
  10687. * @param {number} i the index to use.
  10688. * @return {number} a byte.
  10689. */
  10690. byteAt: function(i) {
  10691. // see implementations
  10692. },
  10693. /**
  10694. * Get the next number with a given byte size.
  10695. * @param {number} size the number of bytes to read.
  10696. * @return {number} the corresponding number.
  10697. */
  10698. readInt: function(size) {
  10699. var result = 0,
  10700. i;
  10701. this.checkOffset(size);
  10702. for (i = this.index + size - 1; i >= this.index; i--) {
  10703. result = (result << 8) + this.byteAt(i);
  10704. }
  10705. this.index += size;
  10706. return result;
  10707. },
  10708. /**
  10709. * Get the next string with a given byte size.
  10710. * @param {number} size the number of bytes to read.
  10711. * @return {string} the corresponding string.
  10712. */
  10713. readString: function(size) {
  10714. return utils.transformTo("string", this.readData(size));
  10715. },
  10716. /**
  10717. * Get raw data without conversion, <size> bytes.
  10718. * @param {number} size the number of bytes to read.
  10719. * @return {Object} the raw data, implementation specific.
  10720. */
  10721. readData: function(size) {
  10722. // see implementations
  10723. },
  10724. /**
  10725. * Find the last occurence of a zip signature (4 bytes).
  10726. * @param {string} sig the signature to find.
  10727. * @return {number} the index of the last occurence, -1 if not found.
  10728. */
  10729. lastIndexOfSignature: function(sig) {
  10730. // see implementations
  10731. },
  10732. /**
  10733. * Get the next date.
  10734. * @return {Date} the date.
  10735. */
  10736. readDate: function() {
  10737. var dostime = this.readInt(4);
  10738. return new Date(
  10739. ((dostime >> 25) & 0x7f) + 1980, // year
  10740. ((dostime >> 21) & 0x0f) - 1, // month
  10741. (dostime >> 16) & 0x1f, // day
  10742. (dostime >> 11) & 0x1f, // hour
  10743. (dostime >> 5) & 0x3f, // minute
  10744. (dostime & 0x1f) << 1); // second
  10745. }
  10746. };
  10747. module.exports = DataReader;
  10748. },{"./utils":104}],89:[function(require,module,exports){
  10749. 'use strict';
  10750. exports.base64 = false;
  10751. exports.binary = false;
  10752. exports.dir = false;
  10753. exports.createFolders = false;
  10754. exports.date = null;
  10755. exports.compression = null;
  10756. exports.compressionOptions = null;
  10757. exports.comment = null;
  10758. exports.unixPermissions = null;
  10759. exports.dosPermissions = null;
  10760. },{}],90:[function(require,module,exports){
  10761. 'use strict';
  10762. var utils = require('./utils');
  10763. /**
  10764. * @deprecated
  10765. * This function will be removed in a future version without replacement.
  10766. */
  10767. exports.string2binary = function(str) {
  10768. return utils.string2binary(str);
  10769. };
  10770. /**
  10771. * @deprecated
  10772. * This function will be removed in a future version without replacement.
  10773. */
  10774. exports.string2Uint8Array = function(str) {
  10775. return utils.transformTo("uint8array", str);
  10776. };
  10777. /**
  10778. * @deprecated
  10779. * This function will be removed in a future version without replacement.
  10780. */
  10781. exports.uint8Array2String = function(array) {
  10782. return utils.transformTo("string", array);
  10783. };
  10784. /**
  10785. * @deprecated
  10786. * This function will be removed in a future version without replacement.
  10787. */
  10788. exports.string2Blob = function(str) {
  10789. var buffer = utils.transformTo("arraybuffer", str);
  10790. return utils.arrayBuffer2Blob(buffer);
  10791. };
  10792. /**
  10793. * @deprecated
  10794. * This function will be removed in a future version without replacement.
  10795. */
  10796. exports.arrayBuffer2Blob = function(buffer) {
  10797. return utils.arrayBuffer2Blob(buffer);
  10798. };
  10799. /**
  10800. * @deprecated
  10801. * This function will be removed in a future version without replacement.
  10802. */
  10803. exports.transformTo = function(outputType, input) {
  10804. return utils.transformTo(outputType, input);
  10805. };
  10806. /**
  10807. * @deprecated
  10808. * This function will be removed in a future version without replacement.
  10809. */
  10810. exports.getTypeOf = function(input) {
  10811. return utils.getTypeOf(input);
  10812. };
  10813. /**
  10814. * @deprecated
  10815. * This function will be removed in a future version without replacement.
  10816. */
  10817. exports.checkSupport = function(type) {
  10818. return utils.checkSupport(type);
  10819. };
  10820. /**
  10821. * @deprecated
  10822. * This value will be removed in a future version without replacement.
  10823. */
  10824. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  10825. /**
  10826. * @deprecated
  10827. * This value will be removed in a future version without replacement.
  10828. */
  10829. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  10830. /**
  10831. * @deprecated
  10832. * This function will be removed in a future version without replacement.
  10833. */
  10834. exports.pretty = function(str) {
  10835. return utils.pretty(str);
  10836. };
  10837. /**
  10838. * @deprecated
  10839. * This function will be removed in a future version without replacement.
  10840. */
  10841. exports.findCompression = function(compressionMethod) {
  10842. return utils.findCompression(compressionMethod);
  10843. };
  10844. /**
  10845. * @deprecated
  10846. * This function will be removed in a future version without replacement.
  10847. */
  10848. exports.isRegExp = function (object) {
  10849. return utils.isRegExp(object);
  10850. };
  10851. },{"./utils":104}],91:[function(require,module,exports){
  10852. 'use strict';
  10853. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  10854. var pako = require("pako");
  10855. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  10856. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  10857. exports.magic = "\x08\x00";
  10858. exports.compress = function(input, compressionOptions) {
  10859. return pako.deflateRaw(input, {
  10860. level : compressionOptions.level || -1 // default compression
  10861. });
  10862. };
  10863. exports.uncompress = function(input) {
  10864. return pako.inflateRaw(input);
  10865. };
  10866. },{"pako":120}],92:[function(require,module,exports){
  10867. 'use strict';
  10868. var base64 = require('./base64');
  10869. /**
  10870. Usage:
  10871. zip = new JSZip();
  10872. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  10873. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  10874. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  10875. zip.remove("tempfile");
  10876. base64zip = zip.generate();
  10877. **/
  10878. /**
  10879. * Representation a of zip file in js
  10880. * @constructor
  10881. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  10882. * @param {Object=} options the options for creating this objects (optional).
  10883. */
  10884. function JSZip(data, options) {
  10885. // if this constructor is used without `new`, it adds `new` before itself:
  10886. if(!(this instanceof JSZip)) return new JSZip(data, options);
  10887. // object containing the files :
  10888. // {
  10889. // "folder/" : {...},
  10890. // "folder/data.txt" : {...}
  10891. // }
  10892. this.files = {};
  10893. this.comment = null;
  10894. // Where we are in the hierarchy
  10895. this.root = "";
  10896. if (data) {
  10897. this.load(data, options);
  10898. }
  10899. this.clone = function() {
  10900. var newObj = new JSZip();
  10901. for (var i in this) {
  10902. if (typeof this[i] !== "function") {
  10903. newObj[i] = this[i];
  10904. }
  10905. }
  10906. return newObj;
  10907. };
  10908. }
  10909. JSZip.prototype = require('./object');
  10910. JSZip.prototype.load = require('./load');
  10911. JSZip.support = require('./support');
  10912. JSZip.defaults = require('./defaults');
  10913. /**
  10914. * @deprecated
  10915. * This namespace will be removed in a future version without replacement.
  10916. */
  10917. JSZip.utils = require('./deprecatedPublicUtils');
  10918. JSZip.base64 = {
  10919. /**
  10920. * @deprecated
  10921. * This method will be removed in a future version without replacement.
  10922. */
  10923. encode : function(input) {
  10924. return base64.encode(input);
  10925. },
  10926. /**
  10927. * @deprecated
  10928. * This method will be removed in a future version without replacement.
  10929. */
  10930. decode : function(input) {
  10931. return base64.decode(input);
  10932. }
  10933. };
  10934. JSZip.compressions = require('./compressions');
  10935. module.exports = JSZip;
  10936. },{"./base64":84,"./compressions":86,"./defaults":89,"./deprecatedPublicUtils":90,"./load":93,"./object":96,"./support":100}],93:[function(require,module,exports){
  10937. 'use strict';
  10938. var base64 = require('./base64');
  10939. var ZipEntries = require('./zipEntries');
  10940. module.exports = function(data, options) {
  10941. var files, zipEntries, i, input;
  10942. options = options || {};
  10943. if (options.base64) {
  10944. data = base64.decode(data);
  10945. }
  10946. zipEntries = new ZipEntries(data, options);
  10947. files = zipEntries.files;
  10948. for (i = 0; i < files.length; i++) {
  10949. input = files[i];
  10950. this.file(input.fileName, input.decompressed, {
  10951. binary: true,
  10952. optimizedBinaryString: true,
  10953. date: input.date,
  10954. dir: input.dir,
  10955. comment : input.fileComment.length ? input.fileComment : null,
  10956. unixPermissions : input.unixPermissions,
  10957. dosPermissions : input.dosPermissions,
  10958. createFolders: options.createFolders
  10959. });
  10960. }
  10961. if (zipEntries.zipComment.length) {
  10962. this.comment = zipEntries.zipComment;
  10963. }
  10964. return this;
  10965. };
  10966. },{"./base64":84,"./zipEntries":105}],94:[function(require,module,exports){
  10967. (function (Buffer){
  10968. 'use strict';
  10969. module.exports = function(data, encoding){
  10970. return new Buffer(data, encoding);
  10971. };
  10972. module.exports.test = function(b){
  10973. return Buffer.isBuffer(b);
  10974. };
  10975. }).call(this,require("buffer").Buffer)
  10976. },{"buffer":77}],95:[function(require,module,exports){
  10977. 'use strict';
  10978. var Uint8ArrayReader = require('./uint8ArrayReader');
  10979. function NodeBufferReader(data) {
  10980. this.data = data;
  10981. this.length = this.data.length;
  10982. this.index = 0;
  10983. }
  10984. NodeBufferReader.prototype = new Uint8ArrayReader();
  10985. /**
  10986. * @see DataReader.readData
  10987. */
  10988. NodeBufferReader.prototype.readData = function(size) {
  10989. this.checkOffset(size);
  10990. var result = this.data.slice(this.index, this.index + size);
  10991. this.index += size;
  10992. return result;
  10993. };
  10994. module.exports = NodeBufferReader;
  10995. },{"./uint8ArrayReader":101}],96:[function(require,module,exports){
  10996. 'use strict';
  10997. var support = require('./support');
  10998. var utils = require('./utils');
  10999. var crc32 = require('./crc32');
  11000. var signature = require('./signature');
  11001. var defaults = require('./defaults');
  11002. var base64 = require('./base64');
  11003. var compressions = require('./compressions');
  11004. var CompressedObject = require('./compressedObject');
  11005. var nodeBuffer = require('./nodeBuffer');
  11006. var utf8 = require('./utf8');
  11007. var StringWriter = require('./stringWriter');
  11008. var Uint8ArrayWriter = require('./uint8ArrayWriter');
  11009. /**
  11010. * Returns the raw data of a ZipObject, decompress the content if necessary.
  11011. * @param {ZipObject} file the file to use.
  11012. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  11013. */
  11014. var getRawData = function(file) {
  11015. if (file._data instanceof CompressedObject) {
  11016. file._data = file._data.getContent();
  11017. file.options.binary = true;
  11018. file.options.base64 = false;
  11019. if (utils.getTypeOf(file._data) === "uint8array") {
  11020. var copy = file._data;
  11021. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  11022. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  11023. file._data = new Uint8Array(copy.length);
  11024. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  11025. if (copy.length !== 0) {
  11026. file._data.set(copy, 0);
  11027. }
  11028. }
  11029. }
  11030. return file._data;
  11031. };
  11032. /**
  11033. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  11034. * @param {ZipObject} file the file to use.
  11035. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  11036. */
  11037. var getBinaryData = function(file) {
  11038. var result = getRawData(file),
  11039. type = utils.getTypeOf(result);
  11040. if (type === "string") {
  11041. if (!file.options.binary) {
  11042. // unicode text !
  11043. // unicode string => binary string is a painful process, check if we can avoid it.
  11044. if (support.nodebuffer) {
  11045. return nodeBuffer(result, "utf-8");
  11046. }
  11047. }
  11048. return file.asBinary();
  11049. }
  11050. return result;
  11051. };
  11052. /**
  11053. * Transform this._data into a string.
  11054. * @param {function} filter a function String -> String, applied if not null on the result.
  11055. * @return {String} the string representing this._data.
  11056. */
  11057. var dataToString = function(asUTF8) {
  11058. var result = getRawData(this);
  11059. if (result === null || typeof result === "undefined") {
  11060. return "";
  11061. }
  11062. // if the data is a base64 string, we decode it before checking the encoding !
  11063. if (this.options.base64) {
  11064. result = base64.decode(result);
  11065. }
  11066. if (asUTF8 && this.options.binary) {
  11067. // JSZip.prototype.utf8decode supports arrays as input
  11068. // skip to array => string step, utf8decode will do it.
  11069. result = out.utf8decode(result);
  11070. }
  11071. else {
  11072. // no utf8 transformation, do the array => string step.
  11073. result = utils.transformTo("string", result);
  11074. }
  11075. if (!asUTF8 && !this.options.binary) {
  11076. result = utils.transformTo("string", out.utf8encode(result));
  11077. }
  11078. return result;
  11079. };
  11080. /**
  11081. * A simple object representing a file in the zip file.
  11082. * @constructor
  11083. * @param {string} name the name of the file
  11084. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  11085. * @param {Object} options the options of the file
  11086. */
  11087. var ZipObject = function(name, data, options) {
  11088. this.name = name;
  11089. this.dir = options.dir;
  11090. this.date = options.date;
  11091. this.comment = options.comment;
  11092. this.unixPermissions = options.unixPermissions;
  11093. this.dosPermissions = options.dosPermissions;
  11094. this._data = data;
  11095. this.options = options;
  11096. /*
  11097. * This object contains initial values for dir and date.
  11098. * With them, we can check if the user changed the deprecated metadata in
  11099. * `ZipObject#options` or not.
  11100. */
  11101. this._initialMetadata = {
  11102. dir : options.dir,
  11103. date : options.date
  11104. };
  11105. };
  11106. ZipObject.prototype = {
  11107. /**
  11108. * Return the content as UTF8 string.
  11109. * @return {string} the UTF8 string.
  11110. */
  11111. asText: function() {
  11112. return dataToString.call(this, true);
  11113. },
  11114. /**
  11115. * Returns the binary content.
  11116. * @return {string} the content as binary.
  11117. */
  11118. asBinary: function() {
  11119. return dataToString.call(this, false);
  11120. },
  11121. /**
  11122. * Returns the content as a nodejs Buffer.
  11123. * @return {Buffer} the content as a Buffer.
  11124. */
  11125. asNodeBuffer: function() {
  11126. var result = getBinaryData(this);
  11127. return utils.transformTo("nodebuffer", result);
  11128. },
  11129. /**
  11130. * Returns the content as an Uint8Array.
  11131. * @return {Uint8Array} the content as an Uint8Array.
  11132. */
  11133. asUint8Array: function() {
  11134. var result = getBinaryData(this);
  11135. return utils.transformTo("uint8array", result);
  11136. },
  11137. /**
  11138. * Returns the content as an ArrayBuffer.
  11139. * @return {ArrayBuffer} the content as an ArrayBufer.
  11140. */
  11141. asArrayBuffer: function() {
  11142. return this.asUint8Array().buffer;
  11143. }
  11144. };
  11145. /**
  11146. * Transform an integer into a string in hexadecimal.
  11147. * @private
  11148. * @param {number} dec the number to convert.
  11149. * @param {number} bytes the number of bytes to generate.
  11150. * @returns {string} the result.
  11151. */
  11152. var decToHex = function(dec, bytes) {
  11153. var hex = "",
  11154. i;
  11155. for (i = 0; i < bytes; i++) {
  11156. hex += String.fromCharCode(dec & 0xff);
  11157. dec = dec >>> 8;
  11158. }
  11159. return hex;
  11160. };
  11161. /**
  11162. * Merge the objects passed as parameters into a new one.
  11163. * @private
  11164. * @param {...Object} var_args All objects to merge.
  11165. * @return {Object} a new object with the data of the others.
  11166. */
  11167. var extend = function() {
  11168. var result = {}, i, attr;
  11169. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  11170. for (attr in arguments[i]) {
  11171. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  11172. result[attr] = arguments[i][attr];
  11173. }
  11174. }
  11175. }
  11176. return result;
  11177. };
  11178. /**
  11179. * Transforms the (incomplete) options from the user into the complete
  11180. * set of options to create a file.
  11181. * @private
  11182. * @param {Object} o the options from the user.
  11183. * @return {Object} the complete set of options.
  11184. */
  11185. var prepareFileAttrs = function(o) {
  11186. o = o || {};
  11187. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  11188. o.binary = true;
  11189. }
  11190. o = extend(o, defaults);
  11191. o.date = o.date || new Date();
  11192. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  11193. return o;
  11194. };
  11195. /**
  11196. * Add a file in the current folder.
  11197. * @private
  11198. * @param {string} name the name of the file
  11199. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  11200. * @param {Object} o the options of the file
  11201. * @return {Object} the new file.
  11202. */
  11203. var fileAdd = function(name, data, o) {
  11204. // be sure sub folders exist
  11205. var dataType = utils.getTypeOf(data),
  11206. parent;
  11207. o = prepareFileAttrs(o);
  11208. if (typeof o.unixPermissions === "string") {
  11209. o.unixPermissions = parseInt(o.unixPermissions, 8);
  11210. }
  11211. // UNX_IFDIR 0040000 see zipinfo.c
  11212. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  11213. o.dir = true;
  11214. }
  11215. // Bit 4 Directory
  11216. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  11217. o.dir = true;
  11218. }
  11219. if (o.dir) {
  11220. name = forceTrailingSlash(name);
  11221. }
  11222. if (o.createFolders && (parent = parentFolder(name))) {
  11223. folderAdd.call(this, parent, true);
  11224. }
  11225. if (o.dir || data === null || typeof data === "undefined") {
  11226. o.base64 = false;
  11227. o.binary = false;
  11228. data = null;
  11229. dataType = null;
  11230. }
  11231. else if (dataType === "string") {
  11232. if (o.binary && !o.base64) {
  11233. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  11234. if (o.optimizedBinaryString !== true) {
  11235. // this is a string, not in a base64 format.
  11236. // Be sure that this is a correct "binary string"
  11237. data = utils.string2binary(data);
  11238. }
  11239. }
  11240. }
  11241. else { // arraybuffer, uint8array, ...
  11242. o.base64 = false;
  11243. o.binary = true;
  11244. if (!dataType && !(data instanceof CompressedObject)) {
  11245. throw new Error("The data of '" + name + "' is in an unsupported format !");
  11246. }
  11247. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  11248. if (dataType === "arraybuffer") {
  11249. data = utils.transformTo("uint8array", data);
  11250. }
  11251. }
  11252. var object = new ZipObject(name, data, o);
  11253. this.files[name] = object;
  11254. return object;
  11255. };
  11256. /**
  11257. * Find the parent folder of the path.
  11258. * @private
  11259. * @param {string} path the path to use
  11260. * @return {string} the parent folder, or ""
  11261. */
  11262. var parentFolder = function (path) {
  11263. if (path.slice(-1) == '/') {
  11264. path = path.substring(0, path.length - 1);
  11265. }
  11266. var lastSlash = path.lastIndexOf('/');
  11267. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  11268. };
  11269. /**
  11270. * Returns the path with a slash at the end.
  11271. * @private
  11272. * @param {String} path the path to check.
  11273. * @return {String} the path with a trailing slash.
  11274. */
  11275. var forceTrailingSlash = function(path) {
  11276. // Check the name ends with a /
  11277. if (path.slice(-1) != "/") {
  11278. path += "/"; // IE doesn't like substr(-1)
  11279. }
  11280. return path;
  11281. };
  11282. /**
  11283. * Add a (sub) folder in the current folder.
  11284. * @private
  11285. * @param {string} name the folder's name
  11286. * @param {boolean=} [createFolders] If true, automatically create sub
  11287. * folders. Defaults to false.
  11288. * @return {Object} the new folder.
  11289. */
  11290. var folderAdd = function(name, createFolders) {
  11291. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  11292. name = forceTrailingSlash(name);
  11293. // Does this folder already exist?
  11294. if (!this.files[name]) {
  11295. fileAdd.call(this, name, null, {
  11296. dir: true,
  11297. createFolders: createFolders
  11298. });
  11299. }
  11300. return this.files[name];
  11301. };
  11302. /**
  11303. * Generate a JSZip.CompressedObject for a given zipOject.
  11304. * @param {ZipObject} file the object to read.
  11305. * @param {JSZip.compression} compression the compression to use.
  11306. * @param {Object} compressionOptions the options to use when compressing.
  11307. * @return {JSZip.CompressedObject} the compressed result.
  11308. */
  11309. var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
  11310. var result = new CompressedObject(),
  11311. content;
  11312. // the data has not been decompressed, we might reuse things !
  11313. if (file._data instanceof CompressedObject) {
  11314. result.uncompressedSize = file._data.uncompressedSize;
  11315. result.crc32 = file._data.crc32;
  11316. if (result.uncompressedSize === 0 || file.dir) {
  11317. compression = compressions['STORE'];
  11318. result.compressedContent = "";
  11319. result.crc32 = 0;
  11320. }
  11321. else if (file._data.compressionMethod === compression.magic) {
  11322. result.compressedContent = file._data.getCompressedContent();
  11323. }
  11324. else {
  11325. content = file._data.getContent();
  11326. // need to decompress / recompress
  11327. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  11328. }
  11329. }
  11330. else {
  11331. // have uncompressed data
  11332. content = getBinaryData(file);
  11333. if (!content || content.length === 0 || file.dir) {
  11334. compression = compressions['STORE'];
  11335. content = "";
  11336. }
  11337. result.uncompressedSize = content.length;
  11338. result.crc32 = crc32(content);
  11339. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
  11340. }
  11341. result.compressedSize = result.compressedContent.length;
  11342. result.compressionMethod = compression.magic;
  11343. return result;
  11344. };
  11345. /**
  11346. * Generate the UNIX part of the external file attributes.
  11347. * @param {Object} unixPermissions the unix permissions or null.
  11348. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  11349. * @return {Number} a 32 bit integer.
  11350. *
  11351. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  11352. *
  11353. * TTTTsstrwxrwxrwx0000000000ADVSHR
  11354. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  11355. * ^^^_________________________ setuid, setgid, sticky
  11356. * ^^^^^^^^^________________ permissions
  11357. * ^^^^^^^^^^______ not used ?
  11358. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  11359. */
  11360. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  11361. var result = unixPermissions;
  11362. if (!unixPermissions) {
  11363. // I can't use octal values in strict mode, hence the hexa.
  11364. // 040775 => 0x41fd
  11365. // 0100664 => 0x81b4
  11366. result = isDir ? 0x41fd : 0x81b4;
  11367. }
  11368. return (result & 0xFFFF) << 16;
  11369. };
  11370. /**
  11371. * Generate the DOS part of the external file attributes.
  11372. * @param {Object} dosPermissions the dos permissions or null.
  11373. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  11374. * @return {Number} a 32 bit integer.
  11375. *
  11376. * Bit 0 Read-Only
  11377. * Bit 1 Hidden
  11378. * Bit 2 System
  11379. * Bit 3 Volume Label
  11380. * Bit 4 Directory
  11381. * Bit 5 Archive
  11382. */
  11383. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  11384. // the dir flag is already set for compatibility
  11385. return (dosPermissions || 0) & 0x3F;
  11386. };
  11387. /**
  11388. * Generate the various parts used in the construction of the final zip file.
  11389. * @param {string} name the file name.
  11390. * @param {ZipObject} file the file content.
  11391. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  11392. * @param {number} offset the current offset from the start of the zip file.
  11393. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  11394. * @return {object} the zip parts.
  11395. */
  11396. var generateZipParts = function(name, file, compressedObject, offset, platform) {
  11397. var data = compressedObject.compressedContent,
  11398. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  11399. comment = file.comment || "",
  11400. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  11401. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  11402. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  11403. o = file.options,
  11404. dosTime,
  11405. dosDate,
  11406. extraFields = "",
  11407. unicodePathExtraField = "",
  11408. unicodeCommentExtraField = "",
  11409. dir, date;
  11410. // handle the deprecated options.dir
  11411. if (file._initialMetadata.dir !== file.dir) {
  11412. dir = file.dir;
  11413. } else {
  11414. dir = o.dir;
  11415. }
  11416. // handle the deprecated options.date
  11417. if(file._initialMetadata.date !== file.date) {
  11418. date = file.date;
  11419. } else {
  11420. date = o.date;
  11421. }
  11422. var extFileAttr = 0;
  11423. var versionMadeBy = 0;
  11424. if (dir) {
  11425. // dos or unix, we set the dos dir flag
  11426. extFileAttr |= 0x00010;
  11427. }
  11428. if(platform === "UNIX") {
  11429. versionMadeBy = 0x031E; // UNIX, version 3.0
  11430. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  11431. } else { // DOS or other, fallback to DOS
  11432. versionMadeBy = 0x0014; // DOS, version 2.0
  11433. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  11434. }
  11435. // date
  11436. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  11437. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  11438. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  11439. dosTime = date.getHours();
  11440. dosTime = dosTime << 6;
  11441. dosTime = dosTime | date.getMinutes();
  11442. dosTime = dosTime << 5;
  11443. dosTime = dosTime | date.getSeconds() / 2;
  11444. dosDate = date.getFullYear() - 1980;
  11445. dosDate = dosDate << 4;
  11446. dosDate = dosDate | (date.getMonth() + 1);
  11447. dosDate = dosDate << 5;
  11448. dosDate = dosDate | date.getDate();
  11449. if (useUTF8ForFileName) {
  11450. // set the unicode path extra field. unzip needs at least one extra
  11451. // field to correctly handle unicode path, so using the path is as good
  11452. // as any other information. This could improve the situation with
  11453. // other archive managers too.
  11454. // This field is usually used without the utf8 flag, with a non
  11455. // unicode path in the header (winrar, winzip). This helps (a bit)
  11456. // with the messy Windows' default compressed folders feature but
  11457. // breaks on p7zip which doesn't seek the unicode path extra field.
  11458. // So for now, UTF-8 everywhere !
  11459. unicodePathExtraField =
  11460. // Version
  11461. decToHex(1, 1) +
  11462. // NameCRC32
  11463. decToHex(crc32(utfEncodedFileName), 4) +
  11464. // UnicodeName
  11465. utfEncodedFileName;
  11466. extraFields +=
  11467. // Info-ZIP Unicode Path Extra Field
  11468. "\x75\x70" +
  11469. // size
  11470. decToHex(unicodePathExtraField.length, 2) +
  11471. // content
  11472. unicodePathExtraField;
  11473. }
  11474. if(useUTF8ForComment) {
  11475. unicodeCommentExtraField =
  11476. // Version
  11477. decToHex(1, 1) +
  11478. // CommentCRC32
  11479. decToHex(this.crc32(utfEncodedComment), 4) +
  11480. // UnicodeName
  11481. utfEncodedComment;
  11482. extraFields +=
  11483. // Info-ZIP Unicode Path Extra Field
  11484. "\x75\x63" +
  11485. // size
  11486. decToHex(unicodeCommentExtraField.length, 2) +
  11487. // content
  11488. unicodeCommentExtraField;
  11489. }
  11490. var header = "";
  11491. // version needed to extract
  11492. header += "\x0A\x00";
  11493. // general purpose bit flag
  11494. // set bit 11 if utf8
  11495. header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  11496. // compression method
  11497. header += compressedObject.compressionMethod;
  11498. // last mod file time
  11499. header += decToHex(dosTime, 2);
  11500. // last mod file date
  11501. header += decToHex(dosDate, 2);
  11502. // crc-32
  11503. header += decToHex(compressedObject.crc32, 4);
  11504. // compressed size
  11505. header += decToHex(compressedObject.compressedSize, 4);
  11506. // uncompressed size
  11507. header += decToHex(compressedObject.uncompressedSize, 4);
  11508. // file name length
  11509. header += decToHex(utfEncodedFileName.length, 2);
  11510. // extra field length
  11511. header += decToHex(extraFields.length, 2);
  11512. var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
  11513. var dirRecord = signature.CENTRAL_FILE_HEADER +
  11514. // version made by (00: DOS)
  11515. decToHex(versionMadeBy, 2) +
  11516. // file header (common to file and central directory)
  11517. header +
  11518. // file comment length
  11519. decToHex(utfEncodedComment.length, 2) +
  11520. // disk number start
  11521. "\x00\x00" +
  11522. // internal file attributes TODO
  11523. "\x00\x00" +
  11524. // external file attributes
  11525. decToHex(extFileAttr, 4) +
  11526. // relative offset of local header
  11527. decToHex(offset, 4) +
  11528. // file name
  11529. utfEncodedFileName +
  11530. // extra field
  11531. extraFields +
  11532. // file comment
  11533. utfEncodedComment;
  11534. return {
  11535. fileRecord: fileRecord,
  11536. dirRecord: dirRecord,
  11537. compressedObject: compressedObject
  11538. };
  11539. };
  11540. // return the actual prototype of JSZip
  11541. var out = {
  11542. /**
  11543. * Read an existing zip and merge the data in the current JSZip object.
  11544. * The implementation is in jszip-load.js, don't forget to include it.
  11545. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  11546. * @param {Object} options Options for loading the stream.
  11547. * options.base64 : is the stream in base64 ? default : false
  11548. * @return {JSZip} the current JSZip object
  11549. */
  11550. load: function(stream, options) {
  11551. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  11552. },
  11553. /**
  11554. * Filter nested files/folders with the specified function.
  11555. * @param {Function} search the predicate to use :
  11556. * function (relativePath, file) {...}
  11557. * It takes 2 arguments : the relative path and the file.
  11558. * @return {Array} An array of matching elements.
  11559. */
  11560. filter: function(search) {
  11561. var result = [],
  11562. filename, relativePath, file, fileClone;
  11563. for (filename in this.files) {
  11564. if (!this.files.hasOwnProperty(filename)) {
  11565. continue;
  11566. }
  11567. file = this.files[filename];
  11568. // return a new object, don't let the user mess with our internal objects :)
  11569. fileClone = new ZipObject(file.name, file._data, extend(file.options));
  11570. relativePath = filename.slice(this.root.length, filename.length);
  11571. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  11572. search(relativePath, fileClone)) { // and the file matches the function
  11573. result.push(fileClone);
  11574. }
  11575. }
  11576. return result;
  11577. },
  11578. /**
  11579. * Add a file to the zip file, or search a file.
  11580. * @param {string|RegExp} name The name of the file to add (if data is defined),
  11581. * the name of the file to find (if no data) or a regex to match files.
  11582. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  11583. * @param {Object} o File options
  11584. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  11585. * a file (when searching by string) or an array of files (when searching by regex).
  11586. */
  11587. file: function(name, data, o) {
  11588. if (arguments.length === 1) {
  11589. if (utils.isRegExp(name)) {
  11590. var regexp = name;
  11591. return this.filter(function(relativePath, file) {
  11592. return !file.dir && regexp.test(relativePath);
  11593. });
  11594. }
  11595. else { // text
  11596. return this.filter(function(relativePath, file) {
  11597. return !file.dir && relativePath === name;
  11598. })[0] || null;
  11599. }
  11600. }
  11601. else { // more than one argument : we have data !
  11602. name = this.root + name;
  11603. fileAdd.call(this, name, data, o);
  11604. }
  11605. return this;
  11606. },
  11607. /**
  11608. * Add a directory to the zip file, or search.
  11609. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  11610. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  11611. */
  11612. folder: function(arg) {
  11613. if (!arg) {
  11614. return this;
  11615. }
  11616. if (utils.isRegExp(arg)) {
  11617. return this.filter(function(relativePath, file) {
  11618. return file.dir && arg.test(relativePath);
  11619. });
  11620. }
  11621. // else, name is a new folder
  11622. var name = this.root + arg;
  11623. var newFolder = folderAdd.call(this, name);
  11624. // Allow chaining by returning a new object with this folder as the root
  11625. var ret = this.clone();
  11626. ret.root = newFolder.name;
  11627. return ret;
  11628. },
  11629. /**
  11630. * Delete a file, or a directory and all sub-files, from the zip
  11631. * @param {string} name the name of the file to delete
  11632. * @return {JSZip} this JSZip object
  11633. */
  11634. remove: function(name) {
  11635. name = this.root + name;
  11636. var file = this.files[name];
  11637. if (!file) {
  11638. // Look for any folders
  11639. if (name.slice(-1) != "/") {
  11640. name += "/";
  11641. }
  11642. file = this.files[name];
  11643. }
  11644. if (file && !file.dir) {
  11645. // file
  11646. delete this.files[name];
  11647. } else {
  11648. // maybe a folder, delete recursively
  11649. var kids = this.filter(function(relativePath, file) {
  11650. return file.name.slice(0, name.length) === name;
  11651. });
  11652. for (var i = 0; i < kids.length; i++) {
  11653. delete this.files[kids[i].name];
  11654. }
  11655. }
  11656. return this;
  11657. },
  11658. /**
  11659. * Generate the complete zip file
  11660. * @param {Object} options the options to generate the zip file :
  11661. * - base64, (deprecated, use type instead) true to generate base64.
  11662. * - compression, "STORE" by default.
  11663. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  11664. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  11665. */
  11666. generate: function(options) {
  11667. options = extend(options || {}, {
  11668. base64: true,
  11669. compression: "STORE",
  11670. compressionOptions : null,
  11671. type: "base64",
  11672. platform: "DOS",
  11673. comment: null,
  11674. mimeType: 'application/zip'
  11675. });
  11676. utils.checkSupport(options.type);
  11677. // accept nodejs `process.platform`
  11678. if(
  11679. options.platform === 'darwin' ||
  11680. options.platform === 'freebsd' ||
  11681. options.platform === 'linux' ||
  11682. options.platform === 'sunos'
  11683. ) {
  11684. options.platform = "UNIX";
  11685. }
  11686. if (options.platform === 'win32') {
  11687. options.platform = "DOS";
  11688. }
  11689. var zipData = [],
  11690. localDirLength = 0,
  11691. centralDirLength = 0,
  11692. writer, i,
  11693. utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
  11694. // first, generate all the zip parts.
  11695. for (var name in this.files) {
  11696. if (!this.files.hasOwnProperty(name)) {
  11697. continue;
  11698. }
  11699. var file = this.files[name];
  11700. var compressionName = file.options.compression || options.compression.toUpperCase();
  11701. var compression = compressions[compressionName];
  11702. if (!compression) {
  11703. throw new Error(compressionName + " is not a valid compression method !");
  11704. }
  11705. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  11706. var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
  11707. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
  11708. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  11709. centralDirLength += zipPart.dirRecord.length;
  11710. zipData.push(zipPart);
  11711. }
  11712. var dirEnd = "";
  11713. // end of central dir signature
  11714. dirEnd = signature.CENTRAL_DIRECTORY_END +
  11715. // number of this disk
  11716. "\x00\x00" +
  11717. // number of the disk with the start of the central directory
  11718. "\x00\x00" +
  11719. // total number of entries in the central directory on this disk
  11720. decToHex(zipData.length, 2) +
  11721. // total number of entries in the central directory
  11722. decToHex(zipData.length, 2) +
  11723. // size of the central directory 4 bytes
  11724. decToHex(centralDirLength, 4) +
  11725. // offset of start of central directory with respect to the starting disk number
  11726. decToHex(localDirLength, 4) +
  11727. // .ZIP file comment length
  11728. decToHex(utfEncodedComment.length, 2) +
  11729. // .ZIP file comment
  11730. utfEncodedComment;
  11731. // we have all the parts (and the total length)
  11732. // time to create a writer !
  11733. var typeName = options.type.toLowerCase();
  11734. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  11735. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  11736. }else{
  11737. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  11738. }
  11739. for (i = 0; i < zipData.length; i++) {
  11740. writer.append(zipData[i].fileRecord);
  11741. writer.append(zipData[i].compressedObject.compressedContent);
  11742. }
  11743. for (i = 0; i < zipData.length; i++) {
  11744. writer.append(zipData[i].dirRecord);
  11745. }
  11746. writer.append(dirEnd);
  11747. var zip = writer.finalize();
  11748. switch(options.type.toLowerCase()) {
  11749. // case "zip is an Uint8Array"
  11750. case "uint8array" :
  11751. case "arraybuffer" :
  11752. case "nodebuffer" :
  11753. return utils.transformTo(options.type.toLowerCase(), zip);
  11754. case "blob" :
  11755. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
  11756. // case "zip is a string"
  11757. case "base64" :
  11758. return (options.base64) ? base64.encode(zip) : zip;
  11759. default : // case "string" :
  11760. return zip;
  11761. }
  11762. },
  11763. /**
  11764. * @deprecated
  11765. * This method will be removed in a future version without replacement.
  11766. */
  11767. crc32: function (input, crc) {
  11768. return crc32(input, crc);
  11769. },
  11770. /**
  11771. * @deprecated
  11772. * This method will be removed in a future version without replacement.
  11773. */
  11774. utf8encode: function (string) {
  11775. return utils.transformTo("string", utf8.utf8encode(string));
  11776. },
  11777. /**
  11778. * @deprecated
  11779. * This method will be removed in a future version without replacement.
  11780. */
  11781. utf8decode: function (input) {
  11782. return utf8.utf8decode(input);
  11783. }
  11784. };
  11785. module.exports = out;
  11786. },{"./base64":84,"./compressedObject":85,"./compressions":86,"./crc32":87,"./defaults":89,"./nodeBuffer":94,"./signature":97,"./stringWriter":99,"./support":100,"./uint8ArrayWriter":102,"./utf8":103,"./utils":104}],97:[function(require,module,exports){
  11787. 'use strict';
  11788. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  11789. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  11790. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  11791. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  11792. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  11793. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  11794. },{}],98:[function(require,module,exports){
  11795. 'use strict';
  11796. var DataReader = require('./dataReader');
  11797. var utils = require('./utils');
  11798. function StringReader(data, optimizedBinaryString) {
  11799. this.data = data;
  11800. if (!optimizedBinaryString) {
  11801. this.data = utils.string2binary(this.data);
  11802. }
  11803. this.length = this.data.length;
  11804. this.index = 0;
  11805. }
  11806. StringReader.prototype = new DataReader();
  11807. /**
  11808. * @see DataReader.byteAt
  11809. */
  11810. StringReader.prototype.byteAt = function(i) {
  11811. return this.data.charCodeAt(i);
  11812. };
  11813. /**
  11814. * @see DataReader.lastIndexOfSignature
  11815. */
  11816. StringReader.prototype.lastIndexOfSignature = function(sig) {
  11817. return this.data.lastIndexOf(sig);
  11818. };
  11819. /**
  11820. * @see DataReader.readData
  11821. */
  11822. StringReader.prototype.readData = function(size) {
  11823. this.checkOffset(size);
  11824. // this will work because the constructor applied the "& 0xff" mask.
  11825. var result = this.data.slice(this.index, this.index + size);
  11826. this.index += size;
  11827. return result;
  11828. };
  11829. module.exports = StringReader;
  11830. },{"./dataReader":88,"./utils":104}],99:[function(require,module,exports){
  11831. 'use strict';
  11832. var utils = require('./utils');
  11833. /**
  11834. * An object to write any content to a string.
  11835. * @constructor
  11836. */
  11837. var StringWriter = function() {
  11838. this.data = [];
  11839. };
  11840. StringWriter.prototype = {
  11841. /**
  11842. * Append any content to the current string.
  11843. * @param {Object} input the content to add.
  11844. */
  11845. append: function(input) {
  11846. input = utils.transformTo("string", input);
  11847. this.data.push(input);
  11848. },
  11849. /**
  11850. * Finalize the construction an return the result.
  11851. * @return {string} the generated string.
  11852. */
  11853. finalize: function() {
  11854. return this.data.join("");
  11855. }
  11856. };
  11857. module.exports = StringWriter;
  11858. },{"./utils":104}],100:[function(require,module,exports){
  11859. (function (Buffer){
  11860. 'use strict';
  11861. exports.base64 = true;
  11862. exports.array = true;
  11863. exports.string = true;
  11864. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  11865. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  11866. // Browserify will provide a Buffer implementation for browsers, which is
  11867. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  11868. exports.nodebuffer = typeof Buffer !== "undefined";
  11869. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  11870. exports.uint8array = typeof Uint8Array !== "undefined";
  11871. if (typeof ArrayBuffer === "undefined") {
  11872. exports.blob = false;
  11873. }
  11874. else {
  11875. var buffer = new ArrayBuffer(0);
  11876. try {
  11877. exports.blob = new Blob([buffer], {
  11878. type: "application/zip"
  11879. }).size === 0;
  11880. }
  11881. catch (e) {
  11882. try {
  11883. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  11884. var builder = new Builder();
  11885. builder.append(buffer);
  11886. exports.blob = builder.getBlob('application/zip').size === 0;
  11887. }
  11888. catch (e) {
  11889. exports.blob = false;
  11890. }
  11891. }
  11892. }
  11893. }).call(this,require("buffer").Buffer)
  11894. },{"buffer":77}],101:[function(require,module,exports){
  11895. 'use strict';
  11896. var DataReader = require('./dataReader');
  11897. function Uint8ArrayReader(data) {
  11898. if (data) {
  11899. this.data = data;
  11900. this.length = this.data.length;
  11901. this.index = 0;
  11902. }
  11903. }
  11904. Uint8ArrayReader.prototype = new DataReader();
  11905. /**
  11906. * @see DataReader.byteAt
  11907. */
  11908. Uint8ArrayReader.prototype.byteAt = function(i) {
  11909. return this.data[i];
  11910. };
  11911. /**
  11912. * @see DataReader.lastIndexOfSignature
  11913. */
  11914. Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  11915. var sig0 = sig.charCodeAt(0),
  11916. sig1 = sig.charCodeAt(1),
  11917. sig2 = sig.charCodeAt(2),
  11918. sig3 = sig.charCodeAt(3);
  11919. for (var i = this.length - 4; i >= 0; --i) {
  11920. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  11921. return i;
  11922. }
  11923. }
  11924. return -1;
  11925. };
  11926. /**
  11927. * @see DataReader.readData
  11928. */
  11929. Uint8ArrayReader.prototype.readData = function(size) {
  11930. this.checkOffset(size);
  11931. if(size === 0) {
  11932. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  11933. return new Uint8Array(0);
  11934. }
  11935. var result = this.data.subarray(this.index, this.index + size);
  11936. this.index += size;
  11937. return result;
  11938. };
  11939. module.exports = Uint8ArrayReader;
  11940. },{"./dataReader":88}],102:[function(require,module,exports){
  11941. 'use strict';
  11942. var utils = require('./utils');
  11943. /**
  11944. * An object to write any content to an Uint8Array.
  11945. * @constructor
  11946. * @param {number} length The length of the array.
  11947. */
  11948. var Uint8ArrayWriter = function(length) {
  11949. this.data = new Uint8Array(length);
  11950. this.index = 0;
  11951. };
  11952. Uint8ArrayWriter.prototype = {
  11953. /**
  11954. * Append any content to the current array.
  11955. * @param {Object} input the content to add.
  11956. */
  11957. append: function(input) {
  11958. if (input.length !== 0) {
  11959. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  11960. input = utils.transformTo("uint8array", input);
  11961. this.data.set(input, this.index);
  11962. this.index += input.length;
  11963. }
  11964. },
  11965. /**
  11966. * Finalize the construction an return the result.
  11967. * @return {Uint8Array} the generated array.
  11968. */
  11969. finalize: function() {
  11970. return this.data;
  11971. }
  11972. };
  11973. module.exports = Uint8ArrayWriter;
  11974. },{"./utils":104}],103:[function(require,module,exports){
  11975. 'use strict';
  11976. var utils = require('./utils');
  11977. var support = require('./support');
  11978. var nodeBuffer = require('./nodeBuffer');
  11979. /**
  11980. * The following functions come from pako, from pako/lib/utils/strings
  11981. * released under the MIT license, see pako https://github.com/nodeca/pako/
  11982. */
  11983. // Table with utf8 lengths (calculated by first byte of sequence)
  11984. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  11985. // because max possible codepoint is 0x10ffff
  11986. var _utf8len = new Array(256);
  11987. for (var i=0; i<256; i++) {
  11988. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  11989. }
  11990. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  11991. // convert string to array (typed, when possible)
  11992. var string2buf = function (str) {
  11993. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  11994. // count binary size
  11995. for (m_pos = 0; m_pos < str_len; m_pos++) {
  11996. c = str.charCodeAt(m_pos);
  11997. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  11998. c2 = str.charCodeAt(m_pos+1);
  11999. if ((c2 & 0xfc00) === 0xdc00) {
  12000. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12001. m_pos++;
  12002. }
  12003. }
  12004. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  12005. }
  12006. // allocate buffer
  12007. if (support.uint8array) {
  12008. buf = new Uint8Array(buf_len);
  12009. } else {
  12010. buf = new Array(buf_len);
  12011. }
  12012. // convert
  12013. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  12014. c = str.charCodeAt(m_pos);
  12015. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  12016. c2 = str.charCodeAt(m_pos+1);
  12017. if ((c2 & 0xfc00) === 0xdc00) {
  12018. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  12019. m_pos++;
  12020. }
  12021. }
  12022. if (c < 0x80) {
  12023. /* one byte */
  12024. buf[i++] = c;
  12025. } else if (c < 0x800) {
  12026. /* two bytes */
  12027. buf[i++] = 0xC0 | (c >>> 6);
  12028. buf[i++] = 0x80 | (c & 0x3f);
  12029. } else if (c < 0x10000) {
  12030. /* three bytes */
  12031. buf[i++] = 0xE0 | (c >>> 12);
  12032. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12033. buf[i++] = 0x80 | (c & 0x3f);
  12034. } else {
  12035. /* four bytes */
  12036. buf[i++] = 0xf0 | (c >>> 18);
  12037. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  12038. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  12039. buf[i++] = 0x80 | (c & 0x3f);
  12040. }
  12041. }
  12042. return buf;
  12043. };
  12044. // Calculate max possible position in utf8 buffer,
  12045. // that will not break sequence. If that's not possible
  12046. // - (very small limits) return max size as is.
  12047. //
  12048. // buf[] - utf8 bytes array
  12049. // max - length limit (mandatory);
  12050. var utf8border = function(buf, max) {
  12051. var pos;
  12052. max = max || buf.length;
  12053. if (max > buf.length) { max = buf.length; }
  12054. // go back from last position, until start of sequence found
  12055. pos = max-1;
  12056. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  12057. // Fuckup - very small and broken sequence,
  12058. // return max, because we should return something anyway.
  12059. if (pos < 0) { return max; }
  12060. // If we came to start of buffer - that means vuffer is too small,
  12061. // return max too.
  12062. if (pos === 0) { return max; }
  12063. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  12064. };
  12065. // convert array to string
  12066. var buf2string = function (buf) {
  12067. var str, i, out, c, c_len;
  12068. var len = buf.length;
  12069. // Reserve max possible length (2 words per char)
  12070. // NB: by unknown reasons, Array is significantly faster for
  12071. // String.fromCharCode.apply than Uint16Array.
  12072. var utf16buf = new Array(len*2);
  12073. for (out=0, i=0; i<len;) {
  12074. c = buf[i++];
  12075. // quick process ascii
  12076. if (c < 0x80) { utf16buf[out++] = c; continue; }
  12077. c_len = _utf8len[c];
  12078. // skip 5 & 6 byte codes
  12079. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  12080. // apply mask on first byte
  12081. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  12082. // join the rest
  12083. while (c_len > 1 && i < len) {
  12084. c = (c << 6) | (buf[i++] & 0x3f);
  12085. c_len--;
  12086. }
  12087. // terminated by end of string?
  12088. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  12089. if (c < 0x10000) {
  12090. utf16buf[out++] = c;
  12091. } else {
  12092. c -= 0x10000;
  12093. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  12094. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  12095. }
  12096. }
  12097. // shrinkBuf(utf16buf, out)
  12098. if (utf16buf.length !== out) {
  12099. if(utf16buf.subarray) {
  12100. utf16buf = utf16buf.subarray(0, out);
  12101. } else {
  12102. utf16buf.length = out;
  12103. }
  12104. }
  12105. // return String.fromCharCode.apply(null, utf16buf);
  12106. return utils.applyFromCharCode(utf16buf);
  12107. };
  12108. // That's all for the pako functions.
  12109. /**
  12110. * Transform a javascript string into an array (typed if possible) of bytes,
  12111. * UTF-8 encoded.
  12112. * @param {String} str the string to encode
  12113. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  12114. */
  12115. exports.utf8encode = function utf8encode(str) {
  12116. if (support.nodebuffer) {
  12117. return nodeBuffer(str, "utf-8");
  12118. }
  12119. return string2buf(str);
  12120. };
  12121. /**
  12122. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  12123. * string into a javascript string.
  12124. * @param {Array|Uint8Array|Buffer} buf the data de decode
  12125. * @return {String} the decoded string.
  12126. */
  12127. exports.utf8decode = function utf8decode(buf) {
  12128. if (support.nodebuffer) {
  12129. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  12130. }
  12131. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  12132. // return buf2string(buf);
  12133. // Chrome prefers to work with "small" chunks of data
  12134. // for the method buf2string.
  12135. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  12136. var result = [], k = 0, len = buf.length, chunk = 65536;
  12137. while (k < len) {
  12138. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  12139. if (support.uint8array) {
  12140. result.push(buf2string(buf.subarray(k, nextBoundary)));
  12141. } else {
  12142. result.push(buf2string(buf.slice(k, nextBoundary)));
  12143. }
  12144. k = nextBoundary;
  12145. }
  12146. return result.join("");
  12147. };
  12148. // vim: set shiftwidth=4 softtabstop=4:
  12149. },{"./nodeBuffer":94,"./support":100,"./utils":104}],104:[function(require,module,exports){
  12150. 'use strict';
  12151. var support = require('./support');
  12152. var compressions = require('./compressions');
  12153. var nodeBuffer = require('./nodeBuffer');
  12154. /**
  12155. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  12156. * @param {string} str the string to transform.
  12157. * @return {String} the binary string.
  12158. */
  12159. exports.string2binary = function(str) {
  12160. var result = "";
  12161. for (var i = 0; i < str.length; i++) {
  12162. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  12163. }
  12164. return result;
  12165. };
  12166. exports.arrayBuffer2Blob = function(buffer, mimeType) {
  12167. exports.checkSupport("blob");
  12168. mimeType = mimeType || 'application/zip';
  12169. try {
  12170. // Blob constructor
  12171. return new Blob([buffer], {
  12172. type: mimeType
  12173. });
  12174. }
  12175. catch (e) {
  12176. try {
  12177. // deprecated, browser only, old way
  12178. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  12179. var builder = new Builder();
  12180. builder.append(buffer);
  12181. return builder.getBlob(mimeType);
  12182. }
  12183. catch (e) {
  12184. // well, fuck ?!
  12185. throw new Error("Bug : can't construct the Blob.");
  12186. }
  12187. }
  12188. };
  12189. /**
  12190. * The identity function.
  12191. * @param {Object} input the input.
  12192. * @return {Object} the same input.
  12193. */
  12194. function identity(input) {
  12195. return input;
  12196. }
  12197. /**
  12198. * Fill in an array with a string.
  12199. * @param {String} str the string to use.
  12200. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  12201. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  12202. */
  12203. function stringToArrayLike(str, array) {
  12204. for (var i = 0; i < str.length; ++i) {
  12205. array[i] = str.charCodeAt(i) & 0xFF;
  12206. }
  12207. return array;
  12208. }
  12209. /**
  12210. * Transform an array-like object to a string.
  12211. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  12212. * @return {String} the result.
  12213. */
  12214. function arrayLikeToString(array) {
  12215. // Performances notes :
  12216. // --------------------
  12217. // String.fromCharCode.apply(null, array) is the fastest, see
  12218. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  12219. // but the stack is limited (and we can get huge arrays !).
  12220. //
  12221. // result += String.fromCharCode(array[i]); generate too many strings !
  12222. //
  12223. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  12224. var chunk = 65536;
  12225. var result = [],
  12226. len = array.length,
  12227. type = exports.getTypeOf(array),
  12228. k = 0,
  12229. canUseApply = true;
  12230. try {
  12231. switch(type) {
  12232. case "uint8array":
  12233. String.fromCharCode.apply(null, new Uint8Array(0));
  12234. break;
  12235. case "nodebuffer":
  12236. String.fromCharCode.apply(null, nodeBuffer(0));
  12237. break;
  12238. }
  12239. } catch(e) {
  12240. canUseApply = false;
  12241. }
  12242. // no apply : slow and painful algorithm
  12243. // default browser on android 4.*
  12244. if (!canUseApply) {
  12245. var resultStr = "";
  12246. for(var i = 0; i < array.length;i++) {
  12247. resultStr += String.fromCharCode(array[i]);
  12248. }
  12249. return resultStr;
  12250. }
  12251. while (k < len && chunk > 1) {
  12252. try {
  12253. if (type === "array" || type === "nodebuffer") {
  12254. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  12255. }
  12256. else {
  12257. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  12258. }
  12259. k += chunk;
  12260. }
  12261. catch (e) {
  12262. chunk = Math.floor(chunk / 2);
  12263. }
  12264. }
  12265. return result.join("");
  12266. }
  12267. exports.applyFromCharCode = arrayLikeToString;
  12268. /**
  12269. * Copy the data from an array-like to an other array-like.
  12270. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  12271. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  12272. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  12273. */
  12274. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  12275. for (var i = 0; i < arrayFrom.length; i++) {
  12276. arrayTo[i] = arrayFrom[i];
  12277. }
  12278. return arrayTo;
  12279. }
  12280. // a matrix containing functions to transform everything into everything.
  12281. var transform = {};
  12282. // string to ?
  12283. transform["string"] = {
  12284. "string": identity,
  12285. "array": function(input) {
  12286. return stringToArrayLike(input, new Array(input.length));
  12287. },
  12288. "arraybuffer": function(input) {
  12289. return transform["string"]["uint8array"](input).buffer;
  12290. },
  12291. "uint8array": function(input) {
  12292. return stringToArrayLike(input, new Uint8Array(input.length));
  12293. },
  12294. "nodebuffer": function(input) {
  12295. return stringToArrayLike(input, nodeBuffer(input.length));
  12296. }
  12297. };
  12298. // array to ?
  12299. transform["array"] = {
  12300. "string": arrayLikeToString,
  12301. "array": identity,
  12302. "arraybuffer": function(input) {
  12303. return (new Uint8Array(input)).buffer;
  12304. },
  12305. "uint8array": function(input) {
  12306. return new Uint8Array(input);
  12307. },
  12308. "nodebuffer": function(input) {
  12309. return nodeBuffer(input);
  12310. }
  12311. };
  12312. // arraybuffer to ?
  12313. transform["arraybuffer"] = {
  12314. "string": function(input) {
  12315. return arrayLikeToString(new Uint8Array(input));
  12316. },
  12317. "array": function(input) {
  12318. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  12319. },
  12320. "arraybuffer": identity,
  12321. "uint8array": function(input) {
  12322. return new Uint8Array(input);
  12323. },
  12324. "nodebuffer": function(input) {
  12325. return nodeBuffer(new Uint8Array(input));
  12326. }
  12327. };
  12328. // uint8array to ?
  12329. transform["uint8array"] = {
  12330. "string": arrayLikeToString,
  12331. "array": function(input) {
  12332. return arrayLikeToArrayLike(input, new Array(input.length));
  12333. },
  12334. "arraybuffer": function(input) {
  12335. return input.buffer;
  12336. },
  12337. "uint8array": identity,
  12338. "nodebuffer": function(input) {
  12339. return nodeBuffer(input);
  12340. }
  12341. };
  12342. // nodebuffer to ?
  12343. transform["nodebuffer"] = {
  12344. "string": arrayLikeToString,
  12345. "array": function(input) {
  12346. return arrayLikeToArrayLike(input, new Array(input.length));
  12347. },
  12348. "arraybuffer": function(input) {
  12349. return transform["nodebuffer"]["uint8array"](input).buffer;
  12350. },
  12351. "uint8array": function(input) {
  12352. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  12353. },
  12354. "nodebuffer": identity
  12355. };
  12356. /**
  12357. * Transform an input into any type.
  12358. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  12359. * If no output type is specified, the unmodified input will be returned.
  12360. * @param {String} outputType the output type.
  12361. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  12362. * @throws {Error} an Error if the browser doesn't support the requested output type.
  12363. */
  12364. exports.transformTo = function(outputType, input) {
  12365. if (!input) {
  12366. // undefined, null, etc
  12367. // an empty string won't harm.
  12368. input = "";
  12369. }
  12370. if (!outputType) {
  12371. return input;
  12372. }
  12373. exports.checkSupport(outputType);
  12374. var inputType = exports.getTypeOf(input);
  12375. var result = transform[inputType][outputType](input);
  12376. return result;
  12377. };
  12378. /**
  12379. * Return the type of the input.
  12380. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  12381. * @param {Object} input the input to identify.
  12382. * @return {String} the (lowercase) type of the input.
  12383. */
  12384. exports.getTypeOf = function(input) {
  12385. if (typeof input === "string") {
  12386. return "string";
  12387. }
  12388. if (Object.prototype.toString.call(input) === "[object Array]") {
  12389. return "array";
  12390. }
  12391. if (support.nodebuffer && nodeBuffer.test(input)) {
  12392. return "nodebuffer";
  12393. }
  12394. if (support.uint8array && input instanceof Uint8Array) {
  12395. return "uint8array";
  12396. }
  12397. if (support.arraybuffer && input instanceof ArrayBuffer) {
  12398. return "arraybuffer";
  12399. }
  12400. };
  12401. /**
  12402. * Throw an exception if the type is not supported.
  12403. * @param {String} type the type to check.
  12404. * @throws {Error} an Error if the browser doesn't support the requested type.
  12405. */
  12406. exports.checkSupport = function(type) {
  12407. var supported = support[type.toLowerCase()];
  12408. if (!supported) {
  12409. throw new Error(type + " is not supported by this browser");
  12410. }
  12411. };
  12412. exports.MAX_VALUE_16BITS = 65535;
  12413. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  12414. /**
  12415. * Prettify a string read as binary.
  12416. * @param {string} str the string to prettify.
  12417. * @return {string} a pretty string.
  12418. */
  12419. exports.pretty = function(str) {
  12420. var res = '',
  12421. code, i;
  12422. for (i = 0; i < (str || "").length; i++) {
  12423. code = str.charCodeAt(i);
  12424. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  12425. }
  12426. return res;
  12427. };
  12428. /**
  12429. * Find a compression registered in JSZip.
  12430. * @param {string} compressionMethod the method magic to find.
  12431. * @return {Object|null} the JSZip compression object, null if none found.
  12432. */
  12433. exports.findCompression = function(compressionMethod) {
  12434. for (var method in compressions) {
  12435. if (!compressions.hasOwnProperty(method)) {
  12436. continue;
  12437. }
  12438. if (compressions[method].magic === compressionMethod) {
  12439. return compressions[method];
  12440. }
  12441. }
  12442. return null;
  12443. };
  12444. /**
  12445. * Cross-window, cross-Node-context regular expression detection
  12446. * @param {Object} object Anything
  12447. * @return {Boolean} true if the object is a regular expression,
  12448. * false otherwise
  12449. */
  12450. exports.isRegExp = function (object) {
  12451. return Object.prototype.toString.call(object) === "[object RegExp]";
  12452. };
  12453. },{"./compressions":86,"./nodeBuffer":94,"./support":100}],105:[function(require,module,exports){
  12454. 'use strict';
  12455. var StringReader = require('./stringReader');
  12456. var NodeBufferReader = require('./nodeBufferReader');
  12457. var Uint8ArrayReader = require('./uint8ArrayReader');
  12458. var utils = require('./utils');
  12459. var sig = require('./signature');
  12460. var ZipEntry = require('./zipEntry');
  12461. var support = require('./support');
  12462. var jszipProto = require('./object');
  12463. // class ZipEntries {{{
  12464. /**
  12465. * All the entries in the zip file.
  12466. * @constructor
  12467. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  12468. * @param {Object} loadOptions Options for loading the stream.
  12469. */
  12470. function ZipEntries(data, loadOptions) {
  12471. this.files = [];
  12472. this.loadOptions = loadOptions;
  12473. if (data) {
  12474. this.load(data);
  12475. }
  12476. }
  12477. ZipEntries.prototype = {
  12478. /**
  12479. * Check that the reader is on the speficied signature.
  12480. * @param {string} expectedSignature the expected signature.
  12481. * @throws {Error} if it is an other signature.
  12482. */
  12483. checkSignature: function(expectedSignature) {
  12484. var signature = this.reader.readString(4);
  12485. if (signature !== expectedSignature) {
  12486. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  12487. }
  12488. },
  12489. /**
  12490. * Read the end of the central directory.
  12491. */
  12492. readBlockEndOfCentral: function() {
  12493. this.diskNumber = this.reader.readInt(2);
  12494. this.diskWithCentralDirStart = this.reader.readInt(2);
  12495. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  12496. this.centralDirRecords = this.reader.readInt(2);
  12497. this.centralDirSize = this.reader.readInt(4);
  12498. this.centralDirOffset = this.reader.readInt(4);
  12499. this.zipCommentLength = this.reader.readInt(2);
  12500. // warning : the encoding depends of the system locale
  12501. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  12502. // On a windows machine, this field is encoded with the localized windows code page.
  12503. this.zipComment = this.reader.readString(this.zipCommentLength);
  12504. // To get consistent behavior with the generation part, we will assume that
  12505. // this is utf8 encoded.
  12506. this.zipComment = jszipProto.utf8decode(this.zipComment);
  12507. },
  12508. /**
  12509. * Read the end of the Zip 64 central directory.
  12510. * Not merged with the method readEndOfCentral :
  12511. * The end of central can coexist with its Zip64 brother,
  12512. * I don't want to read the wrong number of bytes !
  12513. */
  12514. readBlockZip64EndOfCentral: function() {
  12515. this.zip64EndOfCentralSize = this.reader.readInt(8);
  12516. this.versionMadeBy = this.reader.readString(2);
  12517. this.versionNeeded = this.reader.readInt(2);
  12518. this.diskNumber = this.reader.readInt(4);
  12519. this.diskWithCentralDirStart = this.reader.readInt(4);
  12520. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  12521. this.centralDirRecords = this.reader.readInt(8);
  12522. this.centralDirSize = this.reader.readInt(8);
  12523. this.centralDirOffset = this.reader.readInt(8);
  12524. this.zip64ExtensibleData = {};
  12525. var extraDataSize = this.zip64EndOfCentralSize - 44,
  12526. index = 0,
  12527. extraFieldId,
  12528. extraFieldLength,
  12529. extraFieldValue;
  12530. while (index < extraDataSize) {
  12531. extraFieldId = this.reader.readInt(2);
  12532. extraFieldLength = this.reader.readInt(4);
  12533. extraFieldValue = this.reader.readString(extraFieldLength);
  12534. this.zip64ExtensibleData[extraFieldId] = {
  12535. id: extraFieldId,
  12536. length: extraFieldLength,
  12537. value: extraFieldValue
  12538. };
  12539. }
  12540. },
  12541. /**
  12542. * Read the end of the Zip 64 central directory locator.
  12543. */
  12544. readBlockZip64EndOfCentralLocator: function() {
  12545. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  12546. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  12547. this.disksCount = this.reader.readInt(4);
  12548. if (this.disksCount > 1) {
  12549. throw new Error("Multi-volumes zip are not supported");
  12550. }
  12551. },
  12552. /**
  12553. * Read the local files, based on the offset read in the central part.
  12554. */
  12555. readLocalFiles: function() {
  12556. var i, file;
  12557. for (i = 0; i < this.files.length; i++) {
  12558. file = this.files[i];
  12559. this.reader.setIndex(file.localHeaderOffset);
  12560. this.checkSignature(sig.LOCAL_FILE_HEADER);
  12561. file.readLocalPart(this.reader);
  12562. file.handleUTF8();
  12563. file.processAttributes();
  12564. }
  12565. },
  12566. /**
  12567. * Read the central directory.
  12568. */
  12569. readCentralDir: function() {
  12570. var file;
  12571. this.reader.setIndex(this.centralDirOffset);
  12572. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  12573. file = new ZipEntry({
  12574. zip64: this.zip64
  12575. }, this.loadOptions);
  12576. file.readCentralPart(this.reader);
  12577. this.files.push(file);
  12578. }
  12579. },
  12580. /**
  12581. * Read the end of central directory.
  12582. */
  12583. readEndOfCentral: function() {
  12584. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  12585. if (offset === -1) {
  12586. // Check if the content is a truncated zip or complete garbage.
  12587. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  12588. // extractible zip for example) but it can give a good hint.
  12589. // If an ajax request was used without responseType, we will also
  12590. // get unreadable data.
  12591. var isGarbage = true;
  12592. try {
  12593. this.reader.setIndex(0);
  12594. this.checkSignature(sig.LOCAL_FILE_HEADER);
  12595. isGarbage = false;
  12596. } catch (e) {}
  12597. if (isGarbage) {
  12598. throw new Error("Can't find end of central directory : is this a zip file ? " +
  12599. "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
  12600. } else {
  12601. throw new Error("Corrupted zip : can't find end of central directory");
  12602. }
  12603. }
  12604. this.reader.setIndex(offset);
  12605. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  12606. this.readBlockEndOfCentral();
  12607. /* extract from the zip spec :
  12608. 4) If one of the fields in the end of central directory
  12609. record is too small to hold required data, the field
  12610. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  12611. ZIP64 format record should be created.
  12612. 5) The end of central directory record and the
  12613. Zip64 end of central directory locator record must
  12614. reside on the same disk when splitting or spanning
  12615. an archive.
  12616. */
  12617. if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
  12618. this.zip64 = true;
  12619. /*
  12620. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  12621. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  12622. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  12623. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  12624. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  12625. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  12626. */
  12627. // should look for a zip64 EOCD locator
  12628. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  12629. if (offset === -1) {
  12630. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  12631. }
  12632. this.reader.setIndex(offset);
  12633. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  12634. this.readBlockZip64EndOfCentralLocator();
  12635. // now the zip64 EOCD record
  12636. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  12637. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  12638. this.readBlockZip64EndOfCentral();
  12639. }
  12640. },
  12641. prepareReader: function(data) {
  12642. var type = utils.getTypeOf(data);
  12643. if (type === "string" && !support.uint8array) {
  12644. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  12645. }
  12646. else if (type === "nodebuffer") {
  12647. this.reader = new NodeBufferReader(data);
  12648. }
  12649. else {
  12650. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  12651. }
  12652. },
  12653. /**
  12654. * Read a zip file and create ZipEntries.
  12655. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  12656. */
  12657. load: function(data) {
  12658. this.prepareReader(data);
  12659. this.readEndOfCentral();
  12660. this.readCentralDir();
  12661. this.readLocalFiles();
  12662. }
  12663. };
  12664. // }}} end of ZipEntries
  12665. module.exports = ZipEntries;
  12666. },{"./nodeBufferReader":95,"./object":96,"./signature":97,"./stringReader":98,"./support":100,"./uint8ArrayReader":101,"./utils":104,"./zipEntry":106}],106:[function(require,module,exports){
  12667. 'use strict';
  12668. var StringReader = require('./stringReader');
  12669. var utils = require('./utils');
  12670. var CompressedObject = require('./compressedObject');
  12671. var jszipProto = require('./object');
  12672. var MADE_BY_DOS = 0x00;
  12673. var MADE_BY_UNIX = 0x03;
  12674. // class ZipEntry {{{
  12675. /**
  12676. * An entry in the zip file.
  12677. * @constructor
  12678. * @param {Object} options Options of the current file.
  12679. * @param {Object} loadOptions Options for loading the stream.
  12680. */
  12681. function ZipEntry(options, loadOptions) {
  12682. this.options = options;
  12683. this.loadOptions = loadOptions;
  12684. }
  12685. ZipEntry.prototype = {
  12686. /**
  12687. * say if the file is encrypted.
  12688. * @return {boolean} true if the file is encrypted, false otherwise.
  12689. */
  12690. isEncrypted: function() {
  12691. // bit 1 is set
  12692. return (this.bitFlag & 0x0001) === 0x0001;
  12693. },
  12694. /**
  12695. * say if the file has utf-8 filename/comment.
  12696. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  12697. */
  12698. useUTF8: function() {
  12699. // bit 11 is set
  12700. return (this.bitFlag & 0x0800) === 0x0800;
  12701. },
  12702. /**
  12703. * Prepare the function used to generate the compressed content from this ZipFile.
  12704. * @param {DataReader} reader the reader to use.
  12705. * @param {number} from the offset from where we should read the data.
  12706. * @param {number} length the length of the data to read.
  12707. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  12708. */
  12709. prepareCompressedContent: function(reader, from, length) {
  12710. return function() {
  12711. var previousIndex = reader.index;
  12712. reader.setIndex(from);
  12713. var compressedFileData = reader.readData(length);
  12714. reader.setIndex(previousIndex);
  12715. return compressedFileData;
  12716. };
  12717. },
  12718. /**
  12719. * Prepare the function used to generate the uncompressed content from this ZipFile.
  12720. * @param {DataReader} reader the reader to use.
  12721. * @param {number} from the offset from where we should read the data.
  12722. * @param {number} length the length of the data to read.
  12723. * @param {JSZip.compression} compression the compression used on this file.
  12724. * @param {number} uncompressedSize the uncompressed size to expect.
  12725. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  12726. */
  12727. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  12728. return function() {
  12729. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  12730. var uncompressedFileData = compression.uncompress(compressedFileData);
  12731. if (uncompressedFileData.length !== uncompressedSize) {
  12732. throw new Error("Bug : uncompressed data size mismatch");
  12733. }
  12734. return uncompressedFileData;
  12735. };
  12736. },
  12737. /**
  12738. * Read the local part of a zip file and add the info in this object.
  12739. * @param {DataReader} reader the reader to use.
  12740. */
  12741. readLocalPart: function(reader) {
  12742. var compression, localExtraFieldsLength;
  12743. // we already know everything from the central dir !
  12744. // If the central dir data are false, we are doomed.
  12745. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  12746. // The less data we get here, the more reliable this should be.
  12747. // Let's skip the whole header and dash to the data !
  12748. reader.skip(22);
  12749. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  12750. // Strangely, the filename here is OK.
  12751. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  12752. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  12753. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  12754. // the internet.
  12755. //
  12756. // I think I see the logic here : the central directory is used to display
  12757. // content and the local directory is used to extract the files. Mixing / and \
  12758. // may be used to display \ to windows users and use / when extracting the files.
  12759. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  12760. this.fileNameLength = reader.readInt(2);
  12761. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  12762. this.fileName = reader.readString(this.fileNameLength);
  12763. reader.skip(localExtraFieldsLength);
  12764. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  12765. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  12766. }
  12767. compression = utils.findCompression(this.compressionMethod);
  12768. if (compression === null) { // no compression found
  12769. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
  12770. }
  12771. this.decompressed = new CompressedObject();
  12772. this.decompressed.compressedSize = this.compressedSize;
  12773. this.decompressed.uncompressedSize = this.uncompressedSize;
  12774. this.decompressed.crc32 = this.crc32;
  12775. this.decompressed.compressionMethod = this.compressionMethod;
  12776. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  12777. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  12778. // we need to compute the crc32...
  12779. if (this.loadOptions.checkCRC32) {
  12780. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  12781. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  12782. throw new Error("Corrupted zip : CRC32 mismatch");
  12783. }
  12784. }
  12785. },
  12786. /**
  12787. * Read the central part of a zip file and add the info in this object.
  12788. * @param {DataReader} reader the reader to use.
  12789. */
  12790. readCentralPart: function(reader) {
  12791. this.versionMadeBy = reader.readInt(2);
  12792. this.versionNeeded = reader.readInt(2);
  12793. this.bitFlag = reader.readInt(2);
  12794. this.compressionMethod = reader.readString(2);
  12795. this.date = reader.readDate();
  12796. this.crc32 = reader.readInt(4);
  12797. this.compressedSize = reader.readInt(4);
  12798. this.uncompressedSize = reader.readInt(4);
  12799. this.fileNameLength = reader.readInt(2);
  12800. this.extraFieldsLength = reader.readInt(2);
  12801. this.fileCommentLength = reader.readInt(2);
  12802. this.diskNumberStart = reader.readInt(2);
  12803. this.internalFileAttributes = reader.readInt(2);
  12804. this.externalFileAttributes = reader.readInt(4);
  12805. this.localHeaderOffset = reader.readInt(4);
  12806. if (this.isEncrypted()) {
  12807. throw new Error("Encrypted zip are not supported");
  12808. }
  12809. this.fileName = reader.readString(this.fileNameLength);
  12810. this.readExtraFields(reader);
  12811. this.parseZIP64ExtraField(reader);
  12812. this.fileComment = reader.readString(this.fileCommentLength);
  12813. },
  12814. /**
  12815. * Parse the external file attributes and get the unix/dos permissions.
  12816. */
  12817. processAttributes: function () {
  12818. this.unixPermissions = null;
  12819. this.dosPermissions = null;
  12820. var madeBy = this.versionMadeBy >> 8;
  12821. // Check if we have the DOS directory flag set.
  12822. // We look for it in the DOS and UNIX permissions
  12823. // but some unknown platform could set it as a compatibility flag.
  12824. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  12825. if(madeBy === MADE_BY_DOS) {
  12826. // first 6 bits (0 to 5)
  12827. this.dosPermissions = this.externalFileAttributes & 0x3F;
  12828. }
  12829. if(madeBy === MADE_BY_UNIX) {
  12830. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  12831. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  12832. }
  12833. // fail safe : if the name ends with a / it probably means a folder
  12834. if (!this.dir && this.fileName.slice(-1) === '/') {
  12835. this.dir = true;
  12836. }
  12837. },
  12838. /**
  12839. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  12840. * @param {DataReader} reader the reader to use.
  12841. */
  12842. parseZIP64ExtraField: function(reader) {
  12843. if (!this.extraFields[0x0001]) {
  12844. return;
  12845. }
  12846. // should be something, preparing the extra reader
  12847. var extraReader = new StringReader(this.extraFields[0x0001].value);
  12848. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  12849. // won't let us have more.
  12850. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  12851. this.uncompressedSize = extraReader.readInt(8);
  12852. }
  12853. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  12854. this.compressedSize = extraReader.readInt(8);
  12855. }
  12856. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  12857. this.localHeaderOffset = extraReader.readInt(8);
  12858. }
  12859. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  12860. this.diskNumberStart = extraReader.readInt(4);
  12861. }
  12862. },
  12863. /**
  12864. * Read the central part of a zip file and add the info in this object.
  12865. * @param {DataReader} reader the reader to use.
  12866. */
  12867. readExtraFields: function(reader) {
  12868. var start = reader.index,
  12869. extraFieldId,
  12870. extraFieldLength,
  12871. extraFieldValue;
  12872. this.extraFields = this.extraFields || {};
  12873. while (reader.index < start + this.extraFieldsLength) {
  12874. extraFieldId = reader.readInt(2);
  12875. extraFieldLength = reader.readInt(2);
  12876. extraFieldValue = reader.readString(extraFieldLength);
  12877. this.extraFields[extraFieldId] = {
  12878. id: extraFieldId,
  12879. length: extraFieldLength,
  12880. value: extraFieldValue
  12881. };
  12882. }
  12883. },
  12884. /**
  12885. * Apply an UTF8 transformation if needed.
  12886. */
  12887. handleUTF8: function() {
  12888. if (this.useUTF8()) {
  12889. this.fileName = jszipProto.utf8decode(this.fileName);
  12890. this.fileComment = jszipProto.utf8decode(this.fileComment);
  12891. } else {
  12892. var upath = this.findExtraFieldUnicodePath();
  12893. if (upath !== null) {
  12894. this.fileName = upath;
  12895. }
  12896. var ucomment = this.findExtraFieldUnicodeComment();
  12897. if (ucomment !== null) {
  12898. this.fileComment = ucomment;
  12899. }
  12900. }
  12901. },
  12902. /**
  12903. * Find the unicode path declared in the extra field, if any.
  12904. * @return {String} the unicode path, null otherwise.
  12905. */
  12906. findExtraFieldUnicodePath: function() {
  12907. var upathField = this.extraFields[0x7075];
  12908. if (upathField) {
  12909. var extraReader = new StringReader(upathField.value);
  12910. // wrong version
  12911. if (extraReader.readInt(1) !== 1) {
  12912. return null;
  12913. }
  12914. // the crc of the filename changed, this field is out of date.
  12915. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  12916. return null;
  12917. }
  12918. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  12919. }
  12920. return null;
  12921. },
  12922. /**
  12923. * Find the unicode comment declared in the extra field, if any.
  12924. * @return {String} the unicode comment, null otherwise.
  12925. */
  12926. findExtraFieldUnicodeComment: function() {
  12927. var ucommentField = this.extraFields[0x6375];
  12928. if (ucommentField) {
  12929. var extraReader = new StringReader(ucommentField.value);
  12930. // wrong version
  12931. if (extraReader.readInt(1) !== 1) {
  12932. return null;
  12933. }
  12934. // the crc of the comment changed, this field is out of date.
  12935. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  12936. return null;
  12937. }
  12938. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  12939. }
  12940. return null;
  12941. }
  12942. };
  12943. module.exports = ZipEntry;
  12944. },{"./compressedObject":85,"./object":96,"./stringReader":98,"./utils":104}],107:[function(require,module,exports){
  12945. exports.Parser = require("./lib/parser").Parser;
  12946. exports.rules = require("./lib/rules");
  12947. exports.errors = require("./lib/errors");
  12948. exports.results = require("./lib/parsing-results");
  12949. exports.StringSource = require("./lib/StringSource");
  12950. exports.Token = require("./lib/Token");
  12951. exports.bottomUp = require("./lib/bottom-up");
  12952. exports.RegexTokeniser = require("./lib/regex-tokeniser").RegexTokeniser;
  12953. exports.rule = function(ruleBuilder) {
  12954. var rule;
  12955. return function(input) {
  12956. if (!rule) {
  12957. rule = ruleBuilder();
  12958. }
  12959. return rule(input);
  12960. };
  12961. };
  12962. },{"./lib/StringSource":108,"./lib/Token":109,"./lib/bottom-up":111,"./lib/errors":112,"./lib/parser":114,"./lib/parsing-results":115,"./lib/regex-tokeniser":116,"./lib/rules":117}],108:[function(require,module,exports){
  12963. var util = require("util");
  12964. var StringSource = module.exports = function(string, description) {
  12965. var self = {
  12966. asString: function() {
  12967. return string;
  12968. },
  12969. range: function(startIndex, endIndex) {
  12970. return new StringSourceRange(string, description, startIndex, endIndex);
  12971. }
  12972. };
  12973. return self;
  12974. };
  12975. var StringSourceRange = function(string, description, startIndex, endIndex) {
  12976. this._string = string;
  12977. this._description = description;
  12978. this._startIndex = startIndex;
  12979. this._endIndex = endIndex;
  12980. };
  12981. StringSourceRange.prototype.to = function(otherRange) {
  12982. // TODO: Assert that tokens are the same across both iterators
  12983. return new StringSourceRange(this._string, this._description, this._startIndex, otherRange._endIndex);
  12984. };
  12985. StringSourceRange.prototype.describe = function() {
  12986. var position = this._position();
  12987. var description = this._description ? this._description + "\n" : "";
  12988. return util.format("%sLine number: %s\nCharacter number: %s",
  12989. description, position.lineNumber, position.characterNumber);
  12990. };
  12991. StringSourceRange.prototype.lineNumber = function() {
  12992. return this._position().lineNumber;
  12993. };
  12994. StringSourceRange.prototype.characterNumber = function() {
  12995. return this._position().characterNumber;
  12996. };
  12997. StringSourceRange.prototype._position = function() {
  12998. var self = this;
  12999. var index = 0;
  13000. var nextNewLine = function() {
  13001. return self._string.indexOf("\n", index);
  13002. };
  13003. var lineNumber = 1;
  13004. while (nextNewLine() !== -1 && nextNewLine() < this._startIndex) {
  13005. index = nextNewLine() + 1;
  13006. lineNumber += 1;
  13007. }
  13008. var characterNumber = this._startIndex - index + 1;
  13009. return {lineNumber: lineNumber, characterNumber: characterNumber};
  13010. };
  13011. },{"util":157}],109:[function(require,module,exports){
  13012. module.exports = function(name, value, source) {
  13013. this.name = name;
  13014. this.value = value;
  13015. if (source) {
  13016. this.source = source;
  13017. }
  13018. };
  13019. },{}],110:[function(require,module,exports){
  13020. var TokenIterator = module.exports = function(tokens, startIndex) {
  13021. this._tokens = tokens;
  13022. this._startIndex = startIndex || 0;
  13023. };
  13024. TokenIterator.prototype.head = function() {
  13025. return this._tokens[this._startIndex];
  13026. };
  13027. TokenIterator.prototype.tail = function(startIndex) {
  13028. return new TokenIterator(this._tokens, this._startIndex + 1);
  13029. };
  13030. TokenIterator.prototype.toArray = function() {
  13031. return this._tokens.slice(this._startIndex);
  13032. };
  13033. TokenIterator.prototype.end = function() {
  13034. return this._tokens[this._tokens.length - 1];
  13035. };
  13036. // TODO: doesn't need to be a method, can be a separate function,
  13037. // which simplifies implementation of the TokenIterator interface
  13038. TokenIterator.prototype.to = function(end) {
  13039. var start = this.head().source;
  13040. var endToken = end.head() || end.end();
  13041. return start.to(endToken.source);
  13042. };
  13043. },{}],111:[function(require,module,exports){
  13044. var rules = require("./rules");
  13045. var results = require("./parsing-results");
  13046. exports.parser = function(name, prefixRules, infixRuleBuilders) {
  13047. var self = {
  13048. rule: rule,
  13049. leftAssociative: leftAssociative,
  13050. rightAssociative: rightAssociative
  13051. };
  13052. var infixRules = new InfixRules(infixRuleBuilders.map(createInfixRule));
  13053. var prefixRule = rules.firstOf(name, prefixRules);
  13054. function createInfixRule(infixRuleBuilder) {
  13055. return {
  13056. name: infixRuleBuilder.name,
  13057. rule: lazyRule(infixRuleBuilder.ruleBuilder.bind(null, self))
  13058. };
  13059. }
  13060. function rule() {
  13061. return createRule(infixRules);
  13062. }
  13063. function leftAssociative(name) {
  13064. return createRule(infixRules.untilExclusive(name));
  13065. }
  13066. function rightAssociative(name) {
  13067. return createRule(infixRules.untilInclusive(name));
  13068. }
  13069. function createRule(infixRules) {
  13070. return apply.bind(null, infixRules);
  13071. }
  13072. function apply(infixRules, tokens) {
  13073. var leftResult = prefixRule(tokens);
  13074. if (leftResult.isSuccess()) {
  13075. return infixRules.apply(leftResult);
  13076. } else {
  13077. return leftResult;
  13078. }
  13079. }
  13080. return self;
  13081. };
  13082. function InfixRules(infixRules) {
  13083. function untilExclusive(name) {
  13084. return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name)));
  13085. }
  13086. function untilInclusive(name) {
  13087. return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name) + 1));
  13088. }
  13089. function ruleNames() {
  13090. return infixRules.map(function(rule) {
  13091. return rule.name;
  13092. });
  13093. }
  13094. function apply(leftResult) {
  13095. var currentResult;
  13096. var source;
  13097. while (true) {
  13098. currentResult = applyToTokens(leftResult.remaining());
  13099. if (currentResult.isSuccess()) {
  13100. source = leftResult.source().to(currentResult.source());
  13101. leftResult = results.success(
  13102. currentResult.value()(leftResult.value(), source),
  13103. currentResult.remaining(),
  13104. source
  13105. )
  13106. } else if (currentResult.isFailure()) {
  13107. return leftResult;
  13108. } else {
  13109. return currentResult;
  13110. }
  13111. }
  13112. }
  13113. function applyToTokens(tokens) {
  13114. return rules.firstOf("infix", infixRules.map(function(infix) {
  13115. return infix.rule;
  13116. }))(tokens);
  13117. }
  13118. return {
  13119. apply: apply,
  13120. untilExclusive: untilExclusive,
  13121. untilInclusive: untilInclusive
  13122. }
  13123. }
  13124. exports.infix = function(name, ruleBuilder) {
  13125. function map(func) {
  13126. return exports.infix(name, function(parser) {
  13127. var rule = ruleBuilder(parser);
  13128. return function(tokens) {
  13129. var result = rule(tokens);
  13130. return result.map(function(right) {
  13131. return function(left, source) {
  13132. return func(left, right, source);
  13133. };
  13134. });
  13135. };
  13136. });
  13137. }
  13138. return {
  13139. name: name,
  13140. ruleBuilder: ruleBuilder,
  13141. map: map
  13142. };
  13143. }
  13144. // TODO: move into a sensible place and remove duplication
  13145. var lazyRule = function(ruleBuilder) {
  13146. var rule;
  13147. return function(input) {
  13148. if (!rule) {
  13149. rule = ruleBuilder();
  13150. }
  13151. return rule(input);
  13152. };
  13153. };
  13154. },{"./parsing-results":115,"./rules":117}],112:[function(require,module,exports){
  13155. exports.error = function(options) {
  13156. return new Error(options);
  13157. };
  13158. var Error = function(options) {
  13159. this.expected = options.expected;
  13160. this.actual = options.actual;
  13161. this._location = options.location;
  13162. };
  13163. Error.prototype.describe = function() {
  13164. var locationDescription = this._location ? this._location.describe() + ":\n" : "";
  13165. return locationDescription + "Expected " + this.expected + "\nbut got " + this.actual;
  13166. };
  13167. Error.prototype.lineNumber = function() {
  13168. return this._location.lineNumber();
  13169. };
  13170. Error.prototype.characterNumber = function() {
  13171. return this._location.characterNumber();
  13172. };
  13173. },{}],113:[function(require,module,exports){
  13174. var fromArray = exports.fromArray = function(array) {
  13175. var index = 0;
  13176. var hasNext = function() {
  13177. return index < array.length;
  13178. };
  13179. return new LazyIterator({
  13180. hasNext: hasNext,
  13181. next: function() {
  13182. if (!hasNext()) {
  13183. throw new Error("No more elements");
  13184. } else {
  13185. return array[index++];
  13186. }
  13187. }
  13188. });
  13189. };
  13190. var LazyIterator = function(iterator) {
  13191. this._iterator = iterator;
  13192. };
  13193. LazyIterator.prototype.map = function(func) {
  13194. var iterator = this._iterator;
  13195. return new LazyIterator({
  13196. hasNext: function() {
  13197. return iterator.hasNext();
  13198. },
  13199. next: function() {
  13200. return func(iterator.next());
  13201. }
  13202. });
  13203. };
  13204. LazyIterator.prototype.filter = function(condition) {
  13205. var iterator = this._iterator;
  13206. var moved = false;
  13207. var hasNext = false;
  13208. var next;
  13209. var moveIfNecessary = function() {
  13210. if (moved) {
  13211. return;
  13212. }
  13213. moved = true;
  13214. hasNext = false;
  13215. while (iterator.hasNext() && !hasNext) {
  13216. next = iterator.next();
  13217. hasNext = condition(next);
  13218. }
  13219. };
  13220. return new LazyIterator({
  13221. hasNext: function() {
  13222. moveIfNecessary();
  13223. return hasNext;
  13224. },
  13225. next: function() {
  13226. moveIfNecessary();
  13227. var toReturn = next;
  13228. moved = false;
  13229. return toReturn;
  13230. }
  13231. });
  13232. };
  13233. LazyIterator.prototype.first = function() {
  13234. var iterator = this._iterator;
  13235. if (this._iterator.hasNext()) {
  13236. return iterator.next();
  13237. } else {
  13238. return null;
  13239. }
  13240. };
  13241. LazyIterator.prototype.toArray = function() {
  13242. var result = [];
  13243. while (this._iterator.hasNext()) {
  13244. result.push(this._iterator.next());
  13245. }
  13246. return result;
  13247. };
  13248. },{}],114:[function(require,module,exports){
  13249. var TokenIterator = require("./TokenIterator");
  13250. exports.Parser = function(options) {
  13251. var parseTokens = function(parser, tokens) {
  13252. return parser(new TokenIterator(tokens));
  13253. };
  13254. return {
  13255. parseTokens: parseTokens
  13256. };
  13257. };
  13258. },{"./TokenIterator":110}],115:[function(require,module,exports){
  13259. module.exports = {
  13260. failure: function(errors, remaining) {
  13261. if (errors.length < 1) {
  13262. throw new Error("Failure must have errors");
  13263. }
  13264. return new Result({
  13265. status: "failure",
  13266. remaining: remaining,
  13267. errors: errors
  13268. });
  13269. },
  13270. error: function(errors, remaining) {
  13271. if (errors.length < 1) {
  13272. throw new Error("Failure must have errors");
  13273. }
  13274. return new Result({
  13275. status: "error",
  13276. remaining: remaining,
  13277. errors: errors
  13278. });
  13279. },
  13280. success: function(value, remaining, source) {
  13281. return new Result({
  13282. status: "success",
  13283. value: value,
  13284. source: source,
  13285. remaining: remaining,
  13286. errors: []
  13287. });
  13288. },
  13289. cut: function(remaining) {
  13290. return new Result({
  13291. status: "cut",
  13292. remaining: remaining,
  13293. errors: []
  13294. });
  13295. }
  13296. };
  13297. var Result = function(options) {
  13298. this._value = options.value;
  13299. this._status = options.status;
  13300. this._hasValue = options.value !== undefined;
  13301. this._remaining = options.remaining;
  13302. this._source = options.source;
  13303. this._errors = options.errors;
  13304. };
  13305. Result.prototype.map = function(func) {
  13306. if (this._hasValue) {
  13307. return new Result({
  13308. value: func(this._value, this._source),
  13309. status: this._status,
  13310. remaining: this._remaining,
  13311. source: this._source,
  13312. errors: this._errors
  13313. });
  13314. } else {
  13315. return this;
  13316. }
  13317. };
  13318. Result.prototype.changeRemaining = function(remaining) {
  13319. return new Result({
  13320. value: this._value,
  13321. status: this._status,
  13322. remaining: remaining,
  13323. source: this._source,
  13324. errors: this._errors
  13325. });
  13326. };
  13327. Result.prototype.isSuccess = function() {
  13328. return this._status === "success" || this._status === "cut";
  13329. };
  13330. Result.prototype.isFailure = function() {
  13331. return this._status === "failure";
  13332. };
  13333. Result.prototype.isError = function() {
  13334. return this._status === "error";
  13335. };
  13336. Result.prototype.isCut = function() {
  13337. return this._status === "cut";
  13338. };
  13339. Result.prototype.value = function() {
  13340. return this._value;
  13341. };
  13342. Result.prototype.remaining = function() {
  13343. return this._remaining;
  13344. };
  13345. Result.prototype.source = function() {
  13346. return this._source;
  13347. };
  13348. Result.prototype.errors = function() {
  13349. return this._errors;
  13350. };
  13351. },{}],116:[function(require,module,exports){
  13352. var Token = require("./Token");
  13353. var StringSource = require("./StringSource");
  13354. exports.RegexTokeniser = RegexTokeniser;
  13355. function RegexTokeniser(rules) {
  13356. rules = rules.map(function(rule) {
  13357. return {
  13358. name: rule.name,
  13359. regex: new RegExp(rule.regex.source, "g")
  13360. };
  13361. });
  13362. function tokenise(input, description) {
  13363. var source = new StringSource(input, description);
  13364. var index = 0;
  13365. var tokens = [];
  13366. while (index < input.length) {
  13367. var result = readNextToken(input, index, source);
  13368. index = result.endIndex;
  13369. tokens.push(result.token);
  13370. }
  13371. tokens.push(endToken(input, source));
  13372. return tokens;
  13373. }
  13374. function readNextToken(string, startIndex, source) {
  13375. for (var i = 0; i < rules.length; i++) {
  13376. var regex = rules[i].regex;
  13377. regex.lastIndex = startIndex;
  13378. var result = regex.exec(string);
  13379. if (result) {
  13380. var endIndex = startIndex + result[0].length;
  13381. if (result.index === startIndex && endIndex > startIndex) {
  13382. var value = result[1];
  13383. var token = new Token(
  13384. rules[i].name,
  13385. value,
  13386. source.range(startIndex, endIndex)
  13387. );
  13388. return {token: token, endIndex: endIndex};
  13389. }
  13390. }
  13391. }
  13392. var endIndex = startIndex + 1;
  13393. var token = new Token(
  13394. "unrecognisedCharacter",
  13395. string.substring(startIndex, endIndex),
  13396. source.range(startIndex, endIndex)
  13397. );
  13398. return {token: token, endIndex: endIndex};
  13399. }
  13400. function endToken(input, source) {
  13401. return new Token(
  13402. "end",
  13403. null,
  13404. source.range(input.length, input.length)
  13405. );
  13406. }
  13407. return {
  13408. tokenise: tokenise
  13409. }
  13410. }
  13411. },{"./StringSource":108,"./Token":109}],117:[function(require,module,exports){
  13412. var _ = require("underscore");
  13413. var options = require("option");
  13414. var results = require("./parsing-results");
  13415. var errors = require("./errors");
  13416. var lazyIterators = require("./lazy-iterators");
  13417. exports.token = function(tokenType, value) {
  13418. var matchValue = value !== undefined;
  13419. return function(input) {
  13420. var token = input.head();
  13421. if (token && token.name === tokenType && (!matchValue || token.value === value)) {
  13422. return results.success(token.value, input.tail(), token.source);
  13423. } else {
  13424. var expected = describeToken({name: tokenType, value: value});
  13425. return describeTokenMismatch(input, expected);
  13426. }
  13427. };
  13428. };
  13429. exports.tokenOfType = function(tokenType) {
  13430. return exports.token(tokenType);
  13431. };
  13432. exports.firstOf = function(name, parsers) {
  13433. if (!_.isArray(parsers)) {
  13434. parsers = Array.prototype.slice.call(arguments, 1);
  13435. }
  13436. return function(input) {
  13437. return lazyIterators
  13438. .fromArray(parsers)
  13439. .map(function(parser) {
  13440. return parser(input);
  13441. })
  13442. .filter(function(result) {
  13443. return result.isSuccess() || result.isError();
  13444. })
  13445. .first() || describeTokenMismatch(input, name);
  13446. };
  13447. };
  13448. exports.then = function(parser, func) {
  13449. return function(input) {
  13450. var result = parser(input);
  13451. if (!result.map) {
  13452. console.log(result);
  13453. }
  13454. return result.map(func);
  13455. };
  13456. };
  13457. exports.sequence = function() {
  13458. var parsers = Array.prototype.slice.call(arguments, 0);
  13459. var rule = function(input) {
  13460. var result = _.foldl(parsers, function(memo, parser) {
  13461. var result = memo.result;
  13462. var hasCut = memo.hasCut;
  13463. if (!result.isSuccess()) {
  13464. return {result: result, hasCut: hasCut};
  13465. }
  13466. var subResult = parser(result.remaining());
  13467. if (subResult.isCut()) {
  13468. return {result: result, hasCut: true};
  13469. } else if (subResult.isSuccess()) {
  13470. var values;
  13471. if (parser.isCaptured) {
  13472. values = result.value().withValue(parser, subResult.value());
  13473. } else {
  13474. values = result.value();
  13475. }
  13476. var remaining = subResult.remaining();
  13477. var source = input.to(remaining);
  13478. return {
  13479. result: results.success(values, remaining, source),
  13480. hasCut: hasCut
  13481. };
  13482. } else if (hasCut) {
  13483. return {result: results.error(subResult.errors(), subResult.remaining()), hasCut: hasCut};
  13484. } else {
  13485. return {result: subResult, hasCut: hasCut};
  13486. }
  13487. }, {result: results.success(new SequenceValues(), input), hasCut: false}).result;
  13488. var source = input.to(result.remaining());
  13489. return result.map(function(values) {
  13490. return values.withValue(exports.sequence.source, source);
  13491. });
  13492. };
  13493. rule.head = function() {
  13494. var firstCapture = _.find(parsers, isCapturedRule);
  13495. return exports.then(
  13496. rule,
  13497. exports.sequence.extract(firstCapture)
  13498. );
  13499. };
  13500. rule.map = function(func) {
  13501. return exports.then(
  13502. rule,
  13503. function(result) {
  13504. return func.apply(this, result.toArray());
  13505. }
  13506. );
  13507. };
  13508. function isCapturedRule(subRule) {
  13509. return subRule.isCaptured;
  13510. }
  13511. return rule;
  13512. };
  13513. var SequenceValues = function(values, valuesArray) {
  13514. this._values = values || {};
  13515. this._valuesArray = valuesArray || [];
  13516. };
  13517. SequenceValues.prototype.withValue = function(rule, value) {
  13518. if (rule.captureName && rule.captureName in this._values) {
  13519. throw new Error("Cannot add second value for capture \"" + rule.captureName + "\"");
  13520. } else {
  13521. var newValues = _.clone(this._values);
  13522. newValues[rule.captureName] = value;
  13523. var newValuesArray = this._valuesArray.concat([value]);
  13524. return new SequenceValues(newValues, newValuesArray);
  13525. }
  13526. };
  13527. SequenceValues.prototype.get = function(rule) {
  13528. if (rule.captureName in this._values) {
  13529. return this._values[rule.captureName];
  13530. } else {
  13531. throw new Error("No value for capture \"" + rule.captureName + "\"");
  13532. }
  13533. };
  13534. SequenceValues.prototype.toArray = function() {
  13535. return this._valuesArray;
  13536. };
  13537. exports.sequence.capture = function(rule, name) {
  13538. var captureRule = function() {
  13539. return rule.apply(this, arguments);
  13540. };
  13541. captureRule.captureName = name;
  13542. captureRule.isCaptured = true;
  13543. return captureRule;
  13544. };
  13545. exports.sequence.extract = function(rule) {
  13546. return function(result) {
  13547. return result.get(rule);
  13548. };
  13549. };
  13550. exports.sequence.applyValues = function(func) {
  13551. // TODO: check captureName doesn't conflict with source or other captures
  13552. var rules = Array.prototype.slice.call(arguments, 1);
  13553. return function(result) {
  13554. var values = rules.map(function(rule) {
  13555. return result.get(rule);
  13556. });
  13557. return func.apply(this, values);
  13558. };
  13559. };
  13560. exports.sequence.source = {
  13561. captureName: "☃source☃"
  13562. };
  13563. exports.sequence.cut = function() {
  13564. return function(input) {
  13565. return results.cut(input);
  13566. };
  13567. };
  13568. exports.optional = function(rule) {
  13569. return function(input) {
  13570. var result = rule(input);
  13571. if (result.isSuccess()) {
  13572. return result.map(options.some);
  13573. } else if (result.isFailure()) {
  13574. return results.success(options.none, input);
  13575. } else {
  13576. return result;
  13577. }
  13578. };
  13579. };
  13580. exports.zeroOrMoreWithSeparator = function(rule, separator) {
  13581. return repeatedWithSeparator(rule, separator, false);
  13582. };
  13583. exports.oneOrMoreWithSeparator = function(rule, separator) {
  13584. return repeatedWithSeparator(rule, separator, true);
  13585. };
  13586. var zeroOrMore = exports.zeroOrMore = function(rule) {
  13587. return function(input) {
  13588. var values = [];
  13589. var result;
  13590. while ((result = rule(input)) && result.isSuccess()) {
  13591. input = result.remaining();
  13592. values.push(result.value());
  13593. }
  13594. if (result.isError()) {
  13595. return result;
  13596. } else {
  13597. return results.success(values, input);
  13598. }
  13599. };
  13600. };
  13601. exports.oneOrMore = function(rule) {
  13602. return exports.oneOrMoreWithSeparator(rule, noOpRule);
  13603. };
  13604. function noOpRule(input) {
  13605. return results.success(null, input);
  13606. }
  13607. var repeatedWithSeparator = function(rule, separator, isOneOrMore) {
  13608. return function(input) {
  13609. var result = rule(input);
  13610. if (result.isSuccess()) {
  13611. var mainRule = exports.sequence.capture(rule, "main");
  13612. var remainingRule = zeroOrMore(exports.then(
  13613. exports.sequence(separator, mainRule),
  13614. exports.sequence.extract(mainRule)
  13615. ));
  13616. var remainingResult = remainingRule(result.remaining());
  13617. return results.success([result.value()].concat(remainingResult.value()), remainingResult.remaining());
  13618. } else if (isOneOrMore || result.isError()) {
  13619. return result;
  13620. } else {
  13621. return results.success([], input);
  13622. }
  13623. };
  13624. };
  13625. exports.leftAssociative = function(leftRule, rightRule, func) {
  13626. var rights;
  13627. if (func) {
  13628. rights = [{func: func, rule: rightRule}];
  13629. } else {
  13630. rights = rightRule;
  13631. }
  13632. rights = rights.map(function(right) {
  13633. return exports.then(right.rule, function(rightValue) {
  13634. return function(leftValue, source) {
  13635. return right.func(leftValue, rightValue, source);
  13636. };
  13637. });
  13638. });
  13639. var repeatedRule = exports.firstOf.apply(null, ["rules"].concat(rights));
  13640. return function(input) {
  13641. var start = input;
  13642. var leftResult = leftRule(input);
  13643. if (!leftResult.isSuccess()) {
  13644. return leftResult;
  13645. }
  13646. var repeatedResult = repeatedRule(leftResult.remaining());
  13647. while (repeatedResult.isSuccess()) {
  13648. var remaining = repeatedResult.remaining();
  13649. var source = start.to(repeatedResult.remaining());
  13650. var right = repeatedResult.value();
  13651. leftResult = results.success(
  13652. right(leftResult.value(), source),
  13653. remaining,
  13654. source
  13655. );
  13656. repeatedResult = repeatedRule(leftResult.remaining());
  13657. }
  13658. if (repeatedResult.isError()) {
  13659. return repeatedResult;
  13660. }
  13661. return leftResult;
  13662. };
  13663. };
  13664. exports.leftAssociative.firstOf = function() {
  13665. return Array.prototype.slice.call(arguments, 0);
  13666. };
  13667. exports.nonConsuming = function(rule) {
  13668. return function(input) {
  13669. return rule(input).changeRemaining(input);
  13670. };
  13671. };
  13672. var describeToken = function(token) {
  13673. if (token.value) {
  13674. return token.name + " \"" + token.value + "\"";
  13675. } else {
  13676. return token.name;
  13677. }
  13678. };
  13679. function describeTokenMismatch(input, expected) {
  13680. var error;
  13681. var token = input.head();
  13682. if (token) {
  13683. error = errors.error({
  13684. expected: expected,
  13685. actual: describeToken(token),
  13686. location: token.source
  13687. });
  13688. } else {
  13689. error = errors.error({
  13690. expected: expected,
  13691. actual: "end of tokens"
  13692. });
  13693. }
  13694. return results.failure([error], input);
  13695. }
  13696. },{"./errors":112,"./lazy-iterators":113,"./parsing-results":115,"option":119,"underscore":118}],118:[function(require,module,exports){
  13697. // Underscore.js 1.4.4
  13698. // http://underscorejs.org
  13699. // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
  13700. // Underscore may be freely distributed under the MIT license.
  13701. (function() {
  13702. // Baseline setup
  13703. // --------------
  13704. // Establish the root object, `window` in the browser, or `global` on the server.
  13705. var root = this;
  13706. // Save the previous value of the `_` variable.
  13707. var previousUnderscore = root._;
  13708. // Establish the object that gets returned to break out of a loop iteration.
  13709. var breaker = {};
  13710. // Save bytes in the minified (but not gzipped) version:
  13711. var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  13712. // Create quick reference variables for speed access to core prototypes.
  13713. var push = ArrayProto.push,
  13714. slice = ArrayProto.slice,
  13715. concat = ArrayProto.concat,
  13716. toString = ObjProto.toString,
  13717. hasOwnProperty = ObjProto.hasOwnProperty;
  13718. // All **ECMAScript 5** native function implementations that we hope to use
  13719. // are declared here.
  13720. var
  13721. nativeForEach = ArrayProto.forEach,
  13722. nativeMap = ArrayProto.map,
  13723. nativeReduce = ArrayProto.reduce,
  13724. nativeReduceRight = ArrayProto.reduceRight,
  13725. nativeFilter = ArrayProto.filter,
  13726. nativeEvery = ArrayProto.every,
  13727. nativeSome = ArrayProto.some,
  13728. nativeIndexOf = ArrayProto.indexOf,
  13729. nativeLastIndexOf = ArrayProto.lastIndexOf,
  13730. nativeIsArray = Array.isArray,
  13731. nativeKeys = Object.keys,
  13732. nativeBind = FuncProto.bind;
  13733. // Create a safe reference to the Underscore object for use below.
  13734. var _ = function(obj) {
  13735. if (obj instanceof _) return obj;
  13736. if (!(this instanceof _)) return new _(obj);
  13737. this._wrapped = obj;
  13738. };
  13739. // Export the Underscore object for **Node.js**, with
  13740. // backwards-compatibility for the old `require()` API. If we're in
  13741. // the browser, add `_` as a global object via a string identifier,
  13742. // for Closure Compiler "advanced" mode.
  13743. if (typeof exports !== 'undefined') {
  13744. if (typeof module !== 'undefined' && module.exports) {
  13745. exports = module.exports = _;
  13746. }
  13747. exports._ = _;
  13748. } else {
  13749. root._ = _;
  13750. }
  13751. // Current version.
  13752. _.VERSION = '1.4.4';
  13753. // Collection Functions
  13754. // --------------------
  13755. // The cornerstone, an `each` implementation, aka `forEach`.
  13756. // Handles objects with the built-in `forEach`, arrays, and raw objects.
  13757. // Delegates to **ECMAScript 5**'s native `forEach` if available.
  13758. var each = _.each = _.forEach = function(obj, iterator, context) {
  13759. if (obj == null) return;
  13760. if (nativeForEach && obj.forEach === nativeForEach) {
  13761. obj.forEach(iterator, context);
  13762. } else if (obj.length === +obj.length) {
  13763. for (var i = 0, l = obj.length; i < l; i++) {
  13764. if (iterator.call(context, obj[i], i, obj) === breaker) return;
  13765. }
  13766. } else {
  13767. for (var key in obj) {
  13768. if (_.has(obj, key)) {
  13769. if (iterator.call(context, obj[key], key, obj) === breaker) return;
  13770. }
  13771. }
  13772. }
  13773. };
  13774. // Return the results of applying the iterator to each element.
  13775. // Delegates to **ECMAScript 5**'s native `map` if available.
  13776. _.map = _.collect = function(obj, iterator, context) {
  13777. var results = [];
  13778. if (obj == null) return results;
  13779. if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
  13780. each(obj, function(value, index, list) {
  13781. results[results.length] = iterator.call(context, value, index, list);
  13782. });
  13783. return results;
  13784. };
  13785. var reduceError = 'Reduce of empty array with no initial value';
  13786. // **Reduce** builds up a single result from a list of values, aka `inject`,
  13787. // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  13788. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
  13789. var initial = arguments.length > 2;
  13790. if (obj == null) obj = [];
  13791. if (nativeReduce && obj.reduce === nativeReduce) {
  13792. if (context) iterator = _.bind(iterator, context);
  13793. return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
  13794. }
  13795. each(obj, function(value, index, list) {
  13796. if (!initial) {
  13797. memo = value;
  13798. initial = true;
  13799. } else {
  13800. memo = iterator.call(context, memo, value, index, list);
  13801. }
  13802. });
  13803. if (!initial) throw new TypeError(reduceError);
  13804. return memo;
  13805. };
  13806. // The right-associative version of reduce, also known as `foldr`.
  13807. // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  13808. _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
  13809. var initial = arguments.length > 2;
  13810. if (obj == null) obj = [];
  13811. if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
  13812. if (context) iterator = _.bind(iterator, context);
  13813. return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
  13814. }
  13815. var length = obj.length;
  13816. if (length !== +length) {
  13817. var keys = _.keys(obj);
  13818. length = keys.length;
  13819. }
  13820. each(obj, function(value, index, list) {
  13821. index = keys ? keys[--length] : --length;
  13822. if (!initial) {
  13823. memo = obj[index];
  13824. initial = true;
  13825. } else {
  13826. memo = iterator.call(context, memo, obj[index], index, list);
  13827. }
  13828. });
  13829. if (!initial) throw new TypeError(reduceError);
  13830. return memo;
  13831. };
  13832. // Return the first value which passes a truth test. Aliased as `detect`.
  13833. _.find = _.detect = function(obj, iterator, context) {
  13834. var result;
  13835. any(obj, function(value, index, list) {
  13836. if (iterator.call(context, value, index, list)) {
  13837. result = value;
  13838. return true;
  13839. }
  13840. });
  13841. return result;
  13842. };
  13843. // Return all the elements that pass a truth test.
  13844. // Delegates to **ECMAScript 5**'s native `filter` if available.
  13845. // Aliased as `select`.
  13846. _.filter = _.select = function(obj, iterator, context) {
  13847. var results = [];
  13848. if (obj == null) return results;
  13849. if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  13850. each(obj, function(value, index, list) {
  13851. if (iterator.call(context, value, index, list)) results[results.length] = value;
  13852. });
  13853. return results;
  13854. };
  13855. // Return all the elements for which a truth test fails.
  13856. _.reject = function(obj, iterator, context) {
  13857. return _.filter(obj, function(value, index, list) {
  13858. return !iterator.call(context, value, index, list);
  13859. }, context);
  13860. };
  13861. // Determine whether all of the elements match a truth test.
  13862. // Delegates to **ECMAScript 5**'s native `every` if available.
  13863. // Aliased as `all`.
  13864. _.every = _.all = function(obj, iterator, context) {
  13865. iterator || (iterator = _.identity);
  13866. var result = true;
  13867. if (obj == null) return result;
  13868. if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
  13869. each(obj, function(value, index, list) {
  13870. if (!(result = result && iterator.call(context, value, index, list))) return breaker;
  13871. });
  13872. return !!result;
  13873. };
  13874. // Determine if at least one element in the object matches a truth test.
  13875. // Delegates to **ECMAScript 5**'s native `some` if available.
  13876. // Aliased as `any`.
  13877. var any = _.some = _.any = function(obj, iterator, context) {
  13878. iterator || (iterator = _.identity);
  13879. var result = false;
  13880. if (obj == null) return result;
  13881. if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
  13882. each(obj, function(value, index, list) {
  13883. if (result || (result = iterator.call(context, value, index, list))) return breaker;
  13884. });
  13885. return !!result;
  13886. };
  13887. // Determine if the array or object contains a given value (using `===`).
  13888. // Aliased as `include`.
  13889. _.contains = _.include = function(obj, target) {
  13890. if (obj == null) return false;
  13891. if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
  13892. return any(obj, function(value) {
  13893. return value === target;
  13894. });
  13895. };
  13896. // Invoke a method (with arguments) on every item in a collection.
  13897. _.invoke = function(obj, method) {
  13898. var args = slice.call(arguments, 2);
  13899. var isFunc = _.isFunction(method);
  13900. return _.map(obj, function(value) {
  13901. return (isFunc ? method : value[method]).apply(value, args);
  13902. });
  13903. };
  13904. // Convenience version of a common use case of `map`: fetching a property.
  13905. _.pluck = function(obj, key) {
  13906. return _.map(obj, function(value){ return value[key]; });
  13907. };
  13908. // Convenience version of a common use case of `filter`: selecting only objects
  13909. // containing specific `key:value` pairs.
  13910. _.where = function(obj, attrs, first) {
  13911. if (_.isEmpty(attrs)) return first ? null : [];
  13912. return _[first ? 'find' : 'filter'](obj, function(value) {
  13913. for (var key in attrs) {
  13914. if (attrs[key] !== value[key]) return false;
  13915. }
  13916. return true;
  13917. });
  13918. };
  13919. // Convenience version of a common use case of `find`: getting the first object
  13920. // containing specific `key:value` pairs.
  13921. _.findWhere = function(obj, attrs) {
  13922. return _.where(obj, attrs, true);
  13923. };
  13924. // Return the maximum element or (element-based computation).
  13925. // Can't optimize arrays of integers longer than 65,535 elements.
  13926. // See: https://bugs.webkit.org/show_bug.cgi?id=80797
  13927. _.max = function(obj, iterator, context) {
  13928. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  13929. return Math.max.apply(Math, obj);
  13930. }
  13931. if (!iterator && _.isEmpty(obj)) return -Infinity;
  13932. var result = {computed : -Infinity, value: -Infinity};
  13933. each(obj, function(value, index, list) {
  13934. var computed = iterator ? iterator.call(context, value, index, list) : value;
  13935. computed >= result.computed && (result = {value : value, computed : computed});
  13936. });
  13937. return result.value;
  13938. };
  13939. // Return the minimum element (or element-based computation).
  13940. _.min = function(obj, iterator, context) {
  13941. if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
  13942. return Math.min.apply(Math, obj);
  13943. }
  13944. if (!iterator && _.isEmpty(obj)) return Infinity;
  13945. var result = {computed : Infinity, value: Infinity};
  13946. each(obj, function(value, index, list) {
  13947. var computed = iterator ? iterator.call(context, value, index, list) : value;
  13948. computed < result.computed && (result = {value : value, computed : computed});
  13949. });
  13950. return result.value;
  13951. };
  13952. // Shuffle an array.
  13953. _.shuffle = function(obj) {
  13954. var rand;
  13955. var index = 0;
  13956. var shuffled = [];
  13957. each(obj, function(value) {
  13958. rand = _.random(index++);
  13959. shuffled[index - 1] = shuffled[rand];
  13960. shuffled[rand] = value;
  13961. });
  13962. return shuffled;
  13963. };
  13964. // An internal function to generate lookup iterators.
  13965. var lookupIterator = function(value) {
  13966. return _.isFunction(value) ? value : function(obj){ return obj[value]; };
  13967. };
  13968. // Sort the object's values by a criterion produced by an iterator.
  13969. _.sortBy = function(obj, value, context) {
  13970. var iterator = lookupIterator(value);
  13971. return _.pluck(_.map(obj, function(value, index, list) {
  13972. return {
  13973. value : value,
  13974. index : index,
  13975. criteria : iterator.call(context, value, index, list)
  13976. };
  13977. }).sort(function(left, right) {
  13978. var a = left.criteria;
  13979. var b = right.criteria;
  13980. if (a !== b) {
  13981. if (a > b || a === void 0) return 1;
  13982. if (a < b || b === void 0) return -1;
  13983. }
  13984. return left.index < right.index ? -1 : 1;
  13985. }), 'value');
  13986. };
  13987. // An internal function used for aggregate "group by" operations.
  13988. var group = function(obj, value, context, behavior) {
  13989. var result = {};
  13990. var iterator = lookupIterator(value || _.identity);
  13991. each(obj, function(value, index) {
  13992. var key = iterator.call(context, value, index, obj);
  13993. behavior(result, key, value);
  13994. });
  13995. return result;
  13996. };
  13997. // Groups the object's values by a criterion. Pass either a string attribute
  13998. // to group by, or a function that returns the criterion.
  13999. _.groupBy = function(obj, value, context) {
  14000. return group(obj, value, context, function(result, key, value) {
  14001. (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
  14002. });
  14003. };
  14004. // Counts instances of an object that group by a certain criterion. Pass
  14005. // either a string attribute to count by, or a function that returns the
  14006. // criterion.
  14007. _.countBy = function(obj, value, context) {
  14008. return group(obj, value, context, function(result, key) {
  14009. if (!_.has(result, key)) result[key] = 0;
  14010. result[key]++;
  14011. });
  14012. };
  14013. // Use a comparator function to figure out the smallest index at which
  14014. // an object should be inserted so as to maintain order. Uses binary search.
  14015. _.sortedIndex = function(array, obj, iterator, context) {
  14016. iterator = iterator == null ? _.identity : lookupIterator(iterator);
  14017. var value = iterator.call(context, obj);
  14018. var low = 0, high = array.length;
  14019. while (low < high) {
  14020. var mid = (low + high) >>> 1;
  14021. iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
  14022. }
  14023. return low;
  14024. };
  14025. // Safely convert anything iterable into a real, live array.
  14026. _.toArray = function(obj) {
  14027. if (!obj) return [];
  14028. if (_.isArray(obj)) return slice.call(obj);
  14029. if (obj.length === +obj.length) return _.map(obj, _.identity);
  14030. return _.values(obj);
  14031. };
  14032. // Return the number of elements in an object.
  14033. _.size = function(obj) {
  14034. if (obj == null) return 0;
  14035. return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
  14036. };
  14037. // Array Functions
  14038. // ---------------
  14039. // Get the first element of an array. Passing **n** will return the first N
  14040. // values in the array. Aliased as `head` and `take`. The **guard** check
  14041. // allows it to work with `_.map`.
  14042. _.first = _.head = _.take = function(array, n, guard) {
  14043. if (array == null) return void 0;
  14044. return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  14045. };
  14046. // Returns everything but the last entry of the array. Especially useful on
  14047. // the arguments object. Passing **n** will return all the values in
  14048. // the array, excluding the last N. The **guard** check allows it to work with
  14049. // `_.map`.
  14050. _.initial = function(array, n, guard) {
  14051. return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  14052. };
  14053. // Get the last element of an array. Passing **n** will return the last N
  14054. // values in the array. The **guard** check allows it to work with `_.map`.
  14055. _.last = function(array, n, guard) {
  14056. if (array == null) return void 0;
  14057. if ((n != null) && !guard) {
  14058. return slice.call(array, Math.max(array.length - n, 0));
  14059. } else {
  14060. return array[array.length - 1];
  14061. }
  14062. };
  14063. // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  14064. // Especially useful on the arguments object. Passing an **n** will return
  14065. // the rest N values in the array. The **guard**
  14066. // check allows it to work with `_.map`.
  14067. _.rest = _.tail = _.drop = function(array, n, guard) {
  14068. return slice.call(array, (n == null) || guard ? 1 : n);
  14069. };
  14070. // Trim out all falsy values from an array.
  14071. _.compact = function(array) {
  14072. return _.filter(array, _.identity);
  14073. };
  14074. // Internal implementation of a recursive `flatten` function.
  14075. var flatten = function(input, shallow, output) {
  14076. each(input, function(value) {
  14077. if (_.isArray(value)) {
  14078. shallow ? push.apply(output, value) : flatten(value, shallow, output);
  14079. } else {
  14080. output.push(value);
  14081. }
  14082. });
  14083. return output;
  14084. };
  14085. // Return a completely flattened version of an array.
  14086. _.flatten = function(array, shallow) {
  14087. return flatten(array, shallow, []);
  14088. };
  14089. // Return a version of the array that does not contain the specified value(s).
  14090. _.without = function(array) {
  14091. return _.difference(array, slice.call(arguments, 1));
  14092. };
  14093. // Produce a duplicate-free version of the array. If the array has already
  14094. // been sorted, you have the option of using a faster algorithm.
  14095. // Aliased as `unique`.
  14096. _.uniq = _.unique = function(array, isSorted, iterator, context) {
  14097. if (_.isFunction(isSorted)) {
  14098. context = iterator;
  14099. iterator = isSorted;
  14100. isSorted = false;
  14101. }
  14102. var initial = iterator ? _.map(array, iterator, context) : array;
  14103. var results = [];
  14104. var seen = [];
  14105. each(initial, function(value, index) {
  14106. if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
  14107. seen.push(value);
  14108. results.push(array[index]);
  14109. }
  14110. });
  14111. return results;
  14112. };
  14113. // Produce an array that contains the union: each distinct element from all of
  14114. // the passed-in arrays.
  14115. _.union = function() {
  14116. return _.uniq(concat.apply(ArrayProto, arguments));
  14117. };
  14118. // Produce an array that contains every item shared between all the
  14119. // passed-in arrays.
  14120. _.intersection = function(array) {
  14121. var rest = slice.call(arguments, 1);
  14122. return _.filter(_.uniq(array), function(item) {
  14123. return _.every(rest, function(other) {
  14124. return _.indexOf(other, item) >= 0;
  14125. });
  14126. });
  14127. };
  14128. // Take the difference between one array and a number of other arrays.
  14129. // Only the elements present in just the first array will remain.
  14130. _.difference = function(array) {
  14131. var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
  14132. return _.filter(array, function(value){ return !_.contains(rest, value); });
  14133. };
  14134. // Zip together multiple lists into a single array -- elements that share
  14135. // an index go together.
  14136. _.zip = function() {
  14137. var args = slice.call(arguments);
  14138. var length = _.max(_.pluck(args, 'length'));
  14139. var results = new Array(length);
  14140. for (var i = 0; i < length; i++) {
  14141. results[i] = _.pluck(args, "" + i);
  14142. }
  14143. return results;
  14144. };
  14145. // Converts lists into objects. Pass either a single array of `[key, value]`
  14146. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  14147. // the corresponding values.
  14148. _.object = function(list, values) {
  14149. if (list == null) return {};
  14150. var result = {};
  14151. for (var i = 0, l = list.length; i < l; i++) {
  14152. if (values) {
  14153. result[list[i]] = values[i];
  14154. } else {
  14155. result[list[i][0]] = list[i][1];
  14156. }
  14157. }
  14158. return result;
  14159. };
  14160. // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  14161. // we need this function. Return the position of the first occurrence of an
  14162. // item in an array, or -1 if the item is not included in the array.
  14163. // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  14164. // If the array is large and already in sort order, pass `true`
  14165. // for **isSorted** to use binary search.
  14166. _.indexOf = function(array, item, isSorted) {
  14167. if (array == null) return -1;
  14168. var i = 0, l = array.length;
  14169. if (isSorted) {
  14170. if (typeof isSorted == 'number') {
  14171. i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
  14172. } else {
  14173. i = _.sortedIndex(array, item);
  14174. return array[i] === item ? i : -1;
  14175. }
  14176. }
  14177. if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
  14178. for (; i < l; i++) if (array[i] === item) return i;
  14179. return -1;
  14180. };
  14181. // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  14182. _.lastIndexOf = function(array, item, from) {
  14183. if (array == null) return -1;
  14184. var hasIndex = from != null;
  14185. if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
  14186. return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
  14187. }
  14188. var i = (hasIndex ? from : array.length);
  14189. while (i--) if (array[i] === item) return i;
  14190. return -1;
  14191. };
  14192. // Generate an integer Array containing an arithmetic progression. A port of
  14193. // the native Python `range()` function. See
  14194. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  14195. _.range = function(start, stop, step) {
  14196. if (arguments.length <= 1) {
  14197. stop = start || 0;
  14198. start = 0;
  14199. }
  14200. step = arguments[2] || 1;
  14201. var len = Math.max(Math.ceil((stop - start) / step), 0);
  14202. var idx = 0;
  14203. var range = new Array(len);
  14204. while(idx < len) {
  14205. range[idx++] = start;
  14206. start += step;
  14207. }
  14208. return range;
  14209. };
  14210. // Function (ahem) Functions
  14211. // ------------------
  14212. // Create a function bound to a given object (assigning `this`, and arguments,
  14213. // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  14214. // available.
  14215. _.bind = function(func, context) {
  14216. if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  14217. var args = slice.call(arguments, 2);
  14218. return function() {
  14219. return func.apply(context, args.concat(slice.call(arguments)));
  14220. };
  14221. };
  14222. // Partially apply a function by creating a version that has had some of its
  14223. // arguments pre-filled, without changing its dynamic `this` context.
  14224. _.partial = function(func) {
  14225. var args = slice.call(arguments, 1);
  14226. return function() {
  14227. return func.apply(this, args.concat(slice.call(arguments)));
  14228. };
  14229. };
  14230. // Bind all of an object's methods to that object. Useful for ensuring that
  14231. // all callbacks defined on an object belong to it.
  14232. _.bindAll = function(obj) {
  14233. var funcs = slice.call(arguments, 1);
  14234. if (funcs.length === 0) funcs = _.functions(obj);
  14235. each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
  14236. return obj;
  14237. };
  14238. // Memoize an expensive function by storing its results.
  14239. _.memoize = function(func, hasher) {
  14240. var memo = {};
  14241. hasher || (hasher = _.identity);
  14242. return function() {
  14243. var key = hasher.apply(this, arguments);
  14244. return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
  14245. };
  14246. };
  14247. // Delays a function for the given number of milliseconds, and then calls
  14248. // it with the arguments supplied.
  14249. _.delay = function(func, wait) {
  14250. var args = slice.call(arguments, 2);
  14251. return setTimeout(function(){ return func.apply(null, args); }, wait);
  14252. };
  14253. // Defers a function, scheduling it to run after the current call stack has
  14254. // cleared.
  14255. _.defer = function(func) {
  14256. return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  14257. };
  14258. // Returns a function, that, when invoked, will only be triggered at most once
  14259. // during a given window of time.
  14260. _.throttle = function(func, wait) {
  14261. var context, args, timeout, result;
  14262. var previous = 0;
  14263. var later = function() {
  14264. previous = new Date;
  14265. timeout = null;
  14266. result = func.apply(context, args);
  14267. };
  14268. return function() {
  14269. var now = new Date;
  14270. var remaining = wait - (now - previous);
  14271. context = this;
  14272. args = arguments;
  14273. if (remaining <= 0) {
  14274. clearTimeout(timeout);
  14275. timeout = null;
  14276. previous = now;
  14277. result = func.apply(context, args);
  14278. } else if (!timeout) {
  14279. timeout = setTimeout(later, remaining);
  14280. }
  14281. return result;
  14282. };
  14283. };
  14284. // Returns a function, that, as long as it continues to be invoked, will not
  14285. // be triggered. The function will be called after it stops being called for
  14286. // N milliseconds. If `immediate` is passed, trigger the function on the
  14287. // leading edge, instead of the trailing.
  14288. _.debounce = function(func, wait, immediate) {
  14289. var timeout, result;
  14290. return function() {
  14291. var context = this, args = arguments;
  14292. var later = function() {
  14293. timeout = null;
  14294. if (!immediate) result = func.apply(context, args);
  14295. };
  14296. var callNow = immediate && !timeout;
  14297. clearTimeout(timeout);
  14298. timeout = setTimeout(later, wait);
  14299. if (callNow) result = func.apply(context, args);
  14300. return result;
  14301. };
  14302. };
  14303. // Returns a function that will be executed at most one time, no matter how
  14304. // often you call it. Useful for lazy initialization.
  14305. _.once = function(func) {
  14306. var ran = false, memo;
  14307. return function() {
  14308. if (ran) return memo;
  14309. ran = true;
  14310. memo = func.apply(this, arguments);
  14311. func = null;
  14312. return memo;
  14313. };
  14314. };
  14315. // Returns the first function passed as an argument to the second,
  14316. // allowing you to adjust arguments, run code before and after, and
  14317. // conditionally execute the original function.
  14318. _.wrap = function(func, wrapper) {
  14319. return function() {
  14320. var args = [func];
  14321. push.apply(args, arguments);
  14322. return wrapper.apply(this, args);
  14323. };
  14324. };
  14325. // Returns a function that is the composition of a list of functions, each
  14326. // consuming the return value of the function that follows.
  14327. _.compose = function() {
  14328. var funcs = arguments;
  14329. return function() {
  14330. var args = arguments;
  14331. for (var i = funcs.length - 1; i >= 0; i--) {
  14332. args = [funcs[i].apply(this, args)];
  14333. }
  14334. return args[0];
  14335. };
  14336. };
  14337. // Returns a function that will only be executed after being called N times.
  14338. _.after = function(times, func) {
  14339. if (times <= 0) return func();
  14340. return function() {
  14341. if (--times < 1) {
  14342. return func.apply(this, arguments);
  14343. }
  14344. };
  14345. };
  14346. // Object Functions
  14347. // ----------------
  14348. // Retrieve the names of an object's properties.
  14349. // Delegates to **ECMAScript 5**'s native `Object.keys`
  14350. _.keys = nativeKeys || function(obj) {
  14351. if (obj !== Object(obj)) throw new TypeError('Invalid object');
  14352. var keys = [];
  14353. for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
  14354. return keys;
  14355. };
  14356. // Retrieve the values of an object's properties.
  14357. _.values = function(obj) {
  14358. var values = [];
  14359. for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
  14360. return values;
  14361. };
  14362. // Convert an object into a list of `[key, value]` pairs.
  14363. _.pairs = function(obj) {
  14364. var pairs = [];
  14365. for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
  14366. return pairs;
  14367. };
  14368. // Invert the keys and values of an object. The values must be serializable.
  14369. _.invert = function(obj) {
  14370. var result = {};
  14371. for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
  14372. return result;
  14373. };
  14374. // Return a sorted list of the function names available on the object.
  14375. // Aliased as `methods`
  14376. _.functions = _.methods = function(obj) {
  14377. var names = [];
  14378. for (var key in obj) {
  14379. if (_.isFunction(obj[key])) names.push(key);
  14380. }
  14381. return names.sort();
  14382. };
  14383. // Extend a given object with all the properties in passed-in object(s).
  14384. _.extend = function(obj) {
  14385. each(slice.call(arguments, 1), function(source) {
  14386. if (source) {
  14387. for (var prop in source) {
  14388. obj[prop] = source[prop];
  14389. }
  14390. }
  14391. });
  14392. return obj;
  14393. };
  14394. // Return a copy of the object only containing the whitelisted properties.
  14395. _.pick = function(obj) {
  14396. var copy = {};
  14397. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  14398. each(keys, function(key) {
  14399. if (key in obj) copy[key] = obj[key];
  14400. });
  14401. return copy;
  14402. };
  14403. // Return a copy of the object without the blacklisted properties.
  14404. _.omit = function(obj) {
  14405. var copy = {};
  14406. var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
  14407. for (var key in obj) {
  14408. if (!_.contains(keys, key)) copy[key] = obj[key];
  14409. }
  14410. return copy;
  14411. };
  14412. // Fill in a given object with default properties.
  14413. _.defaults = function(obj) {
  14414. each(slice.call(arguments, 1), function(source) {
  14415. if (source) {
  14416. for (var prop in source) {
  14417. if (obj[prop] == null) obj[prop] = source[prop];
  14418. }
  14419. }
  14420. });
  14421. return obj;
  14422. };
  14423. // Create a (shallow-cloned) duplicate of an object.
  14424. _.clone = function(obj) {
  14425. if (!_.isObject(obj)) return obj;
  14426. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  14427. };
  14428. // Invokes interceptor with the obj, and then returns obj.
  14429. // The primary purpose of this method is to "tap into" a method chain, in
  14430. // order to perform operations on intermediate results within the chain.
  14431. _.tap = function(obj, interceptor) {
  14432. interceptor(obj);
  14433. return obj;
  14434. };
  14435. // Internal recursive comparison function for `isEqual`.
  14436. var eq = function(a, b, aStack, bStack) {
  14437. // Identical objects are equal. `0 === -0`, but they aren't identical.
  14438. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
  14439. if (a === b) return a !== 0 || 1 / a == 1 / b;
  14440. // A strict comparison is necessary because `null == undefined`.
  14441. if (a == null || b == null) return a === b;
  14442. // Unwrap any wrapped objects.
  14443. if (a instanceof _) a = a._wrapped;
  14444. if (b instanceof _) b = b._wrapped;
  14445. // Compare `[[Class]]` names.
  14446. var className = toString.call(a);
  14447. if (className != toString.call(b)) return false;
  14448. switch (className) {
  14449. // Strings, numbers, dates, and booleans are compared by value.
  14450. case '[object String]':
  14451. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  14452. // equivalent to `new String("5")`.
  14453. return a == String(b);
  14454. case '[object Number]':
  14455. // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
  14456. // other numeric values.
  14457. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
  14458. case '[object Date]':
  14459. case '[object Boolean]':
  14460. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  14461. // millisecond representations. Note that invalid dates with millisecond representations
  14462. // of `NaN` are not equivalent.
  14463. return +a == +b;
  14464. // RegExps are compared by their source patterns and flags.
  14465. case '[object RegExp]':
  14466. return a.source == b.source &&
  14467. a.global == b.global &&
  14468. a.multiline == b.multiline &&
  14469. a.ignoreCase == b.ignoreCase;
  14470. }
  14471. if (typeof a != 'object' || typeof b != 'object') return false;
  14472. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  14473. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  14474. var length = aStack.length;
  14475. while (length--) {
  14476. // Linear search. Performance is inversely proportional to the number of
  14477. // unique nested structures.
  14478. if (aStack[length] == a) return bStack[length] == b;
  14479. }
  14480. // Add the first object to the stack of traversed objects.
  14481. aStack.push(a);
  14482. bStack.push(b);
  14483. var size = 0, result = true;
  14484. // Recursively compare objects and arrays.
  14485. if (className == '[object Array]') {
  14486. // Compare array lengths to determine if a deep comparison is necessary.
  14487. size = a.length;
  14488. result = size == b.length;
  14489. if (result) {
  14490. // Deep compare the contents, ignoring non-numeric properties.
  14491. while (size--) {
  14492. if (!(result = eq(a[size], b[size], aStack, bStack))) break;
  14493. }
  14494. }
  14495. } else {
  14496. // Objects with different constructors are not equivalent, but `Object`s
  14497. // from different frames are.
  14498. var aCtor = a.constructor, bCtor = b.constructor;
  14499. if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
  14500. _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
  14501. return false;
  14502. }
  14503. // Deep compare objects.
  14504. for (var key in a) {
  14505. if (_.has(a, key)) {
  14506. // Count the expected number of properties.
  14507. size++;
  14508. // Deep compare each member.
  14509. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
  14510. }
  14511. }
  14512. // Ensure that both objects contain the same number of properties.
  14513. if (result) {
  14514. for (key in b) {
  14515. if (_.has(b, key) && !(size--)) break;
  14516. }
  14517. result = !size;
  14518. }
  14519. }
  14520. // Remove the first object from the stack of traversed objects.
  14521. aStack.pop();
  14522. bStack.pop();
  14523. return result;
  14524. };
  14525. // Perform a deep comparison to check if two objects are equal.
  14526. _.isEqual = function(a, b) {
  14527. return eq(a, b, [], []);
  14528. };
  14529. // Is a given array, string, or object empty?
  14530. // An "empty" object has no enumerable own-properties.
  14531. _.isEmpty = function(obj) {
  14532. if (obj == null) return true;
  14533. if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  14534. for (var key in obj) if (_.has(obj, key)) return false;
  14535. return true;
  14536. };
  14537. // Is a given value a DOM element?
  14538. _.isElement = function(obj) {
  14539. return !!(obj && obj.nodeType === 1);
  14540. };
  14541. // Is a given value an array?
  14542. // Delegates to ECMA5's native Array.isArray
  14543. _.isArray = nativeIsArray || function(obj) {
  14544. return toString.call(obj) == '[object Array]';
  14545. };
  14546. // Is a given variable an object?
  14547. _.isObject = function(obj) {
  14548. return obj === Object(obj);
  14549. };
  14550. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
  14551. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
  14552. _['is' + name] = function(obj) {
  14553. return toString.call(obj) == '[object ' + name + ']';
  14554. };
  14555. });
  14556. // Define a fallback version of the method in browsers (ahem, IE), where
  14557. // there isn't any inspectable "Arguments" type.
  14558. if (!_.isArguments(arguments)) {
  14559. _.isArguments = function(obj) {
  14560. return !!(obj && _.has(obj, 'callee'));
  14561. };
  14562. }
  14563. // Optimize `isFunction` if appropriate.
  14564. if (typeof (/./) !== 'function') {
  14565. _.isFunction = function(obj) {
  14566. return typeof obj === 'function';
  14567. };
  14568. }
  14569. // Is a given object a finite number?
  14570. _.isFinite = function(obj) {
  14571. return isFinite(obj) && !isNaN(parseFloat(obj));
  14572. };
  14573. // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  14574. _.isNaN = function(obj) {
  14575. return _.isNumber(obj) && obj != +obj;
  14576. };
  14577. // Is a given value a boolean?
  14578. _.isBoolean = function(obj) {
  14579. return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  14580. };
  14581. // Is a given value equal to null?
  14582. _.isNull = function(obj) {
  14583. return obj === null;
  14584. };
  14585. // Is a given variable undefined?
  14586. _.isUndefined = function(obj) {
  14587. return obj === void 0;
  14588. };
  14589. // Shortcut function for checking if an object has a given property directly
  14590. // on itself (in other words, not on a prototype).
  14591. _.has = function(obj, key) {
  14592. return hasOwnProperty.call(obj, key);
  14593. };
  14594. // Utility Functions
  14595. // -----------------
  14596. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  14597. // previous owner. Returns a reference to the Underscore object.
  14598. _.noConflict = function() {
  14599. root._ = previousUnderscore;
  14600. return this;
  14601. };
  14602. // Keep the identity function around for default iterators.
  14603. _.identity = function(value) {
  14604. return value;
  14605. };
  14606. // Run a function **n** times.
  14607. _.times = function(n, iterator, context) {
  14608. var accum = Array(n);
  14609. for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
  14610. return accum;
  14611. };
  14612. // Return a random integer between min and max (inclusive).
  14613. _.random = function(min, max) {
  14614. if (max == null) {
  14615. max = min;
  14616. min = 0;
  14617. }
  14618. return min + Math.floor(Math.random() * (max - min + 1));
  14619. };
  14620. // List of HTML entities for escaping.
  14621. var entityMap = {
  14622. escape: {
  14623. '&': '&amp;',
  14624. '<': '&lt;',
  14625. '>': '&gt;',
  14626. '"': '&quot;',
  14627. "'": '&#x27;',
  14628. '/': '&#x2F;'
  14629. }
  14630. };
  14631. entityMap.unescape = _.invert(entityMap.escape);
  14632. // Regexes containing the keys and values listed immediately above.
  14633. var entityRegexes = {
  14634. escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
  14635. unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
  14636. };
  14637. // Functions for escaping and unescaping strings to/from HTML interpolation.
  14638. _.each(['escape', 'unescape'], function(method) {
  14639. _[method] = function(string) {
  14640. if (string == null) return '';
  14641. return ('' + string).replace(entityRegexes[method], function(match) {
  14642. return entityMap[method][match];
  14643. });
  14644. };
  14645. });
  14646. // If the value of the named property is a function then invoke it;
  14647. // otherwise, return it.
  14648. _.result = function(object, property) {
  14649. if (object == null) return null;
  14650. var value = object[property];
  14651. return _.isFunction(value) ? value.call(object) : value;
  14652. };
  14653. // Add your own custom functions to the Underscore object.
  14654. _.mixin = function(obj) {
  14655. each(_.functions(obj), function(name){
  14656. var func = _[name] = obj[name];
  14657. _.prototype[name] = function() {
  14658. var args = [this._wrapped];
  14659. push.apply(args, arguments);
  14660. return result.call(this, func.apply(_, args));
  14661. };
  14662. });
  14663. };
  14664. // Generate a unique integer id (unique within the entire client session).
  14665. // Useful for temporary DOM ids.
  14666. var idCounter = 0;
  14667. _.uniqueId = function(prefix) {
  14668. var id = ++idCounter + '';
  14669. return prefix ? prefix + id : id;
  14670. };
  14671. // By default, Underscore uses ERB-style template delimiters, change the
  14672. // following template settings to use alternative delimiters.
  14673. _.templateSettings = {
  14674. evaluate : /<%([\s\S]+?)%>/g,
  14675. interpolate : /<%=([\s\S]+?)%>/g,
  14676. escape : /<%-([\s\S]+?)%>/g
  14677. };
  14678. // When customizing `templateSettings`, if you don't want to define an
  14679. // interpolation, evaluation or escaping regex, we need one that is
  14680. // guaranteed not to match.
  14681. var noMatch = /(.)^/;
  14682. // Certain characters need to be escaped so that they can be put into a
  14683. // string literal.
  14684. var escapes = {
  14685. "'": "'",
  14686. '\\': '\\',
  14687. '\r': 'r',
  14688. '\n': 'n',
  14689. '\t': 't',
  14690. '\u2028': 'u2028',
  14691. '\u2029': 'u2029'
  14692. };
  14693. var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
  14694. // JavaScript micro-templating, similar to John Resig's implementation.
  14695. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  14696. // and correctly escapes quotes within interpolated code.
  14697. _.template = function(text, data, settings) {
  14698. var render;
  14699. settings = _.defaults({}, settings, _.templateSettings);
  14700. // Combine delimiters into one regular expression via alternation.
  14701. var matcher = new RegExp([
  14702. (settings.escape || noMatch).source,
  14703. (settings.interpolate || noMatch).source,
  14704. (settings.evaluate || noMatch).source
  14705. ].join('|') + '|$', 'g');
  14706. // Compile the template source, escaping string literals appropriately.
  14707. var index = 0;
  14708. var source = "__p+='";
  14709. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  14710. source += text.slice(index, offset)
  14711. .replace(escaper, function(match) { return '\\' + escapes[match]; });
  14712. if (escape) {
  14713. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  14714. }
  14715. if (interpolate) {
  14716. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  14717. }
  14718. if (evaluate) {
  14719. source += "';\n" + evaluate + "\n__p+='";
  14720. }
  14721. index = offset + match.length;
  14722. return match;
  14723. });
  14724. source += "';\n";
  14725. // If a variable is not specified, place data values in local scope.
  14726. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  14727. source = "var __t,__p='',__j=Array.prototype.join," +
  14728. "print=function(){__p+=__j.call(arguments,'');};\n" +
  14729. source + "return __p;\n";
  14730. try {
  14731. render = new Function(settings.variable || 'obj', '_', source);
  14732. } catch (e) {
  14733. e.source = source;
  14734. throw e;
  14735. }
  14736. if (data) return render(data, _);
  14737. var template = function(data) {
  14738. return render.call(this, data, _);
  14739. };
  14740. // Provide the compiled function source as a convenience for precompilation.
  14741. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
  14742. return template;
  14743. };
  14744. // Add a "chain" function, which will delegate to the wrapper.
  14745. _.chain = function(obj) {
  14746. return _(obj).chain();
  14747. };
  14748. // OOP
  14749. // ---------------
  14750. // If Underscore is called as a function, it returns a wrapped object that
  14751. // can be used OO-style. This wrapper holds altered versions of all the
  14752. // underscore functions. Wrapped objects may be chained.
  14753. // Helper function to continue chaining intermediate results.
  14754. var result = function(obj) {
  14755. return this._chain ? _(obj).chain() : obj;
  14756. };
  14757. // Add all of the Underscore functions to the wrapper object.
  14758. _.mixin(_);
  14759. // Add all mutator Array functions to the wrapper.
  14760. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  14761. var method = ArrayProto[name];
  14762. _.prototype[name] = function() {
  14763. var obj = this._wrapped;
  14764. method.apply(obj, arguments);
  14765. if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
  14766. return result.call(this, obj);
  14767. };
  14768. });
  14769. // Add all accessor Array functions to the wrapper.
  14770. each(['concat', 'join', 'slice'], function(name) {
  14771. var method = ArrayProto[name];
  14772. _.prototype[name] = function() {
  14773. return result.call(this, method.apply(this._wrapped, arguments));
  14774. };
  14775. });
  14776. _.extend(_.prototype, {
  14777. // Start chaining a wrapped Underscore object.
  14778. chain: function() {
  14779. this._chain = true;
  14780. return this;
  14781. },
  14782. // Extracts the result from a wrapped and chained object.
  14783. value: function() {
  14784. return this._wrapped;
  14785. }
  14786. });
  14787. }).call(this);
  14788. },{}],119:[function(require,module,exports){
  14789. exports.none = Object.create({
  14790. value: function() {
  14791. throw new Error('Called value on none');
  14792. },
  14793. isNone: function() {
  14794. return true;
  14795. },
  14796. isSome: function() {
  14797. return false;
  14798. },
  14799. map: function() {
  14800. return exports.none;
  14801. },
  14802. flatMap: function() {
  14803. return exports.none;
  14804. },
  14805. toArray: function() {
  14806. return [];
  14807. },
  14808. orElse: callOrReturn,
  14809. valueOrElse: callOrReturn
  14810. });
  14811. function callOrReturn(value) {
  14812. if (typeof(value) == "function") {
  14813. return value();
  14814. } else {
  14815. return value;
  14816. }
  14817. }
  14818. exports.some = function(value) {
  14819. return new Some(value);
  14820. };
  14821. var Some = function(value) {
  14822. this._value = value;
  14823. };
  14824. Some.prototype.value = function() {
  14825. return this._value;
  14826. };
  14827. Some.prototype.isNone = function() {
  14828. return false;
  14829. };
  14830. Some.prototype.isSome = function() {
  14831. return true;
  14832. };
  14833. Some.prototype.map = function(func) {
  14834. return new Some(func(this._value));
  14835. };
  14836. Some.prototype.flatMap = function(func) {
  14837. return func(this._value);
  14838. };
  14839. Some.prototype.toArray = function() {
  14840. return [this._value];
  14841. };
  14842. Some.prototype.orElse = function(value) {
  14843. return this;
  14844. };
  14845. Some.prototype.valueOrElse = function(value) {
  14846. return this._value;
  14847. };
  14848. exports.isOption = function(value) {
  14849. return value === exports.none || value instanceof Some;
  14850. };
  14851. exports.fromNullable = function(value) {
  14852. if (value == null) {
  14853. return exports.none;
  14854. }
  14855. return new Some(value);
  14856. }
  14857. },{}],120:[function(require,module,exports){
  14858. // Top level file is just a mixin of submodules & constants
  14859. 'use strict';
  14860. var assign = require('./lib/utils/common').assign;
  14861. var deflate = require('./lib/deflate');
  14862. var inflate = require('./lib/inflate');
  14863. var constants = require('./lib/zlib/constants');
  14864. var pako = {};
  14865. assign(pako, deflate, inflate, constants);
  14866. module.exports = pako;
  14867. },{"./lib/deflate":121,"./lib/inflate":122,"./lib/utils/common":123,"./lib/zlib/constants":126}],121:[function(require,module,exports){
  14868. 'use strict';
  14869. var zlib_deflate = require('./zlib/deflate');
  14870. var utils = require('./utils/common');
  14871. var strings = require('./utils/strings');
  14872. var msg = require('./zlib/messages');
  14873. var ZStream = require('./zlib/zstream');
  14874. var toString = Object.prototype.toString;
  14875. /* Public constants ==========================================================*/
  14876. /* ===========================================================================*/
  14877. var Z_NO_FLUSH = 0;
  14878. var Z_FINISH = 4;
  14879. var Z_OK = 0;
  14880. var Z_STREAM_END = 1;
  14881. var Z_SYNC_FLUSH = 2;
  14882. var Z_DEFAULT_COMPRESSION = -1;
  14883. var Z_DEFAULT_STRATEGY = 0;
  14884. var Z_DEFLATED = 8;
  14885. /* ===========================================================================*/
  14886. /**
  14887. * class Deflate
  14888. *
  14889. * Generic JS-style wrapper for zlib calls. If you don't need
  14890. * streaming behaviour - use more simple functions: [[deflate]],
  14891. * [[deflateRaw]] and [[gzip]].
  14892. **/
  14893. /* internal
  14894. * Deflate.chunks -> Array
  14895. *
  14896. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14897. **/
  14898. /**
  14899. * Deflate.result -> Uint8Array|Array
  14900. *
  14901. * Compressed result, generated by default [[Deflate#onData]]
  14902. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14903. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14904. * push a chunk with explicit flush (call [[Deflate#push]] with
  14905. * `Z_SYNC_FLUSH` param).
  14906. **/
  14907. /**
  14908. * Deflate.err -> Number
  14909. *
  14910. * Error code after deflate finished. 0 (Z_OK) on success.
  14911. * You will not need it in real life, because deflate errors
  14912. * are possible only on wrong options or bad `onData` / `onEnd`
  14913. * custom handlers.
  14914. **/
  14915. /**
  14916. * Deflate.msg -> String
  14917. *
  14918. * Error message, if [[Deflate.err]] != 0
  14919. **/
  14920. /**
  14921. * new Deflate(options)
  14922. * - options (Object): zlib deflate options.
  14923. *
  14924. * Creates new deflator instance with specified params. Throws exception
  14925. * on bad params. Supported options:
  14926. *
  14927. * - `level`
  14928. * - `windowBits`
  14929. * - `memLevel`
  14930. * - `strategy`
  14931. * - `dictionary`
  14932. *
  14933. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14934. * for more information on these.
  14935. *
  14936. * Additional options, for internal needs:
  14937. *
  14938. * - `chunkSize` - size of generated data chunks (16K by default)
  14939. * - `raw` (Boolean) - do raw deflate
  14940. * - `gzip` (Boolean) - create gzip wrapper
  14941. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14942. * (each char code [0..255])
  14943. * - `header` (Object) - custom header for gzip
  14944. * - `text` (Boolean) - true if compressed data believed to be text
  14945. * - `time` (Number) - modification time, unix timestamp
  14946. * - `os` (Number) - operation system code
  14947. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14948. * - `name` (String) - file name (binary string)
  14949. * - `comment` (String) - comment (binary string)
  14950. * - `hcrc` (Boolean) - true if header crc should be added
  14951. *
  14952. * ##### Example:
  14953. *
  14954. * ```javascript
  14955. * var pako = require('pako')
  14956. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14957. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14958. *
  14959. * var deflate = new pako.Deflate({ level: 3});
  14960. *
  14961. * deflate.push(chunk1, false);
  14962. * deflate.push(chunk2, true); // true -> last chunk
  14963. *
  14964. * if (deflate.err) { throw new Error(deflate.err); }
  14965. *
  14966. * console.log(deflate.result);
  14967. * ```
  14968. **/
  14969. function Deflate(options) {
  14970. if (!(this instanceof Deflate)) return new Deflate(options);
  14971. this.options = utils.assign({
  14972. level: Z_DEFAULT_COMPRESSION,
  14973. method: Z_DEFLATED,
  14974. chunkSize: 16384,
  14975. windowBits: 15,
  14976. memLevel: 8,
  14977. strategy: Z_DEFAULT_STRATEGY,
  14978. to: ''
  14979. }, options || {});
  14980. var opt = this.options;
  14981. if (opt.raw && (opt.windowBits > 0)) {
  14982. opt.windowBits = -opt.windowBits;
  14983. }
  14984. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14985. opt.windowBits += 16;
  14986. }
  14987. this.err = 0; // error code, if happens (0 = Z_OK)
  14988. this.msg = ''; // error message
  14989. this.ended = false; // used to avoid multiple onEnd() calls
  14990. this.chunks = []; // chunks of compressed data
  14991. this.strm = new ZStream();
  14992. this.strm.avail_out = 0;
  14993. var status = zlib_deflate.deflateInit2(
  14994. this.strm,
  14995. opt.level,
  14996. opt.method,
  14997. opt.windowBits,
  14998. opt.memLevel,
  14999. opt.strategy
  15000. );
  15001. if (status !== Z_OK) {
  15002. throw new Error(msg[status]);
  15003. }
  15004. if (opt.header) {
  15005. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  15006. }
  15007. if (opt.dictionary) {
  15008. var dict;
  15009. // Convert data if needed
  15010. if (typeof opt.dictionary === 'string') {
  15011. // If we need to compress text, change encoding to utf8.
  15012. dict = strings.string2buf(opt.dictionary);
  15013. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  15014. dict = new Uint8Array(opt.dictionary);
  15015. } else {
  15016. dict = opt.dictionary;
  15017. }
  15018. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  15019. if (status !== Z_OK) {
  15020. throw new Error(msg[status]);
  15021. }
  15022. this._dict_set = true;
  15023. }
  15024. }
  15025. /**
  15026. * Deflate#push(data[, mode]) -> Boolean
  15027. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  15028. * converted to utf8 byte sequence.
  15029. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  15030. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  15031. *
  15032. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  15033. * new compressed chunks. Returns `true` on success. The last data block must have
  15034. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  15035. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  15036. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  15037. *
  15038. * On fail call [[Deflate#onEnd]] with error code and return false.
  15039. *
  15040. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15041. * array format is detected automatically). Also, don't skip last param and always
  15042. * use the same type in your code (boolean or number). That will improve JS speed.
  15043. *
  15044. * For regular `Array`-s make sure all elements are [0..255].
  15045. *
  15046. * ##### Example
  15047. *
  15048. * ```javascript
  15049. * push(chunk, false); // push one of data chunks
  15050. * ...
  15051. * push(chunk, true); // push last chunk
  15052. * ```
  15053. **/
  15054. Deflate.prototype.push = function (data, mode) {
  15055. var strm = this.strm;
  15056. var chunkSize = this.options.chunkSize;
  15057. var status, _mode;
  15058. if (this.ended) { return false; }
  15059. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  15060. // Convert data if needed
  15061. if (typeof data === 'string') {
  15062. // If we need to compress text, change encoding to utf8.
  15063. strm.input = strings.string2buf(data);
  15064. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15065. strm.input = new Uint8Array(data);
  15066. } else {
  15067. strm.input = data;
  15068. }
  15069. strm.next_in = 0;
  15070. strm.avail_in = strm.input.length;
  15071. do {
  15072. if (strm.avail_out === 0) {
  15073. strm.output = new utils.Buf8(chunkSize);
  15074. strm.next_out = 0;
  15075. strm.avail_out = chunkSize;
  15076. }
  15077. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  15078. if (status !== Z_STREAM_END && status !== Z_OK) {
  15079. this.onEnd(status);
  15080. this.ended = true;
  15081. return false;
  15082. }
  15083. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  15084. if (this.options.to === 'string') {
  15085. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  15086. } else {
  15087. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15088. }
  15089. }
  15090. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  15091. // Finalize on the last chunk.
  15092. if (_mode === Z_FINISH) {
  15093. status = zlib_deflate.deflateEnd(this.strm);
  15094. this.onEnd(status);
  15095. this.ended = true;
  15096. return status === Z_OK;
  15097. }
  15098. // callback interim results if Z_SYNC_FLUSH.
  15099. if (_mode === Z_SYNC_FLUSH) {
  15100. this.onEnd(Z_OK);
  15101. strm.avail_out = 0;
  15102. return true;
  15103. }
  15104. return true;
  15105. };
  15106. /**
  15107. * Deflate#onData(chunk) -> Void
  15108. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15109. * on js engine support. When string output requested, each chunk
  15110. * will be string.
  15111. *
  15112. * By default, stores data blocks in `chunks[]` property and glue
  15113. * those in `onEnd`. Override this handler, if you need another behaviour.
  15114. **/
  15115. Deflate.prototype.onData = function (chunk) {
  15116. this.chunks.push(chunk);
  15117. };
  15118. /**
  15119. * Deflate#onEnd(status) -> Void
  15120. * - status (Number): deflate status. 0 (Z_OK) on success,
  15121. * other if not.
  15122. *
  15123. * Called once after you tell deflate that the input stream is
  15124. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15125. * or if an error happened. By default - join collected chunks,
  15126. * free memory and fill `results` / `err` properties.
  15127. **/
  15128. Deflate.prototype.onEnd = function (status) {
  15129. // On success - join
  15130. if (status === Z_OK) {
  15131. if (this.options.to === 'string') {
  15132. this.result = this.chunks.join('');
  15133. } else {
  15134. this.result = utils.flattenChunks(this.chunks);
  15135. }
  15136. }
  15137. this.chunks = [];
  15138. this.err = status;
  15139. this.msg = this.strm.msg;
  15140. };
  15141. /**
  15142. * deflate(data[, options]) -> Uint8Array|Array|String
  15143. * - data (Uint8Array|Array|String): input data to compress.
  15144. * - options (Object): zlib deflate options.
  15145. *
  15146. * Compress `data` with deflate algorithm and `options`.
  15147. *
  15148. * Supported options are:
  15149. *
  15150. * - level
  15151. * - windowBits
  15152. * - memLevel
  15153. * - strategy
  15154. * - dictionary
  15155. *
  15156. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15157. * for more information on these.
  15158. *
  15159. * Sugar (options):
  15160. *
  15161. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15162. * negative windowBits implicitly.
  15163. * - `to` (String) - if equal to 'string', then result will be "binary string"
  15164. * (each char code [0..255])
  15165. *
  15166. * ##### Example:
  15167. *
  15168. * ```javascript
  15169. * var pako = require('pako')
  15170. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  15171. *
  15172. * console.log(pako.deflate(data));
  15173. * ```
  15174. **/
  15175. function deflate(input, options) {
  15176. var deflator = new Deflate(options);
  15177. deflator.push(input, true);
  15178. // That will never happens, if you don't cheat with options :)
  15179. if (deflator.err) { throw deflator.msg; }
  15180. return deflator.result;
  15181. }
  15182. /**
  15183. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  15184. * - data (Uint8Array|Array|String): input data to compress.
  15185. * - options (Object): zlib deflate options.
  15186. *
  15187. * The same as [[deflate]], but creates raw data, without wrapper
  15188. * (header and adler32 crc).
  15189. **/
  15190. function deflateRaw(input, options) {
  15191. options = options || {};
  15192. options.raw = true;
  15193. return deflate(input, options);
  15194. }
  15195. /**
  15196. * gzip(data[, options]) -> Uint8Array|Array|String
  15197. * - data (Uint8Array|Array|String): input data to compress.
  15198. * - options (Object): zlib deflate options.
  15199. *
  15200. * The same as [[deflate]], but create gzip wrapper instead of
  15201. * deflate one.
  15202. **/
  15203. function gzip(input, options) {
  15204. options = options || {};
  15205. options.gzip = true;
  15206. return deflate(input, options);
  15207. }
  15208. exports.Deflate = Deflate;
  15209. exports.deflate = deflate;
  15210. exports.deflateRaw = deflateRaw;
  15211. exports.gzip = gzip;
  15212. },{"./utils/common":123,"./utils/strings":124,"./zlib/deflate":128,"./zlib/messages":133,"./zlib/zstream":135}],122:[function(require,module,exports){
  15213. 'use strict';
  15214. var zlib_inflate = require('./zlib/inflate');
  15215. var utils = require('./utils/common');
  15216. var strings = require('./utils/strings');
  15217. var c = require('./zlib/constants');
  15218. var msg = require('./zlib/messages');
  15219. var ZStream = require('./zlib/zstream');
  15220. var GZheader = require('./zlib/gzheader');
  15221. var toString = Object.prototype.toString;
  15222. /**
  15223. * class Inflate
  15224. *
  15225. * Generic JS-style wrapper for zlib calls. If you don't need
  15226. * streaming behaviour - use more simple functions: [[inflate]]
  15227. * and [[inflateRaw]].
  15228. **/
  15229. /* internal
  15230. * inflate.chunks -> Array
  15231. *
  15232. * Chunks of output data, if [[Inflate#onData]] not overriden.
  15233. **/
  15234. /**
  15235. * Inflate.result -> Uint8Array|Array|String
  15236. *
  15237. * Uncompressed result, generated by default [[Inflate#onData]]
  15238. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  15239. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  15240. * push a chunk with explicit flush (call [[Inflate#push]] with
  15241. * `Z_SYNC_FLUSH` param).
  15242. **/
  15243. /**
  15244. * Inflate.err -> Number
  15245. *
  15246. * Error code after inflate finished. 0 (Z_OK) on success.
  15247. * Should be checked if broken data possible.
  15248. **/
  15249. /**
  15250. * Inflate.msg -> String
  15251. *
  15252. * Error message, if [[Inflate.err]] != 0
  15253. **/
  15254. /**
  15255. * new Inflate(options)
  15256. * - options (Object): zlib inflate options.
  15257. *
  15258. * Creates new inflator instance with specified params. Throws exception
  15259. * on bad params. Supported options:
  15260. *
  15261. * - `windowBits`
  15262. * - `dictionary`
  15263. *
  15264. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15265. * for more information on these.
  15266. *
  15267. * Additional options, for internal needs:
  15268. *
  15269. * - `chunkSize` - size of generated data chunks (16K by default)
  15270. * - `raw` (Boolean) - do raw inflate
  15271. * - `to` (String) - if equal to 'string', then result will be converted
  15272. * from utf8 to utf16 (javascript) string. When string output requested,
  15273. * chunk length can differ from `chunkSize`, depending on content.
  15274. *
  15275. * By default, when no options set, autodetect deflate/gzip data format via
  15276. * wrapper header.
  15277. *
  15278. * ##### Example:
  15279. *
  15280. * ```javascript
  15281. * var pako = require('pako')
  15282. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  15283. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  15284. *
  15285. * var inflate = new pako.Inflate({ level: 3});
  15286. *
  15287. * inflate.push(chunk1, false);
  15288. * inflate.push(chunk2, true); // true -> last chunk
  15289. *
  15290. * if (inflate.err) { throw new Error(inflate.err); }
  15291. *
  15292. * console.log(inflate.result);
  15293. * ```
  15294. **/
  15295. function Inflate(options) {
  15296. if (!(this instanceof Inflate)) return new Inflate(options);
  15297. this.options = utils.assign({
  15298. chunkSize: 16384,
  15299. windowBits: 0,
  15300. to: ''
  15301. }, options || {});
  15302. var opt = this.options;
  15303. // Force window size for `raw` data, if not set directly,
  15304. // because we have no header for autodetect.
  15305. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  15306. opt.windowBits = -opt.windowBits;
  15307. if (opt.windowBits === 0) { opt.windowBits = -15; }
  15308. }
  15309. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  15310. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  15311. !(options && options.windowBits)) {
  15312. opt.windowBits += 32;
  15313. }
  15314. // Gzip header has no info about windows size, we can do autodetect only
  15315. // for deflate. So, if window size not set, force it to max when gzip possible
  15316. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  15317. // bit 3 (16) -> gzipped data
  15318. // bit 4 (32) -> autodetect gzip/deflate
  15319. if ((opt.windowBits & 15) === 0) {
  15320. opt.windowBits |= 15;
  15321. }
  15322. }
  15323. this.err = 0; // error code, if happens (0 = Z_OK)
  15324. this.msg = ''; // error message
  15325. this.ended = false; // used to avoid multiple onEnd() calls
  15326. this.chunks = []; // chunks of compressed data
  15327. this.strm = new ZStream();
  15328. this.strm.avail_out = 0;
  15329. var status = zlib_inflate.inflateInit2(
  15330. this.strm,
  15331. opt.windowBits
  15332. );
  15333. if (status !== c.Z_OK) {
  15334. throw new Error(msg[status]);
  15335. }
  15336. this.header = new GZheader();
  15337. zlib_inflate.inflateGetHeader(this.strm, this.header);
  15338. }
  15339. /**
  15340. * Inflate#push(data[, mode]) -> Boolean
  15341. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  15342. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  15343. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  15344. *
  15345. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  15346. * new output chunks. Returns `true` on success. The last data block must have
  15347. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  15348. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  15349. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  15350. *
  15351. * On fail call [[Inflate#onEnd]] with error code and return false.
  15352. *
  15353. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15354. * format is detected automatically). Also, don't skip last param and always
  15355. * use the same type in your code (boolean or number). That will improve JS speed.
  15356. *
  15357. * For regular `Array`-s make sure all elements are [0..255].
  15358. *
  15359. * ##### Example
  15360. *
  15361. * ```javascript
  15362. * push(chunk, false); // push one of data chunks
  15363. * ...
  15364. * push(chunk, true); // push last chunk
  15365. * ```
  15366. **/
  15367. Inflate.prototype.push = function (data, mode) {
  15368. var strm = this.strm;
  15369. var chunkSize = this.options.chunkSize;
  15370. var dictionary = this.options.dictionary;
  15371. var status, _mode;
  15372. var next_out_utf8, tail, utf8str;
  15373. var dict;
  15374. // Flag to properly process Z_BUF_ERROR on testing inflate call
  15375. // when we check that all output data was flushed.
  15376. var allowBufError = false;
  15377. if (this.ended) { return false; }
  15378. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  15379. // Convert data if needed
  15380. if (typeof data === 'string') {
  15381. // Only binary strings can be decompressed on practice
  15382. strm.input = strings.binstring2buf(data);
  15383. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15384. strm.input = new Uint8Array(data);
  15385. } else {
  15386. strm.input = data;
  15387. }
  15388. strm.next_in = 0;
  15389. strm.avail_in = strm.input.length;
  15390. do {
  15391. if (strm.avail_out === 0) {
  15392. strm.output = new utils.Buf8(chunkSize);
  15393. strm.next_out = 0;
  15394. strm.avail_out = chunkSize;
  15395. }
  15396. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  15397. if (status === c.Z_NEED_DICT && dictionary) {
  15398. // Convert data if needed
  15399. if (typeof dictionary === 'string') {
  15400. dict = strings.string2buf(dictionary);
  15401. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  15402. dict = new Uint8Array(dictionary);
  15403. } else {
  15404. dict = dictionary;
  15405. }
  15406. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  15407. }
  15408. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  15409. status = c.Z_OK;
  15410. allowBufError = false;
  15411. }
  15412. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  15413. this.onEnd(status);
  15414. this.ended = true;
  15415. return false;
  15416. }
  15417. if (strm.next_out) {
  15418. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  15419. if (this.options.to === 'string') {
  15420. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  15421. tail = strm.next_out - next_out_utf8;
  15422. utf8str = strings.buf2string(strm.output, next_out_utf8);
  15423. // move tail
  15424. strm.next_out = tail;
  15425. strm.avail_out = chunkSize - tail;
  15426. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  15427. this.onData(utf8str);
  15428. } else {
  15429. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15430. }
  15431. }
  15432. }
  15433. // When no more input data, we should check that internal inflate buffers
  15434. // are flushed. The only way to do it when avail_out = 0 - run one more
  15435. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  15436. // Here we set flag to process this error properly.
  15437. //
  15438. // NOTE. Deflate does not return error in this case and does not needs such
  15439. // logic.
  15440. if (strm.avail_in === 0 && strm.avail_out === 0) {
  15441. allowBufError = true;
  15442. }
  15443. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  15444. if (status === c.Z_STREAM_END) {
  15445. _mode = c.Z_FINISH;
  15446. }
  15447. // Finalize on the last chunk.
  15448. if (_mode === c.Z_FINISH) {
  15449. status = zlib_inflate.inflateEnd(this.strm);
  15450. this.onEnd(status);
  15451. this.ended = true;
  15452. return status === c.Z_OK;
  15453. }
  15454. // callback interim results if Z_SYNC_FLUSH.
  15455. if (_mode === c.Z_SYNC_FLUSH) {
  15456. this.onEnd(c.Z_OK);
  15457. strm.avail_out = 0;
  15458. return true;
  15459. }
  15460. return true;
  15461. };
  15462. /**
  15463. * Inflate#onData(chunk) -> Void
  15464. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15465. * on js engine support. When string output requested, each chunk
  15466. * will be string.
  15467. *
  15468. * By default, stores data blocks in `chunks[]` property and glue
  15469. * those in `onEnd`. Override this handler, if you need another behaviour.
  15470. **/
  15471. Inflate.prototype.onData = function (chunk) {
  15472. this.chunks.push(chunk);
  15473. };
  15474. /**
  15475. * Inflate#onEnd(status) -> Void
  15476. * - status (Number): inflate status. 0 (Z_OK) on success,
  15477. * other if not.
  15478. *
  15479. * Called either after you tell inflate that the input stream is
  15480. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15481. * or if an error happened. By default - join collected chunks,
  15482. * free memory and fill `results` / `err` properties.
  15483. **/
  15484. Inflate.prototype.onEnd = function (status) {
  15485. // On success - join
  15486. if (status === c.Z_OK) {
  15487. if (this.options.to === 'string') {
  15488. // Glue & convert here, until we teach pako to send
  15489. // utf8 alligned strings to onData
  15490. this.result = this.chunks.join('');
  15491. } else {
  15492. this.result = utils.flattenChunks(this.chunks);
  15493. }
  15494. }
  15495. this.chunks = [];
  15496. this.err = status;
  15497. this.msg = this.strm.msg;
  15498. };
  15499. /**
  15500. * inflate(data[, options]) -> Uint8Array|Array|String
  15501. * - data (Uint8Array|Array|String): input data to decompress.
  15502. * - options (Object): zlib inflate options.
  15503. *
  15504. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  15505. * format via wrapper header by default. That's why we don't provide
  15506. * separate `ungzip` method.
  15507. *
  15508. * Supported options are:
  15509. *
  15510. * - windowBits
  15511. *
  15512. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15513. * for more information.
  15514. *
  15515. * Sugar (options):
  15516. *
  15517. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15518. * negative windowBits implicitly.
  15519. * - `to` (String) - if equal to 'string', then result will be converted
  15520. * from utf8 to utf16 (javascript) string. When string output requested,
  15521. * chunk length can differ from `chunkSize`, depending on content.
  15522. *
  15523. *
  15524. * ##### Example:
  15525. *
  15526. * ```javascript
  15527. * var pako = require('pako')
  15528. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  15529. * , output;
  15530. *
  15531. * try {
  15532. * output = pako.inflate(input);
  15533. * } catch (err)
  15534. * console.log(err);
  15535. * }
  15536. * ```
  15537. **/
  15538. function inflate(input, options) {
  15539. var inflator = new Inflate(options);
  15540. inflator.push(input, true);
  15541. // That will never happens, if you don't cheat with options :)
  15542. if (inflator.err) { throw inflator.msg; }
  15543. return inflator.result;
  15544. }
  15545. /**
  15546. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  15547. * - data (Uint8Array|Array|String): input data to decompress.
  15548. * - options (Object): zlib inflate options.
  15549. *
  15550. * The same as [[inflate]], but creates raw data, without wrapper
  15551. * (header and adler32 crc).
  15552. **/
  15553. function inflateRaw(input, options) {
  15554. options = options || {};
  15555. options.raw = true;
  15556. return inflate(input, options);
  15557. }
  15558. /**
  15559. * ungzip(data[, options]) -> Uint8Array|Array|String
  15560. * - data (Uint8Array|Array|String): input data to decompress.
  15561. * - options (Object): zlib inflate options.
  15562. *
  15563. * Just shortcut to [[inflate]], because it autodetects format
  15564. * by header.content. Done for convenience.
  15565. **/
  15566. exports.Inflate = Inflate;
  15567. exports.inflate = inflate;
  15568. exports.inflateRaw = inflateRaw;
  15569. exports.ungzip = inflate;
  15570. },{"./utils/common":123,"./utils/strings":124,"./zlib/constants":126,"./zlib/gzheader":129,"./zlib/inflate":131,"./zlib/messages":133,"./zlib/zstream":135}],123:[function(require,module,exports){
  15571. 'use strict';
  15572. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15573. (typeof Uint16Array !== 'undefined') &&
  15574. (typeof Int32Array !== 'undefined');
  15575. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15576. var sources = Array.prototype.slice.call(arguments, 1);
  15577. while (sources.length) {
  15578. var source = sources.shift();
  15579. if (!source) { continue; }
  15580. if (typeof source !== 'object') {
  15581. throw new TypeError(source + 'must be non-object');
  15582. }
  15583. for (var p in source) {
  15584. if (source.hasOwnProperty(p)) {
  15585. obj[p] = source[p];
  15586. }
  15587. }
  15588. }
  15589. return obj;
  15590. };
  15591. // reduce buffer size, avoiding mem copy
  15592. exports.shrinkBuf = function (buf, size) {
  15593. if (buf.length === size) { return buf; }
  15594. if (buf.subarray) { return buf.subarray(0, size); }
  15595. buf.length = size;
  15596. return buf;
  15597. };
  15598. var fnTyped = {
  15599. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15600. if (src.subarray && dest.subarray) {
  15601. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  15602. return;
  15603. }
  15604. // Fallback to ordinary array
  15605. for (var i = 0; i < len; i++) {
  15606. dest[dest_offs + i] = src[src_offs + i];
  15607. }
  15608. },
  15609. // Join array of chunks to single array.
  15610. flattenChunks: function (chunks) {
  15611. var i, l, len, pos, chunk, result;
  15612. // calculate data length
  15613. len = 0;
  15614. for (i = 0, l = chunks.length; i < l; i++) {
  15615. len += chunks[i].length;
  15616. }
  15617. // join chunks
  15618. result = new Uint8Array(len);
  15619. pos = 0;
  15620. for (i = 0, l = chunks.length; i < l; i++) {
  15621. chunk = chunks[i];
  15622. result.set(chunk, pos);
  15623. pos += chunk.length;
  15624. }
  15625. return result;
  15626. }
  15627. };
  15628. var fnUntyped = {
  15629. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15630. for (var i = 0; i < len; i++) {
  15631. dest[dest_offs + i] = src[src_offs + i];
  15632. }
  15633. },
  15634. // Join array of chunks to single array.
  15635. flattenChunks: function (chunks) {
  15636. return [].concat.apply([], chunks);
  15637. }
  15638. };
  15639. // Enable/Disable typed arrays use, for testing
  15640. //
  15641. exports.setTyped = function (on) {
  15642. if (on) {
  15643. exports.Buf8 = Uint8Array;
  15644. exports.Buf16 = Uint16Array;
  15645. exports.Buf32 = Int32Array;
  15646. exports.assign(exports, fnTyped);
  15647. } else {
  15648. exports.Buf8 = Array;
  15649. exports.Buf16 = Array;
  15650. exports.Buf32 = Array;
  15651. exports.assign(exports, fnUntyped);
  15652. }
  15653. };
  15654. exports.setTyped(TYPED_OK);
  15655. },{}],124:[function(require,module,exports){
  15656. // String encode/decode helpers
  15657. 'use strict';
  15658. var utils = require('./common');
  15659. // Quick check if we can use fast array to bin string conversion
  15660. //
  15661. // - apply(Array) can fail on Android 2.2
  15662. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15663. //
  15664. var STR_APPLY_OK = true;
  15665. var STR_APPLY_UIA_OK = true;
  15666. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  15667. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  15668. // Table with utf8 lengths (calculated by first byte of sequence)
  15669. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15670. // because max possible codepoint is 0x10ffff
  15671. var _utf8len = new utils.Buf8(256);
  15672. for (var q = 0; q < 256; q++) {
  15673. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15674. }
  15675. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  15676. // convert string to array (typed, when possible)
  15677. exports.string2buf = function (str) {
  15678. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15679. // count binary size
  15680. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15681. c = str.charCodeAt(m_pos);
  15682. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  15683. c2 = str.charCodeAt(m_pos + 1);
  15684. if ((c2 & 0xfc00) === 0xdc00) {
  15685. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15686. m_pos++;
  15687. }
  15688. }
  15689. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15690. }
  15691. // allocate buffer
  15692. buf = new utils.Buf8(buf_len);
  15693. // convert
  15694. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  15695. c = str.charCodeAt(m_pos);
  15696. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  15697. c2 = str.charCodeAt(m_pos + 1);
  15698. if ((c2 & 0xfc00) === 0xdc00) {
  15699. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15700. m_pos++;
  15701. }
  15702. }
  15703. if (c < 0x80) {
  15704. /* one byte */
  15705. buf[i++] = c;
  15706. } else if (c < 0x800) {
  15707. /* two bytes */
  15708. buf[i++] = 0xC0 | (c >>> 6);
  15709. buf[i++] = 0x80 | (c & 0x3f);
  15710. } else if (c < 0x10000) {
  15711. /* three bytes */
  15712. buf[i++] = 0xE0 | (c >>> 12);
  15713. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15714. buf[i++] = 0x80 | (c & 0x3f);
  15715. } else {
  15716. /* four bytes */
  15717. buf[i++] = 0xf0 | (c >>> 18);
  15718. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15719. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15720. buf[i++] = 0x80 | (c & 0x3f);
  15721. }
  15722. }
  15723. return buf;
  15724. };
  15725. // Helper (used in 2 places)
  15726. function buf2binstring(buf, len) {
  15727. // use fallback for big arrays to avoid stack overflow
  15728. if (len < 65537) {
  15729. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15730. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15731. }
  15732. }
  15733. var result = '';
  15734. for (var i = 0; i < len; i++) {
  15735. result += String.fromCharCode(buf[i]);
  15736. }
  15737. return result;
  15738. }
  15739. // Convert byte array to binary string
  15740. exports.buf2binstring = function (buf) {
  15741. return buf2binstring(buf, buf.length);
  15742. };
  15743. // Convert binary string (typed, when possible)
  15744. exports.binstring2buf = function (str) {
  15745. var buf = new utils.Buf8(str.length);
  15746. for (var i = 0, len = buf.length; i < len; i++) {
  15747. buf[i] = str.charCodeAt(i);
  15748. }
  15749. return buf;
  15750. };
  15751. // convert array to string
  15752. exports.buf2string = function (buf, max) {
  15753. var i, out, c, c_len;
  15754. var len = max || buf.length;
  15755. // Reserve max possible length (2 words per char)
  15756. // NB: by unknown reasons, Array is significantly faster for
  15757. // String.fromCharCode.apply than Uint16Array.
  15758. var utf16buf = new Array(len * 2);
  15759. for (out = 0, i = 0; i < len;) {
  15760. c = buf[i++];
  15761. // quick process ascii
  15762. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15763. c_len = _utf8len[c];
  15764. // skip 5 & 6 byte codes
  15765. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  15766. // apply mask on first byte
  15767. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15768. // join the rest
  15769. while (c_len > 1 && i < len) {
  15770. c = (c << 6) | (buf[i++] & 0x3f);
  15771. c_len--;
  15772. }
  15773. // terminated by end of string?
  15774. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15775. if (c < 0x10000) {
  15776. utf16buf[out++] = c;
  15777. } else {
  15778. c -= 0x10000;
  15779. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15780. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15781. }
  15782. }
  15783. return buf2binstring(utf16buf, out);
  15784. };
  15785. // Calculate max possible position in utf8 buffer,
  15786. // that will not break sequence. If that's not possible
  15787. // - (very small limits) return max size as is.
  15788. //
  15789. // buf[] - utf8 bytes array
  15790. // max - length limit (mandatory);
  15791. exports.utf8border = function (buf, max) {
  15792. var pos;
  15793. max = max || buf.length;
  15794. if (max > buf.length) { max = buf.length; }
  15795. // go back from last position, until start of sequence found
  15796. pos = max - 1;
  15797. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15798. // Fuckup - very small and broken sequence,
  15799. // return max, because we should return something anyway.
  15800. if (pos < 0) { return max; }
  15801. // If we came to start of buffer - that means vuffer is too small,
  15802. // return max too.
  15803. if (pos === 0) { return max; }
  15804. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15805. };
  15806. },{"./common":123}],125:[function(require,module,exports){
  15807. 'use strict';
  15808. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15809. // It doesn't worth to make additional optimizationa as in original.
  15810. // Small size is preferable.
  15811. function adler32(adler, buf, len, pos) {
  15812. var s1 = (adler & 0xffff) |0,
  15813. s2 = ((adler >>> 16) & 0xffff) |0,
  15814. n = 0;
  15815. while (len !== 0) {
  15816. // Set limit ~ twice less than 5552, to keep
  15817. // s2 in 31-bits, because we force signed ints.
  15818. // in other case %= will fail.
  15819. n = len > 2000 ? 2000 : len;
  15820. len -= n;
  15821. do {
  15822. s1 = (s1 + buf[pos++]) |0;
  15823. s2 = (s2 + s1) |0;
  15824. } while (--n);
  15825. s1 %= 65521;
  15826. s2 %= 65521;
  15827. }
  15828. return (s1 | (s2 << 16)) |0;
  15829. }
  15830. module.exports = adler32;
  15831. },{}],126:[function(require,module,exports){
  15832. 'use strict';
  15833. module.exports = {
  15834. /* Allowed flush values; see deflate() and inflate() below for details */
  15835. Z_NO_FLUSH: 0,
  15836. Z_PARTIAL_FLUSH: 1,
  15837. Z_SYNC_FLUSH: 2,
  15838. Z_FULL_FLUSH: 3,
  15839. Z_FINISH: 4,
  15840. Z_BLOCK: 5,
  15841. Z_TREES: 6,
  15842. /* Return codes for the compression/decompression functions. Negative values
  15843. * are errors, positive values are used for special but normal events.
  15844. */
  15845. Z_OK: 0,
  15846. Z_STREAM_END: 1,
  15847. Z_NEED_DICT: 2,
  15848. Z_ERRNO: -1,
  15849. Z_STREAM_ERROR: -2,
  15850. Z_DATA_ERROR: -3,
  15851. //Z_MEM_ERROR: -4,
  15852. Z_BUF_ERROR: -5,
  15853. //Z_VERSION_ERROR: -6,
  15854. /* compression levels */
  15855. Z_NO_COMPRESSION: 0,
  15856. Z_BEST_SPEED: 1,
  15857. Z_BEST_COMPRESSION: 9,
  15858. Z_DEFAULT_COMPRESSION: -1,
  15859. Z_FILTERED: 1,
  15860. Z_HUFFMAN_ONLY: 2,
  15861. Z_RLE: 3,
  15862. Z_FIXED: 4,
  15863. Z_DEFAULT_STRATEGY: 0,
  15864. /* Possible values of the data_type field (though see inflate()) */
  15865. Z_BINARY: 0,
  15866. Z_TEXT: 1,
  15867. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15868. Z_UNKNOWN: 2,
  15869. /* The deflate compression method */
  15870. Z_DEFLATED: 8
  15871. //Z_NULL: null // Use -1 or null inline, depending on var type
  15872. };
  15873. },{}],127:[function(require,module,exports){
  15874. 'use strict';
  15875. // Note: we can't get significant speed boost here.
  15876. // So write code to minimize size - no pregenerated tables
  15877. // and array tools dependencies.
  15878. // Use ordinary array, since untyped makes no boost here
  15879. function makeTable() {
  15880. var c, table = [];
  15881. for (var n = 0; n < 256; n++) {
  15882. c = n;
  15883. for (var k = 0; k < 8; k++) {
  15884. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15885. }
  15886. table[n] = c;
  15887. }
  15888. return table;
  15889. }
  15890. // Create table on load. Just 255 signed longs. Not a problem.
  15891. var crcTable = makeTable();
  15892. function crc32(crc, buf, len, pos) {
  15893. var t = crcTable,
  15894. end = pos + len;
  15895. crc ^= -1;
  15896. for (var i = pos; i < end; i++) {
  15897. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15898. }
  15899. return (crc ^ (-1)); // >>> 0;
  15900. }
  15901. module.exports = crc32;
  15902. },{}],128:[function(require,module,exports){
  15903. 'use strict';
  15904. var utils = require('../utils/common');
  15905. var trees = require('./trees');
  15906. var adler32 = require('./adler32');
  15907. var crc32 = require('./crc32');
  15908. var msg = require('./messages');
  15909. /* Public constants ==========================================================*/
  15910. /* ===========================================================================*/
  15911. /* Allowed flush values; see deflate() and inflate() below for details */
  15912. var Z_NO_FLUSH = 0;
  15913. var Z_PARTIAL_FLUSH = 1;
  15914. //var Z_SYNC_FLUSH = 2;
  15915. var Z_FULL_FLUSH = 3;
  15916. var Z_FINISH = 4;
  15917. var Z_BLOCK = 5;
  15918. //var Z_TREES = 6;
  15919. /* Return codes for the compression/decompression functions. Negative values
  15920. * are errors, positive values are used for special but normal events.
  15921. */
  15922. var Z_OK = 0;
  15923. var Z_STREAM_END = 1;
  15924. //var Z_NEED_DICT = 2;
  15925. //var Z_ERRNO = -1;
  15926. var Z_STREAM_ERROR = -2;
  15927. var Z_DATA_ERROR = -3;
  15928. //var Z_MEM_ERROR = -4;
  15929. var Z_BUF_ERROR = -5;
  15930. //var Z_VERSION_ERROR = -6;
  15931. /* compression levels */
  15932. //var Z_NO_COMPRESSION = 0;
  15933. //var Z_BEST_SPEED = 1;
  15934. //var Z_BEST_COMPRESSION = 9;
  15935. var Z_DEFAULT_COMPRESSION = -1;
  15936. var Z_FILTERED = 1;
  15937. var Z_HUFFMAN_ONLY = 2;
  15938. var Z_RLE = 3;
  15939. var Z_FIXED = 4;
  15940. var Z_DEFAULT_STRATEGY = 0;
  15941. /* Possible values of the data_type field (though see inflate()) */
  15942. //var Z_BINARY = 0;
  15943. //var Z_TEXT = 1;
  15944. //var Z_ASCII = 1; // = Z_TEXT
  15945. var Z_UNKNOWN = 2;
  15946. /* The deflate compression method */
  15947. var Z_DEFLATED = 8;
  15948. /*============================================================================*/
  15949. var MAX_MEM_LEVEL = 9;
  15950. /* Maximum value for memLevel in deflateInit2 */
  15951. var MAX_WBITS = 15;
  15952. /* 32K LZ77 window */
  15953. var DEF_MEM_LEVEL = 8;
  15954. var LENGTH_CODES = 29;
  15955. /* number of length codes, not counting the special END_BLOCK code */
  15956. var LITERALS = 256;
  15957. /* number of literal bytes 0..255 */
  15958. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15959. /* number of Literal or Length codes, including the END_BLOCK code */
  15960. var D_CODES = 30;
  15961. /* number of distance codes */
  15962. var BL_CODES = 19;
  15963. /* number of codes used to transfer the bit lengths */
  15964. var HEAP_SIZE = 2 * L_CODES + 1;
  15965. /* maximum heap size */
  15966. var MAX_BITS = 15;
  15967. /* All codes must not exceed MAX_BITS bits */
  15968. var MIN_MATCH = 3;
  15969. var MAX_MATCH = 258;
  15970. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15971. var PRESET_DICT = 0x20;
  15972. var INIT_STATE = 42;
  15973. var EXTRA_STATE = 69;
  15974. var NAME_STATE = 73;
  15975. var COMMENT_STATE = 91;
  15976. var HCRC_STATE = 103;
  15977. var BUSY_STATE = 113;
  15978. var FINISH_STATE = 666;
  15979. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15980. var BS_BLOCK_DONE = 2; /* block flush performed */
  15981. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15982. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15983. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15984. function err(strm, errorCode) {
  15985. strm.msg = msg[errorCode];
  15986. return errorCode;
  15987. }
  15988. function rank(f) {
  15989. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15990. }
  15991. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15992. /* =========================================================================
  15993. * Flush as much pending output as possible. All deflate() output goes
  15994. * through this function so some applications may wish to modify it
  15995. * to avoid allocating a large strm->output buffer and copying into it.
  15996. * (See also read_buf()).
  15997. */
  15998. function flush_pending(strm) {
  15999. var s = strm.state;
  16000. //_tr_flush_bits(s);
  16001. var len = s.pending;
  16002. if (len > strm.avail_out) {
  16003. len = strm.avail_out;
  16004. }
  16005. if (len === 0) { return; }
  16006. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  16007. strm.next_out += len;
  16008. s.pending_out += len;
  16009. strm.total_out += len;
  16010. strm.avail_out -= len;
  16011. s.pending -= len;
  16012. if (s.pending === 0) {
  16013. s.pending_out = 0;
  16014. }
  16015. }
  16016. function flush_block_only(s, last) {
  16017. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  16018. s.block_start = s.strstart;
  16019. flush_pending(s.strm);
  16020. }
  16021. function put_byte(s, b) {
  16022. s.pending_buf[s.pending++] = b;
  16023. }
  16024. /* =========================================================================
  16025. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  16026. * IN assertion: the stream state is correct and there is enough room in
  16027. * pending_buf.
  16028. */
  16029. function putShortMSB(s, b) {
  16030. // put_byte(s, (Byte)(b >> 8));
  16031. // put_byte(s, (Byte)(b & 0xff));
  16032. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  16033. s.pending_buf[s.pending++] = b & 0xff;
  16034. }
  16035. /* ===========================================================================
  16036. * Read a new buffer from the current input stream, update the adler32
  16037. * and total number of bytes read. All deflate() input goes through
  16038. * this function so some applications may wish to modify it to avoid
  16039. * allocating a large strm->input buffer and copying from it.
  16040. * (See also flush_pending()).
  16041. */
  16042. function read_buf(strm, buf, start, size) {
  16043. var len = strm.avail_in;
  16044. if (len > size) { len = size; }
  16045. if (len === 0) { return 0; }
  16046. strm.avail_in -= len;
  16047. // zmemcpy(buf, strm->next_in, len);
  16048. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  16049. if (strm.state.wrap === 1) {
  16050. strm.adler = adler32(strm.adler, buf, len, start);
  16051. }
  16052. else if (strm.state.wrap === 2) {
  16053. strm.adler = crc32(strm.adler, buf, len, start);
  16054. }
  16055. strm.next_in += len;
  16056. strm.total_in += len;
  16057. return len;
  16058. }
  16059. /* ===========================================================================
  16060. * Set match_start to the longest match starting at the given string and
  16061. * return its length. Matches shorter or equal to prev_length are discarded,
  16062. * in which case the result is equal to prev_length and match_start is
  16063. * garbage.
  16064. * IN assertions: cur_match is the head of the hash chain for the current
  16065. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  16066. * OUT assertion: the match length is not greater than s->lookahead.
  16067. */
  16068. function longest_match(s, cur_match) {
  16069. var chain_length = s.max_chain_length; /* max hash chain length */
  16070. var scan = s.strstart; /* current string */
  16071. var match; /* matched string */
  16072. var len; /* length of current match */
  16073. var best_len = s.prev_length; /* best match length so far */
  16074. var nice_match = s.nice_match; /* stop if match long enough */
  16075. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  16076. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  16077. var _win = s.window; // shortcut
  16078. var wmask = s.w_mask;
  16079. var prev = s.prev;
  16080. /* Stop when cur_match becomes <= limit. To simplify the code,
  16081. * we prevent matches with the string of window index 0.
  16082. */
  16083. var strend = s.strstart + MAX_MATCH;
  16084. var scan_end1 = _win[scan + best_len - 1];
  16085. var scan_end = _win[scan + best_len];
  16086. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  16087. * It is easy to get rid of this optimization if necessary.
  16088. */
  16089. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  16090. /* Do not waste too much time if we already have a good match: */
  16091. if (s.prev_length >= s.good_match) {
  16092. chain_length >>= 2;
  16093. }
  16094. /* Do not look for matches beyond the end of the input. This is necessary
  16095. * to make deflate deterministic.
  16096. */
  16097. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  16098. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  16099. do {
  16100. // Assert(cur_match < s->strstart, "no future");
  16101. match = cur_match;
  16102. /* Skip to next match if the match length cannot increase
  16103. * or if the match length is less than 2. Note that the checks below
  16104. * for insufficient lookahead only occur occasionally for performance
  16105. * reasons. Therefore uninitialized memory will be accessed, and
  16106. * conditional jumps will be made that depend on those values.
  16107. * However the length of the match is limited to the lookahead, so
  16108. * the output of deflate is not affected by the uninitialized values.
  16109. */
  16110. if (_win[match + best_len] !== scan_end ||
  16111. _win[match + best_len - 1] !== scan_end1 ||
  16112. _win[match] !== _win[scan] ||
  16113. _win[++match] !== _win[scan + 1]) {
  16114. continue;
  16115. }
  16116. /* The check at best_len-1 can be removed because it will be made
  16117. * again later. (This heuristic is not always a win.)
  16118. * It is not necessary to compare scan[2] and match[2] since they
  16119. * are always equal when the other bytes match, given that
  16120. * the hash keys are equal and that HASH_BITS >= 8.
  16121. */
  16122. scan += 2;
  16123. match++;
  16124. // Assert(*scan == *match, "match[2]?");
  16125. /* We check for insufficient lookahead only every 8th comparison;
  16126. * the 256th check will be made at strstart+258.
  16127. */
  16128. do {
  16129. /*jshint noempty:false*/
  16130. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16131. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16132. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16133. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  16134. scan < strend);
  16135. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  16136. len = MAX_MATCH - (strend - scan);
  16137. scan = strend - MAX_MATCH;
  16138. if (len > best_len) {
  16139. s.match_start = cur_match;
  16140. best_len = len;
  16141. if (len >= nice_match) {
  16142. break;
  16143. }
  16144. scan_end1 = _win[scan + best_len - 1];
  16145. scan_end = _win[scan + best_len];
  16146. }
  16147. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  16148. if (best_len <= s.lookahead) {
  16149. return best_len;
  16150. }
  16151. return s.lookahead;
  16152. }
  16153. /* ===========================================================================
  16154. * Fill the window when the lookahead becomes insufficient.
  16155. * Updates strstart and lookahead.
  16156. *
  16157. * IN assertion: lookahead < MIN_LOOKAHEAD
  16158. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  16159. * At least one byte has been read, or avail_in == 0; reads are
  16160. * performed for at least two bytes (required for the zip translate_eol
  16161. * option -- not supported here).
  16162. */
  16163. function fill_window(s) {
  16164. var _w_size = s.w_size;
  16165. var p, n, m, more, str;
  16166. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  16167. do {
  16168. more = s.window_size - s.lookahead - s.strstart;
  16169. // JS ints have 32 bit, block below not needed
  16170. /* Deal with !@#$% 64K limit: */
  16171. //if (sizeof(int) <= 2) {
  16172. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  16173. // more = wsize;
  16174. //
  16175. // } else if (more == (unsigned)(-1)) {
  16176. // /* Very unlikely, but possible on 16 bit machine if
  16177. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  16178. // */
  16179. // more--;
  16180. // }
  16181. //}
  16182. /* If the window is almost full and there is insufficient lookahead,
  16183. * move the upper half to the lower one to make room in the upper half.
  16184. */
  16185. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  16186. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  16187. s.match_start -= _w_size;
  16188. s.strstart -= _w_size;
  16189. /* we now have strstart >= MAX_DIST */
  16190. s.block_start -= _w_size;
  16191. /* Slide the hash table (could be avoided with 32 bit values
  16192. at the expense of memory usage). We slide even when level == 0
  16193. to keep the hash table consistent if we switch back to level > 0
  16194. later. (Using level 0 permanently is not an optimal usage of
  16195. zlib, so we don't care about this pathological case.)
  16196. */
  16197. n = s.hash_size;
  16198. p = n;
  16199. do {
  16200. m = s.head[--p];
  16201. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  16202. } while (--n);
  16203. n = _w_size;
  16204. p = n;
  16205. do {
  16206. m = s.prev[--p];
  16207. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  16208. /* If n is not on any hash chain, prev[n] is garbage but
  16209. * its value will never be used.
  16210. */
  16211. } while (--n);
  16212. more += _w_size;
  16213. }
  16214. if (s.strm.avail_in === 0) {
  16215. break;
  16216. }
  16217. /* If there was no sliding:
  16218. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  16219. * more == window_size - lookahead - strstart
  16220. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  16221. * => more >= window_size - 2*WSIZE + 2
  16222. * In the BIG_MEM or MMAP case (not yet supported),
  16223. * window_size == input_size + MIN_LOOKAHEAD &&
  16224. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  16225. * Otherwise, window_size == 2*WSIZE so more >= 2.
  16226. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  16227. */
  16228. //Assert(more >= 2, "more < 2");
  16229. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  16230. s.lookahead += n;
  16231. /* Initialize the hash value now that we have some input: */
  16232. if (s.lookahead + s.insert >= MIN_MATCH) {
  16233. str = s.strstart - s.insert;
  16234. s.ins_h = s.window[str];
  16235. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  16236. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  16237. //#if MIN_MATCH != 3
  16238. // Call update_hash() MIN_MATCH-3 more times
  16239. //#endif
  16240. while (s.insert) {
  16241. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  16242. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  16243. s.prev[str & s.w_mask] = s.head[s.ins_h];
  16244. s.head[s.ins_h] = str;
  16245. str++;
  16246. s.insert--;
  16247. if (s.lookahead + s.insert < MIN_MATCH) {
  16248. break;
  16249. }
  16250. }
  16251. }
  16252. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  16253. * but this is not important since only literal bytes will be emitted.
  16254. */
  16255. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  16256. /* If the WIN_INIT bytes after the end of the current data have never been
  16257. * written, then zero those bytes in order to avoid memory check reports of
  16258. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  16259. * the longest match routines. Update the high water mark for the next
  16260. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  16261. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  16262. */
  16263. // if (s.high_water < s.window_size) {
  16264. // var curr = s.strstart + s.lookahead;
  16265. // var init = 0;
  16266. //
  16267. // if (s.high_water < curr) {
  16268. // /* Previous high water mark below current data -- zero WIN_INIT
  16269. // * bytes or up to end of window, whichever is less.
  16270. // */
  16271. // init = s.window_size - curr;
  16272. // if (init > WIN_INIT)
  16273. // init = WIN_INIT;
  16274. // zmemzero(s->window + curr, (unsigned)init);
  16275. // s->high_water = curr + init;
  16276. // }
  16277. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  16278. // /* High water mark at or above current data, but below current data
  16279. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  16280. // * to end of window, whichever is less.
  16281. // */
  16282. // init = (ulg)curr + WIN_INIT - s->high_water;
  16283. // if (init > s->window_size - s->high_water)
  16284. // init = s->window_size - s->high_water;
  16285. // zmemzero(s->window + s->high_water, (unsigned)init);
  16286. // s->high_water += init;
  16287. // }
  16288. // }
  16289. //
  16290. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  16291. // "not enough room for search");
  16292. }
  16293. /* ===========================================================================
  16294. * Copy without compression as much as possible from the input stream, return
  16295. * the current block state.
  16296. * This function does not insert new strings in the dictionary since
  16297. * uncompressible data is probably not useful. This function is used
  16298. * only for the level=0 compression option.
  16299. * NOTE: this function should be optimized to avoid extra copying from
  16300. * window to pending_buf.
  16301. */
  16302. function deflate_stored(s, flush) {
  16303. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  16304. * to pending_buf_size, and each stored block has a 5 byte header:
  16305. */
  16306. var max_block_size = 0xffff;
  16307. if (max_block_size > s.pending_buf_size - 5) {
  16308. max_block_size = s.pending_buf_size - 5;
  16309. }
  16310. /* Copy as much as possible from input to output: */
  16311. for (;;) {
  16312. /* Fill the window as much as possible: */
  16313. if (s.lookahead <= 1) {
  16314. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  16315. // s->block_start >= (long)s->w_size, "slide too late");
  16316. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  16317. // s.block_start >= s.w_size)) {
  16318. // throw new Error("slide too late");
  16319. // }
  16320. fill_window(s);
  16321. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  16322. return BS_NEED_MORE;
  16323. }
  16324. if (s.lookahead === 0) {
  16325. break;
  16326. }
  16327. /* flush the current block */
  16328. }
  16329. //Assert(s->block_start >= 0L, "block gone");
  16330. // if (s.block_start < 0) throw new Error("block gone");
  16331. s.strstart += s.lookahead;
  16332. s.lookahead = 0;
  16333. /* Emit a stored block if pending_buf will be full: */
  16334. var max_start = s.block_start + max_block_size;
  16335. if (s.strstart === 0 || s.strstart >= max_start) {
  16336. /* strstart == 0 is possible when wraparound on 16-bit machine */
  16337. s.lookahead = s.strstart - max_start;
  16338. s.strstart = max_start;
  16339. /*** FLUSH_BLOCK(s, 0); ***/
  16340. flush_block_only(s, false);
  16341. if (s.strm.avail_out === 0) {
  16342. return BS_NEED_MORE;
  16343. }
  16344. /***/
  16345. }
  16346. /* Flush if we may have to slide, otherwise block_start may become
  16347. * negative and the data will be gone:
  16348. */
  16349. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  16350. /*** FLUSH_BLOCK(s, 0); ***/
  16351. flush_block_only(s, false);
  16352. if (s.strm.avail_out === 0) {
  16353. return BS_NEED_MORE;
  16354. }
  16355. /***/
  16356. }
  16357. }
  16358. s.insert = 0;
  16359. if (flush === Z_FINISH) {
  16360. /*** FLUSH_BLOCK(s, 1); ***/
  16361. flush_block_only(s, true);
  16362. if (s.strm.avail_out === 0) {
  16363. return BS_FINISH_STARTED;
  16364. }
  16365. /***/
  16366. return BS_FINISH_DONE;
  16367. }
  16368. if (s.strstart > s.block_start) {
  16369. /*** FLUSH_BLOCK(s, 0); ***/
  16370. flush_block_only(s, false);
  16371. if (s.strm.avail_out === 0) {
  16372. return BS_NEED_MORE;
  16373. }
  16374. /***/
  16375. }
  16376. return BS_NEED_MORE;
  16377. }
  16378. /* ===========================================================================
  16379. * Compress as much as possible from the input stream, return the current
  16380. * block state.
  16381. * This function does not perform lazy evaluation of matches and inserts
  16382. * new strings in the dictionary only for unmatched strings or for short
  16383. * matches. It is used only for the fast compression options.
  16384. */
  16385. function deflate_fast(s, flush) {
  16386. var hash_head; /* head of the hash chain */
  16387. var bflush; /* set if current block must be flushed */
  16388. for (;;) {
  16389. /* Make sure that we always have enough lookahead, except
  16390. * at the end of the input file. We need MAX_MATCH bytes
  16391. * for the next match, plus MIN_MATCH bytes to insert the
  16392. * string following the next match.
  16393. */
  16394. if (s.lookahead < MIN_LOOKAHEAD) {
  16395. fill_window(s);
  16396. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16397. return BS_NEED_MORE;
  16398. }
  16399. if (s.lookahead === 0) {
  16400. break; /* flush the current block */
  16401. }
  16402. }
  16403. /* Insert the string window[strstart .. strstart+2] in the
  16404. * dictionary, and set hash_head to the head of the hash chain:
  16405. */
  16406. hash_head = 0/*NIL*/;
  16407. if (s.lookahead >= MIN_MATCH) {
  16408. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16409. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16410. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16411. s.head[s.ins_h] = s.strstart;
  16412. /***/
  16413. }
  16414. /* Find the longest match, discarding those <= prev_length.
  16415. * At this point we have always match_length < MIN_MATCH
  16416. */
  16417. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  16418. /* To simplify the code, we prevent matches with the string
  16419. * of window index 0 (in particular we have to avoid a match
  16420. * of the string with itself at the start of the input file).
  16421. */
  16422. s.match_length = longest_match(s, hash_head);
  16423. /* longest_match() sets match_start */
  16424. }
  16425. if (s.match_length >= MIN_MATCH) {
  16426. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  16427. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  16428. s.match_length - MIN_MATCH, bflush); ***/
  16429. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  16430. s.lookahead -= s.match_length;
  16431. /* Insert new strings in the hash table only if the match length
  16432. * is not too large. This saves time but degrades compression.
  16433. */
  16434. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  16435. s.match_length--; /* string at strstart already in table */
  16436. do {
  16437. s.strstart++;
  16438. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16439. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16440. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16441. s.head[s.ins_h] = s.strstart;
  16442. /***/
  16443. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  16444. * always MIN_MATCH bytes ahead.
  16445. */
  16446. } while (--s.match_length !== 0);
  16447. s.strstart++;
  16448. } else
  16449. {
  16450. s.strstart += s.match_length;
  16451. s.match_length = 0;
  16452. s.ins_h = s.window[s.strstart];
  16453. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  16454. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  16455. //#if MIN_MATCH != 3
  16456. // Call UPDATE_HASH() MIN_MATCH-3 more times
  16457. //#endif
  16458. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  16459. * matter since it will be recomputed at next deflate call.
  16460. */
  16461. }
  16462. } else {
  16463. /* No match, output a literal byte */
  16464. //Tracevv((stderr,"%c", s.window[s.strstart]));
  16465. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16466. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16467. s.lookahead--;
  16468. s.strstart++;
  16469. }
  16470. if (bflush) {
  16471. /*** FLUSH_BLOCK(s, 0); ***/
  16472. flush_block_only(s, false);
  16473. if (s.strm.avail_out === 0) {
  16474. return BS_NEED_MORE;
  16475. }
  16476. /***/
  16477. }
  16478. }
  16479. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  16480. if (flush === Z_FINISH) {
  16481. /*** FLUSH_BLOCK(s, 1); ***/
  16482. flush_block_only(s, true);
  16483. if (s.strm.avail_out === 0) {
  16484. return BS_FINISH_STARTED;
  16485. }
  16486. /***/
  16487. return BS_FINISH_DONE;
  16488. }
  16489. if (s.last_lit) {
  16490. /*** FLUSH_BLOCK(s, 0); ***/
  16491. flush_block_only(s, false);
  16492. if (s.strm.avail_out === 0) {
  16493. return BS_NEED_MORE;
  16494. }
  16495. /***/
  16496. }
  16497. return BS_BLOCK_DONE;
  16498. }
  16499. /* ===========================================================================
  16500. * Same as above, but achieves better compression. We use a lazy
  16501. * evaluation for matches: a match is finally adopted only if there is
  16502. * no better match at the next window position.
  16503. */
  16504. function deflate_slow(s, flush) {
  16505. var hash_head; /* head of hash chain */
  16506. var bflush; /* set if current block must be flushed */
  16507. var max_insert;
  16508. /* Process the input block. */
  16509. for (;;) {
  16510. /* Make sure that we always have enough lookahead, except
  16511. * at the end of the input file. We need MAX_MATCH bytes
  16512. * for the next match, plus MIN_MATCH bytes to insert the
  16513. * string following the next match.
  16514. */
  16515. if (s.lookahead < MIN_LOOKAHEAD) {
  16516. fill_window(s);
  16517. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16518. return BS_NEED_MORE;
  16519. }
  16520. if (s.lookahead === 0) { break; } /* flush the current block */
  16521. }
  16522. /* Insert the string window[strstart .. strstart+2] in the
  16523. * dictionary, and set hash_head to the head of the hash chain:
  16524. */
  16525. hash_head = 0/*NIL*/;
  16526. if (s.lookahead >= MIN_MATCH) {
  16527. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16528. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16529. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16530. s.head[s.ins_h] = s.strstart;
  16531. /***/
  16532. }
  16533. /* Find the longest match, discarding those <= prev_length.
  16534. */
  16535. s.prev_length = s.match_length;
  16536. s.prev_match = s.match_start;
  16537. s.match_length = MIN_MATCH - 1;
  16538. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16539. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16540. /* To simplify the code, we prevent matches with the string
  16541. * of window index 0 (in particular we have to avoid a match
  16542. * of the string with itself at the start of the input file).
  16543. */
  16544. s.match_length = longest_match(s, hash_head);
  16545. /* longest_match() sets match_start */
  16546. if (s.match_length <= 5 &&
  16547. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16548. /* If prev_match is also MIN_MATCH, match_start is garbage
  16549. * but we will ignore the current match anyway.
  16550. */
  16551. s.match_length = MIN_MATCH - 1;
  16552. }
  16553. }
  16554. /* If there was a match at the previous step and the current
  16555. * match is not better, output the previous match:
  16556. */
  16557. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16558. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16559. /* Do not insert strings in hash table beyond this. */
  16560. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16561. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16562. s.prev_length - MIN_MATCH, bflush);***/
  16563. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  16564. /* Insert in hash table all strings up to the end of the match.
  16565. * strstart-1 and strstart are already inserted. If there is not
  16566. * enough lookahead, the last two strings are not inserted in
  16567. * the hash table.
  16568. */
  16569. s.lookahead -= s.prev_length - 1;
  16570. s.prev_length -= 2;
  16571. do {
  16572. if (++s.strstart <= max_insert) {
  16573. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16574. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16575. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16576. s.head[s.ins_h] = s.strstart;
  16577. /***/
  16578. }
  16579. } while (--s.prev_length !== 0);
  16580. s.match_available = 0;
  16581. s.match_length = MIN_MATCH - 1;
  16582. s.strstart++;
  16583. if (bflush) {
  16584. /*** FLUSH_BLOCK(s, 0); ***/
  16585. flush_block_only(s, false);
  16586. if (s.strm.avail_out === 0) {
  16587. return BS_NEED_MORE;
  16588. }
  16589. /***/
  16590. }
  16591. } else if (s.match_available) {
  16592. /* If there was no match at the previous position, output a
  16593. * single literal. If there was a match but the current match
  16594. * is longer, truncate the previous match to a single literal.
  16595. */
  16596. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16597. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16598. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  16599. if (bflush) {
  16600. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16601. flush_block_only(s, false);
  16602. /***/
  16603. }
  16604. s.strstart++;
  16605. s.lookahead--;
  16606. if (s.strm.avail_out === 0) {
  16607. return BS_NEED_MORE;
  16608. }
  16609. } else {
  16610. /* There is no previous match to compare with, wait for
  16611. * the next step to decide.
  16612. */
  16613. s.match_available = 1;
  16614. s.strstart++;
  16615. s.lookahead--;
  16616. }
  16617. }
  16618. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16619. if (s.match_available) {
  16620. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16621. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16622. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  16623. s.match_available = 0;
  16624. }
  16625. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  16626. if (flush === Z_FINISH) {
  16627. /*** FLUSH_BLOCK(s, 1); ***/
  16628. flush_block_only(s, true);
  16629. if (s.strm.avail_out === 0) {
  16630. return BS_FINISH_STARTED;
  16631. }
  16632. /***/
  16633. return BS_FINISH_DONE;
  16634. }
  16635. if (s.last_lit) {
  16636. /*** FLUSH_BLOCK(s, 0); ***/
  16637. flush_block_only(s, false);
  16638. if (s.strm.avail_out === 0) {
  16639. return BS_NEED_MORE;
  16640. }
  16641. /***/
  16642. }
  16643. return BS_BLOCK_DONE;
  16644. }
  16645. /* ===========================================================================
  16646. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16647. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16648. * deflate switches away from Z_RLE.)
  16649. */
  16650. function deflate_rle(s, flush) {
  16651. var bflush; /* set if current block must be flushed */
  16652. var prev; /* byte at distance one to match */
  16653. var scan, strend; /* scan goes up to strend for length of run */
  16654. var _win = s.window;
  16655. for (;;) {
  16656. /* Make sure that we always have enough lookahead, except
  16657. * at the end of the input file. We need MAX_MATCH bytes
  16658. * for the longest run, plus one for the unrolled loop.
  16659. */
  16660. if (s.lookahead <= MAX_MATCH) {
  16661. fill_window(s);
  16662. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16663. return BS_NEED_MORE;
  16664. }
  16665. if (s.lookahead === 0) { break; } /* flush the current block */
  16666. }
  16667. /* See how many times the previous byte repeats */
  16668. s.match_length = 0;
  16669. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16670. scan = s.strstart - 1;
  16671. prev = _win[scan];
  16672. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16673. strend = s.strstart + MAX_MATCH;
  16674. do {
  16675. /*jshint noempty:false*/
  16676. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16677. prev === _win[++scan] && prev === _win[++scan] &&
  16678. prev === _win[++scan] && prev === _win[++scan] &&
  16679. prev === _win[++scan] && prev === _win[++scan] &&
  16680. scan < strend);
  16681. s.match_length = MAX_MATCH - (strend - scan);
  16682. if (s.match_length > s.lookahead) {
  16683. s.match_length = s.lookahead;
  16684. }
  16685. }
  16686. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16687. }
  16688. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16689. if (s.match_length >= MIN_MATCH) {
  16690. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16691. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16692. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16693. s.lookahead -= s.match_length;
  16694. s.strstart += s.match_length;
  16695. s.match_length = 0;
  16696. } else {
  16697. /* No match, output a literal byte */
  16698. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16699. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16700. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16701. s.lookahead--;
  16702. s.strstart++;
  16703. }
  16704. if (bflush) {
  16705. /*** FLUSH_BLOCK(s, 0); ***/
  16706. flush_block_only(s, false);
  16707. if (s.strm.avail_out === 0) {
  16708. return BS_NEED_MORE;
  16709. }
  16710. /***/
  16711. }
  16712. }
  16713. s.insert = 0;
  16714. if (flush === Z_FINISH) {
  16715. /*** FLUSH_BLOCK(s, 1); ***/
  16716. flush_block_only(s, true);
  16717. if (s.strm.avail_out === 0) {
  16718. return BS_FINISH_STARTED;
  16719. }
  16720. /***/
  16721. return BS_FINISH_DONE;
  16722. }
  16723. if (s.last_lit) {
  16724. /*** FLUSH_BLOCK(s, 0); ***/
  16725. flush_block_only(s, false);
  16726. if (s.strm.avail_out === 0) {
  16727. return BS_NEED_MORE;
  16728. }
  16729. /***/
  16730. }
  16731. return BS_BLOCK_DONE;
  16732. }
  16733. /* ===========================================================================
  16734. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16735. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16736. */
  16737. function deflate_huff(s, flush) {
  16738. var bflush; /* set if current block must be flushed */
  16739. for (;;) {
  16740. /* Make sure that we have a literal to write. */
  16741. if (s.lookahead === 0) {
  16742. fill_window(s);
  16743. if (s.lookahead === 0) {
  16744. if (flush === Z_NO_FLUSH) {
  16745. return BS_NEED_MORE;
  16746. }
  16747. break; /* flush the current block */
  16748. }
  16749. }
  16750. /* Output a literal byte */
  16751. s.match_length = 0;
  16752. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16753. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16754. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16755. s.lookahead--;
  16756. s.strstart++;
  16757. if (bflush) {
  16758. /*** FLUSH_BLOCK(s, 0); ***/
  16759. flush_block_only(s, false);
  16760. if (s.strm.avail_out === 0) {
  16761. return BS_NEED_MORE;
  16762. }
  16763. /***/
  16764. }
  16765. }
  16766. s.insert = 0;
  16767. if (flush === Z_FINISH) {
  16768. /*** FLUSH_BLOCK(s, 1); ***/
  16769. flush_block_only(s, true);
  16770. if (s.strm.avail_out === 0) {
  16771. return BS_FINISH_STARTED;
  16772. }
  16773. /***/
  16774. return BS_FINISH_DONE;
  16775. }
  16776. if (s.last_lit) {
  16777. /*** FLUSH_BLOCK(s, 0); ***/
  16778. flush_block_only(s, false);
  16779. if (s.strm.avail_out === 0) {
  16780. return BS_NEED_MORE;
  16781. }
  16782. /***/
  16783. }
  16784. return BS_BLOCK_DONE;
  16785. }
  16786. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16787. * the desired pack level (0..9). The values given below have been tuned to
  16788. * exclude worst case performance for pathological files. Better values may be
  16789. * found for specific files.
  16790. */
  16791. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  16792. this.good_length = good_length;
  16793. this.max_lazy = max_lazy;
  16794. this.nice_length = nice_length;
  16795. this.max_chain = max_chain;
  16796. this.func = func;
  16797. }
  16798. var configuration_table;
  16799. configuration_table = [
  16800. /* good lazy nice chain */
  16801. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16802. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16803. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16804. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16805. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16806. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16807. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16808. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16809. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16810. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16811. ];
  16812. /* ===========================================================================
  16813. * Initialize the "longest match" routines for a new zlib stream
  16814. */
  16815. function lm_init(s) {
  16816. s.window_size = 2 * s.w_size;
  16817. /*** CLEAR_HASH(s); ***/
  16818. zero(s.head); // Fill with NIL (= 0);
  16819. /* Set the default configuration parameters:
  16820. */
  16821. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16822. s.good_match = configuration_table[s.level].good_length;
  16823. s.nice_match = configuration_table[s.level].nice_length;
  16824. s.max_chain_length = configuration_table[s.level].max_chain;
  16825. s.strstart = 0;
  16826. s.block_start = 0;
  16827. s.lookahead = 0;
  16828. s.insert = 0;
  16829. s.match_length = s.prev_length = MIN_MATCH - 1;
  16830. s.match_available = 0;
  16831. s.ins_h = 0;
  16832. }
  16833. function DeflateState() {
  16834. this.strm = null; /* pointer back to this zlib stream */
  16835. this.status = 0; /* as the name implies */
  16836. this.pending_buf = null; /* output still pending */
  16837. this.pending_buf_size = 0; /* size of pending_buf */
  16838. this.pending_out = 0; /* next pending byte to output to the stream */
  16839. this.pending = 0; /* nb of bytes in the pending buffer */
  16840. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16841. this.gzhead = null; /* gzip header information to write */
  16842. this.gzindex = 0; /* where in extra, name, or comment */
  16843. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16844. this.last_flush = -1; /* value of flush param for previous deflate call */
  16845. this.w_size = 0; /* LZ77 window size (32K by default) */
  16846. this.w_bits = 0; /* log2(w_size) (8..16) */
  16847. this.w_mask = 0; /* w_size - 1 */
  16848. this.window = null;
  16849. /* Sliding window. Input bytes are read into the second half of the window,
  16850. * and move to the first half later to keep a dictionary of at least wSize
  16851. * bytes. With this organization, matches are limited to a distance of
  16852. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16853. * performed with a length multiple of the block size.
  16854. */
  16855. this.window_size = 0;
  16856. /* Actual size of window: 2*wSize, except when the user input buffer
  16857. * is directly used as sliding window.
  16858. */
  16859. this.prev = null;
  16860. /* Link to older string with same hash index. To limit the size of this
  16861. * array to 64K, this link is maintained only for the last 32K strings.
  16862. * An index in this array is thus a window index modulo 32K.
  16863. */
  16864. this.head = null; /* Heads of the hash chains or NIL. */
  16865. this.ins_h = 0; /* hash index of string to be inserted */
  16866. this.hash_size = 0; /* number of elements in hash table */
  16867. this.hash_bits = 0; /* log2(hash_size) */
  16868. this.hash_mask = 0; /* hash_size-1 */
  16869. this.hash_shift = 0;
  16870. /* Number of bits by which ins_h must be shifted at each input
  16871. * step. It must be such that after MIN_MATCH steps, the oldest
  16872. * byte no longer takes part in the hash key, that is:
  16873. * hash_shift * MIN_MATCH >= hash_bits
  16874. */
  16875. this.block_start = 0;
  16876. /* Window position at the beginning of the current output block. Gets
  16877. * negative when the window is moved backwards.
  16878. */
  16879. this.match_length = 0; /* length of best match */
  16880. this.prev_match = 0; /* previous match */
  16881. this.match_available = 0; /* set if previous match exists */
  16882. this.strstart = 0; /* start of string to insert */
  16883. this.match_start = 0; /* start of matching string */
  16884. this.lookahead = 0; /* number of valid bytes ahead in window */
  16885. this.prev_length = 0;
  16886. /* Length of the best match at previous step. Matches not greater than this
  16887. * are discarded. This is used in the lazy match evaluation.
  16888. */
  16889. this.max_chain_length = 0;
  16890. /* To speed up deflation, hash chains are never searched beyond this
  16891. * length. A higher limit improves compression ratio but degrades the
  16892. * speed.
  16893. */
  16894. this.max_lazy_match = 0;
  16895. /* Attempt to find a better match only when the current match is strictly
  16896. * smaller than this value. This mechanism is used only for compression
  16897. * levels >= 4.
  16898. */
  16899. // That's alias to max_lazy_match, don't use directly
  16900. //this.max_insert_length = 0;
  16901. /* Insert new strings in the hash table only if the match length is not
  16902. * greater than this length. This saves time but degrades compression.
  16903. * max_insert_length is used only for compression levels <= 3.
  16904. */
  16905. this.level = 0; /* compression level (1..9) */
  16906. this.strategy = 0; /* favor or force Huffman coding*/
  16907. this.good_match = 0;
  16908. /* Use a faster search when the previous match is longer than this */
  16909. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16910. /* used by trees.c: */
  16911. /* Didn't use ct_data typedef below to suppress compiler warning */
  16912. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16913. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16914. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16915. // Use flat array of DOUBLE size, with interleaved fata,
  16916. // because JS does not support effective
  16917. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16918. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  16919. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  16920. zero(this.dyn_ltree);
  16921. zero(this.dyn_dtree);
  16922. zero(this.bl_tree);
  16923. this.l_desc = null; /* desc. for literal tree */
  16924. this.d_desc = null; /* desc. for distance tree */
  16925. this.bl_desc = null; /* desc. for bit length tree */
  16926. //ush bl_count[MAX_BITS+1];
  16927. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  16928. /* number of codes at each bit length for an optimal tree */
  16929. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16930. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  16931. zero(this.heap);
  16932. this.heap_len = 0; /* number of elements in the heap */
  16933. this.heap_max = 0; /* element of largest frequency */
  16934. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16935. * The same heap array is used to build all trees.
  16936. */
  16937. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  16938. zero(this.depth);
  16939. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16940. */
  16941. this.l_buf = 0; /* buffer index for literals or lengths */
  16942. this.lit_bufsize = 0;
  16943. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16944. * limiting lit_bufsize to 64K:
  16945. * - frequencies can be kept in 16 bit counters
  16946. * - if compression is not successful for the first block, all input
  16947. * data is still in the window so we can still emit a stored block even
  16948. * when input comes from standard input. (This can also be done for
  16949. * all blocks if lit_bufsize is not greater than 32K.)
  16950. * - if compression is not successful for a file smaller than 64K, we can
  16951. * even emit a stored file instead of a stored block (saving 5 bytes).
  16952. * This is applicable only for zip (not gzip or zlib).
  16953. * - creating new Huffman trees less frequently may not provide fast
  16954. * adaptation to changes in the input data statistics. (Take for
  16955. * example a binary file with poorly compressible code followed by
  16956. * a highly compressible string table.) Smaller buffer sizes give
  16957. * fast adaptation but have of course the overhead of transmitting
  16958. * trees more frequently.
  16959. * - I can't count above 4
  16960. */
  16961. this.last_lit = 0; /* running index in l_buf */
  16962. this.d_buf = 0;
  16963. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16964. * the same number of elements. To use different lengths, an extra flag
  16965. * array would be necessary.
  16966. */
  16967. this.opt_len = 0; /* bit length of current block with optimal trees */
  16968. this.static_len = 0; /* bit length of current block with static trees */
  16969. this.matches = 0; /* number of string matches in current block */
  16970. this.insert = 0; /* bytes at end of window left to insert */
  16971. this.bi_buf = 0;
  16972. /* Output buffer. bits are inserted starting at the bottom (least
  16973. * significant bits).
  16974. */
  16975. this.bi_valid = 0;
  16976. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16977. * are always zero.
  16978. */
  16979. // Used for window memory init. We safely ignore it for JS. That makes
  16980. // sense only for pointers and memory check tools.
  16981. //this.high_water = 0;
  16982. /* High water mark offset in window for initialized bytes -- bytes above
  16983. * this are set to zero in order to avoid memory check warnings when
  16984. * longest match routines access bytes past the input. This is then
  16985. * updated to the new high water mark.
  16986. */
  16987. }
  16988. function deflateResetKeep(strm) {
  16989. var s;
  16990. if (!strm || !strm.state) {
  16991. return err(strm, Z_STREAM_ERROR);
  16992. }
  16993. strm.total_in = strm.total_out = 0;
  16994. strm.data_type = Z_UNKNOWN;
  16995. s = strm.state;
  16996. s.pending = 0;
  16997. s.pending_out = 0;
  16998. if (s.wrap < 0) {
  16999. s.wrap = -s.wrap;
  17000. /* was made negative by deflate(..., Z_FINISH); */
  17001. }
  17002. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  17003. strm.adler = (s.wrap === 2) ?
  17004. 0 // crc32(0, Z_NULL, 0)
  17005. :
  17006. 1; // adler32(0, Z_NULL, 0)
  17007. s.last_flush = Z_NO_FLUSH;
  17008. trees._tr_init(s);
  17009. return Z_OK;
  17010. }
  17011. function deflateReset(strm) {
  17012. var ret = deflateResetKeep(strm);
  17013. if (ret === Z_OK) {
  17014. lm_init(strm.state);
  17015. }
  17016. return ret;
  17017. }
  17018. function deflateSetHeader(strm, head) {
  17019. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17020. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  17021. strm.state.gzhead = head;
  17022. return Z_OK;
  17023. }
  17024. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  17025. if (!strm) { // === Z_NULL
  17026. return Z_STREAM_ERROR;
  17027. }
  17028. var wrap = 1;
  17029. if (level === Z_DEFAULT_COMPRESSION) {
  17030. level = 6;
  17031. }
  17032. if (windowBits < 0) { /* suppress zlib wrapper */
  17033. wrap = 0;
  17034. windowBits = -windowBits;
  17035. }
  17036. else if (windowBits > 15) {
  17037. wrap = 2; /* write gzip wrapper instead */
  17038. windowBits -= 16;
  17039. }
  17040. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  17041. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  17042. strategy < 0 || strategy > Z_FIXED) {
  17043. return err(strm, Z_STREAM_ERROR);
  17044. }
  17045. if (windowBits === 8) {
  17046. windowBits = 9;
  17047. }
  17048. /* until 256-byte window bug fixed */
  17049. var s = new DeflateState();
  17050. strm.state = s;
  17051. s.strm = strm;
  17052. s.wrap = wrap;
  17053. s.gzhead = null;
  17054. s.w_bits = windowBits;
  17055. s.w_size = 1 << s.w_bits;
  17056. s.w_mask = s.w_size - 1;
  17057. s.hash_bits = memLevel + 7;
  17058. s.hash_size = 1 << s.hash_bits;
  17059. s.hash_mask = s.hash_size - 1;
  17060. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  17061. s.window = new utils.Buf8(s.w_size * 2);
  17062. s.head = new utils.Buf16(s.hash_size);
  17063. s.prev = new utils.Buf16(s.w_size);
  17064. // Don't need mem init magic for JS.
  17065. //s.high_water = 0; /* nothing written to s->window yet */
  17066. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  17067. s.pending_buf_size = s.lit_bufsize * 4;
  17068. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  17069. //s->pending_buf = (uchf *) overlay;
  17070. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  17071. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  17072. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  17073. s.d_buf = 1 * s.lit_bufsize;
  17074. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  17075. s.l_buf = (1 + 2) * s.lit_bufsize;
  17076. s.level = level;
  17077. s.strategy = strategy;
  17078. s.method = method;
  17079. return deflateReset(strm);
  17080. }
  17081. function deflateInit(strm, level) {
  17082. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  17083. }
  17084. function deflate(strm, flush) {
  17085. var old_flush, s;
  17086. var beg, val; // for gzip header write only
  17087. if (!strm || !strm.state ||
  17088. flush > Z_BLOCK || flush < 0) {
  17089. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  17090. }
  17091. s = strm.state;
  17092. if (!strm.output ||
  17093. (!strm.input && strm.avail_in !== 0) ||
  17094. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  17095. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  17096. }
  17097. s.strm = strm; /* just in case */
  17098. old_flush = s.last_flush;
  17099. s.last_flush = flush;
  17100. /* Write the header */
  17101. if (s.status === INIT_STATE) {
  17102. if (s.wrap === 2) { // GZIP header
  17103. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  17104. put_byte(s, 31);
  17105. put_byte(s, 139);
  17106. put_byte(s, 8);
  17107. if (!s.gzhead) { // s->gzhead == Z_NULL
  17108. put_byte(s, 0);
  17109. put_byte(s, 0);
  17110. put_byte(s, 0);
  17111. put_byte(s, 0);
  17112. put_byte(s, 0);
  17113. put_byte(s, s.level === 9 ? 2 :
  17114. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  17115. 4 : 0));
  17116. put_byte(s, OS_CODE);
  17117. s.status = BUSY_STATE;
  17118. }
  17119. else {
  17120. put_byte(s, (s.gzhead.text ? 1 : 0) +
  17121. (s.gzhead.hcrc ? 2 : 0) +
  17122. (!s.gzhead.extra ? 0 : 4) +
  17123. (!s.gzhead.name ? 0 : 8) +
  17124. (!s.gzhead.comment ? 0 : 16)
  17125. );
  17126. put_byte(s, s.gzhead.time & 0xff);
  17127. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  17128. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  17129. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  17130. put_byte(s, s.level === 9 ? 2 :
  17131. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  17132. 4 : 0));
  17133. put_byte(s, s.gzhead.os & 0xff);
  17134. if (s.gzhead.extra && s.gzhead.extra.length) {
  17135. put_byte(s, s.gzhead.extra.length & 0xff);
  17136. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  17137. }
  17138. if (s.gzhead.hcrc) {
  17139. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  17140. }
  17141. s.gzindex = 0;
  17142. s.status = EXTRA_STATE;
  17143. }
  17144. }
  17145. else // DEFLATE header
  17146. {
  17147. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  17148. var level_flags = -1;
  17149. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  17150. level_flags = 0;
  17151. } else if (s.level < 6) {
  17152. level_flags = 1;
  17153. } else if (s.level === 6) {
  17154. level_flags = 2;
  17155. } else {
  17156. level_flags = 3;
  17157. }
  17158. header |= (level_flags << 6);
  17159. if (s.strstart !== 0) { header |= PRESET_DICT; }
  17160. header += 31 - (header % 31);
  17161. s.status = BUSY_STATE;
  17162. putShortMSB(s, header);
  17163. /* Save the adler32 of the preset dictionary: */
  17164. if (s.strstart !== 0) {
  17165. putShortMSB(s, strm.adler >>> 16);
  17166. putShortMSB(s, strm.adler & 0xffff);
  17167. }
  17168. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  17169. }
  17170. }
  17171. //#ifdef GZIP
  17172. if (s.status === EXTRA_STATE) {
  17173. if (s.gzhead.extra/* != Z_NULL*/) {
  17174. beg = s.pending; /* start of bytes to update crc */
  17175. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  17176. if (s.pending === s.pending_buf_size) {
  17177. if (s.gzhead.hcrc && s.pending > beg) {
  17178. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17179. }
  17180. flush_pending(strm);
  17181. beg = s.pending;
  17182. if (s.pending === s.pending_buf_size) {
  17183. break;
  17184. }
  17185. }
  17186. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  17187. s.gzindex++;
  17188. }
  17189. if (s.gzhead.hcrc && s.pending > beg) {
  17190. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17191. }
  17192. if (s.gzindex === s.gzhead.extra.length) {
  17193. s.gzindex = 0;
  17194. s.status = NAME_STATE;
  17195. }
  17196. }
  17197. else {
  17198. s.status = NAME_STATE;
  17199. }
  17200. }
  17201. if (s.status === NAME_STATE) {
  17202. if (s.gzhead.name/* != Z_NULL*/) {
  17203. beg = s.pending; /* start of bytes to update crc */
  17204. //int val;
  17205. do {
  17206. if (s.pending === s.pending_buf_size) {
  17207. if (s.gzhead.hcrc && s.pending > beg) {
  17208. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17209. }
  17210. flush_pending(strm);
  17211. beg = s.pending;
  17212. if (s.pending === s.pending_buf_size) {
  17213. val = 1;
  17214. break;
  17215. }
  17216. }
  17217. // JS specific: little magic to add zero terminator to end of string
  17218. if (s.gzindex < s.gzhead.name.length) {
  17219. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  17220. } else {
  17221. val = 0;
  17222. }
  17223. put_byte(s, val);
  17224. } while (val !== 0);
  17225. if (s.gzhead.hcrc && s.pending > beg) {
  17226. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17227. }
  17228. if (val === 0) {
  17229. s.gzindex = 0;
  17230. s.status = COMMENT_STATE;
  17231. }
  17232. }
  17233. else {
  17234. s.status = COMMENT_STATE;
  17235. }
  17236. }
  17237. if (s.status === COMMENT_STATE) {
  17238. if (s.gzhead.comment/* != Z_NULL*/) {
  17239. beg = s.pending; /* start of bytes to update crc */
  17240. //int val;
  17241. do {
  17242. if (s.pending === s.pending_buf_size) {
  17243. if (s.gzhead.hcrc && s.pending > beg) {
  17244. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17245. }
  17246. flush_pending(strm);
  17247. beg = s.pending;
  17248. if (s.pending === s.pending_buf_size) {
  17249. val = 1;
  17250. break;
  17251. }
  17252. }
  17253. // JS specific: little magic to add zero terminator to end of string
  17254. if (s.gzindex < s.gzhead.comment.length) {
  17255. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  17256. } else {
  17257. val = 0;
  17258. }
  17259. put_byte(s, val);
  17260. } while (val !== 0);
  17261. if (s.gzhead.hcrc && s.pending > beg) {
  17262. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  17263. }
  17264. if (val === 0) {
  17265. s.status = HCRC_STATE;
  17266. }
  17267. }
  17268. else {
  17269. s.status = HCRC_STATE;
  17270. }
  17271. }
  17272. if (s.status === HCRC_STATE) {
  17273. if (s.gzhead.hcrc) {
  17274. if (s.pending + 2 > s.pending_buf_size) {
  17275. flush_pending(strm);
  17276. }
  17277. if (s.pending + 2 <= s.pending_buf_size) {
  17278. put_byte(s, strm.adler & 0xff);
  17279. put_byte(s, (strm.adler >> 8) & 0xff);
  17280. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  17281. s.status = BUSY_STATE;
  17282. }
  17283. }
  17284. else {
  17285. s.status = BUSY_STATE;
  17286. }
  17287. }
  17288. //#endif
  17289. /* Flush as much pending output as possible */
  17290. if (s.pending !== 0) {
  17291. flush_pending(strm);
  17292. if (strm.avail_out === 0) {
  17293. /* Since avail_out is 0, deflate will be called again with
  17294. * more output space, but possibly with both pending and
  17295. * avail_in equal to zero. There won't be anything to do,
  17296. * but this is not an error situation so make sure we
  17297. * return OK instead of BUF_ERROR at next call of deflate:
  17298. */
  17299. s.last_flush = -1;
  17300. return Z_OK;
  17301. }
  17302. /* Make sure there is something to do and avoid duplicate consecutive
  17303. * flushes. For repeated and useless calls with Z_FINISH, we keep
  17304. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  17305. */
  17306. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  17307. flush !== Z_FINISH) {
  17308. return err(strm, Z_BUF_ERROR);
  17309. }
  17310. /* User must not provide more input after the first FINISH: */
  17311. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  17312. return err(strm, Z_BUF_ERROR);
  17313. }
  17314. /* Start a new block or continue the current one.
  17315. */
  17316. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  17317. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  17318. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  17319. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  17320. configuration_table[s.level].func(s, flush));
  17321. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  17322. s.status = FINISH_STATE;
  17323. }
  17324. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  17325. if (strm.avail_out === 0) {
  17326. s.last_flush = -1;
  17327. /* avoid BUF_ERROR next call, see above */
  17328. }
  17329. return Z_OK;
  17330. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  17331. * of deflate should use the same flush parameter to make sure
  17332. * that the flush is complete. So we don't have to output an
  17333. * empty block here, this will be done at next call. This also
  17334. * ensures that for a very small output buffer, we emit at most
  17335. * one empty block.
  17336. */
  17337. }
  17338. if (bstate === BS_BLOCK_DONE) {
  17339. if (flush === Z_PARTIAL_FLUSH) {
  17340. trees._tr_align(s);
  17341. }
  17342. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  17343. trees._tr_stored_block(s, 0, 0, false);
  17344. /* For a full flush, this empty block will be recognized
  17345. * as a special marker by inflate_sync().
  17346. */
  17347. if (flush === Z_FULL_FLUSH) {
  17348. /*** CLEAR_HASH(s); ***/ /* forget history */
  17349. zero(s.head); // Fill with NIL (= 0);
  17350. if (s.lookahead === 0) {
  17351. s.strstart = 0;
  17352. s.block_start = 0;
  17353. s.insert = 0;
  17354. }
  17355. }
  17356. }
  17357. flush_pending(strm);
  17358. if (strm.avail_out === 0) {
  17359. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  17360. return Z_OK;
  17361. }
  17362. }
  17363. }
  17364. //Assert(strm->avail_out > 0, "bug2");
  17365. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  17366. if (flush !== Z_FINISH) { return Z_OK; }
  17367. if (s.wrap <= 0) { return Z_STREAM_END; }
  17368. /* Write the trailer */
  17369. if (s.wrap === 2) {
  17370. put_byte(s, strm.adler & 0xff);
  17371. put_byte(s, (strm.adler >> 8) & 0xff);
  17372. put_byte(s, (strm.adler >> 16) & 0xff);
  17373. put_byte(s, (strm.adler >> 24) & 0xff);
  17374. put_byte(s, strm.total_in & 0xff);
  17375. put_byte(s, (strm.total_in >> 8) & 0xff);
  17376. put_byte(s, (strm.total_in >> 16) & 0xff);
  17377. put_byte(s, (strm.total_in >> 24) & 0xff);
  17378. }
  17379. else
  17380. {
  17381. putShortMSB(s, strm.adler >>> 16);
  17382. putShortMSB(s, strm.adler & 0xffff);
  17383. }
  17384. flush_pending(strm);
  17385. /* If avail_out is zero, the application will call deflate again
  17386. * to flush the rest.
  17387. */
  17388. if (s.wrap > 0) { s.wrap = -s.wrap; }
  17389. /* write the trailer only once! */
  17390. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  17391. }
  17392. function deflateEnd(strm) {
  17393. var status;
  17394. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17395. return Z_STREAM_ERROR;
  17396. }
  17397. status = strm.state.status;
  17398. if (status !== INIT_STATE &&
  17399. status !== EXTRA_STATE &&
  17400. status !== NAME_STATE &&
  17401. status !== COMMENT_STATE &&
  17402. status !== HCRC_STATE &&
  17403. status !== BUSY_STATE &&
  17404. status !== FINISH_STATE
  17405. ) {
  17406. return err(strm, Z_STREAM_ERROR);
  17407. }
  17408. strm.state = null;
  17409. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  17410. }
  17411. /* =========================================================================
  17412. * Initializes the compression dictionary from the given byte
  17413. * sequence without producing any compressed output.
  17414. */
  17415. function deflateSetDictionary(strm, dictionary) {
  17416. var dictLength = dictionary.length;
  17417. var s;
  17418. var str, n;
  17419. var wrap;
  17420. var avail;
  17421. var next;
  17422. var input;
  17423. var tmpDict;
  17424. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17425. return Z_STREAM_ERROR;
  17426. }
  17427. s = strm.state;
  17428. wrap = s.wrap;
  17429. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  17430. return Z_STREAM_ERROR;
  17431. }
  17432. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  17433. if (wrap === 1) {
  17434. /* adler32(strm->adler, dictionary, dictLength); */
  17435. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  17436. }
  17437. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  17438. /* if dictionary would fill window, just replace the history */
  17439. if (dictLength >= s.w_size) {
  17440. if (wrap === 0) { /* already empty otherwise */
  17441. /*** CLEAR_HASH(s); ***/
  17442. zero(s.head); // Fill with NIL (= 0);
  17443. s.strstart = 0;
  17444. s.block_start = 0;
  17445. s.insert = 0;
  17446. }
  17447. /* use the tail */
  17448. // dictionary = dictionary.slice(dictLength - s.w_size);
  17449. tmpDict = new utils.Buf8(s.w_size);
  17450. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  17451. dictionary = tmpDict;
  17452. dictLength = s.w_size;
  17453. }
  17454. /* insert dictionary into window and hash */
  17455. avail = strm.avail_in;
  17456. next = strm.next_in;
  17457. input = strm.input;
  17458. strm.avail_in = dictLength;
  17459. strm.next_in = 0;
  17460. strm.input = dictionary;
  17461. fill_window(s);
  17462. while (s.lookahead >= MIN_MATCH) {
  17463. str = s.strstart;
  17464. n = s.lookahead - (MIN_MATCH - 1);
  17465. do {
  17466. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17467. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  17468. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17469. s.head[s.ins_h] = str;
  17470. str++;
  17471. } while (--n);
  17472. s.strstart = str;
  17473. s.lookahead = MIN_MATCH - 1;
  17474. fill_window(s);
  17475. }
  17476. s.strstart += s.lookahead;
  17477. s.block_start = s.strstart;
  17478. s.insert = s.lookahead;
  17479. s.lookahead = 0;
  17480. s.match_length = s.prev_length = MIN_MATCH - 1;
  17481. s.match_available = 0;
  17482. strm.next_in = next;
  17483. strm.input = input;
  17484. strm.avail_in = avail;
  17485. s.wrap = wrap;
  17486. return Z_OK;
  17487. }
  17488. exports.deflateInit = deflateInit;
  17489. exports.deflateInit2 = deflateInit2;
  17490. exports.deflateReset = deflateReset;
  17491. exports.deflateResetKeep = deflateResetKeep;
  17492. exports.deflateSetHeader = deflateSetHeader;
  17493. exports.deflate = deflate;
  17494. exports.deflateEnd = deflateEnd;
  17495. exports.deflateSetDictionary = deflateSetDictionary;
  17496. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  17497. /* Not implemented
  17498. exports.deflateBound = deflateBound;
  17499. exports.deflateCopy = deflateCopy;
  17500. exports.deflateParams = deflateParams;
  17501. exports.deflatePending = deflatePending;
  17502. exports.deflatePrime = deflatePrime;
  17503. exports.deflateTune = deflateTune;
  17504. */
  17505. },{"../utils/common":123,"./adler32":125,"./crc32":127,"./messages":133,"./trees":134}],129:[function(require,module,exports){
  17506. 'use strict';
  17507. function GZheader() {
  17508. /* true if compressed data believed to be text */
  17509. this.text = 0;
  17510. /* modification time */
  17511. this.time = 0;
  17512. /* extra flags (not used when writing a gzip file) */
  17513. this.xflags = 0;
  17514. /* operating system */
  17515. this.os = 0;
  17516. /* pointer to extra field or Z_NULL if none */
  17517. this.extra = null;
  17518. /* extra field length (valid if extra != Z_NULL) */
  17519. this.extra_len = 0; // Actually, we don't need it in JS,
  17520. // but leave for few code modifications
  17521. //
  17522. // Setup limits is not necessary because in js we should not preallocate memory
  17523. // for inflate use constant limit in 65536 bytes
  17524. //
  17525. /* space at extra (only when reading header) */
  17526. // this.extra_max = 0;
  17527. /* pointer to zero-terminated file name or Z_NULL */
  17528. this.name = '';
  17529. /* space at name (only when reading header) */
  17530. // this.name_max = 0;
  17531. /* pointer to zero-terminated comment or Z_NULL */
  17532. this.comment = '';
  17533. /* space at comment (only when reading header) */
  17534. // this.comm_max = 0;
  17535. /* true if there was or will be a header crc */
  17536. this.hcrc = 0;
  17537. /* true when done reading gzip header (not used when writing a gzip file) */
  17538. this.done = false;
  17539. }
  17540. module.exports = GZheader;
  17541. },{}],130:[function(require,module,exports){
  17542. 'use strict';
  17543. // See state defs from inflate.js
  17544. var BAD = 30; /* got a data error -- remain here until reset */
  17545. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17546. /*
  17547. Decode literal, length, and distance codes and write out the resulting
  17548. literal and match bytes until either not enough input or output is
  17549. available, an end-of-block is encountered, or a data error is encountered.
  17550. When large enough input and output buffers are supplied to inflate(), for
  17551. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  17552. inflate execution time is spent in this routine.
  17553. Entry assumptions:
  17554. state.mode === LEN
  17555. strm.avail_in >= 6
  17556. strm.avail_out >= 258
  17557. start >= strm.avail_out
  17558. state.bits < 8
  17559. On return, state.mode is one of:
  17560. LEN -- ran out of enough output space or enough available input
  17561. TYPE -- reached end of block code, inflate() to interpret next block
  17562. BAD -- error in block data
  17563. Notes:
  17564. - The maximum input bits used by a length/distance pair is 15 bits for the
  17565. length code, 5 bits for the length extra, 15 bits for the distance code,
  17566. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  17567. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  17568. checking for available input while decoding.
  17569. - The maximum bytes that a single length/distance pair can output is 258
  17570. bytes, which is the maximum length that can be coded. inflate_fast()
  17571. requires strm.avail_out >= 258 for each loop to avoid checking for
  17572. output space.
  17573. */
  17574. module.exports = function inflate_fast(strm, start) {
  17575. var state;
  17576. var _in; /* local strm.input */
  17577. var last; /* have enough input while in < last */
  17578. var _out; /* local strm.output */
  17579. var beg; /* inflate()'s initial strm.output */
  17580. var end; /* while out < end, enough space available */
  17581. //#ifdef INFLATE_STRICT
  17582. var dmax; /* maximum distance from zlib header */
  17583. //#endif
  17584. var wsize; /* window size or zero if not using window */
  17585. var whave; /* valid bytes in the window */
  17586. var wnext; /* window write index */
  17587. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  17588. var s_window; /* allocated sliding window, if wsize != 0 */
  17589. var hold; /* local strm.hold */
  17590. var bits; /* local strm.bits */
  17591. var lcode; /* local strm.lencode */
  17592. var dcode; /* local strm.distcode */
  17593. var lmask; /* mask for first level of length codes */
  17594. var dmask; /* mask for first level of distance codes */
  17595. var here; /* retrieved table entry */
  17596. var op; /* code bits, operation, extra bits, or */
  17597. /* window position, window bytes to copy */
  17598. var len; /* match length, unused bytes */
  17599. var dist; /* match distance */
  17600. var from; /* where to copy match from */
  17601. var from_source;
  17602. var input, output; // JS specific, because we have no pointers
  17603. /* copy state to local variables */
  17604. state = strm.state;
  17605. //here = state.here;
  17606. _in = strm.next_in;
  17607. input = strm.input;
  17608. last = _in + (strm.avail_in - 5);
  17609. _out = strm.next_out;
  17610. output = strm.output;
  17611. beg = _out - (start - strm.avail_out);
  17612. end = _out + (strm.avail_out - 257);
  17613. //#ifdef INFLATE_STRICT
  17614. dmax = state.dmax;
  17615. //#endif
  17616. wsize = state.wsize;
  17617. whave = state.whave;
  17618. wnext = state.wnext;
  17619. s_window = state.window;
  17620. hold = state.hold;
  17621. bits = state.bits;
  17622. lcode = state.lencode;
  17623. dcode = state.distcode;
  17624. lmask = (1 << state.lenbits) - 1;
  17625. dmask = (1 << state.distbits) - 1;
  17626. /* decode literals and length/distances until end-of-block or not enough
  17627. input data or output space */
  17628. top:
  17629. do {
  17630. if (bits < 15) {
  17631. hold += input[_in++] << bits;
  17632. bits += 8;
  17633. hold += input[_in++] << bits;
  17634. bits += 8;
  17635. }
  17636. here = lcode[hold & lmask];
  17637. dolen:
  17638. for (;;) { // Goto emulation
  17639. op = here >>> 24/*here.bits*/;
  17640. hold >>>= op;
  17641. bits -= op;
  17642. op = (here >>> 16) & 0xff/*here.op*/;
  17643. if (op === 0) { /* literal */
  17644. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17645. // "inflate: literal '%c'\n" :
  17646. // "inflate: literal 0x%02x\n", here.val));
  17647. output[_out++] = here & 0xffff/*here.val*/;
  17648. }
  17649. else if (op & 16) { /* length base */
  17650. len = here & 0xffff/*here.val*/;
  17651. op &= 15; /* number of extra bits */
  17652. if (op) {
  17653. if (bits < op) {
  17654. hold += input[_in++] << bits;
  17655. bits += 8;
  17656. }
  17657. len += hold & ((1 << op) - 1);
  17658. hold >>>= op;
  17659. bits -= op;
  17660. }
  17661. //Tracevv((stderr, "inflate: length %u\n", len));
  17662. if (bits < 15) {
  17663. hold += input[_in++] << bits;
  17664. bits += 8;
  17665. hold += input[_in++] << bits;
  17666. bits += 8;
  17667. }
  17668. here = dcode[hold & dmask];
  17669. dodist:
  17670. for (;;) { // goto emulation
  17671. op = here >>> 24/*here.bits*/;
  17672. hold >>>= op;
  17673. bits -= op;
  17674. op = (here >>> 16) & 0xff/*here.op*/;
  17675. if (op & 16) { /* distance base */
  17676. dist = here & 0xffff/*here.val*/;
  17677. op &= 15; /* number of extra bits */
  17678. if (bits < op) {
  17679. hold += input[_in++] << bits;
  17680. bits += 8;
  17681. if (bits < op) {
  17682. hold += input[_in++] << bits;
  17683. bits += 8;
  17684. }
  17685. }
  17686. dist += hold & ((1 << op) - 1);
  17687. //#ifdef INFLATE_STRICT
  17688. if (dist > dmax) {
  17689. strm.msg = 'invalid distance too far back';
  17690. state.mode = BAD;
  17691. break top;
  17692. }
  17693. //#endif
  17694. hold >>>= op;
  17695. bits -= op;
  17696. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17697. op = _out - beg; /* max distance in output */
  17698. if (dist > op) { /* see if copy from window */
  17699. op = dist - op; /* distance back in window */
  17700. if (op > whave) {
  17701. if (state.sane) {
  17702. strm.msg = 'invalid distance too far back';
  17703. state.mode = BAD;
  17704. break top;
  17705. }
  17706. // (!) This block is disabled in zlib defailts,
  17707. // don't enable it for binary compatibility
  17708. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17709. // if (len <= op - whave) {
  17710. // do {
  17711. // output[_out++] = 0;
  17712. // } while (--len);
  17713. // continue top;
  17714. // }
  17715. // len -= op - whave;
  17716. // do {
  17717. // output[_out++] = 0;
  17718. // } while (--op > whave);
  17719. // if (op === 0) {
  17720. // from = _out - dist;
  17721. // do {
  17722. // output[_out++] = output[from++];
  17723. // } while (--len);
  17724. // continue top;
  17725. // }
  17726. //#endif
  17727. }
  17728. from = 0; // window index
  17729. from_source = s_window;
  17730. if (wnext === 0) { /* very common case */
  17731. from += wsize - op;
  17732. if (op < len) { /* some from window */
  17733. len -= op;
  17734. do {
  17735. output[_out++] = s_window[from++];
  17736. } while (--op);
  17737. from = _out - dist; /* rest from output */
  17738. from_source = output;
  17739. }
  17740. }
  17741. else if (wnext < op) { /* wrap around window */
  17742. from += wsize + wnext - op;
  17743. op -= wnext;
  17744. if (op < len) { /* some from end of window */
  17745. len -= op;
  17746. do {
  17747. output[_out++] = s_window[from++];
  17748. } while (--op);
  17749. from = 0;
  17750. if (wnext < len) { /* some from start of window */
  17751. op = wnext;
  17752. len -= op;
  17753. do {
  17754. output[_out++] = s_window[from++];
  17755. } while (--op);
  17756. from = _out - dist; /* rest from output */
  17757. from_source = output;
  17758. }
  17759. }
  17760. }
  17761. else { /* contiguous in window */
  17762. from += wnext - op;
  17763. if (op < len) { /* some from window */
  17764. len -= op;
  17765. do {
  17766. output[_out++] = s_window[from++];
  17767. } while (--op);
  17768. from = _out - dist; /* rest from output */
  17769. from_source = output;
  17770. }
  17771. }
  17772. while (len > 2) {
  17773. output[_out++] = from_source[from++];
  17774. output[_out++] = from_source[from++];
  17775. output[_out++] = from_source[from++];
  17776. len -= 3;
  17777. }
  17778. if (len) {
  17779. output[_out++] = from_source[from++];
  17780. if (len > 1) {
  17781. output[_out++] = from_source[from++];
  17782. }
  17783. }
  17784. }
  17785. else {
  17786. from = _out - dist; /* copy direct from output */
  17787. do { /* minimum length is three */
  17788. output[_out++] = output[from++];
  17789. output[_out++] = output[from++];
  17790. output[_out++] = output[from++];
  17791. len -= 3;
  17792. } while (len > 2);
  17793. if (len) {
  17794. output[_out++] = output[from++];
  17795. if (len > 1) {
  17796. output[_out++] = output[from++];
  17797. }
  17798. }
  17799. }
  17800. }
  17801. else if ((op & 64) === 0) { /* 2nd level distance code */
  17802. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17803. continue dodist;
  17804. }
  17805. else {
  17806. strm.msg = 'invalid distance code';
  17807. state.mode = BAD;
  17808. break top;
  17809. }
  17810. break; // need to emulate goto via "continue"
  17811. }
  17812. }
  17813. else if ((op & 64) === 0) { /* 2nd level length code */
  17814. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17815. continue dolen;
  17816. }
  17817. else if (op & 32) { /* end-of-block */
  17818. //Tracevv((stderr, "inflate: end of block\n"));
  17819. state.mode = TYPE;
  17820. break top;
  17821. }
  17822. else {
  17823. strm.msg = 'invalid literal/length code';
  17824. state.mode = BAD;
  17825. break top;
  17826. }
  17827. break; // need to emulate goto via "continue"
  17828. }
  17829. } while (_in < last && _out < end);
  17830. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17831. len = bits >> 3;
  17832. _in -= len;
  17833. bits -= len << 3;
  17834. hold &= (1 << bits) - 1;
  17835. /* update state and return */
  17836. strm.next_in = _in;
  17837. strm.next_out = _out;
  17838. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17839. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17840. state.hold = hold;
  17841. state.bits = bits;
  17842. return;
  17843. };
  17844. },{}],131:[function(require,module,exports){
  17845. 'use strict';
  17846. var utils = require('../utils/common');
  17847. var adler32 = require('./adler32');
  17848. var crc32 = require('./crc32');
  17849. var inflate_fast = require('./inffast');
  17850. var inflate_table = require('./inftrees');
  17851. var CODES = 0;
  17852. var LENS = 1;
  17853. var DISTS = 2;
  17854. /* Public constants ==========================================================*/
  17855. /* ===========================================================================*/
  17856. /* Allowed flush values; see deflate() and inflate() below for details */
  17857. //var Z_NO_FLUSH = 0;
  17858. //var Z_PARTIAL_FLUSH = 1;
  17859. //var Z_SYNC_FLUSH = 2;
  17860. //var Z_FULL_FLUSH = 3;
  17861. var Z_FINISH = 4;
  17862. var Z_BLOCK = 5;
  17863. var Z_TREES = 6;
  17864. /* Return codes for the compression/decompression functions. Negative values
  17865. * are errors, positive values are used for special but normal events.
  17866. */
  17867. var Z_OK = 0;
  17868. var Z_STREAM_END = 1;
  17869. var Z_NEED_DICT = 2;
  17870. //var Z_ERRNO = -1;
  17871. var Z_STREAM_ERROR = -2;
  17872. var Z_DATA_ERROR = -3;
  17873. var Z_MEM_ERROR = -4;
  17874. var Z_BUF_ERROR = -5;
  17875. //var Z_VERSION_ERROR = -6;
  17876. /* The deflate compression method */
  17877. var Z_DEFLATED = 8;
  17878. /* STATES ====================================================================*/
  17879. /* ===========================================================================*/
  17880. var HEAD = 1; /* i: waiting for magic header */
  17881. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17882. var TIME = 3; /* i: waiting for modification time (gzip) */
  17883. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17884. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17885. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17886. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17887. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17888. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17889. var DICTID = 10; /* i: waiting for dictionary check value */
  17890. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17891. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17892. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17893. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17894. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17895. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17896. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17897. var LENLENS = 18; /* i: waiting for code length code lengths */
  17898. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17899. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17900. var LEN = 21; /* i: waiting for length/lit/eob code */
  17901. var LENEXT = 22; /* i: waiting for length extra bits */
  17902. var DIST = 23; /* i: waiting for distance code */
  17903. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17904. var MATCH = 25; /* o: waiting for output space to copy string */
  17905. var LIT = 26; /* o: waiting for output space to write literal */
  17906. var CHECK = 27; /* i: waiting for 32-bit check value */
  17907. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17908. var DONE = 29; /* finished check, done -- remain here until reset */
  17909. var BAD = 30; /* got a data error -- remain here until reset */
  17910. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17911. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17912. /* ===========================================================================*/
  17913. var ENOUGH_LENS = 852;
  17914. var ENOUGH_DISTS = 592;
  17915. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17916. var MAX_WBITS = 15;
  17917. /* 32K LZ77 window */
  17918. var DEF_WBITS = MAX_WBITS;
  17919. function zswap32(q) {
  17920. return (((q >>> 24) & 0xff) +
  17921. ((q >>> 8) & 0xff00) +
  17922. ((q & 0xff00) << 8) +
  17923. ((q & 0xff) << 24));
  17924. }
  17925. function InflateState() {
  17926. this.mode = 0; /* current inflate mode */
  17927. this.last = false; /* true if processing last block */
  17928. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17929. this.havedict = false; /* true if dictionary provided */
  17930. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17931. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17932. this.check = 0; /* protected copy of check value */
  17933. this.total = 0; /* protected copy of output count */
  17934. // TODO: may be {}
  17935. this.head = null; /* where to save gzip header information */
  17936. /* sliding window */
  17937. this.wbits = 0; /* log base 2 of requested window size */
  17938. this.wsize = 0; /* window size or zero if not using window */
  17939. this.whave = 0; /* valid bytes in the window */
  17940. this.wnext = 0; /* window write index */
  17941. this.window = null; /* allocated sliding window, if needed */
  17942. /* bit accumulator */
  17943. this.hold = 0; /* input bit accumulator */
  17944. this.bits = 0; /* number of bits in "in" */
  17945. /* for string and stored block copying */
  17946. this.length = 0; /* literal or length of data to copy */
  17947. this.offset = 0; /* distance back to copy string from */
  17948. /* for table and code decoding */
  17949. this.extra = 0; /* extra bits needed */
  17950. /* fixed and dynamic code tables */
  17951. this.lencode = null; /* starting table for length/literal codes */
  17952. this.distcode = null; /* starting table for distance codes */
  17953. this.lenbits = 0; /* index bits for lencode */
  17954. this.distbits = 0; /* index bits for distcode */
  17955. /* dynamic table building */
  17956. this.ncode = 0; /* number of code length code lengths */
  17957. this.nlen = 0; /* number of length code lengths */
  17958. this.ndist = 0; /* number of distance code lengths */
  17959. this.have = 0; /* number of code lengths in lens[] */
  17960. this.next = null; /* next available space in codes[] */
  17961. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17962. this.work = new utils.Buf16(288); /* work area for code table building */
  17963. /*
  17964. because we don't have pointers in js, we use lencode and distcode directly
  17965. as buffers so we don't need codes
  17966. */
  17967. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17968. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17969. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17970. this.sane = 0; /* if false, allow invalid distance too far */
  17971. this.back = 0; /* bits back of last unprocessed length/lit */
  17972. this.was = 0; /* initial length of match */
  17973. }
  17974. function inflateResetKeep(strm) {
  17975. var state;
  17976. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17977. state = strm.state;
  17978. strm.total_in = strm.total_out = state.total = 0;
  17979. strm.msg = ''; /*Z_NULL*/
  17980. if (state.wrap) { /* to support ill-conceived Java test suite */
  17981. strm.adler = state.wrap & 1;
  17982. }
  17983. state.mode = HEAD;
  17984. state.last = 0;
  17985. state.havedict = 0;
  17986. state.dmax = 32768;
  17987. state.head = null/*Z_NULL*/;
  17988. state.hold = 0;
  17989. state.bits = 0;
  17990. //state.lencode = state.distcode = state.next = state.codes;
  17991. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17992. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17993. state.sane = 1;
  17994. state.back = -1;
  17995. //Tracev((stderr, "inflate: reset\n"));
  17996. return Z_OK;
  17997. }
  17998. function inflateReset(strm) {
  17999. var state;
  18000. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18001. state = strm.state;
  18002. state.wsize = 0;
  18003. state.whave = 0;
  18004. state.wnext = 0;
  18005. return inflateResetKeep(strm);
  18006. }
  18007. function inflateReset2(strm, windowBits) {
  18008. var wrap;
  18009. var state;
  18010. /* get the state */
  18011. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18012. state = strm.state;
  18013. /* extract wrap request from windowBits parameter */
  18014. if (windowBits < 0) {
  18015. wrap = 0;
  18016. windowBits = -windowBits;
  18017. }
  18018. else {
  18019. wrap = (windowBits >> 4) + 1;
  18020. if (windowBits < 48) {
  18021. windowBits &= 15;
  18022. }
  18023. }
  18024. /* set number of window bits, free window if different */
  18025. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  18026. return Z_STREAM_ERROR;
  18027. }
  18028. if (state.window !== null && state.wbits !== windowBits) {
  18029. state.window = null;
  18030. }
  18031. /* update state and reset the rest of it */
  18032. state.wrap = wrap;
  18033. state.wbits = windowBits;
  18034. return inflateReset(strm);
  18035. }
  18036. function inflateInit2(strm, windowBits) {
  18037. var ret;
  18038. var state;
  18039. if (!strm) { return Z_STREAM_ERROR; }
  18040. //strm.msg = Z_NULL; /* in case we return an error */
  18041. state = new InflateState();
  18042. //if (state === Z_NULL) return Z_MEM_ERROR;
  18043. //Tracev((stderr, "inflate: allocated\n"));
  18044. strm.state = state;
  18045. state.window = null/*Z_NULL*/;
  18046. ret = inflateReset2(strm, windowBits);
  18047. if (ret !== Z_OK) {
  18048. strm.state = null/*Z_NULL*/;
  18049. }
  18050. return ret;
  18051. }
  18052. function inflateInit(strm) {
  18053. return inflateInit2(strm, DEF_WBITS);
  18054. }
  18055. /*
  18056. Return state with length and distance decoding tables and index sizes set to
  18057. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  18058. If BUILDFIXED is defined, then instead this routine builds the tables the
  18059. first time it's called, and returns those tables the first time and
  18060. thereafter. This reduces the size of the code by about 2K bytes, in
  18061. exchange for a little execution time. However, BUILDFIXED should not be
  18062. used for threaded applications, since the rewriting of the tables and virgin
  18063. may not be thread-safe.
  18064. */
  18065. var virgin = true;
  18066. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  18067. function fixedtables(state) {
  18068. /* build fixed huffman tables if first call (may not be thread safe) */
  18069. if (virgin) {
  18070. var sym;
  18071. lenfix = new utils.Buf32(512);
  18072. distfix = new utils.Buf32(32);
  18073. /* literal/length table */
  18074. sym = 0;
  18075. while (sym < 144) { state.lens[sym++] = 8; }
  18076. while (sym < 256) { state.lens[sym++] = 9; }
  18077. while (sym < 280) { state.lens[sym++] = 7; }
  18078. while (sym < 288) { state.lens[sym++] = 8; }
  18079. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  18080. /* distance table */
  18081. sym = 0;
  18082. while (sym < 32) { state.lens[sym++] = 5; }
  18083. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  18084. /* do this just once */
  18085. virgin = false;
  18086. }
  18087. state.lencode = lenfix;
  18088. state.lenbits = 9;
  18089. state.distcode = distfix;
  18090. state.distbits = 5;
  18091. }
  18092. /*
  18093. Update the window with the last wsize (normally 32K) bytes written before
  18094. returning. If window does not exist yet, create it. This is only called
  18095. when a window is already in use, or when output has been written during this
  18096. inflate call, but the end of the deflate stream has not been reached yet.
  18097. It is also called to create a window for dictionary data when a dictionary
  18098. is loaded.
  18099. Providing output buffers larger than 32K to inflate() should provide a speed
  18100. advantage, since only the last 32K of output is copied to the sliding window
  18101. upon return from inflate(), and since all distances after the first 32K of
  18102. output will fall in the output data, making match copies simpler and faster.
  18103. The advantage may be dependent on the size of the processor's data caches.
  18104. */
  18105. function updatewindow(strm, src, end, copy) {
  18106. var dist;
  18107. var state = strm.state;
  18108. /* if it hasn't been done already, allocate space for the window */
  18109. if (state.window === null) {
  18110. state.wsize = 1 << state.wbits;
  18111. state.wnext = 0;
  18112. state.whave = 0;
  18113. state.window = new utils.Buf8(state.wsize);
  18114. }
  18115. /* copy state->wsize or less output bytes into the circular window */
  18116. if (copy >= state.wsize) {
  18117. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  18118. state.wnext = 0;
  18119. state.whave = state.wsize;
  18120. }
  18121. else {
  18122. dist = state.wsize - state.wnext;
  18123. if (dist > copy) {
  18124. dist = copy;
  18125. }
  18126. //zmemcpy(state->window + state->wnext, end - copy, dist);
  18127. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  18128. copy -= dist;
  18129. if (copy) {
  18130. //zmemcpy(state->window, end - copy, copy);
  18131. utils.arraySet(state.window, src, end - copy, copy, 0);
  18132. state.wnext = copy;
  18133. state.whave = state.wsize;
  18134. }
  18135. else {
  18136. state.wnext += dist;
  18137. if (state.wnext === state.wsize) { state.wnext = 0; }
  18138. if (state.whave < state.wsize) { state.whave += dist; }
  18139. }
  18140. }
  18141. return 0;
  18142. }
  18143. function inflate(strm, flush) {
  18144. var state;
  18145. var input, output; // input/output buffers
  18146. var next; /* next input INDEX */
  18147. var put; /* next output INDEX */
  18148. var have, left; /* available input and output */
  18149. var hold; /* bit buffer */
  18150. var bits; /* bits in bit buffer */
  18151. var _in, _out; /* save starting available input and output */
  18152. var copy; /* number of stored or match bytes to copy */
  18153. var from; /* where to copy match bytes from */
  18154. var from_source;
  18155. var here = 0; /* current decoding table entry */
  18156. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  18157. //var last; /* parent table entry */
  18158. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  18159. var len; /* length to copy for repeats, bits to drop */
  18160. var ret; /* return code */
  18161. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  18162. var opts;
  18163. var n; // temporary var for NEED_BITS
  18164. var order = /* permutation of code lengths */
  18165. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  18166. if (!strm || !strm.state || !strm.output ||
  18167. (!strm.input && strm.avail_in !== 0)) {
  18168. return Z_STREAM_ERROR;
  18169. }
  18170. state = strm.state;
  18171. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  18172. //--- LOAD() ---
  18173. put = strm.next_out;
  18174. output = strm.output;
  18175. left = strm.avail_out;
  18176. next = strm.next_in;
  18177. input = strm.input;
  18178. have = strm.avail_in;
  18179. hold = state.hold;
  18180. bits = state.bits;
  18181. //---
  18182. _in = have;
  18183. _out = left;
  18184. ret = Z_OK;
  18185. inf_leave: // goto emulation
  18186. for (;;) {
  18187. switch (state.mode) {
  18188. case HEAD:
  18189. if (state.wrap === 0) {
  18190. state.mode = TYPEDO;
  18191. break;
  18192. }
  18193. //=== NEEDBITS(16);
  18194. while (bits < 16) {
  18195. if (have === 0) { break inf_leave; }
  18196. have--;
  18197. hold += input[next++] << bits;
  18198. bits += 8;
  18199. }
  18200. //===//
  18201. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  18202. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  18203. //=== CRC2(state.check, hold);
  18204. hbuf[0] = hold & 0xff;
  18205. hbuf[1] = (hold >>> 8) & 0xff;
  18206. state.check = crc32(state.check, hbuf, 2, 0);
  18207. //===//
  18208. //=== INITBITS();
  18209. hold = 0;
  18210. bits = 0;
  18211. //===//
  18212. state.mode = FLAGS;
  18213. break;
  18214. }
  18215. state.flags = 0; /* expect zlib header */
  18216. if (state.head) {
  18217. state.head.done = false;
  18218. }
  18219. if (!(state.wrap & 1) || /* check if zlib header allowed */
  18220. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  18221. strm.msg = 'incorrect header check';
  18222. state.mode = BAD;
  18223. break;
  18224. }
  18225. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  18226. strm.msg = 'unknown compression method';
  18227. state.mode = BAD;
  18228. break;
  18229. }
  18230. //--- DROPBITS(4) ---//
  18231. hold >>>= 4;
  18232. bits -= 4;
  18233. //---//
  18234. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  18235. if (state.wbits === 0) {
  18236. state.wbits = len;
  18237. }
  18238. else if (len > state.wbits) {
  18239. strm.msg = 'invalid window size';
  18240. state.mode = BAD;
  18241. break;
  18242. }
  18243. state.dmax = 1 << len;
  18244. //Tracev((stderr, "inflate: zlib header ok\n"));
  18245. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18246. state.mode = hold & 0x200 ? DICTID : TYPE;
  18247. //=== INITBITS();
  18248. hold = 0;
  18249. bits = 0;
  18250. //===//
  18251. break;
  18252. case FLAGS:
  18253. //=== NEEDBITS(16); */
  18254. while (bits < 16) {
  18255. if (have === 0) { break inf_leave; }
  18256. have--;
  18257. hold += input[next++] << bits;
  18258. bits += 8;
  18259. }
  18260. //===//
  18261. state.flags = hold;
  18262. if ((state.flags & 0xff) !== Z_DEFLATED) {
  18263. strm.msg = 'unknown compression method';
  18264. state.mode = BAD;
  18265. break;
  18266. }
  18267. if (state.flags & 0xe000) {
  18268. strm.msg = 'unknown header flags set';
  18269. state.mode = BAD;
  18270. break;
  18271. }
  18272. if (state.head) {
  18273. state.head.text = ((hold >> 8) & 1);
  18274. }
  18275. if (state.flags & 0x0200) {
  18276. //=== CRC2(state.check, hold);
  18277. hbuf[0] = hold & 0xff;
  18278. hbuf[1] = (hold >>> 8) & 0xff;
  18279. state.check = crc32(state.check, hbuf, 2, 0);
  18280. //===//
  18281. }
  18282. //=== INITBITS();
  18283. hold = 0;
  18284. bits = 0;
  18285. //===//
  18286. state.mode = TIME;
  18287. /* falls through */
  18288. case TIME:
  18289. //=== NEEDBITS(32); */
  18290. while (bits < 32) {
  18291. if (have === 0) { break inf_leave; }
  18292. have--;
  18293. hold += input[next++] << bits;
  18294. bits += 8;
  18295. }
  18296. //===//
  18297. if (state.head) {
  18298. state.head.time = hold;
  18299. }
  18300. if (state.flags & 0x0200) {
  18301. //=== CRC4(state.check, hold)
  18302. hbuf[0] = hold & 0xff;
  18303. hbuf[1] = (hold >>> 8) & 0xff;
  18304. hbuf[2] = (hold >>> 16) & 0xff;
  18305. hbuf[3] = (hold >>> 24) & 0xff;
  18306. state.check = crc32(state.check, hbuf, 4, 0);
  18307. //===
  18308. }
  18309. //=== INITBITS();
  18310. hold = 0;
  18311. bits = 0;
  18312. //===//
  18313. state.mode = OS;
  18314. /* falls through */
  18315. case OS:
  18316. //=== NEEDBITS(16); */
  18317. while (bits < 16) {
  18318. if (have === 0) { break inf_leave; }
  18319. have--;
  18320. hold += input[next++] << bits;
  18321. bits += 8;
  18322. }
  18323. //===//
  18324. if (state.head) {
  18325. state.head.xflags = (hold & 0xff);
  18326. state.head.os = (hold >> 8);
  18327. }
  18328. if (state.flags & 0x0200) {
  18329. //=== CRC2(state.check, hold);
  18330. hbuf[0] = hold & 0xff;
  18331. hbuf[1] = (hold >>> 8) & 0xff;
  18332. state.check = crc32(state.check, hbuf, 2, 0);
  18333. //===//
  18334. }
  18335. //=== INITBITS();
  18336. hold = 0;
  18337. bits = 0;
  18338. //===//
  18339. state.mode = EXLEN;
  18340. /* falls through */
  18341. case EXLEN:
  18342. if (state.flags & 0x0400) {
  18343. //=== NEEDBITS(16); */
  18344. while (bits < 16) {
  18345. if (have === 0) { break inf_leave; }
  18346. have--;
  18347. hold += input[next++] << bits;
  18348. bits += 8;
  18349. }
  18350. //===//
  18351. state.length = hold;
  18352. if (state.head) {
  18353. state.head.extra_len = hold;
  18354. }
  18355. if (state.flags & 0x0200) {
  18356. //=== CRC2(state.check, hold);
  18357. hbuf[0] = hold & 0xff;
  18358. hbuf[1] = (hold >>> 8) & 0xff;
  18359. state.check = crc32(state.check, hbuf, 2, 0);
  18360. //===//
  18361. }
  18362. //=== INITBITS();
  18363. hold = 0;
  18364. bits = 0;
  18365. //===//
  18366. }
  18367. else if (state.head) {
  18368. state.head.extra = null/*Z_NULL*/;
  18369. }
  18370. state.mode = EXTRA;
  18371. /* falls through */
  18372. case EXTRA:
  18373. if (state.flags & 0x0400) {
  18374. copy = state.length;
  18375. if (copy > have) { copy = have; }
  18376. if (copy) {
  18377. if (state.head) {
  18378. len = state.head.extra_len - state.length;
  18379. if (!state.head.extra) {
  18380. // Use untyped array for more conveniend processing later
  18381. state.head.extra = new Array(state.head.extra_len);
  18382. }
  18383. utils.arraySet(
  18384. state.head.extra,
  18385. input,
  18386. next,
  18387. // extra field is limited to 65536 bytes
  18388. // - no need for additional size check
  18389. copy,
  18390. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  18391. len
  18392. );
  18393. //zmemcpy(state.head.extra + len, next,
  18394. // len + copy > state.head.extra_max ?
  18395. // state.head.extra_max - len : copy);
  18396. }
  18397. if (state.flags & 0x0200) {
  18398. state.check = crc32(state.check, input, copy, next);
  18399. }
  18400. have -= copy;
  18401. next += copy;
  18402. state.length -= copy;
  18403. }
  18404. if (state.length) { break inf_leave; }
  18405. }
  18406. state.length = 0;
  18407. state.mode = NAME;
  18408. /* falls through */
  18409. case NAME:
  18410. if (state.flags & 0x0800) {
  18411. if (have === 0) { break inf_leave; }
  18412. copy = 0;
  18413. do {
  18414. // TODO: 2 or 1 bytes?
  18415. len = input[next + copy++];
  18416. /* use constant limit because in js we should not preallocate memory */
  18417. if (state.head && len &&
  18418. (state.length < 65536 /*state.head.name_max*/)) {
  18419. state.head.name += String.fromCharCode(len);
  18420. }
  18421. } while (len && copy < have);
  18422. if (state.flags & 0x0200) {
  18423. state.check = crc32(state.check, input, copy, next);
  18424. }
  18425. have -= copy;
  18426. next += copy;
  18427. if (len) { break inf_leave; }
  18428. }
  18429. else if (state.head) {
  18430. state.head.name = null;
  18431. }
  18432. state.length = 0;
  18433. state.mode = COMMENT;
  18434. /* falls through */
  18435. case COMMENT:
  18436. if (state.flags & 0x1000) {
  18437. if (have === 0) { break inf_leave; }
  18438. copy = 0;
  18439. do {
  18440. len = input[next + copy++];
  18441. /* use constant limit because in js we should not preallocate memory */
  18442. if (state.head && len &&
  18443. (state.length < 65536 /*state.head.comm_max*/)) {
  18444. state.head.comment += String.fromCharCode(len);
  18445. }
  18446. } while (len && copy < have);
  18447. if (state.flags & 0x0200) {
  18448. state.check = crc32(state.check, input, copy, next);
  18449. }
  18450. have -= copy;
  18451. next += copy;
  18452. if (len) { break inf_leave; }
  18453. }
  18454. else if (state.head) {
  18455. state.head.comment = null;
  18456. }
  18457. state.mode = HCRC;
  18458. /* falls through */
  18459. case HCRC:
  18460. if (state.flags & 0x0200) {
  18461. //=== NEEDBITS(16); */
  18462. while (bits < 16) {
  18463. if (have === 0) { break inf_leave; }
  18464. have--;
  18465. hold += input[next++] << bits;
  18466. bits += 8;
  18467. }
  18468. //===//
  18469. if (hold !== (state.check & 0xffff)) {
  18470. strm.msg = 'header crc mismatch';
  18471. state.mode = BAD;
  18472. break;
  18473. }
  18474. //=== INITBITS();
  18475. hold = 0;
  18476. bits = 0;
  18477. //===//
  18478. }
  18479. if (state.head) {
  18480. state.head.hcrc = ((state.flags >> 9) & 1);
  18481. state.head.done = true;
  18482. }
  18483. strm.adler = state.check = 0;
  18484. state.mode = TYPE;
  18485. break;
  18486. case DICTID:
  18487. //=== NEEDBITS(32); */
  18488. while (bits < 32) {
  18489. if (have === 0) { break inf_leave; }
  18490. have--;
  18491. hold += input[next++] << bits;
  18492. bits += 8;
  18493. }
  18494. //===//
  18495. strm.adler = state.check = zswap32(hold);
  18496. //=== INITBITS();
  18497. hold = 0;
  18498. bits = 0;
  18499. //===//
  18500. state.mode = DICT;
  18501. /* falls through */
  18502. case DICT:
  18503. if (state.havedict === 0) {
  18504. //--- RESTORE() ---
  18505. strm.next_out = put;
  18506. strm.avail_out = left;
  18507. strm.next_in = next;
  18508. strm.avail_in = have;
  18509. state.hold = hold;
  18510. state.bits = bits;
  18511. //---
  18512. return Z_NEED_DICT;
  18513. }
  18514. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18515. state.mode = TYPE;
  18516. /* falls through */
  18517. case TYPE:
  18518. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  18519. /* falls through */
  18520. case TYPEDO:
  18521. if (state.last) {
  18522. //--- BYTEBITS() ---//
  18523. hold >>>= bits & 7;
  18524. bits -= bits & 7;
  18525. //---//
  18526. state.mode = CHECK;
  18527. break;
  18528. }
  18529. //=== NEEDBITS(3); */
  18530. while (bits < 3) {
  18531. if (have === 0) { break inf_leave; }
  18532. have--;
  18533. hold += input[next++] << bits;
  18534. bits += 8;
  18535. }
  18536. //===//
  18537. state.last = (hold & 0x01)/*BITS(1)*/;
  18538. //--- DROPBITS(1) ---//
  18539. hold >>>= 1;
  18540. bits -= 1;
  18541. //---//
  18542. switch ((hold & 0x03)/*BITS(2)*/) {
  18543. case 0: /* stored block */
  18544. //Tracev((stderr, "inflate: stored block%s\n",
  18545. // state.last ? " (last)" : ""));
  18546. state.mode = STORED;
  18547. break;
  18548. case 1: /* fixed block */
  18549. fixedtables(state);
  18550. //Tracev((stderr, "inflate: fixed codes block%s\n",
  18551. // state.last ? " (last)" : ""));
  18552. state.mode = LEN_; /* decode codes */
  18553. if (flush === Z_TREES) {
  18554. //--- DROPBITS(2) ---//
  18555. hold >>>= 2;
  18556. bits -= 2;
  18557. //---//
  18558. break inf_leave;
  18559. }
  18560. break;
  18561. case 2: /* dynamic block */
  18562. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  18563. // state.last ? " (last)" : ""));
  18564. state.mode = TABLE;
  18565. break;
  18566. case 3:
  18567. strm.msg = 'invalid block type';
  18568. state.mode = BAD;
  18569. }
  18570. //--- DROPBITS(2) ---//
  18571. hold >>>= 2;
  18572. bits -= 2;
  18573. //---//
  18574. break;
  18575. case STORED:
  18576. //--- BYTEBITS() ---// /* go to byte boundary */
  18577. hold >>>= bits & 7;
  18578. bits -= bits & 7;
  18579. //---//
  18580. //=== NEEDBITS(32); */
  18581. while (bits < 32) {
  18582. if (have === 0) { break inf_leave; }
  18583. have--;
  18584. hold += input[next++] << bits;
  18585. bits += 8;
  18586. }
  18587. //===//
  18588. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  18589. strm.msg = 'invalid stored block lengths';
  18590. state.mode = BAD;
  18591. break;
  18592. }
  18593. state.length = hold & 0xffff;
  18594. //Tracev((stderr, "inflate: stored length %u\n",
  18595. // state.length));
  18596. //=== INITBITS();
  18597. hold = 0;
  18598. bits = 0;
  18599. //===//
  18600. state.mode = COPY_;
  18601. if (flush === Z_TREES) { break inf_leave; }
  18602. /* falls through */
  18603. case COPY_:
  18604. state.mode = COPY;
  18605. /* falls through */
  18606. case COPY:
  18607. copy = state.length;
  18608. if (copy) {
  18609. if (copy > have) { copy = have; }
  18610. if (copy > left) { copy = left; }
  18611. if (copy === 0) { break inf_leave; }
  18612. //--- zmemcpy(put, next, copy); ---
  18613. utils.arraySet(output, input, next, copy, put);
  18614. //---//
  18615. have -= copy;
  18616. next += copy;
  18617. left -= copy;
  18618. put += copy;
  18619. state.length -= copy;
  18620. break;
  18621. }
  18622. //Tracev((stderr, "inflate: stored end\n"));
  18623. state.mode = TYPE;
  18624. break;
  18625. case TABLE:
  18626. //=== NEEDBITS(14); */
  18627. while (bits < 14) {
  18628. if (have === 0) { break inf_leave; }
  18629. have--;
  18630. hold += input[next++] << bits;
  18631. bits += 8;
  18632. }
  18633. //===//
  18634. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18635. //--- DROPBITS(5) ---//
  18636. hold >>>= 5;
  18637. bits -= 5;
  18638. //---//
  18639. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18640. //--- DROPBITS(5) ---//
  18641. hold >>>= 5;
  18642. bits -= 5;
  18643. //---//
  18644. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18645. //--- DROPBITS(4) ---//
  18646. hold >>>= 4;
  18647. bits -= 4;
  18648. //---//
  18649. //#ifndef PKZIP_BUG_WORKAROUND
  18650. if (state.nlen > 286 || state.ndist > 30) {
  18651. strm.msg = 'too many length or distance symbols';
  18652. state.mode = BAD;
  18653. break;
  18654. }
  18655. //#endif
  18656. //Tracev((stderr, "inflate: table sizes ok\n"));
  18657. state.have = 0;
  18658. state.mode = LENLENS;
  18659. /* falls through */
  18660. case LENLENS:
  18661. while (state.have < state.ncode) {
  18662. //=== NEEDBITS(3);
  18663. while (bits < 3) {
  18664. if (have === 0) { break inf_leave; }
  18665. have--;
  18666. hold += input[next++] << bits;
  18667. bits += 8;
  18668. }
  18669. //===//
  18670. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18671. //--- DROPBITS(3) ---//
  18672. hold >>>= 3;
  18673. bits -= 3;
  18674. //---//
  18675. }
  18676. while (state.have < 19) {
  18677. state.lens[order[state.have++]] = 0;
  18678. }
  18679. // We have separate tables & no pointers. 2 commented lines below not needed.
  18680. //state.next = state.codes;
  18681. //state.lencode = state.next;
  18682. // Switch to use dynamic table
  18683. state.lencode = state.lendyn;
  18684. state.lenbits = 7;
  18685. opts = { bits: state.lenbits };
  18686. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18687. state.lenbits = opts.bits;
  18688. if (ret) {
  18689. strm.msg = 'invalid code lengths set';
  18690. state.mode = BAD;
  18691. break;
  18692. }
  18693. //Tracev((stderr, "inflate: code lengths ok\n"));
  18694. state.have = 0;
  18695. state.mode = CODELENS;
  18696. /* falls through */
  18697. case CODELENS:
  18698. while (state.have < state.nlen + state.ndist) {
  18699. for (;;) {
  18700. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18701. here_bits = here >>> 24;
  18702. here_op = (here >>> 16) & 0xff;
  18703. here_val = here & 0xffff;
  18704. if ((here_bits) <= bits) { break; }
  18705. //--- PULLBYTE() ---//
  18706. if (have === 0) { break inf_leave; }
  18707. have--;
  18708. hold += input[next++] << bits;
  18709. bits += 8;
  18710. //---//
  18711. }
  18712. if (here_val < 16) {
  18713. //--- DROPBITS(here.bits) ---//
  18714. hold >>>= here_bits;
  18715. bits -= here_bits;
  18716. //---//
  18717. state.lens[state.have++] = here_val;
  18718. }
  18719. else {
  18720. if (here_val === 16) {
  18721. //=== NEEDBITS(here.bits + 2);
  18722. n = here_bits + 2;
  18723. while (bits < n) {
  18724. if (have === 0) { break inf_leave; }
  18725. have--;
  18726. hold += input[next++] << bits;
  18727. bits += 8;
  18728. }
  18729. //===//
  18730. //--- DROPBITS(here.bits) ---//
  18731. hold >>>= here_bits;
  18732. bits -= here_bits;
  18733. //---//
  18734. if (state.have === 0) {
  18735. strm.msg = 'invalid bit length repeat';
  18736. state.mode = BAD;
  18737. break;
  18738. }
  18739. len = state.lens[state.have - 1];
  18740. copy = 3 + (hold & 0x03);//BITS(2);
  18741. //--- DROPBITS(2) ---//
  18742. hold >>>= 2;
  18743. bits -= 2;
  18744. //---//
  18745. }
  18746. else if (here_val === 17) {
  18747. //=== NEEDBITS(here.bits + 3);
  18748. n = here_bits + 3;
  18749. while (bits < n) {
  18750. if (have === 0) { break inf_leave; }
  18751. have--;
  18752. hold += input[next++] << bits;
  18753. bits += 8;
  18754. }
  18755. //===//
  18756. //--- DROPBITS(here.bits) ---//
  18757. hold >>>= here_bits;
  18758. bits -= here_bits;
  18759. //---//
  18760. len = 0;
  18761. copy = 3 + (hold & 0x07);//BITS(3);
  18762. //--- DROPBITS(3) ---//
  18763. hold >>>= 3;
  18764. bits -= 3;
  18765. //---//
  18766. }
  18767. else {
  18768. //=== NEEDBITS(here.bits + 7);
  18769. n = here_bits + 7;
  18770. while (bits < n) {
  18771. if (have === 0) { break inf_leave; }
  18772. have--;
  18773. hold += input[next++] << bits;
  18774. bits += 8;
  18775. }
  18776. //===//
  18777. //--- DROPBITS(here.bits) ---//
  18778. hold >>>= here_bits;
  18779. bits -= here_bits;
  18780. //---//
  18781. len = 0;
  18782. copy = 11 + (hold & 0x7f);//BITS(7);
  18783. //--- DROPBITS(7) ---//
  18784. hold >>>= 7;
  18785. bits -= 7;
  18786. //---//
  18787. }
  18788. if (state.have + copy > state.nlen + state.ndist) {
  18789. strm.msg = 'invalid bit length repeat';
  18790. state.mode = BAD;
  18791. break;
  18792. }
  18793. while (copy--) {
  18794. state.lens[state.have++] = len;
  18795. }
  18796. }
  18797. }
  18798. /* handle error breaks in while */
  18799. if (state.mode === BAD) { break; }
  18800. /* check for end-of-block code (better have one) */
  18801. if (state.lens[256] === 0) {
  18802. strm.msg = 'invalid code -- missing end-of-block';
  18803. state.mode = BAD;
  18804. break;
  18805. }
  18806. /* build code tables -- note: do not change the lenbits or distbits
  18807. values here (9 and 6) without reading the comments in inftrees.h
  18808. concerning the ENOUGH constants, which depend on those values */
  18809. state.lenbits = 9;
  18810. opts = { bits: state.lenbits };
  18811. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18812. // We have separate tables & no pointers. 2 commented lines below not needed.
  18813. // state.next_index = opts.table_index;
  18814. state.lenbits = opts.bits;
  18815. // state.lencode = state.next;
  18816. if (ret) {
  18817. strm.msg = 'invalid literal/lengths set';
  18818. state.mode = BAD;
  18819. break;
  18820. }
  18821. state.distbits = 6;
  18822. //state.distcode.copy(state.codes);
  18823. // Switch to use dynamic table
  18824. state.distcode = state.distdyn;
  18825. opts = { bits: state.distbits };
  18826. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18827. // We have separate tables & no pointers. 2 commented lines below not needed.
  18828. // state.next_index = opts.table_index;
  18829. state.distbits = opts.bits;
  18830. // state.distcode = state.next;
  18831. if (ret) {
  18832. strm.msg = 'invalid distances set';
  18833. state.mode = BAD;
  18834. break;
  18835. }
  18836. //Tracev((stderr, 'inflate: codes ok\n'));
  18837. state.mode = LEN_;
  18838. if (flush === Z_TREES) { break inf_leave; }
  18839. /* falls through */
  18840. case LEN_:
  18841. state.mode = LEN;
  18842. /* falls through */
  18843. case LEN:
  18844. if (have >= 6 && left >= 258) {
  18845. //--- RESTORE() ---
  18846. strm.next_out = put;
  18847. strm.avail_out = left;
  18848. strm.next_in = next;
  18849. strm.avail_in = have;
  18850. state.hold = hold;
  18851. state.bits = bits;
  18852. //---
  18853. inflate_fast(strm, _out);
  18854. //--- LOAD() ---
  18855. put = strm.next_out;
  18856. output = strm.output;
  18857. left = strm.avail_out;
  18858. next = strm.next_in;
  18859. input = strm.input;
  18860. have = strm.avail_in;
  18861. hold = state.hold;
  18862. bits = state.bits;
  18863. //---
  18864. if (state.mode === TYPE) {
  18865. state.back = -1;
  18866. }
  18867. break;
  18868. }
  18869. state.back = 0;
  18870. for (;;) {
  18871. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  18872. here_bits = here >>> 24;
  18873. here_op = (here >>> 16) & 0xff;
  18874. here_val = here & 0xffff;
  18875. if (here_bits <= bits) { break; }
  18876. //--- PULLBYTE() ---//
  18877. if (have === 0) { break inf_leave; }
  18878. have--;
  18879. hold += input[next++] << bits;
  18880. bits += 8;
  18881. //---//
  18882. }
  18883. if (here_op && (here_op & 0xf0) === 0) {
  18884. last_bits = here_bits;
  18885. last_op = here_op;
  18886. last_val = here_val;
  18887. for (;;) {
  18888. here = state.lencode[last_val +
  18889. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18890. here_bits = here >>> 24;
  18891. here_op = (here >>> 16) & 0xff;
  18892. here_val = here & 0xffff;
  18893. if ((last_bits + here_bits) <= bits) { break; }
  18894. //--- PULLBYTE() ---//
  18895. if (have === 0) { break inf_leave; }
  18896. have--;
  18897. hold += input[next++] << bits;
  18898. bits += 8;
  18899. //---//
  18900. }
  18901. //--- DROPBITS(last.bits) ---//
  18902. hold >>>= last_bits;
  18903. bits -= last_bits;
  18904. //---//
  18905. state.back += last_bits;
  18906. }
  18907. //--- DROPBITS(here.bits) ---//
  18908. hold >>>= here_bits;
  18909. bits -= here_bits;
  18910. //---//
  18911. state.back += here_bits;
  18912. state.length = here_val;
  18913. if (here_op === 0) {
  18914. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18915. // "inflate: literal '%c'\n" :
  18916. // "inflate: literal 0x%02x\n", here.val));
  18917. state.mode = LIT;
  18918. break;
  18919. }
  18920. if (here_op & 32) {
  18921. //Tracevv((stderr, "inflate: end of block\n"));
  18922. state.back = -1;
  18923. state.mode = TYPE;
  18924. break;
  18925. }
  18926. if (here_op & 64) {
  18927. strm.msg = 'invalid literal/length code';
  18928. state.mode = BAD;
  18929. break;
  18930. }
  18931. state.extra = here_op & 15;
  18932. state.mode = LENEXT;
  18933. /* falls through */
  18934. case LENEXT:
  18935. if (state.extra) {
  18936. //=== NEEDBITS(state.extra);
  18937. n = state.extra;
  18938. while (bits < n) {
  18939. if (have === 0) { break inf_leave; }
  18940. have--;
  18941. hold += input[next++] << bits;
  18942. bits += 8;
  18943. }
  18944. //===//
  18945. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  18946. //--- DROPBITS(state.extra) ---//
  18947. hold >>>= state.extra;
  18948. bits -= state.extra;
  18949. //---//
  18950. state.back += state.extra;
  18951. }
  18952. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18953. state.was = state.length;
  18954. state.mode = DIST;
  18955. /* falls through */
  18956. case DIST:
  18957. for (;;) {
  18958. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  18959. here_bits = here >>> 24;
  18960. here_op = (here >>> 16) & 0xff;
  18961. here_val = here & 0xffff;
  18962. if ((here_bits) <= bits) { break; }
  18963. //--- PULLBYTE() ---//
  18964. if (have === 0) { break inf_leave; }
  18965. have--;
  18966. hold += input[next++] << bits;
  18967. bits += 8;
  18968. //---//
  18969. }
  18970. if ((here_op & 0xf0) === 0) {
  18971. last_bits = here_bits;
  18972. last_op = here_op;
  18973. last_val = here_val;
  18974. for (;;) {
  18975. here = state.distcode[last_val +
  18976. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18977. here_bits = here >>> 24;
  18978. here_op = (here >>> 16) & 0xff;
  18979. here_val = here & 0xffff;
  18980. if ((last_bits + here_bits) <= bits) { break; }
  18981. //--- PULLBYTE() ---//
  18982. if (have === 0) { break inf_leave; }
  18983. have--;
  18984. hold += input[next++] << bits;
  18985. bits += 8;
  18986. //---//
  18987. }
  18988. //--- DROPBITS(last.bits) ---//
  18989. hold >>>= last_bits;
  18990. bits -= last_bits;
  18991. //---//
  18992. state.back += last_bits;
  18993. }
  18994. //--- DROPBITS(here.bits) ---//
  18995. hold >>>= here_bits;
  18996. bits -= here_bits;
  18997. //---//
  18998. state.back += here_bits;
  18999. if (here_op & 64) {
  19000. strm.msg = 'invalid distance code';
  19001. state.mode = BAD;
  19002. break;
  19003. }
  19004. state.offset = here_val;
  19005. state.extra = (here_op) & 15;
  19006. state.mode = DISTEXT;
  19007. /* falls through */
  19008. case DISTEXT:
  19009. if (state.extra) {
  19010. //=== NEEDBITS(state.extra);
  19011. n = state.extra;
  19012. while (bits < n) {
  19013. if (have === 0) { break inf_leave; }
  19014. have--;
  19015. hold += input[next++] << bits;
  19016. bits += 8;
  19017. }
  19018. //===//
  19019. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  19020. //--- DROPBITS(state.extra) ---//
  19021. hold >>>= state.extra;
  19022. bits -= state.extra;
  19023. //---//
  19024. state.back += state.extra;
  19025. }
  19026. //#ifdef INFLATE_STRICT
  19027. if (state.offset > state.dmax) {
  19028. strm.msg = 'invalid distance too far back';
  19029. state.mode = BAD;
  19030. break;
  19031. }
  19032. //#endif
  19033. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  19034. state.mode = MATCH;
  19035. /* falls through */
  19036. case MATCH:
  19037. if (left === 0) { break inf_leave; }
  19038. copy = _out - left;
  19039. if (state.offset > copy) { /* copy from window */
  19040. copy = state.offset - copy;
  19041. if (copy > state.whave) {
  19042. if (state.sane) {
  19043. strm.msg = 'invalid distance too far back';
  19044. state.mode = BAD;
  19045. break;
  19046. }
  19047. // (!) This block is disabled in zlib defailts,
  19048. // don't enable it for binary compatibility
  19049. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19050. // Trace((stderr, "inflate.c too far\n"));
  19051. // copy -= state.whave;
  19052. // if (copy > state.length) { copy = state.length; }
  19053. // if (copy > left) { copy = left; }
  19054. // left -= copy;
  19055. // state.length -= copy;
  19056. // do {
  19057. // output[put++] = 0;
  19058. // } while (--copy);
  19059. // if (state.length === 0) { state.mode = LEN; }
  19060. // break;
  19061. //#endif
  19062. }
  19063. if (copy > state.wnext) {
  19064. copy -= state.wnext;
  19065. from = state.wsize - copy;
  19066. }
  19067. else {
  19068. from = state.wnext - copy;
  19069. }
  19070. if (copy > state.length) { copy = state.length; }
  19071. from_source = state.window;
  19072. }
  19073. else { /* copy from output */
  19074. from_source = output;
  19075. from = put - state.offset;
  19076. copy = state.length;
  19077. }
  19078. if (copy > left) { copy = left; }
  19079. left -= copy;
  19080. state.length -= copy;
  19081. do {
  19082. output[put++] = from_source[from++];
  19083. } while (--copy);
  19084. if (state.length === 0) { state.mode = LEN; }
  19085. break;
  19086. case LIT:
  19087. if (left === 0) { break inf_leave; }
  19088. output[put++] = state.length;
  19089. left--;
  19090. state.mode = LEN;
  19091. break;
  19092. case CHECK:
  19093. if (state.wrap) {
  19094. //=== NEEDBITS(32);
  19095. while (bits < 32) {
  19096. if (have === 0) { break inf_leave; }
  19097. have--;
  19098. // Use '|' insdead of '+' to make sure that result is signed
  19099. hold |= input[next++] << bits;
  19100. bits += 8;
  19101. }
  19102. //===//
  19103. _out -= left;
  19104. strm.total_out += _out;
  19105. state.total += _out;
  19106. if (_out) {
  19107. strm.adler = state.check =
  19108. /*UPDATE(state.check, put - _out, _out);*/
  19109. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  19110. }
  19111. _out = left;
  19112. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  19113. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  19114. strm.msg = 'incorrect data check';
  19115. state.mode = BAD;
  19116. break;
  19117. }
  19118. //=== INITBITS();
  19119. hold = 0;
  19120. bits = 0;
  19121. //===//
  19122. //Tracev((stderr, "inflate: check matches trailer\n"));
  19123. }
  19124. state.mode = LENGTH;
  19125. /* falls through */
  19126. case LENGTH:
  19127. if (state.wrap && state.flags) {
  19128. //=== NEEDBITS(32);
  19129. while (bits < 32) {
  19130. if (have === 0) { break inf_leave; }
  19131. have--;
  19132. hold += input[next++] << bits;
  19133. bits += 8;
  19134. }
  19135. //===//
  19136. if (hold !== (state.total & 0xffffffff)) {
  19137. strm.msg = 'incorrect length check';
  19138. state.mode = BAD;
  19139. break;
  19140. }
  19141. //=== INITBITS();
  19142. hold = 0;
  19143. bits = 0;
  19144. //===//
  19145. //Tracev((stderr, "inflate: length matches trailer\n"));
  19146. }
  19147. state.mode = DONE;
  19148. /* falls through */
  19149. case DONE:
  19150. ret = Z_STREAM_END;
  19151. break inf_leave;
  19152. case BAD:
  19153. ret = Z_DATA_ERROR;
  19154. break inf_leave;
  19155. case MEM:
  19156. return Z_MEM_ERROR;
  19157. case SYNC:
  19158. /* falls through */
  19159. default:
  19160. return Z_STREAM_ERROR;
  19161. }
  19162. }
  19163. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  19164. /*
  19165. Return from inflate(), updating the total counts and the check value.
  19166. If there was no progress during the inflate() call, return a buffer
  19167. error. Call updatewindow() to create and/or update the window state.
  19168. Note: a memory error from inflate() is non-recoverable.
  19169. */
  19170. //--- RESTORE() ---
  19171. strm.next_out = put;
  19172. strm.avail_out = left;
  19173. strm.next_in = next;
  19174. strm.avail_in = have;
  19175. state.hold = hold;
  19176. state.bits = bits;
  19177. //---
  19178. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  19179. (state.mode < CHECK || flush !== Z_FINISH))) {
  19180. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  19181. state.mode = MEM;
  19182. return Z_MEM_ERROR;
  19183. }
  19184. }
  19185. _in -= strm.avail_in;
  19186. _out -= strm.avail_out;
  19187. strm.total_in += _in;
  19188. strm.total_out += _out;
  19189. state.total += _out;
  19190. if (state.wrap && _out) {
  19191. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  19192. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  19193. }
  19194. strm.data_type = state.bits + (state.last ? 64 : 0) +
  19195. (state.mode === TYPE ? 128 : 0) +
  19196. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  19197. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  19198. ret = Z_BUF_ERROR;
  19199. }
  19200. return ret;
  19201. }
  19202. function inflateEnd(strm) {
  19203. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  19204. return Z_STREAM_ERROR;
  19205. }
  19206. var state = strm.state;
  19207. if (state.window) {
  19208. state.window = null;
  19209. }
  19210. strm.state = null;
  19211. return Z_OK;
  19212. }
  19213. function inflateGetHeader(strm, head) {
  19214. var state;
  19215. /* check state */
  19216. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19217. state = strm.state;
  19218. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  19219. /* save header structure */
  19220. state.head = head;
  19221. head.done = false;
  19222. return Z_OK;
  19223. }
  19224. function inflateSetDictionary(strm, dictionary) {
  19225. var dictLength = dictionary.length;
  19226. var state;
  19227. var dictid;
  19228. var ret;
  19229. /* check state */
  19230. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  19231. state = strm.state;
  19232. if (state.wrap !== 0 && state.mode !== DICT) {
  19233. return Z_STREAM_ERROR;
  19234. }
  19235. /* check for correct dictionary identifier */
  19236. if (state.mode === DICT) {
  19237. dictid = 1; /* adler32(0, null, 0)*/
  19238. /* dictid = adler32(dictid, dictionary, dictLength); */
  19239. dictid = adler32(dictid, dictionary, dictLength, 0);
  19240. if (dictid !== state.check) {
  19241. return Z_DATA_ERROR;
  19242. }
  19243. }
  19244. /* copy dictionary to window using updatewindow(), which will amend the
  19245. existing dictionary if appropriate */
  19246. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  19247. if (ret) {
  19248. state.mode = MEM;
  19249. return Z_MEM_ERROR;
  19250. }
  19251. state.havedict = 1;
  19252. // Tracev((stderr, "inflate: dictionary set\n"));
  19253. return Z_OK;
  19254. }
  19255. exports.inflateReset = inflateReset;
  19256. exports.inflateReset2 = inflateReset2;
  19257. exports.inflateResetKeep = inflateResetKeep;
  19258. exports.inflateInit = inflateInit;
  19259. exports.inflateInit2 = inflateInit2;
  19260. exports.inflate = inflate;
  19261. exports.inflateEnd = inflateEnd;
  19262. exports.inflateGetHeader = inflateGetHeader;
  19263. exports.inflateSetDictionary = inflateSetDictionary;
  19264. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  19265. /* Not implemented
  19266. exports.inflateCopy = inflateCopy;
  19267. exports.inflateGetDictionary = inflateGetDictionary;
  19268. exports.inflateMark = inflateMark;
  19269. exports.inflatePrime = inflatePrime;
  19270. exports.inflateSync = inflateSync;
  19271. exports.inflateSyncPoint = inflateSyncPoint;
  19272. exports.inflateUndermine = inflateUndermine;
  19273. */
  19274. },{"../utils/common":123,"./adler32":125,"./crc32":127,"./inffast":130,"./inftrees":132}],132:[function(require,module,exports){
  19275. 'use strict';
  19276. var utils = require('../utils/common');
  19277. var MAXBITS = 15;
  19278. var ENOUGH_LENS = 852;
  19279. var ENOUGH_DISTS = 592;
  19280. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19281. var CODES = 0;
  19282. var LENS = 1;
  19283. var DISTS = 2;
  19284. var lbase = [ /* Length codes 257..285 base */
  19285. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  19286. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  19287. ];
  19288. var lext = [ /* Length codes 257..285 extra */
  19289. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  19290. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  19291. ];
  19292. var dbase = [ /* Distance codes 0..29 base */
  19293. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  19294. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  19295. 8193, 12289, 16385, 24577, 0, 0
  19296. ];
  19297. var dext = [ /* Distance codes 0..29 extra */
  19298. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  19299. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  19300. 28, 28, 29, 29, 64, 64
  19301. ];
  19302. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  19303. {
  19304. var bits = opts.bits;
  19305. //here = opts.here; /* table entry for duplication */
  19306. var len = 0; /* a code's length in bits */
  19307. var sym = 0; /* index of code symbols */
  19308. var min = 0, max = 0; /* minimum and maximum code lengths */
  19309. var root = 0; /* number of index bits for root table */
  19310. var curr = 0; /* number of index bits for current table */
  19311. var drop = 0; /* code bits to drop for sub-table */
  19312. var left = 0; /* number of prefix codes available */
  19313. var used = 0; /* code entries in table used */
  19314. var huff = 0; /* Huffman code */
  19315. var incr; /* for incrementing code, index */
  19316. var fill; /* index for replicating entries */
  19317. var low; /* low bits for current root entry */
  19318. var mask; /* mask for low root bits */
  19319. var next; /* next available space in table */
  19320. var base = null; /* base value table to use */
  19321. var base_index = 0;
  19322. // var shoextra; /* extra bits table to use */
  19323. var end; /* use base and extra for symbol > end */
  19324. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  19325. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  19326. var extra = null;
  19327. var extra_index = 0;
  19328. var here_bits, here_op, here_val;
  19329. /*
  19330. Process a set of code lengths to create a canonical Huffman code. The
  19331. code lengths are lens[0..codes-1]. Each length corresponds to the
  19332. symbols 0..codes-1. The Huffman code is generated by first sorting the
  19333. symbols by length from short to long, and retaining the symbol order
  19334. for codes with equal lengths. Then the code starts with all zero bits
  19335. for the first code of the shortest length, and the codes are integer
  19336. increments for the same length, and zeros are appended as the length
  19337. increases. For the deflate format, these bits are stored backwards
  19338. from their more natural integer increment ordering, and so when the
  19339. decoding tables are built in the large loop below, the integer codes
  19340. are incremented backwards.
  19341. This routine assumes, but does not check, that all of the entries in
  19342. lens[] are in the range 0..MAXBITS. The caller must assure this.
  19343. 1..MAXBITS is interpreted as that code length. zero means that that
  19344. symbol does not occur in this code.
  19345. The codes are sorted by computing a count of codes for each length,
  19346. creating from that a table of starting indices for each length in the
  19347. sorted table, and then entering the symbols in order in the sorted
  19348. table. The sorted table is work[], with that space being provided by
  19349. the caller.
  19350. The length counts are used for other purposes as well, i.e. finding
  19351. the minimum and maximum length codes, determining if there are any
  19352. codes at all, checking for a valid set of lengths, and looking ahead
  19353. at length counts to determine sub-table sizes when building the
  19354. decoding tables.
  19355. */
  19356. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  19357. for (len = 0; len <= MAXBITS; len++) {
  19358. count[len] = 0;
  19359. }
  19360. for (sym = 0; sym < codes; sym++) {
  19361. count[lens[lens_index + sym]]++;
  19362. }
  19363. /* bound code lengths, force root to be within code lengths */
  19364. root = bits;
  19365. for (max = MAXBITS; max >= 1; max--) {
  19366. if (count[max] !== 0) { break; }
  19367. }
  19368. if (root > max) {
  19369. root = max;
  19370. }
  19371. if (max === 0) { /* no symbols to code at all */
  19372. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  19373. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  19374. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  19375. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  19376. //table.op[opts.table_index] = 64;
  19377. //table.bits[opts.table_index] = 1;
  19378. //table.val[opts.table_index++] = 0;
  19379. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  19380. opts.bits = 1;
  19381. return 0; /* no symbols, but wait for decoding to report error */
  19382. }
  19383. for (min = 1; min < max; min++) {
  19384. if (count[min] !== 0) { break; }
  19385. }
  19386. if (root < min) {
  19387. root = min;
  19388. }
  19389. /* check for an over-subscribed or incomplete set of lengths */
  19390. left = 1;
  19391. for (len = 1; len <= MAXBITS; len++) {
  19392. left <<= 1;
  19393. left -= count[len];
  19394. if (left < 0) {
  19395. return -1;
  19396. } /* over-subscribed */
  19397. }
  19398. if (left > 0 && (type === CODES || max !== 1)) {
  19399. return -1; /* incomplete set */
  19400. }
  19401. /* generate offsets into symbol table for each length for sorting */
  19402. offs[1] = 0;
  19403. for (len = 1; len < MAXBITS; len++) {
  19404. offs[len + 1] = offs[len] + count[len];
  19405. }
  19406. /* sort symbols by length, by symbol order within each length */
  19407. for (sym = 0; sym < codes; sym++) {
  19408. if (lens[lens_index + sym] !== 0) {
  19409. work[offs[lens[lens_index + sym]]++] = sym;
  19410. }
  19411. }
  19412. /*
  19413. Create and fill in decoding tables. In this loop, the table being
  19414. filled is at next and has curr index bits. The code being used is huff
  19415. with length len. That code is converted to an index by dropping drop
  19416. bits off of the bottom. For codes where len is less than drop + curr,
  19417. those top drop + curr - len bits are incremented through all values to
  19418. fill the table with replicated entries.
  19419. root is the number of index bits for the root table. When len exceeds
  19420. root, sub-tables are created pointed to by the root entry with an index
  19421. of the low root bits of huff. This is saved in low to check for when a
  19422. new sub-table should be started. drop is zero when the root table is
  19423. being filled, and drop is root when sub-tables are being filled.
  19424. When a new sub-table is needed, it is necessary to look ahead in the
  19425. code lengths to determine what size sub-table is needed. The length
  19426. counts are used for this, and so count[] is decremented as codes are
  19427. entered in the tables.
  19428. used keeps track of how many table entries have been allocated from the
  19429. provided *table space. It is checked for LENS and DIST tables against
  19430. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  19431. the initial root table size constants. See the comments in inftrees.h
  19432. for more information.
  19433. sym increments through all symbols, and the loop terminates when
  19434. all codes of length max, i.e. all codes, have been processed. This
  19435. routine permits incomplete codes, so another loop after this one fills
  19436. in the rest of the decoding tables with invalid code markers.
  19437. */
  19438. /* set up for code type */
  19439. // poor man optimization - use if-else instead of switch,
  19440. // to avoid deopts in old v8
  19441. if (type === CODES) {
  19442. base = extra = work; /* dummy value--not used */
  19443. end = 19;
  19444. } else if (type === LENS) {
  19445. base = lbase;
  19446. base_index -= 257;
  19447. extra = lext;
  19448. extra_index -= 257;
  19449. end = 256;
  19450. } else { /* DISTS */
  19451. base = dbase;
  19452. extra = dext;
  19453. end = -1;
  19454. }
  19455. /* initialize opts for loop */
  19456. huff = 0; /* starting code */
  19457. sym = 0; /* starting code symbol */
  19458. len = min; /* starting code length */
  19459. next = table_index; /* current table to fill in */
  19460. curr = root; /* current table index bits */
  19461. drop = 0; /* current bits to drop from code for index */
  19462. low = -1; /* trigger new sub-table when len > root */
  19463. used = 1 << root; /* use root table entries */
  19464. mask = used - 1; /* mask for comparing low */
  19465. /* check available table space */
  19466. if ((type === LENS && used > ENOUGH_LENS) ||
  19467. (type === DISTS && used > ENOUGH_DISTS)) {
  19468. return 1;
  19469. }
  19470. var i = 0;
  19471. /* process all codes and make table entries */
  19472. for (;;) {
  19473. i++;
  19474. /* create table entry */
  19475. here_bits = len - drop;
  19476. if (work[sym] < end) {
  19477. here_op = 0;
  19478. here_val = work[sym];
  19479. }
  19480. else if (work[sym] > end) {
  19481. here_op = extra[extra_index + work[sym]];
  19482. here_val = base[base_index + work[sym]];
  19483. }
  19484. else {
  19485. here_op = 32 + 64; /* end of block */
  19486. here_val = 0;
  19487. }
  19488. /* replicate for those indices with low len bits equal to huff */
  19489. incr = 1 << (len - drop);
  19490. fill = 1 << curr;
  19491. min = fill; /* save offset to next table */
  19492. do {
  19493. fill -= incr;
  19494. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  19495. } while (fill !== 0);
  19496. /* backwards increment the len-bit code huff */
  19497. incr = 1 << (len - 1);
  19498. while (huff & incr) {
  19499. incr >>= 1;
  19500. }
  19501. if (incr !== 0) {
  19502. huff &= incr - 1;
  19503. huff += incr;
  19504. } else {
  19505. huff = 0;
  19506. }
  19507. /* go to next symbol, update count, len */
  19508. sym++;
  19509. if (--count[len] === 0) {
  19510. if (len === max) { break; }
  19511. len = lens[lens_index + work[sym]];
  19512. }
  19513. /* create new sub-table if needed */
  19514. if (len > root && (huff & mask) !== low) {
  19515. /* if first time, transition to sub-tables */
  19516. if (drop === 0) {
  19517. drop = root;
  19518. }
  19519. /* increment past last table */
  19520. next += min; /* here min is 1 << curr */
  19521. /* determine length of next table */
  19522. curr = len - drop;
  19523. left = 1 << curr;
  19524. while (curr + drop < max) {
  19525. left -= count[curr + drop];
  19526. if (left <= 0) { break; }
  19527. curr++;
  19528. left <<= 1;
  19529. }
  19530. /* check for enough space */
  19531. used += 1 << curr;
  19532. if ((type === LENS && used > ENOUGH_LENS) ||
  19533. (type === DISTS && used > ENOUGH_DISTS)) {
  19534. return 1;
  19535. }
  19536. /* point entry in root table to sub-table */
  19537. low = huff & mask;
  19538. /*table.op[low] = curr;
  19539. table.bits[low] = root;
  19540. table.val[low] = next - opts.table_index;*/
  19541. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  19542. }
  19543. }
  19544. /* fill in remaining table entry if code is incomplete (guaranteed to have
  19545. at most one remaining entry, since if the code is incomplete, the
  19546. maximum code length that was allowed to get this far is one bit) */
  19547. if (huff !== 0) {
  19548. //table.op[next + huff] = 64; /* invalid code marker */
  19549. //table.bits[next + huff] = len - drop;
  19550. //table.val[next + huff] = 0;
  19551. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  19552. }
  19553. /* set return parameters */
  19554. //opts.table_index += used;
  19555. opts.bits = root;
  19556. return 0;
  19557. };
  19558. },{"../utils/common":123}],133:[function(require,module,exports){
  19559. 'use strict';
  19560. module.exports = {
  19561. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  19562. 1: 'stream end', /* Z_STREAM_END 1 */
  19563. 0: '', /* Z_OK 0 */
  19564. '-1': 'file error', /* Z_ERRNO (-1) */
  19565. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  19566. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  19567. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  19568. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  19569. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  19570. };
  19571. },{}],134:[function(require,module,exports){
  19572. 'use strict';
  19573. var utils = require('../utils/common');
  19574. /* Public constants ==========================================================*/
  19575. /* ===========================================================================*/
  19576. //var Z_FILTERED = 1;
  19577. //var Z_HUFFMAN_ONLY = 2;
  19578. //var Z_RLE = 3;
  19579. var Z_FIXED = 4;
  19580. //var Z_DEFAULT_STRATEGY = 0;
  19581. /* Possible values of the data_type field (though see inflate()) */
  19582. var Z_BINARY = 0;
  19583. var Z_TEXT = 1;
  19584. //var Z_ASCII = 1; // = Z_TEXT
  19585. var Z_UNKNOWN = 2;
  19586. /*============================================================================*/
  19587. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19588. // From zutil.h
  19589. var STORED_BLOCK = 0;
  19590. var STATIC_TREES = 1;
  19591. var DYN_TREES = 2;
  19592. /* The three kinds of block type */
  19593. var MIN_MATCH = 3;
  19594. var MAX_MATCH = 258;
  19595. /* The minimum and maximum match lengths */
  19596. // From deflate.h
  19597. /* ===========================================================================
  19598. * Internal compression state.
  19599. */
  19600. var LENGTH_CODES = 29;
  19601. /* number of length codes, not counting the special END_BLOCK code */
  19602. var LITERALS = 256;
  19603. /* number of literal bytes 0..255 */
  19604. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19605. /* number of Literal or Length codes, including the END_BLOCK code */
  19606. var D_CODES = 30;
  19607. /* number of distance codes */
  19608. var BL_CODES = 19;
  19609. /* number of codes used to transfer the bit lengths */
  19610. var HEAP_SIZE = 2 * L_CODES + 1;
  19611. /* maximum heap size */
  19612. var MAX_BITS = 15;
  19613. /* All codes must not exceed MAX_BITS bits */
  19614. var Buf_size = 16;
  19615. /* size of bit buffer in bi_buf */
  19616. /* ===========================================================================
  19617. * Constants
  19618. */
  19619. var MAX_BL_BITS = 7;
  19620. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19621. var END_BLOCK = 256;
  19622. /* end of block literal code */
  19623. var REP_3_6 = 16;
  19624. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  19625. var REPZ_3_10 = 17;
  19626. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  19627. var REPZ_11_138 = 18;
  19628. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  19629. /* eslint-disable comma-spacing,array-bracket-spacing */
  19630. var extra_lbits = /* extra bits for each length code */
  19631. [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];
  19632. var extra_dbits = /* extra bits for each distance code */
  19633. [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];
  19634. var extra_blbits = /* extra bits for each bit length code */
  19635. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  19636. var bl_order =
  19637. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  19638. /* eslint-enable comma-spacing,array-bracket-spacing */
  19639. /* The lengths of the bit length codes are sent in order of decreasing
  19640. * probability, to avoid transmitting the lengths for unused bit length codes.
  19641. */
  19642. /* ===========================================================================
  19643. * Local data. These are initialized only once.
  19644. */
  19645. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19646. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19647. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  19648. var static_ltree = new Array((L_CODES + 2) * 2);
  19649. zero(static_ltree);
  19650. /* The static literal tree. Since the bit lengths are imposed, there is no
  19651. * need for the L_CODES extra codes used during heap construction. However
  19652. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19653. * below).
  19654. */
  19655. var static_dtree = new Array(D_CODES * 2);
  19656. zero(static_dtree);
  19657. /* The static distance tree. (Actually a trivial tree since all codes use
  19658. * 5 bits.)
  19659. */
  19660. var _dist_code = new Array(DIST_CODE_LEN);
  19661. zero(_dist_code);
  19662. /* Distance codes. The first 256 values correspond to the distances
  19663. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19664. * the 15 bit distances.
  19665. */
  19666. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  19667. zero(_length_code);
  19668. /* length code for each normalized match length (0 == MIN_MATCH) */
  19669. var base_length = new Array(LENGTH_CODES);
  19670. zero(base_length);
  19671. /* First normalized length for each code (0 = MIN_MATCH) */
  19672. var base_dist = new Array(D_CODES);
  19673. zero(base_dist);
  19674. /* First normalized distance for each code (0 = distance of 1) */
  19675. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  19676. this.static_tree = static_tree; /* static tree or NULL */
  19677. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19678. this.extra_base = extra_base; /* base index for extra_bits */
  19679. this.elems = elems; /* max number of elements in the tree */
  19680. this.max_length = max_length; /* max bit length for the codes */
  19681. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19682. this.has_stree = static_tree && static_tree.length;
  19683. }
  19684. var static_l_desc;
  19685. var static_d_desc;
  19686. var static_bl_desc;
  19687. function TreeDesc(dyn_tree, stat_desc) {
  19688. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19689. this.max_code = 0; /* largest code with non zero frequency */
  19690. this.stat_desc = stat_desc; /* the corresponding static tree */
  19691. }
  19692. function d_code(dist) {
  19693. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19694. }
  19695. /* ===========================================================================
  19696. * Output a short LSB first on the stream.
  19697. * IN assertion: there is enough room in pendingBuf.
  19698. */
  19699. function put_short(s, w) {
  19700. // put_byte(s, (uch)((w) & 0xff));
  19701. // put_byte(s, (uch)((ush)(w) >> 8));
  19702. s.pending_buf[s.pending++] = (w) & 0xff;
  19703. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19704. }
  19705. /* ===========================================================================
  19706. * Send a value on a given number of bits.
  19707. * IN assertion: length <= 16 and value fits in length bits.
  19708. */
  19709. function send_bits(s, value, length) {
  19710. if (s.bi_valid > (Buf_size - length)) {
  19711. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19712. put_short(s, s.bi_buf);
  19713. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19714. s.bi_valid += length - Buf_size;
  19715. } else {
  19716. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19717. s.bi_valid += length;
  19718. }
  19719. }
  19720. function send_code(s, c, tree) {
  19721. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  19722. }
  19723. /* ===========================================================================
  19724. * Reverse the first len bits of a code, using straightforward code (a faster
  19725. * method would use a table)
  19726. * IN assertion: 1 <= len <= 15
  19727. */
  19728. function bi_reverse(code, len) {
  19729. var res = 0;
  19730. do {
  19731. res |= code & 1;
  19732. code >>>= 1;
  19733. res <<= 1;
  19734. } while (--len > 0);
  19735. return res >>> 1;
  19736. }
  19737. /* ===========================================================================
  19738. * Flush the bit buffer, keeping at most 7 bits in it.
  19739. */
  19740. function bi_flush(s) {
  19741. if (s.bi_valid === 16) {
  19742. put_short(s, s.bi_buf);
  19743. s.bi_buf = 0;
  19744. s.bi_valid = 0;
  19745. } else if (s.bi_valid >= 8) {
  19746. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19747. s.bi_buf >>= 8;
  19748. s.bi_valid -= 8;
  19749. }
  19750. }
  19751. /* ===========================================================================
  19752. * Compute the optimal bit lengths for a tree and update the total bit length
  19753. * for the current block.
  19754. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19755. * above are the tree nodes sorted by increasing frequency.
  19756. * OUT assertions: the field len is set to the optimal bit length, the
  19757. * array bl_count contains the frequencies for each bit length.
  19758. * The length opt_len is updated; static_len is also updated if stree is
  19759. * not null.
  19760. */
  19761. function gen_bitlen(s, desc)
  19762. // deflate_state *s;
  19763. // tree_desc *desc; /* the tree descriptor */
  19764. {
  19765. var tree = desc.dyn_tree;
  19766. var max_code = desc.max_code;
  19767. var stree = desc.stat_desc.static_tree;
  19768. var has_stree = desc.stat_desc.has_stree;
  19769. var extra = desc.stat_desc.extra_bits;
  19770. var base = desc.stat_desc.extra_base;
  19771. var max_length = desc.stat_desc.max_length;
  19772. var h; /* heap index */
  19773. var n, m; /* iterate over the tree elements */
  19774. var bits; /* bit length */
  19775. var xbits; /* extra bits */
  19776. var f; /* frequency */
  19777. var overflow = 0; /* number of elements with bit length too large */
  19778. for (bits = 0; bits <= MAX_BITS; bits++) {
  19779. s.bl_count[bits] = 0;
  19780. }
  19781. /* In a first pass, compute the optimal bit lengths (which may
  19782. * overflow in the case of the bit length tree).
  19783. */
  19784. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  19785. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  19786. n = s.heap[h];
  19787. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19788. if (bits > max_length) {
  19789. bits = max_length;
  19790. overflow++;
  19791. }
  19792. tree[n * 2 + 1]/*.Len*/ = bits;
  19793. /* We overwrite tree[n].Dad which is no longer needed */
  19794. if (n > max_code) { continue; } /* not a leaf node */
  19795. s.bl_count[bits]++;
  19796. xbits = 0;
  19797. if (n >= base) {
  19798. xbits = extra[n - base];
  19799. }
  19800. f = tree[n * 2]/*.Freq*/;
  19801. s.opt_len += f * (bits + xbits);
  19802. if (has_stree) {
  19803. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  19804. }
  19805. }
  19806. if (overflow === 0) { return; }
  19807. // Trace((stderr,"\nbit length overflow\n"));
  19808. /* This happens for example on obj2 and pic of the Calgary corpus */
  19809. /* Find the first bit length which could increase: */
  19810. do {
  19811. bits = max_length - 1;
  19812. while (s.bl_count[bits] === 0) { bits--; }
  19813. s.bl_count[bits]--; /* move one leaf down the tree */
  19814. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  19815. s.bl_count[max_length]--;
  19816. /* The brother of the overflow item also moves one step up,
  19817. * but this does not affect bl_count[max_length]
  19818. */
  19819. overflow -= 2;
  19820. } while (overflow > 0);
  19821. /* Now recompute all bit lengths, scanning in increasing frequency.
  19822. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19823. * lengths instead of fixing only the wrong ones. This idea is taken
  19824. * from 'ar' written by Haruhiko Okumura.)
  19825. */
  19826. for (bits = max_length; bits !== 0; bits--) {
  19827. n = s.bl_count[bits];
  19828. while (n !== 0) {
  19829. m = s.heap[--h];
  19830. if (m > max_code) { continue; }
  19831. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  19832. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19833. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  19834. tree[m * 2 + 1]/*.Len*/ = bits;
  19835. }
  19836. n--;
  19837. }
  19838. }
  19839. }
  19840. /* ===========================================================================
  19841. * Generate the codes for a given tree and bit counts (which need not be
  19842. * optimal).
  19843. * IN assertion: the array bl_count contains the bit length statistics for
  19844. * the given tree and the field len is set for all tree elements.
  19845. * OUT assertion: the field code is set for all tree elements of non
  19846. * zero code length.
  19847. */
  19848. function gen_codes(tree, max_code, bl_count)
  19849. // ct_data *tree; /* the tree to decorate */
  19850. // int max_code; /* largest code with non zero frequency */
  19851. // ushf *bl_count; /* number of codes at each bit length */
  19852. {
  19853. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  19854. var code = 0; /* running code value */
  19855. var bits; /* bit index */
  19856. var n; /* code index */
  19857. /* The distribution counts are first used to generate the code values
  19858. * without bit reversal.
  19859. */
  19860. for (bits = 1; bits <= MAX_BITS; bits++) {
  19861. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  19862. }
  19863. /* Check that the bit counts in bl_count are consistent. The last code
  19864. * must be all ones.
  19865. */
  19866. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19867. // "inconsistent bit counts");
  19868. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19869. for (n = 0; n <= max_code; n++) {
  19870. var len = tree[n * 2 + 1]/*.Len*/;
  19871. if (len === 0) { continue; }
  19872. /* Now reverse the bits */
  19873. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19874. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19875. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19876. }
  19877. }
  19878. /* ===========================================================================
  19879. * Initialize the various 'constant' tables.
  19880. */
  19881. function tr_static_init() {
  19882. var n; /* iterates over tree elements */
  19883. var bits; /* bit counter */
  19884. var length; /* length value */
  19885. var code; /* code value */
  19886. var dist; /* distance index */
  19887. var bl_count = new Array(MAX_BITS + 1);
  19888. /* number of codes at each bit length for an optimal tree */
  19889. // do check in _tr_init()
  19890. //if (static_init_done) return;
  19891. /* For some embedded targets, global variables are not initialized: */
  19892. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19893. static_l_desc.static_tree = static_ltree;
  19894. static_l_desc.extra_bits = extra_lbits;
  19895. static_d_desc.static_tree = static_dtree;
  19896. static_d_desc.extra_bits = extra_dbits;
  19897. static_bl_desc.extra_bits = extra_blbits;
  19898. #endif*/
  19899. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19900. length = 0;
  19901. for (code = 0; code < LENGTH_CODES - 1; code++) {
  19902. base_length[code] = length;
  19903. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  19904. _length_code[length++] = code;
  19905. }
  19906. }
  19907. //Assert (length == 256, "tr_static_init: length != 256");
  19908. /* Note that the length 255 (match length 258) can be represented
  19909. * in two different ways: code 284 + 5 bits or code 285, so we
  19910. * overwrite length_code[255] to use the best encoding:
  19911. */
  19912. _length_code[length - 1] = code;
  19913. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19914. dist = 0;
  19915. for (code = 0; code < 16; code++) {
  19916. base_dist[code] = dist;
  19917. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  19918. _dist_code[dist++] = code;
  19919. }
  19920. }
  19921. //Assert (dist == 256, "tr_static_init: dist != 256");
  19922. dist >>= 7; /* from now on, all distances are divided by 128 */
  19923. for (; code < D_CODES; code++) {
  19924. base_dist[code] = dist << 7;
  19925. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  19926. _dist_code[256 + dist++] = code;
  19927. }
  19928. }
  19929. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19930. /* Construct the codes of the static literal tree */
  19931. for (bits = 0; bits <= MAX_BITS; bits++) {
  19932. bl_count[bits] = 0;
  19933. }
  19934. n = 0;
  19935. while (n <= 143) {
  19936. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  19937. n++;
  19938. bl_count[8]++;
  19939. }
  19940. while (n <= 255) {
  19941. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  19942. n++;
  19943. bl_count[9]++;
  19944. }
  19945. while (n <= 279) {
  19946. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  19947. n++;
  19948. bl_count[7]++;
  19949. }
  19950. while (n <= 287) {
  19951. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  19952. n++;
  19953. bl_count[8]++;
  19954. }
  19955. /* Codes 286 and 287 do not exist, but we must include them in the
  19956. * tree construction to get a canonical Huffman tree (longest code
  19957. * all ones)
  19958. */
  19959. gen_codes(static_ltree, L_CODES + 1, bl_count);
  19960. /* The static distance tree is trivial: */
  19961. for (n = 0; n < D_CODES; n++) {
  19962. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  19963. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  19964. }
  19965. // Now data ready and we can init static trees
  19966. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  19967. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19968. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19969. //static_init_done = true;
  19970. }
  19971. /* ===========================================================================
  19972. * Initialize a new block.
  19973. */
  19974. function init_block(s) {
  19975. var n; /* iterates over tree elements */
  19976. /* Initialize the trees. */
  19977. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  19978. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  19979. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  19980. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  19981. s.opt_len = s.static_len = 0;
  19982. s.last_lit = s.matches = 0;
  19983. }
  19984. /* ===========================================================================
  19985. * Flush the bit buffer and align the output on a byte boundary
  19986. */
  19987. function bi_windup(s)
  19988. {
  19989. if (s.bi_valid > 8) {
  19990. put_short(s, s.bi_buf);
  19991. } else if (s.bi_valid > 0) {
  19992. //put_byte(s, (Byte)s->bi_buf);
  19993. s.pending_buf[s.pending++] = s.bi_buf;
  19994. }
  19995. s.bi_buf = 0;
  19996. s.bi_valid = 0;
  19997. }
  19998. /* ===========================================================================
  19999. * Copy a stored block, storing first the length and its
  20000. * one's complement if requested.
  20001. */
  20002. function copy_block(s, buf, len, header)
  20003. //DeflateState *s;
  20004. //charf *buf; /* the input data */
  20005. //unsigned len; /* its length */
  20006. //int header; /* true if block header must be written */
  20007. {
  20008. bi_windup(s); /* align on byte boundary */
  20009. if (header) {
  20010. put_short(s, len);
  20011. put_short(s, ~len);
  20012. }
  20013. // while (len--) {
  20014. // put_byte(s, *buf++);
  20015. // }
  20016. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  20017. s.pending += len;
  20018. }
  20019. /* ===========================================================================
  20020. * Compares to subtrees, using the tree depth as tie breaker when
  20021. * the subtrees have equal frequency. This minimizes the worst case length.
  20022. */
  20023. function smaller(tree, n, m, depth) {
  20024. var _n2 = n * 2;
  20025. var _m2 = m * 2;
  20026. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  20027. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  20028. }
  20029. /* ===========================================================================
  20030. * Restore the heap property by moving down the tree starting at node k,
  20031. * exchanging a node with the smallest of its two sons if necessary, stopping
  20032. * when the heap property is re-established (each father smaller than its
  20033. * two sons).
  20034. */
  20035. function pqdownheap(s, tree, k)
  20036. // deflate_state *s;
  20037. // ct_data *tree; /* the tree to restore */
  20038. // int k; /* node to move down */
  20039. {
  20040. var v = s.heap[k];
  20041. var j = k << 1; /* left son of k */
  20042. while (j <= s.heap_len) {
  20043. /* Set j to the smallest of the two sons: */
  20044. if (j < s.heap_len &&
  20045. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  20046. j++;
  20047. }
  20048. /* Exit if v is smaller than both sons */
  20049. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  20050. /* Exchange v with the smallest son */
  20051. s.heap[k] = s.heap[j];
  20052. k = j;
  20053. /* And continue down the tree, setting j to the left son of k */
  20054. j <<= 1;
  20055. }
  20056. s.heap[k] = v;
  20057. }
  20058. // inlined manually
  20059. // var SMALLEST = 1;
  20060. /* ===========================================================================
  20061. * Send the block data compressed using the given Huffman trees
  20062. */
  20063. function compress_block(s, ltree, dtree)
  20064. // deflate_state *s;
  20065. // const ct_data *ltree; /* literal tree */
  20066. // const ct_data *dtree; /* distance tree */
  20067. {
  20068. var dist; /* distance of matched string */
  20069. var lc; /* match length or unmatched char (if dist == 0) */
  20070. var lx = 0; /* running index in l_buf */
  20071. var code; /* the code to send */
  20072. var extra; /* number of extra bits to send */
  20073. if (s.last_lit !== 0) {
  20074. do {
  20075. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  20076. lc = s.pending_buf[s.l_buf + lx];
  20077. lx++;
  20078. if (dist === 0) {
  20079. send_code(s, lc, ltree); /* send a literal byte */
  20080. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  20081. } else {
  20082. /* Here, lc is the match length - MIN_MATCH */
  20083. code = _length_code[lc];
  20084. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  20085. extra = extra_lbits[code];
  20086. if (extra !== 0) {
  20087. lc -= base_length[code];
  20088. send_bits(s, lc, extra); /* send the extra length bits */
  20089. }
  20090. dist--; /* dist is now the match distance - 1 */
  20091. code = d_code(dist);
  20092. //Assert (code < D_CODES, "bad d_code");
  20093. send_code(s, code, dtree); /* send the distance code */
  20094. extra = extra_dbits[code];
  20095. if (extra !== 0) {
  20096. dist -= base_dist[code];
  20097. send_bits(s, dist, extra); /* send the extra distance bits */
  20098. }
  20099. } /* literal or match pair ? */
  20100. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  20101. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  20102. // "pendingBuf overflow");
  20103. } while (lx < s.last_lit);
  20104. }
  20105. send_code(s, END_BLOCK, ltree);
  20106. }
  20107. /* ===========================================================================
  20108. * Construct one Huffman tree and assigns the code bit strings and lengths.
  20109. * Update the total bit length for the current block.
  20110. * IN assertion: the field freq is set for all tree elements.
  20111. * OUT assertions: the fields len and code are set to the optimal bit length
  20112. * and corresponding code. The length opt_len is updated; static_len is
  20113. * also updated if stree is not null. The field max_code is set.
  20114. */
  20115. function build_tree(s, desc)
  20116. // deflate_state *s;
  20117. // tree_desc *desc; /* the tree descriptor */
  20118. {
  20119. var tree = desc.dyn_tree;
  20120. var stree = desc.stat_desc.static_tree;
  20121. var has_stree = desc.stat_desc.has_stree;
  20122. var elems = desc.stat_desc.elems;
  20123. var n, m; /* iterate over heap elements */
  20124. var max_code = -1; /* largest code with non zero frequency */
  20125. var node; /* new node being created */
  20126. /* Construct the initial heap, with least frequent element in
  20127. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  20128. * heap[0] is not used.
  20129. */
  20130. s.heap_len = 0;
  20131. s.heap_max = HEAP_SIZE;
  20132. for (n = 0; n < elems; n++) {
  20133. if (tree[n * 2]/*.Freq*/ !== 0) {
  20134. s.heap[++s.heap_len] = max_code = n;
  20135. s.depth[n] = 0;
  20136. } else {
  20137. tree[n * 2 + 1]/*.Len*/ = 0;
  20138. }
  20139. }
  20140. /* The pkzip format requires that at least one distance code exists,
  20141. * and that at least one bit should be sent even if there is only one
  20142. * possible code. So to avoid special checks later on we force at least
  20143. * two codes of non zero frequency.
  20144. */
  20145. while (s.heap_len < 2) {
  20146. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  20147. tree[node * 2]/*.Freq*/ = 1;
  20148. s.depth[node] = 0;
  20149. s.opt_len--;
  20150. if (has_stree) {
  20151. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  20152. }
  20153. /* node is 0 or 1 so it does not have extra bits */
  20154. }
  20155. desc.max_code = max_code;
  20156. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  20157. * establish sub-heaps of increasing lengths:
  20158. */
  20159. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  20160. /* Construct the Huffman tree by repeatedly combining the least two
  20161. * frequent nodes.
  20162. */
  20163. node = elems; /* next internal node of the tree */
  20164. do {
  20165. //pqremove(s, tree, n); /* n = node of least frequency */
  20166. /*** pqremove ***/
  20167. n = s.heap[1/*SMALLEST*/];
  20168. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  20169. pqdownheap(s, tree, 1/*SMALLEST*/);
  20170. /***/
  20171. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  20172. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  20173. s.heap[--s.heap_max] = m;
  20174. /* Create a new node father of n and m */
  20175. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  20176. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  20177. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  20178. /* and insert the new node in the heap */
  20179. s.heap[1/*SMALLEST*/] = node++;
  20180. pqdownheap(s, tree, 1/*SMALLEST*/);
  20181. } while (s.heap_len >= 2);
  20182. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  20183. /* At this point, the fields freq and dad are set. We can now
  20184. * generate the bit lengths.
  20185. */
  20186. gen_bitlen(s, desc);
  20187. /* The field len is now set, we can generate the bit codes */
  20188. gen_codes(tree, max_code, s.bl_count);
  20189. }
  20190. /* ===========================================================================
  20191. * Scan a literal or distance tree to determine the frequencies of the codes
  20192. * in the bit length tree.
  20193. */
  20194. function scan_tree(s, tree, max_code)
  20195. // deflate_state *s;
  20196. // ct_data *tree; /* the tree to be scanned */
  20197. // int max_code; /* and its largest code of non zero frequency */
  20198. {
  20199. var n; /* iterates over all tree elements */
  20200. var prevlen = -1; /* last emitted length */
  20201. var curlen; /* length of current code */
  20202. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  20203. var count = 0; /* repeat count of the current code */
  20204. var max_count = 7; /* max repeat count */
  20205. var min_count = 4; /* min repeat count */
  20206. if (nextlen === 0) {
  20207. max_count = 138;
  20208. min_count = 3;
  20209. }
  20210. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  20211. for (n = 0; n <= max_code; n++) {
  20212. curlen = nextlen;
  20213. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  20214. if (++count < max_count && curlen === nextlen) {
  20215. continue;
  20216. } else if (count < min_count) {
  20217. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  20218. } else if (curlen !== 0) {
  20219. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  20220. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  20221. } else if (count <= 10) {
  20222. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  20223. } else {
  20224. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  20225. }
  20226. count = 0;
  20227. prevlen = curlen;
  20228. if (nextlen === 0) {
  20229. max_count = 138;
  20230. min_count = 3;
  20231. } else if (curlen === nextlen) {
  20232. max_count = 6;
  20233. min_count = 3;
  20234. } else {
  20235. max_count = 7;
  20236. min_count = 4;
  20237. }
  20238. }
  20239. }
  20240. /* ===========================================================================
  20241. * Send a literal or distance tree in compressed form, using the codes in
  20242. * bl_tree.
  20243. */
  20244. function send_tree(s, tree, max_code)
  20245. // deflate_state *s;
  20246. // ct_data *tree; /* the tree to be scanned */
  20247. // int max_code; /* and its largest code of non zero frequency */
  20248. {
  20249. var n; /* iterates over all tree elements */
  20250. var prevlen = -1; /* last emitted length */
  20251. var curlen; /* length of current code */
  20252. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  20253. var count = 0; /* repeat count of the current code */
  20254. var max_count = 7; /* max repeat count */
  20255. var min_count = 4; /* min repeat count */
  20256. /* tree[max_code+1].Len = -1; */ /* guard already set */
  20257. if (nextlen === 0) {
  20258. max_count = 138;
  20259. min_count = 3;
  20260. }
  20261. for (n = 0; n <= max_code; n++) {
  20262. curlen = nextlen;
  20263. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  20264. if (++count < max_count && curlen === nextlen) {
  20265. continue;
  20266. } else if (count < min_count) {
  20267. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  20268. } else if (curlen !== 0) {
  20269. if (curlen !== prevlen) {
  20270. send_code(s, curlen, s.bl_tree);
  20271. count--;
  20272. }
  20273. //Assert(count >= 3 && count <= 6, " 3_6?");
  20274. send_code(s, REP_3_6, s.bl_tree);
  20275. send_bits(s, count - 3, 2);
  20276. } else if (count <= 10) {
  20277. send_code(s, REPZ_3_10, s.bl_tree);
  20278. send_bits(s, count - 3, 3);
  20279. } else {
  20280. send_code(s, REPZ_11_138, s.bl_tree);
  20281. send_bits(s, count - 11, 7);
  20282. }
  20283. count = 0;
  20284. prevlen = curlen;
  20285. if (nextlen === 0) {
  20286. max_count = 138;
  20287. min_count = 3;
  20288. } else if (curlen === nextlen) {
  20289. max_count = 6;
  20290. min_count = 3;
  20291. } else {
  20292. max_count = 7;
  20293. min_count = 4;
  20294. }
  20295. }
  20296. }
  20297. /* ===========================================================================
  20298. * Construct the Huffman tree for the bit lengths and return the index in
  20299. * bl_order of the last bit length code to send.
  20300. */
  20301. function build_bl_tree(s) {
  20302. var max_blindex; /* index of last bit length code of non zero freq */
  20303. /* Determine the bit length frequencies for literal and distance trees */
  20304. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  20305. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  20306. /* Build the bit length tree: */
  20307. build_tree(s, s.bl_desc);
  20308. /* opt_len now includes the length of the tree representations, except
  20309. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  20310. */
  20311. /* Determine the number of bit length codes to send. The pkzip format
  20312. * requires that at least 4 bit length codes be sent. (appnote.txt says
  20313. * 3 but the actual value used is 4.)
  20314. */
  20315. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  20316. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  20317. break;
  20318. }
  20319. }
  20320. /* Update opt_len to include the bit length tree and counts */
  20321. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  20322. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  20323. // s->opt_len, s->static_len));
  20324. return max_blindex;
  20325. }
  20326. /* ===========================================================================
  20327. * Send the header for a block using dynamic Huffman trees: the counts, the
  20328. * lengths of the bit length codes, the literal tree and the distance tree.
  20329. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  20330. */
  20331. function send_all_trees(s, lcodes, dcodes, blcodes)
  20332. // deflate_state *s;
  20333. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  20334. {
  20335. var rank; /* index in bl_order */
  20336. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  20337. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  20338. // "too many codes");
  20339. //Tracev((stderr, "\nbl counts: "));
  20340. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  20341. send_bits(s, dcodes - 1, 5);
  20342. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  20343. for (rank = 0; rank < blcodes; rank++) {
  20344. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  20345. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  20346. }
  20347. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  20348. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  20349. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  20350. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  20351. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  20352. }
  20353. /* ===========================================================================
  20354. * Check if the data type is TEXT or BINARY, using the following algorithm:
  20355. * - TEXT if the two conditions below are satisfied:
  20356. * a) There are no non-portable control characters belonging to the
  20357. * "black list" (0..6, 14..25, 28..31).
  20358. * b) There is at least one printable character belonging to the
  20359. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  20360. * - BINARY otherwise.
  20361. * - The following partially-portable control characters form a
  20362. * "gray list" that is ignored in this detection algorithm:
  20363. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  20364. * IN assertion: the fields Freq of dyn_ltree are set.
  20365. */
  20366. function detect_data_type(s) {
  20367. /* black_mask is the bit mask of black-listed bytes
  20368. * set bits 0..6, 14..25, and 28..31
  20369. * 0xf3ffc07f = binary 11110011111111111100000001111111
  20370. */
  20371. var black_mask = 0xf3ffc07f;
  20372. var n;
  20373. /* Check for non-textual ("black-listed") bytes. */
  20374. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  20375. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  20376. return Z_BINARY;
  20377. }
  20378. }
  20379. /* Check for textual ("white-listed") bytes. */
  20380. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  20381. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  20382. return Z_TEXT;
  20383. }
  20384. for (n = 32; n < LITERALS; n++) {
  20385. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  20386. return Z_TEXT;
  20387. }
  20388. }
  20389. /* There are no "black-listed" or "white-listed" bytes:
  20390. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  20391. */
  20392. return Z_BINARY;
  20393. }
  20394. var static_init_done = false;
  20395. /* ===========================================================================
  20396. * Initialize the tree data structures for a new zlib stream.
  20397. */
  20398. function _tr_init(s)
  20399. {
  20400. if (!static_init_done) {
  20401. tr_static_init();
  20402. static_init_done = true;
  20403. }
  20404. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  20405. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  20406. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  20407. s.bi_buf = 0;
  20408. s.bi_valid = 0;
  20409. /* Initialize the first block of the first file: */
  20410. init_block(s);
  20411. }
  20412. /* ===========================================================================
  20413. * Send a stored block
  20414. */
  20415. function _tr_stored_block(s, buf, stored_len, last)
  20416. //DeflateState *s;
  20417. //charf *buf; /* input block */
  20418. //ulg stored_len; /* length of input block */
  20419. //int last; /* one if this is the last block for a file */
  20420. {
  20421. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  20422. copy_block(s, buf, stored_len, true); /* with header */
  20423. }
  20424. /* ===========================================================================
  20425. * Send one empty static block to give enough lookahead for inflate.
  20426. * This takes 10 bits, of which 7 may remain in the bit buffer.
  20427. */
  20428. function _tr_align(s) {
  20429. send_bits(s, STATIC_TREES << 1, 3);
  20430. send_code(s, END_BLOCK, static_ltree);
  20431. bi_flush(s);
  20432. }
  20433. /* ===========================================================================
  20434. * Determine the best encoding for the current block: dynamic trees, static
  20435. * trees or store, and output the encoded block to the zip file.
  20436. */
  20437. function _tr_flush_block(s, buf, stored_len, last)
  20438. //DeflateState *s;
  20439. //charf *buf; /* input block, or NULL if too old */
  20440. //ulg stored_len; /* length of input block */
  20441. //int last; /* one if this is the last block for a file */
  20442. {
  20443. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  20444. var max_blindex = 0; /* index of last bit length code of non zero freq */
  20445. /* Build the Huffman trees unless a stored block is forced */
  20446. if (s.level > 0) {
  20447. /* Check if the file is binary or text */
  20448. if (s.strm.data_type === Z_UNKNOWN) {
  20449. s.strm.data_type = detect_data_type(s);
  20450. }
  20451. /* Construct the literal and distance trees */
  20452. build_tree(s, s.l_desc);
  20453. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  20454. // s->static_len));
  20455. build_tree(s, s.d_desc);
  20456. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  20457. // s->static_len));
  20458. /* At this point, opt_len and static_len are the total bit lengths of
  20459. * the compressed block data, excluding the tree representations.
  20460. */
  20461. /* Build the bit length tree for the above two trees, and get the index
  20462. * in bl_order of the last bit length code to send.
  20463. */
  20464. max_blindex = build_bl_tree(s);
  20465. /* Determine the best encoding. Compute the block lengths in bytes. */
  20466. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  20467. static_lenb = (s.static_len + 3 + 7) >>> 3;
  20468. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  20469. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  20470. // s->last_lit));
  20471. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  20472. } else {
  20473. // Assert(buf != (char*)0, "lost buf");
  20474. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  20475. }
  20476. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  20477. /* 4: two words for the lengths */
  20478. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  20479. * Otherwise we can't have processed more than WSIZE input bytes since
  20480. * the last block flush, because compression would have been
  20481. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  20482. * transform a block into a stored block.
  20483. */
  20484. _tr_stored_block(s, buf, stored_len, last);
  20485. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  20486. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  20487. compress_block(s, static_ltree, static_dtree);
  20488. } else {
  20489. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  20490. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  20491. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  20492. }
  20493. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  20494. /* The above check is made mod 2^32, for files larger than 512 MB
  20495. * and uLong implemented on 32 bits.
  20496. */
  20497. init_block(s);
  20498. if (last) {
  20499. bi_windup(s);
  20500. }
  20501. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  20502. // s->compressed_len-7*last));
  20503. }
  20504. /* ===========================================================================
  20505. * Save the match info and tally the frequency counts. Return true if
  20506. * the current block must be flushed.
  20507. */
  20508. function _tr_tally(s, dist, lc)
  20509. // deflate_state *s;
  20510. // unsigned dist; /* distance of matched string */
  20511. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  20512. {
  20513. //var out_length, in_length, dcode;
  20514. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  20515. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  20516. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  20517. s.last_lit++;
  20518. if (dist === 0) {
  20519. /* lc is the unmatched char */
  20520. s.dyn_ltree[lc * 2]/*.Freq*/++;
  20521. } else {
  20522. s.matches++;
  20523. /* Here, lc is the match length - MIN_MATCH */
  20524. dist--; /* dist = match distance - 1 */
  20525. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  20526. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  20527. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  20528. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  20529. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  20530. }
  20531. // (!) This block is disabled in zlib defailts,
  20532. // don't enable it for binary compatibility
  20533. //#ifdef TRUNCATE_BLOCK
  20534. // /* Try to guess if it is profitable to stop the current block here */
  20535. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  20536. // /* Compute an upper bound for the compressed length */
  20537. // out_length = s.last_lit*8;
  20538. // in_length = s.strstart - s.block_start;
  20539. //
  20540. // for (dcode = 0; dcode < D_CODES; dcode++) {
  20541. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  20542. // }
  20543. // out_length >>>= 3;
  20544. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  20545. // // s->last_lit, in_length, out_length,
  20546. // // 100L - out_length*100L/in_length));
  20547. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  20548. // return true;
  20549. // }
  20550. // }
  20551. //#endif
  20552. return (s.last_lit === s.lit_bufsize - 1);
  20553. /* We avoid equality with lit_bufsize because of wraparound at 64K
  20554. * on 16 bit machines and because stored blocks are restricted to
  20555. * 64K-1 bytes.
  20556. */
  20557. }
  20558. exports._tr_init = _tr_init;
  20559. exports._tr_stored_block = _tr_stored_block;
  20560. exports._tr_flush_block = _tr_flush_block;
  20561. exports._tr_tally = _tr_tally;
  20562. exports._tr_align = _tr_align;
  20563. },{"../utils/common":123}],135:[function(require,module,exports){
  20564. 'use strict';
  20565. function ZStream() {
  20566. /* next input byte */
  20567. this.input = null; // JS specific, because we have no pointers
  20568. this.next_in = 0;
  20569. /* number of bytes available at input */
  20570. this.avail_in = 0;
  20571. /* total number of input bytes read so far */
  20572. this.total_in = 0;
  20573. /* next output byte should be put there */
  20574. this.output = null; // JS specific, because we have no pointers
  20575. this.next_out = 0;
  20576. /* remaining free space at output */
  20577. this.avail_out = 0;
  20578. /* total number of bytes output so far */
  20579. this.total_out = 0;
  20580. /* last error message, NULL if no error */
  20581. this.msg = ''/*Z_NULL*/;
  20582. /* not visible by applications */
  20583. this.state = null;
  20584. /* best guess about the data type: binary or text */
  20585. this.data_type = 2/*Z_UNKNOWN*/;
  20586. /* adler32 value of the uncompressed data */
  20587. this.adler = 0;
  20588. }
  20589. module.exports = ZStream;
  20590. },{}],136:[function(require,module,exports){
  20591. (function (process){
  20592. // Copyright Joyent, Inc. and other Node contributors.
  20593. //
  20594. // Permission is hereby granted, free of charge, to any person obtaining a
  20595. // copy of this software and associated documentation files (the
  20596. // "Software"), to deal in the Software without restriction, including
  20597. // without limitation the rights to use, copy, modify, merge, publish,
  20598. // distribute, sublicense, and/or sell copies of the Software, and to permit
  20599. // persons to whom the Software is furnished to do so, subject to the
  20600. // following conditions:
  20601. //
  20602. // The above copyright notice and this permission notice shall be included
  20603. // in all copies or substantial portions of the Software.
  20604. //
  20605. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20606. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20607. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  20608. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20609. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20610. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20611. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  20612. // resolves . and .. elements in a path array with directory names there
  20613. // must be no slashes, empty elements, or device names (c:\) in the array
  20614. // (so also no leading and trailing slashes - it does not distinguish
  20615. // relative and absolute paths)
  20616. function normalizeArray(parts, allowAboveRoot) {
  20617. // if the path tries to go above the root, `up` ends up > 0
  20618. var up = 0;
  20619. for (var i = parts.length - 1; i >= 0; i--) {
  20620. var last = parts[i];
  20621. if (last === '.') {
  20622. parts.splice(i, 1);
  20623. } else if (last === '..') {
  20624. parts.splice(i, 1);
  20625. up++;
  20626. } else if (up) {
  20627. parts.splice(i, 1);
  20628. up--;
  20629. }
  20630. }
  20631. // if the path is allowed to go above the root, restore leading ..s
  20632. if (allowAboveRoot) {
  20633. for (; up--; up) {
  20634. parts.unshift('..');
  20635. }
  20636. }
  20637. return parts;
  20638. }
  20639. // Split a filename into [root, dir, basename, ext], unix version
  20640. // 'root' is just a slash, or nothing.
  20641. var splitPathRe =
  20642. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  20643. var splitPath = function(filename) {
  20644. return splitPathRe.exec(filename).slice(1);
  20645. };
  20646. // path.resolve([from ...], to)
  20647. // posix version
  20648. exports.resolve = function() {
  20649. var resolvedPath = '',
  20650. resolvedAbsolute = false;
  20651. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  20652. var path = (i >= 0) ? arguments[i] : process.cwd();
  20653. // Skip empty and invalid entries
  20654. if (typeof path !== 'string') {
  20655. throw new TypeError('Arguments to path.resolve must be strings');
  20656. } else if (!path) {
  20657. continue;
  20658. }
  20659. resolvedPath = path + '/' + resolvedPath;
  20660. resolvedAbsolute = path.charAt(0) === '/';
  20661. }
  20662. // At this point the path should be resolved to a full absolute path, but
  20663. // handle relative paths to be safe (might happen when process.cwd() fails)
  20664. // Normalize the path
  20665. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  20666. return !!p;
  20667. }), !resolvedAbsolute).join('/');
  20668. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  20669. };
  20670. // path.normalize(path)
  20671. // posix version
  20672. exports.normalize = function(path) {
  20673. var isAbsolute = exports.isAbsolute(path),
  20674. trailingSlash = substr(path, -1) === '/';
  20675. // Normalize the path
  20676. path = normalizeArray(filter(path.split('/'), function(p) {
  20677. return !!p;
  20678. }), !isAbsolute).join('/');
  20679. if (!path && !isAbsolute) {
  20680. path = '.';
  20681. }
  20682. if (path && trailingSlash) {
  20683. path += '/';
  20684. }
  20685. return (isAbsolute ? '/' : '') + path;
  20686. };
  20687. // posix version
  20688. exports.isAbsolute = function(path) {
  20689. return path.charAt(0) === '/';
  20690. };
  20691. // posix version
  20692. exports.join = function() {
  20693. var paths = Array.prototype.slice.call(arguments, 0);
  20694. return exports.normalize(filter(paths, function(p, index) {
  20695. if (typeof p !== 'string') {
  20696. throw new TypeError('Arguments to path.join must be strings');
  20697. }
  20698. return p;
  20699. }).join('/'));
  20700. };
  20701. // path.relative(from, to)
  20702. // posix version
  20703. exports.relative = function(from, to) {
  20704. from = exports.resolve(from).substr(1);
  20705. to = exports.resolve(to).substr(1);
  20706. function trim(arr) {
  20707. var start = 0;
  20708. for (; start < arr.length; start++) {
  20709. if (arr[start] !== '') break;
  20710. }
  20711. var end = arr.length - 1;
  20712. for (; end >= 0; end--) {
  20713. if (arr[end] !== '') break;
  20714. }
  20715. if (start > end) return [];
  20716. return arr.slice(start, end - start + 1);
  20717. }
  20718. var fromParts = trim(from.split('/'));
  20719. var toParts = trim(to.split('/'));
  20720. var length = Math.min(fromParts.length, toParts.length);
  20721. var samePartsLength = length;
  20722. for (var i = 0; i < length; i++) {
  20723. if (fromParts[i] !== toParts[i]) {
  20724. samePartsLength = i;
  20725. break;
  20726. }
  20727. }
  20728. var outputParts = [];
  20729. for (var i = samePartsLength; i < fromParts.length; i++) {
  20730. outputParts.push('..');
  20731. }
  20732. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  20733. return outputParts.join('/');
  20734. };
  20735. exports.sep = '/';
  20736. exports.delimiter = ':';
  20737. exports.dirname = function(path) {
  20738. var result = splitPath(path),
  20739. root = result[0],
  20740. dir = result[1];
  20741. if (!root && !dir) {
  20742. // No dirname whatsoever
  20743. return '.';
  20744. }
  20745. if (dir) {
  20746. // It has a dirname, strip trailing slash
  20747. dir = dir.substr(0, dir.length - 1);
  20748. }
  20749. return root + dir;
  20750. };
  20751. exports.basename = function(path, ext) {
  20752. var f = splitPath(path)[2];
  20753. // TODO: make this comparison case-insensitive on windows?
  20754. if (ext && f.substr(-1 * ext.length) === ext) {
  20755. f = f.substr(0, f.length - ext.length);
  20756. }
  20757. return f;
  20758. };
  20759. exports.extname = function(path) {
  20760. return splitPath(path)[3];
  20761. };
  20762. function filter (xs, f) {
  20763. if (xs.filter) return xs.filter(f);
  20764. var res = [];
  20765. for (var i = 0; i < xs.length; i++) {
  20766. if (f(xs[i], i, xs)) res.push(xs[i]);
  20767. }
  20768. return res;
  20769. }
  20770. // String.prototype.substr - negative index don't work in IE8
  20771. var substr = 'ab'.substr(-1) === 'b'
  20772. ? function (str, start, len) { return str.substr(start, len) }
  20773. : function (str, start, len) {
  20774. if (start < 0) start = str.length + start;
  20775. return str.substr(start, len);
  20776. }
  20777. ;
  20778. }).call(this,require('_process'))
  20779. },{"_process":138}],137:[function(require,module,exports){
  20780. (function (process){
  20781. 'use strict';
  20782. if (!process.version ||
  20783. process.version.indexOf('v0.') === 0 ||
  20784. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  20785. module.exports = nextTick;
  20786. } else {
  20787. module.exports = process.nextTick;
  20788. }
  20789. function nextTick(fn, arg1, arg2, arg3) {
  20790. if (typeof fn !== 'function') {
  20791. throw new TypeError('"callback" argument must be a function');
  20792. }
  20793. var len = arguments.length;
  20794. var args, i;
  20795. switch (len) {
  20796. case 0:
  20797. case 1:
  20798. return process.nextTick(fn);
  20799. case 2:
  20800. return process.nextTick(function afterTickOne() {
  20801. fn.call(null, arg1);
  20802. });
  20803. case 3:
  20804. return process.nextTick(function afterTickTwo() {
  20805. fn.call(null, arg1, arg2);
  20806. });
  20807. case 4:
  20808. return process.nextTick(function afterTickThree() {
  20809. fn.call(null, arg1, arg2, arg3);
  20810. });
  20811. default:
  20812. args = new Array(len - 1);
  20813. i = 0;
  20814. while (i < args.length) {
  20815. args[i++] = arguments[i];
  20816. }
  20817. return process.nextTick(function afterTick() {
  20818. fn.apply(null, args);
  20819. });
  20820. }
  20821. }
  20822. }).call(this,require('_process'))
  20823. },{"_process":138}],138:[function(require,module,exports){
  20824. // shim for using process in browser
  20825. var process = module.exports = {};
  20826. // cached from whatever global is present so that test runners that stub it
  20827. // don't break things. But we need to wrap it in a try catch in case it is
  20828. // wrapped in strict mode code which doesn't define any globals. It's inside a
  20829. // function because try/catches deoptimize in certain engines.
  20830. var cachedSetTimeout;
  20831. var cachedClearTimeout;
  20832. function defaultSetTimout() {
  20833. throw new Error('setTimeout has not been defined');
  20834. }
  20835. function defaultClearTimeout () {
  20836. throw new Error('clearTimeout has not been defined');
  20837. }
  20838. (function () {
  20839. try {
  20840. if (typeof setTimeout === 'function') {
  20841. cachedSetTimeout = setTimeout;
  20842. } else {
  20843. cachedSetTimeout = defaultSetTimout;
  20844. }
  20845. } catch (e) {
  20846. cachedSetTimeout = defaultSetTimout;
  20847. }
  20848. try {
  20849. if (typeof clearTimeout === 'function') {
  20850. cachedClearTimeout = clearTimeout;
  20851. } else {
  20852. cachedClearTimeout = defaultClearTimeout;
  20853. }
  20854. } catch (e) {
  20855. cachedClearTimeout = defaultClearTimeout;
  20856. }
  20857. } ())
  20858. function runTimeout(fun) {
  20859. if (cachedSetTimeout === setTimeout) {
  20860. //normal enviroments in sane situations
  20861. return setTimeout(fun, 0);
  20862. }
  20863. // if setTimeout wasn't available but was latter defined
  20864. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  20865. cachedSetTimeout = setTimeout;
  20866. return setTimeout(fun, 0);
  20867. }
  20868. try {
  20869. // when when somebody has screwed with setTimeout but no I.E. maddness
  20870. return cachedSetTimeout(fun, 0);
  20871. } catch(e){
  20872. try {
  20873. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  20874. return cachedSetTimeout.call(null, fun, 0);
  20875. } catch(e){
  20876. // 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
  20877. return cachedSetTimeout.call(this, fun, 0);
  20878. }
  20879. }
  20880. }
  20881. function runClearTimeout(marker) {
  20882. if (cachedClearTimeout === clearTimeout) {
  20883. //normal enviroments in sane situations
  20884. return clearTimeout(marker);
  20885. }
  20886. // if clearTimeout wasn't available but was latter defined
  20887. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  20888. cachedClearTimeout = clearTimeout;
  20889. return clearTimeout(marker);
  20890. }
  20891. try {
  20892. // when when somebody has screwed with setTimeout but no I.E. maddness
  20893. return cachedClearTimeout(marker);
  20894. } catch (e){
  20895. try {
  20896. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  20897. return cachedClearTimeout.call(null, marker);
  20898. } catch (e){
  20899. // 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.
  20900. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  20901. return cachedClearTimeout.call(this, marker);
  20902. }
  20903. }
  20904. }
  20905. var queue = [];
  20906. var draining = false;
  20907. var currentQueue;
  20908. var queueIndex = -1;
  20909. function cleanUpNextTick() {
  20910. if (!draining || !currentQueue) {
  20911. return;
  20912. }
  20913. draining = false;
  20914. if (currentQueue.length) {
  20915. queue = currentQueue.concat(queue);
  20916. } else {
  20917. queueIndex = -1;
  20918. }
  20919. if (queue.length) {
  20920. drainQueue();
  20921. }
  20922. }
  20923. function drainQueue() {
  20924. if (draining) {
  20925. return;
  20926. }
  20927. var timeout = runTimeout(cleanUpNextTick);
  20928. draining = true;
  20929. var len = queue.length;
  20930. while(len) {
  20931. currentQueue = queue;
  20932. queue = [];
  20933. while (++queueIndex < len) {
  20934. if (currentQueue) {
  20935. currentQueue[queueIndex].run();
  20936. }
  20937. }
  20938. queueIndex = -1;
  20939. len = queue.length;
  20940. }
  20941. currentQueue = null;
  20942. draining = false;
  20943. runClearTimeout(timeout);
  20944. }
  20945. process.nextTick = function (fun) {
  20946. var args = new Array(arguments.length - 1);
  20947. if (arguments.length > 1) {
  20948. for (var i = 1; i < arguments.length; i++) {
  20949. args[i - 1] = arguments[i];
  20950. }
  20951. }
  20952. queue.push(new Item(fun, args));
  20953. if (queue.length === 1 && !draining) {
  20954. runTimeout(drainQueue);
  20955. }
  20956. };
  20957. // v8 likes predictible objects
  20958. function Item(fun, array) {
  20959. this.fun = fun;
  20960. this.array = array;
  20961. }
  20962. Item.prototype.run = function () {
  20963. this.fun.apply(null, this.array);
  20964. };
  20965. process.title = 'browser';
  20966. process.browser = true;
  20967. process.env = {};
  20968. process.argv = [];
  20969. process.version = ''; // empty string to avoid regexp issues
  20970. process.versions = {};
  20971. function noop() {}
  20972. process.on = noop;
  20973. process.addListener = noop;
  20974. process.once = noop;
  20975. process.off = noop;
  20976. process.removeListener = noop;
  20977. process.removeAllListeners = noop;
  20978. process.emit = noop;
  20979. process.binding = function (name) {
  20980. throw new Error('process.binding is not supported');
  20981. };
  20982. process.cwd = function () { return '/' };
  20983. process.chdir = function (dir) {
  20984. throw new Error('process.chdir is not supported');
  20985. };
  20986. process.umask = function() { return 0; };
  20987. },{}],139:[function(require,module,exports){
  20988. module.exports = require("./lib/_stream_duplex.js")
  20989. },{"./lib/_stream_duplex.js":140}],140:[function(require,module,exports){
  20990. // a duplex stream is just a stream that is both readable and writable.
  20991. // Since JS doesn't have multiple prototypal inheritance, this class
  20992. // prototypally inherits from Readable, and then parasitically from
  20993. // Writable.
  20994. 'use strict';
  20995. /*<replacement>*/
  20996. var objectKeys = Object.keys || function (obj) {
  20997. var keys = [];
  20998. for (var key in obj) {
  20999. keys.push(key);
  21000. }return keys;
  21001. };
  21002. /*</replacement>*/
  21003. module.exports = Duplex;
  21004. /*<replacement>*/
  21005. var processNextTick = require('process-nextick-args');
  21006. /*</replacement>*/
  21007. /*<replacement>*/
  21008. var util = require('core-util-is');
  21009. util.inherits = require('inherits');
  21010. /*</replacement>*/
  21011. var Readable = require('./_stream_readable');
  21012. var Writable = require('./_stream_writable');
  21013. util.inherits(Duplex, Readable);
  21014. var keys = objectKeys(Writable.prototype);
  21015. for (var v = 0; v < keys.length; v++) {
  21016. var method = keys[v];
  21017. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  21018. }
  21019. function Duplex(options) {
  21020. if (!(this instanceof Duplex)) return new Duplex(options);
  21021. Readable.call(this, options);
  21022. Writable.call(this, options);
  21023. if (options && options.readable === false) this.readable = false;
  21024. if (options && options.writable === false) this.writable = false;
  21025. this.allowHalfOpen = true;
  21026. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  21027. this.once('end', onend);
  21028. }
  21029. // the no-half-open enforcer
  21030. function onend() {
  21031. // if we allow half-open state, or if the writable side ended,
  21032. // then we're ok.
  21033. if (this.allowHalfOpen || this._writableState.ended) return;
  21034. // no more data can be written.
  21035. // But allow more writes to happen in this tick.
  21036. processNextTick(onEndNT, this);
  21037. }
  21038. function onEndNT(self) {
  21039. self.end();
  21040. }
  21041. function forEach(xs, f) {
  21042. for (var i = 0, l = xs.length; i < l; i++) {
  21043. f(xs[i], i);
  21044. }
  21045. }
  21046. },{"./_stream_readable":142,"./_stream_writable":144,"core-util-is":78,"inherits":81,"process-nextick-args":137}],141:[function(require,module,exports){
  21047. // a passthrough stream.
  21048. // basically just the most minimal sort of Transform stream.
  21049. // Every written chunk gets output as-is.
  21050. 'use strict';
  21051. module.exports = PassThrough;
  21052. var Transform = require('./_stream_transform');
  21053. /*<replacement>*/
  21054. var util = require('core-util-is');
  21055. util.inherits = require('inherits');
  21056. /*</replacement>*/
  21057. util.inherits(PassThrough, Transform);
  21058. function PassThrough(options) {
  21059. if (!(this instanceof PassThrough)) return new PassThrough(options);
  21060. Transform.call(this, options);
  21061. }
  21062. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  21063. cb(null, chunk);
  21064. };
  21065. },{"./_stream_transform":143,"core-util-is":78,"inherits":81}],142:[function(require,module,exports){
  21066. (function (process){
  21067. 'use strict';
  21068. module.exports = Readable;
  21069. /*<replacement>*/
  21070. var processNextTick = require('process-nextick-args');
  21071. /*</replacement>*/
  21072. /*<replacement>*/
  21073. var isArray = require('isarray');
  21074. /*</replacement>*/
  21075. /*<replacement>*/
  21076. var Duplex;
  21077. /*</replacement>*/
  21078. Readable.ReadableState = ReadableState;
  21079. /*<replacement>*/
  21080. var EE = require('events').EventEmitter;
  21081. var EElistenerCount = function (emitter, type) {
  21082. return emitter.listeners(type).length;
  21083. };
  21084. /*</replacement>*/
  21085. /*<replacement>*/
  21086. var Stream;
  21087. (function () {
  21088. try {
  21089. Stream = require('st' + 'ream');
  21090. } catch (_) {} finally {
  21091. if (!Stream) Stream = require('events').EventEmitter;
  21092. }
  21093. })();
  21094. /*</replacement>*/
  21095. var Buffer = require('buffer').Buffer;
  21096. /*<replacement>*/
  21097. var bufferShim = require('buffer-shims');
  21098. /*</replacement>*/
  21099. /*<replacement>*/
  21100. var util = require('core-util-is');
  21101. util.inherits = require('inherits');
  21102. /*</replacement>*/
  21103. /*<replacement>*/
  21104. var debugUtil = require('util');
  21105. var debug = void 0;
  21106. if (debugUtil && debugUtil.debuglog) {
  21107. debug = debugUtil.debuglog('stream');
  21108. } else {
  21109. debug = function () {};
  21110. }
  21111. /*</replacement>*/
  21112. var BufferList = require('./internal/streams/BufferList');
  21113. var StringDecoder;
  21114. util.inherits(Readable, Stream);
  21115. function prependListener(emitter, event, fn) {
  21116. // Sadly this is not cacheable as some libraries bundle their own
  21117. // event emitter implementation with them.
  21118. if (typeof emitter.prependListener === 'function') {
  21119. return emitter.prependListener(event, fn);
  21120. } else {
  21121. // This is a hack to make sure that our error handler is attached before any
  21122. // userland ones. NEVER DO THIS. This is here only because this code needs
  21123. // to continue to work with older versions of Node.js that do not include
  21124. // the prependListener() method. The goal is to eventually remove this hack.
  21125. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  21126. }
  21127. }
  21128. function ReadableState(options, stream) {
  21129. Duplex = Duplex || require('./_stream_duplex');
  21130. options = options || {};
  21131. // object stream flag. Used to make read(n) ignore n and to
  21132. // make all the buffer merging and length checks go away
  21133. this.objectMode = !!options.objectMode;
  21134. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  21135. // the point at which it stops calling _read() to fill the buffer
  21136. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  21137. var hwm = options.highWaterMark;
  21138. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  21139. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  21140. // cast to ints.
  21141. this.highWaterMark = ~~this.highWaterMark;
  21142. // A linked list is used to store data chunks instead of an array because the
  21143. // linked list can remove elements from the beginning faster than
  21144. // array.shift()
  21145. this.buffer = new BufferList();
  21146. this.length = 0;
  21147. this.pipes = null;
  21148. this.pipesCount = 0;
  21149. this.flowing = null;
  21150. this.ended = false;
  21151. this.endEmitted = false;
  21152. this.reading = false;
  21153. // a flag to be able to tell if the onwrite cb is called immediately,
  21154. // or on a later tick. We set this to true at first, because any
  21155. // actions that shouldn't happen until "later" should generally also
  21156. // not happen before the first write call.
  21157. this.sync = true;
  21158. // whenever we return null, then we set a flag to say
  21159. // that we're awaiting a 'readable' event emission.
  21160. this.needReadable = false;
  21161. this.emittedReadable = false;
  21162. this.readableListening = false;
  21163. this.resumeScheduled = false;
  21164. // Crypto is kind of old and crusty. Historically, its default string
  21165. // encoding is 'binary' so we have to make this configurable.
  21166. // Everything else in the universe uses 'utf8', though.
  21167. this.defaultEncoding = options.defaultEncoding || 'utf8';
  21168. // when piping, we only care about 'readable' events that happen
  21169. // after read()ing all the bytes and not getting any pushback.
  21170. this.ranOut = false;
  21171. // the number of writers that are awaiting a drain event in .pipe()s
  21172. this.awaitDrain = 0;
  21173. // if true, a maybeReadMore has been scheduled
  21174. this.readingMore = false;
  21175. this.decoder = null;
  21176. this.encoding = null;
  21177. if (options.encoding) {
  21178. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  21179. this.decoder = new StringDecoder(options.encoding);
  21180. this.encoding = options.encoding;
  21181. }
  21182. }
  21183. function Readable(options) {
  21184. Duplex = Duplex || require('./_stream_duplex');
  21185. if (!(this instanceof Readable)) return new Readable(options);
  21186. this._readableState = new ReadableState(options, this);
  21187. // legacy
  21188. this.readable = true;
  21189. if (options && typeof options.read === 'function') this._read = options.read;
  21190. Stream.call(this);
  21191. }
  21192. // Manually shove something into the read() buffer.
  21193. // This returns true if the highWaterMark has not been hit yet,
  21194. // similar to how Writable.write() returns true if you should
  21195. // write() some more.
  21196. Readable.prototype.push = function (chunk, encoding) {
  21197. var state = this._readableState;
  21198. if (!state.objectMode && typeof chunk === 'string') {
  21199. encoding = encoding || state.defaultEncoding;
  21200. if (encoding !== state.encoding) {
  21201. chunk = bufferShim.from(chunk, encoding);
  21202. encoding = '';
  21203. }
  21204. }
  21205. return readableAddChunk(this, state, chunk, encoding, false);
  21206. };
  21207. // Unshift should *always* be something directly out of read()
  21208. Readable.prototype.unshift = function (chunk) {
  21209. var state = this._readableState;
  21210. return readableAddChunk(this, state, chunk, '', true);
  21211. };
  21212. Readable.prototype.isPaused = function () {
  21213. return this._readableState.flowing === false;
  21214. };
  21215. function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  21216. var er = chunkInvalid(state, chunk);
  21217. if (er) {
  21218. stream.emit('error', er);
  21219. } else if (chunk === null) {
  21220. state.reading = false;
  21221. onEofChunk(stream, state);
  21222. } else if (state.objectMode || chunk && chunk.length > 0) {
  21223. if (state.ended && !addToFront) {
  21224. var e = new Error('stream.push() after EOF');
  21225. stream.emit('error', e);
  21226. } else if (state.endEmitted && addToFront) {
  21227. var _e = new Error('stream.unshift() after end event');
  21228. stream.emit('error', _e);
  21229. } else {
  21230. var skipAdd;
  21231. if (state.decoder && !addToFront && !encoding) {
  21232. chunk = state.decoder.write(chunk);
  21233. skipAdd = !state.objectMode && chunk.length === 0;
  21234. }
  21235. if (!addToFront) state.reading = false;
  21236. // Don't add to the buffer if we've decoded to an empty string chunk and
  21237. // we're not in object mode
  21238. if (!skipAdd) {
  21239. // if we want the data now, just emit it.
  21240. if (state.flowing && state.length === 0 && !state.sync) {
  21241. stream.emit('data', chunk);
  21242. stream.read(0);
  21243. } else {
  21244. // update the buffer info.
  21245. state.length += state.objectMode ? 1 : chunk.length;
  21246. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  21247. if (state.needReadable) emitReadable(stream);
  21248. }
  21249. }
  21250. maybeReadMore(stream, state);
  21251. }
  21252. } else if (!addToFront) {
  21253. state.reading = false;
  21254. }
  21255. return needMoreData(state);
  21256. }
  21257. // if it's past the high water mark, we can push in some more.
  21258. // Also, if we have no data yet, we can stand some
  21259. // more bytes. This is to work around cases where hwm=0,
  21260. // such as the repl. Also, if the push() triggered a
  21261. // readable event, and the user called read(largeNumber) such that
  21262. // needReadable was set, then we ought to push more, so that another
  21263. // 'readable' event will be triggered.
  21264. function needMoreData(state) {
  21265. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  21266. }
  21267. // backwards compatibility.
  21268. Readable.prototype.setEncoding = function (enc) {
  21269. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  21270. this._readableState.decoder = new StringDecoder(enc);
  21271. this._readableState.encoding = enc;
  21272. return this;
  21273. };
  21274. // Don't raise the hwm > 8MB
  21275. var MAX_HWM = 0x800000;
  21276. function computeNewHighWaterMark(n) {
  21277. if (n >= MAX_HWM) {
  21278. n = MAX_HWM;
  21279. } else {
  21280. // Get the next highest power of 2 to prevent increasing hwm excessively in
  21281. // tiny amounts
  21282. n--;
  21283. n |= n >>> 1;
  21284. n |= n >>> 2;
  21285. n |= n >>> 4;
  21286. n |= n >>> 8;
  21287. n |= n >>> 16;
  21288. n++;
  21289. }
  21290. return n;
  21291. }
  21292. // This function is designed to be inlinable, so please take care when making
  21293. // changes to the function body.
  21294. function howMuchToRead(n, state) {
  21295. if (n <= 0 || state.length === 0 && state.ended) return 0;
  21296. if (state.objectMode) return 1;
  21297. if (n !== n) {
  21298. // Only flow one buffer at a time
  21299. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  21300. }
  21301. // If we're asking for more than the current hwm, then raise the hwm.
  21302. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  21303. if (n <= state.length) return n;
  21304. // Don't have enough
  21305. if (!state.ended) {
  21306. state.needReadable = true;
  21307. return 0;
  21308. }
  21309. return state.length;
  21310. }
  21311. // you can override either this method, or the async _read(n) below.
  21312. Readable.prototype.read = function (n) {
  21313. debug('read', n);
  21314. n = parseInt(n, 10);
  21315. var state = this._readableState;
  21316. var nOrig = n;
  21317. if (n !== 0) state.emittedReadable = false;
  21318. // if we're doing read(0) to trigger a readable event, but we
  21319. // already have a bunch of data in the buffer, then just trigger
  21320. // the 'readable' event and move on.
  21321. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  21322. debug('read: emitReadable', state.length, state.ended);
  21323. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  21324. return null;
  21325. }
  21326. n = howMuchToRead(n, state);
  21327. // if we've ended, and we're now clear, then finish it up.
  21328. if (n === 0 && state.ended) {
  21329. if (state.length === 0) endReadable(this);
  21330. return null;
  21331. }
  21332. // All the actual chunk generation logic needs to be
  21333. // *below* the call to _read. The reason is that in certain
  21334. // synthetic stream cases, such as passthrough streams, _read
  21335. // may be a completely synchronous operation which may change
  21336. // the state of the read buffer, providing enough data when
  21337. // before there was *not* enough.
  21338. //
  21339. // So, the steps are:
  21340. // 1. Figure out what the state of things will be after we do
  21341. // a read from the buffer.
  21342. //
  21343. // 2. If that resulting state will trigger a _read, then call _read.
  21344. // Note that this may be asynchronous, or synchronous. Yes, it is
  21345. // deeply ugly to write APIs this way, but that still doesn't mean
  21346. // that the Readable class should behave improperly, as streams are
  21347. // designed to be sync/async agnostic.
  21348. // Take note if the _read call is sync or async (ie, if the read call
  21349. // has returned yet), so that we know whether or not it's safe to emit
  21350. // 'readable' etc.
  21351. //
  21352. // 3. Actually pull the requested chunks out of the buffer and return.
  21353. // if we need a readable event, then we need to do some reading.
  21354. var doRead = state.needReadable;
  21355. debug('need readable', doRead);
  21356. // if we currently have less than the highWaterMark, then also read some
  21357. if (state.length === 0 || state.length - n < state.highWaterMark) {
  21358. doRead = true;
  21359. debug('length less than watermark', doRead);
  21360. }
  21361. // however, if we've ended, then there's no point, and if we're already
  21362. // reading, then it's unnecessary.
  21363. if (state.ended || state.reading) {
  21364. doRead = false;
  21365. debug('reading or ended', doRead);
  21366. } else if (doRead) {
  21367. debug('do read');
  21368. state.reading = true;
  21369. state.sync = true;
  21370. // if the length is currently zero, then we *need* a readable event.
  21371. if (state.length === 0) state.needReadable = true;
  21372. // call internal read method
  21373. this._read(state.highWaterMark);
  21374. state.sync = false;
  21375. // If _read pushed data synchronously, then `reading` will be false,
  21376. // and we need to re-evaluate how much data we can return to the user.
  21377. if (!state.reading) n = howMuchToRead(nOrig, state);
  21378. }
  21379. var ret;
  21380. if (n > 0) ret = fromList(n, state);else ret = null;
  21381. if (ret === null) {
  21382. state.needReadable = true;
  21383. n = 0;
  21384. } else {
  21385. state.length -= n;
  21386. }
  21387. if (state.length === 0) {
  21388. // If we have nothing in the buffer, then we want to know
  21389. // as soon as we *do* get something into the buffer.
  21390. if (!state.ended) state.needReadable = true;
  21391. // If we tried to read() past the EOF, then emit end on the next tick.
  21392. if (nOrig !== n && state.ended) endReadable(this);
  21393. }
  21394. if (ret !== null) this.emit('data', ret);
  21395. return ret;
  21396. };
  21397. function chunkInvalid(state, chunk) {
  21398. var er = null;
  21399. if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
  21400. er = new TypeError('Invalid non-string/buffer chunk');
  21401. }
  21402. return er;
  21403. }
  21404. function onEofChunk(stream, state) {
  21405. if (state.ended) return;
  21406. if (state.decoder) {
  21407. var chunk = state.decoder.end();
  21408. if (chunk && chunk.length) {
  21409. state.buffer.push(chunk);
  21410. state.length += state.objectMode ? 1 : chunk.length;
  21411. }
  21412. }
  21413. state.ended = true;
  21414. // emit 'readable' now to make sure it gets picked up.
  21415. emitReadable(stream);
  21416. }
  21417. // Don't emit readable right away in sync mode, because this can trigger
  21418. // another read() call => stack overflow. This way, it might trigger
  21419. // a nextTick recursion warning, but that's not so bad.
  21420. function emitReadable(stream) {
  21421. var state = stream._readableState;
  21422. state.needReadable = false;
  21423. if (!state.emittedReadable) {
  21424. debug('emitReadable', state.flowing);
  21425. state.emittedReadable = true;
  21426. if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
  21427. }
  21428. }
  21429. function emitReadable_(stream) {
  21430. debug('emit readable');
  21431. stream.emit('readable');
  21432. flow(stream);
  21433. }
  21434. // at this point, the user has presumably seen the 'readable' event,
  21435. // and called read() to consume some data. that may have triggered
  21436. // in turn another _read(n) call, in which case reading = true if
  21437. // it's in progress.
  21438. // However, if we're not ended, or reading, and the length < hwm,
  21439. // then go ahead and try to read some more preemptively.
  21440. function maybeReadMore(stream, state) {
  21441. if (!state.readingMore) {
  21442. state.readingMore = true;
  21443. processNextTick(maybeReadMore_, stream, state);
  21444. }
  21445. }
  21446. function maybeReadMore_(stream, state) {
  21447. var len = state.length;
  21448. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  21449. debug('maybeReadMore read 0');
  21450. stream.read(0);
  21451. if (len === state.length)
  21452. // didn't get any data, stop spinning.
  21453. break;else len = state.length;
  21454. }
  21455. state.readingMore = false;
  21456. }
  21457. // abstract method. to be overridden in specific implementation classes.
  21458. // call cb(er, data) where data is <= n in length.
  21459. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  21460. // arbitrary, and perhaps not very meaningful.
  21461. Readable.prototype._read = function (n) {
  21462. this.emit('error', new Error('_read() is not implemented'));
  21463. };
  21464. Readable.prototype.pipe = function (dest, pipeOpts) {
  21465. var src = this;
  21466. var state = this._readableState;
  21467. switch (state.pipesCount) {
  21468. case 0:
  21469. state.pipes = dest;
  21470. break;
  21471. case 1:
  21472. state.pipes = [state.pipes, dest];
  21473. break;
  21474. default:
  21475. state.pipes.push(dest);
  21476. break;
  21477. }
  21478. state.pipesCount += 1;
  21479. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  21480. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  21481. var endFn = doEnd ? onend : cleanup;
  21482. if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
  21483. dest.on('unpipe', onunpipe);
  21484. function onunpipe(readable) {
  21485. debug('onunpipe');
  21486. if (readable === src) {
  21487. cleanup();
  21488. }
  21489. }
  21490. function onend() {
  21491. debug('onend');
  21492. dest.end();
  21493. }
  21494. // when the dest drains, it reduces the awaitDrain counter
  21495. // on the source. This would be more elegant with a .once()
  21496. // handler in flow(), but adding and removing repeatedly is
  21497. // too slow.
  21498. var ondrain = pipeOnDrain(src);
  21499. dest.on('drain', ondrain);
  21500. var cleanedUp = false;
  21501. function cleanup() {
  21502. debug('cleanup');
  21503. // cleanup event handlers once the pipe is broken
  21504. dest.removeListener('close', onclose);
  21505. dest.removeListener('finish', onfinish);
  21506. dest.removeListener('drain', ondrain);
  21507. dest.removeListener('error', onerror);
  21508. dest.removeListener('unpipe', onunpipe);
  21509. src.removeListener('end', onend);
  21510. src.removeListener('end', cleanup);
  21511. src.removeListener('data', ondata);
  21512. cleanedUp = true;
  21513. // if the reader is waiting for a drain event from this
  21514. // specific writer, then it would cause it to never start
  21515. // flowing again.
  21516. // So, if this is awaiting a drain, then we just call it now.
  21517. // If we don't know, then assume that we are waiting for one.
  21518. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  21519. }
  21520. // If the user pushes more data while we're writing to dest then we'll end up
  21521. // in ondata again. However, we only want to increase awaitDrain once because
  21522. // dest will only emit one 'drain' event for the multiple writes.
  21523. // => Introduce a guard on increasing awaitDrain.
  21524. var increasedAwaitDrain = false;
  21525. src.on('data', ondata);
  21526. function ondata(chunk) {
  21527. debug('ondata');
  21528. increasedAwaitDrain = false;
  21529. var ret = dest.write(chunk);
  21530. if (false === ret && !increasedAwaitDrain) {
  21531. // If the user unpiped during `dest.write()`, it is possible
  21532. // to get stuck in a permanently paused state if that write
  21533. // also returned false.
  21534. // => Check whether `dest` is still a piping destination.
  21535. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  21536. debug('false write response, pause', src._readableState.awaitDrain);
  21537. src._readableState.awaitDrain++;
  21538. increasedAwaitDrain = true;
  21539. }
  21540. src.pause();
  21541. }
  21542. }
  21543. // if the dest has an error, then stop piping into it.
  21544. // however, don't suppress the throwing behavior for this.
  21545. function onerror(er) {
  21546. debug('onerror', er);
  21547. unpipe();
  21548. dest.removeListener('error', onerror);
  21549. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  21550. }
  21551. // Make sure our error handler is attached before userland ones.
  21552. prependListener(dest, 'error', onerror);
  21553. // Both close and finish should trigger unpipe, but only once.
  21554. function onclose() {
  21555. dest.removeListener('finish', onfinish);
  21556. unpipe();
  21557. }
  21558. dest.once('close', onclose);
  21559. function onfinish() {
  21560. debug('onfinish');
  21561. dest.removeListener('close', onclose);
  21562. unpipe();
  21563. }
  21564. dest.once('finish', onfinish);
  21565. function unpipe() {
  21566. debug('unpipe');
  21567. src.unpipe(dest);
  21568. }
  21569. // tell the dest that it's being piped to
  21570. dest.emit('pipe', src);
  21571. // start the flow if it hasn't been started already.
  21572. if (!state.flowing) {
  21573. debug('pipe resume');
  21574. src.resume();
  21575. }
  21576. return dest;
  21577. };
  21578. function pipeOnDrain(src) {
  21579. return function () {
  21580. var state = src._readableState;
  21581. debug('pipeOnDrain', state.awaitDrain);
  21582. if (state.awaitDrain) state.awaitDrain--;
  21583. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  21584. state.flowing = true;
  21585. flow(src);
  21586. }
  21587. };
  21588. }
  21589. Readable.prototype.unpipe = function (dest) {
  21590. var state = this._readableState;
  21591. // if we're not piping anywhere, then do nothing.
  21592. if (state.pipesCount === 0) return this;
  21593. // just one destination. most common case.
  21594. if (state.pipesCount === 1) {
  21595. // passed in one, but it's not the right one.
  21596. if (dest && dest !== state.pipes) return this;
  21597. if (!dest) dest = state.pipes;
  21598. // got a match.
  21599. state.pipes = null;
  21600. state.pipesCount = 0;
  21601. state.flowing = false;
  21602. if (dest) dest.emit('unpipe', this);
  21603. return this;
  21604. }
  21605. // slow case. multiple pipe destinations.
  21606. if (!dest) {
  21607. // remove all.
  21608. var dests = state.pipes;
  21609. var len = state.pipesCount;
  21610. state.pipes = null;
  21611. state.pipesCount = 0;
  21612. state.flowing = false;
  21613. for (var i = 0; i < len; i++) {
  21614. dests[i].emit('unpipe', this);
  21615. }return this;
  21616. }
  21617. // try to find the right one.
  21618. var index = indexOf(state.pipes, dest);
  21619. if (index === -1) return this;
  21620. state.pipes.splice(index, 1);
  21621. state.pipesCount -= 1;
  21622. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  21623. dest.emit('unpipe', this);
  21624. return this;
  21625. };
  21626. // set up data events if they are asked for
  21627. // Ensure readable listeners eventually get something
  21628. Readable.prototype.on = function (ev, fn) {
  21629. var res = Stream.prototype.on.call(this, ev, fn);
  21630. if (ev === 'data') {
  21631. // Start flowing on next tick if stream isn't explicitly paused
  21632. if (this._readableState.flowing !== false) this.resume();
  21633. } else if (ev === 'readable') {
  21634. var state = this._readableState;
  21635. if (!state.endEmitted && !state.readableListening) {
  21636. state.readableListening = state.needReadable = true;
  21637. state.emittedReadable = false;
  21638. if (!state.reading) {
  21639. processNextTick(nReadingNextTick, this);
  21640. } else if (state.length) {
  21641. emitReadable(this, state);
  21642. }
  21643. }
  21644. }
  21645. return res;
  21646. };
  21647. Readable.prototype.addListener = Readable.prototype.on;
  21648. function nReadingNextTick(self) {
  21649. debug('readable nexttick read 0');
  21650. self.read(0);
  21651. }
  21652. // pause() and resume() are remnants of the legacy readable stream API
  21653. // If the user uses them, then switch into old mode.
  21654. Readable.prototype.resume = function () {
  21655. var state = this._readableState;
  21656. if (!state.flowing) {
  21657. debug('resume');
  21658. state.flowing = true;
  21659. resume(this, state);
  21660. }
  21661. return this;
  21662. };
  21663. function resume(stream, state) {
  21664. if (!state.resumeScheduled) {
  21665. state.resumeScheduled = true;
  21666. processNextTick(resume_, stream, state);
  21667. }
  21668. }
  21669. function resume_(stream, state) {
  21670. if (!state.reading) {
  21671. debug('resume read 0');
  21672. stream.read(0);
  21673. }
  21674. state.resumeScheduled = false;
  21675. state.awaitDrain = 0;
  21676. stream.emit('resume');
  21677. flow(stream);
  21678. if (state.flowing && !state.reading) stream.read(0);
  21679. }
  21680. Readable.prototype.pause = function () {
  21681. debug('call pause flowing=%j', this._readableState.flowing);
  21682. if (false !== this._readableState.flowing) {
  21683. debug('pause');
  21684. this._readableState.flowing = false;
  21685. this.emit('pause');
  21686. }
  21687. return this;
  21688. };
  21689. function flow(stream) {
  21690. var state = stream._readableState;
  21691. debug('flow', state.flowing);
  21692. while (state.flowing && stream.read() !== null) {}
  21693. }
  21694. // wrap an old-style stream as the async data source.
  21695. // This is *not* part of the readable stream interface.
  21696. // It is an ugly unfortunate mess of history.
  21697. Readable.prototype.wrap = function (stream) {
  21698. var state = this._readableState;
  21699. var paused = false;
  21700. var self = this;
  21701. stream.on('end', function () {
  21702. debug('wrapped end');
  21703. if (state.decoder && !state.ended) {
  21704. var chunk = state.decoder.end();
  21705. if (chunk && chunk.length) self.push(chunk);
  21706. }
  21707. self.push(null);
  21708. });
  21709. stream.on('data', function (chunk) {
  21710. debug('wrapped data');
  21711. if (state.decoder) chunk = state.decoder.write(chunk);
  21712. // don't skip over falsy values in objectMode
  21713. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  21714. var ret = self.push(chunk);
  21715. if (!ret) {
  21716. paused = true;
  21717. stream.pause();
  21718. }
  21719. });
  21720. // proxy all the other methods.
  21721. // important when wrapping filters and duplexes.
  21722. for (var i in stream) {
  21723. if (this[i] === undefined && typeof stream[i] === 'function') {
  21724. this[i] = function (method) {
  21725. return function () {
  21726. return stream[method].apply(stream, arguments);
  21727. };
  21728. }(i);
  21729. }
  21730. }
  21731. // proxy certain important events.
  21732. var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  21733. forEach(events, function (ev) {
  21734. stream.on(ev, self.emit.bind(self, ev));
  21735. });
  21736. // when we try to consume some more bytes, simply unpause the
  21737. // underlying stream.
  21738. self._read = function (n) {
  21739. debug('wrapped _read', n);
  21740. if (paused) {
  21741. paused = false;
  21742. stream.resume();
  21743. }
  21744. };
  21745. return self;
  21746. };
  21747. // exposed for testing purposes only.
  21748. Readable._fromList = fromList;
  21749. // Pluck off n bytes from an array of buffers.
  21750. // Length is the combined lengths of all the buffers in the list.
  21751. // This function is designed to be inlinable, so please take care when making
  21752. // changes to the function body.
  21753. function fromList(n, state) {
  21754. // nothing buffered
  21755. if (state.length === 0) return null;
  21756. var ret;
  21757. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  21758. // read it all, truncate the list
  21759. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  21760. state.buffer.clear();
  21761. } else {
  21762. // read part of list
  21763. ret = fromListPartial(n, state.buffer, state.decoder);
  21764. }
  21765. return ret;
  21766. }
  21767. // Extracts only enough buffered data to satisfy the amount requested.
  21768. // This function is designed to be inlinable, so please take care when making
  21769. // changes to the function body.
  21770. function fromListPartial(n, list, hasStrings) {
  21771. var ret;
  21772. if (n < list.head.data.length) {
  21773. // slice is the same for buffers and strings
  21774. ret = list.head.data.slice(0, n);
  21775. list.head.data = list.head.data.slice(n);
  21776. } else if (n === list.head.data.length) {
  21777. // first chunk is a perfect match
  21778. ret = list.shift();
  21779. } else {
  21780. // result spans more than one buffer
  21781. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  21782. }
  21783. return ret;
  21784. }
  21785. // Copies a specified amount of characters from the list of buffered data
  21786. // chunks.
  21787. // This function is designed to be inlinable, so please take care when making
  21788. // changes to the function body.
  21789. function copyFromBufferString(n, list) {
  21790. var p = list.head;
  21791. var c = 1;
  21792. var ret = p.data;
  21793. n -= ret.length;
  21794. while (p = p.next) {
  21795. var str = p.data;
  21796. var nb = n > str.length ? str.length : n;
  21797. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  21798. n -= nb;
  21799. if (n === 0) {
  21800. if (nb === str.length) {
  21801. ++c;
  21802. if (p.next) list.head = p.next;else list.head = list.tail = null;
  21803. } else {
  21804. list.head = p;
  21805. p.data = str.slice(nb);
  21806. }
  21807. break;
  21808. }
  21809. ++c;
  21810. }
  21811. list.length -= c;
  21812. return ret;
  21813. }
  21814. // Copies a specified amount of bytes from the list of buffered data chunks.
  21815. // This function is designed to be inlinable, so please take care when making
  21816. // changes to the function body.
  21817. function copyFromBuffer(n, list) {
  21818. var ret = bufferShim.allocUnsafe(n);
  21819. var p = list.head;
  21820. var c = 1;
  21821. p.data.copy(ret);
  21822. n -= p.data.length;
  21823. while (p = p.next) {
  21824. var buf = p.data;
  21825. var nb = n > buf.length ? buf.length : n;
  21826. buf.copy(ret, ret.length - n, 0, nb);
  21827. n -= nb;
  21828. if (n === 0) {
  21829. if (nb === buf.length) {
  21830. ++c;
  21831. if (p.next) list.head = p.next;else list.head = list.tail = null;
  21832. } else {
  21833. list.head = p;
  21834. p.data = buf.slice(nb);
  21835. }
  21836. break;
  21837. }
  21838. ++c;
  21839. }
  21840. list.length -= c;
  21841. return ret;
  21842. }
  21843. function endReadable(stream) {
  21844. var state = stream._readableState;
  21845. // If we get here before consuming all the bytes, then that is a
  21846. // bug in node. Should never happen.
  21847. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  21848. if (!state.endEmitted) {
  21849. state.ended = true;
  21850. processNextTick(endReadableNT, state, stream);
  21851. }
  21852. }
  21853. function endReadableNT(state, stream) {
  21854. // Check that we didn't get one last unshift.
  21855. if (!state.endEmitted && state.length === 0) {
  21856. state.endEmitted = true;
  21857. stream.readable = false;
  21858. stream.emit('end');
  21859. }
  21860. }
  21861. function forEach(xs, f) {
  21862. for (var i = 0, l = xs.length; i < l; i++) {
  21863. f(xs[i], i);
  21864. }
  21865. }
  21866. function indexOf(xs, x) {
  21867. for (var i = 0, l = xs.length; i < l; i++) {
  21868. if (xs[i] === x) return i;
  21869. }
  21870. return -1;
  21871. }
  21872. }).call(this,require('_process'))
  21873. },{"./_stream_duplex":140,"./internal/streams/BufferList":145,"_process":138,"buffer":77,"buffer-shims":76,"core-util-is":78,"events":79,"inherits":81,"isarray":83,"process-nextick-args":137,"string_decoder/":152,"util":75}],143:[function(require,module,exports){
  21874. // a transform stream is a readable/writable stream where you do
  21875. // something with the data. Sometimes it's called a "filter",
  21876. // but that's not a great name for it, since that implies a thing where
  21877. // some bits pass through, and others are simply ignored. (That would
  21878. // be a valid example of a transform, of course.)
  21879. //
  21880. // While the output is causally related to the input, it's not a
  21881. // necessarily symmetric or synchronous transformation. For example,
  21882. // a zlib stream might take multiple plain-text writes(), and then
  21883. // emit a single compressed chunk some time in the future.
  21884. //
  21885. // Here's how this works:
  21886. //
  21887. // The Transform stream has all the aspects of the readable and writable
  21888. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  21889. // internally, and returns false if there's a lot of pending writes
  21890. // buffered up. When you call read(), that calls _read(n) until
  21891. // there's enough pending readable data buffered up.
  21892. //
  21893. // In a transform stream, the written data is placed in a buffer. When
  21894. // _read(n) is called, it transforms the queued up data, calling the
  21895. // buffered _write cb's as it consumes chunks. If consuming a single
  21896. // written chunk would result in multiple output chunks, then the first
  21897. // outputted bit calls the readcb, and subsequent chunks just go into
  21898. // the read buffer, and will cause it to emit 'readable' if necessary.
  21899. //
  21900. // This way, back-pressure is actually determined by the reading side,
  21901. // since _read has to be called to start processing a new chunk. However,
  21902. // a pathological inflate type of transform can cause excessive buffering
  21903. // here. For example, imagine a stream where every byte of input is
  21904. // interpreted as an integer from 0-255, and then results in that many
  21905. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  21906. // 1kb of data being output. In this case, you could write a very small
  21907. // amount of input, and end up with a very large amount of output. In
  21908. // such a pathological inflating mechanism, there'd be no way to tell
  21909. // the system to stop doing the transform. A single 4MB write could
  21910. // cause the system to run out of memory.
  21911. //
  21912. // However, even in such a pathological case, only a single written chunk
  21913. // would be consumed, and then the rest would wait (un-transformed) until
  21914. // the results of the previous transformed chunk were consumed.
  21915. 'use strict';
  21916. module.exports = Transform;
  21917. var Duplex = require('./_stream_duplex');
  21918. /*<replacement>*/
  21919. var util = require('core-util-is');
  21920. util.inherits = require('inherits');
  21921. /*</replacement>*/
  21922. util.inherits(Transform, Duplex);
  21923. function TransformState(stream) {
  21924. this.afterTransform = function (er, data) {
  21925. return afterTransform(stream, er, data);
  21926. };
  21927. this.needTransform = false;
  21928. this.transforming = false;
  21929. this.writecb = null;
  21930. this.writechunk = null;
  21931. this.writeencoding = null;
  21932. }
  21933. function afterTransform(stream, er, data) {
  21934. var ts = stream._transformState;
  21935. ts.transforming = false;
  21936. var cb = ts.writecb;
  21937. if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
  21938. ts.writechunk = null;
  21939. ts.writecb = null;
  21940. if (data !== null && data !== undefined) stream.push(data);
  21941. cb(er);
  21942. var rs = stream._readableState;
  21943. rs.reading = false;
  21944. if (rs.needReadable || rs.length < rs.highWaterMark) {
  21945. stream._read(rs.highWaterMark);
  21946. }
  21947. }
  21948. function Transform(options) {
  21949. if (!(this instanceof Transform)) return new Transform(options);
  21950. Duplex.call(this, options);
  21951. this._transformState = new TransformState(this);
  21952. var stream = this;
  21953. // start out asking for a readable event once data is transformed.
  21954. this._readableState.needReadable = true;
  21955. // we have implemented the _read method, and done the other things
  21956. // that Readable wants before the first _read call, so unset the
  21957. // sync guard flag.
  21958. this._readableState.sync = false;
  21959. if (options) {
  21960. if (typeof options.transform === 'function') this._transform = options.transform;
  21961. if (typeof options.flush === 'function') this._flush = options.flush;
  21962. }
  21963. // When the writable side finishes, then flush out anything remaining.
  21964. this.once('prefinish', function () {
  21965. if (typeof this._flush === 'function') this._flush(function (er, data) {
  21966. done(stream, er, data);
  21967. });else done(stream);
  21968. });
  21969. }
  21970. Transform.prototype.push = function (chunk, encoding) {
  21971. this._transformState.needTransform = false;
  21972. return Duplex.prototype.push.call(this, chunk, encoding);
  21973. };
  21974. // This is the part where you do stuff!
  21975. // override this function in implementation classes.
  21976. // 'chunk' is an input chunk.
  21977. //
  21978. // Call `push(newChunk)` to pass along transformed output
  21979. // to the readable side. You may call 'push' zero or more times.
  21980. //
  21981. // Call `cb(err)` when you are done with this chunk. If you pass
  21982. // an error, then that'll put the hurt on the whole operation. If you
  21983. // never call cb(), then you'll never get another chunk.
  21984. Transform.prototype._transform = function (chunk, encoding, cb) {
  21985. throw new Error('_transform() is not implemented');
  21986. };
  21987. Transform.prototype._write = function (chunk, encoding, cb) {
  21988. var ts = this._transformState;
  21989. ts.writecb = cb;
  21990. ts.writechunk = chunk;
  21991. ts.writeencoding = encoding;
  21992. if (!ts.transforming) {
  21993. var rs = this._readableState;
  21994. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  21995. }
  21996. };
  21997. // Doesn't matter what the args are here.
  21998. // _transform does all the work.
  21999. // That we got here means that the readable side wants more data.
  22000. Transform.prototype._read = function (n) {
  22001. var ts = this._transformState;
  22002. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  22003. ts.transforming = true;
  22004. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  22005. } else {
  22006. // mark that we need a transform, so that any data that comes in
  22007. // will get processed, now that we've asked for it.
  22008. ts.needTransform = true;
  22009. }
  22010. };
  22011. function done(stream, er, data) {
  22012. if (er) return stream.emit('error', er);
  22013. if (data !== null && data !== undefined) stream.push(data);
  22014. // if there's nothing in the write buffer, then that means
  22015. // that nothing more will ever be provided
  22016. var ws = stream._writableState;
  22017. var ts = stream._transformState;
  22018. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  22019. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  22020. return stream.push(null);
  22021. }
  22022. },{"./_stream_duplex":140,"core-util-is":78,"inherits":81}],144:[function(require,module,exports){
  22023. (function (process){
  22024. // A bit simpler than readable streams.
  22025. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  22026. // the drain event emission and buffering.
  22027. 'use strict';
  22028. module.exports = Writable;
  22029. /*<replacement>*/
  22030. var processNextTick = require('process-nextick-args');
  22031. /*</replacement>*/
  22032. /*<replacement>*/
  22033. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
  22034. /*</replacement>*/
  22035. /*<replacement>*/
  22036. var Duplex;
  22037. /*</replacement>*/
  22038. Writable.WritableState = WritableState;
  22039. /*<replacement>*/
  22040. var util = require('core-util-is');
  22041. util.inherits = require('inherits');
  22042. /*</replacement>*/
  22043. /*<replacement>*/
  22044. var internalUtil = {
  22045. deprecate: require('util-deprecate')
  22046. };
  22047. /*</replacement>*/
  22048. /*<replacement>*/
  22049. var Stream;
  22050. (function () {
  22051. try {
  22052. Stream = require('st' + 'ream');
  22053. } catch (_) {} finally {
  22054. if (!Stream) Stream = require('events').EventEmitter;
  22055. }
  22056. })();
  22057. /*</replacement>*/
  22058. var Buffer = require('buffer').Buffer;
  22059. /*<replacement>*/
  22060. var bufferShim = require('buffer-shims');
  22061. /*</replacement>*/
  22062. util.inherits(Writable, Stream);
  22063. function nop() {}
  22064. function WriteReq(chunk, encoding, cb) {
  22065. this.chunk = chunk;
  22066. this.encoding = encoding;
  22067. this.callback = cb;
  22068. this.next = null;
  22069. }
  22070. function WritableState(options, stream) {
  22071. Duplex = Duplex || require('./_stream_duplex');
  22072. options = options || {};
  22073. // object stream flag to indicate whether or not this stream
  22074. // contains buffers or objects.
  22075. this.objectMode = !!options.objectMode;
  22076. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  22077. // the point at which write() starts returning false
  22078. // Note: 0 is a valid value, means that we always return false if
  22079. // the entire buffer is not flushed immediately on write()
  22080. var hwm = options.highWaterMark;
  22081. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  22082. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  22083. // cast to ints.
  22084. this.highWaterMark = ~~this.highWaterMark;
  22085. // drain event flag.
  22086. this.needDrain = false;
  22087. // at the start of calling end()
  22088. this.ending = false;
  22089. // when end() has been called, and returned
  22090. this.ended = false;
  22091. // when 'finish' is emitted
  22092. this.finished = false;
  22093. // should we decode strings into buffers before passing to _write?
  22094. // this is here so that some node-core streams can optimize string
  22095. // handling at a lower level.
  22096. var noDecode = options.decodeStrings === false;
  22097. this.decodeStrings = !noDecode;
  22098. // Crypto is kind of old and crusty. Historically, its default string
  22099. // encoding is 'binary' so we have to make this configurable.
  22100. // Everything else in the universe uses 'utf8', though.
  22101. this.defaultEncoding = options.defaultEncoding || 'utf8';
  22102. // not an actual buffer we keep track of, but a measurement
  22103. // of how much we're waiting to get pushed to some underlying
  22104. // socket or file.
  22105. this.length = 0;
  22106. // a flag to see when we're in the middle of a write.
  22107. this.writing = false;
  22108. // when true all writes will be buffered until .uncork() call
  22109. this.corked = 0;
  22110. // a flag to be able to tell if the onwrite cb is called immediately,
  22111. // or on a later tick. We set this to true at first, because any
  22112. // actions that shouldn't happen until "later" should generally also
  22113. // not happen before the first write call.
  22114. this.sync = true;
  22115. // a flag to know if we're processing previously buffered items, which
  22116. // may call the _write() callback in the same tick, so that we don't
  22117. // end up in an overlapped onwrite situation.
  22118. this.bufferProcessing = false;
  22119. // the callback that's passed to _write(chunk,cb)
  22120. this.onwrite = function (er) {
  22121. onwrite(stream, er);
  22122. };
  22123. // the callback that the user supplies to write(chunk,encoding,cb)
  22124. this.writecb = null;
  22125. // the amount that is being written when _write is called.
  22126. this.writelen = 0;
  22127. this.bufferedRequest = null;
  22128. this.lastBufferedRequest = null;
  22129. // number of pending user-supplied write callbacks
  22130. // this must be 0 before 'finish' can be emitted
  22131. this.pendingcb = 0;
  22132. // emit prefinish if the only thing we're waiting for is _write cbs
  22133. // This is relevant for synchronous Transform streams
  22134. this.prefinished = false;
  22135. // True if the error was already emitted and should not be thrown again
  22136. this.errorEmitted = false;
  22137. // count buffered requests
  22138. this.bufferedRequestCount = 0;
  22139. // allocate the first CorkedRequest, there is always
  22140. // one allocated and free to use, and we maintain at most two
  22141. this.corkedRequestsFree = new CorkedRequest(this);
  22142. }
  22143. WritableState.prototype.getBuffer = function getBuffer() {
  22144. var current = this.bufferedRequest;
  22145. var out = [];
  22146. while (current) {
  22147. out.push(current);
  22148. current = current.next;
  22149. }
  22150. return out;
  22151. };
  22152. (function () {
  22153. try {
  22154. Object.defineProperty(WritableState.prototype, 'buffer', {
  22155. get: internalUtil.deprecate(function () {
  22156. return this.getBuffer();
  22157. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
  22158. });
  22159. } catch (_) {}
  22160. })();
  22161. // Test _writableState for inheritance to account for Duplex streams,
  22162. // whose prototype chain only points to Readable.
  22163. var realHasInstance;
  22164. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  22165. realHasInstance = Function.prototype[Symbol.hasInstance];
  22166. Object.defineProperty(Writable, Symbol.hasInstance, {
  22167. value: function (object) {
  22168. if (realHasInstance.call(this, object)) return true;
  22169. return object && object._writableState instanceof WritableState;
  22170. }
  22171. });
  22172. } else {
  22173. realHasInstance = function (object) {
  22174. return object instanceof this;
  22175. };
  22176. }
  22177. function Writable(options) {
  22178. Duplex = Duplex || require('./_stream_duplex');
  22179. // Writable ctor is applied to Duplexes, too.
  22180. // `realHasInstance` is necessary because using plain `instanceof`
  22181. // would return false, as no `_writableState` property is attached.
  22182. // Trying to use the custom `instanceof` for Writable here will also break the
  22183. // Node.js LazyTransform implementation, which has a non-trivial getter for
  22184. // `_writableState` that would lead to infinite recursion.
  22185. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  22186. return new Writable(options);
  22187. }
  22188. this._writableState = new WritableState(options, this);
  22189. // legacy.
  22190. this.writable = true;
  22191. if (options) {
  22192. if (typeof options.write === 'function') this._write = options.write;
  22193. if (typeof options.writev === 'function') this._writev = options.writev;
  22194. }
  22195. Stream.call(this);
  22196. }
  22197. // Otherwise people can pipe Writable streams, which is just wrong.
  22198. Writable.prototype.pipe = function () {
  22199. this.emit('error', new Error('Cannot pipe, not readable'));
  22200. };
  22201. function writeAfterEnd(stream, cb) {
  22202. var er = new Error('write after end');
  22203. // TODO: defer error events consistently everywhere, not just the cb
  22204. stream.emit('error', er);
  22205. processNextTick(cb, er);
  22206. }
  22207. // Checks that a user-supplied chunk is valid, especially for the particular
  22208. // mode the stream is in. Currently this means that `null` is never accepted
  22209. // and undefined/non-string values are only allowed in object mode.
  22210. function validChunk(stream, state, chunk, cb) {
  22211. var valid = true;
  22212. var er = false;
  22213. if (chunk === null) {
  22214. er = new TypeError('May not write null values to stream');
  22215. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  22216. er = new TypeError('Invalid non-string/buffer chunk');
  22217. }
  22218. if (er) {
  22219. stream.emit('error', er);
  22220. processNextTick(cb, er);
  22221. valid = false;
  22222. }
  22223. return valid;
  22224. }
  22225. Writable.prototype.write = function (chunk, encoding, cb) {
  22226. var state = this._writableState;
  22227. var ret = false;
  22228. var isBuf = Buffer.isBuffer(chunk);
  22229. if (typeof encoding === 'function') {
  22230. cb = encoding;
  22231. encoding = null;
  22232. }
  22233. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  22234. if (typeof cb !== 'function') cb = nop;
  22235. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  22236. state.pendingcb++;
  22237. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  22238. }
  22239. return ret;
  22240. };
  22241. Writable.prototype.cork = function () {
  22242. var state = this._writableState;
  22243. state.corked++;
  22244. };
  22245. Writable.prototype.uncork = function () {
  22246. var state = this._writableState;
  22247. if (state.corked) {
  22248. state.corked--;
  22249. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  22250. }
  22251. };
  22252. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  22253. // node::ParseEncoding() requires lower case.
  22254. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  22255. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  22256. this._writableState.defaultEncoding = encoding;
  22257. return this;
  22258. };
  22259. function decodeChunk(state, chunk, encoding) {
  22260. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  22261. chunk = bufferShim.from(chunk, encoding);
  22262. }
  22263. return chunk;
  22264. }
  22265. // if we're already writing something, then just put this
  22266. // in the queue, and wait our turn. Otherwise, call _write
  22267. // If we return false, then we need a drain event, so set that flag.
  22268. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  22269. if (!isBuf) {
  22270. chunk = decodeChunk(state, chunk, encoding);
  22271. if (Buffer.isBuffer(chunk)) encoding = 'buffer';
  22272. }
  22273. var len = state.objectMode ? 1 : chunk.length;
  22274. state.length += len;
  22275. var ret = state.length < state.highWaterMark;
  22276. // we must ensure that previous needDrain will not be reset to false.
  22277. if (!ret) state.needDrain = true;
  22278. if (state.writing || state.corked) {
  22279. var last = state.lastBufferedRequest;
  22280. state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
  22281. if (last) {
  22282. last.next = state.lastBufferedRequest;
  22283. } else {
  22284. state.bufferedRequest = state.lastBufferedRequest;
  22285. }
  22286. state.bufferedRequestCount += 1;
  22287. } else {
  22288. doWrite(stream, state, false, len, chunk, encoding, cb);
  22289. }
  22290. return ret;
  22291. }
  22292. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  22293. state.writelen = len;
  22294. state.writecb = cb;
  22295. state.writing = true;
  22296. state.sync = true;
  22297. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  22298. state.sync = false;
  22299. }
  22300. function onwriteError(stream, state, sync, er, cb) {
  22301. --state.pendingcb;
  22302. if (sync) processNextTick(cb, er);else cb(er);
  22303. stream._writableState.errorEmitted = true;
  22304. stream.emit('error', er);
  22305. }
  22306. function onwriteStateUpdate(state) {
  22307. state.writing = false;
  22308. state.writecb = null;
  22309. state.length -= state.writelen;
  22310. state.writelen = 0;
  22311. }
  22312. function onwrite(stream, er) {
  22313. var state = stream._writableState;
  22314. var sync = state.sync;
  22315. var cb = state.writecb;
  22316. onwriteStateUpdate(state);
  22317. if (er) onwriteError(stream, state, sync, er, cb);else {
  22318. // Check if we're actually ready to finish, but don't emit yet
  22319. var finished = needFinish(state);
  22320. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  22321. clearBuffer(stream, state);
  22322. }
  22323. if (sync) {
  22324. /*<replacement>*/
  22325. asyncWrite(afterWrite, stream, state, finished, cb);
  22326. /*</replacement>*/
  22327. } else {
  22328. afterWrite(stream, state, finished, cb);
  22329. }
  22330. }
  22331. }
  22332. function afterWrite(stream, state, finished, cb) {
  22333. if (!finished) onwriteDrain(stream, state);
  22334. state.pendingcb--;
  22335. cb();
  22336. finishMaybe(stream, state);
  22337. }
  22338. // Must force callback to be called on nextTick, so that we don't
  22339. // emit 'drain' before the write() consumer gets the 'false' return
  22340. // value, and has a chance to attach a 'drain' listener.
  22341. function onwriteDrain(stream, state) {
  22342. if (state.length === 0 && state.needDrain) {
  22343. state.needDrain = false;
  22344. stream.emit('drain');
  22345. }
  22346. }
  22347. // if there's something in the buffer waiting, then process it
  22348. function clearBuffer(stream, state) {
  22349. state.bufferProcessing = true;
  22350. var entry = state.bufferedRequest;
  22351. if (stream._writev && entry && entry.next) {
  22352. // Fast case, write everything using _writev()
  22353. var l = state.bufferedRequestCount;
  22354. var buffer = new Array(l);
  22355. var holder = state.corkedRequestsFree;
  22356. holder.entry = entry;
  22357. var count = 0;
  22358. while (entry) {
  22359. buffer[count] = entry;
  22360. entry = entry.next;
  22361. count += 1;
  22362. }
  22363. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  22364. // doWrite is almost always async, defer these to save a bit of time
  22365. // as the hot path ends with doWrite
  22366. state.pendingcb++;
  22367. state.lastBufferedRequest = null;
  22368. if (holder.next) {
  22369. state.corkedRequestsFree = holder.next;
  22370. holder.next = null;
  22371. } else {
  22372. state.corkedRequestsFree = new CorkedRequest(state);
  22373. }
  22374. } else {
  22375. // Slow case, write chunks one-by-one
  22376. while (entry) {
  22377. var chunk = entry.chunk;
  22378. var encoding = entry.encoding;
  22379. var cb = entry.callback;
  22380. var len = state.objectMode ? 1 : chunk.length;
  22381. doWrite(stream, state, false, len, chunk, encoding, cb);
  22382. entry = entry.next;
  22383. // if we didn't call the onwrite immediately, then
  22384. // it means that we need to wait until it does.
  22385. // also, that means that the chunk and cb are currently
  22386. // being processed, so move the buffer counter past them.
  22387. if (state.writing) {
  22388. break;
  22389. }
  22390. }
  22391. if (entry === null) state.lastBufferedRequest = null;
  22392. }
  22393. state.bufferedRequestCount = 0;
  22394. state.bufferedRequest = entry;
  22395. state.bufferProcessing = false;
  22396. }
  22397. Writable.prototype._write = function (chunk, encoding, cb) {
  22398. cb(new Error('_write() is not implemented'));
  22399. };
  22400. Writable.prototype._writev = null;
  22401. Writable.prototype.end = function (chunk, encoding, cb) {
  22402. var state = this._writableState;
  22403. if (typeof chunk === 'function') {
  22404. cb = chunk;
  22405. chunk = null;
  22406. encoding = null;
  22407. } else if (typeof encoding === 'function') {
  22408. cb = encoding;
  22409. encoding = null;
  22410. }
  22411. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  22412. // .end() fully uncorks
  22413. if (state.corked) {
  22414. state.corked = 1;
  22415. this.uncork();
  22416. }
  22417. // ignore unnecessary end() calls.
  22418. if (!state.ending && !state.finished) endWritable(this, state, cb);
  22419. };
  22420. function needFinish(state) {
  22421. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  22422. }
  22423. function prefinish(stream, state) {
  22424. if (!state.prefinished) {
  22425. state.prefinished = true;
  22426. stream.emit('prefinish');
  22427. }
  22428. }
  22429. function finishMaybe(stream, state) {
  22430. var need = needFinish(state);
  22431. if (need) {
  22432. if (state.pendingcb === 0) {
  22433. prefinish(stream, state);
  22434. state.finished = true;
  22435. stream.emit('finish');
  22436. } else {
  22437. prefinish(stream, state);
  22438. }
  22439. }
  22440. return need;
  22441. }
  22442. function endWritable(stream, state, cb) {
  22443. state.ending = true;
  22444. finishMaybe(stream, state);
  22445. if (cb) {
  22446. if (state.finished) processNextTick(cb);else stream.once('finish', cb);
  22447. }
  22448. state.ended = true;
  22449. stream.writable = false;
  22450. }
  22451. // It seems a linked list but it is not
  22452. // there will be only 2 of these for each stream
  22453. function CorkedRequest(state) {
  22454. var _this = this;
  22455. this.next = null;
  22456. this.entry = null;
  22457. this.finish = function (err) {
  22458. var entry = _this.entry;
  22459. _this.entry = null;
  22460. while (entry) {
  22461. var cb = entry.callback;
  22462. state.pendingcb--;
  22463. cb(err);
  22464. entry = entry.next;
  22465. }
  22466. if (state.corkedRequestsFree) {
  22467. state.corkedRequestsFree.next = _this;
  22468. } else {
  22469. state.corkedRequestsFree = _this;
  22470. }
  22471. };
  22472. }
  22473. }).call(this,require('_process'))
  22474. },{"./_stream_duplex":140,"_process":138,"buffer":77,"buffer-shims":76,"core-util-is":78,"events":79,"inherits":81,"process-nextick-args":137,"util-deprecate":154}],145:[function(require,module,exports){
  22475. 'use strict';
  22476. var Buffer = require('buffer').Buffer;
  22477. /*<replacement>*/
  22478. var bufferShim = require('buffer-shims');
  22479. /*</replacement>*/
  22480. module.exports = BufferList;
  22481. function BufferList() {
  22482. this.head = null;
  22483. this.tail = null;
  22484. this.length = 0;
  22485. }
  22486. BufferList.prototype.push = function (v) {
  22487. var entry = { data: v, next: null };
  22488. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  22489. this.tail = entry;
  22490. ++this.length;
  22491. };
  22492. BufferList.prototype.unshift = function (v) {
  22493. var entry = { data: v, next: this.head };
  22494. if (this.length === 0) this.tail = entry;
  22495. this.head = entry;
  22496. ++this.length;
  22497. };
  22498. BufferList.prototype.shift = function () {
  22499. if (this.length === 0) return;
  22500. var ret = this.head.data;
  22501. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  22502. --this.length;
  22503. return ret;
  22504. };
  22505. BufferList.prototype.clear = function () {
  22506. this.head = this.tail = null;
  22507. this.length = 0;
  22508. };
  22509. BufferList.prototype.join = function (s) {
  22510. if (this.length === 0) return '';
  22511. var p = this.head;
  22512. var ret = '' + p.data;
  22513. while (p = p.next) {
  22514. ret += s + p.data;
  22515. }return ret;
  22516. };
  22517. BufferList.prototype.concat = function (n) {
  22518. if (this.length === 0) return bufferShim.alloc(0);
  22519. if (this.length === 1) return this.head.data;
  22520. var ret = bufferShim.allocUnsafe(n >>> 0);
  22521. var p = this.head;
  22522. var i = 0;
  22523. while (p) {
  22524. p.data.copy(ret, i);
  22525. i += p.data.length;
  22526. p = p.next;
  22527. }
  22528. return ret;
  22529. };
  22530. },{"buffer":77,"buffer-shims":76}],146:[function(require,module,exports){
  22531. module.exports = require("./lib/_stream_passthrough.js")
  22532. },{"./lib/_stream_passthrough.js":141}],147:[function(require,module,exports){
  22533. (function (process){
  22534. var Stream = (function (){
  22535. try {
  22536. return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
  22537. } catch(_){}
  22538. }());
  22539. exports = module.exports = require('./lib/_stream_readable.js');
  22540. exports.Stream = Stream || exports;
  22541. exports.Readable = exports;
  22542. exports.Writable = require('./lib/_stream_writable.js');
  22543. exports.Duplex = require('./lib/_stream_duplex.js');
  22544. exports.Transform = require('./lib/_stream_transform.js');
  22545. exports.PassThrough = require('./lib/_stream_passthrough.js');
  22546. if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
  22547. module.exports = Stream;
  22548. }
  22549. }).call(this,require('_process'))
  22550. },{"./lib/_stream_duplex.js":140,"./lib/_stream_passthrough.js":141,"./lib/_stream_readable.js":142,"./lib/_stream_transform.js":143,"./lib/_stream_writable.js":144,"_process":138}],148:[function(require,module,exports){
  22551. module.exports = require("./lib/_stream_transform.js")
  22552. },{"./lib/_stream_transform.js":143}],149:[function(require,module,exports){
  22553. module.exports = require("./lib/_stream_writable.js")
  22554. },{"./lib/_stream_writable.js":144}],150:[function(require,module,exports){
  22555. (function (Buffer){
  22556. ;(function (sax) { // wrapper for non-node envs
  22557. sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
  22558. sax.SAXParser = SAXParser
  22559. sax.SAXStream = SAXStream
  22560. sax.createStream = createStream
  22561. // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
  22562. // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
  22563. // since that's the earliest that a buffer overrun could occur. This way, checks are
  22564. // as rare as required, but as often as necessary to ensure never crossing this bound.
  22565. // Furthermore, buffers are only tested at most once per write(), so passing a very
  22566. // large string into write() might have undesirable effects, but this is manageable by
  22567. // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
  22568. // edge case, result in creating at most one complete copy of the string passed in.
  22569. // Set to Infinity to have unlimited buffers.
  22570. sax.MAX_BUFFER_LENGTH = 64 * 1024
  22571. var buffers = [
  22572. 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
  22573. 'procInstName', 'procInstBody', 'entity', 'attribName',
  22574. 'attribValue', 'cdata', 'script'
  22575. ]
  22576. sax.EVENTS = [
  22577. 'text',
  22578. 'processinginstruction',
  22579. 'sgmldeclaration',
  22580. 'doctype',
  22581. 'comment',
  22582. 'attribute',
  22583. 'opentag',
  22584. 'closetag',
  22585. 'opencdata',
  22586. 'cdata',
  22587. 'closecdata',
  22588. 'error',
  22589. 'end',
  22590. 'ready',
  22591. 'script',
  22592. 'opennamespace',
  22593. 'closenamespace'
  22594. ]
  22595. function SAXParser (strict, opt) {
  22596. if (!(this instanceof SAXParser)) {
  22597. return new SAXParser(strict, opt)
  22598. }
  22599. var parser = this
  22600. clearBuffers(parser)
  22601. parser.q = parser.c = ''
  22602. parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
  22603. parser.opt = opt || {}
  22604. parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
  22605. parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
  22606. parser.tags = []
  22607. parser.closed = parser.closedRoot = parser.sawRoot = false
  22608. parser.tag = parser.error = null
  22609. parser.strict = !!strict
  22610. parser.noscript = !!(strict || parser.opt.noscript)
  22611. parser.state = S.BEGIN
  22612. parser.strictEntities = parser.opt.strictEntities
  22613. parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
  22614. parser.attribList = []
  22615. // namespaces form a prototype chain.
  22616. // it always points at the current tag,
  22617. // which protos to its parent tag.
  22618. if (parser.opt.xmlns) {
  22619. parser.ns = Object.create(rootNS)
  22620. }
  22621. // mostly just for error reporting
  22622. parser.trackPosition = parser.opt.position !== false
  22623. if (parser.trackPosition) {
  22624. parser.position = parser.line = parser.column = 0
  22625. }
  22626. emit(parser, 'onready')
  22627. }
  22628. if (!Object.create) {
  22629. Object.create = function (o) {
  22630. function F () {}
  22631. F.prototype = o
  22632. var newf = new F()
  22633. return newf
  22634. }
  22635. }
  22636. if (!Object.keys) {
  22637. Object.keys = function (o) {
  22638. var a = []
  22639. for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
  22640. return a
  22641. }
  22642. }
  22643. function checkBufferLength (parser) {
  22644. var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
  22645. var maxActual = 0
  22646. for (var i = 0, l = buffers.length; i < l; i++) {
  22647. var len = parser[buffers[i]].length
  22648. if (len > maxAllowed) {
  22649. // Text/cdata nodes can get big, and since they're buffered,
  22650. // we can get here under normal conditions.
  22651. // Avoid issues by emitting the text node now,
  22652. // so at least it won't get any bigger.
  22653. switch (buffers[i]) {
  22654. case 'textNode':
  22655. closeText(parser)
  22656. break
  22657. case 'cdata':
  22658. emitNode(parser, 'oncdata', parser.cdata)
  22659. parser.cdata = ''
  22660. break
  22661. case 'script':
  22662. emitNode(parser, 'onscript', parser.script)
  22663. parser.script = ''
  22664. break
  22665. default:
  22666. error(parser, 'Max buffer length exceeded: ' + buffers[i])
  22667. }
  22668. }
  22669. maxActual = Math.max(maxActual, len)
  22670. }
  22671. // schedule the next check for the earliest possible buffer overrun.
  22672. var m = sax.MAX_BUFFER_LENGTH - maxActual
  22673. parser.bufferCheckPosition = m + parser.position
  22674. }
  22675. function clearBuffers (parser) {
  22676. for (var i = 0, l = buffers.length; i < l; i++) {
  22677. parser[buffers[i]] = ''
  22678. }
  22679. }
  22680. function flushBuffers (parser) {
  22681. closeText(parser)
  22682. if (parser.cdata !== '') {
  22683. emitNode(parser, 'oncdata', parser.cdata)
  22684. parser.cdata = ''
  22685. }
  22686. if (parser.script !== '') {
  22687. emitNode(parser, 'onscript', parser.script)
  22688. parser.script = ''
  22689. }
  22690. }
  22691. SAXParser.prototype = {
  22692. end: function () { end(this) },
  22693. write: write,
  22694. resume: function () { this.error = null; return this },
  22695. close: function () { return this.write(null) },
  22696. flush: function () { flushBuffers(this) }
  22697. }
  22698. var Stream
  22699. try {
  22700. Stream = require('stream').Stream
  22701. } catch (ex) {
  22702. Stream = function () {}
  22703. }
  22704. var streamWraps = sax.EVENTS.filter(function (ev) {
  22705. return ev !== 'error' && ev !== 'end'
  22706. })
  22707. function createStream (strict, opt) {
  22708. return new SAXStream(strict, opt)
  22709. }
  22710. function SAXStream (strict, opt) {
  22711. if (!(this instanceof SAXStream)) {
  22712. return new SAXStream(strict, opt)
  22713. }
  22714. Stream.apply(this)
  22715. this._parser = new SAXParser(strict, opt)
  22716. this.writable = true
  22717. this.readable = true
  22718. var me = this
  22719. this._parser.onend = function () {
  22720. me.emit('end')
  22721. }
  22722. this._parser.onerror = function (er) {
  22723. me.emit('error', er)
  22724. // if didn't throw, then means error was handled.
  22725. // go ahead and clear error, so we can write again.
  22726. me._parser.error = null
  22727. }
  22728. this._decoder = null
  22729. streamWraps.forEach(function (ev) {
  22730. Object.defineProperty(me, 'on' + ev, {
  22731. get: function () {
  22732. return me._parser['on' + ev]
  22733. },
  22734. set: function (h) {
  22735. if (!h) {
  22736. me.removeAllListeners(ev)
  22737. me._parser['on' + ev] = h
  22738. return h
  22739. }
  22740. me.on(ev, h)
  22741. },
  22742. enumerable: true,
  22743. configurable: false
  22744. })
  22745. })
  22746. }
  22747. SAXStream.prototype = Object.create(Stream.prototype, {
  22748. constructor: {
  22749. value: SAXStream
  22750. }
  22751. })
  22752. SAXStream.prototype.write = function (data) {
  22753. if (typeof Buffer === 'function' &&
  22754. typeof Buffer.isBuffer === 'function' &&
  22755. Buffer.isBuffer(data)) {
  22756. if (!this._decoder) {
  22757. var SD = require('string_decoder').StringDecoder
  22758. this._decoder = new SD('utf8')
  22759. }
  22760. data = this._decoder.write(data)
  22761. }
  22762. this._parser.write(data.toString())
  22763. this.emit('data', data)
  22764. return true
  22765. }
  22766. SAXStream.prototype.end = function (chunk) {
  22767. if (chunk && chunk.length) {
  22768. this.write(chunk)
  22769. }
  22770. this._parser.end()
  22771. return true
  22772. }
  22773. SAXStream.prototype.on = function (ev, handler) {
  22774. var me = this
  22775. if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
  22776. me._parser['on' + ev] = function () {
  22777. var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
  22778. args.splice(0, 0, ev)
  22779. me.emit.apply(me, args)
  22780. }
  22781. }
  22782. return Stream.prototype.on.call(me, ev, handler)
  22783. }
  22784. // character classes and tokens
  22785. var whitespace = '\r\n\t '
  22786. // this really needs to be replaced with character classes.
  22787. // XML allows all manner of ridiculous numbers and digits.
  22788. var number = '0124356789'
  22789. var letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  22790. // (Letter | "_" | ":")
  22791. var quote = '\'"'
  22792. var attribEnd = whitespace + '>'
  22793. var CDATA = '[CDATA['
  22794. var DOCTYPE = 'DOCTYPE'
  22795. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
  22796. var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
  22797. var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
  22798. // turn all the string character sets into character class objects.
  22799. whitespace = charClass(whitespace)
  22800. number = charClass(number)
  22801. letter = charClass(letter)
  22802. // http://www.w3.org/TR/REC-xml/#NT-NameStartChar
  22803. // This implementation works on strings, a single character at a time
  22804. // as such, it cannot ever support astral-plane characters (10000-EFFFF)
  22805. // without a significant breaking change to either this parser, or the
  22806. // JavaScript language. Implementation of an emoji-capable xml parser
  22807. // is left as an exercise for the reader.
  22808. 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]/
  22809. 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-]/
  22810. 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]/
  22811. 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-]/
  22812. quote = charClass(quote)
  22813. attribEnd = charClass(attribEnd)
  22814. function charClass (str) {
  22815. return str.split('').reduce(function (s, c) {
  22816. s[c] = true
  22817. return s
  22818. }, {})
  22819. }
  22820. function isRegExp (c) {
  22821. return Object.prototype.toString.call(c) === '[object RegExp]'
  22822. }
  22823. function is (charclass, c) {
  22824. return isRegExp(charclass) ? !!c.match(charclass) : charclass[c]
  22825. }
  22826. function not (charclass, c) {
  22827. return !is(charclass, c)
  22828. }
  22829. var S = 0
  22830. sax.STATE = {
  22831. BEGIN: S++, // leading byte order mark or whitespace
  22832. BEGIN_WHITESPACE: S++, // leading whitespace
  22833. TEXT: S++, // general stuff
  22834. TEXT_ENTITY: S++, // &amp and such.
  22835. OPEN_WAKA: S++, // <
  22836. SGML_DECL: S++, // <!BLARG
  22837. SGML_DECL_QUOTED: S++, // <!BLARG foo "bar
  22838. DOCTYPE: S++, // <!DOCTYPE
  22839. DOCTYPE_QUOTED: S++, // <!DOCTYPE "//blah
  22840. DOCTYPE_DTD: S++, // <!DOCTYPE "//blah" [ ...
  22841. DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE "//blah" [ "foo
  22842. COMMENT_STARTING: S++, // <!-
  22843. COMMENT: S++, // <!--
  22844. COMMENT_ENDING: S++, // <!-- blah -
  22845. COMMENT_ENDED: S++, // <!-- blah --
  22846. CDATA: S++, // <![CDATA[ something
  22847. CDATA_ENDING: S++, // ]
  22848. CDATA_ENDING_2: S++, // ]]
  22849. PROC_INST: S++, // <?hi
  22850. PROC_INST_BODY: S++, // <?hi there
  22851. PROC_INST_ENDING: S++, // <?hi "there" ?
  22852. OPEN_TAG: S++, // <strong
  22853. OPEN_TAG_SLASH: S++, // <strong /
  22854. ATTRIB: S++, // <a
  22855. ATTRIB_NAME: S++, // <a foo
  22856. ATTRIB_NAME_SAW_WHITE: S++, // <a foo _
  22857. ATTRIB_VALUE: S++, // <a foo=
  22858. ATTRIB_VALUE_QUOTED: S++, // <a foo="bar
  22859. ATTRIB_VALUE_CLOSED: S++, // <a foo="bar"
  22860. ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar
  22861. ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar="&quot;"
  22862. ATTRIB_VALUE_ENTITY_U: S++, // <foo bar=&quot
  22863. CLOSE_TAG: S++, // </a
  22864. CLOSE_TAG_SAW_WHITE: S++, // </a >
  22865. SCRIPT: S++, // <script> ...
  22866. SCRIPT_ENDING: S++ // <script> ... <
  22867. }
  22868. sax.XML_ENTITIES = {
  22869. 'amp': '&',
  22870. 'gt': '>',
  22871. 'lt': '<',
  22872. 'quot': '"',
  22873. 'apos': "'"
  22874. }
  22875. sax.ENTITIES = {
  22876. 'amp': '&',
  22877. 'gt': '>',
  22878. 'lt': '<',
  22879. 'quot': '"',
  22880. 'apos': "'",
  22881. 'AElig': 198,
  22882. 'Aacute': 193,
  22883. 'Acirc': 194,
  22884. 'Agrave': 192,
  22885. 'Aring': 197,
  22886. 'Atilde': 195,
  22887. 'Auml': 196,
  22888. 'Ccedil': 199,
  22889. 'ETH': 208,
  22890. 'Eacute': 201,
  22891. 'Ecirc': 202,
  22892. 'Egrave': 200,
  22893. 'Euml': 203,
  22894. 'Iacute': 205,
  22895. 'Icirc': 206,
  22896. 'Igrave': 204,
  22897. 'Iuml': 207,
  22898. 'Ntilde': 209,
  22899. 'Oacute': 211,
  22900. 'Ocirc': 212,
  22901. 'Ograve': 210,
  22902. 'Oslash': 216,
  22903. 'Otilde': 213,
  22904. 'Ouml': 214,
  22905. 'THORN': 222,
  22906. 'Uacute': 218,
  22907. 'Ucirc': 219,
  22908. 'Ugrave': 217,
  22909. 'Uuml': 220,
  22910. 'Yacute': 221,
  22911. 'aacute': 225,
  22912. 'acirc': 226,
  22913. 'aelig': 230,
  22914. 'agrave': 224,
  22915. 'aring': 229,
  22916. 'atilde': 227,
  22917. 'auml': 228,
  22918. 'ccedil': 231,
  22919. 'eacute': 233,
  22920. 'ecirc': 234,
  22921. 'egrave': 232,
  22922. 'eth': 240,
  22923. 'euml': 235,
  22924. 'iacute': 237,
  22925. 'icirc': 238,
  22926. 'igrave': 236,
  22927. 'iuml': 239,
  22928. 'ntilde': 241,
  22929. 'oacute': 243,
  22930. 'ocirc': 244,
  22931. 'ograve': 242,
  22932. 'oslash': 248,
  22933. 'otilde': 245,
  22934. 'ouml': 246,
  22935. 'szlig': 223,
  22936. 'thorn': 254,
  22937. 'uacute': 250,
  22938. 'ucirc': 251,
  22939. 'ugrave': 249,
  22940. 'uuml': 252,
  22941. 'yacute': 253,
  22942. 'yuml': 255,
  22943. 'copy': 169,
  22944. 'reg': 174,
  22945. 'nbsp': 160,
  22946. 'iexcl': 161,
  22947. 'cent': 162,
  22948. 'pound': 163,
  22949. 'curren': 164,
  22950. 'yen': 165,
  22951. 'brvbar': 166,
  22952. 'sect': 167,
  22953. 'uml': 168,
  22954. 'ordf': 170,
  22955. 'laquo': 171,
  22956. 'not': 172,
  22957. 'shy': 173,
  22958. 'macr': 175,
  22959. 'deg': 176,
  22960. 'plusmn': 177,
  22961. 'sup1': 185,
  22962. 'sup2': 178,
  22963. 'sup3': 179,
  22964. 'acute': 180,
  22965. 'micro': 181,
  22966. 'para': 182,
  22967. 'middot': 183,
  22968. 'cedil': 184,
  22969. 'ordm': 186,
  22970. 'raquo': 187,
  22971. 'frac14': 188,
  22972. 'frac12': 189,
  22973. 'frac34': 190,
  22974. 'iquest': 191,
  22975. 'times': 215,
  22976. 'divide': 247,
  22977. 'OElig': 338,
  22978. 'oelig': 339,
  22979. 'Scaron': 352,
  22980. 'scaron': 353,
  22981. 'Yuml': 376,
  22982. 'fnof': 402,
  22983. 'circ': 710,
  22984. 'tilde': 732,
  22985. 'Alpha': 913,
  22986. 'Beta': 914,
  22987. 'Gamma': 915,
  22988. 'Delta': 916,
  22989. 'Epsilon': 917,
  22990. 'Zeta': 918,
  22991. 'Eta': 919,
  22992. 'Theta': 920,
  22993. 'Iota': 921,
  22994. 'Kappa': 922,
  22995. 'Lambda': 923,
  22996. 'Mu': 924,
  22997. 'Nu': 925,
  22998. 'Xi': 926,
  22999. 'Omicron': 927,
  23000. 'Pi': 928,
  23001. 'Rho': 929,
  23002. 'Sigma': 931,
  23003. 'Tau': 932,
  23004. 'Upsilon': 933,
  23005. 'Phi': 934,
  23006. 'Chi': 935,
  23007. 'Psi': 936,
  23008. 'Omega': 937,
  23009. 'alpha': 945,
  23010. 'beta': 946,
  23011. 'gamma': 947,
  23012. 'delta': 948,
  23013. 'epsilon': 949,
  23014. 'zeta': 950,
  23015. 'eta': 951,
  23016. 'theta': 952,
  23017. 'iota': 953,
  23018. 'kappa': 954,
  23019. 'lambda': 955,
  23020. 'mu': 956,
  23021. 'nu': 957,
  23022. 'xi': 958,
  23023. 'omicron': 959,
  23024. 'pi': 960,
  23025. 'rho': 961,
  23026. 'sigmaf': 962,
  23027. 'sigma': 963,
  23028. 'tau': 964,
  23029. 'upsilon': 965,
  23030. 'phi': 966,
  23031. 'chi': 967,
  23032. 'psi': 968,
  23033. 'omega': 969,
  23034. 'thetasym': 977,
  23035. 'upsih': 978,
  23036. 'piv': 982,
  23037. 'ensp': 8194,
  23038. 'emsp': 8195,
  23039. 'thinsp': 8201,
  23040. 'zwnj': 8204,
  23041. 'zwj': 8205,
  23042. 'lrm': 8206,
  23043. 'rlm': 8207,
  23044. 'ndash': 8211,
  23045. 'mdash': 8212,
  23046. 'lsquo': 8216,
  23047. 'rsquo': 8217,
  23048. 'sbquo': 8218,
  23049. 'ldquo': 8220,
  23050. 'rdquo': 8221,
  23051. 'bdquo': 8222,
  23052. 'dagger': 8224,
  23053. 'Dagger': 8225,
  23054. 'bull': 8226,
  23055. 'hellip': 8230,
  23056. 'permil': 8240,
  23057. 'prime': 8242,
  23058. 'Prime': 8243,
  23059. 'lsaquo': 8249,
  23060. 'rsaquo': 8250,
  23061. 'oline': 8254,
  23062. 'frasl': 8260,
  23063. 'euro': 8364,
  23064. 'image': 8465,
  23065. 'weierp': 8472,
  23066. 'real': 8476,
  23067. 'trade': 8482,
  23068. 'alefsym': 8501,
  23069. 'larr': 8592,
  23070. 'uarr': 8593,
  23071. 'rarr': 8594,
  23072. 'darr': 8595,
  23073. 'harr': 8596,
  23074. 'crarr': 8629,
  23075. 'lArr': 8656,
  23076. 'uArr': 8657,
  23077. 'rArr': 8658,
  23078. 'dArr': 8659,
  23079. 'hArr': 8660,
  23080. 'forall': 8704,
  23081. 'part': 8706,
  23082. 'exist': 8707,
  23083. 'empty': 8709,
  23084. 'nabla': 8711,
  23085. 'isin': 8712,
  23086. 'notin': 8713,
  23087. 'ni': 8715,
  23088. 'prod': 8719,
  23089. 'sum': 8721,
  23090. 'minus': 8722,
  23091. 'lowast': 8727,
  23092. 'radic': 8730,
  23093. 'prop': 8733,
  23094. 'infin': 8734,
  23095. 'ang': 8736,
  23096. 'and': 8743,
  23097. 'or': 8744,
  23098. 'cap': 8745,
  23099. 'cup': 8746,
  23100. 'int': 8747,
  23101. 'there4': 8756,
  23102. 'sim': 8764,
  23103. 'cong': 8773,
  23104. 'asymp': 8776,
  23105. 'ne': 8800,
  23106. 'equiv': 8801,
  23107. 'le': 8804,
  23108. 'ge': 8805,
  23109. 'sub': 8834,
  23110. 'sup': 8835,
  23111. 'nsub': 8836,
  23112. 'sube': 8838,
  23113. 'supe': 8839,
  23114. 'oplus': 8853,
  23115. 'otimes': 8855,
  23116. 'perp': 8869,
  23117. 'sdot': 8901,
  23118. 'lceil': 8968,
  23119. 'rceil': 8969,
  23120. 'lfloor': 8970,
  23121. 'rfloor': 8971,
  23122. 'lang': 9001,
  23123. 'rang': 9002,
  23124. 'loz': 9674,
  23125. 'spades': 9824,
  23126. 'clubs': 9827,
  23127. 'hearts': 9829,
  23128. 'diams': 9830
  23129. }
  23130. Object.keys(sax.ENTITIES).forEach(function (key) {
  23131. var e = sax.ENTITIES[key]
  23132. var s = typeof e === 'number' ? String.fromCharCode(e) : e
  23133. sax.ENTITIES[key] = s
  23134. })
  23135. for (var s in sax.STATE) {
  23136. sax.STATE[sax.STATE[s]] = s
  23137. }
  23138. // shorthand
  23139. S = sax.STATE
  23140. function emit (parser, event, data) {
  23141. parser[event] && parser[event](data)
  23142. }
  23143. function emitNode (parser, nodeType, data) {
  23144. if (parser.textNode) closeText(parser)
  23145. emit(parser, nodeType, data)
  23146. }
  23147. function closeText (parser) {
  23148. parser.textNode = textopts(parser.opt, parser.textNode)
  23149. if (parser.textNode) emit(parser, 'ontext', parser.textNode)
  23150. parser.textNode = ''
  23151. }
  23152. function textopts (opt, text) {
  23153. if (opt.trim) text = text.trim()
  23154. if (opt.normalize) text = text.replace(/\s+/g, ' ')
  23155. return text
  23156. }
  23157. function error (parser, er) {
  23158. closeText(parser)
  23159. if (parser.trackPosition) {
  23160. er += '\nLine: ' + parser.line +
  23161. '\nColumn: ' + parser.column +
  23162. '\nChar: ' + parser.c
  23163. }
  23164. er = new Error(er)
  23165. parser.error = er
  23166. emit(parser, 'onerror', er)
  23167. return parser
  23168. }
  23169. function end (parser) {
  23170. if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag')
  23171. if ((parser.state !== S.BEGIN) &&
  23172. (parser.state !== S.BEGIN_WHITESPACE) &&
  23173. (parser.state !== S.TEXT)) {
  23174. error(parser, 'Unexpected end')
  23175. }
  23176. closeText(parser)
  23177. parser.c = ''
  23178. parser.closed = true
  23179. emit(parser, 'onend')
  23180. SAXParser.call(parser, parser.strict, parser.opt)
  23181. return parser
  23182. }
  23183. function strictFail (parser, message) {
  23184. if (typeof parser !== 'object' || !(parser instanceof SAXParser)) {
  23185. throw new Error('bad call to strictFail')
  23186. }
  23187. if (parser.strict) {
  23188. error(parser, message)
  23189. }
  23190. }
  23191. function newTag (parser) {
  23192. if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]()
  23193. var parent = parser.tags[parser.tags.length - 1] || parser
  23194. var tag = parser.tag = { name: parser.tagName, attributes: {} }
  23195. // will be overridden if tag contails an xmlns="foo" or xmlns:foo="bar"
  23196. if (parser.opt.xmlns) {
  23197. tag.ns = parent.ns
  23198. }
  23199. parser.attribList.length = 0
  23200. }
  23201. function qname (name, attribute) {
  23202. var i = name.indexOf(':')
  23203. var qualName = i < 0 ? [ '', name ] : name.split(':')
  23204. var prefix = qualName[0]
  23205. var local = qualName[1]
  23206. // <x "xmlns"="http://foo">
  23207. if (attribute && name === 'xmlns') {
  23208. prefix = 'xmlns'
  23209. local = ''
  23210. }
  23211. return { prefix: prefix, local: local }
  23212. }
  23213. function attrib (parser) {
  23214. if (!parser.strict) {
  23215. parser.attribName = parser.attribName[parser.looseCase]()
  23216. }
  23217. if (parser.attribList.indexOf(parser.attribName) !== -1 ||
  23218. parser.tag.attributes.hasOwnProperty(parser.attribName)) {
  23219. parser.attribName = parser.attribValue = ''
  23220. return
  23221. }
  23222. if (parser.opt.xmlns) {
  23223. var qn = qname(parser.attribName, true)
  23224. var prefix = qn.prefix
  23225. var local = qn.local
  23226. if (prefix === 'xmlns') {
  23227. // namespace binding attribute. push the binding into scope
  23228. if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {
  23229. strictFail(parser,
  23230. 'xml: prefix must be bound to ' + XML_NAMESPACE + '\n' +
  23231. 'Actual: ' + parser.attribValue)
  23232. } else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {
  23233. strictFail(parser,
  23234. 'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\n' +
  23235. 'Actual: ' + parser.attribValue)
  23236. } else {
  23237. var tag = parser.tag
  23238. var parent = parser.tags[parser.tags.length - 1] || parser
  23239. if (tag.ns === parent.ns) {
  23240. tag.ns = Object.create(parent.ns)
  23241. }
  23242. tag.ns[local] = parser.attribValue
  23243. }
  23244. }
  23245. // defer onattribute events until all attributes have been seen
  23246. // so any new bindings can take effect. preserve attribute order
  23247. // so deferred events can be emitted in document order
  23248. parser.attribList.push([parser.attribName, parser.attribValue])
  23249. } else {
  23250. // in non-xmlns mode, we can emit the event right away
  23251. parser.tag.attributes[parser.attribName] = parser.attribValue
  23252. emitNode(parser, 'onattribute', {
  23253. name: parser.attribName,
  23254. value: parser.attribValue
  23255. })
  23256. }
  23257. parser.attribName = parser.attribValue = ''
  23258. }
  23259. function openTag (parser, selfClosing) {
  23260. if (parser.opt.xmlns) {
  23261. // emit namespace binding events
  23262. var tag = parser.tag
  23263. // add namespace info to tag
  23264. var qn = qname(parser.tagName)
  23265. tag.prefix = qn.prefix
  23266. tag.local = qn.local
  23267. tag.uri = tag.ns[qn.prefix] || ''
  23268. if (tag.prefix && !tag.uri) {
  23269. strictFail(parser, 'Unbound namespace prefix: ' +
  23270. JSON.stringify(parser.tagName))
  23271. tag.uri = qn.prefix
  23272. }
  23273. var parent = parser.tags[parser.tags.length - 1] || parser
  23274. if (tag.ns && parent.ns !== tag.ns) {
  23275. Object.keys(tag.ns).forEach(function (p) {
  23276. emitNode(parser, 'onopennamespace', {
  23277. prefix: p,
  23278. uri: tag.ns[p]
  23279. })
  23280. })
  23281. }
  23282. // handle deferred onattribute events
  23283. // Note: do not apply default ns to attributes:
  23284. // http://www.w3.org/TR/REC-xml-names/#defaulting
  23285. for (var i = 0, l = parser.attribList.length; i < l; i++) {
  23286. var nv = parser.attribList[i]
  23287. var name = nv[0]
  23288. var value = nv[1]
  23289. var qualName = qname(name, true)
  23290. var prefix = qualName.prefix
  23291. var local = qualName.local
  23292. var uri = prefix === '' ? '' : (tag.ns[prefix] || '')
  23293. var a = {
  23294. name: name,
  23295. value: value,
  23296. prefix: prefix,
  23297. local: local,
  23298. uri: uri
  23299. }
  23300. // if there's any attributes with an undefined namespace,
  23301. // then fail on them now.
  23302. if (prefix && prefix !== 'xmlns' && !uri) {
  23303. strictFail(parser, 'Unbound namespace prefix: ' +
  23304. JSON.stringify(prefix))
  23305. a.uri = prefix
  23306. }
  23307. parser.tag.attributes[name] = a
  23308. emitNode(parser, 'onattribute', a)
  23309. }
  23310. parser.attribList.length = 0
  23311. }
  23312. parser.tag.isSelfClosing = !!selfClosing
  23313. // process the tag
  23314. parser.sawRoot = true
  23315. parser.tags.push(parser.tag)
  23316. emitNode(parser, 'onopentag', parser.tag)
  23317. if (!selfClosing) {
  23318. // special case for <script> in non-strict mode.
  23319. if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {
  23320. parser.state = S.SCRIPT
  23321. } else {
  23322. parser.state = S.TEXT
  23323. }
  23324. parser.tag = null
  23325. parser.tagName = ''
  23326. }
  23327. parser.attribName = parser.attribValue = ''
  23328. parser.attribList.length = 0
  23329. }
  23330. function closeTag (parser) {
  23331. if (!parser.tagName) {
  23332. strictFail(parser, 'Weird empty close tag.')
  23333. parser.textNode += '</>'
  23334. parser.state = S.TEXT
  23335. return
  23336. }
  23337. if (parser.script) {
  23338. if (parser.tagName !== 'script') {
  23339. parser.script += '</' + parser.tagName + '>'
  23340. parser.tagName = ''
  23341. parser.state = S.SCRIPT
  23342. return
  23343. }
  23344. emitNode(parser, 'onscript', parser.script)
  23345. parser.script = ''
  23346. }
  23347. // first make sure that the closing tag actually exists.
  23348. // <a><b></c></b></a> will close everything, otherwise.
  23349. var t = parser.tags.length
  23350. var tagName = parser.tagName
  23351. if (!parser.strict) {
  23352. tagName = tagName[parser.looseCase]()
  23353. }
  23354. var closeTo = tagName
  23355. while (t--) {
  23356. var close = parser.tags[t]
  23357. if (close.name !== closeTo) {
  23358. // fail the first time in strict mode
  23359. strictFail(parser, 'Unexpected close tag')
  23360. } else {
  23361. break
  23362. }
  23363. }
  23364. // didn't find it. we already failed for strict, so just abort.
  23365. if (t < 0) {
  23366. strictFail(parser, 'Unmatched closing tag: ' + parser.tagName)
  23367. parser.textNode += '</' + parser.tagName + '>'
  23368. parser.state = S.TEXT
  23369. return
  23370. }
  23371. parser.tagName = tagName
  23372. var s = parser.tags.length
  23373. while (s-- > t) {
  23374. var tag = parser.tag = parser.tags.pop()
  23375. parser.tagName = parser.tag.name
  23376. emitNode(parser, 'onclosetag', parser.tagName)
  23377. var x = {}
  23378. for (var i in tag.ns) {
  23379. x[i] = tag.ns[i]
  23380. }
  23381. var parent = parser.tags[parser.tags.length - 1] || parser
  23382. if (parser.opt.xmlns && tag.ns !== parent.ns) {
  23383. // remove namespace bindings introduced by tag
  23384. Object.keys(tag.ns).forEach(function (p) {
  23385. var n = tag.ns[p]
  23386. emitNode(parser, 'onclosenamespace', { prefix: p, uri: n })
  23387. })
  23388. }
  23389. }
  23390. if (t === 0) parser.closedRoot = true
  23391. parser.tagName = parser.attribValue = parser.attribName = ''
  23392. parser.attribList.length = 0
  23393. parser.state = S.TEXT
  23394. }
  23395. function parseEntity (parser) {
  23396. var entity = parser.entity
  23397. var entityLC = entity.toLowerCase()
  23398. var num
  23399. var numStr = ''
  23400. if (parser.ENTITIES[entity]) {
  23401. return parser.ENTITIES[entity]
  23402. }
  23403. if (parser.ENTITIES[entityLC]) {
  23404. return parser.ENTITIES[entityLC]
  23405. }
  23406. entity = entityLC
  23407. if (entity.charAt(0) === '#') {
  23408. if (entity.charAt(1) === 'x') {
  23409. entity = entity.slice(2)
  23410. num = parseInt(entity, 16)
  23411. numStr = num.toString(16)
  23412. } else {
  23413. entity = entity.slice(1)
  23414. num = parseInt(entity, 10)
  23415. numStr = num.toString(10)
  23416. }
  23417. }
  23418. entity = entity.replace(/^0+/, '')
  23419. if (numStr.toLowerCase() !== entity) {
  23420. strictFail(parser, 'Invalid character entity')
  23421. return '&' + parser.entity + ';'
  23422. }
  23423. return String.fromCodePoint(num)
  23424. }
  23425. function beginWhiteSpace (parser, c) {
  23426. if (c === '<') {
  23427. parser.state = S.OPEN_WAKA
  23428. parser.startTagPosition = parser.position
  23429. } else if (not(whitespace, c)) {
  23430. // have to process this as a text node.
  23431. // weird, but happens.
  23432. strictFail(parser, 'Non-whitespace before first tag.')
  23433. parser.textNode = c
  23434. parser.state = S.TEXT
  23435. }
  23436. }
  23437. function charAt (chunk, i) {
  23438. var result = ''
  23439. if (i < chunk.length) {
  23440. result = chunk.charAt(i)
  23441. }
  23442. return result
  23443. }
  23444. function write (chunk) {
  23445. var parser = this
  23446. if (this.error) {
  23447. throw this.error
  23448. }
  23449. if (parser.closed) {
  23450. return error(parser,
  23451. 'Cannot write after close. Assign an onready handler.')
  23452. }
  23453. if (chunk === null) {
  23454. return end(parser)
  23455. }
  23456. if (typeof chunk === 'object') {
  23457. chunk = chunk.toString()
  23458. }
  23459. var i = 0
  23460. var c = ''
  23461. while (true) {
  23462. c = charAt(chunk, i++)
  23463. parser.c = c
  23464. if (!c) {
  23465. break
  23466. }
  23467. if (parser.trackPosition) {
  23468. parser.position++
  23469. if (c === '\n') {
  23470. parser.line++
  23471. parser.column = 0
  23472. } else {
  23473. parser.column++
  23474. }
  23475. }
  23476. switch (parser.state) {
  23477. case S.BEGIN:
  23478. parser.state = S.BEGIN_WHITESPACE
  23479. if (c === '\uFEFF') {
  23480. continue
  23481. }
  23482. beginWhiteSpace(parser, c)
  23483. continue
  23484. case S.BEGIN_WHITESPACE:
  23485. beginWhiteSpace(parser, c)
  23486. continue
  23487. case S.TEXT:
  23488. if (parser.sawRoot && !parser.closedRoot) {
  23489. var starti = i - 1
  23490. while (c && c !== '<' && c !== '&') {
  23491. c = charAt(chunk, i++)
  23492. if (c && parser.trackPosition) {
  23493. parser.position++
  23494. if (c === '\n') {
  23495. parser.line++
  23496. parser.column = 0
  23497. } else {
  23498. parser.column++
  23499. }
  23500. }
  23501. }
  23502. parser.textNode += chunk.substring(starti, i - 1)
  23503. }
  23504. if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
  23505. parser.state = S.OPEN_WAKA
  23506. parser.startTagPosition = parser.position
  23507. } else {
  23508. if (not(whitespace, c) && (!parser.sawRoot || parser.closedRoot)) {
  23509. strictFail(parser, 'Text data outside of root node.')
  23510. }
  23511. if (c === '&') {
  23512. parser.state = S.TEXT_ENTITY
  23513. } else {
  23514. parser.textNode += c
  23515. }
  23516. }
  23517. continue
  23518. case S.SCRIPT:
  23519. // only non-strict
  23520. if (c === '<') {
  23521. parser.state = S.SCRIPT_ENDING
  23522. } else {
  23523. parser.script += c
  23524. }
  23525. continue
  23526. case S.SCRIPT_ENDING:
  23527. if (c === '/') {
  23528. parser.state = S.CLOSE_TAG
  23529. } else {
  23530. parser.script += '<' + c
  23531. parser.state = S.SCRIPT
  23532. }
  23533. continue
  23534. case S.OPEN_WAKA:
  23535. // either a /, ?, !, or text is coming next.
  23536. if (c === '!') {
  23537. parser.state = S.SGML_DECL
  23538. parser.sgmlDecl = ''
  23539. } else if (is(whitespace, c)) {
  23540. // wait for it...
  23541. } else if (is(nameStart, c)) {
  23542. parser.state = S.OPEN_TAG
  23543. parser.tagName = c
  23544. } else if (c === '/') {
  23545. parser.state = S.CLOSE_TAG
  23546. parser.tagName = ''
  23547. } else if (c === '?') {
  23548. parser.state = S.PROC_INST
  23549. parser.procInstName = parser.procInstBody = ''
  23550. } else {
  23551. strictFail(parser, 'Unencoded <')
  23552. // if there was some whitespace, then add that in.
  23553. if (parser.startTagPosition + 1 < parser.position) {
  23554. var pad = parser.position - parser.startTagPosition
  23555. c = new Array(pad).join(' ') + c
  23556. }
  23557. parser.textNode += '<' + c
  23558. parser.state = S.TEXT
  23559. }
  23560. continue
  23561. case S.SGML_DECL:
  23562. if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
  23563. emitNode(parser, 'onopencdata')
  23564. parser.state = S.CDATA
  23565. parser.sgmlDecl = ''
  23566. parser.cdata = ''
  23567. } else if (parser.sgmlDecl + c === '--') {
  23568. parser.state = S.COMMENT
  23569. parser.comment = ''
  23570. parser.sgmlDecl = ''
  23571. } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
  23572. parser.state = S.DOCTYPE
  23573. if (parser.doctype || parser.sawRoot) {
  23574. strictFail(parser,
  23575. 'Inappropriately located doctype declaration')
  23576. }
  23577. parser.doctype = ''
  23578. parser.sgmlDecl = ''
  23579. } else if (c === '>') {
  23580. emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl)
  23581. parser.sgmlDecl = ''
  23582. parser.state = S.TEXT
  23583. } else if (is(quote, c)) {
  23584. parser.state = S.SGML_DECL_QUOTED
  23585. parser.sgmlDecl += c
  23586. } else {
  23587. parser.sgmlDecl += c
  23588. }
  23589. continue
  23590. case S.SGML_DECL_QUOTED:
  23591. if (c === parser.q) {
  23592. parser.state = S.SGML_DECL
  23593. parser.q = ''
  23594. }
  23595. parser.sgmlDecl += c
  23596. continue
  23597. case S.DOCTYPE:
  23598. if (c === '>') {
  23599. parser.state = S.TEXT
  23600. emitNode(parser, 'ondoctype', parser.doctype)
  23601. parser.doctype = true // just remember that we saw it.
  23602. } else {
  23603. parser.doctype += c
  23604. if (c === '[') {
  23605. parser.state = S.DOCTYPE_DTD
  23606. } else if (is(quote, c)) {
  23607. parser.state = S.DOCTYPE_QUOTED
  23608. parser.q = c
  23609. }
  23610. }
  23611. continue
  23612. case S.DOCTYPE_QUOTED:
  23613. parser.doctype += c
  23614. if (c === parser.q) {
  23615. parser.q = ''
  23616. parser.state = S.DOCTYPE
  23617. }
  23618. continue
  23619. case S.DOCTYPE_DTD:
  23620. parser.doctype += c
  23621. if (c === ']') {
  23622. parser.state = S.DOCTYPE
  23623. } else if (is(quote, c)) {
  23624. parser.state = S.DOCTYPE_DTD_QUOTED
  23625. parser.q = c
  23626. }
  23627. continue
  23628. case S.DOCTYPE_DTD_QUOTED:
  23629. parser.doctype += c
  23630. if (c === parser.q) {
  23631. parser.state = S.DOCTYPE_DTD
  23632. parser.q = ''
  23633. }
  23634. continue
  23635. case S.COMMENT:
  23636. if (c === '-') {
  23637. parser.state = S.COMMENT_ENDING
  23638. } else {
  23639. parser.comment += c
  23640. }
  23641. continue
  23642. case S.COMMENT_ENDING:
  23643. if (c === '-') {
  23644. parser.state = S.COMMENT_ENDED
  23645. parser.comment = textopts(parser.opt, parser.comment)
  23646. if (parser.comment) {
  23647. emitNode(parser, 'oncomment', parser.comment)
  23648. }
  23649. parser.comment = ''
  23650. } else {
  23651. parser.comment += '-' + c
  23652. parser.state = S.COMMENT
  23653. }
  23654. continue
  23655. case S.COMMENT_ENDED:
  23656. if (c !== '>') {
  23657. strictFail(parser, 'Malformed comment')
  23658. // allow <!-- blah -- bloo --> in non-strict mode,
  23659. // which is a comment of " blah -- bloo "
  23660. parser.comment += '--' + c
  23661. parser.state = S.COMMENT
  23662. } else {
  23663. parser.state = S.TEXT
  23664. }
  23665. continue
  23666. case S.CDATA:
  23667. if (c === ']') {
  23668. parser.state = S.CDATA_ENDING
  23669. } else {
  23670. parser.cdata += c
  23671. }
  23672. continue
  23673. case S.CDATA_ENDING:
  23674. if (c === ']') {
  23675. parser.state = S.CDATA_ENDING_2
  23676. } else {
  23677. parser.cdata += ']' + c
  23678. parser.state = S.CDATA
  23679. }
  23680. continue
  23681. case S.CDATA_ENDING_2:
  23682. if (c === '>') {
  23683. if (parser.cdata) {
  23684. emitNode(parser, 'oncdata', parser.cdata)
  23685. }
  23686. emitNode(parser, 'onclosecdata')
  23687. parser.cdata = ''
  23688. parser.state = S.TEXT
  23689. } else if (c === ']') {
  23690. parser.cdata += ']'
  23691. } else {
  23692. parser.cdata += ']]' + c
  23693. parser.state = S.CDATA
  23694. }
  23695. continue
  23696. case S.PROC_INST:
  23697. if (c === '?') {
  23698. parser.state = S.PROC_INST_ENDING
  23699. } else if (is(whitespace, c)) {
  23700. parser.state = S.PROC_INST_BODY
  23701. } else {
  23702. parser.procInstName += c
  23703. }
  23704. continue
  23705. case S.PROC_INST_BODY:
  23706. if (!parser.procInstBody && is(whitespace, c)) {
  23707. continue
  23708. } else if (c === '?') {
  23709. parser.state = S.PROC_INST_ENDING
  23710. } else {
  23711. parser.procInstBody += c
  23712. }
  23713. continue
  23714. case S.PROC_INST_ENDING:
  23715. if (c === '>') {
  23716. emitNode(parser, 'onprocessinginstruction', {
  23717. name: parser.procInstName,
  23718. body: parser.procInstBody
  23719. })
  23720. parser.procInstName = parser.procInstBody = ''
  23721. parser.state = S.TEXT
  23722. } else {
  23723. parser.procInstBody += '?' + c
  23724. parser.state = S.PROC_INST_BODY
  23725. }
  23726. continue
  23727. case S.OPEN_TAG:
  23728. if (is(nameBody, c)) {
  23729. parser.tagName += c
  23730. } else {
  23731. newTag(parser)
  23732. if (c === '>') {
  23733. openTag(parser)
  23734. } else if (c === '/') {
  23735. parser.state = S.OPEN_TAG_SLASH
  23736. } else {
  23737. if (not(whitespace, c)) {
  23738. strictFail(parser, 'Invalid character in tag name')
  23739. }
  23740. parser.state = S.ATTRIB
  23741. }
  23742. }
  23743. continue
  23744. case S.OPEN_TAG_SLASH:
  23745. if (c === '>') {
  23746. openTag(parser, true)
  23747. closeTag(parser)
  23748. } else {
  23749. strictFail(parser, 'Forward-slash in opening tag not followed by >')
  23750. parser.state = S.ATTRIB
  23751. }
  23752. continue
  23753. case S.ATTRIB:
  23754. // haven't read the attribute name yet.
  23755. if (is(whitespace, c)) {
  23756. continue
  23757. } else if (c === '>') {
  23758. openTag(parser)
  23759. } else if (c === '/') {
  23760. parser.state = S.OPEN_TAG_SLASH
  23761. } else if (is(nameStart, c)) {
  23762. parser.attribName = c
  23763. parser.attribValue = ''
  23764. parser.state = S.ATTRIB_NAME
  23765. } else {
  23766. strictFail(parser, 'Invalid attribute name')
  23767. }
  23768. continue
  23769. case S.ATTRIB_NAME:
  23770. if (c === '=') {
  23771. parser.state = S.ATTRIB_VALUE
  23772. } else if (c === '>') {
  23773. strictFail(parser, 'Attribute without value')
  23774. parser.attribValue = parser.attribName
  23775. attrib(parser)
  23776. openTag(parser)
  23777. } else if (is(whitespace, c)) {
  23778. parser.state = S.ATTRIB_NAME_SAW_WHITE
  23779. } else if (is(nameBody, c)) {
  23780. parser.attribName += c
  23781. } else {
  23782. strictFail(parser, 'Invalid attribute name')
  23783. }
  23784. continue
  23785. case S.ATTRIB_NAME_SAW_WHITE:
  23786. if (c === '=') {
  23787. parser.state = S.ATTRIB_VALUE
  23788. } else if (is(whitespace, c)) {
  23789. continue
  23790. } else {
  23791. strictFail(parser, 'Attribute without value')
  23792. parser.tag.attributes[parser.attribName] = ''
  23793. parser.attribValue = ''
  23794. emitNode(parser, 'onattribute', {
  23795. name: parser.attribName,
  23796. value: ''
  23797. })
  23798. parser.attribName = ''
  23799. if (c === '>') {
  23800. openTag(parser)
  23801. } else if (is(nameStart, c)) {
  23802. parser.attribName = c
  23803. parser.state = S.ATTRIB_NAME
  23804. } else {
  23805. strictFail(parser, 'Invalid attribute name')
  23806. parser.state = S.ATTRIB
  23807. }
  23808. }
  23809. continue
  23810. case S.ATTRIB_VALUE:
  23811. if (is(whitespace, c)) {
  23812. continue
  23813. } else if (is(quote, c)) {
  23814. parser.q = c
  23815. parser.state = S.ATTRIB_VALUE_QUOTED
  23816. } else {
  23817. strictFail(parser, 'Unquoted attribute value')
  23818. parser.state = S.ATTRIB_VALUE_UNQUOTED
  23819. parser.attribValue = c
  23820. }
  23821. continue
  23822. case S.ATTRIB_VALUE_QUOTED:
  23823. if (c !== parser.q) {
  23824. if (c === '&') {
  23825. parser.state = S.ATTRIB_VALUE_ENTITY_Q
  23826. } else {
  23827. parser.attribValue += c
  23828. }
  23829. continue
  23830. }
  23831. attrib(parser)
  23832. parser.q = ''
  23833. parser.state = S.ATTRIB_VALUE_CLOSED
  23834. continue
  23835. case S.ATTRIB_VALUE_CLOSED:
  23836. if (is(whitespace, c)) {
  23837. parser.state = S.ATTRIB
  23838. } else if (c === '>') {
  23839. openTag(parser)
  23840. } else if (c === '/') {
  23841. parser.state = S.OPEN_TAG_SLASH
  23842. } else if (is(nameStart, c)) {
  23843. strictFail(parser, 'No whitespace between attributes')
  23844. parser.attribName = c
  23845. parser.attribValue = ''
  23846. parser.state = S.ATTRIB_NAME
  23847. } else {
  23848. strictFail(parser, 'Invalid attribute name')
  23849. }
  23850. continue
  23851. case S.ATTRIB_VALUE_UNQUOTED:
  23852. if (not(attribEnd, c)) {
  23853. if (c === '&') {
  23854. parser.state = S.ATTRIB_VALUE_ENTITY_U
  23855. } else {
  23856. parser.attribValue += c
  23857. }
  23858. continue
  23859. }
  23860. attrib(parser)
  23861. if (c === '>') {
  23862. openTag(parser)
  23863. } else {
  23864. parser.state = S.ATTRIB
  23865. }
  23866. continue
  23867. case S.CLOSE_TAG:
  23868. if (!parser.tagName) {
  23869. if (is(whitespace, c)) {
  23870. continue
  23871. } else if (not(nameStart, c)) {
  23872. if (parser.script) {
  23873. parser.script += '</' + c
  23874. parser.state = S.SCRIPT
  23875. } else {
  23876. strictFail(parser, 'Invalid tagname in closing tag.')
  23877. }
  23878. } else {
  23879. parser.tagName = c
  23880. }
  23881. } else if (c === '>') {
  23882. closeTag(parser)
  23883. } else if (is(nameBody, c)) {
  23884. parser.tagName += c
  23885. } else if (parser.script) {
  23886. parser.script += '</' + parser.tagName
  23887. parser.tagName = ''
  23888. parser.state = S.SCRIPT
  23889. } else {
  23890. if (not(whitespace, c)) {
  23891. strictFail(parser, 'Invalid tagname in closing tag')
  23892. }
  23893. parser.state = S.CLOSE_TAG_SAW_WHITE
  23894. }
  23895. continue
  23896. case S.CLOSE_TAG_SAW_WHITE:
  23897. if (is(whitespace, c)) {
  23898. continue
  23899. }
  23900. if (c === '>') {
  23901. closeTag(parser)
  23902. } else {
  23903. strictFail(parser, 'Invalid characters in closing tag')
  23904. }
  23905. continue
  23906. case S.TEXT_ENTITY:
  23907. case S.ATTRIB_VALUE_ENTITY_Q:
  23908. case S.ATTRIB_VALUE_ENTITY_U:
  23909. var returnState
  23910. var buffer
  23911. switch (parser.state) {
  23912. case S.TEXT_ENTITY:
  23913. returnState = S.TEXT
  23914. buffer = 'textNode'
  23915. break
  23916. case S.ATTRIB_VALUE_ENTITY_Q:
  23917. returnState = S.ATTRIB_VALUE_QUOTED
  23918. buffer = 'attribValue'
  23919. break
  23920. case S.ATTRIB_VALUE_ENTITY_U:
  23921. returnState = S.ATTRIB_VALUE_UNQUOTED
  23922. buffer = 'attribValue'
  23923. break
  23924. }
  23925. if (c === ';') {
  23926. parser[buffer] += parseEntity(parser)
  23927. parser.entity = ''
  23928. parser.state = returnState
  23929. } else if (is(parser.entity.length ? entityBody : entityStart, c)) {
  23930. parser.entity += c
  23931. } else {
  23932. strictFail(parser, 'Invalid character in entity name')
  23933. parser[buffer] += '&' + parser.entity + c
  23934. parser.entity = ''
  23935. parser.state = returnState
  23936. }
  23937. continue
  23938. default:
  23939. throw new Error(parser, 'Unknown state: ' + parser.state)
  23940. }
  23941. } // while
  23942. if (parser.position >= parser.bufferCheckPosition) {
  23943. checkBufferLength(parser)
  23944. }
  23945. return parser
  23946. }
  23947. /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
  23948. if (!String.fromCodePoint) {
  23949. (function () {
  23950. var stringFromCharCode = String.fromCharCode
  23951. var floor = Math.floor
  23952. var fromCodePoint = function () {
  23953. var MAX_SIZE = 0x4000
  23954. var codeUnits = []
  23955. var highSurrogate
  23956. var lowSurrogate
  23957. var index = -1
  23958. var length = arguments.length
  23959. if (!length) {
  23960. return ''
  23961. }
  23962. var result = ''
  23963. while (++index < length) {
  23964. var codePoint = Number(arguments[index])
  23965. if (
  23966. !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
  23967. codePoint < 0 || // not a valid Unicode code point
  23968. codePoint > 0x10FFFF || // not a valid Unicode code point
  23969. floor(codePoint) !== codePoint // not an integer
  23970. ) {
  23971. throw RangeError('Invalid code point: ' + codePoint)
  23972. }
  23973. if (codePoint <= 0xFFFF) { // BMP code point
  23974. codeUnits.push(codePoint)
  23975. } else { // Astral code point; split in surrogate halves
  23976. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  23977. codePoint -= 0x10000
  23978. highSurrogate = (codePoint >> 10) + 0xD800
  23979. lowSurrogate = (codePoint % 0x400) + 0xDC00
  23980. codeUnits.push(highSurrogate, lowSurrogate)
  23981. }
  23982. if (index + 1 === length || codeUnits.length > MAX_SIZE) {
  23983. result += stringFromCharCode.apply(null, codeUnits)
  23984. codeUnits.length = 0
  23985. }
  23986. }
  23987. return result
  23988. }
  23989. if (Object.defineProperty) {
  23990. Object.defineProperty(String, 'fromCodePoint', {
  23991. value: fromCodePoint,
  23992. configurable: true,
  23993. writable: true
  23994. })
  23995. } else {
  23996. String.fromCodePoint = fromCodePoint
  23997. }
  23998. }())
  23999. }
  24000. })(typeof exports === 'undefined' ? this.sax = {} : exports)
  24001. }).call(this,require("buffer").Buffer)
  24002. },{"buffer":77,"stream":151,"string_decoder":152}],151:[function(require,module,exports){
  24003. // Copyright Joyent, Inc. and other Node contributors.
  24004. //
  24005. // Permission is hereby granted, free of charge, to any person obtaining a
  24006. // copy of this software and associated documentation files (the
  24007. // "Software"), to deal in the Software without restriction, including
  24008. // without limitation the rights to use, copy, modify, merge, publish,
  24009. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24010. // persons to whom the Software is furnished to do so, subject to the
  24011. // following conditions:
  24012. //
  24013. // The above copyright notice and this permission notice shall be included
  24014. // in all copies or substantial portions of the Software.
  24015. //
  24016. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24017. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24018. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24019. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24020. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24021. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24022. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24023. module.exports = Stream;
  24024. var EE = require('events').EventEmitter;
  24025. var inherits = require('inherits');
  24026. inherits(Stream, EE);
  24027. Stream.Readable = require('readable-stream/readable.js');
  24028. Stream.Writable = require('readable-stream/writable.js');
  24029. Stream.Duplex = require('readable-stream/duplex.js');
  24030. Stream.Transform = require('readable-stream/transform.js');
  24031. Stream.PassThrough = require('readable-stream/passthrough.js');
  24032. // Backwards-compat with node 0.4.x
  24033. Stream.Stream = Stream;
  24034. // old-style streams. Note that the pipe method (the only relevant
  24035. // part of this class) is overridden in the Readable class.
  24036. function Stream() {
  24037. EE.call(this);
  24038. }
  24039. Stream.prototype.pipe = function(dest, options) {
  24040. var source = this;
  24041. function ondata(chunk) {
  24042. if (dest.writable) {
  24043. if (false === dest.write(chunk) && source.pause) {
  24044. source.pause();
  24045. }
  24046. }
  24047. }
  24048. source.on('data', ondata);
  24049. function ondrain() {
  24050. if (source.readable && source.resume) {
  24051. source.resume();
  24052. }
  24053. }
  24054. dest.on('drain', ondrain);
  24055. // If the 'end' option is not supplied, dest.end() will be called when
  24056. // source gets the 'end' or 'close' events. Only dest.end() once.
  24057. if (!dest._isStdio && (!options || options.end !== false)) {
  24058. source.on('end', onend);
  24059. source.on('close', onclose);
  24060. }
  24061. var didOnEnd = false;
  24062. function onend() {
  24063. if (didOnEnd) return;
  24064. didOnEnd = true;
  24065. dest.end();
  24066. }
  24067. function onclose() {
  24068. if (didOnEnd) return;
  24069. didOnEnd = true;
  24070. if (typeof dest.destroy === 'function') dest.destroy();
  24071. }
  24072. // don't leave dangling pipes when there are errors.
  24073. function onerror(er) {
  24074. cleanup();
  24075. if (EE.listenerCount(this, 'error') === 0) {
  24076. throw er; // Unhandled stream error in pipe.
  24077. }
  24078. }
  24079. source.on('error', onerror);
  24080. dest.on('error', onerror);
  24081. // remove all the event listeners that were added.
  24082. function cleanup() {
  24083. source.removeListener('data', ondata);
  24084. dest.removeListener('drain', ondrain);
  24085. source.removeListener('end', onend);
  24086. source.removeListener('close', onclose);
  24087. source.removeListener('error', onerror);
  24088. dest.removeListener('error', onerror);
  24089. source.removeListener('end', cleanup);
  24090. source.removeListener('close', cleanup);
  24091. dest.removeListener('close', cleanup);
  24092. }
  24093. source.on('end', cleanup);
  24094. source.on('close', cleanup);
  24095. dest.on('close', cleanup);
  24096. dest.emit('pipe', source);
  24097. // Allow for unix-like usage: A.pipe(B).pipe(C)
  24098. return dest;
  24099. };
  24100. },{"events":79,"inherits":81,"readable-stream/duplex.js":139,"readable-stream/passthrough.js":146,"readable-stream/readable.js":147,"readable-stream/transform.js":148,"readable-stream/writable.js":149}],152:[function(require,module,exports){
  24101. // Copyright Joyent, Inc. and other Node contributors.
  24102. //
  24103. // Permission is hereby granted, free of charge, to any person obtaining a
  24104. // copy of this software and associated documentation files (the
  24105. // "Software"), to deal in the Software without restriction, including
  24106. // without limitation the rights to use, copy, modify, merge, publish,
  24107. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24108. // persons to whom the Software is furnished to do so, subject to the
  24109. // following conditions:
  24110. //
  24111. // The above copyright notice and this permission notice shall be included
  24112. // in all copies or substantial portions of the Software.
  24113. //
  24114. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  24115. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24116. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  24117. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  24118. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  24119. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  24120. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  24121. var Buffer = require('buffer').Buffer;
  24122. var isBufferEncoding = Buffer.isEncoding
  24123. || function(encoding) {
  24124. switch (encoding && encoding.toLowerCase()) {
  24125. 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': return true;
  24126. default: return false;
  24127. }
  24128. }
  24129. function assertEncoding(encoding) {
  24130. if (encoding && !isBufferEncoding(encoding)) {
  24131. throw new Error('Unknown encoding: ' + encoding);
  24132. }
  24133. }
  24134. // StringDecoder provides an interface for efficiently splitting a series of
  24135. // buffers into a series of JS strings without breaking apart multi-byte
  24136. // characters. CESU-8 is handled as part of the UTF-8 encoding.
  24137. //
  24138. // @TODO Handling all encodings inside a single object makes it very difficult
  24139. // to reason about this code, so it should be split up in the future.
  24140. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
  24141. // points as used by CESU-8.
  24142. var StringDecoder = exports.StringDecoder = function(encoding) {
  24143. this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  24144. assertEncoding(encoding);
  24145. switch (this.encoding) {
  24146. case 'utf8':
  24147. // CESU-8 represents each of Surrogate Pair by 3-bytes
  24148. this.surrogateSize = 3;
  24149. break;
  24150. case 'ucs2':
  24151. case 'utf16le':
  24152. // UTF-16 represents each of Surrogate Pair by 2-bytes
  24153. this.surrogateSize = 2;
  24154. this.detectIncompleteChar = utf16DetectIncompleteChar;
  24155. break;
  24156. case 'base64':
  24157. // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
  24158. this.surrogateSize = 3;
  24159. this.detectIncompleteChar = base64DetectIncompleteChar;
  24160. break;
  24161. default:
  24162. this.write = passThroughWrite;
  24163. return;
  24164. }
  24165. // Enough space to store all bytes of a single character. UTF-8 needs 4
  24166. // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
  24167. this.charBuffer = new Buffer(6);
  24168. // Number of bytes received for the current incomplete multi-byte character.
  24169. this.charReceived = 0;
  24170. // Number of bytes expected for the current incomplete multi-byte character.
  24171. this.charLength = 0;
  24172. };
  24173. // write decodes the given buffer and returns it as JS string that is
  24174. // guaranteed to not contain any partial multi-byte characters. Any partial
  24175. // character found at the end of the buffer is buffered up, and will be
  24176. // returned when calling write again with the remaining bytes.
  24177. //
  24178. // Note: Converting a Buffer containing an orphan surrogate to a String
  24179. // currently works, but converting a String to a Buffer (via `new Buffer`, or
  24180. // Buffer#write) will replace incomplete surrogates with the unicode
  24181. // replacement character. See https://codereview.chromium.org/121173009/ .
  24182. StringDecoder.prototype.write = function(buffer) {
  24183. var charStr = '';
  24184. // if our last write ended with an incomplete multibyte character
  24185. while (this.charLength) {
  24186. // determine how many remaining bytes this buffer has to offer for this char
  24187. var available = (buffer.length >= this.charLength - this.charReceived) ?
  24188. this.charLength - this.charReceived :
  24189. buffer.length;
  24190. // add the new bytes to the char buffer
  24191. buffer.copy(this.charBuffer, this.charReceived, 0, available);
  24192. this.charReceived += available;
  24193. if (this.charReceived < this.charLength) {
  24194. // still not enough chars in this buffer? wait for more ...
  24195. return '';
  24196. }
  24197. // remove bytes belonging to the current character from the buffer
  24198. buffer = buffer.slice(available, buffer.length);
  24199. // get the character that was split
  24200. charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  24201. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  24202. var charCode = charStr.charCodeAt(charStr.length - 1);
  24203. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  24204. this.charLength += this.surrogateSize;
  24205. charStr = '';
  24206. continue;
  24207. }
  24208. this.charReceived = this.charLength = 0;
  24209. // if there are no more bytes in this buffer, just emit our char
  24210. if (buffer.length === 0) {
  24211. return charStr;
  24212. }
  24213. break;
  24214. }
  24215. // determine and set charLength / charReceived
  24216. this.detectIncompleteChar(buffer);
  24217. var end = buffer.length;
  24218. if (this.charLength) {
  24219. // buffer the incomplete character bytes we got
  24220. buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
  24221. end -= this.charReceived;
  24222. }
  24223. charStr += buffer.toString(this.encoding, 0, end);
  24224. var end = charStr.length - 1;
  24225. var charCode = charStr.charCodeAt(end);
  24226. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  24227. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  24228. var size = this.surrogateSize;
  24229. this.charLength += size;
  24230. this.charReceived += size;
  24231. this.charBuffer.copy(this.charBuffer, size, 0, size);
  24232. buffer.copy(this.charBuffer, 0, 0, size);
  24233. return charStr.substring(0, end);
  24234. }
  24235. // or just emit the charStr
  24236. return charStr;
  24237. };
  24238. // detectIncompleteChar determines if there is an incomplete UTF-8 character at
  24239. // the end of the given buffer. If so, it sets this.charLength to the byte
  24240. // length that character, and sets this.charReceived to the number of bytes
  24241. // that are available for this character.
  24242. StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  24243. // determine how many bytes we have to check at the end of this buffer
  24244. var i = (buffer.length >= 3) ? 3 : buffer.length;
  24245. // Figure out if one of the last i bytes of our buffer announces an
  24246. // incomplete char.
  24247. for (; i > 0; i--) {
  24248. var c = buffer[buffer.length - i];
  24249. // See http://en.wikipedia.org/wiki/UTF-8#Description
  24250. // 110XXXXX
  24251. if (i == 1 && c >> 5 == 0x06) {
  24252. this.charLength = 2;
  24253. break;
  24254. }
  24255. // 1110XXXX
  24256. if (i <= 2 && c >> 4 == 0x0E) {
  24257. this.charLength = 3;
  24258. break;
  24259. }
  24260. // 11110XXX
  24261. if (i <= 3 && c >> 3 == 0x1E) {
  24262. this.charLength = 4;
  24263. break;
  24264. }
  24265. }
  24266. this.charReceived = i;
  24267. };
  24268. StringDecoder.prototype.end = function(buffer) {
  24269. var res = '';
  24270. if (buffer && buffer.length)
  24271. res = this.write(buffer);
  24272. if (this.charReceived) {
  24273. var cr = this.charReceived;
  24274. var buf = this.charBuffer;
  24275. var enc = this.encoding;
  24276. res += buf.slice(0, cr).toString(enc);
  24277. }
  24278. return res;
  24279. };
  24280. function passThroughWrite(buffer) {
  24281. return buffer.toString(this.encoding);
  24282. }
  24283. function utf16DetectIncompleteChar(buffer) {
  24284. this.charReceived = buffer.length % 2;
  24285. this.charLength = this.charReceived ? 2 : 0;
  24286. }
  24287. function base64DetectIncompleteChar(buffer) {
  24288. this.charReceived = buffer.length % 3;
  24289. this.charLength = this.charReceived ? 3 : 0;
  24290. }
  24291. },{"buffer":77}],153:[function(require,module,exports){
  24292. // Underscore.js 1.8.3
  24293. // http://underscorejs.org
  24294. // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  24295. // Underscore may be freely distributed under the MIT license.
  24296. (function() {
  24297. // Baseline setup
  24298. // --------------
  24299. // Establish the root object, `window` in the browser, or `exports` on the server.
  24300. var root = this;
  24301. // Save the previous value of the `_` variable.
  24302. var previousUnderscore = root._;
  24303. // Save bytes in the minified (but not gzipped) version:
  24304. var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
  24305. // Create quick reference variables for speed access to core prototypes.
  24306. var
  24307. push = ArrayProto.push,
  24308. slice = ArrayProto.slice,
  24309. toString = ObjProto.toString,
  24310. hasOwnProperty = ObjProto.hasOwnProperty;
  24311. // All **ECMAScript 5** native function implementations that we hope to use
  24312. // are declared here.
  24313. var
  24314. nativeIsArray = Array.isArray,
  24315. nativeKeys = Object.keys,
  24316. nativeBind = FuncProto.bind,
  24317. nativeCreate = Object.create;
  24318. // Naked function reference for surrogate-prototype-swapping.
  24319. var Ctor = function(){};
  24320. // Create a safe reference to the Underscore object for use below.
  24321. var _ = function(obj) {
  24322. if (obj instanceof _) return obj;
  24323. if (!(this instanceof _)) return new _(obj);
  24324. this._wrapped = obj;
  24325. };
  24326. // Export the Underscore object for **Node.js**, with
  24327. // backwards-compatibility for the old `require()` API. If we're in
  24328. // the browser, add `_` as a global object.
  24329. if (typeof exports !== 'undefined') {
  24330. if (typeof module !== 'undefined' && module.exports) {
  24331. exports = module.exports = _;
  24332. }
  24333. exports._ = _;
  24334. } else {
  24335. root._ = _;
  24336. }
  24337. // Current version.
  24338. _.VERSION = '1.8.3';
  24339. // Internal function that returns an efficient (for current engines) version
  24340. // of the passed-in callback, to be repeatedly applied in other Underscore
  24341. // functions.
  24342. var optimizeCb = function(func, context, argCount) {
  24343. if (context === void 0) return func;
  24344. switch (argCount == null ? 3 : argCount) {
  24345. case 1: return function(value) {
  24346. return func.call(context, value);
  24347. };
  24348. case 2: return function(value, other) {
  24349. return func.call(context, value, other);
  24350. };
  24351. case 3: return function(value, index, collection) {
  24352. return func.call(context, value, index, collection);
  24353. };
  24354. case 4: return function(accumulator, value, index, collection) {
  24355. return func.call(context, accumulator, value, index, collection);
  24356. };
  24357. }
  24358. return function() {
  24359. return func.apply(context, arguments);
  24360. };
  24361. };
  24362. // A mostly-internal function to generate callbacks that can be applied
  24363. // to each element in a collection, returning the desired result — either
  24364. // identity, an arbitrary callback, a property matcher, or a property accessor.
  24365. var cb = function(value, context, argCount) {
  24366. if (value == null) return _.identity;
  24367. if (_.isFunction(value)) return optimizeCb(value, context, argCount);
  24368. if (_.isObject(value)) return _.matcher(value);
  24369. return _.property(value);
  24370. };
  24371. _.iteratee = function(value, context) {
  24372. return cb(value, context, Infinity);
  24373. };
  24374. // An internal function for creating assigner functions.
  24375. var createAssigner = function(keysFunc, undefinedOnly) {
  24376. return function(obj) {
  24377. var length = arguments.length;
  24378. if (length < 2 || obj == null) return obj;
  24379. for (var index = 1; index < length; index++) {
  24380. var source = arguments[index],
  24381. keys = keysFunc(source),
  24382. l = keys.length;
  24383. for (var i = 0; i < l; i++) {
  24384. var key = keys[i];
  24385. if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
  24386. }
  24387. }
  24388. return obj;
  24389. };
  24390. };
  24391. // An internal function for creating a new object that inherits from another.
  24392. var baseCreate = function(prototype) {
  24393. if (!_.isObject(prototype)) return {};
  24394. if (nativeCreate) return nativeCreate(prototype);
  24395. Ctor.prototype = prototype;
  24396. var result = new Ctor;
  24397. Ctor.prototype = null;
  24398. return result;
  24399. };
  24400. var property = function(key) {
  24401. return function(obj) {
  24402. return obj == null ? void 0 : obj[key];
  24403. };
  24404. };
  24405. // Helper for collection methods to determine whether a collection
  24406. // should be iterated as an array or as an object
  24407. // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  24408. // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  24409. var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  24410. var getLength = property('length');
  24411. var isArrayLike = function(collection) {
  24412. var length = getLength(collection);
  24413. return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  24414. };
  24415. // Collection Functions
  24416. // --------------------
  24417. // The cornerstone, an `each` implementation, aka `forEach`.
  24418. // Handles raw objects in addition to array-likes. Treats all
  24419. // sparse array-likes as if they were dense.
  24420. _.each = _.forEach = function(obj, iteratee, context) {
  24421. iteratee = optimizeCb(iteratee, context);
  24422. var i, length;
  24423. if (isArrayLike(obj)) {
  24424. for (i = 0, length = obj.length; i < length; i++) {
  24425. iteratee(obj[i], i, obj);
  24426. }
  24427. } else {
  24428. var keys = _.keys(obj);
  24429. for (i = 0, length = keys.length; i < length; i++) {
  24430. iteratee(obj[keys[i]], keys[i], obj);
  24431. }
  24432. }
  24433. return obj;
  24434. };
  24435. // Return the results of applying the iteratee to each element.
  24436. _.map = _.collect = function(obj, iteratee, context) {
  24437. iteratee = cb(iteratee, context);
  24438. var keys = !isArrayLike(obj) && _.keys(obj),
  24439. length = (keys || obj).length,
  24440. results = Array(length);
  24441. for (var index = 0; index < length; index++) {
  24442. var currentKey = keys ? keys[index] : index;
  24443. results[index] = iteratee(obj[currentKey], currentKey, obj);
  24444. }
  24445. return results;
  24446. };
  24447. // Create a reducing function iterating left or right.
  24448. function createReduce(dir) {
  24449. // Optimized iterator function as using arguments.length
  24450. // in the main function will deoptimize the, see #1991.
  24451. function iterator(obj, iteratee, memo, keys, index, length) {
  24452. for (; index >= 0 && index < length; index += dir) {
  24453. var currentKey = keys ? keys[index] : index;
  24454. memo = iteratee(memo, obj[currentKey], currentKey, obj);
  24455. }
  24456. return memo;
  24457. }
  24458. return function(obj, iteratee, memo, context) {
  24459. iteratee = optimizeCb(iteratee, context, 4);
  24460. var keys = !isArrayLike(obj) && _.keys(obj),
  24461. length = (keys || obj).length,
  24462. index = dir > 0 ? 0 : length - 1;
  24463. // Determine the initial value if none is provided.
  24464. if (arguments.length < 3) {
  24465. memo = obj[keys ? keys[index] : index];
  24466. index += dir;
  24467. }
  24468. return iterator(obj, iteratee, memo, keys, index, length);
  24469. };
  24470. }
  24471. // **Reduce** builds up a single result from a list of values, aka `inject`,
  24472. // or `foldl`.
  24473. _.reduce = _.foldl = _.inject = createReduce(1);
  24474. // The right-associative version of reduce, also known as `foldr`.
  24475. _.reduceRight = _.foldr = createReduce(-1);
  24476. // Return the first value which passes a truth test. Aliased as `detect`.
  24477. _.find = _.detect = function(obj, predicate, context) {
  24478. var key;
  24479. if (isArrayLike(obj)) {
  24480. key = _.findIndex(obj, predicate, context);
  24481. } else {
  24482. key = _.findKey(obj, predicate, context);
  24483. }
  24484. if (key !== void 0 && key !== -1) return obj[key];
  24485. };
  24486. // Return all the elements that pass a truth test.
  24487. // Aliased as `select`.
  24488. _.filter = _.select = function(obj, predicate, context) {
  24489. var results = [];
  24490. predicate = cb(predicate, context);
  24491. _.each(obj, function(value, index, list) {
  24492. if (predicate(value, index, list)) results.push(value);
  24493. });
  24494. return results;
  24495. };
  24496. // Return all the elements for which a truth test fails.
  24497. _.reject = function(obj, predicate, context) {
  24498. return _.filter(obj, _.negate(cb(predicate)), context);
  24499. };
  24500. // Determine whether all of the elements match a truth test.
  24501. // Aliased as `all`.
  24502. _.every = _.all = function(obj, predicate, context) {
  24503. predicate = cb(predicate, context);
  24504. var keys = !isArrayLike(obj) && _.keys(obj),
  24505. length = (keys || obj).length;
  24506. for (var index = 0; index < length; index++) {
  24507. var currentKey = keys ? keys[index] : index;
  24508. if (!predicate(obj[currentKey], currentKey, obj)) return false;
  24509. }
  24510. return true;
  24511. };
  24512. // Determine if at least one element in the object matches a truth test.
  24513. // Aliased as `any`.
  24514. _.some = _.any = function(obj, predicate, context) {
  24515. predicate = cb(predicate, context);
  24516. var keys = !isArrayLike(obj) && _.keys(obj),
  24517. length = (keys || obj).length;
  24518. for (var index = 0; index < length; index++) {
  24519. var currentKey = keys ? keys[index] : index;
  24520. if (predicate(obj[currentKey], currentKey, obj)) return true;
  24521. }
  24522. return false;
  24523. };
  24524. // Determine if the array or object contains a given item (using `===`).
  24525. // Aliased as `includes` and `include`.
  24526. _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
  24527. if (!isArrayLike(obj)) obj = _.values(obj);
  24528. if (typeof fromIndex != 'number' || guard) fromIndex = 0;
  24529. return _.indexOf(obj, item, fromIndex) >= 0;
  24530. };
  24531. // Invoke a method (with arguments) on every item in a collection.
  24532. _.invoke = function(obj, method) {
  24533. var args = slice.call(arguments, 2);
  24534. var isFunc = _.isFunction(method);
  24535. return _.map(obj, function(value) {
  24536. var func = isFunc ? method : value[method];
  24537. return func == null ? func : func.apply(value, args);
  24538. });
  24539. };
  24540. // Convenience version of a common use case of `map`: fetching a property.
  24541. _.pluck = function(obj, key) {
  24542. return _.map(obj, _.property(key));
  24543. };
  24544. // Convenience version of a common use case of `filter`: selecting only objects
  24545. // containing specific `key:value` pairs.
  24546. _.where = function(obj, attrs) {
  24547. return _.filter(obj, _.matcher(attrs));
  24548. };
  24549. // Convenience version of a common use case of `find`: getting the first object
  24550. // containing specific `key:value` pairs.
  24551. _.findWhere = function(obj, attrs) {
  24552. return _.find(obj, _.matcher(attrs));
  24553. };
  24554. // Return the maximum element (or element-based computation).
  24555. _.max = function(obj, iteratee, context) {
  24556. var result = -Infinity, lastComputed = -Infinity,
  24557. value, computed;
  24558. if (iteratee == null && obj != null) {
  24559. obj = isArrayLike(obj) ? obj : _.values(obj);
  24560. for (var i = 0, length = obj.length; i < length; i++) {
  24561. value = obj[i];
  24562. if (value > result) {
  24563. result = value;
  24564. }
  24565. }
  24566. } else {
  24567. iteratee = cb(iteratee, context);
  24568. _.each(obj, function(value, index, list) {
  24569. computed = iteratee(value, index, list);
  24570. if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
  24571. result = value;
  24572. lastComputed = computed;
  24573. }
  24574. });
  24575. }
  24576. return result;
  24577. };
  24578. // Return the minimum element (or element-based computation).
  24579. _.min = function(obj, iteratee, context) {
  24580. var result = Infinity, lastComputed = Infinity,
  24581. value, computed;
  24582. if (iteratee == null && obj != null) {
  24583. obj = isArrayLike(obj) ? obj : _.values(obj);
  24584. for (var i = 0, length = obj.length; i < length; i++) {
  24585. value = obj[i];
  24586. if (value < result) {
  24587. result = value;
  24588. }
  24589. }
  24590. } else {
  24591. iteratee = cb(iteratee, context);
  24592. _.each(obj, function(value, index, list) {
  24593. computed = iteratee(value, index, list);
  24594. if (computed < lastComputed || computed === Infinity && result === Infinity) {
  24595. result = value;
  24596. lastComputed = computed;
  24597. }
  24598. });
  24599. }
  24600. return result;
  24601. };
  24602. // Shuffle a collection, using the modern version of the
  24603. // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  24604. _.shuffle = function(obj) {
  24605. var set = isArrayLike(obj) ? obj : _.values(obj);
  24606. var length = set.length;
  24607. var shuffled = Array(length);
  24608. for (var index = 0, rand; index < length; index++) {
  24609. rand = _.random(0, index);
  24610. if (rand !== index) shuffled[index] = shuffled[rand];
  24611. shuffled[rand] = set[index];
  24612. }
  24613. return shuffled;
  24614. };
  24615. // Sample **n** random values from a collection.
  24616. // If **n** is not specified, returns a single random element.
  24617. // The internal `guard` argument allows it to work with `map`.
  24618. _.sample = function(obj, n, guard) {
  24619. if (n == null || guard) {
  24620. if (!isArrayLike(obj)) obj = _.values(obj);
  24621. return obj[_.random(obj.length - 1)];
  24622. }
  24623. return _.shuffle(obj).slice(0, Math.max(0, n));
  24624. };
  24625. // Sort the object's values by a criterion produced by an iteratee.
  24626. _.sortBy = function(obj, iteratee, context) {
  24627. iteratee = cb(iteratee, context);
  24628. return _.pluck(_.map(obj, function(value, index, list) {
  24629. return {
  24630. value: value,
  24631. index: index,
  24632. criteria: iteratee(value, index, list)
  24633. };
  24634. }).sort(function(left, right) {
  24635. var a = left.criteria;
  24636. var b = right.criteria;
  24637. if (a !== b) {
  24638. if (a > b || a === void 0) return 1;
  24639. if (a < b || b === void 0) return -1;
  24640. }
  24641. return left.index - right.index;
  24642. }), 'value');
  24643. };
  24644. // An internal function used for aggregate "group by" operations.
  24645. var group = function(behavior) {
  24646. return function(obj, iteratee, context) {
  24647. var result = {};
  24648. iteratee = cb(iteratee, context);
  24649. _.each(obj, function(value, index) {
  24650. var key = iteratee(value, index, obj);
  24651. behavior(result, value, key);
  24652. });
  24653. return result;
  24654. };
  24655. };
  24656. // Groups the object's values by a criterion. Pass either a string attribute
  24657. // to group by, or a function that returns the criterion.
  24658. _.groupBy = group(function(result, value, key) {
  24659. if (_.has(result, key)) result[key].push(value); else result[key] = [value];
  24660. });
  24661. // Indexes the object's values by a criterion, similar to `groupBy`, but for
  24662. // when you know that your index values will be unique.
  24663. _.indexBy = group(function(result, value, key) {
  24664. result[key] = value;
  24665. });
  24666. // Counts instances of an object that group by a certain criterion. Pass
  24667. // either a string attribute to count by, or a function that returns the
  24668. // criterion.
  24669. _.countBy = group(function(result, value, key) {
  24670. if (_.has(result, key)) result[key]++; else result[key] = 1;
  24671. });
  24672. // Safely create a real, live array from anything iterable.
  24673. _.toArray = function(obj) {
  24674. if (!obj) return [];
  24675. if (_.isArray(obj)) return slice.call(obj);
  24676. if (isArrayLike(obj)) return _.map(obj, _.identity);
  24677. return _.values(obj);
  24678. };
  24679. // Return the number of elements in an object.
  24680. _.size = function(obj) {
  24681. if (obj == null) return 0;
  24682. return isArrayLike(obj) ? obj.length : _.keys(obj).length;
  24683. };
  24684. // Split a collection into two arrays: one whose elements all satisfy the given
  24685. // predicate, and one whose elements all do not satisfy the predicate.
  24686. _.partition = function(obj, predicate, context) {
  24687. predicate = cb(predicate, context);
  24688. var pass = [], fail = [];
  24689. _.each(obj, function(value, key, obj) {
  24690. (predicate(value, key, obj) ? pass : fail).push(value);
  24691. });
  24692. return [pass, fail];
  24693. };
  24694. // Array Functions
  24695. // ---------------
  24696. // Get the first element of an array. Passing **n** will return the first N
  24697. // values in the array. Aliased as `head` and `take`. The **guard** check
  24698. // allows it to work with `_.map`.
  24699. _.first = _.head = _.take = function(array, n, guard) {
  24700. if (array == null) return void 0;
  24701. if (n == null || guard) return array[0];
  24702. return _.initial(array, array.length - n);
  24703. };
  24704. // Returns everything but the last entry of the array. Especially useful on
  24705. // the arguments object. Passing **n** will return all the values in
  24706. // the array, excluding the last N.
  24707. _.initial = function(array, n, guard) {
  24708. return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  24709. };
  24710. // Get the last element of an array. Passing **n** will return the last N
  24711. // values in the array.
  24712. _.last = function(array, n, guard) {
  24713. if (array == null) return void 0;
  24714. if (n == null || guard) return array[array.length - 1];
  24715. return _.rest(array, Math.max(0, array.length - n));
  24716. };
  24717. // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  24718. // Especially useful on the arguments object. Passing an **n** will return
  24719. // the rest N values in the array.
  24720. _.rest = _.tail = _.drop = function(array, n, guard) {
  24721. return slice.call(array, n == null || guard ? 1 : n);
  24722. };
  24723. // Trim out all falsy values from an array.
  24724. _.compact = function(array) {
  24725. return _.filter(array, _.identity);
  24726. };
  24727. // Internal implementation of a recursive `flatten` function.
  24728. var flatten = function(input, shallow, strict, startIndex) {
  24729. var output = [], idx = 0;
  24730. for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
  24731. var value = input[i];
  24732. if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
  24733. //flatten current level of array or arguments object
  24734. if (!shallow) value = flatten(value, shallow, strict);
  24735. var j = 0, len = value.length;
  24736. output.length += len;
  24737. while (j < len) {
  24738. output[idx++] = value[j++];
  24739. }
  24740. } else if (!strict) {
  24741. output[idx++] = value;
  24742. }
  24743. }
  24744. return output;
  24745. };
  24746. // Flatten out an array, either recursively (by default), or just one level.
  24747. _.flatten = function(array, shallow) {
  24748. return flatten(array, shallow, false);
  24749. };
  24750. // Return a version of the array that does not contain the specified value(s).
  24751. _.without = function(array) {
  24752. return _.difference(array, slice.call(arguments, 1));
  24753. };
  24754. // Produce a duplicate-free version of the array. If the array has already
  24755. // been sorted, you have the option of using a faster algorithm.
  24756. // Aliased as `unique`.
  24757. _.uniq = _.unique = function(array, isSorted, iteratee, context) {
  24758. if (!_.isBoolean(isSorted)) {
  24759. context = iteratee;
  24760. iteratee = isSorted;
  24761. isSorted = false;
  24762. }
  24763. if (iteratee != null) iteratee = cb(iteratee, context);
  24764. var result = [];
  24765. var seen = [];
  24766. for (var i = 0, length = getLength(array); i < length; i++) {
  24767. var value = array[i],
  24768. computed = iteratee ? iteratee(value, i, array) : value;
  24769. if (isSorted) {
  24770. if (!i || seen !== computed) result.push(value);
  24771. seen = computed;
  24772. } else if (iteratee) {
  24773. if (!_.contains(seen, computed)) {
  24774. seen.push(computed);
  24775. result.push(value);
  24776. }
  24777. } else if (!_.contains(result, value)) {
  24778. result.push(value);
  24779. }
  24780. }
  24781. return result;
  24782. };
  24783. // Produce an array that contains the union: each distinct element from all of
  24784. // the passed-in arrays.
  24785. _.union = function() {
  24786. return _.uniq(flatten(arguments, true, true));
  24787. };
  24788. // Produce an array that contains every item shared between all the
  24789. // passed-in arrays.
  24790. _.intersection = function(array) {
  24791. var result = [];
  24792. var argsLength = arguments.length;
  24793. for (var i = 0, length = getLength(array); i < length; i++) {
  24794. var item = array[i];
  24795. if (_.contains(result, item)) continue;
  24796. for (var j = 1; j < argsLength; j++) {
  24797. if (!_.contains(arguments[j], item)) break;
  24798. }
  24799. if (j === argsLength) result.push(item);
  24800. }
  24801. return result;
  24802. };
  24803. // Take the difference between one array and a number of other arrays.
  24804. // Only the elements present in just the first array will remain.
  24805. _.difference = function(array) {
  24806. var rest = flatten(arguments, true, true, 1);
  24807. return _.filter(array, function(value){
  24808. return !_.contains(rest, value);
  24809. });
  24810. };
  24811. // Zip together multiple lists into a single array -- elements that share
  24812. // an index go together.
  24813. _.zip = function() {
  24814. return _.unzip(arguments);
  24815. };
  24816. // Complement of _.zip. Unzip accepts an array of arrays and groups
  24817. // each array's elements on shared indices
  24818. _.unzip = function(array) {
  24819. var length = array && _.max(array, getLength).length || 0;
  24820. var result = Array(length);
  24821. for (var index = 0; index < length; index++) {
  24822. result[index] = _.pluck(array, index);
  24823. }
  24824. return result;
  24825. };
  24826. // Converts lists into objects. Pass either a single array of `[key, value]`
  24827. // pairs, or two parallel arrays of the same length -- one of keys, and one of
  24828. // the corresponding values.
  24829. _.object = function(list, values) {
  24830. var result = {};
  24831. for (var i = 0, length = getLength(list); i < length; i++) {
  24832. if (values) {
  24833. result[list[i]] = values[i];
  24834. } else {
  24835. result[list[i][0]] = list[i][1];
  24836. }
  24837. }
  24838. return result;
  24839. };
  24840. // Generator function to create the findIndex and findLastIndex functions
  24841. function createPredicateIndexFinder(dir) {
  24842. return function(array, predicate, context) {
  24843. predicate = cb(predicate, context);
  24844. var length = getLength(array);
  24845. var index = dir > 0 ? 0 : length - 1;
  24846. for (; index >= 0 && index < length; index += dir) {
  24847. if (predicate(array[index], index, array)) return index;
  24848. }
  24849. return -1;
  24850. };
  24851. }
  24852. // Returns the first index on an array-like that passes a predicate test
  24853. _.findIndex = createPredicateIndexFinder(1);
  24854. _.findLastIndex = createPredicateIndexFinder(-1);
  24855. // Use a comparator function to figure out the smallest index at which
  24856. // an object should be inserted so as to maintain order. Uses binary search.
  24857. _.sortedIndex = function(array, obj, iteratee, context) {
  24858. iteratee = cb(iteratee, context, 1);
  24859. var value = iteratee(obj);
  24860. var low = 0, high = getLength(array);
  24861. while (low < high) {
  24862. var mid = Math.floor((low + high) / 2);
  24863. if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
  24864. }
  24865. return low;
  24866. };
  24867. // Generator function to create the indexOf and lastIndexOf functions
  24868. function createIndexFinder(dir, predicateFind, sortedIndex) {
  24869. return function(array, item, idx) {
  24870. var i = 0, length = getLength(array);
  24871. if (typeof idx == 'number') {
  24872. if (dir > 0) {
  24873. i = idx >= 0 ? idx : Math.max(idx + length, i);
  24874. } else {
  24875. length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
  24876. }
  24877. } else if (sortedIndex && idx && length) {
  24878. idx = sortedIndex(array, item);
  24879. return array[idx] === item ? idx : -1;
  24880. }
  24881. if (item !== item) {
  24882. idx = predicateFind(slice.call(array, i, length), _.isNaN);
  24883. return idx >= 0 ? idx + i : -1;
  24884. }
  24885. for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
  24886. if (array[idx] === item) return idx;
  24887. }
  24888. return -1;
  24889. };
  24890. }
  24891. // Return the position of the first occurrence of an item in an array,
  24892. // or -1 if the item is not included in the array.
  24893. // If the array is large and already in sort order, pass `true`
  24894. // for **isSorted** to use binary search.
  24895. _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
  24896. _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
  24897. // Generate an integer Array containing an arithmetic progression. A port of
  24898. // the native Python `range()` function. See
  24899. // [the Python documentation](http://docs.python.org/library/functions.html#range).
  24900. _.range = function(start, stop, step) {
  24901. if (stop == null) {
  24902. stop = start || 0;
  24903. start = 0;
  24904. }
  24905. step = step || 1;
  24906. var length = Math.max(Math.ceil((stop - start) / step), 0);
  24907. var range = Array(length);
  24908. for (var idx = 0; idx < length; idx++, start += step) {
  24909. range[idx] = start;
  24910. }
  24911. return range;
  24912. };
  24913. // Function (ahem) Functions
  24914. // ------------------
  24915. // Determines whether to execute a function as a constructor
  24916. // or a normal function with the provided arguments
  24917. var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
  24918. if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
  24919. var self = baseCreate(sourceFunc.prototype);
  24920. var result = sourceFunc.apply(self, args);
  24921. if (_.isObject(result)) return result;
  24922. return self;
  24923. };
  24924. // Create a function bound to a given object (assigning `this`, and arguments,
  24925. // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  24926. // available.
  24927. _.bind = function(func, context) {
  24928. if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
  24929. if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
  24930. var args = slice.call(arguments, 2);
  24931. var bound = function() {
  24932. return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
  24933. };
  24934. return bound;
  24935. };
  24936. // Partially apply a function by creating a version that has had some of its
  24937. // arguments pre-filled, without changing its dynamic `this` context. _ acts
  24938. // as a placeholder, allowing any combination of arguments to be pre-filled.
  24939. _.partial = function(func) {
  24940. var boundArgs = slice.call(arguments, 1);
  24941. var bound = function() {
  24942. var position = 0, length = boundArgs.length;
  24943. var args = Array(length);
  24944. for (var i = 0; i < length; i++) {
  24945. args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
  24946. }
  24947. while (position < arguments.length) args.push(arguments[position++]);
  24948. return executeBound(func, bound, this, this, args);
  24949. };
  24950. return bound;
  24951. };
  24952. // Bind a number of an object's methods to that object. Remaining arguments
  24953. // are the method names to be bound. Useful for ensuring that all callbacks
  24954. // defined on an object belong to it.
  24955. _.bindAll = function(obj) {
  24956. var i, length = arguments.length, key;
  24957. if (length <= 1) throw new Error('bindAll must be passed function names');
  24958. for (i = 1; i < length; i++) {
  24959. key = arguments[i];
  24960. obj[key] = _.bind(obj[key], obj);
  24961. }
  24962. return obj;
  24963. };
  24964. // Memoize an expensive function by storing its results.
  24965. _.memoize = function(func, hasher) {
  24966. var memoize = function(key) {
  24967. var cache = memoize.cache;
  24968. var address = '' + (hasher ? hasher.apply(this, arguments) : key);
  24969. if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
  24970. return cache[address];
  24971. };
  24972. memoize.cache = {};
  24973. return memoize;
  24974. };
  24975. // Delays a function for the given number of milliseconds, and then calls
  24976. // it with the arguments supplied.
  24977. _.delay = function(func, wait) {
  24978. var args = slice.call(arguments, 2);
  24979. return setTimeout(function(){
  24980. return func.apply(null, args);
  24981. }, wait);
  24982. };
  24983. // Defers a function, scheduling it to run after the current call stack has
  24984. // cleared.
  24985. _.defer = _.partial(_.delay, _, 1);
  24986. // Returns a function, that, when invoked, will only be triggered at most once
  24987. // during a given window of time. Normally, the throttled function will run
  24988. // as much as it can, without ever going more than once per `wait` duration;
  24989. // but if you'd like to disable the execution on the leading edge, pass
  24990. // `{leading: false}`. To disable execution on the trailing edge, ditto.
  24991. _.throttle = function(func, wait, options) {
  24992. var context, args, result;
  24993. var timeout = null;
  24994. var previous = 0;
  24995. if (!options) options = {};
  24996. var later = function() {
  24997. previous = options.leading === false ? 0 : _.now();
  24998. timeout = null;
  24999. result = func.apply(context, args);
  25000. if (!timeout) context = args = null;
  25001. };
  25002. return function() {
  25003. var now = _.now();
  25004. if (!previous && options.leading === false) previous = now;
  25005. var remaining = wait - (now - previous);
  25006. context = this;
  25007. args = arguments;
  25008. if (remaining <= 0 || remaining > wait) {
  25009. if (timeout) {
  25010. clearTimeout(timeout);
  25011. timeout = null;
  25012. }
  25013. previous = now;
  25014. result = func.apply(context, args);
  25015. if (!timeout) context = args = null;
  25016. } else if (!timeout && options.trailing !== false) {
  25017. timeout = setTimeout(later, remaining);
  25018. }
  25019. return result;
  25020. };
  25021. };
  25022. // Returns a function, that, as long as it continues to be invoked, will not
  25023. // be triggered. The function will be called after it stops being called for
  25024. // N milliseconds. If `immediate` is passed, trigger the function on the
  25025. // leading edge, instead of the trailing.
  25026. _.debounce = function(func, wait, immediate) {
  25027. var timeout, args, context, timestamp, result;
  25028. var later = function() {
  25029. var last = _.now() - timestamp;
  25030. if (last < wait && last >= 0) {
  25031. timeout = setTimeout(later, wait - last);
  25032. } else {
  25033. timeout = null;
  25034. if (!immediate) {
  25035. result = func.apply(context, args);
  25036. if (!timeout) context = args = null;
  25037. }
  25038. }
  25039. };
  25040. return function() {
  25041. context = this;
  25042. args = arguments;
  25043. timestamp = _.now();
  25044. var callNow = immediate && !timeout;
  25045. if (!timeout) timeout = setTimeout(later, wait);
  25046. if (callNow) {
  25047. result = func.apply(context, args);
  25048. context = args = null;
  25049. }
  25050. return result;
  25051. };
  25052. };
  25053. // Returns the first function passed as an argument to the second,
  25054. // allowing you to adjust arguments, run code before and after, and
  25055. // conditionally execute the original function.
  25056. _.wrap = function(func, wrapper) {
  25057. return _.partial(wrapper, func);
  25058. };
  25059. // Returns a negated version of the passed-in predicate.
  25060. _.negate = function(predicate) {
  25061. return function() {
  25062. return !predicate.apply(this, arguments);
  25063. };
  25064. };
  25065. // Returns a function that is the composition of a list of functions, each
  25066. // consuming the return value of the function that follows.
  25067. _.compose = function() {
  25068. var args = arguments;
  25069. var start = args.length - 1;
  25070. return function() {
  25071. var i = start;
  25072. var result = args[start].apply(this, arguments);
  25073. while (i--) result = args[i].call(this, result);
  25074. return result;
  25075. };
  25076. };
  25077. // Returns a function that will only be executed on and after the Nth call.
  25078. _.after = function(times, func) {
  25079. return function() {
  25080. if (--times < 1) {
  25081. return func.apply(this, arguments);
  25082. }
  25083. };
  25084. };
  25085. // Returns a function that will only be executed up to (but not including) the Nth call.
  25086. _.before = function(times, func) {
  25087. var memo;
  25088. return function() {
  25089. if (--times > 0) {
  25090. memo = func.apply(this, arguments);
  25091. }
  25092. if (times <= 1) func = null;
  25093. return memo;
  25094. };
  25095. };
  25096. // Returns a function that will be executed at most one time, no matter how
  25097. // often you call it. Useful for lazy initialization.
  25098. _.once = _.partial(_.before, 2);
  25099. // Object Functions
  25100. // ----------------
  25101. // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  25102. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  25103. var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
  25104. 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
  25105. function collectNonEnumProps(obj, keys) {
  25106. var nonEnumIdx = nonEnumerableProps.length;
  25107. var constructor = obj.constructor;
  25108. var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
  25109. // Constructor is a special case.
  25110. var prop = 'constructor';
  25111. if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
  25112. while (nonEnumIdx--) {
  25113. prop = nonEnumerableProps[nonEnumIdx];
  25114. if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
  25115. keys.push(prop);
  25116. }
  25117. }
  25118. }
  25119. // Retrieve the names of an object's own properties.
  25120. // Delegates to **ECMAScript 5**'s native `Object.keys`
  25121. _.keys = function(obj) {
  25122. if (!_.isObject(obj)) return [];
  25123. if (nativeKeys) return nativeKeys(obj);
  25124. var keys = [];
  25125. for (var key in obj) if (_.has(obj, key)) keys.push(key);
  25126. // Ahem, IE < 9.
  25127. if (hasEnumBug) collectNonEnumProps(obj, keys);
  25128. return keys;
  25129. };
  25130. // Retrieve all the property names of an object.
  25131. _.allKeys = function(obj) {
  25132. if (!_.isObject(obj)) return [];
  25133. var keys = [];
  25134. for (var key in obj) keys.push(key);
  25135. // Ahem, IE < 9.
  25136. if (hasEnumBug) collectNonEnumProps(obj, keys);
  25137. return keys;
  25138. };
  25139. // Retrieve the values of an object's properties.
  25140. _.values = function(obj) {
  25141. var keys = _.keys(obj);
  25142. var length = keys.length;
  25143. var values = Array(length);
  25144. for (var i = 0; i < length; i++) {
  25145. values[i] = obj[keys[i]];
  25146. }
  25147. return values;
  25148. };
  25149. // Returns the results of applying the iteratee to each element of the object
  25150. // In contrast to _.map it returns an object
  25151. _.mapObject = function(obj, iteratee, context) {
  25152. iteratee = cb(iteratee, context);
  25153. var keys = _.keys(obj),
  25154. length = keys.length,
  25155. results = {},
  25156. currentKey;
  25157. for (var index = 0; index < length; index++) {
  25158. currentKey = keys[index];
  25159. results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
  25160. }
  25161. return results;
  25162. };
  25163. // Convert an object into a list of `[key, value]` pairs.
  25164. _.pairs = function(obj) {
  25165. var keys = _.keys(obj);
  25166. var length = keys.length;
  25167. var pairs = Array(length);
  25168. for (var i = 0; i < length; i++) {
  25169. pairs[i] = [keys[i], obj[keys[i]]];
  25170. }
  25171. return pairs;
  25172. };
  25173. // Invert the keys and values of an object. The values must be serializable.
  25174. _.invert = function(obj) {
  25175. var result = {};
  25176. var keys = _.keys(obj);
  25177. for (var i = 0, length = keys.length; i < length; i++) {
  25178. result[obj[keys[i]]] = keys[i];
  25179. }
  25180. return result;
  25181. };
  25182. // Return a sorted list of the function names available on the object.
  25183. // Aliased as `methods`
  25184. _.functions = _.methods = function(obj) {
  25185. var names = [];
  25186. for (var key in obj) {
  25187. if (_.isFunction(obj[key])) names.push(key);
  25188. }
  25189. return names.sort();
  25190. };
  25191. // Extend a given object with all the properties in passed-in object(s).
  25192. _.extend = createAssigner(_.allKeys);
  25193. // Assigns a given object with all the own properties in the passed-in object(s)
  25194. // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  25195. _.extendOwn = _.assign = createAssigner(_.keys);
  25196. // Returns the first key on an object that passes a predicate test
  25197. _.findKey = function(obj, predicate, context) {
  25198. predicate = cb(predicate, context);
  25199. var keys = _.keys(obj), key;
  25200. for (var i = 0, length = keys.length; i < length; i++) {
  25201. key = keys[i];
  25202. if (predicate(obj[key], key, obj)) return key;
  25203. }
  25204. };
  25205. // Return a copy of the object only containing the whitelisted properties.
  25206. _.pick = function(object, oiteratee, context) {
  25207. var result = {}, obj = object, iteratee, keys;
  25208. if (obj == null) return result;
  25209. if (_.isFunction(oiteratee)) {
  25210. keys = _.allKeys(obj);
  25211. iteratee = optimizeCb(oiteratee, context);
  25212. } else {
  25213. keys = flatten(arguments, false, false, 1);
  25214. iteratee = function(value, key, obj) { return key in obj; };
  25215. obj = Object(obj);
  25216. }
  25217. for (var i = 0, length = keys.length; i < length; i++) {
  25218. var key = keys[i];
  25219. var value = obj[key];
  25220. if (iteratee(value, key, obj)) result[key] = value;
  25221. }
  25222. return result;
  25223. };
  25224. // Return a copy of the object without the blacklisted properties.
  25225. _.omit = function(obj, iteratee, context) {
  25226. if (_.isFunction(iteratee)) {
  25227. iteratee = _.negate(iteratee);
  25228. } else {
  25229. var keys = _.map(flatten(arguments, false, false, 1), String);
  25230. iteratee = function(value, key) {
  25231. return !_.contains(keys, key);
  25232. };
  25233. }
  25234. return _.pick(obj, iteratee, context);
  25235. };
  25236. // Fill in a given object with default properties.
  25237. _.defaults = createAssigner(_.allKeys, true);
  25238. // Creates an object that inherits from the given prototype object.
  25239. // If additional properties are provided then they will be added to the
  25240. // created object.
  25241. _.create = function(prototype, props) {
  25242. var result = baseCreate(prototype);
  25243. if (props) _.extendOwn(result, props);
  25244. return result;
  25245. };
  25246. // Create a (shallow-cloned) duplicate of an object.
  25247. _.clone = function(obj) {
  25248. if (!_.isObject(obj)) return obj;
  25249. return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  25250. };
  25251. // Invokes interceptor with the obj, and then returns obj.
  25252. // The primary purpose of this method is to "tap into" a method chain, in
  25253. // order to perform operations on intermediate results within the chain.
  25254. _.tap = function(obj, interceptor) {
  25255. interceptor(obj);
  25256. return obj;
  25257. };
  25258. // Returns whether an object has a given set of `key:value` pairs.
  25259. _.isMatch = function(object, attrs) {
  25260. var keys = _.keys(attrs), length = keys.length;
  25261. if (object == null) return !length;
  25262. var obj = Object(object);
  25263. for (var i = 0; i < length; i++) {
  25264. var key = keys[i];
  25265. if (attrs[key] !== obj[key] || !(key in obj)) return false;
  25266. }
  25267. return true;
  25268. };
  25269. // Internal recursive comparison function for `isEqual`.
  25270. var eq = function(a, b, aStack, bStack) {
  25271. // Identical objects are equal. `0 === -0`, but they aren't identical.
  25272. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
  25273. if (a === b) return a !== 0 || 1 / a === 1 / b;
  25274. // A strict comparison is necessary because `null == undefined`.
  25275. if (a == null || b == null) return a === b;
  25276. // Unwrap any wrapped objects.
  25277. if (a instanceof _) a = a._wrapped;
  25278. if (b instanceof _) b = b._wrapped;
  25279. // Compare `[[Class]]` names.
  25280. var className = toString.call(a);
  25281. if (className !== toString.call(b)) return false;
  25282. switch (className) {
  25283. // Strings, numbers, regular expressions, dates, and booleans are compared by value.
  25284. case '[object RegExp]':
  25285. // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
  25286. case '[object String]':
  25287. // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
  25288. // equivalent to `new String("5")`.
  25289. return '' + a === '' + b;
  25290. case '[object Number]':
  25291. // `NaN`s are equivalent, but non-reflexive.
  25292. // Object(NaN) is equivalent to NaN
  25293. if (+a !== +a) return +b !== +b;
  25294. // An `egal` comparison is performed for other numeric values.
  25295. return +a === 0 ? 1 / +a === 1 / b : +a === +b;
  25296. case '[object Date]':
  25297. case '[object Boolean]':
  25298. // Coerce dates and booleans to numeric primitive values. Dates are compared by their
  25299. // millisecond representations. Note that invalid dates with millisecond representations
  25300. // of `NaN` are not equivalent.
  25301. return +a === +b;
  25302. }
  25303. var areArrays = className === '[object Array]';
  25304. if (!areArrays) {
  25305. if (typeof a != 'object' || typeof b != 'object') return false;
  25306. // Objects with different constructors are not equivalent, but `Object`s or `Array`s
  25307. // from different frames are.
  25308. var aCtor = a.constructor, bCtor = b.constructor;
  25309. if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
  25310. _.isFunction(bCtor) && bCtor instanceof bCtor)
  25311. && ('constructor' in a && 'constructor' in b)) {
  25312. return false;
  25313. }
  25314. }
  25315. // Assume equality for cyclic structures. The algorithm for detecting cyclic
  25316. // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
  25317. // Initializing stack of traversed objects.
  25318. // It's done here since we only need them for objects and arrays comparison.
  25319. aStack = aStack || [];
  25320. bStack = bStack || [];
  25321. var length = aStack.length;
  25322. while (length--) {
  25323. // Linear search. Performance is inversely proportional to the number of
  25324. // unique nested structures.
  25325. if (aStack[length] === a) return bStack[length] === b;
  25326. }
  25327. // Add the first object to the stack of traversed objects.
  25328. aStack.push(a);
  25329. bStack.push(b);
  25330. // Recursively compare objects and arrays.
  25331. if (areArrays) {
  25332. // Compare array lengths to determine if a deep comparison is necessary.
  25333. length = a.length;
  25334. if (length !== b.length) return false;
  25335. // Deep compare the contents, ignoring non-numeric properties.
  25336. while (length--) {
  25337. if (!eq(a[length], b[length], aStack, bStack)) return false;
  25338. }
  25339. } else {
  25340. // Deep compare objects.
  25341. var keys = _.keys(a), key;
  25342. length = keys.length;
  25343. // Ensure that both objects contain the same number of properties before comparing deep equality.
  25344. if (_.keys(b).length !== length) return false;
  25345. while (length--) {
  25346. // Deep compare each member
  25347. key = keys[length];
  25348. if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
  25349. }
  25350. }
  25351. // Remove the first object from the stack of traversed objects.
  25352. aStack.pop();
  25353. bStack.pop();
  25354. return true;
  25355. };
  25356. // Perform a deep comparison to check if two objects are equal.
  25357. _.isEqual = function(a, b) {
  25358. return eq(a, b);
  25359. };
  25360. // Is a given array, string, or object empty?
  25361. // An "empty" object has no enumerable own-properties.
  25362. _.isEmpty = function(obj) {
  25363. if (obj == null) return true;
  25364. if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
  25365. return _.keys(obj).length === 0;
  25366. };
  25367. // Is a given value a DOM element?
  25368. _.isElement = function(obj) {
  25369. return !!(obj && obj.nodeType === 1);
  25370. };
  25371. // Is a given value an array?
  25372. // Delegates to ECMA5's native Array.isArray
  25373. _.isArray = nativeIsArray || function(obj) {
  25374. return toString.call(obj) === '[object Array]';
  25375. };
  25376. // Is a given variable an object?
  25377. _.isObject = function(obj) {
  25378. var type = typeof obj;
  25379. return type === 'function' || type === 'object' && !!obj;
  25380. };
  25381. // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
  25382. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
  25383. _['is' + name] = function(obj) {
  25384. return toString.call(obj) === '[object ' + name + ']';
  25385. };
  25386. });
  25387. // Define a fallback version of the method in browsers (ahem, IE < 9), where
  25388. // there isn't any inspectable "Arguments" type.
  25389. if (!_.isArguments(arguments)) {
  25390. _.isArguments = function(obj) {
  25391. return _.has(obj, 'callee');
  25392. };
  25393. }
  25394. // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
  25395. // IE 11 (#1621), and in Safari 8 (#1929).
  25396. if (typeof /./ != 'function' && typeof Int8Array != 'object') {
  25397. _.isFunction = function(obj) {
  25398. return typeof obj == 'function' || false;
  25399. };
  25400. }
  25401. // Is a given object a finite number?
  25402. _.isFinite = function(obj) {
  25403. return isFinite(obj) && !isNaN(parseFloat(obj));
  25404. };
  25405. // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  25406. _.isNaN = function(obj) {
  25407. return _.isNumber(obj) && obj !== +obj;
  25408. };
  25409. // Is a given value a boolean?
  25410. _.isBoolean = function(obj) {
  25411. return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  25412. };
  25413. // Is a given value equal to null?
  25414. _.isNull = function(obj) {
  25415. return obj === null;
  25416. };
  25417. // Is a given variable undefined?
  25418. _.isUndefined = function(obj) {
  25419. return obj === void 0;
  25420. };
  25421. // Shortcut function for checking if an object has a given property directly
  25422. // on itself (in other words, not on a prototype).
  25423. _.has = function(obj, key) {
  25424. return obj != null && hasOwnProperty.call(obj, key);
  25425. };
  25426. // Utility Functions
  25427. // -----------------
  25428. // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  25429. // previous owner. Returns a reference to the Underscore object.
  25430. _.noConflict = function() {
  25431. root._ = previousUnderscore;
  25432. return this;
  25433. };
  25434. // Keep the identity function around for default iteratees.
  25435. _.identity = function(value) {
  25436. return value;
  25437. };
  25438. // Predicate-generating functions. Often useful outside of Underscore.
  25439. _.constant = function(value) {
  25440. return function() {
  25441. return value;
  25442. };
  25443. };
  25444. _.noop = function(){};
  25445. _.property = property;
  25446. // Generates a function for a given object that returns a given property.
  25447. _.propertyOf = function(obj) {
  25448. return obj == null ? function(){} : function(key) {
  25449. return obj[key];
  25450. };
  25451. };
  25452. // Returns a predicate for checking whether an object has a given set of
  25453. // `key:value` pairs.
  25454. _.matcher = _.matches = function(attrs) {
  25455. attrs = _.extendOwn({}, attrs);
  25456. return function(obj) {
  25457. return _.isMatch(obj, attrs);
  25458. };
  25459. };
  25460. // Run a function **n** times.
  25461. _.times = function(n, iteratee, context) {
  25462. var accum = Array(Math.max(0, n));
  25463. iteratee = optimizeCb(iteratee, context, 1);
  25464. for (var i = 0; i < n; i++) accum[i] = iteratee(i);
  25465. return accum;
  25466. };
  25467. // Return a random integer between min and max (inclusive).
  25468. _.random = function(min, max) {
  25469. if (max == null) {
  25470. max = min;
  25471. min = 0;
  25472. }
  25473. return min + Math.floor(Math.random() * (max - min + 1));
  25474. };
  25475. // A (possibly faster) way to get the current timestamp as an integer.
  25476. _.now = Date.now || function() {
  25477. return new Date().getTime();
  25478. };
  25479. // List of HTML entities for escaping.
  25480. var escapeMap = {
  25481. '&': '&amp;',
  25482. '<': '&lt;',
  25483. '>': '&gt;',
  25484. '"': '&quot;',
  25485. "'": '&#x27;',
  25486. '`': '&#x60;'
  25487. };
  25488. var unescapeMap = _.invert(escapeMap);
  25489. // Functions for escaping and unescaping strings to/from HTML interpolation.
  25490. var createEscaper = function(map) {
  25491. var escaper = function(match) {
  25492. return map[match];
  25493. };
  25494. // Regexes for identifying a key that needs to be escaped
  25495. var source = '(?:' + _.keys(map).join('|') + ')';
  25496. var testRegexp = RegExp(source);
  25497. var replaceRegexp = RegExp(source, 'g');
  25498. return function(string) {
  25499. string = string == null ? '' : '' + string;
  25500. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  25501. };
  25502. };
  25503. _.escape = createEscaper(escapeMap);
  25504. _.unescape = createEscaper(unescapeMap);
  25505. // If the value of the named `property` is a function then invoke it with the
  25506. // `object` as context; otherwise, return it.
  25507. _.result = function(object, property, fallback) {
  25508. var value = object == null ? void 0 : object[property];
  25509. if (value === void 0) {
  25510. value = fallback;
  25511. }
  25512. return _.isFunction(value) ? value.call(object) : value;
  25513. };
  25514. // Generate a unique integer id (unique within the entire client session).
  25515. // Useful for temporary DOM ids.
  25516. var idCounter = 0;
  25517. _.uniqueId = function(prefix) {
  25518. var id = ++idCounter + '';
  25519. return prefix ? prefix + id : id;
  25520. };
  25521. // By default, Underscore uses ERB-style template delimiters, change the
  25522. // following template settings to use alternative delimiters.
  25523. _.templateSettings = {
  25524. evaluate : /<%([\s\S]+?)%>/g,
  25525. interpolate : /<%=([\s\S]+?)%>/g,
  25526. escape : /<%-([\s\S]+?)%>/g
  25527. };
  25528. // When customizing `templateSettings`, if you don't want to define an
  25529. // interpolation, evaluation or escaping regex, we need one that is
  25530. // guaranteed not to match.
  25531. var noMatch = /(.)^/;
  25532. // Certain characters need to be escaped so that they can be put into a
  25533. // string literal.
  25534. var escapes = {
  25535. "'": "'",
  25536. '\\': '\\',
  25537. '\r': 'r',
  25538. '\n': 'n',
  25539. '\u2028': 'u2028',
  25540. '\u2029': 'u2029'
  25541. };
  25542. var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
  25543. var escapeChar = function(match) {
  25544. return '\\' + escapes[match];
  25545. };
  25546. // JavaScript micro-templating, similar to John Resig's implementation.
  25547. // Underscore templating handles arbitrary delimiters, preserves whitespace,
  25548. // and correctly escapes quotes within interpolated code.
  25549. // NB: `oldSettings` only exists for backwards compatibility.
  25550. _.template = function(text, settings, oldSettings) {
  25551. if (!settings && oldSettings) settings = oldSettings;
  25552. settings = _.defaults({}, settings, _.templateSettings);
  25553. // Combine delimiters into one regular expression via alternation.
  25554. var matcher = RegExp([
  25555. (settings.escape || noMatch).source,
  25556. (settings.interpolate || noMatch).source,
  25557. (settings.evaluate || noMatch).source
  25558. ].join('|') + '|$', 'g');
  25559. // Compile the template source, escaping string literals appropriately.
  25560. var index = 0;
  25561. var source = "__p+='";
  25562. text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
  25563. source += text.slice(index, offset).replace(escaper, escapeChar);
  25564. index = offset + match.length;
  25565. if (escape) {
  25566. source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
  25567. } else if (interpolate) {
  25568. source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
  25569. } else if (evaluate) {
  25570. source += "';\n" + evaluate + "\n__p+='";
  25571. }
  25572. // Adobe VMs need the match returned to produce the correct offest.
  25573. return match;
  25574. });
  25575. source += "';\n";
  25576. // If a variable is not specified, place data values in local scope.
  25577. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
  25578. source = "var __t,__p='',__j=Array.prototype.join," +
  25579. "print=function(){__p+=__j.call(arguments,'');};\n" +
  25580. source + 'return __p;\n';
  25581. try {
  25582. var render = new Function(settings.variable || 'obj', '_', source);
  25583. } catch (e) {
  25584. e.source = source;
  25585. throw e;
  25586. }
  25587. var template = function(data) {
  25588. return render.call(this, data, _);
  25589. };
  25590. // Provide the compiled source as a convenience for precompilation.
  25591. var argument = settings.variable || 'obj';
  25592. template.source = 'function(' + argument + '){\n' + source + '}';
  25593. return template;
  25594. };
  25595. // Add a "chain" function. Start chaining a wrapped Underscore object.
  25596. _.chain = function(obj) {
  25597. var instance = _(obj);
  25598. instance._chain = true;
  25599. return instance;
  25600. };
  25601. // OOP
  25602. // ---------------
  25603. // If Underscore is called as a function, it returns a wrapped object that
  25604. // can be used OO-style. This wrapper holds altered versions of all the
  25605. // underscore functions. Wrapped objects may be chained.
  25606. // Helper function to continue chaining intermediate results.
  25607. var result = function(instance, obj) {
  25608. return instance._chain ? _(obj).chain() : obj;
  25609. };
  25610. // Add your own custom functions to the Underscore object.
  25611. _.mixin = function(obj) {
  25612. _.each(_.functions(obj), function(name) {
  25613. var func = _[name] = obj[name];
  25614. _.prototype[name] = function() {
  25615. var args = [this._wrapped];
  25616. push.apply(args, arguments);
  25617. return result(this, func.apply(_, args));
  25618. };
  25619. });
  25620. };
  25621. // Add all of the Underscore functions to the wrapper object.
  25622. _.mixin(_);
  25623. // Add all mutator Array functions to the wrapper.
  25624. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  25625. var method = ArrayProto[name];
  25626. _.prototype[name] = function() {
  25627. var obj = this._wrapped;
  25628. method.apply(obj, arguments);
  25629. if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
  25630. return result(this, obj);
  25631. };
  25632. });
  25633. // Add all accessor Array functions to the wrapper.
  25634. _.each(['concat', 'join', 'slice'], function(name) {
  25635. var method = ArrayProto[name];
  25636. _.prototype[name] = function() {
  25637. return result(this, method.apply(this._wrapped, arguments));
  25638. };
  25639. });
  25640. // Extracts the result from a wrapped and chained object.
  25641. _.prototype.value = function() {
  25642. return this._wrapped;
  25643. };
  25644. // Provide unwrapping proxy for some methods used in engine operations
  25645. // such as arithmetic and JSON stringification.
  25646. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
  25647. _.prototype.toString = function() {
  25648. return '' + this._wrapped;
  25649. };
  25650. // AMD registration happens at the end for compatibility with AMD loaders
  25651. // that may not enforce next-turn semantics on modules. Even though general
  25652. // practice for AMD registration is to be anonymous, underscore registers
  25653. // as a named module because, like jQuery, it is a base library that is
  25654. // popular enough to be bundled in a third party lib, but not be part of
  25655. // an AMD load request. Those cases could generate an error when an
  25656. // anonymous define() is called outside of a loader request.
  25657. if (typeof define === 'function' && define.amd) {
  25658. define('underscore', [], function() {
  25659. return _;
  25660. });
  25661. }
  25662. }.call(this));
  25663. },{}],154:[function(require,module,exports){
  25664. (function (global){
  25665. /**
  25666. * Module exports.
  25667. */
  25668. module.exports = deprecate;
  25669. /**
  25670. * Mark that a method should not be used.
  25671. * Returns a modified function which warns once by default.
  25672. *
  25673. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  25674. *
  25675. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  25676. * will throw an Error when invoked.
  25677. *
  25678. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  25679. * will invoke `console.trace()` instead of `console.error()`.
  25680. *
  25681. * @param {Function} fn - the function to deprecate
  25682. * @param {String} msg - the string to print to the console when `fn` is invoked
  25683. * @returns {Function} a new "deprecated" version of `fn`
  25684. * @api public
  25685. */
  25686. function deprecate (fn, msg) {
  25687. if (config('noDeprecation')) {
  25688. return fn;
  25689. }
  25690. var warned = false;
  25691. function deprecated() {
  25692. if (!warned) {
  25693. if (config('throwDeprecation')) {
  25694. throw new Error(msg);
  25695. } else if (config('traceDeprecation')) {
  25696. console.trace(msg);
  25697. } else {
  25698. console.warn(msg);
  25699. }
  25700. warned = true;
  25701. }
  25702. return fn.apply(this, arguments);
  25703. }
  25704. return deprecated;
  25705. }
  25706. /**
  25707. * Checks `localStorage` for boolean values for the given `name`.
  25708. *
  25709. * @param {String} name
  25710. * @returns {Boolean}
  25711. * @api private
  25712. */
  25713. function config (name) {
  25714. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  25715. try {
  25716. if (!global.localStorage) return false;
  25717. } catch (_) {
  25718. return false;
  25719. }
  25720. var val = global.localStorage[name];
  25721. if (null == val) return false;
  25722. return String(val).toLowerCase() === 'true';
  25723. }
  25724. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25725. },{}],155:[function(require,module,exports){
  25726. arguments[4][81][0].apply(exports,arguments)
  25727. },{"dup":81}],156:[function(require,module,exports){
  25728. module.exports = function isBuffer(arg) {
  25729. return arg && typeof arg === 'object'
  25730. && typeof arg.copy === 'function'
  25731. && typeof arg.fill === 'function'
  25732. && typeof arg.readUInt8 === 'function';
  25733. }
  25734. },{}],157:[function(require,module,exports){
  25735. (function (process,global){
  25736. // Copyright Joyent, Inc. and other Node contributors.
  25737. //
  25738. // Permission is hereby granted, free of charge, to any person obtaining a
  25739. // copy of this software and associated documentation files (the
  25740. // "Software"), to deal in the Software without restriction, including
  25741. // without limitation the rights to use, copy, modify, merge, publish,
  25742. // distribute, sublicense, and/or sell copies of the Software, and to permit
  25743. // persons to whom the Software is furnished to do so, subject to the
  25744. // following conditions:
  25745. //
  25746. // The above copyright notice and this permission notice shall be included
  25747. // in all copies or substantial portions of the Software.
  25748. //
  25749. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  25750. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25751. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  25752. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  25753. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  25754. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  25755. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  25756. var formatRegExp = /%[sdj%]/g;
  25757. exports.format = function(f) {
  25758. if (!isString(f)) {
  25759. var objects = [];
  25760. for (var i = 0; i < arguments.length; i++) {
  25761. objects.push(inspect(arguments[i]));
  25762. }
  25763. return objects.join(' ');
  25764. }
  25765. var i = 1;
  25766. var args = arguments;
  25767. var len = args.length;
  25768. var str = String(f).replace(formatRegExp, function(x) {
  25769. if (x === '%%') return '%';
  25770. if (i >= len) return x;
  25771. switch (x) {
  25772. case '%s': return String(args[i++]);
  25773. case '%d': return Number(args[i++]);
  25774. case '%j':
  25775. try {
  25776. return JSON.stringify(args[i++]);
  25777. } catch (_) {
  25778. return '[Circular]';
  25779. }
  25780. default:
  25781. return x;
  25782. }
  25783. });
  25784. for (var x = args[i]; i < len; x = args[++i]) {
  25785. if (isNull(x) || !isObject(x)) {
  25786. str += ' ' + x;
  25787. } else {
  25788. str += ' ' + inspect(x);
  25789. }
  25790. }
  25791. return str;
  25792. };
  25793. // Mark that a method should not be used.
  25794. // Returns a modified function which warns once by default.
  25795. // If --no-deprecation is set, then it is a no-op.
  25796. exports.deprecate = function(fn, msg) {
  25797. // Allow for deprecating things in the process of starting up.
  25798. if (isUndefined(global.process)) {
  25799. return function() {
  25800. return exports.deprecate(fn, msg).apply(this, arguments);
  25801. };
  25802. }
  25803. if (process.noDeprecation === true) {
  25804. return fn;
  25805. }
  25806. var warned = false;
  25807. function deprecated() {
  25808. if (!warned) {
  25809. if (process.throwDeprecation) {
  25810. throw new Error(msg);
  25811. } else if (process.traceDeprecation) {
  25812. console.trace(msg);
  25813. } else {
  25814. console.error(msg);
  25815. }
  25816. warned = true;
  25817. }
  25818. return fn.apply(this, arguments);
  25819. }
  25820. return deprecated;
  25821. };
  25822. var debugs = {};
  25823. var debugEnviron;
  25824. exports.debuglog = function(set) {
  25825. if (isUndefined(debugEnviron))
  25826. debugEnviron = process.env.NODE_DEBUG || '';
  25827. set = set.toUpperCase();
  25828. if (!debugs[set]) {
  25829. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  25830. var pid = process.pid;
  25831. debugs[set] = function() {
  25832. var msg = exports.format.apply(exports, arguments);
  25833. console.error('%s %d: %s', set, pid, msg);
  25834. };
  25835. } else {
  25836. debugs[set] = function() {};
  25837. }
  25838. }
  25839. return debugs[set];
  25840. };
  25841. /**
  25842. * Echos the value of a value. Trys to print the value out
  25843. * in the best way possible given the different types.
  25844. *
  25845. * @param {Object} obj The object to print out.
  25846. * @param {Object} opts Optional options object that alters the output.
  25847. */
  25848. /* legacy: obj, showHidden, depth, colors*/
  25849. function inspect(obj, opts) {
  25850. // default options
  25851. var ctx = {
  25852. seen: [],
  25853. stylize: stylizeNoColor
  25854. };
  25855. // legacy...
  25856. if (arguments.length >= 3) ctx.depth = arguments[2];
  25857. if (arguments.length >= 4) ctx.colors = arguments[3];
  25858. if (isBoolean(opts)) {
  25859. // legacy...
  25860. ctx.showHidden = opts;
  25861. } else if (opts) {
  25862. // got an "options" object
  25863. exports._extend(ctx, opts);
  25864. }
  25865. // set default options
  25866. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  25867. if (isUndefined(ctx.depth)) ctx.depth = 2;
  25868. if (isUndefined(ctx.colors)) ctx.colors = false;
  25869. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  25870. if (ctx.colors) ctx.stylize = stylizeWithColor;
  25871. return formatValue(ctx, obj, ctx.depth);
  25872. }
  25873. exports.inspect = inspect;
  25874. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  25875. inspect.colors = {
  25876. 'bold' : [1, 22],
  25877. 'italic' : [3, 23],
  25878. 'underline' : [4, 24],
  25879. 'inverse' : [7, 27],
  25880. 'white' : [37, 39],
  25881. 'grey' : [90, 39],
  25882. 'black' : [30, 39],
  25883. 'blue' : [34, 39],
  25884. 'cyan' : [36, 39],
  25885. 'green' : [32, 39],
  25886. 'magenta' : [35, 39],
  25887. 'red' : [31, 39],
  25888. 'yellow' : [33, 39]
  25889. };
  25890. // Don't use 'blue' not visible on cmd.exe
  25891. inspect.styles = {
  25892. 'special': 'cyan',
  25893. 'number': 'yellow',
  25894. 'boolean': 'yellow',
  25895. 'undefined': 'grey',
  25896. 'null': 'bold',
  25897. 'string': 'green',
  25898. 'date': 'magenta',
  25899. // "name": intentionally not styling
  25900. 'regexp': 'red'
  25901. };
  25902. function stylizeWithColor(str, styleType) {
  25903. var style = inspect.styles[styleType];
  25904. if (style) {
  25905. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  25906. '\u001b[' + inspect.colors[style][1] + 'm';
  25907. } else {
  25908. return str;
  25909. }
  25910. }
  25911. function stylizeNoColor(str, styleType) {
  25912. return str;
  25913. }
  25914. function arrayToHash(array) {
  25915. var hash = {};
  25916. array.forEach(function(val, idx) {
  25917. hash[val] = true;
  25918. });
  25919. return hash;
  25920. }
  25921. function formatValue(ctx, value, recurseTimes) {
  25922. // Provide a hook for user-specified inspect functions.
  25923. // Check that value is an object with an inspect function on it
  25924. if (ctx.customInspect &&
  25925. value &&
  25926. isFunction(value.inspect) &&
  25927. // Filter out the util module, it's inspect function is special
  25928. value.inspect !== exports.inspect &&
  25929. // Also filter out any prototype objects using the circular check.
  25930. !(value.constructor && value.constructor.prototype === value)) {
  25931. var ret = value.inspect(recurseTimes, ctx);
  25932. if (!isString(ret)) {
  25933. ret = formatValue(ctx, ret, recurseTimes);
  25934. }
  25935. return ret;
  25936. }
  25937. // Primitive types cannot have properties
  25938. var primitive = formatPrimitive(ctx, value);
  25939. if (primitive) {
  25940. return primitive;
  25941. }
  25942. // Look up the keys of the object.
  25943. var keys = Object.keys(value);
  25944. var visibleKeys = arrayToHash(keys);
  25945. if (ctx.showHidden) {
  25946. keys = Object.getOwnPropertyNames(value);
  25947. }
  25948. // IE doesn't make error fields non-enumerable
  25949. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  25950. if (isError(value)
  25951. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  25952. return formatError(value);
  25953. }
  25954. // Some type of object without properties can be shortcutted.
  25955. if (keys.length === 0) {
  25956. if (isFunction(value)) {
  25957. var name = value.name ? ': ' + value.name : '';
  25958. return ctx.stylize('[Function' + name + ']', 'special');
  25959. }
  25960. if (isRegExp(value)) {
  25961. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  25962. }
  25963. if (isDate(value)) {
  25964. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  25965. }
  25966. if (isError(value)) {
  25967. return formatError(value);
  25968. }
  25969. }
  25970. var base = '', array = false, braces = ['{', '}'];
  25971. // Make Array say that they are Array
  25972. if (isArray(value)) {
  25973. array = true;
  25974. braces = ['[', ']'];
  25975. }
  25976. // Make functions say that they are functions
  25977. if (isFunction(value)) {
  25978. var n = value.name ? ': ' + value.name : '';
  25979. base = ' [Function' + n + ']';
  25980. }
  25981. // Make RegExps say that they are RegExps
  25982. if (isRegExp(value)) {
  25983. base = ' ' + RegExp.prototype.toString.call(value);
  25984. }
  25985. // Make dates with properties first say the date
  25986. if (isDate(value)) {
  25987. base = ' ' + Date.prototype.toUTCString.call(value);
  25988. }
  25989. // Make error with message first say the error
  25990. if (isError(value)) {
  25991. base = ' ' + formatError(value);
  25992. }
  25993. if (keys.length === 0 && (!array || value.length == 0)) {
  25994. return braces[0] + base + braces[1];
  25995. }
  25996. if (recurseTimes < 0) {
  25997. if (isRegExp(value)) {
  25998. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  25999. } else {
  26000. return ctx.stylize('[Object]', 'special');
  26001. }
  26002. }
  26003. ctx.seen.push(value);
  26004. var output;
  26005. if (array) {
  26006. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  26007. } else {
  26008. output = keys.map(function(key) {
  26009. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  26010. });
  26011. }
  26012. ctx.seen.pop();
  26013. return reduceToSingleString(output, base, braces);
  26014. }
  26015. function formatPrimitive(ctx, value) {
  26016. if (isUndefined(value))
  26017. return ctx.stylize('undefined', 'undefined');
  26018. if (isString(value)) {
  26019. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  26020. .replace(/'/g, "\\'")
  26021. .replace(/\\"/g, '"') + '\'';
  26022. return ctx.stylize(simple, 'string');
  26023. }
  26024. if (isNumber(value))
  26025. return ctx.stylize('' + value, 'number');
  26026. if (isBoolean(value))
  26027. return ctx.stylize('' + value, 'boolean');
  26028. // For some reason typeof null is "object", so special case here.
  26029. if (isNull(value))
  26030. return ctx.stylize('null', 'null');
  26031. }
  26032. function formatError(value) {
  26033. return '[' + Error.prototype.toString.call(value) + ']';
  26034. }
  26035. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  26036. var output = [];
  26037. for (var i = 0, l = value.length; i < l; ++i) {
  26038. if (hasOwnProperty(value, String(i))) {
  26039. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  26040. String(i), true));
  26041. } else {
  26042. output.push('');
  26043. }
  26044. }
  26045. keys.forEach(function(key) {
  26046. if (!key.match(/^\d+$/)) {
  26047. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  26048. key, true));
  26049. }
  26050. });
  26051. return output;
  26052. }
  26053. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  26054. var name, str, desc;
  26055. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  26056. if (desc.get) {
  26057. if (desc.set) {
  26058. str = ctx.stylize('[Getter/Setter]', 'special');
  26059. } else {
  26060. str = ctx.stylize('[Getter]', 'special');
  26061. }
  26062. } else {
  26063. if (desc.set) {
  26064. str = ctx.stylize('[Setter]', 'special');
  26065. }
  26066. }
  26067. if (!hasOwnProperty(visibleKeys, key)) {
  26068. name = '[' + key + ']';
  26069. }
  26070. if (!str) {
  26071. if (ctx.seen.indexOf(desc.value) < 0) {
  26072. if (isNull(recurseTimes)) {
  26073. str = formatValue(ctx, desc.value, null);
  26074. } else {
  26075. str = formatValue(ctx, desc.value, recurseTimes - 1);
  26076. }
  26077. if (str.indexOf('\n') > -1) {
  26078. if (array) {
  26079. str = str.split('\n').map(function(line) {
  26080. return ' ' + line;
  26081. }).join('\n').substr(2);
  26082. } else {
  26083. str = '\n' + str.split('\n').map(function(line) {
  26084. return ' ' + line;
  26085. }).join('\n');
  26086. }
  26087. }
  26088. } else {
  26089. str = ctx.stylize('[Circular]', 'special');
  26090. }
  26091. }
  26092. if (isUndefined(name)) {
  26093. if (array && key.match(/^\d+$/)) {
  26094. return str;
  26095. }
  26096. name = JSON.stringify('' + key);
  26097. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  26098. name = name.substr(1, name.length - 2);
  26099. name = ctx.stylize(name, 'name');
  26100. } else {
  26101. name = name.replace(/'/g, "\\'")
  26102. .replace(/\\"/g, '"')
  26103. .replace(/(^"|"$)/g, "'");
  26104. name = ctx.stylize(name, 'string');
  26105. }
  26106. }
  26107. return name + ': ' + str;
  26108. }
  26109. function reduceToSingleString(output, base, braces) {
  26110. var numLinesEst = 0;
  26111. var length = output.reduce(function(prev, cur) {
  26112. numLinesEst++;
  26113. if (cur.indexOf('\n') >= 0) numLinesEst++;
  26114. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  26115. }, 0);
  26116. if (length > 60) {
  26117. return braces[0] +
  26118. (base === '' ? '' : base + '\n ') +
  26119. ' ' +
  26120. output.join(',\n ') +
  26121. ' ' +
  26122. braces[1];
  26123. }
  26124. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  26125. }
  26126. // NOTE: These type checking functions intentionally don't use `instanceof`
  26127. // because it is fragile and can be easily faked with `Object.create()`.
  26128. function isArray(ar) {
  26129. return Array.isArray(ar);
  26130. }
  26131. exports.isArray = isArray;
  26132. function isBoolean(arg) {
  26133. return typeof arg === 'boolean';
  26134. }
  26135. exports.isBoolean = isBoolean;
  26136. function isNull(arg) {
  26137. return arg === null;
  26138. }
  26139. exports.isNull = isNull;
  26140. function isNullOrUndefined(arg) {
  26141. return arg == null;
  26142. }
  26143. exports.isNullOrUndefined = isNullOrUndefined;
  26144. function isNumber(arg) {
  26145. return typeof arg === 'number';
  26146. }
  26147. exports.isNumber = isNumber;
  26148. function isString(arg) {
  26149. return typeof arg === 'string';
  26150. }
  26151. exports.isString = isString;
  26152. function isSymbol(arg) {
  26153. return typeof arg === 'symbol';
  26154. }
  26155. exports.isSymbol = isSymbol;
  26156. function isUndefined(arg) {
  26157. return arg === void 0;
  26158. }
  26159. exports.isUndefined = isUndefined;
  26160. function isRegExp(re) {
  26161. return isObject(re) && objectToString(re) === '[object RegExp]';
  26162. }
  26163. exports.isRegExp = isRegExp;
  26164. function isObject(arg) {
  26165. return typeof arg === 'object' && arg !== null;
  26166. }
  26167. exports.isObject = isObject;
  26168. function isDate(d) {
  26169. return isObject(d) && objectToString(d) === '[object Date]';
  26170. }
  26171. exports.isDate = isDate;
  26172. function isError(e) {
  26173. return isObject(e) &&
  26174. (objectToString(e) === '[object Error]' || e instanceof Error);
  26175. }
  26176. exports.isError = isError;
  26177. function isFunction(arg) {
  26178. return typeof arg === 'function';
  26179. }
  26180. exports.isFunction = isFunction;
  26181. function isPrimitive(arg) {
  26182. return arg === null ||
  26183. typeof arg === 'boolean' ||
  26184. typeof arg === 'number' ||
  26185. typeof arg === 'string' ||
  26186. typeof arg === 'symbol' || // ES6 symbol
  26187. typeof arg === 'undefined';
  26188. }
  26189. exports.isPrimitive = isPrimitive;
  26190. exports.isBuffer = require('./support/isBuffer');
  26191. function objectToString(o) {
  26192. return Object.prototype.toString.call(o);
  26193. }
  26194. function pad(n) {
  26195. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  26196. }
  26197. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  26198. 'Oct', 'Nov', 'Dec'];
  26199. // 26 Feb 16:19:34
  26200. function timestamp() {
  26201. var d = new Date();
  26202. var time = [pad(d.getHours()),
  26203. pad(d.getMinutes()),
  26204. pad(d.getSeconds())].join(':');
  26205. return [d.getDate(), months[d.getMonth()], time].join(' ');
  26206. }
  26207. // log is just a thin wrapper to console.log that prepends a timestamp
  26208. exports.log = function() {
  26209. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  26210. };
  26211. /**
  26212. * Inherit the prototype methods from one constructor into another.
  26213. *
  26214. * The Function.prototype.inherits from lang.js rewritten as a standalone
  26215. * function (not on Function.prototype). NOTE: If this file is to be loaded
  26216. * during bootstrapping this function needs to be rewritten using some native
  26217. * functions as prototype setup using normal JavaScript does not work as
  26218. * expected during bootstrapping (see mirror.js in r114903).
  26219. *
  26220. * @param {function} ctor Constructor function which needs to inherit the
  26221. * prototype.
  26222. * @param {function} superCtor Constructor function to inherit prototype from.
  26223. */
  26224. exports.inherits = require('inherits');
  26225. exports._extend = function(origin, add) {
  26226. // Don't do anything if add isn't an object
  26227. if (!add || !isObject(add)) return origin;
  26228. var keys = Object.keys(add);
  26229. var i = keys.length;
  26230. while (i--) {
  26231. origin[keys[i]] = add[keys[i]];
  26232. }
  26233. return origin;
  26234. };
  26235. function hasOwnProperty(obj, prop) {
  26236. return Object.prototype.hasOwnProperty.call(obj, prop);
  26237. }
  26238. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26239. },{"./support/isBuffer":156,"_process":138,"inherits":155}],158:[function(require,module,exports){
  26240. // Generated by CoffeeScript 1.12.7
  26241. (function() {
  26242. var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject,
  26243. slice = [].slice,
  26244. hasProp = {}.hasOwnProperty;
  26245. assign = function() {
  26246. var i, key, len, source, sources, target;
  26247. target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  26248. if (isFunction(Object.assign)) {
  26249. Object.assign.apply(null, arguments);
  26250. } else {
  26251. for (i = 0, len = sources.length; i < len; i++) {
  26252. source = sources[i];
  26253. if (source != null) {
  26254. for (key in source) {
  26255. if (!hasProp.call(source, key)) continue;
  26256. target[key] = source[key];
  26257. }
  26258. }
  26259. }
  26260. }
  26261. return target;
  26262. };
  26263. isFunction = function(val) {
  26264. return !!val && Object.prototype.toString.call(val) === '[object Function]';
  26265. };
  26266. isObject = function(val) {
  26267. var ref;
  26268. return !!val && ((ref = typeof val) === 'function' || ref === 'object');
  26269. };
  26270. isArray = function(val) {
  26271. if (isFunction(Array.isArray)) {
  26272. return Array.isArray(val);
  26273. } else {
  26274. return Object.prototype.toString.call(val) === '[object Array]';
  26275. }
  26276. };
  26277. isEmpty = function(val) {
  26278. var key;
  26279. if (isArray(val)) {
  26280. return !val.length;
  26281. } else {
  26282. for (key in val) {
  26283. if (!hasProp.call(val, key)) continue;
  26284. return false;
  26285. }
  26286. return true;
  26287. }
  26288. };
  26289. isPlainObject = function(val) {
  26290. var ctor, proto;
  26291. 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));
  26292. };
  26293. getValue = function(obj) {
  26294. if (isFunction(obj.valueOf)) {
  26295. return obj.valueOf();
  26296. } else {
  26297. return obj;
  26298. }
  26299. };
  26300. module.exports.assign = assign;
  26301. module.exports.isFunction = isFunction;
  26302. module.exports.isObject = isObject;
  26303. module.exports.isArray = isArray;
  26304. module.exports.isEmpty = isEmpty;
  26305. module.exports.isPlainObject = isPlainObject;
  26306. module.exports.getValue = getValue;
  26307. }).call(this);
  26308. },{}],159:[function(require,module,exports){
  26309. // Generated by CoffeeScript 1.12.7
  26310. (function() {
  26311. var XMLAttribute;
  26312. module.exports = XMLAttribute = (function() {
  26313. function XMLAttribute(parent, name, value) {
  26314. this.options = parent.options;
  26315. this.stringify = parent.stringify;
  26316. this.parent = parent;
  26317. if (name == null) {
  26318. throw new Error("Missing attribute name. " + this.debugInfo(name));
  26319. }
  26320. if (value == null) {
  26321. throw new Error("Missing attribute value. " + this.debugInfo(name));
  26322. }
  26323. this.name = this.stringify.attName(name);
  26324. this.value = this.stringify.attValue(value);
  26325. }
  26326. XMLAttribute.prototype.clone = function() {
  26327. return Object.create(this);
  26328. };
  26329. XMLAttribute.prototype.toString = function(options) {
  26330. return this.options.writer.set(options).attribute(this);
  26331. };
  26332. XMLAttribute.prototype.debugInfo = function(name) {
  26333. var ref, ref1;
  26334. name = name || this.name;
  26335. if ((name == null) && !((ref = this.parent) != null ? ref.name : void 0)) {
  26336. return "";
  26337. } else if (name == null) {
  26338. return "parent: <" + this.parent.name + ">";
  26339. } else if (!((ref1 = this.parent) != null ? ref1.name : void 0)) {
  26340. return "attribute: {" + name + "}";
  26341. } else {
  26342. return "attribute: {" + name + "}, parent: <" + this.parent.name + ">";
  26343. }
  26344. };
  26345. return XMLAttribute;
  26346. })();
  26347. }).call(this);
  26348. },{}],160:[function(require,module,exports){
  26349. // Generated by CoffeeScript 1.12.7
  26350. (function() {
  26351. var XMLCData, XMLNode,
  26352. 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; },
  26353. hasProp = {}.hasOwnProperty;
  26354. XMLNode = require('./XMLNode');
  26355. module.exports = XMLCData = (function(superClass) {
  26356. extend(XMLCData, superClass);
  26357. function XMLCData(parent, text) {
  26358. XMLCData.__super__.constructor.call(this, parent);
  26359. if (text == null) {
  26360. throw new Error("Missing CDATA text. " + this.debugInfo());
  26361. }
  26362. this.text = this.stringify.cdata(text);
  26363. }
  26364. XMLCData.prototype.clone = function() {
  26365. return Object.create(this);
  26366. };
  26367. XMLCData.prototype.toString = function(options) {
  26368. return this.options.writer.set(options).cdata(this);
  26369. };
  26370. return XMLCData;
  26371. })(XMLNode);
  26372. }).call(this);
  26373. },{"./XMLNode":171}],161:[function(require,module,exports){
  26374. // Generated by CoffeeScript 1.12.7
  26375. (function() {
  26376. var XMLComment, XMLNode,
  26377. 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; },
  26378. hasProp = {}.hasOwnProperty;
  26379. XMLNode = require('./XMLNode');
  26380. module.exports = XMLComment = (function(superClass) {
  26381. extend(XMLComment, superClass);
  26382. function XMLComment(parent, text) {
  26383. XMLComment.__super__.constructor.call(this, parent);
  26384. if (text == null) {
  26385. throw new Error("Missing comment text. " + this.debugInfo());
  26386. }
  26387. this.text = this.stringify.comment(text);
  26388. }
  26389. XMLComment.prototype.clone = function() {
  26390. return Object.create(this);
  26391. };
  26392. XMLComment.prototype.toString = function(options) {
  26393. return this.options.writer.set(options).comment(this);
  26394. };
  26395. return XMLComment;
  26396. })(XMLNode);
  26397. }).call(this);
  26398. },{"./XMLNode":171}],162:[function(require,module,exports){
  26399. // Generated by CoffeeScript 1.12.7
  26400. (function() {
  26401. var XMLDTDAttList, XMLNode,
  26402. 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; },
  26403. hasProp = {}.hasOwnProperty;
  26404. XMLNode = require('./XMLNode');
  26405. module.exports = XMLDTDAttList = (function(superClass) {
  26406. extend(XMLDTDAttList, superClass);
  26407. function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  26408. XMLDTDAttList.__super__.constructor.call(this, parent);
  26409. if (elementName == null) {
  26410. throw new Error("Missing DTD element name. " + this.debugInfo());
  26411. }
  26412. if (attributeName == null) {
  26413. throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName));
  26414. }
  26415. if (!attributeType) {
  26416. throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName));
  26417. }
  26418. if (!defaultValueType) {
  26419. throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName));
  26420. }
  26421. if (defaultValueType.indexOf('#') !== 0) {
  26422. defaultValueType = '#' + defaultValueType;
  26423. }
  26424. if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
  26425. throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName));
  26426. }
  26427. if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
  26428. throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName));
  26429. }
  26430. this.elementName = this.stringify.eleName(elementName);
  26431. this.attributeName = this.stringify.attName(attributeName);
  26432. this.attributeType = this.stringify.dtdAttType(attributeType);
  26433. this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
  26434. this.defaultValueType = defaultValueType;
  26435. }
  26436. XMLDTDAttList.prototype.toString = function(options) {
  26437. return this.options.writer.set(options).dtdAttList(this);
  26438. };
  26439. return XMLDTDAttList;
  26440. })(XMLNode);
  26441. }).call(this);
  26442. },{"./XMLNode":171}],163:[function(require,module,exports){
  26443. // Generated by CoffeeScript 1.12.7
  26444. (function() {
  26445. var XMLDTDElement, XMLNode,
  26446. 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; },
  26447. hasProp = {}.hasOwnProperty;
  26448. XMLNode = require('./XMLNode');
  26449. module.exports = XMLDTDElement = (function(superClass) {
  26450. extend(XMLDTDElement, superClass);
  26451. function XMLDTDElement(parent, name, value) {
  26452. XMLDTDElement.__super__.constructor.call(this, parent);
  26453. if (name == null) {
  26454. throw new Error("Missing DTD element name. " + this.debugInfo());
  26455. }
  26456. if (!value) {
  26457. value = '(#PCDATA)';
  26458. }
  26459. if (Array.isArray(value)) {
  26460. value = '(' + value.join(',') + ')';
  26461. }
  26462. this.name = this.stringify.eleName(name);
  26463. this.value = this.stringify.dtdElementValue(value);
  26464. }
  26465. XMLDTDElement.prototype.toString = function(options) {
  26466. return this.options.writer.set(options).dtdElement(this);
  26467. };
  26468. return XMLDTDElement;
  26469. })(XMLNode);
  26470. }).call(this);
  26471. },{"./XMLNode":171}],164:[function(require,module,exports){
  26472. // Generated by CoffeeScript 1.12.7
  26473. (function() {
  26474. var XMLDTDEntity, XMLNode, isObject,
  26475. 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; },
  26476. hasProp = {}.hasOwnProperty;
  26477. isObject = require('./Utility').isObject;
  26478. XMLNode = require('./XMLNode');
  26479. module.exports = XMLDTDEntity = (function(superClass) {
  26480. extend(XMLDTDEntity, superClass);
  26481. function XMLDTDEntity(parent, pe, name, value) {
  26482. XMLDTDEntity.__super__.constructor.call(this, parent);
  26483. if (name == null) {
  26484. throw new Error("Missing DTD entity name. " + this.debugInfo(name));
  26485. }
  26486. if (value == null) {
  26487. throw new Error("Missing DTD entity value. " + this.debugInfo(name));
  26488. }
  26489. this.pe = !!pe;
  26490. this.name = this.stringify.eleName(name);
  26491. if (!isObject(value)) {
  26492. this.value = this.stringify.dtdEntityValue(value);
  26493. } else {
  26494. if (!value.pubID && !value.sysID) {
  26495. throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name));
  26496. }
  26497. if (value.pubID && !value.sysID) {
  26498. throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name));
  26499. }
  26500. if (value.pubID != null) {
  26501. this.pubID = this.stringify.dtdPubID(value.pubID);
  26502. }
  26503. if (value.sysID != null) {
  26504. this.sysID = this.stringify.dtdSysID(value.sysID);
  26505. }
  26506. if (value.nData != null) {
  26507. this.nData = this.stringify.dtdNData(value.nData);
  26508. }
  26509. if (this.pe && this.nData) {
  26510. throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name));
  26511. }
  26512. }
  26513. }
  26514. XMLDTDEntity.prototype.toString = function(options) {
  26515. return this.options.writer.set(options).dtdEntity(this);
  26516. };
  26517. return XMLDTDEntity;
  26518. })(XMLNode);
  26519. }).call(this);
  26520. },{"./Utility":158,"./XMLNode":171}],165:[function(require,module,exports){
  26521. // Generated by CoffeeScript 1.12.7
  26522. (function() {
  26523. var XMLDTDNotation, XMLNode,
  26524. 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; },
  26525. hasProp = {}.hasOwnProperty;
  26526. XMLNode = require('./XMLNode');
  26527. module.exports = XMLDTDNotation = (function(superClass) {
  26528. extend(XMLDTDNotation, superClass);
  26529. function XMLDTDNotation(parent, name, value) {
  26530. XMLDTDNotation.__super__.constructor.call(this, parent);
  26531. if (name == null) {
  26532. throw new Error("Missing DTD notation name. " + this.debugInfo(name));
  26533. }
  26534. if (!value.pubID && !value.sysID) {
  26535. throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name));
  26536. }
  26537. this.name = this.stringify.eleName(name);
  26538. if (value.pubID != null) {
  26539. this.pubID = this.stringify.dtdPubID(value.pubID);
  26540. }
  26541. if (value.sysID != null) {
  26542. this.sysID = this.stringify.dtdSysID(value.sysID);
  26543. }
  26544. }
  26545. XMLDTDNotation.prototype.toString = function(options) {
  26546. return this.options.writer.set(options).dtdNotation(this);
  26547. };
  26548. return XMLDTDNotation;
  26549. })(XMLNode);
  26550. }).call(this);
  26551. },{"./XMLNode":171}],166:[function(require,module,exports){
  26552. // Generated by CoffeeScript 1.12.7
  26553. (function() {
  26554. var XMLDeclaration, XMLNode, isObject,
  26555. 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; },
  26556. hasProp = {}.hasOwnProperty;
  26557. isObject = require('./Utility').isObject;
  26558. XMLNode = require('./XMLNode');
  26559. module.exports = XMLDeclaration = (function(superClass) {
  26560. extend(XMLDeclaration, superClass);
  26561. function XMLDeclaration(parent, version, encoding, standalone) {
  26562. var ref;
  26563. XMLDeclaration.__super__.constructor.call(this, parent);
  26564. if (isObject(version)) {
  26565. ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
  26566. }
  26567. if (!version) {
  26568. version = '1.0';
  26569. }
  26570. this.version = this.stringify.xmlVersion(version);
  26571. if (encoding != null) {
  26572. this.encoding = this.stringify.xmlEncoding(encoding);
  26573. }
  26574. if (standalone != null) {
  26575. this.standalone = this.stringify.xmlStandalone(standalone);
  26576. }
  26577. }
  26578. XMLDeclaration.prototype.toString = function(options) {
  26579. return this.options.writer.set(options).declaration(this);
  26580. };
  26581. return XMLDeclaration;
  26582. })(XMLNode);
  26583. }).call(this);
  26584. },{"./Utility":158,"./XMLNode":171}],167:[function(require,module,exports){
  26585. // Generated by CoffeeScript 1.12.7
  26586. (function() {
  26587. var XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNode, isObject,
  26588. 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; },
  26589. hasProp = {}.hasOwnProperty;
  26590. isObject = require('./Utility').isObject;
  26591. XMLNode = require('./XMLNode');
  26592. XMLDTDAttList = require('./XMLDTDAttList');
  26593. XMLDTDEntity = require('./XMLDTDEntity');
  26594. XMLDTDElement = require('./XMLDTDElement');
  26595. XMLDTDNotation = require('./XMLDTDNotation');
  26596. module.exports = XMLDocType = (function(superClass) {
  26597. extend(XMLDocType, superClass);
  26598. function XMLDocType(parent, pubID, sysID) {
  26599. var ref, ref1;
  26600. XMLDocType.__super__.constructor.call(this, parent);
  26601. this.name = "!DOCTYPE";
  26602. this.documentObject = parent;
  26603. if (isObject(pubID)) {
  26604. ref = pubID, pubID = ref.pubID, sysID = ref.sysID;
  26605. }
  26606. if (sysID == null) {
  26607. ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1];
  26608. }
  26609. if (pubID != null) {
  26610. this.pubID = this.stringify.dtdPubID(pubID);
  26611. }
  26612. if (sysID != null) {
  26613. this.sysID = this.stringify.dtdSysID(sysID);
  26614. }
  26615. }
  26616. XMLDocType.prototype.element = function(name, value) {
  26617. var child;
  26618. child = new XMLDTDElement(this, name, value);
  26619. this.children.push(child);
  26620. return this;
  26621. };
  26622. XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  26623. var child;
  26624. child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
  26625. this.children.push(child);
  26626. return this;
  26627. };
  26628. XMLDocType.prototype.entity = function(name, value) {
  26629. var child;
  26630. child = new XMLDTDEntity(this, false, name, value);
  26631. this.children.push(child);
  26632. return this;
  26633. };
  26634. XMLDocType.prototype.pEntity = function(name, value) {
  26635. var child;
  26636. child = new XMLDTDEntity(this, true, name, value);
  26637. this.children.push(child);
  26638. return this;
  26639. };
  26640. XMLDocType.prototype.notation = function(name, value) {
  26641. var child;
  26642. child = new XMLDTDNotation(this, name, value);
  26643. this.children.push(child);
  26644. return this;
  26645. };
  26646. XMLDocType.prototype.toString = function(options) {
  26647. return this.options.writer.set(options).docType(this);
  26648. };
  26649. XMLDocType.prototype.ele = function(name, value) {
  26650. return this.element(name, value);
  26651. };
  26652. XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  26653. return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
  26654. };
  26655. XMLDocType.prototype.ent = function(name, value) {
  26656. return this.entity(name, value);
  26657. };
  26658. XMLDocType.prototype.pent = function(name, value) {
  26659. return this.pEntity(name, value);
  26660. };
  26661. XMLDocType.prototype.not = function(name, value) {
  26662. return this.notation(name, value);
  26663. };
  26664. XMLDocType.prototype.up = function() {
  26665. return this.root() || this.documentObject;
  26666. };
  26667. return XMLDocType;
  26668. })(XMLNode);
  26669. }).call(this);
  26670. },{"./Utility":158,"./XMLDTDAttList":162,"./XMLDTDElement":163,"./XMLDTDEntity":164,"./XMLDTDNotation":165,"./XMLNode":171}],168:[function(require,module,exports){
  26671. // Generated by CoffeeScript 1.12.7
  26672. (function() {
  26673. var XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject,
  26674. 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; },
  26675. hasProp = {}.hasOwnProperty;
  26676. isPlainObject = require('./Utility').isPlainObject;
  26677. XMLNode = require('./XMLNode');
  26678. XMLStringifier = require('./XMLStringifier');
  26679. XMLStringWriter = require('./XMLStringWriter');
  26680. module.exports = XMLDocument = (function(superClass) {
  26681. extend(XMLDocument, superClass);
  26682. function XMLDocument(options) {
  26683. XMLDocument.__super__.constructor.call(this, null);
  26684. this.name = "?xml";
  26685. options || (options = {});
  26686. if (!options.writer) {
  26687. options.writer = new XMLStringWriter();
  26688. }
  26689. this.options = options;
  26690. this.stringify = new XMLStringifier(options);
  26691. this.isDocument = true;
  26692. }
  26693. XMLDocument.prototype.end = function(writer) {
  26694. var writerOptions;
  26695. if (!writer) {
  26696. writer = this.options.writer;
  26697. } else if (isPlainObject(writer)) {
  26698. writerOptions = writer;
  26699. writer = this.options.writer.set(writerOptions);
  26700. }
  26701. return writer.document(this);
  26702. };
  26703. XMLDocument.prototype.toString = function(options) {
  26704. return this.options.writer.set(options).document(this);
  26705. };
  26706. return XMLDocument;
  26707. })(XMLNode);
  26708. }).call(this);
  26709. },{"./Utility":158,"./XMLNode":171,"./XMLStringWriter":175,"./XMLStringifier":176}],169:[function(require,module,exports){
  26710. // Generated by CoffeeScript 1.12.7
  26711. (function() {
  26712. var XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref,
  26713. hasProp = {}.hasOwnProperty;
  26714. ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue;
  26715. XMLElement = require('./XMLElement');
  26716. XMLCData = require('./XMLCData');
  26717. XMLComment = require('./XMLComment');
  26718. XMLRaw = require('./XMLRaw');
  26719. XMLText = require('./XMLText');
  26720. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  26721. XMLDeclaration = require('./XMLDeclaration');
  26722. XMLDocType = require('./XMLDocType');
  26723. XMLDTDAttList = require('./XMLDTDAttList');
  26724. XMLDTDEntity = require('./XMLDTDEntity');
  26725. XMLDTDElement = require('./XMLDTDElement');
  26726. XMLDTDNotation = require('./XMLDTDNotation');
  26727. XMLAttribute = require('./XMLAttribute');
  26728. XMLStringifier = require('./XMLStringifier');
  26729. XMLStringWriter = require('./XMLStringWriter');
  26730. module.exports = XMLDocumentCB = (function() {
  26731. function XMLDocumentCB(options, onData, onEnd) {
  26732. var writerOptions;
  26733. this.name = "?xml";
  26734. options || (options = {});
  26735. if (!options.writer) {
  26736. options.writer = new XMLStringWriter(options);
  26737. } else if (isPlainObject(options.writer)) {
  26738. writerOptions = options.writer;
  26739. options.writer = new XMLStringWriter(writerOptions);
  26740. }
  26741. this.options = options;
  26742. this.writer = options.writer;
  26743. this.stringify = new XMLStringifier(options);
  26744. this.onDataCallback = onData || function() {};
  26745. this.onEndCallback = onEnd || function() {};
  26746. this.currentNode = null;
  26747. this.currentLevel = -1;
  26748. this.openTags = {};
  26749. this.documentStarted = false;
  26750. this.documentCompleted = false;
  26751. this.root = null;
  26752. }
  26753. XMLDocumentCB.prototype.node = function(name, attributes, text) {
  26754. var ref1;
  26755. if (name == null) {
  26756. throw new Error("Missing node name.");
  26757. }
  26758. if (this.root && this.currentLevel === -1) {
  26759. throw new Error("Document can only have one root node. " + this.debugInfo(name));
  26760. }
  26761. this.openCurrent();
  26762. name = getValue(name);
  26763. if (attributes == null) {
  26764. attributes = {};
  26765. }
  26766. attributes = getValue(attributes);
  26767. if (!isObject(attributes)) {
  26768. ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
  26769. }
  26770. this.currentNode = new XMLElement(this, name, attributes);
  26771. this.currentNode.children = false;
  26772. this.currentLevel++;
  26773. this.openTags[this.currentLevel] = this.currentNode;
  26774. if (text != null) {
  26775. this.text(text);
  26776. }
  26777. return this;
  26778. };
  26779. XMLDocumentCB.prototype.element = function(name, attributes, text) {
  26780. if (this.currentNode && this.currentNode instanceof XMLDocType) {
  26781. return this.dtdElement.apply(this, arguments);
  26782. } else {
  26783. return this.node(name, attributes, text);
  26784. }
  26785. };
  26786. XMLDocumentCB.prototype.attribute = function(name, value) {
  26787. var attName, attValue;
  26788. if (!this.currentNode || this.currentNode.children) {
  26789. throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name));
  26790. }
  26791. if (name != null) {
  26792. name = getValue(name);
  26793. }
  26794. if (isObject(name)) {
  26795. for (attName in name) {
  26796. if (!hasProp.call(name, attName)) continue;
  26797. attValue = name[attName];
  26798. this.attribute(attName, attValue);
  26799. }
  26800. } else {
  26801. if (isFunction(value)) {
  26802. value = value.apply();
  26803. }
  26804. if (!this.options.skipNullAttributes || (value != null)) {
  26805. this.currentNode.attributes[name] = new XMLAttribute(this, name, value);
  26806. }
  26807. }
  26808. return this;
  26809. };
  26810. XMLDocumentCB.prototype.text = function(value) {
  26811. var node;
  26812. this.openCurrent();
  26813. node = new XMLText(this, value);
  26814. this.onData(this.writer.text(node, this.currentLevel + 1), this.currentLevel + 1);
  26815. return this;
  26816. };
  26817. XMLDocumentCB.prototype.cdata = function(value) {
  26818. var node;
  26819. this.openCurrent();
  26820. node = new XMLCData(this, value);
  26821. this.onData(this.writer.cdata(node, this.currentLevel + 1), this.currentLevel + 1);
  26822. return this;
  26823. };
  26824. XMLDocumentCB.prototype.comment = function(value) {
  26825. var node;
  26826. this.openCurrent();
  26827. node = new XMLComment(this, value);
  26828. this.onData(this.writer.comment(node, this.currentLevel + 1), this.currentLevel + 1);
  26829. return this;
  26830. };
  26831. XMLDocumentCB.prototype.raw = function(value) {
  26832. var node;
  26833. this.openCurrent();
  26834. node = new XMLRaw(this, value);
  26835. this.onData(this.writer.raw(node, this.currentLevel + 1), this.currentLevel + 1);
  26836. return this;
  26837. };
  26838. XMLDocumentCB.prototype.instruction = function(target, value) {
  26839. var i, insTarget, insValue, len, node;
  26840. this.openCurrent();
  26841. if (target != null) {
  26842. target = getValue(target);
  26843. }
  26844. if (value != null) {
  26845. value = getValue(value);
  26846. }
  26847. if (Array.isArray(target)) {
  26848. for (i = 0, len = target.length; i < len; i++) {
  26849. insTarget = target[i];
  26850. this.instruction(insTarget);
  26851. }
  26852. } else if (isObject(target)) {
  26853. for (insTarget in target) {
  26854. if (!hasProp.call(target, insTarget)) continue;
  26855. insValue = target[insTarget];
  26856. this.instruction(insTarget, insValue);
  26857. }
  26858. } else {
  26859. if (isFunction(value)) {
  26860. value = value.apply();
  26861. }
  26862. node = new XMLProcessingInstruction(this, target, value);
  26863. this.onData(this.writer.processingInstruction(node, this.currentLevel + 1), this.currentLevel + 1);
  26864. }
  26865. return this;
  26866. };
  26867. XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) {
  26868. var node;
  26869. this.openCurrent();
  26870. if (this.documentStarted) {
  26871. throw new Error("declaration() must be the first node.");
  26872. }
  26873. node = new XMLDeclaration(this, version, encoding, standalone);
  26874. this.onData(this.writer.declaration(node, this.currentLevel + 1), this.currentLevel + 1);
  26875. return this;
  26876. };
  26877. XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) {
  26878. this.openCurrent();
  26879. if (root == null) {
  26880. throw new Error("Missing root node name.");
  26881. }
  26882. if (this.root) {
  26883. throw new Error("dtd() must come before the root node.");
  26884. }
  26885. this.currentNode = new XMLDocType(this, pubID, sysID);
  26886. this.currentNode.rootNodeName = root;
  26887. this.currentNode.children = false;
  26888. this.currentLevel++;
  26889. this.openTags[this.currentLevel] = this.currentNode;
  26890. return this;
  26891. };
  26892. XMLDocumentCB.prototype.dtdElement = function(name, value) {
  26893. var node;
  26894. this.openCurrent();
  26895. node = new XMLDTDElement(this, name, value);
  26896. this.onData(this.writer.dtdElement(node, this.currentLevel + 1), this.currentLevel + 1);
  26897. return this;
  26898. };
  26899. XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
  26900. var node;
  26901. this.openCurrent();
  26902. node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
  26903. this.onData(this.writer.dtdAttList(node, this.currentLevel + 1), this.currentLevel + 1);
  26904. return this;
  26905. };
  26906. XMLDocumentCB.prototype.entity = function(name, value) {
  26907. var node;
  26908. this.openCurrent();
  26909. node = new XMLDTDEntity(this, false, name, value);
  26910. this.onData(this.writer.dtdEntity(node, this.currentLevel + 1), this.currentLevel + 1);
  26911. return this;
  26912. };
  26913. XMLDocumentCB.prototype.pEntity = function(name, value) {
  26914. var node;
  26915. this.openCurrent();
  26916. node = new XMLDTDEntity(this, true, name, value);
  26917. this.onData(this.writer.dtdEntity(node, this.currentLevel + 1), this.currentLevel + 1);
  26918. return this;
  26919. };
  26920. XMLDocumentCB.prototype.notation = function(name, value) {
  26921. var node;
  26922. this.openCurrent();
  26923. node = new XMLDTDNotation(this, name, value);
  26924. this.onData(this.writer.dtdNotation(node, this.currentLevel + 1), this.currentLevel + 1);
  26925. return this;
  26926. };
  26927. XMLDocumentCB.prototype.up = function() {
  26928. if (this.currentLevel < 0) {
  26929. throw new Error("The document node has no parent.");
  26930. }
  26931. if (this.currentNode) {
  26932. if (this.currentNode.children) {
  26933. this.closeNode(this.currentNode);
  26934. } else {
  26935. this.openNode(this.currentNode);
  26936. }
  26937. this.currentNode = null;
  26938. } else {
  26939. this.closeNode(this.openTags[this.currentLevel]);
  26940. }
  26941. delete this.openTags[this.currentLevel];
  26942. this.currentLevel--;
  26943. return this;
  26944. };
  26945. XMLDocumentCB.prototype.end = function() {
  26946. while (this.currentLevel >= 0) {
  26947. this.up();
  26948. }
  26949. return this.onEnd();
  26950. };
  26951. XMLDocumentCB.prototype.openCurrent = function() {
  26952. if (this.currentNode) {
  26953. this.currentNode.children = true;
  26954. return this.openNode(this.currentNode);
  26955. }
  26956. };
  26957. XMLDocumentCB.prototype.openNode = function(node) {
  26958. if (!node.isOpen) {
  26959. if (!this.root && this.currentLevel === 0 && node instanceof XMLElement) {
  26960. this.root = node;
  26961. }
  26962. this.onData(this.writer.openNode(node, this.currentLevel), this.currentLevel);
  26963. return node.isOpen = true;
  26964. }
  26965. };
  26966. XMLDocumentCB.prototype.closeNode = function(node) {
  26967. if (!node.isClosed) {
  26968. this.onData(this.writer.closeNode(node, this.currentLevel), this.currentLevel);
  26969. return node.isClosed = true;
  26970. }
  26971. };
  26972. XMLDocumentCB.prototype.onData = function(chunk, level) {
  26973. this.documentStarted = true;
  26974. return this.onDataCallback(chunk, level + 1);
  26975. };
  26976. XMLDocumentCB.prototype.onEnd = function() {
  26977. this.documentCompleted = true;
  26978. return this.onEndCallback();
  26979. };
  26980. XMLDocumentCB.prototype.debugInfo = function(name) {
  26981. if (name == null) {
  26982. return "";
  26983. } else {
  26984. return "node: <" + name + ">";
  26985. }
  26986. };
  26987. XMLDocumentCB.prototype.ele = function() {
  26988. return this.element.apply(this, arguments);
  26989. };
  26990. XMLDocumentCB.prototype.nod = function(name, attributes, text) {
  26991. return this.node(name, attributes, text);
  26992. };
  26993. XMLDocumentCB.prototype.txt = function(value) {
  26994. return this.text(value);
  26995. };
  26996. XMLDocumentCB.prototype.dat = function(value) {
  26997. return this.cdata(value);
  26998. };
  26999. XMLDocumentCB.prototype.com = function(value) {
  27000. return this.comment(value);
  27001. };
  27002. XMLDocumentCB.prototype.ins = function(target, value) {
  27003. return this.instruction(target, value);
  27004. };
  27005. XMLDocumentCB.prototype.dec = function(version, encoding, standalone) {
  27006. return this.declaration(version, encoding, standalone);
  27007. };
  27008. XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) {
  27009. return this.doctype(root, pubID, sysID);
  27010. };
  27011. XMLDocumentCB.prototype.e = function(name, attributes, text) {
  27012. return this.element(name, attributes, text);
  27013. };
  27014. XMLDocumentCB.prototype.n = function(name, attributes, text) {
  27015. return this.node(name, attributes, text);
  27016. };
  27017. XMLDocumentCB.prototype.t = function(value) {
  27018. return this.text(value);
  27019. };
  27020. XMLDocumentCB.prototype.d = function(value) {
  27021. return this.cdata(value);
  27022. };
  27023. XMLDocumentCB.prototype.c = function(value) {
  27024. return this.comment(value);
  27025. };
  27026. XMLDocumentCB.prototype.r = function(value) {
  27027. return this.raw(value);
  27028. };
  27029. XMLDocumentCB.prototype.i = function(target, value) {
  27030. return this.instruction(target, value);
  27031. };
  27032. XMLDocumentCB.prototype.att = function() {
  27033. if (this.currentNode && this.currentNode instanceof XMLDocType) {
  27034. return this.attList.apply(this, arguments);
  27035. } else {
  27036. return this.attribute.apply(this, arguments);
  27037. }
  27038. };
  27039. XMLDocumentCB.prototype.a = function() {
  27040. if (this.currentNode && this.currentNode instanceof XMLDocType) {
  27041. return this.attList.apply(this, arguments);
  27042. } else {
  27043. return this.attribute.apply(this, arguments);
  27044. }
  27045. };
  27046. XMLDocumentCB.prototype.ent = function(name, value) {
  27047. return this.entity(name, value);
  27048. };
  27049. XMLDocumentCB.prototype.pent = function(name, value) {
  27050. return this.pEntity(name, value);
  27051. };
  27052. XMLDocumentCB.prototype.not = function(name, value) {
  27053. return this.notation(name, value);
  27054. };
  27055. return XMLDocumentCB;
  27056. })();
  27057. }).call(this);
  27058. },{"./Utility":158,"./XMLAttribute":159,"./XMLCData":160,"./XMLComment":161,"./XMLDTDAttList":162,"./XMLDTDElement":163,"./XMLDTDEntity":164,"./XMLDTDNotation":165,"./XMLDeclaration":166,"./XMLDocType":167,"./XMLElement":170,"./XMLProcessingInstruction":172,"./XMLRaw":173,"./XMLStringWriter":175,"./XMLStringifier":176,"./XMLText":177}],170:[function(require,module,exports){
  27059. // Generated by CoffeeScript 1.12.7
  27060. (function() {
  27061. var XMLAttribute, XMLElement, XMLNode, getValue, isFunction, isObject, ref,
  27062. 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; },
  27063. hasProp = {}.hasOwnProperty;
  27064. ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue;
  27065. XMLNode = require('./XMLNode');
  27066. XMLAttribute = require('./XMLAttribute');
  27067. module.exports = XMLElement = (function(superClass) {
  27068. extend(XMLElement, superClass);
  27069. function XMLElement(parent, name, attributes) {
  27070. XMLElement.__super__.constructor.call(this, parent);
  27071. if (name == null) {
  27072. throw new Error("Missing element name. " + this.debugInfo());
  27073. }
  27074. this.name = this.stringify.eleName(name);
  27075. this.attributes = {};
  27076. if (attributes != null) {
  27077. this.attribute(attributes);
  27078. }
  27079. if (parent.isDocument) {
  27080. this.isRoot = true;
  27081. this.documentObject = parent;
  27082. parent.rootObject = this;
  27083. }
  27084. }
  27085. XMLElement.prototype.clone = function() {
  27086. var att, attName, clonedSelf, ref1;
  27087. clonedSelf = Object.create(this);
  27088. if (clonedSelf.isRoot) {
  27089. clonedSelf.documentObject = null;
  27090. }
  27091. clonedSelf.attributes = {};
  27092. ref1 = this.attributes;
  27093. for (attName in ref1) {
  27094. if (!hasProp.call(ref1, attName)) continue;
  27095. att = ref1[attName];
  27096. clonedSelf.attributes[attName] = att.clone();
  27097. }
  27098. clonedSelf.children = [];
  27099. this.children.forEach(function(child) {
  27100. var clonedChild;
  27101. clonedChild = child.clone();
  27102. clonedChild.parent = clonedSelf;
  27103. return clonedSelf.children.push(clonedChild);
  27104. });
  27105. return clonedSelf;
  27106. };
  27107. XMLElement.prototype.attribute = function(name, value) {
  27108. var attName, attValue;
  27109. if (name != null) {
  27110. name = getValue(name);
  27111. }
  27112. if (isObject(name)) {
  27113. for (attName in name) {
  27114. if (!hasProp.call(name, attName)) continue;
  27115. attValue = name[attName];
  27116. this.attribute(attName, attValue);
  27117. }
  27118. } else {
  27119. if (isFunction(value)) {
  27120. value = value.apply();
  27121. }
  27122. if (!this.options.skipNullAttributes || (value != null)) {
  27123. this.attributes[name] = new XMLAttribute(this, name, value);
  27124. }
  27125. }
  27126. return this;
  27127. };
  27128. XMLElement.prototype.removeAttribute = function(name) {
  27129. var attName, i, len;
  27130. if (name == null) {
  27131. throw new Error("Missing attribute name. " + this.debugInfo());
  27132. }
  27133. name = getValue(name);
  27134. if (Array.isArray(name)) {
  27135. for (i = 0, len = name.length; i < len; i++) {
  27136. attName = name[i];
  27137. delete this.attributes[attName];
  27138. }
  27139. } else {
  27140. delete this.attributes[name];
  27141. }
  27142. return this;
  27143. };
  27144. XMLElement.prototype.toString = function(options) {
  27145. return this.options.writer.set(options).element(this);
  27146. };
  27147. XMLElement.prototype.att = function(name, value) {
  27148. return this.attribute(name, value);
  27149. };
  27150. XMLElement.prototype.a = function(name, value) {
  27151. return this.attribute(name, value);
  27152. };
  27153. return XMLElement;
  27154. })(XMLNode);
  27155. }).call(this);
  27156. },{"./Utility":158,"./XMLAttribute":159,"./XMLNode":171}],171:[function(require,module,exports){
  27157. // Generated by CoffeeScript 1.12.7
  27158. (function() {
  27159. var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref,
  27160. hasProp = {}.hasOwnProperty;
  27161. ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isEmpty = ref.isEmpty, getValue = ref.getValue;
  27162. XMLElement = null;
  27163. XMLCData = null;
  27164. XMLComment = null;
  27165. XMLDeclaration = null;
  27166. XMLDocType = null;
  27167. XMLRaw = null;
  27168. XMLText = null;
  27169. XMLProcessingInstruction = null;
  27170. module.exports = XMLNode = (function() {
  27171. function XMLNode(parent) {
  27172. this.parent = parent;
  27173. if (this.parent) {
  27174. this.options = this.parent.options;
  27175. this.stringify = this.parent.stringify;
  27176. }
  27177. this.children = [];
  27178. if (!XMLElement) {
  27179. XMLElement = require('./XMLElement');
  27180. XMLCData = require('./XMLCData');
  27181. XMLComment = require('./XMLComment');
  27182. XMLDeclaration = require('./XMLDeclaration');
  27183. XMLDocType = require('./XMLDocType');
  27184. XMLRaw = require('./XMLRaw');
  27185. XMLText = require('./XMLText');
  27186. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  27187. }
  27188. }
  27189. XMLNode.prototype.element = function(name, attributes, text) {
  27190. var childNode, item, j, k, key, lastChild, len, len1, ref1, val;
  27191. lastChild = null;
  27192. if (attributes == null) {
  27193. attributes = {};
  27194. }
  27195. attributes = getValue(attributes);
  27196. if (!isObject(attributes)) {
  27197. ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
  27198. }
  27199. if (name != null) {
  27200. name = getValue(name);
  27201. }
  27202. if (Array.isArray(name)) {
  27203. for (j = 0, len = name.length; j < len; j++) {
  27204. item = name[j];
  27205. lastChild = this.element(item);
  27206. }
  27207. } else if (isFunction(name)) {
  27208. lastChild = this.element(name.apply());
  27209. } else if (isObject(name)) {
  27210. for (key in name) {
  27211. if (!hasProp.call(name, key)) continue;
  27212. val = name[key];
  27213. if (isFunction(val)) {
  27214. val = val.apply();
  27215. }
  27216. if ((isObject(val)) && (isEmpty(val))) {
  27217. val = null;
  27218. }
  27219. if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
  27220. lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
  27221. } else if (!this.options.separateArrayItems && Array.isArray(val)) {
  27222. for (k = 0, len1 = val.length; k < len1; k++) {
  27223. item = val[k];
  27224. childNode = {};
  27225. childNode[key] = item;
  27226. lastChild = this.element(childNode);
  27227. }
  27228. } else if (isObject(val)) {
  27229. lastChild = this.element(key);
  27230. lastChild.element(val);
  27231. } else {
  27232. lastChild = this.element(key, val);
  27233. }
  27234. }
  27235. } else {
  27236. if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
  27237. lastChild = this.text(text);
  27238. } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
  27239. lastChild = this.cdata(text);
  27240. } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
  27241. lastChild = this.comment(text);
  27242. } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
  27243. lastChild = this.raw(text);
  27244. } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) {
  27245. lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text);
  27246. } else {
  27247. lastChild = this.node(name, attributes, text);
  27248. }
  27249. }
  27250. if (lastChild == null) {
  27251. throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo());
  27252. }
  27253. return lastChild;
  27254. };
  27255. XMLNode.prototype.insertBefore = function(name, attributes, text) {
  27256. var child, i, removed;
  27257. if (this.isRoot) {
  27258. throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
  27259. }
  27260. i = this.parent.children.indexOf(this);
  27261. removed = this.parent.children.splice(i);
  27262. child = this.parent.element(name, attributes, text);
  27263. Array.prototype.push.apply(this.parent.children, removed);
  27264. return child;
  27265. };
  27266. XMLNode.prototype.insertAfter = function(name, attributes, text) {
  27267. var child, i, removed;
  27268. if (this.isRoot) {
  27269. throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
  27270. }
  27271. i = this.parent.children.indexOf(this);
  27272. removed = this.parent.children.splice(i + 1);
  27273. child = this.parent.element(name, attributes, text);
  27274. Array.prototype.push.apply(this.parent.children, removed);
  27275. return child;
  27276. };
  27277. XMLNode.prototype.remove = function() {
  27278. var i, ref1;
  27279. if (this.isRoot) {
  27280. throw new Error("Cannot remove the root element. " + this.debugInfo());
  27281. }
  27282. i = this.parent.children.indexOf(this);
  27283. [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref1 = [])), ref1;
  27284. return this.parent;
  27285. };
  27286. XMLNode.prototype.node = function(name, attributes, text) {
  27287. var child, ref1;
  27288. if (name != null) {
  27289. name = getValue(name);
  27290. }
  27291. attributes || (attributes = {});
  27292. attributes = getValue(attributes);
  27293. if (!isObject(attributes)) {
  27294. ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
  27295. }
  27296. child = new XMLElement(this, name, attributes);
  27297. if (text != null) {
  27298. child.text(text);
  27299. }
  27300. this.children.push(child);
  27301. return child;
  27302. };
  27303. XMLNode.prototype.text = function(value) {
  27304. var child;
  27305. child = new XMLText(this, value);
  27306. this.children.push(child);
  27307. return this;
  27308. };
  27309. XMLNode.prototype.cdata = function(value) {
  27310. var child;
  27311. child = new XMLCData(this, value);
  27312. this.children.push(child);
  27313. return this;
  27314. };
  27315. XMLNode.prototype.comment = function(value) {
  27316. var child;
  27317. child = new XMLComment(this, value);
  27318. this.children.push(child);
  27319. return this;
  27320. };
  27321. XMLNode.prototype.commentBefore = function(value) {
  27322. var child, i, removed;
  27323. i = this.parent.children.indexOf(this);
  27324. removed = this.parent.children.splice(i);
  27325. child = this.parent.comment(value);
  27326. Array.prototype.push.apply(this.parent.children, removed);
  27327. return this;
  27328. };
  27329. XMLNode.prototype.commentAfter = function(value) {
  27330. var child, i, removed;
  27331. i = this.parent.children.indexOf(this);
  27332. removed = this.parent.children.splice(i + 1);
  27333. child = this.parent.comment(value);
  27334. Array.prototype.push.apply(this.parent.children, removed);
  27335. return this;
  27336. };
  27337. XMLNode.prototype.raw = function(value) {
  27338. var child;
  27339. child = new XMLRaw(this, value);
  27340. this.children.push(child);
  27341. return this;
  27342. };
  27343. XMLNode.prototype.instruction = function(target, value) {
  27344. var insTarget, insValue, instruction, j, len;
  27345. if (target != null) {
  27346. target = getValue(target);
  27347. }
  27348. if (value != null) {
  27349. value = getValue(value);
  27350. }
  27351. if (Array.isArray(target)) {
  27352. for (j = 0, len = target.length; j < len; j++) {
  27353. insTarget = target[j];
  27354. this.instruction(insTarget);
  27355. }
  27356. } else if (isObject(target)) {
  27357. for (insTarget in target) {
  27358. if (!hasProp.call(target, insTarget)) continue;
  27359. insValue = target[insTarget];
  27360. this.instruction(insTarget, insValue);
  27361. }
  27362. } else {
  27363. if (isFunction(value)) {
  27364. value = value.apply();
  27365. }
  27366. instruction = new XMLProcessingInstruction(this, target, value);
  27367. this.children.push(instruction);
  27368. }
  27369. return this;
  27370. };
  27371. XMLNode.prototype.instructionBefore = function(target, value) {
  27372. var child, i, removed;
  27373. i = this.parent.children.indexOf(this);
  27374. removed = this.parent.children.splice(i);
  27375. child = this.parent.instruction(target, value);
  27376. Array.prototype.push.apply(this.parent.children, removed);
  27377. return this;
  27378. };
  27379. XMLNode.prototype.instructionAfter = function(target, value) {
  27380. var child, i, removed;
  27381. i = this.parent.children.indexOf(this);
  27382. removed = this.parent.children.splice(i + 1);
  27383. child = this.parent.instruction(target, value);
  27384. Array.prototype.push.apply(this.parent.children, removed);
  27385. return this;
  27386. };
  27387. XMLNode.prototype.declaration = function(version, encoding, standalone) {
  27388. var doc, xmldec;
  27389. doc = this.document();
  27390. xmldec = new XMLDeclaration(doc, version, encoding, standalone);
  27391. if (doc.children[0] instanceof XMLDeclaration) {
  27392. doc.children[0] = xmldec;
  27393. } else {
  27394. doc.children.unshift(xmldec);
  27395. }
  27396. return doc.root() || doc;
  27397. };
  27398. XMLNode.prototype.doctype = function(pubID, sysID) {
  27399. var child, doc, doctype, i, j, k, len, len1, ref1, ref2;
  27400. doc = this.document();
  27401. doctype = new XMLDocType(doc, pubID, sysID);
  27402. ref1 = doc.children;
  27403. for (i = j = 0, len = ref1.length; j < len; i = ++j) {
  27404. child = ref1[i];
  27405. if (child instanceof XMLDocType) {
  27406. doc.children[i] = doctype;
  27407. return doctype;
  27408. }
  27409. }
  27410. ref2 = doc.children;
  27411. for (i = k = 0, len1 = ref2.length; k < len1; i = ++k) {
  27412. child = ref2[i];
  27413. if (child.isRoot) {
  27414. doc.children.splice(i, 0, doctype);
  27415. return doctype;
  27416. }
  27417. }
  27418. doc.children.push(doctype);
  27419. return doctype;
  27420. };
  27421. XMLNode.prototype.up = function() {
  27422. if (this.isRoot) {
  27423. throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
  27424. }
  27425. return this.parent;
  27426. };
  27427. XMLNode.prototype.root = function() {
  27428. var node;
  27429. node = this;
  27430. while (node) {
  27431. if (node.isDocument) {
  27432. return node.rootObject;
  27433. } else if (node.isRoot) {
  27434. return node;
  27435. } else {
  27436. node = node.parent;
  27437. }
  27438. }
  27439. };
  27440. XMLNode.prototype.document = function() {
  27441. var node;
  27442. node = this;
  27443. while (node) {
  27444. if (node.isDocument) {
  27445. return node;
  27446. } else {
  27447. node = node.parent;
  27448. }
  27449. }
  27450. };
  27451. XMLNode.prototype.end = function(options) {
  27452. return this.document().end(options);
  27453. };
  27454. XMLNode.prototype.prev = function() {
  27455. var i;
  27456. i = this.parent.children.indexOf(this);
  27457. if (i < 1) {
  27458. throw new Error("Already at the first node. " + this.debugInfo());
  27459. }
  27460. return this.parent.children[i - 1];
  27461. };
  27462. XMLNode.prototype.next = function() {
  27463. var i;
  27464. i = this.parent.children.indexOf(this);
  27465. if (i === -1 || i === this.parent.children.length - 1) {
  27466. throw new Error("Already at the last node. " + this.debugInfo());
  27467. }
  27468. return this.parent.children[i + 1];
  27469. };
  27470. XMLNode.prototype.importDocument = function(doc) {
  27471. var clonedRoot;
  27472. clonedRoot = doc.root().clone();
  27473. clonedRoot.parent = this;
  27474. clonedRoot.isRoot = false;
  27475. this.children.push(clonedRoot);
  27476. return this;
  27477. };
  27478. XMLNode.prototype.debugInfo = function(name) {
  27479. var ref1, ref2;
  27480. name = name || this.name;
  27481. if ((name == null) && !((ref1 = this.parent) != null ? ref1.name : void 0)) {
  27482. return "";
  27483. } else if (name == null) {
  27484. return "parent: <" + this.parent.name + ">";
  27485. } else if (!((ref2 = this.parent) != null ? ref2.name : void 0)) {
  27486. return "node: <" + name + ">";
  27487. } else {
  27488. return "node: <" + name + ">, parent: <" + this.parent.name + ">";
  27489. }
  27490. };
  27491. XMLNode.prototype.ele = function(name, attributes, text) {
  27492. return this.element(name, attributes, text);
  27493. };
  27494. XMLNode.prototype.nod = function(name, attributes, text) {
  27495. return this.node(name, attributes, text);
  27496. };
  27497. XMLNode.prototype.txt = function(value) {
  27498. return this.text(value);
  27499. };
  27500. XMLNode.prototype.dat = function(value) {
  27501. return this.cdata(value);
  27502. };
  27503. XMLNode.prototype.com = function(value) {
  27504. return this.comment(value);
  27505. };
  27506. XMLNode.prototype.ins = function(target, value) {
  27507. return this.instruction(target, value);
  27508. };
  27509. XMLNode.prototype.doc = function() {
  27510. return this.document();
  27511. };
  27512. XMLNode.prototype.dec = function(version, encoding, standalone) {
  27513. return this.declaration(version, encoding, standalone);
  27514. };
  27515. XMLNode.prototype.dtd = function(pubID, sysID) {
  27516. return this.doctype(pubID, sysID);
  27517. };
  27518. XMLNode.prototype.e = function(name, attributes, text) {
  27519. return this.element(name, attributes, text);
  27520. };
  27521. XMLNode.prototype.n = function(name, attributes, text) {
  27522. return this.node(name, attributes, text);
  27523. };
  27524. XMLNode.prototype.t = function(value) {
  27525. return this.text(value);
  27526. };
  27527. XMLNode.prototype.d = function(value) {
  27528. return this.cdata(value);
  27529. };
  27530. XMLNode.prototype.c = function(value) {
  27531. return this.comment(value);
  27532. };
  27533. XMLNode.prototype.r = function(value) {
  27534. return this.raw(value);
  27535. };
  27536. XMLNode.prototype.i = function(target, value) {
  27537. return this.instruction(target, value);
  27538. };
  27539. XMLNode.prototype.u = function() {
  27540. return this.up();
  27541. };
  27542. XMLNode.prototype.importXMLBuilder = function(doc) {
  27543. return this.importDocument(doc);
  27544. };
  27545. return XMLNode;
  27546. })();
  27547. }).call(this);
  27548. },{"./Utility":158,"./XMLCData":160,"./XMLComment":161,"./XMLDeclaration":166,"./XMLDocType":167,"./XMLElement":170,"./XMLProcessingInstruction":172,"./XMLRaw":173,"./XMLText":177}],172:[function(require,module,exports){
  27549. // Generated by CoffeeScript 1.12.7
  27550. (function() {
  27551. var XMLNode, XMLProcessingInstruction,
  27552. 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; },
  27553. hasProp = {}.hasOwnProperty;
  27554. XMLNode = require('./XMLNode');
  27555. module.exports = XMLProcessingInstruction = (function(superClass) {
  27556. extend(XMLProcessingInstruction, superClass);
  27557. function XMLProcessingInstruction(parent, target, value) {
  27558. XMLProcessingInstruction.__super__.constructor.call(this, parent);
  27559. if (target == null) {
  27560. throw new Error("Missing instruction target. " + this.debugInfo());
  27561. }
  27562. this.target = this.stringify.insTarget(target);
  27563. if (value) {
  27564. this.value = this.stringify.insValue(value);
  27565. }
  27566. }
  27567. XMLProcessingInstruction.prototype.clone = function() {
  27568. return Object.create(this);
  27569. };
  27570. XMLProcessingInstruction.prototype.toString = function(options) {
  27571. return this.options.writer.set(options).processingInstruction(this);
  27572. };
  27573. return XMLProcessingInstruction;
  27574. })(XMLNode);
  27575. }).call(this);
  27576. },{"./XMLNode":171}],173:[function(require,module,exports){
  27577. // Generated by CoffeeScript 1.12.7
  27578. (function() {
  27579. var XMLNode, XMLRaw,
  27580. 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; },
  27581. hasProp = {}.hasOwnProperty;
  27582. XMLNode = require('./XMLNode');
  27583. module.exports = XMLRaw = (function(superClass) {
  27584. extend(XMLRaw, superClass);
  27585. function XMLRaw(parent, text) {
  27586. XMLRaw.__super__.constructor.call(this, parent);
  27587. if (text == null) {
  27588. throw new Error("Missing raw text. " + this.debugInfo());
  27589. }
  27590. this.value = this.stringify.raw(text);
  27591. }
  27592. XMLRaw.prototype.clone = function() {
  27593. return Object.create(this);
  27594. };
  27595. XMLRaw.prototype.toString = function(options) {
  27596. return this.options.writer.set(options).raw(this);
  27597. };
  27598. return XMLRaw;
  27599. })(XMLNode);
  27600. }).call(this);
  27601. },{"./XMLNode":171}],174:[function(require,module,exports){
  27602. // Generated by CoffeeScript 1.12.7
  27603. (function() {
  27604. var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStreamWriter, XMLText, XMLWriterBase,
  27605. 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; },
  27606. hasProp = {}.hasOwnProperty;
  27607. XMLDeclaration = require('./XMLDeclaration');
  27608. XMLDocType = require('./XMLDocType');
  27609. XMLCData = require('./XMLCData');
  27610. XMLComment = require('./XMLComment');
  27611. XMLElement = require('./XMLElement');
  27612. XMLRaw = require('./XMLRaw');
  27613. XMLText = require('./XMLText');
  27614. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  27615. XMLDTDAttList = require('./XMLDTDAttList');
  27616. XMLDTDElement = require('./XMLDTDElement');
  27617. XMLDTDEntity = require('./XMLDTDEntity');
  27618. XMLDTDNotation = require('./XMLDTDNotation');
  27619. XMLWriterBase = require('./XMLWriterBase');
  27620. module.exports = XMLStreamWriter = (function(superClass) {
  27621. extend(XMLStreamWriter, superClass);
  27622. function XMLStreamWriter(stream, options) {
  27623. XMLStreamWriter.__super__.constructor.call(this, options);
  27624. this.stream = stream;
  27625. }
  27626. XMLStreamWriter.prototype.document = function(doc) {
  27627. var child, i, j, len, len1, ref, ref1, results;
  27628. ref = doc.children;
  27629. for (i = 0, len = ref.length; i < len; i++) {
  27630. child = ref[i];
  27631. child.isLastRootNode = false;
  27632. }
  27633. doc.children[doc.children.length - 1].isLastRootNode = true;
  27634. ref1 = doc.children;
  27635. results = [];
  27636. for (j = 0, len1 = ref1.length; j < len1; j++) {
  27637. child = ref1[j];
  27638. switch (false) {
  27639. case !(child instanceof XMLDeclaration):
  27640. results.push(this.declaration(child));
  27641. break;
  27642. case !(child instanceof XMLDocType):
  27643. results.push(this.docType(child));
  27644. break;
  27645. case !(child instanceof XMLComment):
  27646. results.push(this.comment(child));
  27647. break;
  27648. case !(child instanceof XMLProcessingInstruction):
  27649. results.push(this.processingInstruction(child));
  27650. break;
  27651. default:
  27652. results.push(this.element(child));
  27653. }
  27654. }
  27655. return results;
  27656. };
  27657. XMLStreamWriter.prototype.attribute = function(att) {
  27658. return this.stream.write(' ' + att.name + '="' + att.value + '"');
  27659. };
  27660. XMLStreamWriter.prototype.cdata = function(node, level) {
  27661. return this.stream.write(this.space(level) + '<![CDATA[' + node.text + ']]>' + this.endline(node));
  27662. };
  27663. XMLStreamWriter.prototype.comment = function(node, level) {
  27664. return this.stream.write(this.space(level) + '<!-- ' + node.text + ' -->' + this.endline(node));
  27665. };
  27666. XMLStreamWriter.prototype.declaration = function(node, level) {
  27667. this.stream.write(this.space(level));
  27668. this.stream.write('<?xml version="' + node.version + '"');
  27669. if (node.encoding != null) {
  27670. this.stream.write(' encoding="' + node.encoding + '"');
  27671. }
  27672. if (node.standalone != null) {
  27673. this.stream.write(' standalone="' + node.standalone + '"');
  27674. }
  27675. this.stream.write(this.spacebeforeslash + '?>');
  27676. return this.stream.write(this.endline(node));
  27677. };
  27678. XMLStreamWriter.prototype.docType = function(node, level) {
  27679. var child, i, len, ref;
  27680. level || (level = 0);
  27681. this.stream.write(this.space(level));
  27682. this.stream.write('<!DOCTYPE ' + node.root().name);
  27683. if (node.pubID && node.sysID) {
  27684. this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
  27685. } else if (node.sysID) {
  27686. this.stream.write(' SYSTEM "' + node.sysID + '"');
  27687. }
  27688. if (node.children.length > 0) {
  27689. this.stream.write(' [');
  27690. this.stream.write(this.endline(node));
  27691. ref = node.children;
  27692. for (i = 0, len = ref.length; i < len; i++) {
  27693. child = ref[i];
  27694. switch (false) {
  27695. case !(child instanceof XMLDTDAttList):
  27696. this.dtdAttList(child, level + 1);
  27697. break;
  27698. case !(child instanceof XMLDTDElement):
  27699. this.dtdElement(child, level + 1);
  27700. break;
  27701. case !(child instanceof XMLDTDEntity):
  27702. this.dtdEntity(child, level + 1);
  27703. break;
  27704. case !(child instanceof XMLDTDNotation):
  27705. this.dtdNotation(child, level + 1);
  27706. break;
  27707. case !(child instanceof XMLCData):
  27708. this.cdata(child, level + 1);
  27709. break;
  27710. case !(child instanceof XMLComment):
  27711. this.comment(child, level + 1);
  27712. break;
  27713. case !(child instanceof XMLProcessingInstruction):
  27714. this.processingInstruction(child, level + 1);
  27715. break;
  27716. default:
  27717. throw new Error("Unknown DTD node type: " + child.constructor.name);
  27718. }
  27719. }
  27720. this.stream.write(']');
  27721. }
  27722. this.stream.write(this.spacebeforeslash + '>');
  27723. return this.stream.write(this.endline(node));
  27724. };
  27725. XMLStreamWriter.prototype.element = function(node, level) {
  27726. var att, child, i, len, name, ref, ref1, space;
  27727. level || (level = 0);
  27728. space = this.space(level);
  27729. this.stream.write(space + '<' + node.name);
  27730. ref = node.attributes;
  27731. for (name in ref) {
  27732. if (!hasProp.call(ref, name)) continue;
  27733. att = ref[name];
  27734. this.attribute(att);
  27735. }
  27736. if (node.children.length === 0 || node.children.every(function(e) {
  27737. return e.value === '';
  27738. })) {
  27739. if (this.allowEmpty) {
  27740. this.stream.write('></' + node.name + '>');
  27741. } else {
  27742. this.stream.write(this.spacebeforeslash + '/>');
  27743. }
  27744. } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
  27745. this.stream.write('>');
  27746. this.stream.write(node.children[0].value);
  27747. this.stream.write('</' + node.name + '>');
  27748. } else {
  27749. this.stream.write('>' + this.newline);
  27750. ref1 = node.children;
  27751. for (i = 0, len = ref1.length; i < len; i++) {
  27752. child = ref1[i];
  27753. switch (false) {
  27754. case !(child instanceof XMLCData):
  27755. this.cdata(child, level + 1);
  27756. break;
  27757. case !(child instanceof XMLComment):
  27758. this.comment(child, level + 1);
  27759. break;
  27760. case !(child instanceof XMLElement):
  27761. this.element(child, level + 1);
  27762. break;
  27763. case !(child instanceof XMLRaw):
  27764. this.raw(child, level + 1);
  27765. break;
  27766. case !(child instanceof XMLText):
  27767. this.text(child, level + 1);
  27768. break;
  27769. case !(child instanceof XMLProcessingInstruction):
  27770. this.processingInstruction(child, level + 1);
  27771. break;
  27772. default:
  27773. throw new Error("Unknown XML node type: " + child.constructor.name);
  27774. }
  27775. }
  27776. this.stream.write(space + '</' + node.name + '>');
  27777. }
  27778. return this.stream.write(this.endline(node));
  27779. };
  27780. XMLStreamWriter.prototype.processingInstruction = function(node, level) {
  27781. this.stream.write(this.space(level) + '<?' + node.target);
  27782. if (node.value) {
  27783. this.stream.write(' ' + node.value);
  27784. }
  27785. return this.stream.write(this.spacebeforeslash + '?>' + this.endline(node));
  27786. };
  27787. XMLStreamWriter.prototype.raw = function(node, level) {
  27788. return this.stream.write(this.space(level) + node.value + this.endline(node));
  27789. };
  27790. XMLStreamWriter.prototype.text = function(node, level) {
  27791. return this.stream.write(this.space(level) + node.value + this.endline(node));
  27792. };
  27793. XMLStreamWriter.prototype.dtdAttList = function(node, level) {
  27794. this.stream.write(this.space(level) + '<!ATTLIST ' + node.elementName + ' ' + node.attributeName + ' ' + node.attributeType);
  27795. if (node.defaultValueType !== '#DEFAULT') {
  27796. this.stream.write(' ' + node.defaultValueType);
  27797. }
  27798. if (node.defaultValue) {
  27799. this.stream.write(' "' + node.defaultValue + '"');
  27800. }
  27801. return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
  27802. };
  27803. XMLStreamWriter.prototype.dtdElement = function(node, level) {
  27804. this.stream.write(this.space(level) + '<!ELEMENT ' + node.name + ' ' + node.value);
  27805. return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
  27806. };
  27807. XMLStreamWriter.prototype.dtdEntity = function(node, level) {
  27808. this.stream.write(this.space(level) + '<!ENTITY');
  27809. if (node.pe) {
  27810. this.stream.write(' %');
  27811. }
  27812. this.stream.write(' ' + node.name);
  27813. if (node.value) {
  27814. this.stream.write(' "' + node.value + '"');
  27815. } else {
  27816. if (node.pubID && node.sysID) {
  27817. this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
  27818. } else if (node.sysID) {
  27819. this.stream.write(' SYSTEM "' + node.sysID + '"');
  27820. }
  27821. if (node.nData) {
  27822. this.stream.write(' NDATA ' + node.nData);
  27823. }
  27824. }
  27825. return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
  27826. };
  27827. XMLStreamWriter.prototype.dtdNotation = function(node, level) {
  27828. this.stream.write(this.space(level) + '<!NOTATION ' + node.name);
  27829. if (node.pubID && node.sysID) {
  27830. this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
  27831. } else if (node.pubID) {
  27832. this.stream.write(' PUBLIC "' + node.pubID + '"');
  27833. } else if (node.sysID) {
  27834. this.stream.write(' SYSTEM "' + node.sysID + '"');
  27835. }
  27836. return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
  27837. };
  27838. XMLStreamWriter.prototype.endline = function(node) {
  27839. if (!node.isLastRootNode) {
  27840. return this.newline;
  27841. } else {
  27842. return '';
  27843. }
  27844. };
  27845. return XMLStreamWriter;
  27846. })(XMLWriterBase);
  27847. }).call(this);
  27848. },{"./XMLCData":160,"./XMLComment":161,"./XMLDTDAttList":162,"./XMLDTDElement":163,"./XMLDTDEntity":164,"./XMLDTDNotation":165,"./XMLDeclaration":166,"./XMLDocType":167,"./XMLElement":170,"./XMLProcessingInstruction":172,"./XMLRaw":173,"./XMLText":177,"./XMLWriterBase":178}],175:[function(require,module,exports){
  27849. // Generated by CoffeeScript 1.12.7
  27850. (function() {
  27851. var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLText, XMLWriterBase,
  27852. 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; },
  27853. hasProp = {}.hasOwnProperty;
  27854. XMLDeclaration = require('./XMLDeclaration');
  27855. XMLDocType = require('./XMLDocType');
  27856. XMLCData = require('./XMLCData');
  27857. XMLComment = require('./XMLComment');
  27858. XMLElement = require('./XMLElement');
  27859. XMLRaw = require('./XMLRaw');
  27860. XMLText = require('./XMLText');
  27861. XMLProcessingInstruction = require('./XMLProcessingInstruction');
  27862. XMLDTDAttList = require('./XMLDTDAttList');
  27863. XMLDTDElement = require('./XMLDTDElement');
  27864. XMLDTDEntity = require('./XMLDTDEntity');
  27865. XMLDTDNotation = require('./XMLDTDNotation');
  27866. XMLWriterBase = require('./XMLWriterBase');
  27867. module.exports = XMLStringWriter = (function(superClass) {
  27868. extend(XMLStringWriter, superClass);
  27869. function XMLStringWriter(options) {
  27870. XMLStringWriter.__super__.constructor.call(this, options);
  27871. }
  27872. XMLStringWriter.prototype.document = function(doc) {
  27873. var child, i, len, r, ref;
  27874. this.textispresent = false;
  27875. r = '';
  27876. ref = doc.children;
  27877. for (i = 0, len = ref.length; i < len; i++) {
  27878. child = ref[i];
  27879. r += (function() {
  27880. switch (false) {
  27881. case !(child instanceof XMLDeclaration):
  27882. return this.declaration(child);
  27883. case !(child instanceof XMLDocType):
  27884. return this.docType(child);
  27885. case !(child instanceof XMLComment):
  27886. return this.comment(child);
  27887. case !(child instanceof XMLProcessingInstruction):
  27888. return this.processingInstruction(child);
  27889. default:
  27890. return this.element(child, 0);
  27891. }
  27892. }).call(this);
  27893. }
  27894. if (this.pretty && r.slice(-this.newline.length) === this.newline) {
  27895. r = r.slice(0, -this.newline.length);
  27896. }
  27897. return r;
  27898. };
  27899. XMLStringWriter.prototype.attribute = function(att) {
  27900. return ' ' + att.name + '="' + att.value + '"';
  27901. };
  27902. XMLStringWriter.prototype.cdata = function(node, level) {
  27903. return this.space(level) + '<![CDATA[' + node.text + ']]>' + this.newline;
  27904. };
  27905. XMLStringWriter.prototype.comment = function(node, level) {
  27906. return this.space(level) + '<!-- ' + node.text + ' -->' + this.newline;
  27907. };
  27908. XMLStringWriter.prototype.declaration = function(node, level) {
  27909. var r;
  27910. r = this.space(level);
  27911. r += '<?xml version="' + node.version + '"';
  27912. if (node.encoding != null) {
  27913. r += ' encoding="' + node.encoding + '"';
  27914. }
  27915. if (node.standalone != null) {
  27916. r += ' standalone="' + node.standalone + '"';
  27917. }
  27918. r += this.spacebeforeslash + '?>';
  27919. r += this.newline;
  27920. return r;
  27921. };
  27922. XMLStringWriter.prototype.docType = function(node, level) {
  27923. var child, i, len, r, ref;
  27924. level || (level = 0);
  27925. r = this.space(level);
  27926. r += '<!DOCTYPE ' + node.root().name;
  27927. if (node.pubID && node.sysID) {
  27928. r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  27929. } else if (node.sysID) {
  27930. r += ' SYSTEM "' + node.sysID + '"';
  27931. }
  27932. if (node.children.length > 0) {
  27933. r += ' [';
  27934. r += this.newline;
  27935. ref = node.children;
  27936. for (i = 0, len = ref.length; i < len; i++) {
  27937. child = ref[i];
  27938. r += (function() {
  27939. switch (false) {
  27940. case !(child instanceof XMLDTDAttList):
  27941. return this.dtdAttList(child, level + 1);
  27942. case !(child instanceof XMLDTDElement):
  27943. return this.dtdElement(child, level + 1);
  27944. case !(child instanceof XMLDTDEntity):
  27945. return this.dtdEntity(child, level + 1);
  27946. case !(child instanceof XMLDTDNotation):
  27947. return this.dtdNotation(child, level + 1);
  27948. case !(child instanceof XMLCData):
  27949. return this.cdata(child, level + 1);
  27950. case !(child instanceof XMLComment):
  27951. return this.comment(child, level + 1);
  27952. case !(child instanceof XMLProcessingInstruction):
  27953. return this.processingInstruction(child, level + 1);
  27954. default:
  27955. throw new Error("Unknown DTD node type: " + child.constructor.name);
  27956. }
  27957. }).call(this);
  27958. }
  27959. r += ']';
  27960. }
  27961. r += this.spacebeforeslash + '>';
  27962. r += this.newline;
  27963. return r;
  27964. };
  27965. XMLStringWriter.prototype.element = function(node, level) {
  27966. var att, child, i, j, len, len1, name, r, ref, ref1, ref2, space, textispresentwasset;
  27967. level || (level = 0);
  27968. textispresentwasset = false;
  27969. if (this.textispresent) {
  27970. this.newline = '';
  27971. this.pretty = false;
  27972. } else {
  27973. this.newline = this.newlinedefault;
  27974. this.pretty = this.prettydefault;
  27975. }
  27976. space = this.space(level);
  27977. r = '';
  27978. r += space + '<' + node.name;
  27979. ref = node.attributes;
  27980. for (name in ref) {
  27981. if (!hasProp.call(ref, name)) continue;
  27982. att = ref[name];
  27983. r += this.attribute(att);
  27984. }
  27985. if (node.children.length === 0 || node.children.every(function(e) {
  27986. return e.value === '';
  27987. })) {
  27988. if (this.allowEmpty) {
  27989. r += '></' + node.name + '>' + this.newline;
  27990. } else {
  27991. r += this.spacebeforeslash + '/>' + this.newline;
  27992. }
  27993. } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
  27994. r += '>';
  27995. r += node.children[0].value;
  27996. r += '</' + node.name + '>' + this.newline;
  27997. } else {
  27998. if (this.dontprettytextnodes) {
  27999. ref1 = node.children;
  28000. for (i = 0, len = ref1.length; i < len; i++) {
  28001. child = ref1[i];
  28002. if (child.value != null) {
  28003. this.textispresent++;
  28004. textispresentwasset = true;
  28005. break;
  28006. }
  28007. }
  28008. }
  28009. if (this.textispresent) {
  28010. this.newline = '';
  28011. this.pretty = false;
  28012. space = this.space(level);
  28013. }
  28014. r += '>' + this.newline;
  28015. ref2 = node.children;
  28016. for (j = 0, len1 = ref2.length; j < len1; j++) {
  28017. child = ref2[j];
  28018. r += (function() {
  28019. switch (false) {
  28020. case !(child instanceof XMLCData):
  28021. return this.cdata(child, level + 1);
  28022. case !(child instanceof XMLComment):
  28023. return this.comment(child, level + 1);
  28024. case !(child instanceof XMLElement):
  28025. return this.element(child, level + 1);
  28026. case !(child instanceof XMLRaw):
  28027. return this.raw(child, level + 1);
  28028. case !(child instanceof XMLText):
  28029. return this.text(child, level + 1);
  28030. case !(child instanceof XMLProcessingInstruction):
  28031. return this.processingInstruction(child, level + 1);
  28032. default:
  28033. throw new Error("Unknown XML node type: " + child.constructor.name);
  28034. }
  28035. }).call(this);
  28036. }
  28037. if (textispresentwasset) {
  28038. this.textispresent--;
  28039. }
  28040. if (!this.textispresent) {
  28041. this.newline = this.newlinedefault;
  28042. this.pretty = this.prettydefault;
  28043. }
  28044. r += space + '</' + node.name + '>' + this.newline;
  28045. }
  28046. return r;
  28047. };
  28048. XMLStringWriter.prototype.processingInstruction = function(node, level) {
  28049. var r;
  28050. r = this.space(level) + '<?' + node.target;
  28051. if (node.value) {
  28052. r += ' ' + node.value;
  28053. }
  28054. r += this.spacebeforeslash + '?>' + this.newline;
  28055. return r;
  28056. };
  28057. XMLStringWriter.prototype.raw = function(node, level) {
  28058. return this.space(level) + node.value + this.newline;
  28059. };
  28060. XMLStringWriter.prototype.text = function(node, level) {
  28061. return this.space(level) + node.value + this.newline;
  28062. };
  28063. XMLStringWriter.prototype.dtdAttList = function(node, level) {
  28064. var r;
  28065. r = this.space(level) + '<!ATTLIST ' + node.elementName + ' ' + node.attributeName + ' ' + node.attributeType;
  28066. if (node.defaultValueType !== '#DEFAULT') {
  28067. r += ' ' + node.defaultValueType;
  28068. }
  28069. if (node.defaultValue) {
  28070. r += ' "' + node.defaultValue + '"';
  28071. }
  28072. r += this.spacebeforeslash + '>' + this.newline;
  28073. return r;
  28074. };
  28075. XMLStringWriter.prototype.dtdElement = function(node, level) {
  28076. return this.space(level) + '<!ELEMENT ' + node.name + ' ' + node.value + this.spacebeforeslash + '>' + this.newline;
  28077. };
  28078. XMLStringWriter.prototype.dtdEntity = function(node, level) {
  28079. var r;
  28080. r = this.space(level) + '<!ENTITY';
  28081. if (node.pe) {
  28082. r += ' %';
  28083. }
  28084. r += ' ' + node.name;
  28085. if (node.value) {
  28086. r += ' "' + node.value + '"';
  28087. } else {
  28088. if (node.pubID && node.sysID) {
  28089. r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  28090. } else if (node.sysID) {
  28091. r += ' SYSTEM "' + node.sysID + '"';
  28092. }
  28093. if (node.nData) {
  28094. r += ' NDATA ' + node.nData;
  28095. }
  28096. }
  28097. r += this.spacebeforeslash + '>' + this.newline;
  28098. return r;
  28099. };
  28100. XMLStringWriter.prototype.dtdNotation = function(node, level) {
  28101. var r;
  28102. r = this.space(level) + '<!NOTATION ' + node.name;
  28103. if (node.pubID && node.sysID) {
  28104. r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  28105. } else if (node.pubID) {
  28106. r += ' PUBLIC "' + node.pubID + '"';
  28107. } else if (node.sysID) {
  28108. r += ' SYSTEM "' + node.sysID + '"';
  28109. }
  28110. r += this.spacebeforeslash + '>' + this.newline;
  28111. return r;
  28112. };
  28113. XMLStringWriter.prototype.openNode = function(node, level) {
  28114. var att, name, r, ref;
  28115. level || (level = 0);
  28116. if (node instanceof XMLElement) {
  28117. r = this.space(level) + '<' + node.name;
  28118. ref = node.attributes;
  28119. for (name in ref) {
  28120. if (!hasProp.call(ref, name)) continue;
  28121. att = ref[name];
  28122. r += this.attribute(att);
  28123. }
  28124. r += (node.children ? '>' : '/>') + this.newline;
  28125. return r;
  28126. } else {
  28127. r = this.space(level) + '<!DOCTYPE ' + node.rootNodeName;
  28128. if (node.pubID && node.sysID) {
  28129. r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
  28130. } else if (node.sysID) {
  28131. r += ' SYSTEM "' + node.sysID + '"';
  28132. }
  28133. r += (node.children ? ' [' : '>') + this.newline;
  28134. return r;
  28135. }
  28136. };
  28137. XMLStringWriter.prototype.closeNode = function(node, level) {
  28138. level || (level = 0);
  28139. switch (false) {
  28140. case !(node instanceof XMLElement):
  28141. return this.space(level) + '</' + node.name + '>' + this.newline;
  28142. case !(node instanceof XMLDocType):
  28143. return this.space(level) + ']>' + this.newline;
  28144. }
  28145. };
  28146. return XMLStringWriter;
  28147. })(XMLWriterBase);
  28148. }).call(this);
  28149. },{"./XMLCData":160,"./XMLComment":161,"./XMLDTDAttList":162,"./XMLDTDElement":163,"./XMLDTDEntity":164,"./XMLDTDNotation":165,"./XMLDeclaration":166,"./XMLDocType":167,"./XMLElement":170,"./XMLProcessingInstruction":172,"./XMLRaw":173,"./XMLText":177,"./XMLWriterBase":178}],176:[function(require,module,exports){
  28150. // Generated by CoffeeScript 1.12.7
  28151. (function() {
  28152. var XMLStringifier,
  28153. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  28154. hasProp = {}.hasOwnProperty;
  28155. module.exports = XMLStringifier = (function() {
  28156. function XMLStringifier(options) {
  28157. this.assertLegalChar = bind(this.assertLegalChar, this);
  28158. var key, ref, value;
  28159. options || (options = {});
  28160. this.noDoubleEncoding = options.noDoubleEncoding;
  28161. ref = options.stringify || {};
  28162. for (key in ref) {
  28163. if (!hasProp.call(ref, key)) continue;
  28164. value = ref[key];
  28165. this[key] = value;
  28166. }
  28167. }
  28168. XMLStringifier.prototype.eleName = function(val) {
  28169. val = '' + val || '';
  28170. return this.assertLegalChar(val);
  28171. };
  28172. XMLStringifier.prototype.eleText = function(val) {
  28173. val = '' + val || '';
  28174. return this.assertLegalChar(this.elEscape(val));
  28175. };
  28176. XMLStringifier.prototype.cdata = function(val) {
  28177. val = '' + val || '';
  28178. val = val.replace(']]>', ']]]]><![CDATA[>');
  28179. return this.assertLegalChar(val);
  28180. };
  28181. XMLStringifier.prototype.comment = function(val) {
  28182. val = '' + val || '';
  28183. if (val.match(/--/)) {
  28184. throw new Error("Comment text cannot contain double-hypen: " + val);
  28185. }
  28186. return this.assertLegalChar(val);
  28187. };
  28188. XMLStringifier.prototype.raw = function(val) {
  28189. return '' + val || '';
  28190. };
  28191. XMLStringifier.prototype.attName = function(val) {
  28192. return val = '' + val || '';
  28193. };
  28194. XMLStringifier.prototype.attValue = function(val) {
  28195. val = '' + val || '';
  28196. return this.attEscape(val);
  28197. };
  28198. XMLStringifier.prototype.insTarget = function(val) {
  28199. return '' + val || '';
  28200. };
  28201. XMLStringifier.prototype.insValue = function(val) {
  28202. val = '' + val || '';
  28203. if (val.match(/\?>/)) {
  28204. throw new Error("Invalid processing instruction value: " + val);
  28205. }
  28206. return val;
  28207. };
  28208. XMLStringifier.prototype.xmlVersion = function(val) {
  28209. val = '' + val || '';
  28210. if (!val.match(/1\.[0-9]+/)) {
  28211. throw new Error("Invalid version number: " + val);
  28212. }
  28213. return val;
  28214. };
  28215. XMLStringifier.prototype.xmlEncoding = function(val) {
  28216. val = '' + val || '';
  28217. if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) {
  28218. throw new Error("Invalid encoding: " + val);
  28219. }
  28220. return val;
  28221. };
  28222. XMLStringifier.prototype.xmlStandalone = function(val) {
  28223. if (val) {
  28224. return "yes";
  28225. } else {
  28226. return "no";
  28227. }
  28228. };
  28229. XMLStringifier.prototype.dtdPubID = function(val) {
  28230. return '' + val || '';
  28231. };
  28232. XMLStringifier.prototype.dtdSysID = function(val) {
  28233. return '' + val || '';
  28234. };
  28235. XMLStringifier.prototype.dtdElementValue = function(val) {
  28236. return '' + val || '';
  28237. };
  28238. XMLStringifier.prototype.dtdAttType = function(val) {
  28239. return '' + val || '';
  28240. };
  28241. XMLStringifier.prototype.dtdAttDefault = function(val) {
  28242. if (val != null) {
  28243. return '' + val || '';
  28244. } else {
  28245. return val;
  28246. }
  28247. };
  28248. XMLStringifier.prototype.dtdEntityValue = function(val) {
  28249. return '' + val || '';
  28250. };
  28251. XMLStringifier.prototype.dtdNData = function(val) {
  28252. return '' + val || '';
  28253. };
  28254. XMLStringifier.prototype.convertAttKey = '@';
  28255. XMLStringifier.prototype.convertPIKey = '?';
  28256. XMLStringifier.prototype.convertTextKey = '#text';
  28257. XMLStringifier.prototype.convertCDataKey = '#cdata';
  28258. XMLStringifier.prototype.convertCommentKey = '#comment';
  28259. XMLStringifier.prototype.convertRawKey = '#raw';
  28260. XMLStringifier.prototype.assertLegalChar = function(str) {
  28261. var res;
  28262. res = str.match(/[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/);
  28263. if (res) {
  28264. throw new Error("Invalid character in string: " + str + " at index " + res.index);
  28265. }
  28266. return str;
  28267. };
  28268. XMLStringifier.prototype.elEscape = function(str) {
  28269. var ampregex;
  28270. ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
  28271. return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
  28272. };
  28273. XMLStringifier.prototype.attEscape = function(str) {
  28274. var ampregex;
  28275. ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
  28276. return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
  28277. };
  28278. return XMLStringifier;
  28279. })();
  28280. }).call(this);
  28281. },{}],177:[function(require,module,exports){
  28282. // Generated by CoffeeScript 1.12.7
  28283. (function() {
  28284. var XMLNode, XMLText,
  28285. 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; },
  28286. hasProp = {}.hasOwnProperty;
  28287. XMLNode = require('./XMLNode');
  28288. module.exports = XMLText = (function(superClass) {
  28289. extend(XMLText, superClass);
  28290. function XMLText(parent, text) {
  28291. XMLText.__super__.constructor.call(this, parent);
  28292. if (text == null) {
  28293. throw new Error("Missing element text. " + this.debugInfo());
  28294. }
  28295. this.value = this.stringify.eleText(text);
  28296. }
  28297. XMLText.prototype.clone = function() {
  28298. return Object.create(this);
  28299. };
  28300. XMLText.prototype.toString = function(options) {
  28301. return this.options.writer.set(options).text(this);
  28302. };
  28303. return XMLText;
  28304. })(XMLNode);
  28305. }).call(this);
  28306. },{"./XMLNode":171}],178:[function(require,module,exports){
  28307. // Generated by CoffeeScript 1.12.7
  28308. (function() {
  28309. var XMLWriterBase,
  28310. hasProp = {}.hasOwnProperty;
  28311. module.exports = XMLWriterBase = (function() {
  28312. function XMLWriterBase(options) {
  28313. var key, ref, ref1, ref2, ref3, ref4, ref5, ref6, value;
  28314. options || (options = {});
  28315. this.pretty = options.pretty || false;
  28316. this.allowEmpty = (ref = options.allowEmpty) != null ? ref : false;
  28317. if (this.pretty) {
  28318. this.indent = (ref1 = options.indent) != null ? ref1 : ' ';
  28319. this.newline = (ref2 = options.newline) != null ? ref2 : '\n';
  28320. this.offset = (ref3 = options.offset) != null ? ref3 : 0;
  28321. this.dontprettytextnodes = (ref4 = options.dontprettytextnodes) != null ? ref4 : 0;
  28322. } else {
  28323. this.indent = '';
  28324. this.newline = '';
  28325. this.offset = 0;
  28326. this.dontprettytextnodes = 0;
  28327. }
  28328. this.spacebeforeslash = (ref5 = options.spacebeforeslash) != null ? ref5 : '';
  28329. if (this.spacebeforeslash === true) {
  28330. this.spacebeforeslash = ' ';
  28331. }
  28332. this.newlinedefault = this.newline;
  28333. this.prettydefault = this.pretty;
  28334. ref6 = options.writer || {};
  28335. for (key in ref6) {
  28336. if (!hasProp.call(ref6, key)) continue;
  28337. value = ref6[key];
  28338. this[key] = value;
  28339. }
  28340. }
  28341. XMLWriterBase.prototype.set = function(options) {
  28342. var key, ref, value;
  28343. options || (options = {});
  28344. if ("pretty" in options) {
  28345. this.pretty = options.pretty;
  28346. }
  28347. if ("allowEmpty" in options) {
  28348. this.allowEmpty = options.allowEmpty;
  28349. }
  28350. if (this.pretty) {
  28351. this.indent = "indent" in options ? options.indent : ' ';
  28352. this.newline = "newline" in options ? options.newline : '\n';
  28353. this.offset = "offset" in options ? options.offset : 0;
  28354. this.dontprettytextnodes = "dontprettytextnodes" in options ? options.dontprettytextnodes : 0;
  28355. } else {
  28356. this.indent = '';
  28357. this.newline = '';
  28358. this.offset = 0;
  28359. this.dontprettytextnodes = 0;
  28360. }
  28361. this.spacebeforeslash = "spacebeforeslash" in options ? options.spacebeforeslash : '';
  28362. if (this.spacebeforeslash === true) {
  28363. this.spacebeforeslash = ' ';
  28364. }
  28365. this.newlinedefault = this.newline;
  28366. this.prettydefault = this.pretty;
  28367. ref = options.writer || {};
  28368. for (key in ref) {
  28369. if (!hasProp.call(ref, key)) continue;
  28370. value = ref[key];
  28371. this[key] = value;
  28372. }
  28373. return this;
  28374. };
  28375. XMLWriterBase.prototype.space = function(level) {
  28376. var indent;
  28377. if (this.pretty) {
  28378. indent = (level || 0) + this.offset + 1;
  28379. if (indent > 0) {
  28380. return new Array(indent).join(this.indent);
  28381. } else {
  28382. return '';
  28383. }
  28384. } else {
  28385. return '';
  28386. }
  28387. };
  28388. return XMLWriterBase;
  28389. })();
  28390. }).call(this);
  28391. },{}],179:[function(require,module,exports){
  28392. // Generated by CoffeeScript 1.12.7
  28393. (function() {
  28394. var XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref;
  28395. ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction;
  28396. XMLDocument = require('./XMLDocument');
  28397. XMLDocumentCB = require('./XMLDocumentCB');
  28398. XMLStringWriter = require('./XMLStringWriter');
  28399. XMLStreamWriter = require('./XMLStreamWriter');
  28400. module.exports.create = function(name, xmldec, doctype, options) {
  28401. var doc, root;
  28402. if (name == null) {
  28403. throw new Error("Root element needs a name.");
  28404. }
  28405. options = assign({}, xmldec, doctype, options);
  28406. doc = new XMLDocument(options);
  28407. root = doc.element(name);
  28408. if (!options.headless) {
  28409. doc.declaration(options);
  28410. if ((options.pubID != null) || (options.sysID != null)) {
  28411. doc.doctype(options);
  28412. }
  28413. }
  28414. return root;
  28415. };
  28416. module.exports.begin = function(options, onData, onEnd) {
  28417. var ref1;
  28418. if (isFunction(options)) {
  28419. ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];
  28420. options = {};
  28421. }
  28422. if (onData) {
  28423. return new XMLDocumentCB(options, onData, onEnd);
  28424. } else {
  28425. return new XMLDocument(options);
  28426. }
  28427. };
  28428. module.exports.stringWriter = function(options) {
  28429. return new XMLStringWriter(options);
  28430. };
  28431. module.exports.streamWriter = function(stream, options) {
  28432. return new XMLStreamWriter(stream, options);
  28433. };
  28434. }).call(this);
  28435. },{"./Utility":158,"./XMLDocument":168,"./XMLDocumentCB":169,"./XMLStreamWriter":174,"./XMLStringWriter":175}]},{},[21])(21)
  28436. });