123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625 |
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: BSD-3-Clause
- //
- // Module: [email protected]
- // License: ISC
- //
- // Module: [email protected]
- // License: ISC
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT or GPLv3
- //
- // Module: [email protected]
- // License: BSD
- //
- // Module: [email protected]
- // License: BSD-2-Clause
- //
- // Module: [email protected]
- // License: BSD
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: ISC
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- // Module: [email protected]
- // License: MIT
- //
- (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){
- var promises = require("../../lib/promises");
- exports.Files = Files;
- function Files() {
- function read(uri) {
- return promises.reject(new Error("could not open external image: '" + uri + "'\ncannot open linked files from a web browser"));
- }
-
- return {
- read: read
- };
- }
- },{"../../lib/promises":23}],2:[function(require,module,exports){
- var promises = require("../lib/promises");
- var zipfile = require("../lib/zipfile");
- exports.openZip = openZip;
- function openZip(options) {
- if (options.arrayBuffer) {
- return promises.resolve(zipfile.openArrayBuffer(options.arrayBuffer));
- } else {
- return promises.reject(new Error("Could not find file in options"));
- }
- }
- },{"../lib/promises":23,"../lib/zipfile":38}],3:[function(require,module,exports){
- var _ = require("underscore");
- var promises = require("./promises");
- var documents = require("./documents");
- var htmlPaths = require("./styles/html-paths");
- var results = require("./results");
- var images = require("./images");
- var Html = require("./html");
- var writers = require("./writers");
- exports.DocumentConverter = DocumentConverter;
- function DocumentConverter(options) {
- return {
- convertToHtml: function(element) {
- var comments = _.indexBy(
- element.type === documents.types.document ? element.comments : [],
- "commentId"
- );
- var conversion = new DocumentConversion(options, comments);
- return conversion.convertToHtml(element);
- }
- };
- }
- function DocumentConversion(options, comments) {
- var noteNumber = 1;
-
- var noteReferences = [];
-
- var referencedComments = [];
-
- options = _.extend({ignoreEmptyParagraphs: true}, options);
- var idPrefix = options.idPrefix === undefined ? "" : options.idPrefix;
- var ignoreEmptyParagraphs = options.ignoreEmptyParagraphs;
-
- var defaultParagraphStyle = htmlPaths.topLevelElement("p");
-
- var styleMap = options.styleMap || [];
-
- function convertToHtml(document) {
- var messages = [];
-
- var html = elementToHtml(document, messages, {});
-
- var deferredNodes = [];
- walkHtml(html, function(node) {
- if (node.type === "deferred") {
- deferredNodes.push(node);
- }
- });
- var deferredValues = {};
- return promises.mapSeries(deferredNodes, function(deferred) {
- return deferred.value().then(function(value) {
- deferredValues[deferred.id] = value;
- });
- }).then(function() {
- function replaceDeferred(nodes) {
- return flatMap(nodes, function(node) {
- if (node.type === "deferred") {
- return deferredValues[node.id];
- } else if (node.children) {
- return [
- _.extend({}, node, {
- children: replaceDeferred(node.children)
- })
- ];
- } else {
- return [node];
- }
- });
- }
- var writer = writers.writer({
- prettyPrint: options.prettyPrint,
- outputFormat: options.outputFormat
- });
- Html.write(writer, Html.simplify(replaceDeferred(html)));
- return new results.Result(writer.asString(), messages);
- });
- }
-
- function convertElements(elements, messages, options) {
- return flatMap(elements, function(element) {
- return elementToHtml(element, messages, options);
- });
- }
- function elementToHtml(element, messages, options) {
- if (!options) {
- throw new Error("options not set");
- }
- var handler = elementConverters[element.type];
- if (handler) {
- return handler(element, messages, options);
- } else {
- return [];
- }
- }
-
- function convertParagraph(element, messages, options) {
- return htmlPathForParagraph(element, messages).wrap(function() {
- var content = convertElements(element.children, messages, options);
- if (ignoreEmptyParagraphs) {
- return content;
- } else {
- return [Html.forceWrite].concat(content);
- }
- });
- }
-
- function htmlPathForParagraph(element, messages) {
- var style = findStyle(element);
-
- if (style) {
- return style.to;
- } else {
- if (element.styleId) {
- messages.push(unrecognisedStyleWarning("paragraph", element));
- }
- return defaultParagraphStyle;
- }
- }
-
- function convertRun(run, messages, options) {
- var nodes = function() {
- return convertElements(run.children, messages, options);
- };
- var paths = [];
- if (run.isSmallCaps) {
- paths.push(findHtmlPathForRunProperty("smallCaps"));
- }
- if (run.isStrikethrough) {
- paths.push(findHtmlPathForRunProperty("strikethrough", "s"));
- }
- if (run.isUnderline) {
- paths.push(findHtmlPathForRunProperty("underline"));
- }
- if (run.verticalAlignment === documents.verticalAlignment.subscript) {
- paths.push(htmlPaths.element("sub", {}, {fresh: false}));
- }
- if (run.verticalAlignment === documents.verticalAlignment.superscript) {
- paths.push(htmlPaths.element("sup", {}, {fresh: false}));
- }
- if (run.isItalic) {
- paths.push(findHtmlPathForRunProperty("italic", "em"));
- }
- if (run.isBold) {
- paths.push(findHtmlPathForRunProperty("bold", "strong"));
- }
- var stylePath = htmlPaths.empty;
- var style = findStyle(run);
- if (style) {
- stylePath = style.to;
- } else if (run.styleId) {
- messages.push(unrecognisedStyleWarning("run", run));
- }
- paths.push(stylePath);
-
- paths.forEach(function(path) {
- nodes = path.wrap.bind(path, nodes);
- });
-
- return nodes();
- }
-
- function findHtmlPathForRunProperty(elementType, defaultTagName) {
- var path = findHtmlPath({type: elementType});
- if (path) {
- return path;
- } else if (defaultTagName) {
- return htmlPaths.element(defaultTagName, {}, {fresh: false});
- } else {
- return htmlPaths.empty;
- }
- }
-
- function findHtmlPath(element, defaultPath) {
- var style = findStyle(element);
- return style ? style.to : defaultPath;
- }
-
- function findStyle(element) {
- for (var i = 0; i < styleMap.length; i++) {
- if (styleMap[i].from.matches(element)) {
- return styleMap[i];
- }
- }
- }
-
- function recoveringConvertImage(convertImage) {
- return function(image, messages) {
- return promises.attempt(function() {
- return convertImage(image, messages);
- }).caught(function(error) {
- messages.push(results.error(error));
- return [];
- });
- };
- }
- function noteHtmlId(note) {
- return referentHtmlId(note.noteType, note.noteId);
- }
-
- function noteRefHtmlId(note) {
- return referenceHtmlId(note.noteType, note.noteId);
- }
-
- function referentHtmlId(referenceType, referenceId) {
- return htmlId(referenceType + "-" + referenceId);
- }
-
- function referenceHtmlId(referenceType, referenceId) {
- return htmlId(referenceType + "-ref-" + referenceId);
- }
-
- function htmlId(suffix) {
- return idPrefix + suffix;
- }
-
- var defaultTablePath = htmlPaths.elements([
- htmlPaths.element("table", {}, {fresh: true})
- ]);
- function convertTable(element, messages, options) {
- return findHtmlPath(element, defaultTablePath).wrap(function() {
- return convertTableChildren(element, messages, options);
- });
- }
- function convertTableChildren(element, messages, options) {
- var bodyIndex = _.findIndex(element.children, function(child) {
- return !child.type === documents.types.tableRow || !child.isHeader;
- });
- if (bodyIndex === -1) {
- bodyIndex = element.children.length;
- }
- var children;
- if (bodyIndex === 0) {
- children = convertElements(
- element.children,
- messages,
- _.extend({}, options, {isTableHeader: false})
- );
- } else {
- var headRows = convertElements(
- element.children.slice(0, bodyIndex),
- messages,
- _.extend({}, options, {isTableHeader: true})
- );
- var bodyRows = convertElements(
- element.children.slice(bodyIndex),
- messages,
- _.extend({}, options, {isTableHeader: false})
- );
- children = [
- Html.freshElement("thead", {}, headRows),
- Html.freshElement("tbody", {}, bodyRows)
- ];
- }
- return [Html.forceWrite].concat(children);
- }
-
- function convertTableRow(element, messages, options) {
- return wrapChildrenInFreshElement(element, "tr", messages, options);
- }
-
- function convertTableCell(element, messages, options) {
- var tagName = options.isTableHeader ? "th" : "td";
- var children = convertElements(element.children, messages, options);
- var attributes = {};
- if (element.colSpan !== 1) {
- attributes.colspan = element.colSpan.toString();
- }
- if (element.rowSpan !== 1) {
- attributes.rowspan = element.rowSpan.toString();
- }
-
- return [
- Html.freshElement(tagName, attributes, [Html.forceWrite].concat(children))
- ];
- }
-
- function convertCommentReference(reference, messages, options) {
- return findHtmlPath(reference, htmlPaths.ignore).wrap(function() {
- var comment = comments[reference.commentId];
- var count = referencedComments.length + 1;
- var label = "[" + commentAuthorLabel(comment) + count + "]";
- referencedComments.push({label: label, comment: comment});
- // TODO: remove duplication with note references
- return [
- Html.freshElement("a", {
- href: "#" + referentHtmlId("comment", reference.commentId),
- id: referenceHtmlId("comment", reference.commentId)
- }, [Html.text(label)])
- ];
- });
- }
-
- function convertComment(referencedComment, messages, options) {
- // TODO: remove duplication with note references
-
- var label = referencedComment.label;
- var comment = referencedComment.comment;
- var body = convertElements(comment.body, messages, options).concat([
- Html.nonFreshElement("p", {}, [
- Html.text(" "),
- Html.freshElement("a", {"href": "#" + referenceHtmlId("comment", comment.commentId)}, [
- Html.text("↑")
- ])
- ])
- ]);
-
- return [
- Html.freshElement(
- "dt",
- {"id": referentHtmlId("comment", comment.commentId)},
- [Html.text("Comment " + label)]
- ),
- Html.freshElement("dd", {}, body)
- ];
- }
-
- function convertBreak(element, messages, options) {
- return htmlPathForBreak(element).wrap(function() {
- return [];
- });
- }
-
- function htmlPathForBreak(element) {
- var style = findStyle(element);
- if (style) {
- return style.to;
- } else if (element.breakType === "line") {
- return htmlPaths.topLevelElement("br");
- } else {
- return htmlPaths.empty;
- }
- }
-
- function wrapChildrenInFreshElement(element, wrapElementName, messages, options) {
- var children = convertElements(element.children, messages, options);
- return [
- Html.freshElement(wrapElementName, {}, [Html.forceWrite].concat(children))
- ];
- }
- var elementConverters = {
- "document": function(document, messages, options) {
- var children = convertElements(document.children, messages, options);
- var notes = noteReferences.map(function(noteReference) {
- return document.notes.resolve(noteReference);
- });
- var notesNodes = convertElements(notes, messages, options);
- return children.concat([
- Html.freshElement("ol", {}, notesNodes),
- Html.freshElement("dl", {}, flatMap(referencedComments, function(referencedComment) {
- return convertComment(referencedComment, messages, options);
- }))
- ]);
- },
- "paragraph": convertParagraph,
- "run": convertRun,
- "text": function(element, messages, options) {
- return [Html.text(element.value)];
- },
- "tab": function(element, messages, options) {
- return [Html.text("\t")];
- },
- "hyperlink": function(element, messages, options) {
- var href = element.anchor ? "#" + htmlId(element.anchor) : element.href;
- var attributes = {href: href};
- if (element.targetFrame != null) {
- attributes.target = element.targetFrame;
- }
- var children = convertElements(element.children, messages, options);
- return [Html.freshElement("a", attributes, children)];
- },
- "bookmarkStart": function(element, messages, options) {
- var anchor = Html.freshElement("a", {
- id: htmlId(element.name)
- }, [Html.forceWrite]);
- return [anchor];
- },
- "noteReference": function(element, messages, options) {
- noteReferences.push(element);
- var anchor = Html.freshElement("a", {
- href: "#" + noteHtmlId(element),
- id: noteRefHtmlId(element)
- }, [Html.text("[" + (noteNumber++) + "]")]);
-
- return [Html.freshElement("sup", {}, [anchor])];
- },
- "note": function(element, messages, options) {
- var children = convertElements(element.body, messages, options);
- var backLink = Html.elementWithTag(htmlPaths.element("p", {}, {fresh: false}), [
- Html.text(" "),
- Html.freshElement("a", {href: "#" + noteRefHtmlId(element)}, [Html.text("↑")])
- ]);
- var body = children.concat([backLink]);
-
- return Html.freshElement("li", {id: noteHtmlId(element)}, body);
- },
- "commentReference": convertCommentReference,
- "comment": convertComment,
- "image": deferredConversion(recoveringConvertImage(options.convertImage || images.dataUri)),
- "table": convertTable,
- "tableRow": convertTableRow,
- "tableCell": convertTableCell,
- "break": convertBreak
- };
- return {
- convertToHtml: convertToHtml
- };
- }
- var deferredId = 1;
- function deferredConversion(func) {
- return function(element, messages, options) {
- return [
- {
- type: "deferred",
- id: deferredId++,
- value: function() {
- return func(element, messages, options);
- }
- }
- ];
- };
- }
- function unrecognisedStyleWarning(type, element) {
- return results.warning(
- "Unrecognised " + type + " style: '" + element.styleName + "'" +
- " (Style ID: " + element.styleId + ")"
- );
- }
- function flatMap(values, func) {
- return _.flatten(values.map(func), true);
- }
- function walkHtml(nodes, callback) {
- nodes.forEach(function(node) {
- callback(node);
- if (node.children) {
- walkHtml(node.children, callback);
- }
- });
- }
- var commentAuthorLabel = exports.commentAuthorLabel = function commentAuthorLabel(comment) {
- return comment.authorInitials || "";
- };
- },{"./documents":4,"./html":18,"./images":20,"./promises":23,"./results":24,"./styles/html-paths":27,"./writers":32,"underscore":153}],4:[function(require,module,exports){
- var _ = require("underscore");
- var types = exports.types = {
- document: "document",
- paragraph: "paragraph",
- run: "run",
- text: "text",
- tab: "tab",
- hyperlink: "hyperlink",
- noteReference: "noteReference",
- image: "image",
- note: "note",
- commentReference: "commentReference",
- comment: "comment",
- table: "table",
- tableRow: "tableRow",
- tableCell: "tableCell",
- "break": "break",
- bookmarkStart: "bookmarkStart"
- };
- function Document(children, options) {
- options = options || {};
- return {
- type: types.document,
- children: children,
- notes: options.notes || new Notes({}),
- comments: options.comments || []
- };
- }
- function Paragraph(children, properties) {
- properties = properties || {};
- var indent = properties.indent || {};
- return {
- type: types.paragraph,
- children: children,
- styleId: properties.styleId || null,
- styleName: properties.styleName || null,
- numbering: properties.numbering || null,
- alignment: properties.alignment || null,
- indent: {
- start: indent.start || null,
- end: indent.end || null,
- firstLine: indent.firstLine || null,
- hanging: indent.hanging || null
- }
- };
- }
- function Run(children, properties) {
- properties = properties || {};
- return {
- type: types.run,
- children: children,
- styleId: properties.styleId || null,
- styleName: properties.styleName || null,
- isBold: properties.isBold,
- isUnderline: properties.isUnderline,
- isItalic: properties.isItalic,
- isStrikethrough: properties.isStrikethrough,
- isSmallCaps: properties.isSmallCaps,
- verticalAlignment: properties.verticalAlignment || verticalAlignment.baseline,
- font: properties.font || null
- };
- }
- var verticalAlignment = {
- baseline: "baseline",
- superscript: "superscript",
- subscript: "subscript"
- };
- function Text(value) {
- return {
- type: types.text,
- value: value
- };
- }
- function Tab() {
- return {
- type: types.tab
- };
- }
- function Hyperlink(children, options) {
- return {
- type: types.hyperlink,
- children: children,
- href: options.href,
- anchor: options.anchor,
- targetFrame: options.targetFrame
- };
- }
- function NoteReference(options) {
- return {
- type: types.noteReference,
- noteType: options.noteType,
- noteId: options.noteId
- };
- }
- function Notes(notes) {
- this._notes = _.indexBy(notes, function(note) {
- return noteKey(note.noteType, note.noteId);
- });
- }
- Notes.prototype.resolve = function(reference) {
- return this.findNoteByKey(noteKey(reference.noteType, reference.noteId));
- };
- Notes.prototype.findNoteByKey = function(key) {
- return this._notes[key] || null;
- };
- function Note(options) {
- return {
- type: types.note,
- noteType: options.noteType,
- noteId: options.noteId,
- body: options.body
- };
- }
- function commentReference(options) {
- return {
- type: types.commentReference,
- commentId: options.commentId
- };
- }
- function comment(options) {
- return {
- type: types.comment,
- commentId: options.commentId,
- body: options.body,
- authorName: options.authorName,
- authorInitials: options.authorInitials
- };
- }
- function noteKey(noteType, id) {
- return noteType + "-" + id;
- }
- function Image(options) {
- return {
- type: types.image,
- read: options.readImage,
- altText: options.altText,
- contentType: options.contentType
- };
- }
- function Table(children, properties) {
- properties = properties || {};
- return {
- type: types.table,
- children: children,
- styleId: properties.styleId || null,
- styleName: properties.styleName || null
- };
- }
- function TableRow(children, options) {
- options = options || {};
- return {
- type: types.tableRow,
- children: children,
- isHeader: options.isHeader || false
- };
- }
- function TableCell(children, options) {
- options = options || {};
- return {
- type: types.tableCell,
- children: children,
- colSpan: options.colSpan == null ? 1 : options.colSpan,
- rowSpan: options.rowSpan == null ? 1 : options.rowSpan
- };
- }
- function Break(breakType) {
- return {
- type: types["break"],
- breakType: breakType
- };
- }
- function BookmarkStart(options) {
- return {
- type: types.bookmarkStart,
- name: options.name
- };
- }
- exports.document = exports.Document = Document;
- exports.paragraph = exports.Paragraph = Paragraph;
- exports.run = exports.Run = Run;
- exports.Text = Text;
- exports.tab = exports.Tab = Tab;
- exports.Hyperlink = Hyperlink;
- exports.noteReference = exports.NoteReference = NoteReference;
- exports.Notes = Notes;
- exports.Note = Note;
- exports.commentReference = commentReference;
- exports.comment = comment;
- exports.Image = Image;
- exports.Table = Table;
- exports.TableRow = TableRow;
- exports.TableCell = TableCell;
- exports.lineBreak = Break("line");
- exports.pageBreak = Break("page");
- exports.columnBreak = Break("column");
- exports.BookmarkStart = BookmarkStart;
- exports.verticalAlignment = verticalAlignment;
- },{"underscore":153}],5:[function(require,module,exports){
- exports.createBodyReader = createBodyReader;
- exports._readNumberingProperties = readNumberingProperties;
- var _ = require("underscore");
- var documents = require("../documents");
- var Result = require("../results").Result;
- var warning = require("../results").warning;
- var uris = require("./uris");
- function createBodyReader(options) {
- return {
- readXmlElement: function(element) {
- return new BodyReader(options).readXmlElement(element);
- },
- readXmlElements: function(elements) {
- return new BodyReader(options).readXmlElements(elements);
- }
- };
- }
- function BodyReader(options) {
- var complexFieldStack = [];
- var currentInstrText = [];
- var relationships = options.relationships;
- var contentTypes = options.contentTypes;
- var docxFile = options.docxFile;
- var files = options.files;
- var numbering = options.numbering;
- var styles = options.styles;
- function readXmlElements(elements) {
- var results = elements.map(readXmlElement);
- return combineResults(results);
- }
- function readXmlElement(element) {
- if (element.type === "element") {
- var handler = xmlElementReaders[element.name];
- if (handler) {
- return handler(element);
- } else if (!Object.prototype.hasOwnProperty.call(ignoreElements, element.name)) {
- var message = warning("An unrecognised element was ignored: " + element.name);
- return emptyResultWithMessages([message]);
- }
- }
- return emptyResult();
- }
-
- function readParagraphIndent(element) {
- return {
- start: element.attributes["w:start"] || element.attributes["w:left"],
- end: element.attributes["w:end"] || element.attributes["w:right"],
- firstLine: element.attributes["w:firstLine"],
- hanging: element.attributes["w:hanging"]
- };
- }
-
- function readRunProperties(element) {
- return readRunStyle(element).map(function(style) {
- return {
- type: "runProperties",
- styleId: style.styleId,
- styleName: style.name,
- verticalAlignment: element.firstOrEmpty("w:vertAlign").attributes["w:val"],
- font: element.firstOrEmpty("w:rFonts").attributes["w:ascii"],
- isBold: readBooleanElement(element.first("w:b")),
- isUnderline: readBooleanElement(element.first("w:u")),
- isItalic: readBooleanElement(element.first("w:i")),
- isStrikethrough: readBooleanElement(element.first("w:strike")),
- isSmallCaps: readBooleanElement(element.first("w:smallCaps"))
- };
- });
- }
-
- function readBooleanElement(element) {
- if (element) {
- var value = element.attributes["w:val"];
- return value !== "false" && value !== "0";
- } else {
- return false;
- }
- }
-
- function readParagraphStyle(element) {
- return readStyle(element, "w:pStyle", "Paragraph", styles.findParagraphStyleById);
- }
-
- function readRunStyle(element) {
- return readStyle(element, "w:rStyle", "Run", styles.findCharacterStyleById);
- }
-
- function readTableStyle(element) {
- return readStyle(element, "w:tblStyle", "Table", styles.findTableStyleById);
- }
-
- function readStyle(element, styleTagName, styleType, findStyleById) {
- var messages = [];
- var styleElement = element.first(styleTagName);
- var styleId = null;
- var name = null;
- if (styleElement) {
- styleId = styleElement.attributes["w:val"];
- if (styleId) {
- var style = findStyleById(styleId);
- if (style) {
- name = style.name;
- } else {
- messages.push(undefinedStyleWarning(styleType, styleId));
- }
- }
- }
- return elementResultWithMessages({styleId: styleId, name: name}, messages);
- }
-
- var unknownComplexField = {type: "unknown"};
-
- function readFldChar(element) {
- var type = element.attributes["w:fldCharType"];
- if (type === "begin") {
- complexFieldStack.push(unknownComplexField);
- currentInstrText = [];
- } else if (type === "end") {
- complexFieldStack.pop();
- } else if (type === "separate") {
- var href = parseHyperlinkFieldCode(currentInstrText.join(''));
- var complexField = href === null ? unknownComplexField : {type: "hyperlink", href: href};
- complexFieldStack.pop();
- complexFieldStack.push(complexField);
- }
- return emptyResult();
- }
-
- function currentHyperlinkHref() {
- var topHyperlink = _.last(complexFieldStack.filter(function(complexField) {
- return complexField.type === "hyperlink";
- }));
- return topHyperlink ? topHyperlink.href : null;
- }
- function parseHyperlinkFieldCode(code) {
- var result = /\s*HYPERLINK "(.*)"/.exec(code);
- if (result) {
- return result[1];
- } else {
- return null;
- }
- }
-
- function readInstrText(element) {
- currentInstrText.push(element.text());
- return emptyResult();
- }
-
- function noteReferenceReader(noteType) {
- return function(element) {
- var noteId = element.attributes["w:id"];
- return elementResult(new documents.NoteReference({
- noteType: noteType,
- noteId: noteId
- }));
- };
- }
-
- function readCommentReference(element) {
- return elementResult(documents.commentReference({
- commentId: element.attributes["w:id"]
- }));
- }
-
- function readChildElements(element) {
- return readXmlElements(element.children);
- }
-
- var xmlElementReaders = {
- "w:p": function(element) {
- return readXmlElements(element.children)
- .map(function(children) {
- var properties = _.find(children, isParagraphProperties);
- return new documents.Paragraph(
- children.filter(negate(isParagraphProperties)),
- properties
- );
- })
- .insertExtra();
- },
- "w:pPr": function(element) {
- return readParagraphStyle(element).map(function(style) {
- return {
- type: "paragraphProperties",
- styleId: style.styleId,
- styleName: style.name,
- alignment: element.firstOrEmpty("w:jc").attributes["w:val"],
- numbering: readNumberingProperties(element.firstOrEmpty("w:numPr"), numbering),
- indent: readParagraphIndent(element.firstOrEmpty("w:ind"))
- };
- });
- },
- "w:r": function(element) {
- return readXmlElements(element.children)
- .map(function(children) {
- var properties = _.find(children, isRunProperties);
- children = children.filter(negate(isRunProperties));
- var hyperlinkHref = currentHyperlinkHref();
- if (hyperlinkHref !== null) {
- children = [new documents.Hyperlink(children, {href: hyperlinkHref})];
- }
- return new documents.Run(children, properties);
- });
- },
- "w:rPr": readRunProperties,
- "w:fldChar": readFldChar,
- "w:instrText": readInstrText,
- "w:t": function(element) {
- return elementResult(new documents.Text(element.text()));
- },
- "w:tab": function(element) {
- return elementResult(new documents.Tab());
- },
- "w:noBreakHyphen": function() {
- return elementResult(new documents.Text("\u2011"));
- },
- "w:hyperlink": function(element) {
- var relationshipId = element.attributes["r:id"];
- var anchor = element.attributes["w:anchor"];
- return readXmlElements(element.children).map(function(children) {
- function create(options) {
- var targetFrame = element.attributes["w:tgtFrame"] || null;
-
- return new documents.Hyperlink(
- children,
- _.extend({targetFrame: targetFrame}, options)
- );
- }
-
- if (relationshipId) {
- var href = relationships.findTargetByRelationshipId(relationshipId);
- if (anchor) {
- href = uris.replaceFragment(href, anchor);
- }
- return create({href: href});
- } else if (anchor) {
- return create({anchor: anchor});
- } else {
- return children;
- }
- });
- },
- "w:tbl": readTable,
- "w:tr": readTableRow,
- "w:tc": readTableCell,
- "w:footnoteReference": noteReferenceReader("footnote"),
- "w:endnoteReference": noteReferenceReader("endnote"),
- "w:commentReference": readCommentReference,
- "w:br": function(element) {
- var breakType = element.attributes["w:type"];
- if (breakType == null || breakType === "textWrapping") {
- return elementResult(documents.lineBreak);
- } else if (breakType === "page") {
- return elementResult(documents.pageBreak);
- } else if (breakType === "column") {
- return elementResult(documents.columnBreak);
- } else {
- return emptyResultWithMessages([warning("Unsupported break type: " + breakType)]);
- }
- },
- "w:bookmarkStart": function(element){
- var name = element.attributes["w:name"];
- if (name === "_GoBack") {
- return emptyResult();
- } else {
- return elementResult(new documents.BookmarkStart({name: name}));
- }
- },
-
- "mc:AlternateContent": function(element) {
- return readChildElements(element.first("mc:Fallback"));
- },
-
- "w:sdt": function(element) {
- return readXmlElements(element.firstOrEmpty("w:sdtContent").children);
- },
- "w:ins": readChildElements,
- "w:object": readChildElements,
- "w:smartTag": readChildElements,
- "w:drawing": readChildElements,
- "w:pict": function(element) {
- return readChildElements(element).toExtra();
- },
- "v:roundrect": readChildElements,
- "v:shape": readChildElements,
- "v:textbox": readChildElements,
- "w:txbxContent": readChildElements,
- "wp:inline": readDrawingElement,
- "wp:anchor": readDrawingElement,
- "v:imagedata": readImageData,
- "v:group": readChildElements,
- "v:rect": readChildElements
- };
-
- return {
- readXmlElement: readXmlElement,
- readXmlElements: readXmlElements
- };
-
- function readTable(element) {
- var propertiesResult = readTableProperties(element.firstOrEmpty("w:tblPr"));
- return readXmlElements(element.children)
- .flatMap(calculateRowSpans)
- .flatMap(function(children) {
- return propertiesResult.map(function(properties) {
- return documents.Table(children, properties);
- });
- });
- }
-
- function readTableProperties(element) {
- return readTableStyle(element).map(function(style) {
- return {
- styleId: style.styleId,
- styleName: style.name
- };
- });
- }
-
- function readTableRow(element) {
- var properties = element.firstOrEmpty("w:trPr");
- var isHeader = !!properties.first("w:tblHeader");
- return readXmlElements(element.children).map(function(children) {
- return documents.TableRow(children, {isHeader: isHeader});
- });
- }
-
- function readTableCell(element) {
- return readXmlElements(element.children).map(function(children) {
- var properties = element.firstOrEmpty("w:tcPr");
-
- var gridSpan = properties.firstOrEmpty("w:gridSpan").attributes["w:val"];
- var colSpan = gridSpan ? parseInt(gridSpan, 10) : 1;
-
- var cell = documents.TableCell(children, {colSpan: colSpan});
- cell._vMerge = readVMerge(properties);
- return cell;
- });
- }
-
- function readVMerge(properties) {
- var element = properties.first("w:vMerge");
- if (element) {
- var val = element.attributes["w:val"];
- return val === "continue" || !val;
- } else {
- return null;
- }
- }
-
- function calculateRowSpans(rows) {
- var unexpectedNonRows = _.any(rows, function(row) {
- return row.type !== documents.types.tableRow;
- });
- if (unexpectedNonRows) {
- return elementResultWithMessages(rows, [warning(
- "unexpected non-row element in table, cell merging may be incorrect"
- )]);
- }
- var unexpectedNonCells = _.any(rows, function(row) {
- return _.any(row.children, function(cell) {
- return cell.type !== documents.types.tableCell;
- });
- });
- if (unexpectedNonCells) {
- return elementResultWithMessages(rows, [warning(
- "unexpected non-cell element in table row, cell merging may be incorrect"
- )]);
- }
-
- var columns = {};
-
- rows.forEach(function(row) {
- var cellIndex = 0;
- row.children.forEach(function(cell) {
- if (cell._vMerge && columns[cellIndex]) {
- columns[cellIndex].rowSpan++;
- } else {
- columns[cellIndex] = cell;
- cell._vMerge = false;
- }
- cellIndex += cell.colSpan;
- });
- });
-
- rows.forEach(function(row) {
- row.children = row.children.filter(function(cell) {
- return !cell._vMerge;
- });
- row.children.forEach(function(cell) {
- delete cell._vMerge;
- });
- });
-
- return elementResult(rows);
- }
- function readDrawingElement(element) {
- var blips = element
- .getElementsByTagName("a:graphic")
- .getElementsByTagName("a:graphicData")
- .getElementsByTagName("pic:pic")
- .getElementsByTagName("pic:blipFill")
- .getElementsByTagName("a:blip");
-
- return combineResults(blips.map(readBlip.bind(null, element)));
- }
-
- function readBlip(element, blip) {
- var properties = element.first("wp:docPr").attributes;
- var altText = isBlank(properties.descr) ? properties.title : properties.descr;
- return readImage(findBlipImageFile(blip), altText);
- }
-
- function isBlank(value) {
- return value == null || /^\s*$/.test(value);
- }
-
- function findBlipImageFile(blip) {
- var embedRelationshipId = blip.attributes["r:embed"];
- var linkRelationshipId = blip.attributes["r:link"];
- if (embedRelationshipId) {
- return findEmbeddedImageFile(embedRelationshipId);
- } else {
- var imagePath = relationships.findTargetByRelationshipId(linkRelationshipId);
- return {
- path: imagePath,
- read: files.read.bind(files, imagePath)
- };
- }
- }
-
- function readImageData(element) {
- var relationshipId = element.attributes['r:id'];
-
- if (relationshipId) {
- return readImage(
- findEmbeddedImageFile(relationshipId),
- element.attributes["o:title"]);
- } else {
- return emptyResultWithMessages([warning("A v:imagedata element without a relationship ID was ignored")]);
- }
- }
-
- function findEmbeddedImageFile(relationshipId) {
- var path = uris.uriToZipEntryName("word", relationships.findTargetByRelationshipId(relationshipId));
- return {
- path: path,
- read: docxFile.read.bind(docxFile, path)
- };
- }
-
- function readImage(imageFile, altText) {
- var contentType = contentTypes.findContentType(imageFile.path);
-
- var image = documents.Image({
- readImage: imageFile.read,
- altText: altText,
- contentType: contentType
- });
- var warnings = supportedImageTypes[contentType] ?
- [] : warning("Image of type " + contentType + " is unlikely to display in web browsers");
- return elementResultWithMessages(image, warnings);
- }
-
- function undefinedStyleWarning(type, styleId) {
- return warning(
- type + " style with ID " + styleId + " was referenced but not defined in the document");
- }
- }
- function readNumberingProperties(element, numbering) {
- var level = element.firstOrEmpty("w:ilvl").attributes["w:val"];
- var numId = element.firstOrEmpty("w:numId").attributes["w:val"];
- if (level === undefined || numId === undefined) {
- return null;
- } else {
- return numbering.findLevel(numId, level);
- }
- }
-
- var supportedImageTypes = {
- "image/png": true,
- "image/gif": true,
- "image/jpeg": true,
- "image/svg+xml": true,
- "image/tiff": true
- };
- var ignoreElements = {
- "office-word:wrap": true,
- "v:shadow": true,
- "v:shapetype": true,
- "w:annotationRef": true,
- "w:bookmarkEnd": true,
- "w:sectPr": true,
- "w:proofErr": true,
- "w:lastRenderedPageBreak": true,
- "w:commentRangeStart": true,
- "w:commentRangeEnd": true,
- "w:del": true,
- "w:footnoteRef": true,
- "w:endnoteRef": true,
- "w:tblPr": true,
- "w:tblGrid": true,
- "w:trPr": true,
- "w:tcPr": true
- };
- function isParagraphProperties(element) {
- return element.type === "paragraphProperties";
- }
- function isRunProperties(element) {
- return element.type === "runProperties";
- }
- function negate(predicate) {
- return function(value) {
- return !predicate(value);
- };
- }
- function emptyResultWithMessages(messages) {
- return new ReadResult(null, null, messages);
- }
- function emptyResult() {
- return new ReadResult(null);
- }
- function elementResult(element) {
- return new ReadResult(element);
- }
- function elementResultWithMessages(element, messages) {
- return new ReadResult(element, null, messages);
- }
- function ReadResult(element, extra, messages) {
- this.value = element || [];
- this.extra = extra;
- this._result = new Result({
- element: this.value,
- extra: extra
- }, messages);
- this.messages = this._result.messages;
- }
- ReadResult.prototype.toExtra = function() {
- return new ReadResult(null, joinElements(this.extra, this.value), this.messages);
- };
- ReadResult.prototype.insertExtra = function() {
- var extra = this.extra;
- if (extra && extra.length) {
- return new ReadResult(joinElements(this.value, extra), null, this.messages);
- } else {
- return this;
- }
- };
- ReadResult.prototype.map = function(func) {
- var result = this._result.map(function(value) {
- return func(value.element);
- });
- return new ReadResult(result.value, this.extra, result.messages);
- };
- ReadResult.prototype.flatMap = function(func) {
- var result = this._result.flatMap(function(value) {
- return func(value.element)._result;
- });
- return new ReadResult(result.value.element, joinElements(this.extra, result.value.extra), result.messages);
- };
- function combineResults(results) {
- var result = Result.combine(_.pluck(results, "_result"));
- return new ReadResult(
- _.flatten(_.pluck(result.value, "element")),
- _.filter(_.flatten(_.pluck(result.value, "extra")), identity),
- result.messages
- );
- }
- function joinElements(first, second) {
- return _.flatten([first, second]);
- }
- function identity(value) {
- return value;
- }
- },{"../documents":4,"../results":24,"./uris":16,"underscore":153}],6:[function(require,module,exports){
- var documents = require("../documents");
- var Result = require("../results").Result;
- function createCommentsReader(bodyReader) {
- function readCommentsXml(element) {
- return Result.combine(element.getElementsByTagName("w:comment")
- .map(readCommentElement));
- }
- function readCommentElement(element) {
- var id = element.attributes["w:id"];
- function readOptionalAttribute(name) {
- return (element.attributes[name] || "").trim() || null;
- }
- return bodyReader.readXmlElements(element.children)
- .map(function(body) {
- return documents.comment({
- commentId: id,
- body: body,
- authorName: readOptionalAttribute("w:author"),
- authorInitials: readOptionalAttribute("w:initials")
- });
- });
- }
-
- return readCommentsXml;
- }
- exports.createCommentsReader = createCommentsReader;
- },{"../documents":4,"../results":24}],7:[function(require,module,exports){
- exports.readContentTypesFromXml = readContentTypesFromXml;
- var fallbackContentTypes = {
- "png": "png",
- "gif": "gif",
- "jpeg": "jpeg",
- "jpg": "jpeg",
- "tif": "tiff",
- "tiff": "tiff",
- "bmp": "bmp"
- };
- exports.defaultContentTypes = contentTypes({}, {});
- function readContentTypesFromXml(element) {
- var extensionDefaults = {};
- var overrides = {};
-
- element.children.forEach(function(child) {
- if (child.name === "content-types:Default") {
- extensionDefaults[child.attributes.Extension] = child.attributes.ContentType;
- }
- if (child.name === "content-types:Override") {
- var name = child.attributes.PartName;
- if (name.charAt(0) === "/") {
- name = name.substring(1);
- }
- overrides[name] = child.attributes.ContentType;
- }
- });
- return contentTypes(overrides, extensionDefaults);
- }
- function contentTypes(overrides, extensionDefaults) {
- return {
- findContentType: function(path) {
- var overrideContentType = overrides[path];
- if (overrideContentType) {
- return overrideContentType;
- } else {
- var pathParts = path.split(".");
- var extension = pathParts[pathParts.length - 1];
- if (extensionDefaults.hasOwnProperty(extension)) {
- return extensionDefaults[extension];
- } else {
- var fallback = fallbackContentTypes[extension.toLowerCase()];
- if (fallback) {
- return "image/" + fallback;
- } else {
- return null;
- }
- }
- }
- }
- };
-
- }
- },{}],8:[function(require,module,exports){
- exports.DocumentXmlReader = DocumentXmlReader;
- var documents = require("../documents");
- var Result = require("../results").Result;
- function DocumentXmlReader(options) {
- var bodyReader = options.bodyReader;
-
- function convertXmlToDocument(element) {
- var body = element.first("w:body");
-
- var result = bodyReader.readXmlElements(body.children)
- .map(function(children) {
- return new documents.Document(children, {
- notes: options.notes,
- comments: options.comments
- });
- });
- return new Result(result.value, result.messages);
- }
-
- return {
- convertXmlToDocument: convertXmlToDocument
- };
- }
- },{"../documents":4,"../results":24}],9:[function(require,module,exports){
- exports.read = read;
- exports._findPartPaths = findPartPaths;
- var path = require("path");
- var promises = require("../promises");
- var documents = require("../documents");
- var Result = require("../results").Result;
- var zipfile = require("../zipfile");
- var readXmlFromZipFile = require("./office-xml-reader").readXmlFromZipFile;
- var createBodyReader = require("./body-reader").createBodyReader;
- var DocumentXmlReader = require("./document-xml-reader").DocumentXmlReader;
- var relationshipsReader = require("./relationships-reader");
- var contentTypesReader = require("./content-types-reader");
- var numberingXml = require("./numbering-xml");
- var stylesReader = require("./styles-reader");
- var notesReader = require("./notes-reader");
- var commentsReader = require("./comments-reader");
- var Files = require("./files").Files;
- function read(docxFile, input) {
- input = input || {};
-
- return promises.props({
- contentTypes: readContentTypesFromZipFile(docxFile),
- partPaths: findPartPaths(docxFile),
- docxFile: docxFile,
- files: new Files(input.path ? path.dirname(input.path) : null)
- }).also(function(result) {
- return {
- numbering: readNumberingFromZipFile(docxFile, result.partPaths.numbering),
- styles: readStylesFromZipFile(docxFile, result.partPaths.styles)
- };
- }).also(function(result) {
- return {
- footnotes: readXmlFileWithBody(result.partPaths.footnotes, result, function(bodyReader, xml) {
- if (xml) {
- return notesReader.createFootnotesReader(bodyReader)(xml);
- } else {
- return new Result([]);
- }
- }),
- endnotes: readXmlFileWithBody(result.partPaths.endnotes, result, function(bodyReader, xml) {
- if (xml) {
- return notesReader.createEndnotesReader(bodyReader)(xml);
- } else {
- return new Result([]);
- }
- }),
- comments: readXmlFileWithBody(result.partPaths.comments, result, function(bodyReader, xml) {
- if (xml) {
- return commentsReader.createCommentsReader(bodyReader)(xml);
- } else {
- return new Result([]);
- }
- })
- };
- }).also(function(result) {
- return {
- notes: result.footnotes.flatMap(function(footnotes) {
- return result.endnotes.map(function(endnotes) {
- return new documents.Notes(footnotes.concat(endnotes));
- });
- })
- };
- }).then(function(result) {
- return readXmlFileWithBody(result.partPaths.mainDocument, result, function(bodyReader, xml) {
- return result.notes.flatMap(function(notes) {
- return result.comments.flatMap(function(comments) {
- var reader = new DocumentXmlReader({
- bodyReader: bodyReader,
- notes: notes,
- comments: comments
- });
- return reader.convertXmlToDocument(xml);
- });
- });
- });
- });
- }
- function findPartPaths(docxFile) {
- return readPackageRelationships(docxFile).then(function(packageRelationships) {
- var mainDocumentPath = findPartPath({
- docxFile: docxFile,
- relationships: packageRelationships,
- relationshipType: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
- basePath: "",
- fallbackPath: "word/document.xml"
- });
-
- if (!docxFile.exists(mainDocumentPath)) {
- throw new Error("Could not find main document part. Are you sure this is a valid .docx file?");
- }
-
- return xmlFileReader({
- filename: relationshipsFilename(mainDocumentPath),
- readElement: relationshipsReader.readRelationships,
- defaultValue: relationshipsReader.defaultValue
- })(docxFile).then(function(documentRelationships) {
- function findPartRelatedToMainDocument(name) {
- return findPartPath({
- docxFile: docxFile,
- relationships: documentRelationships,
- relationshipType: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/" + name,
- basePath: zipfile.splitPath(mainDocumentPath).dirname,
- fallbackPath: "word/" + name + ".xml"
- });
- }
-
- return {
- mainDocument: mainDocumentPath,
- comments: findPartRelatedToMainDocument("comments"),
- endnotes: findPartRelatedToMainDocument("endnotes"),
- footnotes: findPartRelatedToMainDocument("footnotes"),
- numbering: findPartRelatedToMainDocument("numbering"),
- styles: findPartRelatedToMainDocument("styles")
- };
- });
- });
- }
- function findPartPath(options) {
- var docxFile = options.docxFile;
- var relationships = options.relationships;
- var relationshipType = options.relationshipType;
- var basePath = options.basePath;
- var fallbackPath = options.fallbackPath;
-
- var targets = relationships.findTargetsByType(relationshipType);
- var normalisedTargets = targets.map(function(target) {
- return stripPrefix(zipfile.joinPath(basePath, target), "/");
- });
- var validTargets = normalisedTargets.filter(function(target) {
- return docxFile.exists(target);
- });
- if (validTargets.length === 0) {
- return fallbackPath;
- } else {
- return validTargets[0];
- }
- }
- function stripPrefix(value, prefix) {
- if (value.substring(0, prefix.length) === prefix) {
- return value.substring(prefix.length);
- } else {
- return value;
- }
- }
- function xmlFileReader(options) {
- return function(zipFile) {
- return readXmlFromZipFile(zipFile, options.filename)
- .then(function(element) {
- return element ? options.readElement(element) : options.defaultValue;
- });
- };
- }
- function readXmlFileWithBody(filename, options, func) {
- var readRelationshipsFromZipFile = xmlFileReader({
- filename: relationshipsFilename(filename),
- readElement: relationshipsReader.readRelationships,
- defaultValue: relationshipsReader.defaultValue
- });
-
- return readRelationshipsFromZipFile(options.docxFile).then(function(relationships) {
- var bodyReader = new createBodyReader({
- relationships: relationships,
- contentTypes: options.contentTypes,
- docxFile: options.docxFile,
- numbering: options.numbering,
- styles: options.styles,
- files: options.files
- });
- return readXmlFromZipFile(options.docxFile, filename)
- .then(function(xml) {
- return func(bodyReader, xml);
- });
- });
- }
- function relationshipsFilename(filename) {
- var split = zipfile.splitPath(filename);
- return zipfile.joinPath(split.dirname, "_rels", split.basename + ".rels");
- }
- var readContentTypesFromZipFile = xmlFileReader({
- filename: "[Content_Types].xml",
- readElement: contentTypesReader.readContentTypesFromXml,
- defaultValue: contentTypesReader.defaultContentTypes
- });
- function readNumberingFromZipFile(zipFile, path) {
- return xmlFileReader({
- filename: path,
- readElement: numberingXml.readNumberingXml,
- defaultValue: numberingXml.defaultNumbering
- })(zipFile);
- }
- function readStylesFromZipFile(zipFile, path) {
- return xmlFileReader({
- filename: path,
- readElement: stylesReader.readStylesXml,
- defaultValue: stylesReader.defaultStyles
- })(zipFile);
- }
- var readPackageRelationships = xmlFileReader({
- filename: "_rels/.rels",
- readElement: relationshipsReader.readRelationships,
- defaultValue: relationshipsReader.defaultValue
- });
- },{"../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){
- var documents = require("../documents");
- var Result = require("../results").Result;
- exports.createFootnotesReader = createReader.bind(this, "footnote");
- exports.createEndnotesReader = createReader.bind(this, "endnote");
- function createReader(noteType, bodyReader) {
- function readNotesXml(element) {
- return Result.combine(element.getElementsByTagName("w:" + noteType)
- .filter(isFootnoteElement)
- .map(readFootnoteElement));
- }
- function isFootnoteElement(element) {
- var type = element.attributes["w:type"];
- return type !== "continuationSeparator" && type !== "separator";
- }
- function readFootnoteElement(footnoteElement) {
- var id = footnoteElement.attributes["w:id"];
- return bodyReader.readXmlElements(footnoteElement.children)
- .map(function(body) {
- return documents.Note({noteType: noteType, noteId: id, body: body});
- });
- }
-
- return readNotesXml;
- }
- },{"../documents":4,"../results":24}],11:[function(require,module,exports){
- exports.readNumberingXml = readNumberingXml;
- exports.Numbering = Numbering;
- exports.defaultNumbering = new Numbering({});
- function Numbering(nums) {
- return {
- findLevel: function(numId, level) {
- var num = nums[numId];
- if (num) {
- return num[level];
- } else {
- return null;
- }
- }
- };
- }
- function readNumberingXml(root) {
- var abstractNums = readAbstractNums(root);
- var nums = readNums(root, abstractNums);
- return new Numbering(nums);
- }
- function readAbstractNums(root) {
- var abstractNums = {};
- root.getElementsByTagName("w:abstractNum").forEach(function(element) {
- var id = element.attributes["w:abstractNumId"];
- abstractNums[id] = readAbstractNum(element);
- });
- return abstractNums;
- }
- function readAbstractNum(element) {
- var levels = {};
- element.getElementsByTagName("w:lvl").forEach(function(levelElement) {
- var levelIndex = levelElement.attributes["w:ilvl"];
- var numFmt = levelElement.first("w:numFmt").attributes["w:val"];
- levels[levelIndex] = {
- isOrdered: numFmt !== "bullet",
- level: levelIndex
- };
- });
- return levels;
- }
- function readNums(root, abstractNums) {
- var nums = {};
- root.getElementsByTagName("w:num").forEach(function(element) {
- var id = element.attributes["w:numId"];
- var abstractNumId = element.first("w:abstractNumId").attributes["w:val"];
- nums[id] = abstractNums[abstractNumId];
- });
- return nums;
- }
- },{}],12:[function(require,module,exports){
- var _ = require("underscore");
- var promises = require("../promises");
- var xml = require("../xml");
- exports.read = read;
- exports.readXmlFromZipFile = readXmlFromZipFile;
- var xmlNamespaceMap = {
- "http://schemas.openxmlformats.org/wordprocessingml/2006/main": "w",
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships": "r",
- "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing": "wp",
- "http://schemas.openxmlformats.org/drawingml/2006/main": "a",
- "http://schemas.openxmlformats.org/drawingml/2006/picture": "pic",
- "http://schemas.openxmlformats.org/package/2006/content-types": "content-types",
- "urn:schemas-microsoft-com:vml": "v",
- "http://schemas.openxmlformats.org/markup-compatibility/2006": "mc",
- "urn:schemas-microsoft-com:office:word": "office-word"
- };
- function read(xmlString) {
- return xml.readString(xmlString, xmlNamespaceMap)
- .then(function(document) {
- return collapseAlternateContent(document)[0];
- });
- }
- function readXmlFromZipFile(docxFile, path) {
- if (docxFile.exists(path)) {
- return docxFile.read(path, "utf-8")
- .then(stripUtf8Bom)
- .then(read);
- } else {
- return promises.resolve(null);
- }
- }
- function stripUtf8Bom(xmlString) {
- return xmlString.replace(/^\uFEFF/g, '');
- }
- function collapseAlternateContent(node) {
- if (node.type === "element") {
- if (node.name === "mc:AlternateContent") {
- return node.first("mc:Fallback").children;
- } else {
- node.children = _.flatten(node.children.map(collapseAlternateContent, true));
- return [node];
- }
- } else {
- return [node];
- }
- }
- },{"../promises":23,"../xml":34,"underscore":153}],13:[function(require,module,exports){
- exports.readRelationships = readRelationships;
- exports.defaultValue = new Relationships([]);
- exports.Relationships = Relationships;
- function readRelationships(element) {
- var relationships = [];
- element.children.forEach(function(child) {
- if (child.name === "{http://schemas.openxmlformats.org/package/2006/relationships}Relationship") {
- var relationship = {
- relationshipId: child.attributes.Id,
- target: child.attributes.Target,
- type: child.attributes.Type
- };
- relationships.push(relationship);
- }
- });
- return new Relationships(relationships);
- }
- function Relationships(relationships) {
- var targetsByRelationshipId = {};
- relationships.forEach(function(relationship) {
- targetsByRelationshipId[relationship.relationshipId] = relationship.target;
- });
-
- var targetsByType = {};
- relationships.forEach(function(relationship) {
- if (!targetsByType[relationship.type]) {
- targetsByType[relationship.type] = [];
- }
- targetsByType[relationship.type].push(relationship.target);
- });
-
- return {
- findTargetByRelationshipId: function(relationshipId) {
- return targetsByRelationshipId[relationshipId];
- },
- findTargetsByType: function(type) {
- return targetsByType[type] || [];
- }
- };
- }
- },{}],14:[function(require,module,exports){
- var _ = require("underscore");
- var promises = require("../promises");
- var xml = require("../xml");
- exports.writeStyleMap = writeStyleMap;
- exports.readStyleMap = readStyleMap;
- var schema = "http://schemas.zwobble.org/mammoth/style-map";
- var styleMapPath = "mammoth/style-map";
- var styleMapAbsolutePath = "/" + styleMapPath;
- function writeStyleMap(docxFile, styleMap) {
- docxFile.write(styleMapPath, styleMap);
- return updateRelationships(docxFile).then(function() {
- return updateContentTypes(docxFile);
- });
- }
- function updateRelationships(docxFile) {
- var path = "word/_rels/document.xml.rels";
- var relationshipsUri = "http://schemas.openxmlformats.org/package/2006/relationships";
- var relationshipElementName = "{" + relationshipsUri + "}Relationship";
- return docxFile.read(path, "utf8")
- .then(xml.readString)
- .then(function(relationshipsContainer) {
- var relationships = relationshipsContainer.children;
- addOrUpdateElement(relationships, relationshipElementName, "Id", {
- "Id": "rMammothStyleMap",
- "Type": schema,
- "Target": styleMapAbsolutePath
- });
-
- var namespaces = {"": relationshipsUri};
- return docxFile.write(path, xml.writeString(relationshipsContainer, namespaces));
- });
- }
- function updateContentTypes(docxFile) {
- var path = "[Content_Types].xml";
- var contentTypesUri = "http://schemas.openxmlformats.org/package/2006/content-types";
- var overrideName = "{" + contentTypesUri + "}Override";
- return docxFile.read(path, "utf8")
- .then(xml.readString)
- .then(function(typesElement) {
- var children = typesElement.children;
- addOrUpdateElement(children, overrideName, "PartName", {
- "PartName": styleMapAbsolutePath,
- "ContentType": "text/prs.mammoth.style-map"
- });
- var namespaces = {"": contentTypesUri};
- return docxFile.write(path, xml.writeString(typesElement, namespaces));
- });
- }
- function addOrUpdateElement(elements, name, identifyingAttribute, attributes) {
- var existingElement = _.find(elements, function(element) {
- return element.name === name &&
- element.attributes[identifyingAttribute] === attributes[identifyingAttribute];
- });
- if (existingElement) {
- existingElement.attributes = attributes;
- } else {
- elements.push(xml.element(name, attributes));
- }
- }
- function readStyleMap(docxFile) {
- if (docxFile.exists(styleMapPath)) {
- return docxFile.read(styleMapPath, "utf8");
- } else {
- return promises.resolve(null);
- }
- }
- },{"../promises":23,"../xml":34,"underscore":153}],15:[function(require,module,exports){
- exports.readStylesXml = readStylesXml;
- exports.Styles = Styles;
- exports.defaultStyles = new Styles({}, {});
- function Styles(paragraphStyles, characterStyles, tableStyles) {
- return {
- findParagraphStyleById: function(styleId) {
- return paragraphStyles[styleId];
- },
- findCharacterStyleById: function(styleId) {
- return characterStyles[styleId];
- },
- findTableStyleById: function(styleId) {
- return tableStyles[styleId];
- }
- };
- }
- Styles.EMPTY = new Styles({}, {}, {});
- function readStylesXml(root) {
- var paragraphStyles = {};
- var characterStyles = {};
- var tableStyles = {};
-
- var styles = {
- "paragraph": paragraphStyles,
- "character": characterStyles,
- "table": tableStyles
- };
-
- root.getElementsByTagName("w:style").forEach(function(styleElement) {
- var style = readStyleElement(styleElement);
- var styleSet = styles[style.type];
- if (styleSet) {
- styleSet[style.styleId] = style;
- }
- });
-
- return new Styles(paragraphStyles, characterStyles, tableStyles);
- }
- function readStyleElement(styleElement) {
- var type = styleElement.attributes["w:type"];
- var styleId = styleElement.attributes["w:styleId"];
- var name = styleName(styleElement);
- return {type: type, styleId: styleId, name: name};
- }
- function styleName(styleElement) {
- var nameElement = styleElement.first("w:name");
- return nameElement ? nameElement.attributes["w:val"] : null;
- }
- },{}],16:[function(require,module,exports){
- exports.uriToZipEntryName = uriToZipEntryName;
- exports.replaceFragment = replaceFragment;
- function uriToZipEntryName(base, uri) {
- if (uri.charAt(0) === "/") {
- return uri.substr(1);
- } else {
- // In general, we should check first and second for trailing and leading slashes,
- // but in our specific case this seems to be sufficient
- return base + "/" + uri;
- }
- }
- function replaceFragment(uri, fragment) {
- var hashIndex = uri.indexOf("#");
- if (hashIndex !== -1) {
- uri = uri.substring(0, hashIndex);
- }
- return uri + "#" + fragment;
- }
- },{}],17:[function(require,module,exports){
- var htmlPaths = require("../styles/html-paths");
- function nonFreshElement(tagName, attributes, children) {
- return elementWithTag(
- htmlPaths.element(tagName, attributes, {fresh: false}),
- children);
- }
- function freshElement(tagName, attributes, children) {
- var tag = htmlPaths.element(tagName, attributes, {fresh: true});
- return elementWithTag(tag, children);
- }
- function elementWithTag(tag, children) {
- return {
- type: "element",
- tag: tag,
- children: children || []
- };
- }
- function text(value) {
- return {
- type: "text",
- value: value
- };
- }
- var forceWrite = {
- type: "forceWrite"
- };
- exports.freshElement = freshElement;
- exports.nonFreshElement = nonFreshElement;
- exports.elementWithTag = elementWithTag;
- exports.text = text;
- exports.forceWrite = forceWrite;
- var voidTagNames = {
- "br": true,
- "hr": true,
- "img": true
- };
- function isVoidElement(node) {
- return (node.children.length === 0) && voidTagNames[node.tag.tagName];
- }
- exports.isVoidElement = isVoidElement;
- },{"../styles/html-paths":27}],18:[function(require,module,exports){
- var ast = require("./ast");
- exports.freshElement = ast.freshElement;
- exports.nonFreshElement = ast.nonFreshElement;
- exports.elementWithTag = ast.elementWithTag;
- exports.text = ast.text;
- exports.forceWrite = ast.forceWrite;
- exports.simplify = require("./simplify");
- function write(writer, nodes) {
- nodes.forEach(function(node) {
- writeNode(writer, node);
- });
- }
- function writeNode(writer, node) {
- toStrings[node.type](writer, node);
- }
- var toStrings = {
- element: generateElementString,
- text: generateTextString,
- forceWrite: function() { }
- };
- function generateElementString(writer, node) {
- if (ast.isVoidElement(node)) {
- writer.selfClosing(node.tag.tagName, node.tag.attributes);
- } else {
- writer.open(node.tag.tagName, node.tag.attributes);
- write(writer, node.children);
- writer.close(node.tag.tagName);
- }
- }
- function generateTextString(writer, node) {
- writer.text(node.value);
- }
- exports.write = write;
- },{"./ast":17,"./simplify":19}],19:[function(require,module,exports){
- var _ = require("underscore");
- var ast = require("./ast");
- function simplify(nodes) {
- return collapse(removeEmpty(nodes));
- }
- function collapse(nodes) {
- var children = [];
-
- nodes.map(collapseNode).forEach(function(child) {
- appendChild(children, child);
- });
- return children;
- }
- function collapseNode(node) {
- return collapsers[node.type](node);
- }
- var collapsers = {
- element: collapseElement,
- text: identity,
- forceWrite: identity
- };
- function collapseElement(node) {
- return ast.elementWithTag(node.tag, collapse(node.children));
- }
- function identity(value) {
- return value;
- }
- function appendChild(children, child) {
- var lastChild = children[children.length - 1];
- if (child.type === "element" && !child.tag.fresh && lastChild && lastChild.type === "element" && child.tag.matchesElement(lastChild.tag)) {
- if (child.tag.separator) {
- appendChild(lastChild.children, ast.text(child.tag.separator));
- }
- child.children.forEach(function(grandChild) {
- // Mutation is fine since simplifying elements create a copy of the children.
- appendChild(lastChild.children, grandChild);
- });
- } else {
- children.push(child);
- }
- }
- function removeEmpty(nodes) {
- return flatMap(nodes, function(node) {
- return emptiers[node.type](node);
- });
- }
- function flatMap(values, func) {
- return _.flatten(_.map(values, func), true);
- }
- var emptiers = {
- element: elementEmptier,
- text: textEmptier,
- forceWrite: neverEmpty
- };
- function neverEmpty(node) {
- return [node];
- }
- function elementEmptier(element) {
- var children = removeEmpty(element.children);
- if (children.length === 0 && !ast.isVoidElement(element)) {
- return [];
- } else {
- return [ast.elementWithTag(element.tag, children)];
- }
- }
- function textEmptier(node) {
- if (node.value.length === 0) {
- return [];
- } else {
- return [node];
- }
- }
- module.exports = simplify;
- },{"./ast":17,"underscore":153}],20:[function(require,module,exports){
- var _ = require("underscore");
- var promises = require("./promises");
- var Html = require("./html");
- exports.imgElement = imgElement;
- function imgElement(func) {
- return function(element, messages) {
- return promises.when(func(element)).then(function(result) {
- var attributes = _.clone(result);
- if (element.altText) {
- attributes.alt = element.altText;
- }
- return [Html.freshElement("img", attributes)];
- });
- };
- }
- // Undocumented, but retained for backwards-compatibility with 0.3.x
- exports.inline = exports.imgElement;
- exports.dataUri = imgElement(function(element) {
- return element.read("base64").then(function(imageBuffer) {
- return {
- src: "data:" + element.contentType + ";base64," + imageBuffer
- };
- });
- });
- },{"./html":18,"./promises":23,"underscore":153}],21:[function(require,module,exports){
- var _ = require("underscore");
- var docxReader = require("./docx/docx-reader");
- var docxStyleMap = require("./docx/style-map");
- var DocumentConverter = require("./document-to-html").DocumentConverter;
- var readStyle = require("./style-reader").readStyle;
- var readOptions = require("./options-reader").readOptions;
- var unzip = require("./unzip");
- var Result = require("./results").Result;
- exports.convertToHtml = convertToHtml;
- exports.convertToMarkdown = convertToMarkdown;
- exports.convert = convert;
- exports.extractRawText = extractRawText;
- exports.images = require("./images");
- exports.transforms = require("./transforms");
- exports.underline = require("./underline");
- exports.embedStyleMap = embedStyleMap;
- exports.readEmbeddedStyleMap = readEmbeddedStyleMap;
- function convertToHtml(input, options) {
- return convert(input, options);
- }
- function convertToMarkdown(input, options) {
- var markdownOptions = Object.create(options || {});
- markdownOptions.outputFormat = "markdown";
- return convert(input, markdownOptions);
- }
- function convert(input, options) {
- options = readOptions(options);
-
- return unzip.openZip(input)
- .tap(function(docxFile) {
- return docxStyleMap.readStyleMap(docxFile).then(function(styleMap) {
- options.embeddedStyleMap = styleMap;
- });
- })
- .then(function(docxFile) {
- return docxReader.read(docxFile, input)
- .then(function(documentResult) {
- return documentResult.map(options.transformDocument);
- })
- .then(function(documentResult) {
- return convertDocumentToHtml(documentResult, options);
- });
- });
- }
- function readEmbeddedStyleMap(input) {
- return unzip.openZip(input)
- .then(docxStyleMap.readStyleMap);
- }
- function convertDocumentToHtml(documentResult, options) {
- var styleMapResult = parseStyleMap(options.readStyleMap());
- var parsedOptions = _.extend({}, options, {
- styleMap: styleMapResult.value
- });
- var documentConverter = new DocumentConverter(parsedOptions);
-
- return documentResult.flatMapThen(function(document) {
- return styleMapResult.flatMapThen(function(styleMap) {
- return documentConverter.convertToHtml(document);
- });
- });
- }
- function parseStyleMap(styleMap) {
- return Result.combine((styleMap || []).map(readStyle))
- .map(function(styleMap) {
- return styleMap.filter(function(styleMapping) {
- return !!styleMapping;
- });
- });
- }
- function extractRawText(input) {
- return unzip.openZip(input)
- .then(docxReader.read)
- .then(function(documentResult) {
- return documentResult.map(convertElementToRawText);
- });
- }
- function convertElementToRawText(element) {
- if (element.type === "text") {
- return element.value;
- } else {
- var tail = element.type === "paragraph" ? "\n\n" : "";
- return (element.children || []).map(convertElementToRawText).join("") + tail;
- }
- }
- function embedStyleMap(input, styleMap) {
- return unzip.openZip(input)
- .tap(function(docxFile) {
- return docxStyleMap.writeStyleMap(docxFile, styleMap);
- })
- .then(function(docxFile) {
- return {
- toBuffer: docxFile.toBuffer
- };
- });
- }
- exports.styleMapping = function() {
- 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")');
- };
- },{"./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){
- exports.readOptions = readOptions;
- var _ = require("underscore");
- var defaultStyleMap = exports._defaultStyleMap = [
- "p.Heading1 => h1:fresh",
- "p.Heading2 => h2:fresh",
- "p.Heading3 => h3:fresh",
- "p.Heading4 => h4:fresh",
- "p.Heading5 => h5:fresh",
- "p.Heading6 => h6:fresh",
- "p[style-name='Heading 1'] => h1:fresh",
- "p[style-name='Heading 2'] => h2:fresh",
- "p[style-name='Heading 3'] => h3:fresh",
- "p[style-name='Heading 4'] => h4:fresh",
- "p[style-name='Heading 5'] => h5:fresh",
- "p[style-name='Heading 6'] => h6:fresh",
- "p[style-name='heading 1'] => h1:fresh",
- "p[style-name='heading 2'] => h2:fresh",
- "p[style-name='heading 3'] => h3:fresh",
- "p[style-name='heading 4'] => h4:fresh",
- "p[style-name='heading 5'] => h5:fresh",
- "p[style-name='heading 6'] => h6:fresh",
-
- "r[style-name='Strong'] => strong",
-
- "p[style-name='footnote text'] => p:fresh",
- "r[style-name='footnote reference'] =>",
- "p[style-name='endnote text'] => p:fresh",
- "r[style-name='endnote reference'] =>",
- "p[style-name='annotation text'] => p:fresh",
- "r[style-name='annotation reference'] =>",
-
- // LibreOffice
- "p[style-name='Footnote'] => p:fresh",
- "r[style-name='Footnote anchor'] =>",
- "p[style-name='Endnote'] => p:fresh",
- "r[style-name='Endnote anchor'] =>",
-
- "p:unordered-list(1) => ul > li:fresh",
- "p:unordered-list(2) => ul|ol > li > ul > li:fresh",
- "p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh",
- "p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
- "p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
- "p:ordered-list(1) => ol > li:fresh",
- "p:ordered-list(2) => ul|ol > li > ol > li:fresh",
- "p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh",
- "p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
- "p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
-
- "r[style-name='Hyperlink'] =>",
-
- "p[style-name='Normal'] => p:fresh"
- ];
- var standardOptions = exports._standardOptions = {
- transformDocument: identity,
- includeDefaultStyleMap: true,
- includeEmbeddedStyleMap: true
- };
- function readOptions(options) {
- options = options || {};
- return _.extend({}, standardOptions, options, {
- customStyleMap: readStyleMap(options.styleMap),
- readStyleMap: function() {
- var styleMap = this.customStyleMap;
- if (this.includeEmbeddedStyleMap) {
- styleMap = styleMap.concat(readStyleMap(this.embeddedStyleMap));
- }
- if (this.includeDefaultStyleMap) {
- styleMap = styleMap.concat(defaultStyleMap);
- }
- return styleMap;
- }
- });
- }
- function readStyleMap(styleMap) {
- if (!styleMap) {
- return [];
- } else if (_.isString(styleMap)) {
- return styleMap.split("\n")
- .map(function(line) {
- return line.trim();
- })
- .filter(function(line) {
- return line !== "" && line.charAt(0) !== "#";
- });
- } else {
- return styleMap;
- }
- }
- function identity(value) {
- return value;
- }
- },{"underscore":153}],23:[function(require,module,exports){
- var _ = require("underscore");
- var bluebird = require("bluebird/js/release/promise")();
- exports.defer = defer;
- exports.when = bluebird.resolve;
- exports.resolve = bluebird.resolve;
- exports.all = bluebird.all;
- exports.props = bluebird.props;
- exports.reject = bluebird.reject;
- exports.promisify = bluebird.promisify;
- exports.mapSeries = bluebird.mapSeries;
- exports.attempt = bluebird.attempt;
- exports.nfcall = function(func) {
- var args = Array.prototype.slice.call(arguments, 1);
- var promisedFunc = bluebird.promisify(func);
- return promisedFunc.apply(null, args);
- };
- bluebird.prototype.fail = bluebird.prototype.caught;
- bluebird.prototype.also = function(func) {
- return this.then(function(value) {
- var returnValue = _.extend({}, value, func(value));
- return bluebird.props(returnValue);
- });
- };
- function defer() {
- var resolve;
- var reject;
- var promise = new bluebird.Promise(function(resolveArg, rejectArg) {
- resolve = resolveArg;
- reject = rejectArg;
- });
- return {
- resolve: resolve,
- reject: reject,
- promise: promise
- };
- }
- },{"bluebird/js/release/promise":60,"underscore":153}],24:[function(require,module,exports){
- var _ = require("underscore");
- exports.Result = Result;
- exports.success = success;
- exports.warning = warning;
- exports.error = error;
- function Result(value, messages) {
- this.value = value;
- this.messages = messages || [];
- }
- Result.prototype.map = function(func) {
- return new Result(func(this.value), this.messages);
- };
- Result.prototype.flatMap = function(func) {
- var funcResult = func(this.value);
- return new Result(funcResult.value, combineMessages([this, funcResult]));
- };
- Result.prototype.flatMapThen = function(func) {
- var that = this;
- return func(this.value).then(function(otherResult) {
- return new Result(otherResult.value, combineMessages([that, otherResult]));
- });
- };
- Result.combine = function(results) {
- var values = _.flatten(_.pluck(results, "value"));
- var messages = combineMessages(results);
- return new Result(values, messages);
- };
- function success(value) {
- return new Result(value, []);
- }
- function warning(message) {
- return {
- type: "warning",
- message: message
- };
- }
- function error(exception) {
- return {
- type: "error",
- message: exception.message,
- error: exception
- };
- }
- function combineMessages(results) {
- var messages = [];
- _.flatten(_.pluck(results, "messages"), true).forEach(function(message) {
- if (!containsMessage(messages, message)) {
- messages.push(message);
- }
- });
- return messages;
- }
- function containsMessage(messages, message) {
- return _.find(messages, isSameMessage.bind(null, message)) !== undefined;
- }
- function isSameMessage(first, second) {
- return first.type === second.type && first.message === second.message;
- }
- },{"underscore":153}],25:[function(require,module,exports){
- var _ = require("underscore");
- var lop = require("lop");
- var documentMatchers = require("./styles/document-matchers");
- var htmlPaths = require("./styles/html-paths");
- var tokenise = require("./styles/parser/tokeniser").tokenise;
- var results = require("./results");
- exports.readHtmlPath = readHtmlPath;
- exports.readDocumentMatcher = readDocumentMatcher;
- exports.readStyle = readStyle;
- function readStyle(string) {
- return parseString(styleRule, string);
- }
- function createStyleRule() {
- return lop.rules.sequence(
- lop.rules.sequence.capture(documentMatcherRule()),
- lop.rules.tokenOfType("whitespace"),
- lop.rules.tokenOfType("arrow"),
- lop.rules.sequence.capture(lop.rules.optional(lop.rules.sequence(
- lop.rules.tokenOfType("whitespace"),
- lop.rules.sequence.capture(htmlPathRule())
- ).head())),
- lop.rules.tokenOfType("end")
- ).map(function(documentMatcher, htmlPath) {
- return {
- from: documentMatcher,
- to: htmlPath.valueOrElse(htmlPaths.empty)
- };
- });
- }
- function readDocumentMatcher(string) {
- return parseString(documentMatcherRule(), string);
- }
- function documentMatcherRule() {
- var sequence = lop.rules.sequence;
-
- var identifierToConstant = function(identifier, constant) {
- return lop.rules.then(
- lop.rules.token("identifier", identifier),
- function() {
- return constant;
- }
- );
- };
-
- var paragraphRule = identifierToConstant("p", documentMatchers.paragraph);
- var runRule = identifierToConstant("r", documentMatchers.run);
-
- var elementTypeRule = lop.rules.firstOf("p or r or table",
- paragraphRule,
- runRule
- );
-
- var styleIdRule = lop.rules.then(
- classRule,
- function(styleId) {
- return {styleId: styleId};
- }
- );
- var styleNameMatcherRule = lop.rules.firstOf("style name matcher",
- lop.rules.then(
- lop.rules.sequence(
- lop.rules.tokenOfType("equals"),
- lop.rules.sequence.cut(),
- lop.rules.sequence.capture(stringRule)
- ).head(),
- function(styleName) {
- return {styleName: documentMatchers.equalTo(styleName)};
- }
- ),
- lop.rules.then(
- lop.rules.sequence(
- lop.rules.tokenOfType("startsWith"),
- lop.rules.sequence.cut(),
- lop.rules.sequence.capture(stringRule)
- ).head(),
- function(styleName) {
- return {styleName: documentMatchers.startsWith(styleName)};
- }
- )
- );
-
- var styleNameRule = lop.rules.sequence(
- lop.rules.tokenOfType("open-square-bracket"),
- lop.rules.sequence.cut(),
- lop.rules.token("identifier", "style-name"),
- lop.rules.sequence.capture(styleNameMatcherRule),
- lop.rules.tokenOfType("close-square-bracket")
- ).head();
-
- var listTypeRule = lop.rules.firstOf("list type",
- identifierToConstant("ordered-list", {isOrdered: true}),
- identifierToConstant("unordered-list", {isOrdered: false})
- );
- var listRule = sequence(
- lop.rules.tokenOfType("colon"),
- sequence.capture(listTypeRule),
- sequence.cut(),
- lop.rules.tokenOfType("open-paren"),
- sequence.capture(integerRule),
- lop.rules.tokenOfType("close-paren")
- ).map(function(listType, levelNumber) {
- return {
- list: {
- isOrdered: listType.isOrdered,
- levelIndex: levelNumber - 1
- }
- };
- });
- function createMatcherSuffixesRule(rules) {
- var matcherSuffix = lop.rules.firstOf.apply(
- lop.rules.firstOf,
- ["matcher suffix"].concat(rules)
- );
- var matcherSuffixes = lop.rules.zeroOrMore(matcherSuffix);
- return lop.rules.then(matcherSuffixes, function(suffixes) {
- var matcherOptions = {};
- suffixes.forEach(function(suffix) {
- _.extend(matcherOptions, suffix);
- });
- return matcherOptions;
- });
- }
-
- var paragraphOrRun = sequence(
- sequence.capture(elementTypeRule),
- sequence.capture(createMatcherSuffixesRule([
- styleIdRule,
- styleNameRule,
- listRule
- ]))
- ).map(function(createMatcher, matcherOptions) {
- return createMatcher(matcherOptions);
- });
-
- var table = sequence(
- lop.rules.token("identifier", "table"),
- sequence.capture(createMatcherSuffixesRule([
- styleIdRule,
- styleNameRule
- ]))
- ).map(function(options) {
- return documentMatchers.table(options);
- });
- var bold = identifierToConstant("b", documentMatchers.bold);
- var italic = identifierToConstant("i", documentMatchers.italic);
- var underline = identifierToConstant("u", documentMatchers.underline);
- var strikethrough = identifierToConstant("strike", documentMatchers.strikethrough);
- var smallCaps = identifierToConstant("small-caps", documentMatchers.smallCaps);
- var commentReference = identifierToConstant("comment-reference", documentMatchers.commentReference);
-
- var breakMatcher = sequence(
- lop.rules.token("identifier", "br"),
- sequence.cut(),
- lop.rules.tokenOfType("open-square-bracket"),
- lop.rules.token("identifier", "type"),
- lop.rules.tokenOfType("equals"),
- sequence.capture(stringRule),
- lop.rules.tokenOfType("close-square-bracket")
- ).map(function(breakType) {
- switch (breakType) {
- case "line":
- return documentMatchers.lineBreak;
- case "page":
- return documentMatchers.pageBreak;
- case "column":
- return documentMatchers.columnBreak;
- default:
- // TODO: handle unknown document matchers
- }
- });
- return lop.rules.firstOf("element type",
- paragraphOrRun,
- table,
- bold,
- italic,
- underline,
- strikethrough,
- smallCaps,
- commentReference,
- breakMatcher
- );
- }
- function readHtmlPath(string) {
- return parseString(htmlPathRule(), string);
- }
- function htmlPathRule() {
- var capture = lop.rules.sequence.capture;
- var whitespaceRule = lop.rules.tokenOfType("whitespace");
- var freshRule = lop.rules.then(
- lop.rules.optional(lop.rules.sequence(
- lop.rules.tokenOfType("colon"),
- lop.rules.token("identifier", "fresh")
- )),
- function(option) {
- return option.map(function() {
- return true;
- }).valueOrElse(false);
- }
- );
-
- var separatorRule = lop.rules.then(
- lop.rules.optional(lop.rules.sequence(
- lop.rules.tokenOfType("colon"),
- lop.rules.token("identifier", "separator"),
- lop.rules.tokenOfType("open-paren"),
- capture(stringRule),
- lop.rules.tokenOfType("close-paren")
- ).head()),
- function(option) {
- return option.valueOrElse("");
- }
- );
- var tagNamesRule = lop.rules.oneOrMoreWithSeparator(
- identifierRule,
- lop.rules.tokenOfType("choice")
- );
-
- var styleElementRule = lop.rules.sequence(
- capture(tagNamesRule),
- capture(lop.rules.zeroOrMore(classRule)),
- capture(freshRule),
- capture(separatorRule)
- ).map(function(tagName, classNames, fresh, separator) {
- var attributes = {};
- var options = {};
- if (classNames.length > 0) {
- attributes["class"] = classNames.join(" ");
- }
- if (fresh) {
- options.fresh = true;
- }
- if (separator) {
- options.separator = separator;
- }
- return htmlPaths.element(tagName, attributes, options);
- });
-
- return lop.rules.firstOf("html path",
- lop.rules.then(lop.rules.tokenOfType("bang"), function() {
- return htmlPaths.ignore;
- }),
- lop.rules.then(
- lop.rules.zeroOrMoreWithSeparator(
- styleElementRule,
- lop.rules.sequence(
- whitespaceRule,
- lop.rules.tokenOfType("gt"),
- whitespaceRule
- )
- ),
- htmlPaths.elements
- )
- );
- }
-
- var identifierRule = lop.rules.then(
- lop.rules.tokenOfType("identifier"),
- decodeEscapeSequences
- );
- var integerRule = lop.rules.tokenOfType("integer");
- var stringRule = lop.rules.then(
- lop.rules.tokenOfType("string"),
- decodeEscapeSequences
- );
- var escapeSequences = {
- "n": "\n",
- "r": "\r",
- "t": "\t"
- };
- function decodeEscapeSequences(value) {
- return value.replace(/\\(.)/g, function(match, code) {
- return escapeSequences[code] || code;
- });
- }
- var classRule = lop.rules.sequence(
- lop.rules.tokenOfType("dot"),
- lop.rules.sequence.cut(),
- lop.rules.sequence.capture(identifierRule)
- ).head();
- function parseString(rule, string) {
- var tokens = tokenise(string);
- var parser = lop.Parser();
- var parseResult = parser.parseTokens(rule, tokens);
- if (parseResult.isSuccess()) {
- return results.success(parseResult.value());
- } else {
- return new results.Result(null, [results.warning(describeFailure(string, parseResult))]);
- }
- }
- function describeFailure(input, parseResult) {
- return "Did not understand this style mapping, so ignored it: " + input + "\n" +
- parseResult.errors().map(describeError).join("\n");
- }
- function describeError(error) {
- return "Error was at character number " + error.characterNumber() + ": " +
- "Expected " + error.expected + " but got " + error.actual;
- }
- var styleRule = createStyleRule();
- },{"./results":24,"./styles/document-matchers":26,"./styles/html-paths":27,"./styles/parser/tokeniser":28,"lop":107,"underscore":153}],26:[function(require,module,exports){
- exports.paragraph = paragraph;
- exports.run = run;
- exports.table = table;
- exports.bold = new Matcher("bold");
- exports.italic = new Matcher("italic");
- exports.underline = new Matcher("underline");
- exports.strikethrough = new Matcher("strikethrough");
- exports.smallCaps = new Matcher("smallCaps");
- exports.commentReference = new Matcher("commentReference");
- exports.lineBreak = new Matcher("break", {breakType: "line"});
- exports.pageBreak = new Matcher("break", {breakType: "page"});
- exports.columnBreak = new Matcher("break", {breakType: "column"});
- exports.equalTo = equalTo;
- exports.startsWith = startsWith;
- function paragraph(options) {
- return new Matcher("paragraph", options);
- }
- function run(options) {
- return new Matcher("run", options);
- }
- function table(options) {
- return new Matcher("table", options);
- }
- function Matcher(elementType, options) {
- options = options || {};
- this._elementType = elementType;
- this._styleId = options.styleId;
- this._styleName = options.styleName;
- if (options.list) {
- this._listIndex = options.list.levelIndex;
- this._listIsOrdered = options.list.isOrdered;
- }
- }
- Matcher.prototype.matches = function(element) {
- return element.type === this._elementType &&
- (this._styleId === undefined || element.styleId === this._styleId) &&
- (this._styleName === undefined || (element.styleName && this._styleName.operator(this._styleName.operand, element.styleName))) &&
- (this._listIndex === undefined || isList(element, this._listIndex, this._listIsOrdered)) &&
- (this._breakType === undefined || this._breakType === element.breakType);
- };
- function isList(element, levelIndex, isOrdered) {
- return element.numbering &&
- element.numbering.level == levelIndex &&
- element.numbering.isOrdered == isOrdered;
- }
- function equalTo(value) {
- return {
- operator: operatorEqualTo,
- operand: value
- };
- }
- function startsWith(value) {
- return {
- operator: operatorStartsWith,
- operand: value
- };
- }
- function operatorEqualTo(first, second) {
- return first.toUpperCase() === second.toUpperCase();
- }
- function operatorStartsWith(first, second) {
- return second.toUpperCase().indexOf(first.toUpperCase()) === 0;
- }
- },{}],27:[function(require,module,exports){
- var _ = require("underscore");
- var html = require("../html");
- exports.topLevelElement = topLevelElement;
- exports.elements = elements;
- exports.element = element;
- function topLevelElement(tagName, attributes) {
- return elements([element(tagName, attributes, {fresh: true})]);
- }
- function elements(elementStyles) {
- return new HtmlPath(elementStyles.map(function(elementStyle) {
- if (_.isString(elementStyle)) {
- return element(elementStyle);
- } else {
- return elementStyle;
- }
- }));
- }
- function HtmlPath(elements) {
- this._elements = elements;
- }
- HtmlPath.prototype.wrap = function wrap(children) {
- var result = children();
- for (var index = this._elements.length - 1; index >= 0; index--) {
- result = this._elements[index].wrapNodes(result);
- }
- return result;
- };
- function element(tagName, attributes, options) {
- options = options || {};
- return new Element(tagName, attributes, options);
- }
- function Element(tagName, attributes, options) {
- var tagNames = {};
- if (_.isArray(tagName)) {
- tagName.forEach(function(tagName) {
- tagNames[tagName] = true;
- });
- tagName = tagName[0];
- } else {
- tagNames[tagName] = true;
- }
-
- this.tagName = tagName;
- this.tagNames = tagNames;
- this.attributes = attributes || {};
- this.fresh = options.fresh;
- this.separator = options.separator;
- }
- Element.prototype.matchesElement = function(element) {
- return this.tagNames[element.tagName] && _.isEqual(this.attributes || {}, element.attributes || {});
- };
- Element.prototype.wrap = function wrap(generateNodes) {
- return this.wrapNodes(generateNodes());
- };
- Element.prototype.wrapNodes = function wrapNodes(nodes) {
- return [html.elementWithTag(this, nodes)];
- };
- exports.empty = elements([]);
- exports.ignore = {
- wrap: function() {
- return [];
- }
- };
- },{"../html":18,"underscore":153}],28:[function(require,module,exports){
- var lop = require("lop");
- var RegexTokeniser = lop.RegexTokeniser;
- exports.tokenise = tokenise;
- var stringPrefix = "'((?:\\\\.|[^'])*)";
- function tokenise(string) {
- var identifierCharacter = "(?:[a-zA-Z\\-_]|\\\\.)";
- var tokeniser = new RegexTokeniser([
- {name: "identifier", regex: new RegExp("(" + identifierCharacter + "(?:" + identifierCharacter + "|[0-9])*)")},
- {name: "dot", regex: /\./},
- {name: "colon", regex: /:/},
- {name: "gt", regex: />/},
- {name: "whitespace", regex: /\s+/},
- {name: "arrow", regex: /=>/},
- {name: "equals", regex: /=/},
- {name: "startsWith", regex: /\^=/},
- {name: "open-paren", regex: /\(/},
- {name: "close-paren", regex: /\)/},
- {name: "open-square-bracket", regex: /\[/},
- {name: "close-square-bracket", regex: /\]/},
- {name: "string", regex: new RegExp(stringPrefix + "'")},
- {name: "unterminated-string", regex: new RegExp(stringPrefix)},
- {name: "integer", regex: /([0-9]+)/},
- {name: "choice", regex: /\|/},
- {name: "bang", regex: /(!)/}
- ]);
- return tokeniser.tokenise(string);
- }
- },{"lop":107}],29:[function(require,module,exports){
- var _ = require("underscore");
- exports.paragraph = paragraph;
- exports.run = run;
- exports._elements = elements;
- exports.getDescendantsOfType = getDescendantsOfType;
- exports.getDescendants = getDescendants;
- function paragraph(transform) {
- return elementsOfType("paragraph", transform);
- }
- function run(transform) {
- return elementsOfType("run", transform);
- }
- function elementsOfType(elementType, transform) {
- return elements(function(element) {
- if (element.type === elementType) {
- return transform(element);
- } else {
- return element;
- }
- });
- }
- function elements(transform) {
- return function transformElement(element) {
- if (element.children) {
- var children = _.map(element.children, transformElement);
- element = _.extend(element, {children: children});
- }
- return transform(element);
- };
- }
- function getDescendantsOfType(element, type) {
- return getDescendants(element).filter(function(descendant) {
- return descendant.type === type;
- });
- }
- function getDescendants(element) {
- var descendants = [];
- visitDescendants(element, function(descendant) {
- descendants.push(descendant);
- });
- return descendants;
- }
- function visitDescendants(element, visit) {
- if (element.children) {
- element.children.forEach(function(child) {
- visitDescendants(child, visit);
- visit(child);
- });
- }
- }
- },{"underscore":153}],30:[function(require,module,exports){
- var htmlPaths = require("./styles/html-paths");
- var Html = require("./html");
- exports.element = element;
- function element(name) {
- return function(html) {
- return Html.elementWithTag(htmlPaths.element(name), [html]);
- };
- }
- },{"./html":18,"./styles/html-paths":27}],31:[function(require,module,exports){
- var util = require("util");
- var _ = require("underscore");
- exports.writer = writer;
- function writer(options) {
- options = options || {};
- if (options.prettyPrint) {
- return prettyWriter();
- } else {
- return simpleWriter();
- }
- }
- var indentedElements = {
- div: true,
- p: true,
- ul: true,
- li: true
- };
- function prettyWriter() {
- var indentationLevel = 0;
- var indentation = " ";
- var stack = [];
- var start = true;
- var inText = false;
-
- var writer = simpleWriter();
-
- function open(tagName, attributes) {
- if (indentedElements[tagName]) {
- indent();
- }
- stack.push(tagName);
- writer.open(tagName, attributes);
- if (indentedElements[tagName]) {
- indentationLevel++;
- }
- start = false;
- }
-
- function close(tagName) {
- if (indentedElements[tagName]) {
- indentationLevel--;
- indent();
- }
- stack.pop();
- writer.close(tagName);
- }
-
- function text(value) {
- startText();
- var text = isInPre() ? value : value.replace("\n", "\n" + indentation);
- writer.text(text);
- }
-
- function selfClosing(tagName, attributes) {
- indent();
- writer.selfClosing(tagName, attributes);
- }
-
- function insideIndentedElement() {
- return stack.length === 0 || indentedElements[stack[stack.length - 1]];
- }
-
- function startText() {
- if (!inText) {
- indent();
- inText = true;
- }
- }
-
- function indent() {
- inText = false;
- if (!start && insideIndentedElement() && !isInPre()) {
- writer._append("\n");
- for (var i = 0; i < indentationLevel; i++) {
- writer._append(indentation);
- }
- }
- }
-
- function isInPre() {
- return _.some(stack, function(tagName) {
- return tagName === "pre";
- });
- }
-
- return {
- asString: writer.asString,
- open: open,
- close: close,
- text: text,
- selfClosing: selfClosing
- };
- }
- function simpleWriter() {
- var fragments = [];
-
- function open(tagName, attributes) {
- var attributeString = generateAttributeString(attributes);
- fragments.push(util.format("<%s%s>", tagName, attributeString));
- }
-
- function close(tagName) {
- fragments.push(util.format("</%s>", tagName));
- }
-
- function selfClosing(tagName, attributes) {
- var attributeString = generateAttributeString(attributes);
- fragments.push(util.format("<%s%s />", tagName, attributeString));
- }
-
- function generateAttributeString(attributes) {
- return _.map(attributes, function(value, key) {
- return util.format(' %s="%s"', key, escapeHtmlAttribute(value));
- }).join("");
- }
-
- function text(value) {
- fragments.push(escapeHtmlText(value));
- }
-
- function append(html) {
- fragments.push(html);
- }
-
- function asString() {
- return fragments.join("");
- }
-
- return {
- asString: asString,
- open: open,
- close: close,
- text: text,
- selfClosing: selfClosing,
- _append: append
- };
- }
- function escapeHtmlText(value) {
- return value
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>');
- }
- function escapeHtmlAttribute(value) {
- return value
- .replace(/&/g, '&')
- .replace(/"/g, '"')
- .replace(/</g, '<')
- .replace(/>/g, '>');
- }
- },{"underscore":153,"util":157}],32:[function(require,module,exports){
- var htmlWriter = require("./html-writer");
- var markdownWriter = require("./markdown-writer");
- exports.writer = writer;
- function writer(options) {
- options = options || {};
- if (options.outputFormat === "markdown") {
- return markdownWriter.writer();
- } else {
- return htmlWriter.writer(options);
- }
- }
- },{"./html-writer":31,"./markdown-writer":33}],33:[function(require,module,exports){
- var _ = require("underscore");
- function symmetricMarkdownElement(end) {
- return markdownElement(end, end);
- }
- function markdownElement(start, end) {
- return function() {
- return {start: start, end: end};
- };
- }
- function markdownLink(attributes) {
- var href = attributes.href || "";
- if (href) {
- return {
- start: "[",
- end: "](" + href + ")",
- anchorPosition: "before"
- };
- } else {
- return {};
- }
- }
- function markdownImage(attributes) {
- var src = attributes.src || "";
- var altText = attributes.alt || "";
- if (src || altText) {
- return {start: "![" + altText + "](" + src + ")"};
- } else {
- return {};
- }
- }
- function markdownList(options) {
- return function(attributes, list) {
- return {
- start: list ? "\n" : "",
- end: list ? "" : "\n",
- list: {
- isOrdered: options.isOrdered,
- indent: list ? list.indent + 1 : 0,
- count: 0
- }
- };
- };
- }
- function markdownListItem(attributes, list, listItem) {
- list = list || {indent: 0, isOrdered: false, count: 0};
- list.count++;
- listItem.hasClosed = false;
-
- var bullet = list.isOrdered ? list.count + "." : "-";
- var start = repeatString("\t", list.indent) + bullet + " ";
-
- return {
- start: start,
- end: function() {
- if (!listItem.hasClosed) {
- listItem.hasClosed = true;
- return "\n";
- }
- }
- };
- }
- var htmlToMarkdown = {
- "p": markdownElement("", "\n\n"),
- "br": markdownElement("", " \n"),
- "ul": markdownList({isOrdered: false}),
- "ol": markdownList({isOrdered: true}),
- "li": markdownListItem,
- "strong": symmetricMarkdownElement("__"),
- "em": symmetricMarkdownElement("*"),
- "a": markdownLink,
- "img": markdownImage
- };
- (function() {
- for (var i = 1; i <= 6; i++) {
- htmlToMarkdown["h" + i] = markdownElement(repeatString("#", i) + " ", "\n\n");
- }
- })();
- function repeatString(value, count) {
- return new Array(count + 1).join(value);
- }
- function markdownWriter() {
- var fragments = [];
- var elementStack = [];
- var list = null;
- var listItem = {};
-
- function open(tagName, attributes) {
- attributes = attributes || {};
-
- var createElement = htmlToMarkdown[tagName] || function() {
- return {};
- };
- var element = createElement(attributes, list, listItem);
- elementStack.push({end: element.end, list: list});
-
- if (element.list) {
- list = element.list;
- }
-
- var anchorBeforeStart = element.anchorPosition === "before";
- if (anchorBeforeStart) {
- writeAnchor(attributes);
- }
- fragments.push(element.start || "");
- if (!anchorBeforeStart) {
- writeAnchor(attributes);
- }
- }
-
- function writeAnchor(attributes) {
- if (attributes.id) {
- fragments.push('<a id="' + attributes.id + '"></a>');
- }
- }
-
- function close(tagName) {
- var element = elementStack.pop();
- list = element.list;
- var end = _.isFunction(element.end) ? element.end() : element.end;
- fragments.push(end || "");
- }
-
- function selfClosing(tagName, attributes) {
- open(tagName, attributes);
- close(tagName);
- }
-
- function text(value) {
- fragments.push(escapeMarkdown(value));
- }
-
- function asString() {
- return fragments.join("");
- }
- return {
- asString: asString,
- open: open,
- close: close,
- text: text,
- selfClosing: selfClosing
- };
- }
- exports.writer = markdownWriter;
- function escapeMarkdown(value) {
- return value
- .replace(/\\/g, '\\\\')
- .replace(/([\`\*_\{\}\[\]\(\)\#\+\-\.\!])/g, '\\$1');
- }
- },{"underscore":153}],34:[function(require,module,exports){
- var nodes = require("./nodes");
- exports.Element = nodes.Element;
- exports.element = nodes.element;
- exports.text = nodes.text;
- exports.readString = require("./reader").readString;
- exports.writeString = require("./writer").writeString;
- },{"./nodes":35,"./reader":36,"./writer":37}],35:[function(require,module,exports){
- var _ = require("underscore");
- exports.Element = Element;
- exports.element = function(name, attributes, children) {
- return new Element(name, attributes, children);
- };
- exports.text = function(value) {
- return {
- type: "text",
- value: value
- };
- };
- var emptyElement = {
- first: function() {
- return null;
- },
- firstOrEmpty: function() {
- return emptyElement;
- },
- attributes: {}
- };
- function Element(name, attributes, children) {
- this.type = "element";
- this.name = name;
- this.attributes = attributes || {};
- this.children = children || [];
- }
- Element.prototype.first = function(name) {
- return _.find(this.children, function(child) {
- return child.name === name;
- });
- };
- Element.prototype.firstOrEmpty = function(name) {
- return this.first(name) || emptyElement;
- };
- Element.prototype.getElementsByTagName = function(name) {
- var elements = _.filter(this.children, function(child) {
- return child.name === name;
- });
- return toElementList(elements);
- };
- Element.prototype.text = function() {
- if (this.children.length === 0) {
- return "";
- } else if (this.children.length !== 1 || this.children[0].type !== "text") {
- throw new Error("Not implemented");
- }
- return this.children[0].value;
- };
- var elementListPrototype = {
- getElementsByTagName: function(name) {
- return toElementList(_.flatten(this.map(function(element) {
- return element.getElementsByTagName(name);
- }, true)));
- }
- };
- function toElementList(array) {
- return _.extend(array, elementListPrototype);
- }
- },{"underscore":153}],36:[function(require,module,exports){
- var promises = require("../promises");
- var sax = require("sax");
- var _ = require("underscore");
- var nodes = require("./nodes");
- var Element = nodes.Element;
- exports.readString = readString;
- function readString(xmlString, namespaceMap) {
- namespaceMap = namespaceMap || {};
-
- var finished = false;
- var parser = sax.parser(true, {xmlns: true, position: false});
-
- var rootElement = {children: []};
- var currentElement = rootElement;
- var stack = [];
-
- var deferred = promises.defer();
-
- parser.onopentag = function(node) {
- var attributes = mapObject(node.attributes, function(attribute) {
- return attribute.value;
- }, mapName);
-
- var element = new Element(mapName(node), attributes);
- currentElement.children.push(element);
- stack.push(currentElement);
- currentElement = element;
- };
-
- function mapName(node) {
- if (node.uri) {
- var mappedPrefix = namespaceMap[node.uri];
- var prefix;
- if (mappedPrefix) {
- prefix = mappedPrefix + ":";
- } else {
- prefix = "{" + node.uri + "}";
- }
- return prefix + node.local;
- } else {
- return node.local;
- }
- }
-
- parser.onclosetag = function(node) {
- currentElement = stack.pop();
- };
-
- parser.ontext = function(text) {
- if (currentElement !== rootElement) {
- currentElement.children.push(nodes.text(text));
- }
- };
-
- parser.onend = function() {
- if (!finished) {
- finished = true;
- deferred.resolve(rootElement.children[0]);
- }
- };
-
- parser.onerror = function(error) {
- if (!finished) {
- finished = true;
- deferred.reject(error);
- }
- };
-
- parser.write(xmlString).close();
-
- return deferred.promise;
- }
- function mapObject(input, valueFunc, keyFunc) {
- return _.reduce(input, function(result, value, key) {
- var mappedKey = keyFunc(value, key, input);
- result[mappedKey] = valueFunc(value, key, input);
- return result;
- }, {});
- }
- },{"../promises":23,"./nodes":35,"sax":150,"underscore":153}],37:[function(require,module,exports){
- var _ = require("underscore");
- var xmlbuilder = require("xmlbuilder");
- exports.writeString = writeString;
- function writeString(root, namespaces) {
- var uriToPrefix = _.invert(namespaces);
-
- var nodeWriters = {
- element: writeElement,
- text: writeTextNode
- };
- function writeNode(builder, node) {
- return nodeWriters[node.type](builder, node);
- }
- function writeElement(builder, element) {
- var elementBuilder = builder.element(mapElementName(element.name), element.attributes);
- element.children.forEach(function(child) {
- writeNode(elementBuilder, child);
- });
- }
-
- function mapElementName(name) {
- var longFormMatch = /^\{(.*)\}(.*)$/.exec(name);
- if (longFormMatch) {
- var prefix = uriToPrefix[longFormMatch[1]];
- return prefix + (prefix === "" ? "" : ":") + longFormMatch[2];
- } else {
- return name;
- }
- }
-
- function writeDocument(root) {
- var builder = xmlbuilder
- .create(mapElementName(root.name), {
- version: '1.0',
- encoding: 'UTF-8',
- standalone: true
- });
-
- _.forEach(namespaces, function(uri, prefix) {
- var key = "xmlns" + (prefix === "" ? "" : ":" + prefix);
- builder.attribute(key, uri);
- });
-
- root.children.forEach(function(child) {
- writeNode(builder, child);
- });
- return builder.end();
- }
- return writeDocument(root);
- }
- function writeTextNode(builder, node) {
- builder.text(node.value);
- }
- },{"underscore":153,"xmlbuilder":179}],38:[function(require,module,exports){
- (function (Buffer){
- var JSZip = require("jszip");
- var promises = require("./promises");
- exports.openArrayBuffer = openArrayBuffer;
- exports.splitPath = splitPath;
- exports.joinPath = joinPath;
- function openArrayBuffer(arrayBuffer) {
- var zipFile = new JSZip(arrayBuffer);
- function exists(name) {
- return zipFile.file(name) !== null;
- }
-
- function read(name, encoding) {
- var array = zipFile.file(name).asUint8Array();
- var buffer = new Buffer(array);
- if (encoding) {
- return promises.when(buffer.toString(encoding));
- } else {
- return promises.when(buffer);
- }
- }
-
- function write(name, contents) {
- zipFile.file(name, contents);
- }
-
- function toBuffer() {
- return zipFile.generate({type: "nodebuffer"});
- }
-
- return {
- exists: exists,
- read: read,
- write: write,
- toBuffer: toBuffer
- };
- }
- function splitPath(path) {
- var lastIndex = path.lastIndexOf("/");
- if (lastIndex === -1) {
- return {dirname: "", basename: path};
- } else {
- return {
- dirname: path.substring(0, lastIndex),
- basename: path.substring(lastIndex + 1)
- };
- }
- }
- function joinPath() {
- var nonEmptyPaths = Array.prototype.filter.call(arguments, function(path) {
- return path;
- });
-
- var relevantPaths = [];
-
- nonEmptyPaths.forEach(function(path) {
- if (/^\//.test(path)) {
- relevantPaths = [path];
- } else {
- relevantPaths.push(path);
- }
- });
-
- return relevantPaths.join("/");
- }
- }).call(this,require("buffer").Buffer)
- },{"./promises":23,"buffer":77,"jszip":92}],39:[function(require,module,exports){
- 'use strict'
- exports.byteLength = byteLength
- exports.toByteArray = toByteArray
- exports.fromByteArray = fromByteArray
- var lookup = []
- var revLookup = []
- var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
- var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
- for (var i = 0, len = code.length; i < len; ++i) {
- lookup[i] = code[i]
- revLookup[code.charCodeAt(i)] = i
- }
- revLookup['-'.charCodeAt(0)] = 62
- revLookup['_'.charCodeAt(0)] = 63
- function placeHoldersCount (b64) {
- var len = b64.length
- if (len % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
- }
- // the number of equal signs (place holders)
- // if there are two placeholders, than the two characters before it
- // represent one byte
- // if there is only one, then the three characters before it represent 2 bytes
- // this is just a cheap hack to not do indexOf twice
- return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
- }
- function byteLength (b64) {
- // base64 is 4/3 + up to two characters of the original data
- return b64.length * 3 / 4 - placeHoldersCount(b64)
- }
- function toByteArray (b64) {
- var i, j, l, tmp, placeHolders, arr
- var len = b64.length
- placeHolders = placeHoldersCount(b64)
- arr = new Arr(len * 3 / 4 - placeHolders)
- // if there are placeholders, only get up to the last complete 4 chars
- l = placeHolders > 0 ? len - 4 : len
- var L = 0
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
- tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
- arr[L++] = (tmp >> 16) & 0xFF
- arr[L++] = (tmp >> 8) & 0xFF
- arr[L++] = tmp & 0xFF
- }
- if (placeHolders === 2) {
- tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
- arr[L++] = tmp & 0xFF
- } else if (placeHolders === 1) {
- tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
- arr[L++] = (tmp >> 8) & 0xFF
- arr[L++] = tmp & 0xFF
- }
- return arr
- }
- function tripletToBase64 (num) {
- return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
- }
- function encodeChunk (uint8, start, end) {
- var tmp
- var output = []
- for (var i = start; i < end; i += 3) {
- tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
- output.push(tripletToBase64(tmp))
- }
- return output.join('')
- }
- function fromByteArray (uint8) {
- var tmp
- var len = uint8.length
- var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
- var output = ''
- var parts = []
- var maxChunkLength = 16383 // must be multiple of 3
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
- parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
- }
- // pad the end with zeros, but make sure to not forget the extra bytes
- if (extraBytes === 1) {
- tmp = uint8[len - 1]
- output += lookup[tmp >> 2]
- output += lookup[(tmp << 4) & 0x3F]
- output += '=='
- } else if (extraBytes === 2) {
- tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
- output += lookup[tmp >> 10]
- output += lookup[(tmp >> 4) & 0x3F]
- output += lookup[(tmp << 2) & 0x3F]
- output += '='
- }
- parts.push(output)
- return parts.join('')
- }
- },{}],40:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var SomePromiseArray = Promise._SomePromiseArray;
- function any(promises) {
- var ret = new SomePromiseArray(promises);
- var promise = ret.promise();
- ret.setHowMany(1);
- ret.setUnwrap();
- ret.init();
- return promise;
- }
- Promise.any = function (promises) {
- return any(promises);
- };
- Promise.prototype.any = function () {
- return any(this);
- };
- };
- },{}],41:[function(require,module,exports){
- (function (process){
- "use strict";
- var firstLineError;
- try {throw new Error(); } catch (e) {firstLineError = e;}
- var schedule = require("./schedule");
- var Queue = require("./queue");
- var util = require("./util");
- function Async() {
- this._customScheduler = false;
- this._isTickUsed = false;
- this._lateQueue = new Queue(16);
- this._normalQueue = new Queue(16);
- this._haveDrainedQueues = false;
- this._trampolineEnabled = true;
- var self = this;
- this.drainQueues = function () {
- self._drainQueues();
- };
- this._schedule = schedule;
- }
- Async.prototype.setScheduler = function(fn) {
- var prev = this._schedule;
- this._schedule = fn;
- this._customScheduler = true;
- return prev;
- };
- Async.prototype.hasCustomScheduler = function() {
- return this._customScheduler;
- };
- Async.prototype.enableTrampoline = function() {
- this._trampolineEnabled = true;
- };
- Async.prototype.disableTrampolineIfNecessary = function() {
- if (util.hasDevTools) {
- this._trampolineEnabled = false;
- }
- };
- Async.prototype.haveItemsQueued = function () {
- return this._isTickUsed || this._haveDrainedQueues;
- };
- Async.prototype.fatalError = function(e, isNode) {
- if (isNode) {
- process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
- "\n");
- process.exit(2);
- } else {
- this.throwLater(e);
- }
- };
- Async.prototype.throwLater = function(fn, arg) {
- if (arguments.length === 1) {
- arg = fn;
- fn = function () { throw arg; };
- }
- if (typeof setTimeout !== "undefined") {
- setTimeout(function() {
- fn(arg);
- }, 0);
- } else try {
- this._schedule(function() {
- fn(arg);
- });
- } catch (e) {
- throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- };
- function AsyncInvokeLater(fn, receiver, arg) {
- this._lateQueue.push(fn, receiver, arg);
- this._queueTick();
- }
- function AsyncInvoke(fn, receiver, arg) {
- this._normalQueue.push(fn, receiver, arg);
- this._queueTick();
- }
- function AsyncSettlePromises(promise) {
- this._normalQueue._pushOne(promise);
- this._queueTick();
- }
- if (!util.hasDevTools) {
- Async.prototype.invokeLater = AsyncInvokeLater;
- Async.prototype.invoke = AsyncInvoke;
- Async.prototype.settlePromises = AsyncSettlePromises;
- } else {
- Async.prototype.invokeLater = function (fn, receiver, arg) {
- if (this._trampolineEnabled) {
- AsyncInvokeLater.call(this, fn, receiver, arg);
- } else {
- this._schedule(function() {
- setTimeout(function() {
- fn.call(receiver, arg);
- }, 100);
- });
- }
- };
- Async.prototype.invoke = function (fn, receiver, arg) {
- if (this._trampolineEnabled) {
- AsyncInvoke.call(this, fn, receiver, arg);
- } else {
- this._schedule(function() {
- fn.call(receiver, arg);
- });
- }
- };
- Async.prototype.settlePromises = function(promise) {
- if (this._trampolineEnabled) {
- AsyncSettlePromises.call(this, promise);
- } else {
- this._schedule(function() {
- promise._settlePromises();
- });
- }
- };
- }
- Async.prototype._drainQueue = function(queue) {
- while (queue.length() > 0) {
- var fn = queue.shift();
- if (typeof fn !== "function") {
- fn._settlePromises();
- continue;
- }
- var receiver = queue.shift();
- var arg = queue.shift();
- fn.call(receiver, arg);
- }
- };
- Async.prototype._drainQueues = function () {
- this._drainQueue(this._normalQueue);
- this._reset();
- this._haveDrainedQueues = true;
- this._drainQueue(this._lateQueue);
- };
- Async.prototype._queueTick = function () {
- if (!this._isTickUsed) {
- this._isTickUsed = true;
- this._schedule(this.drainQueues);
- }
- };
- Async.prototype._reset = function () {
- this._isTickUsed = false;
- };
- module.exports = Async;
- module.exports.firstLineError = firstLineError;
- }).call(this,require('_process'))
- },{"./queue":64,"./schedule":67,"./util":74,"_process":138}],42:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
- var calledBind = false;
- var rejectThis = function(_, e) {
- this._reject(e);
- };
- var targetRejected = function(e, context) {
- context.promiseRejectionQueued = true;
- context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
- };
- var bindingResolved = function(thisArg, context) {
- if (((this._bitField & 50397184) === 0)) {
- this._resolveCallback(context.target);
- }
- };
- var bindingRejected = function(e, context) {
- if (!context.promiseRejectionQueued) this._reject(e);
- };
- Promise.prototype.bind = function (thisArg) {
- if (!calledBind) {
- calledBind = true;
- Promise.prototype._propagateFrom = debug.propagateFromFunction();
- Promise.prototype._boundValue = debug.boundValueFunction();
- }
- var maybePromise = tryConvertToPromise(thisArg);
- var ret = new Promise(INTERNAL);
- ret._propagateFrom(this, 1);
- var target = this._target();
- ret._setBoundTo(maybePromise);
- if (maybePromise instanceof Promise) {
- var context = {
- promiseRejectionQueued: false,
- promise: ret,
- target: target,
- bindingPromise: maybePromise
- };
- target._then(INTERNAL, targetRejected, undefined, ret, context);
- maybePromise._then(
- bindingResolved, bindingRejected, undefined, ret, context);
- ret._setOnCancel(maybePromise);
- } else {
- ret._resolveCallback(target);
- }
- return ret;
- };
- Promise.prototype._setBoundTo = function (obj) {
- if (obj !== undefined) {
- this._bitField = this._bitField | 2097152;
- this._boundTo = obj;
- } else {
- this._bitField = this._bitField & (~2097152);
- }
- };
- Promise.prototype._isBound = function () {
- return (this._bitField & 2097152) === 2097152;
- };
- Promise.bind = function (thisArg, value) {
- return Promise.resolve(value).bind(thisArg);
- };
- };
- },{}],43:[function(require,module,exports){
- "use strict";
- var cr = Object.create;
- if (cr) {
- var callerCache = cr(null);
- var getterCache = cr(null);
- callerCache[" size"] = getterCache[" size"] = 0;
- }
- module.exports = function(Promise) {
- var util = require("./util");
- var canEvaluate = util.canEvaluate;
- var isIdentifier = util.isIdentifier;
- var getMethodCaller;
- var getGetter;
- if (!false) {
- var makeMethodCaller = function (methodName) {
- return new Function("ensureMethod", " \n\
- return function(obj) { \n\
- 'use strict' \n\
- var len = this.length; \n\
- ensureMethod(obj, 'methodName'); \n\
- switch(len) { \n\
- case 1: return obj.methodName(this[0]); \n\
- case 2: return obj.methodName(this[0], this[1]); \n\
- case 3: return obj.methodName(this[0], this[1], this[2]); \n\
- case 0: return obj.methodName(); \n\
- default: \n\
- return obj.methodName.apply(obj, this); \n\
- } \n\
- }; \n\
- ".replace(/methodName/g, methodName))(ensureMethod);
- };
- var makeGetter = function (propertyName) {
- return new Function("obj", " \n\
- 'use strict'; \n\
- return obj.propertyName; \n\
- ".replace("propertyName", propertyName));
- };
- var getCompiled = function(name, compiler, cache) {
- var ret = cache[name];
- if (typeof ret !== "function") {
- if (!isIdentifier(name)) {
- return null;
- }
- ret = compiler(name);
- cache[name] = ret;
- cache[" size"]++;
- if (cache[" size"] > 512) {
- var keys = Object.keys(cache);
- for (var i = 0; i < 256; ++i) delete cache[keys[i]];
- cache[" size"] = keys.length - 256;
- }
- }
- return ret;
- };
- getMethodCaller = function(name) {
- return getCompiled(name, makeMethodCaller, callerCache);
- };
- getGetter = function(name) {
- return getCompiled(name, makeGetter, getterCache);
- };
- }
- function ensureMethod(obj, methodName) {
- var fn;
- if (obj != null) fn = obj[methodName];
- if (typeof fn !== "function") {
- var message = "Object " + util.classString(obj) + " has no method '" +
- util.toString(methodName) + "'";
- throw new Promise.TypeError(message);
- }
- return fn;
- }
- function caller(obj) {
- var methodName = this.pop();
- var fn = ensureMethod(obj, methodName);
- return fn.apply(obj, this);
- }
- Promise.prototype.call = function (methodName) {
- 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];};
- if (!false) {
- if (canEvaluate) {
- var maybeCaller = getMethodCaller(methodName);
- if (maybeCaller !== null) {
- return this._then(
- maybeCaller, undefined, undefined, args, undefined);
- }
- }
- }
- args.push(methodName);
- return this._then(caller, undefined, undefined, args, undefined);
- };
- function namedGetter(obj) {
- return obj[this];
- }
- function indexedGetter(obj) {
- var index = +this;
- if (index < 0) index = Math.max(0, index + obj.length);
- return obj[index];
- }
- Promise.prototype.get = function (propertyName) {
- var isIndex = (typeof propertyName === "number");
- var getter;
- if (!isIndex) {
- if (canEvaluate) {
- var maybeGetter = getGetter(propertyName);
- getter = maybeGetter !== null ? maybeGetter : namedGetter;
- } else {
- getter = namedGetter;
- }
- } else {
- getter = indexedGetter;
- }
- return this._then(getter, undefined, undefined, propertyName, undefined);
- };
- };
- },{"./util":74}],44:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, PromiseArray, apiRejection, debug) {
- var util = require("./util");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var async = Promise._async;
- Promise.prototype["break"] = Promise.prototype.cancel = function() {
- if (!debug.cancellation()) return this._warn("cancellation is disabled");
- var promise = this;
- var child = promise;
- while (promise._isCancellable()) {
- if (!promise._cancelBy(child)) {
- if (child._isFollowing()) {
- child._followee().cancel();
- } else {
- child._cancelBranched();
- }
- break;
- }
- var parent = promise._cancellationParent;
- if (parent == null || !parent._isCancellable()) {
- if (promise._isFollowing()) {
- promise._followee().cancel();
- } else {
- promise._cancelBranched();
- }
- break;
- } else {
- if (promise._isFollowing()) promise._followee().cancel();
- promise._setWillBeCancelled();
- child = promise;
- promise = parent;
- }
- }
- };
- Promise.prototype._branchHasCancelled = function() {
- this._branchesRemainingToCancel--;
- };
- Promise.prototype._enoughBranchesHaveCancelled = function() {
- return this._branchesRemainingToCancel === undefined ||
- this._branchesRemainingToCancel <= 0;
- };
- Promise.prototype._cancelBy = function(canceller) {
- if (canceller === this) {
- this._branchesRemainingToCancel = 0;
- this._invokeOnCancel();
- return true;
- } else {
- this._branchHasCancelled();
- if (this._enoughBranchesHaveCancelled()) {
- this._invokeOnCancel();
- return true;
- }
- }
- return false;
- };
- Promise.prototype._cancelBranched = function() {
- if (this._enoughBranchesHaveCancelled()) {
- this._cancel();
- }
- };
- Promise.prototype._cancel = function() {
- if (!this._isCancellable()) return;
- this._setCancelled();
- async.invoke(this._cancelPromises, this, undefined);
- };
- Promise.prototype._cancelPromises = function() {
- if (this._length() > 0) this._settlePromises();
- };
- Promise.prototype._unsetOnCancel = function() {
- this._onCancelField = undefined;
- };
- Promise.prototype._isCancellable = function() {
- return this.isPending() && !this._isCancelled();
- };
- Promise.prototype.isCancellable = function() {
- return this.isPending() && !this.isCancelled();
- };
- Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
- if (util.isArray(onCancelCallback)) {
- for (var i = 0; i < onCancelCallback.length; ++i) {
- this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
- }
- } else if (onCancelCallback !== undefined) {
- if (typeof onCancelCallback === "function") {
- if (!internalOnly) {
- var e = tryCatch(onCancelCallback).call(this._boundValue());
- if (e === errorObj) {
- this._attachExtraTrace(e.e);
- async.throwLater(e.e);
- }
- }
- } else {
- onCancelCallback._resultCancelled(this);
- }
- }
- };
- Promise.prototype._invokeOnCancel = function() {
- var onCancelCallback = this._onCancel();
- this._unsetOnCancel();
- async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
- };
- Promise.prototype._invokeInternalOnCancel = function() {
- if (this._isCancellable()) {
- this._doInvokeOnCancel(this._onCancel(), true);
- this._unsetOnCancel();
- }
- };
- Promise.prototype._resultCancelled = function() {
- this.cancel();
- };
- };
- },{"./util":74}],45:[function(require,module,exports){
- "use strict";
- module.exports = function(NEXT_FILTER) {
- var util = require("./util");
- var getKeys = require("./es5").keys;
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- function catchFilter(instances, cb, promise) {
- return function(e) {
- var boundTo = promise._boundValue();
- predicateLoop: for (var i = 0; i < instances.length; ++i) {
- var item = instances[i];
- if (item === Error ||
- (item != null && item.prototype instanceof Error)) {
- if (e instanceof item) {
- return tryCatch(cb).call(boundTo, e);
- }
- } else if (typeof item === "function") {
- var matchesPredicate = tryCatch(item).call(boundTo, e);
- if (matchesPredicate === errorObj) {
- return matchesPredicate;
- } else if (matchesPredicate) {
- return tryCatch(cb).call(boundTo, e);
- }
- } else if (util.isObject(e)) {
- var keys = getKeys(item);
- for (var j = 0; j < keys.length; ++j) {
- var key = keys[j];
- if (item[key] != e[key]) {
- continue predicateLoop;
- }
- }
- return tryCatch(cb).call(boundTo, e);
- }
- }
- return NEXT_FILTER;
- };
- }
- return catchFilter;
- };
- },{"./es5":51,"./util":74}],46:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var longStackTraces = false;
- var contextStack = [];
- Promise.prototype._promiseCreated = function() {};
- Promise.prototype._pushContext = function() {};
- Promise.prototype._popContext = function() {return null;};
- Promise._peekContext = Promise.prototype._peekContext = function() {};
- function Context() {
- this._trace = new Context.CapturedTrace(peekContext());
- }
- Context.prototype._pushContext = function () {
- if (this._trace !== undefined) {
- this._trace._promiseCreated = null;
- contextStack.push(this._trace);
- }
- };
- Context.prototype._popContext = function () {
- if (this._trace !== undefined) {
- var trace = contextStack.pop();
- var ret = trace._promiseCreated;
- trace._promiseCreated = null;
- return ret;
- }
- return null;
- };
- function createContext() {
- if (longStackTraces) return new Context();
- }
- function peekContext() {
- var lastIndex = contextStack.length - 1;
- if (lastIndex >= 0) {
- return contextStack[lastIndex];
- }
- return undefined;
- }
- Context.CapturedTrace = null;
- Context.create = createContext;
- Context.deactivateLongStackTraces = function() {};
- Context.activateLongStackTraces = function() {
- var Promise_pushContext = Promise.prototype._pushContext;
- var Promise_popContext = Promise.prototype._popContext;
- var Promise_PeekContext = Promise._peekContext;
- var Promise_peekContext = Promise.prototype._peekContext;
- var Promise_promiseCreated = Promise.prototype._promiseCreated;
- Context.deactivateLongStackTraces = function() {
- Promise.prototype._pushContext = Promise_pushContext;
- Promise.prototype._popContext = Promise_popContext;
- Promise._peekContext = Promise_PeekContext;
- Promise.prototype._peekContext = Promise_peekContext;
- Promise.prototype._promiseCreated = Promise_promiseCreated;
- longStackTraces = false;
- };
- longStackTraces = true;
- Promise.prototype._pushContext = Context.prototype._pushContext;
- Promise.prototype._popContext = Context.prototype._popContext;
- Promise._peekContext = Promise.prototype._peekContext = peekContext;
- Promise.prototype._promiseCreated = function() {
- var ctx = this._peekContext();
- if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
- };
- };
- return Context;
- };
- },{}],47:[function(require,module,exports){
- (function (process){
- "use strict";
- module.exports = function(Promise, Context) {
- var getDomain = Promise._getDomain;
- var async = Promise._async;
- var Warning = require("./errors").Warning;
- var util = require("./util");
- var canAttachTrace = util.canAttachTrace;
- var unhandledRejectionHandled;
- var possiblyUnhandledRejection;
- var bluebirdFramePattern =
- /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
- var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
- var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
- var stackFramePattern = null;
- var formatStack = null;
- var indentStackFrames = false;
- var printWarning;
- var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
- (false ||
- util.env("BLUEBIRD_DEBUG") ||
- util.env("NODE_ENV") === "development"));
- var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
- (debugging || util.env("BLUEBIRD_WARNINGS")));
- var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
- (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
- var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
- (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
- Promise.prototype.suppressUnhandledRejections = function() {
- var target = this._target();
- target._bitField = ((target._bitField & (~1048576)) |
- 524288);
- };
- Promise.prototype._ensurePossibleRejectionHandled = function () {
- if ((this._bitField & 524288) !== 0) return;
- this._setRejectionIsUnhandled();
- async.invokeLater(this._notifyUnhandledRejection, this, undefined);
- };
- Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
- fireRejectionEvent("rejectionHandled",
- unhandledRejectionHandled, undefined, this);
- };
- Promise.prototype._setReturnedNonUndefined = function() {
- this._bitField = this._bitField | 268435456;
- };
- Promise.prototype._returnedNonUndefined = function() {
- return (this._bitField & 268435456) !== 0;
- };
- Promise.prototype._notifyUnhandledRejection = function () {
- if (this._isRejectionUnhandled()) {
- var reason = this._settledValue();
- this._setUnhandledRejectionIsNotified();
- fireRejectionEvent("unhandledRejection",
- possiblyUnhandledRejection, reason, this);
- }
- };
- Promise.prototype._setUnhandledRejectionIsNotified = function () {
- this._bitField = this._bitField | 262144;
- };
- Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
- this._bitField = this._bitField & (~262144);
- };
- Promise.prototype._isUnhandledRejectionNotified = function () {
- return (this._bitField & 262144) > 0;
- };
- Promise.prototype._setRejectionIsUnhandled = function () {
- this._bitField = this._bitField | 1048576;
- };
- Promise.prototype._unsetRejectionIsUnhandled = function () {
- this._bitField = this._bitField & (~1048576);
- if (this._isUnhandledRejectionNotified()) {
- this._unsetUnhandledRejectionIsNotified();
- this._notifyUnhandledRejectionIsHandled();
- }
- };
- Promise.prototype._isRejectionUnhandled = function () {
- return (this._bitField & 1048576) > 0;
- };
- Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
- return warn(message, shouldUseOwnTrace, promise || this);
- };
- Promise.onPossiblyUnhandledRejection = function (fn) {
- var domain = getDomain();
- possiblyUnhandledRejection =
- typeof fn === "function" ? (domain === null ?
- fn : util.domainBind(domain, fn))
- : undefined;
- };
- Promise.onUnhandledRejectionHandled = function (fn) {
- var domain = getDomain();
- unhandledRejectionHandled =
- typeof fn === "function" ? (domain === null ?
- fn : util.domainBind(domain, fn))
- : undefined;
- };
- var disableLongStackTraces = function() {};
- Promise.longStackTraces = function () {
- if (async.haveItemsQueued() && !config.longStackTraces) {
- throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- if (!config.longStackTraces && longStackTracesIsSupported()) {
- var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
- var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
- config.longStackTraces = true;
- disableLongStackTraces = function() {
- if (async.haveItemsQueued() && !config.longStackTraces) {
- throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- Promise.prototype._captureStackTrace = Promise_captureStackTrace;
- Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
- Context.deactivateLongStackTraces();
- async.enableTrampoline();
- config.longStackTraces = false;
- };
- Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
- Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
- Context.activateLongStackTraces();
- async.disableTrampolineIfNecessary();
- }
- };
- Promise.hasLongStackTraces = function () {
- return config.longStackTraces && longStackTracesIsSupported();
- };
- var fireDomEvent = (function() {
- try {
- if (typeof CustomEvent === "function") {
- var event = new CustomEvent("CustomEvent");
- util.global.dispatchEvent(event);
- return function(name, event) {
- var domEvent = new CustomEvent(name.toLowerCase(), {
- detail: event,
- cancelable: true
- });
- return !util.global.dispatchEvent(domEvent);
- };
- } else if (typeof Event === "function") {
- var event = new Event("CustomEvent");
- util.global.dispatchEvent(event);
- return function(name, event) {
- var domEvent = new Event(name.toLowerCase(), {
- cancelable: true
- });
- domEvent.detail = event;
- return !util.global.dispatchEvent(domEvent);
- };
- } else {
- var event = document.createEvent("CustomEvent");
- event.initCustomEvent("testingtheevent", false, true, {});
- util.global.dispatchEvent(event);
- return function(name, event) {
- var domEvent = document.createEvent("CustomEvent");
- domEvent.initCustomEvent(name.toLowerCase(), false, true,
- event);
- return !util.global.dispatchEvent(domEvent);
- };
- }
- } catch (e) {}
- return function() {
- return false;
- };
- })();
- var fireGlobalEvent = (function() {
- if (util.isNode) {
- return function() {
- return process.emit.apply(process, arguments);
- };
- } else {
- if (!util.global) {
- return function() {
- return false;
- };
- }
- return function(name) {
- var methodName = "on" + name.toLowerCase();
- var method = util.global[methodName];
- if (!method) return false;
- method.apply(util.global, [].slice.call(arguments, 1));
- return true;
- };
- }
- })();
- function generatePromiseLifecycleEventObject(name, promise) {
- return {promise: promise};
- }
- var eventToObjectGenerator = {
- promiseCreated: generatePromiseLifecycleEventObject,
- promiseFulfilled: generatePromiseLifecycleEventObject,
- promiseRejected: generatePromiseLifecycleEventObject,
- promiseResolved: generatePromiseLifecycleEventObject,
- promiseCancelled: generatePromiseLifecycleEventObject,
- promiseChained: function(name, promise, child) {
- return {promise: promise, child: child};
- },
- warning: function(name, warning) {
- return {warning: warning};
- },
- unhandledRejection: function (name, reason, promise) {
- return {reason: reason, promise: promise};
- },
- rejectionHandled: generatePromiseLifecycleEventObject
- };
- var activeFireEvent = function (name) {
- var globalEventFired = false;
- try {
- globalEventFired = fireGlobalEvent.apply(null, arguments);
- } catch (e) {
- async.throwLater(e);
- globalEventFired = true;
- }
- var domEventFired = false;
- try {
- domEventFired = fireDomEvent(name,
- eventToObjectGenerator[name].apply(null, arguments));
- } catch (e) {
- async.throwLater(e);
- domEventFired = true;
- }
- return domEventFired || globalEventFired;
- };
- Promise.config = function(opts) {
- opts = Object(opts);
- if ("longStackTraces" in opts) {
- if (opts.longStackTraces) {
- Promise.longStackTraces();
- } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
- disableLongStackTraces();
- }
- }
- if ("warnings" in opts) {
- var warningsOption = opts.warnings;
- config.warnings = !!warningsOption;
- wForgottenReturn = config.warnings;
- if (util.isObject(warningsOption)) {
- if ("wForgottenReturn" in warningsOption) {
- wForgottenReturn = !!warningsOption.wForgottenReturn;
- }
- }
- }
- if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
- if (async.haveItemsQueued()) {
- throw new Error(
- "cannot enable cancellation after promises are in use");
- }
- Promise.prototype._clearCancellationData =
- cancellationClearCancellationData;
- Promise.prototype._propagateFrom = cancellationPropagateFrom;
- Promise.prototype._onCancel = cancellationOnCancel;
- Promise.prototype._setOnCancel = cancellationSetOnCancel;
- Promise.prototype._attachCancellationCallback =
- cancellationAttachCancellationCallback;
- Promise.prototype._execute = cancellationExecute;
- propagateFromFunction = cancellationPropagateFrom;
- config.cancellation = true;
- }
- if ("monitoring" in opts) {
- if (opts.monitoring && !config.monitoring) {
- config.monitoring = true;
- Promise.prototype._fireEvent = activeFireEvent;
- } else if (!opts.monitoring && config.monitoring) {
- config.monitoring = false;
- Promise.prototype._fireEvent = defaultFireEvent;
- }
- }
- return Promise;
- };
- function defaultFireEvent() { return false; }
- Promise.prototype._fireEvent = defaultFireEvent;
- Promise.prototype._execute = function(executor, resolve, reject) {
- try {
- executor(resolve, reject);
- } catch (e) {
- return e;
- }
- };
- Promise.prototype._onCancel = function () {};
- Promise.prototype._setOnCancel = function (handler) { ; };
- Promise.prototype._attachCancellationCallback = function(onCancel) {
- ;
- };
- Promise.prototype._captureStackTrace = function () {};
- Promise.prototype._attachExtraTrace = function () {};
- Promise.prototype._clearCancellationData = function() {};
- Promise.prototype._propagateFrom = function (parent, flags) {
- ;
- ;
- };
- function cancellationExecute(executor, resolve, reject) {
- var promise = this;
- try {
- executor(resolve, reject, function(onCancel) {
- if (typeof onCancel !== "function") {
- throw new TypeError("onCancel must be a function, got: " +
- util.toString(onCancel));
- }
- promise._attachCancellationCallback(onCancel);
- });
- } catch (e) {
- return e;
- }
- }
- function cancellationAttachCancellationCallback(onCancel) {
- if (!this._isCancellable()) return this;
- var previousOnCancel = this._onCancel();
- if (previousOnCancel !== undefined) {
- if (util.isArray(previousOnCancel)) {
- previousOnCancel.push(onCancel);
- } else {
- this._setOnCancel([previousOnCancel, onCancel]);
- }
- } else {
- this._setOnCancel(onCancel);
- }
- }
- function cancellationOnCancel() {
- return this._onCancelField;
- }
- function cancellationSetOnCancel(onCancel) {
- this._onCancelField = onCancel;
- }
- function cancellationClearCancellationData() {
- this._cancellationParent = undefined;
- this._onCancelField = undefined;
- }
- function cancellationPropagateFrom(parent, flags) {
- if ((flags & 1) !== 0) {
- this._cancellationParent = parent;
- var branchesRemainingToCancel = parent._branchesRemainingToCancel;
- if (branchesRemainingToCancel === undefined) {
- branchesRemainingToCancel = 0;
- }
- parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
- }
- if ((flags & 2) !== 0 && parent._isBound()) {
- this._setBoundTo(parent._boundTo);
- }
- }
- function bindingPropagateFrom(parent, flags) {
- if ((flags & 2) !== 0 && parent._isBound()) {
- this._setBoundTo(parent._boundTo);
- }
- }
- var propagateFromFunction = bindingPropagateFrom;
- function boundValueFunction() {
- var ret = this._boundTo;
- if (ret !== undefined) {
- if (ret instanceof Promise) {
- if (ret.isFulfilled()) {
- return ret.value();
- } else {
- return undefined;
- }
- }
- }
- return ret;
- }
- function longStackTracesCaptureStackTrace() {
- this._trace = new CapturedTrace(this._peekContext());
- }
- function longStackTracesAttachExtraTrace(error, ignoreSelf) {
- if (canAttachTrace(error)) {
- var trace = this._trace;
- if (trace !== undefined) {
- if (ignoreSelf) trace = trace._parent;
- }
- if (trace !== undefined) {
- trace.attachExtraTrace(error);
- } else if (!error.__stackCleaned__) {
- var parsed = parseStackAndMessage(error);
- util.notEnumerableProp(error, "stack",
- parsed.message + "\n" + parsed.stack.join("\n"));
- util.notEnumerableProp(error, "__stackCleaned__", true);
- }
- }
- }
- function checkForgottenReturns(returnValue, promiseCreated, name, promise,
- parent) {
- if (returnValue === undefined && promiseCreated !== null &&
- wForgottenReturn) {
- if (parent !== undefined && parent._returnedNonUndefined()) return;
- if ((promise._bitField & 65535) === 0) return;
- if (name) name = name + " ";
- var handlerLine = "";
- var creatorLine = "";
- if (promiseCreated._trace) {
- var traceLines = promiseCreated._trace.stack.split("\n");
- var stack = cleanStack(traceLines);
- for (var i = stack.length - 1; i >= 0; --i) {
- var line = stack[i];
- if (!nodeFramePattern.test(line)) {
- var lineMatches = line.match(parseLinePattern);
- if (lineMatches) {
- handlerLine = "at " + lineMatches[1] +
- ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
- }
- break;
- }
- }
- if (stack.length > 0) {
- var firstUserLine = stack[0];
- for (var i = 0; i < traceLines.length; ++i) {
- if (traceLines[i] === firstUserLine) {
- if (i > 0) {
- creatorLine = "\n" + traceLines[i - 1];
- }
- break;
- }
- }
- }
- }
- var msg = "a promise was created in a " + name +
- "handler " + handlerLine + "but was not returned from it, " +
- "see http://goo.gl/rRqMUw" +
- creatorLine;
- promise._warn(msg, true, promiseCreated);
- }
- }
- function deprecated(name, replacement) {
- var message = name +
- " is deprecated and will be removed in a future version.";
- if (replacement) message += " Use " + replacement + " instead.";
- return warn(message);
- }
- function warn(message, shouldUseOwnTrace, promise) {
- if (!config.warnings) return;
- var warning = new Warning(message);
- var ctx;
- if (shouldUseOwnTrace) {
- promise._attachExtraTrace(warning);
- } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
- ctx.attachExtraTrace(warning);
- } else {
- var parsed = parseStackAndMessage(warning);
- warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
- }
- if (!activeFireEvent("warning", warning)) {
- formatAndLogError(warning, "", true);
- }
- }
- function reconstructStack(message, stacks) {
- for (var i = 0; i < stacks.length - 1; ++i) {
- stacks[i].push("From previous event:");
- stacks[i] = stacks[i].join("\n");
- }
- if (i < stacks.length) {
- stacks[i] = stacks[i].join("\n");
- }
- return message + "\n" + stacks.join("\n");
- }
- function removeDuplicateOrEmptyJumps(stacks) {
- for (var i = 0; i < stacks.length; ++i) {
- if (stacks[i].length === 0 ||
- ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
- stacks.splice(i, 1);
- i--;
- }
- }
- }
- function removeCommonRoots(stacks) {
- var current = stacks[0];
- for (var i = 1; i < stacks.length; ++i) {
- var prev = stacks[i];
- var currentLastIndex = current.length - 1;
- var currentLastLine = current[currentLastIndex];
- var commonRootMeetPoint = -1;
- for (var j = prev.length - 1; j >= 0; --j) {
- if (prev[j] === currentLastLine) {
- commonRootMeetPoint = j;
- break;
- }
- }
- for (var j = commonRootMeetPoint; j >= 0; --j) {
- var line = prev[j];
- if (current[currentLastIndex] === line) {
- current.pop();
- currentLastIndex--;
- } else {
- break;
- }
- }
- current = prev;
- }
- }
- function cleanStack(stack) {
- var ret = [];
- for (var i = 0; i < stack.length; ++i) {
- var line = stack[i];
- var isTraceLine = " (No stack trace)" === line ||
- stackFramePattern.test(line);
- var isInternalFrame = isTraceLine && shouldIgnore(line);
- if (isTraceLine && !isInternalFrame) {
- if (indentStackFrames && line.charAt(0) !== " ") {
- line = " " + line;
- }
- ret.push(line);
- }
- }
- return ret;
- }
- function stackFramesAsArray(error) {
- var stack = error.stack.replace(/\s+$/g, "").split("\n");
- for (var i = 0; i < stack.length; ++i) {
- var line = stack[i];
- if (" (No stack trace)" === line || stackFramePattern.test(line)) {
- break;
- }
- }
- if (i > 0 && error.name != "SyntaxError") {
- stack = stack.slice(i);
- }
- return stack;
- }
- function parseStackAndMessage(error) {
- var stack = error.stack;
- var message = error.toString();
- stack = typeof stack === "string" && stack.length > 0
- ? stackFramesAsArray(error) : [" (No stack trace)"];
- return {
- message: message,
- stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
- };
- }
- function formatAndLogError(error, title, isSoft) {
- if (typeof console !== "undefined") {
- var message;
- if (util.isObject(error)) {
- var stack = error.stack;
- message = title + formatStack(stack, error);
- } else {
- message = title + String(error);
- }
- if (typeof printWarning === "function") {
- printWarning(message, isSoft);
- } else if (typeof console.log === "function" ||
- typeof console.log === "object") {
- console.log(message);
- }
- }
- }
- function fireRejectionEvent(name, localHandler, reason, promise) {
- var localEventFired = false;
- try {
- if (typeof localHandler === "function") {
- localEventFired = true;
- if (name === "rejectionHandled") {
- localHandler(promise);
- } else {
- localHandler(reason, promise);
- }
- }
- } catch (e) {
- async.throwLater(e);
- }
- if (name === "unhandledRejection") {
- if (!activeFireEvent(name, reason, promise) && !localEventFired) {
- formatAndLogError(reason, "Unhandled rejection ");
- }
- } else {
- activeFireEvent(name, promise);
- }
- }
- function formatNonError(obj) {
- var str;
- if (typeof obj === "function") {
- str = "[function " +
- (obj.name || "anonymous") +
- "]";
- } else {
- str = obj && typeof obj.toString === "function"
- ? obj.toString() : util.toString(obj);
- var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
- if (ruselessToString.test(str)) {
- try {
- var newStr = JSON.stringify(obj);
- str = newStr;
- }
- catch(e) {
- }
- }
- if (str.length === 0) {
- str = "(empty array)";
- }
- }
- return ("(<" + snip(str) + ">, no stack trace)");
- }
- function snip(str) {
- var maxChars = 41;
- if (str.length < maxChars) {
- return str;
- }
- return str.substr(0, maxChars - 3) + "...";
- }
- function longStackTracesIsSupported() {
- return typeof captureStackTrace === "function";
- }
- var shouldIgnore = function() { return false; };
- var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
- function parseLineInfo(line) {
- var matches = line.match(parseLineInfoRegex);
- if (matches) {
- return {
- fileName: matches[1],
- line: parseInt(matches[2], 10)
- };
- }
- }
- function setBounds(firstLineError, lastLineError) {
- if (!longStackTracesIsSupported()) return;
- var firstStackLines = firstLineError.stack.split("\n");
- var lastStackLines = lastLineError.stack.split("\n");
- var firstIndex = -1;
- var lastIndex = -1;
- var firstFileName;
- var lastFileName;
- for (var i = 0; i < firstStackLines.length; ++i) {
- var result = parseLineInfo(firstStackLines[i]);
- if (result) {
- firstFileName = result.fileName;
- firstIndex = result.line;
- break;
- }
- }
- for (var i = 0; i < lastStackLines.length; ++i) {
- var result = parseLineInfo(lastStackLines[i]);
- if (result) {
- lastFileName = result.fileName;
- lastIndex = result.line;
- break;
- }
- }
- if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
- firstFileName !== lastFileName || firstIndex >= lastIndex) {
- return;
- }
- shouldIgnore = function(line) {
- if (bluebirdFramePattern.test(line)) return true;
- var info = parseLineInfo(line);
- if (info) {
- if (info.fileName === firstFileName &&
- (firstIndex <= info.line && info.line <= lastIndex)) {
- return true;
- }
- }
- return false;
- };
- }
- function CapturedTrace(parent) {
- this._parent = parent;
- this._promisesCreated = 0;
- var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
- captureStackTrace(this, CapturedTrace);
- if (length > 32) this.uncycle();
- }
- util.inherits(CapturedTrace, Error);
- Context.CapturedTrace = CapturedTrace;
- CapturedTrace.prototype.uncycle = function() {
- var length = this._length;
- if (length < 2) return;
- var nodes = [];
- var stackToIndex = {};
- for (var i = 0, node = this; node !== undefined; ++i) {
- nodes.push(node);
- node = node._parent;
- }
- length = this._length = i;
- for (var i = length - 1; i >= 0; --i) {
- var stack = nodes[i].stack;
- if (stackToIndex[stack] === undefined) {
- stackToIndex[stack] = i;
- }
- }
- for (var i = 0; i < length; ++i) {
- var currentStack = nodes[i].stack;
- var index = stackToIndex[currentStack];
- if (index !== undefined && index !== i) {
- if (index > 0) {
- nodes[index - 1]._parent = undefined;
- nodes[index - 1]._length = 1;
- }
- nodes[i]._parent = undefined;
- nodes[i]._length = 1;
- var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
- if (index < length - 1) {
- cycleEdgeNode._parent = nodes[index + 1];
- cycleEdgeNode._parent.uncycle();
- cycleEdgeNode._length =
- cycleEdgeNode._parent._length + 1;
- } else {
- cycleEdgeNode._parent = undefined;
- cycleEdgeNode._length = 1;
- }
- var currentChildLength = cycleEdgeNode._length + 1;
- for (var j = i - 2; j >= 0; --j) {
- nodes[j]._length = currentChildLength;
- currentChildLength++;
- }
- return;
- }
- }
- };
- CapturedTrace.prototype.attachExtraTrace = function(error) {
- if (error.__stackCleaned__) return;
- this.uncycle();
- var parsed = parseStackAndMessage(error);
- var message = parsed.message;
- var stacks = [parsed.stack];
- var trace = this;
- while (trace !== undefined) {
- stacks.push(cleanStack(trace.stack.split("\n")));
- trace = trace._parent;
- }
- removeCommonRoots(stacks);
- removeDuplicateOrEmptyJumps(stacks);
- util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
- util.notEnumerableProp(error, "__stackCleaned__", true);
- };
- var captureStackTrace = (function stackDetection() {
- var v8stackFramePattern = /^\s*at\s*/;
- var v8stackFormatter = function(stack, error) {
- if (typeof stack === "string") return stack;
- if (error.name !== undefined &&
- error.message !== undefined) {
- return error.toString();
- }
- return formatNonError(error);
- };
- if (typeof Error.stackTraceLimit === "number" &&
- typeof Error.captureStackTrace === "function") {
- Error.stackTraceLimit += 6;
- stackFramePattern = v8stackFramePattern;
- formatStack = v8stackFormatter;
- var captureStackTrace = Error.captureStackTrace;
- shouldIgnore = function(line) {
- return bluebirdFramePattern.test(line);
- };
- return function(receiver, ignoreUntil) {
- Error.stackTraceLimit += 6;
- captureStackTrace(receiver, ignoreUntil);
- Error.stackTraceLimit -= 6;
- };
- }
- var err = new Error();
- if (typeof err.stack === "string" &&
- err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
- stackFramePattern = /@/;
- formatStack = v8stackFormatter;
- indentStackFrames = true;
- return function captureStackTrace(o) {
- o.stack = new Error().stack;
- };
- }
- var hasStackAfterThrow;
- try { throw new Error(); }
- catch(e) {
- hasStackAfterThrow = ("stack" in e);
- }
- if (!("stack" in err) && hasStackAfterThrow &&
- typeof Error.stackTraceLimit === "number") {
- stackFramePattern = v8stackFramePattern;
- formatStack = v8stackFormatter;
- return function captureStackTrace(o) {
- Error.stackTraceLimit += 6;
- try { throw new Error(); }
- catch(e) { o.stack = e.stack; }
- Error.stackTraceLimit -= 6;
- };
- }
- formatStack = function(stack, error) {
- if (typeof stack === "string") return stack;
- if ((typeof error === "object" ||
- typeof error === "function") &&
- error.name !== undefined &&
- error.message !== undefined) {
- return error.toString();
- }
- return formatNonError(error);
- };
- return null;
- })([]);
- if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
- printWarning = function (message) {
- console.warn(message);
- };
- if (util.isNode && process.stderr.isTTY) {
- printWarning = function(message, isSoft) {
- var color = isSoft ? "\u001b[33m" : "\u001b[31m";
- console.warn(color + message + "\u001b[0m\n");
- };
- } else if (!util.isNode && typeof (new Error().stack) === "string") {
- printWarning = function(message, isSoft) {
- console.warn("%c" + message,
- isSoft ? "color: darkorange" : "color: red");
- };
- }
- }
- var config = {
- warnings: warnings,
- longStackTraces: false,
- cancellation: false,
- monitoring: false
- };
- if (longStackTraces) Promise.longStackTraces();
- return {
- longStackTraces: function() {
- return config.longStackTraces;
- },
- warnings: function() {
- return config.warnings;
- },
- cancellation: function() {
- return config.cancellation;
- },
- monitoring: function() {
- return config.monitoring;
- },
- propagateFromFunction: function() {
- return propagateFromFunction;
- },
- boundValueFunction: function() {
- return boundValueFunction;
- },
- checkForgottenReturns: checkForgottenReturns,
- setBounds: setBounds,
- warn: warn,
- deprecated: deprecated,
- CapturedTrace: CapturedTrace,
- fireDomEvent: fireDomEvent,
- fireGlobalEvent: fireGlobalEvent
- };
- };
- }).call(this,require('_process'))
- },{"./errors":50,"./util":74,"_process":138}],48:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise) {
- function returner() {
- return this.value;
- }
- function thrower() {
- throw this.reason;
- }
- Promise.prototype["return"] =
- Promise.prototype.thenReturn = function (value) {
- if (value instanceof Promise) value.suppressUnhandledRejections();
- return this._then(
- returner, undefined, undefined, {value: value}, undefined);
- };
- Promise.prototype["throw"] =
- Promise.prototype.thenThrow = function (reason) {
- return this._then(
- thrower, undefined, undefined, {reason: reason}, undefined);
- };
- Promise.prototype.catchThrow = function (reason) {
- if (arguments.length <= 1) {
- return this._then(
- undefined, thrower, undefined, {reason: reason}, undefined);
- } else {
- var _reason = arguments[1];
- var handler = function() {throw _reason;};
- return this.caught(reason, handler);
- }
- };
- Promise.prototype.catchReturn = function (value) {
- if (arguments.length <= 1) {
- if (value instanceof Promise) value.suppressUnhandledRejections();
- return this._then(
- undefined, returner, undefined, {value: value}, undefined);
- } else {
- var _value = arguments[1];
- if (_value instanceof Promise) _value.suppressUnhandledRejections();
- var handler = function() {return _value;};
- return this.caught(value, handler);
- }
- };
- };
- },{}],49:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var PromiseReduce = Promise.reduce;
- var PromiseAll = Promise.all;
- function promiseAllThis() {
- return PromiseAll(this);
- }
- function PromiseMapSeries(promises, fn) {
- return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
- }
- Promise.prototype.each = function (fn) {
- return PromiseReduce(this, fn, INTERNAL, 0)
- ._then(promiseAllThis, undefined, undefined, this, undefined);
- };
- Promise.prototype.mapSeries = function (fn) {
- return PromiseReduce(this, fn, INTERNAL, INTERNAL);
- };
- Promise.each = function (promises, fn) {
- return PromiseReduce(promises, fn, INTERNAL, 0)
- ._then(promiseAllThis, undefined, undefined, promises, undefined);
- };
- Promise.mapSeries = PromiseMapSeries;
- };
- },{}],50:[function(require,module,exports){
- "use strict";
- var es5 = require("./es5");
- var Objectfreeze = es5.freeze;
- var util = require("./util");
- var inherits = util.inherits;
- var notEnumerableProp = util.notEnumerableProp;
- function subError(nameProperty, defaultMessage) {
- function SubError(message) {
- if (!(this instanceof SubError)) return new SubError(message);
- notEnumerableProp(this, "message",
- typeof message === "string" ? message : defaultMessage);
- notEnumerableProp(this, "name", nameProperty);
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- } else {
- Error.call(this);
- }
- }
- inherits(SubError, Error);
- return SubError;
- }
- var _TypeError, _RangeError;
- var Warning = subError("Warning", "warning");
- var CancellationError = subError("CancellationError", "cancellation error");
- var TimeoutError = subError("TimeoutError", "timeout error");
- var AggregateError = subError("AggregateError", "aggregate error");
- try {
- _TypeError = TypeError;
- _RangeError = RangeError;
- } catch(e) {
- _TypeError = subError("TypeError", "type error");
- _RangeError = subError("RangeError", "range error");
- }
- var methods = ("join pop push shift unshift slice filter forEach some " +
- "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
- for (var i = 0; i < methods.length; ++i) {
- if (typeof Array.prototype[methods[i]] === "function") {
- AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
- }
- }
- es5.defineProperty(AggregateError.prototype, "length", {
- value: 0,
- configurable: false,
- writable: true,
- enumerable: true
- });
- AggregateError.prototype["isOperational"] = true;
- var level = 0;
- AggregateError.prototype.toString = function() {
- var indent = Array(level * 4 + 1).join(" ");
- var ret = "\n" + indent + "AggregateError of:" + "\n";
- level++;
- indent = Array(level * 4 + 1).join(" ");
- for (var i = 0; i < this.length; ++i) {
- var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
- var lines = str.split("\n");
- for (var j = 0; j < lines.length; ++j) {
- lines[j] = indent + lines[j];
- }
- str = lines.join("\n");
- ret += str + "\n";
- }
- level--;
- return ret;
- };
- function OperationalError(message) {
- if (!(this instanceof OperationalError))
- return new OperationalError(message);
- notEnumerableProp(this, "name", "OperationalError");
- notEnumerableProp(this, "message", message);
- this.cause = message;
- this["isOperational"] = true;
- if (message instanceof Error) {
- notEnumerableProp(this, "message", message.message);
- notEnumerableProp(this, "stack", message.stack);
- } else if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
- }
- inherits(OperationalError, Error);
- var errorTypes = Error["__BluebirdErrorTypes__"];
- if (!errorTypes) {
- errorTypes = Objectfreeze({
- CancellationError: CancellationError,
- TimeoutError: TimeoutError,
- OperationalError: OperationalError,
- RejectionError: OperationalError,
- AggregateError: AggregateError
- });
- es5.defineProperty(Error, "__BluebirdErrorTypes__", {
- value: errorTypes,
- writable: false,
- enumerable: false,
- configurable: false
- });
- }
- module.exports = {
- Error: Error,
- TypeError: _TypeError,
- RangeError: _RangeError,
- CancellationError: errorTypes.CancellationError,
- OperationalError: errorTypes.OperationalError,
- TimeoutError: errorTypes.TimeoutError,
- AggregateError: errorTypes.AggregateError,
- Warning: Warning
- };
- },{"./es5":51,"./util":74}],51:[function(require,module,exports){
- var isES5 = (function(){
- "use strict";
- return this === undefined;
- })();
- if (isES5) {
- module.exports = {
- freeze: Object.freeze,
- defineProperty: Object.defineProperty,
- getDescriptor: Object.getOwnPropertyDescriptor,
- keys: Object.keys,
- names: Object.getOwnPropertyNames,
- getPrototypeOf: Object.getPrototypeOf,
- isArray: Array.isArray,
- isES5: isES5,
- propertyIsWritable: function(obj, prop) {
- var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
- return !!(!descriptor || descriptor.writable || descriptor.set);
- }
- };
- } else {
- var has = {}.hasOwnProperty;
- var str = {}.toString;
- var proto = {}.constructor.prototype;
- var ObjectKeys = function (o) {
- var ret = [];
- for (var key in o) {
- if (has.call(o, key)) {
- ret.push(key);
- }
- }
- return ret;
- };
- var ObjectGetDescriptor = function(o, key) {
- return {value: o[key]};
- };
- var ObjectDefineProperty = function (o, key, desc) {
- o[key] = desc.value;
- return o;
- };
- var ObjectFreeze = function (obj) {
- return obj;
- };
- var ObjectGetPrototypeOf = function (obj) {
- try {
- return Object(obj).constructor.prototype;
- }
- catch (e) {
- return proto;
- }
- };
- var ArrayIsArray = function (obj) {
- try {
- return str.call(obj) === "[object Array]";
- }
- catch(e) {
- return false;
- }
- };
- module.exports = {
- isArray: ArrayIsArray,
- keys: ObjectKeys,
- names: ObjectKeys,
- defineProperty: ObjectDefineProperty,
- getDescriptor: ObjectGetDescriptor,
- freeze: ObjectFreeze,
- getPrototypeOf: ObjectGetPrototypeOf,
- isES5: isES5,
- propertyIsWritable: function() {
- return true;
- }
- };
- }
- },{}],52:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var PromiseMap = Promise.map;
- Promise.prototype.filter = function (fn, options) {
- return PromiseMap(this, fn, options, INTERNAL);
- };
- Promise.filter = function (promises, fn, options) {
- return PromiseMap(promises, fn, options, INTERNAL);
- };
- };
- },{}],53:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, tryConvertToPromise) {
- var util = require("./util");
- var CancellationError = Promise.CancellationError;
- var errorObj = util.errorObj;
- function PassThroughHandlerContext(promise, type, handler) {
- this.promise = promise;
- this.type = type;
- this.handler = handler;
- this.called = false;
- this.cancelPromise = null;
- }
- PassThroughHandlerContext.prototype.isFinallyHandler = function() {
- return this.type === 0;
- };
- function FinallyHandlerCancelReaction(finallyHandler) {
- this.finallyHandler = finallyHandler;
- }
- FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
- checkCancel(this.finallyHandler);
- };
- function checkCancel(ctx, reason) {
- if (ctx.cancelPromise != null) {
- if (arguments.length > 1) {
- ctx.cancelPromise._reject(reason);
- } else {
- ctx.cancelPromise._cancel();
- }
- ctx.cancelPromise = null;
- return true;
- }
- return false;
- }
- function succeed() {
- return finallyHandler.call(this, this.promise._target()._settledValue());
- }
- function fail(reason) {
- if (checkCancel(this, reason)) return;
- errorObj.e = reason;
- return errorObj;
- }
- function finallyHandler(reasonOrValue) {
- var promise = this.promise;
- var handler = this.handler;
- if (!this.called) {
- this.called = true;
- var ret = this.isFinallyHandler()
- ? handler.call(promise._boundValue())
- : handler.call(promise._boundValue(), reasonOrValue);
- if (ret !== undefined) {
- promise._setReturnedNonUndefined();
- var maybePromise = tryConvertToPromise(ret, promise);
- if (maybePromise instanceof Promise) {
- if (this.cancelPromise != null) {
- if (maybePromise._isCancelled()) {
- var reason =
- new CancellationError("late cancellation observer");
- promise._attachExtraTrace(reason);
- errorObj.e = reason;
- return errorObj;
- } else if (maybePromise.isPending()) {
- maybePromise._attachCancellationCallback(
- new FinallyHandlerCancelReaction(this));
- }
- }
- return maybePromise._then(
- succeed, fail, undefined, this, undefined);
- }
- }
- }
- if (promise.isRejected()) {
- checkCancel(this);
- errorObj.e = reasonOrValue;
- return errorObj;
- } else {
- checkCancel(this);
- return reasonOrValue;
- }
- }
- Promise.prototype._passThrough = function(handler, type, success, fail) {
- if (typeof handler !== "function") return this.then();
- return this._then(success,
- fail,
- undefined,
- new PassThroughHandlerContext(this, type, handler),
- undefined);
- };
- Promise.prototype.lastly =
- Promise.prototype["finally"] = function (handler) {
- return this._passThrough(handler,
- 0,
- finallyHandler,
- finallyHandler);
- };
- Promise.prototype.tap = function (handler) {
- return this._passThrough(handler, 1, finallyHandler);
- };
- return PassThroughHandlerContext;
- };
- },{"./util":74}],54:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise,
- apiRejection,
- INTERNAL,
- tryConvertToPromise,
- Proxyable,
- debug) {
- var errors = require("./errors");
- var TypeError = errors.TypeError;
- var util = require("./util");
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- var yieldHandlers = [];
- function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
- for (var i = 0; i < yieldHandlers.length; ++i) {
- traceParent._pushContext();
- var result = tryCatch(yieldHandlers[i])(value);
- traceParent._popContext();
- if (result === errorObj) {
- traceParent._pushContext();
- var ret = Promise.reject(errorObj.e);
- traceParent._popContext();
- return ret;
- }
- var maybePromise = tryConvertToPromise(result, traceParent);
- if (maybePromise instanceof Promise) return maybePromise;
- }
- return null;
- }
- function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
- if (debug.cancellation()) {
- var internal = new Promise(INTERNAL);
- var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
- this._promise = internal.lastly(function() {
- return _finallyPromise;
- });
- internal._captureStackTrace();
- internal._setOnCancel(this);
- } else {
- var promise = this._promise = new Promise(INTERNAL);
- promise._captureStackTrace();
- }
- this._stack = stack;
- this._generatorFunction = generatorFunction;
- this._receiver = receiver;
- this._generator = undefined;
- this._yieldHandlers = typeof yieldHandler === "function"
- ? [yieldHandler].concat(yieldHandlers)
- : yieldHandlers;
- this._yieldedPromise = null;
- this._cancellationPhase = false;
- }
- util.inherits(PromiseSpawn, Proxyable);
- PromiseSpawn.prototype._isResolved = function() {
- return this._promise === null;
- };
- PromiseSpawn.prototype._cleanup = function() {
- this._promise = this._generator = null;
- if (debug.cancellation() && this._finallyPromise !== null) {
- this._finallyPromise._fulfill();
- this._finallyPromise = null;
- }
- };
- PromiseSpawn.prototype._promiseCancelled = function() {
- if (this._isResolved()) return;
- var implementsReturn = typeof this._generator["return"] !== "undefined";
- var result;
- if (!implementsReturn) {
- var reason = new Promise.CancellationError(
- "generator .return() sentinel");
- Promise.coroutine.returnSentinel = reason;
- this._promise._attachExtraTrace(reason);
- this._promise._pushContext();
- result = tryCatch(this._generator["throw"]).call(this._generator,
- reason);
- this._promise._popContext();
- } else {
- this._promise._pushContext();
- result = tryCatch(this._generator["return"]).call(this._generator,
- undefined);
- this._promise._popContext();
- }
- this._cancellationPhase = true;
- this._yieldedPromise = null;
- this._continue(result);
- };
- PromiseSpawn.prototype._promiseFulfilled = function(value) {
- this._yieldedPromise = null;
- this._promise._pushContext();
- var result = tryCatch(this._generator.next).call(this._generator, value);
- this._promise._popContext();
- this._continue(result);
- };
- PromiseSpawn.prototype._promiseRejected = function(reason) {
- this._yieldedPromise = null;
- this._promise._attachExtraTrace(reason);
- this._promise._pushContext();
- var result = tryCatch(this._generator["throw"])
- .call(this._generator, reason);
- this._promise._popContext();
- this._continue(result);
- };
- PromiseSpawn.prototype._resultCancelled = function() {
- if (this._yieldedPromise instanceof Promise) {
- var promise = this._yieldedPromise;
- this._yieldedPromise = null;
- promise.cancel();
- }
- };
- PromiseSpawn.prototype.promise = function () {
- return this._promise;
- };
- PromiseSpawn.prototype._run = function () {
- this._generator = this._generatorFunction.call(this._receiver);
- this._receiver =
- this._generatorFunction = undefined;
- this._promiseFulfilled(undefined);
- };
- PromiseSpawn.prototype._continue = function (result) {
- var promise = this._promise;
- if (result === errorObj) {
- this._cleanup();
- if (this._cancellationPhase) {
- return promise.cancel();
- } else {
- return promise._rejectCallback(result.e, false);
- }
- }
- var value = result.value;
- if (result.done === true) {
- this._cleanup();
- if (this._cancellationPhase) {
- return promise.cancel();
- } else {
- return promise._resolveCallback(value);
- }
- } else {
- var maybePromise = tryConvertToPromise(value, this._promise);
- if (!(maybePromise instanceof Promise)) {
- maybePromise =
- promiseFromYieldHandler(maybePromise,
- this._yieldHandlers,
- this._promise);
- if (maybePromise === null) {
- this._promiseRejected(
- new TypeError(
- "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) +
- "From coroutine:\u000a" +
- this._stack.split("\n").slice(1, -7).join("\n")
- )
- );
- return;
- }
- }
- maybePromise = maybePromise._target();
- var bitField = maybePromise._bitField;
- ;
- if (((bitField & 50397184) === 0)) {
- this._yieldedPromise = maybePromise;
- maybePromise._proxy(this, null);
- } else if (((bitField & 33554432) !== 0)) {
- Promise._async.invoke(
- this._promiseFulfilled, this, maybePromise._value()
- );
- } else if (((bitField & 16777216) !== 0)) {
- Promise._async.invoke(
- this._promiseRejected, this, maybePromise._reason()
- );
- } else {
- this._promiseCancelled();
- }
- }
- };
- Promise.coroutine = function (generatorFunction, options) {
- if (typeof generatorFunction !== "function") {
- throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- var yieldHandler = Object(options).yieldHandler;
- var PromiseSpawn$ = PromiseSpawn;
- var stack = new Error().stack;
- return function () {
- var generator = generatorFunction.apply(this, arguments);
- var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
- stack);
- var ret = spawn.promise();
- spawn._generator = generator;
- spawn._promiseFulfilled(undefined);
- return ret;
- };
- };
- Promise.coroutine.addYieldHandler = function(fn) {
- if (typeof fn !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(fn));
- }
- yieldHandlers.push(fn);
- };
- Promise.spawn = function (generatorFunction) {
- debug.deprecated("Promise.spawn()", "Promise.coroutine()");
- if (typeof generatorFunction !== "function") {
- return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- var spawn = new PromiseSpawn(generatorFunction, this);
- var ret = spawn.promise();
- spawn._run(Promise.spawn);
- return ret;
- };
- };
- },{"./errors":50,"./util":74}],55:[function(require,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
- getDomain) {
- var util = require("./util");
- var canEvaluate = util.canEvaluate;
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var reject;
- if (!false) {
- if (canEvaluate) {
- var thenCallback = function(i) {
- return new Function("value", "holder", " \n\
- 'use strict'; \n\
- holder.pIndex = value; \n\
- holder.checkFulfillment(this); \n\
- ".replace(/Index/g, i));
- };
- var promiseSetter = function(i) {
- return new Function("promise", "holder", " \n\
- 'use strict'; \n\
- holder.pIndex = promise; \n\
- ".replace(/Index/g, i));
- };
- var generateHolderClass = function(total) {
- var props = new Array(total);
- for (var i = 0; i < props.length; ++i) {
- props[i] = "this.p" + (i+1);
- }
- var assignment = props.join(" = ") + " = null;";
- var cancellationCode= "var promise;\n" + props.map(function(prop) {
- return " \n\
- promise = " + prop + "; \n\
- if (promise instanceof Promise) { \n\
- promise.cancel(); \n\
- } \n\
- ";
- }).join("\n");
- var passedArguments = props.join(", ");
- var name = "Holder$" + total;
- var code = "return function(tryCatch, errorObj, Promise, async) { \n\
- 'use strict'; \n\
- function [TheName](fn) { \n\
- [TheProperties] \n\
- this.fn = fn; \n\
- this.asyncNeeded = true; \n\
- this.now = 0; \n\
- } \n\
- \n\
- [TheName].prototype._callFunction = function(promise) { \n\
- promise._pushContext(); \n\
- var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
- promise._popContext(); \n\
- if (ret === errorObj) { \n\
- promise._rejectCallback(ret.e, false); \n\
- } else { \n\
- promise._resolveCallback(ret); \n\
- } \n\
- }; \n\
- \n\
- [TheName].prototype.checkFulfillment = function(promise) { \n\
- var now = ++this.now; \n\
- if (now === [TheTotal]) { \n\
- if (this.asyncNeeded) { \n\
- async.invoke(this._callFunction, this, promise); \n\
- } else { \n\
- this._callFunction(promise); \n\
- } \n\
- \n\
- } \n\
- }; \n\
- \n\
- [TheName].prototype._resultCancelled = function() { \n\
- [CancellationCode] \n\
- }; \n\
- \n\
- return [TheName]; \n\
- }(tryCatch, errorObj, Promise, async); \n\
- ";
- code = code.replace(/\[TheName\]/g, name)
- .replace(/\[TheTotal\]/g, total)
- .replace(/\[ThePassedArguments\]/g, passedArguments)
- .replace(/\[TheProperties\]/g, assignment)
- .replace(/\[CancellationCode\]/g, cancellationCode);
- return new Function("tryCatch", "errorObj", "Promise", "async", code)
- (tryCatch, errorObj, Promise, async);
- };
- var holderClasses = [];
- var thenCallbacks = [];
- var promiseSetters = [];
- for (var i = 0; i < 8; ++i) {
- holderClasses.push(generateHolderClass(i + 1));
- thenCallbacks.push(thenCallback(i + 1));
- promiseSetters.push(promiseSetter(i + 1));
- }
- reject = function (reason) {
- this._reject(reason);
- };
- }}
- Promise.join = function () {
- var last = arguments.length - 1;
- var fn;
- if (last > 0 && typeof arguments[last] === "function") {
- fn = arguments[last];
- if (!false) {
- if (last <= 8 && canEvaluate) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- var HolderClass = holderClasses[last - 1];
- var holder = new HolderClass(fn);
- var callbacks = thenCallbacks;
- for (var i = 0; i < last; ++i) {
- var maybePromise = tryConvertToPromise(arguments[i], ret);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- var bitField = maybePromise._bitField;
- ;
- if (((bitField & 50397184) === 0)) {
- maybePromise._then(callbacks[i], reject,
- undefined, ret, holder);
- promiseSetters[i](maybePromise, holder);
- holder.asyncNeeded = false;
- } else if (((bitField & 33554432) !== 0)) {
- callbacks[i].call(ret,
- maybePromise._value(), holder);
- } else if (((bitField & 16777216) !== 0)) {
- ret._reject(maybePromise._reason());
- } else {
- ret._cancel();
- }
- } else {
- callbacks[i].call(ret, maybePromise, holder);
- }
- }
- if (!ret._isFateSealed()) {
- if (holder.asyncNeeded) {
- var domain = getDomain();
- if (domain !== null) {
- holder.fn = util.domainBind(domain, holder.fn);
- }
- }
- ret._setAsyncGuaranteed();
- ret._setOnCancel(holder);
- }
- return ret;
- }
- }
- }
- var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
- if (fn) args.pop();
- var ret = new PromiseArray(args).promise();
- return fn !== undefined ? ret.spread(fn) : ret;
- };
- };
- },{"./util":74}],56:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise,
- PromiseArray,
- apiRejection,
- tryConvertToPromise,
- INTERNAL,
- debug) {
- var getDomain = Promise._getDomain;
- var util = require("./util");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var async = Promise._async;
- function MappingPromiseArray(promises, fn, limit, _filter) {
- this.constructor$(promises);
- this._promise._captureStackTrace();
- var domain = getDomain();
- this._callback = domain === null ? fn : util.domainBind(domain, fn);
- this._preservedValues = _filter === INTERNAL
- ? new Array(this.length())
- : null;
- this._limit = limit;
- this._inFlight = 0;
- this._queue = [];
- async.invoke(this._asyncInit, this, undefined);
- }
- util.inherits(MappingPromiseArray, PromiseArray);
- MappingPromiseArray.prototype._asyncInit = function() {
- this._init$(undefined, -2);
- };
- MappingPromiseArray.prototype._init = function () {};
- MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
- var values = this._values;
- var length = this.length();
- var preservedValues = this._preservedValues;
- var limit = this._limit;
- if (index < 0) {
- index = (index * -1) - 1;
- values[index] = value;
- if (limit >= 1) {
- this._inFlight--;
- this._drainQueue();
- if (this._isResolved()) return true;
- }
- } else {
- if (limit >= 1 && this._inFlight >= limit) {
- values[index] = value;
- this._queue.push(index);
- return false;
- }
- if (preservedValues !== null) preservedValues[index] = value;
- var promise = this._promise;
- var callback = this._callback;
- var receiver = promise._boundValue();
- promise._pushContext();
- var ret = tryCatch(callback).call(receiver, value, index, length);
- var promiseCreated = promise._popContext();
- debug.checkForgottenReturns(
- ret,
- promiseCreated,
- preservedValues !== null ? "Promise.filter" : "Promise.map",
- promise
- );
- if (ret === errorObj) {
- this._reject(ret.e);
- return true;
- }
- var maybePromise = tryConvertToPromise(ret, this._promise);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- var bitField = maybePromise._bitField;
- ;
- if (((bitField & 50397184) === 0)) {
- if (limit >= 1) this._inFlight++;
- values[index] = maybePromise;
- maybePromise._proxy(this, (index + 1) * -1);
- return false;
- } else if (((bitField & 33554432) !== 0)) {
- ret = maybePromise._value();
- } else if (((bitField & 16777216) !== 0)) {
- this._reject(maybePromise._reason());
- return true;
- } else {
- this._cancel();
- return true;
- }
- }
- values[index] = ret;
- }
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= length) {
- if (preservedValues !== null) {
- this._filter(values, preservedValues);
- } else {
- this._resolve(values);
- }
- return true;
- }
- return false;
- };
- MappingPromiseArray.prototype._drainQueue = function () {
- var queue = this._queue;
- var limit = this._limit;
- var values = this._values;
- while (queue.length > 0 && this._inFlight < limit) {
- if (this._isResolved()) return;
- var index = queue.pop();
- this._promiseFulfilled(values[index], index);
- }
- };
- MappingPromiseArray.prototype._filter = function (booleans, values) {
- var len = values.length;
- var ret = new Array(len);
- var j = 0;
- for (var i = 0; i < len; ++i) {
- if (booleans[i]) ret[j++] = values[i];
- }
- ret.length = j;
- this._resolve(ret);
- };
- MappingPromiseArray.prototype.preservedValues = function () {
- return this._preservedValues;
- };
- function map(promises, fn, options, _filter) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- var limit = 0;
- if (options !== undefined) {
- if (typeof options === "object" && options !== null) {
- if (typeof options.concurrency !== "number") {
- return Promise.reject(
- new TypeError("'concurrency' must be a number but it is " +
- util.classString(options.concurrency)));
- }
- limit = options.concurrency;
- } else {
- return Promise.reject(new TypeError(
- "options argument must be an object but it is " +
- util.classString(options)));
- }
- }
- limit = typeof limit === "number" &&
- isFinite(limit) && limit >= 1 ? limit : 0;
- return new MappingPromiseArray(promises, fn, limit, _filter).promise();
- }
- Promise.prototype.map = function (fn, options) {
- return map(this, fn, options, null);
- };
- Promise.map = function (promises, fn, options, _filter) {
- return map(promises, fn, options, _filter);
- };
- };
- },{"./util":74}],57:[function(require,module,exports){
- "use strict";
- module.exports =
- function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
- var util = require("./util");
- var tryCatch = util.tryCatch;
- Promise.method = function (fn) {
- if (typeof fn !== "function") {
- throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
- }
- return function () {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._pushContext();
- var value = tryCatch(fn).apply(this, arguments);
- var promiseCreated = ret._popContext();
- debug.checkForgottenReturns(
- value, promiseCreated, "Promise.method", ret);
- ret._resolveFromSyncValue(value);
- return ret;
- };
- };
- Promise.attempt = Promise["try"] = function (fn) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._pushContext();
- var value;
- if (arguments.length > 1) {
- debug.deprecated("calling Promise.try with more than 1 argument");
- var arg = arguments[1];
- var ctx = arguments[2];
- value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
- : tryCatch(fn).call(ctx, arg);
- } else {
- value = tryCatch(fn)();
- }
- var promiseCreated = ret._popContext();
- debug.checkForgottenReturns(
- value, promiseCreated, "Promise.try", ret);
- ret._resolveFromSyncValue(value);
- return ret;
- };
- Promise.prototype._resolveFromSyncValue = function (value) {
- if (value === util.errorObj) {
- this._rejectCallback(value.e, false);
- } else {
- this._resolveCallback(value, true);
- }
- };
- };
- },{"./util":74}],58:[function(require,module,exports){
- "use strict";
- var util = require("./util");
- var maybeWrapAsError = util.maybeWrapAsError;
- var errors = require("./errors");
- var OperationalError = errors.OperationalError;
- var es5 = require("./es5");
- function isUntypedError(obj) {
- return obj instanceof Error &&
- es5.getPrototypeOf(obj) === Error.prototype;
- }
- var rErrorKey = /^(?:name|message|stack|cause)$/;
- function wrapAsOperationalError(obj) {
- var ret;
- if (isUntypedError(obj)) {
- ret = new OperationalError(obj);
- ret.name = obj.name;
- ret.message = obj.message;
- ret.stack = obj.stack;
- var keys = es5.keys(obj);
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (!rErrorKey.test(key)) {
- ret[key] = obj[key];
- }
- }
- return ret;
- }
- util.markAsOriginatingFromRejection(obj);
- return obj;
- }
- function nodebackForPromise(promise, multiArgs) {
- return function(err, value) {
- if (promise === null) return;
- if (err) {
- var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
- promise._attachExtraTrace(wrapped);
- promise._reject(wrapped);
- } else if (!multiArgs) {
- promise._fulfill(value);
- } else {
- 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];};
- promise._fulfill(args);
- }
- promise = null;
- };
- }
- module.exports = nodebackForPromise;
- },{"./errors":50,"./es5":51,"./util":74}],59:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var util = require("./util");
- var async = Promise._async;
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- function spreadAdapter(val, nodeback) {
- var promise = this;
- if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
- var ret =
- tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
- function successAdapter(val, nodeback) {
- var promise = this;
- var receiver = promise._boundValue();
- var ret = val === undefined
- ? tryCatch(nodeback).call(receiver, null)
- : tryCatch(nodeback).call(receiver, null, val);
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
- function errorAdapter(reason, nodeback) {
- var promise = this;
- if (!reason) {
- var newReason = new Error(reason + "");
- newReason.cause = reason;
- reason = newReason;
- }
- var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
- Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
- options) {
- if (typeof nodeback == "function") {
- var adapter = successAdapter;
- if (options !== undefined && Object(options).spread) {
- adapter = spreadAdapter;
- }
- this._then(
- adapter,
- errorAdapter,
- undefined,
- this,
- nodeback
- );
- }
- return this;
- };
- };
- },{"./util":74}],60:[function(require,module,exports){
- (function (process){
- "use strict";
- module.exports = function() {
- var makeSelfResolutionError = function () {
- return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- };
- var reflectHandler = function() {
- return new Promise.PromiseInspection(this._target());
- };
- var apiRejection = function(msg) {
- return Promise.reject(new TypeError(msg));
- };
- function Proxyable() {}
- var UNDEFINED_BINDING = {};
- var util = require("./util");
- var getDomain;
- if (util.isNode) {
- getDomain = function() {
- var ret = process.domain;
- if (ret === undefined) ret = null;
- return ret;
- };
- } else {
- getDomain = function() {
- return null;
- };
- }
- util.notEnumerableProp(Promise, "_getDomain", getDomain);
- var es5 = require("./es5");
- var Async = require("./async");
- var async = new Async();
- es5.defineProperty(Promise, "_async", {value: async});
- var errors = require("./errors");
- var TypeError = Promise.TypeError = errors.TypeError;
- Promise.RangeError = errors.RangeError;
- var CancellationError = Promise.CancellationError = errors.CancellationError;
- Promise.TimeoutError = errors.TimeoutError;
- Promise.OperationalError = errors.OperationalError;
- Promise.RejectionError = errors.OperationalError;
- Promise.AggregateError = errors.AggregateError;
- var INTERNAL = function(){};
- var APPLY = {};
- var NEXT_FILTER = {};
- var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
- var PromiseArray =
- require("./promise_array")(Promise, INTERNAL,
- tryConvertToPromise, apiRejection, Proxyable);
- var Context = require("./context")(Promise);
- /*jshint unused:false*/
- var createContext = Context.create;
- var debug = require("./debuggability")(Promise, Context);
- var CapturedTrace = debug.CapturedTrace;
- var PassThroughHandlerContext =
- require("./finally")(Promise, tryConvertToPromise);
- var catchFilter = require("./catch_filter")(NEXT_FILTER);
- var nodebackForPromise = require("./nodeback");
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- function check(self, executor) {
- if (typeof executor !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(executor));
- }
- if (self.constructor !== Promise) {
- throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- }
- function Promise(executor) {
- this._bitField = 0;
- this._fulfillmentHandler0 = undefined;
- this._rejectionHandler0 = undefined;
- this._promise0 = undefined;
- this._receiver0 = undefined;
- if (executor !== INTERNAL) {
- check(this, executor);
- this._resolveFromExecutor(executor);
- }
- this._promiseCreated();
- this._fireEvent("promiseCreated", this);
- }
- Promise.prototype.toString = function () {
- return "[object Promise]";
- };
- Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
- var len = arguments.length;
- if (len > 1) {
- var catchInstances = new Array(len - 1),
- j = 0, i;
- for (i = 0; i < len - 1; ++i) {
- var item = arguments[i];
- if (util.isObject(item)) {
- catchInstances[j++] = item;
- } else {
- return apiRejection("expecting an object but got " +
- "A catch statement predicate " + util.classString(item));
- }
- }
- catchInstances.length = j;
- fn = arguments[i];
- return this.then(undefined, catchFilter(catchInstances, fn, this));
- }
- return this.then(undefined, fn);
- };
- Promise.prototype.reflect = function () {
- return this._then(reflectHandler,
- reflectHandler, undefined, this, undefined);
- };
- Promise.prototype.then = function (didFulfill, didReject) {
- if (debug.warnings() && arguments.length > 0 &&
- typeof didFulfill !== "function" &&
- typeof didReject !== "function") {
- var msg = ".then() only accepts functions but was passed: " +
- util.classString(didFulfill);
- if (arguments.length > 1) {
- msg += ", " + util.classString(didReject);
- }
- this._warn(msg);
- }
- return this._then(didFulfill, didReject, undefined, undefined, undefined);
- };
- Promise.prototype.done = function (didFulfill, didReject) {
- var promise =
- this._then(didFulfill, didReject, undefined, undefined, undefined);
- promise._setIsFinal();
- };
- Promise.prototype.spread = function (fn) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- return this.all()._then(fn, undefined, undefined, APPLY, undefined);
- };
- Promise.prototype.toJSON = function () {
- var ret = {
- isFulfilled: false,
- isRejected: false,
- fulfillmentValue: undefined,
- rejectionReason: undefined
- };
- if (this.isFulfilled()) {
- ret.fulfillmentValue = this.value();
- ret.isFulfilled = true;
- } else if (this.isRejected()) {
- ret.rejectionReason = this.reason();
- ret.isRejected = true;
- }
- return ret;
- };
- Promise.prototype.all = function () {
- if (arguments.length > 0) {
- this._warn(".all() was passed arguments but it does not take any");
- }
- return new PromiseArray(this).promise();
- };
- Promise.prototype.error = function (fn) {
- return this.caught(util.originatesFromRejection, fn);
- };
- Promise.getNewLibraryCopy = module.exports;
- Promise.is = function (val) {
- return val instanceof Promise;
- };
- Promise.fromNode = Promise.fromCallback = function(fn) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
- : false;
- var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
- if (result === errorObj) {
- ret._rejectCallback(result.e, true);
- }
- if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
- return ret;
- };
- Promise.all = function (promises) {
- return new PromiseArray(promises).promise();
- };
- Promise.cast = function (obj) {
- var ret = tryConvertToPromise(obj);
- if (!(ret instanceof Promise)) {
- ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._setFulfilled();
- ret._rejectionHandler0 = obj;
- }
- return ret;
- };
- Promise.resolve = Promise.fulfilled = Promise.cast;
- Promise.reject = Promise.rejected = function (reason) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._rejectCallback(reason, true);
- return ret;
- };
- Promise.setScheduler = function(fn) {
- if (typeof fn !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(fn));
- }
- return async.setScheduler(fn);
- };
- Promise.prototype._then = function (
- didFulfill,
- didReject,
- _, receiver,
- internalData
- ) {
- var haveInternalData = internalData !== undefined;
- var promise = haveInternalData ? internalData : new Promise(INTERNAL);
- var target = this._target();
- var bitField = target._bitField;
- if (!haveInternalData) {
- promise._propagateFrom(this, 3);
- promise._captureStackTrace();
- if (receiver === undefined &&
- ((this._bitField & 2097152) !== 0)) {
- if (!((bitField & 50397184) === 0)) {
- receiver = this._boundValue();
- } else {
- receiver = target === this ? undefined : this._boundTo;
- }
- }
- this._fireEvent("promiseChained", this, promise);
- }
- var domain = getDomain();
- if (!((bitField & 50397184) === 0)) {
- var handler, value, settler = target._settlePromiseCtx;
- if (((bitField & 33554432) !== 0)) {
- value = target._rejectionHandler0;
- handler = didFulfill;
- } else if (((bitField & 16777216) !== 0)) {
- value = target._fulfillmentHandler0;
- handler = didReject;
- target._unsetRejectionIsUnhandled();
- } else {
- settler = target._settlePromiseLateCancellationObserver;
- value = new CancellationError("late cancellation observer");
- target._attachExtraTrace(value);
- handler = didReject;
- }
- async.invoke(settler, target, {
- handler: domain === null ? handler
- : (typeof handler === "function" &&
- util.domainBind(domain, handler)),
- promise: promise,
- receiver: receiver,
- value: value
- });
- } else {
- target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
- }
- return promise;
- };
- Promise.prototype._length = function () {
- return this._bitField & 65535;
- };
- Promise.prototype._isFateSealed = function () {
- return (this._bitField & 117506048) !== 0;
- };
- Promise.prototype._isFollowing = function () {
- return (this._bitField & 67108864) === 67108864;
- };
- Promise.prototype._setLength = function (len) {
- this._bitField = (this._bitField & -65536) |
- (len & 65535);
- };
- Promise.prototype._setFulfilled = function () {
- this._bitField = this._bitField | 33554432;
- this._fireEvent("promiseFulfilled", this);
- };
- Promise.prototype._setRejected = function () {
- this._bitField = this._bitField | 16777216;
- this._fireEvent("promiseRejected", this);
- };
- Promise.prototype._setFollowing = function () {
- this._bitField = this._bitField | 67108864;
- this._fireEvent("promiseResolved", this);
- };
- Promise.prototype._setIsFinal = function () {
- this._bitField = this._bitField | 4194304;
- };
- Promise.prototype._isFinal = function () {
- return (this._bitField & 4194304) > 0;
- };
- Promise.prototype._unsetCancelled = function() {
- this._bitField = this._bitField & (~65536);
- };
- Promise.prototype._setCancelled = function() {
- this._bitField = this._bitField | 65536;
- this._fireEvent("promiseCancelled", this);
- };
- Promise.prototype._setWillBeCancelled = function() {
- this._bitField = this._bitField | 8388608;
- };
- Promise.prototype._setAsyncGuaranteed = function() {
- if (async.hasCustomScheduler()) return;
- this._bitField = this._bitField | 134217728;
- };
- Promise.prototype._receiverAt = function (index) {
- var ret = index === 0 ? this._receiver0 : this[
- index * 4 - 4 + 3];
- if (ret === UNDEFINED_BINDING) {
- return undefined;
- } else if (ret === undefined && this._isBound()) {
- return this._boundValue();
- }
- return ret;
- };
- Promise.prototype._promiseAt = function (index) {
- return this[
- index * 4 - 4 + 2];
- };
- Promise.prototype._fulfillmentHandlerAt = function (index) {
- return this[
- index * 4 - 4 + 0];
- };
- Promise.prototype._rejectionHandlerAt = function (index) {
- return this[
- index * 4 - 4 + 1];
- };
- Promise.prototype._boundValue = function() {};
- Promise.prototype._migrateCallback0 = function (follower) {
- var bitField = follower._bitField;
- var fulfill = follower._fulfillmentHandler0;
- var reject = follower._rejectionHandler0;
- var promise = follower._promise0;
- var receiver = follower._receiverAt(0);
- if (receiver === undefined) receiver = UNDEFINED_BINDING;
- this._addCallbacks(fulfill, reject, promise, receiver, null);
- };
- Promise.prototype._migrateCallbackAt = function (follower, index) {
- var fulfill = follower._fulfillmentHandlerAt(index);
- var reject = follower._rejectionHandlerAt(index);
- var promise = follower._promiseAt(index);
- var receiver = follower._receiverAt(index);
- if (receiver === undefined) receiver = UNDEFINED_BINDING;
- this._addCallbacks(fulfill, reject, promise, receiver, null);
- };
- Promise.prototype._addCallbacks = function (
- fulfill,
- reject,
- promise,
- receiver,
- domain
- ) {
- var index = this._length();
- if (index >= 65535 - 4) {
- index = 0;
- this._setLength(0);
- }
- if (index === 0) {
- this._promise0 = promise;
- this._receiver0 = receiver;
- if (typeof fulfill === "function") {
- this._fulfillmentHandler0 =
- domain === null ? fulfill : util.domainBind(domain, fulfill);
- }
- if (typeof reject === "function") {
- this._rejectionHandler0 =
- domain === null ? reject : util.domainBind(domain, reject);
- }
- } else {
- var base = index * 4 - 4;
- this[base + 2] = promise;
- this[base + 3] = receiver;
- if (typeof fulfill === "function") {
- this[base + 0] =
- domain === null ? fulfill : util.domainBind(domain, fulfill);
- }
- if (typeof reject === "function") {
- this[base + 1] =
- domain === null ? reject : util.domainBind(domain, reject);
- }
- }
- this._setLength(index + 1);
- return index;
- };
- Promise.prototype._proxy = function (proxyable, arg) {
- this._addCallbacks(undefined, undefined, arg, proxyable, null);
- };
- Promise.prototype._resolveCallback = function(value, shouldBind) {
- if (((this._bitField & 117506048) !== 0)) return;
- if (value === this)
- return this._rejectCallback(makeSelfResolutionError(), false);
- var maybePromise = tryConvertToPromise(value, this);
- if (!(maybePromise instanceof Promise)) return this._fulfill(value);
- if (shouldBind) this._propagateFrom(maybePromise, 2);
- var promise = maybePromise._target();
- if (promise === this) {
- this._reject(makeSelfResolutionError());
- return;
- }
- var bitField = promise._bitField;
- if (((bitField & 50397184) === 0)) {
- var len = this._length();
- if (len > 0) promise._migrateCallback0(this);
- for (var i = 1; i < len; ++i) {
- promise._migrateCallbackAt(this, i);
- }
- this._setFollowing();
- this._setLength(0);
- this._setFollowee(promise);
- } else if (((bitField & 33554432) !== 0)) {
- this._fulfill(promise._value());
- } else if (((bitField & 16777216) !== 0)) {
- this._reject(promise._reason());
- } else {
- var reason = new CancellationError("late cancellation observer");
- promise._attachExtraTrace(reason);
- this._reject(reason);
- }
- };
- Promise.prototype._rejectCallback =
- function(reason, synchronous, ignoreNonErrorWarnings) {
- var trace = util.ensureErrorObject(reason);
- var hasStack = trace === reason;
- if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
- var message = "a promise was rejected with a non-error: " +
- util.classString(reason);
- this._warn(message, true);
- }
- this._attachExtraTrace(trace, synchronous ? hasStack : false);
- this._reject(reason);
- };
- Promise.prototype._resolveFromExecutor = function (executor) {
- var promise = this;
- this._captureStackTrace();
- this._pushContext();
- var synchronous = true;
- var r = this._execute(executor, function(value) {
- promise._resolveCallback(value);
- }, function (reason) {
- promise._rejectCallback(reason, synchronous);
- });
- synchronous = false;
- this._popContext();
- if (r !== undefined) {
- promise._rejectCallback(r, true);
- }
- };
- Promise.prototype._settlePromiseFromHandler = function (
- handler, receiver, value, promise
- ) {
- var bitField = promise._bitField;
- if (((bitField & 65536) !== 0)) return;
- promise._pushContext();
- var x;
- if (receiver === APPLY) {
- if (!value || typeof value.length !== "number") {
- x = errorObj;
- x.e = new TypeError("cannot .spread() a non-array: " +
- util.classString(value));
- } else {
- x = tryCatch(handler).apply(this._boundValue(), value);
- }
- } else {
- x = tryCatch(handler).call(receiver, value);
- }
- var promiseCreated = promise._popContext();
- bitField = promise._bitField;
- if (((bitField & 65536) !== 0)) return;
- if (x === NEXT_FILTER) {
- promise._reject(value);
- } else if (x === errorObj) {
- promise._rejectCallback(x.e, false);
- } else {
- debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
- promise._resolveCallback(x);
- }
- };
- Promise.prototype._target = function() {
- var ret = this;
- while (ret._isFollowing()) ret = ret._followee();
- return ret;
- };
- Promise.prototype._followee = function() {
- return this._rejectionHandler0;
- };
- Promise.prototype._setFollowee = function(promise) {
- this._rejectionHandler0 = promise;
- };
- Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
- var isPromise = promise instanceof Promise;
- var bitField = this._bitField;
- var asyncGuaranteed = ((bitField & 134217728) !== 0);
- if (((bitField & 65536) !== 0)) {
- if (isPromise) promise._invokeInternalOnCancel();
- if (receiver instanceof PassThroughHandlerContext &&
- receiver.isFinallyHandler()) {
- receiver.cancelPromise = promise;
- if (tryCatch(handler).call(receiver, value) === errorObj) {
- promise._reject(errorObj.e);
- }
- } else if (handler === reflectHandler) {
- promise._fulfill(reflectHandler.call(receiver));
- } else if (receiver instanceof Proxyable) {
- receiver._promiseCancelled(promise);
- } else if (isPromise || promise instanceof PromiseArray) {
- promise._cancel();
- } else {
- receiver.cancel();
- }
- } else if (typeof handler === "function") {
- if (!isPromise) {
- handler.call(receiver, value, promise);
- } else {
- if (asyncGuaranteed) promise._setAsyncGuaranteed();
- this._settlePromiseFromHandler(handler, receiver, value, promise);
- }
- } else if (receiver instanceof Proxyable) {
- if (!receiver._isResolved()) {
- if (((bitField & 33554432) !== 0)) {
- receiver._promiseFulfilled(value, promise);
- } else {
- receiver._promiseRejected(value, promise);
- }
- }
- } else if (isPromise) {
- if (asyncGuaranteed) promise._setAsyncGuaranteed();
- if (((bitField & 33554432) !== 0)) {
- promise._fulfill(value);
- } else {
- promise._reject(value);
- }
- }
- };
- Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
- var handler = ctx.handler;
- var promise = ctx.promise;
- var receiver = ctx.receiver;
- var value = ctx.value;
- if (typeof handler === "function") {
- if (!(promise instanceof Promise)) {
- handler.call(receiver, value, promise);
- } else {
- this._settlePromiseFromHandler(handler, receiver, value, promise);
- }
- } else if (promise instanceof Promise) {
- promise._reject(value);
- }
- };
- Promise.prototype._settlePromiseCtx = function(ctx) {
- this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
- };
- Promise.prototype._settlePromise0 = function(handler, value, bitField) {
- var promise = this._promise0;
- var receiver = this._receiverAt(0);
- this._promise0 = undefined;
- this._receiver0 = undefined;
- this._settlePromise(promise, handler, receiver, value);
- };
- Promise.prototype._clearCallbackDataAtIndex = function(index) {
- var base = index * 4 - 4;
- this[base + 2] =
- this[base + 3] =
- this[base + 0] =
- this[base + 1] = undefined;
- };
- Promise.prototype._fulfill = function (value) {
- var bitField = this._bitField;
- if (((bitField & 117506048) >>> 16)) return;
- if (value === this) {
- var err = makeSelfResolutionError();
- this._attachExtraTrace(err);
- return this._reject(err);
- }
- this._setFulfilled();
- this._rejectionHandler0 = value;
- if ((bitField & 65535) > 0) {
- if (((bitField & 134217728) !== 0)) {
- this._settlePromises();
- } else {
- async.settlePromises(this);
- }
- }
- };
- Promise.prototype._reject = function (reason) {
- var bitField = this._bitField;
- if (((bitField & 117506048) >>> 16)) return;
- this._setRejected();
- this._fulfillmentHandler0 = reason;
- if (this._isFinal()) {
- return async.fatalError(reason, util.isNode);
- }
- if ((bitField & 65535) > 0) {
- async.settlePromises(this);
- } else {
- this._ensurePossibleRejectionHandled();
- }
- };
- Promise.prototype._fulfillPromises = function (len, value) {
- for (var i = 1; i < len; i++) {
- var handler = this._fulfillmentHandlerAt(i);
- var promise = this._promiseAt(i);
- var receiver = this._receiverAt(i);
- this._clearCallbackDataAtIndex(i);
- this._settlePromise(promise, handler, receiver, value);
- }
- };
- Promise.prototype._rejectPromises = function (len, reason) {
- for (var i = 1; i < len; i++) {
- var handler = this._rejectionHandlerAt(i);
- var promise = this._promiseAt(i);
- var receiver = this._receiverAt(i);
- this._clearCallbackDataAtIndex(i);
- this._settlePromise(promise, handler, receiver, reason);
- }
- };
- Promise.prototype._settlePromises = function () {
- var bitField = this._bitField;
- var len = (bitField & 65535);
- if (len > 0) {
- if (((bitField & 16842752) !== 0)) {
- var reason = this._fulfillmentHandler0;
- this._settlePromise0(this._rejectionHandler0, reason, bitField);
- this._rejectPromises(len, reason);
- } else {
- var value = this._rejectionHandler0;
- this._settlePromise0(this._fulfillmentHandler0, value, bitField);
- this._fulfillPromises(len, value);
- }
- this._setLength(0);
- }
- this._clearCancellationData();
- };
- Promise.prototype._settledValue = function() {
- var bitField = this._bitField;
- if (((bitField & 33554432) !== 0)) {
- return this._rejectionHandler0;
- } else if (((bitField & 16777216) !== 0)) {
- return this._fulfillmentHandler0;
- }
- };
- function deferResolve(v) {this.promise._resolveCallback(v);}
- function deferReject(v) {this.promise._rejectCallback(v, false);}
- Promise.defer = Promise.pending = function() {
- debug.deprecated("Promise.defer", "new Promise");
- var promise = new Promise(INTERNAL);
- return {
- promise: promise,
- resolve: deferResolve,
- reject: deferReject
- };
- };
- util.notEnumerableProp(Promise,
- "_makeSelfResolutionError",
- makeSelfResolutionError);
- require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
- debug);
- require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
- require("./cancel")(Promise, PromiseArray, apiRejection, debug);
- require("./direct_resolve")(Promise);
- require("./synchronous_inspection")(Promise);
- require("./join")(
- Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
- Promise.Promise = Promise;
- Promise.version = "3.4.7";
- require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
- require('./call_get.js')(Promise);
- require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
- require('./timers.js')(Promise, INTERNAL, debug);
- require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
- require('./nodeify.js')(Promise);
- require('./promisify.js')(Promise, INTERNAL);
- require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
- require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
- require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
- require('./settle.js')(Promise, PromiseArray, debug);
- require('./some.js')(Promise, PromiseArray, apiRejection);
- require('./filter.js')(Promise, INTERNAL);
- require('./each.js')(Promise, INTERNAL);
- require('./any.js')(Promise);
-
- util.toFastProperties(Promise);
- util.toFastProperties(Promise.prototype);
- function fillTypes(value) {
- var p = new Promise(INTERNAL);
- p._fulfillmentHandler0 = value;
- p._rejectionHandler0 = value;
- p._promise0 = value;
- p._receiver0 = value;
- }
- // Complete slack tracking, opt out of field-type tracking and
- // stabilize map
- fillTypes({a: 1});
- fillTypes({b: 2});
- fillTypes({c: 3});
- fillTypes(1);
- fillTypes(function(){});
- fillTypes(undefined);
- fillTypes(false);
- fillTypes(new Promise(INTERNAL));
- debug.setBounds(Async.firstLineError, util.lastLineError);
- return Promise;
- };
- }).call(this,require('_process'))
- },{"./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){
- "use strict";
- module.exports = function(Promise, INTERNAL, tryConvertToPromise,
- apiRejection, Proxyable) {
- var util = require("./util");
- var isArray = util.isArray;
- function toResolutionValue(val) {
- switch(val) {
- case -2: return [];
- case -3: return {};
- }
- }
- function PromiseArray(values) {
- var promise = this._promise = new Promise(INTERNAL);
- if (values instanceof Promise) {
- promise._propagateFrom(values, 3);
- }
- promise._setOnCancel(this);
- this._values = values;
- this._length = 0;
- this._totalResolved = 0;
- this._init(undefined, -2);
- }
- util.inherits(PromiseArray, Proxyable);
- PromiseArray.prototype.length = function () {
- return this._length;
- };
- PromiseArray.prototype.promise = function () {
- return this._promise;
- };
- PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
- var values = tryConvertToPromise(this._values, this._promise);
- if (values instanceof Promise) {
- values = values._target();
- var bitField = values._bitField;
- ;
- this._values = values;
- if (((bitField & 50397184) === 0)) {
- this._promise._setAsyncGuaranteed();
- return values._then(
- init,
- this._reject,
- undefined,
- this,
- resolveValueIfEmpty
- );
- } else if (((bitField & 33554432) !== 0)) {
- values = values._value();
- } else if (((bitField & 16777216) !== 0)) {
- return this._reject(values._reason());
- } else {
- return this._cancel();
- }
- }
- values = util.asArray(values);
- if (values === null) {
- var err = apiRejection(
- "expecting an array or an iterable object but got " + util.classString(values)).reason();
- this._promise._rejectCallback(err, false);
- return;
- }
- if (values.length === 0) {
- if (resolveValueIfEmpty === -5) {
- this._resolveEmptyArray();
- }
- else {
- this._resolve(toResolutionValue(resolveValueIfEmpty));
- }
- return;
- }
- this._iterate(values);
- };
- PromiseArray.prototype._iterate = function(values) {
- var len = this.getActualLength(values.length);
- this._length = len;
- this._values = this.shouldCopyValues() ? new Array(len) : this._values;
- var result = this._promise;
- var isResolved = false;
- var bitField = null;
- for (var i = 0; i < len; ++i) {
- var maybePromise = tryConvertToPromise(values[i], result);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- bitField = maybePromise._bitField;
- } else {
- bitField = null;
- }
- if (isResolved) {
- if (bitField !== null) {
- maybePromise.suppressUnhandledRejections();
- }
- } else if (bitField !== null) {
- if (((bitField & 50397184) === 0)) {
- maybePromise._proxy(this, i);
- this._values[i] = maybePromise;
- } else if (((bitField & 33554432) !== 0)) {
- isResolved = this._promiseFulfilled(maybePromise._value(), i);
- } else if (((bitField & 16777216) !== 0)) {
- isResolved = this._promiseRejected(maybePromise._reason(), i);
- } else {
- isResolved = this._promiseCancelled(i);
- }
- } else {
- isResolved = this._promiseFulfilled(maybePromise, i);
- }
- }
- if (!isResolved) result._setAsyncGuaranteed();
- };
- PromiseArray.prototype._isResolved = function () {
- return this._values === null;
- };
- PromiseArray.prototype._resolve = function (value) {
- this._values = null;
- this._promise._fulfill(value);
- };
- PromiseArray.prototype._cancel = function() {
- if (this._isResolved() || !this._promise._isCancellable()) return;
- this._values = null;
- this._promise._cancel();
- };
- PromiseArray.prototype._reject = function (reason) {
- this._values = null;
- this._promise._rejectCallback(reason, false);
- };
- PromiseArray.prototype._promiseFulfilled = function (value, index) {
- this._values[index] = value;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- this._resolve(this._values);
- return true;
- }
- return false;
- };
- PromiseArray.prototype._promiseCancelled = function() {
- this._cancel();
- return true;
- };
- PromiseArray.prototype._promiseRejected = function (reason) {
- this._totalResolved++;
- this._reject(reason);
- return true;
- };
- PromiseArray.prototype._resultCancelled = function() {
- if (this._isResolved()) return;
- var values = this._values;
- this._cancel();
- if (values instanceof Promise) {
- values.cancel();
- } else {
- for (var i = 0; i < values.length; ++i) {
- if (values[i] instanceof Promise) {
- values[i].cancel();
- }
- }
- }
- };
- PromiseArray.prototype.shouldCopyValues = function () {
- return true;
- };
- PromiseArray.prototype.getActualLength = function (len) {
- return len;
- };
- return PromiseArray;
- };
- },{"./util":74}],62:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var THIS = {};
- var util = require("./util");
- var nodebackForPromise = require("./nodeback");
- var withAppended = util.withAppended;
- var maybeWrapAsError = util.maybeWrapAsError;
- var canEvaluate = util.canEvaluate;
- var TypeError = require("./errors").TypeError;
- var defaultSuffix = "Async";
- var defaultPromisified = {__isPromisified__: true};
- var noCopyProps = [
- "arity", "length",
- "name",
- "arguments",
- "caller",
- "callee",
- "prototype",
- "__isPromisified__"
- ];
- var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
- var defaultFilter = function(name) {
- return util.isIdentifier(name) &&
- name.charAt(0) !== "_" &&
- name !== "constructor";
- };
- function propsFilter(key) {
- return !noCopyPropsPattern.test(key);
- }
- function isPromisified(fn) {
- try {
- return fn.__isPromisified__ === true;
- }
- catch (e) {
- return false;
- }
- }
- function hasPromisified(obj, key, suffix) {
- var val = util.getDataPropertyOrDefault(obj, key + suffix,
- defaultPromisified);
- return val ? isPromisified(val) : false;
- }
- function checkValid(ret, suffix, suffixRegexp) {
- for (var i = 0; i < ret.length; i += 2) {
- var key = ret[i];
- if (suffixRegexp.test(key)) {
- var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
- for (var j = 0; j < ret.length; j += 2) {
- if (ret[j] === keyWithoutAsyncSuffix) {
- throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
- .replace("%s", suffix));
- }
- }
- }
- }
- }
- function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
- var keys = util.inheritedDataKeys(obj);
- var ret = [];
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- var value = obj[key];
- var passesDefaultFilter = filter === defaultFilter
- ? true : defaultFilter(key, value, obj);
- if (typeof value === "function" &&
- !isPromisified(value) &&
- !hasPromisified(obj, key, suffix) &&
- filter(key, value, obj, passesDefaultFilter)) {
- ret.push(key, value);
- }
- }
- checkValid(ret, suffix, suffixRegexp);
- return ret;
- }
- var escapeIdentRegex = function(str) {
- return str.replace(/([$])/, "\\$");
- };
- var makeNodePromisifiedEval;
- if (!false) {
- var switchCaseArgumentOrder = function(likelyArgumentCount) {
- var ret = [likelyArgumentCount];
- var min = Math.max(0, likelyArgumentCount - 1 - 3);
- for(var i = likelyArgumentCount - 1; i >= min; --i) {
- ret.push(i);
- }
- for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
- ret.push(i);
- }
- return ret;
- };
- var argumentSequence = function(argumentCount) {
- return util.filledRange(argumentCount, "_arg", "");
- };
- var parameterDeclaration = function(parameterCount) {
- return util.filledRange(
- Math.max(parameterCount, 3), "_arg", "");
- };
- var parameterCount = function(fn) {
- if (typeof fn.length === "number") {
- return Math.max(Math.min(fn.length, 1023 + 1), 0);
- }
- return 0;
- };
- makeNodePromisifiedEval =
- function(callback, receiver, originalName, fn, _, multiArgs) {
- var newParameterCount = Math.max(0, parameterCount(fn) - 1);
- var argumentOrder = switchCaseArgumentOrder(newParameterCount);
- var shouldProxyThis = typeof callback === "string" || receiver === THIS;
- function generateCallForArgumentCount(count) {
- var args = argumentSequence(count).join(", ");
- var comma = count > 0 ? ", " : "";
- var ret;
- if (shouldProxyThis) {
- ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
- } else {
- ret = receiver === undefined
- ? "ret = callback({{args}}, nodeback); break;\n"
- : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
- }
- return ret.replace("{{args}}", args).replace(", ", comma);
- }
- function generateArgumentSwitchCase() {
- var ret = "";
- for (var i = 0; i < argumentOrder.length; ++i) {
- ret += "case " + argumentOrder[i] +":" +
- generateCallForArgumentCount(argumentOrder[i]);
- }
- ret += " \n\
- default: \n\
- var args = new Array(len + 1); \n\
- var i = 0; \n\
- for (var i = 0; i < len; ++i) { \n\
- args[i] = arguments[i]; \n\
- } \n\
- args[i] = nodeback; \n\
- [CodeForCall] \n\
- break; \n\
- ".replace("[CodeForCall]", (shouldProxyThis
- ? "ret = callback.apply(this, args);\n"
- : "ret = callback.apply(receiver, args);\n"));
- return ret;
- }
- var getFunctionCode = typeof callback === "string"
- ? ("this != null ? this['"+callback+"'] : fn")
- : "fn";
- var body = "'use strict'; \n\
- var ret = function (Parameters) { \n\
- 'use strict'; \n\
- var len = arguments.length; \n\
- var promise = new Promise(INTERNAL); \n\
- promise._captureStackTrace(); \n\
- var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
- var ret; \n\
- var callback = tryCatch([GetFunctionCode]); \n\
- switch(len) { \n\
- [CodeForSwitchCase] \n\
- } \n\
- if (ret === errorObj) { \n\
- promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
- } \n\
- if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
- return promise; \n\
- }; \n\
- notEnumerableProp(ret, '__isPromisified__', true); \n\
- return ret; \n\
- ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
- .replace("[GetFunctionCode]", getFunctionCode);
- body = body.replace("Parameters", parameterDeclaration(newParameterCount));
- return new Function("Promise",
- "fn",
- "receiver",
- "withAppended",
- "maybeWrapAsError",
- "nodebackForPromise",
- "tryCatch",
- "errorObj",
- "notEnumerableProp",
- "INTERNAL",
- body)(
- Promise,
- fn,
- receiver,
- withAppended,
- maybeWrapAsError,
- nodebackForPromise,
- util.tryCatch,
- util.errorObj,
- util.notEnumerableProp,
- INTERNAL);
- };
- }
- function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
- var defaultThis = (function() {return this;})();
- var method = callback;
- if (typeof method === "string") {
- callback = fn;
- }
- function promisified() {
- var _receiver = receiver;
- if (receiver === THIS) _receiver = this;
- var promise = new Promise(INTERNAL);
- promise._captureStackTrace();
- var cb = typeof method === "string" && this !== defaultThis
- ? this[method] : callback;
- var fn = nodebackForPromise(promise, multiArgs);
- try {
- cb.apply(_receiver, withAppended(arguments, fn));
- } catch(e) {
- promise._rejectCallback(maybeWrapAsError(e), true, true);
- }
- if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
- return promise;
- }
- util.notEnumerableProp(promisified, "__isPromisified__", true);
- return promisified;
- }
- var makeNodePromisified = canEvaluate
- ? makeNodePromisifiedEval
- : makeNodePromisifiedClosure;
- function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
- var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
- var methods =
- promisifiableMethods(obj, suffix, suffixRegexp, filter);
- for (var i = 0, len = methods.length; i < len; i+= 2) {
- var key = methods[i];
- var fn = methods[i+1];
- var promisifiedKey = key + suffix;
- if (promisifier === makeNodePromisified) {
- obj[promisifiedKey] =
- makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
- } else {
- var promisified = promisifier(fn, function() {
- return makeNodePromisified(key, THIS, key,
- fn, suffix, multiArgs);
- });
- util.notEnumerableProp(promisified, "__isPromisified__", true);
- obj[promisifiedKey] = promisified;
- }
- }
- util.toFastProperties(obj);
- return obj;
- }
- function promisify(callback, receiver, multiArgs) {
- return makeNodePromisified(callback, receiver, undefined,
- callback, null, multiArgs);
- }
- Promise.promisify = function (fn, options) {
- if (typeof fn !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(fn));
- }
- if (isPromisified(fn)) {
- return fn;
- }
- options = Object(options);
- var receiver = options.context === undefined ? THIS : options.context;
- var multiArgs = !!options.multiArgs;
- var ret = promisify(fn, receiver, multiArgs);
- util.copyDescriptors(fn, ret, propsFilter);
- return ret;
- };
- Promise.promisifyAll = function (target, options) {
- if (typeof target !== "function" && typeof target !== "object") {
- throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- options = Object(options);
- var multiArgs = !!options.multiArgs;
- var suffix = options.suffix;
- if (typeof suffix !== "string") suffix = defaultSuffix;
- var filter = options.filter;
- if (typeof filter !== "function") filter = defaultFilter;
- var promisifier = options.promisifier;
- if (typeof promisifier !== "function") promisifier = makeNodePromisified;
- if (!util.isIdentifier(suffix)) {
- throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- var keys = util.inheritedDataKeys(target);
- for (var i = 0; i < keys.length; ++i) {
- var value = target[keys[i]];
- if (keys[i] !== "constructor" &&
- util.isClass(value)) {
- promisifyAll(value.prototype, suffix, filter, promisifier,
- multiArgs);
- promisifyAll(value, suffix, filter, promisifier, multiArgs);
- }
- }
- return promisifyAll(target, suffix, filter, promisifier, multiArgs);
- };
- };
- },{"./errors":50,"./nodeback":58,"./util":74}],63:[function(require,module,exports){
- "use strict";
- module.exports = function(
- Promise, PromiseArray, tryConvertToPromise, apiRejection) {
- var util = require("./util");
- var isObject = util.isObject;
- var es5 = require("./es5");
- var Es6Map;
- if (typeof Map === "function") Es6Map = Map;
- var mapToEntries = (function() {
- var index = 0;
- var size = 0;
- function extractEntry(value, key) {
- this[index] = value;
- this[index + size] = key;
- index++;
- }
- return function mapToEntries(map) {
- size = map.size;
- index = 0;
- var ret = new Array(map.size * 2);
- map.forEach(extractEntry, ret);
- return ret;
- };
- })();
- var entriesToMap = function(entries) {
- var ret = new Es6Map();
- var length = entries.length / 2 | 0;
- for (var i = 0; i < length; ++i) {
- var key = entries[length + i];
- var value = entries[i];
- ret.set(key, value);
- }
- return ret;
- };
- function PropertiesPromiseArray(obj) {
- var isMap = false;
- var entries;
- if (Es6Map !== undefined && obj instanceof Es6Map) {
- entries = mapToEntries(obj);
- isMap = true;
- } else {
- var keys = es5.keys(obj);
- var len = keys.length;
- entries = new Array(len * 2);
- for (var i = 0; i < len; ++i) {
- var key = keys[i];
- entries[i] = obj[key];
- entries[i + len] = key;
- }
- }
- this.constructor$(entries);
- this._isMap = isMap;
- this._init$(undefined, -3);
- }
- util.inherits(PropertiesPromiseArray, PromiseArray);
- PropertiesPromiseArray.prototype._init = function () {};
- PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
- this._values[index] = value;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- var val;
- if (this._isMap) {
- val = entriesToMap(this._values);
- } else {
- val = {};
- var keyOffset = this.length();
- for (var i = 0, len = this.length(); i < len; ++i) {
- val[this._values[i + keyOffset]] = this._values[i];
- }
- }
- this._resolve(val);
- return true;
- }
- return false;
- };
- PropertiesPromiseArray.prototype.shouldCopyValues = function () {
- return false;
- };
- PropertiesPromiseArray.prototype.getActualLength = function (len) {
- return len >> 1;
- };
- function props(promises) {
- var ret;
- var castValue = tryConvertToPromise(promises);
- if (!isObject(castValue)) {
- return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- } else if (castValue instanceof Promise) {
- ret = castValue._then(
- Promise.props, undefined, undefined, undefined, undefined);
- } else {
- ret = new PropertiesPromiseArray(castValue).promise();
- }
- if (castValue instanceof Promise) {
- ret._propagateFrom(castValue, 2);
- }
- return ret;
- }
- Promise.prototype.props = function () {
- return props(this);
- };
- Promise.props = function (promises) {
- return props(promises);
- };
- };
- },{"./es5":51,"./util":74}],64:[function(require,module,exports){
- "use strict";
- function arrayMove(src, srcIndex, dst, dstIndex, len) {
- for (var j = 0; j < len; ++j) {
- dst[j + dstIndex] = src[j + srcIndex];
- src[j + srcIndex] = void 0;
- }
- }
- function Queue(capacity) {
- this._capacity = capacity;
- this._length = 0;
- this._front = 0;
- }
- Queue.prototype._willBeOverCapacity = function (size) {
- return this._capacity < size;
- };
- Queue.prototype._pushOne = function (arg) {
- var length = this.length();
- this._checkCapacity(length + 1);
- var i = (this._front + length) & (this._capacity - 1);
- this[i] = arg;
- this._length = length + 1;
- };
- Queue.prototype.push = function (fn, receiver, arg) {
- var length = this.length() + 3;
- if (this._willBeOverCapacity(length)) {
- this._pushOne(fn);
- this._pushOne(receiver);
- this._pushOne(arg);
- return;
- }
- var j = this._front + length - 3;
- this._checkCapacity(length);
- var wrapMask = this._capacity - 1;
- this[(j + 0) & wrapMask] = fn;
- this[(j + 1) & wrapMask] = receiver;
- this[(j + 2) & wrapMask] = arg;
- this._length = length;
- };
- Queue.prototype.shift = function () {
- var front = this._front,
- ret = this[front];
- this[front] = undefined;
- this._front = (front + 1) & (this._capacity - 1);
- this._length--;
- return ret;
- };
- Queue.prototype.length = function () {
- return this._length;
- };
- Queue.prototype._checkCapacity = function (size) {
- if (this._capacity < size) {
- this._resizeTo(this._capacity << 1);
- }
- };
- Queue.prototype._resizeTo = function (capacity) {
- var oldCapacity = this._capacity;
- this._capacity = capacity;
- var front = this._front;
- var length = this._length;
- var moveItemsCount = (front + length) & (oldCapacity - 1);
- arrayMove(this, 0, this, oldCapacity, moveItemsCount);
- };
- module.exports = Queue;
- },{}],65:[function(require,module,exports){
- "use strict";
- module.exports = function(
- Promise, INTERNAL, tryConvertToPromise, apiRejection) {
- var util = require("./util");
- var raceLater = function (promise) {
- return promise.then(function(array) {
- return race(array, promise);
- });
- };
- function race(promises, parent) {
- var maybePromise = tryConvertToPromise(promises);
- if (maybePromise instanceof Promise) {
- return raceLater(maybePromise);
- } else {
- promises = util.asArray(promises);
- if (promises === null)
- return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
- }
- var ret = new Promise(INTERNAL);
- if (parent !== undefined) {
- ret._propagateFrom(parent, 3);
- }
- var fulfill = ret._fulfill;
- var reject = ret._reject;
- for (var i = 0, len = promises.length; i < len; ++i) {
- var val = promises[i];
- if (val === undefined && !(i in promises)) {
- continue;
- }
- Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
- }
- return ret;
- }
- Promise.race = function (promises) {
- return race(promises, undefined);
- };
- Promise.prototype.race = function () {
- return race(this, undefined);
- };
- };
- },{"./util":74}],66:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise,
- PromiseArray,
- apiRejection,
- tryConvertToPromise,
- INTERNAL,
- debug) {
- var getDomain = Promise._getDomain;
- var util = require("./util");
- var tryCatch = util.tryCatch;
- function ReductionPromiseArray(promises, fn, initialValue, _each) {
- this.constructor$(promises);
- var domain = getDomain();
- this._fn = domain === null ? fn : util.domainBind(domain, fn);
- if (initialValue !== undefined) {
- initialValue = Promise.resolve(initialValue);
- initialValue._attachCancellationCallback(this);
- }
- this._initialValue = initialValue;
- this._currentCancellable = null;
- if(_each === INTERNAL) {
- this._eachValues = Array(this._length);
- } else if (_each === 0) {
- this._eachValues = null;
- } else {
- this._eachValues = undefined;
- }
- this._promise._captureStackTrace();
- this._init$(undefined, -5);
- }
- util.inherits(ReductionPromiseArray, PromiseArray);
- ReductionPromiseArray.prototype._gotAccum = function(accum) {
- if (this._eachValues !== undefined &&
- this._eachValues !== null &&
- accum !== INTERNAL) {
- this._eachValues.push(accum);
- }
- };
- ReductionPromiseArray.prototype._eachComplete = function(value) {
- if (this._eachValues !== null) {
- this._eachValues.push(value);
- }
- return this._eachValues;
- };
- ReductionPromiseArray.prototype._init = function() {};
- ReductionPromiseArray.prototype._resolveEmptyArray = function() {
- this._resolve(this._eachValues !== undefined ? this._eachValues
- : this._initialValue);
- };
- ReductionPromiseArray.prototype.shouldCopyValues = function () {
- return false;
- };
- ReductionPromiseArray.prototype._resolve = function(value) {
- this._promise._resolveCallback(value);
- this._values = null;
- };
- ReductionPromiseArray.prototype._resultCancelled = function(sender) {
- if (sender === this._initialValue) return this._cancel();
- if (this._isResolved()) return;
- this._resultCancelled$();
- if (this._currentCancellable instanceof Promise) {
- this._currentCancellable.cancel();
- }
- if (this._initialValue instanceof Promise) {
- this._initialValue.cancel();
- }
- };
- ReductionPromiseArray.prototype._iterate = function (values) {
- this._values = values;
- var value;
- var i;
- var length = values.length;
- if (this._initialValue !== undefined) {
- value = this._initialValue;
- i = 0;
- } else {
- value = Promise.resolve(values[0]);
- i = 1;
- }
- this._currentCancellable = value;
- if (!value.isRejected()) {
- for (; i < length; ++i) {
- var ctx = {
- accum: null,
- value: values[i],
- index: i,
- length: length,
- array: this
- };
- value = value._then(gotAccum, undefined, undefined, ctx, undefined);
- }
- }
- if (this._eachValues !== undefined) {
- value = value
- ._then(this._eachComplete, undefined, undefined, this, undefined);
- }
- value._then(completed, completed, undefined, value, this);
- };
- Promise.prototype.reduce = function (fn, initialValue) {
- return reduce(this, fn, initialValue, null);
- };
- Promise.reduce = function (promises, fn, initialValue, _each) {
- return reduce(promises, fn, initialValue, _each);
- };
- function completed(valueOrReason, array) {
- if (this.isFulfilled()) {
- array._resolve(valueOrReason);
- } else {
- array._reject(valueOrReason);
- }
- }
- function reduce(promises, fn, initialValue, _each) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
- return array.promise();
- }
- function gotAccum(accum) {
- this.accum = accum;
- this.array._gotAccum(accum);
- var value = tryConvertToPromise(this.value, this.array._promise);
- if (value instanceof Promise) {
- this.array._currentCancellable = value;
- return value._then(gotValue, undefined, undefined, this, undefined);
- } else {
- return gotValue.call(this, value);
- }
- }
- function gotValue(value) {
- var array = this.array;
- var promise = array._promise;
- var fn = tryCatch(array._fn);
- promise._pushContext();
- var ret;
- if (array._eachValues !== undefined) {
- ret = fn.call(promise._boundValue(), value, this.index, this.length);
- } else {
- ret = fn.call(promise._boundValue(),
- this.accum, value, this.index, this.length);
- }
- if (ret instanceof Promise) {
- array._currentCancellable = ret;
- }
- var promiseCreated = promise._popContext();
- debug.checkForgottenReturns(
- ret,
- promiseCreated,
- array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
- promise
- );
- return ret;
- }
- };
- },{"./util":74}],67:[function(require,module,exports){
- (function (process,global){
- "use strict";
- var util = require("./util");
- var schedule;
- var noAsyncScheduler = function() {
- throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- };
- var NativePromise = util.getNativePromise();
- if (util.isNode && typeof MutationObserver === "undefined") {
- var GlobalSetImmediate = global.setImmediate;
- var ProcessNextTick = process.nextTick;
- schedule = util.isRecentNode
- ? function(fn) { GlobalSetImmediate.call(global, fn); }
- : function(fn) { ProcessNextTick.call(process, fn); };
- } else if (typeof NativePromise === "function" &&
- typeof NativePromise.resolve === "function") {
- var nativePromise = NativePromise.resolve();
- schedule = function(fn) {
- nativePromise.then(fn);
- };
- } else if ((typeof MutationObserver !== "undefined") &&
- !(typeof window !== "undefined" &&
- window.navigator &&
- (window.navigator.standalone || window.cordova))) {
- schedule = (function() {
- var div = document.createElement("div");
- var opts = {attributes: true};
- var toggleScheduled = false;
- var div2 = document.createElement("div");
- var o2 = new MutationObserver(function() {
- div.classList.toggle("foo");
- toggleScheduled = false;
- });
- o2.observe(div2, opts);
- var scheduleToggle = function() {
- if (toggleScheduled) return;
- toggleScheduled = true;
- div2.classList.toggle("foo");
- };
- return function schedule(fn) {
- var o = new MutationObserver(function() {
- o.disconnect();
- fn();
- });
- o.observe(div, opts);
- scheduleToggle();
- };
- })();
- } else if (typeof setImmediate !== "undefined") {
- schedule = function (fn) {
- setImmediate(fn);
- };
- } else if (typeof setTimeout !== "undefined") {
- schedule = function (fn) {
- setTimeout(fn, 0);
- };
- } else {
- schedule = noAsyncScheduler;
- }
- module.exports = schedule;
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./util":74,"_process":138}],68:[function(require,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, debug) {
- var PromiseInspection = Promise.PromiseInspection;
- var util = require("./util");
- function SettledPromiseArray(values) {
- this.constructor$(values);
- }
- util.inherits(SettledPromiseArray, PromiseArray);
- SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
- this._values[index] = inspection;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- this._resolve(this._values);
- return true;
- }
- return false;
- };
- SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
- var ret = new PromiseInspection();
- ret._bitField = 33554432;
- ret._settledValueField = value;
- return this._promiseResolved(index, ret);
- };
- SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
- var ret = new PromiseInspection();
- ret._bitField = 16777216;
- ret._settledValueField = reason;
- return this._promiseResolved(index, ret);
- };
- Promise.settle = function (promises) {
- debug.deprecated(".settle()", ".reflect()");
- return new SettledPromiseArray(promises).promise();
- };
- Promise.prototype.settle = function () {
- return Promise.settle(this);
- };
- };
- },{"./util":74}],69:[function(require,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, apiRejection) {
- var util = require("./util");
- var RangeError = require("./errors").RangeError;
- var AggregateError = require("./errors").AggregateError;
- var isArray = util.isArray;
- var CANCELLATION = {};
- function SomePromiseArray(values) {
- this.constructor$(values);
- this._howMany = 0;
- this._unwrap = false;
- this._initialized = false;
- }
- util.inherits(SomePromiseArray, PromiseArray);
- SomePromiseArray.prototype._init = function () {
- if (!this._initialized) {
- return;
- }
- if (this._howMany === 0) {
- this._resolve([]);
- return;
- }
- this._init$(undefined, -5);
- var isArrayResolved = isArray(this._values);
- if (!this._isResolved() &&
- isArrayResolved &&
- this._howMany > this._canPossiblyFulfill()) {
- this._reject(this._getRangeError(this.length()));
- }
- };
- SomePromiseArray.prototype.init = function () {
- this._initialized = true;
- this._init();
- };
- SomePromiseArray.prototype.setUnwrap = function () {
- this._unwrap = true;
- };
- SomePromiseArray.prototype.howMany = function () {
- return this._howMany;
- };
- SomePromiseArray.prototype.setHowMany = function (count) {
- this._howMany = count;
- };
- SomePromiseArray.prototype._promiseFulfilled = function (value) {
- this._addFulfilled(value);
- if (this._fulfilled() === this.howMany()) {
- this._values.length = this.howMany();
- if (this.howMany() === 1 && this._unwrap) {
- this._resolve(this._values[0]);
- } else {
- this._resolve(this._values);
- }
- return true;
- }
- return false;
- };
- SomePromiseArray.prototype._promiseRejected = function (reason) {
- this._addRejected(reason);
- return this._checkOutcome();
- };
- SomePromiseArray.prototype._promiseCancelled = function () {
- if (this._values instanceof Promise || this._values == null) {
- return this._cancel();
- }
- this._addRejected(CANCELLATION);
- return this._checkOutcome();
- };
- SomePromiseArray.prototype._checkOutcome = function() {
- if (this.howMany() > this._canPossiblyFulfill()) {
- var e = new AggregateError();
- for (var i = this.length(); i < this._values.length; ++i) {
- if (this._values[i] !== CANCELLATION) {
- e.push(this._values[i]);
- }
- }
- if (e.length > 0) {
- this._reject(e);
- } else {
- this._cancel();
- }
- return true;
- }
- return false;
- };
- SomePromiseArray.prototype._fulfilled = function () {
- return this._totalResolved;
- };
- SomePromiseArray.prototype._rejected = function () {
- return this._values.length - this.length();
- };
- SomePromiseArray.prototype._addRejected = function (reason) {
- this._values.push(reason);
- };
- SomePromiseArray.prototype._addFulfilled = function (value) {
- this._values[this._totalResolved++] = value;
- };
- SomePromiseArray.prototype._canPossiblyFulfill = function () {
- return this.length() - this._rejected();
- };
- SomePromiseArray.prototype._getRangeError = function (count) {
- var message = "Input array must contain at least " +
- this._howMany + " items but contains only " + count + " items";
- return new RangeError(message);
- };
- SomePromiseArray.prototype._resolveEmptyArray = function () {
- this._reject(this._getRangeError(0));
- };
- function some(promises, howMany) {
- if ((howMany | 0) !== howMany || howMany < 0) {
- return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- var ret = new SomePromiseArray(promises);
- var promise = ret.promise();
- ret.setHowMany(howMany);
- ret.init();
- return promise;
- }
- Promise.some = function (promises, howMany) {
- return some(promises, howMany);
- };
- Promise.prototype.some = function (howMany) {
- return some(this, howMany);
- };
- Promise._SomePromiseArray = SomePromiseArray;
- };
- },{"./errors":50,"./util":74}],70:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise) {
- function PromiseInspection(promise) {
- if (promise !== undefined) {
- promise = promise._target();
- this._bitField = promise._bitField;
- this._settledValueField = promise._isFateSealed()
- ? promise._settledValue() : undefined;
- }
- else {
- this._bitField = 0;
- this._settledValueField = undefined;
- }
- }
- PromiseInspection.prototype._settledValue = function() {
- return this._settledValueField;
- };
- var value = PromiseInspection.prototype.value = function () {
- if (!this.isFulfilled()) {
- throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- return this._settledValue();
- };
- var reason = PromiseInspection.prototype.error =
- PromiseInspection.prototype.reason = function () {
- if (!this.isRejected()) {
- throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- return this._settledValue();
- };
- var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
- return (this._bitField & 33554432) !== 0;
- };
- var isRejected = PromiseInspection.prototype.isRejected = function () {
- return (this._bitField & 16777216) !== 0;
- };
- var isPending = PromiseInspection.prototype.isPending = function () {
- return (this._bitField & 50397184) === 0;
- };
- var isResolved = PromiseInspection.prototype.isResolved = function () {
- return (this._bitField & 50331648) !== 0;
- };
- PromiseInspection.prototype.isCancelled = function() {
- return (this._bitField & 8454144) !== 0;
- };
- Promise.prototype.__isCancelled = function() {
- return (this._bitField & 65536) === 65536;
- };
- Promise.prototype._isCancelled = function() {
- return this._target().__isCancelled();
- };
- Promise.prototype.isCancelled = function() {
- return (this._target()._bitField & 8454144) !== 0;
- };
- Promise.prototype.isPending = function() {
- return isPending.call(this._target());
- };
- Promise.prototype.isRejected = function() {
- return isRejected.call(this._target());
- };
- Promise.prototype.isFulfilled = function() {
- return isFulfilled.call(this._target());
- };
- Promise.prototype.isResolved = function() {
- return isResolved.call(this._target());
- };
- Promise.prototype.value = function() {
- return value.call(this._target());
- };
- Promise.prototype.reason = function() {
- var target = this._target();
- target._unsetRejectionIsUnhandled();
- return reason.call(target);
- };
- Promise.prototype._value = function() {
- return this._settledValue();
- };
- Promise.prototype._reason = function() {
- this._unsetRejectionIsUnhandled();
- return this._settledValue();
- };
- Promise.PromiseInspection = PromiseInspection;
- };
- },{}],71:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var util = require("./util");
- var errorObj = util.errorObj;
- var isObject = util.isObject;
- function tryConvertToPromise(obj, context) {
- if (isObject(obj)) {
- if (obj instanceof Promise) return obj;
- var then = getThen(obj);
- if (then === errorObj) {
- if (context) context._pushContext();
- var ret = Promise.reject(then.e);
- if (context) context._popContext();
- return ret;
- } else if (typeof then === "function") {
- if (isAnyBluebirdPromise(obj)) {
- var ret = new Promise(INTERNAL);
- obj._then(
- ret._fulfill,
- ret._reject,
- undefined,
- ret,
- null
- );
- return ret;
- }
- return doThenable(obj, then, context);
- }
- }
- return obj;
- }
- function doGetThen(obj) {
- return obj.then;
- }
- function getThen(obj) {
- try {
- return doGetThen(obj);
- } catch (e) {
- errorObj.e = e;
- return errorObj;
- }
- }
- var hasProp = {}.hasOwnProperty;
- function isAnyBluebirdPromise(obj) {
- try {
- return hasProp.call(obj, "_promise0");
- } catch (e) {
- return false;
- }
- }
- function doThenable(x, then, context) {
- var promise = new Promise(INTERNAL);
- var ret = promise;
- if (context) context._pushContext();
- promise._captureStackTrace();
- if (context) context._popContext();
- var synchronous = true;
- var result = util.tryCatch(then).call(x, resolve, reject);
- synchronous = false;
- if (promise && result === errorObj) {
- promise._rejectCallback(result.e, true, true);
- promise = null;
- }
- function resolve(value) {
- if (!promise) return;
- promise._resolveCallback(value);
- promise = null;
- }
- function reject(reason) {
- if (!promise) return;
- promise._rejectCallback(reason, synchronous, true);
- promise = null;
- }
- return ret;
- }
- return tryConvertToPromise;
- };
- },{"./util":74}],72:[function(require,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL, debug) {
- var util = require("./util");
- var TimeoutError = Promise.TimeoutError;
- function HandleWrapper(handle) {
- this.handle = handle;
- }
- HandleWrapper.prototype._resultCancelled = function() {
- clearTimeout(this.handle);
- };
- var afterValue = function(value) { return delay(+this).thenReturn(value); };
- var delay = Promise.delay = function (ms, value) {
- var ret;
- var handle;
- if (value !== undefined) {
- ret = Promise.resolve(value)
- ._then(afterValue, null, null, ms, undefined);
- if (debug.cancellation() && value instanceof Promise) {
- ret._setOnCancel(value);
- }
- } else {
- ret = new Promise(INTERNAL);
- handle = setTimeout(function() { ret._fulfill(); }, +ms);
- if (debug.cancellation()) {
- ret._setOnCancel(new HandleWrapper(handle));
- }
- ret._captureStackTrace();
- }
- ret._setAsyncGuaranteed();
- return ret;
- };
- Promise.prototype.delay = function (ms) {
- return delay(ms, this);
- };
- var afterTimeout = function (promise, message, parent) {
- var err;
- if (typeof message !== "string") {
- if (message instanceof Error) {
- err = message;
- } else {
- err = new TimeoutError("operation timed out");
- }
- } else {
- err = new TimeoutError(message);
- }
- util.markAsOriginatingFromRejection(err);
- promise._attachExtraTrace(err);
- promise._reject(err);
- if (parent != null) {
- parent.cancel();
- }
- };
- function successClear(value) {
- clearTimeout(this.handle);
- return value;
- }
- function failureClear(reason) {
- clearTimeout(this.handle);
- throw reason;
- }
- Promise.prototype.timeout = function (ms, message) {
- ms = +ms;
- var ret, parent;
- var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
- if (ret.isPending()) {
- afterTimeout(ret, message, parent);
- }
- }, ms));
- if (debug.cancellation()) {
- parent = this.then();
- ret = parent._then(successClear, failureClear,
- undefined, handleWrapper, undefined);
- ret._setOnCancel(handleWrapper);
- } else {
- ret = this._then(successClear, failureClear,
- undefined, handleWrapper, undefined);
- }
- return ret;
- };
- };
- },{"./util":74}],73:[function(require,module,exports){
- "use strict";
- module.exports = function (Promise, apiRejection, tryConvertToPromise,
- createContext, INTERNAL, debug) {
- var util = require("./util");
- var TypeError = require("./errors").TypeError;
- var inherits = require("./util").inherits;
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- var NULL = {};
- function thrower(e) {
- setTimeout(function(){throw e;}, 0);
- }
- function castPreservingDisposable(thenable) {
- var maybePromise = tryConvertToPromise(thenable);
- if (maybePromise !== thenable &&
- typeof thenable._isDisposable === "function" &&
- typeof thenable._getDisposer === "function" &&
- thenable._isDisposable()) {
- maybePromise._setDisposable(thenable._getDisposer());
- }
- return maybePromise;
- }
- function dispose(resources, inspection) {
- var i = 0;
- var len = resources.length;
- var ret = new Promise(INTERNAL);
- function iterator() {
- if (i >= len) return ret._fulfill();
- var maybePromise = castPreservingDisposable(resources[i++]);
- if (maybePromise instanceof Promise &&
- maybePromise._isDisposable()) {
- try {
- maybePromise = tryConvertToPromise(
- maybePromise._getDisposer().tryDispose(inspection),
- resources.promise);
- } catch (e) {
- return thrower(e);
- }
- if (maybePromise instanceof Promise) {
- return maybePromise._then(iterator, thrower,
- null, null, null);
- }
- }
- iterator();
- }
- iterator();
- return ret;
- }
- function Disposer(data, promise, context) {
- this._data = data;
- this._promise = promise;
- this._context = context;
- }
- Disposer.prototype.data = function () {
- return this._data;
- };
- Disposer.prototype.promise = function () {
- return this._promise;
- };
- Disposer.prototype.resource = function () {
- if (this.promise().isFulfilled()) {
- return this.promise().value();
- }
- return NULL;
- };
- Disposer.prototype.tryDispose = function(inspection) {
- var resource = this.resource();
- var context = this._context;
- if (context !== undefined) context._pushContext();
- var ret = resource !== NULL
- ? this.doDispose(resource, inspection) : null;
- if (context !== undefined) context._popContext();
- this._promise._unsetDisposable();
- this._data = null;
- return ret;
- };
- Disposer.isDisposer = function (d) {
- return (d != null &&
- typeof d.resource === "function" &&
- typeof d.tryDispose === "function");
- };
- function FunctionDisposer(fn, promise, context) {
- this.constructor$(fn, promise, context);
- }
- inherits(FunctionDisposer, Disposer);
- FunctionDisposer.prototype.doDispose = function (resource, inspection) {
- var fn = this.data();
- return fn.call(resource, resource, inspection);
- };
- function maybeUnwrapDisposer(value) {
- if (Disposer.isDisposer(value)) {
- this.resources[this.index]._setDisposable(value);
- return value.promise();
- }
- return value;
- }
- function ResourceList(length) {
- this.length = length;
- this.promise = null;
- this[length-1] = null;
- }
- ResourceList.prototype._resultCancelled = function() {
- var len = this.length;
- for (var i = 0; i < len; ++i) {
- var item = this[i];
- if (item instanceof Promise) {
- item.cancel();
- }
- }
- };
- Promise.using = function () {
- var len = arguments.length;
- if (len < 2) return apiRejection(
- "you must pass at least 2 arguments to Promise.using");
- var fn = arguments[len - 1];
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- var input;
- var spreadArgs = true;
- if (len === 2 && Array.isArray(arguments[0])) {
- input = arguments[0];
- len = input.length;
- spreadArgs = false;
- } else {
- input = arguments;
- len--;
- }
- var resources = new ResourceList(len);
- for (var i = 0; i < len; ++i) {
- var resource = input[i];
- if (Disposer.isDisposer(resource)) {
- var disposer = resource;
- resource = resource.promise();
- resource._setDisposable(disposer);
- } else {
- var maybePromise = tryConvertToPromise(resource);
- if (maybePromise instanceof Promise) {
- resource =
- maybePromise._then(maybeUnwrapDisposer, null, null, {
- resources: resources,
- index: i
- }, undefined);
- }
- }
- resources[i] = resource;
- }
- var reflectedResources = new Array(resources.length);
- for (var i = 0; i < reflectedResources.length; ++i) {
- reflectedResources[i] = Promise.resolve(resources[i]).reflect();
- }
- var resultPromise = Promise.all(reflectedResources)
- .then(function(inspections) {
- for (var i = 0; i < inspections.length; ++i) {
- var inspection = inspections[i];
- if (inspection.isRejected()) {
- errorObj.e = inspection.error();
- return errorObj;
- } else if (!inspection.isFulfilled()) {
- resultPromise.cancel();
- return;
- }
- inspections[i] = inspection.value();
- }
- promise._pushContext();
- fn = tryCatch(fn);
- var ret = spreadArgs
- ? fn.apply(undefined, inspections) : fn(inspections);
- var promiseCreated = promise._popContext();
- debug.checkForgottenReturns(
- ret, promiseCreated, "Promise.using", promise);
- return ret;
- });
- var promise = resultPromise.lastly(function() {
- var inspection = new Promise.PromiseInspection(resultPromise);
- return dispose(resources, inspection);
- });
- resources.promise = promise;
- promise._setOnCancel(resources);
- return promise;
- };
- Promise.prototype._setDisposable = function (disposer) {
- this._bitField = this._bitField | 131072;
- this._disposer = disposer;
- };
- Promise.prototype._isDisposable = function () {
- return (this._bitField & 131072) > 0;
- };
- Promise.prototype._getDisposer = function () {
- return this._disposer;
- };
- Promise.prototype._unsetDisposable = function () {
- this._bitField = this._bitField & (~131072);
- this._disposer = undefined;
- };
- Promise.prototype.disposer = function (fn) {
- if (typeof fn === "function") {
- return new FunctionDisposer(fn, this, createContext());
- }
- throw new TypeError();
- };
- };
- },{"./errors":50,"./util":74}],74:[function(require,module,exports){
- (function (process,global){
- "use strict";
- var es5 = require("./es5");
- var canEvaluate = typeof navigator == "undefined";
- var errorObj = {e: {}};
- var tryCatchTarget;
- var globalObject = typeof self !== "undefined" ? self :
- typeof window !== "undefined" ? window :
- typeof global !== "undefined" ? global :
- this !== undefined ? this : null;
- function tryCatcher() {
- try {
- var target = tryCatchTarget;
- tryCatchTarget = null;
- return target.apply(this, arguments);
- } catch (e) {
- errorObj.e = e;
- return errorObj;
- }
- }
- function tryCatch(fn) {
- tryCatchTarget = fn;
- return tryCatcher;
- }
- var inherits = function(Child, Parent) {
- var hasProp = {}.hasOwnProperty;
- function T() {
- this.constructor = Child;
- this.constructor$ = Parent;
- for (var propertyName in Parent.prototype) {
- if (hasProp.call(Parent.prototype, propertyName) &&
- propertyName.charAt(propertyName.length-1) !== "$"
- ) {
- this[propertyName + "$"] = Parent.prototype[propertyName];
- }
- }
- }
- T.prototype = Parent.prototype;
- Child.prototype = new T();
- return Child.prototype;
- };
- function isPrimitive(val) {
- return val == null || val === true || val === false ||
- typeof val === "string" || typeof val === "number";
- }
- function isObject(value) {
- return typeof value === "function" ||
- typeof value === "object" && value !== null;
- }
- function maybeWrapAsError(maybeError) {
- if (!isPrimitive(maybeError)) return maybeError;
- return new Error(safeToString(maybeError));
- }
- function withAppended(target, appendee) {
- var len = target.length;
- var ret = new Array(len + 1);
- var i;
- for (i = 0; i < len; ++i) {
- ret[i] = target[i];
- }
- ret[i] = appendee;
- return ret;
- }
- function getDataPropertyOrDefault(obj, key, defaultValue) {
- if (es5.isES5) {
- var desc = Object.getOwnPropertyDescriptor(obj, key);
- if (desc != null) {
- return desc.get == null && desc.set == null
- ? desc.value
- : defaultValue;
- }
- } else {
- return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
- }
- }
- function notEnumerableProp(obj, name, value) {
- if (isPrimitive(obj)) return obj;
- var descriptor = {
- value: value,
- configurable: true,
- enumerable: false,
- writable: true
- };
- es5.defineProperty(obj, name, descriptor);
- return obj;
- }
- function thrower(r) {
- throw r;
- }
- var inheritedDataKeys = (function() {
- var excludedPrototypes = [
- Array.prototype,
- Object.prototype,
- Function.prototype
- ];
- var isExcludedProto = function(val) {
- for (var i = 0; i < excludedPrototypes.length; ++i) {
- if (excludedPrototypes[i] === val) {
- return true;
- }
- }
- return false;
- };
- if (es5.isES5) {
- var getKeys = Object.getOwnPropertyNames;
- return function(obj) {
- var ret = [];
- var visitedKeys = Object.create(null);
- while (obj != null && !isExcludedProto(obj)) {
- var keys;
- try {
- keys = getKeys(obj);
- } catch (e) {
- return ret;
- }
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (visitedKeys[key]) continue;
- visitedKeys[key] = true;
- var desc = Object.getOwnPropertyDescriptor(obj, key);
- if (desc != null && desc.get == null && desc.set == null) {
- ret.push(key);
- }
- }
- obj = es5.getPrototypeOf(obj);
- }
- return ret;
- };
- } else {
- var hasProp = {}.hasOwnProperty;
- return function(obj) {
- if (isExcludedProto(obj)) return [];
- var ret = [];
- /*jshint forin:false */
- enumeration: for (var key in obj) {
- if (hasProp.call(obj, key)) {
- ret.push(key);
- } else {
- for (var i = 0; i < excludedPrototypes.length; ++i) {
- if (hasProp.call(excludedPrototypes[i], key)) {
- continue enumeration;
- }
- }
- ret.push(key);
- }
- }
- return ret;
- };
- }
- })();
- var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
- function isClass(fn) {
- try {
- if (typeof fn === "function") {
- var keys = es5.names(fn.prototype);
- var hasMethods = es5.isES5 && keys.length > 1;
- var hasMethodsOtherThanConstructor = keys.length > 0 &&
- !(keys.length === 1 && keys[0] === "constructor");
- var hasThisAssignmentAndStaticMethods =
- thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
- if (hasMethods || hasMethodsOtherThanConstructor ||
- hasThisAssignmentAndStaticMethods) {
- return true;
- }
- }
- return false;
- } catch (e) {
- return false;
- }
- }
- function toFastProperties(obj) {
- /*jshint -W027,-W055,-W031*/
- function FakeConstructor() {}
- FakeConstructor.prototype = obj;
- var l = 8;
- while (l--) new FakeConstructor();
- return obj;
- eval(obj);
- }
- var rident = /^[a-z$_][a-z$_0-9]*$/i;
- function isIdentifier(str) {
- return rident.test(str);
- }
- function filledRange(count, prefix, suffix) {
- var ret = new Array(count);
- for(var i = 0; i < count; ++i) {
- ret[i] = prefix + i + suffix;
- }
- return ret;
- }
- function safeToString(obj) {
- try {
- return obj + "";
- } catch (e) {
- return "[no string representation]";
- }
- }
- function isError(obj) {
- return obj !== null &&
- typeof obj === "object" &&
- typeof obj.message === "string" &&
- typeof obj.name === "string";
- }
- function markAsOriginatingFromRejection(e) {
- try {
- notEnumerableProp(e, "isOperational", true);
- }
- catch(ignore) {}
- }
- function originatesFromRejection(e) {
- if (e == null) return false;
- return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
- e["isOperational"] === true);
- }
- function canAttachTrace(obj) {
- return isError(obj) && es5.propertyIsWritable(obj, "stack");
- }
- var ensureErrorObject = (function() {
- if (!("stack" in new Error())) {
- return function(value) {
- if (canAttachTrace(value)) return value;
- try {throw new Error(safeToString(value));}
- catch(err) {return err;}
- };
- } else {
- return function(value) {
- if (canAttachTrace(value)) return value;
- return new Error(safeToString(value));
- };
- }
- })();
- function classString(obj) {
- return {}.toString.call(obj);
- }
- function copyDescriptors(from, to, filter) {
- var keys = es5.names(from);
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (filter(key)) {
- try {
- es5.defineProperty(to, key, es5.getDescriptor(from, key));
- } catch (ignore) {}
- }
- }
- }
- var asArray = function(v) {
- if (es5.isArray(v)) {
- return v;
- }
- return null;
- };
- if (typeof Symbol !== "undefined" && Symbol.iterator) {
- var ArrayFrom = typeof Array.from === "function" ? function(v) {
- return Array.from(v);
- } : function(v) {
- var ret = [];
- var it = v[Symbol.iterator]();
- var itResult;
- while (!((itResult = it.next()).done)) {
- ret.push(itResult.value);
- }
- return ret;
- };
- asArray = function(v) {
- if (es5.isArray(v)) {
- return v;
- } else if (v != null && typeof v[Symbol.iterator] === "function") {
- return ArrayFrom(v);
- }
- return null;
- };
- }
- var isNode = typeof process !== "undefined" &&
- classString(process).toLowerCase() === "[object process]";
- var hasEnvVariables = typeof process !== "undefined" &&
- typeof process.env !== "undefined";
- function env(key) {
- return hasEnvVariables ? process.env[key] : undefined;
- }
- function getNativePromise() {
- if (typeof Promise === "function") {
- try {
- var promise = new Promise(function(){});
- if ({}.toString.call(promise) === "[object Promise]") {
- return Promise;
- }
- } catch (e) {}
- }
- }
- function domainBind(self, cb) {
- return self.bind(cb);
- }
- var ret = {
- isClass: isClass,
- isIdentifier: isIdentifier,
- inheritedDataKeys: inheritedDataKeys,
- getDataPropertyOrDefault: getDataPropertyOrDefault,
- thrower: thrower,
- isArray: es5.isArray,
- asArray: asArray,
- notEnumerableProp: notEnumerableProp,
- isPrimitive: isPrimitive,
- isObject: isObject,
- isError: isError,
- canEvaluate: canEvaluate,
- errorObj: errorObj,
- tryCatch: tryCatch,
- inherits: inherits,
- withAppended: withAppended,
- maybeWrapAsError: maybeWrapAsError,
- toFastProperties: toFastProperties,
- filledRange: filledRange,
- toString: safeToString,
- canAttachTrace: canAttachTrace,
- ensureErrorObject: ensureErrorObject,
- originatesFromRejection: originatesFromRejection,
- markAsOriginatingFromRejection: markAsOriginatingFromRejection,
- classString: classString,
- copyDescriptors: copyDescriptors,
- hasDevTools: typeof chrome !== "undefined" && chrome &&
- typeof chrome.loadTimes === "function",
- isNode: isNode,
- hasEnvVariables: hasEnvVariables,
- env: env,
- global: globalObject,
- getNativePromise: getNativePromise,
- domainBind: domainBind
- };
- ret.isRecentNode = ret.isNode && (function() {
- var version = process.versions.node.split(".").map(Number);
- return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
- })();
- if (ret.isNode) ret.toFastProperties(process);
- try {throw new Error(); } catch (e) {ret.lastLineError = e;}
- module.exports = ret;
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./es5":51,"_process":138}],75:[function(require,module,exports){
- },{}],76:[function(require,module,exports){
- (function (global){
- 'use strict';
- var buffer = require('buffer');
- var Buffer = buffer.Buffer;
- var SlowBuffer = buffer.SlowBuffer;
- var MAX_LEN = buffer.kMaxLength || 2147483647;
- exports.alloc = function alloc(size, fill, encoding) {
- if (typeof Buffer.alloc === 'function') {
- return Buffer.alloc(size, fill, encoding);
- }
- if (typeof encoding === 'number') {
- throw new TypeError('encoding must not be number');
- }
- if (typeof size !== 'number') {
- throw new TypeError('size must be a number');
- }
- if (size > MAX_LEN) {
- throw new RangeError('size is too large');
- }
- var enc = encoding;
- var _fill = fill;
- if (_fill === undefined) {
- enc = undefined;
- _fill = 0;
- }
- var buf = new Buffer(size);
- if (typeof _fill === 'string') {
- var fillBuf = new Buffer(_fill, enc);
- var flen = fillBuf.length;
- var i = -1;
- while (++i < size) {
- buf[i] = fillBuf[i % flen];
- }
- } else {
- buf.fill(_fill);
- }
- return buf;
- }
- exports.allocUnsafe = function allocUnsafe(size) {
- if (typeof Buffer.allocUnsafe === 'function') {
- return Buffer.allocUnsafe(size);
- }
- if (typeof size !== 'number') {
- throw new TypeError('size must be a number');
- }
- if (size > MAX_LEN) {
- throw new RangeError('size is too large');
- }
- return new Buffer(size);
- }
- exports.from = function from(value, encodingOrOffset, length) {
- if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
- return Buffer.from(value, encodingOrOffset, length);
- }
- if (typeof value === 'number') {
- throw new TypeError('"value" argument must not be a number');
- }
- if (typeof value === 'string') {
- return new Buffer(value, encodingOrOffset);
- }
- if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
- var offset = encodingOrOffset;
- if (arguments.length === 1) {
- return new Buffer(value);
- }
- if (typeof offset === 'undefined') {
- offset = 0;
- }
- var len = length;
- if (typeof len === 'undefined') {
- len = value.byteLength - offset;
- }
- if (offset >= value.byteLength) {
- throw new RangeError('\'offset\' is out of bounds');
- }
- if (len > value.byteLength - offset) {
- throw new RangeError('\'length\' is out of bounds');
- }
- return new Buffer(value.slice(offset, offset + len));
- }
- if (Buffer.isBuffer(value)) {
- var out = new Buffer(value.length);
- value.copy(out, 0, 0, value.length);
- return out;
- }
- if (value) {
- if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
- return new Buffer(value);
- }
- if (value.type === 'Buffer' && Array.isArray(value.data)) {
- return new Buffer(value.data);
- }
- }
- throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
- }
- exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
- if (typeof Buffer.allocUnsafeSlow === 'function') {
- return Buffer.allocUnsafeSlow(size);
- }
- if (typeof size !== 'number') {
- throw new TypeError('size must be a number');
- }
- if (size >= MAX_LEN) {
- throw new RangeError('size is too large');
- }
- return new SlowBuffer(size);
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"buffer":77}],77:[function(require,module,exports){
- (function (global){
- /*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
- * @license MIT
- */
- /* eslint-disable no-proto */
- 'use strict'
- var base64 = require('base64-js')
- var ieee754 = require('ieee754')
- var isArray = require('isarray')
- exports.Buffer = Buffer
- exports.SlowBuffer = SlowBuffer
- exports.INSPECT_MAX_BYTES = 50
- /**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- * === true Use Uint8Array implementation (fastest)
- * === false Use Object implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * Due to various browser bugs, sometimes the Object implementation will be used even
- * when the browser supports typed arrays.
- *
- * Note:
- *
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
- *
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
- *
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
- * incorrect length in some situations.
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
- * get the Object implementation, which is slower but behaves correctly.
- */
- Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
- ? global.TYPED_ARRAY_SUPPORT
- : typedArraySupport()
- /*
- * Export kMaxLength after typed array support is determined.
- */
- exports.kMaxLength = kMaxLength()
- function typedArraySupport () {
- try {
- var arr = new Uint8Array(1)
- arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
- return arr.foo() === 42 && // typed array instances can be augmented
- typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
- arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
- } catch (e) {
- return false
- }
- }
- function kMaxLength () {
- return Buffer.TYPED_ARRAY_SUPPORT
- ? 0x7fffffff
- : 0x3fffffff
- }
- function createBuffer (that, length) {
- if (kMaxLength() < length) {
- throw new RangeError('Invalid typed array length')
- }
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = new Uint8Array(length)
- that.__proto__ = Buffer.prototype
- } else {
- // Fallback: Return an object instance of the Buffer class
- if (that === null) {
- that = new Buffer(length)
- }
- that.length = length
- }
- return that
- }
- /**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
- function Buffer (arg, encodingOrOffset, length) {
- if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
- return new Buffer(arg, encodingOrOffset, length)
- }
- // Common case.
- if (typeof arg === 'number') {
- if (typeof encodingOrOffset === 'string') {
- throw new Error(
- 'If encoding is specified then the first argument must be a string'
- )
- }
- return allocUnsafe(this, arg)
- }
- return from(this, arg, encodingOrOffset, length)
- }
- Buffer.poolSize = 8192 // not used by this implementation
- // TODO: Legacy, not needed anymore. Remove in next major version.
- Buffer._augment = function (arr) {
- arr.__proto__ = Buffer.prototype
- return arr
- }
- function from (that, value, encodingOrOffset, length) {
- if (typeof value === 'number') {
- throw new TypeError('"value" argument must not be a number')
- }
- if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
- return fromArrayBuffer(that, value, encodingOrOffset, length)
- }
- if (typeof value === 'string') {
- return fromString(that, value, encodingOrOffset)
- }
- return fromObject(that, value)
- }
- /**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
- Buffer.from = function (value, encodingOrOffset, length) {
- return from(null, value, encodingOrOffset, length)
- }
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- Buffer.prototype.__proto__ = Uint8Array.prototype
- Buffer.__proto__ = Uint8Array
- if (typeof Symbol !== 'undefined' && Symbol.species &&
- Buffer[Symbol.species] === Buffer) {
- // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
- Object.defineProperty(Buffer, Symbol.species, {
- value: null,
- configurable: true
- })
- }
- }
- function assertSize (size) {
- if (typeof size !== 'number') {
- throw new TypeError('"size" argument must be a number')
- } else if (size < 0) {
- throw new RangeError('"size" argument must not be negative')
- }
- }
- function alloc (that, size, fill, encoding) {
- assertSize(size)
- if (size <= 0) {
- return createBuffer(that, size)
- }
- if (fill !== undefined) {
- // Only pay attention to encoding if it's a string. This
- // prevents accidentally sending in a number that would
- // be interpretted as a start offset.
- return typeof encoding === 'string'
- ? createBuffer(that, size).fill(fill, encoding)
- : createBuffer(that, size).fill(fill)
- }
- return createBuffer(that, size)
- }
- /**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
- Buffer.alloc = function (size, fill, encoding) {
- return alloc(null, size, fill, encoding)
- }
- function allocUnsafe (that, size) {
- assertSize(size)
- that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- for (var i = 0; i < size; ++i) {
- that[i] = 0
- }
- }
- return that
- }
- /**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
- Buffer.allocUnsafe = function (size) {
- return allocUnsafe(null, size)
- }
- /**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
- Buffer.allocUnsafeSlow = function (size) {
- return allocUnsafe(null, size)
- }
- function fromString (that, string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') {
- encoding = 'utf8'
- }
- if (!Buffer.isEncoding(encoding)) {
- throw new TypeError('"encoding" must be a valid string encoding')
- }
- var length = byteLength(string, encoding) | 0
- that = createBuffer(that, length)
- var actual = that.write(string, encoding)
- if (actual !== length) {
- // Writing a hex string, for example, that contains invalid characters will
- // cause everything after the first invalid character to be ignored. (e.g.
- // 'abxxcd' will be treated as 'ab')
- that = that.slice(0, actual)
- }
- return that
- }
- function fromArrayLike (that, array) {
- var length = array.length < 0 ? 0 : checked(array.length) | 0
- that = createBuffer(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
- }
- return that
- }
- function fromArrayBuffer (that, array, byteOffset, length) {
- array.byteLength // this throws if `array` is not a valid ArrayBuffer
- if (byteOffset < 0 || array.byteLength < byteOffset) {
- throw new RangeError('\'offset\' is out of bounds')
- }
- if (array.byteLength < byteOffset + (length || 0)) {
- throw new RangeError('\'length\' is out of bounds')
- }
- if (byteOffset === undefined && length === undefined) {
- array = new Uint8Array(array)
- } else if (length === undefined) {
- array = new Uint8Array(array, byteOffset)
- } else {
- array = new Uint8Array(array, byteOffset, length)
- }
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = array
- that.__proto__ = Buffer.prototype
- } else {
- // Fallback: Return an object instance of the Buffer class
- that = fromArrayLike(that, array)
- }
- return that
- }
- function fromObject (that, obj) {
- if (Buffer.isBuffer(obj)) {
- var len = checked(obj.length) | 0
- that = createBuffer(that, len)
- if (that.length === 0) {
- return that
- }
- obj.copy(that, 0, 0, len)
- return that
- }
- if (obj) {
- if ((typeof ArrayBuffer !== 'undefined' &&
- obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
- if (typeof obj.length !== 'number' || isnan(obj.length)) {
- return createBuffer(that, 0)
- }
- return fromArrayLike(that, obj)
- }
- if (obj.type === 'Buffer' && isArray(obj.data)) {
- return fromArrayLike(that, obj.data)
- }
- }
- throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
- }
- function checked (length) {
- // Note: cannot use `length < kMaxLength()` here because that fails when
- // length is NaN (which is otherwise coerced to zero.)
- if (length >= kMaxLength()) {
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
- }
- return length | 0
- }
- function SlowBuffer (length) {
- if (+length != length) { // eslint-disable-line eqeqeq
- length = 0
- }
- return Buffer.alloc(+length)
- }
- Buffer.isBuffer = function isBuffer (b) {
- return !!(b != null && b._isBuffer)
- }
- Buffer.compare = function compare (a, b) {
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
- throw new TypeError('Arguments must be Buffers')
- }
- if (a === b) return 0
- var x = a.length
- var y = b.length
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i]
- y = b[i]
- break
- }
- }
- if (x < y) return -1
- if (y < x) return 1
- return 0
- }
- Buffer.isEncoding = function isEncoding (encoding) {
- switch (String(encoding).toLowerCase()) {
- case 'hex':
- case 'utf8':
- case 'utf-8':
- case 'ascii':
- case 'latin1':
- case 'binary':
- case 'base64':
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return true
- default:
- return false
- }
- }
- Buffer.concat = function concat (list, length) {
- if (!isArray(list)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- if (list.length === 0) {
- return Buffer.alloc(0)
- }
- var i
- if (length === undefined) {
- length = 0
- for (i = 0; i < list.length; ++i) {
- length += list[i].length
- }
- }
- var buffer = Buffer.allocUnsafe(length)
- var pos = 0
- for (i = 0; i < list.length; ++i) {
- var buf = list[i]
- if (!Buffer.isBuffer(buf)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- buf.copy(buffer, pos)
- pos += buf.length
- }
- return buffer
- }
- function byteLength (string, encoding) {
- if (Buffer.isBuffer(string)) {
- return string.length
- }
- if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
- (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
- return string.byteLength
- }
- if (typeof string !== 'string') {
- string = '' + string
- }
- var len = string.length
- if (len === 0) return 0
- // Use a for loop to avoid recursion
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'ascii':
- case 'latin1':
- case 'binary':
- return len
- case 'utf8':
- case 'utf-8':
- case undefined:
- return utf8ToBytes(string).length
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return len * 2
- case 'hex':
- return len >>> 1
- case 'base64':
- return base64ToBytes(string).length
- default:
- if (loweredCase) return utf8ToBytes(string).length // assume utf8
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.byteLength = byteLength
- function slowToString (encoding, start, end) {
- var loweredCase = false
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
- // property of a typed array.
- // This behaves neither like String nor Uint8Array in that we set start/end
- // to their upper/lower bounds if the value passed is out of range.
- // undefined is handled specially as per ECMA-262 6th Edition,
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
- if (start === undefined || start < 0) {
- start = 0
- }
- // Return early if start > this.length. Done here to prevent potential uint32
- // coercion fail below.
- if (start > this.length) {
- return ''
- }
- if (end === undefined || end > this.length) {
- end = this.length
- }
- if (end <= 0) {
- return ''
- }
- // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
- end >>>= 0
- start >>>= 0
- if (end <= start) {
- return ''
- }
- if (!encoding) encoding = 'utf8'
- while (true) {
- switch (encoding) {
- case 'hex':
- return hexSlice(this, start, end)
- case 'utf8':
- case 'utf-8':
- return utf8Slice(this, start, end)
- case 'ascii':
- return asciiSlice(this, start, end)
- case 'latin1':
- case 'binary':
- return latin1Slice(this, start, end)
- case 'base64':
- return base64Slice(this, start, end)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return utf16leSlice(this, start, end)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = (encoding + '').toLowerCase()
- loweredCase = true
- }
- }
- }
- // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
- // Buffer instances.
- Buffer.prototype._isBuffer = true
- function swap (b, n, m) {
- var i = b[n]
- b[n] = b[m]
- b[m] = i
- }
- Buffer.prototype.swap16 = function swap16 () {
- var len = this.length
- if (len % 2 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 16-bits')
- }
- for (var i = 0; i < len; i += 2) {
- swap(this, i, i + 1)
- }
- return this
- }
- Buffer.prototype.swap32 = function swap32 () {
- var len = this.length
- if (len % 4 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 32-bits')
- }
- for (var i = 0; i < len; i += 4) {
- swap(this, i, i + 3)
- swap(this, i + 1, i + 2)
- }
- return this
- }
- Buffer.prototype.swap64 = function swap64 () {
- var len = this.length
- if (len % 8 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 64-bits')
- }
- for (var i = 0; i < len; i += 8) {
- swap(this, i, i + 7)
- swap(this, i + 1, i + 6)
- swap(this, i + 2, i + 5)
- swap(this, i + 3, i + 4)
- }
- return this
- }
- Buffer.prototype.toString = function toString () {
- var length = this.length | 0
- if (length === 0) return ''
- if (arguments.length === 0) return utf8Slice(this, 0, length)
- return slowToString.apply(this, arguments)
- }
- Buffer.prototype.equals = function equals (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return true
- return Buffer.compare(this, b) === 0
- }
- Buffer.prototype.inspect = function inspect () {
- var str = ''
- var max = exports.INSPECT_MAX_BYTES
- if (this.length > 0) {
- str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
- if (this.length > max) str += ' ... '
- }
- return '<Buffer ' + str + '>'
- }
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
- if (!Buffer.isBuffer(target)) {
- throw new TypeError('Argument must be a Buffer')
- }
- if (start === undefined) {
- start = 0
- }
- if (end === undefined) {
- end = target ? target.length : 0
- }
- if (thisStart === undefined) {
- thisStart = 0
- }
- if (thisEnd === undefined) {
- thisEnd = this.length
- }
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
- throw new RangeError('out of range index')
- }
- if (thisStart >= thisEnd && start >= end) {
- return 0
- }
- if (thisStart >= thisEnd) {
- return -1
- }
- if (start >= end) {
- return 1
- }
- start >>>= 0
- end >>>= 0
- thisStart >>>= 0
- thisEnd >>>= 0
- if (this === target) return 0
- var x = thisEnd - thisStart
- var y = end - start
- var len = Math.min(x, y)
- var thisCopy = this.slice(thisStart, thisEnd)
- var targetCopy = target.slice(start, end)
- for (var i = 0; i < len; ++i) {
- if (thisCopy[i] !== targetCopy[i]) {
- x = thisCopy[i]
- y = targetCopy[i]
- break
- }
- }
- if (x < y) return -1
- if (y < x) return 1
- return 0
- }
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
- //
- // Arguments:
- // - buffer - a Buffer to search
- // - val - a string, Buffer, or number
- // - byteOffset - an index into `buffer`; will be clamped to an int32
- // - encoding - an optional encoding, relevant is val is a string
- // - dir - true for indexOf, false for lastIndexOf
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
- // Empty buffer means no match
- if (buffer.length === 0) return -1
- // Normalize byteOffset
- if (typeof byteOffset === 'string') {
- encoding = byteOffset
- byteOffset = 0
- } else if (byteOffset > 0x7fffffff) {
- byteOffset = 0x7fffffff
- } else if (byteOffset < -0x80000000) {
- byteOffset = -0x80000000
- }
- byteOffset = +byteOffset // Coerce to Number.
- if (isNaN(byteOffset)) {
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
- byteOffset = dir ? 0 : (buffer.length - 1)
- }
- // Normalize byteOffset: negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset
- if (byteOffset >= buffer.length) {
- if (dir) return -1
- else byteOffset = buffer.length - 1
- } else if (byteOffset < 0) {
- if (dir) byteOffset = 0
- else return -1
- }
- // Normalize val
- if (typeof val === 'string') {
- val = Buffer.from(val, encoding)
- }
- // Finally, search either indexOf (if dir is true) or lastIndexOf
- if (Buffer.isBuffer(val)) {
- // Special case: looking for empty string/buffer always fails
- if (val.length === 0) {
- return -1
- }
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
- } else if (typeof val === 'number') {
- val = val & 0xFF // Search for a byte value [0-255]
- if (Buffer.TYPED_ARRAY_SUPPORT &&
- typeof Uint8Array.prototype.indexOf === 'function') {
- if (dir) {
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
- } else {
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
- }
- }
- return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
- }
- throw new TypeError('val must be string, number or Buffer')
- }
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
- var indexSize = 1
- var arrLength = arr.length
- var valLength = val.length
- if (encoding !== undefined) {
- encoding = String(encoding).toLowerCase()
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
- encoding === 'utf16le' || encoding === 'utf-16le') {
- if (arr.length < 2 || val.length < 2) {
- return -1
- }
- indexSize = 2
- arrLength /= 2
- valLength /= 2
- byteOffset /= 2
- }
- }
- function read (buf, i) {
- if (indexSize === 1) {
- return buf[i]
- } else {
- return buf.readUInt16BE(i * indexSize)
- }
- }
- var i
- if (dir) {
- var foundIndex = -1
- for (i = byteOffset; i < arrLength; i++) {
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
- if (foundIndex === -1) foundIndex = i
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
- } else {
- if (foundIndex !== -1) i -= i - foundIndex
- foundIndex = -1
- }
- }
- } else {
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
- for (i = byteOffset; i >= 0; i--) {
- var found = true
- for (var j = 0; j < valLength; j++) {
- if (read(arr, i + j) !== read(val, j)) {
- found = false
- break
- }
- }
- if (found) return i
- }
- }
- return -1
- }
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
- return this.indexOf(val, byteOffset, encoding) !== -1
- }
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
- }
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
- }
- function hexWrite (buf, string, offset, length) {
- offset = Number(offset) || 0
- var remaining = buf.length - offset
- if (!length) {
- length = remaining
- } else {
- length = Number(length)
- if (length > remaining) {
- length = remaining
- }
- }
- // must be an even number of digits
- var strLen = string.length
- if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
- if (length > strLen / 2) {
- length = strLen / 2
- }
- for (var i = 0; i < length; ++i) {
- var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (isNaN(parsed)) return i
- buf[offset + i] = parsed
- }
- return i
- }
- function utf8Write (buf, string, offset, length) {
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
- }
- function asciiWrite (buf, string, offset, length) {
- return blitBuffer(asciiToBytes(string), buf, offset, length)
- }
- function latin1Write (buf, string, offset, length) {
- return asciiWrite(buf, string, offset, length)
- }
- function base64Write (buf, string, offset, length) {
- return blitBuffer(base64ToBytes(string), buf, offset, length)
- }
- function ucs2Write (buf, string, offset, length) {
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
- }
- Buffer.prototype.write = function write (string, offset, length, encoding) {
- // Buffer#write(string)
- if (offset === undefined) {
- encoding = 'utf8'
- length = this.length
- offset = 0
- // Buffer#write(string, encoding)
- } else if (length === undefined && typeof offset === 'string') {
- encoding = offset
- length = this.length
- offset = 0
- // Buffer#write(string, offset[, length][, encoding])
- } else if (isFinite(offset)) {
- offset = offset | 0
- if (isFinite(length)) {
- length = length | 0
- if (encoding === undefined) encoding = 'utf8'
- } else {
- encoding = length
- length = undefined
- }
- // legacy write(string, encoding, offset, length) - remove in v0.13
- } else {
- throw new Error(
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
- )
- }
- var remaining = this.length - offset
- if (length === undefined || length > remaining) length = remaining
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('Attempt to write outside buffer bounds')
- }
- if (!encoding) encoding = 'utf8'
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'hex':
- return hexWrite(this, string, offset, length)
- case 'utf8':
- case 'utf-8':
- return utf8Write(this, string, offset, length)
- case 'ascii':
- return asciiWrite(this, string, offset, length)
- case 'latin1':
- case 'binary':
- return latin1Write(this, string, offset, length)
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- return base64Write(this, string, offset, length)
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return ucs2Write(this, string, offset, length)
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.prototype.toJSON = function toJSON () {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this._arr || this, 0)
- }
- }
- function base64Slice (buf, start, end) {
- if (start === 0 && end === buf.length) {
- return base64.fromByteArray(buf)
- } else {
- return base64.fromByteArray(buf.slice(start, end))
- }
- }
- function utf8Slice (buf, start, end) {
- end = Math.min(buf.length, end)
- var res = []
- var i = start
- while (i < end) {
- var firstByte = buf[i]
- var codePoint = null
- var bytesPerSequence = (firstByte > 0xEF) ? 4
- : (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1
- if (i + bytesPerSequence <= end) {
- var secondByte, thirdByte, fourthByte, tempCodePoint
- switch (bytesPerSequence) {
- case 1:
- if (firstByte < 0x80) {
- codePoint = firstByte
- }
- break
- case 2:
- secondByte = buf[i + 1]
- if ((secondByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
- if (tempCodePoint > 0x7F) {
- codePoint = tempCodePoint
- }
- }
- break
- case 3:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
- codePoint = tempCodePoint
- }
- }
- break
- case 4:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- fourthByte = buf[i + 3]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
- codePoint = tempCodePoint
- }
- }
- }
- }
- if (codePoint === null) {
- // we did not generate a valid codePoint so insert a
- // replacement char (U+FFFD) and advance only 1 byte
- codePoint = 0xFFFD
- bytesPerSequence = 1
- } else if (codePoint > 0xFFFF) {
- // encode to utf16 (surrogate pair dance)
- codePoint -= 0x10000
- res.push(codePoint >>> 10 & 0x3FF | 0xD800)
- codePoint = 0xDC00 | codePoint & 0x3FF
- }
- res.push(codePoint)
- i += bytesPerSequence
- }
- return decodeCodePointsArray(res)
- }
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
- // the lowest limit is Chrome, with 0x10000 args.
- // We go 1 magnitude less, for safety
- var MAX_ARGUMENTS_LENGTH = 0x1000
- function decodeCodePointsArray (codePoints) {
- var len = codePoints.length
- if (len <= MAX_ARGUMENTS_LENGTH) {
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
- }
- // Decode in chunks to avoid "call stack size exceeded".
- var res = ''
- var i = 0
- while (i < len) {
- res += String.fromCharCode.apply(
- String,
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
- )
- }
- return res
- }
- function asciiSlice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i] & 0x7F)
- }
- return ret
- }
- function latin1Slice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i])
- }
- return ret
- }
- function hexSlice (buf, start, end) {
- var len = buf.length
- if (!start || start < 0) start = 0
- if (!end || end < 0 || end > len) end = len
- var out = ''
- for (var i = start; i < end; ++i) {
- out += toHex(buf[i])
- }
- return out
- }
- function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end)
- var res = ''
- for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
- }
- return res
- }
- Buffer.prototype.slice = function slice (start, end) {
- var len = this.length
- start = ~~start
- end = end === undefined ? len : ~~end
- if (start < 0) {
- start += len
- if (start < 0) start = 0
- } else if (start > len) {
- start = len
- }
- if (end < 0) {
- end += len
- if (end < 0) end = 0
- } else if (end > len) {
- end = len
- }
- if (end < start) end = start
- var newBuf
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- newBuf = this.subarray(start, end)
- newBuf.__proto__ = Buffer.prototype
- } else {
- var sliceLen = end - start
- newBuf = new Buffer(sliceLen, undefined)
- for (var i = 0; i < sliceLen; ++i) {
- newBuf[i] = this[i + start]
- }
- }
- return newBuf
- }
- /*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
- function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
- }
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- return val
- }
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) {
- checkOffset(offset, byteLength, this.length)
- }
- var val = this[offset + --byteLength]
- var mul = 1
- while (byteLength > 0 && (mul *= 0x100)) {
- val += this[offset + --byteLength] * mul
- }
- return val
- }
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length)
- return this[offset]
- }
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- return this[offset] | (this[offset + 1] << 8)
- }
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- return (this[offset] << 8) | this[offset + 1]
- }
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ((this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16)) +
- (this[offset + 3] * 0x1000000)
- }
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
- }
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- mul *= 0x80
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- return val
- }
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
- var i = byteLength
- var mul = 1
- var val = this[offset + --i]
- while (i > 0 && (mul *= 0x100)) {
- val += this[offset + --i] * mul
- }
- mul *= 0x80
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- return val
- }
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length)
- if (!(this[offset] & 0x80)) return (this[offset])
- return ((0xff - this[offset] + 1) * -1)
- }
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset] | (this[offset + 1] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset + 1] | (this[offset] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
- }
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
- }
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, true, 23, 4)
- }
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, false, 23, 4)
- }
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, true, 52, 8)
- }
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, false, 52, 8)
- }
- function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- }
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
- var mul = 1
- var i = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
- var i = byteLength - 1
- var mul = 1
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
- this[offset] = (value & 0xff)
- return offset + 1
- }
- function objectWriteUInt16 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
- buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
- (littleEndian ? i : 1 - i) * 8
- }
- }
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
- return offset + 2
- }
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
- return offset + 2
- }
- function objectWriteUInt32 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffffffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
- buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
- }
- }
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset + 3] = (value >>> 24)
- this[offset + 2] = (value >>> 16)
- this[offset + 1] = (value >>> 8)
- this[offset] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
- return offset + 4
- }
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
- return offset + 4
- }
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
- var i = 0
- var mul = 1
- var sub = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
- var i = byteLength - 1
- var mul = 1
- var sub = 0
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
- return offset + byteLength
- }
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
- if (value < 0) value = 0xff + value + 1
- this[offset] = (value & 0xff)
- return offset + 1
- }
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
- return offset + 2
- }
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
- return offset + 2
- }
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- this[offset + 2] = (value >>> 16)
- this[offset + 3] = (value >>> 24)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
- return offset + 4
- }
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (value < 0) value = 0xffffffff + value + 1
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
- return offset + 4
- }
- function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- if (offset < 0) throw new RangeError('Index out of range')
- }
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
- }
- ieee754.write(buf, value, offset, littleEndian, 23, 4)
- return offset + 4
- }
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
- return writeFloat(this, value, offset, true, noAssert)
- }
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
- return writeFloat(this, value, offset, false, noAssert)
- }
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
- }
- ieee754.write(buf, value, offset, littleEndian, 52, 8)
- return offset + 8
- }
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
- return writeDouble(this, value, offset, true, noAssert)
- }
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
- return writeDouble(this, value, offset, false, noAssert)
- }
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
- if (!start) start = 0
- if (!end && end !== 0) end = this.length
- if (targetStart >= target.length) targetStart = target.length
- if (!targetStart) targetStart = 0
- if (end > 0 && end < start) end = start
- // Copy 0 bytes; we're done
- if (end === start) return 0
- if (target.length === 0 || this.length === 0) return 0
- // Fatal error conditions
- if (targetStart < 0) {
- throw new RangeError('targetStart out of bounds')
- }
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
- // Are we oob?
- if (end > this.length) end = this.length
- if (target.length - targetStart < end - start) {
- end = target.length - targetStart + start
- }
- var len = end - start
- var i
- if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (i = len - 1; i >= 0; --i) {
- target[i + targetStart] = this[i + start]
- }
- } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
- // ascending copy from start
- for (i = 0; i < len; ++i) {
- target[i + targetStart] = this[i + start]
- }
- } else {
- Uint8Array.prototype.set.call(
- target,
- this.subarray(start, start + len),
- targetStart
- )
- }
- return len
- }
- // Usage:
- // buffer.fill(number[, offset[, end]])
- // buffer.fill(buffer[, offset[, end]])
- // buffer.fill(string[, offset[, end]][, encoding])
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
- // Handle string cases:
- if (typeof val === 'string') {
- if (typeof start === 'string') {
- encoding = start
- start = 0
- end = this.length
- } else if (typeof end === 'string') {
- encoding = end
- end = this.length
- }
- if (val.length === 1) {
- var code = val.charCodeAt(0)
- if (code < 256) {
- val = code
- }
- }
- if (encoding !== undefined && typeof encoding !== 'string') {
- throw new TypeError('encoding must be a string')
- }
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
- } else if (typeof val === 'number') {
- val = val & 255
- }
- // Invalid ranges are not set to a default, so can range check early.
- if (start < 0 || this.length < start || this.length < end) {
- throw new RangeError('Out of range index')
- }
- if (end <= start) {
- return this
- }
- start = start >>> 0
- end = end === undefined ? this.length : end >>> 0
- if (!val) val = 0
- var i
- if (typeof val === 'number') {
- for (i = start; i < end; ++i) {
- this[i] = val
- }
- } else {
- var bytes = Buffer.isBuffer(val)
- ? val
- : utf8ToBytes(new Buffer(val, encoding).toString())
- var len = bytes.length
- for (i = 0; i < end - start; ++i) {
- this[i + start] = bytes[i % len]
- }
- }
- return this
- }
- // HELPER FUNCTIONS
- // ================
- var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
- function base64clean (str) {
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = stringtrim(str).replace(INVALID_BASE64_RE, '')
- // Node converts strings with length < 2 to ''
- if (str.length < 2) return ''
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
- while (str.length % 4 !== 0) {
- str = str + '='
- }
- return str
- }
- function stringtrim (str) {
- if (str.trim) return str.trim()
- return str.replace(/^\s+|\s+$/g, '')
- }
- function toHex (n) {
- if (n < 16) return '0' + n.toString(16)
- return n.toString(16)
- }
- function utf8ToBytes (string, units) {
- units = units || Infinity
- var codePoint
- var length = string.length
- var leadSurrogate = null
- var bytes = []
- for (var i = 0; i < length; ++i) {
- codePoint = string.charCodeAt(i)
- // is surrogate component
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
- // last char was a lead
- if (!leadSurrogate) {
- // no lead yet
- if (codePoint > 0xDBFF) {
- // unexpected trail
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- } else if (i + 1 === length) {
- // unpaired lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- }
- // valid lead
- leadSurrogate = codePoint
- continue
- }
- // 2 leads in a row
- if (codePoint < 0xDC00) {
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- leadSurrogate = codePoint
- continue
- }
- // valid surrogate pair
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
- } else if (leadSurrogate) {
- // valid bmp char, but last char was a lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- }
- leadSurrogate = null
- // encode utf8
- if (codePoint < 0x80) {
- if ((units -= 1) < 0) break
- bytes.push(codePoint)
- } else if (codePoint < 0x800) {
- if ((units -= 2) < 0) break
- bytes.push(
- codePoint >> 0x6 | 0xC0,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x10000) {
- if ((units -= 3) < 0) break
- bytes.push(
- codePoint >> 0xC | 0xE0,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x110000) {
- if ((units -= 4) < 0) break
- bytes.push(
- codePoint >> 0x12 | 0xF0,
- codePoint >> 0xC & 0x3F | 0x80,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else {
- throw new Error('Invalid code point')
- }
- }
- return bytes
- }
- function asciiToBytes (str) {
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push(str.charCodeAt(i) & 0xFF)
- }
- return byteArray
- }
- function utf16leToBytes (str, units) {
- var c, hi, lo
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- if ((units -= 2) < 0) break
- c = str.charCodeAt(i)
- hi = c >> 8
- lo = c % 256
- byteArray.push(lo)
- byteArray.push(hi)
- }
- return byteArray
- }
- function base64ToBytes (str) {
- return base64.toByteArray(base64clean(str))
- }
- function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; ++i) {
- if ((i + offset >= dst.length) || (i >= src.length)) break
- dst[i + offset] = src[i]
- }
- return i
- }
- function isnan (val) {
- return val !== val // eslint-disable-line no-self-compare
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"base64-js":39,"ieee754":80,"isarray":83}],78:[function(require,module,exports){
- (function (Buffer){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // NOTE: These type checking functions intentionally don't use `instanceof`
- // because it is fragile and can be easily faked with `Object.create()`.
- function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
- }
- return objectToString(arg) === '[object Array]';
- }
- exports.isArray = isArray;
- function isBoolean(arg) {
- return typeof arg === 'boolean';
- }
- exports.isBoolean = isBoolean;
- function isNull(arg) {
- return arg === null;
- }
- exports.isNull = isNull;
- function isNullOrUndefined(arg) {
- return arg == null;
- }
- exports.isNullOrUndefined = isNullOrUndefined;
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- exports.isNumber = isNumber;
- function isString(arg) {
- return typeof arg === 'string';
- }
- exports.isString = isString;
- function isSymbol(arg) {
- return typeof arg === 'symbol';
- }
- exports.isSymbol = isSymbol;
- function isUndefined(arg) {
- return arg === void 0;
- }
- exports.isUndefined = isUndefined;
- function isRegExp(re) {
- return objectToString(re) === '[object RegExp]';
- }
- exports.isRegExp = isRegExp;
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- exports.isObject = isObject;
- function isDate(d) {
- return objectToString(d) === '[object Date]';
- }
- exports.isDate = isDate;
- function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
- }
- exports.isError = isError;
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- exports.isFunction = isFunction;
- function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
- }
- exports.isPrimitive = isPrimitive;
- exports.isBuffer = Buffer.isBuffer;
- function objectToString(o) {
- return Object.prototype.toString.call(o);
- }
- }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
- },{"../../is-buffer/index.js":82}],79:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- function EventEmitter() {
- this._events = this._events || {};
- this._maxListeners = this._maxListeners || undefined;
- }
- module.exports = EventEmitter;
- // Backwards-compat with node 0.10.x
- EventEmitter.EventEmitter = EventEmitter;
- EventEmitter.prototype._events = undefined;
- EventEmitter.prototype._maxListeners = undefined;
- // By default EventEmitters will print a warning if more than 10 listeners are
- // added to it. This is a useful default which helps finding memory leaks.
- EventEmitter.defaultMaxListeners = 10;
- // Obviously not all Emitters should be limited to 10. This function allows
- // that to be increased. Set to zero for unlimited.
- EventEmitter.prototype.setMaxListeners = function(n) {
- if (!isNumber(n) || n < 0 || isNaN(n))
- throw TypeError('n must be a positive number');
- this._maxListeners = n;
- return this;
- };
- EventEmitter.prototype.emit = function(type) {
- var er, handler, len, args, i, listeners;
- if (!this._events)
- this._events = {};
- // If there is no 'error' event listener then throw.
- if (type === 'error') {
- if (!this._events.error ||
- (isObject(this._events.error) && !this._events.error.length)) {
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
- err.context = er;
- throw err;
- }
- }
- }
- handler = this._events[type];
- if (isUndefined(handler))
- return false;
- if (isFunction(handler)) {
- switch (arguments.length) {
- // fast cases
- case 1:
- handler.call(this);
- break;
- case 2:
- handler.call(this, arguments[1]);
- break;
- case 3:
- handler.call(this, arguments[1], arguments[2]);
- break;
- // slower
- default:
- args = Array.prototype.slice.call(arguments, 1);
- handler.apply(this, args);
- }
- } else if (isObject(handler)) {
- args = Array.prototype.slice.call(arguments, 1);
- listeners = handler.slice();
- len = listeners.length;
- for (i = 0; i < len; i++)
- listeners[i].apply(this, args);
- }
- return true;
- };
- EventEmitter.prototype.addListener = function(type, listener) {
- var m;
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- if (!this._events)
- this._events = {};
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (this._events.newListener)
- this.emit('newListener', type,
- isFunction(listener.listener) ?
- listener.listener : listener);
- if (!this._events[type])
- // Optimize the case of one listener. Don't need the extra array object.
- this._events[type] = listener;
- else if (isObject(this._events[type]))
- // If we've already got an array, just append.
- this._events[type].push(listener);
- else
- // Adding the second element, need to change to array.
- this._events[type] = [this._events[type], listener];
- // Check for listener leak
- if (isObject(this._events[type]) && !this._events[type].warned) {
- if (!isUndefined(this._maxListeners)) {
- m = this._maxListeners;
- } else {
- m = EventEmitter.defaultMaxListeners;
- }
- if (m && m > 0 && this._events[type].length > m) {
- this._events[type].warned = true;
- console.error('(node) warning: possible EventEmitter memory ' +
- 'leak detected. %d listeners added. ' +
- 'Use emitter.setMaxListeners() to increase limit.',
- this._events[type].length);
- if (typeof console.trace === 'function') {
- // not supported in IE 10
- console.trace();
- }
- }
- }
- return this;
- };
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
- EventEmitter.prototype.once = function(type, listener) {
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- var fired = false;
- function g() {
- this.removeListener(type, g);
- if (!fired) {
- fired = true;
- listener.apply(this, arguments);
- }
- }
- g.listener = listener;
- this.on(type, g);
- return this;
- };
- // emits a 'removeListener' event iff the listener was removed
- EventEmitter.prototype.removeListener = function(type, listener) {
- var list, position, length, i;
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- if (!this._events || !this._events[type])
- return this;
- list = this._events[type];
- length = list.length;
- position = -1;
- if (list === listener ||
- (isFunction(list.listener) && list.listener === listener)) {
- delete this._events[type];
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
- } else if (isObject(list)) {
- for (i = length; i-- > 0;) {
- if (list[i] === listener ||
- (list[i].listener && list[i].listener === listener)) {
- position = i;
- break;
- }
- }
- if (position < 0)
- return this;
- if (list.length === 1) {
- list.length = 0;
- delete this._events[type];
- } else {
- list.splice(position, 1);
- }
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
- }
- return this;
- };
- EventEmitter.prototype.removeAllListeners = function(type) {
- var key, listeners;
- if (!this._events)
- return this;
- // not listening for removeListener, no need to emit
- if (!this._events.removeListener) {
- if (arguments.length === 0)
- this._events = {};
- else if (this._events[type])
- delete this._events[type];
- return this;
- }
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- for (key in this._events) {
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = {};
- return this;
- }
- listeners = this._events[type];
- if (isFunction(listeners)) {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- while (listeners.length)
- this.removeListener(type, listeners[listeners.length - 1]);
- }
- delete this._events[type];
- return this;
- };
- EventEmitter.prototype.listeners = function(type) {
- var ret;
- if (!this._events || !this._events[type])
- ret = [];
- else if (isFunction(this._events[type]))
- ret = [this._events[type]];
- else
- ret = this._events[type].slice();
- return ret;
- };
- EventEmitter.prototype.listenerCount = function(type) {
- if (this._events) {
- var evlistener = this._events[type];
- if (isFunction(evlistener))
- return 1;
- else if (evlistener)
- return evlistener.length;
- }
- return 0;
- };
- EventEmitter.listenerCount = function(emitter, type) {
- return emitter.listenerCount(type);
- };
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- function isUndefined(arg) {
- return arg === void 0;
- }
- },{}],80:[function(require,module,exports){
- exports.read = function (buffer, offset, isLE, mLen, nBytes) {
- var e, m
- var eLen = nBytes * 8 - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var nBits = -7
- var i = isLE ? (nBytes - 1) : 0
- var d = isLE ? -1 : 1
- var s = buffer[offset + i]
- i += d
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- m = e & ((1 << (-nBits)) - 1)
- e >>= (-nBits)
- nBits += mLen
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- if (e === 0) {
- e = 1 - eBias
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen)
- e = e - eBias
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
- }
- exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c
- var eLen = nBytes * 8 - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
- var i = isLE ? 0 : (nBytes - 1)
- var d = isLE ? 1 : -1
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
- value = Math.abs(value)
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0
- e = eMax
- } else {
- e = Math.floor(Math.log(value) / Math.LN2)
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--
- c *= 2
- }
- if (e + eBias >= 1) {
- value += rt / c
- } else {
- value += rt * Math.pow(2, 1 - eBias)
- }
- if (value * c >= 2) {
- e++
- c /= 2
- }
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen)
- e = e + eBias
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
- }
- }
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- e = (e << mLen) | m
- eLen += mLen
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- buffer[offset + i - d] |= s * 128
- }
- },{}],81:[function(require,module,exports){
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
- },{}],82:[function(require,module,exports){
- /*!
- * Determine if an object is a Buffer
- *
- * @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
- * @license MIT
- */
- // The _isBuffer check is for Safari 5-7 support, because it's missing
- // Object.prototype.constructor. Remove this eventually
- module.exports = function (obj) {
- return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
- }
- function isBuffer (obj) {
- return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
- }
- // For Node v0.10 support. Remove this eventually.
- function isSlowBuffer (obj) {
- return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
- }
- },{}],83:[function(require,module,exports){
- var toString = {}.toString;
- module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
- };
- },{}],84:[function(require,module,exports){
- 'use strict';
- // private property
- var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- // public method for encoding
- exports.encode = function(input, utf8) {
- var output = "";
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
- while (i < input.length) {
- chr1 = input.charCodeAt(i++);
- chr2 = input.charCodeAt(i++);
- chr3 = input.charCodeAt(i++);
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- }
- else if (isNaN(chr3)) {
- enc4 = 64;
- }
- output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
- }
- return output;
- };
- // public method for decoding
- exports.decode = function(input, utf8) {
- var output = "";
- var chr1, chr2, chr3;
- var enc1, enc2, enc3, enc4;
- var i = 0;
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- while (i < input.length) {
- enc1 = _keyStr.indexOf(input.charAt(i++));
- enc2 = _keyStr.indexOf(input.charAt(i++));
- enc3 = _keyStr.indexOf(input.charAt(i++));
- enc4 = _keyStr.indexOf(input.charAt(i++));
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
- output = output + String.fromCharCode(chr1);
- if (enc3 != 64) {
- output = output + String.fromCharCode(chr2);
- }
- if (enc4 != 64) {
- output = output + String.fromCharCode(chr3);
- }
- }
- return output;
- };
- },{}],85:[function(require,module,exports){
- 'use strict';
- function CompressedObject() {
- this.compressedSize = 0;
- this.uncompressedSize = 0;
- this.crc32 = 0;
- this.compressionMethod = null;
- this.compressedContent = null;
- }
- CompressedObject.prototype = {
- /**
- * Return the decompressed content in an unspecified format.
- * The format will depend on the decompressor.
- * @return {Object} the decompressed content.
- */
- getContent: function() {
- return null; // see implementation
- },
- /**
- * Return the compressed content in an unspecified format.
- * The format will depend on the compressed conten source.
- * @return {Object} the compressed content.
- */
- getCompressedContent: function() {
- return null; // see implementation
- }
- };
- module.exports = CompressedObject;
- },{}],86:[function(require,module,exports){
- 'use strict';
- exports.STORE = {
- magic: "\x00\x00",
- compress: function(content, compressionOptions) {
- return content; // no compression
- },
- uncompress: function(content) {
- return content; // no compression
- },
- compressInputType: null,
- uncompressInputType: null
- };
- exports.DEFLATE = require('./flate');
- },{"./flate":91}],87:[function(require,module,exports){
- 'use strict';
- var utils = require('./utils');
- var table = [
- 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
- 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
- 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
- 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
- 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
- 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
- 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
- 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
- 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
- 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
- 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
- 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
- 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
- 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
- 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
- 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
- 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
- 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
- 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
- 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
- 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
- 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
- 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
- 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
- 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
- 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
- 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
- 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
- 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
- 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
- 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
- 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
- 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
- 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
- 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
- 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
- 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
- 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
- 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
- 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
- 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
- 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
- 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
- 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
- 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
- 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
- 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
- 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
- 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
- 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
- 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
- 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
- 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
- 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
- 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
- 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
- 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
- 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
- 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
- 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
- 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
- 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
- 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
- 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
- ];
- /**
- *
- * Javascript crc32
- * http://www.webtoolkit.info/
- *
- */
- module.exports = function crc32(input, crc) {
- if (typeof input === "undefined" || !input.length) {
- return 0;
- }
- var isArray = utils.getTypeOf(input) !== "string";
- if (typeof(crc) == "undefined") {
- crc = 0;
- }
- var x = 0;
- var y = 0;
- var b = 0;
- crc = crc ^ (-1);
- for (var i = 0, iTop = input.length; i < iTop; i++) {
- b = isArray ? input[i] : input.charCodeAt(i);
- y = (crc ^ b) & 0xFF;
- x = table[y];
- crc = (crc >>> 8) ^ x;
- }
- return crc ^ (-1);
- };
- // vim: set shiftwidth=4 softtabstop=4:
- },{"./utils":104}],88:[function(require,module,exports){
- 'use strict';
- var utils = require('./utils');
- function DataReader(data) {
- this.data = null; // type : see implementation
- this.length = 0;
- this.index = 0;
- }
- DataReader.prototype = {
- /**
- * Check that the offset will not go too far.
- * @param {string} offset the additional offset to check.
- * @throws {Error} an Error if the offset is out of bounds.
- */
- checkOffset: function(offset) {
- this.checkIndex(this.index + offset);
- },
- /**
- * Check that the specifed index will not be too far.
- * @param {string} newIndex the index to check.
- * @throws {Error} an Error if the index is out of bounds.
- */
- checkIndex: function(newIndex) {
- if (this.length < newIndex || newIndex < 0) {
- throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
- }
- },
- /**
- * Change the index.
- * @param {number} newIndex The new index.
- * @throws {Error} if the new index is out of the data.
- */
- setIndex: function(newIndex) {
- this.checkIndex(newIndex);
- this.index = newIndex;
- },
- /**
- * Skip the next n bytes.
- * @param {number} n the number of bytes to skip.
- * @throws {Error} if the new index is out of the data.
- */
- skip: function(n) {
- this.setIndex(this.index + n);
- },
- /**
- * Get the byte at the specified index.
- * @param {number} i the index to use.
- * @return {number} a byte.
- */
- byteAt: function(i) {
- // see implementations
- },
- /**
- * Get the next number with a given byte size.
- * @param {number} size the number of bytes to read.
- * @return {number} the corresponding number.
- */
- readInt: function(size) {
- var result = 0,
- i;
- this.checkOffset(size);
- for (i = this.index + size - 1; i >= this.index; i--) {
- result = (result << 8) + this.byteAt(i);
- }
- this.index += size;
- return result;
- },
- /**
- * Get the next string with a given byte size.
- * @param {number} size the number of bytes to read.
- * @return {string} the corresponding string.
- */
- readString: function(size) {
- return utils.transformTo("string", this.readData(size));
- },
- /**
- * Get raw data without conversion, <size> bytes.
- * @param {number} size the number of bytes to read.
- * @return {Object} the raw data, implementation specific.
- */
- readData: function(size) {
- // see implementations
- },
- /**
- * Find the last occurence of a zip signature (4 bytes).
- * @param {string} sig the signature to find.
- * @return {number} the index of the last occurence, -1 if not found.
- */
- lastIndexOfSignature: function(sig) {
- // see implementations
- },
- /**
- * Get the next date.
- * @return {Date} the date.
- */
- readDate: function() {
- var dostime = this.readInt(4);
- return new Date(
- ((dostime >> 25) & 0x7f) + 1980, // year
- ((dostime >> 21) & 0x0f) - 1, // month
- (dostime >> 16) & 0x1f, // day
- (dostime >> 11) & 0x1f, // hour
- (dostime >> 5) & 0x3f, // minute
- (dostime & 0x1f) << 1); // second
- }
- };
- module.exports = DataReader;
- },{"./utils":104}],89:[function(require,module,exports){
- 'use strict';
- exports.base64 = false;
- exports.binary = false;
- exports.dir = false;
- exports.createFolders = false;
- exports.date = null;
- exports.compression = null;
- exports.compressionOptions = null;
- exports.comment = null;
- exports.unixPermissions = null;
- exports.dosPermissions = null;
- },{}],90:[function(require,module,exports){
- 'use strict';
- var utils = require('./utils');
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.string2binary = function(str) {
- return utils.string2binary(str);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.string2Uint8Array = function(str) {
- return utils.transformTo("uint8array", str);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.uint8Array2String = function(array) {
- return utils.transformTo("string", array);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.string2Blob = function(str) {
- var buffer = utils.transformTo("arraybuffer", str);
- return utils.arrayBuffer2Blob(buffer);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.arrayBuffer2Blob = function(buffer) {
- return utils.arrayBuffer2Blob(buffer);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.transformTo = function(outputType, input) {
- return utils.transformTo(outputType, input);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.getTypeOf = function(input) {
- return utils.getTypeOf(input);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.checkSupport = function(type) {
- return utils.checkSupport(type);
- };
- /**
- * @deprecated
- * This value will be removed in a future version without replacement.
- */
- exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
- /**
- * @deprecated
- * This value will be removed in a future version without replacement.
- */
- exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.pretty = function(str) {
- return utils.pretty(str);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.findCompression = function(compressionMethod) {
- return utils.findCompression(compressionMethod);
- };
- /**
- * @deprecated
- * This function will be removed in a future version without replacement.
- */
- exports.isRegExp = function (object) {
- return utils.isRegExp(object);
- };
- },{"./utils":104}],91:[function(require,module,exports){
- 'use strict';
- var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
- var pako = require("pako");
- exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
- exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
- exports.magic = "\x08\x00";
- exports.compress = function(input, compressionOptions) {
- return pako.deflateRaw(input, {
- level : compressionOptions.level || -1 // default compression
- });
- };
- exports.uncompress = function(input) {
- return pako.inflateRaw(input);
- };
- },{"pako":120}],92:[function(require,module,exports){
- 'use strict';
- var base64 = require('./base64');
- /**
- Usage:
- zip = new JSZip();
- zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
- zip.folder("images").file("smile.gif", base64Data, {base64: true});
- zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
- zip.remove("tempfile");
- base64zip = zip.generate();
- **/
- /**
- * Representation a of zip file in js
- * @constructor
- * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
- * @param {Object=} options the options for creating this objects (optional).
- */
- function JSZip(data, options) {
- // if this constructor is used without `new`, it adds `new` before itself:
- if(!(this instanceof JSZip)) return new JSZip(data, options);
- // object containing the files :
- // {
- // "folder/" : {...},
- // "folder/data.txt" : {...}
- // }
- this.files = {};
- this.comment = null;
- // Where we are in the hierarchy
- this.root = "";
- if (data) {
- this.load(data, options);
- }
- this.clone = function() {
- var newObj = new JSZip();
- for (var i in this) {
- if (typeof this[i] !== "function") {
- newObj[i] = this[i];
- }
- }
- return newObj;
- };
- }
- JSZip.prototype = require('./object');
- JSZip.prototype.load = require('./load');
- JSZip.support = require('./support');
- JSZip.defaults = require('./defaults');
- /**
- * @deprecated
- * This namespace will be removed in a future version without replacement.
- */
- JSZip.utils = require('./deprecatedPublicUtils');
- JSZip.base64 = {
- /**
- * @deprecated
- * This method will be removed in a future version without replacement.
- */
- encode : function(input) {
- return base64.encode(input);
- },
- /**
- * @deprecated
- * This method will be removed in a future version without replacement.
- */
- decode : function(input) {
- return base64.decode(input);
- }
- };
- JSZip.compressions = require('./compressions');
- module.exports = JSZip;
- },{"./base64":84,"./compressions":86,"./defaults":89,"./deprecatedPublicUtils":90,"./load":93,"./object":96,"./support":100}],93:[function(require,module,exports){
- 'use strict';
- var base64 = require('./base64');
- var ZipEntries = require('./zipEntries');
- module.exports = function(data, options) {
- var files, zipEntries, i, input;
- options = options || {};
- if (options.base64) {
- data = base64.decode(data);
- }
- zipEntries = new ZipEntries(data, options);
- files = zipEntries.files;
- for (i = 0; i < files.length; i++) {
- input = files[i];
- this.file(input.fileName, input.decompressed, {
- binary: true,
- optimizedBinaryString: true,
- date: input.date,
- dir: input.dir,
- comment : input.fileComment.length ? input.fileComment : null,
- unixPermissions : input.unixPermissions,
- dosPermissions : input.dosPermissions,
- createFolders: options.createFolders
- });
- }
- if (zipEntries.zipComment.length) {
- this.comment = zipEntries.zipComment;
- }
- return this;
- };
- },{"./base64":84,"./zipEntries":105}],94:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- module.exports = function(data, encoding){
- return new Buffer(data, encoding);
- };
- module.exports.test = function(b){
- return Buffer.isBuffer(b);
- };
- }).call(this,require("buffer").Buffer)
- },{"buffer":77}],95:[function(require,module,exports){
- 'use strict';
- var Uint8ArrayReader = require('./uint8ArrayReader');
- function NodeBufferReader(data) {
- this.data = data;
- this.length = this.data.length;
- this.index = 0;
- }
- NodeBufferReader.prototype = new Uint8ArrayReader();
- /**
- * @see DataReader.readData
- */
- NodeBufferReader.prototype.readData = function(size) {
- this.checkOffset(size);
- var result = this.data.slice(this.index, this.index + size);
- this.index += size;
- return result;
- };
- module.exports = NodeBufferReader;
- },{"./uint8ArrayReader":101}],96:[function(require,module,exports){
- 'use strict';
- var support = require('./support');
- var utils = require('./utils');
- var crc32 = require('./crc32');
- var signature = require('./signature');
- var defaults = require('./defaults');
- var base64 = require('./base64');
- var compressions = require('./compressions');
- var CompressedObject = require('./compressedObject');
- var nodeBuffer = require('./nodeBuffer');
- var utf8 = require('./utf8');
- var StringWriter = require('./stringWriter');
- var Uint8ArrayWriter = require('./uint8ArrayWriter');
- /**
- * Returns the raw data of a ZipObject, decompress the content if necessary.
- * @param {ZipObject} file the file to use.
- * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
- */
- var getRawData = function(file) {
- if (file._data instanceof CompressedObject) {
- file._data = file._data.getContent();
- file.options.binary = true;
- file.options.base64 = false;
- if (utils.getTypeOf(file._data) === "uint8array") {
- var copy = file._data;
- // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
- // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
- file._data = new Uint8Array(copy.length);
- // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
- if (copy.length !== 0) {
- file._data.set(copy, 0);
- }
- }
- }
- return file._data;
- };
- /**
- * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
- * @param {ZipObject} file the file to use.
- * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
- */
- var getBinaryData = function(file) {
- var result = getRawData(file),
- type = utils.getTypeOf(result);
- if (type === "string") {
- if (!file.options.binary) {
- // unicode text !
- // unicode string => binary string is a painful process, check if we can avoid it.
- if (support.nodebuffer) {
- return nodeBuffer(result, "utf-8");
- }
- }
- return file.asBinary();
- }
- return result;
- };
- /**
- * Transform this._data into a string.
- * @param {function} filter a function String -> String, applied if not null on the result.
- * @return {String} the string representing this._data.
- */
- var dataToString = function(asUTF8) {
- var result = getRawData(this);
- if (result === null || typeof result === "undefined") {
- return "";
- }
- // if the data is a base64 string, we decode it before checking the encoding !
- if (this.options.base64) {
- result = base64.decode(result);
- }
- if (asUTF8 && this.options.binary) {
- // JSZip.prototype.utf8decode supports arrays as input
- // skip to array => string step, utf8decode will do it.
- result = out.utf8decode(result);
- }
- else {
- // no utf8 transformation, do the array => string step.
- result = utils.transformTo("string", result);
- }
- if (!asUTF8 && !this.options.binary) {
- result = utils.transformTo("string", out.utf8encode(result));
- }
- return result;
- };
- /**
- * A simple object representing a file in the zip file.
- * @constructor
- * @param {string} name the name of the file
- * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
- * @param {Object} options the options of the file
- */
- var ZipObject = function(name, data, options) {
- this.name = name;
- this.dir = options.dir;
- this.date = options.date;
- this.comment = options.comment;
- this.unixPermissions = options.unixPermissions;
- this.dosPermissions = options.dosPermissions;
- this._data = data;
- this.options = options;
- /*
- * This object contains initial values for dir and date.
- * With them, we can check if the user changed the deprecated metadata in
- * `ZipObject#options` or not.
- */
- this._initialMetadata = {
- dir : options.dir,
- date : options.date
- };
- };
- ZipObject.prototype = {
- /**
- * Return the content as UTF8 string.
- * @return {string} the UTF8 string.
- */
- asText: function() {
- return dataToString.call(this, true);
- },
- /**
- * Returns the binary content.
- * @return {string} the content as binary.
- */
- asBinary: function() {
- return dataToString.call(this, false);
- },
- /**
- * Returns the content as a nodejs Buffer.
- * @return {Buffer} the content as a Buffer.
- */
- asNodeBuffer: function() {
- var result = getBinaryData(this);
- return utils.transformTo("nodebuffer", result);
- },
- /**
- * Returns the content as an Uint8Array.
- * @return {Uint8Array} the content as an Uint8Array.
- */
- asUint8Array: function() {
- var result = getBinaryData(this);
- return utils.transformTo("uint8array", result);
- },
- /**
- * Returns the content as an ArrayBuffer.
- * @return {ArrayBuffer} the content as an ArrayBufer.
- */
- asArrayBuffer: function() {
- return this.asUint8Array().buffer;
- }
- };
- /**
- * Transform an integer into a string in hexadecimal.
- * @private
- * @param {number} dec the number to convert.
- * @param {number} bytes the number of bytes to generate.
- * @returns {string} the result.
- */
- var decToHex = function(dec, bytes) {
- var hex = "",
- i;
- for (i = 0; i < bytes; i++) {
- hex += String.fromCharCode(dec & 0xff);
- dec = dec >>> 8;
- }
- return hex;
- };
- /**
- * Merge the objects passed as parameters into a new one.
- * @private
- * @param {...Object} var_args All objects to merge.
- * @return {Object} a new object with the data of the others.
- */
- var extend = function() {
- var result = {}, i, attr;
- for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
- for (attr in arguments[i]) {
- if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
- result[attr] = arguments[i][attr];
- }
- }
- }
- return result;
- };
- /**
- * Transforms the (incomplete) options from the user into the complete
- * set of options to create a file.
- * @private
- * @param {Object} o the options from the user.
- * @return {Object} the complete set of options.
- */
- var prepareFileAttrs = function(o) {
- o = o || {};
- if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
- o.binary = true;
- }
- o = extend(o, defaults);
- o.date = o.date || new Date();
- if (o.compression !== null) o.compression = o.compression.toUpperCase();
- return o;
- };
- /**
- * Add a file in the current folder.
- * @private
- * @param {string} name the name of the file
- * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
- * @param {Object} o the options of the file
- * @return {Object} the new file.
- */
- var fileAdd = function(name, data, o) {
- // be sure sub folders exist
- var dataType = utils.getTypeOf(data),
- parent;
- o = prepareFileAttrs(o);
- if (typeof o.unixPermissions === "string") {
- o.unixPermissions = parseInt(o.unixPermissions, 8);
- }
- // UNX_IFDIR 0040000 see zipinfo.c
- if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
- o.dir = true;
- }
- // Bit 4 Directory
- if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
- o.dir = true;
- }
- if (o.dir) {
- name = forceTrailingSlash(name);
- }
- if (o.createFolders && (parent = parentFolder(name))) {
- folderAdd.call(this, parent, true);
- }
- if (o.dir || data === null || typeof data === "undefined") {
- o.base64 = false;
- o.binary = false;
- data = null;
- dataType = null;
- }
- else if (dataType === "string") {
- if (o.binary && !o.base64) {
- // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
- if (o.optimizedBinaryString !== true) {
- // this is a string, not in a base64 format.
- // Be sure that this is a correct "binary string"
- data = utils.string2binary(data);
- }
- }
- }
- else { // arraybuffer, uint8array, ...
- o.base64 = false;
- o.binary = true;
- if (!dataType && !(data instanceof CompressedObject)) {
- throw new Error("The data of '" + name + "' is in an unsupported format !");
- }
- // special case : it's way easier to work with Uint8Array than with ArrayBuffer
- if (dataType === "arraybuffer") {
- data = utils.transformTo("uint8array", data);
- }
- }
- var object = new ZipObject(name, data, o);
- this.files[name] = object;
- return object;
- };
- /**
- * Find the parent folder of the path.
- * @private
- * @param {string} path the path to use
- * @return {string} the parent folder, or ""
- */
- var parentFolder = function (path) {
- if (path.slice(-1) == '/') {
- path = path.substring(0, path.length - 1);
- }
- var lastSlash = path.lastIndexOf('/');
- return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
- };
- /**
- * Returns the path with a slash at the end.
- * @private
- * @param {String} path the path to check.
- * @return {String} the path with a trailing slash.
- */
- var forceTrailingSlash = function(path) {
- // Check the name ends with a /
- if (path.slice(-1) != "/") {
- path += "/"; // IE doesn't like substr(-1)
- }
- return path;
- };
- /**
- * Add a (sub) folder in the current folder.
- * @private
- * @param {string} name the folder's name
- * @param {boolean=} [createFolders] If true, automatically create sub
- * folders. Defaults to false.
- * @return {Object} the new folder.
- */
- var folderAdd = function(name, createFolders) {
- createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
- name = forceTrailingSlash(name);
- // Does this folder already exist?
- if (!this.files[name]) {
- fileAdd.call(this, name, null, {
- dir: true,
- createFolders: createFolders
- });
- }
- return this.files[name];
- };
- /**
- * Generate a JSZip.CompressedObject for a given zipOject.
- * @param {ZipObject} file the object to read.
- * @param {JSZip.compression} compression the compression to use.
- * @param {Object} compressionOptions the options to use when compressing.
- * @return {JSZip.CompressedObject} the compressed result.
- */
- var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
- var result = new CompressedObject(),
- content;
- // the data has not been decompressed, we might reuse things !
- if (file._data instanceof CompressedObject) {
- result.uncompressedSize = file._data.uncompressedSize;
- result.crc32 = file._data.crc32;
- if (result.uncompressedSize === 0 || file.dir) {
- compression = compressions['STORE'];
- result.compressedContent = "";
- result.crc32 = 0;
- }
- else if (file._data.compressionMethod === compression.magic) {
- result.compressedContent = file._data.getCompressedContent();
- }
- else {
- content = file._data.getContent();
- // need to decompress / recompress
- result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
- }
- }
- else {
- // have uncompressed data
- content = getBinaryData(file);
- if (!content || content.length === 0 || file.dir) {
- compression = compressions['STORE'];
- content = "";
- }
- result.uncompressedSize = content.length;
- result.crc32 = crc32(content);
- result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
- }
- result.compressedSize = result.compressedContent.length;
- result.compressionMethod = compression.magic;
- return result;
- };
- /**
- * Generate the UNIX part of the external file attributes.
- * @param {Object} unixPermissions the unix permissions or null.
- * @param {Boolean} isDir true if the entry is a directory, false otherwise.
- * @return {Number} a 32 bit integer.
- *
- * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
- *
- * TTTTsstrwxrwxrwx0000000000ADVSHR
- * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
- * ^^^_________________________ setuid, setgid, sticky
- * ^^^^^^^^^________________ permissions
- * ^^^^^^^^^^______ not used ?
- * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
- */
- var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
- var result = unixPermissions;
- if (!unixPermissions) {
- // I can't use octal values in strict mode, hence the hexa.
- // 040775 => 0x41fd
- // 0100664 => 0x81b4
- result = isDir ? 0x41fd : 0x81b4;
- }
- return (result & 0xFFFF) << 16;
- };
- /**
- * Generate the DOS part of the external file attributes.
- * @param {Object} dosPermissions the dos permissions or null.
- * @param {Boolean} isDir true if the entry is a directory, false otherwise.
- * @return {Number} a 32 bit integer.
- *
- * Bit 0 Read-Only
- * Bit 1 Hidden
- * Bit 2 System
- * Bit 3 Volume Label
- * Bit 4 Directory
- * Bit 5 Archive
- */
- var generateDosExternalFileAttr = function (dosPermissions, isDir) {
- // the dir flag is already set for compatibility
- return (dosPermissions || 0) & 0x3F;
- };
- /**
- * Generate the various parts used in the construction of the final zip file.
- * @param {string} name the file name.
- * @param {ZipObject} file the file content.
- * @param {JSZip.CompressedObject} compressedObject the compressed object.
- * @param {number} offset the current offset from the start of the zip file.
- * @param {String} platform let's pretend we are this platform (change platform dependents fields)
- * @return {object} the zip parts.
- */
- var generateZipParts = function(name, file, compressedObject, offset, platform) {
- var data = compressedObject.compressedContent,
- utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
- comment = file.comment || "",
- utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
- useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
- useUTF8ForComment = utfEncodedComment.length !== comment.length,
- o = file.options,
- dosTime,
- dosDate,
- extraFields = "",
- unicodePathExtraField = "",
- unicodeCommentExtraField = "",
- dir, date;
- // handle the deprecated options.dir
- if (file._initialMetadata.dir !== file.dir) {
- dir = file.dir;
- } else {
- dir = o.dir;
- }
- // handle the deprecated options.date
- if(file._initialMetadata.date !== file.date) {
- date = file.date;
- } else {
- date = o.date;
- }
- var extFileAttr = 0;
- var versionMadeBy = 0;
- if (dir) {
- // dos or unix, we set the dos dir flag
- extFileAttr |= 0x00010;
- }
- if(platform === "UNIX") {
- versionMadeBy = 0x031E; // UNIX, version 3.0
- extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
- } else { // DOS or other, fallback to DOS
- versionMadeBy = 0x0014; // DOS, version 2.0
- extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
- }
- // date
- // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
- // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
- // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
- dosTime = date.getHours();
- dosTime = dosTime << 6;
- dosTime = dosTime | date.getMinutes();
- dosTime = dosTime << 5;
- dosTime = dosTime | date.getSeconds() / 2;
- dosDate = date.getFullYear() - 1980;
- dosDate = dosDate << 4;
- dosDate = dosDate | (date.getMonth() + 1);
- dosDate = dosDate << 5;
- dosDate = dosDate | date.getDate();
- if (useUTF8ForFileName) {
- // set the unicode path extra field. unzip needs at least one extra
- // field to correctly handle unicode path, so using the path is as good
- // as any other information. This could improve the situation with
- // other archive managers too.
- // This field is usually used without the utf8 flag, with a non
- // unicode path in the header (winrar, winzip). This helps (a bit)
- // with the messy Windows' default compressed folders feature but
- // breaks on p7zip which doesn't seek the unicode path extra field.
- // So for now, UTF-8 everywhere !
- unicodePathExtraField =
- // Version
- decToHex(1, 1) +
- // NameCRC32
- decToHex(crc32(utfEncodedFileName), 4) +
- // UnicodeName
- utfEncodedFileName;
- extraFields +=
- // Info-ZIP Unicode Path Extra Field
- "\x75\x70" +
- // size
- decToHex(unicodePathExtraField.length, 2) +
- // content
- unicodePathExtraField;
- }
- if(useUTF8ForComment) {
- unicodeCommentExtraField =
- // Version
- decToHex(1, 1) +
- // CommentCRC32
- decToHex(this.crc32(utfEncodedComment), 4) +
- // UnicodeName
- utfEncodedComment;
- extraFields +=
- // Info-ZIP Unicode Path Extra Field
- "\x75\x63" +
- // size
- decToHex(unicodeCommentExtraField.length, 2) +
- // content
- unicodeCommentExtraField;
- }
- var header = "";
- // version needed to extract
- header += "\x0A\x00";
- // general purpose bit flag
- // set bit 11 if utf8
- header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
- // compression method
- header += compressedObject.compressionMethod;
- // last mod file time
- header += decToHex(dosTime, 2);
- // last mod file date
- header += decToHex(dosDate, 2);
- // crc-32
- header += decToHex(compressedObject.crc32, 4);
- // compressed size
- header += decToHex(compressedObject.compressedSize, 4);
- // uncompressed size
- header += decToHex(compressedObject.uncompressedSize, 4);
- // file name length
- header += decToHex(utfEncodedFileName.length, 2);
- // extra field length
- header += decToHex(extraFields.length, 2);
- var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
- var dirRecord = signature.CENTRAL_FILE_HEADER +
- // version made by (00: DOS)
- decToHex(versionMadeBy, 2) +
- // file header (common to file and central directory)
- header +
- // file comment length
- decToHex(utfEncodedComment.length, 2) +
- // disk number start
- "\x00\x00" +
- // internal file attributes TODO
- "\x00\x00" +
- // external file attributes
- decToHex(extFileAttr, 4) +
- // relative offset of local header
- decToHex(offset, 4) +
- // file name
- utfEncodedFileName +
- // extra field
- extraFields +
- // file comment
- utfEncodedComment;
- return {
- fileRecord: fileRecord,
- dirRecord: dirRecord,
- compressedObject: compressedObject
- };
- };
- // return the actual prototype of JSZip
- var out = {
- /**
- * Read an existing zip and merge the data in the current JSZip object.
- * The implementation is in jszip-load.js, don't forget to include it.
- * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
- * @param {Object} options Options for loading the stream.
- * options.base64 : is the stream in base64 ? default : false
- * @return {JSZip} the current JSZip object
- */
- load: function(stream, options) {
- throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
- },
- /**
- * Filter nested files/folders with the specified function.
- * @param {Function} search the predicate to use :
- * function (relativePath, file) {...}
- * It takes 2 arguments : the relative path and the file.
- * @return {Array} An array of matching elements.
- */
- filter: function(search) {
- var result = [],
- filename, relativePath, file, fileClone;
- for (filename in this.files) {
- if (!this.files.hasOwnProperty(filename)) {
- continue;
- }
- file = this.files[filename];
- // return a new object, don't let the user mess with our internal objects :)
- fileClone = new ZipObject(file.name, file._data, extend(file.options));
- relativePath = filename.slice(this.root.length, filename.length);
- if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
- search(relativePath, fileClone)) { // and the file matches the function
- result.push(fileClone);
- }
- }
- return result;
- },
- /**
- * Add a file to the zip file, or search a file.
- * @param {string|RegExp} name The name of the file to add (if data is defined),
- * the name of the file to find (if no data) or a regex to match files.
- * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
- * @param {Object} o File options
- * @return {JSZip|Object|Array} this JSZip object (when adding a file),
- * a file (when searching by string) or an array of files (when searching by regex).
- */
- file: function(name, data, o) {
- if (arguments.length === 1) {
- if (utils.isRegExp(name)) {
- var regexp = name;
- return this.filter(function(relativePath, file) {
- return !file.dir && regexp.test(relativePath);
- });
- }
- else { // text
- return this.filter(function(relativePath, file) {
- return !file.dir && relativePath === name;
- })[0] || null;
- }
- }
- else { // more than one argument : we have data !
- name = this.root + name;
- fileAdd.call(this, name, data, o);
- }
- return this;
- },
- /**
- * Add a directory to the zip file, or search.
- * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
- * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
- */
- folder: function(arg) {
- if (!arg) {
- return this;
- }
- if (utils.isRegExp(arg)) {
- return this.filter(function(relativePath, file) {
- return file.dir && arg.test(relativePath);
- });
- }
- // else, name is a new folder
- var name = this.root + arg;
- var newFolder = folderAdd.call(this, name);
- // Allow chaining by returning a new object with this folder as the root
- var ret = this.clone();
- ret.root = newFolder.name;
- return ret;
- },
- /**
- * Delete a file, or a directory and all sub-files, from the zip
- * @param {string} name the name of the file to delete
- * @return {JSZip} this JSZip object
- */
- remove: function(name) {
- name = this.root + name;
- var file = this.files[name];
- if (!file) {
- // Look for any folders
- if (name.slice(-1) != "/") {
- name += "/";
- }
- file = this.files[name];
- }
- if (file && !file.dir) {
- // file
- delete this.files[name];
- } else {
- // maybe a folder, delete recursively
- var kids = this.filter(function(relativePath, file) {
- return file.name.slice(0, name.length) === name;
- });
- for (var i = 0; i < kids.length; i++) {
- delete this.files[kids[i].name];
- }
- }
- return this;
- },
- /**
- * Generate the complete zip file
- * @param {Object} options the options to generate the zip file :
- * - base64, (deprecated, use type instead) true to generate base64.
- * - compression, "STORE" by default.
- * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
- * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
- */
- generate: function(options) {
- options = extend(options || {}, {
- base64: true,
- compression: "STORE",
- compressionOptions : null,
- type: "base64",
- platform: "DOS",
- comment: null,
- mimeType: 'application/zip'
- });
- utils.checkSupport(options.type);
- // accept nodejs `process.platform`
- if(
- options.platform === 'darwin' ||
- options.platform === 'freebsd' ||
- options.platform === 'linux' ||
- options.platform === 'sunos'
- ) {
- options.platform = "UNIX";
- }
- if (options.platform === 'win32') {
- options.platform = "DOS";
- }
- var zipData = [],
- localDirLength = 0,
- centralDirLength = 0,
- writer, i,
- utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
- // first, generate all the zip parts.
- for (var name in this.files) {
- if (!this.files.hasOwnProperty(name)) {
- continue;
- }
- var file = this.files[name];
- var compressionName = file.options.compression || options.compression.toUpperCase();
- var compression = compressions[compressionName];
- if (!compression) {
- throw new Error(compressionName + " is not a valid compression method !");
- }
- var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
- var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
- var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
- localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
- centralDirLength += zipPart.dirRecord.length;
- zipData.push(zipPart);
- }
- var dirEnd = "";
- // end of central dir signature
- dirEnd = signature.CENTRAL_DIRECTORY_END +
- // number of this disk
- "\x00\x00" +
- // number of the disk with the start of the central directory
- "\x00\x00" +
- // total number of entries in the central directory on this disk
- decToHex(zipData.length, 2) +
- // total number of entries in the central directory
- decToHex(zipData.length, 2) +
- // size of the central directory 4 bytes
- decToHex(centralDirLength, 4) +
- // offset of start of central directory with respect to the starting disk number
- decToHex(localDirLength, 4) +
- // .ZIP file comment length
- decToHex(utfEncodedComment.length, 2) +
- // .ZIP file comment
- utfEncodedComment;
- // we have all the parts (and the total length)
- // time to create a writer !
- var typeName = options.type.toLowerCase();
- if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
- writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
- }else{
- writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
- }
- for (i = 0; i < zipData.length; i++) {
- writer.append(zipData[i].fileRecord);
- writer.append(zipData[i].compressedObject.compressedContent);
- }
- for (i = 0; i < zipData.length; i++) {
- writer.append(zipData[i].dirRecord);
- }
- writer.append(dirEnd);
- var zip = writer.finalize();
- switch(options.type.toLowerCase()) {
- // case "zip is an Uint8Array"
- case "uint8array" :
- case "arraybuffer" :
- case "nodebuffer" :
- return utils.transformTo(options.type.toLowerCase(), zip);
- case "blob" :
- return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
- // case "zip is a string"
- case "base64" :
- return (options.base64) ? base64.encode(zip) : zip;
- default : // case "string" :
- return zip;
- }
- },
- /**
- * @deprecated
- * This method will be removed in a future version without replacement.
- */
- crc32: function (input, crc) {
- return crc32(input, crc);
- },
- /**
- * @deprecated
- * This method will be removed in a future version without replacement.
- */
- utf8encode: function (string) {
- return utils.transformTo("string", utf8.utf8encode(string));
- },
- /**
- * @deprecated
- * This method will be removed in a future version without replacement.
- */
- utf8decode: function (input) {
- return utf8.utf8decode(input);
- }
- };
- module.exports = out;
- },{"./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){
- 'use strict';
- exports.LOCAL_FILE_HEADER = "PK\x03\x04";
- exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
- exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
- exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
- exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
- exports.DATA_DESCRIPTOR = "PK\x07\x08";
- },{}],98:[function(require,module,exports){
- 'use strict';
- var DataReader = require('./dataReader');
- var utils = require('./utils');
- function StringReader(data, optimizedBinaryString) {
- this.data = data;
- if (!optimizedBinaryString) {
- this.data = utils.string2binary(this.data);
- }
- this.length = this.data.length;
- this.index = 0;
- }
- StringReader.prototype = new DataReader();
- /**
- * @see DataReader.byteAt
- */
- StringReader.prototype.byteAt = function(i) {
- return this.data.charCodeAt(i);
- };
- /**
- * @see DataReader.lastIndexOfSignature
- */
- StringReader.prototype.lastIndexOfSignature = function(sig) {
- return this.data.lastIndexOf(sig);
- };
- /**
- * @see DataReader.readData
- */
- StringReader.prototype.readData = function(size) {
- this.checkOffset(size);
- // this will work because the constructor applied the "& 0xff" mask.
- var result = this.data.slice(this.index, this.index + size);
- this.index += size;
- return result;
- };
- module.exports = StringReader;
- },{"./dataReader":88,"./utils":104}],99:[function(require,module,exports){
- 'use strict';
- var utils = require('./utils');
- /**
- * An object to write any content to a string.
- * @constructor
- */
- var StringWriter = function() {
- this.data = [];
- };
- StringWriter.prototype = {
- /**
- * Append any content to the current string.
- * @param {Object} input the content to add.
- */
- append: function(input) {
- input = utils.transformTo("string", input);
- this.data.push(input);
- },
- /**
- * Finalize the construction an return the result.
- * @return {string} the generated string.
- */
- finalize: function() {
- return this.data.join("");
- }
- };
- module.exports = StringWriter;
- },{"./utils":104}],100:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- exports.base64 = true;
- exports.array = true;
- exports.string = true;
- exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
- // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
- // Browserify will provide a Buffer implementation for browsers, which is
- // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
- exports.nodebuffer = typeof Buffer !== "undefined";
- // contains true if JSZip can read/generate Uint8Array, false otherwise.
- exports.uint8array = typeof Uint8Array !== "undefined";
- if (typeof ArrayBuffer === "undefined") {
- exports.blob = false;
- }
- else {
- var buffer = new ArrayBuffer(0);
- try {
- exports.blob = new Blob([buffer], {
- type: "application/zip"
- }).size === 0;
- }
- catch (e) {
- try {
- var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
- var builder = new Builder();
- builder.append(buffer);
- exports.blob = builder.getBlob('application/zip').size === 0;
- }
- catch (e) {
- exports.blob = false;
- }
- }
- }
- }).call(this,require("buffer").Buffer)
- },{"buffer":77}],101:[function(require,module,exports){
- 'use strict';
- var DataReader = require('./dataReader');
- function Uint8ArrayReader(data) {
- if (data) {
- this.data = data;
- this.length = this.data.length;
- this.index = 0;
- }
- }
- Uint8ArrayReader.prototype = new DataReader();
- /**
- * @see DataReader.byteAt
- */
- Uint8ArrayReader.prototype.byteAt = function(i) {
- return this.data[i];
- };
- /**
- * @see DataReader.lastIndexOfSignature
- */
- Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
- var sig0 = sig.charCodeAt(0),
- sig1 = sig.charCodeAt(1),
- sig2 = sig.charCodeAt(2),
- sig3 = sig.charCodeAt(3);
- for (var i = this.length - 4; i >= 0; --i) {
- if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
- return i;
- }
- }
- return -1;
- };
- /**
- * @see DataReader.readData
- */
- Uint8ArrayReader.prototype.readData = function(size) {
- this.checkOffset(size);
- if(size === 0) {
- // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
- return new Uint8Array(0);
- }
- var result = this.data.subarray(this.index, this.index + size);
- this.index += size;
- return result;
- };
- module.exports = Uint8ArrayReader;
- },{"./dataReader":88}],102:[function(require,module,exports){
- 'use strict';
- var utils = require('./utils');
- /**
- * An object to write any content to an Uint8Array.
- * @constructor
- * @param {number} length The length of the array.
- */
- var Uint8ArrayWriter = function(length) {
- this.data = new Uint8Array(length);
- this.index = 0;
- };
- Uint8ArrayWriter.prototype = {
- /**
- * Append any content to the current array.
- * @param {Object} input the content to add.
- */
- append: function(input) {
- if (input.length !== 0) {
- // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
- input = utils.transformTo("uint8array", input);
- this.data.set(input, this.index);
- this.index += input.length;
- }
- },
- /**
- * Finalize the construction an return the result.
- * @return {Uint8Array} the generated array.
- */
- finalize: function() {
- return this.data;
- }
- };
- module.exports = Uint8ArrayWriter;
- },{"./utils":104}],103:[function(require,module,exports){
- 'use strict';
- var utils = require('./utils');
- var support = require('./support');
- var nodeBuffer = require('./nodeBuffer');
- /**
- * The following functions come from pako, from pako/lib/utils/strings
- * released under the MIT license, see pako https://github.com/nodeca/pako/
- */
- // Table with utf8 lengths (calculated by first byte of sequence)
- // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
- // because max possible codepoint is 0x10ffff
- var _utf8len = new Array(256);
- for (var i=0; i<256; i++) {
- _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
- }
- _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
- // convert string to array (typed, when possible)
- var string2buf = function (str) {
- var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
- // count binary size
- for (m_pos = 0; m_pos < str_len; m_pos++) {
- c = str.charCodeAt(m_pos);
- if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
- c2 = str.charCodeAt(m_pos+1);
- if ((c2 & 0xfc00) === 0xdc00) {
- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
- m_pos++;
- }
- }
- buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
- }
- // allocate buffer
- if (support.uint8array) {
- buf = new Uint8Array(buf_len);
- } else {
- buf = new Array(buf_len);
- }
- // convert
- for (i=0, m_pos = 0; i < buf_len; m_pos++) {
- c = str.charCodeAt(m_pos);
- if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
- c2 = str.charCodeAt(m_pos+1);
- if ((c2 & 0xfc00) === 0xdc00) {
- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
- m_pos++;
- }
- }
- if (c < 0x80) {
- /* one byte */
- buf[i++] = c;
- } else if (c < 0x800) {
- /* two bytes */
- buf[i++] = 0xC0 | (c >>> 6);
- buf[i++] = 0x80 | (c & 0x3f);
- } else if (c < 0x10000) {
- /* three bytes */
- buf[i++] = 0xE0 | (c >>> 12);
- buf[i++] = 0x80 | (c >>> 6 & 0x3f);
- buf[i++] = 0x80 | (c & 0x3f);
- } else {
- /* four bytes */
- buf[i++] = 0xf0 | (c >>> 18);
- buf[i++] = 0x80 | (c >>> 12 & 0x3f);
- buf[i++] = 0x80 | (c >>> 6 & 0x3f);
- buf[i++] = 0x80 | (c & 0x3f);
- }
- }
- return buf;
- };
- // Calculate max possible position in utf8 buffer,
- // that will not break sequence. If that's not possible
- // - (very small limits) return max size as is.
- //
- // buf[] - utf8 bytes array
- // max - length limit (mandatory);
- var utf8border = function(buf, max) {
- var pos;
- max = max || buf.length;
- if (max > buf.length) { max = buf.length; }
- // go back from last position, until start of sequence found
- pos = max-1;
- while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
- // Fuckup - very small and broken sequence,
- // return max, because we should return something anyway.
- if (pos < 0) { return max; }
- // If we came to start of buffer - that means vuffer is too small,
- // return max too.
- if (pos === 0) { return max; }
- return (pos + _utf8len[buf[pos]] > max) ? pos : max;
- };
- // convert array to string
- var buf2string = function (buf) {
- var str, i, out, c, c_len;
- var len = buf.length;
- // Reserve max possible length (2 words per char)
- // NB: by unknown reasons, Array is significantly faster for
- // String.fromCharCode.apply than Uint16Array.
- var utf16buf = new Array(len*2);
- for (out=0, i=0; i<len;) {
- c = buf[i++];
- // quick process ascii
- if (c < 0x80) { utf16buf[out++] = c; continue; }
- c_len = _utf8len[c];
- // skip 5 & 6 byte codes
- if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
- // apply mask on first byte
- c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
- // join the rest
- while (c_len > 1 && i < len) {
- c = (c << 6) | (buf[i++] & 0x3f);
- c_len--;
- }
- // terminated by end of string?
- if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
- if (c < 0x10000) {
- utf16buf[out++] = c;
- } else {
- c -= 0x10000;
- utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
- utf16buf[out++] = 0xdc00 | (c & 0x3ff);
- }
- }
- // shrinkBuf(utf16buf, out)
- if (utf16buf.length !== out) {
- if(utf16buf.subarray) {
- utf16buf = utf16buf.subarray(0, out);
- } else {
- utf16buf.length = out;
- }
- }
- // return String.fromCharCode.apply(null, utf16buf);
- return utils.applyFromCharCode(utf16buf);
- };
- // That's all for the pako functions.
- /**
- * Transform a javascript string into an array (typed if possible) of bytes,
- * UTF-8 encoded.
- * @param {String} str the string to encode
- * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
- */
- exports.utf8encode = function utf8encode(str) {
- if (support.nodebuffer) {
- return nodeBuffer(str, "utf-8");
- }
- return string2buf(str);
- };
- /**
- * Transform a bytes array (or a representation) representing an UTF-8 encoded
- * string into a javascript string.
- * @param {Array|Uint8Array|Buffer} buf the data de decode
- * @return {String} the decoded string.
- */
- exports.utf8decode = function utf8decode(buf) {
- if (support.nodebuffer) {
- return utils.transformTo("nodebuffer", buf).toString("utf-8");
- }
- buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
- // return buf2string(buf);
- // Chrome prefers to work with "small" chunks of data
- // for the method buf2string.
- // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
- var result = [], k = 0, len = buf.length, chunk = 65536;
- while (k < len) {
- var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
- if (support.uint8array) {
- result.push(buf2string(buf.subarray(k, nextBoundary)));
- } else {
- result.push(buf2string(buf.slice(k, nextBoundary)));
- }
- k = nextBoundary;
- }
- return result.join("");
- };
- // vim: set shiftwidth=4 softtabstop=4:
- },{"./nodeBuffer":94,"./support":100,"./utils":104}],104:[function(require,module,exports){
- 'use strict';
- var support = require('./support');
- var compressions = require('./compressions');
- var nodeBuffer = require('./nodeBuffer');
- /**
- * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
- * @param {string} str the string to transform.
- * @return {String} the binary string.
- */
- exports.string2binary = function(str) {
- var result = "";
- for (var i = 0; i < str.length; i++) {
- result += String.fromCharCode(str.charCodeAt(i) & 0xff);
- }
- return result;
- };
- exports.arrayBuffer2Blob = function(buffer, mimeType) {
- exports.checkSupport("blob");
- mimeType = mimeType || 'application/zip';
- try {
- // Blob constructor
- return new Blob([buffer], {
- type: mimeType
- });
- }
- catch (e) {
- try {
- // deprecated, browser only, old way
- var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
- var builder = new Builder();
- builder.append(buffer);
- return builder.getBlob(mimeType);
- }
- catch (e) {
- // well, fuck ?!
- throw new Error("Bug : can't construct the Blob.");
- }
- }
- };
- /**
- * The identity function.
- * @param {Object} input the input.
- * @return {Object} the same input.
- */
- function identity(input) {
- return input;
- }
- /**
- * Fill in an array with a string.
- * @param {String} str the string to use.
- * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
- * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
- */
- function stringToArrayLike(str, array) {
- for (var i = 0; i < str.length; ++i) {
- array[i] = str.charCodeAt(i) & 0xFF;
- }
- return array;
- }
- /**
- * Transform an array-like object to a string.
- * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
- * @return {String} the result.
- */
- function arrayLikeToString(array) {
- // Performances notes :
- // --------------------
- // String.fromCharCode.apply(null, array) is the fastest, see
- // see http://jsperf.com/converting-a-uint8array-to-a-string/2
- // but the stack is limited (and we can get huge arrays !).
- //
- // result += String.fromCharCode(array[i]); generate too many strings !
- //
- // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
- var chunk = 65536;
- var result = [],
- len = array.length,
- type = exports.getTypeOf(array),
- k = 0,
- canUseApply = true;
- try {
- switch(type) {
- case "uint8array":
- String.fromCharCode.apply(null, new Uint8Array(0));
- break;
- case "nodebuffer":
- String.fromCharCode.apply(null, nodeBuffer(0));
- break;
- }
- } catch(e) {
- canUseApply = false;
- }
- // no apply : slow and painful algorithm
- // default browser on android 4.*
- if (!canUseApply) {
- var resultStr = "";
- for(var i = 0; i < array.length;i++) {
- resultStr += String.fromCharCode(array[i]);
- }
- return resultStr;
- }
- while (k < len && chunk > 1) {
- try {
- if (type === "array" || type === "nodebuffer") {
- result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
- }
- else {
- result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
- }
- k += chunk;
- }
- catch (e) {
- chunk = Math.floor(chunk / 2);
- }
- }
- return result.join("");
- }
- exports.applyFromCharCode = arrayLikeToString;
- /**
- * Copy the data from an array-like to an other array-like.
- * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
- * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
- * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
- */
- function arrayLikeToArrayLike(arrayFrom, arrayTo) {
- for (var i = 0; i < arrayFrom.length; i++) {
- arrayTo[i] = arrayFrom[i];
- }
- return arrayTo;
- }
- // a matrix containing functions to transform everything into everything.
- var transform = {};
- // string to ?
- transform["string"] = {
- "string": identity,
- "array": function(input) {
- return stringToArrayLike(input, new Array(input.length));
- },
- "arraybuffer": function(input) {
- return transform["string"]["uint8array"](input).buffer;
- },
- "uint8array": function(input) {
- return stringToArrayLike(input, new Uint8Array(input.length));
- },
- "nodebuffer": function(input) {
- return stringToArrayLike(input, nodeBuffer(input.length));
- }
- };
- // array to ?
- transform["array"] = {
- "string": arrayLikeToString,
- "array": identity,
- "arraybuffer": function(input) {
- return (new Uint8Array(input)).buffer;
- },
- "uint8array": function(input) {
- return new Uint8Array(input);
- },
- "nodebuffer": function(input) {
- return nodeBuffer(input);
- }
- };
- // arraybuffer to ?
- transform["arraybuffer"] = {
- "string": function(input) {
- return arrayLikeToString(new Uint8Array(input));
- },
- "array": function(input) {
- return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
- },
- "arraybuffer": identity,
- "uint8array": function(input) {
- return new Uint8Array(input);
- },
- "nodebuffer": function(input) {
- return nodeBuffer(new Uint8Array(input));
- }
- };
- // uint8array to ?
- transform["uint8array"] = {
- "string": arrayLikeToString,
- "array": function(input) {
- return arrayLikeToArrayLike(input, new Array(input.length));
- },
- "arraybuffer": function(input) {
- return input.buffer;
- },
- "uint8array": identity,
- "nodebuffer": function(input) {
- return nodeBuffer(input);
- }
- };
- // nodebuffer to ?
- transform["nodebuffer"] = {
- "string": arrayLikeToString,
- "array": function(input) {
- return arrayLikeToArrayLike(input, new Array(input.length));
- },
- "arraybuffer": function(input) {
- return transform["nodebuffer"]["uint8array"](input).buffer;
- },
- "uint8array": function(input) {
- return arrayLikeToArrayLike(input, new Uint8Array(input.length));
- },
- "nodebuffer": identity
- };
- /**
- * Transform an input into any type.
- * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
- * If no output type is specified, the unmodified input will be returned.
- * @param {String} outputType the output type.
- * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
- * @throws {Error} an Error if the browser doesn't support the requested output type.
- */
- exports.transformTo = function(outputType, input) {
- if (!input) {
- // undefined, null, etc
- // an empty string won't harm.
- input = "";
- }
- if (!outputType) {
- return input;
- }
- exports.checkSupport(outputType);
- var inputType = exports.getTypeOf(input);
- var result = transform[inputType][outputType](input);
- return result;
- };
- /**
- * Return the type of the input.
- * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
- * @param {Object} input the input to identify.
- * @return {String} the (lowercase) type of the input.
- */
- exports.getTypeOf = function(input) {
- if (typeof input === "string") {
- return "string";
- }
- if (Object.prototype.toString.call(input) === "[object Array]") {
- return "array";
- }
- if (support.nodebuffer && nodeBuffer.test(input)) {
- return "nodebuffer";
- }
- if (support.uint8array && input instanceof Uint8Array) {
- return "uint8array";
- }
- if (support.arraybuffer && input instanceof ArrayBuffer) {
- return "arraybuffer";
- }
- };
- /**
- * Throw an exception if the type is not supported.
- * @param {String} type the type to check.
- * @throws {Error} an Error if the browser doesn't support the requested type.
- */
- exports.checkSupport = function(type) {
- var supported = support[type.toLowerCase()];
- if (!supported) {
- throw new Error(type + " is not supported by this browser");
- }
- };
- exports.MAX_VALUE_16BITS = 65535;
- exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
- /**
- * Prettify a string read as binary.
- * @param {string} str the string to prettify.
- * @return {string} a pretty string.
- */
- exports.pretty = function(str) {
- var res = '',
- code, i;
- for (i = 0; i < (str || "").length; i++) {
- code = str.charCodeAt(i);
- res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
- }
- return res;
- };
- /**
- * Find a compression registered in JSZip.
- * @param {string} compressionMethod the method magic to find.
- * @return {Object|null} the JSZip compression object, null if none found.
- */
- exports.findCompression = function(compressionMethod) {
- for (var method in compressions) {
- if (!compressions.hasOwnProperty(method)) {
- continue;
- }
- if (compressions[method].magic === compressionMethod) {
- return compressions[method];
- }
- }
- return null;
- };
- /**
- * Cross-window, cross-Node-context regular expression detection
- * @param {Object} object Anything
- * @return {Boolean} true if the object is a regular expression,
- * false otherwise
- */
- exports.isRegExp = function (object) {
- return Object.prototype.toString.call(object) === "[object RegExp]";
- };
- },{"./compressions":86,"./nodeBuffer":94,"./support":100}],105:[function(require,module,exports){
- 'use strict';
- var StringReader = require('./stringReader');
- var NodeBufferReader = require('./nodeBufferReader');
- var Uint8ArrayReader = require('./uint8ArrayReader');
- var utils = require('./utils');
- var sig = require('./signature');
- var ZipEntry = require('./zipEntry');
- var support = require('./support');
- var jszipProto = require('./object');
- // class ZipEntries {{{
- /**
- * All the entries in the zip file.
- * @constructor
- * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
- * @param {Object} loadOptions Options for loading the stream.
- */
- function ZipEntries(data, loadOptions) {
- this.files = [];
- this.loadOptions = loadOptions;
- if (data) {
- this.load(data);
- }
- }
- ZipEntries.prototype = {
- /**
- * Check that the reader is on the speficied signature.
- * @param {string} expectedSignature the expected signature.
- * @throws {Error} if it is an other signature.
- */
- checkSignature: function(expectedSignature) {
- var signature = this.reader.readString(4);
- if (signature !== expectedSignature) {
- throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
- }
- },
- /**
- * Read the end of the central directory.
- */
- readBlockEndOfCentral: function() {
- this.diskNumber = this.reader.readInt(2);
- this.diskWithCentralDirStart = this.reader.readInt(2);
- this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
- this.centralDirRecords = this.reader.readInt(2);
- this.centralDirSize = this.reader.readInt(4);
- this.centralDirOffset = this.reader.readInt(4);
- this.zipCommentLength = this.reader.readInt(2);
- // warning : the encoding depends of the system locale
- // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
- // On a windows machine, this field is encoded with the localized windows code page.
- this.zipComment = this.reader.readString(this.zipCommentLength);
- // To get consistent behavior with the generation part, we will assume that
- // this is utf8 encoded.
- this.zipComment = jszipProto.utf8decode(this.zipComment);
- },
- /**
- * Read the end of the Zip 64 central directory.
- * Not merged with the method readEndOfCentral :
- * The end of central can coexist with its Zip64 brother,
- * I don't want to read the wrong number of bytes !
- */
- readBlockZip64EndOfCentral: function() {
- this.zip64EndOfCentralSize = this.reader.readInt(8);
- this.versionMadeBy = this.reader.readString(2);
- this.versionNeeded = this.reader.readInt(2);
- this.diskNumber = this.reader.readInt(4);
- this.diskWithCentralDirStart = this.reader.readInt(4);
- this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
- this.centralDirRecords = this.reader.readInt(8);
- this.centralDirSize = this.reader.readInt(8);
- this.centralDirOffset = this.reader.readInt(8);
- this.zip64ExtensibleData = {};
- var extraDataSize = this.zip64EndOfCentralSize - 44,
- index = 0,
- extraFieldId,
- extraFieldLength,
- extraFieldValue;
- while (index < extraDataSize) {
- extraFieldId = this.reader.readInt(2);
- extraFieldLength = this.reader.readInt(4);
- extraFieldValue = this.reader.readString(extraFieldLength);
- this.zip64ExtensibleData[extraFieldId] = {
- id: extraFieldId,
- length: extraFieldLength,
- value: extraFieldValue
- };
- }
- },
- /**
- * Read the end of the Zip 64 central directory locator.
- */
- readBlockZip64EndOfCentralLocator: function() {
- this.diskWithZip64CentralDirStart = this.reader.readInt(4);
- this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
- this.disksCount = this.reader.readInt(4);
- if (this.disksCount > 1) {
- throw new Error("Multi-volumes zip are not supported");
- }
- },
- /**
- * Read the local files, based on the offset read in the central part.
- */
- readLocalFiles: function() {
- var i, file;
- for (i = 0; i < this.files.length; i++) {
- file = this.files[i];
- this.reader.setIndex(file.localHeaderOffset);
- this.checkSignature(sig.LOCAL_FILE_HEADER);
- file.readLocalPart(this.reader);
- file.handleUTF8();
- file.processAttributes();
- }
- },
- /**
- * Read the central directory.
- */
- readCentralDir: function() {
- var file;
- this.reader.setIndex(this.centralDirOffset);
- while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
- file = new ZipEntry({
- zip64: this.zip64
- }, this.loadOptions);
- file.readCentralPart(this.reader);
- this.files.push(file);
- }
- },
- /**
- * Read the end of central directory.
- */
- readEndOfCentral: function() {
- var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
- if (offset === -1) {
- // Check if the content is a truncated zip or complete garbage.
- // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
- // extractible zip for example) but it can give a good hint.
- // If an ajax request was used without responseType, we will also
- // get unreadable data.
- var isGarbage = true;
- try {
- this.reader.setIndex(0);
- this.checkSignature(sig.LOCAL_FILE_HEADER);
- isGarbage = false;
- } catch (e) {}
- if (isGarbage) {
- throw new Error("Can't find end of central directory : is this a zip file ? " +
- "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
- } else {
- throw new Error("Corrupted zip : can't find end of central directory");
- }
- }
- this.reader.setIndex(offset);
- this.checkSignature(sig.CENTRAL_DIRECTORY_END);
- this.readBlockEndOfCentral();
- /* extract from the zip spec :
- 4) If one of the fields in the end of central directory
- record is too small to hold required data, the field
- should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
- ZIP64 format record should be created.
- 5) The end of central directory record and the
- Zip64 end of central directory locator record must
- reside on the same disk when splitting or spanning
- an archive.
- */
- 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) {
- this.zip64 = true;
- /*
- Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
- the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
- all numbers as 64-bit double precision IEEE 754 floating point numbers.
- So, we have 53bits for integers and bitwise operations treat everything as 32bits.
- see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
- and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
- */
- // should look for a zip64 EOCD locator
- offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
- if (offset === -1) {
- throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
- }
- this.reader.setIndex(offset);
- this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
- this.readBlockZip64EndOfCentralLocator();
- // now the zip64 EOCD record
- this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
- this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
- this.readBlockZip64EndOfCentral();
- }
- },
- prepareReader: function(data) {
- var type = utils.getTypeOf(data);
- if (type === "string" && !support.uint8array) {
- this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
- }
- else if (type === "nodebuffer") {
- this.reader = new NodeBufferReader(data);
- }
- else {
- this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
- }
- },
- /**
- * Read a zip file and create ZipEntries.
- * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
- */
- load: function(data) {
- this.prepareReader(data);
- this.readEndOfCentral();
- this.readCentralDir();
- this.readLocalFiles();
- }
- };
- // }}} end of ZipEntries
- module.exports = ZipEntries;
- },{"./nodeBufferReader":95,"./object":96,"./signature":97,"./stringReader":98,"./support":100,"./uint8ArrayReader":101,"./utils":104,"./zipEntry":106}],106:[function(require,module,exports){
- 'use strict';
- var StringReader = require('./stringReader');
- var utils = require('./utils');
- var CompressedObject = require('./compressedObject');
- var jszipProto = require('./object');
- var MADE_BY_DOS = 0x00;
- var MADE_BY_UNIX = 0x03;
- // class ZipEntry {{{
- /**
- * An entry in the zip file.
- * @constructor
- * @param {Object} options Options of the current file.
- * @param {Object} loadOptions Options for loading the stream.
- */
- function ZipEntry(options, loadOptions) {
- this.options = options;
- this.loadOptions = loadOptions;
- }
- ZipEntry.prototype = {
- /**
- * say if the file is encrypted.
- * @return {boolean} true if the file is encrypted, false otherwise.
- */
- isEncrypted: function() {
- // bit 1 is set
- return (this.bitFlag & 0x0001) === 0x0001;
- },
- /**
- * say if the file has utf-8 filename/comment.
- * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
- */
- useUTF8: function() {
- // bit 11 is set
- return (this.bitFlag & 0x0800) === 0x0800;
- },
- /**
- * Prepare the function used to generate the compressed content from this ZipFile.
- * @param {DataReader} reader the reader to use.
- * @param {number} from the offset from where we should read the data.
- * @param {number} length the length of the data to read.
- * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
- */
- prepareCompressedContent: function(reader, from, length) {
- return function() {
- var previousIndex = reader.index;
- reader.setIndex(from);
- var compressedFileData = reader.readData(length);
- reader.setIndex(previousIndex);
- return compressedFileData;
- };
- },
- /**
- * Prepare the function used to generate the uncompressed content from this ZipFile.
- * @param {DataReader} reader the reader to use.
- * @param {number} from the offset from where we should read the data.
- * @param {number} length the length of the data to read.
- * @param {JSZip.compression} compression the compression used on this file.
- * @param {number} uncompressedSize the uncompressed size to expect.
- * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
- */
- prepareContent: function(reader, from, length, compression, uncompressedSize) {
- return function() {
- var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
- var uncompressedFileData = compression.uncompress(compressedFileData);
- if (uncompressedFileData.length !== uncompressedSize) {
- throw new Error("Bug : uncompressed data size mismatch");
- }
- return uncompressedFileData;
- };
- },
- /**
- * Read the local part of a zip file and add the info in this object.
- * @param {DataReader} reader the reader to use.
- */
- readLocalPart: function(reader) {
- var compression, localExtraFieldsLength;
- // we already know everything from the central dir !
- // If the central dir data are false, we are doomed.
- // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
- // The less data we get here, the more reliable this should be.
- // Let's skip the whole header and dash to the data !
- reader.skip(22);
- // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
- // Strangely, the filename here is OK.
- // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
- // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
- // Search "unzip mismatching "local" filename continuing with "central" filename version" on
- // the internet.
- //
- // I think I see the logic here : the central directory is used to display
- // content and the local directory is used to extract the files. Mixing / and \
- // may be used to display \ to windows users and use / when extracting the files.
- // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
- this.fileNameLength = reader.readInt(2);
- localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
- this.fileName = reader.readString(this.fileNameLength);
- reader.skip(localExtraFieldsLength);
- if (this.compressedSize == -1 || this.uncompressedSize == -1) {
- throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
- }
- compression = utils.findCompression(this.compressionMethod);
- if (compression === null) { // no compression found
- throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
- }
- this.decompressed = new CompressedObject();
- this.decompressed.compressedSize = this.compressedSize;
- this.decompressed.uncompressedSize = this.uncompressedSize;
- this.decompressed.crc32 = this.crc32;
- this.decompressed.compressionMethod = this.compressionMethod;
- this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
- this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
- // we need to compute the crc32...
- if (this.loadOptions.checkCRC32) {
- this.decompressed = utils.transformTo("string", this.decompressed.getContent());
- if (jszipProto.crc32(this.decompressed) !== this.crc32) {
- throw new Error("Corrupted zip : CRC32 mismatch");
- }
- }
- },
- /**
- * Read the central part of a zip file and add the info in this object.
- * @param {DataReader} reader the reader to use.
- */
- readCentralPart: function(reader) {
- this.versionMadeBy = reader.readInt(2);
- this.versionNeeded = reader.readInt(2);
- this.bitFlag = reader.readInt(2);
- this.compressionMethod = reader.readString(2);
- this.date = reader.readDate();
- this.crc32 = reader.readInt(4);
- this.compressedSize = reader.readInt(4);
- this.uncompressedSize = reader.readInt(4);
- this.fileNameLength = reader.readInt(2);
- this.extraFieldsLength = reader.readInt(2);
- this.fileCommentLength = reader.readInt(2);
- this.diskNumberStart = reader.readInt(2);
- this.internalFileAttributes = reader.readInt(2);
- this.externalFileAttributes = reader.readInt(4);
- this.localHeaderOffset = reader.readInt(4);
- if (this.isEncrypted()) {
- throw new Error("Encrypted zip are not supported");
- }
- this.fileName = reader.readString(this.fileNameLength);
- this.readExtraFields(reader);
- this.parseZIP64ExtraField(reader);
- this.fileComment = reader.readString(this.fileCommentLength);
- },
- /**
- * Parse the external file attributes and get the unix/dos permissions.
- */
- processAttributes: function () {
- this.unixPermissions = null;
- this.dosPermissions = null;
- var madeBy = this.versionMadeBy >> 8;
- // Check if we have the DOS directory flag set.
- // We look for it in the DOS and UNIX permissions
- // but some unknown platform could set it as a compatibility flag.
- this.dir = this.externalFileAttributes & 0x0010 ? true : false;
- if(madeBy === MADE_BY_DOS) {
- // first 6 bits (0 to 5)
- this.dosPermissions = this.externalFileAttributes & 0x3F;
- }
- if(madeBy === MADE_BY_UNIX) {
- this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
- // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
- }
- // fail safe : if the name ends with a / it probably means a folder
- if (!this.dir && this.fileName.slice(-1) === '/') {
- this.dir = true;
- }
- },
- /**
- * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
- * @param {DataReader} reader the reader to use.
- */
- parseZIP64ExtraField: function(reader) {
- if (!this.extraFields[0x0001]) {
- return;
- }
- // should be something, preparing the extra reader
- var extraReader = new StringReader(this.extraFields[0x0001].value);
- // I really hope that these 64bits integer can fit in 32 bits integer, because js
- // won't let us have more.
- if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
- this.uncompressedSize = extraReader.readInt(8);
- }
- if (this.compressedSize === utils.MAX_VALUE_32BITS) {
- this.compressedSize = extraReader.readInt(8);
- }
- if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
- this.localHeaderOffset = extraReader.readInt(8);
- }
- if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
- this.diskNumberStart = extraReader.readInt(4);
- }
- },
- /**
- * Read the central part of a zip file and add the info in this object.
- * @param {DataReader} reader the reader to use.
- */
- readExtraFields: function(reader) {
- var start = reader.index,
- extraFieldId,
- extraFieldLength,
- extraFieldValue;
- this.extraFields = this.extraFields || {};
- while (reader.index < start + this.extraFieldsLength) {
- extraFieldId = reader.readInt(2);
- extraFieldLength = reader.readInt(2);
- extraFieldValue = reader.readString(extraFieldLength);
- this.extraFields[extraFieldId] = {
- id: extraFieldId,
- length: extraFieldLength,
- value: extraFieldValue
- };
- }
- },
- /**
- * Apply an UTF8 transformation if needed.
- */
- handleUTF8: function() {
- if (this.useUTF8()) {
- this.fileName = jszipProto.utf8decode(this.fileName);
- this.fileComment = jszipProto.utf8decode(this.fileComment);
- } else {
- var upath = this.findExtraFieldUnicodePath();
- if (upath !== null) {
- this.fileName = upath;
- }
- var ucomment = this.findExtraFieldUnicodeComment();
- if (ucomment !== null) {
- this.fileComment = ucomment;
- }
- }
- },
- /**
- * Find the unicode path declared in the extra field, if any.
- * @return {String} the unicode path, null otherwise.
- */
- findExtraFieldUnicodePath: function() {
- var upathField = this.extraFields[0x7075];
- if (upathField) {
- var extraReader = new StringReader(upathField.value);
- // wrong version
- if (extraReader.readInt(1) !== 1) {
- return null;
- }
- // the crc of the filename changed, this field is out of date.
- if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
- return null;
- }
- return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
- }
- return null;
- },
- /**
- * Find the unicode comment declared in the extra field, if any.
- * @return {String} the unicode comment, null otherwise.
- */
- findExtraFieldUnicodeComment: function() {
- var ucommentField = this.extraFields[0x6375];
- if (ucommentField) {
- var extraReader = new StringReader(ucommentField.value);
- // wrong version
- if (extraReader.readInt(1) !== 1) {
- return null;
- }
- // the crc of the comment changed, this field is out of date.
- if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
- return null;
- }
- return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
- }
- return null;
- }
- };
- module.exports = ZipEntry;
- },{"./compressedObject":85,"./object":96,"./stringReader":98,"./utils":104}],107:[function(require,module,exports){
- exports.Parser = require("./lib/parser").Parser;
- exports.rules = require("./lib/rules");
- exports.errors = require("./lib/errors");
- exports.results = require("./lib/parsing-results");
- exports.StringSource = require("./lib/StringSource");
- exports.Token = require("./lib/Token");
- exports.bottomUp = require("./lib/bottom-up");
- exports.RegexTokeniser = require("./lib/regex-tokeniser").RegexTokeniser;
- exports.rule = function(ruleBuilder) {
- var rule;
- return function(input) {
- if (!rule) {
- rule = ruleBuilder();
- }
- return rule(input);
- };
- };
- },{"./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){
- var util = require("util");
- var StringSource = module.exports = function(string, description) {
- var self = {
- asString: function() {
- return string;
- },
- range: function(startIndex, endIndex) {
- return new StringSourceRange(string, description, startIndex, endIndex);
- }
- };
- return self;
- };
- var StringSourceRange = function(string, description, startIndex, endIndex) {
- this._string = string;
- this._description = description;
- this._startIndex = startIndex;
- this._endIndex = endIndex;
- };
- StringSourceRange.prototype.to = function(otherRange) {
- // TODO: Assert that tokens are the same across both iterators
- return new StringSourceRange(this._string, this._description, this._startIndex, otherRange._endIndex);
- };
- StringSourceRange.prototype.describe = function() {
- var position = this._position();
- var description = this._description ? this._description + "\n" : "";
- return util.format("%sLine number: %s\nCharacter number: %s",
- description, position.lineNumber, position.characterNumber);
- };
- StringSourceRange.prototype.lineNumber = function() {
- return this._position().lineNumber;
- };
- StringSourceRange.prototype.characterNumber = function() {
- return this._position().characterNumber;
- };
- StringSourceRange.prototype._position = function() {
- var self = this;
- var index = 0;
- var nextNewLine = function() {
- return self._string.indexOf("\n", index);
- };
-
- var lineNumber = 1;
- while (nextNewLine() !== -1 && nextNewLine() < this._startIndex) {
- index = nextNewLine() + 1;
- lineNumber += 1;
- }
- var characterNumber = this._startIndex - index + 1;
- return {lineNumber: lineNumber, characterNumber: characterNumber};
- };
- },{"util":157}],109:[function(require,module,exports){
- module.exports = function(name, value, source) {
- this.name = name;
- this.value = value;
- if (source) {
- this.source = source;
- }
- };
- },{}],110:[function(require,module,exports){
- var TokenIterator = module.exports = function(tokens, startIndex) {
- this._tokens = tokens;
- this._startIndex = startIndex || 0;
- };
- TokenIterator.prototype.head = function() {
- return this._tokens[this._startIndex];
- };
- TokenIterator.prototype.tail = function(startIndex) {
- return new TokenIterator(this._tokens, this._startIndex + 1);
- };
- TokenIterator.prototype.toArray = function() {
- return this._tokens.slice(this._startIndex);
- };
- TokenIterator.prototype.end = function() {
- return this._tokens[this._tokens.length - 1];
- };
- // TODO: doesn't need to be a method, can be a separate function,
- // which simplifies implementation of the TokenIterator interface
- TokenIterator.prototype.to = function(end) {
- var start = this.head().source;
- var endToken = end.head() || end.end();
- return start.to(endToken.source);
- };
- },{}],111:[function(require,module,exports){
- var rules = require("./rules");
- var results = require("./parsing-results");
- exports.parser = function(name, prefixRules, infixRuleBuilders) {
- var self = {
- rule: rule,
- leftAssociative: leftAssociative,
- rightAssociative: rightAssociative
- };
-
- var infixRules = new InfixRules(infixRuleBuilders.map(createInfixRule));
- var prefixRule = rules.firstOf(name, prefixRules);
-
- function createInfixRule(infixRuleBuilder) {
- return {
- name: infixRuleBuilder.name,
- rule: lazyRule(infixRuleBuilder.ruleBuilder.bind(null, self))
- };
- }
-
- function rule() {
- return createRule(infixRules);
- }
-
- function leftAssociative(name) {
- return createRule(infixRules.untilExclusive(name));
- }
-
- function rightAssociative(name) {
- return createRule(infixRules.untilInclusive(name));
- }
-
- function createRule(infixRules) {
- return apply.bind(null, infixRules);
- }
-
- function apply(infixRules, tokens) {
- var leftResult = prefixRule(tokens);
- if (leftResult.isSuccess()) {
- return infixRules.apply(leftResult);
- } else {
- return leftResult;
- }
- }
-
- return self;
- };
- function InfixRules(infixRules) {
- function untilExclusive(name) {
- return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name)));
- }
-
- function untilInclusive(name) {
- return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name) + 1));
- }
-
- function ruleNames() {
- return infixRules.map(function(rule) {
- return rule.name;
- });
- }
-
- function apply(leftResult) {
- var currentResult;
- var source;
- while (true) {
- currentResult = applyToTokens(leftResult.remaining());
- if (currentResult.isSuccess()) {
- source = leftResult.source().to(currentResult.source());
- leftResult = results.success(
- currentResult.value()(leftResult.value(), source),
- currentResult.remaining(),
- source
- )
- } else if (currentResult.isFailure()) {
- return leftResult;
- } else {
- return currentResult;
- }
- }
- }
-
- function applyToTokens(tokens) {
- return rules.firstOf("infix", infixRules.map(function(infix) {
- return infix.rule;
- }))(tokens);
- }
-
- return {
- apply: apply,
- untilExclusive: untilExclusive,
- untilInclusive: untilInclusive
- }
- }
- exports.infix = function(name, ruleBuilder) {
- function map(func) {
- return exports.infix(name, function(parser) {
- var rule = ruleBuilder(parser);
- return function(tokens) {
- var result = rule(tokens);
- return result.map(function(right) {
- return function(left, source) {
- return func(left, right, source);
- };
- });
- };
- });
- }
-
- return {
- name: name,
- ruleBuilder: ruleBuilder,
- map: map
- };
- }
- // TODO: move into a sensible place and remove duplication
- var lazyRule = function(ruleBuilder) {
- var rule;
- return function(input) {
- if (!rule) {
- rule = ruleBuilder();
- }
- return rule(input);
- };
- };
- },{"./parsing-results":115,"./rules":117}],112:[function(require,module,exports){
- exports.error = function(options) {
- return new Error(options);
- };
- var Error = function(options) {
- this.expected = options.expected;
- this.actual = options.actual;
- this._location = options.location;
- };
- Error.prototype.describe = function() {
- var locationDescription = this._location ? this._location.describe() + ":\n" : "";
- return locationDescription + "Expected " + this.expected + "\nbut got " + this.actual;
- };
- Error.prototype.lineNumber = function() {
- return this._location.lineNumber();
- };
- Error.prototype.characterNumber = function() {
- return this._location.characterNumber();
- };
- },{}],113:[function(require,module,exports){
- var fromArray = exports.fromArray = function(array) {
- var index = 0;
- var hasNext = function() {
- return index < array.length;
- };
- return new LazyIterator({
- hasNext: hasNext,
- next: function() {
- if (!hasNext()) {
- throw new Error("No more elements");
- } else {
- return array[index++];
- }
- }
- });
- };
- var LazyIterator = function(iterator) {
- this._iterator = iterator;
- };
- LazyIterator.prototype.map = function(func) {
- var iterator = this._iterator;
- return new LazyIterator({
- hasNext: function() {
- return iterator.hasNext();
- },
- next: function() {
- return func(iterator.next());
- }
- });
- };
- LazyIterator.prototype.filter = function(condition) {
- var iterator = this._iterator;
-
- var moved = false;
- var hasNext = false;
- var next;
- var moveIfNecessary = function() {
- if (moved) {
- return;
- }
- moved = true;
- hasNext = false;
- while (iterator.hasNext() && !hasNext) {
- next = iterator.next();
- hasNext = condition(next);
- }
- };
-
- return new LazyIterator({
- hasNext: function() {
- moveIfNecessary();
- return hasNext;
- },
- next: function() {
- moveIfNecessary();
- var toReturn = next;
- moved = false;
- return toReturn;
- }
- });
- };
- LazyIterator.prototype.first = function() {
- var iterator = this._iterator;
- if (this._iterator.hasNext()) {
- return iterator.next();
- } else {
- return null;
- }
- };
- LazyIterator.prototype.toArray = function() {
- var result = [];
- while (this._iterator.hasNext()) {
- result.push(this._iterator.next());
- }
- return result;
- };
- },{}],114:[function(require,module,exports){
- var TokenIterator = require("./TokenIterator");
- exports.Parser = function(options) {
- var parseTokens = function(parser, tokens) {
- return parser(new TokenIterator(tokens));
- };
-
- return {
- parseTokens: parseTokens
- };
- };
- },{"./TokenIterator":110}],115:[function(require,module,exports){
- module.exports = {
- failure: function(errors, remaining) {
- if (errors.length < 1) {
- throw new Error("Failure must have errors");
- }
- return new Result({
- status: "failure",
- remaining: remaining,
- errors: errors
- });
- },
- error: function(errors, remaining) {
- if (errors.length < 1) {
- throw new Error("Failure must have errors");
- }
- return new Result({
- status: "error",
- remaining: remaining,
- errors: errors
- });
- },
- success: function(value, remaining, source) {
- return new Result({
- status: "success",
- value: value,
- source: source,
- remaining: remaining,
- errors: []
- });
- },
- cut: function(remaining) {
- return new Result({
- status: "cut",
- remaining: remaining,
- errors: []
- });
- }
- };
- var Result = function(options) {
- this._value = options.value;
- this._status = options.status;
- this._hasValue = options.value !== undefined;
- this._remaining = options.remaining;
- this._source = options.source;
- this._errors = options.errors;
- };
- Result.prototype.map = function(func) {
- if (this._hasValue) {
- return new Result({
- value: func(this._value, this._source),
- status: this._status,
- remaining: this._remaining,
- source: this._source,
- errors: this._errors
- });
- } else {
- return this;
- }
- };
- Result.prototype.changeRemaining = function(remaining) {
- return new Result({
- value: this._value,
- status: this._status,
- remaining: remaining,
- source: this._source,
- errors: this._errors
- });
- };
- Result.prototype.isSuccess = function() {
- return this._status === "success" || this._status === "cut";
- };
- Result.prototype.isFailure = function() {
- return this._status === "failure";
- };
- Result.prototype.isError = function() {
- return this._status === "error";
- };
- Result.prototype.isCut = function() {
- return this._status === "cut";
- };
- Result.prototype.value = function() {
- return this._value;
- };
- Result.prototype.remaining = function() {
- return this._remaining;
- };
- Result.prototype.source = function() {
- return this._source;
- };
- Result.prototype.errors = function() {
- return this._errors;
- };
- },{}],116:[function(require,module,exports){
- var Token = require("./Token");
- var StringSource = require("./StringSource");
- exports.RegexTokeniser = RegexTokeniser;
- function RegexTokeniser(rules) {
- rules = rules.map(function(rule) {
- return {
- name: rule.name,
- regex: new RegExp(rule.regex.source, "g")
- };
- });
-
- function tokenise(input, description) {
- var source = new StringSource(input, description);
- var index = 0;
- var tokens = [];
-
- while (index < input.length) {
- var result = readNextToken(input, index, source);
- index = result.endIndex;
- tokens.push(result.token);
- }
-
- tokens.push(endToken(input, source));
- return tokens;
- }
- function readNextToken(string, startIndex, source) {
- for (var i = 0; i < rules.length; i++) {
- var regex = rules[i].regex;
- regex.lastIndex = startIndex;
- var result = regex.exec(string);
-
- if (result) {
- var endIndex = startIndex + result[0].length;
- if (result.index === startIndex && endIndex > startIndex) {
- var value = result[1];
- var token = new Token(
- rules[i].name,
- value,
- source.range(startIndex, endIndex)
- );
- return {token: token, endIndex: endIndex};
- }
- }
- }
- var endIndex = startIndex + 1;
- var token = new Token(
- "unrecognisedCharacter",
- string.substring(startIndex, endIndex),
- source.range(startIndex, endIndex)
- );
- return {token: token, endIndex: endIndex};
- }
-
- function endToken(input, source) {
- return new Token(
- "end",
- null,
- source.range(input.length, input.length)
- );
- }
-
- return {
- tokenise: tokenise
- }
- }
- },{"./StringSource":108,"./Token":109}],117:[function(require,module,exports){
- var _ = require("underscore");
- var options = require("option");
- var results = require("./parsing-results");
- var errors = require("./errors");
- var lazyIterators = require("./lazy-iterators");
- exports.token = function(tokenType, value) {
- var matchValue = value !== undefined;
- return function(input) {
- var token = input.head();
- if (token && token.name === tokenType && (!matchValue || token.value === value)) {
- return results.success(token.value, input.tail(), token.source);
- } else {
- var expected = describeToken({name: tokenType, value: value});
- return describeTokenMismatch(input, expected);
- }
- };
- };
- exports.tokenOfType = function(tokenType) {
- return exports.token(tokenType);
- };
- exports.firstOf = function(name, parsers) {
- if (!_.isArray(parsers)) {
- parsers = Array.prototype.slice.call(arguments, 1);
- }
- return function(input) {
- return lazyIterators
- .fromArray(parsers)
- .map(function(parser) {
- return parser(input);
- })
- .filter(function(result) {
- return result.isSuccess() || result.isError();
- })
- .first() || describeTokenMismatch(input, name);
- };
- };
- exports.then = function(parser, func) {
- return function(input) {
- var result = parser(input);
- if (!result.map) {
- console.log(result);
- }
- return result.map(func);
- };
- };
- exports.sequence = function() {
- var parsers = Array.prototype.slice.call(arguments, 0);
- var rule = function(input) {
- var result = _.foldl(parsers, function(memo, parser) {
- var result = memo.result;
- var hasCut = memo.hasCut;
- if (!result.isSuccess()) {
- return {result: result, hasCut: hasCut};
- }
- var subResult = parser(result.remaining());
- if (subResult.isCut()) {
- return {result: result, hasCut: true};
- } else if (subResult.isSuccess()) {
- var values;
- if (parser.isCaptured) {
- values = result.value().withValue(parser, subResult.value());
- } else {
- values = result.value();
- }
- var remaining = subResult.remaining();
- var source = input.to(remaining);
- return {
- result: results.success(values, remaining, source),
- hasCut: hasCut
- };
- } else if (hasCut) {
- return {result: results.error(subResult.errors(), subResult.remaining()), hasCut: hasCut};
- } else {
- return {result: subResult, hasCut: hasCut};
- }
- }, {result: results.success(new SequenceValues(), input), hasCut: false}).result;
- var source = input.to(result.remaining());
- return result.map(function(values) {
- return values.withValue(exports.sequence.source, source);
- });
- };
- rule.head = function() {
- var firstCapture = _.find(parsers, isCapturedRule);
- return exports.then(
- rule,
- exports.sequence.extract(firstCapture)
- );
- };
- rule.map = function(func) {
- return exports.then(
- rule,
- function(result) {
- return func.apply(this, result.toArray());
- }
- );
- };
-
- function isCapturedRule(subRule) {
- return subRule.isCaptured;
- }
-
- return rule;
- };
- var SequenceValues = function(values, valuesArray) {
- this._values = values || {};
- this._valuesArray = valuesArray || [];
- };
- SequenceValues.prototype.withValue = function(rule, value) {
- if (rule.captureName && rule.captureName in this._values) {
- throw new Error("Cannot add second value for capture \"" + rule.captureName + "\"");
- } else {
- var newValues = _.clone(this._values);
- newValues[rule.captureName] = value;
- var newValuesArray = this._valuesArray.concat([value]);
- return new SequenceValues(newValues, newValuesArray);
- }
- };
- SequenceValues.prototype.get = function(rule) {
- if (rule.captureName in this._values) {
- return this._values[rule.captureName];
- } else {
- throw new Error("No value for capture \"" + rule.captureName + "\"");
- }
- };
- SequenceValues.prototype.toArray = function() {
- return this._valuesArray;
- };
- exports.sequence.capture = function(rule, name) {
- var captureRule = function() {
- return rule.apply(this, arguments);
- };
- captureRule.captureName = name;
- captureRule.isCaptured = true;
- return captureRule;
- };
- exports.sequence.extract = function(rule) {
- return function(result) {
- return result.get(rule);
- };
- };
- exports.sequence.applyValues = function(func) {
- // TODO: check captureName doesn't conflict with source or other captures
- var rules = Array.prototype.slice.call(arguments, 1);
- return function(result) {
- var values = rules.map(function(rule) {
- return result.get(rule);
- });
- return func.apply(this, values);
- };
- };
- exports.sequence.source = {
- captureName: "☃source☃"
- };
- exports.sequence.cut = function() {
- return function(input) {
- return results.cut(input);
- };
- };
- exports.optional = function(rule) {
- return function(input) {
- var result = rule(input);
- if (result.isSuccess()) {
- return result.map(options.some);
- } else if (result.isFailure()) {
- return results.success(options.none, input);
- } else {
- return result;
- }
- };
- };
- exports.zeroOrMoreWithSeparator = function(rule, separator) {
- return repeatedWithSeparator(rule, separator, false);
- };
- exports.oneOrMoreWithSeparator = function(rule, separator) {
- return repeatedWithSeparator(rule, separator, true);
- };
- var zeroOrMore = exports.zeroOrMore = function(rule) {
- return function(input) {
- var values = [];
- var result;
- while ((result = rule(input)) && result.isSuccess()) {
- input = result.remaining();
- values.push(result.value());
- }
- if (result.isError()) {
- return result;
- } else {
- return results.success(values, input);
- }
- };
- };
- exports.oneOrMore = function(rule) {
- return exports.oneOrMoreWithSeparator(rule, noOpRule);
- };
- function noOpRule(input) {
- return results.success(null, input);
- }
- var repeatedWithSeparator = function(rule, separator, isOneOrMore) {
- return function(input) {
- var result = rule(input);
- if (result.isSuccess()) {
- var mainRule = exports.sequence.capture(rule, "main");
- var remainingRule = zeroOrMore(exports.then(
- exports.sequence(separator, mainRule),
- exports.sequence.extract(mainRule)
- ));
- var remainingResult = remainingRule(result.remaining());
- return results.success([result.value()].concat(remainingResult.value()), remainingResult.remaining());
- } else if (isOneOrMore || result.isError()) {
- return result;
- } else {
- return results.success([], input);
- }
- };
- };
- exports.leftAssociative = function(leftRule, rightRule, func) {
- var rights;
- if (func) {
- rights = [{func: func, rule: rightRule}];
- } else {
- rights = rightRule;
- }
- rights = rights.map(function(right) {
- return exports.then(right.rule, function(rightValue) {
- return function(leftValue, source) {
- return right.func(leftValue, rightValue, source);
- };
- });
- });
- var repeatedRule = exports.firstOf.apply(null, ["rules"].concat(rights));
-
- return function(input) {
- var start = input;
- var leftResult = leftRule(input);
- if (!leftResult.isSuccess()) {
- return leftResult;
- }
- var repeatedResult = repeatedRule(leftResult.remaining());
- while (repeatedResult.isSuccess()) {
- var remaining = repeatedResult.remaining();
- var source = start.to(repeatedResult.remaining());
- var right = repeatedResult.value();
- leftResult = results.success(
- right(leftResult.value(), source),
- remaining,
- source
- );
- repeatedResult = repeatedRule(leftResult.remaining());
- }
- if (repeatedResult.isError()) {
- return repeatedResult;
- }
- return leftResult;
- };
- };
- exports.leftAssociative.firstOf = function() {
- return Array.prototype.slice.call(arguments, 0);
- };
- exports.nonConsuming = function(rule) {
- return function(input) {
- return rule(input).changeRemaining(input);
- };
- };
- var describeToken = function(token) {
- if (token.value) {
- return token.name + " \"" + token.value + "\"";
- } else {
- return token.name;
- }
- };
- function describeTokenMismatch(input, expected) {
- var error;
- var token = input.head();
- if (token) {
- error = errors.error({
- expected: expected,
- actual: describeToken(token),
- location: token.source
- });
- } else {
- error = errors.error({
- expected: expected,
- actual: "end of tokens"
- });
- }
- return results.failure([error], input);
- }
- },{"./errors":112,"./lazy-iterators":113,"./parsing-results":115,"option":119,"underscore":118}],118:[function(require,module,exports){
- // Underscore.js 1.4.4
- // http://underscorejs.org
- // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
- // Underscore may be freely distributed under the MIT license.
- (function() {
- // Baseline setup
- // --------------
- // Establish the root object, `window` in the browser, or `global` on the server.
- var root = this;
- // Save the previous value of the `_` variable.
- var previousUnderscore = root._;
- // Establish the object that gets returned to break out of a loop iteration.
- var breaker = {};
- // Save bytes in the minified (but not gzipped) version:
- var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
- // Create quick reference variables for speed access to core prototypes.
- var push = ArrayProto.push,
- slice = ArrayProto.slice,
- concat = ArrayProto.concat,
- toString = ObjProto.toString,
- hasOwnProperty = ObjProto.hasOwnProperty;
- // All **ECMAScript 5** native function implementations that we hope to use
- // are declared here.
- var
- nativeForEach = ArrayProto.forEach,
- nativeMap = ArrayProto.map,
- nativeReduce = ArrayProto.reduce,
- nativeReduceRight = ArrayProto.reduceRight,
- nativeFilter = ArrayProto.filter,
- nativeEvery = ArrayProto.every,
- nativeSome = ArrayProto.some,
- nativeIndexOf = ArrayProto.indexOf,
- nativeLastIndexOf = ArrayProto.lastIndexOf,
- nativeIsArray = Array.isArray,
- nativeKeys = Object.keys,
- nativeBind = FuncProto.bind;
- // Create a safe reference to the Underscore object for use below.
- var _ = function(obj) {
- if (obj instanceof _) return obj;
- if (!(this instanceof _)) return new _(obj);
- this._wrapped = obj;
- };
- // Export the Underscore object for **Node.js**, with
- // backwards-compatibility for the old `require()` API. If we're in
- // the browser, add `_` as a global object via a string identifier,
- // for Closure Compiler "advanced" mode.
- if (typeof exports !== 'undefined') {
- if (typeof module !== 'undefined' && module.exports) {
- exports = module.exports = _;
- }
- exports._ = _;
- } else {
- root._ = _;
- }
- // Current version.
- _.VERSION = '1.4.4';
- // Collection Functions
- // --------------------
- // The cornerstone, an `each` implementation, aka `forEach`.
- // Handles objects with the built-in `forEach`, arrays, and raw objects.
- // Delegates to **ECMAScript 5**'s native `forEach` if available.
- var each = _.each = _.forEach = function(obj, iterator, context) {
- if (obj == null) return;
- if (nativeForEach && obj.forEach === nativeForEach) {
- obj.forEach(iterator, context);
- } else if (obj.length === +obj.length) {
- for (var i = 0, l = obj.length; i < l; i++) {
- if (iterator.call(context, obj[i], i, obj) === breaker) return;
- }
- } else {
- for (var key in obj) {
- if (_.has(obj, key)) {
- if (iterator.call(context, obj[key], key, obj) === breaker) return;
- }
- }
- }
- };
- // Return the results of applying the iterator to each element.
- // Delegates to **ECMAScript 5**'s native `map` if available.
- _.map = _.collect = function(obj, iterator, context) {
- var results = [];
- if (obj == null) return results;
- if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
- each(obj, function(value, index, list) {
- results[results.length] = iterator.call(context, value, index, list);
- });
- return results;
- };
- var reduceError = 'Reduce of empty array with no initial value';
- // **Reduce** builds up a single result from a list of values, aka `inject`,
- // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
- _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
- var initial = arguments.length > 2;
- if (obj == null) obj = [];
- if (nativeReduce && obj.reduce === nativeReduce) {
- if (context) iterator = _.bind(iterator, context);
- return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
- }
- each(obj, function(value, index, list) {
- if (!initial) {
- memo = value;
- initial = true;
- } else {
- memo = iterator.call(context, memo, value, index, list);
- }
- });
- if (!initial) throw new TypeError(reduceError);
- return memo;
- };
- // The right-associative version of reduce, also known as `foldr`.
- // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
- _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
- var initial = arguments.length > 2;
- if (obj == null) obj = [];
- if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
- if (context) iterator = _.bind(iterator, context);
- return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
- }
- var length = obj.length;
- if (length !== +length) {
- var keys = _.keys(obj);
- length = keys.length;
- }
- each(obj, function(value, index, list) {
- index = keys ? keys[--length] : --length;
- if (!initial) {
- memo = obj[index];
- initial = true;
- } else {
- memo = iterator.call(context, memo, obj[index], index, list);
- }
- });
- if (!initial) throw new TypeError(reduceError);
- return memo;
- };
- // Return the first value which passes a truth test. Aliased as `detect`.
- _.find = _.detect = function(obj, iterator, context) {
- var result;
- any(obj, function(value, index, list) {
- if (iterator.call(context, value, index, list)) {
- result = value;
- return true;
- }
- });
- return result;
- };
- // Return all the elements that pass a truth test.
- // Delegates to **ECMAScript 5**'s native `filter` if available.
- // Aliased as `select`.
- _.filter = _.select = function(obj, iterator, context) {
- var results = [];
- if (obj == null) return results;
- if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
- each(obj, function(value, index, list) {
- if (iterator.call(context, value, index, list)) results[results.length] = value;
- });
- return results;
- };
- // Return all the elements for which a truth test fails.
- _.reject = function(obj, iterator, context) {
- return _.filter(obj, function(value, index, list) {
- return !iterator.call(context, value, index, list);
- }, context);
- };
- // Determine whether all of the elements match a truth test.
- // Delegates to **ECMAScript 5**'s native `every` if available.
- // Aliased as `all`.
- _.every = _.all = function(obj, iterator, context) {
- iterator || (iterator = _.identity);
- var result = true;
- if (obj == null) return result;
- if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
- each(obj, function(value, index, list) {
- if (!(result = result && iterator.call(context, value, index, list))) return breaker;
- });
- return !!result;
- };
- // Determine if at least one element in the object matches a truth test.
- // Delegates to **ECMAScript 5**'s native `some` if available.
- // Aliased as `any`.
- var any = _.some = _.any = function(obj, iterator, context) {
- iterator || (iterator = _.identity);
- var result = false;
- if (obj == null) return result;
- if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
- each(obj, function(value, index, list) {
- if (result || (result = iterator.call(context, value, index, list))) return breaker;
- });
- return !!result;
- };
- // Determine if the array or object contains a given value (using `===`).
- // Aliased as `include`.
- _.contains = _.include = function(obj, target) {
- if (obj == null) return false;
- if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
- return any(obj, function(value) {
- return value === target;
- });
- };
- // Invoke a method (with arguments) on every item in a collection.
- _.invoke = function(obj, method) {
- var args = slice.call(arguments, 2);
- var isFunc = _.isFunction(method);
- return _.map(obj, function(value) {
- return (isFunc ? method : value[method]).apply(value, args);
- });
- };
- // Convenience version of a common use case of `map`: fetching a property.
- _.pluck = function(obj, key) {
- return _.map(obj, function(value){ return value[key]; });
- };
- // Convenience version of a common use case of `filter`: selecting only objects
- // containing specific `key:value` pairs.
- _.where = function(obj, attrs, first) {
- if (_.isEmpty(attrs)) return first ? null : [];
- return _[first ? 'find' : 'filter'](obj, function(value) {
- for (var key in attrs) {
- if (attrs[key] !== value[key]) return false;
- }
- return true;
- });
- };
- // Convenience version of a common use case of `find`: getting the first object
- // containing specific `key:value` pairs.
- _.findWhere = function(obj, attrs) {
- return _.where(obj, attrs, true);
- };
- // Return the maximum element or (element-based computation).
- // Can't optimize arrays of integers longer than 65,535 elements.
- // See: https://bugs.webkit.org/show_bug.cgi?id=80797
- _.max = function(obj, iterator, context) {
- if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
- return Math.max.apply(Math, obj);
- }
- if (!iterator && _.isEmpty(obj)) return -Infinity;
- var result = {computed : -Infinity, value: -Infinity};
- each(obj, function(value, index, list) {
- var computed = iterator ? iterator.call(context, value, index, list) : value;
- computed >= result.computed && (result = {value : value, computed : computed});
- });
- return result.value;
- };
- // Return the minimum element (or element-based computation).
- _.min = function(obj, iterator, context) {
- if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
- return Math.min.apply(Math, obj);
- }
- if (!iterator && _.isEmpty(obj)) return Infinity;
- var result = {computed : Infinity, value: Infinity};
- each(obj, function(value, index, list) {
- var computed = iterator ? iterator.call(context, value, index, list) : value;
- computed < result.computed && (result = {value : value, computed : computed});
- });
- return result.value;
- };
- // Shuffle an array.
- _.shuffle = function(obj) {
- var rand;
- var index = 0;
- var shuffled = [];
- each(obj, function(value) {
- rand = _.random(index++);
- shuffled[index - 1] = shuffled[rand];
- shuffled[rand] = value;
- });
- return shuffled;
- };
- // An internal function to generate lookup iterators.
- var lookupIterator = function(value) {
- return _.isFunction(value) ? value : function(obj){ return obj[value]; };
- };
- // Sort the object's values by a criterion produced by an iterator.
- _.sortBy = function(obj, value, context) {
- var iterator = lookupIterator(value);
- return _.pluck(_.map(obj, function(value, index, list) {
- return {
- value : value,
- index : index,
- criteria : iterator.call(context, value, index, list)
- };
- }).sort(function(left, right) {
- var a = left.criteria;
- var b = right.criteria;
- if (a !== b) {
- if (a > b || a === void 0) return 1;
- if (a < b || b === void 0) return -1;
- }
- return left.index < right.index ? -1 : 1;
- }), 'value');
- };
- // An internal function used for aggregate "group by" operations.
- var group = function(obj, value, context, behavior) {
- var result = {};
- var iterator = lookupIterator(value || _.identity);
- each(obj, function(value, index) {
- var key = iterator.call(context, value, index, obj);
- behavior(result, key, value);
- });
- return result;
- };
- // Groups the object's values by a criterion. Pass either a string attribute
- // to group by, or a function that returns the criterion.
- _.groupBy = function(obj, value, context) {
- return group(obj, value, context, function(result, key, value) {
- (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
- });
- };
- // Counts instances of an object that group by a certain criterion. Pass
- // either a string attribute to count by, or a function that returns the
- // criterion.
- _.countBy = function(obj, value, context) {
- return group(obj, value, context, function(result, key) {
- if (!_.has(result, key)) result[key] = 0;
- result[key]++;
- });
- };
- // Use a comparator function to figure out the smallest index at which
- // an object should be inserted so as to maintain order. Uses binary search.
- _.sortedIndex = function(array, obj, iterator, context) {
- iterator = iterator == null ? _.identity : lookupIterator(iterator);
- var value = iterator.call(context, obj);
- var low = 0, high = array.length;
- while (low < high) {
- var mid = (low + high) >>> 1;
- iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
- }
- return low;
- };
- // Safely convert anything iterable into a real, live array.
- _.toArray = function(obj) {
- if (!obj) return [];
- if (_.isArray(obj)) return slice.call(obj);
- if (obj.length === +obj.length) return _.map(obj, _.identity);
- return _.values(obj);
- };
- // Return the number of elements in an object.
- _.size = function(obj) {
- if (obj == null) return 0;
- return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
- };
- // Array Functions
- // ---------------
- // Get the first element of an array. Passing **n** will return the first N
- // values in the array. Aliased as `head` and `take`. The **guard** check
- // allows it to work with `_.map`.
- _.first = _.head = _.take = function(array, n, guard) {
- if (array == null) return void 0;
- return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
- };
- // Returns everything but the last entry of the array. Especially useful on
- // the arguments object. Passing **n** will return all the values in
- // the array, excluding the last N. The **guard** check allows it to work with
- // `_.map`.
- _.initial = function(array, n, guard) {
- return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
- };
- // Get the last element of an array. Passing **n** will return the last N
- // values in the array. The **guard** check allows it to work with `_.map`.
- _.last = function(array, n, guard) {
- if (array == null) return void 0;
- if ((n != null) && !guard) {
- return slice.call(array, Math.max(array.length - n, 0));
- } else {
- return array[array.length - 1];
- }
- };
- // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
- // Especially useful on the arguments object. Passing an **n** will return
- // the rest N values in the array. The **guard**
- // check allows it to work with `_.map`.
- _.rest = _.tail = _.drop = function(array, n, guard) {
- return slice.call(array, (n == null) || guard ? 1 : n);
- };
- // Trim out all falsy values from an array.
- _.compact = function(array) {
- return _.filter(array, _.identity);
- };
- // Internal implementation of a recursive `flatten` function.
- var flatten = function(input, shallow, output) {
- each(input, function(value) {
- if (_.isArray(value)) {
- shallow ? push.apply(output, value) : flatten(value, shallow, output);
- } else {
- output.push(value);
- }
- });
- return output;
- };
- // Return a completely flattened version of an array.
- _.flatten = function(array, shallow) {
- return flatten(array, shallow, []);
- };
- // Return a version of the array that does not contain the specified value(s).
- _.without = function(array) {
- return _.difference(array, slice.call(arguments, 1));
- };
- // Produce a duplicate-free version of the array. If the array has already
- // been sorted, you have the option of using a faster algorithm.
- // Aliased as `unique`.
- _.uniq = _.unique = function(array, isSorted, iterator, context) {
- if (_.isFunction(isSorted)) {
- context = iterator;
- iterator = isSorted;
- isSorted = false;
- }
- var initial = iterator ? _.map(array, iterator, context) : array;
- var results = [];
- var seen = [];
- each(initial, function(value, index) {
- if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
- seen.push(value);
- results.push(array[index]);
- }
- });
- return results;
- };
- // Produce an array that contains the union: each distinct element from all of
- // the passed-in arrays.
- _.union = function() {
- return _.uniq(concat.apply(ArrayProto, arguments));
- };
- // Produce an array that contains every item shared between all the
- // passed-in arrays.
- _.intersection = function(array) {
- var rest = slice.call(arguments, 1);
- return _.filter(_.uniq(array), function(item) {
- return _.every(rest, function(other) {
- return _.indexOf(other, item) >= 0;
- });
- });
- };
- // Take the difference between one array and a number of other arrays.
- // Only the elements present in just the first array will remain.
- _.difference = function(array) {
- var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
- return _.filter(array, function(value){ return !_.contains(rest, value); });
- };
- // Zip together multiple lists into a single array -- elements that share
- // an index go together.
- _.zip = function() {
- var args = slice.call(arguments);
- var length = _.max(_.pluck(args, 'length'));
- var results = new Array(length);
- for (var i = 0; i < length; i++) {
- results[i] = _.pluck(args, "" + i);
- }
- return results;
- };
- // Converts lists into objects. Pass either a single array of `[key, value]`
- // pairs, or two parallel arrays of the same length -- one of keys, and one of
- // the corresponding values.
- _.object = function(list, values) {
- if (list == null) return {};
- var result = {};
- for (var i = 0, l = list.length; i < l; i++) {
- if (values) {
- result[list[i]] = values[i];
- } else {
- result[list[i][0]] = list[i][1];
- }
- }
- return result;
- };
- // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
- // we need this function. Return the position of the first occurrence of an
- // item in an array, or -1 if the item is not included in the array.
- // Delegates to **ECMAScript 5**'s native `indexOf` if available.
- // If the array is large and already in sort order, pass `true`
- // for **isSorted** to use binary search.
- _.indexOf = function(array, item, isSorted) {
- if (array == null) return -1;
- var i = 0, l = array.length;
- if (isSorted) {
- if (typeof isSorted == 'number') {
- i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
- } else {
- i = _.sortedIndex(array, item);
- return array[i] === item ? i : -1;
- }
- }
- if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
- for (; i < l; i++) if (array[i] === item) return i;
- return -1;
- };
- // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
- _.lastIndexOf = function(array, item, from) {
- if (array == null) return -1;
- var hasIndex = from != null;
- if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
- return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
- }
- var i = (hasIndex ? from : array.length);
- while (i--) if (array[i] === item) return i;
- return -1;
- };
- // Generate an integer Array containing an arithmetic progression. A port of
- // the native Python `range()` function. See
- // [the Python documentation](http://docs.python.org/library/functions.html#range).
- _.range = function(start, stop, step) {
- if (arguments.length <= 1) {
- stop = start || 0;
- start = 0;
- }
- step = arguments[2] || 1;
- var len = Math.max(Math.ceil((stop - start) / step), 0);
- var idx = 0;
- var range = new Array(len);
- while(idx < len) {
- range[idx++] = start;
- start += step;
- }
- return range;
- };
- // Function (ahem) Functions
- // ------------------
- // Create a function bound to a given object (assigning `this`, and arguments,
- // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
- // available.
- _.bind = function(func, context) {
- if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
- var args = slice.call(arguments, 2);
- return function() {
- return func.apply(context, args.concat(slice.call(arguments)));
- };
- };
- // Partially apply a function by creating a version that has had some of its
- // arguments pre-filled, without changing its dynamic `this` context.
- _.partial = function(func) {
- var args = slice.call(arguments, 1);
- return function() {
- return func.apply(this, args.concat(slice.call(arguments)));
- };
- };
- // Bind all of an object's methods to that object. Useful for ensuring that
- // all callbacks defined on an object belong to it.
- _.bindAll = function(obj) {
- var funcs = slice.call(arguments, 1);
- if (funcs.length === 0) funcs = _.functions(obj);
- each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
- return obj;
- };
- // Memoize an expensive function by storing its results.
- _.memoize = function(func, hasher) {
- var memo = {};
- hasher || (hasher = _.identity);
- return function() {
- var key = hasher.apply(this, arguments);
- return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
- };
- };
- // Delays a function for the given number of milliseconds, and then calls
- // it with the arguments supplied.
- _.delay = function(func, wait) {
- var args = slice.call(arguments, 2);
- return setTimeout(function(){ return func.apply(null, args); }, wait);
- };
- // Defers a function, scheduling it to run after the current call stack has
- // cleared.
- _.defer = function(func) {
- return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
- };
- // Returns a function, that, when invoked, will only be triggered at most once
- // during a given window of time.
- _.throttle = function(func, wait) {
- var context, args, timeout, result;
- var previous = 0;
- var later = function() {
- previous = new Date;
- timeout = null;
- result = func.apply(context, args);
- };
- return function() {
- var now = new Date;
- var remaining = wait - (now - previous);
- context = this;
- args = arguments;
- if (remaining <= 0) {
- clearTimeout(timeout);
- timeout = null;
- previous = now;
- result = func.apply(context, args);
- } else if (!timeout) {
- timeout = setTimeout(later, remaining);
- }
- return result;
- };
- };
- // Returns a function, that, as long as it continues to be invoked, will not
- // be triggered. The function will be called after it stops being called for
- // N milliseconds. If `immediate` is passed, trigger the function on the
- // leading edge, instead of the trailing.
- _.debounce = function(func, wait, immediate) {
- var timeout, result;
- return function() {
- var context = this, args = arguments;
- var later = function() {
- timeout = null;
- if (!immediate) result = func.apply(context, args);
- };
- var callNow = immediate && !timeout;
- clearTimeout(timeout);
- timeout = setTimeout(later, wait);
- if (callNow) result = func.apply(context, args);
- return result;
- };
- };
- // Returns a function that will be executed at most one time, no matter how
- // often you call it. Useful for lazy initialization.
- _.once = function(func) {
- var ran = false, memo;
- return function() {
- if (ran) return memo;
- ran = true;
- memo = func.apply(this, arguments);
- func = null;
- return memo;
- };
- };
- // Returns the first function passed as an argument to the second,
- // allowing you to adjust arguments, run code before and after, and
- // conditionally execute the original function.
- _.wrap = function(func, wrapper) {
- return function() {
- var args = [func];
- push.apply(args, arguments);
- return wrapper.apply(this, args);
- };
- };
- // Returns a function that is the composition of a list of functions, each
- // consuming the return value of the function that follows.
- _.compose = function() {
- var funcs = arguments;
- return function() {
- var args = arguments;
- for (var i = funcs.length - 1; i >= 0; i--) {
- args = [funcs[i].apply(this, args)];
- }
- return args[0];
- };
- };
- // Returns a function that will only be executed after being called N times.
- _.after = function(times, func) {
- if (times <= 0) return func();
- return function() {
- if (--times < 1) {
- return func.apply(this, arguments);
- }
- };
- };
- // Object Functions
- // ----------------
- // Retrieve the names of an object's properties.
- // Delegates to **ECMAScript 5**'s native `Object.keys`
- _.keys = nativeKeys || function(obj) {
- if (obj !== Object(obj)) throw new TypeError('Invalid object');
- var keys = [];
- for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
- return keys;
- };
- // Retrieve the values of an object's properties.
- _.values = function(obj) {
- var values = [];
- for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
- return values;
- };
- // Convert an object into a list of `[key, value]` pairs.
- _.pairs = function(obj) {
- var pairs = [];
- for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
- return pairs;
- };
- // Invert the keys and values of an object. The values must be serializable.
- _.invert = function(obj) {
- var result = {};
- for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
- return result;
- };
- // Return a sorted list of the function names available on the object.
- // Aliased as `methods`
- _.functions = _.methods = function(obj) {
- var names = [];
- for (var key in obj) {
- if (_.isFunction(obj[key])) names.push(key);
- }
- return names.sort();
- };
- // Extend a given object with all the properties in passed-in object(s).
- _.extend = function(obj) {
- each(slice.call(arguments, 1), function(source) {
- if (source) {
- for (var prop in source) {
- obj[prop] = source[prop];
- }
- }
- });
- return obj;
- };
- // Return a copy of the object only containing the whitelisted properties.
- _.pick = function(obj) {
- var copy = {};
- var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
- each(keys, function(key) {
- if (key in obj) copy[key] = obj[key];
- });
- return copy;
- };
- // Return a copy of the object without the blacklisted properties.
- _.omit = function(obj) {
- var copy = {};
- var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
- for (var key in obj) {
- if (!_.contains(keys, key)) copy[key] = obj[key];
- }
- return copy;
- };
- // Fill in a given object with default properties.
- _.defaults = function(obj) {
- each(slice.call(arguments, 1), function(source) {
- if (source) {
- for (var prop in source) {
- if (obj[prop] == null) obj[prop] = source[prop];
- }
- }
- });
- return obj;
- };
- // Create a (shallow-cloned) duplicate of an object.
- _.clone = function(obj) {
- if (!_.isObject(obj)) return obj;
- return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
- };
- // Invokes interceptor with the obj, and then returns obj.
- // The primary purpose of this method is to "tap into" a method chain, in
- // order to perform operations on intermediate results within the chain.
- _.tap = function(obj, interceptor) {
- interceptor(obj);
- return obj;
- };
- // Internal recursive comparison function for `isEqual`.
- var eq = function(a, b, aStack, bStack) {
- // Identical objects are equal. `0 === -0`, but they aren't identical.
- // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
- if (a === b) return a !== 0 || 1 / a == 1 / b;
- // A strict comparison is necessary because `null == undefined`.
- if (a == null || b == null) return a === b;
- // Unwrap any wrapped objects.
- if (a instanceof _) a = a._wrapped;
- if (b instanceof _) b = b._wrapped;
- // Compare `[[Class]]` names.
- var className = toString.call(a);
- if (className != toString.call(b)) return false;
- switch (className) {
- // Strings, numbers, dates, and booleans are compared by value.
- case '[object String]':
- // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
- // equivalent to `new String("5")`.
- return a == String(b);
- case '[object Number]':
- // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
- // other numeric values.
- return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
- case '[object Date]':
- case '[object Boolean]':
- // Coerce dates and booleans to numeric primitive values. Dates are compared by their
- // millisecond representations. Note that invalid dates with millisecond representations
- // of `NaN` are not equivalent.
- return +a == +b;
- // RegExps are compared by their source patterns and flags.
- case '[object RegExp]':
- return a.source == b.source &&
- a.global == b.global &&
- a.multiline == b.multiline &&
- a.ignoreCase == b.ignoreCase;
- }
- if (typeof a != 'object' || typeof b != 'object') return false;
- // Assume equality for cyclic structures. The algorithm for detecting cyclic
- // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
- var length = aStack.length;
- while (length--) {
- // Linear search. Performance is inversely proportional to the number of
- // unique nested structures.
- if (aStack[length] == a) return bStack[length] == b;
- }
- // Add the first object to the stack of traversed objects.
- aStack.push(a);
- bStack.push(b);
- var size = 0, result = true;
- // Recursively compare objects and arrays.
- if (className == '[object Array]') {
- // Compare array lengths to determine if a deep comparison is necessary.
- size = a.length;
- result = size == b.length;
- if (result) {
- // Deep compare the contents, ignoring non-numeric properties.
- while (size--) {
- if (!(result = eq(a[size], b[size], aStack, bStack))) break;
- }
- }
- } else {
- // Objects with different constructors are not equivalent, but `Object`s
- // from different frames are.
- var aCtor = a.constructor, bCtor = b.constructor;
- if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
- _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
- return false;
- }
- // Deep compare objects.
- for (var key in a) {
- if (_.has(a, key)) {
- // Count the expected number of properties.
- size++;
- // Deep compare each member.
- if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
- }
- }
- // Ensure that both objects contain the same number of properties.
- if (result) {
- for (key in b) {
- if (_.has(b, key) && !(size--)) break;
- }
- result = !size;
- }
- }
- // Remove the first object from the stack of traversed objects.
- aStack.pop();
- bStack.pop();
- return result;
- };
- // Perform a deep comparison to check if two objects are equal.
- _.isEqual = function(a, b) {
- return eq(a, b, [], []);
- };
- // Is a given array, string, or object empty?
- // An "empty" object has no enumerable own-properties.
- _.isEmpty = function(obj) {
- if (obj == null) return true;
- if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
- for (var key in obj) if (_.has(obj, key)) return false;
- return true;
- };
- // Is a given value a DOM element?
- _.isElement = function(obj) {
- return !!(obj && obj.nodeType === 1);
- };
- // Is a given value an array?
- // Delegates to ECMA5's native Array.isArray
- _.isArray = nativeIsArray || function(obj) {
- return toString.call(obj) == '[object Array]';
- };
- // Is a given variable an object?
- _.isObject = function(obj) {
- return obj === Object(obj);
- };
- // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
- each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
- _['is' + name] = function(obj) {
- return toString.call(obj) == '[object ' + name + ']';
- };
- });
- // Define a fallback version of the method in browsers (ahem, IE), where
- // there isn't any inspectable "Arguments" type.
- if (!_.isArguments(arguments)) {
- _.isArguments = function(obj) {
- return !!(obj && _.has(obj, 'callee'));
- };
- }
- // Optimize `isFunction` if appropriate.
- if (typeof (/./) !== 'function') {
- _.isFunction = function(obj) {
- return typeof obj === 'function';
- };
- }
- // Is a given object a finite number?
- _.isFinite = function(obj) {
- return isFinite(obj) && !isNaN(parseFloat(obj));
- };
- // Is the given value `NaN`? (NaN is the only number which does not equal itself).
- _.isNaN = function(obj) {
- return _.isNumber(obj) && obj != +obj;
- };
- // Is a given value a boolean?
- _.isBoolean = function(obj) {
- return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
- };
- // Is a given value equal to null?
- _.isNull = function(obj) {
- return obj === null;
- };
- // Is a given variable undefined?
- _.isUndefined = function(obj) {
- return obj === void 0;
- };
- // Shortcut function for checking if an object has a given property directly
- // on itself (in other words, not on a prototype).
- _.has = function(obj, key) {
- return hasOwnProperty.call(obj, key);
- };
- // Utility Functions
- // -----------------
- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
- // previous owner. Returns a reference to the Underscore object.
- _.noConflict = function() {
- root._ = previousUnderscore;
- return this;
- };
- // Keep the identity function around for default iterators.
- _.identity = function(value) {
- return value;
- };
- // Run a function **n** times.
- _.times = function(n, iterator, context) {
- var accum = Array(n);
- for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
- return accum;
- };
- // Return a random integer between min and max (inclusive).
- _.random = function(min, max) {
- if (max == null) {
- max = min;
- min = 0;
- }
- return min + Math.floor(Math.random() * (max - min + 1));
- };
- // List of HTML entities for escaping.
- var entityMap = {
- escape: {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": ''',
- '/': '/'
- }
- };
- entityMap.unescape = _.invert(entityMap.escape);
- // Regexes containing the keys and values listed immediately above.
- var entityRegexes = {
- escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
- unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
- };
- // Functions for escaping and unescaping strings to/from HTML interpolation.
- _.each(['escape', 'unescape'], function(method) {
- _[method] = function(string) {
- if (string == null) return '';
- return ('' + string).replace(entityRegexes[method], function(match) {
- return entityMap[method][match];
- });
- };
- });
- // If the value of the named property is a function then invoke it;
- // otherwise, return it.
- _.result = function(object, property) {
- if (object == null) return null;
- var value = object[property];
- return _.isFunction(value) ? value.call(object) : value;
- };
- // Add your own custom functions to the Underscore object.
- _.mixin = function(obj) {
- each(_.functions(obj), function(name){
- var func = _[name] = obj[name];
- _.prototype[name] = function() {
- var args = [this._wrapped];
- push.apply(args, arguments);
- return result.call(this, func.apply(_, args));
- };
- });
- };
- // Generate a unique integer id (unique within the entire client session).
- // Useful for temporary DOM ids.
- var idCounter = 0;
- _.uniqueId = function(prefix) {
- var id = ++idCounter + '';
- return prefix ? prefix + id : id;
- };
- // By default, Underscore uses ERB-style template delimiters, change the
- // following template settings to use alternative delimiters.
- _.templateSettings = {
- evaluate : /<%([\s\S]+?)%>/g,
- interpolate : /<%=([\s\S]+?)%>/g,
- escape : /<%-([\s\S]+?)%>/g
- };
- // When customizing `templateSettings`, if you don't want to define an
- // interpolation, evaluation or escaping regex, we need one that is
- // guaranteed not to match.
- var noMatch = /(.)^/;
- // Certain characters need to be escaped so that they can be put into a
- // string literal.
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\t': 't',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
- var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- _.template = function(text, data, settings) {
- var render;
- settings = _.defaults({}, settings, _.templateSettings);
- // Combine delimiters into one regular expression via alternation.
- var matcher = new RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
- // Compile the template source, escaping string literals appropriately.
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset)
- .replace(escaper, function(match) { return '\\' + escapes[match]; });
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- }
- if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- }
- if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
- index = offset + match.length;
- return match;
- });
- source += "';\n";
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + "return __p;\n";
- try {
- render = new Function(settings.variable || 'obj', '_', source);
- } catch (e) {
- e.source = source;
- throw e;
- }
- if (data) return render(data, _);
- var template = function(data) {
- return render.call(this, data, _);
- };
- // Provide the compiled function source as a convenience for precompilation.
- template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
- return template;
- };
- // Add a "chain" function, which will delegate to the wrapper.
- _.chain = function(obj) {
- return _(obj).chain();
- };
- // OOP
- // ---------------
- // If Underscore is called as a function, it returns a wrapped object that
- // can be used OO-style. This wrapper holds altered versions of all the
- // underscore functions. Wrapped objects may be chained.
- // Helper function to continue chaining intermediate results.
- var result = function(obj) {
- return this._chain ? _(obj).chain() : obj;
- };
- // Add all of the Underscore functions to the wrapper object.
- _.mixin(_);
- // Add all mutator Array functions to the wrapper.
- each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- var obj = this._wrapped;
- method.apply(obj, arguments);
- if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
- return result.call(this, obj);
- };
- });
- // Add all accessor Array functions to the wrapper.
- each(['concat', 'join', 'slice'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- return result.call(this, method.apply(this._wrapped, arguments));
- };
- });
- _.extend(_.prototype, {
- // Start chaining a wrapped Underscore object.
- chain: function() {
- this._chain = true;
- return this;
- },
- // Extracts the result from a wrapped and chained object.
- value: function() {
- return this._wrapped;
- }
- });
- }).call(this);
- },{}],119:[function(require,module,exports){
- exports.none = Object.create({
- value: function() {
- throw new Error('Called value on none');
- },
- isNone: function() {
- return true;
- },
- isSome: function() {
- return false;
- },
- map: function() {
- return exports.none;
- },
- flatMap: function() {
- return exports.none;
- },
- toArray: function() {
- return [];
- },
- orElse: callOrReturn,
- valueOrElse: callOrReturn
- });
- function callOrReturn(value) {
- if (typeof(value) == "function") {
- return value();
- } else {
- return value;
- }
- }
- exports.some = function(value) {
- return new Some(value);
- };
- var Some = function(value) {
- this._value = value;
- };
- Some.prototype.value = function() {
- return this._value;
- };
- Some.prototype.isNone = function() {
- return false;
- };
- Some.prototype.isSome = function() {
- return true;
- };
- Some.prototype.map = function(func) {
- return new Some(func(this._value));
- };
- Some.prototype.flatMap = function(func) {
- return func(this._value);
- };
- Some.prototype.toArray = function() {
- return [this._value];
- };
- Some.prototype.orElse = function(value) {
- return this;
- };
- Some.prototype.valueOrElse = function(value) {
- return this._value;
- };
- exports.isOption = function(value) {
- return value === exports.none || value instanceof Some;
- };
- exports.fromNullable = function(value) {
- if (value == null) {
- return exports.none;
- }
- return new Some(value);
- }
- },{}],120:[function(require,module,exports){
- // Top level file is just a mixin of submodules & constants
- 'use strict';
- var assign = require('./lib/utils/common').assign;
- var deflate = require('./lib/deflate');
- var inflate = require('./lib/inflate');
- var constants = require('./lib/zlib/constants');
- var pako = {};
- assign(pako, deflate, inflate, constants);
- module.exports = pako;
- },{"./lib/deflate":121,"./lib/inflate":122,"./lib/utils/common":123,"./lib/zlib/constants":126}],121:[function(require,module,exports){
- 'use strict';
- var zlib_deflate = require('./zlib/deflate');
- var utils = require('./utils/common');
- var strings = require('./utils/strings');
- var msg = require('./zlib/messages');
- var ZStream = require('./zlib/zstream');
- var toString = Object.prototype.toString;
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- var Z_NO_FLUSH = 0;
- var Z_FINISH = 4;
- var Z_OK = 0;
- var Z_STREAM_END = 1;
- var Z_SYNC_FLUSH = 2;
- var Z_DEFAULT_COMPRESSION = -1;
- var Z_DEFAULT_STRATEGY = 0;
- var Z_DEFLATED = 8;
- /* ===========================================================================*/
- /**
- * class Deflate
- *
- * Generic JS-style wrapper for zlib calls. If you don't need
- * streaming behaviour - use more simple functions: [[deflate]],
- * [[deflateRaw]] and [[gzip]].
- **/
- /* internal
- * Deflate.chunks -> Array
- *
- * Chunks of output data, if [[Deflate#onData]] not overriden.
- **/
- /**
- * Deflate.result -> Uint8Array|Array
- *
- * Compressed result, generated by default [[Deflate#onData]]
- * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
- * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
- * push a chunk with explicit flush (call [[Deflate#push]] with
- * `Z_SYNC_FLUSH` param).
- **/
- /**
- * Deflate.err -> Number
- *
- * Error code after deflate finished. 0 (Z_OK) on success.
- * You will not need it in real life, because deflate errors
- * are possible only on wrong options or bad `onData` / `onEnd`
- * custom handlers.
- **/
- /**
- * Deflate.msg -> String
- *
- * Error message, if [[Deflate.err]] != 0
- **/
- /**
- * new Deflate(options)
- * - options (Object): zlib deflate options.
- *
- * Creates new deflator instance with specified params. Throws exception
- * on bad params. Supported options:
- *
- * - `level`
- * - `windowBits`
- * - `memLevel`
- * - `strategy`
- * - `dictionary`
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information on these.
- *
- * Additional options, for internal needs:
- *
- * - `chunkSize` - size of generated data chunks (16K by default)
- * - `raw` (Boolean) - do raw deflate
- * - `gzip` (Boolean) - create gzip wrapper
- * - `to` (String) - if equal to 'string', then result will be "binary string"
- * (each char code [0..255])
- * - `header` (Object) - custom header for gzip
- * - `text` (Boolean) - true if compressed data believed to be text
- * - `time` (Number) - modification time, unix timestamp
- * - `os` (Number) - operation system code
- * - `extra` (Array) - array of bytes with extra data (max 65536)
- * - `name` (String) - file name (binary string)
- * - `comment` (String) - comment (binary string)
- * - `hcrc` (Boolean) - true if header crc should be added
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
- *
- * var deflate = new pako.Deflate({ level: 3});
- *
- * deflate.push(chunk1, false);
- * deflate.push(chunk2, true); // true -> last chunk
- *
- * if (deflate.err) { throw new Error(deflate.err); }
- *
- * console.log(deflate.result);
- * ```
- **/
- function Deflate(options) {
- if (!(this instanceof Deflate)) return new Deflate(options);
- this.options = utils.assign({
- level: Z_DEFAULT_COMPRESSION,
- method: Z_DEFLATED,
- chunkSize: 16384,
- windowBits: 15,
- memLevel: 8,
- strategy: Z_DEFAULT_STRATEGY,
- to: ''
- }, options || {});
- var opt = this.options;
- if (opt.raw && (opt.windowBits > 0)) {
- opt.windowBits = -opt.windowBits;
- }
- else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
- opt.windowBits += 16;
- }
- this.err = 0; // error code, if happens (0 = Z_OK)
- this.msg = ''; // error message
- this.ended = false; // used to avoid multiple onEnd() calls
- this.chunks = []; // chunks of compressed data
- this.strm = new ZStream();
- this.strm.avail_out = 0;
- var status = zlib_deflate.deflateInit2(
- this.strm,
- opt.level,
- opt.method,
- opt.windowBits,
- opt.memLevel,
- opt.strategy
- );
- if (status !== Z_OK) {
- throw new Error(msg[status]);
- }
- if (opt.header) {
- zlib_deflate.deflateSetHeader(this.strm, opt.header);
- }
- if (opt.dictionary) {
- var dict;
- // Convert data if needed
- if (typeof opt.dictionary === 'string') {
- // If we need to compress text, change encoding to utf8.
- dict = strings.string2buf(opt.dictionary);
- } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
- dict = new Uint8Array(opt.dictionary);
- } else {
- dict = opt.dictionary;
- }
- status = zlib_deflate.deflateSetDictionary(this.strm, dict);
- if (status !== Z_OK) {
- throw new Error(msg[status]);
- }
- this._dict_set = true;
- }
- }
- /**
- * Deflate#push(data[, mode]) -> Boolean
- * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
- * converted to utf8 byte sequence.
- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
- *
- * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
- * new compressed chunks. Returns `true` on success. The last data block must have
- * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
- * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
- * can use mode Z_SYNC_FLUSH, keeping the compression context.
- *
- * On fail call [[Deflate#onEnd]] with error code and return false.
- *
- * We strongly recommend to use `Uint8Array` on input for best speed (output
- * array format is detected automatically). Also, don't skip last param and always
- * use the same type in your code (boolean or number). That will improve JS speed.
- *
- * For regular `Array`-s make sure all elements are [0..255].
- *
- * ##### Example
- *
- * ```javascript
- * push(chunk, false); // push one of data chunks
- * ...
- * push(chunk, true); // push last chunk
- * ```
- **/
- Deflate.prototype.push = function (data, mode) {
- var strm = this.strm;
- var chunkSize = this.options.chunkSize;
- var status, _mode;
- if (this.ended) { return false; }
- _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
- // Convert data if needed
- if (typeof data === 'string') {
- // If we need to compress text, change encoding to utf8.
- strm.input = strings.string2buf(data);
- } else if (toString.call(data) === '[object ArrayBuffer]') {
- strm.input = new Uint8Array(data);
- } else {
- strm.input = data;
- }
- strm.next_in = 0;
- strm.avail_in = strm.input.length;
- do {
- if (strm.avail_out === 0) {
- strm.output = new utils.Buf8(chunkSize);
- strm.next_out = 0;
- strm.avail_out = chunkSize;
- }
- status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
- if (status !== Z_STREAM_END && status !== Z_OK) {
- this.onEnd(status);
- this.ended = true;
- return false;
- }
- if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
- if (this.options.to === 'string') {
- this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
- } else {
- this.onData(utils.shrinkBuf(strm.output, strm.next_out));
- }
- }
- } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
- // Finalize on the last chunk.
- if (_mode === Z_FINISH) {
- status = zlib_deflate.deflateEnd(this.strm);
- this.onEnd(status);
- this.ended = true;
- return status === Z_OK;
- }
- // callback interim results if Z_SYNC_FLUSH.
- if (_mode === Z_SYNC_FLUSH) {
- this.onEnd(Z_OK);
- strm.avail_out = 0;
- return true;
- }
- return true;
- };
- /**
- * Deflate#onData(chunk) -> Void
- * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
- * on js engine support. When string output requested, each chunk
- * will be string.
- *
- * By default, stores data blocks in `chunks[]` property and glue
- * those in `onEnd`. Override this handler, if you need another behaviour.
- **/
- Deflate.prototype.onData = function (chunk) {
- this.chunks.push(chunk);
- };
- /**
- * Deflate#onEnd(status) -> Void
- * - status (Number): deflate status. 0 (Z_OK) on success,
- * other if not.
- *
- * Called once after you tell deflate that the input stream is
- * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
- * or if an error happened. By default - join collected chunks,
- * free memory and fill `results` / `err` properties.
- **/
- Deflate.prototype.onEnd = function (status) {
- // On success - join
- if (status === Z_OK) {
- if (this.options.to === 'string') {
- this.result = this.chunks.join('');
- } else {
- this.result = utils.flattenChunks(this.chunks);
- }
- }
- this.chunks = [];
- this.err = status;
- this.msg = this.strm.msg;
- };
- /**
- * deflate(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to compress.
- * - options (Object): zlib deflate options.
- *
- * Compress `data` with deflate algorithm and `options`.
- *
- * Supported options are:
- *
- * - level
- * - windowBits
- * - memLevel
- * - strategy
- * - dictionary
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information on these.
- *
- * Sugar (options):
- *
- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
- * negative windowBits implicitly.
- * - `to` (String) - if equal to 'string', then result will be "binary string"
- * (each char code [0..255])
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
- *
- * console.log(pako.deflate(data));
- * ```
- **/
- function deflate(input, options) {
- var deflator = new Deflate(options);
- deflator.push(input, true);
- // That will never happens, if you don't cheat with options :)
- if (deflator.err) { throw deflator.msg; }
- return deflator.result;
- }
- /**
- * deflateRaw(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to compress.
- * - options (Object): zlib deflate options.
- *
- * The same as [[deflate]], but creates raw data, without wrapper
- * (header and adler32 crc).
- **/
- function deflateRaw(input, options) {
- options = options || {};
- options.raw = true;
- return deflate(input, options);
- }
- /**
- * gzip(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to compress.
- * - options (Object): zlib deflate options.
- *
- * The same as [[deflate]], but create gzip wrapper instead of
- * deflate one.
- **/
- function gzip(input, options) {
- options = options || {};
- options.gzip = true;
- return deflate(input, options);
- }
- exports.Deflate = Deflate;
- exports.deflate = deflate;
- exports.deflateRaw = deflateRaw;
- exports.gzip = gzip;
- },{"./utils/common":123,"./utils/strings":124,"./zlib/deflate":128,"./zlib/messages":133,"./zlib/zstream":135}],122:[function(require,module,exports){
- 'use strict';
- var zlib_inflate = require('./zlib/inflate');
- var utils = require('./utils/common');
- var strings = require('./utils/strings');
- var c = require('./zlib/constants');
- var msg = require('./zlib/messages');
- var ZStream = require('./zlib/zstream');
- var GZheader = require('./zlib/gzheader');
- var toString = Object.prototype.toString;
- /**
- * class Inflate
- *
- * Generic JS-style wrapper for zlib calls. If you don't need
- * streaming behaviour - use more simple functions: [[inflate]]
- * and [[inflateRaw]].
- **/
- /* internal
- * inflate.chunks -> Array
- *
- * Chunks of output data, if [[Inflate#onData]] not overriden.
- **/
- /**
- * Inflate.result -> Uint8Array|Array|String
- *
- * Uncompressed result, generated by default [[Inflate#onData]]
- * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
- * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
- * push a chunk with explicit flush (call [[Inflate#push]] with
- * `Z_SYNC_FLUSH` param).
- **/
- /**
- * Inflate.err -> Number
- *
- * Error code after inflate finished. 0 (Z_OK) on success.
- * Should be checked if broken data possible.
- **/
- /**
- * Inflate.msg -> String
- *
- * Error message, if [[Inflate.err]] != 0
- **/
- /**
- * new Inflate(options)
- * - options (Object): zlib inflate options.
- *
- * Creates new inflator instance with specified params. Throws exception
- * on bad params. Supported options:
- *
- * - `windowBits`
- * - `dictionary`
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information on these.
- *
- * Additional options, for internal needs:
- *
- * - `chunkSize` - size of generated data chunks (16K by default)
- * - `raw` (Boolean) - do raw inflate
- * - `to` (String) - if equal to 'string', then result will be converted
- * from utf8 to utf16 (javascript) string. When string output requested,
- * chunk length can differ from `chunkSize`, depending on content.
- *
- * By default, when no options set, autodetect deflate/gzip data format via
- * wrapper header.
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
- *
- * var inflate = new pako.Inflate({ level: 3});
- *
- * inflate.push(chunk1, false);
- * inflate.push(chunk2, true); // true -> last chunk
- *
- * if (inflate.err) { throw new Error(inflate.err); }
- *
- * console.log(inflate.result);
- * ```
- **/
- function Inflate(options) {
- if (!(this instanceof Inflate)) return new Inflate(options);
- this.options = utils.assign({
- chunkSize: 16384,
- windowBits: 0,
- to: ''
- }, options || {});
- var opt = this.options;
- // Force window size for `raw` data, if not set directly,
- // because we have no header for autodetect.
- if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
- opt.windowBits = -opt.windowBits;
- if (opt.windowBits === 0) { opt.windowBits = -15; }
- }
- // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
- if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
- !(options && options.windowBits)) {
- opt.windowBits += 32;
- }
- // Gzip header has no info about windows size, we can do autodetect only
- // for deflate. So, if window size not set, force it to max when gzip possible
- if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
- // bit 3 (16) -> gzipped data
- // bit 4 (32) -> autodetect gzip/deflate
- if ((opt.windowBits & 15) === 0) {
- opt.windowBits |= 15;
- }
- }
- this.err = 0; // error code, if happens (0 = Z_OK)
- this.msg = ''; // error message
- this.ended = false; // used to avoid multiple onEnd() calls
- this.chunks = []; // chunks of compressed data
- this.strm = new ZStream();
- this.strm.avail_out = 0;
- var status = zlib_inflate.inflateInit2(
- this.strm,
- opt.windowBits
- );
- if (status !== c.Z_OK) {
- throw new Error(msg[status]);
- }
- this.header = new GZheader();
- zlib_inflate.inflateGetHeader(this.strm, this.header);
- }
- /**
- * Inflate#push(data[, mode]) -> Boolean
- * - data (Uint8Array|Array|ArrayBuffer|String): input data
- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
- *
- * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
- * new output chunks. Returns `true` on success. The last data block must have
- * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
- * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
- * can use mode Z_SYNC_FLUSH, keeping the decompression context.
- *
- * On fail call [[Inflate#onEnd]] with error code and return false.
- *
- * We strongly recommend to use `Uint8Array` on input for best speed (output
- * format is detected automatically). Also, don't skip last param and always
- * use the same type in your code (boolean or number). That will improve JS speed.
- *
- * For regular `Array`-s make sure all elements are [0..255].
- *
- * ##### Example
- *
- * ```javascript
- * push(chunk, false); // push one of data chunks
- * ...
- * push(chunk, true); // push last chunk
- * ```
- **/
- Inflate.prototype.push = function (data, mode) {
- var strm = this.strm;
- var chunkSize = this.options.chunkSize;
- var dictionary = this.options.dictionary;
- var status, _mode;
- var next_out_utf8, tail, utf8str;
- var dict;
- // Flag to properly process Z_BUF_ERROR on testing inflate call
- // when we check that all output data was flushed.
- var allowBufError = false;
- if (this.ended) { return false; }
- _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
- // Convert data if needed
- if (typeof data === 'string') {
- // Only binary strings can be decompressed on practice
- strm.input = strings.binstring2buf(data);
- } else if (toString.call(data) === '[object ArrayBuffer]') {
- strm.input = new Uint8Array(data);
- } else {
- strm.input = data;
- }
- strm.next_in = 0;
- strm.avail_in = strm.input.length;
- do {
- if (strm.avail_out === 0) {
- strm.output = new utils.Buf8(chunkSize);
- strm.next_out = 0;
- strm.avail_out = chunkSize;
- }
- status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
- if (status === c.Z_NEED_DICT && dictionary) {
- // Convert data if needed
- if (typeof dictionary === 'string') {
- dict = strings.string2buf(dictionary);
- } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
- dict = new Uint8Array(dictionary);
- } else {
- dict = dictionary;
- }
- status = zlib_inflate.inflateSetDictionary(this.strm, dict);
- }
- if (status === c.Z_BUF_ERROR && allowBufError === true) {
- status = c.Z_OK;
- allowBufError = false;
- }
- if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
- this.onEnd(status);
- this.ended = true;
- return false;
- }
- if (strm.next_out) {
- if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
- if (this.options.to === 'string') {
- next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
- tail = strm.next_out - next_out_utf8;
- utf8str = strings.buf2string(strm.output, next_out_utf8);
- // move tail
- strm.next_out = tail;
- strm.avail_out = chunkSize - tail;
- if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
- this.onData(utf8str);
- } else {
- this.onData(utils.shrinkBuf(strm.output, strm.next_out));
- }
- }
- }
- // When no more input data, we should check that internal inflate buffers
- // are flushed. The only way to do it when avail_out = 0 - run one more
- // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
- // Here we set flag to process this error properly.
- //
- // NOTE. Deflate does not return error in this case and does not needs such
- // logic.
- if (strm.avail_in === 0 && strm.avail_out === 0) {
- allowBufError = true;
- }
- } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
- if (status === c.Z_STREAM_END) {
- _mode = c.Z_FINISH;
- }
- // Finalize on the last chunk.
- if (_mode === c.Z_FINISH) {
- status = zlib_inflate.inflateEnd(this.strm);
- this.onEnd(status);
- this.ended = true;
- return status === c.Z_OK;
- }
- // callback interim results if Z_SYNC_FLUSH.
- if (_mode === c.Z_SYNC_FLUSH) {
- this.onEnd(c.Z_OK);
- strm.avail_out = 0;
- return true;
- }
- return true;
- };
- /**
- * Inflate#onData(chunk) -> Void
- * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
- * on js engine support. When string output requested, each chunk
- * will be string.
- *
- * By default, stores data blocks in `chunks[]` property and glue
- * those in `onEnd`. Override this handler, if you need another behaviour.
- **/
- Inflate.prototype.onData = function (chunk) {
- this.chunks.push(chunk);
- };
- /**
- * Inflate#onEnd(status) -> Void
- * - status (Number): inflate status. 0 (Z_OK) on success,
- * other if not.
- *
- * Called either after you tell inflate that the input stream is
- * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
- * or if an error happened. By default - join collected chunks,
- * free memory and fill `results` / `err` properties.
- **/
- Inflate.prototype.onEnd = function (status) {
- // On success - join
- if (status === c.Z_OK) {
- if (this.options.to === 'string') {
- // Glue & convert here, until we teach pako to send
- // utf8 alligned strings to onData
- this.result = this.chunks.join('');
- } else {
- this.result = utils.flattenChunks(this.chunks);
- }
- }
- this.chunks = [];
- this.err = status;
- this.msg = this.strm.msg;
- };
- /**
- * inflate(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to decompress.
- * - options (Object): zlib inflate options.
- *
- * Decompress `data` with inflate/ungzip and `options`. Autodetect
- * format via wrapper header by default. That's why we don't provide
- * separate `ungzip` method.
- *
- * Supported options are:
- *
- * - windowBits
- *
- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
- * for more information.
- *
- * Sugar (options):
- *
- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
- * negative windowBits implicitly.
- * - `to` (String) - if equal to 'string', then result will be converted
- * from utf8 to utf16 (javascript) string. When string output requested,
- * chunk length can differ from `chunkSize`, depending on content.
- *
- *
- * ##### Example:
- *
- * ```javascript
- * var pako = require('pako')
- * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
- * , output;
- *
- * try {
- * output = pako.inflate(input);
- * } catch (err)
- * console.log(err);
- * }
- * ```
- **/
- function inflate(input, options) {
- var inflator = new Inflate(options);
- inflator.push(input, true);
- // That will never happens, if you don't cheat with options :)
- if (inflator.err) { throw inflator.msg; }
- return inflator.result;
- }
- /**
- * inflateRaw(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to decompress.
- * - options (Object): zlib inflate options.
- *
- * The same as [[inflate]], but creates raw data, without wrapper
- * (header and adler32 crc).
- **/
- function inflateRaw(input, options) {
- options = options || {};
- options.raw = true;
- return inflate(input, options);
- }
- /**
- * ungzip(data[, options]) -> Uint8Array|Array|String
- * - data (Uint8Array|Array|String): input data to decompress.
- * - options (Object): zlib inflate options.
- *
- * Just shortcut to [[inflate]], because it autodetects format
- * by header.content. Done for convenience.
- **/
- exports.Inflate = Inflate;
- exports.inflate = inflate;
- exports.inflateRaw = inflateRaw;
- exports.ungzip = inflate;
- },{"./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){
- 'use strict';
- var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
- (typeof Uint16Array !== 'undefined') &&
- (typeof Int32Array !== 'undefined');
- exports.assign = function (obj /*from1, from2, from3, ...*/) {
- var sources = Array.prototype.slice.call(arguments, 1);
- while (sources.length) {
- var source = sources.shift();
- if (!source) { continue; }
- if (typeof source !== 'object') {
- throw new TypeError(source + 'must be non-object');
- }
- for (var p in source) {
- if (source.hasOwnProperty(p)) {
- obj[p] = source[p];
- }
- }
- }
- return obj;
- };
- // reduce buffer size, avoiding mem copy
- exports.shrinkBuf = function (buf, size) {
- if (buf.length === size) { return buf; }
- if (buf.subarray) { return buf.subarray(0, size); }
- buf.length = size;
- return buf;
- };
- var fnTyped = {
- arraySet: function (dest, src, src_offs, len, dest_offs) {
- if (src.subarray && dest.subarray) {
- dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
- return;
- }
- // Fallback to ordinary array
- for (var i = 0; i < len; i++) {
- dest[dest_offs + i] = src[src_offs + i];
- }
- },
- // Join array of chunks to single array.
- flattenChunks: function (chunks) {
- var i, l, len, pos, chunk, result;
- // calculate data length
- len = 0;
- for (i = 0, l = chunks.length; i < l; i++) {
- len += chunks[i].length;
- }
- // join chunks
- result = new Uint8Array(len);
- pos = 0;
- for (i = 0, l = chunks.length; i < l; i++) {
- chunk = chunks[i];
- result.set(chunk, pos);
- pos += chunk.length;
- }
- return result;
- }
- };
- var fnUntyped = {
- arraySet: function (dest, src, src_offs, len, dest_offs) {
- for (var i = 0; i < len; i++) {
- dest[dest_offs + i] = src[src_offs + i];
- }
- },
- // Join array of chunks to single array.
- flattenChunks: function (chunks) {
- return [].concat.apply([], chunks);
- }
- };
- // Enable/Disable typed arrays use, for testing
- //
- exports.setTyped = function (on) {
- if (on) {
- exports.Buf8 = Uint8Array;
- exports.Buf16 = Uint16Array;
- exports.Buf32 = Int32Array;
- exports.assign(exports, fnTyped);
- } else {
- exports.Buf8 = Array;
- exports.Buf16 = Array;
- exports.Buf32 = Array;
- exports.assign(exports, fnUntyped);
- }
- };
- exports.setTyped(TYPED_OK);
- },{}],124:[function(require,module,exports){
- // String encode/decode helpers
- 'use strict';
- var utils = require('./common');
- // Quick check if we can use fast array to bin string conversion
- //
- // - apply(Array) can fail on Android 2.2
- // - apply(Uint8Array) can fail on iOS 5.1 Safary
- //
- var STR_APPLY_OK = true;
- var STR_APPLY_UIA_OK = true;
- try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
- try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
- // Table with utf8 lengths (calculated by first byte of sequence)
- // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
- // because max possible codepoint is 0x10ffff
- var _utf8len = new utils.Buf8(256);
- for (var q = 0; q < 256; q++) {
- _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
- }
- _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
- // convert string to array (typed, when possible)
- exports.string2buf = function (str) {
- var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
- // count binary size
- for (m_pos = 0; m_pos < str_len; m_pos++) {
- c = str.charCodeAt(m_pos);
- if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
- c2 = str.charCodeAt(m_pos + 1);
- if ((c2 & 0xfc00) === 0xdc00) {
- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
- m_pos++;
- }
- }
- buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
- }
- // allocate buffer
- buf = new utils.Buf8(buf_len);
- // convert
- for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
- c = str.charCodeAt(m_pos);
- if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
- c2 = str.charCodeAt(m_pos + 1);
- if ((c2 & 0xfc00) === 0xdc00) {
- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
- m_pos++;
- }
- }
- if (c < 0x80) {
- /* one byte */
- buf[i++] = c;
- } else if (c < 0x800) {
- /* two bytes */
- buf[i++] = 0xC0 | (c >>> 6);
- buf[i++] = 0x80 | (c & 0x3f);
- } else if (c < 0x10000) {
- /* three bytes */
- buf[i++] = 0xE0 | (c >>> 12);
- buf[i++] = 0x80 | (c >>> 6 & 0x3f);
- buf[i++] = 0x80 | (c & 0x3f);
- } else {
- /* four bytes */
- buf[i++] = 0xf0 | (c >>> 18);
- buf[i++] = 0x80 | (c >>> 12 & 0x3f);
- buf[i++] = 0x80 | (c >>> 6 & 0x3f);
- buf[i++] = 0x80 | (c & 0x3f);
- }
- }
- return buf;
- };
- // Helper (used in 2 places)
- function buf2binstring(buf, len) {
- // use fallback for big arrays to avoid stack overflow
- if (len < 65537) {
- if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
- return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
- }
- }
- var result = '';
- for (var i = 0; i < len; i++) {
- result += String.fromCharCode(buf[i]);
- }
- return result;
- }
- // Convert byte array to binary string
- exports.buf2binstring = function (buf) {
- return buf2binstring(buf, buf.length);
- };
- // Convert binary string (typed, when possible)
- exports.binstring2buf = function (str) {
- var buf = new utils.Buf8(str.length);
- for (var i = 0, len = buf.length; i < len; i++) {
- buf[i] = str.charCodeAt(i);
- }
- return buf;
- };
- // convert array to string
- exports.buf2string = function (buf, max) {
- var i, out, c, c_len;
- var len = max || buf.length;
- // Reserve max possible length (2 words per char)
- // NB: by unknown reasons, Array is significantly faster for
- // String.fromCharCode.apply than Uint16Array.
- var utf16buf = new Array(len * 2);
- for (out = 0, i = 0; i < len;) {
- c = buf[i++];
- // quick process ascii
- if (c < 0x80) { utf16buf[out++] = c; continue; }
- c_len = _utf8len[c];
- // skip 5 & 6 byte codes
- if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
- // apply mask on first byte
- c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
- // join the rest
- while (c_len > 1 && i < len) {
- c = (c << 6) | (buf[i++] & 0x3f);
- c_len--;
- }
- // terminated by end of string?
- if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
- if (c < 0x10000) {
- utf16buf[out++] = c;
- } else {
- c -= 0x10000;
- utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
- utf16buf[out++] = 0xdc00 | (c & 0x3ff);
- }
- }
- return buf2binstring(utf16buf, out);
- };
- // Calculate max possible position in utf8 buffer,
- // that will not break sequence. If that's not possible
- // - (very small limits) return max size as is.
- //
- // buf[] - utf8 bytes array
- // max - length limit (mandatory);
- exports.utf8border = function (buf, max) {
- var pos;
- max = max || buf.length;
- if (max > buf.length) { max = buf.length; }
- // go back from last position, until start of sequence found
- pos = max - 1;
- while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
- // Fuckup - very small and broken sequence,
- // return max, because we should return something anyway.
- if (pos < 0) { return max; }
- // If we came to start of buffer - that means vuffer is too small,
- // return max too.
- if (pos === 0) { return max; }
- return (pos + _utf8len[buf[pos]] > max) ? pos : max;
- };
- },{"./common":123}],125:[function(require,module,exports){
- 'use strict';
- // Note: adler32 takes 12% for level 0 and 2% for level 6.
- // It doesn't worth to make additional optimizationa as in original.
- // Small size is preferable.
- function adler32(adler, buf, len, pos) {
- var s1 = (adler & 0xffff) |0,
- s2 = ((adler >>> 16) & 0xffff) |0,
- n = 0;
- while (len !== 0) {
- // Set limit ~ twice less than 5552, to keep
- // s2 in 31-bits, because we force signed ints.
- // in other case %= will fail.
- n = len > 2000 ? 2000 : len;
- len -= n;
- do {
- s1 = (s1 + buf[pos++]) |0;
- s2 = (s2 + s1) |0;
- } while (--n);
- s1 %= 65521;
- s2 %= 65521;
- }
- return (s1 | (s2 << 16)) |0;
- }
- module.exports = adler32;
- },{}],126:[function(require,module,exports){
- 'use strict';
- module.exports = {
- /* Allowed flush values; see deflate() and inflate() below for details */
- Z_NO_FLUSH: 0,
- Z_PARTIAL_FLUSH: 1,
- Z_SYNC_FLUSH: 2,
- Z_FULL_FLUSH: 3,
- Z_FINISH: 4,
- Z_BLOCK: 5,
- Z_TREES: 6,
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- Z_OK: 0,
- Z_STREAM_END: 1,
- Z_NEED_DICT: 2,
- Z_ERRNO: -1,
- Z_STREAM_ERROR: -2,
- Z_DATA_ERROR: -3,
- //Z_MEM_ERROR: -4,
- Z_BUF_ERROR: -5,
- //Z_VERSION_ERROR: -6,
- /* compression levels */
- Z_NO_COMPRESSION: 0,
- Z_BEST_SPEED: 1,
- Z_BEST_COMPRESSION: 9,
- Z_DEFAULT_COMPRESSION: -1,
- Z_FILTERED: 1,
- Z_HUFFMAN_ONLY: 2,
- Z_RLE: 3,
- Z_FIXED: 4,
- Z_DEFAULT_STRATEGY: 0,
- /* Possible values of the data_type field (though see inflate()) */
- Z_BINARY: 0,
- Z_TEXT: 1,
- //Z_ASCII: 1, // = Z_TEXT (deprecated)
- Z_UNKNOWN: 2,
- /* The deflate compression method */
- Z_DEFLATED: 8
- //Z_NULL: null // Use -1 or null inline, depending on var type
- };
- },{}],127:[function(require,module,exports){
- 'use strict';
- // Note: we can't get significant speed boost here.
- // So write code to minimize size - no pregenerated tables
- // and array tools dependencies.
- // Use ordinary array, since untyped makes no boost here
- function makeTable() {
- var c, table = [];
- for (var n = 0; n < 256; n++) {
- c = n;
- for (var k = 0; k < 8; k++) {
- c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
- }
- table[n] = c;
- }
- return table;
- }
- // Create table on load. Just 255 signed longs. Not a problem.
- var crcTable = makeTable();
- function crc32(crc, buf, len, pos) {
- var t = crcTable,
- end = pos + len;
- crc ^= -1;
- for (var i = pos; i < end; i++) {
- crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
- }
- return (crc ^ (-1)); // >>> 0;
- }
- module.exports = crc32;
- },{}],128:[function(require,module,exports){
- 'use strict';
- var utils = require('../utils/common');
- var trees = require('./trees');
- var adler32 = require('./adler32');
- var crc32 = require('./crc32');
- var msg = require('./messages');
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- /* Allowed flush values; see deflate() and inflate() below for details */
- var Z_NO_FLUSH = 0;
- var Z_PARTIAL_FLUSH = 1;
- //var Z_SYNC_FLUSH = 2;
- var Z_FULL_FLUSH = 3;
- var Z_FINISH = 4;
- var Z_BLOCK = 5;
- //var Z_TREES = 6;
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- var Z_OK = 0;
- var Z_STREAM_END = 1;
- //var Z_NEED_DICT = 2;
- //var Z_ERRNO = -1;
- var Z_STREAM_ERROR = -2;
- var Z_DATA_ERROR = -3;
- //var Z_MEM_ERROR = -4;
- var Z_BUF_ERROR = -5;
- //var Z_VERSION_ERROR = -6;
- /* compression levels */
- //var Z_NO_COMPRESSION = 0;
- //var Z_BEST_SPEED = 1;
- //var Z_BEST_COMPRESSION = 9;
- var Z_DEFAULT_COMPRESSION = -1;
- var Z_FILTERED = 1;
- var Z_HUFFMAN_ONLY = 2;
- var Z_RLE = 3;
- var Z_FIXED = 4;
- var Z_DEFAULT_STRATEGY = 0;
- /* Possible values of the data_type field (though see inflate()) */
- //var Z_BINARY = 0;
- //var Z_TEXT = 1;
- //var Z_ASCII = 1; // = Z_TEXT
- var Z_UNKNOWN = 2;
- /* The deflate compression method */
- var Z_DEFLATED = 8;
- /*============================================================================*/
- var MAX_MEM_LEVEL = 9;
- /* Maximum value for memLevel in deflateInit2 */
- var MAX_WBITS = 15;
- /* 32K LZ77 window */
- var DEF_MEM_LEVEL = 8;
- var LENGTH_CODES = 29;
- /* number of length codes, not counting the special END_BLOCK code */
- var LITERALS = 256;
- /* number of literal bytes 0..255 */
- var L_CODES = LITERALS + 1 + LENGTH_CODES;
- /* number of Literal or Length codes, including the END_BLOCK code */
- var D_CODES = 30;
- /* number of distance codes */
- var BL_CODES = 19;
- /* number of codes used to transfer the bit lengths */
- var HEAP_SIZE = 2 * L_CODES + 1;
- /* maximum heap size */
- var MAX_BITS = 15;
- /* All codes must not exceed MAX_BITS bits */
- var MIN_MATCH = 3;
- var MAX_MATCH = 258;
- var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
- var PRESET_DICT = 0x20;
- var INIT_STATE = 42;
- var EXTRA_STATE = 69;
- var NAME_STATE = 73;
- var COMMENT_STATE = 91;
- var HCRC_STATE = 103;
- var BUSY_STATE = 113;
- var FINISH_STATE = 666;
- var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
- var BS_BLOCK_DONE = 2; /* block flush performed */
- var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
- var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
- var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
- function err(strm, errorCode) {
- strm.msg = msg[errorCode];
- return errorCode;
- }
- function rank(f) {
- return ((f) << 1) - ((f) > 4 ? 9 : 0);
- }
- function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
- /* =========================================================================
- * Flush as much pending output as possible. All deflate() output goes
- * through this function so some applications may wish to modify it
- * to avoid allocating a large strm->output buffer and copying into it.
- * (See also read_buf()).
- */
- function flush_pending(strm) {
- var s = strm.state;
- //_tr_flush_bits(s);
- var len = s.pending;
- if (len > strm.avail_out) {
- len = strm.avail_out;
- }
- if (len === 0) { return; }
- utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
- strm.next_out += len;
- s.pending_out += len;
- strm.total_out += len;
- strm.avail_out -= len;
- s.pending -= len;
- if (s.pending === 0) {
- s.pending_out = 0;
- }
- }
- function flush_block_only(s, last) {
- trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
- s.block_start = s.strstart;
- flush_pending(s.strm);
- }
- function put_byte(s, b) {
- s.pending_buf[s.pending++] = b;
- }
- /* =========================================================================
- * Put a short in the pending buffer. The 16-bit value is put in MSB order.
- * IN assertion: the stream state is correct and there is enough room in
- * pending_buf.
- */
- function putShortMSB(s, b) {
- // put_byte(s, (Byte)(b >> 8));
- // put_byte(s, (Byte)(b & 0xff));
- s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
- s.pending_buf[s.pending++] = b & 0xff;
- }
- /* ===========================================================================
- * Read a new buffer from the current input stream, update the adler32
- * and total number of bytes read. All deflate() input goes through
- * this function so some applications may wish to modify it to avoid
- * allocating a large strm->input buffer and copying from it.
- * (See also flush_pending()).
- */
- function read_buf(strm, buf, start, size) {
- var len = strm.avail_in;
- if (len > size) { len = size; }
- if (len === 0) { return 0; }
- strm.avail_in -= len;
- // zmemcpy(buf, strm->next_in, len);
- utils.arraySet(buf, strm.input, strm.next_in, len, start);
- if (strm.state.wrap === 1) {
- strm.adler = adler32(strm.adler, buf, len, start);
- }
- else if (strm.state.wrap === 2) {
- strm.adler = crc32(strm.adler, buf, len, start);
- }
- strm.next_in += len;
- strm.total_in += len;
- return len;
- }
- /* ===========================================================================
- * Set match_start to the longest match starting at the given string and
- * return its length. Matches shorter or equal to prev_length are discarded,
- * in which case the result is equal to prev_length and match_start is
- * garbage.
- * IN assertions: cur_match is the head of the hash chain for the current
- * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
- * OUT assertion: the match length is not greater than s->lookahead.
- */
- function longest_match(s, cur_match) {
- var chain_length = s.max_chain_length; /* max hash chain length */
- var scan = s.strstart; /* current string */
- var match; /* matched string */
- var len; /* length of current match */
- var best_len = s.prev_length; /* best match length so far */
- var nice_match = s.nice_match; /* stop if match long enough */
- var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
- s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
- var _win = s.window; // shortcut
- var wmask = s.w_mask;
- var prev = s.prev;
- /* Stop when cur_match becomes <= limit. To simplify the code,
- * we prevent matches with the string of window index 0.
- */
- var strend = s.strstart + MAX_MATCH;
- var scan_end1 = _win[scan + best_len - 1];
- var scan_end = _win[scan + best_len];
- /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
- * It is easy to get rid of this optimization if necessary.
- */
- // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
- /* Do not waste too much time if we already have a good match: */
- if (s.prev_length >= s.good_match) {
- chain_length >>= 2;
- }
- /* Do not look for matches beyond the end of the input. This is necessary
- * to make deflate deterministic.
- */
- if (nice_match > s.lookahead) { nice_match = s.lookahead; }
- // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
- do {
- // Assert(cur_match < s->strstart, "no future");
- match = cur_match;
- /* Skip to next match if the match length cannot increase
- * or if the match length is less than 2. Note that the checks below
- * for insufficient lookahead only occur occasionally for performance
- * reasons. Therefore uninitialized memory will be accessed, and
- * conditional jumps will be made that depend on those values.
- * However the length of the match is limited to the lookahead, so
- * the output of deflate is not affected by the uninitialized values.
- */
- if (_win[match + best_len] !== scan_end ||
- _win[match + best_len - 1] !== scan_end1 ||
- _win[match] !== _win[scan] ||
- _win[++match] !== _win[scan + 1]) {
- continue;
- }
- /* The check at best_len-1 can be removed because it will be made
- * again later. (This heuristic is not always a win.)
- * It is not necessary to compare scan[2] and match[2] since they
- * are always equal when the other bytes match, given that
- * the hash keys are equal and that HASH_BITS >= 8.
- */
- scan += 2;
- match++;
- // Assert(*scan == *match, "match[2]?");
- /* We check for insufficient lookahead only every 8th comparison;
- * the 256th check will be made at strstart+258.
- */
- do {
- /*jshint noempty:false*/
- } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- scan < strend);
- // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
- len = MAX_MATCH - (strend - scan);
- scan = strend - MAX_MATCH;
- if (len > best_len) {
- s.match_start = cur_match;
- best_len = len;
- if (len >= nice_match) {
- break;
- }
- scan_end1 = _win[scan + best_len - 1];
- scan_end = _win[scan + best_len];
- }
- } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
- if (best_len <= s.lookahead) {
- return best_len;
- }
- return s.lookahead;
- }
- /* ===========================================================================
- * Fill the window when the lookahead becomes insufficient.
- * Updates strstart and lookahead.
- *
- * IN assertion: lookahead < MIN_LOOKAHEAD
- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
- * At least one byte has been read, or avail_in == 0; reads are
- * performed for at least two bytes (required for the zip translate_eol
- * option -- not supported here).
- */
- function fill_window(s) {
- var _w_size = s.w_size;
- var p, n, m, more, str;
- //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
- do {
- more = s.window_size - s.lookahead - s.strstart;
- // JS ints have 32 bit, block below not needed
- /* Deal with !@#$% 64K limit: */
- //if (sizeof(int) <= 2) {
- // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
- // more = wsize;
- //
- // } else if (more == (unsigned)(-1)) {
- // /* Very unlikely, but possible on 16 bit machine if
- // * strstart == 0 && lookahead == 1 (input done a byte at time)
- // */
- // more--;
- // }
- //}
- /* If the window is almost full and there is insufficient lookahead,
- * move the upper half to the lower one to make room in the upper half.
- */
- if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
- utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
- s.match_start -= _w_size;
- s.strstart -= _w_size;
- /* we now have strstart >= MAX_DIST */
- s.block_start -= _w_size;
- /* Slide the hash table (could be avoided with 32 bit values
- at the expense of memory usage). We slide even when level == 0
- to keep the hash table consistent if we switch back to level > 0
- later. (Using level 0 permanently is not an optimal usage of
- zlib, so we don't care about this pathological case.)
- */
- n = s.hash_size;
- p = n;
- do {
- m = s.head[--p];
- s.head[p] = (m >= _w_size ? m - _w_size : 0);
- } while (--n);
- n = _w_size;
- p = n;
- do {
- m = s.prev[--p];
- s.prev[p] = (m >= _w_size ? m - _w_size : 0);
- /* If n is not on any hash chain, prev[n] is garbage but
- * its value will never be used.
- */
- } while (--n);
- more += _w_size;
- }
- if (s.strm.avail_in === 0) {
- break;
- }
- /* If there was no sliding:
- * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
- * more == window_size - lookahead - strstart
- * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
- * => more >= window_size - 2*WSIZE + 2
- * In the BIG_MEM or MMAP case (not yet supported),
- * window_size == input_size + MIN_LOOKAHEAD &&
- * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
- * Otherwise, window_size == 2*WSIZE so more >= 2.
- * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
- */
- //Assert(more >= 2, "more < 2");
- n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
- s.lookahead += n;
- /* Initialize the hash value now that we have some input: */
- if (s.lookahead + s.insert >= MIN_MATCH) {
- str = s.strstart - s.insert;
- s.ins_h = s.window[str];
- /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
- //#if MIN_MATCH != 3
- // Call update_hash() MIN_MATCH-3 more times
- //#endif
- while (s.insert) {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
- s.prev[str & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = str;
- str++;
- s.insert--;
- if (s.lookahead + s.insert < MIN_MATCH) {
- break;
- }
- }
- }
- /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
- * but this is not important since only literal bytes will be emitted.
- */
- } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
- /* If the WIN_INIT bytes after the end of the current data have never been
- * written, then zero those bytes in order to avoid memory check reports of
- * the use of uninitialized (or uninitialised as Julian writes) bytes by
- * the longest match routines. Update the high water mark for the next
- * time through here. WIN_INIT is set to MAX_MATCH since the longest match
- * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
- */
- // if (s.high_water < s.window_size) {
- // var curr = s.strstart + s.lookahead;
- // var init = 0;
- //
- // if (s.high_water < curr) {
- // /* Previous high water mark below current data -- zero WIN_INIT
- // * bytes or up to end of window, whichever is less.
- // */
- // init = s.window_size - curr;
- // if (init > WIN_INIT)
- // init = WIN_INIT;
- // zmemzero(s->window + curr, (unsigned)init);
- // s->high_water = curr + init;
- // }
- // else if (s->high_water < (ulg)curr + WIN_INIT) {
- // /* High water mark at or above current data, but below current data
- // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
- // * to end of window, whichever is less.
- // */
- // init = (ulg)curr + WIN_INIT - s->high_water;
- // if (init > s->window_size - s->high_water)
- // init = s->window_size - s->high_water;
- // zmemzero(s->window + s->high_water, (unsigned)init);
- // s->high_water += init;
- // }
- // }
- //
- // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
- // "not enough room for search");
- }
- /* ===========================================================================
- * Copy without compression as much as possible from the input stream, return
- * the current block state.
- * This function does not insert new strings in the dictionary since
- * uncompressible data is probably not useful. This function is used
- * only for the level=0 compression option.
- * NOTE: this function should be optimized to avoid extra copying from
- * window to pending_buf.
- */
- function deflate_stored(s, flush) {
- /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
- * to pending_buf_size, and each stored block has a 5 byte header:
- */
- var max_block_size = 0xffff;
- if (max_block_size > s.pending_buf_size - 5) {
- max_block_size = s.pending_buf_size - 5;
- }
- /* Copy as much as possible from input to output: */
- for (;;) {
- /* Fill the window as much as possible: */
- if (s.lookahead <= 1) {
- //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
- // s->block_start >= (long)s->w_size, "slide too late");
- // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
- // s.block_start >= s.w_size)) {
- // throw new Error("slide too late");
- // }
- fill_window(s);
- if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) {
- break;
- }
- /* flush the current block */
- }
- //Assert(s->block_start >= 0L, "block gone");
- // if (s.block_start < 0) throw new Error("block gone");
- s.strstart += s.lookahead;
- s.lookahead = 0;
- /* Emit a stored block if pending_buf will be full: */
- var max_start = s.block_start + max_block_size;
- if (s.strstart === 0 || s.strstart >= max_start) {
- /* strstart == 0 is possible when wraparound on 16-bit machine */
- s.lookahead = s.strstart - max_start;
- s.strstart = max_start;
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- /* Flush if we may have to slide, otherwise block_start may become
- * negative and the data will be gone:
- */
- if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.strstart > s.block_start) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_NEED_MORE;
- }
- /* ===========================================================================
- * Compress as much as possible from the input stream, return the current
- * block state.
- * This function does not perform lazy evaluation of matches and inserts
- * new strings in the dictionary only for unmatched strings or for short
- * matches. It is used only for the fast compression options.
- */
- function deflate_fast(s, flush) {
- var hash_head; /* head of the hash chain */
- var bflush; /* set if current block must be flushed */
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) {
- break; /* flush the current block */
- }
- }
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- /* Find the longest match, discarding those <= prev_length.
- * At this point we have always match_length < MIN_MATCH
- */
- if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
- }
- if (s.match_length >= MIN_MATCH) {
- // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
- /*** _tr_tally_dist(s, s.strstart - s.match_start,
- s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
- s.lookahead -= s.match_length;
- /* Insert new strings in the hash table only if the match length
- * is not too large. This saves time but degrades compression.
- */
- if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
- s.match_length--; /* string at strstart already in table */
- do {
- s.strstart++;
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- /* strstart never exceeds WSIZE-MAX_MATCH, so there are
- * always MIN_MATCH bytes ahead.
- */
- } while (--s.match_length !== 0);
- s.strstart++;
- } else
- {
- s.strstart += s.match_length;
- s.match_length = 0;
- s.ins_h = s.window[s.strstart];
- /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
- //#if MIN_MATCH != 3
- // Call UPDATE_HASH() MIN_MATCH-3 more times
- //#endif
- /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
- * matter since it will be recomputed at next deflate call.
- */
- }
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s.window[s.strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * Same as above, but achieves better compression. We use a lazy
- * evaluation for matches: a match is finally adopted only if there is
- * no better match at the next window position.
- */
- function deflate_slow(s, flush) {
- var hash_head; /* head of hash chain */
- var bflush; /* set if current block must be flushed */
- var max_insert;
- /* Process the input block. */
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- /* Find the longest match, discarding those <= prev_length.
- */
- s.prev_length = s.match_length;
- s.prev_match = s.match_start;
- s.match_length = MIN_MATCH - 1;
- if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
- s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
- if (s.match_length <= 5 &&
- (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
- /* If prev_match is also MIN_MATCH, match_start is garbage
- * but we will ignore the current match anyway.
- */
- s.match_length = MIN_MATCH - 1;
- }
- }
- /* If there was a match at the previous step and the current
- * match is not better, output the previous match:
- */
- if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
- max_insert = s.strstart + s.lookahead - MIN_MATCH;
- /* Do not insert strings in hash table beyond this. */
- //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
- /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
- s.prev_length - MIN_MATCH, bflush);***/
- bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
- /* Insert in hash table all strings up to the end of the match.
- * strstart-1 and strstart are already inserted. If there is not
- * enough lookahead, the last two strings are not inserted in
- * the hash table.
- */
- s.lookahead -= s.prev_length - 1;
- s.prev_length -= 2;
- do {
- if (++s.strstart <= max_insert) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- } while (--s.prev_length !== 0);
- s.match_available = 0;
- s.match_length = MIN_MATCH - 1;
- s.strstart++;
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- } else if (s.match_available) {
- /* If there was no match at the previous position, output a
- * single literal. If there was a match but the current match
- * is longer, truncate the previous match to a single literal.
- */
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
- if (bflush) {
- /*** FLUSH_BLOCK_ONLY(s, 0) ***/
- flush_block_only(s, false);
- /***/
- }
- s.strstart++;
- s.lookahead--;
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- } else {
- /* There is no previous match to compare with, wait for
- * the next step to decide.
- */
- s.match_available = 1;
- s.strstart++;
- s.lookahead--;
- }
- }
- //Assert (flush != Z_NO_FLUSH, "no flush?");
- if (s.match_available) {
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
- s.match_available = 0;
- }
- s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * For Z_RLE, simply look for runs of bytes, generate matches only of distance
- * one. Do not maintain a hash table. (It will be regenerated if this run of
- * deflate switches away from Z_RLE.)
- */
- function deflate_rle(s, flush) {
- var bflush; /* set if current block must be flushed */
- var prev; /* byte at distance one to match */
- var scan, strend; /* scan goes up to strend for length of run */
- var _win = s.window;
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the longest run, plus one for the unrolled loop.
- */
- if (s.lookahead <= MAX_MATCH) {
- fill_window(s);
- if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
- /* See how many times the previous byte repeats */
- s.match_length = 0;
- if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
- scan = s.strstart - 1;
- prev = _win[scan];
- if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
- strend = s.strstart + MAX_MATCH;
- do {
- /*jshint noempty:false*/
- } while (prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- scan < strend);
- s.match_length = MAX_MATCH - (strend - scan);
- if (s.match_length > s.lookahead) {
- s.match_length = s.lookahead;
- }
- }
- //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
- }
- /* Emit match if have run of MIN_MATCH or longer, else emit literal */
- if (s.match_length >= MIN_MATCH) {
- //check_match(s, s.strstart, s.strstart - 1, s.match_length);
- /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
- s.lookahead -= s.match_length;
- s.strstart += s.match_length;
- s.match_length = 0;
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* ===========================================================================
- * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
- * (It will be regenerated if this run of deflate switches away from Huffman.)
- */
- function deflate_huff(s, flush) {
- var bflush; /* set if current block must be flushed */
- for (;;) {
- /* Make sure that we have a literal to write. */
- if (s.lookahead === 0) {
- fill_window(s);
- if (s.lookahead === 0) {
- if (flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- break; /* flush the current block */
- }
- }
- /* Output a literal byte */
- s.match_length = 0;
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
- }
- /* Values for max_lazy_match, good_match and max_chain_length, depending on
- * the desired pack level (0..9). The values given below have been tuned to
- * exclude worst case performance for pathological files. Better values may be
- * found for specific files.
- */
- function Config(good_length, max_lazy, nice_length, max_chain, func) {
- this.good_length = good_length;
- this.max_lazy = max_lazy;
- this.nice_length = nice_length;
- this.max_chain = max_chain;
- this.func = func;
- }
- var configuration_table;
- configuration_table = [
- /* good lazy nice chain */
- new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
- new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
- new Config(4, 5, 16, 8, deflate_fast), /* 2 */
- new Config(4, 6, 32, 32, deflate_fast), /* 3 */
- new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
- new Config(8, 16, 32, 32, deflate_slow), /* 5 */
- new Config(8, 16, 128, 128, deflate_slow), /* 6 */
- new Config(8, 32, 128, 256, deflate_slow), /* 7 */
- new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
- new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
- ];
- /* ===========================================================================
- * Initialize the "longest match" routines for a new zlib stream
- */
- function lm_init(s) {
- s.window_size = 2 * s.w_size;
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
- /* Set the default configuration parameters:
- */
- s.max_lazy_match = configuration_table[s.level].max_lazy;
- s.good_match = configuration_table[s.level].good_length;
- s.nice_match = configuration_table[s.level].nice_length;
- s.max_chain_length = configuration_table[s.level].max_chain;
- s.strstart = 0;
- s.block_start = 0;
- s.lookahead = 0;
- s.insert = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- s.ins_h = 0;
- }
- function DeflateState() {
- this.strm = null; /* pointer back to this zlib stream */
- this.status = 0; /* as the name implies */
- this.pending_buf = null; /* output still pending */
- this.pending_buf_size = 0; /* size of pending_buf */
- this.pending_out = 0; /* next pending byte to output to the stream */
- this.pending = 0; /* nb of bytes in the pending buffer */
- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
- this.gzhead = null; /* gzip header information to write */
- this.gzindex = 0; /* where in extra, name, or comment */
- this.method = Z_DEFLATED; /* can only be DEFLATED */
- this.last_flush = -1; /* value of flush param for previous deflate call */
- this.w_size = 0; /* LZ77 window size (32K by default) */
- this.w_bits = 0; /* log2(w_size) (8..16) */
- this.w_mask = 0; /* w_size - 1 */
- this.window = null;
- /* Sliding window. Input bytes are read into the second half of the window,
- * and move to the first half later to keep a dictionary of at least wSize
- * bytes. With this organization, matches are limited to a distance of
- * wSize-MAX_MATCH bytes, but this ensures that IO is always
- * performed with a length multiple of the block size.
- */
- this.window_size = 0;
- /* Actual size of window: 2*wSize, except when the user input buffer
- * is directly used as sliding window.
- */
- this.prev = null;
- /* Link to older string with same hash index. To limit the size of this
- * array to 64K, this link is maintained only for the last 32K strings.
- * An index in this array is thus a window index modulo 32K.
- */
- this.head = null; /* Heads of the hash chains or NIL. */
- this.ins_h = 0; /* hash index of string to be inserted */
- this.hash_size = 0; /* number of elements in hash table */
- this.hash_bits = 0; /* log2(hash_size) */
- this.hash_mask = 0; /* hash_size-1 */
- this.hash_shift = 0;
- /* Number of bits by which ins_h must be shifted at each input
- * step. It must be such that after MIN_MATCH steps, the oldest
- * byte no longer takes part in the hash key, that is:
- * hash_shift * MIN_MATCH >= hash_bits
- */
- this.block_start = 0;
- /* Window position at the beginning of the current output block. Gets
- * negative when the window is moved backwards.
- */
- this.match_length = 0; /* length of best match */
- this.prev_match = 0; /* previous match */
- this.match_available = 0; /* set if previous match exists */
- this.strstart = 0; /* start of string to insert */
- this.match_start = 0; /* start of matching string */
- this.lookahead = 0; /* number of valid bytes ahead in window */
- this.prev_length = 0;
- /* Length of the best match at previous step. Matches not greater than this
- * are discarded. This is used in the lazy match evaluation.
- */
- this.max_chain_length = 0;
- /* To speed up deflation, hash chains are never searched beyond this
- * length. A higher limit improves compression ratio but degrades the
- * speed.
- */
- this.max_lazy_match = 0;
- /* Attempt to find a better match only when the current match is strictly
- * smaller than this value. This mechanism is used only for compression
- * levels >= 4.
- */
- // That's alias to max_lazy_match, don't use directly
- //this.max_insert_length = 0;
- /* Insert new strings in the hash table only if the match length is not
- * greater than this length. This saves time but degrades compression.
- * max_insert_length is used only for compression levels <= 3.
- */
- this.level = 0; /* compression level (1..9) */
- this.strategy = 0; /* favor or force Huffman coding*/
- this.good_match = 0;
- /* Use a faster search when the previous match is longer than this */
- this.nice_match = 0; /* Stop searching when current match exceeds this */
- /* used by trees.c: */
- /* Didn't use ct_data typedef below to suppress compiler warning */
- // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
- // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
- // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
- // Use flat array of DOUBLE size, with interleaved fata,
- // because JS does not support effective
- this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
- this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
- this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
- zero(this.dyn_ltree);
- zero(this.dyn_dtree);
- zero(this.bl_tree);
- this.l_desc = null; /* desc. for literal tree */
- this.d_desc = null; /* desc. for distance tree */
- this.bl_desc = null; /* desc. for bit length tree */
- //ush bl_count[MAX_BITS+1];
- this.bl_count = new utils.Buf16(MAX_BITS + 1);
- /* number of codes at each bit length for an optimal tree */
- //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
- this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
- zero(this.heap);
- this.heap_len = 0; /* number of elements in the heap */
- this.heap_max = 0; /* element of largest frequency */
- /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
- * The same heap array is used to build all trees.
- */
- this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
- zero(this.depth);
- /* Depth of each subtree used as tie breaker for trees of equal frequency
- */
- this.l_buf = 0; /* buffer index for literals or lengths */
- this.lit_bufsize = 0;
- /* Size of match buffer for literals/lengths. There are 4 reasons for
- * limiting lit_bufsize to 64K:
- * - frequencies can be kept in 16 bit counters
- * - if compression is not successful for the first block, all input
- * data is still in the window so we can still emit a stored block even
- * when input comes from standard input. (This can also be done for
- * all blocks if lit_bufsize is not greater than 32K.)
- * - if compression is not successful for a file smaller than 64K, we can
- * even emit a stored file instead of a stored block (saving 5 bytes).
- * This is applicable only for zip (not gzip or zlib).
- * - creating new Huffman trees less frequently may not provide fast
- * adaptation to changes in the input data statistics. (Take for
- * example a binary file with poorly compressible code followed by
- * a highly compressible string table.) Smaller buffer sizes give
- * fast adaptation but have of course the overhead of transmitting
- * trees more frequently.
- * - I can't count above 4
- */
- this.last_lit = 0; /* running index in l_buf */
- this.d_buf = 0;
- /* Buffer index for distances. To simplify the code, d_buf and l_buf have
- * the same number of elements. To use different lengths, an extra flag
- * array would be necessary.
- */
- this.opt_len = 0; /* bit length of current block with optimal trees */
- this.static_len = 0; /* bit length of current block with static trees */
- this.matches = 0; /* number of string matches in current block */
- this.insert = 0; /* bytes at end of window left to insert */
- this.bi_buf = 0;
- /* Output buffer. bits are inserted starting at the bottom (least
- * significant bits).
- */
- this.bi_valid = 0;
- /* Number of valid bits in bi_buf. All bits above the last valid bit
- * are always zero.
- */
- // Used for window memory init. We safely ignore it for JS. That makes
- // sense only for pointers and memory check tools.
- //this.high_water = 0;
- /* High water mark offset in window for initialized bytes -- bytes above
- * this are set to zero in order to avoid memory check warnings when
- * longest match routines access bytes past the input. This is then
- * updated to the new high water mark.
- */
- }
- function deflateResetKeep(strm) {
- var s;
- if (!strm || !strm.state) {
- return err(strm, Z_STREAM_ERROR);
- }
- strm.total_in = strm.total_out = 0;
- strm.data_type = Z_UNKNOWN;
- s = strm.state;
- s.pending = 0;
- s.pending_out = 0;
- if (s.wrap < 0) {
- s.wrap = -s.wrap;
- /* was made negative by deflate(..., Z_FINISH); */
- }
- s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
- strm.adler = (s.wrap === 2) ?
- 0 // crc32(0, Z_NULL, 0)
- :
- 1; // adler32(0, Z_NULL, 0)
- s.last_flush = Z_NO_FLUSH;
- trees._tr_init(s);
- return Z_OK;
- }
- function deflateReset(strm) {
- var ret = deflateResetKeep(strm);
- if (ret === Z_OK) {
- lm_init(strm.state);
- }
- return ret;
- }
- function deflateSetHeader(strm, head) {
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
- strm.state.gzhead = head;
- return Z_OK;
- }
- function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
- if (!strm) { // === Z_NULL
- return Z_STREAM_ERROR;
- }
- var wrap = 1;
- if (level === Z_DEFAULT_COMPRESSION) {
- level = 6;
- }
- if (windowBits < 0) { /* suppress zlib wrapper */
- wrap = 0;
- windowBits = -windowBits;
- }
- else if (windowBits > 15) {
- wrap = 2; /* write gzip wrapper instead */
- windowBits -= 16;
- }
- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
- windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
- strategy < 0 || strategy > Z_FIXED) {
- return err(strm, Z_STREAM_ERROR);
- }
- if (windowBits === 8) {
- windowBits = 9;
- }
- /* until 256-byte window bug fixed */
- var s = new DeflateState();
- strm.state = s;
- s.strm = strm;
- s.wrap = wrap;
- s.gzhead = null;
- s.w_bits = windowBits;
- s.w_size = 1 << s.w_bits;
- s.w_mask = s.w_size - 1;
- s.hash_bits = memLevel + 7;
- s.hash_size = 1 << s.hash_bits;
- s.hash_mask = s.hash_size - 1;
- s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
- s.window = new utils.Buf8(s.w_size * 2);
- s.head = new utils.Buf16(s.hash_size);
- s.prev = new utils.Buf16(s.w_size);
- // Don't need mem init magic for JS.
- //s.high_water = 0; /* nothing written to s->window yet */
- s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
- s.pending_buf_size = s.lit_bufsize * 4;
- //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
- //s->pending_buf = (uchf *) overlay;
- s.pending_buf = new utils.Buf8(s.pending_buf_size);
- // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
- //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
- s.d_buf = 1 * s.lit_bufsize;
- //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
- s.l_buf = (1 + 2) * s.lit_bufsize;
- s.level = level;
- s.strategy = strategy;
- s.method = method;
- return deflateReset(strm);
- }
- function deflateInit(strm, level) {
- return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
- }
- function deflate(strm, flush) {
- var old_flush, s;
- var beg, val; // for gzip header write only
- if (!strm || !strm.state ||
- flush > Z_BLOCK || flush < 0) {
- return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
- }
- s = strm.state;
- if (!strm.output ||
- (!strm.input && strm.avail_in !== 0) ||
- (s.status === FINISH_STATE && flush !== Z_FINISH)) {
- return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
- }
- s.strm = strm; /* just in case */
- old_flush = s.last_flush;
- s.last_flush = flush;
- /* Write the header */
- if (s.status === INIT_STATE) {
- if (s.wrap === 2) { // GZIP header
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- put_byte(s, 31);
- put_byte(s, 139);
- put_byte(s, 8);
- if (!s.gzhead) { // s->gzhead == Z_NULL
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, OS_CODE);
- s.status = BUSY_STATE;
- }
- else {
- put_byte(s, (s.gzhead.text ? 1 : 0) +
- (s.gzhead.hcrc ? 2 : 0) +
- (!s.gzhead.extra ? 0 : 4) +
- (!s.gzhead.name ? 0 : 8) +
- (!s.gzhead.comment ? 0 : 16)
- );
- put_byte(s, s.gzhead.time & 0xff);
- put_byte(s, (s.gzhead.time >> 8) & 0xff);
- put_byte(s, (s.gzhead.time >> 16) & 0xff);
- put_byte(s, (s.gzhead.time >> 24) & 0xff);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, s.gzhead.os & 0xff);
- if (s.gzhead.extra && s.gzhead.extra.length) {
- put_byte(s, s.gzhead.extra.length & 0xff);
- put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
- }
- if (s.gzhead.hcrc) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
- }
- s.gzindex = 0;
- s.status = EXTRA_STATE;
- }
- }
- else // DEFLATE header
- {
- var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
- var level_flags = -1;
- if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
- level_flags = 0;
- } else if (s.level < 6) {
- level_flags = 1;
- } else if (s.level === 6) {
- level_flags = 2;
- } else {
- level_flags = 3;
- }
- header |= (level_flags << 6);
- if (s.strstart !== 0) { header |= PRESET_DICT; }
- header += 31 - (header % 31);
- s.status = BUSY_STATE;
- putShortMSB(s, header);
- /* Save the adler32 of the preset dictionary: */
- if (s.strstart !== 0) {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
- strm.adler = 1; // adler32(0L, Z_NULL, 0);
- }
- }
- //#ifdef GZIP
- if (s.status === EXTRA_STATE) {
- if (s.gzhead.extra/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- break;
- }
- }
- put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
- s.gzindex++;
- }
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (s.gzindex === s.gzhead.extra.length) {
- s.gzindex = 0;
- s.status = NAME_STATE;
- }
- }
- else {
- s.status = NAME_STATE;
- }
- }
- if (s.status === NAME_STATE) {
- if (s.gzhead.name/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.name.length) {
- val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.gzindex = 0;
- s.status = COMMENT_STATE;
- }
- }
- else {
- s.status = COMMENT_STATE;
- }
- }
- if (s.status === COMMENT_STATE) {
- if (s.gzhead.comment/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.comment.length) {
- val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.status = HCRC_STATE;
- }
- }
- else {
- s.status = HCRC_STATE;
- }
- }
- if (s.status === HCRC_STATE) {
- if (s.gzhead.hcrc) {
- if (s.pending + 2 > s.pending_buf_size) {
- flush_pending(strm);
- }
- if (s.pending + 2 <= s.pending_buf_size) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- s.status = BUSY_STATE;
- }
- }
- else {
- s.status = BUSY_STATE;
- }
- }
- //#endif
- /* Flush as much pending output as possible */
- if (s.pending !== 0) {
- flush_pending(strm);
- if (strm.avail_out === 0) {
- /* Since avail_out is 0, deflate will be called again with
- * more output space, but possibly with both pending and
- * avail_in equal to zero. There won't be anything to do,
- * but this is not an error situation so make sure we
- * return OK instead of BUF_ERROR at next call of deflate:
- */
- s.last_flush = -1;
- return Z_OK;
- }
- /* Make sure there is something to do and avoid duplicate consecutive
- * flushes. For repeated and useless calls with Z_FINISH, we keep
- * returning Z_STREAM_END instead of Z_BUF_ERROR.
- */
- } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
- flush !== Z_FINISH) {
- return err(strm, Z_BUF_ERROR);
- }
- /* User must not provide more input after the first FINISH: */
- if (s.status === FINISH_STATE && strm.avail_in !== 0) {
- return err(strm, Z_BUF_ERROR);
- }
- /* Start a new block or continue the current one.
- */
- if (strm.avail_in !== 0 || s.lookahead !== 0 ||
- (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
- var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
- (s.strategy === Z_RLE ? deflate_rle(s, flush) :
- configuration_table[s.level].func(s, flush));
- if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
- s.status = FINISH_STATE;
- }
- if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
- if (strm.avail_out === 0) {
- s.last_flush = -1;
- /* avoid BUF_ERROR next call, see above */
- }
- return Z_OK;
- /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
- * of deflate should use the same flush parameter to make sure
- * that the flush is complete. So we don't have to output an
- * empty block here, this will be done at next call. This also
- * ensures that for a very small output buffer, we emit at most
- * one empty block.
- */
- }
- if (bstate === BS_BLOCK_DONE) {
- if (flush === Z_PARTIAL_FLUSH) {
- trees._tr_align(s);
- }
- else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
- trees._tr_stored_block(s, 0, 0, false);
- /* For a full flush, this empty block will be recognized
- * as a special marker by inflate_sync().
- */
- if (flush === Z_FULL_FLUSH) {
- /*** CLEAR_HASH(s); ***/ /* forget history */
- zero(s.head); // Fill with NIL (= 0);
- if (s.lookahead === 0) {
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- }
- }
- flush_pending(strm);
- if (strm.avail_out === 0) {
- s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
- return Z_OK;
- }
- }
- }
- //Assert(strm->avail_out > 0, "bug2");
- //if (strm.avail_out <= 0) { throw new Error("bug2");}
- if (flush !== Z_FINISH) { return Z_OK; }
- if (s.wrap <= 0) { return Z_STREAM_END; }
- /* Write the trailer */
- if (s.wrap === 2) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- put_byte(s, (strm.adler >> 16) & 0xff);
- put_byte(s, (strm.adler >> 24) & 0xff);
- put_byte(s, strm.total_in & 0xff);
- put_byte(s, (strm.total_in >> 8) & 0xff);
- put_byte(s, (strm.total_in >> 16) & 0xff);
- put_byte(s, (strm.total_in >> 24) & 0xff);
- }
- else
- {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
- flush_pending(strm);
- /* If avail_out is zero, the application will call deflate again
- * to flush the rest.
- */
- if (s.wrap > 0) { s.wrap = -s.wrap; }
- /* write the trailer only once! */
- return s.pending !== 0 ? Z_OK : Z_STREAM_END;
- }
- function deflateEnd(strm) {
- var status;
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
- status = strm.state.status;
- if (status !== INIT_STATE &&
- status !== EXTRA_STATE &&
- status !== NAME_STATE &&
- status !== COMMENT_STATE &&
- status !== HCRC_STATE &&
- status !== BUSY_STATE &&
- status !== FINISH_STATE
- ) {
- return err(strm, Z_STREAM_ERROR);
- }
- strm.state = null;
- return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
- }
- /* =========================================================================
- * Initializes the compression dictionary from the given byte
- * sequence without producing any compressed output.
- */
- function deflateSetDictionary(strm, dictionary) {
- var dictLength = dictionary.length;
- var s;
- var str, n;
- var wrap;
- var avail;
- var next;
- var input;
- var tmpDict;
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
- s = strm.state;
- wrap = s.wrap;
- if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
- return Z_STREAM_ERROR;
- }
- /* when using zlib wrappers, compute Adler-32 for provided dictionary */
- if (wrap === 1) {
- /* adler32(strm->adler, dictionary, dictLength); */
- strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
- }
- s.wrap = 0; /* avoid computing Adler-32 in read_buf */
- /* if dictionary would fill window, just replace the history */
- if (dictLength >= s.w_size) {
- if (wrap === 0) { /* already empty otherwise */
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- /* use the tail */
- // dictionary = dictionary.slice(dictLength - s.w_size);
- tmpDict = new utils.Buf8(s.w_size);
- utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
- dictionary = tmpDict;
- dictLength = s.w_size;
- }
- /* insert dictionary into window and hash */
- avail = strm.avail_in;
- next = strm.next_in;
- input = strm.input;
- strm.avail_in = dictLength;
- strm.next_in = 0;
- strm.input = dictionary;
- fill_window(s);
- while (s.lookahead >= MIN_MATCH) {
- str = s.strstart;
- n = s.lookahead - (MIN_MATCH - 1);
- do {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
- s.prev[str & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = str;
- str++;
- } while (--n);
- s.strstart = str;
- s.lookahead = MIN_MATCH - 1;
- fill_window(s);
- }
- s.strstart += s.lookahead;
- s.block_start = s.strstart;
- s.insert = s.lookahead;
- s.lookahead = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- strm.next_in = next;
- strm.input = input;
- strm.avail_in = avail;
- s.wrap = wrap;
- return Z_OK;
- }
- exports.deflateInit = deflateInit;
- exports.deflateInit2 = deflateInit2;
- exports.deflateReset = deflateReset;
- exports.deflateResetKeep = deflateResetKeep;
- exports.deflateSetHeader = deflateSetHeader;
- exports.deflate = deflate;
- exports.deflateEnd = deflateEnd;
- exports.deflateSetDictionary = deflateSetDictionary;
- exports.deflateInfo = 'pako deflate (from Nodeca project)';
- /* Not implemented
- exports.deflateBound = deflateBound;
- exports.deflateCopy = deflateCopy;
- exports.deflateParams = deflateParams;
- exports.deflatePending = deflatePending;
- exports.deflatePrime = deflatePrime;
- exports.deflateTune = deflateTune;
- */
- },{"../utils/common":123,"./adler32":125,"./crc32":127,"./messages":133,"./trees":134}],129:[function(require,module,exports){
- 'use strict';
- function GZheader() {
- /* true if compressed data believed to be text */
- this.text = 0;
- /* modification time */
- this.time = 0;
- /* extra flags (not used when writing a gzip file) */
- this.xflags = 0;
- /* operating system */
- this.os = 0;
- /* pointer to extra field or Z_NULL if none */
- this.extra = null;
- /* extra field length (valid if extra != Z_NULL) */
- this.extra_len = 0; // Actually, we don't need it in JS,
- // but leave for few code modifications
- //
- // Setup limits is not necessary because in js we should not preallocate memory
- // for inflate use constant limit in 65536 bytes
- //
- /* space at extra (only when reading header) */
- // this.extra_max = 0;
- /* pointer to zero-terminated file name or Z_NULL */
- this.name = '';
- /* space at name (only when reading header) */
- // this.name_max = 0;
- /* pointer to zero-terminated comment or Z_NULL */
- this.comment = '';
- /* space at comment (only when reading header) */
- // this.comm_max = 0;
- /* true if there was or will be a header crc */
- this.hcrc = 0;
- /* true when done reading gzip header (not used when writing a gzip file) */
- this.done = false;
- }
- module.exports = GZheader;
- },{}],130:[function(require,module,exports){
- 'use strict';
- // See state defs from inflate.js
- var BAD = 30; /* got a data error -- remain here until reset */
- var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
- /*
- Decode literal, length, and distance codes and write out the resulting
- literal and match bytes until either not enough input or output is
- available, an end-of-block is encountered, or a data error is encountered.
- When large enough input and output buffers are supplied to inflate(), for
- example, a 16K input buffer and a 64K output buffer, more than 95% of the
- inflate execution time is spent in this routine.
- Entry assumptions:
- state.mode === LEN
- strm.avail_in >= 6
- strm.avail_out >= 258
- start >= strm.avail_out
- state.bits < 8
- On return, state.mode is one of:
- LEN -- ran out of enough output space or enough available input
- TYPE -- reached end of block code, inflate() to interpret next block
- BAD -- error in block data
- Notes:
- - The maximum input bits used by a length/distance pair is 15 bits for the
- length code, 5 bits for the length extra, 15 bits for the distance code,
- and 13 bits for the distance extra. This totals 48 bits, or six bytes.
- Therefore if strm.avail_in >= 6, then there is enough input to avoid
- checking for available input while decoding.
- - The maximum bytes that a single length/distance pair can output is 258
- bytes, which is the maximum length that can be coded. inflate_fast()
- requires strm.avail_out >= 258 for each loop to avoid checking for
- output space.
- */
- module.exports = function inflate_fast(strm, start) {
- var state;
- var _in; /* local strm.input */
- var last; /* have enough input while in < last */
- var _out; /* local strm.output */
- var beg; /* inflate()'s initial strm.output */
- var end; /* while out < end, enough space available */
- //#ifdef INFLATE_STRICT
- var dmax; /* maximum distance from zlib header */
- //#endif
- var wsize; /* window size or zero if not using window */
- var whave; /* valid bytes in the window */
- var wnext; /* window write index */
- // Use `s_window` instead `window`, avoid conflict with instrumentation tools
- var s_window; /* allocated sliding window, if wsize != 0 */
- var hold; /* local strm.hold */
- var bits; /* local strm.bits */
- var lcode; /* local strm.lencode */
- var dcode; /* local strm.distcode */
- var lmask; /* mask for first level of length codes */
- var dmask; /* mask for first level of distance codes */
- var here; /* retrieved table entry */
- var op; /* code bits, operation, extra bits, or */
- /* window position, window bytes to copy */
- var len; /* match length, unused bytes */
- var dist; /* match distance */
- var from; /* where to copy match from */
- var from_source;
- var input, output; // JS specific, because we have no pointers
- /* copy state to local variables */
- state = strm.state;
- //here = state.here;
- _in = strm.next_in;
- input = strm.input;
- last = _in + (strm.avail_in - 5);
- _out = strm.next_out;
- output = strm.output;
- beg = _out - (start - strm.avail_out);
- end = _out + (strm.avail_out - 257);
- //#ifdef INFLATE_STRICT
- dmax = state.dmax;
- //#endif
- wsize = state.wsize;
- whave = state.whave;
- wnext = state.wnext;
- s_window = state.window;
- hold = state.hold;
- bits = state.bits;
- lcode = state.lencode;
- dcode = state.distcode;
- lmask = (1 << state.lenbits) - 1;
- dmask = (1 << state.distbits) - 1;
- /* decode literals and length/distances until end-of-block or not enough
- input data or output space */
- top:
- do {
- if (bits < 15) {
- hold += input[_in++] << bits;
- bits += 8;
- hold += input[_in++] << bits;
- bits += 8;
- }
- here = lcode[hold & lmask];
- dolen:
- for (;;) { // Goto emulation
- op = here >>> 24/*here.bits*/;
- hold >>>= op;
- bits -= op;
- op = (here >>> 16) & 0xff/*here.op*/;
- if (op === 0) { /* literal */
- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
- // "inflate: literal '%c'\n" :
- // "inflate: literal 0x%02x\n", here.val));
- output[_out++] = here & 0xffff/*here.val*/;
- }
- else if (op & 16) { /* length base */
- len = here & 0xffff/*here.val*/;
- op &= 15; /* number of extra bits */
- if (op) {
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- }
- len += hold & ((1 << op) - 1);
- hold >>>= op;
- bits -= op;
- }
- //Tracevv((stderr, "inflate: length %u\n", len));
- if (bits < 15) {
- hold += input[_in++] << bits;
- bits += 8;
- hold += input[_in++] << bits;
- bits += 8;
- }
- here = dcode[hold & dmask];
- dodist:
- for (;;) { // goto emulation
- op = here >>> 24/*here.bits*/;
- hold >>>= op;
- bits -= op;
- op = (here >>> 16) & 0xff/*here.op*/;
- if (op & 16) { /* distance base */
- dist = here & 0xffff/*here.val*/;
- op &= 15; /* number of extra bits */
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- }
- }
- dist += hold & ((1 << op) - 1);
- //#ifdef INFLATE_STRICT
- if (dist > dmax) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break top;
- }
- //#endif
- hold >>>= op;
- bits -= op;
- //Tracevv((stderr, "inflate: distance %u\n", dist));
- op = _out - beg; /* max distance in output */
- if (dist > op) { /* see if copy from window */
- op = dist - op; /* distance back in window */
- if (op > whave) {
- if (state.sane) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break top;
- }
- // (!) This block is disabled in zlib defailts,
- // don't enable it for binary compatibility
- //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
- // if (len <= op - whave) {
- // do {
- // output[_out++] = 0;
- // } while (--len);
- // continue top;
- // }
- // len -= op - whave;
- // do {
- // output[_out++] = 0;
- // } while (--op > whave);
- // if (op === 0) {
- // from = _out - dist;
- // do {
- // output[_out++] = output[from++];
- // } while (--len);
- // continue top;
- // }
- //#endif
- }
- from = 0; // window index
- from_source = s_window;
- if (wnext === 0) { /* very common case */
- from += wsize - op;
- if (op < len) { /* some from window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- else if (wnext < op) { /* wrap around window */
- from += wsize + wnext - op;
- op -= wnext;
- if (op < len) { /* some from end of window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = 0;
- if (wnext < len) { /* some from start of window */
- op = wnext;
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- }
- else { /* contiguous in window */
- from += wnext - op;
- if (op < len) { /* some from window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- while (len > 2) {
- output[_out++] = from_source[from++];
- output[_out++] = from_source[from++];
- output[_out++] = from_source[from++];
- len -= 3;
- }
- if (len) {
- output[_out++] = from_source[from++];
- if (len > 1) {
- output[_out++] = from_source[from++];
- }
- }
- }
- else {
- from = _out - dist; /* copy direct from output */
- do { /* minimum length is three */
- output[_out++] = output[from++];
- output[_out++] = output[from++];
- output[_out++] = output[from++];
- len -= 3;
- } while (len > 2);
- if (len) {
- output[_out++] = output[from++];
- if (len > 1) {
- output[_out++] = output[from++];
- }
- }
- }
- }
- else if ((op & 64) === 0) { /* 2nd level distance code */
- here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
- continue dodist;
- }
- else {
- strm.msg = 'invalid distance code';
- state.mode = BAD;
- break top;
- }
- break; // need to emulate goto via "continue"
- }
- }
- else if ((op & 64) === 0) { /* 2nd level length code */
- here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
- continue dolen;
- }
- else if (op & 32) { /* end-of-block */
- //Tracevv((stderr, "inflate: end of block\n"));
- state.mode = TYPE;
- break top;
- }
- else {
- strm.msg = 'invalid literal/length code';
- state.mode = BAD;
- break top;
- }
- break; // need to emulate goto via "continue"
- }
- } while (_in < last && _out < end);
- /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
- len = bits >> 3;
- _in -= len;
- bits -= len << 3;
- hold &= (1 << bits) - 1;
- /* update state and return */
- strm.next_in = _in;
- strm.next_out = _out;
- strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
- strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
- state.hold = hold;
- state.bits = bits;
- return;
- };
- },{}],131:[function(require,module,exports){
- 'use strict';
- var utils = require('../utils/common');
- var adler32 = require('./adler32');
- var crc32 = require('./crc32');
- var inflate_fast = require('./inffast');
- var inflate_table = require('./inftrees');
- var CODES = 0;
- var LENS = 1;
- var DISTS = 2;
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- /* Allowed flush values; see deflate() and inflate() below for details */
- //var Z_NO_FLUSH = 0;
- //var Z_PARTIAL_FLUSH = 1;
- //var Z_SYNC_FLUSH = 2;
- //var Z_FULL_FLUSH = 3;
- var Z_FINISH = 4;
- var Z_BLOCK = 5;
- var Z_TREES = 6;
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- var Z_OK = 0;
- var Z_STREAM_END = 1;
- var Z_NEED_DICT = 2;
- //var Z_ERRNO = -1;
- var Z_STREAM_ERROR = -2;
- var Z_DATA_ERROR = -3;
- var Z_MEM_ERROR = -4;
- var Z_BUF_ERROR = -5;
- //var Z_VERSION_ERROR = -6;
- /* The deflate compression method */
- var Z_DEFLATED = 8;
- /* STATES ====================================================================*/
- /* ===========================================================================*/
- var HEAD = 1; /* i: waiting for magic header */
- var FLAGS = 2; /* i: waiting for method and flags (gzip) */
- var TIME = 3; /* i: waiting for modification time (gzip) */
- var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
- var EXLEN = 5; /* i: waiting for extra length (gzip) */
- var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
- var NAME = 7; /* i: waiting for end of file name (gzip) */
- var COMMENT = 8; /* i: waiting for end of comment (gzip) */
- var HCRC = 9; /* i: waiting for header crc (gzip) */
- var DICTID = 10; /* i: waiting for dictionary check value */
- var DICT = 11; /* waiting for inflateSetDictionary() call */
- var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
- var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
- var STORED = 14; /* i: waiting for stored size (length and complement) */
- var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
- var COPY = 16; /* i/o: waiting for input or output to copy stored block */
- var TABLE = 17; /* i: waiting for dynamic block table lengths */
- var LENLENS = 18; /* i: waiting for code length code lengths */
- var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
- var LEN_ = 20; /* i: same as LEN below, but only first time in */
- var LEN = 21; /* i: waiting for length/lit/eob code */
- var LENEXT = 22; /* i: waiting for length extra bits */
- var DIST = 23; /* i: waiting for distance code */
- var DISTEXT = 24; /* i: waiting for distance extra bits */
- var MATCH = 25; /* o: waiting for output space to copy string */
- var LIT = 26; /* o: waiting for output space to write literal */
- var CHECK = 27; /* i: waiting for 32-bit check value */
- var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
- var DONE = 29; /* finished check, done -- remain here until reset */
- var BAD = 30; /* got a data error -- remain here until reset */
- var MEM = 31; /* got an inflate() memory error -- remain here until reset */
- var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
- /* ===========================================================================*/
- var ENOUGH_LENS = 852;
- var ENOUGH_DISTS = 592;
- //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
- var MAX_WBITS = 15;
- /* 32K LZ77 window */
- var DEF_WBITS = MAX_WBITS;
- function zswap32(q) {
- return (((q >>> 24) & 0xff) +
- ((q >>> 8) & 0xff00) +
- ((q & 0xff00) << 8) +
- ((q & 0xff) << 24));
- }
- function InflateState() {
- this.mode = 0; /* current inflate mode */
- this.last = false; /* true if processing last block */
- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
- this.havedict = false; /* true if dictionary provided */
- this.flags = 0; /* gzip header method and flags (0 if zlib) */
- this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
- this.check = 0; /* protected copy of check value */
- this.total = 0; /* protected copy of output count */
- // TODO: may be {}
- this.head = null; /* where to save gzip header information */
- /* sliding window */
- this.wbits = 0; /* log base 2 of requested window size */
- this.wsize = 0; /* window size or zero if not using window */
- this.whave = 0; /* valid bytes in the window */
- this.wnext = 0; /* window write index */
- this.window = null; /* allocated sliding window, if needed */
- /* bit accumulator */
- this.hold = 0; /* input bit accumulator */
- this.bits = 0; /* number of bits in "in" */
- /* for string and stored block copying */
- this.length = 0; /* literal or length of data to copy */
- this.offset = 0; /* distance back to copy string from */
- /* for table and code decoding */
- this.extra = 0; /* extra bits needed */
- /* fixed and dynamic code tables */
- this.lencode = null; /* starting table for length/literal codes */
- this.distcode = null; /* starting table for distance codes */
- this.lenbits = 0; /* index bits for lencode */
- this.distbits = 0; /* index bits for distcode */
- /* dynamic table building */
- this.ncode = 0; /* number of code length code lengths */
- this.nlen = 0; /* number of length code lengths */
- this.ndist = 0; /* number of distance code lengths */
- this.have = 0; /* number of code lengths in lens[] */
- this.next = null; /* next available space in codes[] */
- this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
- this.work = new utils.Buf16(288); /* work area for code table building */
- /*
- because we don't have pointers in js, we use lencode and distcode directly
- as buffers so we don't need codes
- */
- //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
- this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
- this.distdyn = null; /* dynamic table for distance codes (JS specific) */
- this.sane = 0; /* if false, allow invalid distance too far */
- this.back = 0; /* bits back of last unprocessed length/lit */
- this.was = 0; /* initial length of match */
- }
- function inflateResetKeep(strm) {
- var state;
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- strm.total_in = strm.total_out = state.total = 0;
- strm.msg = ''; /*Z_NULL*/
- if (state.wrap) { /* to support ill-conceived Java test suite */
- strm.adler = state.wrap & 1;
- }
- state.mode = HEAD;
- state.last = 0;
- state.havedict = 0;
- state.dmax = 32768;
- state.head = null/*Z_NULL*/;
- state.hold = 0;
- state.bits = 0;
- //state.lencode = state.distcode = state.next = state.codes;
- state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
- state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
- state.sane = 1;
- state.back = -1;
- //Tracev((stderr, "inflate: reset\n"));
- return Z_OK;
- }
- function inflateReset(strm) {
- var state;
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- state.wsize = 0;
- state.whave = 0;
- state.wnext = 0;
- return inflateResetKeep(strm);
- }
- function inflateReset2(strm, windowBits) {
- var wrap;
- var state;
- /* get the state */
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- /* extract wrap request from windowBits parameter */
- if (windowBits < 0) {
- wrap = 0;
- windowBits = -windowBits;
- }
- else {
- wrap = (windowBits >> 4) + 1;
- if (windowBits < 48) {
- windowBits &= 15;
- }
- }
- /* set number of window bits, free window if different */
- if (windowBits && (windowBits < 8 || windowBits > 15)) {
- return Z_STREAM_ERROR;
- }
- if (state.window !== null && state.wbits !== windowBits) {
- state.window = null;
- }
- /* update state and reset the rest of it */
- state.wrap = wrap;
- state.wbits = windowBits;
- return inflateReset(strm);
- }
- function inflateInit2(strm, windowBits) {
- var ret;
- var state;
- if (!strm) { return Z_STREAM_ERROR; }
- //strm.msg = Z_NULL; /* in case we return an error */
- state = new InflateState();
- //if (state === Z_NULL) return Z_MEM_ERROR;
- //Tracev((stderr, "inflate: allocated\n"));
- strm.state = state;
- state.window = null/*Z_NULL*/;
- ret = inflateReset2(strm, windowBits);
- if (ret !== Z_OK) {
- strm.state = null/*Z_NULL*/;
- }
- return ret;
- }
- function inflateInit(strm) {
- return inflateInit2(strm, DEF_WBITS);
- }
- /*
- Return state with length and distance decoding tables and index sizes set to
- fixed code decoding. Normally this returns fixed tables from inffixed.h.
- If BUILDFIXED is defined, then instead this routine builds the tables the
- first time it's called, and returns those tables the first time and
- thereafter. This reduces the size of the code by about 2K bytes, in
- exchange for a little execution time. However, BUILDFIXED should not be
- used for threaded applications, since the rewriting of the tables and virgin
- may not be thread-safe.
- */
- var virgin = true;
- var lenfix, distfix; // We have no pointers in JS, so keep tables separate
- function fixedtables(state) {
- /* build fixed huffman tables if first call (may not be thread safe) */
- if (virgin) {
- var sym;
- lenfix = new utils.Buf32(512);
- distfix = new utils.Buf32(32);
- /* literal/length table */
- sym = 0;
- while (sym < 144) { state.lens[sym++] = 8; }
- while (sym < 256) { state.lens[sym++] = 9; }
- while (sym < 280) { state.lens[sym++] = 7; }
- while (sym < 288) { state.lens[sym++] = 8; }
- inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
- /* distance table */
- sym = 0;
- while (sym < 32) { state.lens[sym++] = 5; }
- inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
- /* do this just once */
- virgin = false;
- }
- state.lencode = lenfix;
- state.lenbits = 9;
- state.distcode = distfix;
- state.distbits = 5;
- }
- /*
- Update the window with the last wsize (normally 32K) bytes written before
- returning. If window does not exist yet, create it. This is only called
- when a window is already in use, or when output has been written during this
- inflate call, but the end of the deflate stream has not been reached yet.
- It is also called to create a window for dictionary data when a dictionary
- is loaded.
- Providing output buffers larger than 32K to inflate() should provide a speed
- advantage, since only the last 32K of output is copied to the sliding window
- upon return from inflate(), and since all distances after the first 32K of
- output will fall in the output data, making match copies simpler and faster.
- The advantage may be dependent on the size of the processor's data caches.
- */
- function updatewindow(strm, src, end, copy) {
- var dist;
- var state = strm.state;
- /* if it hasn't been done already, allocate space for the window */
- if (state.window === null) {
- state.wsize = 1 << state.wbits;
- state.wnext = 0;
- state.whave = 0;
- state.window = new utils.Buf8(state.wsize);
- }
- /* copy state->wsize or less output bytes into the circular window */
- if (copy >= state.wsize) {
- utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
- state.wnext = 0;
- state.whave = state.wsize;
- }
- else {
- dist = state.wsize - state.wnext;
- if (dist > copy) {
- dist = copy;
- }
- //zmemcpy(state->window + state->wnext, end - copy, dist);
- utils.arraySet(state.window, src, end - copy, dist, state.wnext);
- copy -= dist;
- if (copy) {
- //zmemcpy(state->window, end - copy, copy);
- utils.arraySet(state.window, src, end - copy, copy, 0);
- state.wnext = copy;
- state.whave = state.wsize;
- }
- else {
- state.wnext += dist;
- if (state.wnext === state.wsize) { state.wnext = 0; }
- if (state.whave < state.wsize) { state.whave += dist; }
- }
- }
- return 0;
- }
- function inflate(strm, flush) {
- var state;
- var input, output; // input/output buffers
- var next; /* next input INDEX */
- var put; /* next output INDEX */
- var have, left; /* available input and output */
- var hold; /* bit buffer */
- var bits; /* bits in bit buffer */
- var _in, _out; /* save starting available input and output */
- var copy; /* number of stored or match bytes to copy */
- var from; /* where to copy match bytes from */
- var from_source;
- var here = 0; /* current decoding table entry */
- var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
- //var last; /* parent table entry */
- var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
- var len; /* length to copy for repeats, bits to drop */
- var ret; /* return code */
- var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
- var opts;
- var n; // temporary var for NEED_BITS
- var order = /* permutation of code lengths */
- [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
- if (!strm || !strm.state || !strm.output ||
- (!strm.input && strm.avail_in !== 0)) {
- return Z_STREAM_ERROR;
- }
- state = strm.state;
- if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
- //--- LOAD() ---
- put = strm.next_out;
- output = strm.output;
- left = strm.avail_out;
- next = strm.next_in;
- input = strm.input;
- have = strm.avail_in;
- hold = state.hold;
- bits = state.bits;
- //---
- _in = have;
- _out = left;
- ret = Z_OK;
- inf_leave: // goto emulation
- for (;;) {
- switch (state.mode) {
- case HEAD:
- if (state.wrap === 0) {
- state.mode = TYPEDO;
- break;
- }
- //=== NEEDBITS(16);
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
- state.check = 0/*crc32(0L, Z_NULL, 0)*/;
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = FLAGS;
- break;
- }
- state.flags = 0; /* expect zlib header */
- if (state.head) {
- state.head.done = false;
- }
- if (!(state.wrap & 1) || /* check if zlib header allowed */
- (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
- strm.msg = 'incorrect header check';
- state.mode = BAD;
- break;
- }
- if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
- strm.msg = 'unknown compression method';
- state.mode = BAD;
- break;
- }
- //--- DROPBITS(4) ---//
- hold >>>= 4;
- bits -= 4;
- //---//
- len = (hold & 0x0f)/*BITS(4)*/ + 8;
- if (state.wbits === 0) {
- state.wbits = len;
- }
- else if (len > state.wbits) {
- strm.msg = 'invalid window size';
- state.mode = BAD;
- break;
- }
- state.dmax = 1 << len;
- //Tracev((stderr, "inflate: zlib header ok\n"));
- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
- state.mode = hold & 0x200 ? DICTID : TYPE;
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- break;
- case FLAGS:
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.flags = hold;
- if ((state.flags & 0xff) !== Z_DEFLATED) {
- strm.msg = 'unknown compression method';
- state.mode = BAD;
- break;
- }
- if (state.flags & 0xe000) {
- strm.msg = 'unknown header flags set';
- state.mode = BAD;
- break;
- }
- if (state.head) {
- state.head.text = ((hold >> 8) & 1);
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = TIME;
- /* falls through */
- case TIME:
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (state.head) {
- state.head.time = hold;
- }
- if (state.flags & 0x0200) {
- //=== CRC4(state.check, hold)
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- hbuf[2] = (hold >>> 16) & 0xff;
- hbuf[3] = (hold >>> 24) & 0xff;
- state.check = crc32(state.check, hbuf, 4, 0);
- //===
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = OS;
- /* falls through */
- case OS:
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (state.head) {
- state.head.xflags = (hold & 0xff);
- state.head.os = (hold >> 8);
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = EXLEN;
- /* falls through */
- case EXLEN:
- if (state.flags & 0x0400) {
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.length = hold;
- if (state.head) {
- state.head.extra_len = hold;
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- }
- else if (state.head) {
- state.head.extra = null/*Z_NULL*/;
- }
- state.mode = EXTRA;
- /* falls through */
- case EXTRA:
- if (state.flags & 0x0400) {
- copy = state.length;
- if (copy > have) { copy = have; }
- if (copy) {
- if (state.head) {
- len = state.head.extra_len - state.length;
- if (!state.head.extra) {
- // Use untyped array for more conveniend processing later
- state.head.extra = new Array(state.head.extra_len);
- }
- utils.arraySet(
- state.head.extra,
- input,
- next,
- // extra field is limited to 65536 bytes
- // - no need for additional size check
- copy,
- /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
- len
- );
- //zmemcpy(state.head.extra + len, next,
- // len + copy > state.head.extra_max ?
- // state.head.extra_max - len : copy);
- }
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- state.length -= copy;
- }
- if (state.length) { break inf_leave; }
- }
- state.length = 0;
- state.mode = NAME;
- /* falls through */
- case NAME:
- if (state.flags & 0x0800) {
- if (have === 0) { break inf_leave; }
- copy = 0;
- do {
- // TODO: 2 or 1 bytes?
- len = input[next + copy++];
- /* use constant limit because in js we should not preallocate memory */
- if (state.head && len &&
- (state.length < 65536 /*state.head.name_max*/)) {
- state.head.name += String.fromCharCode(len);
- }
- } while (len && copy < have);
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- if (len) { break inf_leave; }
- }
- else if (state.head) {
- state.head.name = null;
- }
- state.length = 0;
- state.mode = COMMENT;
- /* falls through */
- case COMMENT:
- if (state.flags & 0x1000) {
- if (have === 0) { break inf_leave; }
- copy = 0;
- do {
- len = input[next + copy++];
- /* use constant limit because in js we should not preallocate memory */
- if (state.head && len &&
- (state.length < 65536 /*state.head.comm_max*/)) {
- state.head.comment += String.fromCharCode(len);
- }
- } while (len && copy < have);
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- if (len) { break inf_leave; }
- }
- else if (state.head) {
- state.head.comment = null;
- }
- state.mode = HCRC;
- /* falls through */
- case HCRC:
- if (state.flags & 0x0200) {
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (hold !== (state.check & 0xffff)) {
- strm.msg = 'header crc mismatch';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- }
- if (state.head) {
- state.head.hcrc = ((state.flags >> 9) & 1);
- state.head.done = true;
- }
- strm.adler = state.check = 0;
- state.mode = TYPE;
- break;
- case DICTID:
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- strm.adler = state.check = zswap32(hold);
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = DICT;
- /* falls through */
- case DICT:
- if (state.havedict === 0) {
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- return Z_NEED_DICT;
- }
- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
- state.mode = TYPE;
- /* falls through */
- case TYPE:
- if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case TYPEDO:
- if (state.last) {
- //--- BYTEBITS() ---//
- hold >>>= bits & 7;
- bits -= bits & 7;
- //---//
- state.mode = CHECK;
- break;
- }
- //=== NEEDBITS(3); */
- while (bits < 3) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.last = (hold & 0x01)/*BITS(1)*/;
- //--- DROPBITS(1) ---//
- hold >>>= 1;
- bits -= 1;
- //---//
- switch ((hold & 0x03)/*BITS(2)*/) {
- case 0: /* stored block */
- //Tracev((stderr, "inflate: stored block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = STORED;
- break;
- case 1: /* fixed block */
- fixedtables(state);
- //Tracev((stderr, "inflate: fixed codes block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = LEN_; /* decode codes */
- if (flush === Z_TREES) {
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- break inf_leave;
- }
- break;
- case 2: /* dynamic block */
- //Tracev((stderr, "inflate: dynamic codes block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = TABLE;
- break;
- case 3:
- strm.msg = 'invalid block type';
- state.mode = BAD;
- }
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- break;
- case STORED:
- //--- BYTEBITS() ---// /* go to byte boundary */
- hold >>>= bits & 7;
- bits -= bits & 7;
- //---//
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
- strm.msg = 'invalid stored block lengths';
- state.mode = BAD;
- break;
- }
- state.length = hold & 0xffff;
- //Tracev((stderr, "inflate: stored length %u\n",
- // state.length));
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = COPY_;
- if (flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case COPY_:
- state.mode = COPY;
- /* falls through */
- case COPY:
- copy = state.length;
- if (copy) {
- if (copy > have) { copy = have; }
- if (copy > left) { copy = left; }
- if (copy === 0) { break inf_leave; }
- //--- zmemcpy(put, next, copy); ---
- utils.arraySet(output, input, next, copy, put);
- //---//
- have -= copy;
- next += copy;
- left -= copy;
- put += copy;
- state.length -= copy;
- break;
- }
- //Tracev((stderr, "inflate: stored end\n"));
- state.mode = TYPE;
- break;
- case TABLE:
- //=== NEEDBITS(14); */
- while (bits < 14) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
- //--- DROPBITS(5) ---//
- hold >>>= 5;
- bits -= 5;
- //---//
- state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
- //--- DROPBITS(5) ---//
- hold >>>= 5;
- bits -= 5;
- //---//
- state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
- //--- DROPBITS(4) ---//
- hold >>>= 4;
- bits -= 4;
- //---//
- //#ifndef PKZIP_BUG_WORKAROUND
- if (state.nlen > 286 || state.ndist > 30) {
- strm.msg = 'too many length or distance symbols';
- state.mode = BAD;
- break;
- }
- //#endif
- //Tracev((stderr, "inflate: table sizes ok\n"));
- state.have = 0;
- state.mode = LENLENS;
- /* falls through */
- case LENLENS:
- while (state.have < state.ncode) {
- //=== NEEDBITS(3);
- while (bits < 3) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
- //--- DROPBITS(3) ---//
- hold >>>= 3;
- bits -= 3;
- //---//
- }
- while (state.have < 19) {
- state.lens[order[state.have++]] = 0;
- }
- // We have separate tables & no pointers. 2 commented lines below not needed.
- //state.next = state.codes;
- //state.lencode = state.next;
- // Switch to use dynamic table
- state.lencode = state.lendyn;
- state.lenbits = 7;
- opts = { bits: state.lenbits };
- ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
- state.lenbits = opts.bits;
- if (ret) {
- strm.msg = 'invalid code lengths set';
- state.mode = BAD;
- break;
- }
- //Tracev((stderr, "inflate: code lengths ok\n"));
- state.have = 0;
- state.mode = CODELENS;
- /* falls through */
- case CODELENS:
- while (state.have < state.nlen + state.ndist) {
- for (;;) {
- here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if (here_val < 16) {
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.lens[state.have++] = here_val;
- }
- else {
- if (here_val === 16) {
- //=== NEEDBITS(here.bits + 2);
- n = here_bits + 2;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- if (state.have === 0) {
- strm.msg = 'invalid bit length repeat';
- state.mode = BAD;
- break;
- }
- len = state.lens[state.have - 1];
- copy = 3 + (hold & 0x03);//BITS(2);
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- }
- else if (here_val === 17) {
- //=== NEEDBITS(here.bits + 3);
- n = here_bits + 3;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- len = 0;
- copy = 3 + (hold & 0x07);//BITS(3);
- //--- DROPBITS(3) ---//
- hold >>>= 3;
- bits -= 3;
- //---//
- }
- else {
- //=== NEEDBITS(here.bits + 7);
- n = here_bits + 7;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- len = 0;
- copy = 11 + (hold & 0x7f);//BITS(7);
- //--- DROPBITS(7) ---//
- hold >>>= 7;
- bits -= 7;
- //---//
- }
- if (state.have + copy > state.nlen + state.ndist) {
- strm.msg = 'invalid bit length repeat';
- state.mode = BAD;
- break;
- }
- while (copy--) {
- state.lens[state.have++] = len;
- }
- }
- }
- /* handle error breaks in while */
- if (state.mode === BAD) { break; }
- /* check for end-of-block code (better have one) */
- if (state.lens[256] === 0) {
- strm.msg = 'invalid code -- missing end-of-block';
- state.mode = BAD;
- break;
- }
- /* build code tables -- note: do not change the lenbits or distbits
- values here (9 and 6) without reading the comments in inftrees.h
- concerning the ENOUGH constants, which depend on those values */
- state.lenbits = 9;
- opts = { bits: state.lenbits };
- ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
- // We have separate tables & no pointers. 2 commented lines below not needed.
- // state.next_index = opts.table_index;
- state.lenbits = opts.bits;
- // state.lencode = state.next;
- if (ret) {
- strm.msg = 'invalid literal/lengths set';
- state.mode = BAD;
- break;
- }
- state.distbits = 6;
- //state.distcode.copy(state.codes);
- // Switch to use dynamic table
- state.distcode = state.distdyn;
- opts = { bits: state.distbits };
- ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
- // We have separate tables & no pointers. 2 commented lines below not needed.
- // state.next_index = opts.table_index;
- state.distbits = opts.bits;
- // state.distcode = state.next;
- if (ret) {
- strm.msg = 'invalid distances set';
- state.mode = BAD;
- break;
- }
- //Tracev((stderr, 'inflate: codes ok\n'));
- state.mode = LEN_;
- if (flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case LEN_:
- state.mode = LEN;
- /* falls through */
- case LEN:
- if (have >= 6 && left >= 258) {
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- inflate_fast(strm, _out);
- //--- LOAD() ---
- put = strm.next_out;
- output = strm.output;
- left = strm.avail_out;
- next = strm.next_in;
- input = strm.input;
- have = strm.avail_in;
- hold = state.hold;
- bits = state.bits;
- //---
- if (state.mode === TYPE) {
- state.back = -1;
- }
- break;
- }
- state.back = 0;
- for (;;) {
- here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if (here_bits <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if (here_op && (here_op & 0xf0) === 0) {
- last_bits = here_bits;
- last_op = here_op;
- last_val = here_val;
- for (;;) {
- here = state.lencode[last_val +
- ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((last_bits + here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- //--- DROPBITS(last.bits) ---//
- hold >>>= last_bits;
- bits -= last_bits;
- //---//
- state.back += last_bits;
- }
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.back += here_bits;
- state.length = here_val;
- if (here_op === 0) {
- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
- // "inflate: literal '%c'\n" :
- // "inflate: literal 0x%02x\n", here.val));
- state.mode = LIT;
- break;
- }
- if (here_op & 32) {
- //Tracevv((stderr, "inflate: end of block\n"));
- state.back = -1;
- state.mode = TYPE;
- break;
- }
- if (here_op & 64) {
- strm.msg = 'invalid literal/length code';
- state.mode = BAD;
- break;
- }
- state.extra = here_op & 15;
- state.mode = LENEXT;
- /* falls through */
- case LENEXT:
- if (state.extra) {
- //=== NEEDBITS(state.extra);
- n = state.extra;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
- //--- DROPBITS(state.extra) ---//
- hold >>>= state.extra;
- bits -= state.extra;
- //---//
- state.back += state.extra;
- }
- //Tracevv((stderr, "inflate: length %u\n", state.length));
- state.was = state.length;
- state.mode = DIST;
- /* falls through */
- case DIST:
- for (;;) {
- here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if ((here_op & 0xf0) === 0) {
- last_bits = here_bits;
- last_op = here_op;
- last_val = here_val;
- for (;;) {
- here = state.distcode[last_val +
- ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
- if ((last_bits + here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- //--- DROPBITS(last.bits) ---//
- hold >>>= last_bits;
- bits -= last_bits;
- //---//
- state.back += last_bits;
- }
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.back += here_bits;
- if (here_op & 64) {
- strm.msg = 'invalid distance code';
- state.mode = BAD;
- break;
- }
- state.offset = here_val;
- state.extra = (here_op) & 15;
- state.mode = DISTEXT;
- /* falls through */
- case DISTEXT:
- if (state.extra) {
- //=== NEEDBITS(state.extra);
- n = state.extra;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
- //--- DROPBITS(state.extra) ---//
- hold >>>= state.extra;
- bits -= state.extra;
- //---//
- state.back += state.extra;
- }
- //#ifdef INFLATE_STRICT
- if (state.offset > state.dmax) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break;
- }
- //#endif
- //Tracevv((stderr, "inflate: distance %u\n", state.offset));
- state.mode = MATCH;
- /* falls through */
- case MATCH:
- if (left === 0) { break inf_leave; }
- copy = _out - left;
- if (state.offset > copy) { /* copy from window */
- copy = state.offset - copy;
- if (copy > state.whave) {
- if (state.sane) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break;
- }
- // (!) This block is disabled in zlib defailts,
- // don't enable it for binary compatibility
- //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
- // Trace((stderr, "inflate.c too far\n"));
- // copy -= state.whave;
- // if (copy > state.length) { copy = state.length; }
- // if (copy > left) { copy = left; }
- // left -= copy;
- // state.length -= copy;
- // do {
- // output[put++] = 0;
- // } while (--copy);
- // if (state.length === 0) { state.mode = LEN; }
- // break;
- //#endif
- }
- if (copy > state.wnext) {
- copy -= state.wnext;
- from = state.wsize - copy;
- }
- else {
- from = state.wnext - copy;
- }
- if (copy > state.length) { copy = state.length; }
- from_source = state.window;
- }
- else { /* copy from output */
- from_source = output;
- from = put - state.offset;
- copy = state.length;
- }
- if (copy > left) { copy = left; }
- left -= copy;
- state.length -= copy;
- do {
- output[put++] = from_source[from++];
- } while (--copy);
- if (state.length === 0) { state.mode = LEN; }
- break;
- case LIT:
- if (left === 0) { break inf_leave; }
- output[put++] = state.length;
- left--;
- state.mode = LEN;
- break;
- case CHECK:
- if (state.wrap) {
- //=== NEEDBITS(32);
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- // Use '|' insdead of '+' to make sure that result is signed
- hold |= input[next++] << bits;
- bits += 8;
- }
- //===//
- _out -= left;
- strm.total_out += _out;
- state.total += _out;
- if (_out) {
- strm.adler = state.check =
- /*UPDATE(state.check, put - _out, _out);*/
- (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
- }
- _out = left;
- // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
- if ((state.flags ? hold : zswap32(hold)) !== state.check) {
- strm.msg = 'incorrect data check';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- //Tracev((stderr, "inflate: check matches trailer\n"));
- }
- state.mode = LENGTH;
- /* falls through */
- case LENGTH:
- if (state.wrap && state.flags) {
- //=== NEEDBITS(32);
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (hold !== (state.total & 0xffffffff)) {
- strm.msg = 'incorrect length check';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- //Tracev((stderr, "inflate: length matches trailer\n"));
- }
- state.mode = DONE;
- /* falls through */
- case DONE:
- ret = Z_STREAM_END;
- break inf_leave;
- case BAD:
- ret = Z_DATA_ERROR;
- break inf_leave;
- case MEM:
- return Z_MEM_ERROR;
- case SYNC:
- /* falls through */
- default:
- return Z_STREAM_ERROR;
- }
- }
- // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
- /*
- Return from inflate(), updating the total counts and the check value.
- If there was no progress during the inflate() call, return a buffer
- error. Call updatewindow() to create and/or update the window state.
- Note: a memory error from inflate() is non-recoverable.
- */
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
- (state.mode < CHECK || flush !== Z_FINISH))) {
- if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
- state.mode = MEM;
- return Z_MEM_ERROR;
- }
- }
- _in -= strm.avail_in;
- _out -= strm.avail_out;
- strm.total_in += _in;
- strm.total_out += _out;
- state.total += _out;
- if (state.wrap && _out) {
- strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
- (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
- }
- strm.data_type = state.bits + (state.last ? 64 : 0) +
- (state.mode === TYPE ? 128 : 0) +
- (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
- if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
- ret = Z_BUF_ERROR;
- }
- return ret;
- }
- function inflateEnd(strm) {
- if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
- return Z_STREAM_ERROR;
- }
- var state = strm.state;
- if (state.window) {
- state.window = null;
- }
- strm.state = null;
- return Z_OK;
- }
- function inflateGetHeader(strm, head) {
- var state;
- /* check state */
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
- /* save header structure */
- state.head = head;
- head.done = false;
- return Z_OK;
- }
- function inflateSetDictionary(strm, dictionary) {
- var dictLength = dictionary.length;
- var state;
- var dictid;
- var ret;
- /* check state */
- if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
- state = strm.state;
- if (state.wrap !== 0 && state.mode !== DICT) {
- return Z_STREAM_ERROR;
- }
- /* check for correct dictionary identifier */
- if (state.mode === DICT) {
- dictid = 1; /* adler32(0, null, 0)*/
- /* dictid = adler32(dictid, dictionary, dictLength); */
- dictid = adler32(dictid, dictionary, dictLength, 0);
- if (dictid !== state.check) {
- return Z_DATA_ERROR;
- }
- }
- /* copy dictionary to window using updatewindow(), which will amend the
- existing dictionary if appropriate */
- ret = updatewindow(strm, dictionary, dictLength, dictLength);
- if (ret) {
- state.mode = MEM;
- return Z_MEM_ERROR;
- }
- state.havedict = 1;
- // Tracev((stderr, "inflate: dictionary set\n"));
- return Z_OK;
- }
- exports.inflateReset = inflateReset;
- exports.inflateReset2 = inflateReset2;
- exports.inflateResetKeep = inflateResetKeep;
- exports.inflateInit = inflateInit;
- exports.inflateInit2 = inflateInit2;
- exports.inflate = inflate;
- exports.inflateEnd = inflateEnd;
- exports.inflateGetHeader = inflateGetHeader;
- exports.inflateSetDictionary = inflateSetDictionary;
- exports.inflateInfo = 'pako inflate (from Nodeca project)';
- /* Not implemented
- exports.inflateCopy = inflateCopy;
- exports.inflateGetDictionary = inflateGetDictionary;
- exports.inflateMark = inflateMark;
- exports.inflatePrime = inflatePrime;
- exports.inflateSync = inflateSync;
- exports.inflateSyncPoint = inflateSyncPoint;
- exports.inflateUndermine = inflateUndermine;
- */
- },{"../utils/common":123,"./adler32":125,"./crc32":127,"./inffast":130,"./inftrees":132}],132:[function(require,module,exports){
- 'use strict';
- var utils = require('../utils/common');
- var MAXBITS = 15;
- var ENOUGH_LENS = 852;
- var ENOUGH_DISTS = 592;
- //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
- var CODES = 0;
- var LENS = 1;
- var DISTS = 2;
- var lbase = [ /* Length codes 257..285 base */
- 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
- 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
- ];
- var lext = [ /* Length codes 257..285 extra */
- 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
- 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
- ];
- var dbase = [ /* Distance codes 0..29 base */
- 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
- 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
- 8193, 12289, 16385, 24577, 0, 0
- ];
- var dext = [ /* Distance codes 0..29 extra */
- 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
- 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
- 28, 28, 29, 29, 64, 64
- ];
- module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
- {
- var bits = opts.bits;
- //here = opts.here; /* table entry for duplication */
- var len = 0; /* a code's length in bits */
- var sym = 0; /* index of code symbols */
- var min = 0, max = 0; /* minimum and maximum code lengths */
- var root = 0; /* number of index bits for root table */
- var curr = 0; /* number of index bits for current table */
- var drop = 0; /* code bits to drop for sub-table */
- var left = 0; /* number of prefix codes available */
- var used = 0; /* code entries in table used */
- var huff = 0; /* Huffman code */
- var incr; /* for incrementing code, index */
- var fill; /* index for replicating entries */
- var low; /* low bits for current root entry */
- var mask; /* mask for low root bits */
- var next; /* next available space in table */
- var base = null; /* base value table to use */
- var base_index = 0;
- // var shoextra; /* extra bits table to use */
- var end; /* use base and extra for symbol > end */
- var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
- var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
- var extra = null;
- var extra_index = 0;
- var here_bits, here_op, here_val;
- /*
- Process a set of code lengths to create a canonical Huffman code. The
- code lengths are lens[0..codes-1]. Each length corresponds to the
- symbols 0..codes-1. The Huffman code is generated by first sorting the
- symbols by length from short to long, and retaining the symbol order
- for codes with equal lengths. Then the code starts with all zero bits
- for the first code of the shortest length, and the codes are integer
- increments for the same length, and zeros are appended as the length
- increases. For the deflate format, these bits are stored backwards
- from their more natural integer increment ordering, and so when the
- decoding tables are built in the large loop below, the integer codes
- are incremented backwards.
- This routine assumes, but does not check, that all of the entries in
- lens[] are in the range 0..MAXBITS. The caller must assure this.
- 1..MAXBITS is interpreted as that code length. zero means that that
- symbol does not occur in this code.
- The codes are sorted by computing a count of codes for each length,
- creating from that a table of starting indices for each length in the
- sorted table, and then entering the symbols in order in the sorted
- table. The sorted table is work[], with that space being provided by
- the caller.
- The length counts are used for other purposes as well, i.e. finding
- the minimum and maximum length codes, determining if there are any
- codes at all, checking for a valid set of lengths, and looking ahead
- at length counts to determine sub-table sizes when building the
- decoding tables.
- */
- /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
- for (len = 0; len <= MAXBITS; len++) {
- count[len] = 0;
- }
- for (sym = 0; sym < codes; sym++) {
- count[lens[lens_index + sym]]++;
- }
- /* bound code lengths, force root to be within code lengths */
- root = bits;
- for (max = MAXBITS; max >= 1; max--) {
- if (count[max] !== 0) { break; }
- }
- if (root > max) {
- root = max;
- }
- if (max === 0) { /* no symbols to code at all */
- //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
- //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
- //table.val[opts.table_index++] = 0; //here.val = (var short)0;
- table[table_index++] = (1 << 24) | (64 << 16) | 0;
- //table.op[opts.table_index] = 64;
- //table.bits[opts.table_index] = 1;
- //table.val[opts.table_index++] = 0;
- table[table_index++] = (1 << 24) | (64 << 16) | 0;
- opts.bits = 1;
- return 0; /* no symbols, but wait for decoding to report error */
- }
- for (min = 1; min < max; min++) {
- if (count[min] !== 0) { break; }
- }
- if (root < min) {
- root = min;
- }
- /* check for an over-subscribed or incomplete set of lengths */
- left = 1;
- for (len = 1; len <= MAXBITS; len++) {
- left <<= 1;
- left -= count[len];
- if (left < 0) {
- return -1;
- } /* over-subscribed */
- }
- if (left > 0 && (type === CODES || max !== 1)) {
- return -1; /* incomplete set */
- }
- /* generate offsets into symbol table for each length for sorting */
- offs[1] = 0;
- for (len = 1; len < MAXBITS; len++) {
- offs[len + 1] = offs[len] + count[len];
- }
- /* sort symbols by length, by symbol order within each length */
- for (sym = 0; sym < codes; sym++) {
- if (lens[lens_index + sym] !== 0) {
- work[offs[lens[lens_index + sym]]++] = sym;
- }
- }
- /*
- Create and fill in decoding tables. In this loop, the table being
- filled is at next and has curr index bits. The code being used is huff
- with length len. That code is converted to an index by dropping drop
- bits off of the bottom. For codes where len is less than drop + curr,
- those top drop + curr - len bits are incremented through all values to
- fill the table with replicated entries.
- root is the number of index bits for the root table. When len exceeds
- root, sub-tables are created pointed to by the root entry with an index
- of the low root bits of huff. This is saved in low to check for when a
- new sub-table should be started. drop is zero when the root table is
- being filled, and drop is root when sub-tables are being filled.
- When a new sub-table is needed, it is necessary to look ahead in the
- code lengths to determine what size sub-table is needed. The length
- counts are used for this, and so count[] is decremented as codes are
- entered in the tables.
- used keeps track of how many table entries have been allocated from the
- provided *table space. It is checked for LENS and DIST tables against
- the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
- the initial root table size constants. See the comments in inftrees.h
- for more information.
- sym increments through all symbols, and the loop terminates when
- all codes of length max, i.e. all codes, have been processed. This
- routine permits incomplete codes, so another loop after this one fills
- in the rest of the decoding tables with invalid code markers.
- */
- /* set up for code type */
- // poor man optimization - use if-else instead of switch,
- // to avoid deopts in old v8
- if (type === CODES) {
- base = extra = work; /* dummy value--not used */
- end = 19;
- } else if (type === LENS) {
- base = lbase;
- base_index -= 257;
- extra = lext;
- extra_index -= 257;
- end = 256;
- } else { /* DISTS */
- base = dbase;
- extra = dext;
- end = -1;
- }
- /* initialize opts for loop */
- huff = 0; /* starting code */
- sym = 0; /* starting code symbol */
- len = min; /* starting code length */
- next = table_index; /* current table to fill in */
- curr = root; /* current table index bits */
- drop = 0; /* current bits to drop from code for index */
- low = -1; /* trigger new sub-table when len > root */
- used = 1 << root; /* use root table entries */
- mask = used - 1; /* mask for comparing low */
- /* check available table space */
- if ((type === LENS && used > ENOUGH_LENS) ||
- (type === DISTS && used > ENOUGH_DISTS)) {
- return 1;
- }
- var i = 0;
- /* process all codes and make table entries */
- for (;;) {
- i++;
- /* create table entry */
- here_bits = len - drop;
- if (work[sym] < end) {
- here_op = 0;
- here_val = work[sym];
- }
- else if (work[sym] > end) {
- here_op = extra[extra_index + work[sym]];
- here_val = base[base_index + work[sym]];
- }
- else {
- here_op = 32 + 64; /* end of block */
- here_val = 0;
- }
- /* replicate for those indices with low len bits equal to huff */
- incr = 1 << (len - drop);
- fill = 1 << curr;
- min = fill; /* save offset to next table */
- do {
- fill -= incr;
- table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
- } while (fill !== 0);
- /* backwards increment the len-bit code huff */
- incr = 1 << (len - 1);
- while (huff & incr) {
- incr >>= 1;
- }
- if (incr !== 0) {
- huff &= incr - 1;
- huff += incr;
- } else {
- huff = 0;
- }
- /* go to next symbol, update count, len */
- sym++;
- if (--count[len] === 0) {
- if (len === max) { break; }
- len = lens[lens_index + work[sym]];
- }
- /* create new sub-table if needed */
- if (len > root && (huff & mask) !== low) {
- /* if first time, transition to sub-tables */
- if (drop === 0) {
- drop = root;
- }
- /* increment past last table */
- next += min; /* here min is 1 << curr */
- /* determine length of next table */
- curr = len - drop;
- left = 1 << curr;
- while (curr + drop < max) {
- left -= count[curr + drop];
- if (left <= 0) { break; }
- curr++;
- left <<= 1;
- }
- /* check for enough space */
- used += 1 << curr;
- if ((type === LENS && used > ENOUGH_LENS) ||
- (type === DISTS && used > ENOUGH_DISTS)) {
- return 1;
- }
- /* point entry in root table to sub-table */
- low = huff & mask;
- /*table.op[low] = curr;
- table.bits[low] = root;
- table.val[low] = next - opts.table_index;*/
- table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
- }
- }
- /* fill in remaining table entry if code is incomplete (guaranteed to have
- at most one remaining entry, since if the code is incomplete, the
- maximum code length that was allowed to get this far is one bit) */
- if (huff !== 0) {
- //table.op[next + huff] = 64; /* invalid code marker */
- //table.bits[next + huff] = len - drop;
- //table.val[next + huff] = 0;
- table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
- }
- /* set return parameters */
- //opts.table_index += used;
- opts.bits = root;
- return 0;
- };
- },{"../utils/common":123}],133:[function(require,module,exports){
- 'use strict';
- module.exports = {
- 2: 'need dictionary', /* Z_NEED_DICT 2 */
- 1: 'stream end', /* Z_STREAM_END 1 */
- 0: '', /* Z_OK 0 */
- '-1': 'file error', /* Z_ERRNO (-1) */
- '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
- '-3': 'data error', /* Z_DATA_ERROR (-3) */
- '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
- '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
- '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
- };
- },{}],134:[function(require,module,exports){
- 'use strict';
- var utils = require('../utils/common');
- /* Public constants ==========================================================*/
- /* ===========================================================================*/
- //var Z_FILTERED = 1;
- //var Z_HUFFMAN_ONLY = 2;
- //var Z_RLE = 3;
- var Z_FIXED = 4;
- //var Z_DEFAULT_STRATEGY = 0;
- /* Possible values of the data_type field (though see inflate()) */
- var Z_BINARY = 0;
- var Z_TEXT = 1;
- //var Z_ASCII = 1; // = Z_TEXT
- var Z_UNKNOWN = 2;
- /*============================================================================*/
- function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
- // From zutil.h
- var STORED_BLOCK = 0;
- var STATIC_TREES = 1;
- var DYN_TREES = 2;
- /* The three kinds of block type */
- var MIN_MATCH = 3;
- var MAX_MATCH = 258;
- /* The minimum and maximum match lengths */
- // From deflate.h
- /* ===========================================================================
- * Internal compression state.
- */
- var LENGTH_CODES = 29;
- /* number of length codes, not counting the special END_BLOCK code */
- var LITERALS = 256;
- /* number of literal bytes 0..255 */
- var L_CODES = LITERALS + 1 + LENGTH_CODES;
- /* number of Literal or Length codes, including the END_BLOCK code */
- var D_CODES = 30;
- /* number of distance codes */
- var BL_CODES = 19;
- /* number of codes used to transfer the bit lengths */
- var HEAP_SIZE = 2 * L_CODES + 1;
- /* maximum heap size */
- var MAX_BITS = 15;
- /* All codes must not exceed MAX_BITS bits */
- var Buf_size = 16;
- /* size of bit buffer in bi_buf */
- /* ===========================================================================
- * Constants
- */
- var MAX_BL_BITS = 7;
- /* Bit length codes must not exceed MAX_BL_BITS bits */
- var END_BLOCK = 256;
- /* end of block literal code */
- var REP_3_6 = 16;
- /* repeat previous bit length 3-6 times (2 bits of repeat count) */
- var REPZ_3_10 = 17;
- /* repeat a zero length 3-10 times (3 bits of repeat count) */
- var REPZ_11_138 = 18;
- /* repeat a zero length 11-138 times (7 bits of repeat count) */
- /* eslint-disable comma-spacing,array-bracket-spacing */
- var extra_lbits = /* extra bits for each length code */
- [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];
- var extra_dbits = /* extra bits for each distance code */
- [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];
- var extra_blbits = /* extra bits for each bit length code */
- [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
- var bl_order =
- [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
- /* eslint-enable comma-spacing,array-bracket-spacing */
- /* The lengths of the bit length codes are sent in order of decreasing
- * probability, to avoid transmitting the lengths for unused bit length codes.
- */
- /* ===========================================================================
- * Local data. These are initialized only once.
- */
- // We pre-fill arrays with 0 to avoid uninitialized gaps
- var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
- // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
- var static_ltree = new Array((L_CODES + 2) * 2);
- zero(static_ltree);
- /* The static literal tree. Since the bit lengths are imposed, there is no
- * need for the L_CODES extra codes used during heap construction. However
- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
- * below).
- */
- var static_dtree = new Array(D_CODES * 2);
- zero(static_dtree);
- /* The static distance tree. (Actually a trivial tree since all codes use
- * 5 bits.)
- */
- var _dist_code = new Array(DIST_CODE_LEN);
- zero(_dist_code);
- /* Distance codes. The first 256 values correspond to the distances
- * 3 .. 258, the last 256 values correspond to the top 8 bits of
- * the 15 bit distances.
- */
- var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
- zero(_length_code);
- /* length code for each normalized match length (0 == MIN_MATCH) */
- var base_length = new Array(LENGTH_CODES);
- zero(base_length);
- /* First normalized length for each code (0 = MIN_MATCH) */
- var base_dist = new Array(D_CODES);
- zero(base_dist);
- /* First normalized distance for each code (0 = distance of 1) */
- function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
- this.static_tree = static_tree; /* static tree or NULL */
- this.extra_bits = extra_bits; /* extra bits for each code or NULL */
- this.extra_base = extra_base; /* base index for extra_bits */
- this.elems = elems; /* max number of elements in the tree */
- this.max_length = max_length; /* max bit length for the codes */
- // show if `static_tree` has data or dummy - needed for monomorphic objects
- this.has_stree = static_tree && static_tree.length;
- }
- var static_l_desc;
- var static_d_desc;
- var static_bl_desc;
- function TreeDesc(dyn_tree, stat_desc) {
- this.dyn_tree = dyn_tree; /* the dynamic tree */
- this.max_code = 0; /* largest code with non zero frequency */
- this.stat_desc = stat_desc; /* the corresponding static tree */
- }
- function d_code(dist) {
- return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
- }
- /* ===========================================================================
- * Output a short LSB first on the stream.
- * IN assertion: there is enough room in pendingBuf.
- */
- function put_short(s, w) {
- // put_byte(s, (uch)((w) & 0xff));
- // put_byte(s, (uch)((ush)(w) >> 8));
- s.pending_buf[s.pending++] = (w) & 0xff;
- s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
- }
- /* ===========================================================================
- * Send a value on a given number of bits.
- * IN assertion: length <= 16 and value fits in length bits.
- */
- function send_bits(s, value, length) {
- if (s.bi_valid > (Buf_size - length)) {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- put_short(s, s.bi_buf);
- s.bi_buf = value >> (Buf_size - s.bi_valid);
- s.bi_valid += length - Buf_size;
- } else {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- s.bi_valid += length;
- }
- }
- function send_code(s, c, tree) {
- send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
- }
- /* ===========================================================================
- * Reverse the first len bits of a code, using straightforward code (a faster
- * method would use a table)
- * IN assertion: 1 <= len <= 15
- */
- function bi_reverse(code, len) {
- var res = 0;
- do {
- res |= code & 1;
- code >>>= 1;
- res <<= 1;
- } while (--len > 0);
- return res >>> 1;
- }
- /* ===========================================================================
- * Flush the bit buffer, keeping at most 7 bits in it.
- */
- function bi_flush(s) {
- if (s.bi_valid === 16) {
- put_short(s, s.bi_buf);
- s.bi_buf = 0;
- s.bi_valid = 0;
- } else if (s.bi_valid >= 8) {
- s.pending_buf[s.pending++] = s.bi_buf & 0xff;
- s.bi_buf >>= 8;
- s.bi_valid -= 8;
- }
- }
- /* ===========================================================================
- * Compute the optimal bit lengths for a tree and update the total bit length
- * for the current block.
- * IN assertion: the fields freq and dad are set, heap[heap_max] and
- * above are the tree nodes sorted by increasing frequency.
- * OUT assertions: the field len is set to the optimal bit length, the
- * array bl_count contains the frequencies for each bit length.
- * The length opt_len is updated; static_len is also updated if stree is
- * not null.
- */
- function gen_bitlen(s, desc)
- // deflate_state *s;
- // tree_desc *desc; /* the tree descriptor */
- {
- var tree = desc.dyn_tree;
- var max_code = desc.max_code;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var extra = desc.stat_desc.extra_bits;
- var base = desc.stat_desc.extra_base;
- var max_length = desc.stat_desc.max_length;
- var h; /* heap index */
- var n, m; /* iterate over the tree elements */
- var bits; /* bit length */
- var xbits; /* extra bits */
- var f; /* frequency */
- var overflow = 0; /* number of elements with bit length too large */
- for (bits = 0; bits <= MAX_BITS; bits++) {
- s.bl_count[bits] = 0;
- }
- /* In a first pass, compute the optimal bit lengths (which may
- * overflow in the case of the bit length tree).
- */
- tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
- for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
- n = s.heap[h];
- bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
- if (bits > max_length) {
- bits = max_length;
- overflow++;
- }
- tree[n * 2 + 1]/*.Len*/ = bits;
- /* We overwrite tree[n].Dad which is no longer needed */
- if (n > max_code) { continue; } /* not a leaf node */
- s.bl_count[bits]++;
- xbits = 0;
- if (n >= base) {
- xbits = extra[n - base];
- }
- f = tree[n * 2]/*.Freq*/;
- s.opt_len += f * (bits + xbits);
- if (has_stree) {
- s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
- }
- }
- if (overflow === 0) { return; }
- // Trace((stderr,"\nbit length overflow\n"));
- /* This happens for example on obj2 and pic of the Calgary corpus */
- /* Find the first bit length which could increase: */
- do {
- bits = max_length - 1;
- while (s.bl_count[bits] === 0) { bits--; }
- s.bl_count[bits]--; /* move one leaf down the tree */
- s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
- s.bl_count[max_length]--;
- /* The brother of the overflow item also moves one step up,
- * but this does not affect bl_count[max_length]
- */
- overflow -= 2;
- } while (overflow > 0);
- /* Now recompute all bit lengths, scanning in increasing frequency.
- * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
- * lengths instead of fixing only the wrong ones. This idea is taken
- * from 'ar' written by Haruhiko Okumura.)
- */
- for (bits = max_length; bits !== 0; bits--) {
- n = s.bl_count[bits];
- while (n !== 0) {
- m = s.heap[--h];
- if (m > max_code) { continue; }
- if (tree[m * 2 + 1]/*.Len*/ !== bits) {
- // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
- s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
- tree[m * 2 + 1]/*.Len*/ = bits;
- }
- n--;
- }
- }
- }
- /* ===========================================================================
- * Generate the codes for a given tree and bit counts (which need not be
- * optimal).
- * IN assertion: the array bl_count contains the bit length statistics for
- * the given tree and the field len is set for all tree elements.
- * OUT assertion: the field code is set for all tree elements of non
- * zero code length.
- */
- function gen_codes(tree, max_code, bl_count)
- // ct_data *tree; /* the tree to decorate */
- // int max_code; /* largest code with non zero frequency */
- // ushf *bl_count; /* number of codes at each bit length */
- {
- var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
- var code = 0; /* running code value */
- var bits; /* bit index */
- var n; /* code index */
- /* The distribution counts are first used to generate the code values
- * without bit reversal.
- */
- for (bits = 1; bits <= MAX_BITS; bits++) {
- next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
- }
- /* Check that the bit counts in bl_count are consistent. The last code
- * must be all ones.
- */
- //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
- // "inconsistent bit counts");
- //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
- for (n = 0; n <= max_code; n++) {
- var len = tree[n * 2 + 1]/*.Len*/;
- if (len === 0) { continue; }
- /* Now reverse the bits */
- tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
- //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
- // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
- }
- }
- /* ===========================================================================
- * Initialize the various 'constant' tables.
- */
- function tr_static_init() {
- var n; /* iterates over tree elements */
- var bits; /* bit counter */
- var length; /* length value */
- var code; /* code value */
- var dist; /* distance index */
- var bl_count = new Array(MAX_BITS + 1);
- /* number of codes at each bit length for an optimal tree */
- // do check in _tr_init()
- //if (static_init_done) return;
- /* For some embedded targets, global variables are not initialized: */
- /*#ifdef NO_INIT_GLOBAL_POINTERS
- static_l_desc.static_tree = static_ltree;
- static_l_desc.extra_bits = extra_lbits;
- static_d_desc.static_tree = static_dtree;
- static_d_desc.extra_bits = extra_dbits;
- static_bl_desc.extra_bits = extra_blbits;
- #endif*/
- /* Initialize the mapping length (0..255) -> length code (0..28) */
- length = 0;
- for (code = 0; code < LENGTH_CODES - 1; code++) {
- base_length[code] = length;
- for (n = 0; n < (1 << extra_lbits[code]); n++) {
- _length_code[length++] = code;
- }
- }
- //Assert (length == 256, "tr_static_init: length != 256");
- /* Note that the length 255 (match length 258) can be represented
- * in two different ways: code 284 + 5 bits or code 285, so we
- * overwrite length_code[255] to use the best encoding:
- */
- _length_code[length - 1] = code;
- /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
- dist = 0;
- for (code = 0; code < 16; code++) {
- base_dist[code] = dist;
- for (n = 0; n < (1 << extra_dbits[code]); n++) {
- _dist_code[dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: dist != 256");
- dist >>= 7; /* from now on, all distances are divided by 128 */
- for (; code < D_CODES; code++) {
- base_dist[code] = dist << 7;
- for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
- _dist_code[256 + dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: 256+dist != 512");
- /* Construct the codes of the static literal tree */
- for (bits = 0; bits <= MAX_BITS; bits++) {
- bl_count[bits] = 0;
- }
- n = 0;
- while (n <= 143) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- while (n <= 255) {
- static_ltree[n * 2 + 1]/*.Len*/ = 9;
- n++;
- bl_count[9]++;
- }
- while (n <= 279) {
- static_ltree[n * 2 + 1]/*.Len*/ = 7;
- n++;
- bl_count[7]++;
- }
- while (n <= 287) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- /* Codes 286 and 287 do not exist, but we must include them in the
- * tree construction to get a canonical Huffman tree (longest code
- * all ones)
- */
- gen_codes(static_ltree, L_CODES + 1, bl_count);
- /* The static distance tree is trivial: */
- for (n = 0; n < D_CODES; n++) {
- static_dtree[n * 2 + 1]/*.Len*/ = 5;
- static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
- }
- // Now data ready and we can init static trees
- static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
- static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
- static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
- //static_init_done = true;
- }
- /* ===========================================================================
- * Initialize a new block.
- */
- function init_block(s) {
- var n; /* iterates over tree elements */
- /* Initialize the trees. */
- for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
- s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
- s.opt_len = s.static_len = 0;
- s.last_lit = s.matches = 0;
- }
- /* ===========================================================================
- * Flush the bit buffer and align the output on a byte boundary
- */
- function bi_windup(s)
- {
- if (s.bi_valid > 8) {
- put_short(s, s.bi_buf);
- } else if (s.bi_valid > 0) {
- //put_byte(s, (Byte)s->bi_buf);
- s.pending_buf[s.pending++] = s.bi_buf;
- }
- s.bi_buf = 0;
- s.bi_valid = 0;
- }
- /* ===========================================================================
- * Copy a stored block, storing first the length and its
- * one's complement if requested.
- */
- function copy_block(s, buf, len, header)
- //DeflateState *s;
- //charf *buf; /* the input data */
- //unsigned len; /* its length */
- //int header; /* true if block header must be written */
- {
- bi_windup(s); /* align on byte boundary */
- if (header) {
- put_short(s, len);
- put_short(s, ~len);
- }
- // while (len--) {
- // put_byte(s, *buf++);
- // }
- utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
- s.pending += len;
- }
- /* ===========================================================================
- * Compares to subtrees, using the tree depth as tie breaker when
- * the subtrees have equal frequency. This minimizes the worst case length.
- */
- function smaller(tree, n, m, depth) {
- var _n2 = n * 2;
- var _m2 = m * 2;
- return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
- (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
- }
- /* ===========================================================================
- * Restore the heap property by moving down the tree starting at node k,
- * exchanging a node with the smallest of its two sons if necessary, stopping
- * when the heap property is re-established (each father smaller than its
- * two sons).
- */
- function pqdownheap(s, tree, k)
- // deflate_state *s;
- // ct_data *tree; /* the tree to restore */
- // int k; /* node to move down */
- {
- var v = s.heap[k];
- var j = k << 1; /* left son of k */
- while (j <= s.heap_len) {
- /* Set j to the smallest of the two sons: */
- if (j < s.heap_len &&
- smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
- j++;
- }
- /* Exit if v is smaller than both sons */
- if (smaller(tree, v, s.heap[j], s.depth)) { break; }
- /* Exchange v with the smallest son */
- s.heap[k] = s.heap[j];
- k = j;
- /* And continue down the tree, setting j to the left son of k */
- j <<= 1;
- }
- s.heap[k] = v;
- }
- // inlined manually
- // var SMALLEST = 1;
- /* ===========================================================================
- * Send the block data compressed using the given Huffman trees
- */
- function compress_block(s, ltree, dtree)
- // deflate_state *s;
- // const ct_data *ltree; /* literal tree */
- // const ct_data *dtree; /* distance tree */
- {
- var dist; /* distance of matched string */
- var lc; /* match length or unmatched char (if dist == 0) */
- var lx = 0; /* running index in l_buf */
- var code; /* the code to send */
- var extra; /* number of extra bits to send */
- if (s.last_lit !== 0) {
- do {
- dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
- lc = s.pending_buf[s.l_buf + lx];
- lx++;
- if (dist === 0) {
- send_code(s, lc, ltree); /* send a literal byte */
- //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
- } else {
- /* Here, lc is the match length - MIN_MATCH */
- code = _length_code[lc];
- send_code(s, code + LITERALS + 1, ltree); /* send the length code */
- extra = extra_lbits[code];
- if (extra !== 0) {
- lc -= base_length[code];
- send_bits(s, lc, extra); /* send the extra length bits */
- }
- dist--; /* dist is now the match distance - 1 */
- code = d_code(dist);
- //Assert (code < D_CODES, "bad d_code");
- send_code(s, code, dtree); /* send the distance code */
- extra = extra_dbits[code];
- if (extra !== 0) {
- dist -= base_dist[code];
- send_bits(s, dist, extra); /* send the extra distance bits */
- }
- } /* literal or match pair ? */
- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
- //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
- // "pendingBuf overflow");
- } while (lx < s.last_lit);
- }
- send_code(s, END_BLOCK, ltree);
- }
- /* ===========================================================================
- * Construct one Huffman tree and assigns the code bit strings and lengths.
- * Update the total bit length for the current block.
- * IN assertion: the field freq is set for all tree elements.
- * OUT assertions: the fields len and code are set to the optimal bit length
- * and corresponding code. The length opt_len is updated; static_len is
- * also updated if stree is not null. The field max_code is set.
- */
- function build_tree(s, desc)
- // deflate_state *s;
- // tree_desc *desc; /* the tree descriptor */
- {
- var tree = desc.dyn_tree;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var elems = desc.stat_desc.elems;
- var n, m; /* iterate over heap elements */
- var max_code = -1; /* largest code with non zero frequency */
- var node; /* new node being created */
- /* Construct the initial heap, with least frequent element in
- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
- * heap[0] is not used.
- */
- s.heap_len = 0;
- s.heap_max = HEAP_SIZE;
- for (n = 0; n < elems; n++) {
- if (tree[n * 2]/*.Freq*/ !== 0) {
- s.heap[++s.heap_len] = max_code = n;
- s.depth[n] = 0;
- } else {
- tree[n * 2 + 1]/*.Len*/ = 0;
- }
- }
- /* The pkzip format requires that at least one distance code exists,
- * and that at least one bit should be sent even if there is only one
- * possible code. So to avoid special checks later on we force at least
- * two codes of non zero frequency.
- */
- while (s.heap_len < 2) {
- node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
- tree[node * 2]/*.Freq*/ = 1;
- s.depth[node] = 0;
- s.opt_len--;
- if (has_stree) {
- s.static_len -= stree[node * 2 + 1]/*.Len*/;
- }
- /* node is 0 or 1 so it does not have extra bits */
- }
- desc.max_code = max_code;
- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
- * establish sub-heaps of increasing lengths:
- */
- for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
- /* Construct the Huffman tree by repeatedly combining the least two
- * frequent nodes.
- */
- node = elems; /* next internal node of the tree */
- do {
- //pqremove(s, tree, n); /* n = node of least frequency */
- /*** pqremove ***/
- n = s.heap[1/*SMALLEST*/];
- s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
- pqdownheap(s, tree, 1/*SMALLEST*/);
- /***/
- m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
- s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
- s.heap[--s.heap_max] = m;
- /* Create a new node father of n and m */
- tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
- s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
- tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
- /* and insert the new node in the heap */
- s.heap[1/*SMALLEST*/] = node++;
- pqdownheap(s, tree, 1/*SMALLEST*/);
- } while (s.heap_len >= 2);
- s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
- /* At this point, the fields freq and dad are set. We can now
- * generate the bit lengths.
- */
- gen_bitlen(s, desc);
- /* The field len is now set, we can generate the bit codes */
- gen_codes(tree, max_code, s.bl_count);
- }
- /* ===========================================================================
- * Scan a literal or distance tree to determine the frequencies of the codes
- * in the bit length tree.
- */
- function scan_tree(s, tree, max_code)
- // deflate_state *s;
- // ct_data *tree; /* the tree to be scanned */
- // int max_code; /* and its largest code of non zero frequency */
- {
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
- tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
- if (++count < max_count && curlen === nextlen) {
- continue;
- } else if (count < min_count) {
- s.bl_tree[curlen * 2]/*.Freq*/ += count;
- } else if (curlen !== 0) {
- if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
- s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
- } else if (count <= 10) {
- s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
- } else {
- s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
- }
- count = 0;
- prevlen = curlen;
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
- }
- /* ===========================================================================
- * Send a literal or distance tree in compressed form, using the codes in
- * bl_tree.
- */
- function send_tree(s, tree, max_code)
- // deflate_state *s;
- // ct_data *tree; /* the tree to be scanned */
- // int max_code; /* and its largest code of non zero frequency */
- {
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
- /* tree[max_code+1].Len = -1; */ /* guard already set */
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
- if (++count < max_count && curlen === nextlen) {
- continue;
- } else if (count < min_count) {
- do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
- } else if (curlen !== 0) {
- if (curlen !== prevlen) {
- send_code(s, curlen, s.bl_tree);
- count--;
- }
- //Assert(count >= 3 && count <= 6, " 3_6?");
- send_code(s, REP_3_6, s.bl_tree);
- send_bits(s, count - 3, 2);
- } else if (count <= 10) {
- send_code(s, REPZ_3_10, s.bl_tree);
- send_bits(s, count - 3, 3);
- } else {
- send_code(s, REPZ_11_138, s.bl_tree);
- send_bits(s, count - 11, 7);
- }
- count = 0;
- prevlen = curlen;
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
- }
- /* ===========================================================================
- * Construct the Huffman tree for the bit lengths and return the index in
- * bl_order of the last bit length code to send.
- */
- function build_bl_tree(s) {
- var max_blindex; /* index of last bit length code of non zero freq */
- /* Determine the bit length frequencies for literal and distance trees */
- scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
- scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
- /* Build the bit length tree: */
- build_tree(s, s.bl_desc);
- /* opt_len now includes the length of the tree representations, except
- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
- */
- /* Determine the number of bit length codes to send. The pkzip format
- * requires that at least 4 bit length codes be sent. (appnote.txt says
- * 3 but the actual value used is 4.)
- */
- for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
- if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
- break;
- }
- }
- /* Update opt_len to include the bit length tree and counts */
- s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
- //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
- // s->opt_len, s->static_len));
- return max_blindex;
- }
- /* ===========================================================================
- * Send the header for a block using dynamic Huffman trees: the counts, the
- * lengths of the bit length codes, the literal tree and the distance tree.
- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
- */
- function send_all_trees(s, lcodes, dcodes, blcodes)
- // deflate_state *s;
- // int lcodes, dcodes, blcodes; /* number of codes for each tree */
- {
- var rank; /* index in bl_order */
- //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
- //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
- // "too many codes");
- //Tracev((stderr, "\nbl counts: "));
- send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
- send_bits(s, dcodes - 1, 5);
- send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
- for (rank = 0; rank < blcodes; rank++) {
- //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
- send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
- }
- //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
- send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
- //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
- send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
- //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
- }
- /* ===========================================================================
- * Check if the data type is TEXT or BINARY, using the following algorithm:
- * - TEXT if the two conditions below are satisfied:
- * a) There are no non-portable control characters belonging to the
- * "black list" (0..6, 14..25, 28..31).
- * b) There is at least one printable character belonging to the
- * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
- * - BINARY otherwise.
- * - The following partially-portable control characters form a
- * "gray list" that is ignored in this detection algorithm:
- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
- * IN assertion: the fields Freq of dyn_ltree are set.
- */
- function detect_data_type(s) {
- /* black_mask is the bit mask of black-listed bytes
- * set bits 0..6, 14..25, and 28..31
- * 0xf3ffc07f = binary 11110011111111111100000001111111
- */
- var black_mask = 0xf3ffc07f;
- var n;
- /* Check for non-textual ("black-listed") bytes. */
- for (n = 0; n <= 31; n++, black_mask >>>= 1) {
- if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
- return Z_BINARY;
- }
- }
- /* Check for textual ("white-listed") bytes. */
- if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
- s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- for (n = 32; n < LITERALS; n++) {
- if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- }
- /* There are no "black-listed" or "white-listed" bytes:
- * this stream either is empty or has tolerated ("gray-listed") bytes only.
- */
- return Z_BINARY;
- }
- var static_init_done = false;
- /* ===========================================================================
- * Initialize the tree data structures for a new zlib stream.
- */
- function _tr_init(s)
- {
- if (!static_init_done) {
- tr_static_init();
- static_init_done = true;
- }
- s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
- s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
- s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
- s.bi_buf = 0;
- s.bi_valid = 0;
- /* Initialize the first block of the first file: */
- init_block(s);
- }
- /* ===========================================================================
- * Send a stored block
- */
- function _tr_stored_block(s, buf, stored_len, last)
- //DeflateState *s;
- //charf *buf; /* input block */
- //ulg stored_len; /* length of input block */
- //int last; /* one if this is the last block for a file */
- {
- send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
- copy_block(s, buf, stored_len, true); /* with header */
- }
- /* ===========================================================================
- * Send one empty static block to give enough lookahead for inflate.
- * This takes 10 bits, of which 7 may remain in the bit buffer.
- */
- function _tr_align(s) {
- send_bits(s, STATIC_TREES << 1, 3);
- send_code(s, END_BLOCK, static_ltree);
- bi_flush(s);
- }
- /* ===========================================================================
- * Determine the best encoding for the current block: dynamic trees, static
- * trees or store, and output the encoded block to the zip file.
- */
- function _tr_flush_block(s, buf, stored_len, last)
- //DeflateState *s;
- //charf *buf; /* input block, or NULL if too old */
- //ulg stored_len; /* length of input block */
- //int last; /* one if this is the last block for a file */
- {
- var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
- var max_blindex = 0; /* index of last bit length code of non zero freq */
- /* Build the Huffman trees unless a stored block is forced */
- if (s.level > 0) {
- /* Check if the file is binary or text */
- if (s.strm.data_type === Z_UNKNOWN) {
- s.strm.data_type = detect_data_type(s);
- }
- /* Construct the literal and distance trees */
- build_tree(s, s.l_desc);
- // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
- build_tree(s, s.d_desc);
- // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
- /* At this point, opt_len and static_len are the total bit lengths of
- * the compressed block data, excluding the tree representations.
- */
- /* Build the bit length tree for the above two trees, and get the index
- * in bl_order of the last bit length code to send.
- */
- max_blindex = build_bl_tree(s);
- /* Determine the best encoding. Compute the block lengths in bytes. */
- opt_lenb = (s.opt_len + 3 + 7) >>> 3;
- static_lenb = (s.static_len + 3 + 7) >>> 3;
- // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
- // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
- // s->last_lit));
- if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
- } else {
- // Assert(buf != (char*)0, "lost buf");
- opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
- }
- if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
- /* 4: two words for the lengths */
- /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
- * Otherwise we can't have processed more than WSIZE input bytes since
- * the last block flush, because compression would have been
- * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
- * transform a block into a stored block.
- */
- _tr_stored_block(s, buf, stored_len, last);
- } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
- send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
- compress_block(s, static_ltree, static_dtree);
- } else {
- send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
- send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
- compress_block(s, s.dyn_ltree, s.dyn_dtree);
- }
- // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
- /* The above check is made mod 2^32, for files larger than 512 MB
- * and uLong implemented on 32 bits.
- */
- init_block(s);
- if (last) {
- bi_windup(s);
- }
- // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
- // s->compressed_len-7*last));
- }
- /* ===========================================================================
- * Save the match info and tally the frequency counts. Return true if
- * the current block must be flushed.
- */
- function _tr_tally(s, dist, lc)
- // deflate_state *s;
- // unsigned dist; /* distance of matched string */
- // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
- {
- //var out_length, in_length, dcode;
- s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
- s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
- s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
- s.last_lit++;
- if (dist === 0) {
- /* lc is the unmatched char */
- s.dyn_ltree[lc * 2]/*.Freq*/++;
- } else {
- s.matches++;
- /* Here, lc is the match length - MIN_MATCH */
- dist--; /* dist = match distance - 1 */
- //Assert((ush)dist < (ush)MAX_DIST(s) &&
- // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
- // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
- s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
- s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
- }
- // (!) This block is disabled in zlib defailts,
- // don't enable it for binary compatibility
- //#ifdef TRUNCATE_BLOCK
- // /* Try to guess if it is profitable to stop the current block here */
- // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
- // /* Compute an upper bound for the compressed length */
- // out_length = s.last_lit*8;
- // in_length = s.strstart - s.block_start;
- //
- // for (dcode = 0; dcode < D_CODES; dcode++) {
- // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
- // }
- // out_length >>>= 3;
- // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
- // // s->last_lit, in_length, out_length,
- // // 100L - out_length*100L/in_length));
- // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
- // return true;
- // }
- // }
- //#endif
- return (s.last_lit === s.lit_bufsize - 1);
- /* We avoid equality with lit_bufsize because of wraparound at 64K
- * on 16 bit machines and because stored blocks are restricted to
- * 64K-1 bytes.
- */
- }
- exports._tr_init = _tr_init;
- exports._tr_stored_block = _tr_stored_block;
- exports._tr_flush_block = _tr_flush_block;
- exports._tr_tally = _tr_tally;
- exports._tr_align = _tr_align;
- },{"../utils/common":123}],135:[function(require,module,exports){
- 'use strict';
- function ZStream() {
- /* next input byte */
- this.input = null; // JS specific, because we have no pointers
- this.next_in = 0;
- /* number of bytes available at input */
- this.avail_in = 0;
- /* total number of input bytes read so far */
- this.total_in = 0;
- /* next output byte should be put there */
- this.output = null; // JS specific, because we have no pointers
- this.next_out = 0;
- /* remaining free space at output */
- this.avail_out = 0;
- /* total number of bytes output so far */
- this.total_out = 0;
- /* last error message, NULL if no error */
- this.msg = ''/*Z_NULL*/;
- /* not visible by applications */
- this.state = null;
- /* best guess about the data type: binary or text */
- this.data_type = 2/*Z_UNKNOWN*/;
- /* adler32 value of the uncompressed data */
- this.adler = 0;
- }
- module.exports = ZStream;
- },{}],136:[function(require,module,exports){
- (function (process){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- // resolves . and .. elements in a path array with directory names there
- // must be no slashes, empty elements, or device names (c:\) in the array
- // (so also no leading and trailing slashes - it does not distinguish
- // relative and absolute paths)
- function normalizeArray(parts, allowAboveRoot) {
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = parts.length - 1; i >= 0; i--) {
- var last = parts[i];
- if (last === '.') {
- parts.splice(i, 1);
- } else if (last === '..') {
- parts.splice(i, 1);
- up++;
- } else if (up) {
- parts.splice(i, 1);
- up--;
- }
- }
- // if the path is allowed to go above the root, restore leading ..s
- if (allowAboveRoot) {
- for (; up--; up) {
- parts.unshift('..');
- }
- }
- return parts;
- }
- // Split a filename into [root, dir, basename, ext], unix version
- // 'root' is just a slash, or nothing.
- var splitPathRe =
- /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
- var splitPath = function(filename) {
- return splitPathRe.exec(filename).slice(1);
- };
- // path.resolve([from ...], to)
- // posix version
- exports.resolve = function() {
- var resolvedPath = '',
- resolvedAbsolute = false;
- for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
- var path = (i >= 0) ? arguments[i] : process.cwd();
- // Skip empty and invalid entries
- if (typeof path !== 'string') {
- throw new TypeError('Arguments to path.resolve must be strings');
- } else if (!path) {
- continue;
- }
- resolvedPath = path + '/' + resolvedPath;
- resolvedAbsolute = path.charAt(0) === '/';
- }
- // At this point the path should be resolved to a full absolute path, but
- // handle relative paths to be safe (might happen when process.cwd() fails)
- // Normalize the path
- resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
- return !!p;
- }), !resolvedAbsolute).join('/');
- return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
- };
- // path.normalize(path)
- // posix version
- exports.normalize = function(path) {
- var isAbsolute = exports.isAbsolute(path),
- trailingSlash = substr(path, -1) === '/';
- // Normalize the path
- path = normalizeArray(filter(path.split('/'), function(p) {
- return !!p;
- }), !isAbsolute).join('/');
- if (!path && !isAbsolute) {
- path = '.';
- }
- if (path && trailingSlash) {
- path += '/';
- }
- return (isAbsolute ? '/' : '') + path;
- };
- // posix version
- exports.isAbsolute = function(path) {
- return path.charAt(0) === '/';
- };
- // posix version
- exports.join = function() {
- var paths = Array.prototype.slice.call(arguments, 0);
- return exports.normalize(filter(paths, function(p, index) {
- if (typeof p !== 'string') {
- throw new TypeError('Arguments to path.join must be strings');
- }
- return p;
- }).join('/'));
- };
- // path.relative(from, to)
- // posix version
- exports.relative = function(from, to) {
- from = exports.resolve(from).substr(1);
- to = exports.resolve(to).substr(1);
- function trim(arr) {
- var start = 0;
- for (; start < arr.length; start++) {
- if (arr[start] !== '') break;
- }
- var end = arr.length - 1;
- for (; end >= 0; end--) {
- if (arr[end] !== '') break;
- }
- if (start > end) return [];
- return arr.slice(start, end - start + 1);
- }
- var fromParts = trim(from.split('/'));
- var toParts = trim(to.split('/'));
- var length = Math.min(fromParts.length, toParts.length);
- var samePartsLength = length;
- for (var i = 0; i < length; i++) {
- if (fromParts[i] !== toParts[i]) {
- samePartsLength = i;
- break;
- }
- }
- var outputParts = [];
- for (var i = samePartsLength; i < fromParts.length; i++) {
- outputParts.push('..');
- }
- outputParts = outputParts.concat(toParts.slice(samePartsLength));
- return outputParts.join('/');
- };
- exports.sep = '/';
- exports.delimiter = ':';
- exports.dirname = function(path) {
- var result = splitPath(path),
- root = result[0],
- dir = result[1];
- if (!root && !dir) {
- // No dirname whatsoever
- return '.';
- }
- if (dir) {
- // It has a dirname, strip trailing slash
- dir = dir.substr(0, dir.length - 1);
- }
- return root + dir;
- };
- exports.basename = function(path, ext) {
- var f = splitPath(path)[2];
- // TODO: make this comparison case-insensitive on windows?
- if (ext && f.substr(-1 * ext.length) === ext) {
- f = f.substr(0, f.length - ext.length);
- }
- return f;
- };
- exports.extname = function(path) {
- return splitPath(path)[3];
- };
- function filter (xs, f) {
- if (xs.filter) return xs.filter(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- if (f(xs[i], i, xs)) res.push(xs[i]);
- }
- return res;
- }
- // String.prototype.substr - negative index don't work in IE8
- var substr = 'ab'.substr(-1) === 'b'
- ? function (str, start, len) { return str.substr(start, len) }
- : function (str, start, len) {
- if (start < 0) start = str.length + start;
- return str.substr(start, len);
- }
- ;
- }).call(this,require('_process'))
- },{"_process":138}],137:[function(require,module,exports){
- (function (process){
- 'use strict';
- if (!process.version ||
- process.version.indexOf('v0.') === 0 ||
- process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
- module.exports = nextTick;
- } else {
- module.exports = process.nextTick;
- }
- function nextTick(fn, arg1, arg2, arg3) {
- if (typeof fn !== 'function') {
- throw new TypeError('"callback" argument must be a function');
- }
- var len = arguments.length;
- var args, i;
- switch (len) {
- case 0:
- case 1:
- return process.nextTick(fn);
- case 2:
- return process.nextTick(function afterTickOne() {
- fn.call(null, arg1);
- });
- case 3:
- return process.nextTick(function afterTickTwo() {
- fn.call(null, arg1, arg2);
- });
- case 4:
- return process.nextTick(function afterTickThree() {
- fn.call(null, arg1, arg2, arg3);
- });
- default:
- args = new Array(len - 1);
- i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
- }
- return process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
- }
- }
- }).call(this,require('_process'))
- },{"_process":138}],138:[function(require,module,exports){
- // shim for using process in browser
- var process = module.exports = {};
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
- var cachedSetTimeout;
- var cachedClearTimeout;
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // 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
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // 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.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
- function noop() {}
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
- },{}],139:[function(require,module,exports){
- module.exports = require("./lib/_stream_duplex.js")
- },{"./lib/_stream_duplex.js":140}],140:[function(require,module,exports){
- // a duplex stream is just a stream that is both readable and writable.
- // Since JS doesn't have multiple prototypal inheritance, this class
- // prototypally inherits from Readable, and then parasitically from
- // Writable.
- 'use strict';
- /*<replacement>*/
- var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- keys.push(key);
- }return keys;
- };
- /*</replacement>*/
- module.exports = Duplex;
- /*<replacement>*/
- var processNextTick = require('process-nextick-args');
- /*</replacement>*/
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- var Readable = require('./_stream_readable');
- var Writable = require('./_stream_writable');
- util.inherits(Duplex, Readable);
- var keys = objectKeys(Writable.prototype);
- for (var v = 0; v < keys.length; v++) {
- var method = keys[v];
- if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
- }
- function Duplex(options) {
- if (!(this instanceof Duplex)) return new Duplex(options);
- Readable.call(this, options);
- Writable.call(this, options);
- if (options && options.readable === false) this.readable = false;
- if (options && options.writable === false) this.writable = false;
- this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
- this.once('end', onend);
- }
- // the no-half-open enforcer
- function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended) return;
- // no more data can be written.
- // But allow more writes to happen in this tick.
- processNextTick(onEndNT, this);
- }
- function onEndNT(self) {
- self.end();
- }
- function forEach(xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
- }
- },{"./_stream_readable":142,"./_stream_writable":144,"core-util-is":78,"inherits":81,"process-nextick-args":137}],141:[function(require,module,exports){
- // a passthrough stream.
- // basically just the most minimal sort of Transform stream.
- // Every written chunk gets output as-is.
- 'use strict';
- module.exports = PassThrough;
- var Transform = require('./_stream_transform');
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- util.inherits(PassThrough, Transform);
- function PassThrough(options) {
- if (!(this instanceof PassThrough)) return new PassThrough(options);
- Transform.call(this, options);
- }
- PassThrough.prototype._transform = function (chunk, encoding, cb) {
- cb(null, chunk);
- };
- },{"./_stream_transform":143,"core-util-is":78,"inherits":81}],142:[function(require,module,exports){
- (function (process){
- 'use strict';
- module.exports = Readable;
- /*<replacement>*/
- var processNextTick = require('process-nextick-args');
- /*</replacement>*/
- /*<replacement>*/
- var isArray = require('isarray');
- /*</replacement>*/
- /*<replacement>*/
- var Duplex;
- /*</replacement>*/
- Readable.ReadableState = ReadableState;
- /*<replacement>*/
- var EE = require('events').EventEmitter;
- var EElistenerCount = function (emitter, type) {
- return emitter.listeners(type).length;
- };
- /*</replacement>*/
- /*<replacement>*/
- var Stream;
- (function () {
- try {
- Stream = require('st' + 'ream');
- } catch (_) {} finally {
- if (!Stream) Stream = require('events').EventEmitter;
- }
- })();
- /*</replacement>*/
- var Buffer = require('buffer').Buffer;
- /*<replacement>*/
- var bufferShim = require('buffer-shims');
- /*</replacement>*/
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- /*<replacement>*/
- var debugUtil = require('util');
- var debug = void 0;
- if (debugUtil && debugUtil.debuglog) {
- debug = debugUtil.debuglog('stream');
- } else {
- debug = function () {};
- }
- /*</replacement>*/
- var BufferList = require('./internal/streams/BufferList');
- var StringDecoder;
- util.inherits(Readable, Stream);
- function prependListener(emitter, event, fn) {
- // Sadly this is not cacheable as some libraries bundle their own
- // event emitter implementation with them.
- if (typeof emitter.prependListener === 'function') {
- return emitter.prependListener(event, fn);
- } else {
- // This is a hack to make sure that our error handler is attached before any
- // userland ones. NEVER DO THIS. This is here only because this code needs
- // to continue to work with older versions of Node.js that do not include
- // the prependListener() method. The goal is to eventually remove this hack.
- 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]];
- }
- }
- function ReadableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
- options = options || {};
- // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
- if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
- // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
- var hwm = options.highWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
- // A linked list is used to store data chunks instead of an array because the
- // linked list can remove elements from the beginning faster than
- // array.shift()
- this.buffer = new BufferList();
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false;
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
- // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
- this.resumeScheduled = false;
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
- // when piping, we only care about 'readable' events that happen
- // after read()ing all the bytes and not getting any pushback.
- this.ranOut = false;
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
- }
- }
- function Readable(options) {
- Duplex = Duplex || require('./_stream_duplex');
- if (!(this instanceof Readable)) return new Readable(options);
- this._readableState = new ReadableState(options, this);
- // legacy
- this.readable = true;
- if (options && typeof options.read === 'function') this._read = options.read;
- Stream.call(this);
- }
- // Manually shove something into the read() buffer.
- // This returns true if the highWaterMark has not been hit yet,
- // similar to how Writable.write() returns true if you should
- // write() some more.
- Readable.prototype.push = function (chunk, encoding) {
- var state = this._readableState;
- if (!state.objectMode && typeof chunk === 'string') {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = bufferShim.from(chunk, encoding);
- encoding = '';
- }
- }
- return readableAddChunk(this, state, chunk, encoding, false);
- };
- // Unshift should *always* be something directly out of read()
- Readable.prototype.unshift = function (chunk) {
- var state = this._readableState;
- return readableAddChunk(this, state, chunk, '', true);
- };
- Readable.prototype.isPaused = function () {
- return this._readableState.flowing === false;
- };
- function readableAddChunk(stream, state, chunk, encoding, addToFront) {
- var er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (state.ended && !addToFront) {
- var e = new Error('stream.push() after EOF');
- stream.emit('error', e);
- } else if (state.endEmitted && addToFront) {
- var _e = new Error('stream.unshift() after end event');
- stream.emit('error', _e);
- } else {
- var skipAdd;
- if (state.decoder && !addToFront && !encoding) {
- chunk = state.decoder.write(chunk);
- skipAdd = !state.objectMode && chunk.length === 0;
- }
- if (!addToFront) state.reading = false;
- // Don't add to the buffer if we've decoded to an empty string chunk and
- // we're not in object mode
- if (!skipAdd) {
- // if we want the data now, just emit it.
- if (state.flowing && state.length === 0 && !state.sync) {
- stream.emit('data', chunk);
- stream.read(0);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
- if (state.needReadable) emitReadable(stream);
- }
- }
- maybeReadMore(stream, state);
- }
- } else if (!addToFront) {
- state.reading = false;
- }
- return needMoreData(state);
- }
- // if it's past the high water mark, we can push in some more.
- // Also, if we have no data yet, we can stand some
- // more bytes. This is to work around cases where hwm=0,
- // such as the repl. Also, if the push() triggered a
- // readable event, and the user called read(largeNumber) such that
- // needReadable was set, then we ought to push more, so that another
- // 'readable' event will be triggered.
- function needMoreData(state) {
- return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
- }
- // backwards compatibility.
- Readable.prototype.setEncoding = function (enc) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
- return this;
- };
- // Don't raise the hwm > 8MB
- var MAX_HWM = 0x800000;
- function computeNewHighWaterMark(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2 to prevent increasing hwm excessively in
- // tiny amounts
- n--;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- n++;
- }
- return n;
- }
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function howMuchToRead(n, state) {
- if (n <= 0 || state.length === 0 && state.ended) return 0;
- if (state.objectMode) return 1;
- if (n !== n) {
- // Only flow one buffer at a time
- if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
- }
- // If we're asking for more than the current hwm, then raise the hwm.
- if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
- if (n <= state.length) return n;
- // Don't have enough
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- }
- return state.length;
- }
- // you can override either this method, or the async _read(n) below.
- Readable.prototype.read = function (n) {
- debug('read', n);
- n = parseInt(n, 10);
- var state = this._readableState;
- var nOrig = n;
- if (n !== 0) state.emittedReadable = false;
- // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
- return null;
- }
- n = howMuchToRead(n, state);
- // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- if (state.length === 0) endReadable(this);
- return null;
- }
- // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead);
- // if we currently have less than the highWaterMark, then also read some
- if (state.length === 0 || state.length - n < state.highWaterMark) {
- doRead = true;
- debug('length less than watermark', doRead);
- }
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading) {
- doRead = false;
- debug('reading or ended', doRead);
- } else if (doRead) {
- debug('do read');
- state.reading = true;
- state.sync = true;
- // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0) state.needReadable = true;
- // call internal read method
- this._read(state.highWaterMark);
- state.sync = false;
- // If _read pushed data synchronously, then `reading` will be false,
- // and we need to re-evaluate how much data we can return to the user.
- if (!state.reading) n = howMuchToRead(nOrig, state);
- }
- var ret;
- if (n > 0) ret = fromList(n, state);else ret = null;
- if (ret === null) {
- state.needReadable = true;
- n = 0;
- } else {
- state.length -= n;
- }
- if (state.length === 0) {
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (!state.ended) state.needReadable = true;
- // If we tried to read() past the EOF, then emit end on the next tick.
- if (nOrig !== n && state.ended) endReadable(this);
- }
- if (ret !== null) this.emit('data', ret);
- return ret;
- };
- function chunkInvalid(state, chunk) {
- var er = null;
- if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- return er;
- }
- function onEofChunk(stream, state) {
- if (state.ended) return;
- if (state.decoder) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
- }
- state.ended = true;
- // emit 'readable' now to make sure it gets picked up.
- emitReadable(stream);
- }
- // Don't emit readable right away in sync mode, because this can trigger
- // another read() call => stack overflow. This way, it might trigger
- // a nextTick recursion warning, but that's not so bad.
- function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
- }
- }
- function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
- flow(stream);
- }
- // at this point, the user has presumably seen the 'readable' event,
- // and called read() to consume some data. that may have triggered
- // in turn another _read(n) call, in which case reading = true if
- // it's in progress.
- // However, if we're not ended, or reading, and the length < hwm,
- // then go ahead and try to read some more preemptively.
- function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- processNextTick(maybeReadMore_, stream, state);
- }
- }
- function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;else len = state.length;
- }
- state.readingMore = false;
- }
- // abstract method. to be overridden in specific implementation classes.
- // call cb(er, data) where data is <= n in length.
- // for virtual (non-string, non-buffer) streams, "length" is somewhat
- // arbitrary, and perhaps not very meaningful.
- Readable.prototype._read = function (n) {
- this.emit('error', new Error('_read() is not implemented'));
- };
- Readable.prototype.pipe = function (dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
- }
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
- var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
- var endFn = doEnd ? onend : cleanup;
- if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
- dest.on('unpipe', onunpipe);
- function onunpipe(readable) {
- debug('onunpipe');
- if (readable === src) {
- cleanup();
- }
- }
- function onend() {
- debug('onend');
- dest.end();
- }
- // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
- var cleanedUp = false;
- function cleanup() {
- debug('cleanup');
- // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', cleanup);
- src.removeListener('data', ondata);
- cleanedUp = true;
- // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
- }
- // If the user pushes more data while we're writing to dest then we'll end up
- // in ondata again. However, we only want to increase awaitDrain once because
- // dest will only emit one 'drain' event for the multiple writes.
- // => Introduce a guard on increasing awaitDrain.
- var increasedAwaitDrain = false;
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- increasedAwaitDrain = false;
- var ret = dest.write(chunk);
- if (false === ret && !increasedAwaitDrain) {
- // If the user unpiped during `dest.write()`, it is possible
- // to get stuck in a permanently paused state if that write
- // also returned false.
- // => Check whether `dest` is still a piping destination.
- if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
- debug('false write response, pause', src._readableState.awaitDrain);
- src._readableState.awaitDrain++;
- increasedAwaitDrain = true;
- }
- src.pause();
- }
- }
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
- }
- // Make sure our error handler is attached before userland ones.
- prependListener(dest, 'error', onerror);
- // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- debug('onfinish');
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
- function unpipe() {
- debug('unpipe');
- src.unpipe(dest);
- }
- // tell the dest that it's being piped to
- dest.emit('pipe', src);
- // start the flow if it hasn't been started already.
- if (!state.flowing) {
- debug('pipe resume');
- src.resume();
- }
- return dest;
- };
- function pipeOnDrain(src) {
- return function () {
- var state = src._readableState;
- debug('pipeOnDrain', state.awaitDrain);
- if (state.awaitDrain) state.awaitDrain--;
- if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
- state.flowing = true;
- flow(src);
- }
- };
- }
- Readable.prototype.unpipe = function (dest) {
- var state = this._readableState;
- // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0) return this;
- // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes) return this;
- if (!dest) dest = state.pipes;
- // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- if (dest) dest.emit('unpipe', this);
- return this;
- }
- // slow case. multiple pipe destinations.
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- for (var i = 0; i < len; i++) {
- dests[i].emit('unpipe', this);
- }return this;
- }
- // try to find the right one.
- var index = indexOf(state.pipes, dest);
- if (index === -1) return this;
- state.pipes.splice(index, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1) state.pipes = state.pipes[0];
- dest.emit('unpipe', this);
- return this;
- };
- // set up data events if they are asked for
- // Ensure readable listeners eventually get something
- Readable.prototype.on = function (ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
- if (ev === 'data') {
- // Start flowing on next tick if stream isn't explicitly paused
- if (this._readableState.flowing !== false) this.resume();
- } else if (ev === 'readable') {
- var state = this._readableState;
- if (!state.endEmitted && !state.readableListening) {
- state.readableListening = state.needReadable = true;
- state.emittedReadable = false;
- if (!state.reading) {
- processNextTick(nReadingNextTick, this);
- } else if (state.length) {
- emitReadable(this, state);
- }
- }
- }
- return res;
- };
- Readable.prototype.addListener = Readable.prototype.on;
- function nReadingNextTick(self) {
- debug('readable nexttick read 0');
- self.read(0);
- }
- // pause() and resume() are remnants of the legacy readable stream API
- // If the user uses them, then switch into old mode.
- Readable.prototype.resume = function () {
- var state = this._readableState;
- if (!state.flowing) {
- debug('resume');
- state.flowing = true;
- resume(this, state);
- }
- return this;
- };
- function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- processNextTick(resume_, stream, state);
- }
- }
- function resume_(stream, state) {
- if (!state.reading) {
- debug('resume read 0');
- stream.read(0);
- }
- state.resumeScheduled = false;
- state.awaitDrain = 0;
- stream.emit('resume');
- flow(stream);
- if (state.flowing && !state.reading) stream.read(0);
- }
- Readable.prototype.pause = function () {
- debug('call pause flowing=%j', this._readableState.flowing);
- if (false !== this._readableState.flowing) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- return this;
- };
- function flow(stream) {
- var state = stream._readableState;
- debug('flow', state.flowing);
- while (state.flowing && stream.read() !== null) {}
- }
- // wrap an old-style stream as the async data source.
- // This is *not* part of the readable stream interface.
- // It is an ugly unfortunate mess of history.
- Readable.prototype.wrap = function (stream) {
- var state = this._readableState;
- var paused = false;
- var self = this;
- stream.on('end', function () {
- debug('wrapped end');
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) self.push(chunk);
- }
- self.push(null);
- });
- stream.on('data', function (chunk) {
- debug('wrapped data');
- if (state.decoder) chunk = state.decoder.write(chunk);
- // don't skip over falsy values in objectMode
- if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
- var ret = self.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- });
- // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (this[i] === undefined && typeof stream[i] === 'function') {
- this[i] = function (method) {
- return function () {
- return stream[method].apply(stream, arguments);
- };
- }(i);
- }
- }
- // proxy certain important events.
- var events = ['error', 'close', 'destroy', 'pause', 'resume'];
- forEach(events, function (ev) {
- stream.on(ev, self.emit.bind(self, ev));
- });
- // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- self._read = function (n) {
- debug('wrapped _read', n);
- if (paused) {
- paused = false;
- stream.resume();
- }
- };
- return self;
- };
- // exposed for testing purposes only.
- Readable._fromList = fromList;
- // Pluck off n bytes from an array of buffers.
- // Length is the combined lengths of all the buffers in the list.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function fromList(n, state) {
- // nothing buffered
- if (state.length === 0) return null;
- var ret;
- if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
- // read it all, truncate the list
- 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);
- state.buffer.clear();
- } else {
- // read part of list
- ret = fromListPartial(n, state.buffer, state.decoder);
- }
- return ret;
- }
- // Extracts only enough buffered data to satisfy the amount requested.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function fromListPartial(n, list, hasStrings) {
- var ret;
- if (n < list.head.data.length) {
- // slice is the same for buffers and strings
- ret = list.head.data.slice(0, n);
- list.head.data = list.head.data.slice(n);
- } else if (n === list.head.data.length) {
- // first chunk is a perfect match
- ret = list.shift();
- } else {
- // result spans more than one buffer
- ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
- }
- return ret;
- }
- // Copies a specified amount of characters from the list of buffered data
- // chunks.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function copyFromBufferString(n, list) {
- var p = list.head;
- var c = 1;
- var ret = p.data;
- n -= ret.length;
- while (p = p.next) {
- var str = p.data;
- var nb = n > str.length ? str.length : n;
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
- n -= nb;
- if (n === 0) {
- if (nb === str.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = str.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
- }
- // Copies a specified amount of bytes from the list of buffered data chunks.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function copyFromBuffer(n, list) {
- var ret = bufferShim.allocUnsafe(n);
- var p = list.head;
- var c = 1;
- p.data.copy(ret);
- n -= p.data.length;
- while (p = p.next) {
- var buf = p.data;
- var nb = n > buf.length ? buf.length : n;
- buf.copy(ret, ret.length - n, 0, nb);
- n -= nb;
- if (n === 0) {
- if (nb === buf.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = buf.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
- }
- function endReadable(stream) {
- var state = stream._readableState;
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
- if (!state.endEmitted) {
- state.ended = true;
- processNextTick(endReadableNT, state, stream);
- }
- }
- function endReadableNT(state, stream) {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
- }
- function forEach(xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
- }
- function indexOf(xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
- }
- return -1;
- }
- }).call(this,require('_process'))
- },{"./_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){
- // a transform stream is a readable/writable stream where you do
- // something with the data. Sometimes it's called a "filter",
- // but that's not a great name for it, since that implies a thing where
- // some bits pass through, and others are simply ignored. (That would
- // be a valid example of a transform, of course.)
- //
- // While the output is causally related to the input, it's not a
- // necessarily symmetric or synchronous transformation. For example,
- // a zlib stream might take multiple plain-text writes(), and then
- // emit a single compressed chunk some time in the future.
- //
- // Here's how this works:
- //
- // The Transform stream has all the aspects of the readable and writable
- // stream classes. When you write(chunk), that calls _write(chunk,cb)
- // internally, and returns false if there's a lot of pending writes
- // buffered up. When you call read(), that calls _read(n) until
- // there's enough pending readable data buffered up.
- //
- // In a transform stream, the written data is placed in a buffer. When
- // _read(n) is called, it transforms the queued up data, calling the
- // buffered _write cb's as it consumes chunks. If consuming a single
- // written chunk would result in multiple output chunks, then the first
- // outputted bit calls the readcb, and subsequent chunks just go into
- // the read buffer, and will cause it to emit 'readable' if necessary.
- //
- // This way, back-pressure is actually determined by the reading side,
- // since _read has to be called to start processing a new chunk. However,
- // a pathological inflate type of transform can cause excessive buffering
- // here. For example, imagine a stream where every byte of input is
- // interpreted as an integer from 0-255, and then results in that many
- // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
- // 1kb of data being output. In this case, you could write a very small
- // amount of input, and end up with a very large amount of output. In
- // such a pathological inflating mechanism, there'd be no way to tell
- // the system to stop doing the transform. A single 4MB write could
- // cause the system to run out of memory.
- //
- // However, even in such a pathological case, only a single written chunk
- // would be consumed, and then the rest would wait (un-transformed) until
- // the results of the previous transformed chunk were consumed.
- 'use strict';
- module.exports = Transform;
- var Duplex = require('./_stream_duplex');
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- util.inherits(Transform, Duplex);
- function TransformState(stream) {
- this.afterTransform = function (er, data) {
- return afterTransform(stream, er, data);
- };
- this.needTransform = false;
- this.transforming = false;
- this.writecb = null;
- this.writechunk = null;
- this.writeencoding = null;
- }
- function afterTransform(stream, er, data) {
- var ts = stream._transformState;
- ts.transforming = false;
- var cb = ts.writecb;
- if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
- ts.writechunk = null;
- ts.writecb = null;
- if (data !== null && data !== undefined) stream.push(data);
- cb(er);
- var rs = stream._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- stream._read(rs.highWaterMark);
- }
- }
- function Transform(options) {
- if (!(this instanceof Transform)) return new Transform(options);
- Duplex.call(this, options);
- this._transformState = new TransformState(this);
- var stream = this;
- // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true;
- // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
- if (options) {
- if (typeof options.transform === 'function') this._transform = options.transform;
- if (typeof options.flush === 'function') this._flush = options.flush;
- }
- // When the writable side finishes, then flush out anything remaining.
- this.once('prefinish', function () {
- if (typeof this._flush === 'function') this._flush(function (er, data) {
- done(stream, er, data);
- });else done(stream);
- });
- }
- Transform.prototype.push = function (chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
- };
- // This is the part where you do stuff!
- // override this function in implementation classes.
- // 'chunk' is an input chunk.
- //
- // Call `push(newChunk)` to pass along transformed output
- // to the readable side. You may call 'push' zero or more times.
- //
- // Call `cb(err)` when you are done with this chunk. If you pass
- // an error, then that'll put the hurt on the whole operation. If you
- // never call cb(), then you'll never get another chunk.
- Transform.prototype._transform = function (chunk, encoding, cb) {
- throw new Error('_transform() is not implemented');
- };
- Transform.prototype._write = function (chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
- }
- };
- // Doesn't matter what the args are here.
- // _transform does all the work.
- // That we got here means that the readable side wants more data.
- Transform.prototype._read = function (n) {
- var ts = this._transformState;
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
- }
- };
- function done(stream, er, data) {
- if (er) return stream.emit('error', er);
- if (data !== null && data !== undefined) stream.push(data);
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- var ws = stream._writableState;
- var ts = stream._transformState;
- if (ws.length) throw new Error('Calling transform done when ws.length != 0');
- if (ts.transforming) throw new Error('Calling transform done when still transforming');
- return stream.push(null);
- }
- },{"./_stream_duplex":140,"core-util-is":78,"inherits":81}],144:[function(require,module,exports){
- (function (process){
- // A bit simpler than readable streams.
- // Implement an async ._write(chunk, encoding, cb), and it'll handle all
- // the drain event emission and buffering.
- 'use strict';
- module.exports = Writable;
- /*<replacement>*/
- var processNextTick = require('process-nextick-args');
- /*</replacement>*/
- /*<replacement>*/
- var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
- /*</replacement>*/
- /*<replacement>*/
- var Duplex;
- /*</replacement>*/
- Writable.WritableState = WritableState;
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
- /*<replacement>*/
- var internalUtil = {
- deprecate: require('util-deprecate')
- };
- /*</replacement>*/
- /*<replacement>*/
- var Stream;
- (function () {
- try {
- Stream = require('st' + 'ream');
- } catch (_) {} finally {
- if (!Stream) Stream = require('events').EventEmitter;
- }
- })();
- /*</replacement>*/
- var Buffer = require('buffer').Buffer;
- /*<replacement>*/
- var bufferShim = require('buffer-shims');
- /*</replacement>*/
- util.inherits(Writable, Stream);
- function nop() {}
- function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
- this.next = null;
- }
- function WritableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
- options = options || {};
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
- if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
- // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
- // cast to ints.
- this.highWaterMark = ~~this.highWaterMark;
- // drain event flag.
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
- // a flag to see when we're in the middle of a write.
- this.writing = false;
- // when true all writes will be buffered until .uncork() call
- this.corked = 0;
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function (er) {
- onwrite(stream, er);
- };
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
- // the amount that is being written when _write is called.
- this.writelen = 0;
- this.bufferedRequest = null;
- this.lastBufferedRequest = null;
- // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0;
- // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false;
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
- // count buffered requests
- this.bufferedRequestCount = 0;
- // allocate the first CorkedRequest, there is always
- // one allocated and free to use, and we maintain at most two
- this.corkedRequestsFree = new CorkedRequest(this);
- }
- WritableState.prototype.getBuffer = function getBuffer() {
- var current = this.bufferedRequest;
- var out = [];
- while (current) {
- out.push(current);
- current = current.next;
- }
- return out;
- };
- (function () {
- try {
- Object.defineProperty(WritableState.prototype, 'buffer', {
- get: internalUtil.deprecate(function () {
- return this.getBuffer();
- }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
- });
- } catch (_) {}
- })();
- // Test _writableState for inheritance to account for Duplex streams,
- // whose prototype chain only points to Readable.
- var realHasInstance;
- if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
- realHasInstance = Function.prototype[Symbol.hasInstance];
- Object.defineProperty(Writable, Symbol.hasInstance, {
- value: function (object) {
- if (realHasInstance.call(this, object)) return true;
- return object && object._writableState instanceof WritableState;
- }
- });
- } else {
- realHasInstance = function (object) {
- return object instanceof this;
- };
- }
- function Writable(options) {
- Duplex = Duplex || require('./_stream_duplex');
- // Writable ctor is applied to Duplexes, too.
- // `realHasInstance` is necessary because using plain `instanceof`
- // would return false, as no `_writableState` property is attached.
- // Trying to use the custom `instanceof` for Writable here will also break the
- // Node.js LazyTransform implementation, which has a non-trivial getter for
- // `_writableState` that would lead to infinite recursion.
- if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
- return new Writable(options);
- }
- this._writableState = new WritableState(options, this);
- // legacy.
- this.writable = true;
- if (options) {
- if (typeof options.write === 'function') this._write = options.write;
- if (typeof options.writev === 'function') this._writev = options.writev;
- }
- Stream.call(this);
- }
- // Otherwise people can pipe Writable streams, which is just wrong.
- Writable.prototype.pipe = function () {
- this.emit('error', new Error('Cannot pipe, not readable'));
- };
- function writeAfterEnd(stream, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- processNextTick(cb, er);
- }
- // Checks that a user-supplied chunk is valid, especially for the particular
- // mode the stream is in. Currently this means that `null` is never accepted
- // and undefined/non-string values are only allowed in object mode.
- function validChunk(stream, state, chunk, cb) {
- var valid = true;
- var er = false;
- if (chunk === null) {
- er = new TypeError('May not write null values to stream');
- } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- if (er) {
- stream.emit('error', er);
- processNextTick(cb, er);
- valid = false;
- }
- return valid;
- }
- Writable.prototype.write = function (chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
- var isBuf = Buffer.isBuffer(chunk);
- if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
- if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
- if (typeof cb !== 'function') cb = nop;
- if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
- state.pendingcb++;
- ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
- }
- return ret;
- };
- Writable.prototype.cork = function () {
- var state = this._writableState;
- state.corked++;
- };
- Writable.prototype.uncork = function () {
- var state = this._writableState;
- if (state.corked) {
- state.corked--;
- if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
- }
- };
- Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
- // node::ParseEncoding() requires lower case.
- if (typeof encoding === 'string') encoding = encoding.toLowerCase();
- 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);
- this._writableState.defaultEncoding = encoding;
- return this;
- };
- function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
- chunk = bufferShim.from(chunk, encoding);
- }
- return chunk;
- }
- // if we're already writing something, then just put this
- // in the queue, and wait our turn. Otherwise, call _write
- // If we return false, then we need a drain event, so set that flag.
- function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
- if (!isBuf) {
- chunk = decodeChunk(state, chunk, encoding);
- if (Buffer.isBuffer(chunk)) encoding = 'buffer';
- }
- var len = state.objectMode ? 1 : chunk.length;
- state.length += len;
- var ret = state.length < state.highWaterMark;
- // we must ensure that previous needDrain will not be reset to false.
- if (!ret) state.needDrain = true;
- if (state.writing || state.corked) {
- var last = state.lastBufferedRequest;
- state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
- if (last) {
- last.next = state.lastBufferedRequest;
- } else {
- state.bufferedRequest = state.lastBufferedRequest;
- }
- state.bufferedRequestCount += 1;
- } else {
- doWrite(stream, state, false, len, chunk, encoding, cb);
- }
- return ret;
- }
- function doWrite(stream, state, writev, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
- }
- function onwriteError(stream, state, sync, er, cb) {
- --state.pendingcb;
- if (sync) processNextTick(cb, er);else cb(er);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- }
- function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
- }
- function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
- onwriteStateUpdate(state);
- if (er) onwriteError(stream, state, sync, er, cb);else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state);
- if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
- clearBuffer(stream, state);
- }
- if (sync) {
- /*<replacement>*/
- asyncWrite(afterWrite, stream, state, finished, cb);
- /*</replacement>*/
- } else {
- afterWrite(stream, state, finished, cb);
- }
- }
- }
- function afterWrite(stream, state, finished, cb) {
- if (!finished) onwriteDrain(stream, state);
- state.pendingcb--;
- cb();
- finishMaybe(stream, state);
- }
- // Must force callback to be called on nextTick, so that we don't
- // emit 'drain' before the write() consumer gets the 'false' return
- // value, and has a chance to attach a 'drain' listener.
- function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
- }
- }
- // if there's something in the buffer waiting, then process it
- function clearBuffer(stream, state) {
- state.bufferProcessing = true;
- var entry = state.bufferedRequest;
- if (stream._writev && entry && entry.next) {
- // Fast case, write everything using _writev()
- var l = state.bufferedRequestCount;
- var buffer = new Array(l);
- var holder = state.corkedRequestsFree;
- holder.entry = entry;
- var count = 0;
- while (entry) {
- buffer[count] = entry;
- entry = entry.next;
- count += 1;
- }
- doWrite(stream, state, true, state.length, buffer, '', holder.finish);
- // doWrite is almost always async, defer these to save a bit of time
- // as the hot path ends with doWrite
- state.pendingcb++;
- state.lastBufferedRequest = null;
- if (holder.next) {
- state.corkedRequestsFree = holder.next;
- holder.next = null;
- } else {
- state.corkedRequestsFree = new CorkedRequest(state);
- }
- } else {
- // Slow case, write chunks one-by-one
- while (entry) {
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
- doWrite(stream, state, false, len, chunk, encoding, cb);
- entry = entry.next;
- // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- break;
- }
- }
- if (entry === null) state.lastBufferedRequest = null;
- }
- state.bufferedRequestCount = 0;
- state.bufferedRequest = entry;
- state.bufferProcessing = false;
- }
- Writable.prototype._write = function (chunk, encoding, cb) {
- cb(new Error('_write() is not implemented'));
- };
- Writable.prototype._writev = null;
- Writable.prototype.end = function (chunk, encoding, cb) {
- var state = this._writableState;
- if (typeof chunk === 'function') {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
- if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
- // .end() fully uncorks
- if (state.corked) {
- state.corked = 1;
- this.uncork();
- }
- // ignore unnecessary end() calls.
- if (!state.ending && !state.finished) endWritable(this, state, cb);
- };
- function needFinish(state) {
- return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
- }
- function prefinish(stream, state) {
- if (!state.prefinished) {
- state.prefinished = true;
- stream.emit('prefinish');
- }
- }
- function finishMaybe(stream, state) {
- var need = needFinish(state);
- if (need) {
- if (state.pendingcb === 0) {
- prefinish(stream, state);
- state.finished = true;
- stream.emit('finish');
- } else {
- prefinish(stream, state);
- }
- }
- return need;
- }
- function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished) processNextTick(cb);else stream.once('finish', cb);
- }
- state.ended = true;
- stream.writable = false;
- }
- // It seems a linked list but it is not
- // there will be only 2 of these for each stream
- function CorkedRequest(state) {
- var _this = this;
- this.next = null;
- this.entry = null;
- this.finish = function (err) {
- var entry = _this.entry;
- _this.entry = null;
- while (entry) {
- var cb = entry.callback;
- state.pendingcb--;
- cb(err);
- entry = entry.next;
- }
- if (state.corkedRequestsFree) {
- state.corkedRequestsFree.next = _this;
- } else {
- state.corkedRequestsFree = _this;
- }
- };
- }
- }).call(this,require('_process'))
- },{"./_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){
- 'use strict';
- var Buffer = require('buffer').Buffer;
- /*<replacement>*/
- var bufferShim = require('buffer-shims');
- /*</replacement>*/
- module.exports = BufferList;
- function BufferList() {
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
- BufferList.prototype.push = function (v) {
- var entry = { data: v, next: null };
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
- this.tail = entry;
- ++this.length;
- };
- BufferList.prototype.unshift = function (v) {
- var entry = { data: v, next: this.head };
- if (this.length === 0) this.tail = entry;
- this.head = entry;
- ++this.length;
- };
- BufferList.prototype.shift = function () {
- if (this.length === 0) return;
- var ret = this.head.data;
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
- --this.length;
- return ret;
- };
- BufferList.prototype.clear = function () {
- this.head = this.tail = null;
- this.length = 0;
- };
- BufferList.prototype.join = function (s) {
- if (this.length === 0) return '';
- var p = this.head;
- var ret = '' + p.data;
- while (p = p.next) {
- ret += s + p.data;
- }return ret;
- };
- BufferList.prototype.concat = function (n) {
- if (this.length === 0) return bufferShim.alloc(0);
- if (this.length === 1) return this.head.data;
- var ret = bufferShim.allocUnsafe(n >>> 0);
- var p = this.head;
- var i = 0;
- while (p) {
- p.data.copy(ret, i);
- i += p.data.length;
- p = p.next;
- }
- return ret;
- };
- },{"buffer":77,"buffer-shims":76}],146:[function(require,module,exports){
- module.exports = require("./lib/_stream_passthrough.js")
- },{"./lib/_stream_passthrough.js":141}],147:[function(require,module,exports){
- (function (process){
- var Stream = (function (){
- try {
- return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
- } catch(_){}
- }());
- exports = module.exports = require('./lib/_stream_readable.js');
- exports.Stream = Stream || exports;
- exports.Readable = exports;
- exports.Writable = require('./lib/_stream_writable.js');
- exports.Duplex = require('./lib/_stream_duplex.js');
- exports.Transform = require('./lib/_stream_transform.js');
- exports.PassThrough = require('./lib/_stream_passthrough.js');
- if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
- module.exports = Stream;
- }
- }).call(this,require('_process'))
- },{"./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){
- module.exports = require("./lib/_stream_transform.js")
- },{"./lib/_stream_transform.js":143}],149:[function(require,module,exports){
- module.exports = require("./lib/_stream_writable.js")
- },{"./lib/_stream_writable.js":144}],150:[function(require,module,exports){
- (function (Buffer){
- ;(function (sax) { // wrapper for non-node envs
- sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
- sax.SAXParser = SAXParser
- sax.SAXStream = SAXStream
- sax.createStream = createStream
- // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
- // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
- // since that's the earliest that a buffer overrun could occur. This way, checks are
- // as rare as required, but as often as necessary to ensure never crossing this bound.
- // Furthermore, buffers are only tested at most once per write(), so passing a very
- // large string into write() might have undesirable effects, but this is manageable by
- // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
- // edge case, result in creating at most one complete copy of the string passed in.
- // Set to Infinity to have unlimited buffers.
- sax.MAX_BUFFER_LENGTH = 64 * 1024
- var buffers = [
- 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
- 'procInstName', 'procInstBody', 'entity', 'attribName',
- 'attribValue', 'cdata', 'script'
- ]
- sax.EVENTS = [
- 'text',
- 'processinginstruction',
- 'sgmldeclaration',
- 'doctype',
- 'comment',
- 'attribute',
- 'opentag',
- 'closetag',
- 'opencdata',
- 'cdata',
- 'closecdata',
- 'error',
- 'end',
- 'ready',
- 'script',
- 'opennamespace',
- 'closenamespace'
- ]
- function SAXParser (strict, opt) {
- if (!(this instanceof SAXParser)) {
- return new SAXParser(strict, opt)
- }
- var parser = this
- clearBuffers(parser)
- parser.q = parser.c = ''
- parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
- parser.opt = opt || {}
- parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
- parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
- parser.tags = []
- parser.closed = parser.closedRoot = parser.sawRoot = false
- parser.tag = parser.error = null
- parser.strict = !!strict
- parser.noscript = !!(strict || parser.opt.noscript)
- parser.state = S.BEGIN
- parser.strictEntities = parser.opt.strictEntities
- parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
- parser.attribList = []
- // namespaces form a prototype chain.
- // it always points at the current tag,
- // which protos to its parent tag.
- if (parser.opt.xmlns) {
- parser.ns = Object.create(rootNS)
- }
- // mostly just for error reporting
- parser.trackPosition = parser.opt.position !== false
- if (parser.trackPosition) {
- parser.position = parser.line = parser.column = 0
- }
- emit(parser, 'onready')
- }
- if (!Object.create) {
- Object.create = function (o) {
- function F () {}
- F.prototype = o
- var newf = new F()
- return newf
- }
- }
- if (!Object.keys) {
- Object.keys = function (o) {
- var a = []
- for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
- return a
- }
- }
- function checkBufferLength (parser) {
- var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
- var maxActual = 0
- for (var i = 0, l = buffers.length; i < l; i++) {
- var len = parser[buffers[i]].length
- if (len > maxAllowed) {
- // Text/cdata nodes can get big, and since they're buffered,
- // we can get here under normal conditions.
- // Avoid issues by emitting the text node now,
- // so at least it won't get any bigger.
- switch (buffers[i]) {
- case 'textNode':
- closeText(parser)
- break
- case 'cdata':
- emitNode(parser, 'oncdata', parser.cdata)
- parser.cdata = ''
- break
- case 'script':
- emitNode(parser, 'onscript', parser.script)
- parser.script = ''
- break
- default:
- error(parser, 'Max buffer length exceeded: ' + buffers[i])
- }
- }
- maxActual = Math.max(maxActual, len)
- }
- // schedule the next check for the earliest possible buffer overrun.
- var m = sax.MAX_BUFFER_LENGTH - maxActual
- parser.bufferCheckPosition = m + parser.position
- }
- function clearBuffers (parser) {
- for (var i = 0, l = buffers.length; i < l; i++) {
- parser[buffers[i]] = ''
- }
- }
- function flushBuffers (parser) {
- closeText(parser)
- if (parser.cdata !== '') {
- emitNode(parser, 'oncdata', parser.cdata)
- parser.cdata = ''
- }
- if (parser.script !== '') {
- emitNode(parser, 'onscript', parser.script)
- parser.script = ''
- }
- }
- SAXParser.prototype = {
- end: function () { end(this) },
- write: write,
- resume: function () { this.error = null; return this },
- close: function () { return this.write(null) },
- flush: function () { flushBuffers(this) }
- }
- var Stream
- try {
- Stream = require('stream').Stream
- } catch (ex) {
- Stream = function () {}
- }
- var streamWraps = sax.EVENTS.filter(function (ev) {
- return ev !== 'error' && ev !== 'end'
- })
- function createStream (strict, opt) {
- return new SAXStream(strict, opt)
- }
- function SAXStream (strict, opt) {
- if (!(this instanceof SAXStream)) {
- return new SAXStream(strict, opt)
- }
- Stream.apply(this)
- this._parser = new SAXParser(strict, opt)
- this.writable = true
- this.readable = true
- var me = this
- this._parser.onend = function () {
- me.emit('end')
- }
- this._parser.onerror = function (er) {
- me.emit('error', er)
- // if didn't throw, then means error was handled.
- // go ahead and clear error, so we can write again.
- me._parser.error = null
- }
- this._decoder = null
- streamWraps.forEach(function (ev) {
- Object.defineProperty(me, 'on' + ev, {
- get: function () {
- return me._parser['on' + ev]
- },
- set: function (h) {
- if (!h) {
- me.removeAllListeners(ev)
- me._parser['on' + ev] = h
- return h
- }
- me.on(ev, h)
- },
- enumerable: true,
- configurable: false
- })
- })
- }
- SAXStream.prototype = Object.create(Stream.prototype, {
- constructor: {
- value: SAXStream
- }
- })
- SAXStream.prototype.write = function (data) {
- if (typeof Buffer === 'function' &&
- typeof Buffer.isBuffer === 'function' &&
- Buffer.isBuffer(data)) {
- if (!this._decoder) {
- var SD = require('string_decoder').StringDecoder
- this._decoder = new SD('utf8')
- }
- data = this._decoder.write(data)
- }
- this._parser.write(data.toString())
- this.emit('data', data)
- return true
- }
- SAXStream.prototype.end = function (chunk) {
- if (chunk && chunk.length) {
- this.write(chunk)
- }
- this._parser.end()
- return true
- }
- SAXStream.prototype.on = function (ev, handler) {
- var me = this
- if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
- me._parser['on' + ev] = function () {
- var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
- args.splice(0, 0, ev)
- me.emit.apply(me, args)
- }
- }
- return Stream.prototype.on.call(me, ev, handler)
- }
- // character classes and tokens
- var whitespace = '\r\n\t '
- // this really needs to be replaced with character classes.
- // XML allows all manner of ridiculous numbers and digits.
- var number = '0124356789'
- var letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
- // (Letter | "_" | ":")
- var quote = '\'"'
- var attribEnd = whitespace + '>'
- var CDATA = '[CDATA['
- var DOCTYPE = 'DOCTYPE'
- var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
- var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
- var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
- // turn all the string character sets into character class objects.
- whitespace = charClass(whitespace)
- number = charClass(number)
- letter = charClass(letter)
- // http://www.w3.org/TR/REC-xml/#NT-NameStartChar
- // This implementation works on strings, a single character at a time
- // as such, it cannot ever support astral-plane characters (10000-EFFFF)
- // without a significant breaking change to either this parser, or the
- // JavaScript language. Implementation of an emoji-capable xml parser
- // is left as an exercise for the reader.
- 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]/
- 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-]/
- 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]/
- 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-]/
- quote = charClass(quote)
- attribEnd = charClass(attribEnd)
- function charClass (str) {
- return str.split('').reduce(function (s, c) {
- s[c] = true
- return s
- }, {})
- }
- function isRegExp (c) {
- return Object.prototype.toString.call(c) === '[object RegExp]'
- }
- function is (charclass, c) {
- return isRegExp(charclass) ? !!c.match(charclass) : charclass[c]
- }
- function not (charclass, c) {
- return !is(charclass, c)
- }
- var S = 0
- sax.STATE = {
- BEGIN: S++, // leading byte order mark or whitespace
- BEGIN_WHITESPACE: S++, // leading whitespace
- TEXT: S++, // general stuff
- TEXT_ENTITY: S++, // & and such.
- OPEN_WAKA: S++, // <
- SGML_DECL: S++, // <!BLARG
- SGML_DECL_QUOTED: S++, // <!BLARG foo "bar
- DOCTYPE: S++, // <!DOCTYPE
- DOCTYPE_QUOTED: S++, // <!DOCTYPE "//blah
- DOCTYPE_DTD: S++, // <!DOCTYPE "//blah" [ ...
- DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE "//blah" [ "foo
- COMMENT_STARTING: S++, // <!-
- COMMENT: S++, // <!--
- COMMENT_ENDING: S++, // <!-- blah -
- COMMENT_ENDED: S++, // <!-- blah --
- CDATA: S++, // <![CDATA[ something
- CDATA_ENDING: S++, // ]
- CDATA_ENDING_2: S++, // ]]
- PROC_INST: S++, // <?hi
- PROC_INST_BODY: S++, // <?hi there
- PROC_INST_ENDING: S++, // <?hi "there" ?
- OPEN_TAG: S++, // <strong
- OPEN_TAG_SLASH: S++, // <strong /
- ATTRIB: S++, // <a
- ATTRIB_NAME: S++, // <a foo
- ATTRIB_NAME_SAW_WHITE: S++, // <a foo _
- ATTRIB_VALUE: S++, // <a foo=
- ATTRIB_VALUE_QUOTED: S++, // <a foo="bar
- ATTRIB_VALUE_CLOSED: S++, // <a foo="bar"
- ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar
- ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar="""
- ATTRIB_VALUE_ENTITY_U: S++, // <foo bar="
- CLOSE_TAG: S++, // </a
- CLOSE_TAG_SAW_WHITE: S++, // </a >
- SCRIPT: S++, // <script> ...
- SCRIPT_ENDING: S++ // <script> ... <
- }
- sax.XML_ENTITIES = {
- 'amp': '&',
- 'gt': '>',
- 'lt': '<',
- 'quot': '"',
- 'apos': "'"
- }
- sax.ENTITIES = {
- 'amp': '&',
- 'gt': '>',
- 'lt': '<',
- 'quot': '"',
- 'apos': "'",
- 'AElig': 198,
- 'Aacute': 193,
- 'Acirc': 194,
- 'Agrave': 192,
- 'Aring': 197,
- 'Atilde': 195,
- 'Auml': 196,
- 'Ccedil': 199,
- 'ETH': 208,
- 'Eacute': 201,
- 'Ecirc': 202,
- 'Egrave': 200,
- 'Euml': 203,
- 'Iacute': 205,
- 'Icirc': 206,
- 'Igrave': 204,
- 'Iuml': 207,
- 'Ntilde': 209,
- 'Oacute': 211,
- 'Ocirc': 212,
- 'Ograve': 210,
- 'Oslash': 216,
- 'Otilde': 213,
- 'Ouml': 214,
- 'THORN': 222,
- 'Uacute': 218,
- 'Ucirc': 219,
- 'Ugrave': 217,
- 'Uuml': 220,
- 'Yacute': 221,
- 'aacute': 225,
- 'acirc': 226,
- 'aelig': 230,
- 'agrave': 224,
- 'aring': 229,
- 'atilde': 227,
- 'auml': 228,
- 'ccedil': 231,
- 'eacute': 233,
- 'ecirc': 234,
- 'egrave': 232,
- 'eth': 240,
- 'euml': 235,
- 'iacute': 237,
- 'icirc': 238,
- 'igrave': 236,
- 'iuml': 239,
- 'ntilde': 241,
- 'oacute': 243,
- 'ocirc': 244,
- 'ograve': 242,
- 'oslash': 248,
- 'otilde': 245,
- 'ouml': 246,
- 'szlig': 223,
- 'thorn': 254,
- 'uacute': 250,
- 'ucirc': 251,
- 'ugrave': 249,
- 'uuml': 252,
- 'yacute': 253,
- 'yuml': 255,
- 'copy': 169,
- 'reg': 174,
- 'nbsp': 160,
- 'iexcl': 161,
- 'cent': 162,
- 'pound': 163,
- 'curren': 164,
- 'yen': 165,
- 'brvbar': 166,
- 'sect': 167,
- 'uml': 168,
- 'ordf': 170,
- 'laquo': 171,
- 'not': 172,
- 'shy': 173,
- 'macr': 175,
- 'deg': 176,
- 'plusmn': 177,
- 'sup1': 185,
- 'sup2': 178,
- 'sup3': 179,
- 'acute': 180,
- 'micro': 181,
- 'para': 182,
- 'middot': 183,
- 'cedil': 184,
- 'ordm': 186,
- 'raquo': 187,
- 'frac14': 188,
- 'frac12': 189,
- 'frac34': 190,
- 'iquest': 191,
- 'times': 215,
- 'divide': 247,
- 'OElig': 338,
- 'oelig': 339,
- 'Scaron': 352,
- 'scaron': 353,
- 'Yuml': 376,
- 'fnof': 402,
- 'circ': 710,
- 'tilde': 732,
- 'Alpha': 913,
- 'Beta': 914,
- 'Gamma': 915,
- 'Delta': 916,
- 'Epsilon': 917,
- 'Zeta': 918,
- 'Eta': 919,
- 'Theta': 920,
- 'Iota': 921,
- 'Kappa': 922,
- 'Lambda': 923,
- 'Mu': 924,
- 'Nu': 925,
- 'Xi': 926,
- 'Omicron': 927,
- 'Pi': 928,
- 'Rho': 929,
- 'Sigma': 931,
- 'Tau': 932,
- 'Upsilon': 933,
- 'Phi': 934,
- 'Chi': 935,
- 'Psi': 936,
- 'Omega': 937,
- 'alpha': 945,
- 'beta': 946,
- 'gamma': 947,
- 'delta': 948,
- 'epsilon': 949,
- 'zeta': 950,
- 'eta': 951,
- 'theta': 952,
- 'iota': 953,
- 'kappa': 954,
- 'lambda': 955,
- 'mu': 956,
- 'nu': 957,
- 'xi': 958,
- 'omicron': 959,
- 'pi': 960,
- 'rho': 961,
- 'sigmaf': 962,
- 'sigma': 963,
- 'tau': 964,
- 'upsilon': 965,
- 'phi': 966,
- 'chi': 967,
- 'psi': 968,
- 'omega': 969,
- 'thetasym': 977,
- 'upsih': 978,
- 'piv': 982,
- 'ensp': 8194,
- 'emsp': 8195,
- 'thinsp': 8201,
- 'zwnj': 8204,
- 'zwj': 8205,
- 'lrm': 8206,
- 'rlm': 8207,
- 'ndash': 8211,
- 'mdash': 8212,
- 'lsquo': 8216,
- 'rsquo': 8217,
- 'sbquo': 8218,
- 'ldquo': 8220,
- 'rdquo': 8221,
- 'bdquo': 8222,
- 'dagger': 8224,
- 'Dagger': 8225,
- 'bull': 8226,
- 'hellip': 8230,
- 'permil': 8240,
- 'prime': 8242,
- 'Prime': 8243,
- 'lsaquo': 8249,
- 'rsaquo': 8250,
- 'oline': 8254,
- 'frasl': 8260,
- 'euro': 8364,
- 'image': 8465,
- 'weierp': 8472,
- 'real': 8476,
- 'trade': 8482,
- 'alefsym': 8501,
- 'larr': 8592,
- 'uarr': 8593,
- 'rarr': 8594,
- 'darr': 8595,
- 'harr': 8596,
- 'crarr': 8629,
- 'lArr': 8656,
- 'uArr': 8657,
- 'rArr': 8658,
- 'dArr': 8659,
- 'hArr': 8660,
- 'forall': 8704,
- 'part': 8706,
- 'exist': 8707,
- 'empty': 8709,
- 'nabla': 8711,
- 'isin': 8712,
- 'notin': 8713,
- 'ni': 8715,
- 'prod': 8719,
- 'sum': 8721,
- 'minus': 8722,
- 'lowast': 8727,
- 'radic': 8730,
- 'prop': 8733,
- 'infin': 8734,
- 'ang': 8736,
- 'and': 8743,
- 'or': 8744,
- 'cap': 8745,
- 'cup': 8746,
- 'int': 8747,
- 'there4': 8756,
- 'sim': 8764,
- 'cong': 8773,
- 'asymp': 8776,
- 'ne': 8800,
- 'equiv': 8801,
- 'le': 8804,
- 'ge': 8805,
- 'sub': 8834,
- 'sup': 8835,
- 'nsub': 8836,
- 'sube': 8838,
- 'supe': 8839,
- 'oplus': 8853,
- 'otimes': 8855,
- 'perp': 8869,
- 'sdot': 8901,
- 'lceil': 8968,
- 'rceil': 8969,
- 'lfloor': 8970,
- 'rfloor': 8971,
- 'lang': 9001,
- 'rang': 9002,
- 'loz': 9674,
- 'spades': 9824,
- 'clubs': 9827,
- 'hearts': 9829,
- 'diams': 9830
- }
- Object.keys(sax.ENTITIES).forEach(function (key) {
- var e = sax.ENTITIES[key]
- var s = typeof e === 'number' ? String.fromCharCode(e) : e
- sax.ENTITIES[key] = s
- })
- for (var s in sax.STATE) {
- sax.STATE[sax.STATE[s]] = s
- }
- // shorthand
- S = sax.STATE
- function emit (parser, event, data) {
- parser[event] && parser[event](data)
- }
- function emitNode (parser, nodeType, data) {
- if (parser.textNode) closeText(parser)
- emit(parser, nodeType, data)
- }
- function closeText (parser) {
- parser.textNode = textopts(parser.opt, parser.textNode)
- if (parser.textNode) emit(parser, 'ontext', parser.textNode)
- parser.textNode = ''
- }
- function textopts (opt, text) {
- if (opt.trim) text = text.trim()
- if (opt.normalize) text = text.replace(/\s+/g, ' ')
- return text
- }
- function error (parser, er) {
- closeText(parser)
- if (parser.trackPosition) {
- er += '\nLine: ' + parser.line +
- '\nColumn: ' + parser.column +
- '\nChar: ' + parser.c
- }
- er = new Error(er)
- parser.error = er
- emit(parser, 'onerror', er)
- return parser
- }
- function end (parser) {
- if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag')
- if ((parser.state !== S.BEGIN) &&
- (parser.state !== S.BEGIN_WHITESPACE) &&
- (parser.state !== S.TEXT)) {
- error(parser, 'Unexpected end')
- }
- closeText(parser)
- parser.c = ''
- parser.closed = true
- emit(parser, 'onend')
- SAXParser.call(parser, parser.strict, parser.opt)
- return parser
- }
- function strictFail (parser, message) {
- if (typeof parser !== 'object' || !(parser instanceof SAXParser)) {
- throw new Error('bad call to strictFail')
- }
- if (parser.strict) {
- error(parser, message)
- }
- }
- function newTag (parser) {
- if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]()
- var parent = parser.tags[parser.tags.length - 1] || parser
- var tag = parser.tag = { name: parser.tagName, attributes: {} }
- // will be overridden if tag contails an xmlns="foo" or xmlns:foo="bar"
- if (parser.opt.xmlns) {
- tag.ns = parent.ns
- }
- parser.attribList.length = 0
- }
- function qname (name, attribute) {
- var i = name.indexOf(':')
- var qualName = i < 0 ? [ '', name ] : name.split(':')
- var prefix = qualName[0]
- var local = qualName[1]
- // <x "xmlns"="http://foo">
- if (attribute && name === 'xmlns') {
- prefix = 'xmlns'
- local = ''
- }
- return { prefix: prefix, local: local }
- }
- function attrib (parser) {
- if (!parser.strict) {
- parser.attribName = parser.attribName[parser.looseCase]()
- }
- if (parser.attribList.indexOf(parser.attribName) !== -1 ||
- parser.tag.attributes.hasOwnProperty(parser.attribName)) {
- parser.attribName = parser.attribValue = ''
- return
- }
- if (parser.opt.xmlns) {
- var qn = qname(parser.attribName, true)
- var prefix = qn.prefix
- var local = qn.local
- if (prefix === 'xmlns') {
- // namespace binding attribute. push the binding into scope
- if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {
- strictFail(parser,
- 'xml: prefix must be bound to ' + XML_NAMESPACE + '\n' +
- 'Actual: ' + parser.attribValue)
- } else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {
- strictFail(parser,
- 'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\n' +
- 'Actual: ' + parser.attribValue)
- } else {
- var tag = parser.tag
- var parent = parser.tags[parser.tags.length - 1] || parser
- if (tag.ns === parent.ns) {
- tag.ns = Object.create(parent.ns)
- }
- tag.ns[local] = parser.attribValue
- }
- }
- // defer onattribute events until all attributes have been seen
- // so any new bindings can take effect. preserve attribute order
- // so deferred events can be emitted in document order
- parser.attribList.push([parser.attribName, parser.attribValue])
- } else {
- // in non-xmlns mode, we can emit the event right away
- parser.tag.attributes[parser.attribName] = parser.attribValue
- emitNode(parser, 'onattribute', {
- name: parser.attribName,
- value: parser.attribValue
- })
- }
- parser.attribName = parser.attribValue = ''
- }
- function openTag (parser, selfClosing) {
- if (parser.opt.xmlns) {
- // emit namespace binding events
- var tag = parser.tag
- // add namespace info to tag
- var qn = qname(parser.tagName)
- tag.prefix = qn.prefix
- tag.local = qn.local
- tag.uri = tag.ns[qn.prefix] || ''
- if (tag.prefix && !tag.uri) {
- strictFail(parser, 'Unbound namespace prefix: ' +
- JSON.stringify(parser.tagName))
- tag.uri = qn.prefix
- }
- var parent = parser.tags[parser.tags.length - 1] || parser
- if (tag.ns && parent.ns !== tag.ns) {
- Object.keys(tag.ns).forEach(function (p) {
- emitNode(parser, 'onopennamespace', {
- prefix: p,
- uri: tag.ns[p]
- })
- })
- }
- // handle deferred onattribute events
- // Note: do not apply default ns to attributes:
- // http://www.w3.org/TR/REC-xml-names/#defaulting
- for (var i = 0, l = parser.attribList.length; i < l; i++) {
- var nv = parser.attribList[i]
- var name = nv[0]
- var value = nv[1]
- var qualName = qname(name, true)
- var prefix = qualName.prefix
- var local = qualName.local
- var uri = prefix === '' ? '' : (tag.ns[prefix] || '')
- var a = {
- name: name,
- value: value,
- prefix: prefix,
- local: local,
- uri: uri
- }
- // if there's any attributes with an undefined namespace,
- // then fail on them now.
- if (prefix && prefix !== 'xmlns' && !uri) {
- strictFail(parser, 'Unbound namespace prefix: ' +
- JSON.stringify(prefix))
- a.uri = prefix
- }
- parser.tag.attributes[name] = a
- emitNode(parser, 'onattribute', a)
- }
- parser.attribList.length = 0
- }
- parser.tag.isSelfClosing = !!selfClosing
- // process the tag
- parser.sawRoot = true
- parser.tags.push(parser.tag)
- emitNode(parser, 'onopentag', parser.tag)
- if (!selfClosing) {
- // special case for <script> in non-strict mode.
- if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {
- parser.state = S.SCRIPT
- } else {
- parser.state = S.TEXT
- }
- parser.tag = null
- parser.tagName = ''
- }
- parser.attribName = parser.attribValue = ''
- parser.attribList.length = 0
- }
- function closeTag (parser) {
- if (!parser.tagName) {
- strictFail(parser, 'Weird empty close tag.')
- parser.textNode += '</>'
- parser.state = S.TEXT
- return
- }
- if (parser.script) {
- if (parser.tagName !== 'script') {
- parser.script += '</' + parser.tagName + '>'
- parser.tagName = ''
- parser.state = S.SCRIPT
- return
- }
- emitNode(parser, 'onscript', parser.script)
- parser.script = ''
- }
- // first make sure that the closing tag actually exists.
- // <a><b></c></b></a> will close everything, otherwise.
- var t = parser.tags.length
- var tagName = parser.tagName
- if (!parser.strict) {
- tagName = tagName[parser.looseCase]()
- }
- var closeTo = tagName
- while (t--) {
- var close = parser.tags[t]
- if (close.name !== closeTo) {
- // fail the first time in strict mode
- strictFail(parser, 'Unexpected close tag')
- } else {
- break
- }
- }
- // didn't find it. we already failed for strict, so just abort.
- if (t < 0) {
- strictFail(parser, 'Unmatched closing tag: ' + parser.tagName)
- parser.textNode += '</' + parser.tagName + '>'
- parser.state = S.TEXT
- return
- }
- parser.tagName = tagName
- var s = parser.tags.length
- while (s-- > t) {
- var tag = parser.tag = parser.tags.pop()
- parser.tagName = parser.tag.name
- emitNode(parser, 'onclosetag', parser.tagName)
- var x = {}
- for (var i in tag.ns) {
- x[i] = tag.ns[i]
- }
- var parent = parser.tags[parser.tags.length - 1] || parser
- if (parser.opt.xmlns && tag.ns !== parent.ns) {
- // remove namespace bindings introduced by tag
- Object.keys(tag.ns).forEach(function (p) {
- var n = tag.ns[p]
- emitNode(parser, 'onclosenamespace', { prefix: p, uri: n })
- })
- }
- }
- if (t === 0) parser.closedRoot = true
- parser.tagName = parser.attribValue = parser.attribName = ''
- parser.attribList.length = 0
- parser.state = S.TEXT
- }
- function parseEntity (parser) {
- var entity = parser.entity
- var entityLC = entity.toLowerCase()
- var num
- var numStr = ''
- if (parser.ENTITIES[entity]) {
- return parser.ENTITIES[entity]
- }
- if (parser.ENTITIES[entityLC]) {
- return parser.ENTITIES[entityLC]
- }
- entity = entityLC
- if (entity.charAt(0) === '#') {
- if (entity.charAt(1) === 'x') {
- entity = entity.slice(2)
- num = parseInt(entity, 16)
- numStr = num.toString(16)
- } else {
- entity = entity.slice(1)
- num = parseInt(entity, 10)
- numStr = num.toString(10)
- }
- }
- entity = entity.replace(/^0+/, '')
- if (numStr.toLowerCase() !== entity) {
- strictFail(parser, 'Invalid character entity')
- return '&' + parser.entity + ';'
- }
- return String.fromCodePoint(num)
- }
- function beginWhiteSpace (parser, c) {
- if (c === '<') {
- parser.state = S.OPEN_WAKA
- parser.startTagPosition = parser.position
- } else if (not(whitespace, c)) {
- // have to process this as a text node.
- // weird, but happens.
- strictFail(parser, 'Non-whitespace before first tag.')
- parser.textNode = c
- parser.state = S.TEXT
- }
- }
- function charAt (chunk, i) {
- var result = ''
- if (i < chunk.length) {
- result = chunk.charAt(i)
- }
- return result
- }
- function write (chunk) {
- var parser = this
- if (this.error) {
- throw this.error
- }
- if (parser.closed) {
- return error(parser,
- 'Cannot write after close. Assign an onready handler.')
- }
- if (chunk === null) {
- return end(parser)
- }
- if (typeof chunk === 'object') {
- chunk = chunk.toString()
- }
- var i = 0
- var c = ''
- while (true) {
- c = charAt(chunk, i++)
- parser.c = c
- if (!c) {
- break
- }
- if (parser.trackPosition) {
- parser.position++
- if (c === '\n') {
- parser.line++
- parser.column = 0
- } else {
- parser.column++
- }
- }
- switch (parser.state) {
- case S.BEGIN:
- parser.state = S.BEGIN_WHITESPACE
- if (c === '\uFEFF') {
- continue
- }
- beginWhiteSpace(parser, c)
- continue
- case S.BEGIN_WHITESPACE:
- beginWhiteSpace(parser, c)
- continue
- case S.TEXT:
- if (parser.sawRoot && !parser.closedRoot) {
- var starti = i - 1
- while (c && c !== '<' && c !== '&') {
- c = charAt(chunk, i++)
- if (c && parser.trackPosition) {
- parser.position++
- if (c === '\n') {
- parser.line++
- parser.column = 0
- } else {
- parser.column++
- }
- }
- }
- parser.textNode += chunk.substring(starti, i - 1)
- }
- if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
- parser.state = S.OPEN_WAKA
- parser.startTagPosition = parser.position
- } else {
- if (not(whitespace, c) && (!parser.sawRoot || parser.closedRoot)) {
- strictFail(parser, 'Text data outside of root node.')
- }
- if (c === '&') {
- parser.state = S.TEXT_ENTITY
- } else {
- parser.textNode += c
- }
- }
- continue
- case S.SCRIPT:
- // only non-strict
- if (c === '<') {
- parser.state = S.SCRIPT_ENDING
- } else {
- parser.script += c
- }
- continue
- case S.SCRIPT_ENDING:
- if (c === '/') {
- parser.state = S.CLOSE_TAG
- } else {
- parser.script += '<' + c
- parser.state = S.SCRIPT
- }
- continue
- case S.OPEN_WAKA:
- // either a /, ?, !, or text is coming next.
- if (c === '!') {
- parser.state = S.SGML_DECL
- parser.sgmlDecl = ''
- } else if (is(whitespace, c)) {
- // wait for it...
- } else if (is(nameStart, c)) {
- parser.state = S.OPEN_TAG
- parser.tagName = c
- } else if (c === '/') {
- parser.state = S.CLOSE_TAG
- parser.tagName = ''
- } else if (c === '?') {
- parser.state = S.PROC_INST
- parser.procInstName = parser.procInstBody = ''
- } else {
- strictFail(parser, 'Unencoded <')
- // if there was some whitespace, then add that in.
- if (parser.startTagPosition + 1 < parser.position) {
- var pad = parser.position - parser.startTagPosition
- c = new Array(pad).join(' ') + c
- }
- parser.textNode += '<' + c
- parser.state = S.TEXT
- }
- continue
- case S.SGML_DECL:
- if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
- emitNode(parser, 'onopencdata')
- parser.state = S.CDATA
- parser.sgmlDecl = ''
- parser.cdata = ''
- } else if (parser.sgmlDecl + c === '--') {
- parser.state = S.COMMENT
- parser.comment = ''
- parser.sgmlDecl = ''
- } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
- parser.state = S.DOCTYPE
- if (parser.doctype || parser.sawRoot) {
- strictFail(parser,
- 'Inappropriately located doctype declaration')
- }
- parser.doctype = ''
- parser.sgmlDecl = ''
- } else if (c === '>') {
- emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl)
- parser.sgmlDecl = ''
- parser.state = S.TEXT
- } else if (is(quote, c)) {
- parser.state = S.SGML_DECL_QUOTED
- parser.sgmlDecl += c
- } else {
- parser.sgmlDecl += c
- }
- continue
- case S.SGML_DECL_QUOTED:
- if (c === parser.q) {
- parser.state = S.SGML_DECL
- parser.q = ''
- }
- parser.sgmlDecl += c
- continue
- case S.DOCTYPE:
- if (c === '>') {
- parser.state = S.TEXT
- emitNode(parser, 'ondoctype', parser.doctype)
- parser.doctype = true // just remember that we saw it.
- } else {
- parser.doctype += c
- if (c === '[') {
- parser.state = S.DOCTYPE_DTD
- } else if (is(quote, c)) {
- parser.state = S.DOCTYPE_QUOTED
- parser.q = c
- }
- }
- continue
- case S.DOCTYPE_QUOTED:
- parser.doctype += c
- if (c === parser.q) {
- parser.q = ''
- parser.state = S.DOCTYPE
- }
- continue
- case S.DOCTYPE_DTD:
- parser.doctype += c
- if (c === ']') {
- parser.state = S.DOCTYPE
- } else if (is(quote, c)) {
- parser.state = S.DOCTYPE_DTD_QUOTED
- parser.q = c
- }
- continue
- case S.DOCTYPE_DTD_QUOTED:
- parser.doctype += c
- if (c === parser.q) {
- parser.state = S.DOCTYPE_DTD
- parser.q = ''
- }
- continue
- case S.COMMENT:
- if (c === '-') {
- parser.state = S.COMMENT_ENDING
- } else {
- parser.comment += c
- }
- continue
- case S.COMMENT_ENDING:
- if (c === '-') {
- parser.state = S.COMMENT_ENDED
- parser.comment = textopts(parser.opt, parser.comment)
- if (parser.comment) {
- emitNode(parser, 'oncomment', parser.comment)
- }
- parser.comment = ''
- } else {
- parser.comment += '-' + c
- parser.state = S.COMMENT
- }
- continue
- case S.COMMENT_ENDED:
- if (c !== '>') {
- strictFail(parser, 'Malformed comment')
- // allow <!-- blah -- bloo --> in non-strict mode,
- // which is a comment of " blah -- bloo "
- parser.comment += '--' + c
- parser.state = S.COMMENT
- } else {
- parser.state = S.TEXT
- }
- continue
- case S.CDATA:
- if (c === ']') {
- parser.state = S.CDATA_ENDING
- } else {
- parser.cdata += c
- }
- continue
- case S.CDATA_ENDING:
- if (c === ']') {
- parser.state = S.CDATA_ENDING_2
- } else {
- parser.cdata += ']' + c
- parser.state = S.CDATA
- }
- continue
- case S.CDATA_ENDING_2:
- if (c === '>') {
- if (parser.cdata) {
- emitNode(parser, 'oncdata', parser.cdata)
- }
- emitNode(parser, 'onclosecdata')
- parser.cdata = ''
- parser.state = S.TEXT
- } else if (c === ']') {
- parser.cdata += ']'
- } else {
- parser.cdata += ']]' + c
- parser.state = S.CDATA
- }
- continue
- case S.PROC_INST:
- if (c === '?') {
- parser.state = S.PROC_INST_ENDING
- } else if (is(whitespace, c)) {
- parser.state = S.PROC_INST_BODY
- } else {
- parser.procInstName += c
- }
- continue
- case S.PROC_INST_BODY:
- if (!parser.procInstBody && is(whitespace, c)) {
- continue
- } else if (c === '?') {
- parser.state = S.PROC_INST_ENDING
- } else {
- parser.procInstBody += c
- }
- continue
- case S.PROC_INST_ENDING:
- if (c === '>') {
- emitNode(parser, 'onprocessinginstruction', {
- name: parser.procInstName,
- body: parser.procInstBody
- })
- parser.procInstName = parser.procInstBody = ''
- parser.state = S.TEXT
- } else {
- parser.procInstBody += '?' + c
- parser.state = S.PROC_INST_BODY
- }
- continue
- case S.OPEN_TAG:
- if (is(nameBody, c)) {
- parser.tagName += c
- } else {
- newTag(parser)
- if (c === '>') {
- openTag(parser)
- } else if (c === '/') {
- parser.state = S.OPEN_TAG_SLASH
- } else {
- if (not(whitespace, c)) {
- strictFail(parser, 'Invalid character in tag name')
- }
- parser.state = S.ATTRIB
- }
- }
- continue
- case S.OPEN_TAG_SLASH:
- if (c === '>') {
- openTag(parser, true)
- closeTag(parser)
- } else {
- strictFail(parser, 'Forward-slash in opening tag not followed by >')
- parser.state = S.ATTRIB
- }
- continue
- case S.ATTRIB:
- // haven't read the attribute name yet.
- if (is(whitespace, c)) {
- continue
- } else if (c === '>') {
- openTag(parser)
- } else if (c === '/') {
- parser.state = S.OPEN_TAG_SLASH
- } else if (is(nameStart, c)) {
- parser.attribName = c
- parser.attribValue = ''
- parser.state = S.ATTRIB_NAME
- } else {
- strictFail(parser, 'Invalid attribute name')
- }
- continue
- case S.ATTRIB_NAME:
- if (c === '=') {
- parser.state = S.ATTRIB_VALUE
- } else if (c === '>') {
- strictFail(parser, 'Attribute without value')
- parser.attribValue = parser.attribName
- attrib(parser)
- openTag(parser)
- } else if (is(whitespace, c)) {
- parser.state = S.ATTRIB_NAME_SAW_WHITE
- } else if (is(nameBody, c)) {
- parser.attribName += c
- } else {
- strictFail(parser, 'Invalid attribute name')
- }
- continue
- case S.ATTRIB_NAME_SAW_WHITE:
- if (c === '=') {
- parser.state = S.ATTRIB_VALUE
- } else if (is(whitespace, c)) {
- continue
- } else {
- strictFail(parser, 'Attribute without value')
- parser.tag.attributes[parser.attribName] = ''
- parser.attribValue = ''
- emitNode(parser, 'onattribute', {
- name: parser.attribName,
- value: ''
- })
- parser.attribName = ''
- if (c === '>') {
- openTag(parser)
- } else if (is(nameStart, c)) {
- parser.attribName = c
- parser.state = S.ATTRIB_NAME
- } else {
- strictFail(parser, 'Invalid attribute name')
- parser.state = S.ATTRIB
- }
- }
- continue
- case S.ATTRIB_VALUE:
- if (is(whitespace, c)) {
- continue
- } else if (is(quote, c)) {
- parser.q = c
- parser.state = S.ATTRIB_VALUE_QUOTED
- } else {
- strictFail(parser, 'Unquoted attribute value')
- parser.state = S.ATTRIB_VALUE_UNQUOTED
- parser.attribValue = c
- }
- continue
- case S.ATTRIB_VALUE_QUOTED:
- if (c !== parser.q) {
- if (c === '&') {
- parser.state = S.ATTRIB_VALUE_ENTITY_Q
- } else {
- parser.attribValue += c
- }
- continue
- }
- attrib(parser)
- parser.q = ''
- parser.state = S.ATTRIB_VALUE_CLOSED
- continue
- case S.ATTRIB_VALUE_CLOSED:
- if (is(whitespace, c)) {
- parser.state = S.ATTRIB
- } else if (c === '>') {
- openTag(parser)
- } else if (c === '/') {
- parser.state = S.OPEN_TAG_SLASH
- } else if (is(nameStart, c)) {
- strictFail(parser, 'No whitespace between attributes')
- parser.attribName = c
- parser.attribValue = ''
- parser.state = S.ATTRIB_NAME
- } else {
- strictFail(parser, 'Invalid attribute name')
- }
- continue
- case S.ATTRIB_VALUE_UNQUOTED:
- if (not(attribEnd, c)) {
- if (c === '&') {
- parser.state = S.ATTRIB_VALUE_ENTITY_U
- } else {
- parser.attribValue += c
- }
- continue
- }
- attrib(parser)
- if (c === '>') {
- openTag(parser)
- } else {
- parser.state = S.ATTRIB
- }
- continue
- case S.CLOSE_TAG:
- if (!parser.tagName) {
- if (is(whitespace, c)) {
- continue
- } else if (not(nameStart, c)) {
- if (parser.script) {
- parser.script += '</' + c
- parser.state = S.SCRIPT
- } else {
- strictFail(parser, 'Invalid tagname in closing tag.')
- }
- } else {
- parser.tagName = c
- }
- } else if (c === '>') {
- closeTag(parser)
- } else if (is(nameBody, c)) {
- parser.tagName += c
- } else if (parser.script) {
- parser.script += '</' + parser.tagName
- parser.tagName = ''
- parser.state = S.SCRIPT
- } else {
- if (not(whitespace, c)) {
- strictFail(parser, 'Invalid tagname in closing tag')
- }
- parser.state = S.CLOSE_TAG_SAW_WHITE
- }
- continue
- case S.CLOSE_TAG_SAW_WHITE:
- if (is(whitespace, c)) {
- continue
- }
- if (c === '>') {
- closeTag(parser)
- } else {
- strictFail(parser, 'Invalid characters in closing tag')
- }
- continue
- case S.TEXT_ENTITY:
- case S.ATTRIB_VALUE_ENTITY_Q:
- case S.ATTRIB_VALUE_ENTITY_U:
- var returnState
- var buffer
- switch (parser.state) {
- case S.TEXT_ENTITY:
- returnState = S.TEXT
- buffer = 'textNode'
- break
- case S.ATTRIB_VALUE_ENTITY_Q:
- returnState = S.ATTRIB_VALUE_QUOTED
- buffer = 'attribValue'
- break
- case S.ATTRIB_VALUE_ENTITY_U:
- returnState = S.ATTRIB_VALUE_UNQUOTED
- buffer = 'attribValue'
- break
- }
- if (c === ';') {
- parser[buffer] += parseEntity(parser)
- parser.entity = ''
- parser.state = returnState
- } else if (is(parser.entity.length ? entityBody : entityStart, c)) {
- parser.entity += c
- } else {
- strictFail(parser, 'Invalid character in entity name')
- parser[buffer] += '&' + parser.entity + c
- parser.entity = ''
- parser.state = returnState
- }
- continue
- default:
- throw new Error(parser, 'Unknown state: ' + parser.state)
- }
- } // while
- if (parser.position >= parser.bufferCheckPosition) {
- checkBufferLength(parser)
- }
- return parser
- }
- /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
- if (!String.fromCodePoint) {
- (function () {
- var stringFromCharCode = String.fromCharCode
- var floor = Math.floor
- var fromCodePoint = function () {
- var MAX_SIZE = 0x4000
- var codeUnits = []
- var highSurrogate
- var lowSurrogate
- var index = -1
- var length = arguments.length
- if (!length) {
- return ''
- }
- var result = ''
- while (++index < length) {
- var codePoint = Number(arguments[index])
- if (
- !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
- codePoint < 0 || // not a valid Unicode code point
- codePoint > 0x10FFFF || // not a valid Unicode code point
- floor(codePoint) !== codePoint // not an integer
- ) {
- throw RangeError('Invalid code point: ' + codePoint)
- }
- if (codePoint <= 0xFFFF) { // BMP code point
- codeUnits.push(codePoint)
- } else { // Astral code point; split in surrogate halves
- // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
- codePoint -= 0x10000
- highSurrogate = (codePoint >> 10) + 0xD800
- lowSurrogate = (codePoint % 0x400) + 0xDC00
- codeUnits.push(highSurrogate, lowSurrogate)
- }
- if (index + 1 === length || codeUnits.length > MAX_SIZE) {
- result += stringFromCharCode.apply(null, codeUnits)
- codeUnits.length = 0
- }
- }
- return result
- }
- if (Object.defineProperty) {
- Object.defineProperty(String, 'fromCodePoint', {
- value: fromCodePoint,
- configurable: true,
- writable: true
- })
- } else {
- String.fromCodePoint = fromCodePoint
- }
- }())
- }
- })(typeof exports === 'undefined' ? this.sax = {} : exports)
- }).call(this,require("buffer").Buffer)
- },{"buffer":77,"stream":151,"string_decoder":152}],151:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- module.exports = Stream;
- var EE = require('events').EventEmitter;
- var inherits = require('inherits');
- inherits(Stream, EE);
- Stream.Readable = require('readable-stream/readable.js');
- Stream.Writable = require('readable-stream/writable.js');
- Stream.Duplex = require('readable-stream/duplex.js');
- Stream.Transform = require('readable-stream/transform.js');
- Stream.PassThrough = require('readable-stream/passthrough.js');
- // Backwards-compat with node 0.4.x
- Stream.Stream = Stream;
- // old-style streams. Note that the pipe method (the only relevant
- // part of this class) is overridden in the Readable class.
- function Stream() {
- EE.call(this);
- }
- Stream.prototype.pipe = function(dest, options) {
- var source = this;
- function ondata(chunk) {
- if (dest.writable) {
- if (false === dest.write(chunk) && source.pause) {
- source.pause();
- }
- }
- }
- source.on('data', ondata);
- function ondrain() {
- if (source.readable && source.resume) {
- source.resume();
- }
- }
- dest.on('drain', ondrain);
- // If the 'end' option is not supplied, dest.end() will be called when
- // source gets the 'end' or 'close' events. Only dest.end() once.
- if (!dest._isStdio && (!options || options.end !== false)) {
- source.on('end', onend);
- source.on('close', onclose);
- }
- var didOnEnd = false;
- function onend() {
- if (didOnEnd) return;
- didOnEnd = true;
- dest.end();
- }
- function onclose() {
- if (didOnEnd) return;
- didOnEnd = true;
- if (typeof dest.destroy === 'function') dest.destroy();
- }
- // don't leave dangling pipes when there are errors.
- function onerror(er) {
- cleanup();
- if (EE.listenerCount(this, 'error') === 0) {
- throw er; // Unhandled stream error in pipe.
- }
- }
- source.on('error', onerror);
- dest.on('error', onerror);
- // remove all the event listeners that were added.
- function cleanup() {
- source.removeListener('data', ondata);
- dest.removeListener('drain', ondrain);
- source.removeListener('end', onend);
- source.removeListener('close', onclose);
- source.removeListener('error', onerror);
- dest.removeListener('error', onerror);
- source.removeListener('end', cleanup);
- source.removeListener('close', cleanup);
- dest.removeListener('close', cleanup);
- }
- source.on('end', cleanup);
- source.on('close', cleanup);
- dest.on('close', cleanup);
- dest.emit('pipe', source);
- // Allow for unix-like usage: A.pipe(B).pipe(C)
- return dest;
- };
- },{"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){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var Buffer = require('buffer').Buffer;
- var isBufferEncoding = Buffer.isEncoding
- || function(encoding) {
- switch (encoding && encoding.toLowerCase()) {
- 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;
- default: return false;
- }
- }
- function assertEncoding(encoding) {
- if (encoding && !isBufferEncoding(encoding)) {
- throw new Error('Unknown encoding: ' + encoding);
- }
- }
- // StringDecoder provides an interface for efficiently splitting a series of
- // buffers into a series of JS strings without breaking apart multi-byte
- // characters. CESU-8 is handled as part of the UTF-8 encoding.
- //
- // @TODO Handling all encodings inside a single object makes it very difficult
- // to reason about this code, so it should be split up in the future.
- // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
- // points as used by CESU-8.
- var StringDecoder = exports.StringDecoder = function(encoding) {
- this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
- assertEncoding(encoding);
- switch (this.encoding) {
- case 'utf8':
- // CESU-8 represents each of Surrogate Pair by 3-bytes
- this.surrogateSize = 3;
- break;
- case 'ucs2':
- case 'utf16le':
- // UTF-16 represents each of Surrogate Pair by 2-bytes
- this.surrogateSize = 2;
- this.detectIncompleteChar = utf16DetectIncompleteChar;
- break;
- case 'base64':
- // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
- this.surrogateSize = 3;
- this.detectIncompleteChar = base64DetectIncompleteChar;
- break;
- default:
- this.write = passThroughWrite;
- return;
- }
- // Enough space to store all bytes of a single character. UTF-8 needs 4
- // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
- this.charBuffer = new Buffer(6);
- // Number of bytes received for the current incomplete multi-byte character.
- this.charReceived = 0;
- // Number of bytes expected for the current incomplete multi-byte character.
- this.charLength = 0;
- };
- // write decodes the given buffer and returns it as JS string that is
- // guaranteed to not contain any partial multi-byte characters. Any partial
- // character found at the end of the buffer is buffered up, and will be
- // returned when calling write again with the remaining bytes.
- //
- // Note: Converting a Buffer containing an orphan surrogate to a String
- // currently works, but converting a String to a Buffer (via `new Buffer`, or
- // Buffer#write) will replace incomplete surrogates with the unicode
- // replacement character. See https://codereview.chromium.org/121173009/ .
- StringDecoder.prototype.write = function(buffer) {
- var charStr = '';
- // if our last write ended with an incomplete multibyte character
- while (this.charLength) {
- // determine how many remaining bytes this buffer has to offer for this char
- var available = (buffer.length >= this.charLength - this.charReceived) ?
- this.charLength - this.charReceived :
- buffer.length;
- // add the new bytes to the char buffer
- buffer.copy(this.charBuffer, this.charReceived, 0, available);
- this.charReceived += available;
- if (this.charReceived < this.charLength) {
- // still not enough chars in this buffer? wait for more ...
- return '';
- }
- // remove bytes belonging to the current character from the buffer
- buffer = buffer.slice(available, buffer.length);
- // get the character that was split
- charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
- // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
- var charCode = charStr.charCodeAt(charStr.length - 1);
- if (charCode >= 0xD800 && charCode <= 0xDBFF) {
- this.charLength += this.surrogateSize;
- charStr = '';
- continue;
- }
- this.charReceived = this.charLength = 0;
- // if there are no more bytes in this buffer, just emit our char
- if (buffer.length === 0) {
- return charStr;
- }
- break;
- }
- // determine and set charLength / charReceived
- this.detectIncompleteChar(buffer);
- var end = buffer.length;
- if (this.charLength) {
- // buffer the incomplete character bytes we got
- buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
- end -= this.charReceived;
- }
- charStr += buffer.toString(this.encoding, 0, end);
- var end = charStr.length - 1;
- var charCode = charStr.charCodeAt(end);
- // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
- if (charCode >= 0xD800 && charCode <= 0xDBFF) {
- var size = this.surrogateSize;
- this.charLength += size;
- this.charReceived += size;
- this.charBuffer.copy(this.charBuffer, size, 0, size);
- buffer.copy(this.charBuffer, 0, 0, size);
- return charStr.substring(0, end);
- }
- // or just emit the charStr
- return charStr;
- };
- // detectIncompleteChar determines if there is an incomplete UTF-8 character at
- // the end of the given buffer. If so, it sets this.charLength to the byte
- // length that character, and sets this.charReceived to the number of bytes
- // that are available for this character.
- StringDecoder.prototype.detectIncompleteChar = function(buffer) {
- // determine how many bytes we have to check at the end of this buffer
- var i = (buffer.length >= 3) ? 3 : buffer.length;
- // Figure out if one of the last i bytes of our buffer announces an
- // incomplete char.
- for (; i > 0; i--) {
- var c = buffer[buffer.length - i];
- // See http://en.wikipedia.org/wiki/UTF-8#Description
- // 110XXXXX
- if (i == 1 && c >> 5 == 0x06) {
- this.charLength = 2;
- break;
- }
- // 1110XXXX
- if (i <= 2 && c >> 4 == 0x0E) {
- this.charLength = 3;
- break;
- }
- // 11110XXX
- if (i <= 3 && c >> 3 == 0x1E) {
- this.charLength = 4;
- break;
- }
- }
- this.charReceived = i;
- };
- StringDecoder.prototype.end = function(buffer) {
- var res = '';
- if (buffer && buffer.length)
- res = this.write(buffer);
- if (this.charReceived) {
- var cr = this.charReceived;
- var buf = this.charBuffer;
- var enc = this.encoding;
- res += buf.slice(0, cr).toString(enc);
- }
- return res;
- };
- function passThroughWrite(buffer) {
- return buffer.toString(this.encoding);
- }
- function utf16DetectIncompleteChar(buffer) {
- this.charReceived = buffer.length % 2;
- this.charLength = this.charReceived ? 2 : 0;
- }
- function base64DetectIncompleteChar(buffer) {
- this.charReceived = buffer.length % 3;
- this.charLength = this.charReceived ? 3 : 0;
- }
- },{"buffer":77}],153:[function(require,module,exports){
- // Underscore.js 1.8.3
- // http://underscorejs.org
- // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- // Underscore may be freely distributed under the MIT license.
- (function() {
- // Baseline setup
- // --------------
- // Establish the root object, `window` in the browser, or `exports` on the server.
- var root = this;
- // Save the previous value of the `_` variable.
- var previousUnderscore = root._;
- // Save bytes in the minified (but not gzipped) version:
- var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
- // Create quick reference variables for speed access to core prototypes.
- var
- push = ArrayProto.push,
- slice = ArrayProto.slice,
- toString = ObjProto.toString,
- hasOwnProperty = ObjProto.hasOwnProperty;
- // All **ECMAScript 5** native function implementations that we hope to use
- // are declared here.
- var
- nativeIsArray = Array.isArray,
- nativeKeys = Object.keys,
- nativeBind = FuncProto.bind,
- nativeCreate = Object.create;
- // Naked function reference for surrogate-prototype-swapping.
- var Ctor = function(){};
- // Create a safe reference to the Underscore object for use below.
- var _ = function(obj) {
- if (obj instanceof _) return obj;
- if (!(this instanceof _)) return new _(obj);
- this._wrapped = obj;
- };
- // Export the Underscore object for **Node.js**, with
- // backwards-compatibility for the old `require()` API. If we're in
- // the browser, add `_` as a global object.
- if (typeof exports !== 'undefined') {
- if (typeof module !== 'undefined' && module.exports) {
- exports = module.exports = _;
- }
- exports._ = _;
- } else {
- root._ = _;
- }
- // Current version.
- _.VERSION = '1.8.3';
- // Internal function that returns an efficient (for current engines) version
- // of the passed-in callback, to be repeatedly applied in other Underscore
- // functions.
- var optimizeCb = function(func, context, argCount) {
- if (context === void 0) return func;
- switch (argCount == null ? 3 : argCount) {
- case 1: return function(value) {
- return func.call(context, value);
- };
- case 2: return function(value, other) {
- return func.call(context, value, other);
- };
- case 3: return function(value, index, collection) {
- return func.call(context, value, index, collection);
- };
- case 4: return function(accumulator, value, index, collection) {
- return func.call(context, accumulator, value, index, collection);
- };
- }
- return function() {
- return func.apply(context, arguments);
- };
- };
- // A mostly-internal function to generate callbacks that can be applied
- // to each element in a collection, returning the desired result — either
- // identity, an arbitrary callback, a property matcher, or a property accessor.
- var cb = function(value, context, argCount) {
- if (value == null) return _.identity;
- if (_.isFunction(value)) return optimizeCb(value, context, argCount);
- if (_.isObject(value)) return _.matcher(value);
- return _.property(value);
- };
- _.iteratee = function(value, context) {
- return cb(value, context, Infinity);
- };
- // An internal function for creating assigner functions.
- var createAssigner = function(keysFunc, undefinedOnly) {
- return function(obj) {
- var length = arguments.length;
- if (length < 2 || obj == null) return obj;
- for (var index = 1; index < length; index++) {
- var source = arguments[index],
- keys = keysFunc(source),
- l = keys.length;
- for (var i = 0; i < l; i++) {
- var key = keys[i];
- if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
- }
- }
- return obj;
- };
- };
- // An internal function for creating a new object that inherits from another.
- var baseCreate = function(prototype) {
- if (!_.isObject(prototype)) return {};
- if (nativeCreate) return nativeCreate(prototype);
- Ctor.prototype = prototype;
- var result = new Ctor;
- Ctor.prototype = null;
- return result;
- };
- var property = function(key) {
- return function(obj) {
- return obj == null ? void 0 : obj[key];
- };
- };
- // Helper for collection methods to determine whether a collection
- // should be iterated as an array or as an object
- // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
- // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
- var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
- var getLength = property('length');
- var isArrayLike = function(collection) {
- var length = getLength(collection);
- return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
- };
- // Collection Functions
- // --------------------
- // The cornerstone, an `each` implementation, aka `forEach`.
- // Handles raw objects in addition to array-likes. Treats all
- // sparse array-likes as if they were dense.
- _.each = _.forEach = function(obj, iteratee, context) {
- iteratee = optimizeCb(iteratee, context);
- var i, length;
- if (isArrayLike(obj)) {
- for (i = 0, length = obj.length; i < length; i++) {
- iteratee(obj[i], i, obj);
- }
- } else {
- var keys = _.keys(obj);
- for (i = 0, length = keys.length; i < length; i++) {
- iteratee(obj[keys[i]], keys[i], obj);
- }
- }
- return obj;
- };
- // Return the results of applying the iteratee to each element.
- _.map = _.collect = function(obj, iteratee, context) {
- iteratee = cb(iteratee, context);
- var keys = !isArrayLike(obj) && _.keys(obj),
- length = (keys || obj).length,
- results = Array(length);
- for (var index = 0; index < length; index++) {
- var currentKey = keys ? keys[index] : index;
- results[index] = iteratee(obj[currentKey], currentKey, obj);
- }
- return results;
- };
- // Create a reducing function iterating left or right.
- function createReduce(dir) {
- // Optimized iterator function as using arguments.length
- // in the main function will deoptimize the, see #1991.
- function iterator(obj, iteratee, memo, keys, index, length) {
- for (; index >= 0 && index < length; index += dir) {
- var currentKey = keys ? keys[index] : index;
- memo = iteratee(memo, obj[currentKey], currentKey, obj);
- }
- return memo;
- }
- return function(obj, iteratee, memo, context) {
- iteratee = optimizeCb(iteratee, context, 4);
- var keys = !isArrayLike(obj) && _.keys(obj),
- length = (keys || obj).length,
- index = dir > 0 ? 0 : length - 1;
- // Determine the initial value if none is provided.
- if (arguments.length < 3) {
- memo = obj[keys ? keys[index] : index];
- index += dir;
- }
- return iterator(obj, iteratee, memo, keys, index, length);
- };
- }
- // **Reduce** builds up a single result from a list of values, aka `inject`,
- // or `foldl`.
- _.reduce = _.foldl = _.inject = createReduce(1);
- // The right-associative version of reduce, also known as `foldr`.
- _.reduceRight = _.foldr = createReduce(-1);
- // Return the first value which passes a truth test. Aliased as `detect`.
- _.find = _.detect = function(obj, predicate, context) {
- var key;
- if (isArrayLike(obj)) {
- key = _.findIndex(obj, predicate, context);
- } else {
- key = _.findKey(obj, predicate, context);
- }
- if (key !== void 0 && key !== -1) return obj[key];
- };
- // Return all the elements that pass a truth test.
- // Aliased as `select`.
- _.filter = _.select = function(obj, predicate, context) {
- var results = [];
- predicate = cb(predicate, context);
- _.each(obj, function(value, index, list) {
- if (predicate(value, index, list)) results.push(value);
- });
- return results;
- };
- // Return all the elements for which a truth test fails.
- _.reject = function(obj, predicate, context) {
- return _.filter(obj, _.negate(cb(predicate)), context);
- };
- // Determine whether all of the elements match a truth test.
- // Aliased as `all`.
- _.every = _.all = function(obj, predicate, context) {
- predicate = cb(predicate, context);
- var keys = !isArrayLike(obj) && _.keys(obj),
- length = (keys || obj).length;
- for (var index = 0; index < length; index++) {
- var currentKey = keys ? keys[index] : index;
- if (!predicate(obj[currentKey], currentKey, obj)) return false;
- }
- return true;
- };
- // Determine if at least one element in the object matches a truth test.
- // Aliased as `any`.
- _.some = _.any = function(obj, predicate, context) {
- predicate = cb(predicate, context);
- var keys = !isArrayLike(obj) && _.keys(obj),
- length = (keys || obj).length;
- for (var index = 0; index < length; index++) {
- var currentKey = keys ? keys[index] : index;
- if (predicate(obj[currentKey], currentKey, obj)) return true;
- }
- return false;
- };
- // Determine if the array or object contains a given item (using `===`).
- // Aliased as `includes` and `include`.
- _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
- if (!isArrayLike(obj)) obj = _.values(obj);
- if (typeof fromIndex != 'number' || guard) fromIndex = 0;
- return _.indexOf(obj, item, fromIndex) >= 0;
- };
- // Invoke a method (with arguments) on every item in a collection.
- _.invoke = function(obj, method) {
- var args = slice.call(arguments, 2);
- var isFunc = _.isFunction(method);
- return _.map(obj, function(value) {
- var func = isFunc ? method : value[method];
- return func == null ? func : func.apply(value, args);
- });
- };
- // Convenience version of a common use case of `map`: fetching a property.
- _.pluck = function(obj, key) {
- return _.map(obj, _.property(key));
- };
- // Convenience version of a common use case of `filter`: selecting only objects
- // containing specific `key:value` pairs.
- _.where = function(obj, attrs) {
- return _.filter(obj, _.matcher(attrs));
- };
- // Convenience version of a common use case of `find`: getting the first object
- // containing specific `key:value` pairs.
- _.findWhere = function(obj, attrs) {
- return _.find(obj, _.matcher(attrs));
- };
- // Return the maximum element (or element-based computation).
- _.max = function(obj, iteratee, context) {
- var result = -Infinity, lastComputed = -Infinity,
- value, computed;
- if (iteratee == null && obj != null) {
- obj = isArrayLike(obj) ? obj : _.values(obj);
- for (var i = 0, length = obj.length; i < length; i++) {
- value = obj[i];
- if (value > result) {
- result = value;
- }
- }
- } else {
- iteratee = cb(iteratee, context);
- _.each(obj, function(value, index, list) {
- computed = iteratee(value, index, list);
- if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
- result = value;
- lastComputed = computed;
- }
- });
- }
- return result;
- };
- // Return the minimum element (or element-based computation).
- _.min = function(obj, iteratee, context) {
- var result = Infinity, lastComputed = Infinity,
- value, computed;
- if (iteratee == null && obj != null) {
- obj = isArrayLike(obj) ? obj : _.values(obj);
- for (var i = 0, length = obj.length; i < length; i++) {
- value = obj[i];
- if (value < result) {
- result = value;
- }
- }
- } else {
- iteratee = cb(iteratee, context);
- _.each(obj, function(value, index, list) {
- computed = iteratee(value, index, list);
- if (computed < lastComputed || computed === Infinity && result === Infinity) {
- result = value;
- lastComputed = computed;
- }
- });
- }
- return result;
- };
- // Shuffle a collection, using the modern version of the
- // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
- _.shuffle = function(obj) {
- var set = isArrayLike(obj) ? obj : _.values(obj);
- var length = set.length;
- var shuffled = Array(length);
- for (var index = 0, rand; index < length; index++) {
- rand = _.random(0, index);
- if (rand !== index) shuffled[index] = shuffled[rand];
- shuffled[rand] = set[index];
- }
- return shuffled;
- };
- // Sample **n** random values from a collection.
- // If **n** is not specified, returns a single random element.
- // The internal `guard` argument allows it to work with `map`.
- _.sample = function(obj, n, guard) {
- if (n == null || guard) {
- if (!isArrayLike(obj)) obj = _.values(obj);
- return obj[_.random(obj.length - 1)];
- }
- return _.shuffle(obj).slice(0, Math.max(0, n));
- };
- // Sort the object's values by a criterion produced by an iteratee.
- _.sortBy = function(obj, iteratee, context) {
- iteratee = cb(iteratee, context);
- return _.pluck(_.map(obj, function(value, index, list) {
- return {
- value: value,
- index: index,
- criteria: iteratee(value, index, list)
- };
- }).sort(function(left, right) {
- var a = left.criteria;
- var b = right.criteria;
- if (a !== b) {
- if (a > b || a === void 0) return 1;
- if (a < b || b === void 0) return -1;
- }
- return left.index - right.index;
- }), 'value');
- };
- // An internal function used for aggregate "group by" operations.
- var group = function(behavior) {
- return function(obj, iteratee, context) {
- var result = {};
- iteratee = cb(iteratee, context);
- _.each(obj, function(value, index) {
- var key = iteratee(value, index, obj);
- behavior(result, value, key);
- });
- return result;
- };
- };
- // Groups the object's values by a criterion. Pass either a string attribute
- // to group by, or a function that returns the criterion.
- _.groupBy = group(function(result, value, key) {
- if (_.has(result, key)) result[key].push(value); else result[key] = [value];
- });
- // Indexes the object's values by a criterion, similar to `groupBy`, but for
- // when you know that your index values will be unique.
- _.indexBy = group(function(result, value, key) {
- result[key] = value;
- });
- // Counts instances of an object that group by a certain criterion. Pass
- // either a string attribute to count by, or a function that returns the
- // criterion.
- _.countBy = group(function(result, value, key) {
- if (_.has(result, key)) result[key]++; else result[key] = 1;
- });
- // Safely create a real, live array from anything iterable.
- _.toArray = function(obj) {
- if (!obj) return [];
- if (_.isArray(obj)) return slice.call(obj);
- if (isArrayLike(obj)) return _.map(obj, _.identity);
- return _.values(obj);
- };
- // Return the number of elements in an object.
- _.size = function(obj) {
- if (obj == null) return 0;
- return isArrayLike(obj) ? obj.length : _.keys(obj).length;
- };
- // Split a collection into two arrays: one whose elements all satisfy the given
- // predicate, and one whose elements all do not satisfy the predicate.
- _.partition = function(obj, predicate, context) {
- predicate = cb(predicate, context);
- var pass = [], fail = [];
- _.each(obj, function(value, key, obj) {
- (predicate(value, key, obj) ? pass : fail).push(value);
- });
- return [pass, fail];
- };
- // Array Functions
- // ---------------
- // Get the first element of an array. Passing **n** will return the first N
- // values in the array. Aliased as `head` and `take`. The **guard** check
- // allows it to work with `_.map`.
- _.first = _.head = _.take = function(array, n, guard) {
- if (array == null) return void 0;
- if (n == null || guard) return array[0];
- return _.initial(array, array.length - n);
- };
- // Returns everything but the last entry of the array. Especially useful on
- // the arguments object. Passing **n** will return all the values in
- // the array, excluding the last N.
- _.initial = function(array, n, guard) {
- return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
- };
- // Get the last element of an array. Passing **n** will return the last N
- // values in the array.
- _.last = function(array, n, guard) {
- if (array == null) return void 0;
- if (n == null || guard) return array[array.length - 1];
- return _.rest(array, Math.max(0, array.length - n));
- };
- // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
- // Especially useful on the arguments object. Passing an **n** will return
- // the rest N values in the array.
- _.rest = _.tail = _.drop = function(array, n, guard) {
- return slice.call(array, n == null || guard ? 1 : n);
- };
- // Trim out all falsy values from an array.
- _.compact = function(array) {
- return _.filter(array, _.identity);
- };
- // Internal implementation of a recursive `flatten` function.
- var flatten = function(input, shallow, strict, startIndex) {
- var output = [], idx = 0;
- for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
- var value = input[i];
- if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
- //flatten current level of array or arguments object
- if (!shallow) value = flatten(value, shallow, strict);
- var j = 0, len = value.length;
- output.length += len;
- while (j < len) {
- output[idx++] = value[j++];
- }
- } else if (!strict) {
- output[idx++] = value;
- }
- }
- return output;
- };
- // Flatten out an array, either recursively (by default), or just one level.
- _.flatten = function(array, shallow) {
- return flatten(array, shallow, false);
- };
- // Return a version of the array that does not contain the specified value(s).
- _.without = function(array) {
- return _.difference(array, slice.call(arguments, 1));
- };
- // Produce a duplicate-free version of the array. If the array has already
- // been sorted, you have the option of using a faster algorithm.
- // Aliased as `unique`.
- _.uniq = _.unique = function(array, isSorted, iteratee, context) {
- if (!_.isBoolean(isSorted)) {
- context = iteratee;
- iteratee = isSorted;
- isSorted = false;
- }
- if (iteratee != null) iteratee = cb(iteratee, context);
- var result = [];
- var seen = [];
- for (var i = 0, length = getLength(array); i < length; i++) {
- var value = array[i],
- computed = iteratee ? iteratee(value, i, array) : value;
- if (isSorted) {
- if (!i || seen !== computed) result.push(value);
- seen = computed;
- } else if (iteratee) {
- if (!_.contains(seen, computed)) {
- seen.push(computed);
- result.push(value);
- }
- } else if (!_.contains(result, value)) {
- result.push(value);
- }
- }
- return result;
- };
- // Produce an array that contains the union: each distinct element from all of
- // the passed-in arrays.
- _.union = function() {
- return _.uniq(flatten(arguments, true, true));
- };
- // Produce an array that contains every item shared between all the
- // passed-in arrays.
- _.intersection = function(array) {
- var result = [];
- var argsLength = arguments.length;
- for (var i = 0, length = getLength(array); i < length; i++) {
- var item = array[i];
- if (_.contains(result, item)) continue;
- for (var j = 1; j < argsLength; j++) {
- if (!_.contains(arguments[j], item)) break;
- }
- if (j === argsLength) result.push(item);
- }
- return result;
- };
- // Take the difference between one array and a number of other arrays.
- // Only the elements present in just the first array will remain.
- _.difference = function(array) {
- var rest = flatten(arguments, true, true, 1);
- return _.filter(array, function(value){
- return !_.contains(rest, value);
- });
- };
- // Zip together multiple lists into a single array -- elements that share
- // an index go together.
- _.zip = function() {
- return _.unzip(arguments);
- };
- // Complement of _.zip. Unzip accepts an array of arrays and groups
- // each array's elements on shared indices
- _.unzip = function(array) {
- var length = array && _.max(array, getLength).length || 0;
- var result = Array(length);
- for (var index = 0; index < length; index++) {
- result[index] = _.pluck(array, index);
- }
- return result;
- };
- // Converts lists into objects. Pass either a single array of `[key, value]`
- // pairs, or two parallel arrays of the same length -- one of keys, and one of
- // the corresponding values.
- _.object = function(list, values) {
- var result = {};
- for (var i = 0, length = getLength(list); i < length; i++) {
- if (values) {
- result[list[i]] = values[i];
- } else {
- result[list[i][0]] = list[i][1];
- }
- }
- return result;
- };
- // Generator function to create the findIndex and findLastIndex functions
- function createPredicateIndexFinder(dir) {
- return function(array, predicate, context) {
- predicate = cb(predicate, context);
- var length = getLength(array);
- var index = dir > 0 ? 0 : length - 1;
- for (; index >= 0 && index < length; index += dir) {
- if (predicate(array[index], index, array)) return index;
- }
- return -1;
- };
- }
- // Returns the first index on an array-like that passes a predicate test
- _.findIndex = createPredicateIndexFinder(1);
- _.findLastIndex = createPredicateIndexFinder(-1);
- // Use a comparator function to figure out the smallest index at which
- // an object should be inserted so as to maintain order. Uses binary search.
- _.sortedIndex = function(array, obj, iteratee, context) {
- iteratee = cb(iteratee, context, 1);
- var value = iteratee(obj);
- var low = 0, high = getLength(array);
- while (low < high) {
- var mid = Math.floor((low + high) / 2);
- if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
- }
- return low;
- };
- // Generator function to create the indexOf and lastIndexOf functions
- function createIndexFinder(dir, predicateFind, sortedIndex) {
- return function(array, item, idx) {
- var i = 0, length = getLength(array);
- if (typeof idx == 'number') {
- if (dir > 0) {
- i = idx >= 0 ? idx : Math.max(idx + length, i);
- } else {
- length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
- }
- } else if (sortedIndex && idx && length) {
- idx = sortedIndex(array, item);
- return array[idx] === item ? idx : -1;
- }
- if (item !== item) {
- idx = predicateFind(slice.call(array, i, length), _.isNaN);
- return idx >= 0 ? idx + i : -1;
- }
- for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
- if (array[idx] === item) return idx;
- }
- return -1;
- };
- }
- // Return the position of the first occurrence of an item in an array,
- // or -1 if the item is not included in the array.
- // If the array is large and already in sort order, pass `true`
- // for **isSorted** to use binary search.
- _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
- _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
- // Generate an integer Array containing an arithmetic progression. A port of
- // the native Python `range()` function. See
- // [the Python documentation](http://docs.python.org/library/functions.html#range).
- _.range = function(start, stop, step) {
- if (stop == null) {
- stop = start || 0;
- start = 0;
- }
- step = step || 1;
- var length = Math.max(Math.ceil((stop - start) / step), 0);
- var range = Array(length);
- for (var idx = 0; idx < length; idx++, start += step) {
- range[idx] = start;
- }
- return range;
- };
- // Function (ahem) Functions
- // ------------------
- // Determines whether to execute a function as a constructor
- // or a normal function with the provided arguments
- var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
- if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
- var self = baseCreate(sourceFunc.prototype);
- var result = sourceFunc.apply(self, args);
- if (_.isObject(result)) return result;
- return self;
- };
- // Create a function bound to a given object (assigning `this`, and arguments,
- // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
- // available.
- _.bind = function(func, context) {
- if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
- if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
- var args = slice.call(arguments, 2);
- var bound = function() {
- return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
- };
- return bound;
- };
- // Partially apply a function by creating a version that has had some of its
- // arguments pre-filled, without changing its dynamic `this` context. _ acts
- // as a placeholder, allowing any combination of arguments to be pre-filled.
- _.partial = function(func) {
- var boundArgs = slice.call(arguments, 1);
- var bound = function() {
- var position = 0, length = boundArgs.length;
- var args = Array(length);
- for (var i = 0; i < length; i++) {
- args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
- }
- while (position < arguments.length) args.push(arguments[position++]);
- return executeBound(func, bound, this, this, args);
- };
- return bound;
- };
- // Bind a number of an object's methods to that object. Remaining arguments
- // are the method names to be bound. Useful for ensuring that all callbacks
- // defined on an object belong to it.
- _.bindAll = function(obj) {
- var i, length = arguments.length, key;
- if (length <= 1) throw new Error('bindAll must be passed function names');
- for (i = 1; i < length; i++) {
- key = arguments[i];
- obj[key] = _.bind(obj[key], obj);
- }
- return obj;
- };
- // Memoize an expensive function by storing its results.
- _.memoize = function(func, hasher) {
- var memoize = function(key) {
- var cache = memoize.cache;
- var address = '' + (hasher ? hasher.apply(this, arguments) : key);
- if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
- return cache[address];
- };
- memoize.cache = {};
- return memoize;
- };
- // Delays a function for the given number of milliseconds, and then calls
- // it with the arguments supplied.
- _.delay = function(func, wait) {
- var args = slice.call(arguments, 2);
- return setTimeout(function(){
- return func.apply(null, args);
- }, wait);
- };
- // Defers a function, scheduling it to run after the current call stack has
- // cleared.
- _.defer = _.partial(_.delay, _, 1);
- // Returns a function, that, when invoked, will only be triggered at most once
- // during a given window of time. Normally, the throttled function will run
- // as much as it can, without ever going more than once per `wait` duration;
- // but if you'd like to disable the execution on the leading edge, pass
- // `{leading: false}`. To disable execution on the trailing edge, ditto.
- _.throttle = function(func, wait, options) {
- var context, args, result;
- var timeout = null;
- var previous = 0;
- if (!options) options = {};
- var later = function() {
- previous = options.leading === false ? 0 : _.now();
- timeout = null;
- result = func.apply(context, args);
- if (!timeout) context = args = null;
- };
- return function() {
- var now = _.now();
- if (!previous && options.leading === false) previous = now;
- var remaining = wait - (now - previous);
- context = this;
- args = arguments;
- if (remaining <= 0 || remaining > wait) {
- if (timeout) {
- clearTimeout(timeout);
- timeout = null;
- }
- previous = now;
- result = func.apply(context, args);
- if (!timeout) context = args = null;
- } else if (!timeout && options.trailing !== false) {
- timeout = setTimeout(later, remaining);
- }
- return result;
- };
- };
- // Returns a function, that, as long as it continues to be invoked, will not
- // be triggered. The function will be called after it stops being called for
- // N milliseconds. If `immediate` is passed, trigger the function on the
- // leading edge, instead of the trailing.
- _.debounce = function(func, wait, immediate) {
- var timeout, args, context, timestamp, result;
- var later = function() {
- var last = _.now() - timestamp;
- if (last < wait && last >= 0) {
- timeout = setTimeout(later, wait - last);
- } else {
- timeout = null;
- if (!immediate) {
- result = func.apply(context, args);
- if (!timeout) context = args = null;
- }
- }
- };
- return function() {
- context = this;
- args = arguments;
- timestamp = _.now();
- var callNow = immediate && !timeout;
- if (!timeout) timeout = setTimeout(later, wait);
- if (callNow) {
- result = func.apply(context, args);
- context = args = null;
- }
- return result;
- };
- };
- // Returns the first function passed as an argument to the second,
- // allowing you to adjust arguments, run code before and after, and
- // conditionally execute the original function.
- _.wrap = function(func, wrapper) {
- return _.partial(wrapper, func);
- };
- // Returns a negated version of the passed-in predicate.
- _.negate = function(predicate) {
- return function() {
- return !predicate.apply(this, arguments);
- };
- };
- // Returns a function that is the composition of a list of functions, each
- // consuming the return value of the function that follows.
- _.compose = function() {
- var args = arguments;
- var start = args.length - 1;
- return function() {
- var i = start;
- var result = args[start].apply(this, arguments);
- while (i--) result = args[i].call(this, result);
- return result;
- };
- };
- // Returns a function that will only be executed on and after the Nth call.
- _.after = function(times, func) {
- return function() {
- if (--times < 1) {
- return func.apply(this, arguments);
- }
- };
- };
- // Returns a function that will only be executed up to (but not including) the Nth call.
- _.before = function(times, func) {
- var memo;
- return function() {
- if (--times > 0) {
- memo = func.apply(this, arguments);
- }
- if (times <= 1) func = null;
- return memo;
- };
- };
- // Returns a function that will be executed at most one time, no matter how
- // often you call it. Useful for lazy initialization.
- _.once = _.partial(_.before, 2);
- // Object Functions
- // ----------------
- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
- var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
- var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
- 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
- function collectNonEnumProps(obj, keys) {
- var nonEnumIdx = nonEnumerableProps.length;
- var constructor = obj.constructor;
- var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
- // Constructor is a special case.
- var prop = 'constructor';
- if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
- while (nonEnumIdx--) {
- prop = nonEnumerableProps[nonEnumIdx];
- if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
- keys.push(prop);
- }
- }
- }
- // Retrieve the names of an object's own properties.
- // Delegates to **ECMAScript 5**'s native `Object.keys`
- _.keys = function(obj) {
- if (!_.isObject(obj)) return [];
- if (nativeKeys) return nativeKeys(obj);
- var keys = [];
- for (var key in obj) if (_.has(obj, key)) keys.push(key);
- // Ahem, IE < 9.
- if (hasEnumBug) collectNonEnumProps(obj, keys);
- return keys;
- };
- // Retrieve all the property names of an object.
- _.allKeys = function(obj) {
- if (!_.isObject(obj)) return [];
- var keys = [];
- for (var key in obj) keys.push(key);
- // Ahem, IE < 9.
- if (hasEnumBug) collectNonEnumProps(obj, keys);
- return keys;
- };
- // Retrieve the values of an object's properties.
- _.values = function(obj) {
- var keys = _.keys(obj);
- var length = keys.length;
- var values = Array(length);
- for (var i = 0; i < length; i++) {
- values[i] = obj[keys[i]];
- }
- return values;
- };
- // Returns the results of applying the iteratee to each element of the object
- // In contrast to _.map it returns an object
- _.mapObject = function(obj, iteratee, context) {
- iteratee = cb(iteratee, context);
- var keys = _.keys(obj),
- length = keys.length,
- results = {},
- currentKey;
- for (var index = 0; index < length; index++) {
- currentKey = keys[index];
- results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
- }
- return results;
- };
- // Convert an object into a list of `[key, value]` pairs.
- _.pairs = function(obj) {
- var keys = _.keys(obj);
- var length = keys.length;
- var pairs = Array(length);
- for (var i = 0; i < length; i++) {
- pairs[i] = [keys[i], obj[keys[i]]];
- }
- return pairs;
- };
- // Invert the keys and values of an object. The values must be serializable.
- _.invert = function(obj) {
- var result = {};
- var keys = _.keys(obj);
- for (var i = 0, length = keys.length; i < length; i++) {
- result[obj[keys[i]]] = keys[i];
- }
- return result;
- };
- // Return a sorted list of the function names available on the object.
- // Aliased as `methods`
- _.functions = _.methods = function(obj) {
- var names = [];
- for (var key in obj) {
- if (_.isFunction(obj[key])) names.push(key);
- }
- return names.sort();
- };
- // Extend a given object with all the properties in passed-in object(s).
- _.extend = createAssigner(_.allKeys);
- // Assigns a given object with all the own properties in the passed-in object(s)
- // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
- _.extendOwn = _.assign = createAssigner(_.keys);
- // Returns the first key on an object that passes a predicate test
- _.findKey = function(obj, predicate, context) {
- predicate = cb(predicate, context);
- var keys = _.keys(obj), key;
- for (var i = 0, length = keys.length; i < length; i++) {
- key = keys[i];
- if (predicate(obj[key], key, obj)) return key;
- }
- };
- // Return a copy of the object only containing the whitelisted properties.
- _.pick = function(object, oiteratee, context) {
- var result = {}, obj = object, iteratee, keys;
- if (obj == null) return result;
- if (_.isFunction(oiteratee)) {
- keys = _.allKeys(obj);
- iteratee = optimizeCb(oiteratee, context);
- } else {
- keys = flatten(arguments, false, false, 1);
- iteratee = function(value, key, obj) { return key in obj; };
- obj = Object(obj);
- }
- for (var i = 0, length = keys.length; i < length; i++) {
- var key = keys[i];
- var value = obj[key];
- if (iteratee(value, key, obj)) result[key] = value;
- }
- return result;
- };
- // Return a copy of the object without the blacklisted properties.
- _.omit = function(obj, iteratee, context) {
- if (_.isFunction(iteratee)) {
- iteratee = _.negate(iteratee);
- } else {
- var keys = _.map(flatten(arguments, false, false, 1), String);
- iteratee = function(value, key) {
- return !_.contains(keys, key);
- };
- }
- return _.pick(obj, iteratee, context);
- };
- // Fill in a given object with default properties.
- _.defaults = createAssigner(_.allKeys, true);
- // Creates an object that inherits from the given prototype object.
- // If additional properties are provided then they will be added to the
- // created object.
- _.create = function(prototype, props) {
- var result = baseCreate(prototype);
- if (props) _.extendOwn(result, props);
- return result;
- };
- // Create a (shallow-cloned) duplicate of an object.
- _.clone = function(obj) {
- if (!_.isObject(obj)) return obj;
- return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
- };
- // Invokes interceptor with the obj, and then returns obj.
- // The primary purpose of this method is to "tap into" a method chain, in
- // order to perform operations on intermediate results within the chain.
- _.tap = function(obj, interceptor) {
- interceptor(obj);
- return obj;
- };
- // Returns whether an object has a given set of `key:value` pairs.
- _.isMatch = function(object, attrs) {
- var keys = _.keys(attrs), length = keys.length;
- if (object == null) return !length;
- var obj = Object(object);
- for (var i = 0; i < length; i++) {
- var key = keys[i];
- if (attrs[key] !== obj[key] || !(key in obj)) return false;
- }
- return true;
- };
- // Internal recursive comparison function for `isEqual`.
- var eq = function(a, b, aStack, bStack) {
- // Identical objects are equal. `0 === -0`, but they aren't identical.
- // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
- if (a === b) return a !== 0 || 1 / a === 1 / b;
- // A strict comparison is necessary because `null == undefined`.
- if (a == null || b == null) return a === b;
- // Unwrap any wrapped objects.
- if (a instanceof _) a = a._wrapped;
- if (b instanceof _) b = b._wrapped;
- // Compare `[[Class]]` names.
- var className = toString.call(a);
- if (className !== toString.call(b)) return false;
- switch (className) {
- // Strings, numbers, regular expressions, dates, and booleans are compared by value.
- case '[object RegExp]':
- // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
- case '[object String]':
- // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
- // equivalent to `new String("5")`.
- return '' + a === '' + b;
- case '[object Number]':
- // `NaN`s are equivalent, but non-reflexive.
- // Object(NaN) is equivalent to NaN
- if (+a !== +a) return +b !== +b;
- // An `egal` comparison is performed for other numeric values.
- return +a === 0 ? 1 / +a === 1 / b : +a === +b;
- case '[object Date]':
- case '[object Boolean]':
- // Coerce dates and booleans to numeric primitive values. Dates are compared by their
- // millisecond representations. Note that invalid dates with millisecond representations
- // of `NaN` are not equivalent.
- return +a === +b;
- }
- var areArrays = className === '[object Array]';
- if (!areArrays) {
- if (typeof a != 'object' || typeof b != 'object') return false;
- // Objects with different constructors are not equivalent, but `Object`s or `Array`s
- // from different frames are.
- var aCtor = a.constructor, bCtor = b.constructor;
- if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
- _.isFunction(bCtor) && bCtor instanceof bCtor)
- && ('constructor' in a && 'constructor' in b)) {
- return false;
- }
- }
- // Assume equality for cyclic structures. The algorithm for detecting cyclic
- // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
- // Initializing stack of traversed objects.
- // It's done here since we only need them for objects and arrays comparison.
- aStack = aStack || [];
- bStack = bStack || [];
- var length = aStack.length;
- while (length--) {
- // Linear search. Performance is inversely proportional to the number of
- // unique nested structures.
- if (aStack[length] === a) return bStack[length] === b;
- }
- // Add the first object to the stack of traversed objects.
- aStack.push(a);
- bStack.push(b);
- // Recursively compare objects and arrays.
- if (areArrays) {
- // Compare array lengths to determine if a deep comparison is necessary.
- length = a.length;
- if (length !== b.length) return false;
- // Deep compare the contents, ignoring non-numeric properties.
- while (length--) {
- if (!eq(a[length], b[length], aStack, bStack)) return false;
- }
- } else {
- // Deep compare objects.
- var keys = _.keys(a), key;
- length = keys.length;
- // Ensure that both objects contain the same number of properties before comparing deep equality.
- if (_.keys(b).length !== length) return false;
- while (length--) {
- // Deep compare each member
- key = keys[length];
- if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
- }
- }
- // Remove the first object from the stack of traversed objects.
- aStack.pop();
- bStack.pop();
- return true;
- };
- // Perform a deep comparison to check if two objects are equal.
- _.isEqual = function(a, b) {
- return eq(a, b);
- };
- // Is a given array, string, or object empty?
- // An "empty" object has no enumerable own-properties.
- _.isEmpty = function(obj) {
- if (obj == null) return true;
- if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
- return _.keys(obj).length === 0;
- };
- // Is a given value a DOM element?
- _.isElement = function(obj) {
- return !!(obj && obj.nodeType === 1);
- };
- // Is a given value an array?
- // Delegates to ECMA5's native Array.isArray
- _.isArray = nativeIsArray || function(obj) {
- return toString.call(obj) === '[object Array]';
- };
- // Is a given variable an object?
- _.isObject = function(obj) {
- var type = typeof obj;
- return type === 'function' || type === 'object' && !!obj;
- };
- // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
- _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
- _['is' + name] = function(obj) {
- return toString.call(obj) === '[object ' + name + ']';
- };
- });
- // Define a fallback version of the method in browsers (ahem, IE < 9), where
- // there isn't any inspectable "Arguments" type.
- if (!_.isArguments(arguments)) {
- _.isArguments = function(obj) {
- return _.has(obj, 'callee');
- };
- }
- // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
- // IE 11 (#1621), and in Safari 8 (#1929).
- if (typeof /./ != 'function' && typeof Int8Array != 'object') {
- _.isFunction = function(obj) {
- return typeof obj == 'function' || false;
- };
- }
- // Is a given object a finite number?
- _.isFinite = function(obj) {
- return isFinite(obj) && !isNaN(parseFloat(obj));
- };
- // Is the given value `NaN`? (NaN is the only number which does not equal itself).
- _.isNaN = function(obj) {
- return _.isNumber(obj) && obj !== +obj;
- };
- // Is a given value a boolean?
- _.isBoolean = function(obj) {
- return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
- };
- // Is a given value equal to null?
- _.isNull = function(obj) {
- return obj === null;
- };
- // Is a given variable undefined?
- _.isUndefined = function(obj) {
- return obj === void 0;
- };
- // Shortcut function for checking if an object has a given property directly
- // on itself (in other words, not on a prototype).
- _.has = function(obj, key) {
- return obj != null && hasOwnProperty.call(obj, key);
- };
- // Utility Functions
- // -----------------
- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
- // previous owner. Returns a reference to the Underscore object.
- _.noConflict = function() {
- root._ = previousUnderscore;
- return this;
- };
- // Keep the identity function around for default iteratees.
- _.identity = function(value) {
- return value;
- };
- // Predicate-generating functions. Often useful outside of Underscore.
- _.constant = function(value) {
- return function() {
- return value;
- };
- };
- _.noop = function(){};
- _.property = property;
- // Generates a function for a given object that returns a given property.
- _.propertyOf = function(obj) {
- return obj == null ? function(){} : function(key) {
- return obj[key];
- };
- };
- // Returns a predicate for checking whether an object has a given set of
- // `key:value` pairs.
- _.matcher = _.matches = function(attrs) {
- attrs = _.extendOwn({}, attrs);
- return function(obj) {
- return _.isMatch(obj, attrs);
- };
- };
- // Run a function **n** times.
- _.times = function(n, iteratee, context) {
- var accum = Array(Math.max(0, n));
- iteratee = optimizeCb(iteratee, context, 1);
- for (var i = 0; i < n; i++) accum[i] = iteratee(i);
- return accum;
- };
- // Return a random integer between min and max (inclusive).
- _.random = function(min, max) {
- if (max == null) {
- max = min;
- min = 0;
- }
- return min + Math.floor(Math.random() * (max - min + 1));
- };
- // A (possibly faster) way to get the current timestamp as an integer.
- _.now = Date.now || function() {
- return new Date().getTime();
- };
- // List of HTML entities for escaping.
- var escapeMap = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": ''',
- '`': '`'
- };
- var unescapeMap = _.invert(escapeMap);
- // Functions for escaping and unescaping strings to/from HTML interpolation.
- var createEscaper = function(map) {
- var escaper = function(match) {
- return map[match];
- };
- // Regexes for identifying a key that needs to be escaped
- var source = '(?:' + _.keys(map).join('|') + ')';
- var testRegexp = RegExp(source);
- var replaceRegexp = RegExp(source, 'g');
- return function(string) {
- string = string == null ? '' : '' + string;
- return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
- };
- };
- _.escape = createEscaper(escapeMap);
- _.unescape = createEscaper(unescapeMap);
- // If the value of the named `property` is a function then invoke it with the
- // `object` as context; otherwise, return it.
- _.result = function(object, property, fallback) {
- var value = object == null ? void 0 : object[property];
- if (value === void 0) {
- value = fallback;
- }
- return _.isFunction(value) ? value.call(object) : value;
- };
- // Generate a unique integer id (unique within the entire client session).
- // Useful for temporary DOM ids.
- var idCounter = 0;
- _.uniqueId = function(prefix) {
- var id = ++idCounter + '';
- return prefix ? prefix + id : id;
- };
- // By default, Underscore uses ERB-style template delimiters, change the
- // following template settings to use alternative delimiters.
- _.templateSettings = {
- evaluate : /<%([\s\S]+?)%>/g,
- interpolate : /<%=([\s\S]+?)%>/g,
- escape : /<%-([\s\S]+?)%>/g
- };
- // When customizing `templateSettings`, if you don't want to define an
- // interpolation, evaluation or escaping regex, we need one that is
- // guaranteed not to match.
- var noMatch = /(.)^/;
- // Certain characters need to be escaped so that they can be put into a
- // string literal.
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
- var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
- var escapeChar = function(match) {
- return '\\' + escapes[match];
- };
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- // NB: `oldSettings` only exists for backwards compatibility.
- _.template = function(text, settings, oldSettings) {
- if (!settings && oldSettings) settings = oldSettings;
- settings = _.defaults({}, settings, _.templateSettings);
- // Combine delimiters into one regular expression via alternation.
- var matcher = RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
- // Compile the template source, escaping string literals appropriately.
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset).replace(escaper, escapeChar);
- index = offset + match.length;
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- } else if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- } else if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
- // Adobe VMs need the match returned to produce the correct offest.
- return match;
- });
- source += "';\n";
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + 'return __p;\n';
- try {
- var render = new Function(settings.variable || 'obj', '_', source);
- } catch (e) {
- e.source = source;
- throw e;
- }
- var template = function(data) {
- return render.call(this, data, _);
- };
- // Provide the compiled source as a convenience for precompilation.
- var argument = settings.variable || 'obj';
- template.source = 'function(' + argument + '){\n' + source + '}';
- return template;
- };
- // Add a "chain" function. Start chaining a wrapped Underscore object.
- _.chain = function(obj) {
- var instance = _(obj);
- instance._chain = true;
- return instance;
- };
- // OOP
- // ---------------
- // If Underscore is called as a function, it returns a wrapped object that
- // can be used OO-style. This wrapper holds altered versions of all the
- // underscore functions. Wrapped objects may be chained.
- // Helper function to continue chaining intermediate results.
- var result = function(instance, obj) {
- return instance._chain ? _(obj).chain() : obj;
- };
- // Add your own custom functions to the Underscore object.
- _.mixin = function(obj) {
- _.each(_.functions(obj), function(name) {
- var func = _[name] = obj[name];
- _.prototype[name] = function() {
- var args = [this._wrapped];
- push.apply(args, arguments);
- return result(this, func.apply(_, args));
- };
- });
- };
- // Add all of the Underscore functions to the wrapper object.
- _.mixin(_);
- // Add all mutator Array functions to the wrapper.
- _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- var obj = this._wrapped;
- method.apply(obj, arguments);
- if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
- return result(this, obj);
- };
- });
- // Add all accessor Array functions to the wrapper.
- _.each(['concat', 'join', 'slice'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- return result(this, method.apply(this._wrapped, arguments));
- };
- });
- // Extracts the result from a wrapped and chained object.
- _.prototype.value = function() {
- return this._wrapped;
- };
- // Provide unwrapping proxy for some methods used in engine operations
- // such as arithmetic and JSON stringification.
- _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
- _.prototype.toString = function() {
- return '' + this._wrapped;
- };
- // AMD registration happens at the end for compatibility with AMD loaders
- // that may not enforce next-turn semantics on modules. Even though general
- // practice for AMD registration is to be anonymous, underscore registers
- // as a named module because, like jQuery, it is a base library that is
- // popular enough to be bundled in a third party lib, but not be part of
- // an AMD load request. Those cases could generate an error when an
- // anonymous define() is called outside of a loader request.
- if (typeof define === 'function' && define.amd) {
- define('underscore', [], function() {
- return _;
- });
- }
- }.call(this));
- },{}],154:[function(require,module,exports){
- (function (global){
- /**
- * Module exports.
- */
- module.exports = deprecate;
- /**
- * Mark that a method should not be used.
- * Returns a modified function which warns once by default.
- *
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
- *
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
- * will throw an Error when invoked.
- *
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
- * will invoke `console.trace()` instead of `console.error()`.
- *
- * @param {Function} fn - the function to deprecate
- * @param {String} msg - the string to print to the console when `fn` is invoked
- * @returns {Function} a new "deprecated" version of `fn`
- * @api public
- */
- function deprecate (fn, msg) {
- if (config('noDeprecation')) {
- return fn;
- }
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (config('throwDeprecation')) {
- throw new Error(msg);
- } else if (config('traceDeprecation')) {
- console.trace(msg);
- } else {
- console.warn(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
- return deprecated;
- }
- /**
- * Checks `localStorage` for boolean values for the given `name`.
- *
- * @param {String} name
- * @returns {Boolean}
- * @api private
- */
- function config (name) {
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
- try {
- if (!global.localStorage) return false;
- } catch (_) {
- return false;
- }
- var val = global.localStorage[name];
- if (null == val) return false;
- return String(val).toLowerCase() === 'true';
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],155:[function(require,module,exports){
- arguments[4][81][0].apply(exports,arguments)
- },{"dup":81}],156:[function(require,module,exports){
- module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
- }
- },{}],157:[function(require,module,exports){
- (function (process,global){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var formatRegExp = /%[sdj%]/g;
- exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
- };
- // Mark that a method should not be used.
- // Returns a modified function which warns once by default.
- // If --no-deprecation is set, then it is a no-op.
- exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
- if (process.noDeprecation === true) {
- return fn;
- }
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
- return deprecated;
- };
- var debugs = {};
- var debugEnviron;
- exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
- };
- /**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
- /* legacy: obj, showHidden, depth, colors*/
- function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
- }
- exports.inspect = inspect;
- // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
- inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
- };
- // Don't use 'blue' not visible on cmd.exe
- inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
- };
- function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
- }
- function stylizeNoColor(str, styleType) {
- return str;
- }
- function arrayToHash(array) {
- var hash = {};
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
- return hash;
- }
- function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
- var base = '', array = false, braces = ['{', '}'];
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
- ctx.seen.push(value);
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
- ctx.seen.pop();
- return reduceToSingleString(output, base, braces);
- }
- function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
- }
- function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
- }
- function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
- }
- function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
- return name + ': ' + str;
- }
- function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
- }
- // NOTE: These type checking functions intentionally don't use `instanceof`
- // because it is fragile and can be easily faked with `Object.create()`.
- function isArray(ar) {
- return Array.isArray(ar);
- }
- exports.isArray = isArray;
- function isBoolean(arg) {
- return typeof arg === 'boolean';
- }
- exports.isBoolean = isBoolean;
- function isNull(arg) {
- return arg === null;
- }
- exports.isNull = isNull;
- function isNullOrUndefined(arg) {
- return arg == null;
- }
- exports.isNullOrUndefined = isNullOrUndefined;
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- exports.isNumber = isNumber;
- function isString(arg) {
- return typeof arg === 'string';
- }
- exports.isString = isString;
- function isSymbol(arg) {
- return typeof arg === 'symbol';
- }
- exports.isSymbol = isSymbol;
- function isUndefined(arg) {
- return arg === void 0;
- }
- exports.isUndefined = isUndefined;
- function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
- }
- exports.isRegExp = isRegExp;
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- exports.isObject = isObject;
- function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
- }
- exports.isDate = isDate;
- function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
- }
- exports.isError = isError;
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- exports.isFunction = isFunction;
- function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
- }
- exports.isPrimitive = isPrimitive;
- exports.isBuffer = require('./support/isBuffer');
- function objectToString(o) {
- return Object.prototype.toString.call(o);
- }
- function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
- }
- var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
- // 26 Feb 16:19:34
- function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
- }
- // log is just a thin wrapper to console.log that prepends a timestamp
- exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
- };
- /**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
- exports.inherits = require('inherits');
- exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
- };
- function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
- }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"./support/isBuffer":156,"_process":138,"inherits":155}],158:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject,
- slice = [].slice,
- hasProp = {}.hasOwnProperty;
- assign = function() {
- var i, key, len, source, sources, target;
- target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
- if (isFunction(Object.assign)) {
- Object.assign.apply(null, arguments);
- } else {
- for (i = 0, len = sources.length; i < len; i++) {
- source = sources[i];
- if (source != null) {
- for (key in source) {
- if (!hasProp.call(source, key)) continue;
- target[key] = source[key];
- }
- }
- }
- }
- return target;
- };
- isFunction = function(val) {
- return !!val && Object.prototype.toString.call(val) === '[object Function]';
- };
- isObject = function(val) {
- var ref;
- return !!val && ((ref = typeof val) === 'function' || ref === 'object');
- };
- isArray = function(val) {
- if (isFunction(Array.isArray)) {
- return Array.isArray(val);
- } else {
- return Object.prototype.toString.call(val) === '[object Array]';
- }
- };
- isEmpty = function(val) {
- var key;
- if (isArray(val)) {
- return !val.length;
- } else {
- for (key in val) {
- if (!hasProp.call(val, key)) continue;
- return false;
- }
- return true;
- }
- };
- isPlainObject = function(val) {
- var ctor, proto;
- 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));
- };
- getValue = function(obj) {
- if (isFunction(obj.valueOf)) {
- return obj.valueOf();
- } else {
- return obj;
- }
- };
- module.exports.assign = assign;
- module.exports.isFunction = isFunction;
- module.exports.isObject = isObject;
- module.exports.isArray = isArray;
- module.exports.isEmpty = isEmpty;
- module.exports.isPlainObject = isPlainObject;
- module.exports.getValue = getValue;
- }).call(this);
- },{}],159:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLAttribute;
- module.exports = XMLAttribute = (function() {
- function XMLAttribute(parent, name, value) {
- this.options = parent.options;
- this.stringify = parent.stringify;
- this.parent = parent;
- if (name == null) {
- throw new Error("Missing attribute name. " + this.debugInfo(name));
- }
- if (value == null) {
- throw new Error("Missing attribute value. " + this.debugInfo(name));
- }
- this.name = this.stringify.attName(name);
- this.value = this.stringify.attValue(value);
- }
- XMLAttribute.prototype.clone = function() {
- return Object.create(this);
- };
- XMLAttribute.prototype.toString = function(options) {
- return this.options.writer.set(options).attribute(this);
- };
- XMLAttribute.prototype.debugInfo = function(name) {
- var ref, ref1;
- name = name || this.name;
- if ((name == null) && !((ref = this.parent) != null ? ref.name : void 0)) {
- return "";
- } else if (name == null) {
- return "parent: <" + this.parent.name + ">";
- } else if (!((ref1 = this.parent) != null ? ref1.name : void 0)) {
- return "attribute: {" + name + "}";
- } else {
- return "attribute: {" + name + "}, parent: <" + this.parent.name + ">";
- }
- };
- return XMLAttribute;
- })();
- }).call(this);
- },{}],160:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLCData, XMLNode,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLCData = (function(superClass) {
- extend(XMLCData, superClass);
- function XMLCData(parent, text) {
- XMLCData.__super__.constructor.call(this, parent);
- if (text == null) {
- throw new Error("Missing CDATA text. " + this.debugInfo());
- }
- this.text = this.stringify.cdata(text);
- }
- XMLCData.prototype.clone = function() {
- return Object.create(this);
- };
- XMLCData.prototype.toString = function(options) {
- return this.options.writer.set(options).cdata(this);
- };
- return XMLCData;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],161:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLComment, XMLNode,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLComment = (function(superClass) {
- extend(XMLComment, superClass);
- function XMLComment(parent, text) {
- XMLComment.__super__.constructor.call(this, parent);
- if (text == null) {
- throw new Error("Missing comment text. " + this.debugInfo());
- }
- this.text = this.stringify.comment(text);
- }
- XMLComment.prototype.clone = function() {
- return Object.create(this);
- };
- XMLComment.prototype.toString = function(options) {
- return this.options.writer.set(options).comment(this);
- };
- return XMLComment;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],162:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDTDAttList, XMLNode,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLDTDAttList = (function(superClass) {
- extend(XMLDTDAttList, superClass);
- function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
- XMLDTDAttList.__super__.constructor.call(this, parent);
- if (elementName == null) {
- throw new Error("Missing DTD element name. " + this.debugInfo());
- }
- if (attributeName == null) {
- throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName));
- }
- if (!attributeType) {
- throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName));
- }
- if (!defaultValueType) {
- throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName));
- }
- if (defaultValueType.indexOf('#') !== 0) {
- defaultValueType = '#' + defaultValueType;
- }
- if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
- throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName));
- }
- if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
- throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName));
- }
- this.elementName = this.stringify.eleName(elementName);
- this.attributeName = this.stringify.attName(attributeName);
- this.attributeType = this.stringify.dtdAttType(attributeType);
- this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
- this.defaultValueType = defaultValueType;
- }
- XMLDTDAttList.prototype.toString = function(options) {
- return this.options.writer.set(options).dtdAttList(this);
- };
- return XMLDTDAttList;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],163:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDTDElement, XMLNode,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLDTDElement = (function(superClass) {
- extend(XMLDTDElement, superClass);
- function XMLDTDElement(parent, name, value) {
- XMLDTDElement.__super__.constructor.call(this, parent);
- if (name == null) {
- throw new Error("Missing DTD element name. " + this.debugInfo());
- }
- if (!value) {
- value = '(#PCDATA)';
- }
- if (Array.isArray(value)) {
- value = '(' + value.join(',') + ')';
- }
- this.name = this.stringify.eleName(name);
- this.value = this.stringify.dtdElementValue(value);
- }
- XMLDTDElement.prototype.toString = function(options) {
- return this.options.writer.set(options).dtdElement(this);
- };
- return XMLDTDElement;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],164:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDTDEntity, XMLNode, isObject,
- 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; },
- hasProp = {}.hasOwnProperty;
- isObject = require('./Utility').isObject;
- XMLNode = require('./XMLNode');
- module.exports = XMLDTDEntity = (function(superClass) {
- extend(XMLDTDEntity, superClass);
- function XMLDTDEntity(parent, pe, name, value) {
- XMLDTDEntity.__super__.constructor.call(this, parent);
- if (name == null) {
- throw new Error("Missing DTD entity name. " + this.debugInfo(name));
- }
- if (value == null) {
- throw new Error("Missing DTD entity value. " + this.debugInfo(name));
- }
- this.pe = !!pe;
- this.name = this.stringify.eleName(name);
- if (!isObject(value)) {
- this.value = this.stringify.dtdEntityValue(value);
- } else {
- if (!value.pubID && !value.sysID) {
- throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name));
- }
- if (value.pubID && !value.sysID) {
- throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name));
- }
- if (value.pubID != null) {
- this.pubID = this.stringify.dtdPubID(value.pubID);
- }
- if (value.sysID != null) {
- this.sysID = this.stringify.dtdSysID(value.sysID);
- }
- if (value.nData != null) {
- this.nData = this.stringify.dtdNData(value.nData);
- }
- if (this.pe && this.nData) {
- throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name));
- }
- }
- }
- XMLDTDEntity.prototype.toString = function(options) {
- return this.options.writer.set(options).dtdEntity(this);
- };
- return XMLDTDEntity;
- })(XMLNode);
- }).call(this);
- },{"./Utility":158,"./XMLNode":171}],165:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDTDNotation, XMLNode,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLDTDNotation = (function(superClass) {
- extend(XMLDTDNotation, superClass);
- function XMLDTDNotation(parent, name, value) {
- XMLDTDNotation.__super__.constructor.call(this, parent);
- if (name == null) {
- throw new Error("Missing DTD notation name. " + this.debugInfo(name));
- }
- if (!value.pubID && !value.sysID) {
- throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name));
- }
- this.name = this.stringify.eleName(name);
- if (value.pubID != null) {
- this.pubID = this.stringify.dtdPubID(value.pubID);
- }
- if (value.sysID != null) {
- this.sysID = this.stringify.dtdSysID(value.sysID);
- }
- }
- XMLDTDNotation.prototype.toString = function(options) {
- return this.options.writer.set(options).dtdNotation(this);
- };
- return XMLDTDNotation;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],166:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDeclaration, XMLNode, isObject,
- 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; },
- hasProp = {}.hasOwnProperty;
- isObject = require('./Utility').isObject;
- XMLNode = require('./XMLNode');
- module.exports = XMLDeclaration = (function(superClass) {
- extend(XMLDeclaration, superClass);
- function XMLDeclaration(parent, version, encoding, standalone) {
- var ref;
- XMLDeclaration.__super__.constructor.call(this, parent);
- if (isObject(version)) {
- ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
- }
- if (!version) {
- version = '1.0';
- }
- this.version = this.stringify.xmlVersion(version);
- if (encoding != null) {
- this.encoding = this.stringify.xmlEncoding(encoding);
- }
- if (standalone != null) {
- this.standalone = this.stringify.xmlStandalone(standalone);
- }
- }
- XMLDeclaration.prototype.toString = function(options) {
- return this.options.writer.set(options).declaration(this);
- };
- return XMLDeclaration;
- })(XMLNode);
- }).call(this);
- },{"./Utility":158,"./XMLNode":171}],167:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNode, isObject,
- 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; },
- hasProp = {}.hasOwnProperty;
- isObject = require('./Utility').isObject;
- XMLNode = require('./XMLNode');
- XMLDTDAttList = require('./XMLDTDAttList');
- XMLDTDEntity = require('./XMLDTDEntity');
- XMLDTDElement = require('./XMLDTDElement');
- XMLDTDNotation = require('./XMLDTDNotation');
- module.exports = XMLDocType = (function(superClass) {
- extend(XMLDocType, superClass);
- function XMLDocType(parent, pubID, sysID) {
- var ref, ref1;
- XMLDocType.__super__.constructor.call(this, parent);
- this.name = "!DOCTYPE";
- this.documentObject = parent;
- if (isObject(pubID)) {
- ref = pubID, pubID = ref.pubID, sysID = ref.sysID;
- }
- if (sysID == null) {
- ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1];
- }
- if (pubID != null) {
- this.pubID = this.stringify.dtdPubID(pubID);
- }
- if (sysID != null) {
- this.sysID = this.stringify.dtdSysID(sysID);
- }
- }
- XMLDocType.prototype.element = function(name, value) {
- var child;
- child = new XMLDTDElement(this, name, value);
- this.children.push(child);
- return this;
- };
- XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
- var child;
- child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
- this.children.push(child);
- return this;
- };
- XMLDocType.prototype.entity = function(name, value) {
- var child;
- child = new XMLDTDEntity(this, false, name, value);
- this.children.push(child);
- return this;
- };
- XMLDocType.prototype.pEntity = function(name, value) {
- var child;
- child = new XMLDTDEntity(this, true, name, value);
- this.children.push(child);
- return this;
- };
- XMLDocType.prototype.notation = function(name, value) {
- var child;
- child = new XMLDTDNotation(this, name, value);
- this.children.push(child);
- return this;
- };
- XMLDocType.prototype.toString = function(options) {
- return this.options.writer.set(options).docType(this);
- };
- XMLDocType.prototype.ele = function(name, value) {
- return this.element(name, value);
- };
- XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
- return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
- };
- XMLDocType.prototype.ent = function(name, value) {
- return this.entity(name, value);
- };
- XMLDocType.prototype.pent = function(name, value) {
- return this.pEntity(name, value);
- };
- XMLDocType.prototype.not = function(name, value) {
- return this.notation(name, value);
- };
- XMLDocType.prototype.up = function() {
- return this.root() || this.documentObject;
- };
- return XMLDocType;
- })(XMLNode);
- }).call(this);
- },{"./Utility":158,"./XMLDTDAttList":162,"./XMLDTDElement":163,"./XMLDTDEntity":164,"./XMLDTDNotation":165,"./XMLNode":171}],168:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject,
- 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; },
- hasProp = {}.hasOwnProperty;
- isPlainObject = require('./Utility').isPlainObject;
- XMLNode = require('./XMLNode');
- XMLStringifier = require('./XMLStringifier');
- XMLStringWriter = require('./XMLStringWriter');
- module.exports = XMLDocument = (function(superClass) {
- extend(XMLDocument, superClass);
- function XMLDocument(options) {
- XMLDocument.__super__.constructor.call(this, null);
- this.name = "?xml";
- options || (options = {});
- if (!options.writer) {
- options.writer = new XMLStringWriter();
- }
- this.options = options;
- this.stringify = new XMLStringifier(options);
- this.isDocument = true;
- }
- XMLDocument.prototype.end = function(writer) {
- var writerOptions;
- if (!writer) {
- writer = this.options.writer;
- } else if (isPlainObject(writer)) {
- writerOptions = writer;
- writer = this.options.writer.set(writerOptions);
- }
- return writer.document(this);
- };
- XMLDocument.prototype.toString = function(options) {
- return this.options.writer.set(options).document(this);
- };
- return XMLDocument;
- })(XMLNode);
- }).call(this);
- },{"./Utility":158,"./XMLNode":171,"./XMLStringWriter":175,"./XMLStringifier":176}],169:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref,
- hasProp = {}.hasOwnProperty;
- ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue;
- XMLElement = require('./XMLElement');
- XMLCData = require('./XMLCData');
- XMLComment = require('./XMLComment');
- XMLRaw = require('./XMLRaw');
- XMLText = require('./XMLText');
- XMLProcessingInstruction = require('./XMLProcessingInstruction');
- XMLDeclaration = require('./XMLDeclaration');
- XMLDocType = require('./XMLDocType');
- XMLDTDAttList = require('./XMLDTDAttList');
- XMLDTDEntity = require('./XMLDTDEntity');
- XMLDTDElement = require('./XMLDTDElement');
- XMLDTDNotation = require('./XMLDTDNotation');
- XMLAttribute = require('./XMLAttribute');
- XMLStringifier = require('./XMLStringifier');
- XMLStringWriter = require('./XMLStringWriter');
- module.exports = XMLDocumentCB = (function() {
- function XMLDocumentCB(options, onData, onEnd) {
- var writerOptions;
- this.name = "?xml";
- options || (options = {});
- if (!options.writer) {
- options.writer = new XMLStringWriter(options);
- } else if (isPlainObject(options.writer)) {
- writerOptions = options.writer;
- options.writer = new XMLStringWriter(writerOptions);
- }
- this.options = options;
- this.writer = options.writer;
- this.stringify = new XMLStringifier(options);
- this.onDataCallback = onData || function() {};
- this.onEndCallback = onEnd || function() {};
- this.currentNode = null;
- this.currentLevel = -1;
- this.openTags = {};
- this.documentStarted = false;
- this.documentCompleted = false;
- this.root = null;
- }
- XMLDocumentCB.prototype.node = function(name, attributes, text) {
- var ref1;
- if (name == null) {
- throw new Error("Missing node name.");
- }
- if (this.root && this.currentLevel === -1) {
- throw new Error("Document can only have one root node. " + this.debugInfo(name));
- }
- this.openCurrent();
- name = getValue(name);
- if (attributes == null) {
- attributes = {};
- }
- attributes = getValue(attributes);
- if (!isObject(attributes)) {
- ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
- }
- this.currentNode = new XMLElement(this, name, attributes);
- this.currentNode.children = false;
- this.currentLevel++;
- this.openTags[this.currentLevel] = this.currentNode;
- if (text != null) {
- this.text(text);
- }
- return this;
- };
- XMLDocumentCB.prototype.element = function(name, attributes, text) {
- if (this.currentNode && this.currentNode instanceof XMLDocType) {
- return this.dtdElement.apply(this, arguments);
- } else {
- return this.node(name, attributes, text);
- }
- };
- XMLDocumentCB.prototype.attribute = function(name, value) {
- var attName, attValue;
- if (!this.currentNode || this.currentNode.children) {
- throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name));
- }
- if (name != null) {
- name = getValue(name);
- }
- if (isObject(name)) {
- for (attName in name) {
- if (!hasProp.call(name, attName)) continue;
- attValue = name[attName];
- this.attribute(attName, attValue);
- }
- } else {
- if (isFunction(value)) {
- value = value.apply();
- }
- if (!this.options.skipNullAttributes || (value != null)) {
- this.currentNode.attributes[name] = new XMLAttribute(this, name, value);
- }
- }
- return this;
- };
- XMLDocumentCB.prototype.text = function(value) {
- var node;
- this.openCurrent();
- node = new XMLText(this, value);
- this.onData(this.writer.text(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.cdata = function(value) {
- var node;
- this.openCurrent();
- node = new XMLCData(this, value);
- this.onData(this.writer.cdata(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.comment = function(value) {
- var node;
- this.openCurrent();
- node = new XMLComment(this, value);
- this.onData(this.writer.comment(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.raw = function(value) {
- var node;
- this.openCurrent();
- node = new XMLRaw(this, value);
- this.onData(this.writer.raw(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.instruction = function(target, value) {
- var i, insTarget, insValue, len, node;
- this.openCurrent();
- if (target != null) {
- target = getValue(target);
- }
- if (value != null) {
- value = getValue(value);
- }
- if (Array.isArray(target)) {
- for (i = 0, len = target.length; i < len; i++) {
- insTarget = target[i];
- this.instruction(insTarget);
- }
- } else if (isObject(target)) {
- for (insTarget in target) {
- if (!hasProp.call(target, insTarget)) continue;
- insValue = target[insTarget];
- this.instruction(insTarget, insValue);
- }
- } else {
- if (isFunction(value)) {
- value = value.apply();
- }
- node = new XMLProcessingInstruction(this, target, value);
- this.onData(this.writer.processingInstruction(node, this.currentLevel + 1), this.currentLevel + 1);
- }
- return this;
- };
- XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) {
- var node;
- this.openCurrent();
- if (this.documentStarted) {
- throw new Error("declaration() must be the first node.");
- }
- node = new XMLDeclaration(this, version, encoding, standalone);
- this.onData(this.writer.declaration(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) {
- this.openCurrent();
- if (root == null) {
- throw new Error("Missing root node name.");
- }
- if (this.root) {
- throw new Error("dtd() must come before the root node.");
- }
- this.currentNode = new XMLDocType(this, pubID, sysID);
- this.currentNode.rootNodeName = root;
- this.currentNode.children = false;
- this.currentLevel++;
- this.openTags[this.currentLevel] = this.currentNode;
- return this;
- };
- XMLDocumentCB.prototype.dtdElement = function(name, value) {
- var node;
- this.openCurrent();
- node = new XMLDTDElement(this, name, value);
- this.onData(this.writer.dtdElement(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
- var node;
- this.openCurrent();
- node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
- this.onData(this.writer.dtdAttList(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.entity = function(name, value) {
- var node;
- this.openCurrent();
- node = new XMLDTDEntity(this, false, name, value);
- this.onData(this.writer.dtdEntity(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.pEntity = function(name, value) {
- var node;
- this.openCurrent();
- node = new XMLDTDEntity(this, true, name, value);
- this.onData(this.writer.dtdEntity(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.notation = function(name, value) {
- var node;
- this.openCurrent();
- node = new XMLDTDNotation(this, name, value);
- this.onData(this.writer.dtdNotation(node, this.currentLevel + 1), this.currentLevel + 1);
- return this;
- };
- XMLDocumentCB.prototype.up = function() {
- if (this.currentLevel < 0) {
- throw new Error("The document node has no parent.");
- }
- if (this.currentNode) {
- if (this.currentNode.children) {
- this.closeNode(this.currentNode);
- } else {
- this.openNode(this.currentNode);
- }
- this.currentNode = null;
- } else {
- this.closeNode(this.openTags[this.currentLevel]);
- }
- delete this.openTags[this.currentLevel];
- this.currentLevel--;
- return this;
- };
- XMLDocumentCB.prototype.end = function() {
- while (this.currentLevel >= 0) {
- this.up();
- }
- return this.onEnd();
- };
- XMLDocumentCB.prototype.openCurrent = function() {
- if (this.currentNode) {
- this.currentNode.children = true;
- return this.openNode(this.currentNode);
- }
- };
- XMLDocumentCB.prototype.openNode = function(node) {
- if (!node.isOpen) {
- if (!this.root && this.currentLevel === 0 && node instanceof XMLElement) {
- this.root = node;
- }
- this.onData(this.writer.openNode(node, this.currentLevel), this.currentLevel);
- return node.isOpen = true;
- }
- };
- XMLDocumentCB.prototype.closeNode = function(node) {
- if (!node.isClosed) {
- this.onData(this.writer.closeNode(node, this.currentLevel), this.currentLevel);
- return node.isClosed = true;
- }
- };
- XMLDocumentCB.prototype.onData = function(chunk, level) {
- this.documentStarted = true;
- return this.onDataCallback(chunk, level + 1);
- };
- XMLDocumentCB.prototype.onEnd = function() {
- this.documentCompleted = true;
- return this.onEndCallback();
- };
- XMLDocumentCB.prototype.debugInfo = function(name) {
- if (name == null) {
- return "";
- } else {
- return "node: <" + name + ">";
- }
- };
- XMLDocumentCB.prototype.ele = function() {
- return this.element.apply(this, arguments);
- };
- XMLDocumentCB.prototype.nod = function(name, attributes, text) {
- return this.node(name, attributes, text);
- };
- XMLDocumentCB.prototype.txt = function(value) {
- return this.text(value);
- };
- XMLDocumentCB.prototype.dat = function(value) {
- return this.cdata(value);
- };
- XMLDocumentCB.prototype.com = function(value) {
- return this.comment(value);
- };
- XMLDocumentCB.prototype.ins = function(target, value) {
- return this.instruction(target, value);
- };
- XMLDocumentCB.prototype.dec = function(version, encoding, standalone) {
- return this.declaration(version, encoding, standalone);
- };
- XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) {
- return this.doctype(root, pubID, sysID);
- };
- XMLDocumentCB.prototype.e = function(name, attributes, text) {
- return this.element(name, attributes, text);
- };
- XMLDocumentCB.prototype.n = function(name, attributes, text) {
- return this.node(name, attributes, text);
- };
- XMLDocumentCB.prototype.t = function(value) {
- return this.text(value);
- };
- XMLDocumentCB.prototype.d = function(value) {
- return this.cdata(value);
- };
- XMLDocumentCB.prototype.c = function(value) {
- return this.comment(value);
- };
- XMLDocumentCB.prototype.r = function(value) {
- return this.raw(value);
- };
- XMLDocumentCB.prototype.i = function(target, value) {
- return this.instruction(target, value);
- };
- XMLDocumentCB.prototype.att = function() {
- if (this.currentNode && this.currentNode instanceof XMLDocType) {
- return this.attList.apply(this, arguments);
- } else {
- return this.attribute.apply(this, arguments);
- }
- };
- XMLDocumentCB.prototype.a = function() {
- if (this.currentNode && this.currentNode instanceof XMLDocType) {
- return this.attList.apply(this, arguments);
- } else {
- return this.attribute.apply(this, arguments);
- }
- };
- XMLDocumentCB.prototype.ent = function(name, value) {
- return this.entity(name, value);
- };
- XMLDocumentCB.prototype.pent = function(name, value) {
- return this.pEntity(name, value);
- };
- XMLDocumentCB.prototype.not = function(name, value) {
- return this.notation(name, value);
- };
- return XMLDocumentCB;
- })();
- }).call(this);
- },{"./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){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLAttribute, XMLElement, XMLNode, getValue, isFunction, isObject, ref,
- 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; },
- hasProp = {}.hasOwnProperty;
- ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue;
- XMLNode = require('./XMLNode');
- XMLAttribute = require('./XMLAttribute');
- module.exports = XMLElement = (function(superClass) {
- extend(XMLElement, superClass);
- function XMLElement(parent, name, attributes) {
- XMLElement.__super__.constructor.call(this, parent);
- if (name == null) {
- throw new Error("Missing element name. " + this.debugInfo());
- }
- this.name = this.stringify.eleName(name);
- this.attributes = {};
- if (attributes != null) {
- this.attribute(attributes);
- }
- if (parent.isDocument) {
- this.isRoot = true;
- this.documentObject = parent;
- parent.rootObject = this;
- }
- }
- XMLElement.prototype.clone = function() {
- var att, attName, clonedSelf, ref1;
- clonedSelf = Object.create(this);
- if (clonedSelf.isRoot) {
- clonedSelf.documentObject = null;
- }
- clonedSelf.attributes = {};
- ref1 = this.attributes;
- for (attName in ref1) {
- if (!hasProp.call(ref1, attName)) continue;
- att = ref1[attName];
- clonedSelf.attributes[attName] = att.clone();
- }
- clonedSelf.children = [];
- this.children.forEach(function(child) {
- var clonedChild;
- clonedChild = child.clone();
- clonedChild.parent = clonedSelf;
- return clonedSelf.children.push(clonedChild);
- });
- return clonedSelf;
- };
- XMLElement.prototype.attribute = function(name, value) {
- var attName, attValue;
- if (name != null) {
- name = getValue(name);
- }
- if (isObject(name)) {
- for (attName in name) {
- if (!hasProp.call(name, attName)) continue;
- attValue = name[attName];
- this.attribute(attName, attValue);
- }
- } else {
- if (isFunction(value)) {
- value = value.apply();
- }
- if (!this.options.skipNullAttributes || (value != null)) {
- this.attributes[name] = new XMLAttribute(this, name, value);
- }
- }
- return this;
- };
- XMLElement.prototype.removeAttribute = function(name) {
- var attName, i, len;
- if (name == null) {
- throw new Error("Missing attribute name. " + this.debugInfo());
- }
- name = getValue(name);
- if (Array.isArray(name)) {
- for (i = 0, len = name.length; i < len; i++) {
- attName = name[i];
- delete this.attributes[attName];
- }
- } else {
- delete this.attributes[name];
- }
- return this;
- };
- XMLElement.prototype.toString = function(options) {
- return this.options.writer.set(options).element(this);
- };
- XMLElement.prototype.att = function(name, value) {
- return this.attribute(name, value);
- };
- XMLElement.prototype.a = function(name, value) {
- return this.attribute(name, value);
- };
- return XMLElement;
- })(XMLNode);
- }).call(this);
- },{"./Utility":158,"./XMLAttribute":159,"./XMLNode":171}],171:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref,
- hasProp = {}.hasOwnProperty;
- ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isEmpty = ref.isEmpty, getValue = ref.getValue;
- XMLElement = null;
- XMLCData = null;
- XMLComment = null;
- XMLDeclaration = null;
- XMLDocType = null;
- XMLRaw = null;
- XMLText = null;
- XMLProcessingInstruction = null;
- module.exports = XMLNode = (function() {
- function XMLNode(parent) {
- this.parent = parent;
- if (this.parent) {
- this.options = this.parent.options;
- this.stringify = this.parent.stringify;
- }
- this.children = [];
- if (!XMLElement) {
- XMLElement = require('./XMLElement');
- XMLCData = require('./XMLCData');
- XMLComment = require('./XMLComment');
- XMLDeclaration = require('./XMLDeclaration');
- XMLDocType = require('./XMLDocType');
- XMLRaw = require('./XMLRaw');
- XMLText = require('./XMLText');
- XMLProcessingInstruction = require('./XMLProcessingInstruction');
- }
- }
- XMLNode.prototype.element = function(name, attributes, text) {
- var childNode, item, j, k, key, lastChild, len, len1, ref1, val;
- lastChild = null;
- if (attributes == null) {
- attributes = {};
- }
- attributes = getValue(attributes);
- if (!isObject(attributes)) {
- ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
- }
- if (name != null) {
- name = getValue(name);
- }
- if (Array.isArray(name)) {
- for (j = 0, len = name.length; j < len; j++) {
- item = name[j];
- lastChild = this.element(item);
- }
- } else if (isFunction(name)) {
- lastChild = this.element(name.apply());
- } else if (isObject(name)) {
- for (key in name) {
- if (!hasProp.call(name, key)) continue;
- val = name[key];
- if (isFunction(val)) {
- val = val.apply();
- }
- if ((isObject(val)) && (isEmpty(val))) {
- val = null;
- }
- if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
- lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
- } else if (!this.options.separateArrayItems && Array.isArray(val)) {
- for (k = 0, len1 = val.length; k < len1; k++) {
- item = val[k];
- childNode = {};
- childNode[key] = item;
- lastChild = this.element(childNode);
- }
- } else if (isObject(val)) {
- lastChild = this.element(key);
- lastChild.element(val);
- } else {
- lastChild = this.element(key, val);
- }
- }
- } else {
- if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
- lastChild = this.text(text);
- } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
- lastChild = this.cdata(text);
- } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
- lastChild = this.comment(text);
- } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
- lastChild = this.raw(text);
- } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) {
- lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text);
- } else {
- lastChild = this.node(name, attributes, text);
- }
- }
- if (lastChild == null) {
- throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo());
- }
- return lastChild;
- };
- XMLNode.prototype.insertBefore = function(name, attributes, text) {
- var child, i, removed;
- if (this.isRoot) {
- throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
- }
- i = this.parent.children.indexOf(this);
- removed = this.parent.children.splice(i);
- child = this.parent.element(name, attributes, text);
- Array.prototype.push.apply(this.parent.children, removed);
- return child;
- };
- XMLNode.prototype.insertAfter = function(name, attributes, text) {
- var child, i, removed;
- if (this.isRoot) {
- throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
- }
- i = this.parent.children.indexOf(this);
- removed = this.parent.children.splice(i + 1);
- child = this.parent.element(name, attributes, text);
- Array.prototype.push.apply(this.parent.children, removed);
- return child;
- };
- XMLNode.prototype.remove = function() {
- var i, ref1;
- if (this.isRoot) {
- throw new Error("Cannot remove the root element. " + this.debugInfo());
- }
- i = this.parent.children.indexOf(this);
- [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref1 = [])), ref1;
- return this.parent;
- };
- XMLNode.prototype.node = function(name, attributes, text) {
- var child, ref1;
- if (name != null) {
- name = getValue(name);
- }
- attributes || (attributes = {});
- attributes = getValue(attributes);
- if (!isObject(attributes)) {
- ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
- }
- child = new XMLElement(this, name, attributes);
- if (text != null) {
- child.text(text);
- }
- this.children.push(child);
- return child;
- };
- XMLNode.prototype.text = function(value) {
- var child;
- child = new XMLText(this, value);
- this.children.push(child);
- return this;
- };
- XMLNode.prototype.cdata = function(value) {
- var child;
- child = new XMLCData(this, value);
- this.children.push(child);
- return this;
- };
- XMLNode.prototype.comment = function(value) {
- var child;
- child = new XMLComment(this, value);
- this.children.push(child);
- return this;
- };
- XMLNode.prototype.commentBefore = function(value) {
- var child, i, removed;
- i = this.parent.children.indexOf(this);
- removed = this.parent.children.splice(i);
- child = this.parent.comment(value);
- Array.prototype.push.apply(this.parent.children, removed);
- return this;
- };
- XMLNode.prototype.commentAfter = function(value) {
- var child, i, removed;
- i = this.parent.children.indexOf(this);
- removed = this.parent.children.splice(i + 1);
- child = this.parent.comment(value);
- Array.prototype.push.apply(this.parent.children, removed);
- return this;
- };
- XMLNode.prototype.raw = function(value) {
- var child;
- child = new XMLRaw(this, value);
- this.children.push(child);
- return this;
- };
- XMLNode.prototype.instruction = function(target, value) {
- var insTarget, insValue, instruction, j, len;
- if (target != null) {
- target = getValue(target);
- }
- if (value != null) {
- value = getValue(value);
- }
- if (Array.isArray(target)) {
- for (j = 0, len = target.length; j < len; j++) {
- insTarget = target[j];
- this.instruction(insTarget);
- }
- } else if (isObject(target)) {
- for (insTarget in target) {
- if (!hasProp.call(target, insTarget)) continue;
- insValue = target[insTarget];
- this.instruction(insTarget, insValue);
- }
- } else {
- if (isFunction(value)) {
- value = value.apply();
- }
- instruction = new XMLProcessingInstruction(this, target, value);
- this.children.push(instruction);
- }
- return this;
- };
- XMLNode.prototype.instructionBefore = function(target, value) {
- var child, i, removed;
- i = this.parent.children.indexOf(this);
- removed = this.parent.children.splice(i);
- child = this.parent.instruction(target, value);
- Array.prototype.push.apply(this.parent.children, removed);
- return this;
- };
- XMLNode.prototype.instructionAfter = function(target, value) {
- var child, i, removed;
- i = this.parent.children.indexOf(this);
- removed = this.parent.children.splice(i + 1);
- child = this.parent.instruction(target, value);
- Array.prototype.push.apply(this.parent.children, removed);
- return this;
- };
- XMLNode.prototype.declaration = function(version, encoding, standalone) {
- var doc, xmldec;
- doc = this.document();
- xmldec = new XMLDeclaration(doc, version, encoding, standalone);
- if (doc.children[0] instanceof XMLDeclaration) {
- doc.children[0] = xmldec;
- } else {
- doc.children.unshift(xmldec);
- }
- return doc.root() || doc;
- };
- XMLNode.prototype.doctype = function(pubID, sysID) {
- var child, doc, doctype, i, j, k, len, len1, ref1, ref2;
- doc = this.document();
- doctype = new XMLDocType(doc, pubID, sysID);
- ref1 = doc.children;
- for (i = j = 0, len = ref1.length; j < len; i = ++j) {
- child = ref1[i];
- if (child instanceof XMLDocType) {
- doc.children[i] = doctype;
- return doctype;
- }
- }
- ref2 = doc.children;
- for (i = k = 0, len1 = ref2.length; k < len1; i = ++k) {
- child = ref2[i];
- if (child.isRoot) {
- doc.children.splice(i, 0, doctype);
- return doctype;
- }
- }
- doc.children.push(doctype);
- return doctype;
- };
- XMLNode.prototype.up = function() {
- if (this.isRoot) {
- throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
- }
- return this.parent;
- };
- XMLNode.prototype.root = function() {
- var node;
- node = this;
- while (node) {
- if (node.isDocument) {
- return node.rootObject;
- } else if (node.isRoot) {
- return node;
- } else {
- node = node.parent;
- }
- }
- };
- XMLNode.prototype.document = function() {
- var node;
- node = this;
- while (node) {
- if (node.isDocument) {
- return node;
- } else {
- node = node.parent;
- }
- }
- };
- XMLNode.prototype.end = function(options) {
- return this.document().end(options);
- };
- XMLNode.prototype.prev = function() {
- var i;
- i = this.parent.children.indexOf(this);
- if (i < 1) {
- throw new Error("Already at the first node. " + this.debugInfo());
- }
- return this.parent.children[i - 1];
- };
- XMLNode.prototype.next = function() {
- var i;
- i = this.parent.children.indexOf(this);
- if (i === -1 || i === this.parent.children.length - 1) {
- throw new Error("Already at the last node. " + this.debugInfo());
- }
- return this.parent.children[i + 1];
- };
- XMLNode.prototype.importDocument = function(doc) {
- var clonedRoot;
- clonedRoot = doc.root().clone();
- clonedRoot.parent = this;
- clonedRoot.isRoot = false;
- this.children.push(clonedRoot);
- return this;
- };
- XMLNode.prototype.debugInfo = function(name) {
- var ref1, ref2;
- name = name || this.name;
- if ((name == null) && !((ref1 = this.parent) != null ? ref1.name : void 0)) {
- return "";
- } else if (name == null) {
- return "parent: <" + this.parent.name + ">";
- } else if (!((ref2 = this.parent) != null ? ref2.name : void 0)) {
- return "node: <" + name + ">";
- } else {
- return "node: <" + name + ">, parent: <" + this.parent.name + ">";
- }
- };
- XMLNode.prototype.ele = function(name, attributes, text) {
- return this.element(name, attributes, text);
- };
- XMLNode.prototype.nod = function(name, attributes, text) {
- return this.node(name, attributes, text);
- };
- XMLNode.prototype.txt = function(value) {
- return this.text(value);
- };
- XMLNode.prototype.dat = function(value) {
- return this.cdata(value);
- };
- XMLNode.prototype.com = function(value) {
- return this.comment(value);
- };
- XMLNode.prototype.ins = function(target, value) {
- return this.instruction(target, value);
- };
- XMLNode.prototype.doc = function() {
- return this.document();
- };
- XMLNode.prototype.dec = function(version, encoding, standalone) {
- return this.declaration(version, encoding, standalone);
- };
- XMLNode.prototype.dtd = function(pubID, sysID) {
- return this.doctype(pubID, sysID);
- };
- XMLNode.prototype.e = function(name, attributes, text) {
- return this.element(name, attributes, text);
- };
- XMLNode.prototype.n = function(name, attributes, text) {
- return this.node(name, attributes, text);
- };
- XMLNode.prototype.t = function(value) {
- return this.text(value);
- };
- XMLNode.prototype.d = function(value) {
- return this.cdata(value);
- };
- XMLNode.prototype.c = function(value) {
- return this.comment(value);
- };
- XMLNode.prototype.r = function(value) {
- return this.raw(value);
- };
- XMLNode.prototype.i = function(target, value) {
- return this.instruction(target, value);
- };
- XMLNode.prototype.u = function() {
- return this.up();
- };
- XMLNode.prototype.importXMLBuilder = function(doc) {
- return this.importDocument(doc);
- };
- return XMLNode;
- })();
- }).call(this);
- },{"./Utility":158,"./XMLCData":160,"./XMLComment":161,"./XMLDeclaration":166,"./XMLDocType":167,"./XMLElement":170,"./XMLProcessingInstruction":172,"./XMLRaw":173,"./XMLText":177}],172:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLNode, XMLProcessingInstruction,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLProcessingInstruction = (function(superClass) {
- extend(XMLProcessingInstruction, superClass);
- function XMLProcessingInstruction(parent, target, value) {
- XMLProcessingInstruction.__super__.constructor.call(this, parent);
- if (target == null) {
- throw new Error("Missing instruction target. " + this.debugInfo());
- }
- this.target = this.stringify.insTarget(target);
- if (value) {
- this.value = this.stringify.insValue(value);
- }
- }
- XMLProcessingInstruction.prototype.clone = function() {
- return Object.create(this);
- };
- XMLProcessingInstruction.prototype.toString = function(options) {
- return this.options.writer.set(options).processingInstruction(this);
- };
- return XMLProcessingInstruction;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],173:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLNode, XMLRaw,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLRaw = (function(superClass) {
- extend(XMLRaw, superClass);
- function XMLRaw(parent, text) {
- XMLRaw.__super__.constructor.call(this, parent);
- if (text == null) {
- throw new Error("Missing raw text. " + this.debugInfo());
- }
- this.value = this.stringify.raw(text);
- }
- XMLRaw.prototype.clone = function() {
- return Object.create(this);
- };
- XMLRaw.prototype.toString = function(options) {
- return this.options.writer.set(options).raw(this);
- };
- return XMLRaw;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],174:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStreamWriter, XMLText, XMLWriterBase,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLDeclaration = require('./XMLDeclaration');
- XMLDocType = require('./XMLDocType');
- XMLCData = require('./XMLCData');
- XMLComment = require('./XMLComment');
- XMLElement = require('./XMLElement');
- XMLRaw = require('./XMLRaw');
- XMLText = require('./XMLText');
- XMLProcessingInstruction = require('./XMLProcessingInstruction');
- XMLDTDAttList = require('./XMLDTDAttList');
- XMLDTDElement = require('./XMLDTDElement');
- XMLDTDEntity = require('./XMLDTDEntity');
- XMLDTDNotation = require('./XMLDTDNotation');
- XMLWriterBase = require('./XMLWriterBase');
- module.exports = XMLStreamWriter = (function(superClass) {
- extend(XMLStreamWriter, superClass);
- function XMLStreamWriter(stream, options) {
- XMLStreamWriter.__super__.constructor.call(this, options);
- this.stream = stream;
- }
- XMLStreamWriter.prototype.document = function(doc) {
- var child, i, j, len, len1, ref, ref1, results;
- ref = doc.children;
- for (i = 0, len = ref.length; i < len; i++) {
- child = ref[i];
- child.isLastRootNode = false;
- }
- doc.children[doc.children.length - 1].isLastRootNode = true;
- ref1 = doc.children;
- results = [];
- for (j = 0, len1 = ref1.length; j < len1; j++) {
- child = ref1[j];
- switch (false) {
- case !(child instanceof XMLDeclaration):
- results.push(this.declaration(child));
- break;
- case !(child instanceof XMLDocType):
- results.push(this.docType(child));
- break;
- case !(child instanceof XMLComment):
- results.push(this.comment(child));
- break;
- case !(child instanceof XMLProcessingInstruction):
- results.push(this.processingInstruction(child));
- break;
- default:
- results.push(this.element(child));
- }
- }
- return results;
- };
- XMLStreamWriter.prototype.attribute = function(att) {
- return this.stream.write(' ' + att.name + '="' + att.value + '"');
- };
- XMLStreamWriter.prototype.cdata = function(node, level) {
- return this.stream.write(this.space(level) + '<![CDATA[' + node.text + ']]>' + this.endline(node));
- };
- XMLStreamWriter.prototype.comment = function(node, level) {
- return this.stream.write(this.space(level) + '<!-- ' + node.text + ' -->' + this.endline(node));
- };
- XMLStreamWriter.prototype.declaration = function(node, level) {
- this.stream.write(this.space(level));
- this.stream.write('<?xml version="' + node.version + '"');
- if (node.encoding != null) {
- this.stream.write(' encoding="' + node.encoding + '"');
- }
- if (node.standalone != null) {
- this.stream.write(' standalone="' + node.standalone + '"');
- }
- this.stream.write(this.spacebeforeslash + '?>');
- return this.stream.write(this.endline(node));
- };
- XMLStreamWriter.prototype.docType = function(node, level) {
- var child, i, len, ref;
- level || (level = 0);
- this.stream.write(this.space(level));
- this.stream.write('<!DOCTYPE ' + node.root().name);
- if (node.pubID && node.sysID) {
- this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
- } else if (node.sysID) {
- this.stream.write(' SYSTEM "' + node.sysID + '"');
- }
- if (node.children.length > 0) {
- this.stream.write(' [');
- this.stream.write(this.endline(node));
- ref = node.children;
- for (i = 0, len = ref.length; i < len; i++) {
- child = ref[i];
- switch (false) {
- case !(child instanceof XMLDTDAttList):
- this.dtdAttList(child, level + 1);
- break;
- case !(child instanceof XMLDTDElement):
- this.dtdElement(child, level + 1);
- break;
- case !(child instanceof XMLDTDEntity):
- this.dtdEntity(child, level + 1);
- break;
- case !(child instanceof XMLDTDNotation):
- this.dtdNotation(child, level + 1);
- break;
- case !(child instanceof XMLCData):
- this.cdata(child, level + 1);
- break;
- case !(child instanceof XMLComment):
- this.comment(child, level + 1);
- break;
- case !(child instanceof XMLProcessingInstruction):
- this.processingInstruction(child, level + 1);
- break;
- default:
- throw new Error("Unknown DTD node type: " + child.constructor.name);
- }
- }
- this.stream.write(']');
- }
- this.stream.write(this.spacebeforeslash + '>');
- return this.stream.write(this.endline(node));
- };
- XMLStreamWriter.prototype.element = function(node, level) {
- var att, child, i, len, name, ref, ref1, space;
- level || (level = 0);
- space = this.space(level);
- this.stream.write(space + '<' + node.name);
- ref = node.attributes;
- for (name in ref) {
- if (!hasProp.call(ref, name)) continue;
- att = ref[name];
- this.attribute(att);
- }
- if (node.children.length === 0 || node.children.every(function(e) {
- return e.value === '';
- })) {
- if (this.allowEmpty) {
- this.stream.write('></' + node.name + '>');
- } else {
- this.stream.write(this.spacebeforeslash + '/>');
- }
- } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
- this.stream.write('>');
- this.stream.write(node.children[0].value);
- this.stream.write('</' + node.name + '>');
- } else {
- this.stream.write('>' + this.newline);
- ref1 = node.children;
- for (i = 0, len = ref1.length; i < len; i++) {
- child = ref1[i];
- switch (false) {
- case !(child instanceof XMLCData):
- this.cdata(child, level + 1);
- break;
- case !(child instanceof XMLComment):
- this.comment(child, level + 1);
- break;
- case !(child instanceof XMLElement):
- this.element(child, level + 1);
- break;
- case !(child instanceof XMLRaw):
- this.raw(child, level + 1);
- break;
- case !(child instanceof XMLText):
- this.text(child, level + 1);
- break;
- case !(child instanceof XMLProcessingInstruction):
- this.processingInstruction(child, level + 1);
- break;
- default:
- throw new Error("Unknown XML node type: " + child.constructor.name);
- }
- }
- this.stream.write(space + '</' + node.name + '>');
- }
- return this.stream.write(this.endline(node));
- };
- XMLStreamWriter.prototype.processingInstruction = function(node, level) {
- this.stream.write(this.space(level) + '<?' + node.target);
- if (node.value) {
- this.stream.write(' ' + node.value);
- }
- return this.stream.write(this.spacebeforeslash + '?>' + this.endline(node));
- };
- XMLStreamWriter.prototype.raw = function(node, level) {
- return this.stream.write(this.space(level) + node.value + this.endline(node));
- };
- XMLStreamWriter.prototype.text = function(node, level) {
- return this.stream.write(this.space(level) + node.value + this.endline(node));
- };
- XMLStreamWriter.prototype.dtdAttList = function(node, level) {
- this.stream.write(this.space(level) + '<!ATTLIST ' + node.elementName + ' ' + node.attributeName + ' ' + node.attributeType);
- if (node.defaultValueType !== '#DEFAULT') {
- this.stream.write(' ' + node.defaultValueType);
- }
- if (node.defaultValue) {
- this.stream.write(' "' + node.defaultValue + '"');
- }
- return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
- };
- XMLStreamWriter.prototype.dtdElement = function(node, level) {
- this.stream.write(this.space(level) + '<!ELEMENT ' + node.name + ' ' + node.value);
- return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
- };
- XMLStreamWriter.prototype.dtdEntity = function(node, level) {
- this.stream.write(this.space(level) + '<!ENTITY');
- if (node.pe) {
- this.stream.write(' %');
- }
- this.stream.write(' ' + node.name);
- if (node.value) {
- this.stream.write(' "' + node.value + '"');
- } else {
- if (node.pubID && node.sysID) {
- this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
- } else if (node.sysID) {
- this.stream.write(' SYSTEM "' + node.sysID + '"');
- }
- if (node.nData) {
- this.stream.write(' NDATA ' + node.nData);
- }
- }
- return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
- };
- XMLStreamWriter.prototype.dtdNotation = function(node, level) {
- this.stream.write(this.space(level) + '<!NOTATION ' + node.name);
- if (node.pubID && node.sysID) {
- this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
- } else if (node.pubID) {
- this.stream.write(' PUBLIC "' + node.pubID + '"');
- } else if (node.sysID) {
- this.stream.write(' SYSTEM "' + node.sysID + '"');
- }
- return this.stream.write(this.spacebeforeslash + '>' + this.endline(node));
- };
- XMLStreamWriter.prototype.endline = function(node) {
- if (!node.isLastRootNode) {
- return this.newline;
- } else {
- return '';
- }
- };
- return XMLStreamWriter;
- })(XMLWriterBase);
- }).call(this);
- },{"./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){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLText, XMLWriterBase,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLDeclaration = require('./XMLDeclaration');
- XMLDocType = require('./XMLDocType');
- XMLCData = require('./XMLCData');
- XMLComment = require('./XMLComment');
- XMLElement = require('./XMLElement');
- XMLRaw = require('./XMLRaw');
- XMLText = require('./XMLText');
- XMLProcessingInstruction = require('./XMLProcessingInstruction');
- XMLDTDAttList = require('./XMLDTDAttList');
- XMLDTDElement = require('./XMLDTDElement');
- XMLDTDEntity = require('./XMLDTDEntity');
- XMLDTDNotation = require('./XMLDTDNotation');
- XMLWriterBase = require('./XMLWriterBase');
- module.exports = XMLStringWriter = (function(superClass) {
- extend(XMLStringWriter, superClass);
- function XMLStringWriter(options) {
- XMLStringWriter.__super__.constructor.call(this, options);
- }
- XMLStringWriter.prototype.document = function(doc) {
- var child, i, len, r, ref;
- this.textispresent = false;
- r = '';
- ref = doc.children;
- for (i = 0, len = ref.length; i < len; i++) {
- child = ref[i];
- r += (function() {
- switch (false) {
- case !(child instanceof XMLDeclaration):
- return this.declaration(child);
- case !(child instanceof XMLDocType):
- return this.docType(child);
- case !(child instanceof XMLComment):
- return this.comment(child);
- case !(child instanceof XMLProcessingInstruction):
- return this.processingInstruction(child);
- default:
- return this.element(child, 0);
- }
- }).call(this);
- }
- if (this.pretty && r.slice(-this.newline.length) === this.newline) {
- r = r.slice(0, -this.newline.length);
- }
- return r;
- };
- XMLStringWriter.prototype.attribute = function(att) {
- return ' ' + att.name + '="' + att.value + '"';
- };
- XMLStringWriter.prototype.cdata = function(node, level) {
- return this.space(level) + '<![CDATA[' + node.text + ']]>' + this.newline;
- };
- XMLStringWriter.prototype.comment = function(node, level) {
- return this.space(level) + '<!-- ' + node.text + ' -->' + this.newline;
- };
- XMLStringWriter.prototype.declaration = function(node, level) {
- var r;
- r = this.space(level);
- r += '<?xml version="' + node.version + '"';
- if (node.encoding != null) {
- r += ' encoding="' + node.encoding + '"';
- }
- if (node.standalone != null) {
- r += ' standalone="' + node.standalone + '"';
- }
- r += this.spacebeforeslash + '?>';
- r += this.newline;
- return r;
- };
- XMLStringWriter.prototype.docType = function(node, level) {
- var child, i, len, r, ref;
- level || (level = 0);
- r = this.space(level);
- r += '<!DOCTYPE ' + node.root().name;
- if (node.pubID && node.sysID) {
- r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
- } else if (node.sysID) {
- r += ' SYSTEM "' + node.sysID + '"';
- }
- if (node.children.length > 0) {
- r += ' [';
- r += this.newline;
- ref = node.children;
- for (i = 0, len = ref.length; i < len; i++) {
- child = ref[i];
- r += (function() {
- switch (false) {
- case !(child instanceof XMLDTDAttList):
- return this.dtdAttList(child, level + 1);
- case !(child instanceof XMLDTDElement):
- return this.dtdElement(child, level + 1);
- case !(child instanceof XMLDTDEntity):
- return this.dtdEntity(child, level + 1);
- case !(child instanceof XMLDTDNotation):
- return this.dtdNotation(child, level + 1);
- case !(child instanceof XMLCData):
- return this.cdata(child, level + 1);
- case !(child instanceof XMLComment):
- return this.comment(child, level + 1);
- case !(child instanceof XMLProcessingInstruction):
- return this.processingInstruction(child, level + 1);
- default:
- throw new Error("Unknown DTD node type: " + child.constructor.name);
- }
- }).call(this);
- }
- r += ']';
- }
- r += this.spacebeforeslash + '>';
- r += this.newline;
- return r;
- };
- XMLStringWriter.prototype.element = function(node, level) {
- var att, child, i, j, len, len1, name, r, ref, ref1, ref2, space, textispresentwasset;
- level || (level = 0);
- textispresentwasset = false;
- if (this.textispresent) {
- this.newline = '';
- this.pretty = false;
- } else {
- this.newline = this.newlinedefault;
- this.pretty = this.prettydefault;
- }
- space = this.space(level);
- r = '';
- r += space + '<' + node.name;
- ref = node.attributes;
- for (name in ref) {
- if (!hasProp.call(ref, name)) continue;
- att = ref[name];
- r += this.attribute(att);
- }
- if (node.children.length === 0 || node.children.every(function(e) {
- return e.value === '';
- })) {
- if (this.allowEmpty) {
- r += '></' + node.name + '>' + this.newline;
- } else {
- r += this.spacebeforeslash + '/>' + this.newline;
- }
- } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
- r += '>';
- r += node.children[0].value;
- r += '</' + node.name + '>' + this.newline;
- } else {
- if (this.dontprettytextnodes) {
- ref1 = node.children;
- for (i = 0, len = ref1.length; i < len; i++) {
- child = ref1[i];
- if (child.value != null) {
- this.textispresent++;
- textispresentwasset = true;
- break;
- }
- }
- }
- if (this.textispresent) {
- this.newline = '';
- this.pretty = false;
- space = this.space(level);
- }
- r += '>' + this.newline;
- ref2 = node.children;
- for (j = 0, len1 = ref2.length; j < len1; j++) {
- child = ref2[j];
- r += (function() {
- switch (false) {
- case !(child instanceof XMLCData):
- return this.cdata(child, level + 1);
- case !(child instanceof XMLComment):
- return this.comment(child, level + 1);
- case !(child instanceof XMLElement):
- return this.element(child, level + 1);
- case !(child instanceof XMLRaw):
- return this.raw(child, level + 1);
- case !(child instanceof XMLText):
- return this.text(child, level + 1);
- case !(child instanceof XMLProcessingInstruction):
- return this.processingInstruction(child, level + 1);
- default:
- throw new Error("Unknown XML node type: " + child.constructor.name);
- }
- }).call(this);
- }
- if (textispresentwasset) {
- this.textispresent--;
- }
- if (!this.textispresent) {
- this.newline = this.newlinedefault;
- this.pretty = this.prettydefault;
- }
- r += space + '</' + node.name + '>' + this.newline;
- }
- return r;
- };
- XMLStringWriter.prototype.processingInstruction = function(node, level) {
- var r;
- r = this.space(level) + '<?' + node.target;
- if (node.value) {
- r += ' ' + node.value;
- }
- r += this.spacebeforeslash + '?>' + this.newline;
- return r;
- };
- XMLStringWriter.prototype.raw = function(node, level) {
- return this.space(level) + node.value + this.newline;
- };
- XMLStringWriter.prototype.text = function(node, level) {
- return this.space(level) + node.value + this.newline;
- };
- XMLStringWriter.prototype.dtdAttList = function(node, level) {
- var r;
- r = this.space(level) + '<!ATTLIST ' + node.elementName + ' ' + node.attributeName + ' ' + node.attributeType;
- if (node.defaultValueType !== '#DEFAULT') {
- r += ' ' + node.defaultValueType;
- }
- if (node.defaultValue) {
- r += ' "' + node.defaultValue + '"';
- }
- r += this.spacebeforeslash + '>' + this.newline;
- return r;
- };
- XMLStringWriter.prototype.dtdElement = function(node, level) {
- return this.space(level) + '<!ELEMENT ' + node.name + ' ' + node.value + this.spacebeforeslash + '>' + this.newline;
- };
- XMLStringWriter.prototype.dtdEntity = function(node, level) {
- var r;
- r = this.space(level) + '<!ENTITY';
- if (node.pe) {
- r += ' %';
- }
- r += ' ' + node.name;
- if (node.value) {
- r += ' "' + node.value + '"';
- } else {
- if (node.pubID && node.sysID) {
- r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
- } else if (node.sysID) {
- r += ' SYSTEM "' + node.sysID + '"';
- }
- if (node.nData) {
- r += ' NDATA ' + node.nData;
- }
- }
- r += this.spacebeforeslash + '>' + this.newline;
- return r;
- };
- XMLStringWriter.prototype.dtdNotation = function(node, level) {
- var r;
- r = this.space(level) + '<!NOTATION ' + node.name;
- if (node.pubID && node.sysID) {
- r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
- } else if (node.pubID) {
- r += ' PUBLIC "' + node.pubID + '"';
- } else if (node.sysID) {
- r += ' SYSTEM "' + node.sysID + '"';
- }
- r += this.spacebeforeslash + '>' + this.newline;
- return r;
- };
- XMLStringWriter.prototype.openNode = function(node, level) {
- var att, name, r, ref;
- level || (level = 0);
- if (node instanceof XMLElement) {
- r = this.space(level) + '<' + node.name;
- ref = node.attributes;
- for (name in ref) {
- if (!hasProp.call(ref, name)) continue;
- att = ref[name];
- r += this.attribute(att);
- }
- r += (node.children ? '>' : '/>') + this.newline;
- return r;
- } else {
- r = this.space(level) + '<!DOCTYPE ' + node.rootNodeName;
- if (node.pubID && node.sysID) {
- r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
- } else if (node.sysID) {
- r += ' SYSTEM "' + node.sysID + '"';
- }
- r += (node.children ? ' [' : '>') + this.newline;
- return r;
- }
- };
- XMLStringWriter.prototype.closeNode = function(node, level) {
- level || (level = 0);
- switch (false) {
- case !(node instanceof XMLElement):
- return this.space(level) + '</' + node.name + '>' + this.newline;
- case !(node instanceof XMLDocType):
- return this.space(level) + ']>' + this.newline;
- }
- };
- return XMLStringWriter;
- })(XMLWriterBase);
- }).call(this);
- },{"./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){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLStringifier,
- bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
- hasProp = {}.hasOwnProperty;
- module.exports = XMLStringifier = (function() {
- function XMLStringifier(options) {
- this.assertLegalChar = bind(this.assertLegalChar, this);
- var key, ref, value;
- options || (options = {});
- this.noDoubleEncoding = options.noDoubleEncoding;
- ref = options.stringify || {};
- for (key in ref) {
- if (!hasProp.call(ref, key)) continue;
- value = ref[key];
- this[key] = value;
- }
- }
- XMLStringifier.prototype.eleName = function(val) {
- val = '' + val || '';
- return this.assertLegalChar(val);
- };
- XMLStringifier.prototype.eleText = function(val) {
- val = '' + val || '';
- return this.assertLegalChar(this.elEscape(val));
- };
- XMLStringifier.prototype.cdata = function(val) {
- val = '' + val || '';
- val = val.replace(']]>', ']]]]><![CDATA[>');
- return this.assertLegalChar(val);
- };
- XMLStringifier.prototype.comment = function(val) {
- val = '' + val || '';
- if (val.match(/--/)) {
- throw new Error("Comment text cannot contain double-hypen: " + val);
- }
- return this.assertLegalChar(val);
- };
- XMLStringifier.prototype.raw = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.attName = function(val) {
- return val = '' + val || '';
- };
- XMLStringifier.prototype.attValue = function(val) {
- val = '' + val || '';
- return this.attEscape(val);
- };
- XMLStringifier.prototype.insTarget = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.insValue = function(val) {
- val = '' + val || '';
- if (val.match(/\?>/)) {
- throw new Error("Invalid processing instruction value: " + val);
- }
- return val;
- };
- XMLStringifier.prototype.xmlVersion = function(val) {
- val = '' + val || '';
- if (!val.match(/1\.[0-9]+/)) {
- throw new Error("Invalid version number: " + val);
- }
- return val;
- };
- XMLStringifier.prototype.xmlEncoding = function(val) {
- val = '' + val || '';
- if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) {
- throw new Error("Invalid encoding: " + val);
- }
- return val;
- };
- XMLStringifier.prototype.xmlStandalone = function(val) {
- if (val) {
- return "yes";
- } else {
- return "no";
- }
- };
- XMLStringifier.prototype.dtdPubID = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.dtdSysID = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.dtdElementValue = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.dtdAttType = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.dtdAttDefault = function(val) {
- if (val != null) {
- return '' + val || '';
- } else {
- return val;
- }
- };
- XMLStringifier.prototype.dtdEntityValue = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.dtdNData = function(val) {
- return '' + val || '';
- };
- XMLStringifier.prototype.convertAttKey = '@';
- XMLStringifier.prototype.convertPIKey = '?';
- XMLStringifier.prototype.convertTextKey = '#text';
- XMLStringifier.prototype.convertCDataKey = '#cdata';
- XMLStringifier.prototype.convertCommentKey = '#comment';
- XMLStringifier.prototype.convertRawKey = '#raw';
- XMLStringifier.prototype.assertLegalChar = function(str) {
- var res;
- res = str.match(/[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/);
- if (res) {
- throw new Error("Invalid character in string: " + str + " at index " + res.index);
- }
- return str;
- };
- XMLStringifier.prototype.elEscape = function(str) {
- var ampregex;
- ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
- return str.replace(ampregex, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\r/g, '
');
- };
- XMLStringifier.prototype.attEscape = function(str) {
- var ampregex;
- ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
- return str.replace(ampregex, '&').replace(/</g, '<').replace(/"/g, '"').replace(/\t/g, '	').replace(/\n/g, '
').replace(/\r/g, '
');
- };
- return XMLStringifier;
- })();
- }).call(this);
- },{}],177:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLNode, XMLText,
- 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; },
- hasProp = {}.hasOwnProperty;
- XMLNode = require('./XMLNode');
- module.exports = XMLText = (function(superClass) {
- extend(XMLText, superClass);
- function XMLText(parent, text) {
- XMLText.__super__.constructor.call(this, parent);
- if (text == null) {
- throw new Error("Missing element text. " + this.debugInfo());
- }
- this.value = this.stringify.eleText(text);
- }
- XMLText.prototype.clone = function() {
- return Object.create(this);
- };
- XMLText.prototype.toString = function(options) {
- return this.options.writer.set(options).text(this);
- };
- return XMLText;
- })(XMLNode);
- }).call(this);
- },{"./XMLNode":171}],178:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLWriterBase,
- hasProp = {}.hasOwnProperty;
- module.exports = XMLWriterBase = (function() {
- function XMLWriterBase(options) {
- var key, ref, ref1, ref2, ref3, ref4, ref5, ref6, value;
- options || (options = {});
- this.pretty = options.pretty || false;
- this.allowEmpty = (ref = options.allowEmpty) != null ? ref : false;
- if (this.pretty) {
- this.indent = (ref1 = options.indent) != null ? ref1 : ' ';
- this.newline = (ref2 = options.newline) != null ? ref2 : '\n';
- this.offset = (ref3 = options.offset) != null ? ref3 : 0;
- this.dontprettytextnodes = (ref4 = options.dontprettytextnodes) != null ? ref4 : 0;
- } else {
- this.indent = '';
- this.newline = '';
- this.offset = 0;
- this.dontprettytextnodes = 0;
- }
- this.spacebeforeslash = (ref5 = options.spacebeforeslash) != null ? ref5 : '';
- if (this.spacebeforeslash === true) {
- this.spacebeforeslash = ' ';
- }
- this.newlinedefault = this.newline;
- this.prettydefault = this.pretty;
- ref6 = options.writer || {};
- for (key in ref6) {
- if (!hasProp.call(ref6, key)) continue;
- value = ref6[key];
- this[key] = value;
- }
- }
- XMLWriterBase.prototype.set = function(options) {
- var key, ref, value;
- options || (options = {});
- if ("pretty" in options) {
- this.pretty = options.pretty;
- }
- if ("allowEmpty" in options) {
- this.allowEmpty = options.allowEmpty;
- }
- if (this.pretty) {
- this.indent = "indent" in options ? options.indent : ' ';
- this.newline = "newline" in options ? options.newline : '\n';
- this.offset = "offset" in options ? options.offset : 0;
- this.dontprettytextnodes = "dontprettytextnodes" in options ? options.dontprettytextnodes : 0;
- } else {
- this.indent = '';
- this.newline = '';
- this.offset = 0;
- this.dontprettytextnodes = 0;
- }
- this.spacebeforeslash = "spacebeforeslash" in options ? options.spacebeforeslash : '';
- if (this.spacebeforeslash === true) {
- this.spacebeforeslash = ' ';
- }
- this.newlinedefault = this.newline;
- this.prettydefault = this.pretty;
- ref = options.writer || {};
- for (key in ref) {
- if (!hasProp.call(ref, key)) continue;
- value = ref[key];
- this[key] = value;
- }
- return this;
- };
- XMLWriterBase.prototype.space = function(level) {
- var indent;
- if (this.pretty) {
- indent = (level || 0) + this.offset + 1;
- if (indent > 0) {
- return new Array(indent).join(this.indent);
- } else {
- return '';
- }
- } else {
- return '';
- }
- };
- return XMLWriterBase;
- })();
- }).call(this);
- },{}],179:[function(require,module,exports){
- // Generated by CoffeeScript 1.12.7
- (function() {
- var XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref;
- ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction;
- XMLDocument = require('./XMLDocument');
- XMLDocumentCB = require('./XMLDocumentCB');
- XMLStringWriter = require('./XMLStringWriter');
- XMLStreamWriter = require('./XMLStreamWriter');
- module.exports.create = function(name, xmldec, doctype, options) {
- var doc, root;
- if (name == null) {
- throw new Error("Root element needs a name.");
- }
- options = assign({}, xmldec, doctype, options);
- doc = new XMLDocument(options);
- root = doc.element(name);
- if (!options.headless) {
- doc.declaration(options);
- if ((options.pubID != null) || (options.sysID != null)) {
- doc.doctype(options);
- }
- }
- return root;
- };
- module.exports.begin = function(options, onData, onEnd) {
- var ref1;
- if (isFunction(options)) {
- ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];
- options = {};
- }
- if (onData) {
- return new XMLDocumentCB(options, onData, onEnd);
- } else {
- return new XMLDocument(options);
- }
- };
- module.exports.stringWriter = function(options) {
- return new XMLStringWriter(options);
- };
- module.exports.streamWriter = function(stream, options) {
- return new XMLStreamWriter(stream, options);
- };
- }).call(this);
- },{"./Utility":158,"./XMLDocument":168,"./XMLDocumentCB":169,"./XMLStreamWriter":174,"./XMLStringWriter":175}]},{},[21])(21)
- });
|