星火管控前端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xlsx.extendscript.js 1005KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878
  1. /*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  2. /*! shim.js (C) 2013-present SheetJS -- http://sheetjs.com */
  3. /* ES3/5 Compatibility shims and other utilities for older browsers. */
  4. // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
  5. if(!Object.keys) Object.keys = (function() {
  6. var hasOwnProperty = Object.prototype.hasOwnProperty,
  7. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  8. dontEnums = [
  9. 'toString',
  10. 'toLocaleString',
  11. 'valueOf',
  12. 'hasOwnProperty',
  13. 'isPrototypeOf',
  14. 'propertyIsEnumerable',
  15. 'constructor'
  16. ],
  17. dontEnumsLength = dontEnums.length;
  18. return function(obj) {
  19. if(typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
  20. var result = [];
  21. for(var prop in obj) if(hasOwnProperty.call(obj, prop)) result.push(prop);
  22. if(hasDontEnumBug)
  23. for(var i=0; i < dontEnumsLength; ++i)
  24. if(hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  25. return result;
  26. };
  27. })();
  28. if(!String.prototype.trim) String.prototype.trim = function() {
  29. var s = this.replace(/^\s+/, '');
  30. for(var i = s.length - 1; i >=0 ; --i) if(!s.charAt(i).match(/^\s/)) return s.slice(0,i+1);
  31. return "";
  32. };
  33. if(!Array.prototype.forEach) Array.prototype.forEach = function(cb) {
  34. var len = (this.length>>>0), self = (arguments[1]||void 0);
  35. for(var i=0; i<len; ++i) if(i in this) self ? cb.call(self, this[i], i, this) : cb(this[i], i, this);
  36. };
  37. if(!Array.prototype.map) Array.prototype.map = function(cb) {
  38. var len = (this.length>>>0), self = (arguments[1]||void 0), A = new Array(len);
  39. for(var i=0; i<len; ++i) if(i in this) A[i] = self ? cb.call(self, this[i], i, this) : cb(this[i], i, this);
  40. return A;
  41. };
  42. if(!Array.prototype.indexOf) Array.prototype.indexOf = function(needle) {
  43. var len = (this.length>>>0), i = ((arguments[1]|0)||0);
  44. for(i<0 && (i+=len)<0 && (i=0); i<len; ++i) if(this[i] === needle) return i;
  45. return -1;
  46. };
  47. if(!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(needle) {
  48. var len = (this.length>>>0), i = len - 1;
  49. for(; i>=0; --i) if(this[i] === needle) return i;
  50. return -1;
  51. };
  52. if(!Array.isArray) Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; };
  53. if(!Date.prototype.toISOString) Date.prototype.toISOString = (function() {
  54. function p(n,i) { return ('0000000' + n).slice(-(i||2)); }
  55. return function _toISOString() {
  56. var y = this.getUTCFullYear(), yr = "";
  57. if(y>9999) yr = '+' + p( y, 6);
  58. else if(y<0) yr = '-' + p(-y, 6);
  59. else yr = p( y, 4);
  60. return [
  61. yr, p(this.getUTCMonth()+1), p(this.getUTCDate())
  62. ].join('-') + 'T' + [
  63. p(this.getUTCHours()), p(this.getUTCMinutes()), p(this.getUTCSeconds())
  64. ].join(':') + '.' + p(this.getUTCMilliseconds(),3) + 'Z';
  65. };
  66. }());
  67. if(typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) ArrayBuffer.prototype.slice = function(start, end) {
  68. if(start == null) start = 0;
  69. if(start < 0) { start += this.byteLength; if(start < 0) start = 0; }
  70. if(start >= this.byteLength) return new Uint8Array(0);
  71. if(end == null) end = this.byteLength;
  72. if(end < 0) { end += this.byteLength; if(end < 0) end = 0; }
  73. if(end > this.byteLength) end = this.byteLength;
  74. if(start > end) return new Uint8Array(0);
  75. var out = new ArrayBuffer(end - start);
  76. var view = new Uint8Array(out);
  77. var data = new Uint8Array(this, start, end - start)
  78. /* IE10 should have Uint8Array#set */
  79. if(view.set) view.set(data); else while(start <= --end) view[end - start] = data[end];
  80. return out;
  81. };
  82. if(typeof Uint8Array !== 'undefined' && !Uint8Array.prototype.slice) Uint8Array.prototype.slice = function(start, end) {
  83. if(start == null) start = 0;
  84. if(start < 0) { start += this.length; if(start < 0) start = 0; }
  85. if(start >= this.length) return new Uint8Array(0);
  86. if(end == null) end = this.length;
  87. if(end < 0) { end += this.length; if(end < 0) end = 0; }
  88. if(end > this.length) end = this.length;
  89. if(start > end) return new Uint8Array(0);
  90. var out = new Uint8Array(end - start);
  91. while(start <= --end) out[end - start] = this[end];
  92. return out;
  93. };
  94. // VBScript + ActiveX fallback for IE5+
  95. var IE_SaveFile = (function() { try {
  96. if(typeof IE_SaveFile_Impl == "undefined") document.write([
  97. '<script type="text/vbscript" language="vbscript">',
  98. 'IE_GetProfileAndPath_Key = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\"',
  99. 'Function IE_GetProfileAndPath(key): Set wshell = CreateObject("WScript.Shell"): IE_GetProfileAndPath = wshell.RegRead(IE_GetProfileAndPath_Key & key): IE_GetProfileAndPath = wshell.ExpandEnvironmentStrings("%USERPROFILE%") & "!" & IE_GetProfileAndPath: End Function',
  100. 'Function IE_SaveFile_Impl(FileName, payload): Dim data, plen, i, bit: data = CStr(payload): plen = Len(data): Set fso = CreateObject("Scripting.FileSystemObject"): fso.CreateTextFile FileName, True: Set f = fso.GetFile(FileName): Set stream = f.OpenAsTextStream(2, 0): For i = 1 To plen Step 3: bit = Mid(data, i, 2): stream.write Chr(CLng("&h" & bit)): Next: stream.Close: IE_SaveFile_Impl = True: End Function',
  101. '|/script>'.replace("|","<")
  102. ].join("\r\n"));
  103. if(typeof IE_SaveFile_Impl == "undefined") return void 0;
  104. var IE_GetPath = (function() {
  105. var DDP1 = "";
  106. try { DDP1 = IE_GetProfileAndPath("{374DE290-123F-4565-9164-39C4925E467B}"); } catch(e) { try { DDP1 = IE_GetProfileAndPath("Personal"); } catch(e) { try { DDP1 = IE_GetProfileAndPath("Desktop"); } catch(e) { throw e; }}}
  107. var o = DDP1.split("!");
  108. DDP = o[1].replace("%USERPROFILE%", o[0]);
  109. return function(path) { return DDP + "\\" + path; };
  110. })();
  111. function fix_data(data) {
  112. var out = [];
  113. var T = typeof data == "string";
  114. for(var i = 0; i < data.length; ++i) out.push(("00"+(T ? data.charCodeAt(i) : data[i]).toString(16)).slice(-2));
  115. var o = out.join("|");
  116. return o;
  117. }
  118. return function(data, filename) { return IE_SaveFile_Impl(IE_GetPath(filename), fix_data(data)); };
  119. } catch(e) { return void 0; }})();
  120. var IE_LoadFile = (function() { try {
  121. if(typeof IE_LoadFile_Impl == "undefined") document.write([
  122. '<script type="text/vbscript" language="vbscript">',
  123. 'Function IE_LoadFile_Impl(FileName): Dim out(), plen, i, cc: Set fso = CreateObject("Scripting.FileSystemObject"): Set f = fso.GetFile(FileName): Set stream = f.OpenAsTextStream(1, 0): plen = f.Size: ReDim out(plen): For i = 1 To plen Step 1: cc = Hex(Asc(stream.read(1))): If Len(cc) < 2 Then: cc = "0" & cc: End If: out(i) = cc: Next: IE_LoadFile_Impl = Join(out,""): End Function',
  124. '|/script>'.replace("|","<")
  125. ].join("\r\n"));
  126. if(typeof IE_LoadFile_Impl == "undefined") return void 0;
  127. function fix_data(data) {
  128. var out = [];
  129. for(var i = 0; i < data.length; i+=2) out.push(String.fromCharCode(parseInt(data.slice(i, i+2), 16)));
  130. var o = out.join("");
  131. return o;
  132. }
  133. return function(filename) { return fix_data(IE_LoadFile_Impl(filename)); };
  134. } catch(e) { return void 0; }})();
  135. // getComputedStyle polyfill from https://gist.github.com/8HNHoFtE/5891086
  136. if(typeof window !== 'undefined' && typeof window.getComputedStyle !== 'function') {
  137. window.getComputedStyle = function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}
  138. }
  139. var DO_NOT_EXPORT_CODEPAGE = true;
  140. var DO_NOT_EXPORT_JSZIP = true;
  141. /*
  142. JSZip - A Javascript class for generating and reading zip files
  143. <http://stuartk.com/jszip>
  144. (c) 2009-2014 Stuart Knightley <stuart [at] stuartk.com>
  145. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  146. JSZip uses the library pako released under the MIT license :
  147. https://github.com/nodeca/pako/blob/master/LICENSE
  148. Note: since JSZip 3 removed critical functionality, this version assigns to the
  149. `JSZipSync` variable. Another JSZip version can be loaded in parallel.
  150. */
  151. (function(e){
  152. if("object"==typeof exports&&"undefined"!=typeof module&&"undefined"==typeof DO_NOT_EXPORT_JSZIP)module.exports=e();
  153. else if("function"==typeof define&&define.amd&&"undefined"==typeof DO_NOT_EXPORT_JSZIP){JSZipSync=e();define([],e);}
  154. else{
  155. var f;
  156. "undefined"!=typeof globalThis?f=globalThis:
  157. "undefined"!=typeof window?f=window:
  158. "undefined"!=typeof global?f=global:
  159. "undefined"!=typeof $ && $.global?f=$.global:
  160. "undefined"!=typeof self&&(f=self),f.JSZipSync=e()
  161. }
  162. }(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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(_dereq_,module,exports){
  163. 'use strict';
  164. // private property
  165. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  166. // public method for encoding
  167. exports.encode = function(input, utf8) {
  168. var output = "";
  169. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  170. var i = 0;
  171. while (i < input.length) {
  172. chr1 = input.charCodeAt(i++);
  173. chr2 = input.charCodeAt(i++);
  174. chr3 = input.charCodeAt(i++);
  175. enc1 = chr1 >> 2;
  176. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  177. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  178. enc4 = chr3 & 63;
  179. if (isNaN(chr2)) {
  180. enc3 = enc4 = 64;
  181. }
  182. else if (isNaN(chr3)) {
  183. enc4 = 64;
  184. }
  185. output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
  186. }
  187. return output;
  188. };
  189. // public method for decoding
  190. exports.decode = function(input, utf8) {
  191. var output = "";
  192. var chr1, chr2, chr3;
  193. var enc1, enc2, enc3, enc4;
  194. var i = 0;
  195. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  196. while (i < input.length) {
  197. enc1 = _keyStr.indexOf(input.charAt(i++));
  198. enc2 = _keyStr.indexOf(input.charAt(i++));
  199. enc3 = _keyStr.indexOf(input.charAt(i++));
  200. enc4 = _keyStr.indexOf(input.charAt(i++));
  201. chr1 = (enc1 << 2) | (enc2 >> 4);
  202. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  203. chr3 = ((enc3 & 3) << 6) | enc4;
  204. output = output + String.fromCharCode(chr1);
  205. if (enc3 != 64) {
  206. output = output + String.fromCharCode(chr2);
  207. }
  208. if (enc4 != 64) {
  209. output = output + String.fromCharCode(chr3);
  210. }
  211. }
  212. return output;
  213. };
  214. },{}],2:[function(_dereq_,module,exports){
  215. 'use strict';
  216. function CompressedObject() {
  217. this.compressedSize = 0;
  218. this.uncompressedSize = 0;
  219. this.crc32 = 0;
  220. this.compressionMethod = null;
  221. this.compressedContent = null;
  222. }
  223. CompressedObject.prototype = {
  224. /**
  225. * Return the decompressed content in an unspecified format.
  226. * The format will depend on the decompressor.
  227. * @return {Object} the decompressed content.
  228. */
  229. getContent: function() {
  230. return null; // see implementation
  231. },
  232. /**
  233. * Return the compressed content in an unspecified format.
  234. * The format will depend on the compressed conten source.
  235. * @return {Object} the compressed content.
  236. */
  237. getCompressedContent: function() {
  238. return null; // see implementation
  239. }
  240. };
  241. module.exports = CompressedObject;
  242. },{}],3:[function(_dereq_,module,exports){
  243. 'use strict';
  244. exports.STORE = {
  245. magic: "\x00\x00",
  246. compress: function(content) {
  247. return content; // no compression
  248. },
  249. uncompress: function(content) {
  250. return content; // no compression
  251. },
  252. compressInputType: null,
  253. uncompressInputType: null
  254. };
  255. exports.DEFLATE = _dereq_('./flate');
  256. },{"./flate":8}],4:[function(_dereq_,module,exports){
  257. 'use strict';
  258. var utils = _dereq_('./utils');
  259. var table = [
  260. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  261. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  262. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  263. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  264. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  265. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  266. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  267. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  268. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  269. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  270. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  271. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  272. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  273. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  274. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  275. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  276. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  277. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  278. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  279. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  280. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  281. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  282. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  283. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  284. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  285. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  286. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  287. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  288. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  289. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  290. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  291. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  292. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  293. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  294. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  295. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  296. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  297. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  298. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  299. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  300. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  301. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  302. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  303. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  304. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  305. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  306. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  307. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  308. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  309. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  310. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  311. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  312. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  313. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  314. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  315. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  316. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  317. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  318. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  319. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  320. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  321. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  322. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  323. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  324. ];
  325. /**
  326. *
  327. * Javascript crc32
  328. * http://www.webtoolkit.info/
  329. *
  330. */
  331. module.exports = function crc32(input, crc) {
  332. if (typeof input === "undefined" || !input.length) {
  333. return 0;
  334. }
  335. var isArray = utils.getTypeOf(input) !== "string";
  336. if (typeof(crc) == "undefined") {
  337. crc = 0;
  338. }
  339. var x = 0;
  340. var y = 0;
  341. var b = 0;
  342. crc = crc ^ (-1);
  343. for (var i = 0, iTop = input.length; i < iTop; i++) {
  344. b = isArray ? input[i] : input.charCodeAt(i);
  345. y = (crc ^ b) & 0xFF;
  346. x = table[y];
  347. crc = (crc >>> 8) ^ x;
  348. }
  349. return crc ^ (-1);
  350. };
  351. // vim: set shiftwidth=4 softtabstop=4:
  352. },{"./utils":21}],5:[function(_dereq_,module,exports){
  353. 'use strict';
  354. var utils = _dereq_('./utils');
  355. function DataReader(data) {
  356. this.data = null; // type : see implementation
  357. this.length = 0;
  358. this.index = 0;
  359. }
  360. DataReader.prototype = {
  361. /**
  362. * Check that the offset will not go too far.
  363. * @param {string} offset the additional offset to check.
  364. * @throws {Error} an Error if the offset is out of bounds.
  365. */
  366. checkOffset: function(offset) {
  367. this.checkIndex(this.index + offset);
  368. },
  369. /**
  370. * Check that the specifed index will not be too far.
  371. * @param {string} newIndex the index to check.
  372. * @throws {Error} an Error if the index is out of bounds.
  373. */
  374. checkIndex: function(newIndex) {
  375. if (this.length < newIndex || newIndex < 0) {
  376. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  377. }
  378. },
  379. /**
  380. * Change the index.
  381. * @param {number} newIndex The new index.
  382. * @throws {Error} if the new index is out of the data.
  383. */
  384. setIndex: function(newIndex) {
  385. this.checkIndex(newIndex);
  386. this.index = newIndex;
  387. },
  388. /**
  389. * Skip the next n bytes.
  390. * @param {number} n the number of bytes to skip.
  391. * @throws {Error} if the new index is out of the data.
  392. */
  393. skip: function(n) {
  394. this.setIndex(this.index + n);
  395. },
  396. /**
  397. * Get the byte at the specified index.
  398. * @param {number} i the index to use.
  399. * @return {number} a byte.
  400. */
  401. byteAt: function(i) {
  402. // see implementations
  403. },
  404. /**
  405. * Get the next number with a given byte size.
  406. * @param {number} size the number of bytes to read.
  407. * @return {number} the corresponding number.
  408. */
  409. readInt: function(size) {
  410. var result = 0,
  411. i;
  412. this.checkOffset(size);
  413. for (i = this.index + size - 1; i >= this.index; i--) {
  414. result = (result << 8) + this.byteAt(i);
  415. }
  416. this.index += size;
  417. return result;
  418. },
  419. /**
  420. * Get the next string with a given byte size.
  421. * @param {number} size the number of bytes to read.
  422. * @return {string} the corresponding string.
  423. */
  424. readString: function(size) {
  425. return utils.transformTo("string", this.readData(size));
  426. },
  427. /**
  428. * Get raw data without conversion, <size> bytes.
  429. * @param {number} size the number of bytes to read.
  430. * @return {Object} the raw data, implementation specific.
  431. */
  432. readData: function(size) {
  433. // see implementations
  434. },
  435. /**
  436. * Find the last occurence of a zip signature (4 bytes).
  437. * @param {string} sig the signature to find.
  438. * @return {number} the index of the last occurence, -1 if not found.
  439. */
  440. lastIndexOfSignature: function(sig) {
  441. // see implementations
  442. },
  443. /**
  444. * Get the next date.
  445. * @return {Date} the date.
  446. */
  447. readDate: function() {
  448. var dostime = this.readInt(4);
  449. return new Date(
  450. ((dostime >> 25) & 0x7f) + 1980, // year
  451. ((dostime >> 21) & 0x0f) - 1, // month
  452. (dostime >> 16) & 0x1f, // day
  453. (dostime >> 11) & 0x1f, // hour
  454. (dostime >> 5) & 0x3f, // minute
  455. (dostime & 0x1f) << 1); // second
  456. }
  457. };
  458. module.exports = DataReader;
  459. },{"./utils":21}],6:[function(_dereq_,module,exports){
  460. 'use strict';
  461. exports.base64 = false;
  462. exports.binary = false;
  463. exports.dir = false;
  464. exports.createFolders = false;
  465. exports.date = null;
  466. exports.compression = null;
  467. exports.comment = null;
  468. },{}],7:[function(_dereq_,module,exports){
  469. 'use strict';
  470. var utils = _dereq_('./utils');
  471. /**
  472. * @deprecated
  473. * This function will be removed in a future version without replacement.
  474. */
  475. exports.string2binary = function(str) {
  476. return utils.string2binary(str);
  477. };
  478. /**
  479. * @deprecated
  480. * This function will be removed in a future version without replacement.
  481. */
  482. exports.string2Uint8Array = function(str) {
  483. return utils.transformTo("uint8array", str);
  484. };
  485. /**
  486. * @deprecated
  487. * This function will be removed in a future version without replacement.
  488. */
  489. exports.uint8Array2String = function(array) {
  490. return utils.transformTo("string", array);
  491. };
  492. /**
  493. * @deprecated
  494. * This function will be removed in a future version without replacement.
  495. */
  496. exports.string2Blob = function(str) {
  497. var buffer = utils.transformTo("arraybuffer", str);
  498. return utils.arrayBuffer2Blob(buffer);
  499. };
  500. /**
  501. * @deprecated
  502. * This function will be removed in a future version without replacement.
  503. */
  504. exports.arrayBuffer2Blob = function(buffer) {
  505. return utils.arrayBuffer2Blob(buffer);
  506. };
  507. /**
  508. * @deprecated
  509. * This function will be removed in a future version without replacement.
  510. */
  511. exports.transformTo = function(outputType, input) {
  512. return utils.transformTo(outputType, input);
  513. };
  514. /**
  515. * @deprecated
  516. * This function will be removed in a future version without replacement.
  517. */
  518. exports.getTypeOf = function(input) {
  519. return utils.getTypeOf(input);
  520. };
  521. /**
  522. * @deprecated
  523. * This function will be removed in a future version without replacement.
  524. */
  525. exports.checkSupport = function(type) {
  526. return utils.checkSupport(type);
  527. };
  528. /**
  529. * @deprecated
  530. * This value will be removed in a future version without replacement.
  531. */
  532. exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
  533. /**
  534. * @deprecated
  535. * This value will be removed in a future version without replacement.
  536. */
  537. exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
  538. /**
  539. * @deprecated
  540. * This function will be removed in a future version without replacement.
  541. */
  542. exports.pretty = function(str) {
  543. return utils.pretty(str);
  544. };
  545. /**
  546. * @deprecated
  547. * This function will be removed in a future version without replacement.
  548. */
  549. exports.findCompression = function(compressionMethod) {
  550. return utils.findCompression(compressionMethod);
  551. };
  552. /**
  553. * @deprecated
  554. * This function will be removed in a future version without replacement.
  555. */
  556. exports.isRegExp = function (object) {
  557. return utils.isRegExp(object);
  558. };
  559. },{"./utils":21}],8:[function(_dereq_,module,exports){
  560. 'use strict';
  561. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  562. var pako = _dereq_("pako");
  563. exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  564. exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
  565. exports.magic = "\x08\x00";
  566. exports.compress = function(input) {
  567. return pako.deflateRaw(input);
  568. };
  569. exports.uncompress = function(input) {
  570. return pako.inflateRaw(input);
  571. };
  572. },{"pako":24}],9:[function(_dereq_,module,exports){
  573. 'use strict';
  574. var base64 = _dereq_('./base64');
  575. /**
  576. Usage:
  577. zip = new JSZip();
  578. zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
  579. zip.folder("images").file("smile.gif", base64Data, {base64: true});
  580. zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
  581. zip.remove("tempfile");
  582. base64zip = zip.generate();
  583. **/
  584. /**
  585. * Representation a of zip file in js
  586. * @constructor
  587. * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
  588. * @param {Object=} options the options for creating this objects (optional).
  589. */
  590. function JSZipSync(data, options) {
  591. // if this constructor is used without `new`, it adds `new` before itself:
  592. if(!(this instanceof JSZipSync)) return new JSZipSync(data, options);
  593. // object containing the files :
  594. // {
  595. // "folder/" : {...},
  596. // "folder/data.txt" : {...}
  597. // }
  598. this.files = {};
  599. this.comment = null;
  600. // Where we are in the hierarchy
  601. this.root = "";
  602. if (data) {
  603. this.load(data, options);
  604. }
  605. this.clone = function() {
  606. var newObj = new JSZipSync();
  607. for (var i in this) {
  608. if (typeof this[i] !== "function") {
  609. newObj[i] = this[i];
  610. }
  611. }
  612. return newObj;
  613. };
  614. }
  615. JSZipSync.prototype = _dereq_('./object');
  616. JSZipSync.prototype.load = _dereq_('./load');
  617. JSZipSync.support = _dereq_('./support');
  618. JSZipSync.defaults = _dereq_('./defaults');
  619. /**
  620. * @deprecated
  621. * This namespace will be removed in a future version without replacement.
  622. */
  623. JSZipSync.utils = _dereq_('./deprecatedPublicUtils');
  624. JSZipSync.base64 = {
  625. /**
  626. * @deprecated
  627. * This method will be removed in a future version without replacement.
  628. */
  629. encode : function(input) {
  630. return base64.encode(input);
  631. },
  632. /**
  633. * @deprecated
  634. * This method will be removed in a future version without replacement.
  635. */
  636. decode : function(input) {
  637. return base64.decode(input);
  638. }
  639. };
  640. JSZipSync.compressions = _dereq_('./compressions');
  641. module.exports = JSZipSync;
  642. },{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(_dereq_,module,exports){
  643. 'use strict';
  644. var base64 = _dereq_('./base64');
  645. var ZipEntries = _dereq_('./zipEntries');
  646. module.exports = function(data, options) {
  647. var files, zipEntries, i, input;
  648. options = options || {};
  649. if (options.base64) {
  650. data = base64.decode(data);
  651. }
  652. zipEntries = new ZipEntries(data, options);
  653. files = zipEntries.files;
  654. for (i = 0; i < files.length; i++) {
  655. input = files[i];
  656. this.file(input.fileName, input.decompressed, {
  657. binary: true,
  658. optimizedBinaryString: true,
  659. date: input.date,
  660. dir: input.dir,
  661. comment : input.fileComment.length ? input.fileComment : null,
  662. createFolders: options.createFolders
  663. });
  664. }
  665. if (zipEntries.zipComment.length) {
  666. this.comment = zipEntries.zipComment;
  667. }
  668. return this;
  669. };
  670. },{"./base64":1,"./zipEntries":22}],11:[function(_dereq_,module,exports){
  671. (function (Buffer){
  672. 'use strict';
  673. var Buffer_from = /*::(*/function(){}/*:: :any)*/;
  674. if(typeof Buffer !== 'undefined') {
  675. var nbfs = !Buffer.from;
  676. if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
  677. Buffer_from = nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
  678. // $FlowIgnore
  679. if(!Buffer.alloc) Buffer.alloc = function(n) { return new Buffer(n); };
  680. }
  681. module.exports = function(data, encoding){
  682. return typeof data == 'number' ? Buffer.alloc(data) : Buffer_from(data, encoding);
  683. };
  684. module.exports.test = function(b){
  685. return Buffer.isBuffer(b);
  686. };
  687. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  688. },{}],12:[function(_dereq_,module,exports){
  689. 'use strict';
  690. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  691. function NodeBufferReader(data) {
  692. this.data = data;
  693. this.length = this.data.length;
  694. this.index = 0;
  695. }
  696. NodeBufferReader.prototype = new Uint8ArrayReader();
  697. /**
  698. * @see DataReader.readData
  699. */
  700. NodeBufferReader.prototype.readData = function(size) {
  701. this.checkOffset(size);
  702. var result = this.data.slice(this.index, this.index + size);
  703. this.index += size;
  704. return result;
  705. };
  706. module.exports = NodeBufferReader;
  707. },{"./uint8ArrayReader":18}],13:[function(_dereq_,module,exports){
  708. 'use strict';
  709. var support = _dereq_('./support');
  710. var utils = _dereq_('./utils');
  711. var crc32 = _dereq_('./crc32');
  712. var signature = _dereq_('./signature');
  713. var defaults = _dereq_('./defaults');
  714. var base64 = _dereq_('./base64');
  715. var compressions = _dereq_('./compressions');
  716. var CompressedObject = _dereq_('./compressedObject');
  717. var nodeBuffer = _dereq_('./nodeBuffer');
  718. var utf8 = _dereq_('./utf8');
  719. var StringWriter = _dereq_('./stringWriter');
  720. var Uint8ArrayWriter = _dereq_('./uint8ArrayWriter');
  721. /**
  722. * Returns the raw data of a ZipObject, decompress the content if necessary.
  723. * @param {ZipObject} file the file to use.
  724. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  725. */
  726. var getRawData = function(file) {
  727. if (file._data instanceof CompressedObject) {
  728. file._data = file._data.getContent();
  729. file.options.binary = true;
  730. file.options.base64 = false;
  731. if (utils.getTypeOf(file._data) === "uint8array") {
  732. var copy = file._data;
  733. // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
  734. // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
  735. file._data = new Uint8Array(copy.length);
  736. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  737. if (copy.length !== 0) {
  738. file._data.set(copy, 0);
  739. }
  740. }
  741. }
  742. return file._data;
  743. };
  744. /**
  745. * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
  746. * @param {ZipObject} file the file to use.
  747. * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
  748. */
  749. var getBinaryData = function(file) {
  750. var result = getRawData(file),
  751. type = utils.getTypeOf(result);
  752. if (type === "string") {
  753. if (!file.options.binary) {
  754. // unicode text !
  755. // unicode string => binary string is a painful process, check if we can avoid it.
  756. if (support.nodebuffer) {
  757. return nodeBuffer(result, "utf-8");
  758. }
  759. }
  760. return file.asBinary();
  761. }
  762. return result;
  763. };
  764. /**
  765. * Transform this._data into a string.
  766. * @param {function} filter a function String -> String, applied if not null on the result.
  767. * @return {String} the string representing this._data.
  768. */
  769. var dataToString = function(asUTF8) {
  770. var result = getRawData(this);
  771. if (result === null || typeof result === "undefined") {
  772. return "";
  773. }
  774. // if the data is a base64 string, we decode it before checking the encoding !
  775. if (this.options.base64) {
  776. result = base64.decode(result);
  777. }
  778. if (asUTF8 && this.options.binary) {
  779. // JSZip.prototype.utf8decode supports arrays as input
  780. // skip to array => string step, utf8decode will do it.
  781. result = out.utf8decode(result);
  782. }
  783. else {
  784. // no utf8 transformation, do the array => string step.
  785. result = utils.transformTo("string", result);
  786. }
  787. if (!asUTF8 && !this.options.binary) {
  788. result = utils.transformTo("string", out.utf8encode(result));
  789. }
  790. return result;
  791. };
  792. /**
  793. * A simple object representing a file in the zip file.
  794. * @constructor
  795. * @param {string} name the name of the file
  796. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  797. * @param {Object} options the options of the file
  798. */
  799. var ZipObject = function(name, data, options) {
  800. this.name = name;
  801. this.dir = options.dir;
  802. this.date = options.date;
  803. this.comment = options.comment;
  804. this._data = data;
  805. this.options = options;
  806. /*
  807. * This object contains initial values for dir and date.
  808. * With them, we can check if the user changed the deprecated metadata in
  809. * `ZipObject#options` or not.
  810. */
  811. this._initialMetadata = {
  812. dir : options.dir,
  813. date : options.date
  814. };
  815. };
  816. ZipObject.prototype = {
  817. /**
  818. * Return the content as UTF8 string.
  819. * @return {string} the UTF8 string.
  820. */
  821. asText: function() {
  822. return dataToString.call(this, true);
  823. },
  824. /**
  825. * Returns the binary content.
  826. * @return {string} the content as binary.
  827. */
  828. asBinary: function() {
  829. return dataToString.call(this, false);
  830. },
  831. /**
  832. * Returns the content as a nodejs Buffer.
  833. * @return {Buffer} the content as a Buffer.
  834. */
  835. asNodeBuffer: function() {
  836. var result = getBinaryData(this);
  837. return utils.transformTo("nodebuffer", result);
  838. },
  839. /**
  840. * Returns the content as an Uint8Array.
  841. * @return {Uint8Array} the content as an Uint8Array.
  842. */
  843. asUint8Array: function() {
  844. var result = getBinaryData(this);
  845. return utils.transformTo("uint8array", result);
  846. },
  847. /**
  848. * Returns the content as an ArrayBuffer.
  849. * @return {ArrayBuffer} the content as an ArrayBufer.
  850. */
  851. asArrayBuffer: function() {
  852. return this.asUint8Array().buffer;
  853. }
  854. };
  855. /**
  856. * Transform an integer into a string in hexadecimal.
  857. * @private
  858. * @param {number} dec the number to convert.
  859. * @param {number} bytes the number of bytes to generate.
  860. * @returns {string} the result.
  861. */
  862. var decToHex = function(dec, bytes) {
  863. var hex = "",
  864. i;
  865. for (i = 0; i < bytes; i++) {
  866. hex += String.fromCharCode(dec & 0xff);
  867. dec = dec >>> 8;
  868. }
  869. return hex;
  870. };
  871. /**
  872. * Merge the objects passed as parameters into a new one.
  873. * @private
  874. * @param {...Object} var_args All objects to merge.
  875. * @return {Object} a new object with the data of the others.
  876. */
  877. var extend = function() {
  878. var result = {}, i, attr;
  879. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  880. for (attr in arguments[i]) {
  881. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  882. result[attr] = arguments[i][attr];
  883. }
  884. }
  885. }
  886. return result;
  887. };
  888. /**
  889. * Transforms the (incomplete) options from the user into the complete
  890. * set of options to create a file.
  891. * @private
  892. * @param {Object} o the options from the user.
  893. * @return {Object} the complete set of options.
  894. */
  895. var prepareFileAttrs = function(o) {
  896. o = o || {};
  897. if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
  898. o.binary = true;
  899. }
  900. o = extend(o, defaults);
  901. o.date = o.date || new Date();
  902. if (o.compression !== null) o.compression = o.compression.toUpperCase();
  903. return o;
  904. };
  905. /**
  906. * Add a file in the current folder.
  907. * @private
  908. * @param {string} name the name of the file
  909. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  910. * @param {Object} o the options of the file
  911. * @return {Object} the new file.
  912. */
  913. var fileAdd = function(name, data, o) {
  914. // be sure sub folders exist
  915. var dataType = utils.getTypeOf(data),
  916. parent;
  917. o = prepareFileAttrs(o);
  918. if (o.createFolders && (parent = parentFolder(name))) {
  919. folderAdd.call(this, parent, true);
  920. }
  921. if (o.dir || data === null || typeof data === "undefined") {
  922. o.base64 = false;
  923. o.binary = false;
  924. data = null;
  925. }
  926. else if (dataType === "string") {
  927. if (o.binary && !o.base64) {
  928. // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
  929. if (o.optimizedBinaryString !== true) {
  930. // this is a string, not in a base64 format.
  931. // Be sure that this is a correct "binary string"
  932. data = utils.string2binary(data);
  933. }
  934. }
  935. }
  936. else { // arraybuffer, uint8array, ...
  937. o.base64 = false;
  938. o.binary = true;
  939. if (!dataType && !(data instanceof CompressedObject)) {
  940. throw new Error("The data of '" + name + "' is in an unsupported format !");
  941. }
  942. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  943. if (dataType === "arraybuffer") {
  944. data = utils.transformTo("uint8array", data);
  945. }
  946. }
  947. var object = new ZipObject(name, data, o);
  948. this.files[name] = object;
  949. return object;
  950. };
  951. /**
  952. * Find the parent folder of the path.
  953. * @private
  954. * @param {string} path the path to use
  955. * @return {string} the parent folder, or ""
  956. */
  957. var parentFolder = function (path) {
  958. if (path.slice(-1) == '/') {
  959. path = path.substring(0, path.length - 1);
  960. }
  961. var lastSlash = path.lastIndexOf('/');
  962. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  963. };
  964. /**
  965. * Add a (sub) folder in the current folder.
  966. * @private
  967. * @param {string} name the folder's name
  968. * @param {boolean=} [createFolders] If true, automatically create sub
  969. * folders. Defaults to false.
  970. * @return {Object} the new folder.
  971. */
  972. var folderAdd = function(name, createFolders) {
  973. // Check the name ends with a /
  974. if (name.slice(-1) != "/") {
  975. name += "/"; // IE doesn't like substr(-1)
  976. }
  977. createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
  978. // Does this folder already exist?
  979. if (!this.files[name]) {
  980. fileAdd.call(this, name, null, {
  981. dir: true,
  982. createFolders: createFolders
  983. });
  984. }
  985. return this.files[name];
  986. };
  987. /**
  988. * Generate a JSZip.CompressedObject for a given zipOject.
  989. * @param {ZipObject} file the object to read.
  990. * @param {JSZip.compression} compression the compression to use.
  991. * @return {JSZip.CompressedObject} the compressed result.
  992. */
  993. var generateCompressedObjectFrom = function(file, compression) {
  994. var result = new CompressedObject(),
  995. content;
  996. // the data has not been decompressed, we might reuse things !
  997. if (file._data instanceof CompressedObject) {
  998. result.uncompressedSize = file._data.uncompressedSize;
  999. result.crc32 = file._data.crc32;
  1000. if (result.uncompressedSize === 0 || file.dir) {
  1001. compression = compressions['STORE'];
  1002. result.compressedContent = "";
  1003. result.crc32 = 0;
  1004. }
  1005. else if (file._data.compressionMethod === compression.magic) {
  1006. result.compressedContent = file._data.getCompressedContent();
  1007. }
  1008. else {
  1009. content = file._data.getContent();
  1010. // need to decompress / recompress
  1011. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content));
  1012. }
  1013. }
  1014. else {
  1015. // have uncompressed data
  1016. content = getBinaryData(file);
  1017. if (!content || content.length === 0 || file.dir) {
  1018. compression = compressions['STORE'];
  1019. content = "";
  1020. }
  1021. result.uncompressedSize = content.length;
  1022. result.crc32 = crc32(content);
  1023. result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content));
  1024. }
  1025. result.compressedSize = result.compressedContent.length;
  1026. result.compressionMethod = compression.magic;
  1027. return result;
  1028. };
  1029. /**
  1030. * Generate the various parts used in the construction of the final zip file.
  1031. * @param {string} name the file name.
  1032. * @param {ZipObject} file the file content.
  1033. * @param {JSZip.CompressedObject} compressedObject the compressed object.
  1034. * @param {number} offset the current offset from the start of the zip file.
  1035. * @return {object} the zip parts.
  1036. */
  1037. var generateZipParts = function(name, file, compressedObject, offset) {
  1038. var data = compressedObject.compressedContent,
  1039. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  1040. comment = file.comment || "",
  1041. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  1042. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  1043. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  1044. o = file.options,
  1045. dosTime,
  1046. dosDate,
  1047. extraFields = "",
  1048. unicodePathExtraField = "",
  1049. unicodeCommentExtraField = "",
  1050. dir, date;
  1051. // handle the deprecated options.dir
  1052. if (file._initialMetadata.dir !== file.dir) {
  1053. dir = file.dir;
  1054. } else {
  1055. dir = o.dir;
  1056. }
  1057. // handle the deprecated options.date
  1058. if(file._initialMetadata.date !== file.date) {
  1059. date = file.date;
  1060. } else {
  1061. date = o.date;
  1062. }
  1063. dosTime = date.getHours();
  1064. dosTime = dosTime << 6;
  1065. dosTime = dosTime | date.getMinutes();
  1066. dosTime = dosTime << 5;
  1067. dosTime = dosTime | date.getSeconds() / 2;
  1068. dosDate = date.getFullYear() - 1980;
  1069. dosDate = dosDate << 4;
  1070. dosDate = dosDate | (date.getMonth() + 1);
  1071. dosDate = dosDate << 5;
  1072. dosDate = dosDate | date.getDate();
  1073. if (useUTF8ForFileName) {
  1074. // set the unicode path extra field. unzip needs at least one extra
  1075. // field to correctly handle unicode path, so using the path is as good
  1076. // as any other information. This could improve the situation with
  1077. // other archive managers too.
  1078. // This field is usually used without the utf8 flag, with a non
  1079. // unicode path in the header (winrar, winzip). This helps (a bit)
  1080. // with the messy Windows' default compressed folders feature but
  1081. // breaks on p7zip which doesn't seek the unicode path extra field.
  1082. // So for now, UTF-8 everywhere !
  1083. unicodePathExtraField =
  1084. // Version
  1085. decToHex(1, 1) +
  1086. // NameCRC32
  1087. decToHex(crc32(utfEncodedFileName), 4) +
  1088. // UnicodeName
  1089. utfEncodedFileName;
  1090. extraFields +=
  1091. // Info-ZIP Unicode Path Extra Field
  1092. "\x75\x70" +
  1093. // size
  1094. decToHex(unicodePathExtraField.length, 2) +
  1095. // content
  1096. unicodePathExtraField;
  1097. }
  1098. if(useUTF8ForComment) {
  1099. unicodeCommentExtraField =
  1100. // Version
  1101. decToHex(1, 1) +
  1102. // CommentCRC32
  1103. decToHex(this.crc32(utfEncodedComment), 4) +
  1104. // UnicodeName
  1105. utfEncodedComment;
  1106. extraFields +=
  1107. // Info-ZIP Unicode Path Extra Field
  1108. "\x75\x63" +
  1109. // size
  1110. decToHex(unicodeCommentExtraField.length, 2) +
  1111. // content
  1112. unicodeCommentExtraField;
  1113. }
  1114. var header = "";
  1115. // version needed to extract
  1116. header += "\x0A\x00";
  1117. // general purpose bit flag
  1118. // set bit 11 if utf8
  1119. header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
  1120. // compression method
  1121. header += compressedObject.compressionMethod;
  1122. // last mod file time
  1123. header += decToHex(dosTime, 2);
  1124. // last mod file date
  1125. header += decToHex(dosDate, 2);
  1126. // crc-32
  1127. header += decToHex(compressedObject.crc32, 4);
  1128. // compressed size
  1129. header += decToHex(compressedObject.compressedSize, 4);
  1130. // uncompressed size
  1131. header += decToHex(compressedObject.uncompressedSize, 4);
  1132. // file name length
  1133. header += decToHex(utfEncodedFileName.length, 2);
  1134. // extra field length
  1135. header += decToHex(extraFields.length, 2);
  1136. var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
  1137. var dirRecord = signature.CENTRAL_FILE_HEADER +
  1138. // version made by (00: DOS)
  1139. "\x14\x00" +
  1140. // file header (common to file and central directory)
  1141. header +
  1142. // file comment length
  1143. decToHex(utfEncodedComment.length, 2) +
  1144. // disk number start
  1145. "\x00\x00" +
  1146. // internal file attributes TODO
  1147. "\x00\x00" +
  1148. // external file attributes
  1149. (dir === true ? "\x10\x00\x00\x00" : "\x00\x00\x00\x00") +
  1150. // relative offset of local header
  1151. decToHex(offset, 4) +
  1152. // file name
  1153. utfEncodedFileName +
  1154. // extra field
  1155. extraFields +
  1156. // file comment
  1157. utfEncodedComment;
  1158. return {
  1159. fileRecord: fileRecord,
  1160. dirRecord: dirRecord,
  1161. compressedObject: compressedObject
  1162. };
  1163. };
  1164. // return the actual prototype of JSZip
  1165. var out = {
  1166. /**
  1167. * Read an existing zip and merge the data in the current JSZip object.
  1168. * The implementation is in jszip-load.js, don't forget to include it.
  1169. * @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
  1170. * @param {Object} options Options for loading the stream.
  1171. * options.base64 : is the stream in base64 ? default : false
  1172. * @return {JSZip} the current JSZip object
  1173. */
  1174. load: function(stream, options) {
  1175. throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
  1176. },
  1177. /**
  1178. * Filter nested files/folders with the specified function.
  1179. * @param {Function} search the predicate to use :
  1180. * function (relativePath, file) {...}
  1181. * It takes 2 arguments : the relative path and the file.
  1182. * @return {Array} An array of matching elements.
  1183. */
  1184. filter: function(search) {
  1185. var result = [],
  1186. filename, relativePath, file, fileClone;
  1187. for (filename in this.files) {
  1188. if (!this.files.hasOwnProperty(filename)) {
  1189. continue;
  1190. }
  1191. file = this.files[filename];
  1192. // return a new object, don't let the user mess with our internal objects :)
  1193. fileClone = new ZipObject(file.name, file._data, extend(file.options));
  1194. relativePath = filename.slice(this.root.length, filename.length);
  1195. if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
  1196. search(relativePath, fileClone)) { // and the file matches the function
  1197. result.push(fileClone);
  1198. }
  1199. }
  1200. return result;
  1201. },
  1202. /**
  1203. * Add a file to the zip file, or search a file.
  1204. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1205. * the name of the file to find (if no data) or a regex to match files.
  1206. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1207. * @param {Object} o File options
  1208. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1209. * a file (when searching by string) or an array of files (when searching by regex).
  1210. */
  1211. file: function(name, data, o) {
  1212. if (arguments.length === 1) {
  1213. if (utils.isRegExp(name)) {
  1214. var regexp = name;
  1215. return this.filter(function(relativePath, file) {
  1216. return !file.dir && regexp.test(relativePath);
  1217. });
  1218. }
  1219. else { // text
  1220. return this.filter(function(relativePath, file) {
  1221. return !file.dir && relativePath === name;
  1222. })[0] || null;
  1223. }
  1224. }
  1225. else { // more than one argument : we have data !
  1226. name = this.root + name;
  1227. fileAdd.call(this, name, data, o);
  1228. }
  1229. return this;
  1230. },
  1231. /**
  1232. * Add a directory to the zip file, or search.
  1233. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1234. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1235. */
  1236. folder: function(arg) {
  1237. if (!arg) {
  1238. return this;
  1239. }
  1240. if (utils.isRegExp(arg)) {
  1241. return this.filter(function(relativePath, file) {
  1242. return file.dir && arg.test(relativePath);
  1243. });
  1244. }
  1245. // else, name is a new folder
  1246. var name = this.root + arg;
  1247. var newFolder = folderAdd.call(this, name);
  1248. // Allow chaining by returning a new object with this folder as the root
  1249. var ret = this.clone();
  1250. ret.root = newFolder.name;
  1251. return ret;
  1252. },
  1253. /**
  1254. * Delete a file, or a directory and all sub-files, from the zip
  1255. * @param {string} name the name of the file to delete
  1256. * @return {JSZip} this JSZip object
  1257. */
  1258. remove: function(name) {
  1259. name = this.root + name;
  1260. var file = this.files[name];
  1261. if (!file) {
  1262. // Look for any folders
  1263. if (name.slice(-1) != "/") {
  1264. name += "/";
  1265. }
  1266. file = this.files[name];
  1267. }
  1268. if (file && !file.dir) {
  1269. // file
  1270. delete this.files[name];
  1271. } else {
  1272. // maybe a folder, delete recursively
  1273. var kids = this.filter(function(relativePath, file) {
  1274. return file.name.slice(0, name.length) === name;
  1275. });
  1276. for (var i = 0; i < kids.length; i++) {
  1277. delete this.files[kids[i].name];
  1278. }
  1279. }
  1280. return this;
  1281. },
  1282. /**
  1283. * Generate the complete zip file
  1284. * @param {Object} options the options to generate the zip file :
  1285. * - base64, (deprecated, use type instead) true to generate base64.
  1286. * - compression, "STORE" by default.
  1287. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1288. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1289. */
  1290. generate: function(options) {
  1291. options = extend(options || {}, {
  1292. base64: true,
  1293. compression: "STORE",
  1294. type: "base64",
  1295. comment: null
  1296. });
  1297. utils.checkSupport(options.type);
  1298. var zipData = [],
  1299. localDirLength = 0,
  1300. centralDirLength = 0,
  1301. writer, i,
  1302. utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
  1303. // first, generate all the zip parts.
  1304. for (var name in this.files) {
  1305. if (!this.files.hasOwnProperty(name)) {
  1306. continue;
  1307. }
  1308. var file = this.files[name];
  1309. var compressionName = file.options.compression || options.compression.toUpperCase();
  1310. var compression = compressions[compressionName];
  1311. if (!compression) {
  1312. throw new Error(compressionName + " is not a valid compression method !");
  1313. }
  1314. var compressedObject = generateCompressedObjectFrom.call(this, file, compression);
  1315. var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength);
  1316. localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
  1317. centralDirLength += zipPart.dirRecord.length;
  1318. zipData.push(zipPart);
  1319. }
  1320. var dirEnd = "";
  1321. // end of central dir signature
  1322. dirEnd = signature.CENTRAL_DIRECTORY_END +
  1323. // number of this disk
  1324. "\x00\x00" +
  1325. // number of the disk with the start of the central directory
  1326. "\x00\x00" +
  1327. // total number of entries in the central directory on this disk
  1328. decToHex(zipData.length, 2) +
  1329. // total number of entries in the central directory
  1330. decToHex(zipData.length, 2) +
  1331. // size of the central directory 4 bytes
  1332. decToHex(centralDirLength, 4) +
  1333. // offset of start of central directory with respect to the starting disk number
  1334. decToHex(localDirLength, 4) +
  1335. // .ZIP file comment length
  1336. decToHex(utfEncodedComment.length, 2) +
  1337. // .ZIP file comment
  1338. utfEncodedComment;
  1339. // we have all the parts (and the total length)
  1340. // time to create a writer !
  1341. var typeName = options.type.toLowerCase();
  1342. if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
  1343. writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
  1344. }else{
  1345. writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
  1346. }
  1347. for (i = 0; i < zipData.length; i++) {
  1348. writer.append(zipData[i].fileRecord);
  1349. writer.append(zipData[i].compressedObject.compressedContent);
  1350. }
  1351. for (i = 0; i < zipData.length; i++) {
  1352. writer.append(zipData[i].dirRecord);
  1353. }
  1354. writer.append(dirEnd);
  1355. var zip = writer.finalize();
  1356. switch(options.type.toLowerCase()) {
  1357. // case "zip is an Uint8Array"
  1358. case "uint8array" :
  1359. case "arraybuffer" :
  1360. case "nodebuffer" :
  1361. return utils.transformTo(options.type.toLowerCase(), zip);
  1362. case "blob" :
  1363. return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip));
  1364. // case "zip is a string"
  1365. case "base64" :
  1366. return (options.base64) ? base64.encode(zip) : zip;
  1367. default : // case "string" :
  1368. return zip;
  1369. }
  1370. },
  1371. /**
  1372. * @deprecated
  1373. * This method will be removed in a future version without replacement.
  1374. */
  1375. crc32: function (input, crc) {
  1376. return crc32(input, crc);
  1377. },
  1378. /**
  1379. * @deprecated
  1380. * This method will be removed in a future version without replacement.
  1381. */
  1382. utf8encode: function (string) {
  1383. return utils.transformTo("string", utf8.utf8encode(string));
  1384. },
  1385. /**
  1386. * @deprecated
  1387. * This method will be removed in a future version without replacement.
  1388. */
  1389. utf8decode: function (input) {
  1390. return utf8.utf8decode(input);
  1391. }
  1392. };
  1393. module.exports = out;
  1394. },{"./base64":1,"./compressedObject":2,"./compressions":3,"./crc32":4,"./defaults":6,"./nodeBuffer":11,"./signature":14,"./stringWriter":16,"./support":17,"./uint8ArrayWriter":19,"./utf8":20,"./utils":21}],14:[function(_dereq_,module,exports){
  1395. 'use strict';
  1396. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  1397. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  1398. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  1399. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  1400. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  1401. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  1402. },{}],15:[function(_dereq_,module,exports){
  1403. 'use strict';
  1404. var DataReader = _dereq_('./dataReader');
  1405. var utils = _dereq_('./utils');
  1406. function StringReader(data, optimizedBinaryString) {
  1407. this.data = data;
  1408. if (!optimizedBinaryString) {
  1409. this.data = utils.string2binary(this.data);
  1410. }
  1411. this.length = this.data.length;
  1412. this.index = 0;
  1413. }
  1414. StringReader.prototype = new DataReader();
  1415. /**
  1416. * @see DataReader.byteAt
  1417. */
  1418. StringReader.prototype.byteAt = function(i) {
  1419. return this.data.charCodeAt(i);
  1420. };
  1421. /**
  1422. * @see DataReader.lastIndexOfSignature
  1423. */
  1424. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1425. return this.data.lastIndexOf(sig);
  1426. };
  1427. /**
  1428. * @see DataReader.readData
  1429. */
  1430. StringReader.prototype.readData = function(size) {
  1431. this.checkOffset(size);
  1432. // this will work because the constructor applied the "& 0xff" mask.
  1433. var result = this.data.slice(this.index, this.index + size);
  1434. this.index += size;
  1435. return result;
  1436. };
  1437. module.exports = StringReader;
  1438. },{"./dataReader":5,"./utils":21}],16:[function(_dereq_,module,exports){
  1439. 'use strict';
  1440. var utils = _dereq_('./utils');
  1441. /**
  1442. * An object to write any content to a string.
  1443. * @constructor
  1444. */
  1445. var StringWriter = function() {
  1446. this.data = [];
  1447. };
  1448. StringWriter.prototype = {
  1449. /**
  1450. * Append any content to the current string.
  1451. * @param {Object} input the content to add.
  1452. */
  1453. append: function(input) {
  1454. input = utils.transformTo("string", input);
  1455. this.data.push(input);
  1456. },
  1457. /**
  1458. * Finalize the construction an return the result.
  1459. * @return {string} the generated string.
  1460. */
  1461. finalize: function() {
  1462. return this.data.join("");
  1463. }
  1464. };
  1465. module.exports = StringWriter;
  1466. },{"./utils":21}],17:[function(_dereq_,module,exports){
  1467. (function (Buffer){
  1468. 'use strict';
  1469. exports.base64 = true;
  1470. exports.array = true;
  1471. exports.string = true;
  1472. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  1473. // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
  1474. // Browserify will provide a Buffer implementation for browsers, which is
  1475. // an augmented Uint8Array (i.e., can be used as either Buffer or U8).
  1476. exports.nodebuffer = typeof Buffer !== "undefined";
  1477. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  1478. exports.uint8array = typeof Uint8Array !== "undefined";
  1479. if (typeof ArrayBuffer === "undefined") {
  1480. exports.blob = false;
  1481. }
  1482. else {
  1483. var buffer = new ArrayBuffer(0);
  1484. try {
  1485. exports.blob = new Blob([buffer], {
  1486. type: "application/zip"
  1487. }).size === 0;
  1488. }
  1489. catch (e) {
  1490. try {
  1491. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  1492. var builder = new Builder();
  1493. builder.append(buffer);
  1494. exports.blob = builder.getBlob('application/zip').size === 0;
  1495. }
  1496. catch (e) {
  1497. exports.blob = false;
  1498. }
  1499. }
  1500. }
  1501. }).call(this,(typeof Buffer !== "undefined" ? Buffer : undefined))
  1502. },{}],18:[function(_dereq_,module,exports){
  1503. 'use strict';
  1504. var DataReader = _dereq_('./dataReader');
  1505. function Uint8ArrayReader(data) {
  1506. if (data) {
  1507. this.data = data;
  1508. this.length = this.data.length;
  1509. this.index = 0;
  1510. }
  1511. }
  1512. Uint8ArrayReader.prototype = new DataReader();
  1513. /**
  1514. * @see DataReader.byteAt
  1515. */
  1516. Uint8ArrayReader.prototype.byteAt = function(i) {
  1517. return this.data[i];
  1518. };
  1519. /**
  1520. * @see DataReader.lastIndexOfSignature
  1521. */
  1522. Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1523. var sig0 = sig.charCodeAt(0),
  1524. sig1 = sig.charCodeAt(1),
  1525. sig2 = sig.charCodeAt(2),
  1526. sig3 = sig.charCodeAt(3);
  1527. for (var i = this.length - 4; i >= 0; --i) {
  1528. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1529. return i;
  1530. }
  1531. }
  1532. return -1;
  1533. };
  1534. /**
  1535. * @see DataReader.readData
  1536. */
  1537. Uint8ArrayReader.prototype.readData = function(size) {
  1538. this.checkOffset(size);
  1539. if(size === 0) {
  1540. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1541. return new Uint8Array(0);
  1542. }
  1543. var result = this.data.subarray(this.index, this.index + size);
  1544. this.index += size;
  1545. return result;
  1546. };
  1547. module.exports = Uint8ArrayReader;
  1548. },{"./dataReader":5}],19:[function(_dereq_,module,exports){
  1549. 'use strict';
  1550. var utils = _dereq_('./utils');
  1551. /**
  1552. * An object to write any content to an Uint8Array.
  1553. * @constructor
  1554. * @param {number} length The length of the array.
  1555. */
  1556. var Uint8ArrayWriter = function(length) {
  1557. this.data = new Uint8Array(length);
  1558. this.index = 0;
  1559. };
  1560. Uint8ArrayWriter.prototype = {
  1561. /**
  1562. * Append any content to the current array.
  1563. * @param {Object} input the content to add.
  1564. */
  1565. append: function(input) {
  1566. if (input.length !== 0) {
  1567. // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
  1568. input = utils.transformTo("uint8array", input);
  1569. this.data.set(input, this.index);
  1570. this.index += input.length;
  1571. }
  1572. },
  1573. /**
  1574. * Finalize the construction an return the result.
  1575. * @return {Uint8Array} the generated array.
  1576. */
  1577. finalize: function() {
  1578. return this.data;
  1579. }
  1580. };
  1581. module.exports = Uint8ArrayWriter;
  1582. },{"./utils":21}],20:[function(_dereq_,module,exports){
  1583. 'use strict';
  1584. var utils = _dereq_('./utils');
  1585. var support = _dereq_('./support');
  1586. var nodeBuffer = _dereq_('./nodeBuffer');
  1587. /**
  1588. * The following functions come from pako, from pako/lib/utils/strings
  1589. * released under the MIT license, see pako https://github.com/nodeca/pako/
  1590. */
  1591. // Table with utf8 lengths (calculated by first byte of sequence)
  1592. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  1593. // because max possible codepoint is 0x10ffff
  1594. var _utf8len = new Array(256);
  1595. for (var i=0; i<256; i++) {
  1596. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  1597. }
  1598. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  1599. // convert string to array (typed, when possible)
  1600. var string2buf = function (str) {
  1601. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  1602. // count binary size
  1603. for (m_pos = 0; m_pos < str_len; m_pos++) {
  1604. c = str.charCodeAt(m_pos);
  1605. if (((c & 0xfc00) === 0xd800) && (m_pos+1 < str_len)) {
  1606. c2 = str.charCodeAt(m_pos+1);
  1607. if ((c2 & 0xfc00) === 0xdc00) {
  1608. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1609. m_pos++;
  1610. }
  1611. }
  1612. buf_len += (c < 0x80) ? 1 : ((c < 0x800) ? 2 : ((c < 0x10000) ? 3 : 4));
  1613. }
  1614. // allocate buffer
  1615. if (support.uint8array) {
  1616. buf = new Uint8Array(buf_len);
  1617. } else {
  1618. buf = new Array(buf_len);
  1619. }
  1620. // convert
  1621. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  1622. c = str.charCodeAt(m_pos);
  1623. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  1624. c2 = str.charCodeAt(m_pos+1);
  1625. if ((c2 & 0xfc00) === 0xdc00) {
  1626. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  1627. m_pos++;
  1628. }
  1629. }
  1630. if (c < 0x80) {
  1631. /* one byte */
  1632. buf[i++] = c;
  1633. } else if (c < 0x800) {
  1634. /* two bytes */
  1635. buf[i++] = 0xC0 | (c >>> 6);
  1636. buf[i++] = 0x80 | (c & 0x3f);
  1637. } else if (c < 0x10000) {
  1638. /* three bytes */
  1639. buf[i++] = 0xE0 | (c >>> 12);
  1640. buf[i++] = 0x80 | ((c >>> 6) & 0x3f);
  1641. buf[i++] = 0x80 | (c & 0x3f);
  1642. } else {
  1643. /* four bytes */
  1644. buf[i++] = 0xf0 | (c >>> 18);
  1645. buf[i++] = 0x80 | ((c >>> 12) & 0x3f);
  1646. buf[i++] = 0x80 | ((c >>> 6) & 0x3f);
  1647. buf[i++] = 0x80 | (c & 0x3f);
  1648. }
  1649. }
  1650. return buf;
  1651. };
  1652. // Calculate max possible position in utf8 buffer,
  1653. // that will not break sequence. If that's not possible
  1654. // - (very small limits) return max size as is.
  1655. //
  1656. // buf[] - utf8 bytes array
  1657. // max - length limit (mandatory);
  1658. var utf8border = function(buf, max) {
  1659. var pos;
  1660. max = max || buf.length;
  1661. if (max > buf.length) { max = buf.length; }
  1662. // go back from last position, until start of sequence found
  1663. pos = max-1;
  1664. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  1665. // Fuckup - very small and broken sequence,
  1666. // return max, because we should return something anyway.
  1667. if (pos < 0) { return max; }
  1668. // If we came to start of buffer - that means vuffer is too small,
  1669. // return max too.
  1670. if (pos === 0) { return max; }
  1671. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  1672. };
  1673. // convert array to string
  1674. var buf2string = function (buf) {
  1675. var str, i, out, c, c_len;
  1676. var len = buf.length;
  1677. // Reserve max possible length (2 words per char)
  1678. // NB: by unknown reasons, Array is significantly faster for
  1679. // String.fromCharCode.apply than Uint16Array.
  1680. var utf16buf = new Array(len*2);
  1681. for (out=0, i=0; i<len;) {
  1682. c = buf[i++];
  1683. // quick process ascii
  1684. if (c < 0x80) { utf16buf[out++] = c; continue; }
  1685. c_len = _utf8len[c];
  1686. // skip 5 & 6 byte codes
  1687. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  1688. // apply mask on first byte
  1689. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  1690. // join the rest
  1691. while (c_len > 1 && i < len) {
  1692. c = (c << 6) | (buf[i++] & 0x3f);
  1693. c_len--;
  1694. }
  1695. // terminated by end of string?
  1696. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  1697. if (c < 0x10000) {
  1698. utf16buf[out++] = c;
  1699. } else {
  1700. c -= 0x10000;
  1701. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  1702. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  1703. }
  1704. }
  1705. // shrinkBuf(utf16buf, out)
  1706. if (utf16buf.length !== out) {
  1707. if(utf16buf.subarray) {
  1708. utf16buf = utf16buf.subarray(0, out);
  1709. } else {
  1710. utf16buf.length = out;
  1711. }
  1712. }
  1713. // return String.fromCharCode.apply(null, utf16buf);
  1714. return utils.applyFromCharCode(utf16buf);
  1715. };
  1716. // That's all for the pako functions.
  1717. /**
  1718. * Transform a javascript string into an array (typed if possible) of bytes,
  1719. * UTF-8 encoded.
  1720. * @param {String} str the string to encode
  1721. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  1722. */
  1723. exports.utf8encode = function utf8encode(str) {
  1724. if (support.nodebuffer) {
  1725. return nodeBuffer(str, "utf-8");
  1726. }
  1727. return string2buf(str);
  1728. };
  1729. /**
  1730. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  1731. * string into a javascript string.
  1732. * @param {Array|Uint8Array|Buffer} buf the data de decode
  1733. * @return {String} the decoded string.
  1734. */
  1735. exports.utf8decode = function utf8decode(buf) {
  1736. if (support.nodebuffer) {
  1737. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  1738. }
  1739. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  1740. // return buf2string(buf);
  1741. // Chrome prefers to work with "small" chunks of data
  1742. // for the method buf2string.
  1743. // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
  1744. var result = [], k = 0, len = buf.length, chunk = 65536;
  1745. while (k < len) {
  1746. var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
  1747. if (support.uint8array) {
  1748. result.push(buf2string(buf.subarray(k, nextBoundary)));
  1749. } else {
  1750. result.push(buf2string(buf.slice(k, nextBoundary)));
  1751. }
  1752. k = nextBoundary;
  1753. }
  1754. return result.join("");
  1755. };
  1756. // vim: set shiftwidth=4 softtabstop=4:
  1757. },{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(_dereq_,module,exports){
  1758. 'use strict';
  1759. var support = _dereq_('./support');
  1760. var compressions = _dereq_('./compressions');
  1761. var nodeBuffer = _dereq_('./nodeBuffer');
  1762. /**
  1763. * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
  1764. * @param {string} str the string to transform.
  1765. * @return {String} the binary string.
  1766. */
  1767. exports.string2binary = function(str) {
  1768. var result = "";
  1769. for (var i = 0; i < str.length; i++) {
  1770. result += String.fromCharCode(str.charCodeAt(i) & 0xff);
  1771. }
  1772. return result;
  1773. };
  1774. exports.arrayBuffer2Blob = function(buffer) {
  1775. exports.checkSupport("blob");
  1776. try {
  1777. // Blob constructor
  1778. return new Blob([buffer], {
  1779. type: "application/zip"
  1780. });
  1781. }
  1782. catch (e) {
  1783. try {
  1784. // deprecated, browser only, old way
  1785. var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  1786. var builder = new Builder();
  1787. builder.append(buffer);
  1788. return builder.getBlob('application/zip');
  1789. }
  1790. catch (e) {
  1791. // well, fuck ?!
  1792. throw new Error("Bug : can't construct the Blob.");
  1793. }
  1794. }
  1795. };
  1796. /**
  1797. * The identity function.
  1798. * @param {Object} input the input.
  1799. * @return {Object} the same input.
  1800. */
  1801. function identity(input) {
  1802. return input;
  1803. }
  1804. /**
  1805. * Fill in an array with a string.
  1806. * @param {String} str the string to use.
  1807. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  1808. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  1809. */
  1810. function stringToArrayLike(str, array) {
  1811. for (var i = 0; i < str.length; ++i) {
  1812. array[i] = str.charCodeAt(i) & 0xFF;
  1813. }
  1814. return array;
  1815. }
  1816. /**
  1817. * Transform an array-like object to a string.
  1818. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  1819. * @return {String} the result.
  1820. */
  1821. function arrayLikeToString(array) {
  1822. // Performances notes :
  1823. // --------------------
  1824. // String.fromCharCode.apply(null, array) is the fastest, see
  1825. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  1826. // but the stack is limited (and we can get huge arrays !).
  1827. //
  1828. // result += String.fromCharCode(array[i]); generate too many strings !
  1829. //
  1830. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  1831. var chunk = 65536;
  1832. var result = [],
  1833. len = array.length,
  1834. type = exports.getTypeOf(array),
  1835. k = 0,
  1836. canUseApply = true;
  1837. try {
  1838. switch(type) {
  1839. case "uint8array":
  1840. String.fromCharCode.apply(null, new Uint8Array(0));
  1841. break;
  1842. case "nodebuffer":
  1843. String.fromCharCode.apply(null, nodeBuffer(0));
  1844. break;
  1845. }
  1846. } catch(e) {
  1847. canUseApply = false;
  1848. }
  1849. // no apply : slow and painful algorithm
  1850. // default browser on android 4.*
  1851. if (!canUseApply) {
  1852. var resultStr = "";
  1853. for(var i = 0; i < array.length;i++) {
  1854. resultStr += String.fromCharCode(array[i]);
  1855. }
  1856. return resultStr;
  1857. }
  1858. while (k < len && chunk > 1) {
  1859. try {
  1860. if (type === "array" || type === "nodebuffer") {
  1861. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  1862. }
  1863. else {
  1864. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  1865. }
  1866. k += chunk;
  1867. }
  1868. catch (e) {
  1869. chunk = Math.floor(chunk / 2);
  1870. }
  1871. }
  1872. return result.join("");
  1873. }
  1874. exports.applyFromCharCode = arrayLikeToString;
  1875. /**
  1876. * Copy the data from an array-like to an other array-like.
  1877. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  1878. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  1879. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  1880. */
  1881. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  1882. for (var i = 0; i < arrayFrom.length; i++) {
  1883. arrayTo[i] = arrayFrom[i];
  1884. }
  1885. return arrayTo;
  1886. }
  1887. // a matrix containing functions to transform everything into everything.
  1888. var transform = {};
  1889. // string to ?
  1890. transform["string"] = {
  1891. "string": identity,
  1892. "array": function(input) {
  1893. return stringToArrayLike(input, new Array(input.length));
  1894. },
  1895. "arraybuffer": function(input) {
  1896. return transform["string"]["uint8array"](input).buffer;
  1897. },
  1898. "uint8array": function(input) {
  1899. return stringToArrayLike(input, new Uint8Array(input.length));
  1900. },
  1901. "nodebuffer": function(input) {
  1902. return stringToArrayLike(input, nodeBuffer(input.length));
  1903. }
  1904. };
  1905. // array to ?
  1906. transform["array"] = {
  1907. "string": arrayLikeToString,
  1908. "array": identity,
  1909. "arraybuffer": function(input) {
  1910. return (new Uint8Array(input)).buffer;
  1911. },
  1912. "uint8array": function(input) {
  1913. return new Uint8Array(input);
  1914. },
  1915. "nodebuffer": function(input) {
  1916. return nodeBuffer(input);
  1917. }
  1918. };
  1919. // arraybuffer to ?
  1920. transform["arraybuffer"] = {
  1921. "string": function(input) {
  1922. return arrayLikeToString(new Uint8Array(input));
  1923. },
  1924. "array": function(input) {
  1925. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  1926. },
  1927. "arraybuffer": identity,
  1928. "uint8array": function(input) {
  1929. return new Uint8Array(input);
  1930. },
  1931. "nodebuffer": function(input) {
  1932. return nodeBuffer(new Uint8Array(input));
  1933. }
  1934. };
  1935. // uint8array to ?
  1936. transform["uint8array"] = {
  1937. "string": arrayLikeToString,
  1938. "array": function(input) {
  1939. return arrayLikeToArrayLike(input, new Array(input.length));
  1940. },
  1941. "arraybuffer": function(input) {
  1942. return input.buffer;
  1943. },
  1944. "uint8array": identity,
  1945. "nodebuffer": function(input) {
  1946. return nodeBuffer(input);
  1947. }
  1948. };
  1949. // nodebuffer to ?
  1950. transform["nodebuffer"] = {
  1951. "string": arrayLikeToString,
  1952. "array": function(input) {
  1953. return arrayLikeToArrayLike(input, new Array(input.length));
  1954. },
  1955. "arraybuffer": function(input) {
  1956. return transform["nodebuffer"]["uint8array"](input).buffer;
  1957. },
  1958. "uint8array": function(input) {
  1959. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  1960. },
  1961. "nodebuffer": identity
  1962. };
  1963. /**
  1964. * Transform an input into any type.
  1965. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  1966. * If no output type is specified, the unmodified input will be returned.
  1967. * @param {String} outputType the output type.
  1968. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  1969. * @throws {Error} an Error if the browser doesn't support the requested output type.
  1970. */
  1971. exports.transformTo = function(outputType, input) {
  1972. if (!input) {
  1973. // undefined, null, etc
  1974. // an empty string won't harm.
  1975. input = "";
  1976. }
  1977. if (!outputType) {
  1978. return input;
  1979. }
  1980. exports.checkSupport(outputType);
  1981. var inputType = exports.getTypeOf(input);
  1982. var result = transform[inputType][outputType](input);
  1983. return result;
  1984. };
  1985. /**
  1986. * Return the type of the input.
  1987. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  1988. * @param {Object} input the input to identify.
  1989. * @return {String} the (lowercase) type of the input.
  1990. */
  1991. exports.getTypeOf = function(input) {
  1992. if (typeof input === "string") {
  1993. return "string";
  1994. }
  1995. if (Object.prototype.toString.call(input) === "[object Array]") {
  1996. return "array";
  1997. }
  1998. if (support.nodebuffer && nodeBuffer.test(input)) {
  1999. return "nodebuffer";
  2000. }
  2001. if (support.uint8array && input instanceof Uint8Array) {
  2002. return "uint8array";
  2003. }
  2004. if (support.arraybuffer && input instanceof ArrayBuffer) {
  2005. return "arraybuffer";
  2006. }
  2007. };
  2008. /**
  2009. * Throw an exception if the type is not supported.
  2010. * @param {String} type the type to check.
  2011. * @throws {Error} an Error if the browser doesn't support the requested type.
  2012. */
  2013. exports.checkSupport = function(type) {
  2014. var supported = support[type.toLowerCase()];
  2015. if (!supported) {
  2016. throw new Error(type + " is not supported by this browser");
  2017. }
  2018. };
  2019. exports.MAX_VALUE_16BITS = 65535;
  2020. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  2021. /**
  2022. * Prettify a string read as binary.
  2023. * @param {string} str the string to prettify.
  2024. * @return {string} a pretty string.
  2025. */
  2026. exports.pretty = function(str) {
  2027. var res = '',
  2028. code, i;
  2029. for (i = 0; i < (str || "").length; i++) {
  2030. code = str.charCodeAt(i);
  2031. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  2032. }
  2033. return res;
  2034. };
  2035. /**
  2036. * Find a compression registered in JSZip.
  2037. * @param {string} compressionMethod the method magic to find.
  2038. * @return {Object|null} the JSZip compression object, null if none found.
  2039. */
  2040. exports.findCompression = function(compressionMethod) {
  2041. for (var method in compressions) {
  2042. if (!compressions.hasOwnProperty(method)) {
  2043. continue;
  2044. }
  2045. if (compressions[method].magic === compressionMethod) {
  2046. return compressions[method];
  2047. }
  2048. }
  2049. return null;
  2050. };
  2051. /**
  2052. * Cross-window, cross-Node-context regular expression detection
  2053. * @param {Object} object Anything
  2054. * @return {Boolean} true if the object is a regular expression,
  2055. * false otherwise
  2056. */
  2057. exports.isRegExp = function (object) {
  2058. return Object.prototype.toString.call(object) === "[object RegExp]";
  2059. };
  2060. },{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(_dereq_,module,exports){
  2061. 'use strict';
  2062. var StringReader = _dereq_('./stringReader');
  2063. var NodeBufferReader = _dereq_('./nodeBufferReader');
  2064. var Uint8ArrayReader = _dereq_('./uint8ArrayReader');
  2065. var utils = _dereq_('./utils');
  2066. var sig = _dereq_('./signature');
  2067. var ZipEntry = _dereq_('./zipEntry');
  2068. var support = _dereq_('./support');
  2069. var jszipProto = _dereq_('./object');
  2070. // class ZipEntries {{{
  2071. /**
  2072. * All the entries in the zip file.
  2073. * @constructor
  2074. * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
  2075. * @param {Object} loadOptions Options for loading the stream.
  2076. */
  2077. function ZipEntries(data, loadOptions) {
  2078. this.files = [];
  2079. this.loadOptions = loadOptions;
  2080. if (data) {
  2081. this.load(data);
  2082. }
  2083. }
  2084. ZipEntries.prototype = {
  2085. /**
  2086. * Check that the reader is on the speficied signature.
  2087. * @param {string} expectedSignature the expected signature.
  2088. * @throws {Error} if it is an other signature.
  2089. */
  2090. checkSignature: function(expectedSignature) {
  2091. var signature = this.reader.readString(4);
  2092. if (signature !== expectedSignature) {
  2093. throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  2094. }
  2095. },
  2096. /**
  2097. * Read the end of the central directory.
  2098. */
  2099. readBlockEndOfCentral: function() {
  2100. this.diskNumber = this.reader.readInt(2);
  2101. this.diskWithCentralDirStart = this.reader.readInt(2);
  2102. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  2103. this.centralDirRecords = this.reader.readInt(2);
  2104. this.centralDirSize = this.reader.readInt(4);
  2105. this.centralDirOffset = this.reader.readInt(4);
  2106. this.zipCommentLength = this.reader.readInt(2);
  2107. // warning : the encoding depends of the system locale
  2108. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  2109. // On a windows machine, this field is encoded with the localized windows code page.
  2110. this.zipComment = this.reader.readString(this.zipCommentLength);
  2111. // To get consistent behavior with the generation part, we will assume that
  2112. // this is utf8 encoded.
  2113. this.zipComment = jszipProto.utf8decode(this.zipComment);
  2114. },
  2115. /**
  2116. * Read the end of the Zip 64 central directory.
  2117. * Not merged with the method readEndOfCentral :
  2118. * The end of central can coexist with its Zip64 brother,
  2119. * I don't want to read the wrong number of bytes !
  2120. */
  2121. readBlockZip64EndOfCentral: function() {
  2122. this.zip64EndOfCentralSize = this.reader.readInt(8);
  2123. this.versionMadeBy = this.reader.readString(2);
  2124. this.versionNeeded = this.reader.readInt(2);
  2125. this.diskNumber = this.reader.readInt(4);
  2126. this.diskWithCentralDirStart = this.reader.readInt(4);
  2127. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  2128. this.centralDirRecords = this.reader.readInt(8);
  2129. this.centralDirSize = this.reader.readInt(8);
  2130. this.centralDirOffset = this.reader.readInt(8);
  2131. this.zip64ExtensibleData = {};
  2132. var extraDataSize = this.zip64EndOfCentralSize - 44,
  2133. index = 0,
  2134. extraFieldId,
  2135. extraFieldLength,
  2136. extraFieldValue;
  2137. while (index < extraDataSize) {
  2138. extraFieldId = this.reader.readInt(2);
  2139. extraFieldLength = this.reader.readInt(4);
  2140. extraFieldValue = this.reader.readString(extraFieldLength);
  2141. this.zip64ExtensibleData[extraFieldId] = {
  2142. id: extraFieldId,
  2143. length: extraFieldLength,
  2144. value: extraFieldValue
  2145. };
  2146. }
  2147. },
  2148. /**
  2149. * Read the end of the Zip 64 central directory locator.
  2150. */
  2151. readBlockZip64EndOfCentralLocator: function() {
  2152. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  2153. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  2154. this.disksCount = this.reader.readInt(4);
  2155. if (this.disksCount > 1) {
  2156. throw new Error("Multi-volumes zip are not supported");
  2157. }
  2158. },
  2159. /**
  2160. * Read the local files, based on the offset read in the central part.
  2161. */
  2162. readLocalFiles: function() {
  2163. var i, file;
  2164. for (i = 0; i < this.files.length; i++) {
  2165. file = this.files[i];
  2166. this.reader.setIndex(file.localHeaderOffset);
  2167. this.checkSignature(sig.LOCAL_FILE_HEADER);
  2168. file.readLocalPart(this.reader);
  2169. file.handleUTF8();
  2170. }
  2171. },
  2172. /**
  2173. * Read the central directory.
  2174. */
  2175. readCentralDir: function() {
  2176. var file;
  2177. this.reader.setIndex(this.centralDirOffset);
  2178. while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
  2179. file = new ZipEntry({
  2180. zip64: this.zip64
  2181. }, this.loadOptions);
  2182. file.readCentralPart(this.reader);
  2183. this.files.push(file);
  2184. }
  2185. },
  2186. /**
  2187. * Read the end of central directory.
  2188. */
  2189. readEndOfCentral: function() {
  2190. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  2191. if (offset === -1) {
  2192. throw new Error("Corrupted zip : can't find end of central directory");
  2193. }
  2194. this.reader.setIndex(offset);
  2195. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  2196. this.readBlockEndOfCentral();
  2197. /* extract from the zip spec :
  2198. 4) If one of the fields in the end of central directory
  2199. record is too small to hold required data, the field
  2200. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  2201. ZIP64 format record should be created.
  2202. 5) The end of central directory record and the
  2203. Zip64 end of central directory locator record must
  2204. reside on the same disk when splitting or spanning
  2205. an archive.
  2206. */
  2207. 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) {
  2208. this.zip64 = true;
  2209. /*
  2210. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  2211. the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
  2212. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  2213. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  2214. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  2215. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  2216. */
  2217. // should look for a zip64 EOCD locator
  2218. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2219. if (offset === -1) {
  2220. throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
  2221. }
  2222. this.reader.setIndex(offset);
  2223. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  2224. this.readBlockZip64EndOfCentralLocator();
  2225. // now the zip64 EOCD record
  2226. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  2227. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  2228. this.readBlockZip64EndOfCentral();
  2229. }
  2230. },
  2231. prepareReader: function(data) {
  2232. var type = utils.getTypeOf(data);
  2233. if (type === "string" && !support.uint8array) {
  2234. this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
  2235. }
  2236. else if (type === "nodebuffer") {
  2237. this.reader = new NodeBufferReader(data);
  2238. }
  2239. else {
  2240. this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
  2241. }
  2242. },
  2243. /**
  2244. * Read a zip file and create ZipEntries.
  2245. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  2246. */
  2247. load: function(data) {
  2248. this.prepareReader(data);
  2249. this.readEndOfCentral();
  2250. this.readCentralDir();
  2251. this.readLocalFiles();
  2252. }
  2253. };
  2254. // }}} end of ZipEntries
  2255. module.exports = ZipEntries;
  2256. },{"./nodeBufferReader":12,"./object":13,"./signature":14,"./stringReader":15,"./support":17,"./uint8ArrayReader":18,"./utils":21,"./zipEntry":23}],23:[function(_dereq_,module,exports){
  2257. 'use strict';
  2258. var StringReader = _dereq_('./stringReader');
  2259. var utils = _dereq_('./utils');
  2260. var CompressedObject = _dereq_('./compressedObject');
  2261. var jszipProto = _dereq_('./object');
  2262. // class ZipEntry {{{
  2263. /**
  2264. * An entry in the zip file.
  2265. * @constructor
  2266. * @param {Object} options Options of the current file.
  2267. * @param {Object} loadOptions Options for loading the stream.
  2268. */
  2269. function ZipEntry(options, loadOptions) {
  2270. this.options = options;
  2271. this.loadOptions = loadOptions;
  2272. }
  2273. ZipEntry.prototype = {
  2274. /**
  2275. * say if the file is encrypted.
  2276. * @return {boolean} true if the file is encrypted, false otherwise.
  2277. */
  2278. isEncrypted: function() {
  2279. // bit 1 is set
  2280. return (this.bitFlag & 0x0001) === 0x0001;
  2281. },
  2282. /**
  2283. * say if the file has utf-8 filename/comment.
  2284. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  2285. */
  2286. useUTF8: function() {
  2287. // bit 11 is set
  2288. return (this.bitFlag & 0x0800) === 0x0800;
  2289. },
  2290. /**
  2291. * Prepare the function used to generate the compressed content from this ZipFile.
  2292. * @param {DataReader} reader the reader to use.
  2293. * @param {number} from the offset from where we should read the data.
  2294. * @param {number} length the length of the data to read.
  2295. * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
  2296. */
  2297. prepareCompressedContent: function(reader, from, length) {
  2298. return function() {
  2299. var previousIndex = reader.index;
  2300. reader.setIndex(from);
  2301. var compressedFileData = reader.readData(length);
  2302. reader.setIndex(previousIndex);
  2303. return compressedFileData;
  2304. };
  2305. },
  2306. /**
  2307. * Prepare the function used to generate the uncompressed content from this ZipFile.
  2308. * @param {DataReader} reader the reader to use.
  2309. * @param {number} from the offset from where we should read the data.
  2310. * @param {number} length the length of the data to read.
  2311. * @param {JSZip.compression} compression the compression used on this file.
  2312. * @param {number} uncompressedSize the uncompressed size to expect.
  2313. * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
  2314. */
  2315. prepareContent: function(reader, from, length, compression, uncompressedSize) {
  2316. return function() {
  2317. var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
  2318. var uncompressedFileData = compression.uncompress(compressedFileData);
  2319. if (uncompressedFileData.length !== uncompressedSize) {
  2320. throw new Error("Bug : uncompressed data size mismatch");
  2321. }
  2322. return uncompressedFileData;
  2323. };
  2324. },
  2325. /**
  2326. * Read the local part of a zip file and add the info in this object.
  2327. * @param {DataReader} reader the reader to use.
  2328. */
  2329. readLocalPart: function(reader) {
  2330. var compression, localExtraFieldsLength;
  2331. // we already know everything from the central dir !
  2332. // If the central dir data are false, we are doomed.
  2333. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  2334. // The less data we get here, the more reliable this should be.
  2335. // Let's skip the whole header and dash to the data !
  2336. reader.skip(22);
  2337. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  2338. // Strangely, the filename here is OK.
  2339. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  2340. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  2341. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  2342. // the internet.
  2343. //
  2344. // I think I see the logic here : the central directory is used to display
  2345. // content and the local directory is used to extract the files. Mixing / and \
  2346. // may be used to display \ to windows users and use / when extracting the files.
  2347. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  2348. this.fileNameLength = reader.readInt(2);
  2349. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  2350. this.fileName = reader.readString(this.fileNameLength);
  2351. reader.skip(localExtraFieldsLength);
  2352. if (this.compressedSize == -1 || this.uncompressedSize == -1) {
  2353. throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
  2354. }
  2355. compression = utils.findCompression(this.compressionMethod);
  2356. if (compression === null) { // no compression found
  2357. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
  2358. }
  2359. this.decompressed = new CompressedObject();
  2360. this.decompressed.compressedSize = this.compressedSize;
  2361. this.decompressed.uncompressedSize = this.uncompressedSize;
  2362. this.decompressed.crc32 = this.crc32;
  2363. this.decompressed.compressionMethod = this.compressionMethod;
  2364. this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
  2365. this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
  2366. // we need to compute the crc32...
  2367. if (this.loadOptions.checkCRC32) {
  2368. this.decompressed = utils.transformTo("string", this.decompressed.getContent());
  2369. if (jszipProto.crc32(this.decompressed) !== this.crc32) {
  2370. throw new Error("Corrupted zip : CRC32 mismatch");
  2371. }
  2372. }
  2373. },
  2374. /**
  2375. * Read the central part of a zip file and add the info in this object.
  2376. * @param {DataReader} reader the reader to use.
  2377. */
  2378. readCentralPart: function(reader) {
  2379. this.versionMadeBy = reader.readString(2);
  2380. this.versionNeeded = reader.readInt(2);
  2381. this.bitFlag = reader.readInt(2);
  2382. this.compressionMethod = reader.readString(2);
  2383. this.date = reader.readDate();
  2384. this.crc32 = reader.readInt(4);
  2385. this.compressedSize = reader.readInt(4);
  2386. this.uncompressedSize = reader.readInt(4);
  2387. this.fileNameLength = reader.readInt(2);
  2388. this.extraFieldsLength = reader.readInt(2);
  2389. this.fileCommentLength = reader.readInt(2);
  2390. this.diskNumberStart = reader.readInt(2);
  2391. this.internalFileAttributes = reader.readInt(2);
  2392. this.externalFileAttributes = reader.readInt(4);
  2393. this.localHeaderOffset = reader.readInt(4);
  2394. if (this.isEncrypted()) {
  2395. throw new Error("Encrypted zip are not supported");
  2396. }
  2397. this.fileName = reader.readString(this.fileNameLength);
  2398. this.readExtraFields(reader);
  2399. this.parseZIP64ExtraField(reader);
  2400. this.fileComment = reader.readString(this.fileCommentLength);
  2401. // warning, this is true only for zip with madeBy == DOS (plateform dependent feature)
  2402. this.dir = this.externalFileAttributes & 0x00000010 ? true : false;
  2403. },
  2404. /**
  2405. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  2406. * @param {DataReader} reader the reader to use.
  2407. */
  2408. parseZIP64ExtraField: function(reader) {
  2409. if (!this.extraFields[0x0001]) {
  2410. return;
  2411. }
  2412. // should be something, preparing the extra reader
  2413. var extraReader = new StringReader(this.extraFields[0x0001].value);
  2414. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  2415. // won't let us have more.
  2416. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  2417. this.uncompressedSize = extraReader.readInt(8);
  2418. }
  2419. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  2420. this.compressedSize = extraReader.readInt(8);
  2421. }
  2422. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  2423. this.localHeaderOffset = extraReader.readInt(8);
  2424. }
  2425. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  2426. this.diskNumberStart = extraReader.readInt(4);
  2427. }
  2428. },
  2429. /**
  2430. * Read the central part of a zip file and add the info in this object.
  2431. * @param {DataReader} reader the reader to use.
  2432. */
  2433. readExtraFields: function(reader) {
  2434. var start = reader.index,
  2435. extraFieldId,
  2436. extraFieldLength,
  2437. extraFieldValue;
  2438. this.extraFields = this.extraFields || {};
  2439. while (reader.index < start + this.extraFieldsLength) {
  2440. extraFieldId = reader.readInt(2);
  2441. extraFieldLength = reader.readInt(2);
  2442. extraFieldValue = reader.readString(extraFieldLength);
  2443. this.extraFields[extraFieldId] = {
  2444. id: extraFieldId,
  2445. length: extraFieldLength,
  2446. value: extraFieldValue
  2447. };
  2448. }
  2449. },
  2450. /**
  2451. * Apply an UTF8 transformation if needed.
  2452. */
  2453. handleUTF8: function() {
  2454. if (this.useUTF8()) {
  2455. this.fileName = jszipProto.utf8decode(this.fileName);
  2456. this.fileComment = jszipProto.utf8decode(this.fileComment);
  2457. } else {
  2458. var upath = this.findExtraFieldUnicodePath();
  2459. if (upath !== null) {
  2460. this.fileName = upath;
  2461. }
  2462. var ucomment = this.findExtraFieldUnicodeComment();
  2463. if (ucomment !== null) {
  2464. this.fileComment = ucomment;
  2465. }
  2466. }
  2467. },
  2468. /**
  2469. * Find the unicode path declared in the extra field, if any.
  2470. * @return {String} the unicode path, null otherwise.
  2471. */
  2472. findExtraFieldUnicodePath: function() {
  2473. var upathField = this.extraFields[0x7075];
  2474. if (upathField) {
  2475. var extraReader = new StringReader(upathField.value);
  2476. // wrong version
  2477. if (extraReader.readInt(1) !== 1) {
  2478. return null;
  2479. }
  2480. // the crc of the filename changed, this field is out of date.
  2481. if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
  2482. return null;
  2483. }
  2484. return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
  2485. }
  2486. return null;
  2487. },
  2488. /**
  2489. * Find the unicode comment declared in the extra field, if any.
  2490. * @return {String} the unicode comment, null otherwise.
  2491. */
  2492. findExtraFieldUnicodeComment: function() {
  2493. var ucommentField = this.extraFields[0x6375];
  2494. if (ucommentField) {
  2495. var extraReader = new StringReader(ucommentField.value);
  2496. // wrong version
  2497. if (extraReader.readInt(1) !== 1) {
  2498. return null;
  2499. }
  2500. // the crc of the comment changed, this field is out of date.
  2501. if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
  2502. return null;
  2503. }
  2504. return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
  2505. }
  2506. return null;
  2507. }
  2508. };
  2509. module.exports = ZipEntry;
  2510. },{"./compressedObject":2,"./object":13,"./stringReader":15,"./utils":21}],24:[function(_dereq_,module,exports){
  2511. // Top level file is just a mixin of submodules & constants
  2512. 'use strict';
  2513. var assign = _dereq_('./lib/utils/common').assign;
  2514. var deflate = _dereq_('./lib/deflate');
  2515. var inflate = _dereq_('./lib/inflate');
  2516. var constants = _dereq_('./lib/zlib/constants');
  2517. var pako = {};
  2518. assign(pako, deflate, inflate, constants);
  2519. module.exports = pako;
  2520. },{"./lib/deflate":25,"./lib/inflate":26,"./lib/utils/common":27,"./lib/zlib/constants":30}],25:[function(_dereq_,module,exports){
  2521. 'use strict';
  2522. var zlib_deflate = _dereq_('./zlib/deflate.js');
  2523. var utils = _dereq_('./utils/common');
  2524. var strings = _dereq_('./utils/strings');
  2525. var msg = _dereq_('./zlib/messages');
  2526. var zstream = _dereq_('./zlib/zstream');
  2527. /* Public constants ==========================================================*/
  2528. /* ===========================================================================*/
  2529. var Z_NO_FLUSH = 0;
  2530. var Z_FINISH = 4;
  2531. var Z_OK = 0;
  2532. var Z_STREAM_END = 1;
  2533. var Z_DEFAULT_COMPRESSION = -1;
  2534. var Z_DEFAULT_STRATEGY = 0;
  2535. var Z_DEFLATED = 8;
  2536. /* ===========================================================================*/
  2537. /**
  2538. * class Deflate
  2539. *
  2540. * Generic JS-style wrapper for zlib calls. If you don't need
  2541. * streaming behaviour - use more simple functions: [[deflate]],
  2542. * [[deflateRaw]] and [[gzip]].
  2543. **/
  2544. /* internal
  2545. * Deflate.chunks -> Array
  2546. *
  2547. * Chunks of output data, if [[Deflate#onData]] not overriden.
  2548. **/
  2549. /**
  2550. * Deflate.result -> Uint8Array|Array
  2551. *
  2552. * Compressed result, generated by default [[Deflate#onData]]
  2553. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  2554. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  2555. **/
  2556. /**
  2557. * Deflate.err -> Number
  2558. *
  2559. * Error code after deflate finished. 0 (Z_OK) on success.
  2560. * You will not need it in real life, because deflate errors
  2561. * are possible only on wrong options or bad `onData` / `onEnd`
  2562. * custom handlers.
  2563. **/
  2564. /**
  2565. * Deflate.msg -> String
  2566. *
  2567. * Error message, if [[Deflate.err]] != 0
  2568. **/
  2569. /**
  2570. * new Deflate(options)
  2571. * - options (Object): zlib deflate options.
  2572. *
  2573. * Creates new deflator instance with specified params. Throws exception
  2574. * on bad params. Supported options:
  2575. *
  2576. * - `level`
  2577. * - `windowBits`
  2578. * - `memLevel`
  2579. * - `strategy`
  2580. *
  2581. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2582. * for more information on these.
  2583. *
  2584. * Additional options, for internal needs:
  2585. *
  2586. * - `chunkSize` - size of generated data chunks (16K by default)
  2587. * - `raw` (Boolean) - do raw deflate
  2588. * - `gzip` (Boolean) - create gzip wrapper
  2589. * - `to` (String) - if equal to 'string', then result will be "binary string"
  2590. * (each char code [0..255])
  2591. * - `header` (Object) - custom header for gzip
  2592. * - `text` (Boolean) - true if compressed data believed to be text
  2593. * - `time` (Number) - modification time, unix timestamp
  2594. * - `os` (Number) - operation system code
  2595. * - `extra` (Array) - array of bytes with extra data (max 65536)
  2596. * - `name` (String) - file name (binary string)
  2597. * - `comment` (String) - comment (binary string)
  2598. * - `hcrc` (Boolean) - true if header crc should be added
  2599. *
  2600. * ##### Example:
  2601. *
  2602. * ```javascript
  2603. * var pako = require('pako')
  2604. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  2605. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  2606. *
  2607. * var deflate = new pako.Deflate({ level: 3});
  2608. *
  2609. * deflate.push(chunk1, false);
  2610. * deflate.push(chunk2, true); // true -> last chunk
  2611. *
  2612. * if (deflate.err) { throw new Error(deflate.err); }
  2613. *
  2614. * console.log(deflate.result);
  2615. * ```
  2616. **/
  2617. var Deflate = function(options) {
  2618. this.options = utils.assign({
  2619. level: Z_DEFAULT_COMPRESSION,
  2620. method: Z_DEFLATED,
  2621. chunkSize: 16384,
  2622. windowBits: 15,
  2623. memLevel: 8,
  2624. strategy: Z_DEFAULT_STRATEGY,
  2625. to: ''
  2626. }, options || {});
  2627. var opt = this.options;
  2628. if (opt.raw && (opt.windowBits > 0)) {
  2629. opt.windowBits = -opt.windowBits;
  2630. }
  2631. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  2632. opt.windowBits += 16;
  2633. }
  2634. this.err = 0; // error code, if happens (0 = Z_OK)
  2635. this.msg = ''; // error message
  2636. this.ended = false; // used to avoid multiple onEnd() calls
  2637. this.chunks = []; // chunks of compressed data
  2638. this.strm = new zstream();
  2639. this.strm.avail_out = 0;
  2640. var status = zlib_deflate.deflateInit2(
  2641. this.strm,
  2642. opt.level,
  2643. opt.method,
  2644. opt.windowBits,
  2645. opt.memLevel,
  2646. opt.strategy
  2647. );
  2648. if (status !== Z_OK) {
  2649. throw new Error(msg[status]);
  2650. }
  2651. if (opt.header) {
  2652. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  2653. }
  2654. };
  2655. /**
  2656. * Deflate#push(data[, mode]) -> Boolean
  2657. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  2658. * utf8 byte sequence.
  2659. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  2660. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  2661. *
  2662. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  2663. * new compressed chunks. Returns `true` on success. The last data block must have
  2664. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  2665. * [[Deflate#onEnd]].
  2666. *
  2667. * On fail call [[Deflate#onEnd]] with error code and return false.
  2668. *
  2669. * We strongly recommend to use `Uint8Array` on input for best speed (output
  2670. * array format is detected automatically). Also, don't skip last param and always
  2671. * use the same type in your code (boolean or number). That will improve JS speed.
  2672. *
  2673. * For regular `Array`-s make sure all elements are [0..255].
  2674. *
  2675. * ##### Example
  2676. *
  2677. * ```javascript
  2678. * push(chunk, false); // push one of data chunks
  2679. * ...
  2680. * push(chunk, true); // push last chunk
  2681. * ```
  2682. **/
  2683. Deflate.prototype.push = function(data, mode) {
  2684. var strm = this.strm;
  2685. var chunkSize = this.options.chunkSize;
  2686. var status, _mode;
  2687. if (this.ended) { return false; }
  2688. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  2689. // Convert data if needed
  2690. if (typeof data === 'string') {
  2691. // If we need to compress text, change encoding to utf8.
  2692. strm.input = strings.string2buf(data);
  2693. } else {
  2694. strm.input = data;
  2695. }
  2696. strm.next_in = 0;
  2697. strm.avail_in = strm.input.length;
  2698. do {
  2699. if (strm.avail_out === 0) {
  2700. strm.output = new utils.Buf8(chunkSize);
  2701. strm.next_out = 0;
  2702. strm.avail_out = chunkSize;
  2703. }
  2704. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  2705. if (status !== Z_STREAM_END && status !== Z_OK) {
  2706. this.onEnd(status);
  2707. this.ended = true;
  2708. return false;
  2709. }
  2710. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  2711. if (this.options.to === 'string') {
  2712. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  2713. } else {
  2714. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  2715. }
  2716. }
  2717. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  2718. // Finalize on the last chunk.
  2719. if (_mode === Z_FINISH) {
  2720. status = zlib_deflate.deflateEnd(this.strm);
  2721. this.onEnd(status);
  2722. this.ended = true;
  2723. return status === Z_OK;
  2724. }
  2725. return true;
  2726. };
  2727. /**
  2728. * Deflate#onData(chunk) -> Void
  2729. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  2730. * on js engine support. When string output requested, each chunk
  2731. * will be string.
  2732. *
  2733. * By default, stores data blocks in `chunks[]` property and glue
  2734. * those in `onEnd`. Override this handler, if you need another behaviour.
  2735. **/
  2736. Deflate.prototype.onData = function(chunk) {
  2737. this.chunks.push(chunk);
  2738. };
  2739. /**
  2740. * Deflate#onEnd(status) -> Void
  2741. * - status (Number): deflate status. 0 (Z_OK) on success,
  2742. * other if not.
  2743. *
  2744. * Called once after you tell deflate that input stream complete
  2745. * or error happenned. By default - join collected chunks,
  2746. * free memory and fill `results` / `err` properties.
  2747. **/
  2748. Deflate.prototype.onEnd = function(status) {
  2749. // On success - join
  2750. if (status === Z_OK) {
  2751. if (this.options.to === 'string') {
  2752. this.result = this.chunks.join('');
  2753. } else {
  2754. this.result = utils.flattenChunks(this.chunks);
  2755. }
  2756. }
  2757. this.chunks = [];
  2758. this.err = status;
  2759. this.msg = this.strm.msg;
  2760. };
  2761. /**
  2762. * deflate(data[, options]) -> Uint8Array|Array|String
  2763. * - data (Uint8Array|Array|String): input data to compress.
  2764. * - options (Object): zlib deflate options.
  2765. *
  2766. * Compress `data` with deflate alrorythm and `options`.
  2767. *
  2768. * Supported options are:
  2769. *
  2770. * - level
  2771. * - windowBits
  2772. * - memLevel
  2773. * - strategy
  2774. *
  2775. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2776. * for more information on these.
  2777. *
  2778. * Sugar (options):
  2779. *
  2780. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  2781. * negative windowBits implicitly.
  2782. * - `to` (String) - if equal to 'string', then result will be "binary string"
  2783. * (each char code [0..255])
  2784. *
  2785. * ##### Example:
  2786. *
  2787. * ```javascript
  2788. * var pako = require('pako')
  2789. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  2790. *
  2791. * console.log(pako.deflate(data));
  2792. * ```
  2793. **/
  2794. function deflate(input, options) {
  2795. var deflator = new Deflate(options);
  2796. deflator.push(input, true);
  2797. // That will never happens, if you don't cheat with options :)
  2798. if (deflator.err) { throw deflator.msg; }
  2799. return deflator.result;
  2800. }
  2801. /**
  2802. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  2803. * - data (Uint8Array|Array|String): input data to compress.
  2804. * - options (Object): zlib deflate options.
  2805. *
  2806. * The same as [[deflate]], but creates raw data, without wrapper
  2807. * (header and adler32 crc).
  2808. **/
  2809. function deflateRaw(input, options) {
  2810. options = options || {};
  2811. options.raw = true;
  2812. return deflate(input, options);
  2813. }
  2814. /**
  2815. * gzip(data[, options]) -> Uint8Array|Array|String
  2816. * - data (Uint8Array|Array|String): input data to compress.
  2817. * - options (Object): zlib deflate options.
  2818. *
  2819. * The same as [[deflate]], but create gzip wrapper instead of
  2820. * deflate one.
  2821. **/
  2822. function gzip(input, options) {
  2823. options = options || {};
  2824. options.gzip = true;
  2825. return deflate(input, options);
  2826. }
  2827. exports.Deflate = Deflate;
  2828. exports.deflate = deflate;
  2829. exports.deflateRaw = deflateRaw;
  2830. exports.gzip = gzip;
  2831. },{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(_dereq_,module,exports){
  2832. 'use strict';
  2833. var zlib_inflate = _dereq_('./zlib/inflate.js');
  2834. var utils = _dereq_('./utils/common');
  2835. var strings = _dereq_('./utils/strings');
  2836. var c = _dereq_('./zlib/constants');
  2837. var msg = _dereq_('./zlib/messages');
  2838. var zstream = _dereq_('./zlib/zstream');
  2839. var gzheader = _dereq_('./zlib/gzheader');
  2840. /**
  2841. * class Inflate
  2842. *
  2843. * Generic JS-style wrapper for zlib calls. If you don't need
  2844. * streaming behaviour - use more simple functions: [[inflate]]
  2845. * and [[inflateRaw]].
  2846. **/
  2847. /* internal
  2848. * inflate.chunks -> Array
  2849. *
  2850. * Chunks of output data, if [[Inflate#onData]] not overriden.
  2851. **/
  2852. /**
  2853. * Inflate.result -> Uint8Array|Array|String
  2854. *
  2855. * Uncompressed result, generated by default [[Inflate#onData]]
  2856. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  2857. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  2858. **/
  2859. /**
  2860. * Inflate.err -> Number
  2861. *
  2862. * Error code after inflate finished. 0 (Z_OK) on success.
  2863. * Should be checked if broken data possible.
  2864. **/
  2865. /**
  2866. * Inflate.msg -> String
  2867. *
  2868. * Error message, if [[Inflate.err]] != 0
  2869. **/
  2870. /**
  2871. * new Inflate(options)
  2872. * - options (Object): zlib inflate options.
  2873. *
  2874. * Creates new inflator instance with specified params. Throws exception
  2875. * on bad params. Supported options:
  2876. *
  2877. * - `windowBits`
  2878. *
  2879. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  2880. * for more information on these.
  2881. *
  2882. * Additional options, for internal needs:
  2883. *
  2884. * - `chunkSize` - size of generated data chunks (16K by default)
  2885. * - `raw` (Boolean) - do raw inflate
  2886. * - `to` (String) - if equal to 'string', then result will be converted
  2887. * from utf8 to utf16 (javascript) string. When string output requested,
  2888. * chunk length can differ from `chunkSize`, depending on content.
  2889. *
  2890. * By default, when no options set, autodetect deflate/gzip data format via
  2891. * wrapper header.
  2892. *
  2893. * ##### Example:
  2894. *
  2895. * ```javascript
  2896. * var pako = require('pako')
  2897. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  2898. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  2899. *
  2900. * var inflate = new pako.Inflate({ level: 3});
  2901. *
  2902. * inflate.push(chunk1, false);
  2903. * inflate.push(chunk2, true); // true -> last chunk
  2904. *
  2905. * if (inflate.err) { throw new Error(inflate.err); }
  2906. *
  2907. * console.log(inflate.result);
  2908. * ```
  2909. **/
  2910. var Inflate = function(options) {
  2911. this.options = utils.assign({
  2912. chunkSize: 16384,
  2913. windowBits: 0,
  2914. to: ''
  2915. }, options || {});
  2916. var opt = this.options;
  2917. // Force window size for `raw` data, if not set directly,
  2918. // because we have no header for autodetect.
  2919. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  2920. opt.windowBits = -opt.windowBits;
  2921. if (opt.windowBits === 0) { opt.windowBits = -15; }
  2922. }
  2923. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  2924. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  2925. !(options && options.windowBits)) {
  2926. opt.windowBits += 32;
  2927. }
  2928. // Gzip header has no info about windows size, we can do autodetect only
  2929. // for deflate. So, if window size not set, force it to max when gzip possible
  2930. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  2931. // bit 3 (16) -> gzipped data
  2932. // bit 4 (32) -> autodetect gzip/deflate
  2933. if ((opt.windowBits & 15) === 0) {
  2934. opt.windowBits |= 15;
  2935. }
  2936. }
  2937. this.err = 0; // error code, if happens (0 = Z_OK)
  2938. this.msg = ''; // error message
  2939. this.ended = false; // used to avoid multiple onEnd() calls
  2940. this.chunks = []; // chunks of compressed data
  2941. this.strm = new zstream();
  2942. this.strm.avail_out = 0;
  2943. var status = zlib_inflate.inflateInit2(
  2944. this.strm,
  2945. opt.windowBits
  2946. );
  2947. if (status !== c.Z_OK) {
  2948. throw new Error(msg[status]);
  2949. }
  2950. this.header = new gzheader();
  2951. zlib_inflate.inflateGetHeader(this.strm, this.header);
  2952. };
  2953. /**
  2954. * Inflate#push(data[, mode]) -> Boolean
  2955. * - data (Uint8Array|Array|String): input data
  2956. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  2957. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  2958. *
  2959. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  2960. * new output chunks. Returns `true` on success. The last data block must have
  2961. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  2962. * [[Inflate#onEnd]].
  2963. *
  2964. * On fail call [[Inflate#onEnd]] with error code and return false.
  2965. *
  2966. * We strongly recommend to use `Uint8Array` on input for best speed (output
  2967. * format is detected automatically). Also, don't skip last param and always
  2968. * use the same type in your code (boolean or number). That will improve JS speed.
  2969. *
  2970. * For regular `Array`-s make sure all elements are [0..255].
  2971. *
  2972. * ##### Example
  2973. *
  2974. * ```javascript
  2975. * push(chunk, false); // push one of data chunks
  2976. * ...
  2977. * push(chunk, true); // push last chunk
  2978. * ```
  2979. **/
  2980. Inflate.prototype.push = function(data, mode) {
  2981. var strm = this.strm;
  2982. var chunkSize = this.options.chunkSize;
  2983. var status, _mode;
  2984. var next_out_utf8, tail, utf8str;
  2985. if (this.ended) { return false; }
  2986. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  2987. // Convert data if needed
  2988. if (typeof data === 'string') {
  2989. // Only binary strings can be decompressed on practice
  2990. strm.input = strings.binstring2buf(data);
  2991. } else {
  2992. strm.input = data;
  2993. }
  2994. strm.next_in = 0;
  2995. strm.avail_in = strm.input.length;
  2996. do {
  2997. if (strm.avail_out === 0) {
  2998. strm.output = new utils.Buf8(chunkSize);
  2999. strm.next_out = 0;
  3000. strm.avail_out = chunkSize;
  3001. }
  3002. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  3003. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  3004. this.onEnd(status);
  3005. this.ended = true;
  3006. return false;
  3007. }
  3008. if (strm.next_out) {
  3009. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  3010. if (this.options.to === 'string') {
  3011. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  3012. tail = strm.next_out - next_out_utf8;
  3013. utf8str = strings.buf2string(strm.output, next_out_utf8);
  3014. // move tail
  3015. strm.next_out = tail;
  3016. strm.avail_out = chunkSize - tail;
  3017. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  3018. this.onData(utf8str);
  3019. } else {
  3020. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  3021. }
  3022. }
  3023. }
  3024. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  3025. if (status === c.Z_STREAM_END) {
  3026. _mode = c.Z_FINISH;
  3027. }
  3028. // Finalize on the last chunk.
  3029. if (_mode === c.Z_FINISH) {
  3030. status = zlib_inflate.inflateEnd(this.strm);
  3031. this.onEnd(status);
  3032. this.ended = true;
  3033. return status === c.Z_OK;
  3034. }
  3035. return true;
  3036. };
  3037. /**
  3038. * Inflate#onData(chunk) -> Void
  3039. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  3040. * on js engine support. When string output requested, each chunk
  3041. * will be string.
  3042. *
  3043. * By default, stores data blocks in `chunks[]` property and glue
  3044. * those in `onEnd`. Override this handler, if you need another behaviour.
  3045. **/
  3046. Inflate.prototype.onData = function(chunk) {
  3047. this.chunks.push(chunk);
  3048. };
  3049. /**
  3050. * Inflate#onEnd(status) -> Void
  3051. * - status (Number): inflate status. 0 (Z_OK) on success,
  3052. * other if not.
  3053. *
  3054. * Called once after you tell inflate that input stream complete
  3055. * or error happenned. By default - join collected chunks,
  3056. * free memory and fill `results` / `err` properties.
  3057. **/
  3058. Inflate.prototype.onEnd = function(status) {
  3059. // On success - join
  3060. if (status === c.Z_OK) {
  3061. if (this.options.to === 'string') {
  3062. // Glue & convert here, until we teach pako to send
  3063. // utf8 alligned strings to onData
  3064. this.result = this.chunks.join('');
  3065. } else {
  3066. this.result = utils.flattenChunks(this.chunks);
  3067. }
  3068. }
  3069. this.chunks = [];
  3070. this.err = status;
  3071. this.msg = this.strm.msg;
  3072. };
  3073. /**
  3074. * inflate(data[, options]) -> Uint8Array|Array|String
  3075. * - data (Uint8Array|Array|String): input data to decompress.
  3076. * - options (Object): zlib inflate options.
  3077. *
  3078. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  3079. * format via wrapper header by default. That's why we don't provide
  3080. * separate `ungzip` method.
  3081. *
  3082. * Supported options are:
  3083. *
  3084. * - windowBits
  3085. *
  3086. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  3087. * for more information.
  3088. *
  3089. * Sugar (options):
  3090. *
  3091. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  3092. * negative windowBits implicitly.
  3093. * - `to` (String) - if equal to 'string', then result will be converted
  3094. * from utf8 to utf16 (javascript) string. When string output requested,
  3095. * chunk length can differ from `chunkSize`, depending on content.
  3096. *
  3097. *
  3098. * ##### Example:
  3099. *
  3100. * ```javascript
  3101. * var pako = require('pako')
  3102. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  3103. * , output;
  3104. *
  3105. * try {
  3106. * output = pako.inflate(input);
  3107. * } catch (err)
  3108. * console.log(err);
  3109. * }
  3110. * ```
  3111. **/
  3112. function inflate(input, options) {
  3113. var inflator = new Inflate(options);
  3114. inflator.push(input, true);
  3115. // That will never happens, if you don't cheat with options :)
  3116. if (inflator.err) { throw inflator.msg; }
  3117. return inflator.result;
  3118. }
  3119. /**
  3120. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  3121. * - data (Uint8Array|Array|String): input data to decompress.
  3122. * - options (Object): zlib inflate options.
  3123. *
  3124. * The same as [[inflate]], but creates raw data, without wrapper
  3125. * (header and adler32 crc).
  3126. **/
  3127. function inflateRaw(input, options) {
  3128. options = options || {};
  3129. options.raw = true;
  3130. return inflate(input, options);
  3131. }
  3132. /**
  3133. * ungzip(data[, options]) -> Uint8Array|Array|String
  3134. * - data (Uint8Array|Array|String): input data to decompress.
  3135. * - options (Object): zlib inflate options.
  3136. *
  3137. * Just shortcut to [[inflate]], because it autodetects format
  3138. * by header.content. Done for convenience.
  3139. **/
  3140. exports.Inflate = Inflate;
  3141. exports.inflate = inflate;
  3142. exports.inflateRaw = inflateRaw;
  3143. exports.ungzip = inflate;
  3144. },{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(_dereq_,module,exports){
  3145. 'use strict';
  3146. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  3147. (typeof Uint16Array !== 'undefined') &&
  3148. (typeof Int32Array !== 'undefined');
  3149. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  3150. var sources = Array.prototype.slice.call(arguments, 1);
  3151. while (sources.length) {
  3152. var source = sources.shift();
  3153. if (!source) { continue; }
  3154. if (typeof(source) !== 'object') {
  3155. throw new TypeError(source + 'must be non-object');
  3156. }
  3157. for (var p in source) {
  3158. if (source.hasOwnProperty(p)) {
  3159. obj[p] = source[p];
  3160. }
  3161. }
  3162. }
  3163. return obj;
  3164. };
  3165. // reduce buffer size, avoiding mem copy
  3166. exports.shrinkBuf = function (buf, size) {
  3167. if (buf.length === size) { return buf; }
  3168. if (buf.subarray) { return buf.subarray(0, size); }
  3169. buf.length = size;
  3170. return buf;
  3171. };
  3172. var fnTyped = {
  3173. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3174. if (src.subarray && dest.subarray) {
  3175. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  3176. return;
  3177. }
  3178. // Fallback to ordinary array
  3179. for(var i=0; i<len; i++) {
  3180. dest[dest_offs + i] = src[src_offs + i];
  3181. }
  3182. },
  3183. // Join array of chunks to single array.
  3184. flattenChunks: function(chunks) {
  3185. var i, l, len, pos, chunk, result;
  3186. // calculate data length
  3187. len = 0;
  3188. for (i=0, l=chunks.length; i<l; i++) {
  3189. len += chunks[i].length;
  3190. }
  3191. // join chunks
  3192. result = new Uint8Array(len);
  3193. pos = 0;
  3194. for (i=0, l=chunks.length; i<l; i++) {
  3195. chunk = chunks[i];
  3196. result.set(chunk, pos);
  3197. pos += chunk.length;
  3198. }
  3199. return result;
  3200. }
  3201. };
  3202. var fnUntyped = {
  3203. arraySet: function (dest, src, src_offs, len, dest_offs) {
  3204. for(var i=0; i<len; i++) {
  3205. dest[dest_offs + i] = src[src_offs + i];
  3206. }
  3207. },
  3208. // Join array of chunks to single array.
  3209. flattenChunks: function(chunks) {
  3210. return [].concat.apply([], chunks);
  3211. }
  3212. };
  3213. // Enable/Disable typed arrays use, for testing
  3214. //
  3215. exports.setTyped = function (on) {
  3216. if (on) {
  3217. exports.Buf8 = Uint8Array;
  3218. exports.Buf16 = Uint16Array;
  3219. exports.Buf32 = Int32Array;
  3220. exports.assign(exports, fnTyped);
  3221. } else {
  3222. exports.Buf8 = Array;
  3223. exports.Buf16 = Array;
  3224. exports.Buf32 = Array;
  3225. exports.assign(exports, fnUntyped);
  3226. }
  3227. };
  3228. exports.setTyped(TYPED_OK);
  3229. },{}],28:[function(_dereq_,module,exports){
  3230. // String encode/decode helpers
  3231. 'use strict';
  3232. var utils = _dereq_('./common');
  3233. // Quick check if we can use fast array to bin string conversion
  3234. //
  3235. // - apply(Array) can fail on Android 2.2
  3236. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  3237. //
  3238. var STR_APPLY_OK = true;
  3239. var STR_APPLY_UIA_OK = true;
  3240. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  3241. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  3242. // Table with utf8 lengths (calculated by first byte of sequence)
  3243. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  3244. // because max possible codepoint is 0x10ffff
  3245. var _utf8len = new utils.Buf8(256);
  3246. for (var i=0; i<256; i++) {
  3247. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  3248. }
  3249. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  3250. // convert string to array (typed, when possible)
  3251. exports.string2buf = function (str) {
  3252. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  3253. // count binary size
  3254. for (m_pos = 0; m_pos < str_len; m_pos++) {
  3255. c = str.charCodeAt(m_pos);
  3256. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3257. c2 = str.charCodeAt(m_pos+1);
  3258. if ((c2 & 0xfc00) === 0xdc00) {
  3259. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3260. m_pos++;
  3261. }
  3262. }
  3263. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  3264. }
  3265. // allocate buffer
  3266. buf = new utils.Buf8(buf_len);
  3267. // convert
  3268. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  3269. c = str.charCodeAt(m_pos);
  3270. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  3271. c2 = str.charCodeAt(m_pos+1);
  3272. if ((c2 & 0xfc00) === 0xdc00) {
  3273. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  3274. m_pos++;
  3275. }
  3276. }
  3277. if (c < 0x80) {
  3278. /* one byte */
  3279. buf[i++] = c;
  3280. } else if (c < 0x800) {
  3281. /* two bytes */
  3282. buf[i++] = 0xC0 | (c >>> 6);
  3283. buf[i++] = 0x80 | (c & 0x3f);
  3284. } else if (c < 0x10000) {
  3285. /* three bytes */
  3286. buf[i++] = 0xE0 | (c >>> 12);
  3287. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3288. buf[i++] = 0x80 | (c & 0x3f);
  3289. } else {
  3290. /* four bytes */
  3291. buf[i++] = 0xf0 | (c >>> 18);
  3292. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  3293. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  3294. buf[i++] = 0x80 | (c & 0x3f);
  3295. }
  3296. }
  3297. return buf;
  3298. };
  3299. // Helper (used in 2 places)
  3300. function buf2binstring(buf, len) {
  3301. // use fallback for big arrays to avoid stack overflow
  3302. if (len < 65537) {
  3303. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  3304. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  3305. }
  3306. }
  3307. var result = '';
  3308. for(var i=0; i < len; i++) {
  3309. result += String.fromCharCode(buf[i]);
  3310. }
  3311. return result;
  3312. }
  3313. // Convert byte array to binary string
  3314. exports.buf2binstring = function(buf) {
  3315. return buf2binstring(buf, buf.length);
  3316. };
  3317. // Convert binary string (typed, when possible)
  3318. exports.binstring2buf = function(str) {
  3319. var buf = new utils.Buf8(str.length);
  3320. for(var i=0, len=buf.length; i < len; i++) {
  3321. buf[i] = str.charCodeAt(i);
  3322. }
  3323. return buf;
  3324. };
  3325. // convert array to string
  3326. exports.buf2string = function (buf, max) {
  3327. var i, out, c, c_len;
  3328. var len = max || buf.length;
  3329. // Reserve max possible length (2 words per char)
  3330. // NB: by unknown reasons, Array is significantly faster for
  3331. // String.fromCharCode.apply than Uint16Array.
  3332. var utf16buf = new Array(len*2);
  3333. for (out=0, i=0; i<len;) {
  3334. c = buf[i++];
  3335. // quick process ascii
  3336. if (c < 0x80) { utf16buf[out++] = c; continue; }
  3337. c_len = _utf8len[c];
  3338. // skip 5 & 6 byte codes
  3339. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  3340. // apply mask on first byte
  3341. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  3342. // join the rest
  3343. while (c_len > 1 && i < len) {
  3344. c = (c << 6) | (buf[i++] & 0x3f);
  3345. c_len--;
  3346. }
  3347. // terminated by end of string?
  3348. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  3349. if (c < 0x10000) {
  3350. utf16buf[out++] = c;
  3351. } else {
  3352. c -= 0x10000;
  3353. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  3354. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  3355. }
  3356. }
  3357. return buf2binstring(utf16buf, out);
  3358. };
  3359. // Calculate max possible position in utf8 buffer,
  3360. // that will not break sequence. If that's not possible
  3361. // - (very small limits) return max size as is.
  3362. //
  3363. // buf[] - utf8 bytes array
  3364. // max - length limit (mandatory);
  3365. exports.utf8border = function(buf, max) {
  3366. var pos;
  3367. max = max || buf.length;
  3368. if (max > buf.length) { max = buf.length; }
  3369. // go back from last position, until start of sequence found
  3370. pos = max-1;
  3371. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  3372. // Fuckup - very small and broken sequence,
  3373. // return max, because we should return something anyway.
  3374. if (pos < 0) { return max; }
  3375. // If we came to start of buffer - that means vuffer is too small,
  3376. // return max too.
  3377. if (pos === 0) { return max; }
  3378. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  3379. };
  3380. },{"./common":27}],29:[function(_dereq_,module,exports){
  3381. 'use strict';
  3382. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  3383. // It doesn't worth to make additional optimizationa as in original.
  3384. // Small size is preferable.
  3385. function adler32(adler, buf, len, pos) {
  3386. var s1 = (adler & 0xffff) |0
  3387. , s2 = ((adler >>> 16) & 0xffff) |0
  3388. , n = 0;
  3389. while (len !== 0) {
  3390. // Set limit ~ twice less than 5552, to keep
  3391. // s2 in 31-bits, because we force signed ints.
  3392. // in other case %= will fail.
  3393. n = len > 2000 ? 2000 : len;
  3394. len -= n;
  3395. do {
  3396. s1 = (s1 + buf[pos++]) |0;
  3397. s2 = (s2 + s1) |0;
  3398. } while (--n);
  3399. s1 %= 65521;
  3400. s2 %= 65521;
  3401. }
  3402. return (s1 | (s2 << 16)) |0;
  3403. }
  3404. module.exports = adler32;
  3405. },{}],30:[function(_dereq_,module,exports){
  3406. module.exports = {
  3407. /* Allowed flush values; see deflate() and inflate() below for details */
  3408. Z_NO_FLUSH: 0,
  3409. Z_PARTIAL_FLUSH: 1,
  3410. Z_SYNC_FLUSH: 2,
  3411. Z_FULL_FLUSH: 3,
  3412. Z_FINISH: 4,
  3413. Z_BLOCK: 5,
  3414. Z_TREES: 6,
  3415. /* Return codes for the compression/decompression functions. Negative values
  3416. * are errors, positive values are used for special but normal events.
  3417. */
  3418. Z_OK: 0,
  3419. Z_STREAM_END: 1,
  3420. Z_NEED_DICT: 2,
  3421. Z_ERRNO: -1,
  3422. Z_STREAM_ERROR: -2,
  3423. Z_DATA_ERROR: -3,
  3424. //Z_MEM_ERROR: -4,
  3425. Z_BUF_ERROR: -5,
  3426. //Z_VERSION_ERROR: -6,
  3427. /* compression levels */
  3428. Z_NO_COMPRESSION: 0,
  3429. Z_BEST_SPEED: 1,
  3430. Z_BEST_COMPRESSION: 9,
  3431. Z_DEFAULT_COMPRESSION: -1,
  3432. Z_FILTERED: 1,
  3433. Z_HUFFMAN_ONLY: 2,
  3434. Z_RLE: 3,
  3435. Z_FIXED: 4,
  3436. Z_DEFAULT_STRATEGY: 0,
  3437. /* Possible values of the data_type field (though see inflate()) */
  3438. Z_BINARY: 0,
  3439. Z_TEXT: 1,
  3440. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  3441. Z_UNKNOWN: 2,
  3442. /* The deflate compression method */
  3443. Z_DEFLATED: 8
  3444. //Z_NULL: null // Use -1 or null inline, depending on var type
  3445. };
  3446. },{}],31:[function(_dereq_,module,exports){
  3447. 'use strict';
  3448. // Note: we can't get significant speed boost here.
  3449. // So write code to minimize size - no pregenerated tables
  3450. // and array tools dependencies.
  3451. // Use ordinary array, since untyped makes no boost here
  3452. function makeTable() {
  3453. var c, table = [];
  3454. for(var n =0; n < 256; n++){
  3455. c = n;
  3456. for(var k =0; k < 8; k++){
  3457. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  3458. }
  3459. table[n] = c;
  3460. }
  3461. return table;
  3462. }
  3463. // Create table on load. Just 255 signed longs. Not a problem.
  3464. var crcTable = makeTable();
  3465. function crc32(crc, buf, len, pos) {
  3466. var t = crcTable
  3467. , end = pos + len;
  3468. crc = crc ^ (-1);
  3469. for (var i = pos; i < end; i++ ) {
  3470. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  3471. }
  3472. return (crc ^ (-1)); // >>> 0;
  3473. }
  3474. module.exports = crc32;
  3475. },{}],32:[function(_dereq_,module,exports){
  3476. 'use strict';
  3477. var utils = _dereq_('../utils/common');
  3478. var trees = _dereq_('./trees');
  3479. var adler32 = _dereq_('./adler32');
  3480. var crc32 = _dereq_('./crc32');
  3481. var msg = _dereq_('./messages');
  3482. /* Public constants ==========================================================*/
  3483. /* ===========================================================================*/
  3484. /* Allowed flush values; see deflate() and inflate() below for details */
  3485. var Z_NO_FLUSH = 0;
  3486. var Z_PARTIAL_FLUSH = 1;
  3487. //var Z_SYNC_FLUSH = 2;
  3488. var Z_FULL_FLUSH = 3;
  3489. var Z_FINISH = 4;
  3490. var Z_BLOCK = 5;
  3491. //var Z_TREES = 6;
  3492. /* Return codes for the compression/decompression functions. Negative values
  3493. * are errors, positive values are used for special but normal events.
  3494. */
  3495. var Z_OK = 0;
  3496. var Z_STREAM_END = 1;
  3497. //var Z_NEED_DICT = 2;
  3498. //var Z_ERRNO = -1;
  3499. var Z_STREAM_ERROR = -2;
  3500. var Z_DATA_ERROR = -3;
  3501. //var Z_MEM_ERROR = -4;
  3502. var Z_BUF_ERROR = -5;
  3503. //var Z_VERSION_ERROR = -6;
  3504. /* compression levels */
  3505. //var Z_NO_COMPRESSION = 0;
  3506. //var Z_BEST_SPEED = 1;
  3507. //var Z_BEST_COMPRESSION = 9;
  3508. var Z_DEFAULT_COMPRESSION = -1;
  3509. var Z_FILTERED = 1;
  3510. var Z_HUFFMAN_ONLY = 2;
  3511. var Z_RLE = 3;
  3512. var Z_FIXED = 4;
  3513. var Z_DEFAULT_STRATEGY = 0;
  3514. /* Possible values of the data_type field (though see inflate()) */
  3515. //var Z_BINARY = 0;
  3516. //var Z_TEXT = 1;
  3517. //var Z_ASCII = 1; // = Z_TEXT
  3518. var Z_UNKNOWN = 2;
  3519. /* The deflate compression method */
  3520. var Z_DEFLATED = 8;
  3521. /*============================================================================*/
  3522. var MAX_MEM_LEVEL = 9;
  3523. /* Maximum value for memLevel in deflateInit2 */
  3524. var MAX_WBITS = 15;
  3525. /* 32K LZ77 window */
  3526. var DEF_MEM_LEVEL = 8;
  3527. var LENGTH_CODES = 29;
  3528. /* number of length codes, not counting the special END_BLOCK code */
  3529. var LITERALS = 256;
  3530. /* number of literal bytes 0..255 */
  3531. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  3532. /* number of Literal or Length codes, including the END_BLOCK code */
  3533. var D_CODES = 30;
  3534. /* number of distance codes */
  3535. var BL_CODES = 19;
  3536. /* number of codes used to transfer the bit lengths */
  3537. var HEAP_SIZE = 2*L_CODES + 1;
  3538. /* maximum heap size */
  3539. var MAX_BITS = 15;
  3540. /* All codes must not exceed MAX_BITS bits */
  3541. var MIN_MATCH = 3;
  3542. var MAX_MATCH = 258;
  3543. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  3544. var PRESET_DICT = 0x20;
  3545. var INIT_STATE = 42;
  3546. var EXTRA_STATE = 69;
  3547. var NAME_STATE = 73;
  3548. var COMMENT_STATE = 91;
  3549. var HCRC_STATE = 103;
  3550. var BUSY_STATE = 113;
  3551. var FINISH_STATE = 666;
  3552. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  3553. var BS_BLOCK_DONE = 2; /* block flush performed */
  3554. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  3555. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  3556. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  3557. function err(strm, errorCode) {
  3558. strm.msg = msg[errorCode];
  3559. return errorCode;
  3560. }
  3561. function rank(f) {
  3562. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  3563. }
  3564. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  3565. /* =========================================================================
  3566. * Flush as much pending output as possible. All deflate() output goes
  3567. * through this function so some applications may wish to modify it
  3568. * to avoid allocating a large strm->output buffer and copying into it.
  3569. * (See also read_buf()).
  3570. */
  3571. function flush_pending(strm) {
  3572. var s = strm.state;
  3573. //_tr_flush_bits(s);
  3574. var len = s.pending;
  3575. if (len > strm.avail_out) {
  3576. len = strm.avail_out;
  3577. }
  3578. if (len === 0) { return; }
  3579. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  3580. strm.next_out += len;
  3581. s.pending_out += len;
  3582. strm.total_out += len;
  3583. strm.avail_out -= len;
  3584. s.pending -= len;
  3585. if (s.pending === 0) {
  3586. s.pending_out = 0;
  3587. }
  3588. }
  3589. function flush_block_only (s, last) {
  3590. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  3591. s.block_start = s.strstart;
  3592. flush_pending(s.strm);
  3593. }
  3594. function put_byte(s, b) {
  3595. s.pending_buf[s.pending++] = b;
  3596. }
  3597. /* =========================================================================
  3598. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  3599. * IN assertion: the stream state is correct and there is enough room in
  3600. * pending_buf.
  3601. */
  3602. function putShortMSB(s, b) {
  3603. // put_byte(s, (Byte)(b >> 8));
  3604. // put_byte(s, (Byte)(b & 0xff));
  3605. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  3606. s.pending_buf[s.pending++] = b & 0xff;
  3607. }
  3608. /* ===========================================================================
  3609. * Read a new buffer from the current input stream, update the adler32
  3610. * and total number of bytes read. All deflate() input goes through
  3611. * this function so some applications may wish to modify it to avoid
  3612. * allocating a large strm->input buffer and copying from it.
  3613. * (See also flush_pending()).
  3614. */
  3615. function read_buf(strm, buf, start, size) {
  3616. var len = strm.avail_in;
  3617. if (len > size) { len = size; }
  3618. if (len === 0) { return 0; }
  3619. strm.avail_in -= len;
  3620. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  3621. if (strm.state.wrap === 1) {
  3622. strm.adler = adler32(strm.adler, buf, len, start);
  3623. }
  3624. else if (strm.state.wrap === 2) {
  3625. strm.adler = crc32(strm.adler, buf, len, start);
  3626. }
  3627. strm.next_in += len;
  3628. strm.total_in += len;
  3629. return len;
  3630. }
  3631. /* ===========================================================================
  3632. * Set match_start to the longest match starting at the given string and
  3633. * return its length. Matches shorter or equal to prev_length are discarded,
  3634. * in which case the result is equal to prev_length and match_start is
  3635. * garbage.
  3636. * IN assertions: cur_match is the head of the hash chain for the current
  3637. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  3638. * OUT assertion: the match length is not greater than s->lookahead.
  3639. */
  3640. function longest_match(s, cur_match) {
  3641. var chain_length = s.max_chain_length; /* max hash chain length */
  3642. var scan = s.strstart; /* current string */
  3643. var match; /* matched string */
  3644. var len; /* length of current match */
  3645. var best_len = s.prev_length; /* best match length so far */
  3646. var nice_match = s.nice_match; /* stop if match long enough */
  3647. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  3648. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  3649. var _win = s.window; // shortcut
  3650. var wmask = s.w_mask;
  3651. var prev = s.prev;
  3652. /* Stop when cur_match becomes <= limit. To simplify the code,
  3653. * we prevent matches with the string of window index 0.
  3654. */
  3655. var strend = s.strstart + MAX_MATCH;
  3656. var scan_end1 = _win[scan + best_len - 1];
  3657. var scan_end = _win[scan + best_len];
  3658. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  3659. * It is easy to get rid of this optimization if necessary.
  3660. */
  3661. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  3662. /* Do not waste too much time if we already have a good match: */
  3663. if (s.prev_length >= s.good_match) {
  3664. chain_length >>= 2;
  3665. }
  3666. /* Do not look for matches beyond the end of the input. This is necessary
  3667. * to make deflate deterministic.
  3668. */
  3669. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  3670. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  3671. do {
  3672. // Assert(cur_match < s->strstart, "no future");
  3673. match = cur_match;
  3674. /* Skip to next match if the match length cannot increase
  3675. * or if the match length is less than 2. Note that the checks below
  3676. * for insufficient lookahead only occur occasionally for performance
  3677. * reasons. Therefore uninitialized memory will be accessed, and
  3678. * conditional jumps will be made that depend on those values.
  3679. * However the length of the match is limited to the lookahead, so
  3680. * the output of deflate is not affected by the uninitialized values.
  3681. */
  3682. if (_win[match + best_len] !== scan_end ||
  3683. _win[match + best_len - 1] !== scan_end1 ||
  3684. _win[match] !== _win[scan] ||
  3685. _win[++match] !== _win[scan + 1]) {
  3686. continue;
  3687. }
  3688. /* The check at best_len-1 can be removed because it will be made
  3689. * again later. (This heuristic is not always a win.)
  3690. * It is not necessary to compare scan[2] and match[2] since they
  3691. * are always equal when the other bytes match, given that
  3692. * the hash keys are equal and that HASH_BITS >= 8.
  3693. */
  3694. scan += 2;
  3695. match++;
  3696. // Assert(*scan == *match, "match[2]?");
  3697. /* We check for insufficient lookahead only every 8th comparison;
  3698. * the 256th check will be made at strstart+258.
  3699. */
  3700. do {
  3701. /*jshint noempty:false*/
  3702. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3703. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3704. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3705. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  3706. scan < strend);
  3707. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  3708. len = MAX_MATCH - (strend - scan);
  3709. scan = strend - MAX_MATCH;
  3710. if (len > best_len) {
  3711. s.match_start = cur_match;
  3712. best_len = len;
  3713. if (len >= nice_match) {
  3714. break;
  3715. }
  3716. scan_end1 = _win[scan + best_len - 1];
  3717. scan_end = _win[scan + best_len];
  3718. }
  3719. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  3720. if (best_len <= s.lookahead) {
  3721. return best_len;
  3722. }
  3723. return s.lookahead;
  3724. }
  3725. /* ===========================================================================
  3726. * Fill the window when the lookahead becomes insufficient.
  3727. * Updates strstart and lookahead.
  3728. *
  3729. * IN assertion: lookahead < MIN_LOOKAHEAD
  3730. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  3731. * At least one byte has been read, or avail_in == 0; reads are
  3732. * performed for at least two bytes (required for the zip translate_eol
  3733. * option -- not supported here).
  3734. */
  3735. function fill_window(s) {
  3736. var _w_size = s.w_size;
  3737. var p, n, m, more, str;
  3738. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  3739. do {
  3740. more = s.window_size - s.lookahead - s.strstart;
  3741. // JS ints have 32 bit, block below not needed
  3742. /* Deal with !@#$% 64K limit: */
  3743. //if (sizeof(int) <= 2) {
  3744. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  3745. // more = wsize;
  3746. //
  3747. // } else if (more == (unsigned)(-1)) {
  3748. // /* Very unlikely, but possible on 16 bit machine if
  3749. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  3750. // */
  3751. // more--;
  3752. // }
  3753. //}
  3754. /* If the window is almost full and there is insufficient lookahead,
  3755. * move the upper half to the lower one to make room in the upper half.
  3756. */
  3757. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  3758. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  3759. s.match_start -= _w_size;
  3760. s.strstart -= _w_size;
  3761. /* we now have strstart >= MAX_DIST */
  3762. s.block_start -= _w_size;
  3763. /* Slide the hash table (could be avoided with 32 bit values
  3764. at the expense of memory usage). We slide even when level == 0
  3765. to keep the hash table consistent if we switch back to level > 0
  3766. later. (Using level 0 permanently is not an optimal usage of
  3767. zlib, so we don't care about this pathological case.)
  3768. */
  3769. n = s.hash_size;
  3770. p = n;
  3771. do {
  3772. m = s.head[--p];
  3773. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  3774. } while (--n);
  3775. n = _w_size;
  3776. p = n;
  3777. do {
  3778. m = s.prev[--p];
  3779. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  3780. /* If n is not on any hash chain, prev[n] is garbage but
  3781. * its value will never be used.
  3782. */
  3783. } while (--n);
  3784. more += _w_size;
  3785. }
  3786. if (s.strm.avail_in === 0) {
  3787. break;
  3788. }
  3789. /* If there was no sliding:
  3790. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  3791. * more == window_size - lookahead - strstart
  3792. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  3793. * => more >= window_size - 2*WSIZE + 2
  3794. * In the BIG_MEM or MMAP case (not yet supported),
  3795. * window_size == input_size + MIN_LOOKAHEAD &&
  3796. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  3797. * Otherwise, window_size == 2*WSIZE so more >= 2.
  3798. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  3799. */
  3800. //Assert(more >= 2, "more < 2");
  3801. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  3802. s.lookahead += n;
  3803. /* Initialize the hash value now that we have some input: */
  3804. if (s.lookahead + s.insert >= MIN_MATCH) {
  3805. str = s.strstart - s.insert;
  3806. s.ins_h = s.window[str];
  3807. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  3808. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  3809. //#if MIN_MATCH != 3
  3810. // Call update_hash() MIN_MATCH-3 more times
  3811. //#endif
  3812. while (s.insert) {
  3813. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  3814. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  3815. s.prev[str & s.w_mask] = s.head[s.ins_h];
  3816. s.head[s.ins_h] = str;
  3817. str++;
  3818. s.insert--;
  3819. if (s.lookahead + s.insert < MIN_MATCH) {
  3820. break;
  3821. }
  3822. }
  3823. }
  3824. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  3825. * but this is not important since only literal bytes will be emitted.
  3826. */
  3827. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  3828. /* If the WIN_INIT bytes after the end of the current data have never been
  3829. * written, then zero those bytes in order to avoid memory check reports of
  3830. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  3831. * the longest match routines. Update the high water mark for the next
  3832. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  3833. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  3834. */
  3835. // if (s.high_water < s.window_size) {
  3836. // var curr = s.strstart + s.lookahead;
  3837. // var init = 0;
  3838. //
  3839. // if (s.high_water < curr) {
  3840. // /* Previous high water mark below current data -- zero WIN_INIT
  3841. // * bytes or up to end of window, whichever is less.
  3842. // */
  3843. // init = s.window_size - curr;
  3844. // if (init > WIN_INIT)
  3845. // init = WIN_INIT;
  3846. // zmemzero(s->window + curr, (unsigned)init);
  3847. // s->high_water = curr + init;
  3848. // }
  3849. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  3850. // /* High water mark at or above current data, but below current data
  3851. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  3852. // * to end of window, whichever is less.
  3853. // */
  3854. // init = (ulg)curr + WIN_INIT - s->high_water;
  3855. // if (init > s->window_size - s->high_water)
  3856. // init = s->window_size - s->high_water;
  3857. // zmemzero(s->window + s->high_water, (unsigned)init);
  3858. // s->high_water += init;
  3859. // }
  3860. // }
  3861. //
  3862. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  3863. // "not enough room for search");
  3864. }
  3865. /* ===========================================================================
  3866. * Copy without compression as much as possible from the input stream, return
  3867. * the current block state.
  3868. * This function does not insert new strings in the dictionary since
  3869. * uncompressible data is probably not useful. This function is used
  3870. * only for the level=0 compression option.
  3871. * NOTE: this function should be optimized to avoid extra copying from
  3872. * window to pending_buf.
  3873. */
  3874. function deflate_stored(s, flush) {
  3875. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  3876. * to pending_buf_size, and each stored block has a 5 byte header:
  3877. */
  3878. var max_block_size = 0xffff;
  3879. if (max_block_size > s.pending_buf_size - 5) {
  3880. max_block_size = s.pending_buf_size - 5;
  3881. }
  3882. /* Copy as much as possible from input to output: */
  3883. for (;;) {
  3884. /* Fill the window as much as possible: */
  3885. if (s.lookahead <= 1) {
  3886. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  3887. // s->block_start >= (long)s->w_size, "slide too late");
  3888. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  3889. // s.block_start >= s.w_size)) {
  3890. // throw new Error("slide too late");
  3891. // }
  3892. fill_window(s);
  3893. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  3894. return BS_NEED_MORE;
  3895. }
  3896. if (s.lookahead === 0) {
  3897. break;
  3898. }
  3899. /* flush the current block */
  3900. }
  3901. //Assert(s->block_start >= 0L, "block gone");
  3902. // if (s.block_start < 0) throw new Error("block gone");
  3903. s.strstart += s.lookahead;
  3904. s.lookahead = 0;
  3905. /* Emit a stored block if pending_buf will be full: */
  3906. var max_start = s.block_start + max_block_size;
  3907. if (s.strstart === 0 || s.strstart >= max_start) {
  3908. /* strstart == 0 is possible when wraparound on 16-bit machine */
  3909. s.lookahead = s.strstart - max_start;
  3910. s.strstart = max_start;
  3911. /*** FLUSH_BLOCK(s, 0); ***/
  3912. flush_block_only(s, false);
  3913. if (s.strm.avail_out === 0) {
  3914. return BS_NEED_MORE;
  3915. }
  3916. /***/
  3917. }
  3918. /* Flush if we may have to slide, otherwise block_start may become
  3919. * negative and the data will be gone:
  3920. */
  3921. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  3922. /*** FLUSH_BLOCK(s, 0); ***/
  3923. flush_block_only(s, false);
  3924. if (s.strm.avail_out === 0) {
  3925. return BS_NEED_MORE;
  3926. }
  3927. /***/
  3928. }
  3929. }
  3930. s.insert = 0;
  3931. if (flush === Z_FINISH) {
  3932. /*** FLUSH_BLOCK(s, 1); ***/
  3933. flush_block_only(s, true);
  3934. if (s.strm.avail_out === 0) {
  3935. return BS_FINISH_STARTED;
  3936. }
  3937. /***/
  3938. return BS_FINISH_DONE;
  3939. }
  3940. if (s.strstart > s.block_start) {
  3941. /*** FLUSH_BLOCK(s, 0); ***/
  3942. flush_block_only(s, false);
  3943. if (s.strm.avail_out === 0) {
  3944. return BS_NEED_MORE;
  3945. }
  3946. /***/
  3947. }
  3948. return BS_NEED_MORE;
  3949. }
  3950. /* ===========================================================================
  3951. * Compress as much as possible from the input stream, return the current
  3952. * block state.
  3953. * This function does not perform lazy evaluation of matches and inserts
  3954. * new strings in the dictionary only for unmatched strings or for short
  3955. * matches. It is used only for the fast compression options.
  3956. */
  3957. function deflate_fast(s, flush) {
  3958. var hash_head; /* head of the hash chain */
  3959. var bflush; /* set if current block must be flushed */
  3960. for (;;) {
  3961. /* Make sure that we always have enough lookahead, except
  3962. * at the end of the input file. We need MAX_MATCH bytes
  3963. * for the next match, plus MIN_MATCH bytes to insert the
  3964. * string following the next match.
  3965. */
  3966. if (s.lookahead < MIN_LOOKAHEAD) {
  3967. fill_window(s);
  3968. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  3969. return BS_NEED_MORE;
  3970. }
  3971. if (s.lookahead === 0) {
  3972. break; /* flush the current block */
  3973. }
  3974. }
  3975. /* Insert the string window[strstart .. strstart+2] in the
  3976. * dictionary, and set hash_head to the head of the hash chain:
  3977. */
  3978. hash_head = 0/*NIL*/;
  3979. if (s.lookahead >= MIN_MATCH) {
  3980. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  3981. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  3982. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  3983. s.head[s.ins_h] = s.strstart;
  3984. /***/
  3985. }
  3986. /* Find the longest match, discarding those <= prev_length.
  3987. * At this point we have always match_length < MIN_MATCH
  3988. */
  3989. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  3990. /* To simplify the code, we prevent matches with the string
  3991. * of window index 0 (in particular we have to avoid a match
  3992. * of the string with itself at the start of the input file).
  3993. */
  3994. s.match_length = longest_match(s, hash_head);
  3995. /* longest_match() sets match_start */
  3996. }
  3997. if (s.match_length >= MIN_MATCH) {
  3998. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  3999. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  4000. s.match_length - MIN_MATCH, bflush); ***/
  4001. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  4002. s.lookahead -= s.match_length;
  4003. /* Insert new strings in the hash table only if the match length
  4004. * is not too large. This saves time but degrades compression.
  4005. */
  4006. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  4007. s.match_length--; /* string at strstart already in table */
  4008. do {
  4009. s.strstart++;
  4010. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4011. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4012. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4013. s.head[s.ins_h] = s.strstart;
  4014. /***/
  4015. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  4016. * always MIN_MATCH bytes ahead.
  4017. */
  4018. } while (--s.match_length !== 0);
  4019. s.strstart++;
  4020. } else
  4021. {
  4022. s.strstart += s.match_length;
  4023. s.match_length = 0;
  4024. s.ins_h = s.window[s.strstart];
  4025. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  4026. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  4027. //#if MIN_MATCH != 3
  4028. // Call UPDATE_HASH() MIN_MATCH-3 more times
  4029. //#endif
  4030. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  4031. * matter since it will be recomputed at next deflate call.
  4032. */
  4033. }
  4034. } else {
  4035. /* No match, output a literal byte */
  4036. //Tracevv((stderr,"%c", s.window[s.strstart]));
  4037. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4038. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4039. s.lookahead--;
  4040. s.strstart++;
  4041. }
  4042. if (bflush) {
  4043. /*** FLUSH_BLOCK(s, 0); ***/
  4044. flush_block_only(s, false);
  4045. if (s.strm.avail_out === 0) {
  4046. return BS_NEED_MORE;
  4047. }
  4048. /***/
  4049. }
  4050. }
  4051. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  4052. if (flush === Z_FINISH) {
  4053. /*** FLUSH_BLOCK(s, 1); ***/
  4054. flush_block_only(s, true);
  4055. if (s.strm.avail_out === 0) {
  4056. return BS_FINISH_STARTED;
  4057. }
  4058. /***/
  4059. return BS_FINISH_DONE;
  4060. }
  4061. if (s.last_lit) {
  4062. /*** FLUSH_BLOCK(s, 0); ***/
  4063. flush_block_only(s, false);
  4064. if (s.strm.avail_out === 0) {
  4065. return BS_NEED_MORE;
  4066. }
  4067. /***/
  4068. }
  4069. return BS_BLOCK_DONE;
  4070. }
  4071. /* ===========================================================================
  4072. * Same as above, but achieves better compression. We use a lazy
  4073. * evaluation for matches: a match is finally adopted only if there is
  4074. * no better match at the next window position.
  4075. */
  4076. function deflate_slow(s, flush) {
  4077. var hash_head; /* head of hash chain */
  4078. var bflush; /* set if current block must be flushed */
  4079. var max_insert;
  4080. /* Process the input block. */
  4081. for (;;) {
  4082. /* Make sure that we always have enough lookahead, except
  4083. * at the end of the input file. We need MAX_MATCH bytes
  4084. * for the next match, plus MIN_MATCH bytes to insert the
  4085. * string following the next match.
  4086. */
  4087. if (s.lookahead < MIN_LOOKAHEAD) {
  4088. fill_window(s);
  4089. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  4090. return BS_NEED_MORE;
  4091. }
  4092. if (s.lookahead === 0) { break; } /* flush the current block */
  4093. }
  4094. /* Insert the string window[strstart .. strstart+2] in the
  4095. * dictionary, and set hash_head to the head of the hash chain:
  4096. */
  4097. hash_head = 0/*NIL*/;
  4098. if (s.lookahead >= MIN_MATCH) {
  4099. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4100. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4101. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4102. s.head[s.ins_h] = s.strstart;
  4103. /***/
  4104. }
  4105. /* Find the longest match, discarding those <= prev_length.
  4106. */
  4107. s.prev_length = s.match_length;
  4108. s.prev_match = s.match_start;
  4109. s.match_length = MIN_MATCH-1;
  4110. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  4111. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  4112. /* To simplify the code, we prevent matches with the string
  4113. * of window index 0 (in particular we have to avoid a match
  4114. * of the string with itself at the start of the input file).
  4115. */
  4116. s.match_length = longest_match(s, hash_head);
  4117. /* longest_match() sets match_start */
  4118. if (s.match_length <= 5 &&
  4119. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  4120. /* If prev_match is also MIN_MATCH, match_start is garbage
  4121. * but we will ignore the current match anyway.
  4122. */
  4123. s.match_length = MIN_MATCH-1;
  4124. }
  4125. }
  4126. /* If there was a match at the previous step and the current
  4127. * match is not better, output the previous match:
  4128. */
  4129. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  4130. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  4131. /* Do not insert strings in hash table beyond this. */
  4132. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  4133. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  4134. s.prev_length - MIN_MATCH, bflush);***/
  4135. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  4136. /* Insert in hash table all strings up to the end of the match.
  4137. * strstart-1 and strstart are already inserted. If there is not
  4138. * enough lookahead, the last two strings are not inserted in
  4139. * the hash table.
  4140. */
  4141. s.lookahead -= s.prev_length-1;
  4142. s.prev_length -= 2;
  4143. do {
  4144. if (++s.strstart <= max_insert) {
  4145. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  4146. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  4147. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  4148. s.head[s.ins_h] = s.strstart;
  4149. /***/
  4150. }
  4151. } while (--s.prev_length !== 0);
  4152. s.match_available = 0;
  4153. s.match_length = MIN_MATCH-1;
  4154. s.strstart++;
  4155. if (bflush) {
  4156. /*** FLUSH_BLOCK(s, 0); ***/
  4157. flush_block_only(s, false);
  4158. if (s.strm.avail_out === 0) {
  4159. return BS_NEED_MORE;
  4160. }
  4161. /***/
  4162. }
  4163. } else if (s.match_available) {
  4164. /* If there was no match at the previous position, output a
  4165. * single literal. If there was a match but the current match
  4166. * is longer, truncate the previous match to a single literal.
  4167. */
  4168. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4169. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4170. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4171. if (bflush) {
  4172. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  4173. flush_block_only(s, false);
  4174. /***/
  4175. }
  4176. s.strstart++;
  4177. s.lookahead--;
  4178. if (s.strm.avail_out === 0) {
  4179. return BS_NEED_MORE;
  4180. }
  4181. } else {
  4182. /* There is no previous match to compare with, wait for
  4183. * the next step to decide.
  4184. */
  4185. s.match_available = 1;
  4186. s.strstart++;
  4187. s.lookahead--;
  4188. }
  4189. }
  4190. //Assert (flush != Z_NO_FLUSH, "no flush?");
  4191. if (s.match_available) {
  4192. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  4193. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  4194. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  4195. s.match_available = 0;
  4196. }
  4197. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  4198. if (flush === Z_FINISH) {
  4199. /*** FLUSH_BLOCK(s, 1); ***/
  4200. flush_block_only(s, true);
  4201. if (s.strm.avail_out === 0) {
  4202. return BS_FINISH_STARTED;
  4203. }
  4204. /***/
  4205. return BS_FINISH_DONE;
  4206. }
  4207. if (s.last_lit) {
  4208. /*** FLUSH_BLOCK(s, 0); ***/
  4209. flush_block_only(s, false);
  4210. if (s.strm.avail_out === 0) {
  4211. return BS_NEED_MORE;
  4212. }
  4213. /***/
  4214. }
  4215. return BS_BLOCK_DONE;
  4216. }
  4217. /* ===========================================================================
  4218. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  4219. * one. Do not maintain a hash table. (It will be regenerated if this run of
  4220. * deflate switches away from Z_RLE.)
  4221. */
  4222. function deflate_rle(s, flush) {
  4223. var bflush; /* set if current block must be flushed */
  4224. var prev; /* byte at distance one to match */
  4225. var scan, strend; /* scan goes up to strend for length of run */
  4226. var _win = s.window;
  4227. for (;;) {
  4228. /* Make sure that we always have enough lookahead, except
  4229. * at the end of the input file. We need MAX_MATCH bytes
  4230. * for the longest run, plus one for the unrolled loop.
  4231. */
  4232. if (s.lookahead <= MAX_MATCH) {
  4233. fill_window(s);
  4234. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  4235. return BS_NEED_MORE;
  4236. }
  4237. if (s.lookahead === 0) { break; } /* flush the current block */
  4238. }
  4239. /* See how many times the previous byte repeats */
  4240. s.match_length = 0;
  4241. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  4242. scan = s.strstart - 1;
  4243. prev = _win[scan];
  4244. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  4245. strend = s.strstart + MAX_MATCH;
  4246. do {
  4247. /*jshint noempty:false*/
  4248. } while (prev === _win[++scan] && prev === _win[++scan] &&
  4249. prev === _win[++scan] && prev === _win[++scan] &&
  4250. prev === _win[++scan] && prev === _win[++scan] &&
  4251. prev === _win[++scan] && prev === _win[++scan] &&
  4252. scan < strend);
  4253. s.match_length = MAX_MATCH - (strend - scan);
  4254. if (s.match_length > s.lookahead) {
  4255. s.match_length = s.lookahead;
  4256. }
  4257. }
  4258. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  4259. }
  4260. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  4261. if (s.match_length >= MIN_MATCH) {
  4262. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  4263. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  4264. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  4265. s.lookahead -= s.match_length;
  4266. s.strstart += s.match_length;
  4267. s.match_length = 0;
  4268. } else {
  4269. /* No match, output a literal byte */
  4270. //Tracevv((stderr,"%c", s->window[s->strstart]));
  4271. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4272. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4273. s.lookahead--;
  4274. s.strstart++;
  4275. }
  4276. if (bflush) {
  4277. /*** FLUSH_BLOCK(s, 0); ***/
  4278. flush_block_only(s, false);
  4279. if (s.strm.avail_out === 0) {
  4280. return BS_NEED_MORE;
  4281. }
  4282. /***/
  4283. }
  4284. }
  4285. s.insert = 0;
  4286. if (flush === Z_FINISH) {
  4287. /*** FLUSH_BLOCK(s, 1); ***/
  4288. flush_block_only(s, true);
  4289. if (s.strm.avail_out === 0) {
  4290. return BS_FINISH_STARTED;
  4291. }
  4292. /***/
  4293. return BS_FINISH_DONE;
  4294. }
  4295. if (s.last_lit) {
  4296. /*** FLUSH_BLOCK(s, 0); ***/
  4297. flush_block_only(s, false);
  4298. if (s.strm.avail_out === 0) {
  4299. return BS_NEED_MORE;
  4300. }
  4301. /***/
  4302. }
  4303. return BS_BLOCK_DONE;
  4304. }
  4305. /* ===========================================================================
  4306. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  4307. * (It will be regenerated if this run of deflate switches away from Huffman.)
  4308. */
  4309. function deflate_huff(s, flush) {
  4310. var bflush; /* set if current block must be flushed */
  4311. for (;;) {
  4312. /* Make sure that we have a literal to write. */
  4313. if (s.lookahead === 0) {
  4314. fill_window(s);
  4315. if (s.lookahead === 0) {
  4316. if (flush === Z_NO_FLUSH) {
  4317. return BS_NEED_MORE;
  4318. }
  4319. break; /* flush the current block */
  4320. }
  4321. }
  4322. /* Output a literal byte */
  4323. s.match_length = 0;
  4324. //Tracevv((stderr,"%c", s->window[s->strstart]));
  4325. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  4326. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  4327. s.lookahead--;
  4328. s.strstart++;
  4329. if (bflush) {
  4330. /*** FLUSH_BLOCK(s, 0); ***/
  4331. flush_block_only(s, false);
  4332. if (s.strm.avail_out === 0) {
  4333. return BS_NEED_MORE;
  4334. }
  4335. /***/
  4336. }
  4337. }
  4338. s.insert = 0;
  4339. if (flush === Z_FINISH) {
  4340. /*** FLUSH_BLOCK(s, 1); ***/
  4341. flush_block_only(s, true);
  4342. if (s.strm.avail_out === 0) {
  4343. return BS_FINISH_STARTED;
  4344. }
  4345. /***/
  4346. return BS_FINISH_DONE;
  4347. }
  4348. if (s.last_lit) {
  4349. /*** FLUSH_BLOCK(s, 0); ***/
  4350. flush_block_only(s, false);
  4351. if (s.strm.avail_out === 0) {
  4352. return BS_NEED_MORE;
  4353. }
  4354. /***/
  4355. }
  4356. return BS_BLOCK_DONE;
  4357. }
  4358. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  4359. * the desired pack level (0..9). The values given below have been tuned to
  4360. * exclude worst case performance for pathological files. Better values may be
  4361. * found for specific files.
  4362. */
  4363. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  4364. this.good_length = good_length;
  4365. this.max_lazy = max_lazy;
  4366. this.nice_length = nice_length;
  4367. this.max_chain = max_chain;
  4368. this.func = func;
  4369. };
  4370. var configuration_table;
  4371. configuration_table = [
  4372. /* good lazy nice chain */
  4373. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  4374. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  4375. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  4376. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  4377. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  4378. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  4379. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  4380. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  4381. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  4382. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  4383. ];
  4384. /* ===========================================================================
  4385. * Initialize the "longest match" routines for a new zlib stream
  4386. */
  4387. function lm_init(s) {
  4388. s.window_size = 2 * s.w_size;
  4389. /*** CLEAR_HASH(s); ***/
  4390. zero(s.head); // Fill with NIL (= 0);
  4391. /* Set the default configuration parameters:
  4392. */
  4393. s.max_lazy_match = configuration_table[s.level].max_lazy;
  4394. s.good_match = configuration_table[s.level].good_length;
  4395. s.nice_match = configuration_table[s.level].nice_length;
  4396. s.max_chain_length = configuration_table[s.level].max_chain;
  4397. s.strstart = 0;
  4398. s.block_start = 0;
  4399. s.lookahead = 0;
  4400. s.insert = 0;
  4401. s.match_length = s.prev_length = MIN_MATCH - 1;
  4402. s.match_available = 0;
  4403. s.ins_h = 0;
  4404. }
  4405. function DeflateState() {
  4406. this.strm = null; /* pointer back to this zlib stream */
  4407. this.status = 0; /* as the name implies */
  4408. this.pending_buf = null; /* output still pending */
  4409. this.pending_buf_size = 0; /* size of pending_buf */
  4410. this.pending_out = 0; /* next pending byte to output to the stream */
  4411. this.pending = 0; /* nb of bytes in the pending buffer */
  4412. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  4413. this.gzhead = null; /* gzip header information to write */
  4414. this.gzindex = 0; /* where in extra, name, or comment */
  4415. this.method = Z_DEFLATED; /* can only be DEFLATED */
  4416. this.last_flush = -1; /* value of flush param for previous deflate call */
  4417. this.w_size = 0; /* LZ77 window size (32K by default) */
  4418. this.w_bits = 0; /* log2(w_size) (8..16) */
  4419. this.w_mask = 0; /* w_size - 1 */
  4420. this.window = null;
  4421. /* Sliding window. Input bytes are read into the second half of the window,
  4422. * and move to the first half later to keep a dictionary of at least wSize
  4423. * bytes. With this organization, matches are limited to a distance of
  4424. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  4425. * performed with a length multiple of the block size.
  4426. */
  4427. this.window_size = 0;
  4428. /* Actual size of window: 2*wSize, except when the user input buffer
  4429. * is directly used as sliding window.
  4430. */
  4431. this.prev = null;
  4432. /* Link to older string with same hash index. To limit the size of this
  4433. * array to 64K, this link is maintained only for the last 32K strings.
  4434. * An index in this array is thus a window index modulo 32K.
  4435. */
  4436. this.head = null; /* Heads of the hash chains or NIL. */
  4437. this.ins_h = 0; /* hash index of string to be inserted */
  4438. this.hash_size = 0; /* number of elements in hash table */
  4439. this.hash_bits = 0; /* log2(hash_size) */
  4440. this.hash_mask = 0; /* hash_size-1 */
  4441. this.hash_shift = 0;
  4442. /* Number of bits by which ins_h must be shifted at each input
  4443. * step. It must be such that after MIN_MATCH steps, the oldest
  4444. * byte no longer takes part in the hash key, that is:
  4445. * hash_shift * MIN_MATCH >= hash_bits
  4446. */
  4447. this.block_start = 0;
  4448. /* Window position at the beginning of the current output block. Gets
  4449. * negative when the window is moved backwards.
  4450. */
  4451. this.match_length = 0; /* length of best match */
  4452. this.prev_match = 0; /* previous match */
  4453. this.match_available = 0; /* set if previous match exists */
  4454. this.strstart = 0; /* start of string to insert */
  4455. this.match_start = 0; /* start of matching string */
  4456. this.lookahead = 0; /* number of valid bytes ahead in window */
  4457. this.prev_length = 0;
  4458. /* Length of the best match at previous step. Matches not greater than this
  4459. * are discarded. This is used in the lazy match evaluation.
  4460. */
  4461. this.max_chain_length = 0;
  4462. /* To speed up deflation, hash chains are never searched beyond this
  4463. * length. A higher limit improves compression ratio but degrades the
  4464. * speed.
  4465. */
  4466. this.max_lazy_match = 0;
  4467. /* Attempt to find a better match only when the current match is strictly
  4468. * smaller than this value. This mechanism is used only for compression
  4469. * levels >= 4.
  4470. */
  4471. // That's alias to max_lazy_match, don't use directly
  4472. //this.max_insert_length = 0;
  4473. /* Insert new strings in the hash table only if the match length is not
  4474. * greater than this length. This saves time but degrades compression.
  4475. * max_insert_length is used only for compression levels <= 3.
  4476. */
  4477. this.level = 0; /* compression level (1..9) */
  4478. this.strategy = 0; /* favor or force Huffman coding*/
  4479. this.good_match = 0;
  4480. /* Use a faster search when the previous match is longer than this */
  4481. this.nice_match = 0; /* Stop searching when current match exceeds this */
  4482. /* used by trees.c: */
  4483. /* Didn't use ct_data typedef below to suppress compiler warning */
  4484. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  4485. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  4486. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  4487. // Use flat array of DOUBLE size, with interleaved fata,
  4488. // because JS does not support effective
  4489. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  4490. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  4491. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  4492. zero(this.dyn_ltree);
  4493. zero(this.dyn_dtree);
  4494. zero(this.bl_tree);
  4495. this.l_desc = null; /* desc. for literal tree */
  4496. this.d_desc = null; /* desc. for distance tree */
  4497. this.bl_desc = null; /* desc. for bit length tree */
  4498. //ush bl_count[MAX_BITS+1];
  4499. this.bl_count = new utils.Buf16(MAX_BITS+1);
  4500. /* number of codes at each bit length for an optimal tree */
  4501. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  4502. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  4503. zero(this.heap);
  4504. this.heap_len = 0; /* number of elements in the heap */
  4505. this.heap_max = 0; /* element of largest frequency */
  4506. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  4507. * The same heap array is used to build all trees.
  4508. */
  4509. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  4510. zero(this.depth);
  4511. /* Depth of each subtree used as tie breaker for trees of equal frequency
  4512. */
  4513. this.l_buf = 0; /* buffer index for literals or lengths */
  4514. this.lit_bufsize = 0;
  4515. /* Size of match buffer for literals/lengths. There are 4 reasons for
  4516. * limiting lit_bufsize to 64K:
  4517. * - frequencies can be kept in 16 bit counters
  4518. * - if compression is not successful for the first block, all input
  4519. * data is still in the window so we can still emit a stored block even
  4520. * when input comes from standard input. (This can also be done for
  4521. * all blocks if lit_bufsize is not greater than 32K.)
  4522. * - if compression is not successful for a file smaller than 64K, we can
  4523. * even emit a stored file instead of a stored block (saving 5 bytes).
  4524. * This is applicable only for zip (not gzip or zlib).
  4525. * - creating new Huffman trees less frequently may not provide fast
  4526. * adaptation to changes in the input data statistics. (Take for
  4527. * example a binary file with poorly compressible code followed by
  4528. * a highly compressible string table.) Smaller buffer sizes give
  4529. * fast adaptation but have of course the overhead of transmitting
  4530. * trees more frequently.
  4531. * - I can't count above 4
  4532. */
  4533. this.last_lit = 0; /* running index in l_buf */
  4534. this.d_buf = 0;
  4535. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  4536. * the same number of elements. To use different lengths, an extra flag
  4537. * array would be necessary.
  4538. */
  4539. this.opt_len = 0; /* bit length of current block with optimal trees */
  4540. this.static_len = 0; /* bit length of current block with static trees */
  4541. this.matches = 0; /* number of string matches in current block */
  4542. this.insert = 0; /* bytes at end of window left to insert */
  4543. this.bi_buf = 0;
  4544. /* Output buffer. bits are inserted starting at the bottom (least
  4545. * significant bits).
  4546. */
  4547. this.bi_valid = 0;
  4548. /* Number of valid bits in bi_buf. All bits above the last valid bit
  4549. * are always zero.
  4550. */
  4551. // Used for window memory init. We safely ignore it for JS. That makes
  4552. // sense only for pointers and memory check tools.
  4553. //this.high_water = 0;
  4554. /* High water mark offset in window for initialized bytes -- bytes above
  4555. * this are set to zero in order to avoid memory check warnings when
  4556. * longest match routines access bytes past the input. This is then
  4557. * updated to the new high water mark.
  4558. */
  4559. }
  4560. function deflateResetKeep(strm) {
  4561. var s;
  4562. if (!strm || !strm.state) {
  4563. return err(strm, Z_STREAM_ERROR);
  4564. }
  4565. strm.total_in = strm.total_out = 0;
  4566. strm.data_type = Z_UNKNOWN;
  4567. s = strm.state;
  4568. s.pending = 0;
  4569. s.pending_out = 0;
  4570. if (s.wrap < 0) {
  4571. s.wrap = -s.wrap;
  4572. /* was made negative by deflate(..., Z_FINISH); */
  4573. }
  4574. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  4575. strm.adler = (s.wrap === 2) ?
  4576. 0 // crc32(0, Z_NULL, 0)
  4577. :
  4578. 1; // adler32(0, Z_NULL, 0)
  4579. s.last_flush = Z_NO_FLUSH;
  4580. trees._tr_init(s);
  4581. return Z_OK;
  4582. }
  4583. function deflateReset(strm) {
  4584. var ret = deflateResetKeep(strm);
  4585. if (ret === Z_OK) {
  4586. lm_init(strm.state);
  4587. }
  4588. return ret;
  4589. }
  4590. function deflateSetHeader(strm, head) {
  4591. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  4592. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  4593. strm.state.gzhead = head;
  4594. return Z_OK;
  4595. }
  4596. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  4597. if (!strm) { // === Z_NULL
  4598. return Z_STREAM_ERROR;
  4599. }
  4600. var wrap = 1;
  4601. if (level === Z_DEFAULT_COMPRESSION) {
  4602. level = 6;
  4603. }
  4604. if (windowBits < 0) { /* suppress zlib wrapper */
  4605. wrap = 0;
  4606. windowBits = -windowBits;
  4607. }
  4608. else if (windowBits > 15) {
  4609. wrap = 2; /* write gzip wrapper instead */
  4610. windowBits -= 16;
  4611. }
  4612. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  4613. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  4614. strategy < 0 || strategy > Z_FIXED) {
  4615. return err(strm, Z_STREAM_ERROR);
  4616. }
  4617. if (windowBits === 8) {
  4618. windowBits = 9;
  4619. }
  4620. /* until 256-byte window bug fixed */
  4621. var s = new DeflateState();
  4622. strm.state = s;
  4623. s.strm = strm;
  4624. s.wrap = wrap;
  4625. s.gzhead = null;
  4626. s.w_bits = windowBits;
  4627. s.w_size = 1 << s.w_bits;
  4628. s.w_mask = s.w_size - 1;
  4629. s.hash_bits = memLevel + 7;
  4630. s.hash_size = 1 << s.hash_bits;
  4631. s.hash_mask = s.hash_size - 1;
  4632. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  4633. s.window = new utils.Buf8(s.w_size * 2);
  4634. s.head = new utils.Buf16(s.hash_size);
  4635. s.prev = new utils.Buf16(s.w_size);
  4636. // Don't need mem init magic for JS.
  4637. //s.high_water = 0; /* nothing written to s->window yet */
  4638. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  4639. s.pending_buf_size = s.lit_bufsize * 4;
  4640. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  4641. s.d_buf = s.lit_bufsize >> 1;
  4642. s.l_buf = (1 + 2) * s.lit_bufsize;
  4643. s.level = level;
  4644. s.strategy = strategy;
  4645. s.method = method;
  4646. return deflateReset(strm);
  4647. }
  4648. function deflateInit(strm, level) {
  4649. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  4650. }
  4651. function deflate(strm, flush) {
  4652. var old_flush, s;
  4653. var beg, val; // for gzip header write only
  4654. if (!strm || !strm.state ||
  4655. flush > Z_BLOCK || flush < 0) {
  4656. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  4657. }
  4658. s = strm.state;
  4659. if (!strm.output ||
  4660. (!strm.input && strm.avail_in !== 0) ||
  4661. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  4662. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  4663. }
  4664. s.strm = strm; /* just in case */
  4665. old_flush = s.last_flush;
  4666. s.last_flush = flush;
  4667. /* Write the header */
  4668. if (s.status === INIT_STATE) {
  4669. if (s.wrap === 2) { // GZIP header
  4670. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  4671. put_byte(s, 31);
  4672. put_byte(s, 139);
  4673. put_byte(s, 8);
  4674. if (!s.gzhead) { // s->gzhead == Z_NULL
  4675. put_byte(s, 0);
  4676. put_byte(s, 0);
  4677. put_byte(s, 0);
  4678. put_byte(s, 0);
  4679. put_byte(s, 0);
  4680. put_byte(s, s.level === 9 ? 2 :
  4681. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  4682. 4 : 0));
  4683. put_byte(s, OS_CODE);
  4684. s.status = BUSY_STATE;
  4685. }
  4686. else {
  4687. put_byte(s, (s.gzhead.text ? 1 : 0) +
  4688. (s.gzhead.hcrc ? 2 : 0) +
  4689. (!s.gzhead.extra ? 0 : 4) +
  4690. (!s.gzhead.name ? 0 : 8) +
  4691. (!s.gzhead.comment ? 0 : 16)
  4692. );
  4693. put_byte(s, s.gzhead.time & 0xff);
  4694. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  4695. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  4696. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  4697. put_byte(s, s.level === 9 ? 2 :
  4698. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  4699. 4 : 0));
  4700. put_byte(s, s.gzhead.os & 0xff);
  4701. if (s.gzhead.extra && s.gzhead.extra.length) {
  4702. put_byte(s, s.gzhead.extra.length & 0xff);
  4703. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  4704. }
  4705. if (s.gzhead.hcrc) {
  4706. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  4707. }
  4708. s.gzindex = 0;
  4709. s.status = EXTRA_STATE;
  4710. }
  4711. }
  4712. else // DEFLATE header
  4713. {
  4714. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  4715. var level_flags = -1;
  4716. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  4717. level_flags = 0;
  4718. } else if (s.level < 6) {
  4719. level_flags = 1;
  4720. } else if (s.level === 6) {
  4721. level_flags = 2;
  4722. } else {
  4723. level_flags = 3;
  4724. }
  4725. header |= (level_flags << 6);
  4726. if (s.strstart !== 0) { header |= PRESET_DICT; }
  4727. header += 31 - (header % 31);
  4728. s.status = BUSY_STATE;
  4729. putShortMSB(s, header);
  4730. /* Save the adler32 of the preset dictionary: */
  4731. if (s.strstart !== 0) {
  4732. putShortMSB(s, strm.adler >>> 16);
  4733. putShortMSB(s, strm.adler & 0xffff);
  4734. }
  4735. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  4736. }
  4737. }
  4738. //#ifdef GZIP
  4739. if (s.status === EXTRA_STATE) {
  4740. if (s.gzhead.extra/* != Z_NULL*/) {
  4741. beg = s.pending; /* start of bytes to update crc */
  4742. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  4743. if (s.pending === s.pending_buf_size) {
  4744. if (s.gzhead.hcrc && s.pending > beg) {
  4745. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4746. }
  4747. flush_pending(strm);
  4748. beg = s.pending;
  4749. if (s.pending === s.pending_buf_size) {
  4750. break;
  4751. }
  4752. }
  4753. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  4754. s.gzindex++;
  4755. }
  4756. if (s.gzhead.hcrc && s.pending > beg) {
  4757. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4758. }
  4759. if (s.gzindex === s.gzhead.extra.length) {
  4760. s.gzindex = 0;
  4761. s.status = NAME_STATE;
  4762. }
  4763. }
  4764. else {
  4765. s.status = NAME_STATE;
  4766. }
  4767. }
  4768. if (s.status === NAME_STATE) {
  4769. if (s.gzhead.name/* != Z_NULL*/) {
  4770. beg = s.pending; /* start of bytes to update crc */
  4771. //int val;
  4772. do {
  4773. if (s.pending === s.pending_buf_size) {
  4774. if (s.gzhead.hcrc && s.pending > beg) {
  4775. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4776. }
  4777. flush_pending(strm);
  4778. beg = s.pending;
  4779. if (s.pending === s.pending_buf_size) {
  4780. val = 1;
  4781. break;
  4782. }
  4783. }
  4784. // JS specific: little magic to add zero terminator to end of string
  4785. if (s.gzindex < s.gzhead.name.length) {
  4786. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  4787. } else {
  4788. val = 0;
  4789. }
  4790. put_byte(s, val);
  4791. } while (val !== 0);
  4792. if (s.gzhead.hcrc && s.pending > beg){
  4793. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4794. }
  4795. if (val === 0) {
  4796. s.gzindex = 0;
  4797. s.status = COMMENT_STATE;
  4798. }
  4799. }
  4800. else {
  4801. s.status = COMMENT_STATE;
  4802. }
  4803. }
  4804. if (s.status === COMMENT_STATE) {
  4805. if (s.gzhead.comment/* != Z_NULL*/) {
  4806. beg = s.pending; /* start of bytes to update crc */
  4807. //int val;
  4808. do {
  4809. if (s.pending === s.pending_buf_size) {
  4810. if (s.gzhead.hcrc && s.pending > beg) {
  4811. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4812. }
  4813. flush_pending(strm);
  4814. beg = s.pending;
  4815. if (s.pending === s.pending_buf_size) {
  4816. val = 1;
  4817. break;
  4818. }
  4819. }
  4820. // JS specific: little magic to add zero terminator to end of string
  4821. if (s.gzindex < s.gzhead.comment.length) {
  4822. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  4823. } else {
  4824. val = 0;
  4825. }
  4826. put_byte(s, val);
  4827. } while (val !== 0);
  4828. if (s.gzhead.hcrc && s.pending > beg) {
  4829. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  4830. }
  4831. if (val === 0) {
  4832. s.status = HCRC_STATE;
  4833. }
  4834. }
  4835. else {
  4836. s.status = HCRC_STATE;
  4837. }
  4838. }
  4839. if (s.status === HCRC_STATE) {
  4840. if (s.gzhead.hcrc) {
  4841. if (s.pending + 2 > s.pending_buf_size) {
  4842. flush_pending(strm);
  4843. }
  4844. if (s.pending + 2 <= s.pending_buf_size) {
  4845. put_byte(s, strm.adler & 0xff);
  4846. put_byte(s, (strm.adler >> 8) & 0xff);
  4847. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  4848. s.status = BUSY_STATE;
  4849. }
  4850. }
  4851. else {
  4852. s.status = BUSY_STATE;
  4853. }
  4854. }
  4855. //#endif
  4856. /* Flush as much pending output as possible */
  4857. if (s.pending !== 0) {
  4858. flush_pending(strm);
  4859. if (strm.avail_out === 0) {
  4860. /* Since avail_out is 0, deflate will be called again with
  4861. * more output space, but possibly with both pending and
  4862. * avail_in equal to zero. There won't be anything to do,
  4863. * but this is not an error situation so make sure we
  4864. * return OK instead of BUF_ERROR at next call of deflate:
  4865. */
  4866. s.last_flush = -1;
  4867. return Z_OK;
  4868. }
  4869. /* Make sure there is something to do and avoid duplicate consecutive
  4870. * flushes. For repeated and useless calls with Z_FINISH, we keep
  4871. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  4872. */
  4873. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  4874. flush !== Z_FINISH) {
  4875. return err(strm, Z_BUF_ERROR);
  4876. }
  4877. /* User must not provide more input after the first FINISH: */
  4878. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  4879. return err(strm, Z_BUF_ERROR);
  4880. }
  4881. /* Start a new block or continue the current one.
  4882. */
  4883. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  4884. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  4885. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  4886. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  4887. configuration_table[s.level].func(s, flush));
  4888. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  4889. s.status = FINISH_STATE;
  4890. }
  4891. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  4892. if (strm.avail_out === 0) {
  4893. s.last_flush = -1;
  4894. /* avoid BUF_ERROR next call, see above */
  4895. }
  4896. return Z_OK;
  4897. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  4898. * of deflate should use the same flush parameter to make sure
  4899. * that the flush is complete. So we don't have to output an
  4900. * empty block here, this will be done at next call. This also
  4901. * ensures that for a very small output buffer, we emit at most
  4902. * one empty block.
  4903. */
  4904. }
  4905. if (bstate === BS_BLOCK_DONE) {
  4906. if (flush === Z_PARTIAL_FLUSH) {
  4907. trees._tr_align(s);
  4908. }
  4909. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  4910. trees._tr_stored_block(s, 0, 0, false);
  4911. /* For a full flush, this empty block will be recognized
  4912. * as a special marker by inflate_sync().
  4913. */
  4914. if (flush === Z_FULL_FLUSH) {
  4915. /*** CLEAR_HASH(s); ***/ /* forget history */
  4916. zero(s.head); // Fill with NIL (= 0);
  4917. if (s.lookahead === 0) {
  4918. s.strstart = 0;
  4919. s.block_start = 0;
  4920. s.insert = 0;
  4921. }
  4922. }
  4923. }
  4924. flush_pending(strm);
  4925. if (strm.avail_out === 0) {
  4926. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  4927. return Z_OK;
  4928. }
  4929. }
  4930. }
  4931. //Assert(strm->avail_out > 0, "bug2");
  4932. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  4933. if (flush !== Z_FINISH) { return Z_OK; }
  4934. if (s.wrap <= 0) { return Z_STREAM_END; }
  4935. /* Write the trailer */
  4936. if (s.wrap === 2) {
  4937. put_byte(s, strm.adler & 0xff);
  4938. put_byte(s, (strm.adler >> 8) & 0xff);
  4939. put_byte(s, (strm.adler >> 16) & 0xff);
  4940. put_byte(s, (strm.adler >> 24) & 0xff);
  4941. put_byte(s, strm.total_in & 0xff);
  4942. put_byte(s, (strm.total_in >> 8) & 0xff);
  4943. put_byte(s, (strm.total_in >> 16) & 0xff);
  4944. put_byte(s, (strm.total_in >> 24) & 0xff);
  4945. }
  4946. else
  4947. {
  4948. putShortMSB(s, strm.adler >>> 16);
  4949. putShortMSB(s, strm.adler & 0xffff);
  4950. }
  4951. flush_pending(strm);
  4952. /* If avail_out is zero, the application will call deflate again
  4953. * to flush the rest.
  4954. */
  4955. if (s.wrap > 0) { s.wrap = -s.wrap; }
  4956. /* write the trailer only once! */
  4957. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  4958. }
  4959. function deflateEnd(strm) {
  4960. var status;
  4961. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  4962. return Z_STREAM_ERROR;
  4963. }
  4964. status = strm.state.status;
  4965. if (status !== INIT_STATE &&
  4966. status !== EXTRA_STATE &&
  4967. status !== NAME_STATE &&
  4968. status !== COMMENT_STATE &&
  4969. status !== HCRC_STATE &&
  4970. status !== BUSY_STATE &&
  4971. status !== FINISH_STATE
  4972. ) {
  4973. return err(strm, Z_STREAM_ERROR);
  4974. }
  4975. strm.state = null;
  4976. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  4977. }
  4978. /* =========================================================================
  4979. * Copy the source state to the destination state
  4980. */
  4981. //function deflateCopy(dest, source) {
  4982. //
  4983. //}
  4984. exports.deflateInit = deflateInit;
  4985. exports.deflateInit2 = deflateInit2;
  4986. exports.deflateReset = deflateReset;
  4987. exports.deflateResetKeep = deflateResetKeep;
  4988. exports.deflateSetHeader = deflateSetHeader;
  4989. exports.deflate = deflate;
  4990. exports.deflateEnd = deflateEnd;
  4991. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  4992. /* Not implemented
  4993. exports.deflateBound = deflateBound;
  4994. exports.deflateCopy = deflateCopy;
  4995. exports.deflateSetDictionary = deflateSetDictionary;
  4996. exports.deflateParams = deflateParams;
  4997. exports.deflatePending = deflatePending;
  4998. exports.deflatePrime = deflatePrime;
  4999. exports.deflateTune = deflateTune;
  5000. */
  5001. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(_dereq_,module,exports){
  5002. 'use strict';
  5003. function GZheader() {
  5004. /* true if compressed data believed to be text */
  5005. this.text = 0;
  5006. /* modification time */
  5007. this.time = 0;
  5008. /* extra flags (not used when writing a gzip file) */
  5009. this.xflags = 0;
  5010. /* operating system */
  5011. this.os = 0;
  5012. /* pointer to extra field or Z_NULL if none */
  5013. this.extra = null;
  5014. /* extra field length (valid if extra != Z_NULL) */
  5015. this.extra_len = 0; // Actually, we don't need it in JS,
  5016. // but leave for few code modifications
  5017. //
  5018. // Setup limits is not necessary because in js we should not preallocate memory
  5019. // for inflate use constant limit in 65536 bytes
  5020. //
  5021. /* space at extra (only when reading header) */
  5022. // this.extra_max = 0;
  5023. /* pointer to zero-terminated file name or Z_NULL */
  5024. this.name = '';
  5025. /* space at name (only when reading header) */
  5026. // this.name_max = 0;
  5027. /* pointer to zero-terminated comment or Z_NULL */
  5028. this.comment = '';
  5029. /* space at comment (only when reading header) */
  5030. // this.comm_max = 0;
  5031. /* true if there was or will be a header crc */
  5032. this.hcrc = 0;
  5033. /* true when done reading gzip header (not used when writing a gzip file) */
  5034. this.done = false;
  5035. }
  5036. module.exports = GZheader;
  5037. },{}],34:[function(_dereq_,module,exports){
  5038. 'use strict';
  5039. // See state defs from inflate.js
  5040. var BAD = 30; /* got a data error -- remain here until reset */
  5041. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5042. /*
  5043. Decode literal, length, and distance codes and write out the resulting
  5044. literal and match bytes until either not enough input or output is
  5045. available, an end-of-block is encountered, or a data error is encountered.
  5046. When large enough input and output buffers are supplied to inflate(), for
  5047. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  5048. inflate execution time is spent in this routine.
  5049. Entry assumptions:
  5050. state.mode === LEN
  5051. strm.avail_in >= 6
  5052. strm.avail_out >= 258
  5053. start >= strm.avail_out
  5054. state.bits < 8
  5055. On return, state.mode is one of:
  5056. LEN -- ran out of enough output space or enough available input
  5057. TYPE -- reached end of block code, inflate() to interpret next block
  5058. BAD -- error in block data
  5059. Notes:
  5060. - The maximum input bits used by a length/distance pair is 15 bits for the
  5061. length code, 5 bits for the length extra, 15 bits for the distance code,
  5062. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  5063. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  5064. checking for available input while decoding.
  5065. - The maximum bytes that a single length/distance pair can output is 258
  5066. bytes, which is the maximum length that can be coded. inflate_fast()
  5067. requires strm.avail_out >= 258 for each loop to avoid checking for
  5068. output space.
  5069. */
  5070. module.exports = function inflate_fast(strm, start) {
  5071. var state;
  5072. var _in; /* local strm.input */
  5073. var last; /* have enough input while in < last */
  5074. var _out; /* local strm.output */
  5075. var beg; /* inflate()'s initial strm.output */
  5076. var end; /* while out < end, enough space available */
  5077. //#ifdef INFLATE_STRICT
  5078. var dmax; /* maximum distance from zlib header */
  5079. //#endif
  5080. var wsize; /* window size or zero if not using window */
  5081. var whave; /* valid bytes in the window */
  5082. var wnext; /* window write index */
  5083. var window; /* allocated sliding window, if wsize != 0 */
  5084. var hold; /* local strm.hold */
  5085. var bits; /* local strm.bits */
  5086. var lcode; /* local strm.lencode */
  5087. var dcode; /* local strm.distcode */
  5088. var lmask; /* mask for first level of length codes */
  5089. var dmask; /* mask for first level of distance codes */
  5090. var here; /* retrieved table entry */
  5091. var op; /* code bits, operation, extra bits, or */
  5092. /* window position, window bytes to copy */
  5093. var len; /* match length, unused bytes */
  5094. var dist; /* match distance */
  5095. var from; /* where to copy match from */
  5096. var from_source;
  5097. var input, output; // JS specific, because we have no pointers
  5098. /* copy state to local variables */
  5099. state = strm.state;
  5100. //here = state.here;
  5101. _in = strm.next_in;
  5102. input = strm.input;
  5103. last = _in + (strm.avail_in - 5);
  5104. _out = strm.next_out;
  5105. output = strm.output;
  5106. beg = _out - (start - strm.avail_out);
  5107. end = _out + (strm.avail_out - 257);
  5108. //#ifdef INFLATE_STRICT
  5109. dmax = state.dmax;
  5110. //#endif
  5111. wsize = state.wsize;
  5112. whave = state.whave;
  5113. wnext = state.wnext;
  5114. window = state.window;
  5115. hold = state.hold;
  5116. bits = state.bits;
  5117. lcode = state.lencode;
  5118. dcode = state.distcode;
  5119. lmask = (1 << state.lenbits) - 1;
  5120. dmask = (1 << state.distbits) - 1;
  5121. /* decode literals and length/distances until end-of-block or not enough
  5122. input data or output space */
  5123. top:
  5124. do {
  5125. if (bits < 15) {
  5126. hold += input[_in++] << bits;
  5127. bits += 8;
  5128. hold += input[_in++] << bits;
  5129. bits += 8;
  5130. }
  5131. here = lcode[hold & lmask];
  5132. dolen:
  5133. for (;;) { // Goto emulation
  5134. op = here >>> 24/*here.bits*/;
  5135. hold >>>= op;
  5136. bits -= op;
  5137. op = (here >>> 16) & 0xff/*here.op*/;
  5138. if (op === 0) { /* literal */
  5139. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  5140. // "inflate: literal '%c'\n" :
  5141. // "inflate: literal 0x%02x\n", here.val));
  5142. output[_out++] = here & 0xffff/*here.val*/;
  5143. }
  5144. else if (op & 16) { /* length base */
  5145. len = here & 0xffff/*here.val*/;
  5146. op &= 15; /* number of extra bits */
  5147. if (op) {
  5148. if (bits < op) {
  5149. hold += input[_in++] << bits;
  5150. bits += 8;
  5151. }
  5152. len += hold & ((1 << op) - 1);
  5153. hold >>>= op;
  5154. bits -= op;
  5155. }
  5156. //Tracevv((stderr, "inflate: length %u\n", len));
  5157. if (bits < 15) {
  5158. hold += input[_in++] << bits;
  5159. bits += 8;
  5160. hold += input[_in++] << bits;
  5161. bits += 8;
  5162. }
  5163. here = dcode[hold & dmask];
  5164. dodist:
  5165. for (;;) { // goto emulation
  5166. op = here >>> 24/*here.bits*/;
  5167. hold >>>= op;
  5168. bits -= op;
  5169. op = (here >>> 16) & 0xff/*here.op*/;
  5170. if (op & 16) { /* distance base */
  5171. dist = here & 0xffff/*here.val*/;
  5172. op &= 15; /* number of extra bits */
  5173. if (bits < op) {
  5174. hold += input[_in++] << bits;
  5175. bits += 8;
  5176. if (bits < op) {
  5177. hold += input[_in++] << bits;
  5178. bits += 8;
  5179. }
  5180. }
  5181. dist += hold & ((1 << op) - 1);
  5182. //#ifdef INFLATE_STRICT
  5183. if (dist > dmax) {
  5184. strm.msg = 'invalid distance too far back';
  5185. state.mode = BAD;
  5186. break top;
  5187. }
  5188. //#endif
  5189. hold >>>= op;
  5190. bits -= op;
  5191. //Tracevv((stderr, "inflate: distance %u\n", dist));
  5192. op = _out - beg; /* max distance in output */
  5193. if (dist > op) { /* see if copy from window */
  5194. op = dist - op; /* distance back in window */
  5195. if (op > whave) {
  5196. if (state.sane) {
  5197. strm.msg = 'invalid distance too far back';
  5198. state.mode = BAD;
  5199. break top;
  5200. }
  5201. // (!) This block is disabled in zlib defailts,
  5202. // don't enable it for binary compatibility
  5203. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  5204. // if (len <= op - whave) {
  5205. // do {
  5206. // output[_out++] = 0;
  5207. // } while (--len);
  5208. // continue top;
  5209. // }
  5210. // len -= op - whave;
  5211. // do {
  5212. // output[_out++] = 0;
  5213. // } while (--op > whave);
  5214. // if (op === 0) {
  5215. // from = _out - dist;
  5216. // do {
  5217. // output[_out++] = output[from++];
  5218. // } while (--len);
  5219. // continue top;
  5220. // }
  5221. //#endif
  5222. }
  5223. from = 0; // window index
  5224. from_source = window;
  5225. if (wnext === 0) { /* very common case */
  5226. from += wsize - op;
  5227. if (op < len) { /* some from window */
  5228. len -= op;
  5229. do {
  5230. output[_out++] = window[from++];
  5231. } while (--op);
  5232. from = _out - dist; /* rest from output */
  5233. from_source = output;
  5234. }
  5235. }
  5236. else if (wnext < op) { /* wrap around window */
  5237. from += wsize + wnext - op;
  5238. op -= wnext;
  5239. if (op < len) { /* some from end of window */
  5240. len -= op;
  5241. do {
  5242. output[_out++] = window[from++];
  5243. } while (--op);
  5244. from = 0;
  5245. if (wnext < len) { /* some from start of window */
  5246. op = wnext;
  5247. len -= op;
  5248. do {
  5249. output[_out++] = window[from++];
  5250. } while (--op);
  5251. from = _out - dist; /* rest from output */
  5252. from_source = output;
  5253. }
  5254. }
  5255. }
  5256. else { /* contiguous in window */
  5257. from += wnext - op;
  5258. if (op < len) { /* some from window */
  5259. len -= op;
  5260. do {
  5261. output[_out++] = window[from++];
  5262. } while (--op);
  5263. from = _out - dist; /* rest from output */
  5264. from_source = output;
  5265. }
  5266. }
  5267. while (len > 2) {
  5268. output[_out++] = from_source[from++];
  5269. output[_out++] = from_source[from++];
  5270. output[_out++] = from_source[from++];
  5271. len -= 3;
  5272. }
  5273. if (len) {
  5274. output[_out++] = from_source[from++];
  5275. if (len > 1) {
  5276. output[_out++] = from_source[from++];
  5277. }
  5278. }
  5279. }
  5280. else {
  5281. from = _out - dist; /* copy direct from output */
  5282. do { /* minimum length is three */
  5283. output[_out++] = output[from++];
  5284. output[_out++] = output[from++];
  5285. output[_out++] = output[from++];
  5286. len -= 3;
  5287. } while (len > 2);
  5288. if (len) {
  5289. output[_out++] = output[from++];
  5290. if (len > 1) {
  5291. output[_out++] = output[from++];
  5292. }
  5293. }
  5294. }
  5295. }
  5296. else if ((op & 64) === 0) { /* 2nd level distance code */
  5297. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  5298. continue dodist;
  5299. }
  5300. else {
  5301. strm.msg = 'invalid distance code';
  5302. state.mode = BAD;
  5303. break top;
  5304. }
  5305. break; // need to emulate goto via "continue"
  5306. }
  5307. }
  5308. else if ((op & 64) === 0) { /* 2nd level length code */
  5309. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  5310. continue dolen;
  5311. }
  5312. else if (op & 32) { /* end-of-block */
  5313. //Tracevv((stderr, "inflate: end of block\n"));
  5314. state.mode = TYPE;
  5315. break top;
  5316. }
  5317. else {
  5318. strm.msg = 'invalid literal/length code';
  5319. state.mode = BAD;
  5320. break top;
  5321. }
  5322. break; // need to emulate goto via "continue"
  5323. }
  5324. } while (_in < last && _out < end);
  5325. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  5326. len = bits >> 3;
  5327. _in -= len;
  5328. bits -= len << 3;
  5329. hold &= (1 << bits) - 1;
  5330. /* update state and return */
  5331. strm.next_in = _in;
  5332. strm.next_out = _out;
  5333. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  5334. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  5335. state.hold = hold;
  5336. state.bits = bits;
  5337. return;
  5338. };
  5339. },{}],35:[function(_dereq_,module,exports){
  5340. 'use strict';
  5341. var utils = _dereq_('../utils/common');
  5342. var adler32 = _dereq_('./adler32');
  5343. var crc32 = _dereq_('./crc32');
  5344. var inflate_fast = _dereq_('./inffast');
  5345. var inflate_table = _dereq_('./inftrees');
  5346. var CODES = 0;
  5347. var LENS = 1;
  5348. var DISTS = 2;
  5349. /* Public constants ==========================================================*/
  5350. /* ===========================================================================*/
  5351. /* Allowed flush values; see deflate() and inflate() below for details */
  5352. //var Z_NO_FLUSH = 0;
  5353. //var Z_PARTIAL_FLUSH = 1;
  5354. //var Z_SYNC_FLUSH = 2;
  5355. //var Z_FULL_FLUSH = 3;
  5356. var Z_FINISH = 4;
  5357. var Z_BLOCK = 5;
  5358. var Z_TREES = 6;
  5359. /* Return codes for the compression/decompression functions. Negative values
  5360. * are errors, positive values are used for special but normal events.
  5361. */
  5362. var Z_OK = 0;
  5363. var Z_STREAM_END = 1;
  5364. var Z_NEED_DICT = 2;
  5365. //var Z_ERRNO = -1;
  5366. var Z_STREAM_ERROR = -2;
  5367. var Z_DATA_ERROR = -3;
  5368. var Z_MEM_ERROR = -4;
  5369. var Z_BUF_ERROR = -5;
  5370. //var Z_VERSION_ERROR = -6;
  5371. /* The deflate compression method */
  5372. var Z_DEFLATED = 8;
  5373. /* STATES ====================================================================*/
  5374. /* ===========================================================================*/
  5375. var HEAD = 1; /* i: waiting for magic header */
  5376. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  5377. var TIME = 3; /* i: waiting for modification time (gzip) */
  5378. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  5379. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  5380. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  5381. var NAME = 7; /* i: waiting for end of file name (gzip) */
  5382. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  5383. var HCRC = 9; /* i: waiting for header crc (gzip) */
  5384. var DICTID = 10; /* i: waiting for dictionary check value */
  5385. var DICT = 11; /* waiting for inflateSetDictionary() call */
  5386. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5387. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  5388. var STORED = 14; /* i: waiting for stored size (length and complement) */
  5389. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  5390. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  5391. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  5392. var LENLENS = 18; /* i: waiting for code length code lengths */
  5393. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  5394. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  5395. var LEN = 21; /* i: waiting for length/lit/eob code */
  5396. var LENEXT = 22; /* i: waiting for length extra bits */
  5397. var DIST = 23; /* i: waiting for distance code */
  5398. var DISTEXT = 24; /* i: waiting for distance extra bits */
  5399. var MATCH = 25; /* o: waiting for output space to copy string */
  5400. var LIT = 26; /* o: waiting for output space to write literal */
  5401. var CHECK = 27; /* i: waiting for 32-bit check value */
  5402. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  5403. var DONE = 29; /* finished check, done -- remain here until reset */
  5404. var BAD = 30; /* got a data error -- remain here until reset */
  5405. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  5406. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  5407. /* ===========================================================================*/
  5408. var ENOUGH_LENS = 852;
  5409. var ENOUGH_DISTS = 592;
  5410. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  5411. var MAX_WBITS = 15;
  5412. /* 32K LZ77 window */
  5413. var DEF_WBITS = MAX_WBITS;
  5414. function ZSWAP32(q) {
  5415. return (((q >>> 24) & 0xff) +
  5416. ((q >>> 8) & 0xff00) +
  5417. ((q & 0xff00) << 8) +
  5418. ((q & 0xff) << 24));
  5419. }
  5420. function InflateState() {
  5421. this.mode = 0; /* current inflate mode */
  5422. this.last = false; /* true if processing last block */
  5423. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  5424. this.havedict = false; /* true if dictionary provided */
  5425. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  5426. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  5427. this.check = 0; /* protected copy of check value */
  5428. this.total = 0; /* protected copy of output count */
  5429. // TODO: may be {}
  5430. this.head = null; /* where to save gzip header information */
  5431. /* sliding window */
  5432. this.wbits = 0; /* log base 2 of requested window size */
  5433. this.wsize = 0; /* window size or zero if not using window */
  5434. this.whave = 0; /* valid bytes in the window */
  5435. this.wnext = 0; /* window write index */
  5436. this.window = null; /* allocated sliding window, if needed */
  5437. /* bit accumulator */
  5438. this.hold = 0; /* input bit accumulator */
  5439. this.bits = 0; /* number of bits in "in" */
  5440. /* for string and stored block copying */
  5441. this.length = 0; /* literal or length of data to copy */
  5442. this.offset = 0; /* distance back to copy string from */
  5443. /* for table and code decoding */
  5444. this.extra = 0; /* extra bits needed */
  5445. /* fixed and dynamic code tables */
  5446. this.lencode = null; /* starting table for length/literal codes */
  5447. this.distcode = null; /* starting table for distance codes */
  5448. this.lenbits = 0; /* index bits for lencode */
  5449. this.distbits = 0; /* index bits for distcode */
  5450. /* dynamic table building */
  5451. this.ncode = 0; /* number of code length code lengths */
  5452. this.nlen = 0; /* number of length code lengths */
  5453. this.ndist = 0; /* number of distance code lengths */
  5454. this.have = 0; /* number of code lengths in lens[] */
  5455. this.next = null; /* next available space in codes[] */
  5456. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  5457. this.work = new utils.Buf16(288); /* work area for code table building */
  5458. /*
  5459. because we don't have pointers in js, we use lencode and distcode directly
  5460. as buffers so we don't need codes
  5461. */
  5462. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  5463. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  5464. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  5465. this.sane = 0; /* if false, allow invalid distance too far */
  5466. this.back = 0; /* bits back of last unprocessed length/lit */
  5467. this.was = 0; /* initial length of match */
  5468. }
  5469. function inflateResetKeep(strm) {
  5470. var state;
  5471. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5472. state = strm.state;
  5473. strm.total_in = strm.total_out = state.total = 0;
  5474. strm.msg = ''; /*Z_NULL*/
  5475. if (state.wrap) { /* to support ill-conceived Java test suite */
  5476. strm.adler = state.wrap & 1;
  5477. }
  5478. state.mode = HEAD;
  5479. state.last = 0;
  5480. state.havedict = 0;
  5481. state.dmax = 32768;
  5482. state.head = null/*Z_NULL*/;
  5483. state.hold = 0;
  5484. state.bits = 0;
  5485. //state.lencode = state.distcode = state.next = state.codes;
  5486. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  5487. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  5488. state.sane = 1;
  5489. state.back = -1;
  5490. //Tracev((stderr, "inflate: reset\n"));
  5491. return Z_OK;
  5492. }
  5493. function inflateReset(strm) {
  5494. var state;
  5495. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5496. state = strm.state;
  5497. state.wsize = 0;
  5498. state.whave = 0;
  5499. state.wnext = 0;
  5500. return inflateResetKeep(strm);
  5501. }
  5502. function inflateReset2(strm, windowBits) {
  5503. var wrap;
  5504. var state;
  5505. /* get the state */
  5506. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5507. state = strm.state;
  5508. /* extract wrap request from windowBits parameter */
  5509. if (windowBits < 0) {
  5510. wrap = 0;
  5511. windowBits = -windowBits;
  5512. }
  5513. else {
  5514. wrap = (windowBits >> 4) + 1;
  5515. if (windowBits < 48) {
  5516. windowBits &= 15;
  5517. }
  5518. }
  5519. /* set number of window bits, free window if different */
  5520. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  5521. return Z_STREAM_ERROR;
  5522. }
  5523. if (state.window !== null && state.wbits !== windowBits) {
  5524. state.window = null;
  5525. }
  5526. /* update state and reset the rest of it */
  5527. state.wrap = wrap;
  5528. state.wbits = windowBits;
  5529. return inflateReset(strm);
  5530. }
  5531. function inflateInit2(strm, windowBits) {
  5532. var ret;
  5533. var state;
  5534. if (!strm) { return Z_STREAM_ERROR; }
  5535. //strm.msg = Z_NULL; /* in case we return an error */
  5536. state = new InflateState();
  5537. //if (state === Z_NULL) return Z_MEM_ERROR;
  5538. //Tracev((stderr, "inflate: allocated\n"));
  5539. strm.state = state;
  5540. state.window = null/*Z_NULL*/;
  5541. ret = inflateReset2(strm, windowBits);
  5542. if (ret !== Z_OK) {
  5543. strm.state = null/*Z_NULL*/;
  5544. }
  5545. return ret;
  5546. }
  5547. function inflateInit(strm) {
  5548. return inflateInit2(strm, DEF_WBITS);
  5549. }
  5550. /*
  5551. Return state with length and distance decoding tables and index sizes set to
  5552. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  5553. If BUILDFIXED is defined, then instead this routine builds the tables the
  5554. first time it's called, and returns those tables the first time and
  5555. thereafter. This reduces the size of the code by about 2K bytes, in
  5556. exchange for a little execution time. However, BUILDFIXED should not be
  5557. used for threaded applications, since the rewriting of the tables and virgin
  5558. may not be thread-safe.
  5559. */
  5560. var virgin = true;
  5561. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  5562. function fixedtables(state) {
  5563. /* build fixed huffman tables if first call (may not be thread safe) */
  5564. if (virgin) {
  5565. var sym;
  5566. lenfix = new utils.Buf32(512);
  5567. distfix = new utils.Buf32(32);
  5568. /* literal/length table */
  5569. sym = 0;
  5570. while (sym < 144) { state.lens[sym++] = 8; }
  5571. while (sym < 256) { state.lens[sym++] = 9; }
  5572. while (sym < 280) { state.lens[sym++] = 7; }
  5573. while (sym < 288) { state.lens[sym++] = 8; }
  5574. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  5575. /* distance table */
  5576. sym = 0;
  5577. while (sym < 32) { state.lens[sym++] = 5; }
  5578. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  5579. /* do this just once */
  5580. virgin = false;
  5581. }
  5582. state.lencode = lenfix;
  5583. state.lenbits = 9;
  5584. state.distcode = distfix;
  5585. state.distbits = 5;
  5586. }
  5587. /*
  5588. Update the window with the last wsize (normally 32K) bytes written before
  5589. returning. If window does not exist yet, create it. This is only called
  5590. when a window is already in use, or when output has been written during this
  5591. inflate call, but the end of the deflate stream has not been reached yet.
  5592. It is also called to create a window for dictionary data when a dictionary
  5593. is loaded.
  5594. Providing output buffers larger than 32K to inflate() should provide a speed
  5595. advantage, since only the last 32K of output is copied to the sliding window
  5596. upon return from inflate(), and since all distances after the first 32K of
  5597. output will fall in the output data, making match copies simpler and faster.
  5598. The advantage may be dependent on the size of the processor's data caches.
  5599. */
  5600. function updatewindow(strm, src, end, copy) {
  5601. var dist;
  5602. var state = strm.state;
  5603. /* if it hasn't been done already, allocate space for the window */
  5604. if (state.window === null) {
  5605. state.wsize = 1 << state.wbits;
  5606. state.wnext = 0;
  5607. state.whave = 0;
  5608. state.window = new utils.Buf8(state.wsize);
  5609. }
  5610. /* copy state->wsize or less output bytes into the circular window */
  5611. if (copy >= state.wsize) {
  5612. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  5613. state.wnext = 0;
  5614. state.whave = state.wsize;
  5615. }
  5616. else {
  5617. dist = state.wsize - state.wnext;
  5618. if (dist > copy) {
  5619. dist = copy;
  5620. }
  5621. //zmemcpy(state->window + state->wnext, end - copy, dist);
  5622. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  5623. copy -= dist;
  5624. if (copy) {
  5625. //zmemcpy(state->window, end - copy, copy);
  5626. utils.arraySet(state.window,src, end - copy, copy, 0);
  5627. state.wnext = copy;
  5628. state.whave = state.wsize;
  5629. }
  5630. else {
  5631. state.wnext += dist;
  5632. if (state.wnext === state.wsize) { state.wnext = 0; }
  5633. if (state.whave < state.wsize) { state.whave += dist; }
  5634. }
  5635. }
  5636. return 0;
  5637. }
  5638. function inflate(strm, flush) {
  5639. var state;
  5640. var input, output; // input/output buffers
  5641. var next; /* next input INDEX */
  5642. var put; /* next output INDEX */
  5643. var have, left; /* available input and output */
  5644. var hold; /* bit buffer */
  5645. var bits; /* bits in bit buffer */
  5646. var _in, _out; /* save starting available input and output */
  5647. var copy; /* number of stored or match bytes to copy */
  5648. var from; /* where to copy match bytes from */
  5649. var from_source;
  5650. var here = 0; /* current decoding table entry */
  5651. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  5652. //var last; /* parent table entry */
  5653. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  5654. var len; /* length to copy for repeats, bits to drop */
  5655. var ret; /* return code */
  5656. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  5657. var opts;
  5658. var n; // temporary var for NEED_BITS
  5659. var order = /* permutation of code lengths */
  5660. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  5661. if (!strm || !strm.state || !strm.output ||
  5662. (!strm.input && strm.avail_in !== 0)) {
  5663. return Z_STREAM_ERROR;
  5664. }
  5665. state = strm.state;
  5666. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  5667. //--- LOAD() ---
  5668. put = strm.next_out;
  5669. output = strm.output;
  5670. left = strm.avail_out;
  5671. next = strm.next_in;
  5672. input = strm.input;
  5673. have = strm.avail_in;
  5674. hold = state.hold;
  5675. bits = state.bits;
  5676. //---
  5677. _in = have;
  5678. _out = left;
  5679. ret = Z_OK;
  5680. inf_leave: // goto emulation
  5681. for (;;) {
  5682. switch (state.mode) {
  5683. case HEAD:
  5684. if (state.wrap === 0) {
  5685. state.mode = TYPEDO;
  5686. break;
  5687. }
  5688. //=== NEEDBITS(16);
  5689. while (bits < 16) {
  5690. if (have === 0) { break inf_leave; }
  5691. have--;
  5692. hold += input[next++] << bits;
  5693. bits += 8;
  5694. }
  5695. //===//
  5696. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  5697. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  5698. //=== CRC2(state.check, hold);
  5699. hbuf[0] = hold & 0xff;
  5700. hbuf[1] = (hold >>> 8) & 0xff;
  5701. state.check = crc32(state.check, hbuf, 2, 0);
  5702. //===//
  5703. //=== INITBITS();
  5704. hold = 0;
  5705. bits = 0;
  5706. //===//
  5707. state.mode = FLAGS;
  5708. break;
  5709. }
  5710. state.flags = 0; /* expect zlib header */
  5711. if (state.head) {
  5712. state.head.done = false;
  5713. }
  5714. if (!(state.wrap & 1) || /* check if zlib header allowed */
  5715. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  5716. strm.msg = 'incorrect header check';
  5717. state.mode = BAD;
  5718. break;
  5719. }
  5720. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  5721. strm.msg = 'unknown compression method';
  5722. state.mode = BAD;
  5723. break;
  5724. }
  5725. //--- DROPBITS(4) ---//
  5726. hold >>>= 4;
  5727. bits -= 4;
  5728. //---//
  5729. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  5730. if (state.wbits === 0) {
  5731. state.wbits = len;
  5732. }
  5733. else if (len > state.wbits) {
  5734. strm.msg = 'invalid window size';
  5735. state.mode = BAD;
  5736. break;
  5737. }
  5738. state.dmax = 1 << len;
  5739. //Tracev((stderr, "inflate: zlib header ok\n"));
  5740. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  5741. state.mode = hold & 0x200 ? DICTID : TYPE;
  5742. //=== INITBITS();
  5743. hold = 0;
  5744. bits = 0;
  5745. //===//
  5746. break;
  5747. case FLAGS:
  5748. //=== NEEDBITS(16); */
  5749. while (bits < 16) {
  5750. if (have === 0) { break inf_leave; }
  5751. have--;
  5752. hold += input[next++] << bits;
  5753. bits += 8;
  5754. }
  5755. //===//
  5756. state.flags = hold;
  5757. if ((state.flags & 0xff) !== Z_DEFLATED) {
  5758. strm.msg = 'unknown compression method';
  5759. state.mode = BAD;
  5760. break;
  5761. }
  5762. if (state.flags & 0xe000) {
  5763. strm.msg = 'unknown header flags set';
  5764. state.mode = BAD;
  5765. break;
  5766. }
  5767. if (state.head) {
  5768. state.head.text = ((hold >> 8) & 1);
  5769. }
  5770. if (state.flags & 0x0200) {
  5771. //=== CRC2(state.check, hold);
  5772. hbuf[0] = hold & 0xff;
  5773. hbuf[1] = (hold >>> 8) & 0xff;
  5774. state.check = crc32(state.check, hbuf, 2, 0);
  5775. //===//
  5776. }
  5777. //=== INITBITS();
  5778. hold = 0;
  5779. bits = 0;
  5780. //===//
  5781. state.mode = TIME;
  5782. /* falls through */
  5783. case TIME:
  5784. //=== NEEDBITS(32); */
  5785. while (bits < 32) {
  5786. if (have === 0) { break inf_leave; }
  5787. have--;
  5788. hold += input[next++] << bits;
  5789. bits += 8;
  5790. }
  5791. //===//
  5792. if (state.head) {
  5793. state.head.time = hold;
  5794. }
  5795. if (state.flags & 0x0200) {
  5796. //=== CRC4(state.check, hold)
  5797. hbuf[0] = hold & 0xff;
  5798. hbuf[1] = (hold >>> 8) & 0xff;
  5799. hbuf[2] = (hold >>> 16) & 0xff;
  5800. hbuf[3] = (hold >>> 24) & 0xff;
  5801. state.check = crc32(state.check, hbuf, 4, 0);
  5802. //===
  5803. }
  5804. //=== INITBITS();
  5805. hold = 0;
  5806. bits = 0;
  5807. //===//
  5808. state.mode = OS;
  5809. /* falls through */
  5810. case OS:
  5811. //=== NEEDBITS(16); */
  5812. while (bits < 16) {
  5813. if (have === 0) { break inf_leave; }
  5814. have--;
  5815. hold += input[next++] << bits;
  5816. bits += 8;
  5817. }
  5818. //===//
  5819. if (state.head) {
  5820. state.head.xflags = (hold & 0xff);
  5821. state.head.os = (hold >> 8);
  5822. }
  5823. if (state.flags & 0x0200) {
  5824. //=== CRC2(state.check, hold);
  5825. hbuf[0] = hold & 0xff;
  5826. hbuf[1] = (hold >>> 8) & 0xff;
  5827. state.check = crc32(state.check, hbuf, 2, 0);
  5828. //===//
  5829. }
  5830. //=== INITBITS();
  5831. hold = 0;
  5832. bits = 0;
  5833. //===//
  5834. state.mode = EXLEN;
  5835. /* falls through */
  5836. case EXLEN:
  5837. if (state.flags & 0x0400) {
  5838. //=== NEEDBITS(16); */
  5839. while (bits < 16) {
  5840. if (have === 0) { break inf_leave; }
  5841. have--;
  5842. hold += input[next++] << bits;
  5843. bits += 8;
  5844. }
  5845. //===//
  5846. state.length = hold;
  5847. if (state.head) {
  5848. state.head.extra_len = hold;
  5849. }
  5850. if (state.flags & 0x0200) {
  5851. //=== CRC2(state.check, hold);
  5852. hbuf[0] = hold & 0xff;
  5853. hbuf[1] = (hold >>> 8) & 0xff;
  5854. state.check = crc32(state.check, hbuf, 2, 0);
  5855. //===//
  5856. }
  5857. //=== INITBITS();
  5858. hold = 0;
  5859. bits = 0;
  5860. //===//
  5861. }
  5862. else if (state.head) {
  5863. state.head.extra = null/*Z_NULL*/;
  5864. }
  5865. state.mode = EXTRA;
  5866. /* falls through */
  5867. case EXTRA:
  5868. if (state.flags & 0x0400) {
  5869. copy = state.length;
  5870. if (copy > have) { copy = have; }
  5871. if (copy) {
  5872. if (state.head) {
  5873. len = state.head.extra_len - state.length;
  5874. if (!state.head.extra) {
  5875. // Use untyped array for more conveniend processing later
  5876. state.head.extra = new Array(state.head.extra_len);
  5877. }
  5878. utils.arraySet(
  5879. state.head.extra,
  5880. input,
  5881. next,
  5882. // extra field is limited to 65536 bytes
  5883. // - no need for additional size check
  5884. copy,
  5885. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  5886. len
  5887. );
  5888. //zmemcpy(state.head.extra + len, next,
  5889. // len + copy > state.head.extra_max ?
  5890. // state.head.extra_max - len : copy);
  5891. }
  5892. if (state.flags & 0x0200) {
  5893. state.check = crc32(state.check, input, copy, next);
  5894. }
  5895. have -= copy;
  5896. next += copy;
  5897. state.length -= copy;
  5898. }
  5899. if (state.length) { break inf_leave; }
  5900. }
  5901. state.length = 0;
  5902. state.mode = NAME;
  5903. /* falls through */
  5904. case NAME:
  5905. if (state.flags & 0x0800) {
  5906. if (have === 0) { break inf_leave; }
  5907. copy = 0;
  5908. do {
  5909. // TODO: 2 or 1 bytes?
  5910. len = input[next + copy++];
  5911. /* use constant limit because in js we should not preallocate memory */
  5912. if (state.head && len &&
  5913. (state.length < 65536 /*state.head.name_max*/)) {
  5914. state.head.name += String.fromCharCode(len);
  5915. }
  5916. } while (len && copy < have);
  5917. if (state.flags & 0x0200) {
  5918. state.check = crc32(state.check, input, copy, next);
  5919. }
  5920. have -= copy;
  5921. next += copy;
  5922. if (len) { break inf_leave; }
  5923. }
  5924. else if (state.head) {
  5925. state.head.name = null;
  5926. }
  5927. state.length = 0;
  5928. state.mode = COMMENT;
  5929. /* falls through */
  5930. case COMMENT:
  5931. if (state.flags & 0x1000) {
  5932. if (have === 0) { break inf_leave; }
  5933. copy = 0;
  5934. do {
  5935. len = input[next + copy++];
  5936. /* use constant limit because in js we should not preallocate memory */
  5937. if (state.head && len &&
  5938. (state.length < 65536 /*state.head.comm_max*/)) {
  5939. state.head.comment += String.fromCharCode(len);
  5940. }
  5941. } while (len && copy < have);
  5942. if (state.flags & 0x0200) {
  5943. state.check = crc32(state.check, input, copy, next);
  5944. }
  5945. have -= copy;
  5946. next += copy;
  5947. if (len) { break inf_leave; }
  5948. }
  5949. else if (state.head) {
  5950. state.head.comment = null;
  5951. }
  5952. state.mode = HCRC;
  5953. /* falls through */
  5954. case HCRC:
  5955. if (state.flags & 0x0200) {
  5956. //=== NEEDBITS(16); */
  5957. while (bits < 16) {
  5958. if (have === 0) { break inf_leave; }
  5959. have--;
  5960. hold += input[next++] << bits;
  5961. bits += 8;
  5962. }
  5963. //===//
  5964. if (hold !== (state.check & 0xffff)) {
  5965. strm.msg = 'header crc mismatch';
  5966. state.mode = BAD;
  5967. break;
  5968. }
  5969. //=== INITBITS();
  5970. hold = 0;
  5971. bits = 0;
  5972. //===//
  5973. }
  5974. if (state.head) {
  5975. state.head.hcrc = ((state.flags >> 9) & 1);
  5976. state.head.done = true;
  5977. }
  5978. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  5979. state.mode = TYPE;
  5980. break;
  5981. case DICTID:
  5982. //=== NEEDBITS(32); */
  5983. while (bits < 32) {
  5984. if (have === 0) { break inf_leave; }
  5985. have--;
  5986. hold += input[next++] << bits;
  5987. bits += 8;
  5988. }
  5989. //===//
  5990. strm.adler = state.check = ZSWAP32(hold);
  5991. //=== INITBITS();
  5992. hold = 0;
  5993. bits = 0;
  5994. //===//
  5995. state.mode = DICT;
  5996. /* falls through */
  5997. case DICT:
  5998. if (state.havedict === 0) {
  5999. //--- RESTORE() ---
  6000. strm.next_out = put;
  6001. strm.avail_out = left;
  6002. strm.next_in = next;
  6003. strm.avail_in = have;
  6004. state.hold = hold;
  6005. state.bits = bits;
  6006. //---
  6007. return Z_NEED_DICT;
  6008. }
  6009. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6010. state.mode = TYPE;
  6011. /* falls through */
  6012. case TYPE:
  6013. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  6014. /* falls through */
  6015. case TYPEDO:
  6016. if (state.last) {
  6017. //--- BYTEBITS() ---//
  6018. hold >>>= bits & 7;
  6019. bits -= bits & 7;
  6020. //---//
  6021. state.mode = CHECK;
  6022. break;
  6023. }
  6024. //=== NEEDBITS(3); */
  6025. while (bits < 3) {
  6026. if (have === 0) { break inf_leave; }
  6027. have--;
  6028. hold += input[next++] << bits;
  6029. bits += 8;
  6030. }
  6031. //===//
  6032. state.last = (hold & 0x01)/*BITS(1)*/;
  6033. //--- DROPBITS(1) ---//
  6034. hold >>>= 1;
  6035. bits -= 1;
  6036. //---//
  6037. switch ((hold & 0x03)/*BITS(2)*/) {
  6038. case 0: /* stored block */
  6039. //Tracev((stderr, "inflate: stored block%s\n",
  6040. // state.last ? " (last)" : ""));
  6041. state.mode = STORED;
  6042. break;
  6043. case 1: /* fixed block */
  6044. fixedtables(state);
  6045. //Tracev((stderr, "inflate: fixed codes block%s\n",
  6046. // state.last ? " (last)" : ""));
  6047. state.mode = LEN_; /* decode codes */
  6048. if (flush === Z_TREES) {
  6049. //--- DROPBITS(2) ---//
  6050. hold >>>= 2;
  6051. bits -= 2;
  6052. //---//
  6053. break inf_leave;
  6054. }
  6055. break;
  6056. case 2: /* dynamic block */
  6057. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  6058. // state.last ? " (last)" : ""));
  6059. state.mode = TABLE;
  6060. break;
  6061. case 3:
  6062. strm.msg = 'invalid block type';
  6063. state.mode = BAD;
  6064. }
  6065. //--- DROPBITS(2) ---//
  6066. hold >>>= 2;
  6067. bits -= 2;
  6068. //---//
  6069. break;
  6070. case STORED:
  6071. //--- BYTEBITS() ---// /* go to byte boundary */
  6072. hold >>>= bits & 7;
  6073. bits -= bits & 7;
  6074. //---//
  6075. //=== NEEDBITS(32); */
  6076. while (bits < 32) {
  6077. if (have === 0) { break inf_leave; }
  6078. have--;
  6079. hold += input[next++] << bits;
  6080. bits += 8;
  6081. }
  6082. //===//
  6083. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  6084. strm.msg = 'invalid stored block lengths';
  6085. state.mode = BAD;
  6086. break;
  6087. }
  6088. state.length = hold & 0xffff;
  6089. //Tracev((stderr, "inflate: stored length %u\n",
  6090. // state.length));
  6091. //=== INITBITS();
  6092. hold = 0;
  6093. bits = 0;
  6094. //===//
  6095. state.mode = COPY_;
  6096. if (flush === Z_TREES) { break inf_leave; }
  6097. /* falls through */
  6098. case COPY_:
  6099. state.mode = COPY;
  6100. /* falls through */
  6101. case COPY:
  6102. copy = state.length;
  6103. if (copy) {
  6104. if (copy > have) { copy = have; }
  6105. if (copy > left) { copy = left; }
  6106. if (copy === 0) { break inf_leave; }
  6107. //--- zmemcpy(put, next, copy); ---
  6108. utils.arraySet(output, input, next, copy, put);
  6109. //---//
  6110. have -= copy;
  6111. next += copy;
  6112. left -= copy;
  6113. put += copy;
  6114. state.length -= copy;
  6115. break;
  6116. }
  6117. //Tracev((stderr, "inflate: stored end\n"));
  6118. state.mode = TYPE;
  6119. break;
  6120. case TABLE:
  6121. //=== NEEDBITS(14); */
  6122. while (bits < 14) {
  6123. if (have === 0) { break inf_leave; }
  6124. have--;
  6125. hold += input[next++] << bits;
  6126. bits += 8;
  6127. }
  6128. //===//
  6129. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  6130. //--- DROPBITS(5) ---//
  6131. hold >>>= 5;
  6132. bits -= 5;
  6133. //---//
  6134. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  6135. //--- DROPBITS(5) ---//
  6136. hold >>>= 5;
  6137. bits -= 5;
  6138. //---//
  6139. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  6140. //--- DROPBITS(4) ---//
  6141. hold >>>= 4;
  6142. bits -= 4;
  6143. //---//
  6144. //#ifndef PKZIP_BUG_WORKAROUND
  6145. if (state.nlen > 286 || state.ndist > 30) {
  6146. strm.msg = 'too many length or distance symbols';
  6147. state.mode = BAD;
  6148. break;
  6149. }
  6150. //#endif
  6151. //Tracev((stderr, "inflate: table sizes ok\n"));
  6152. state.have = 0;
  6153. state.mode = LENLENS;
  6154. /* falls through */
  6155. case LENLENS:
  6156. while (state.have < state.ncode) {
  6157. //=== NEEDBITS(3);
  6158. while (bits < 3) {
  6159. if (have === 0) { break inf_leave; }
  6160. have--;
  6161. hold += input[next++] << bits;
  6162. bits += 8;
  6163. }
  6164. //===//
  6165. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  6166. //--- DROPBITS(3) ---//
  6167. hold >>>= 3;
  6168. bits -= 3;
  6169. //---//
  6170. }
  6171. while (state.have < 19) {
  6172. state.lens[order[state.have++]] = 0;
  6173. }
  6174. // We have separate tables & no pointers. 2 commented lines below not needed.
  6175. //state.next = state.codes;
  6176. //state.lencode = state.next;
  6177. // Switch to use dynamic table
  6178. state.lencode = state.lendyn;
  6179. state.lenbits = 7;
  6180. opts = {bits: state.lenbits};
  6181. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  6182. state.lenbits = opts.bits;
  6183. if (ret) {
  6184. strm.msg = 'invalid code lengths set';
  6185. state.mode = BAD;
  6186. break;
  6187. }
  6188. //Tracev((stderr, "inflate: code lengths ok\n"));
  6189. state.have = 0;
  6190. state.mode = CODELENS;
  6191. /* falls through */
  6192. case CODELENS:
  6193. while (state.have < state.nlen + state.ndist) {
  6194. for (;;) {
  6195. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  6196. here_bits = here >>> 24;
  6197. here_op = (here >>> 16) & 0xff;
  6198. here_val = here & 0xffff;
  6199. if ((here_bits) <= bits) { break; }
  6200. //--- PULLBYTE() ---//
  6201. if (have === 0) { break inf_leave; }
  6202. have--;
  6203. hold += input[next++] << bits;
  6204. bits += 8;
  6205. //---//
  6206. }
  6207. if (here_val < 16) {
  6208. //--- DROPBITS(here.bits) ---//
  6209. hold >>>= here_bits;
  6210. bits -= here_bits;
  6211. //---//
  6212. state.lens[state.have++] = here_val;
  6213. }
  6214. else {
  6215. if (here_val === 16) {
  6216. //=== NEEDBITS(here.bits + 2);
  6217. n = here_bits + 2;
  6218. while (bits < n) {
  6219. if (have === 0) { break inf_leave; }
  6220. have--;
  6221. hold += input[next++] << bits;
  6222. bits += 8;
  6223. }
  6224. //===//
  6225. //--- DROPBITS(here.bits) ---//
  6226. hold >>>= here_bits;
  6227. bits -= here_bits;
  6228. //---//
  6229. if (state.have === 0) {
  6230. strm.msg = 'invalid bit length repeat';
  6231. state.mode = BAD;
  6232. break;
  6233. }
  6234. len = state.lens[state.have - 1];
  6235. copy = 3 + (hold & 0x03);//BITS(2);
  6236. //--- DROPBITS(2) ---//
  6237. hold >>>= 2;
  6238. bits -= 2;
  6239. //---//
  6240. }
  6241. else if (here_val === 17) {
  6242. //=== NEEDBITS(here.bits + 3);
  6243. n = here_bits + 3;
  6244. while (bits < n) {
  6245. if (have === 0) { break inf_leave; }
  6246. have--;
  6247. hold += input[next++] << bits;
  6248. bits += 8;
  6249. }
  6250. //===//
  6251. //--- DROPBITS(here.bits) ---//
  6252. hold >>>= here_bits;
  6253. bits -= here_bits;
  6254. //---//
  6255. len = 0;
  6256. copy = 3 + (hold & 0x07);//BITS(3);
  6257. //--- DROPBITS(3) ---//
  6258. hold >>>= 3;
  6259. bits -= 3;
  6260. //---//
  6261. }
  6262. else {
  6263. //=== NEEDBITS(here.bits + 7);
  6264. n = here_bits + 7;
  6265. while (bits < n) {
  6266. if (have === 0) { break inf_leave; }
  6267. have--;
  6268. hold += input[next++] << bits;
  6269. bits += 8;
  6270. }
  6271. //===//
  6272. //--- DROPBITS(here.bits) ---//
  6273. hold >>>= here_bits;
  6274. bits -= here_bits;
  6275. //---//
  6276. len = 0;
  6277. copy = 11 + (hold & 0x7f);//BITS(7);
  6278. //--- DROPBITS(7) ---//
  6279. hold >>>= 7;
  6280. bits -= 7;
  6281. //---//
  6282. }
  6283. if (state.have + copy > state.nlen + state.ndist) {
  6284. strm.msg = 'invalid bit length repeat';
  6285. state.mode = BAD;
  6286. break;
  6287. }
  6288. while (copy--) {
  6289. state.lens[state.have++] = len;
  6290. }
  6291. }
  6292. }
  6293. /* handle error breaks in while */
  6294. if (state.mode === BAD) { break; }
  6295. /* check for end-of-block code (better have one) */
  6296. if (state.lens[256] === 0) {
  6297. strm.msg = 'invalid code -- missing end-of-block';
  6298. state.mode = BAD;
  6299. break;
  6300. }
  6301. /* build code tables -- note: do not change the lenbits or distbits
  6302. values here (9 and 6) without reading the comments in inftrees.h
  6303. concerning the ENOUGH constants, which depend on those values */
  6304. state.lenbits = 9;
  6305. opts = {bits: state.lenbits};
  6306. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  6307. // We have separate tables & no pointers. 2 commented lines below not needed.
  6308. // state.next_index = opts.table_index;
  6309. state.lenbits = opts.bits;
  6310. // state.lencode = state.next;
  6311. if (ret) {
  6312. strm.msg = 'invalid literal/lengths set';
  6313. state.mode = BAD;
  6314. break;
  6315. }
  6316. state.distbits = 6;
  6317. //state.distcode.copy(state.codes);
  6318. // Switch to use dynamic table
  6319. state.distcode = state.distdyn;
  6320. opts = {bits: state.distbits};
  6321. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  6322. // We have separate tables & no pointers. 2 commented lines below not needed.
  6323. // state.next_index = opts.table_index;
  6324. state.distbits = opts.bits;
  6325. // state.distcode = state.next;
  6326. if (ret) {
  6327. strm.msg = 'invalid distances set';
  6328. state.mode = BAD;
  6329. break;
  6330. }
  6331. //Tracev((stderr, 'inflate: codes ok\n'));
  6332. state.mode = LEN_;
  6333. if (flush === Z_TREES) { break inf_leave; }
  6334. /* falls through */
  6335. case LEN_:
  6336. state.mode = LEN;
  6337. /* falls through */
  6338. case LEN:
  6339. if (have >= 6 && left >= 258) {
  6340. //--- RESTORE() ---
  6341. strm.next_out = put;
  6342. strm.avail_out = left;
  6343. strm.next_in = next;
  6344. strm.avail_in = have;
  6345. state.hold = hold;
  6346. state.bits = bits;
  6347. //---
  6348. inflate_fast(strm, _out);
  6349. //--- LOAD() ---
  6350. put = strm.next_out;
  6351. output = strm.output;
  6352. left = strm.avail_out;
  6353. next = strm.next_in;
  6354. input = strm.input;
  6355. have = strm.avail_in;
  6356. hold = state.hold;
  6357. bits = state.bits;
  6358. //---
  6359. if (state.mode === TYPE) {
  6360. state.back = -1;
  6361. }
  6362. break;
  6363. }
  6364. state.back = 0;
  6365. for (;;) {
  6366. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  6367. here_bits = here >>> 24;
  6368. here_op = (here >>> 16) & 0xff;
  6369. here_val = here & 0xffff;
  6370. if (here_bits <= bits) { break; }
  6371. //--- PULLBYTE() ---//
  6372. if (have === 0) { break inf_leave; }
  6373. have--;
  6374. hold += input[next++] << bits;
  6375. bits += 8;
  6376. //---//
  6377. }
  6378. if (here_op && (here_op & 0xf0) === 0) {
  6379. last_bits = here_bits;
  6380. last_op = here_op;
  6381. last_val = here_val;
  6382. for (;;) {
  6383. here = state.lencode[last_val +
  6384. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6385. here_bits = here >>> 24;
  6386. here_op = (here >>> 16) & 0xff;
  6387. here_val = here & 0xffff;
  6388. if ((last_bits + here_bits) <= bits) { break; }
  6389. //--- PULLBYTE() ---//
  6390. if (have === 0) { break inf_leave; }
  6391. have--;
  6392. hold += input[next++] << bits;
  6393. bits += 8;
  6394. //---//
  6395. }
  6396. //--- DROPBITS(last.bits) ---//
  6397. hold >>>= last_bits;
  6398. bits -= last_bits;
  6399. //---//
  6400. state.back += last_bits;
  6401. }
  6402. //--- DROPBITS(here.bits) ---//
  6403. hold >>>= here_bits;
  6404. bits -= here_bits;
  6405. //---//
  6406. state.back += here_bits;
  6407. state.length = here_val;
  6408. if (here_op === 0) {
  6409. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  6410. // "inflate: literal '%c'\n" :
  6411. // "inflate: literal 0x%02x\n", here.val));
  6412. state.mode = LIT;
  6413. break;
  6414. }
  6415. if (here_op & 32) {
  6416. //Tracevv((stderr, "inflate: end of block\n"));
  6417. state.back = -1;
  6418. state.mode = TYPE;
  6419. break;
  6420. }
  6421. if (here_op & 64) {
  6422. strm.msg = 'invalid literal/length code';
  6423. state.mode = BAD;
  6424. break;
  6425. }
  6426. state.extra = here_op & 15;
  6427. state.mode = LENEXT;
  6428. /* falls through */
  6429. case LENEXT:
  6430. if (state.extra) {
  6431. //=== NEEDBITS(state.extra);
  6432. n = state.extra;
  6433. while (bits < n) {
  6434. if (have === 0) { break inf_leave; }
  6435. have--;
  6436. hold += input[next++] << bits;
  6437. bits += 8;
  6438. }
  6439. //===//
  6440. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  6441. //--- DROPBITS(state.extra) ---//
  6442. hold >>>= state.extra;
  6443. bits -= state.extra;
  6444. //---//
  6445. state.back += state.extra;
  6446. }
  6447. //Tracevv((stderr, "inflate: length %u\n", state.length));
  6448. state.was = state.length;
  6449. state.mode = DIST;
  6450. /* falls through */
  6451. case DIST:
  6452. for (;;) {
  6453. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  6454. here_bits = here >>> 24;
  6455. here_op = (here >>> 16) & 0xff;
  6456. here_val = here & 0xffff;
  6457. if ((here_bits) <= bits) { break; }
  6458. //--- PULLBYTE() ---//
  6459. if (have === 0) { break inf_leave; }
  6460. have--;
  6461. hold += input[next++] << bits;
  6462. bits += 8;
  6463. //---//
  6464. }
  6465. if ((here_op & 0xf0) === 0) {
  6466. last_bits = here_bits;
  6467. last_op = here_op;
  6468. last_val = here_val;
  6469. for (;;) {
  6470. here = state.distcode[last_val +
  6471. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6472. here_bits = here >>> 24;
  6473. here_op = (here >>> 16) & 0xff;
  6474. here_val = here & 0xffff;
  6475. if ((last_bits + here_bits) <= bits) { break; }
  6476. //--- PULLBYTE() ---//
  6477. if (have === 0) { break inf_leave; }
  6478. have--;
  6479. hold += input[next++] << bits;
  6480. bits += 8;
  6481. //---//
  6482. }
  6483. //--- DROPBITS(last.bits) ---//
  6484. hold >>>= last_bits;
  6485. bits -= last_bits;
  6486. //---//
  6487. state.back += last_bits;
  6488. }
  6489. //--- DROPBITS(here.bits) ---//
  6490. hold >>>= here_bits;
  6491. bits -= here_bits;
  6492. //---//
  6493. state.back += here_bits;
  6494. if (here_op & 64) {
  6495. strm.msg = 'invalid distance code';
  6496. state.mode = BAD;
  6497. break;
  6498. }
  6499. state.offset = here_val;
  6500. state.extra = (here_op) & 15;
  6501. state.mode = DISTEXT;
  6502. /* falls through */
  6503. case DISTEXT:
  6504. if (state.extra) {
  6505. //=== NEEDBITS(state.extra);
  6506. n = state.extra;
  6507. while (bits < n) {
  6508. if (have === 0) { break inf_leave; }
  6509. have--;
  6510. hold += input[next++] << bits;
  6511. bits += 8;
  6512. }
  6513. //===//
  6514. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  6515. //--- DROPBITS(state.extra) ---//
  6516. hold >>>= state.extra;
  6517. bits -= state.extra;
  6518. //---//
  6519. state.back += state.extra;
  6520. }
  6521. //#ifdef INFLATE_STRICT
  6522. if (state.offset > state.dmax) {
  6523. strm.msg = 'invalid distance too far back';
  6524. state.mode = BAD;
  6525. break;
  6526. }
  6527. //#endif
  6528. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  6529. state.mode = MATCH;
  6530. /* falls through */
  6531. case MATCH:
  6532. if (left === 0) { break inf_leave; }
  6533. copy = _out - left;
  6534. if (state.offset > copy) { /* copy from window */
  6535. copy = state.offset - copy;
  6536. if (copy > state.whave) {
  6537. if (state.sane) {
  6538. strm.msg = 'invalid distance too far back';
  6539. state.mode = BAD;
  6540. break;
  6541. }
  6542. // (!) This block is disabled in zlib defailts,
  6543. // don't enable it for binary compatibility
  6544. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  6545. // Trace((stderr, "inflate.c too far\n"));
  6546. // copy -= state.whave;
  6547. // if (copy > state.length) { copy = state.length; }
  6548. // if (copy > left) { copy = left; }
  6549. // left -= copy;
  6550. // state.length -= copy;
  6551. // do {
  6552. // output[put++] = 0;
  6553. // } while (--copy);
  6554. // if (state.length === 0) { state.mode = LEN; }
  6555. // break;
  6556. //#endif
  6557. }
  6558. if (copy > state.wnext) {
  6559. copy -= state.wnext;
  6560. from = state.wsize - copy;
  6561. }
  6562. else {
  6563. from = state.wnext - copy;
  6564. }
  6565. if (copy > state.length) { copy = state.length; }
  6566. from_source = state.window;
  6567. }
  6568. else { /* copy from output */
  6569. from_source = output;
  6570. from = put - state.offset;
  6571. copy = state.length;
  6572. }
  6573. if (copy > left) { copy = left; }
  6574. left -= copy;
  6575. state.length -= copy;
  6576. do {
  6577. output[put++] = from_source[from++];
  6578. } while (--copy);
  6579. if (state.length === 0) { state.mode = LEN; }
  6580. break;
  6581. case LIT:
  6582. if (left === 0) { break inf_leave; }
  6583. output[put++] = state.length;
  6584. left--;
  6585. state.mode = LEN;
  6586. break;
  6587. case CHECK:
  6588. if (state.wrap) {
  6589. //=== NEEDBITS(32);
  6590. while (bits < 32) {
  6591. if (have === 0) { break inf_leave; }
  6592. have--;
  6593. // Use '|' insdead of '+' to make sure that result is signed
  6594. hold |= input[next++] << bits;
  6595. bits += 8;
  6596. }
  6597. //===//
  6598. _out -= left;
  6599. strm.total_out += _out;
  6600. state.total += _out;
  6601. if (_out) {
  6602. strm.adler = state.check =
  6603. /*UPDATE(state.check, put - _out, _out);*/
  6604. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  6605. }
  6606. _out = left;
  6607. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  6608. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  6609. strm.msg = 'incorrect data check';
  6610. state.mode = BAD;
  6611. break;
  6612. }
  6613. //=== INITBITS();
  6614. hold = 0;
  6615. bits = 0;
  6616. //===//
  6617. //Tracev((stderr, "inflate: check matches trailer\n"));
  6618. }
  6619. state.mode = LENGTH;
  6620. /* falls through */
  6621. case LENGTH:
  6622. if (state.wrap && state.flags) {
  6623. //=== NEEDBITS(32);
  6624. while (bits < 32) {
  6625. if (have === 0) { break inf_leave; }
  6626. have--;
  6627. hold += input[next++] << bits;
  6628. bits += 8;
  6629. }
  6630. //===//
  6631. if (hold !== (state.total & 0xffffffff)) {
  6632. strm.msg = 'incorrect length check';
  6633. state.mode = BAD;
  6634. break;
  6635. }
  6636. //=== INITBITS();
  6637. hold = 0;
  6638. bits = 0;
  6639. //===//
  6640. //Tracev((stderr, "inflate: length matches trailer\n"));
  6641. }
  6642. state.mode = DONE;
  6643. /* falls through */
  6644. case DONE:
  6645. ret = Z_STREAM_END;
  6646. break inf_leave;
  6647. case BAD:
  6648. ret = Z_DATA_ERROR;
  6649. break inf_leave;
  6650. case MEM:
  6651. return Z_MEM_ERROR;
  6652. case SYNC:
  6653. /* falls through */
  6654. default:
  6655. return Z_STREAM_ERROR;
  6656. }
  6657. }
  6658. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  6659. /*
  6660. Return from inflate(), updating the total counts and the check value.
  6661. If there was no progress during the inflate() call, return a buffer
  6662. error. Call updatewindow() to create and/or update the window state.
  6663. Note: a memory error from inflate() is non-recoverable.
  6664. */
  6665. //--- RESTORE() ---
  6666. strm.next_out = put;
  6667. strm.avail_out = left;
  6668. strm.next_in = next;
  6669. strm.avail_in = have;
  6670. state.hold = hold;
  6671. state.bits = bits;
  6672. //---
  6673. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  6674. (state.mode < CHECK || flush !== Z_FINISH))) {
  6675. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  6676. state.mode = MEM;
  6677. return Z_MEM_ERROR;
  6678. }
  6679. }
  6680. _in -= strm.avail_in;
  6681. _out -= strm.avail_out;
  6682. strm.total_in += _in;
  6683. strm.total_out += _out;
  6684. state.total += _out;
  6685. if (state.wrap && _out) {
  6686. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  6687. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  6688. }
  6689. strm.data_type = state.bits + (state.last ? 64 : 0) +
  6690. (state.mode === TYPE ? 128 : 0) +
  6691. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  6692. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  6693. ret = Z_BUF_ERROR;
  6694. }
  6695. return ret;
  6696. }
  6697. function inflateEnd(strm) {
  6698. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  6699. return Z_STREAM_ERROR;
  6700. }
  6701. var state = strm.state;
  6702. if (state.window) {
  6703. state.window = null;
  6704. }
  6705. strm.state = null;
  6706. return Z_OK;
  6707. }
  6708. function inflateGetHeader(strm, head) {
  6709. var state;
  6710. /* check state */
  6711. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6712. state = strm.state;
  6713. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  6714. /* save header structure */
  6715. state.head = head;
  6716. head.done = false;
  6717. return Z_OK;
  6718. }
  6719. exports.inflateReset = inflateReset;
  6720. exports.inflateReset2 = inflateReset2;
  6721. exports.inflateResetKeep = inflateResetKeep;
  6722. exports.inflateInit = inflateInit;
  6723. exports.inflateInit2 = inflateInit2;
  6724. exports.inflate = inflate;
  6725. exports.inflateEnd = inflateEnd;
  6726. exports.inflateGetHeader = inflateGetHeader;
  6727. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  6728. /* Not implemented
  6729. exports.inflateCopy = inflateCopy;
  6730. exports.inflateGetDictionary = inflateGetDictionary;
  6731. exports.inflateMark = inflateMark;
  6732. exports.inflatePrime = inflatePrime;
  6733. exports.inflateSetDictionary = inflateSetDictionary;
  6734. exports.inflateSync = inflateSync;
  6735. exports.inflateSyncPoint = inflateSyncPoint;
  6736. exports.inflateUndermine = inflateUndermine;
  6737. */
  6738. },{"../utils/common":27,"./adler32":29,"./crc32":31,"./inffast":34,"./inftrees":36}],36:[function(_dereq_,module,exports){
  6739. 'use strict';
  6740. var utils = _dereq_('../utils/common');
  6741. var MAXBITS = 15;
  6742. var ENOUGH_LENS = 852;
  6743. var ENOUGH_DISTS = 592;
  6744. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  6745. var CODES = 0;
  6746. var LENS = 1;
  6747. var DISTS = 2;
  6748. var lbase = [ /* Length codes 257..285 base */
  6749. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  6750. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  6751. ];
  6752. var lext = [ /* Length codes 257..285 extra */
  6753. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  6754. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  6755. ];
  6756. var dbase = [ /* Distance codes 0..29 base */
  6757. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  6758. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  6759. 8193, 12289, 16385, 24577, 0, 0
  6760. ];
  6761. var dext = [ /* Distance codes 0..29 extra */
  6762. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  6763. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  6764. 28, 28, 29, 29, 64, 64
  6765. ];
  6766. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  6767. {
  6768. var bits = opts.bits;
  6769. //here = opts.here; /* table entry for duplication */
  6770. var len = 0; /* a code's length in bits */
  6771. var sym = 0; /* index of code symbols */
  6772. var min = 0, max = 0; /* minimum and maximum code lengths */
  6773. var root = 0; /* number of index bits for root table */
  6774. var curr = 0; /* number of index bits for current table */
  6775. var drop = 0; /* code bits to drop for sub-table */
  6776. var left = 0; /* number of prefix codes available */
  6777. var used = 0; /* code entries in table used */
  6778. var huff = 0; /* Huffman code */
  6779. var incr; /* for incrementing code, index */
  6780. var fill; /* index for replicating entries */
  6781. var low; /* low bits for current root entry */
  6782. var mask; /* mask for low root bits */
  6783. var next; /* next available space in table */
  6784. var base = null; /* base value table to use */
  6785. var base_index = 0;
  6786. // var shoextra; /* extra bits table to use */
  6787. var end; /* use base and extra for symbol > end */
  6788. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  6789. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  6790. var extra = null;
  6791. var extra_index = 0;
  6792. var here_bits, here_op, here_val;
  6793. /*
  6794. Process a set of code lengths to create a canonical Huffman code. The
  6795. code lengths are lens[0..codes-1]. Each length corresponds to the
  6796. symbols 0..codes-1. The Huffman code is generated by first sorting the
  6797. symbols by length from short to long, and retaining the symbol order
  6798. for codes with equal lengths. Then the code starts with all zero bits
  6799. for the first code of the shortest length, and the codes are integer
  6800. increments for the same length, and zeros are appended as the length
  6801. increases. For the deflate format, these bits are stored backwards
  6802. from their more natural integer increment ordering, and so when the
  6803. decoding tables are built in the large loop below, the integer codes
  6804. are incremented backwards.
  6805. This routine assumes, but does not check, that all of the entries in
  6806. lens[] are in the range 0..MAXBITS. The caller must assure this.
  6807. 1..MAXBITS is interpreted as that code length. zero means that that
  6808. symbol does not occur in this code.
  6809. The codes are sorted by computing a count of codes for each length,
  6810. creating from that a table of starting indices for each length in the
  6811. sorted table, and then entering the symbols in order in the sorted
  6812. table. The sorted table is work[], with that space being provided by
  6813. the caller.
  6814. The length counts are used for other purposes as well, i.e. finding
  6815. the minimum and maximum length codes, determining if there are any
  6816. codes at all, checking for a valid set of lengths, and looking ahead
  6817. at length counts to determine sub-table sizes when building the
  6818. decoding tables.
  6819. */
  6820. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  6821. for (len = 0; len <= MAXBITS; len++) {
  6822. count[len] = 0;
  6823. }
  6824. for (sym = 0; sym < codes; sym++) {
  6825. count[lens[lens_index + sym]]++;
  6826. }
  6827. /* bound code lengths, force root to be within code lengths */
  6828. root = bits;
  6829. for (max = MAXBITS; max >= 1; max--) {
  6830. if (count[max] !== 0) { break; }
  6831. }
  6832. if (root > max) {
  6833. root = max;
  6834. }
  6835. if (max === 0) { /* no symbols to code at all */
  6836. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  6837. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  6838. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  6839. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  6840. //table.op[opts.table_index] = 64;
  6841. //table.bits[opts.table_index] = 1;
  6842. //table.val[opts.table_index++] = 0;
  6843. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  6844. opts.bits = 1;
  6845. return 0; /* no symbols, but wait for decoding to report error */
  6846. }
  6847. for (min = 1; min < max; min++) {
  6848. if (count[min] !== 0) { break; }
  6849. }
  6850. if (root < min) {
  6851. root = min;
  6852. }
  6853. /* check for an over-subscribed or incomplete set of lengths */
  6854. left = 1;
  6855. for (len = 1; len <= MAXBITS; len++) {
  6856. left <<= 1;
  6857. left -= count[len];
  6858. if (left < 0) {
  6859. return -1;
  6860. } /* over-subscribed */
  6861. }
  6862. if (left > 0 && (type === CODES || max !== 1)) {
  6863. return -1; /* incomplete set */
  6864. }
  6865. /* generate offsets into symbol table for each length for sorting */
  6866. offs[1] = 0;
  6867. for (len = 1; len < MAXBITS; len++) {
  6868. offs[len + 1] = offs[len] + count[len];
  6869. }
  6870. /* sort symbols by length, by symbol order within each length */
  6871. for (sym = 0; sym < codes; sym++) {
  6872. if (lens[lens_index + sym] !== 0) {
  6873. work[offs[lens[lens_index + sym]]++] = sym;
  6874. }
  6875. }
  6876. /*
  6877. Create and fill in decoding tables. In this loop, the table being
  6878. filled is at next and has curr index bits. The code being used is huff
  6879. with length len. That code is converted to an index by dropping drop
  6880. bits off of the bottom. For codes where len is less than drop + curr,
  6881. those top drop + curr - len bits are incremented through all values to
  6882. fill the table with replicated entries.
  6883. root is the number of index bits for the root table. When len exceeds
  6884. root, sub-tables are created pointed to by the root entry with an index
  6885. of the low root bits of huff. This is saved in low to check for when a
  6886. new sub-table should be started. drop is zero when the root table is
  6887. being filled, and drop is root when sub-tables are being filled.
  6888. When a new sub-table is needed, it is necessary to look ahead in the
  6889. code lengths to determine what size sub-table is needed. The length
  6890. counts are used for this, and so count[] is decremented as codes are
  6891. entered in the tables.
  6892. used keeps track of how many table entries have been allocated from the
  6893. provided *table space. It is checked for LENS and DIST tables against
  6894. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  6895. the initial root table size constants. See the comments in inftrees.h
  6896. for more information.
  6897. sym increments through all symbols, and the loop terminates when
  6898. all codes of length max, i.e. all codes, have been processed. This
  6899. routine permits incomplete codes, so another loop after this one fills
  6900. in the rest of the decoding tables with invalid code markers.
  6901. */
  6902. /* set up for code type */
  6903. // poor man optimization - use if-else instead of switch,
  6904. // to avoid deopts in old v8
  6905. if (type === CODES) {
  6906. base = extra = work; /* dummy value--not used */
  6907. end = 19;
  6908. } else if (type === LENS) {
  6909. base = lbase;
  6910. base_index -= 257;
  6911. extra = lext;
  6912. extra_index -= 257;
  6913. end = 256;
  6914. } else { /* DISTS */
  6915. base = dbase;
  6916. extra = dext;
  6917. end = -1;
  6918. }
  6919. /* initialize opts for loop */
  6920. huff = 0; /* starting code */
  6921. sym = 0; /* starting code symbol */
  6922. len = min; /* starting code length */
  6923. next = table_index; /* current table to fill in */
  6924. curr = root; /* current table index bits */
  6925. drop = 0; /* current bits to drop from code for index */
  6926. low = -1; /* trigger new sub-table when len > root */
  6927. used = 1 << root; /* use root table entries */
  6928. mask = used - 1; /* mask for comparing low */
  6929. /* check available table space */
  6930. if ((type === LENS && used > ENOUGH_LENS) ||
  6931. (type === DISTS && used > ENOUGH_DISTS)) {
  6932. return 1;
  6933. }
  6934. var i=0;
  6935. /* process all codes and make table entries */
  6936. for (;;) {
  6937. i++;
  6938. /* create table entry */
  6939. here_bits = len - drop;
  6940. if (work[sym] < end) {
  6941. here_op = 0;
  6942. here_val = work[sym];
  6943. }
  6944. else if (work[sym] > end) {
  6945. here_op = extra[extra_index + work[sym]];
  6946. here_val = base[base_index + work[sym]];
  6947. }
  6948. else {
  6949. here_op = 32 + 64; /* end of block */
  6950. here_val = 0;
  6951. }
  6952. /* replicate for those indices with low len bits equal to huff */
  6953. incr = 1 << (len - drop);
  6954. fill = 1 << curr;
  6955. min = fill; /* save offset to next table */
  6956. do {
  6957. fill -= incr;
  6958. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  6959. } while (fill !== 0);
  6960. /* backwards increment the len-bit code huff */
  6961. incr = 1 << (len - 1);
  6962. while (huff & incr) {
  6963. incr >>= 1;
  6964. }
  6965. if (incr !== 0) {
  6966. huff &= incr - 1;
  6967. huff += incr;
  6968. } else {
  6969. huff = 0;
  6970. }
  6971. /* go to next symbol, update count, len */
  6972. sym++;
  6973. if (--count[len] === 0) {
  6974. if (len === max) { break; }
  6975. len = lens[lens_index + work[sym]];
  6976. }
  6977. /* create new sub-table if needed */
  6978. if (len > root && (huff & mask) !== low) {
  6979. /* if first time, transition to sub-tables */
  6980. if (drop === 0) {
  6981. drop = root;
  6982. }
  6983. /* increment past last table */
  6984. next += min; /* here min is 1 << curr */
  6985. /* determine length of next table */
  6986. curr = len - drop;
  6987. left = 1 << curr;
  6988. while (curr + drop < max) {
  6989. left -= count[curr + drop];
  6990. if (left <= 0) { break; }
  6991. curr++;
  6992. left <<= 1;
  6993. }
  6994. /* check for enough space */
  6995. used += 1 << curr;
  6996. if ((type === LENS && used > ENOUGH_LENS) ||
  6997. (type === DISTS && used > ENOUGH_DISTS)) {
  6998. return 1;
  6999. }
  7000. /* point entry in root table to sub-table */
  7001. low = huff & mask;
  7002. /*table.op[low] = curr;
  7003. table.bits[low] = root;
  7004. table.val[low] = next - opts.table_index;*/
  7005. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  7006. }
  7007. }
  7008. /* fill in remaining table entry if code is incomplete (guaranteed to have
  7009. at most one remaining entry, since if the code is incomplete, the
  7010. maximum code length that was allowed to get this far is one bit) */
  7011. if (huff !== 0) {
  7012. //table.op[next + huff] = 64; /* invalid code marker */
  7013. //table.bits[next + huff] = len - drop;
  7014. //table.val[next + huff] = 0;
  7015. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  7016. }
  7017. /* set return parameters */
  7018. //opts.table_index += used;
  7019. opts.bits = root;
  7020. return 0;
  7021. };
  7022. },{"../utils/common":27}],37:[function(_dereq_,module,exports){
  7023. 'use strict';
  7024. module.exports = {
  7025. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  7026. '1': 'stream end', /* Z_STREAM_END 1 */
  7027. '0': '', /* Z_OK 0 */
  7028. '-1': 'file error', /* Z_ERRNO (-1) */
  7029. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  7030. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  7031. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  7032. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  7033. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  7034. };
  7035. },{}],38:[function(_dereq_,module,exports){
  7036. 'use strict';
  7037. var utils = _dereq_('../utils/common');
  7038. /* Public constants ==========================================================*/
  7039. /* ===========================================================================*/
  7040. //var Z_FILTERED = 1;
  7041. //var Z_HUFFMAN_ONLY = 2;
  7042. //var Z_RLE = 3;
  7043. var Z_FIXED = 4;
  7044. //var Z_DEFAULT_STRATEGY = 0;
  7045. /* Possible values of the data_type field (though see inflate()) */
  7046. var Z_BINARY = 0;
  7047. var Z_TEXT = 1;
  7048. //var Z_ASCII = 1; // = Z_TEXT
  7049. var Z_UNKNOWN = 2;
  7050. /*============================================================================*/
  7051. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  7052. // From zutil.h
  7053. var STORED_BLOCK = 0;
  7054. var STATIC_TREES = 1;
  7055. var DYN_TREES = 2;
  7056. /* The three kinds of block type */
  7057. var MIN_MATCH = 3;
  7058. var MAX_MATCH = 258;
  7059. /* The minimum and maximum match lengths */
  7060. // From deflate.h
  7061. /* ===========================================================================
  7062. * Internal compression state.
  7063. */
  7064. var LENGTH_CODES = 29;
  7065. /* number of length codes, not counting the special END_BLOCK code */
  7066. var LITERALS = 256;
  7067. /* number of literal bytes 0..255 */
  7068. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  7069. /* number of Literal or Length codes, including the END_BLOCK code */
  7070. var D_CODES = 30;
  7071. /* number of distance codes */
  7072. var BL_CODES = 19;
  7073. /* number of codes used to transfer the bit lengths */
  7074. var HEAP_SIZE = 2*L_CODES + 1;
  7075. /* maximum heap size */
  7076. var MAX_BITS = 15;
  7077. /* All codes must not exceed MAX_BITS bits */
  7078. var Buf_size = 16;
  7079. /* size of bit buffer in bi_buf */
  7080. /* ===========================================================================
  7081. * Constants
  7082. */
  7083. var MAX_BL_BITS = 7;
  7084. /* Bit length codes must not exceed MAX_BL_BITS bits */
  7085. var END_BLOCK = 256;
  7086. /* end of block literal code */
  7087. var REP_3_6 = 16;
  7088. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  7089. var REPZ_3_10 = 17;
  7090. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  7091. var REPZ_11_138 = 18;
  7092. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  7093. var extra_lbits = /* extra bits for each length code */
  7094. [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];
  7095. var extra_dbits = /* extra bits for each distance code */
  7096. [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];
  7097. var extra_blbits = /* extra bits for each bit length code */
  7098. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  7099. var bl_order =
  7100. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  7101. /* The lengths of the bit length codes are sent in order of decreasing
  7102. * probability, to avoid transmitting the lengths for unused bit length codes.
  7103. */
  7104. /* ===========================================================================
  7105. * Local data. These are initialized only once.
  7106. */
  7107. // We pre-fill arrays with 0 to avoid uninitialized gaps
  7108. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  7109. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  7110. var static_ltree = new Array((L_CODES+2) * 2);
  7111. zero(static_ltree);
  7112. /* The static literal tree. Since the bit lengths are imposed, there is no
  7113. * need for the L_CODES extra codes used during heap construction. However
  7114. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  7115. * below).
  7116. */
  7117. var static_dtree = new Array(D_CODES * 2);
  7118. zero(static_dtree);
  7119. /* The static distance tree. (Actually a trivial tree since all codes use
  7120. * 5 bits.)
  7121. */
  7122. var _dist_code = new Array(DIST_CODE_LEN);
  7123. zero(_dist_code);
  7124. /* Distance codes. The first 256 values correspond to the distances
  7125. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  7126. * the 15 bit distances.
  7127. */
  7128. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  7129. zero(_length_code);
  7130. /* length code for each normalized match length (0 == MIN_MATCH) */
  7131. var base_length = new Array(LENGTH_CODES);
  7132. zero(base_length);
  7133. /* First normalized length for each code (0 = MIN_MATCH) */
  7134. var base_dist = new Array(D_CODES);
  7135. zero(base_dist);
  7136. /* First normalized distance for each code (0 = distance of 1) */
  7137. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  7138. this.static_tree = static_tree; /* static tree or NULL */
  7139. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  7140. this.extra_base = extra_base; /* base index for extra_bits */
  7141. this.elems = elems; /* max number of elements in the tree */
  7142. this.max_length = max_length; /* max bit length for the codes */
  7143. // show if `static_tree` has data or dummy - needed for monomorphic objects
  7144. this.has_stree = static_tree && static_tree.length;
  7145. };
  7146. var static_l_desc;
  7147. var static_d_desc;
  7148. var static_bl_desc;
  7149. var TreeDesc = function(dyn_tree, stat_desc) {
  7150. this.dyn_tree = dyn_tree; /* the dynamic tree */
  7151. this.max_code = 0; /* largest code with non zero frequency */
  7152. this.stat_desc = stat_desc; /* the corresponding static tree */
  7153. };
  7154. function d_code(dist) {
  7155. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  7156. }
  7157. /* ===========================================================================
  7158. * Output a short LSB first on the stream.
  7159. * IN assertion: there is enough room in pendingBuf.
  7160. */
  7161. function put_short (s, w) {
  7162. // put_byte(s, (uch)((w) & 0xff));
  7163. // put_byte(s, (uch)((ush)(w) >> 8));
  7164. s.pending_buf[s.pending++] = (w) & 0xff;
  7165. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  7166. }
  7167. /* ===========================================================================
  7168. * Send a value on a given number of bits.
  7169. * IN assertion: length <= 16 and value fits in length bits.
  7170. */
  7171. function send_bits(s, value, length) {
  7172. if (s.bi_valid > (Buf_size - length)) {
  7173. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  7174. put_short(s, s.bi_buf);
  7175. s.bi_buf = value >> (Buf_size - s.bi_valid);
  7176. s.bi_valid += length - Buf_size;
  7177. } else {
  7178. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  7179. s.bi_valid += length;
  7180. }
  7181. }
  7182. function send_code(s, c, tree) {
  7183. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  7184. }
  7185. /* ===========================================================================
  7186. * Reverse the first len bits of a code, using straightforward code (a faster
  7187. * method would use a table)
  7188. * IN assertion: 1 <= len <= 15
  7189. */
  7190. function bi_reverse(code, len) {
  7191. var res = 0;
  7192. do {
  7193. res |= code & 1;
  7194. code >>>= 1;
  7195. res <<= 1;
  7196. } while (--len > 0);
  7197. return res >>> 1;
  7198. }
  7199. /* ===========================================================================
  7200. * Flush the bit buffer, keeping at most 7 bits in it.
  7201. */
  7202. function bi_flush(s) {
  7203. if (s.bi_valid === 16) {
  7204. put_short(s, s.bi_buf);
  7205. s.bi_buf = 0;
  7206. s.bi_valid = 0;
  7207. } else if (s.bi_valid >= 8) {
  7208. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  7209. s.bi_buf >>= 8;
  7210. s.bi_valid -= 8;
  7211. }
  7212. }
  7213. /* ===========================================================================
  7214. * Compute the optimal bit lengths for a tree and update the total bit length
  7215. * for the current block.
  7216. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  7217. * above are the tree nodes sorted by increasing frequency.
  7218. * OUT assertions: the field len is set to the optimal bit length, the
  7219. * array bl_count contains the frequencies for each bit length.
  7220. * The length opt_len is updated; static_len is also updated if stree is
  7221. * not null.
  7222. */
  7223. function gen_bitlen(s, desc)
  7224. // deflate_state *s;
  7225. // tree_desc *desc; /* the tree descriptor */
  7226. {
  7227. var tree = desc.dyn_tree;
  7228. var max_code = desc.max_code;
  7229. var stree = desc.stat_desc.static_tree;
  7230. var has_stree = desc.stat_desc.has_stree;
  7231. var extra = desc.stat_desc.extra_bits;
  7232. var base = desc.stat_desc.extra_base;
  7233. var max_length = desc.stat_desc.max_length;
  7234. var h; /* heap index */
  7235. var n, m; /* iterate over the tree elements */
  7236. var bits; /* bit length */
  7237. var xbits; /* extra bits */
  7238. var f; /* frequency */
  7239. var overflow = 0; /* number of elements with bit length too large */
  7240. for (bits = 0; bits <= MAX_BITS; bits++) {
  7241. s.bl_count[bits] = 0;
  7242. }
  7243. /* In a first pass, compute the optimal bit lengths (which may
  7244. * overflow in the case of the bit length tree).
  7245. */
  7246. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  7247. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  7248. n = s.heap[h];
  7249. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  7250. if (bits > max_length) {
  7251. bits = max_length;
  7252. overflow++;
  7253. }
  7254. tree[n*2 + 1]/*.Len*/ = bits;
  7255. /* We overwrite tree[n].Dad which is no longer needed */
  7256. if (n > max_code) { continue; } /* not a leaf node */
  7257. s.bl_count[bits]++;
  7258. xbits = 0;
  7259. if (n >= base) {
  7260. xbits = extra[n-base];
  7261. }
  7262. f = tree[n * 2]/*.Freq*/;
  7263. s.opt_len += f * (bits + xbits);
  7264. if (has_stree) {
  7265. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  7266. }
  7267. }
  7268. if (overflow === 0) { return; }
  7269. // Trace((stderr,"\nbit length overflow\n"));
  7270. /* This happens for example on obj2 and pic of the Calgary corpus */
  7271. /* Find the first bit length which could increase: */
  7272. do {
  7273. bits = max_length-1;
  7274. while (s.bl_count[bits] === 0) { bits--; }
  7275. s.bl_count[bits]--; /* move one leaf down the tree */
  7276. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  7277. s.bl_count[max_length]--;
  7278. /* The brother of the overflow item also moves one step up,
  7279. * but this does not affect bl_count[max_length]
  7280. */
  7281. overflow -= 2;
  7282. } while (overflow > 0);
  7283. /* Now recompute all bit lengths, scanning in increasing frequency.
  7284. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  7285. * lengths instead of fixing only the wrong ones. This idea is taken
  7286. * from 'ar' written by Haruhiko Okumura.)
  7287. */
  7288. for (bits = max_length; bits !== 0; bits--) {
  7289. n = s.bl_count[bits];
  7290. while (n !== 0) {
  7291. m = s.heap[--h];
  7292. if (m > max_code) { continue; }
  7293. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  7294. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  7295. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  7296. tree[m*2 + 1]/*.Len*/ = bits;
  7297. }
  7298. n--;
  7299. }
  7300. }
  7301. }
  7302. /* ===========================================================================
  7303. * Generate the codes for a given tree and bit counts (which need not be
  7304. * optimal).
  7305. * IN assertion: the array bl_count contains the bit length statistics for
  7306. * the given tree and the field len is set for all tree elements.
  7307. * OUT assertion: the field code is set for all tree elements of non
  7308. * zero code length.
  7309. */
  7310. function gen_codes(tree, max_code, bl_count)
  7311. // ct_data *tree; /* the tree to decorate */
  7312. // int max_code; /* largest code with non zero frequency */
  7313. // ushf *bl_count; /* number of codes at each bit length */
  7314. {
  7315. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  7316. var code = 0; /* running code value */
  7317. var bits; /* bit index */
  7318. var n; /* code index */
  7319. /* The distribution counts are first used to generate the code values
  7320. * without bit reversal.
  7321. */
  7322. for (bits = 1; bits <= MAX_BITS; bits++) {
  7323. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  7324. }
  7325. /* Check that the bit counts in bl_count are consistent. The last code
  7326. * must be all ones.
  7327. */
  7328. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  7329. // "inconsistent bit counts");
  7330. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  7331. for (n = 0; n <= max_code; n++) {
  7332. var len = tree[n*2 + 1]/*.Len*/;
  7333. if (len === 0) { continue; }
  7334. /* Now reverse the bits */
  7335. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  7336. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  7337. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  7338. }
  7339. }
  7340. /* ===========================================================================
  7341. * Initialize the various 'constant' tables.
  7342. */
  7343. function tr_static_init() {
  7344. var n; /* iterates over tree elements */
  7345. var bits; /* bit counter */
  7346. var length; /* length value */
  7347. var code; /* code value */
  7348. var dist; /* distance index */
  7349. var bl_count = new Array(MAX_BITS+1);
  7350. /* number of codes at each bit length for an optimal tree */
  7351. // do check in _tr_init()
  7352. //if (static_init_done) return;
  7353. /* For some embedded targets, global variables are not initialized: */
  7354. /*#ifdef NO_INIT_GLOBAL_POINTERS
  7355. static_l_desc.static_tree = static_ltree;
  7356. static_l_desc.extra_bits = extra_lbits;
  7357. static_d_desc.static_tree = static_dtree;
  7358. static_d_desc.extra_bits = extra_dbits;
  7359. static_bl_desc.extra_bits = extra_blbits;
  7360. #endif*/
  7361. /* Initialize the mapping length (0..255) -> length code (0..28) */
  7362. length = 0;
  7363. for (code = 0; code < LENGTH_CODES-1; code++) {
  7364. base_length[code] = length;
  7365. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  7366. _length_code[length++] = code;
  7367. }
  7368. }
  7369. //Assert (length == 256, "tr_static_init: length != 256");
  7370. /* Note that the length 255 (match length 258) can be represented
  7371. * in two different ways: code 284 + 5 bits or code 285, so we
  7372. * overwrite length_code[255] to use the best encoding:
  7373. */
  7374. _length_code[length-1] = code;
  7375. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  7376. dist = 0;
  7377. for (code = 0 ; code < 16; code++) {
  7378. base_dist[code] = dist;
  7379. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  7380. _dist_code[dist++] = code;
  7381. }
  7382. }
  7383. //Assert (dist == 256, "tr_static_init: dist != 256");
  7384. dist >>= 7; /* from now on, all distances are divided by 128 */
  7385. for ( ; code < D_CODES; code++) {
  7386. base_dist[code] = dist << 7;
  7387. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  7388. _dist_code[256 + dist++] = code;
  7389. }
  7390. }
  7391. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  7392. /* Construct the codes of the static literal tree */
  7393. for (bits = 0; bits <= MAX_BITS; bits++) {
  7394. bl_count[bits] = 0;
  7395. }
  7396. n = 0;
  7397. while (n <= 143) {
  7398. static_ltree[n*2 + 1]/*.Len*/ = 8;
  7399. n++;
  7400. bl_count[8]++;
  7401. }
  7402. while (n <= 255) {
  7403. static_ltree[n*2 + 1]/*.Len*/ = 9;
  7404. n++;
  7405. bl_count[9]++;
  7406. }
  7407. while (n <= 279) {
  7408. static_ltree[n*2 + 1]/*.Len*/ = 7;
  7409. n++;
  7410. bl_count[7]++;
  7411. }
  7412. while (n <= 287) {
  7413. static_ltree[n*2 + 1]/*.Len*/ = 8;
  7414. n++;
  7415. bl_count[8]++;
  7416. }
  7417. /* Codes 286 and 287 do not exist, but we must include them in the
  7418. * tree construction to get a canonical Huffman tree (longest code
  7419. * all ones)
  7420. */
  7421. gen_codes(static_ltree, L_CODES+1, bl_count);
  7422. /* The static distance tree is trivial: */
  7423. for (n = 0; n < D_CODES; n++) {
  7424. static_dtree[n*2 + 1]/*.Len*/ = 5;
  7425. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  7426. }
  7427. // Now data ready and we can init static trees
  7428. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  7429. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  7430. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  7431. //static_init_done = true;
  7432. }
  7433. /* ===========================================================================
  7434. * Initialize a new block.
  7435. */
  7436. function init_block(s) {
  7437. var n; /* iterates over tree elements */
  7438. /* Initialize the trees. */
  7439. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  7440. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  7441. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  7442. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  7443. s.opt_len = s.static_len = 0;
  7444. s.last_lit = s.matches = 0;
  7445. }
  7446. /* ===========================================================================
  7447. * Flush the bit buffer and align the output on a byte boundary
  7448. */
  7449. function bi_windup(s)
  7450. {
  7451. if (s.bi_valid > 8) {
  7452. put_short(s, s.bi_buf);
  7453. } else if (s.bi_valid > 0) {
  7454. //put_byte(s, (Byte)s->bi_buf);
  7455. s.pending_buf[s.pending++] = s.bi_buf;
  7456. }
  7457. s.bi_buf = 0;
  7458. s.bi_valid = 0;
  7459. }
  7460. /* ===========================================================================
  7461. * Copy a stored block, storing first the length and its
  7462. * one's complement if requested.
  7463. */
  7464. function copy_block(s, buf, len, header)
  7465. //DeflateState *s;
  7466. //charf *buf; /* the input data */
  7467. //unsigned len; /* its length */
  7468. //int header; /* true if block header must be written */
  7469. {
  7470. bi_windup(s); /* align on byte boundary */
  7471. if (header) {
  7472. put_short(s, len);
  7473. put_short(s, ~len);
  7474. }
  7475. // while (len--) {
  7476. // put_byte(s, *buf++);
  7477. // }
  7478. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  7479. s.pending += len;
  7480. }
  7481. /* ===========================================================================
  7482. * Compares to subtrees, using the tree depth as tie breaker when
  7483. * the subtrees have equal frequency. This minimizes the worst case length.
  7484. */
  7485. function smaller(tree, n, m, depth) {
  7486. var _n2 = n*2;
  7487. var _m2 = m*2;
  7488. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  7489. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  7490. }
  7491. /* ===========================================================================
  7492. * Restore the heap property by moving down the tree starting at node k,
  7493. * exchanging a node with the smallest of its two sons if necessary, stopping
  7494. * when the heap property is re-established (each father smaller than its
  7495. * two sons).
  7496. */
  7497. function pqdownheap(s, tree, k)
  7498. // deflate_state *s;
  7499. // ct_data *tree; /* the tree to restore */
  7500. // int k; /* node to move down */
  7501. {
  7502. var v = s.heap[k];
  7503. var j = k << 1; /* left son of k */
  7504. while (j <= s.heap_len) {
  7505. /* Set j to the smallest of the two sons: */
  7506. if (j < s.heap_len &&
  7507. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  7508. j++;
  7509. }
  7510. /* Exit if v is smaller than both sons */
  7511. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  7512. /* Exchange v with the smallest son */
  7513. s.heap[k] = s.heap[j];
  7514. k = j;
  7515. /* And continue down the tree, setting j to the left son of k */
  7516. j <<= 1;
  7517. }
  7518. s.heap[k] = v;
  7519. }
  7520. // inlined manually
  7521. // var SMALLEST = 1;
  7522. /* ===========================================================================
  7523. * Send the block data compressed using the given Huffman trees
  7524. */
  7525. function compress_block(s, ltree, dtree)
  7526. // deflate_state *s;
  7527. // const ct_data *ltree; /* literal tree */
  7528. // const ct_data *dtree; /* distance tree */
  7529. {
  7530. var dist; /* distance of matched string */
  7531. var lc; /* match length or unmatched char (if dist == 0) */
  7532. var lx = 0; /* running index in l_buf */
  7533. var code; /* the code to send */
  7534. var extra; /* number of extra bits to send */
  7535. if (s.last_lit !== 0) {
  7536. do {
  7537. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  7538. lc = s.pending_buf[s.l_buf + lx];
  7539. lx++;
  7540. if (dist === 0) {
  7541. send_code(s, lc, ltree); /* send a literal byte */
  7542. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  7543. } else {
  7544. /* Here, lc is the match length - MIN_MATCH */
  7545. code = _length_code[lc];
  7546. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  7547. extra = extra_lbits[code];
  7548. if (extra !== 0) {
  7549. lc -= base_length[code];
  7550. send_bits(s, lc, extra); /* send the extra length bits */
  7551. }
  7552. dist--; /* dist is now the match distance - 1 */
  7553. code = d_code(dist);
  7554. //Assert (code < D_CODES, "bad d_code");
  7555. send_code(s, code, dtree); /* send the distance code */
  7556. extra = extra_dbits[code];
  7557. if (extra !== 0) {
  7558. dist -= base_dist[code];
  7559. send_bits(s, dist, extra); /* send the extra distance bits */
  7560. }
  7561. } /* literal or match pair ? */
  7562. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  7563. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  7564. // "pendingBuf overflow");
  7565. } while (lx < s.last_lit);
  7566. }
  7567. send_code(s, END_BLOCK, ltree);
  7568. }
  7569. /* ===========================================================================
  7570. * Construct one Huffman tree and assigns the code bit strings and lengths.
  7571. * Update the total bit length for the current block.
  7572. * IN assertion: the field freq is set for all tree elements.
  7573. * OUT assertions: the fields len and code are set to the optimal bit length
  7574. * and corresponding code. The length opt_len is updated; static_len is
  7575. * also updated if stree is not null. The field max_code is set.
  7576. */
  7577. function build_tree(s, desc)
  7578. // deflate_state *s;
  7579. // tree_desc *desc; /* the tree descriptor */
  7580. {
  7581. var tree = desc.dyn_tree;
  7582. var stree = desc.stat_desc.static_tree;
  7583. var has_stree = desc.stat_desc.has_stree;
  7584. var elems = desc.stat_desc.elems;
  7585. var n, m; /* iterate over heap elements */
  7586. var max_code = -1; /* largest code with non zero frequency */
  7587. var node; /* new node being created */
  7588. /* Construct the initial heap, with least frequent element in
  7589. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  7590. * heap[0] is not used.
  7591. */
  7592. s.heap_len = 0;
  7593. s.heap_max = HEAP_SIZE;
  7594. for (n = 0; n < elems; n++) {
  7595. if (tree[n * 2]/*.Freq*/ !== 0) {
  7596. s.heap[++s.heap_len] = max_code = n;
  7597. s.depth[n] = 0;
  7598. } else {
  7599. tree[n*2 + 1]/*.Len*/ = 0;
  7600. }
  7601. }
  7602. /* The pkzip format requires that at least one distance code exists,
  7603. * and that at least one bit should be sent even if there is only one
  7604. * possible code. So to avoid special checks later on we force at least
  7605. * two codes of non zero frequency.
  7606. */
  7607. while (s.heap_len < 2) {
  7608. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  7609. tree[node * 2]/*.Freq*/ = 1;
  7610. s.depth[node] = 0;
  7611. s.opt_len--;
  7612. if (has_stree) {
  7613. s.static_len -= stree[node*2 + 1]/*.Len*/;
  7614. }
  7615. /* node is 0 or 1 so it does not have extra bits */
  7616. }
  7617. desc.max_code = max_code;
  7618. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  7619. * establish sub-heaps of increasing lengths:
  7620. */
  7621. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  7622. /* Construct the Huffman tree by repeatedly combining the least two
  7623. * frequent nodes.
  7624. */
  7625. node = elems; /* next internal node of the tree */
  7626. do {
  7627. //pqremove(s, tree, n); /* n = node of least frequency */
  7628. /*** pqremove ***/
  7629. n = s.heap[1/*SMALLEST*/];
  7630. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  7631. pqdownheap(s, tree, 1/*SMALLEST*/);
  7632. /***/
  7633. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  7634. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  7635. s.heap[--s.heap_max] = m;
  7636. /* Create a new node father of n and m */
  7637. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  7638. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  7639. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  7640. /* and insert the new node in the heap */
  7641. s.heap[1/*SMALLEST*/] = node++;
  7642. pqdownheap(s, tree, 1/*SMALLEST*/);
  7643. } while (s.heap_len >= 2);
  7644. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  7645. /* At this point, the fields freq and dad are set. We can now
  7646. * generate the bit lengths.
  7647. */
  7648. gen_bitlen(s, desc);
  7649. /* The field len is now set, we can generate the bit codes */
  7650. gen_codes(tree, max_code, s.bl_count);
  7651. }
  7652. /* ===========================================================================
  7653. * Scan a literal or distance tree to determine the frequencies of the codes
  7654. * in the bit length tree.
  7655. */
  7656. function scan_tree(s, tree, max_code)
  7657. // deflate_state *s;
  7658. // ct_data *tree; /* the tree to be scanned */
  7659. // int max_code; /* and its largest code of non zero frequency */
  7660. {
  7661. var n; /* iterates over all tree elements */
  7662. var prevlen = -1; /* last emitted length */
  7663. var curlen; /* length of current code */
  7664. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  7665. var count = 0; /* repeat count of the current code */
  7666. var max_count = 7; /* max repeat count */
  7667. var min_count = 4; /* min repeat count */
  7668. if (nextlen === 0) {
  7669. max_count = 138;
  7670. min_count = 3;
  7671. }
  7672. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  7673. for (n = 0; n <= max_code; n++) {
  7674. curlen = nextlen;
  7675. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  7676. if (++count < max_count && curlen === nextlen) {
  7677. continue;
  7678. } else if (count < min_count) {
  7679. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  7680. } else if (curlen !== 0) {
  7681. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  7682. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  7683. } else if (count <= 10) {
  7684. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  7685. } else {
  7686. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  7687. }
  7688. count = 0;
  7689. prevlen = curlen;
  7690. if (nextlen === 0) {
  7691. max_count = 138;
  7692. min_count = 3;
  7693. } else if (curlen === nextlen) {
  7694. max_count = 6;
  7695. min_count = 3;
  7696. } else {
  7697. max_count = 7;
  7698. min_count = 4;
  7699. }
  7700. }
  7701. }
  7702. /* ===========================================================================
  7703. * Send a literal or distance tree in compressed form, using the codes in
  7704. * bl_tree.
  7705. */
  7706. function send_tree(s, tree, max_code)
  7707. // deflate_state *s;
  7708. // ct_data *tree; /* the tree to be scanned */
  7709. // int max_code; /* and its largest code of non zero frequency */
  7710. {
  7711. var n; /* iterates over all tree elements */
  7712. var prevlen = -1; /* last emitted length */
  7713. var curlen; /* length of current code */
  7714. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  7715. var count = 0; /* repeat count of the current code */
  7716. var max_count = 7; /* max repeat count */
  7717. var min_count = 4; /* min repeat count */
  7718. /* tree[max_code+1].Len = -1; */ /* guard already set */
  7719. if (nextlen === 0) {
  7720. max_count = 138;
  7721. min_count = 3;
  7722. }
  7723. for (n = 0; n <= max_code; n++) {
  7724. curlen = nextlen;
  7725. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  7726. if (++count < max_count && curlen === nextlen) {
  7727. continue;
  7728. } else if (count < min_count) {
  7729. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  7730. } else if (curlen !== 0) {
  7731. if (curlen !== prevlen) {
  7732. send_code(s, curlen, s.bl_tree);
  7733. count--;
  7734. }
  7735. //Assert(count >= 3 && count <= 6, " 3_6?");
  7736. send_code(s, REP_3_6, s.bl_tree);
  7737. send_bits(s, count-3, 2);
  7738. } else if (count <= 10) {
  7739. send_code(s, REPZ_3_10, s.bl_tree);
  7740. send_bits(s, count-3, 3);
  7741. } else {
  7742. send_code(s, REPZ_11_138, s.bl_tree);
  7743. send_bits(s, count-11, 7);
  7744. }
  7745. count = 0;
  7746. prevlen = curlen;
  7747. if (nextlen === 0) {
  7748. max_count = 138;
  7749. min_count = 3;
  7750. } else if (curlen === nextlen) {
  7751. max_count = 6;
  7752. min_count = 3;
  7753. } else {
  7754. max_count = 7;
  7755. min_count = 4;
  7756. }
  7757. }
  7758. }
  7759. /* ===========================================================================
  7760. * Construct the Huffman tree for the bit lengths and return the index in
  7761. * bl_order of the last bit length code to send.
  7762. */
  7763. function build_bl_tree(s) {
  7764. var max_blindex; /* index of last bit length code of non zero freq */
  7765. /* Determine the bit length frequencies for literal and distance trees */
  7766. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  7767. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  7768. /* Build the bit length tree: */
  7769. build_tree(s, s.bl_desc);
  7770. /* opt_len now includes the length of the tree representations, except
  7771. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  7772. */
  7773. /* Determine the number of bit length codes to send. The pkzip format
  7774. * requires that at least 4 bit length codes be sent. (appnote.txt says
  7775. * 3 but the actual value used is 4.)
  7776. */
  7777. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  7778. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  7779. break;
  7780. }
  7781. }
  7782. /* Update opt_len to include the bit length tree and counts */
  7783. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  7784. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  7785. // s->opt_len, s->static_len));
  7786. return max_blindex;
  7787. }
  7788. /* ===========================================================================
  7789. * Send the header for a block using dynamic Huffman trees: the counts, the
  7790. * lengths of the bit length codes, the literal tree and the distance tree.
  7791. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  7792. */
  7793. function send_all_trees(s, lcodes, dcodes, blcodes)
  7794. // deflate_state *s;
  7795. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  7796. {
  7797. var rank; /* index in bl_order */
  7798. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  7799. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  7800. // "too many codes");
  7801. //Tracev((stderr, "\nbl counts: "));
  7802. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  7803. send_bits(s, dcodes-1, 5);
  7804. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  7805. for (rank = 0; rank < blcodes; rank++) {
  7806. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  7807. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  7808. }
  7809. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  7810. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  7811. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  7812. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  7813. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  7814. }
  7815. /* ===========================================================================
  7816. * Check if the data type is TEXT or BINARY, using the following algorithm:
  7817. * - TEXT if the two conditions below are satisfied:
  7818. * a) There are no non-portable control characters belonging to the
  7819. * "black list" (0..6, 14..25, 28..31).
  7820. * b) There is at least one printable character belonging to the
  7821. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  7822. * - BINARY otherwise.
  7823. * - The following partially-portable control characters form a
  7824. * "gray list" that is ignored in this detection algorithm:
  7825. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  7826. * IN assertion: the fields Freq of dyn_ltree are set.
  7827. */
  7828. function detect_data_type(s) {
  7829. /* black_mask is the bit mask of black-listed bytes
  7830. * set bits 0..6, 14..25, and 28..31
  7831. * 0xf3ffc07f = binary 11110011111111111100000001111111
  7832. */
  7833. var black_mask = 0xf3ffc07f;
  7834. var n;
  7835. /* Check for non-textual ("black-listed") bytes. */
  7836. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  7837. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  7838. return Z_BINARY;
  7839. }
  7840. }
  7841. /* Check for textual ("white-listed") bytes. */
  7842. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  7843. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  7844. return Z_TEXT;
  7845. }
  7846. for (n = 32; n < LITERALS; n++) {
  7847. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  7848. return Z_TEXT;
  7849. }
  7850. }
  7851. /* There are no "black-listed" or "white-listed" bytes:
  7852. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  7853. */
  7854. return Z_BINARY;
  7855. }
  7856. var static_init_done = false;
  7857. /* ===========================================================================
  7858. * Initialize the tree data structures for a new zlib stream.
  7859. */
  7860. function _tr_init(s)
  7861. {
  7862. if (!static_init_done) {
  7863. tr_static_init();
  7864. static_init_done = true;
  7865. }
  7866. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  7867. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  7868. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  7869. s.bi_buf = 0;
  7870. s.bi_valid = 0;
  7871. /* Initialize the first block of the first file: */
  7872. init_block(s);
  7873. }
  7874. /* ===========================================================================
  7875. * Send a stored block
  7876. */
  7877. function _tr_stored_block(s, buf, stored_len, last)
  7878. //DeflateState *s;
  7879. //charf *buf; /* input block */
  7880. //ulg stored_len; /* length of input block */
  7881. //int last; /* one if this is the last block for a file */
  7882. {
  7883. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  7884. copy_block(s, buf, stored_len, true); /* with header */
  7885. }
  7886. /* ===========================================================================
  7887. * Send one empty static block to give enough lookahead for inflate.
  7888. * This takes 10 bits, of which 7 may remain in the bit buffer.
  7889. */
  7890. function _tr_align(s) {
  7891. send_bits(s, STATIC_TREES<<1, 3);
  7892. send_code(s, END_BLOCK, static_ltree);
  7893. bi_flush(s);
  7894. }
  7895. /* ===========================================================================
  7896. * Determine the best encoding for the current block: dynamic trees, static
  7897. * trees or store, and output the encoded block to the zip file.
  7898. */
  7899. function _tr_flush_block(s, buf, stored_len, last)
  7900. //DeflateState *s;
  7901. //charf *buf; /* input block, or NULL if too old */
  7902. //ulg stored_len; /* length of input block */
  7903. //int last; /* one if this is the last block for a file */
  7904. {
  7905. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  7906. var max_blindex = 0; /* index of last bit length code of non zero freq */
  7907. /* Build the Huffman trees unless a stored block is forced */
  7908. if (s.level > 0) {
  7909. /* Check if the file is binary or text */
  7910. if (s.strm.data_type === Z_UNKNOWN) {
  7911. s.strm.data_type = detect_data_type(s);
  7912. }
  7913. /* Construct the literal and distance trees */
  7914. build_tree(s, s.l_desc);
  7915. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  7916. // s->static_len));
  7917. build_tree(s, s.d_desc);
  7918. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  7919. // s->static_len));
  7920. /* At this point, opt_len and static_len are the total bit lengths of
  7921. * the compressed block data, excluding the tree representations.
  7922. */
  7923. /* Build the bit length tree for the above two trees, and get the index
  7924. * in bl_order of the last bit length code to send.
  7925. */
  7926. max_blindex = build_bl_tree(s);
  7927. /* Determine the best encoding. Compute the block lengths in bytes. */
  7928. opt_lenb = (s.opt_len+3+7) >>> 3;
  7929. static_lenb = (s.static_len+3+7) >>> 3;
  7930. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  7931. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  7932. // s->last_lit));
  7933. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  7934. } else {
  7935. // Assert(buf != (char*)0, "lost buf");
  7936. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  7937. }
  7938. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  7939. /* 4: two words for the lengths */
  7940. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  7941. * Otherwise we can't have processed more than WSIZE input bytes since
  7942. * the last block flush, because compression would have been
  7943. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  7944. * transform a block into a stored block.
  7945. */
  7946. _tr_stored_block(s, buf, stored_len, last);
  7947. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  7948. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  7949. compress_block(s, static_ltree, static_dtree);
  7950. } else {
  7951. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  7952. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  7953. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  7954. }
  7955. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  7956. /* The above check is made mod 2^32, for files larger than 512 MB
  7957. * and uLong implemented on 32 bits.
  7958. */
  7959. init_block(s);
  7960. if (last) {
  7961. bi_windup(s);
  7962. }
  7963. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  7964. // s->compressed_len-7*last));
  7965. }
  7966. /* ===========================================================================
  7967. * Save the match info and tally the frequency counts. Return true if
  7968. * the current block must be flushed.
  7969. */
  7970. function _tr_tally(s, dist, lc)
  7971. // deflate_state *s;
  7972. // unsigned dist; /* distance of matched string */
  7973. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  7974. {
  7975. //var out_length, in_length, dcode;
  7976. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  7977. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  7978. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  7979. s.last_lit++;
  7980. if (dist === 0) {
  7981. /* lc is the unmatched char */
  7982. s.dyn_ltree[lc*2]/*.Freq*/++;
  7983. } else {
  7984. s.matches++;
  7985. /* Here, lc is the match length - MIN_MATCH */
  7986. dist--; /* dist = match distance - 1 */
  7987. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  7988. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  7989. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  7990. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  7991. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  7992. }
  7993. // (!) This block is disabled in zlib defailts,
  7994. // don't enable it for binary compatibility
  7995. //#ifdef TRUNCATE_BLOCK
  7996. // /* Try to guess if it is profitable to stop the current block here */
  7997. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  7998. // /* Compute an upper bound for the compressed length */
  7999. // out_length = s.last_lit*8;
  8000. // in_length = s.strstart - s.block_start;
  8001. //
  8002. // for (dcode = 0; dcode < D_CODES; dcode++) {
  8003. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  8004. // }
  8005. // out_length >>>= 3;
  8006. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  8007. // // s->last_lit, in_length, out_length,
  8008. // // 100L - out_length*100L/in_length));
  8009. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  8010. // return true;
  8011. // }
  8012. // }
  8013. //#endif
  8014. return (s.last_lit === s.lit_bufsize-1);
  8015. /* We avoid equality with lit_bufsize because of wraparound at 64K
  8016. * on 16 bit machines and because stored blocks are restricted to
  8017. * 64K-1 bytes.
  8018. */
  8019. }
  8020. exports._tr_init = _tr_init;
  8021. exports._tr_stored_block = _tr_stored_block;
  8022. exports._tr_flush_block = _tr_flush_block;
  8023. exports._tr_tally = _tr_tally;
  8024. exports._tr_align = _tr_align;
  8025. },{"../utils/common":27}],39:[function(_dereq_,module,exports){
  8026. 'use strict';
  8027. function ZStream() {
  8028. /* next input byte */
  8029. this.input = null; // JS specific, because we have no pointers
  8030. this.next_in = 0;
  8031. /* number of bytes available at input */
  8032. this.avail_in = 0;
  8033. /* total number of input bytes read so far */
  8034. this.total_in = 0;
  8035. /* next output byte should be put there */
  8036. this.output = null; // JS specific, because we have no pointers
  8037. this.next_out = 0;
  8038. /* remaining free space at output */
  8039. this.avail_out = 0;
  8040. /* total number of bytes output so far */
  8041. this.total_out = 0;
  8042. /* last error message, NULL if no error */
  8043. this.msg = ''/*Z_NULL*/;
  8044. /* not visible by applications */
  8045. this.state = null;
  8046. /* best guess about the data type: binary or text */
  8047. this.data_type = 2/*Z_UNKNOWN*/;
  8048. /* adler32 value of the uncompressed data */
  8049. this.adler = 0;
  8050. }
  8051. module.exports = ZStream;
  8052. },{}]},{},[9])
  8053. (9)
  8054. }));
  8055. /*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
  8056. /* vim: set ts=2: */
  8057. /*exported XLSX2 */
  8058. /*global global, exports, module, require:false, process:false, Buffer:false, ArrayBuffer:false */
  8059. var XLSX2 = {};
  8060. function make_xlsx_lib(XLSX2){
  8061. XLSX2.version = '0.17.0';
  8062. var current_codepage = 1200, current_ansi = 1252;
  8063. /*global cptable:true, window */
  8064. if(typeof module !== "undefined" && typeof require !== 'undefined') {
  8065. if(typeof cptable === 'undefined') {
  8066. if(typeof global !== 'undefined') global.cptable = undefined;
  8067. else if(typeof window !== 'undefined') window.cptable = undefined;
  8068. }
  8069. }
  8070. var VALID_ANSI = [ 874, 932, 936, 949, 950 ];
  8071. for(var i = 0; i <= 8; ++i) VALID_ANSI.push(1250 + i);
  8072. /* ECMA-376 Part I 18.4.1 charset to codepage mapping */
  8073. var CS2CP = ({
  8074. 0: 1252, /* ANSI */
  8075. 1: 65001, /* DEFAULT */
  8076. 2: 65001, /* SYMBOL */
  8077. 77: 10000, /* MAC */
  8078. 128: 932, /* SHIFTJIS */
  8079. 129: 949, /* HANGUL */
  8080. 130: 1361, /* JOHAB */
  8081. 134: 936, /* GB2312 */
  8082. 136: 950, /* CHINESEBIG5 */
  8083. 161: 1253, /* GREEK */
  8084. 162: 1254, /* TURKISH */
  8085. 163: 1258, /* VIETNAMESE */
  8086. 177: 1255, /* HEBREW */
  8087. 178: 1256, /* ARABIC */
  8088. 186: 1257, /* BALTIC */
  8089. 204: 1251, /* RUSSIAN */
  8090. 222: 874, /* THAI */
  8091. 238: 1250, /* EASTEUROPE */
  8092. 255: 1252, /* OEM */
  8093. 69: 6969 /* MISC */
  8094. });
  8095. var set_ansi = function(cp) { if(VALID_ANSI.indexOf(cp) == -1) return; current_ansi = CS2CP[0] = cp; };
  8096. function reset_ansi() { set_ansi(1252); }
  8097. var set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  8098. function reset_cp() { set_cp(1200); reset_ansi(); }
  8099. function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; }
  8100. function utf16leread(data) {
  8101. var o = [];
  8102. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i) + (data.charCodeAt(2*i+1)<<8));
  8103. return o.join("");
  8104. }
  8105. function utf16beread(data) {
  8106. var o = [];
  8107. for(var i = 0; i < (data.length>>1); ++i) o[i] = String.fromCharCode(data.charCodeAt(2*i+1) + (data.charCodeAt(2*i)<<8));
  8108. return o.join("");
  8109. }
  8110. var debom = function(data) {
  8111. var c1 = data.charCodeAt(0), c2 = data.charCodeAt(1);
  8112. if(c1 == 0xFF && c2 == 0xFE) return utf16leread(data.slice(2));
  8113. if(c1 == 0xFE && c2 == 0xFF) return utf16beread(data.slice(2));
  8114. if(c1 == 0xFEFF) return data.slice(1);
  8115. return data;
  8116. };
  8117. var _getchar = function _gc1(x) { return String.fromCharCode(x); };
  8118. var _getansi = function _ga1(x) { return String.fromCharCode(x); };
  8119. if(typeof cptable !== 'undefined') {
  8120. set_cp = function(cp) { current_codepage = cp; set_ansi(cp); };
  8121. debom = function(data) {
  8122. if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return cptable.utils.decode(1200, char_codes(data.slice(2))); }
  8123. return data;
  8124. };
  8125. _getchar = function _gc2(x) {
  8126. if(current_codepage === 1200) return String.fromCharCode(x);
  8127. return cptable.utils.decode(current_codepage, [x&255,x>>8])[0];
  8128. };
  8129. _getansi = function _ga2(x) {
  8130. return cptable.utils.decode(current_ansi, [x])[0];
  8131. };
  8132. }
  8133. var DENSE = null;
  8134. var DIF_XL = true;
  8135. var Base64 = (function make_b64(){
  8136. var map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8137. return {
  8138. encode: function(input) {
  8139. var o = "";
  8140. var c1=0, c2=0, c3=0, e1=0, e2=0, e3=0, e4=0;
  8141. for(var i = 0; i < input.length; ) {
  8142. c1 = input.charCodeAt(i++);
  8143. e1 = (c1 >> 2);
  8144. c2 = input.charCodeAt(i++);
  8145. e2 = ((c1 & 3) << 4) | (c2 >> 4);
  8146. c3 = input.charCodeAt(i++);
  8147. e3 = ((c2 & 15) << 2) | (c3 >> 6);
  8148. e4 = (c3 & 63);
  8149. if (isNaN(c2)) { e3 = e4 = 64; }
  8150. else if (isNaN(c3)) { e4 = 64; }
  8151. o += map.charAt(e1) + map.charAt(e2) + map.charAt(e3) + map.charAt(e4);
  8152. }
  8153. return o;
  8154. },
  8155. decode: function b64_decode(input) {
  8156. var o = "";
  8157. var c1=0, c2=0, c3=0, e1=0, e2=0, e3=0, e4=0;
  8158. input = input.replace(/[^\w\+\/\=]/g, "");
  8159. for(var i = 0; i < input.length;) {
  8160. e1 = map.indexOf(input.charAt(i++));
  8161. e2 = map.indexOf(input.charAt(i++));
  8162. c1 = (e1 << 2) | (e2 >> 4);
  8163. o += String.fromCharCode(c1);
  8164. e3 = map.indexOf(input.charAt(i++));
  8165. c2 = ((e2 & 15) << 4) | (e3 >> 2);
  8166. if (e3 !== 64) { o += String.fromCharCode(c2); }
  8167. e4 = map.indexOf(input.charAt(i++));
  8168. c3 = ((e3 & 3) << 6) | e4;
  8169. if (e4 !== 64) { o += String.fromCharCode(c3); }
  8170. }
  8171. return o;
  8172. }
  8173. };
  8174. })();
  8175. var has_buf = (typeof Buffer !== 'undefined' && typeof process !== 'undefined' && typeof process.versions !== 'undefined' && !!process.versions.node);
  8176. var Buffer_from = function(){};
  8177. if(typeof Buffer !== 'undefined') {
  8178. var nbfs = !Buffer.from;
  8179. if(!nbfs) try { Buffer.from("foo", "utf8"); } catch(e) { nbfs = true; }
  8180. Buffer_from = nbfs ? function(buf, enc) { return (enc) ? new Buffer(buf, enc) : new Buffer(buf); } : Buffer.from.bind(Buffer);
  8181. // $FlowIgnore
  8182. if(!Buffer.alloc) Buffer.alloc = function(n) { return new Buffer(n); };
  8183. // $FlowIgnore
  8184. if(!Buffer.allocUnsafe) Buffer.allocUnsafe = function(n) { return new Buffer(n); };
  8185. }
  8186. function new_raw_buf(len) {
  8187. /* jshint -W056 */
  8188. return has_buf ? Buffer.alloc(len) : new Array(len);
  8189. /* jshint +W056 */
  8190. }
  8191. function new_unsafe_buf(len) {
  8192. /* jshint -W056 */
  8193. return has_buf ? Buffer.allocUnsafe(len) : new Array(len);
  8194. /* jshint +W056 */
  8195. }
  8196. var s2a = function s2a(s) {
  8197. if(has_buf) return Buffer_from(s, "binary");
  8198. return s.split("").map(function(x){ return x.charCodeAt(0) & 0xff; });
  8199. };
  8200. function s2ab(s) {
  8201. if(typeof ArrayBuffer === 'undefined') return s2a(s);
  8202. var buf = new ArrayBuffer(s.length), view = new Uint8Array(buf);
  8203. for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  8204. return buf;
  8205. }
  8206. function a2s(data) {
  8207. if(Array.isArray(data)) return data.map(function(c) { return String.fromCharCode(c); }).join("");
  8208. var o = []; for(var i = 0; i < data.length; ++i) o[i] = String.fromCharCode(data[i]); return o.join("");
  8209. }
  8210. function a2u(data) {
  8211. if(typeof Uint8Array === 'undefined') throw new Error("Unsupported");
  8212. return new Uint8Array(data);
  8213. }
  8214. function ab2a(data) {
  8215. if(typeof ArrayBuffer == 'undefined') throw new Error("Unsupported");
  8216. if(data instanceof ArrayBuffer) return ab2a(new Uint8Array(data));
  8217. var o = new Array(data.length);
  8218. for(var i = 0; i < data.length; ++i) o[i] = data[i];
  8219. return o;
  8220. }
  8221. var bconcat = function(bufs) { return [].concat.apply([], bufs); };
  8222. var chr0 = /\u0000/g, chr1 = /[\u0001-\u0006]/g;
  8223. /* ssf.js (C) 2013-present SheetJS -- http://sheetjs.com */
  8224. /*jshint -W041 */
  8225. var SSF = ({});
  8226. var make_ssf = function make_ssf(SSF){
  8227. SSF.version = '0.11.2';
  8228. function _strrev(x) { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; }
  8229. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  8230. function pad0(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  8231. function pad_(v,d){var t=""+v;return t.length>=d?t:fill(' ',d-t.length)+t;}
  8232. function rpad_(v,d){var t=""+v; return t.length>=d?t:t+fill(' ',d-t.length);}
  8233. function pad0r1(v,d){var t=""+Math.round(v); return t.length>=d?t:fill('0',d-t.length)+t;}
  8234. function pad0r2(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;}
  8235. var p2_32 = Math.pow(2,32);
  8236. function pad0r(v,d){if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); }
  8237. function isgeneral(s, i) { i = i || 0; return s.length >= 7 + i && (s.charCodeAt(i)|32) === 103 && (s.charCodeAt(i+1)|32) === 101 && (s.charCodeAt(i+2)|32) === 110 && (s.charCodeAt(i+3)|32) === 101 && (s.charCodeAt(i+4)|32) === 114 && (s.charCodeAt(i+5)|32) === 97 && (s.charCodeAt(i+6)|32) === 108; }
  8238. var days = [
  8239. ['Sun', 'Sunday'],
  8240. ['Mon', 'Monday'],
  8241. ['Tue', 'Tuesday'],
  8242. ['Wed', 'Wednesday'],
  8243. ['Thu', 'Thursday'],
  8244. ['Fri', 'Friday'],
  8245. ['Sat', 'Saturday']
  8246. ];
  8247. var months = [
  8248. ['J', 'Jan', 'January'],
  8249. ['F', 'Feb', 'February'],
  8250. ['M', 'Mar', 'March'],
  8251. ['A', 'Apr', 'April'],
  8252. ['M', 'May', 'May'],
  8253. ['J', 'Jun', 'June'],
  8254. ['J', 'Jul', 'July'],
  8255. ['A', 'Aug', 'August'],
  8256. ['S', 'Sep', 'September'],
  8257. ['O', 'Oct', 'October'],
  8258. ['N', 'Nov', 'November'],
  8259. ['D', 'Dec', 'December']
  8260. ];
  8261. function init_table(t) {
  8262. t[0]= 'General';
  8263. t[1]= '0';
  8264. t[2]= '0.00';
  8265. t[3]= '#,##0';
  8266. t[4]= '#,##0.00';
  8267. t[9]= '0%';
  8268. t[10]= '0.00%';
  8269. t[11]= '0.00E+00';
  8270. t[12]= '# ?/?';
  8271. t[13]= '# ??/??';
  8272. t[14]= 'm/d/yy';
  8273. t[15]= 'd-mmm-yy';
  8274. t[16]= 'd-mmm';
  8275. t[17]= 'mmm-yy';
  8276. t[18]= 'h:mm AM/PM';
  8277. t[19]= 'h:mm:ss AM/PM';
  8278. t[20]= 'h:mm';
  8279. t[21]= 'h:mm:ss';
  8280. t[22]= 'm/d/yy h:mm';
  8281. t[37]= '#,##0 ;(#,##0)';
  8282. t[38]= '#,##0 ;[Red](#,##0)';
  8283. t[39]= '#,##0.00;(#,##0.00)';
  8284. t[40]= '#,##0.00;[Red](#,##0.00)';
  8285. t[45]= 'mm:ss';
  8286. t[46]= '[h]:mm:ss';
  8287. t[47]= 'mmss.0';
  8288. t[48]= '##0.0E+0';
  8289. t[49]= '@';
  8290. t[56]= '"上午/下午 "hh"時"mm"分"ss"秒 "';
  8291. }
  8292. var table_fmt = {};
  8293. init_table(table_fmt);
  8294. /* Defaults determined by systematically testing in Excel 2019 */
  8295. /* These formats appear to default to other formats in the table */
  8296. var default_map = [];
  8297. var defi = 0;
  8298. // 5 -> 37 ... 8 -> 40
  8299. for(defi = 5; defi <= 8; ++defi) default_map[defi] = 32 + defi;
  8300. // 23 -> 0 ... 26 -> 0
  8301. for(defi = 23; defi <= 26; ++defi) default_map[defi] = 0;
  8302. // 27 -> 14 ... 31 -> 14
  8303. for(defi = 27; defi <= 31; ++defi) default_map[defi] = 14;
  8304. // 50 -> 14 ... 58 -> 14
  8305. for(defi = 50; defi <= 58; ++defi) default_map[defi] = 14;
  8306. // 59 -> 1 ... 62 -> 4
  8307. for(defi = 59; defi <= 62; ++defi) default_map[defi] = defi - 58;
  8308. // 67 -> 9 ... 68 -> 10
  8309. for(defi = 67; defi <= 68; ++defi) default_map[defi] = defi - 58;
  8310. // 72 -> 14 ... 75 -> 17
  8311. for(defi = 72; defi <= 75; ++defi) default_map[defi] = defi - 58;
  8312. // 69 -> 12 ... 71 -> 14
  8313. for(defi = 67; defi <= 68; ++defi) default_map[defi] = defi - 57;
  8314. // 76 -> 20 ... 78 -> 22
  8315. for(defi = 76; defi <= 78; ++defi) default_map[defi] = defi - 56;
  8316. // 79 -> 45 ... 81 -> 47
  8317. for(defi = 79; defi <= 81; ++defi) default_map[defi] = defi - 34;
  8318. // 82 -> 0 ... 65536 -> 0 (omitted)
  8319. /* These formats technically refer to Accounting formats with no equivalent */
  8320. var default_str = [];
  8321. // 5 -- Currency, 0 decimal, black negative
  8322. default_str[5] = default_str[63] = '"$"#,##0_);\\("$"#,##0\\)';
  8323. // 6 -- Currency, 0 decimal, red negative
  8324. default_str[6] = default_str[64] = '"$"#,##0_);[Red]\\("$"#,##0\\)';
  8325. // 7 -- Currency, 2 decimal, black negative
  8326. default_str[7] = default_str[65] = '"$"#,##0.00_);\\("$"#,##0.00\\)';
  8327. // 8 -- Currency, 2 decimal, red negative
  8328. default_str[8] = default_str[66] = '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)';
  8329. // 41 -- Accounting, 0 decimal, No Symbol
  8330. default_str[41] = '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)';
  8331. // 42 -- Accounting, 0 decimal, $ Symbol
  8332. default_str[42] = '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)';
  8333. // 43 -- Accounting, 2 decimal, No Symbol
  8334. default_str[43] = '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)';
  8335. // 44 -- Accounting, 2 decimal, $ Symbol
  8336. default_str[44] = '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)';
  8337. function frac(x, D, mixed) {
  8338. var sgn = x < 0 ? -1 : 1;
  8339. var B = x * sgn;
  8340. var P_2 = 0, P_1 = 1, P = 0;
  8341. var Q_2 = 1, Q_1 = 0, Q = 0;
  8342. var A = Math.floor(B);
  8343. while(Q_1 < D) {
  8344. A = Math.floor(B);
  8345. P = A * P_1 + P_2;
  8346. Q = A * Q_1 + Q_2;
  8347. if((B - A) < 0.00000005) break;
  8348. B = 1 / (B - A);
  8349. P_2 = P_1; P_1 = P;
  8350. Q_2 = Q_1; Q_1 = Q;
  8351. }
  8352. if(Q > D) { if(Q_1 > D) { Q = Q_2; P = P_2; } else { Q = Q_1; P = P_1; } }
  8353. if(!mixed) return [0, sgn * P, Q];
  8354. var q = Math.floor(sgn * P/Q);
  8355. return [q, sgn*P - q*Q, Q];
  8356. }
  8357. function parse_date_code(v,opts,b2) {
  8358. if(v > 2958465 || v < 0) return null;
  8359. var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0;
  8360. var dout=[];
  8361. var out={D:date, T:time, u:86400*(v-date)-time,y:0,m:0,d:0,H:0,M:0,S:0,q:0};
  8362. if(Math.abs(out.u) < 1e-6) out.u = 0;
  8363. if(opts && opts.date1904) date += 1462;
  8364. if(out.u > 0.9999) {
  8365. out.u = 0;
  8366. if(++time == 86400) { out.T = time = 0; ++date; ++out.D; }
  8367. }
  8368. if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;}
  8369. else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;}
  8370. else {
  8371. if(date > 60) --date;
  8372. /* 1 = Jan 1 1900 in Gregorian */
  8373. var d = new Date(1900, 0, 1);
  8374. d.setDate(d.getDate() + date - 1);
  8375. dout = [d.getFullYear(), d.getMonth()+1,d.getDate()];
  8376. dow = d.getDay();
  8377. if(date < 60) dow = (dow + 6) % 7;
  8378. if(b2) dow = fix_hijri(d, dout);
  8379. }
  8380. out.y = dout[0]; out.m = dout[1]; out.d = dout[2];
  8381. out.S = time % 60; time = Math.floor(time / 60);
  8382. out.M = time % 60; time = Math.floor(time / 60);
  8383. out.H = time;
  8384. out.q = dow;
  8385. return out;
  8386. }
  8387. SSF.parse_date_code = parse_date_code;
  8388. var basedate = new Date(1899, 11, 31, 0, 0, 0);
  8389. var dnthresh = basedate.getTime();
  8390. var base1904 = new Date(1900, 2, 1, 0, 0, 0);
  8391. function datenum_local(v, date1904) {
  8392. var epoch = v.getTime();
  8393. if(date1904) epoch -= 1461*24*60*60*1000;
  8394. else if(v >= base1904) epoch += 24*60*60*1000;
  8395. return (epoch - (dnthresh + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000)) / (24 * 60 * 60 * 1000);
  8396. }
  8397. /* The longest 32-bit integer text is "-4294967296", exactly 11 chars */
  8398. function general_fmt_int(v) { return v.toString(10); }
  8399. SSF._general_int = general_fmt_int;
  8400. /* ECMA-376 18.8.30 numFmt*/
  8401. /* Note: `toPrecision` uses standard form when prec > E and E >= -6 */
  8402. var general_fmt_num = (function make_general_fmt_num() {
  8403. var trailing_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)$/;
  8404. function strip_decimal(o) {
  8405. return (o.indexOf(".") == -1) ? o : o.replace(trailing_zeroes_and_decimal, "$1");
  8406. }
  8407. /* General Exponential always shows 2 digits exp and trims the mantissa */
  8408. var mantissa_zeroes_and_decimal = /(?:\.0*|(\.\d*[1-9])0+)[Ee]/;
  8409. var exp_with_single_digit = /(E[+-])(\d)$/;
  8410. function normalize_exp(o) {
  8411. if(o.indexOf("E") == -1) return o;
  8412. return o.replace(mantissa_zeroes_and_decimal,"$1E").replace(exp_with_single_digit,"$10$2");
  8413. }
  8414. /* exponent >= -9 and <= 9 */
  8415. function small_exp(v) {
  8416. var w = (v<0?12:11);
  8417. var o = strip_decimal(v.toFixed(12)); if(o.length <= w) return o;
  8418. o = v.toPrecision(10); if(o.length <= w) return o;
  8419. return v.toExponential(5);
  8420. }
  8421. /* exponent >= 11 or <= -10 likely exponential */
  8422. function large_exp(v) {
  8423. var o = strip_decimal(v.toFixed(11));
  8424. return (o.length > (v<0?12:11) || o === "0" || o === "-0") ? v.toPrecision(6) : o;
  8425. }
  8426. function general_fmt_num_base(v) {
  8427. var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o;
  8428. if(V >= -4 && V <= -1) o = v.toPrecision(10+V);
  8429. else if(Math.abs(V) <= 9) o = small_exp(v);
  8430. else if(V === 10) o = v.toFixed(10).substr(0,12);
  8431. else o = large_exp(v);
  8432. return strip_decimal(normalize_exp(o.toUpperCase()));
  8433. }
  8434. return general_fmt_num_base;
  8435. })();
  8436. SSF._general_num = general_fmt_num;
  8437. /*
  8438. "General" rules:
  8439. - text is passed through ("@")
  8440. - booleans are rendered as TRUE/FALSE
  8441. - "up to 11 characters" displayed for numbers
  8442. - Default date format (code 14) used for Dates
  8443. TODO: technically the display depends on the width of the cell
  8444. */
  8445. function general_fmt(v, opts) {
  8446. switch(typeof v) {
  8447. case 'string': return v;
  8448. case 'boolean': return v ? "TRUE" : "FALSE";
  8449. case 'number': return (v|0) === v ? v.toString(10) : general_fmt_num(v);
  8450. case 'undefined': return "";
  8451. case 'object':
  8452. if(v == null) return "";
  8453. if(v instanceof Date) return format(14, datenum_local(v, opts && opts.date1904), opts);
  8454. }
  8455. throw new Error("unsupported value in General format: " + v);
  8456. }
  8457. SSF._general = general_fmt;
  8458. function fix_hijri(date, o) {
  8459. /* TODO: properly adjust y/m/d and */
  8460. o[0] -= 581;
  8461. var dow = date.getDay();
  8462. if(date < 60) dow = (dow + 6) % 7;
  8463. return dow;
  8464. }
  8465. //var THAI_DIGITS = "\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59".split("");
  8466. /*jshint -W086 */
  8467. function write_date(type, fmt, val, ss0) {
  8468. var o="", ss=0, tt=0, y = val.y, out, outl = 0;
  8469. switch(type) {
  8470. case 98: /* 'b' buddhist year */
  8471. y = val.y + 543;
  8472. /* falls through */
  8473. case 121: /* 'y' year */
  8474. switch(fmt.length) {
  8475. case 1: case 2: out = y % 100; outl = 2; break;
  8476. default: out = y % 10000; outl = 4; break;
  8477. } break;
  8478. case 109: /* 'm' month */
  8479. switch(fmt.length) {
  8480. case 1: case 2: out = val.m; outl = fmt.length; break;
  8481. case 3: return months[val.m-1][1];
  8482. case 5: return months[val.m-1][0];
  8483. default: return months[val.m-1][2];
  8484. } break;
  8485. case 100: /* 'd' day */
  8486. switch(fmt.length) {
  8487. case 1: case 2: out = val.d; outl = fmt.length; break;
  8488. case 3: return days[val.q][0];
  8489. default: return days[val.q][1];
  8490. } break;
  8491. case 104: /* 'h' 12-hour */
  8492. switch(fmt.length) {
  8493. case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break;
  8494. default: throw 'bad hour format: ' + fmt;
  8495. } break;
  8496. case 72: /* 'H' 24-hour */
  8497. switch(fmt.length) {
  8498. case 1: case 2: out = val.H; outl = fmt.length; break;
  8499. default: throw 'bad hour format: ' + fmt;
  8500. } break;
  8501. case 77: /* 'M' minutes */
  8502. switch(fmt.length) {
  8503. case 1: case 2: out = val.M; outl = fmt.length; break;
  8504. default: throw 'bad minute format: ' + fmt;
  8505. } break;
  8506. case 115: /* 's' seconds */
  8507. if(fmt != 's' && fmt != 'ss' && fmt != '.0' && fmt != '.00' && fmt != '.000') throw 'bad second format: ' + fmt;
  8508. if(val.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val.S, fmt.length);
  8509. if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100;
  8510. else tt = ss0 === 1 ? 10 : 1;
  8511. ss = Math.round((tt)*(val.S + val.u));
  8512. if(ss >= 60*tt) ss = 0;
  8513. if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt;
  8514. o = pad0(ss,2 + ss0);
  8515. if(fmt === 'ss') return o.substr(0,2);
  8516. return "." + o.substr(2,fmt.length-1);
  8517. case 90: /* 'Z' absolute time */
  8518. switch(fmt) {
  8519. case '[h]': case '[hh]': out = val.D*24+val.H; break;
  8520. case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break;
  8521. case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break;
  8522. default: throw 'bad abstime format: ' + fmt;
  8523. } outl = fmt.length === 3 ? 1 : 2; break;
  8524. case 101: /* 'e' era */
  8525. out = y; outl = 1; break;
  8526. }
  8527. var outstr = outl > 0 ? pad0(out, outl) : "";
  8528. return outstr;
  8529. }
  8530. /*jshint +W086 */
  8531. function commaify(s) {
  8532. var w = 3;
  8533. if(s.length <= w) return s;
  8534. var j = (s.length % w), o = s.substr(0,j);
  8535. for(; j!=s.length; j+=w) o+=(o.length > 0 ? "," : "") + s.substr(j,w);
  8536. return o;
  8537. }
  8538. var write_num = (function make_write_num(){
  8539. var pct1 = /%/g;
  8540. function write_num_pct(type, fmt, val){
  8541. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  8542. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  8543. }
  8544. function write_num_cm(type, fmt, val){
  8545. var idx = fmt.length - 1;
  8546. while(fmt.charCodeAt(idx-1) === 44) --idx;
  8547. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  8548. }
  8549. function write_num_exp(fmt, val){
  8550. var o;
  8551. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  8552. if(fmt.match(/^#+0.0E\+0$/)) {
  8553. if(val == 0) return "0.0E+0";
  8554. else if(val < 0) return "-" + write_num_exp(fmt, -val);
  8555. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  8556. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  8557. if(ee < 0) ee += period;
  8558. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  8559. if(o.indexOf("e") === -1) {
  8560. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  8561. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  8562. else o += "E+" + (fakee - ee);
  8563. while(o.substr(0,2) === "0.") {
  8564. o = o.charAt(0) + o.substr(2,period) + "." + o.substr(2+period);
  8565. o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0.");
  8566. }
  8567. o = o.replace(/\+-/,"-");
  8568. }
  8569. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  8570. } else o = val.toExponential(idx);
  8571. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  8572. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  8573. return o.replace("e","E");
  8574. }
  8575. var frac1 = /# (\?+)( ?)\/( ?)(\d+)/;
  8576. function write_num_f1(r, aval, sign) {
  8577. var den = parseInt(r[4],10), rr = Math.round(aval * den), base = Math.floor(rr/den);
  8578. var myn = (rr - base*den), myd = den;
  8579. return sign + (base === 0 ? "" : ""+base) + " " + (myn === 0 ? fill(" ", r[1].length + 1 + r[4].length) : pad_(myn,r[1].length) + r[2] + "/" + r[3] + pad0(myd,r[4].length));
  8580. }
  8581. function write_num_f2(r, aval, sign) {
  8582. return sign + (aval === 0 ? "" : ""+aval) + fill(" ", r[1].length + 2 + r[4].length);
  8583. }
  8584. var dec1 = /^#*0*\.([0#]+)/;
  8585. var closeparen = /\).*[0#]/;
  8586. var phone = /\(###\) ###\\?-####/;
  8587. function hashq(str) {
  8588. var o = "", cc;
  8589. for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) {
  8590. case 35: break;
  8591. case 63: o+= " "; break;
  8592. case 48: o+= "0"; break;
  8593. default: o+= String.fromCharCode(cc);
  8594. }
  8595. return o;
  8596. }
  8597. function rnd(val, d) { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); }
  8598. function dec(val, d) {
  8599. var _frac = val - Math.floor(val), dd = Math.pow(10,d);
  8600. if (d < ('' + Math.round(_frac * dd)).length) return 0;
  8601. return Math.round(_frac * dd);
  8602. }
  8603. function carry(val, d) {
  8604. if (d < ('' + Math.round((val-Math.floor(val))*Math.pow(10,d))).length) {
  8605. return 1;
  8606. }
  8607. return 0;
  8608. }
  8609. function flr(val) {
  8610. if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0));
  8611. return ""+Math.floor(val);
  8612. }
  8613. function write_num_flt(type, fmt, val) {
  8614. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  8615. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  8616. if(val >= 0) return write_num_flt('n', ffmt, val);
  8617. return '(' + write_num_flt('n', ffmt, -val) + ')';
  8618. }
  8619. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val);
  8620. if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val);
  8621. if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val);
  8622. if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  8623. var o;
  8624. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  8625. if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length);
  8626. if(fmt.match(/^[#?]+$/)) {
  8627. o = pad0r(val,0); if(o === "0") o = "";
  8628. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8629. }
  8630. if((r = fmt.match(frac1))) return write_num_f1(r, aval, sign);
  8631. if(fmt.match(/^#+0+$/)) return sign + pad0r(aval,fmt.length - fmt.indexOf("0"));
  8632. if((r = fmt.match(dec1))) {
  8633. o = rnd(val, r[1].length).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1])).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  8634. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  8635. }
  8636. fmt = fmt.replace(/^#+([0.])/, "$1");
  8637. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  8638. return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  8639. }
  8640. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify(pad0r(aval,0));
  8641. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  8642. return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(""+(Math.floor(val) + carry(val, r[1].length))) + "." + pad0(dec(val, r[1].length),r[1].length);
  8643. }
  8644. if((r = fmt.match(/^#,#*,#0/))) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val);
  8645. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  8646. o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val));
  8647. ri = 0;
  8648. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  8649. }
  8650. if(fmt.match(phone)) {
  8651. o = write_num_flt(type, "##########", val);
  8652. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  8653. }
  8654. var oa = "";
  8655. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8656. ri = Math.min(r[4].length,7);
  8657. ff = frac(aval, Math.pow(10,ri)-1, false);
  8658. o = "" + sign;
  8659. oa = write_num("n", r[1], ff[1]);
  8660. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  8661. o += oa + r[2] + "/" + r[3];
  8662. oa = rpad_(ff[2],ri);
  8663. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  8664. o += oa;
  8665. return o;
  8666. }
  8667. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8668. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  8669. ff = frac(aval, Math.pow(10,ri)-1, true);
  8670. return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
  8671. }
  8672. if((r = fmt.match(/^[#0?]+$/))) {
  8673. o = pad0r(val, 0);
  8674. if(fmt.length <= o.length) return o;
  8675. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8676. }
  8677. if((r = fmt.match(/^([#0?]+)\.([#0]+)$/))) {
  8678. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  8679. ri = o.indexOf(".");
  8680. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  8681. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  8682. }
  8683. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  8684. ri = dec(val, r[1].length);
  8685. return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(flr(val)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(ri,r[1].length);
  8686. }
  8687. switch(fmt) {
  8688. case "###,##0.00": return write_num_flt(type, "#,##0.00", val);
  8689. case "###,###":
  8690. case "##,###":
  8691. case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : "";
  8692. case "###,###.00": return write_num_flt(type, "###,##0.00",val).replace(/^0\./,".");
  8693. case "#,###.00": return write_num_flt(type, "#,##0.00",val).replace(/^0\./,".");
  8694. default:
  8695. }
  8696. throw new Error("unsupported format |" + fmt + "|");
  8697. }
  8698. function write_num_cm2(type, fmt, val){
  8699. var idx = fmt.length - 1;
  8700. while(fmt.charCodeAt(idx-1) === 44) --idx;
  8701. return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx)));
  8702. }
  8703. function write_num_pct2(type, fmt, val){
  8704. var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length;
  8705. return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul);
  8706. }
  8707. function write_num_exp2(fmt, val){
  8708. var o;
  8709. var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1;
  8710. if(fmt.match(/^#+0.0E\+0$/)) {
  8711. if(val == 0) return "0.0E+0";
  8712. else if(val < 0) return "-" + write_num_exp2(fmt, -val);
  8713. var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E');
  8714. var ee = Math.floor(Math.log(val)*Math.LOG10E)%period;
  8715. if(ee < 0) ee += period;
  8716. o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period);
  8717. if(!o.match(/[Ee]/)) {
  8718. var fakee = Math.floor(Math.log(val)*Math.LOG10E);
  8719. if(o.indexOf(".") === -1) o = o.charAt(0) + "." + o.substr(1) + "E+" + (fakee - o.length+ee);
  8720. else o += "E+" + (fakee - ee);
  8721. o = o.replace(/\+-/,"-");
  8722. }
  8723. o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; });
  8724. } else o = val.toExponential(idx);
  8725. if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o.charAt(o.length-1);
  8726. if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e");
  8727. return o.replace("e","E");
  8728. }
  8729. function write_num_int(type, fmt, val) {
  8730. if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) {
  8731. var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,"");
  8732. if(val >= 0) return write_num_int('n', ffmt, val);
  8733. return '(' + write_num_int('n', ffmt, -val) + ')';
  8734. }
  8735. if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val);
  8736. if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val);
  8737. if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val);
  8738. if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt.charAt(1)==' '?2:1),val);
  8739. var o;
  8740. var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : "";
  8741. if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length);
  8742. if(fmt.match(/^[#?]+$/)) {
  8743. o = (""+val); if(val === 0) o = "";
  8744. return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8745. }
  8746. if((r = fmt.match(frac1))) return write_num_f2(r, aval, sign);
  8747. if(fmt.match(/^#+0+$/)) return sign + pad0(aval,fmt.length - fmt.indexOf("0"));
  8748. if((r = fmt.match(dec1))) {
  8749. o = (""+val).replace(/^([^\.]+)$/,"$1."+hashq(r[1])).replace(/\.$/,"."+hashq(r[1]));
  8750. o = o.replace(/\.(\d*)$/,function($$, $1) {
  8751. return "." + $1 + fill("0", hashq(r[1]).length-$1.length); });
  8752. return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,".");
  8753. }
  8754. fmt = fmt.replace(/^#+([0.])/, "$1");
  8755. if((r = fmt.match(/^(0*)\.(#*)$/))) {
  8756. return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":".");
  8757. }
  8758. if((r = fmt.match(/^#{1,3},##0(\.?)$/))) return sign + commaify((""+aval));
  8759. if((r = fmt.match(/^#,##0\.([#0]*0)$/))) {
  8760. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill('0',r[1].length);
  8761. }
  8762. if((r = fmt.match(/^#,#*,#0/))) return write_num_int(type,fmt.replace(/^#,#*,/,""),val);
  8763. if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/))) {
  8764. o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val));
  8765. ri = 0;
  8766. return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o.charAt(ri++):x==='0'?'0':"";}));
  8767. }
  8768. if(fmt.match(phone)) {
  8769. o = write_num_int(type, "##########", val);
  8770. return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6);
  8771. }
  8772. var oa = "";
  8773. if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8774. ri = Math.min(r[4].length,7);
  8775. ff = frac(aval, Math.pow(10,ri)-1, false);
  8776. o = "" + sign;
  8777. oa = write_num("n", r[1], ff[1]);
  8778. if(oa.charAt(oa.length-1) == " ") oa = oa.substr(0,oa.length-1) + "0";
  8779. o += oa + r[2] + "/" + r[3];
  8780. oa = rpad_(ff[2],ri);
  8781. if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa;
  8782. o += oa;
  8783. return o;
  8784. }
  8785. if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/))) {
  8786. ri = Math.min(Math.max(r[1].length, r[4].length),7);
  8787. ff = frac(aval, Math.pow(10,ri)-1, true);
  8788. return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length));
  8789. }
  8790. if((r = fmt.match(/^[#0?]+$/))) {
  8791. o = "" + val;
  8792. if(fmt.length <= o.length) return o;
  8793. return hashq(fmt.substr(0,fmt.length-o.length)) + o;
  8794. }
  8795. if((r = fmt.match(/^([#0]+)\.([#0]+)$/))) {
  8796. o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1");
  8797. ri = o.indexOf(".");
  8798. var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres;
  8799. return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres));
  8800. }
  8801. if((r = fmt.match(/^00,000\.([#0]*0)$/))) {
  8802. return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify(""+val).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(0,r[1].length);
  8803. }
  8804. switch(fmt) {
  8805. case "###,###":
  8806. case "##,###":
  8807. case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : "";
  8808. default:
  8809. if(fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0,fmt.lastIndexOf(".")), val) + hashq(fmt.slice(fmt.lastIndexOf(".")));
  8810. }
  8811. throw new Error("unsupported format |" + fmt + "|");
  8812. }
  8813. return function write_num(type, fmt, val) {
  8814. return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val);
  8815. };})();
  8816. function split_fmt(fmt) {
  8817. var out = [];
  8818. var in_str = false/*, cc*/;
  8819. for(var i = 0, j = 0; i < fmt.length; ++i) switch((/*cc=*/fmt.charCodeAt(i))) {
  8820. case 34: /* '"' */
  8821. in_str = !in_str; break;
  8822. case 95: case 42: case 92: /* '_' '*' '\\' */
  8823. ++i; break;
  8824. case 59: /* ';' */
  8825. out[out.length] = fmt.substr(j,i-j);
  8826. j = i+1;
  8827. }
  8828. out[out.length] = fmt.substr(j);
  8829. if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string ");
  8830. return out;
  8831. }
  8832. SSF._split = split_fmt;
  8833. var abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/;
  8834. function fmt_is_date(fmt) {
  8835. var i = 0, /*cc = 0,*/ c = "", o = "";
  8836. while(i < fmt.length) {
  8837. switch((c = fmt.charAt(i))) {
  8838. case 'G': if(isgeneral(fmt, i)) i+= 6; i++; break;
  8839. case '"': for(;(/*cc=*/fmt.charCodeAt(++i)) !== 34 && i < fmt.length;){/*empty*/} ++i; break;
  8840. case '\\': i+=2; break;
  8841. case '_': i+=2; break;
  8842. case '@': ++i; break;
  8843. case 'B': case 'b':
  8844. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") return true;
  8845. /* falls through */
  8846. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  8847. /* falls through */
  8848. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g': return true;
  8849. case 'A': case 'a': case '上':
  8850. if(fmt.substr(i, 3).toUpperCase() === "A/P") return true;
  8851. if(fmt.substr(i, 5).toUpperCase() === "AM/PM") return true;
  8852. if(fmt.substr(i, 5).toUpperCase() === "上午/下午") return true;
  8853. ++i; break;
  8854. case '[':
  8855. o = c;
  8856. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  8857. if(o.match(abstime)) return true;
  8858. break;
  8859. case '.':
  8860. /* falls through */
  8861. case '0': case '#':
  8862. while(i < fmt.length && ("0#?.,E+-%".indexOf(c=fmt.charAt(++i)) > -1 || (c=='\\' && fmt.charAt(i+1) == "-" && "0#".indexOf(fmt.charAt(i+2))>-1))){/* empty */}
  8863. break;
  8864. case '?': while(fmt.charAt(++i) === c){/* empty */} break;
  8865. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break;
  8866. case '(': case ')': ++i; break;
  8867. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  8868. while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1){/* empty */} break;
  8869. case ' ': ++i; break;
  8870. default: ++i; break;
  8871. }
  8872. }
  8873. return false;
  8874. }
  8875. SSF.is_date = fmt_is_date;
  8876. function eval_fmt(fmt, v, opts, flen) {
  8877. var out = [], o = "", i = 0, c = "", lst='t', dt, j, cc;
  8878. var hr='H';
  8879. /* Tokenize */
  8880. while(i < fmt.length) {
  8881. switch((c = fmt.charAt(i))) {
  8882. case 'G': /* General */
  8883. if(!isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt);
  8884. out[out.length] = {t:'G', v:'General'}; i+=7; break;
  8885. case '"': /* Literal text */
  8886. for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc);
  8887. out[out.length] = {t:'t', v:o}; ++i; break;
  8888. case '\\': var w = fmt.charAt(++i), t = (w === "(" || w === ")") ? w : 't';
  8889. out[out.length] = {t:t, v:w}; ++i; break;
  8890. case '_': out[out.length] = {t:'t', v:" "}; i+=2; break;
  8891. case '@': /* Text Placeholder */
  8892. out[out.length] = {t:'T', v:v}; ++i; break;
  8893. case 'B': case 'b':
  8894. if(fmt.charAt(i+1) === "1" || fmt.charAt(i+1) === "2") {
  8895. if(dt==null) { dt=parse_date_code(v, opts, fmt.charAt(i+1) === "2"); if(dt==null) return ""; }
  8896. out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break;
  8897. }
  8898. /* falls through */
  8899. case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E':
  8900. c = c.toLowerCase();
  8901. /* falls through */
  8902. case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g':
  8903. if(v < 0) return "";
  8904. if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
  8905. o = c; while(++i < fmt.length && fmt.charAt(i).toLowerCase() === c) o+=c;
  8906. if(c === 'm' && lst.toLowerCase() === 'h') c = 'M';
  8907. if(c === 'h') c = hr;
  8908. out[out.length] = {t:c, v:o}; lst = c; break;
  8909. case 'A': case 'a': case '上':
  8910. var q={t:c, v:c};
  8911. if(dt==null) dt=parse_date_code(v, opts);
  8912. if(fmt.substr(i, 3).toUpperCase() === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;}
  8913. else if(fmt.substr(i,5).toUpperCase() === "AM/PM") { if(dt!=null) q.v = dt.H >= 12 ? "PM" : "AM"; q.t = 'T'; i+=5; hr='h'; }
  8914. else if(fmt.substr(i,5).toUpperCase() === "上午/下午") { if(dt!=null) q.v = dt.H >= 12 ? "下午" : "上午"; q.t = 'T'; i+=5; hr='h'; }
  8915. else { q.t = "t"; ++i; }
  8916. if(dt==null && q.t === 'T') return "";
  8917. out[out.length] = q; lst = c; break;
  8918. case '[':
  8919. o = c;
  8920. while(fmt.charAt(i++) !== ']' && i < fmt.length) o += fmt.charAt(i);
  8921. if(o.slice(-1) !== ']') throw 'unterminated "[" block: |' + o + '|';
  8922. if(o.match(abstime)) {
  8923. if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; }
  8924. out[out.length] = {t:'Z', v:o.toLowerCase()};
  8925. lst = o.charAt(1);
  8926. } else if(o.indexOf("$") > -1) {
  8927. o = (o.match(/\$([^-\[\]]*)/)||[])[1]||"$";
  8928. if(!fmt_is_date(fmt)) out[out.length] = {t:'t',v:o};
  8929. }
  8930. break;
  8931. /* Numbers */
  8932. case '.':
  8933. if(dt != null) {
  8934. o = c; while(++i < fmt.length && (c=fmt.charAt(i)) === "0") o += c;
  8935. out[out.length] = {t:'s', v:o}; break;
  8936. }
  8937. /* falls through */
  8938. case '0': case '#':
  8939. o = c; while(++i < fmt.length && "0#?.,E+-%".indexOf(c=fmt.charAt(i)) > -1) o += c;
  8940. out[out.length] = {t:'n', v:o}; break;
  8941. case '?':
  8942. o = c; while(fmt.charAt(++i) === c) o+=c;
  8943. out[out.length] = {t:c, v:o}; lst = c; break;
  8944. case '*': ++i; if(fmt.charAt(i) == ' ' || fmt.charAt(i) == '*') ++i; break; // **
  8945. case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break;
  8946. case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  8947. o = c; while(i < fmt.length && "0123456789".indexOf(fmt.charAt(++i)) > -1) o+=fmt.charAt(i);
  8948. out[out.length] = {t:'D', v:o}; break;
  8949. case ' ': out[out.length] = {t:c, v:c}; ++i; break;
  8950. case '$': out[out.length] = {t:'t', v:'$'}; ++i; break;
  8951. default:
  8952. if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxzP".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt);
  8953. out[out.length] = {t:'t', v:c}; ++i; break;
  8954. }
  8955. }
  8956. /* Scan for date/time parts */
  8957. var bt = 0, ss0 = 0, ssm;
  8958. for(i=out.length-1, lst='t'; i >= 0; --i) {
  8959. switch(out[i].t) {
  8960. case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break;
  8961. case 's':
  8962. if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1);
  8963. if(bt < 3) bt = 3;
  8964. /* falls through */
  8965. case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break;
  8966. case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break;
  8967. case 'X': /*if(out[i].v === "B2");*/
  8968. break;
  8969. case 'Z':
  8970. if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1;
  8971. if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2;
  8972. if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3;
  8973. }
  8974. }
  8975. /* time rounding depends on presence of minute / second / usec fields */
  8976. switch(bt) {
  8977. case 0: break;
  8978. case 1:
  8979. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  8980. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  8981. if(dt.M >= 60) { dt.M = 0; ++dt.H; }
  8982. break;
  8983. case 2:
  8984. if(dt.u >= 0.5) { dt.u = 0; ++dt.S; }
  8985. if(dt.S >= 60) { dt.S = 0; ++dt.M; }
  8986. break;
  8987. }
  8988. /* replace fields */
  8989. var nstr = "", jj;
  8990. for(i=0; i < out.length; ++i) {
  8991. switch(out[i].t) {
  8992. case 't': case 'T': case ' ': case 'D': break;
  8993. case 'X': out[i].v = ""; out[i].t = ";"; break;
  8994. case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z':
  8995. out[i].v = write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0);
  8996. out[i].t = 't'; break;
  8997. case 'n': case '?':
  8998. jj = i+1;
  8999. while(out[jj] != null && (
  9000. (c=out[jj].t) === "?" || c === "D" ||
  9001. ((c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/')) ||
  9002. (out[i].t === '(' && (c === ' ' || c === 'n' || c === ')')) ||
  9003. (c === 't' && (out[jj].v === '/' || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?'))
  9004. )) {
  9005. out[i].v += out[jj].v;
  9006. out[jj] = {v:"", t:";"}; ++jj;
  9007. }
  9008. nstr += out[i].v;
  9009. i = jj-1; break;
  9010. case 'G': out[i].t = 't'; out[i].v = general_fmt(v,opts); break;
  9011. }
  9012. }
  9013. var vv = "", myv, ostr;
  9014. if(nstr.length > 0) {
  9015. if(nstr.charCodeAt(0) == 40) /* '(' */ {
  9016. myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v);
  9017. ostr = write_num('n', nstr, myv);
  9018. } else {
  9019. myv = (v<0 && flen > 1 ? -v : v);
  9020. ostr = write_num('n', nstr, myv);
  9021. if(myv < 0 && out[0] && out[0].t == 't') {
  9022. ostr = ostr.substr(1);
  9023. out[0].v = "-" + out[0].v;
  9024. }
  9025. }
  9026. jj=ostr.length-1;
  9027. var decpt = out.length;
  9028. for(i=0; i < out.length; ++i) if(out[i] != null && out[i].t != 't' && out[i].v.indexOf(".") > -1) { decpt = i; break; }
  9029. var lasti=out.length;
  9030. if(decpt === out.length && ostr.indexOf("E") === -1) {
  9031. for(i=out.length-1; i>= 0;--i) {
  9032. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  9033. if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); }
  9034. else if(jj < 0) out[i].v = "";
  9035. else { out[i].v = ostr.substr(0, jj+1); jj = -1; }
  9036. out[i].t = 't';
  9037. lasti = i;
  9038. }
  9039. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  9040. }
  9041. else if(decpt !== out.length && ostr.indexOf("E") === -1) {
  9042. jj = ostr.indexOf(".")-1;
  9043. for(i=decpt; i>= 0; --i) {
  9044. if(out[i] == null || 'n?'.indexOf(out[i].t) === -1) continue;
  9045. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1;
  9046. vv = out[i].v.substr(j+1);
  9047. for(; j>=0; --j) {
  9048. if(jj>=0 && (out[i].v.charAt(j) === "0" || out[i].v.charAt(j) === "#")) vv = ostr.charAt(jj--) + vv;
  9049. }
  9050. out[i].v = vv;
  9051. out[i].t = 't';
  9052. lasti = i;
  9053. }
  9054. if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v;
  9055. jj = ostr.indexOf(".")+1;
  9056. for(i=decpt; i<out.length; ++i) {
  9057. if(out[i] == null || ('n?('.indexOf(out[i].t) === -1 && i !== decpt)) continue;
  9058. j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0;
  9059. vv = out[i].v.substr(0,j);
  9060. for(; j<out[i].v.length; ++j) {
  9061. if(jj<ostr.length) vv += ostr.charAt(jj++);
  9062. }
  9063. out[i].v = vv;
  9064. out[i].t = 't';
  9065. lasti = i;
  9066. }
  9067. }
  9068. }
  9069. for(i=0; i<out.length; ++i) if(out[i] != null && 'n?'.indexOf(out[i].t)>-1) {
  9070. myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v);
  9071. out[i].v = write_num(out[i].t, out[i].v, myv);
  9072. out[i].t = 't';
  9073. }
  9074. var retval = "";
  9075. for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v;
  9076. return retval;
  9077. }
  9078. SSF._eval = eval_fmt;
  9079. var cfregex = /\[[=<>]/;
  9080. var cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/;
  9081. function chkcond(v, rr) {
  9082. if(rr == null) return false;
  9083. var thresh = parseFloat(rr[2]);
  9084. switch(rr[1]) {
  9085. case "=": if(v == thresh) return true; break;
  9086. case ">": if(v > thresh) return true; break;
  9087. case "<": if(v < thresh) return true; break;
  9088. case "<>": if(v != thresh) return true; break;
  9089. case ">=": if(v >= thresh) return true; break;
  9090. case "<=": if(v <= thresh) return true; break;
  9091. }
  9092. return false;
  9093. }
  9094. function choose_fmt(f, v) {
  9095. var fmt = split_fmt(f);
  9096. var l = fmt.length, lat = fmt[l-1].indexOf("@");
  9097. if(l<4 && lat>-1) --l;
  9098. if(fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|");
  9099. if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"];
  9100. switch(fmt.length) {
  9101. case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break;
  9102. case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break;
  9103. case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break;
  9104. case 4: break;
  9105. }
  9106. var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2];
  9107. if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff];
  9108. if(fmt[0].match(cfregex) != null || fmt[1].match(cfregex) != null) {
  9109. var m1 = fmt[0].match(cfregex2);
  9110. var m2 = fmt[1].match(cfregex2);
  9111. return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]];
  9112. }
  9113. return [l, ff];
  9114. }
  9115. function format(fmt,v,o) {
  9116. if(o == null) o = {};
  9117. var sfmt = "";
  9118. switch(typeof fmt) {
  9119. case "string":
  9120. if(fmt == "m/d/yy" && o.dateNF) sfmt = o.dateNF;
  9121. else sfmt = fmt;
  9122. break;
  9123. case "number":
  9124. if(fmt == 14 && o.dateNF) sfmt = o.dateNF;
  9125. else sfmt = (o.table != null ? (o.table) : table_fmt)[fmt];
  9126. if(sfmt == null) sfmt = (o.table && o.table[default_map[fmt]]) || table_fmt[default_map[fmt]];
  9127. if(sfmt == null) sfmt = default_str[fmt] || "General";
  9128. break;
  9129. }
  9130. if(isgeneral(sfmt,0)) return general_fmt(v, o);
  9131. if(v instanceof Date) v = datenum_local(v, o.date1904);
  9132. var f = choose_fmt(sfmt, v);
  9133. if(isgeneral(f[1])) return general_fmt(v, o);
  9134. if(v === true) v = "TRUE"; else if(v === false) v = "FALSE";
  9135. else if(v === "" || v == null) return "";
  9136. return eval_fmt(f[1], v, o, f[0]);
  9137. }
  9138. function load_entry(fmt, idx) {
  9139. if(typeof idx != 'number') {
  9140. idx = +idx || -1;
  9141. for(var i = 0; i < 0x0188; ++i) {
  9142. if(table_fmt[i] == undefined) { if(idx < 0) idx = i; continue; }
  9143. if(table_fmt[i] == fmt) { idx = i; break; }
  9144. }
  9145. if(idx < 0) idx = 0x187;
  9146. }
  9147. table_fmt[idx] = fmt;
  9148. return idx;
  9149. }
  9150. SSF.load = load_entry;
  9151. SSF._table = table_fmt;
  9152. SSF.get_table = function get_table() { return table_fmt; };
  9153. SSF.load_table = function load_table(tbl) {
  9154. for(var i=0; i!=0x0188; ++i)
  9155. if(tbl[i] !== undefined) load_entry(tbl[i], i);
  9156. };
  9157. SSF.init_table = init_table;
  9158. SSF.format = format;
  9159. };
  9160. make_ssf(SSF);
  9161. /* map from xlml named formats to SSF TODO: localize */
  9162. var XLMLFormatMap/*{[string]:string}*/ = ({
  9163. "General Number": "General",
  9164. "General Date": SSF._table[22],
  9165. "Long Date": "dddd, mmmm dd, yyyy",
  9166. "Medium Date": SSF._table[15],
  9167. "Short Date": SSF._table[14],
  9168. "Long Time": SSF._table[19],
  9169. "Medium Time": SSF._table[18],
  9170. "Short Time": SSF._table[20],
  9171. "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  9172. "Fixed": SSF._table[2],
  9173. "Standard": SSF._table[4],
  9174. "Percent": SSF._table[10],
  9175. "Scientific": SSF._table[11],
  9176. "Yes/No": '"Yes";"Yes";"No";@',
  9177. "True/False": '"True";"True";"False";@',
  9178. "On/Off": '"Yes";"Yes";"No";@'
  9179. });
  9180. var SSFImplicit/*{[number]:string}*/ = ({
  9181. "5": '"$"#,##0_);\\("$"#,##0\\)',
  9182. "6": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  9183. "7": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  9184. "8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  9185. "23": 'General', "24": 'General', "25": 'General', "26": 'General',
  9186. "27": 'm/d/yy', "28": 'm/d/yy', "29": 'm/d/yy', "30": 'm/d/yy', "31": 'm/d/yy',
  9187. "32": 'h:mm:ss', "33": 'h:mm:ss', "34": 'h:mm:ss', "35": 'h:mm:ss',
  9188. "36": 'm/d/yy',
  9189. "41": '_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)',
  9190. "42": '_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)',
  9191. "43": '_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)',
  9192. "44": '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
  9193. "50": 'm/d/yy', "51": 'm/d/yy', "52": 'm/d/yy', "53": 'm/d/yy', "54": 'm/d/yy',
  9194. "55": 'm/d/yy', "56": 'm/d/yy', "57": 'm/d/yy', "58": 'm/d/yy',
  9195. "59": '0',
  9196. "60": '0.00',
  9197. "61": '#,##0',
  9198. "62": '#,##0.00',
  9199. "63": '"$"#,##0_);\\("$"#,##0\\)',
  9200. "64": '"$"#,##0_);[Red]\\("$"#,##0\\)',
  9201. "65": '"$"#,##0.00_);\\("$"#,##0.00\\)',
  9202. "66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)',
  9203. "67": '0%',
  9204. "68": '0.00%',
  9205. "69": '# ?/?',
  9206. "70": '# ??/??',
  9207. "71": 'm/d/yy',
  9208. "72": 'm/d/yy',
  9209. "73": 'd-mmm-yy',
  9210. "74": 'd-mmm',
  9211. "75": 'mmm-yy',
  9212. "76": 'h:mm',
  9213. "77": 'h:mm:ss',
  9214. "78": 'm/d/yy h:mm',
  9215. "79": 'mm:ss',
  9216. "80": '[h]:mm:ss',
  9217. "81": 'mmss.0'
  9218. });
  9219. /* dateNF parse TODO: move to SSF */
  9220. var dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g;
  9221. function dateNF_regex(dateNF) {
  9222. var fmt = typeof dateNF == "number" ? SSF._table[dateNF] : dateNF;
  9223. fmt = fmt.replace(dateNFregex, "(\\d+)");
  9224. return new RegExp("^" + fmt + "$");
  9225. }
  9226. function dateNF_fix(str, dateNF, match) {
  9227. var Y = -1, m = -1, d = -1, H = -1, M = -1, S = -1;
  9228. (dateNF.match(dateNFregex)||[]).forEach(function(n, i) {
  9229. var v = parseInt(match[i+1], 10);
  9230. switch(n.toLowerCase().charAt(0)) {
  9231. case 'y': Y = v; break; case 'd': d = v; break;
  9232. case 'h': H = v; break; case 's': S = v; break;
  9233. case 'm': if(H >= 0) M = v; else m = v; break;
  9234. }
  9235. });
  9236. if(S >= 0 && M == -1 && m >= 0) { M = m; m = -1; }
  9237. var datestr = (("" + (Y>=0?Y: new Date().getFullYear())).slice(-4) + "-" + ("00" + (m>=1?m:1)).slice(-2) + "-" + ("00" + (d>=1?d:1)).slice(-2));
  9238. if(datestr.length == 7) datestr = "0" + datestr;
  9239. if(datestr.length == 8) datestr = "20" + datestr;
  9240. var timestr = (("00" + (H>=0?H:0)).slice(-2) + ":" + ("00" + (M>=0?M:0)).slice(-2) + ":" + ("00" + (S>=0?S:0)).slice(-2));
  9241. if(H == -1 && M == -1 && S == -1) return datestr;
  9242. if(Y == -1 && m == -1 && d == -1) return timestr;
  9243. return datestr + "T" + timestr;
  9244. }
  9245. var DO_NOT_EXPORT_CFB = true;
  9246. /* cfb.js (C) 2013-present SheetJS -- http://sheetjs.com */
  9247. /* vim: set ts=2: */
  9248. /*jshint eqnull:true */
  9249. /*exported CFB */
  9250. /*global Uint8Array:false, Uint16Array:false */
  9251. /* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
  9252. /* vim: set ts=2: */
  9253. /*exported CRC32 */
  9254. var CRC32;
  9255. (function (factory) {
  9256. /*jshint ignore:start */
  9257. /*eslint-disable */
  9258. factory(CRC32 = {});
  9259. /*eslint-enable */
  9260. /*jshint ignore:end */
  9261. }(function(CRC32) {
  9262. CRC32.version = '1.2.0';
  9263. /* see perf/crc32table.js */
  9264. /*global Int32Array */
  9265. function signed_crc_table() {
  9266. var c = 0, table = new Array(256);
  9267. for(var n =0; n != 256; ++n){
  9268. c = n;
  9269. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9270. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9271. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9272. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9273. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9274. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9275. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9276. c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));
  9277. table[n] = c;
  9278. }
  9279. return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;
  9280. }
  9281. var T = signed_crc_table();
  9282. function crc32_bstr(bstr, seed) {
  9283. var C = seed ^ -1, L = bstr.length - 1;
  9284. for(var i = 0; i < L;) {
  9285. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  9286. C = (C>>>8) ^ T[(C^bstr.charCodeAt(i++))&0xFF];
  9287. }
  9288. if(i === L) C = (C>>>8) ^ T[(C ^ bstr.charCodeAt(i))&0xFF];
  9289. return C ^ -1;
  9290. }
  9291. function crc32_buf(buf, seed) {
  9292. if(buf.length > 10000) return crc32_buf_8(buf, seed);
  9293. var C = seed ^ -1, L = buf.length - 3;
  9294. for(var i = 0; i < L;) {
  9295. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9296. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9297. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9298. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9299. }
  9300. while(i < L+3) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9301. return C ^ -1;
  9302. }
  9303. function crc32_buf_8(buf, seed) {
  9304. var C = seed ^ -1, L = buf.length - 7;
  9305. for(var i = 0; i < L;) {
  9306. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9307. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9308. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9309. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9310. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9311. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9312. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9313. C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9314. }
  9315. while(i < L+7) C = (C>>>8) ^ T[(C^buf[i++])&0xFF];
  9316. return C ^ -1;
  9317. }
  9318. function crc32_str(str, seed) {
  9319. var C = seed ^ -1;
  9320. for(var i = 0, L=str.length, c, d; i < L;) {
  9321. c = str.charCodeAt(i++);
  9322. if(c < 0x80) {
  9323. C = (C>>>8) ^ T[(C ^ c)&0xFF];
  9324. } else if(c < 0x800) {
  9325. C = (C>>>8) ^ T[(C ^ (192|((c>>6)&31)))&0xFF];
  9326. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  9327. } else if(c >= 0xD800 && c < 0xE000) {
  9328. c = (c&1023)+64; d = str.charCodeAt(i++)&1023;
  9329. C = (C>>>8) ^ T[(C ^ (240|((c>>8)&7)))&0xFF];
  9330. C = (C>>>8) ^ T[(C ^ (128|((c>>2)&63)))&0xFF];
  9331. C = (C>>>8) ^ T[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];
  9332. C = (C>>>8) ^ T[(C ^ (128|(d&63)))&0xFF];
  9333. } else {
  9334. C = (C>>>8) ^ T[(C ^ (224|((c>>12)&15)))&0xFF];
  9335. C = (C>>>8) ^ T[(C ^ (128|((c>>6)&63)))&0xFF];
  9336. C = (C>>>8) ^ T[(C ^ (128|(c&63)))&0xFF];
  9337. }
  9338. }
  9339. return C ^ -1;
  9340. }
  9341. CRC32.table = T;
  9342. CRC32.bstr = crc32_bstr;
  9343. CRC32.buf = crc32_buf;
  9344. CRC32.str = crc32_str;
  9345. }));
  9346. /* [MS-CFB] v20171201 */
  9347. var CFB = (function _CFB(){
  9348. var exports = {};
  9349. exports.version = '1.1.4';
  9350. /* [MS-CFB] 2.6.4 */
  9351. function namecmp(l, r) {
  9352. var L = l.split("/"), R = r.split("/");
  9353. for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
  9354. if((c = L[i].length - R[i].length)) return c;
  9355. if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
  9356. }
  9357. return L.length - R.length;
  9358. }
  9359. function dirname(p) {
  9360. if(p.charAt(p.length - 1) == "/") return (p.slice(0,-1).indexOf("/") === -1) ? p : dirname(p.slice(0, -1));
  9361. var c = p.lastIndexOf("/");
  9362. return (c === -1) ? p : p.slice(0, c+1);
  9363. }
  9364. function filename(p) {
  9365. if(p.charAt(p.length - 1) == "/") return filename(p.slice(0, -1));
  9366. var c = p.lastIndexOf("/");
  9367. return (c === -1) ? p : p.slice(c+1);
  9368. }
  9369. /* -------------------------------------------------------------------------- */
  9370. /* DOS Date format:
  9371. high|YYYYYYYm.mmmddddd.HHHHHMMM.MMMSSSSS|low
  9372. add 1980 to stored year
  9373. stored second should be doubled
  9374. */
  9375. /* write JS date to buf as a DOS date */
  9376. function write_dos_date(buf, date) {
  9377. if(typeof date === "string") date = new Date(date);
  9378. var hms = date.getHours();
  9379. hms = hms << 6 | date.getMinutes();
  9380. hms = hms << 5 | (date.getSeconds()>>>1);
  9381. buf.write_shift(2, hms);
  9382. var ymd = (date.getFullYear() - 1980);
  9383. ymd = ymd << 4 | (date.getMonth()+1);
  9384. ymd = ymd << 5 | date.getDate();
  9385. buf.write_shift(2, ymd);
  9386. }
  9387. /* read four bytes from buf and interpret as a DOS date */
  9388. function parse_dos_date(buf) {
  9389. var hms = buf.read_shift(2) & 0xFFFF;
  9390. var ymd = buf.read_shift(2) & 0xFFFF;
  9391. var val = new Date();
  9392. var d = ymd & 0x1F; ymd >>>= 5;
  9393. var m = ymd & 0x0F; ymd >>>= 4;
  9394. val.setMilliseconds(0);
  9395. val.setFullYear(ymd + 1980);
  9396. val.setMonth(m-1);
  9397. val.setDate(d);
  9398. var S = hms & 0x1F; hms >>>= 5;
  9399. var M = hms & 0x3F; hms >>>= 6;
  9400. val.setHours(hms);
  9401. val.setMinutes(M);
  9402. val.setSeconds(S<<1);
  9403. return val;
  9404. }
  9405. function parse_extra_field(blob) {
  9406. prep_blob(blob, 0);
  9407. var o = {};
  9408. var flags = 0;
  9409. while(blob.l <= blob.length - 4) {
  9410. var type = blob.read_shift(2);
  9411. var sz = blob.read_shift(2), tgt = blob.l + sz;
  9412. var p = {};
  9413. switch(type) {
  9414. /* UNIX-style Timestamps */
  9415. case 0x5455: {
  9416. flags = blob.read_shift(1);
  9417. if(flags & 1) p.mtime = blob.read_shift(4);
  9418. /* for some reason, CD flag corresponds to LFH */
  9419. if(sz > 5) {
  9420. if(flags & 2) p.atime = blob.read_shift(4);
  9421. if(flags & 4) p.ctime = blob.read_shift(4);
  9422. }
  9423. if(p.mtime) p.mt = new Date(p.mtime*1000);
  9424. }
  9425. break;
  9426. }
  9427. blob.l = tgt;
  9428. o[type] = p;
  9429. }
  9430. return o;
  9431. }
  9432. var fs;
  9433. function get_fs() { return fs || (fs = require('fs')); }
  9434. function parse(file, options) {
  9435. if(file[0] == 0x50 && file[1] == 0x4b) return parse_zip(file, options);
  9436. if(file.length < 512) throw new Error("CFB file size " + file.length + " < 512");
  9437. var mver = 3;
  9438. var ssz = 512;
  9439. var nmfs = 0; // number of mini FAT sectors
  9440. var difat_sec_cnt = 0;
  9441. var dir_start = 0;
  9442. var minifat_start = 0;
  9443. var difat_start = 0;
  9444. var fat_addrs = []; // locations of FAT sectors
  9445. /* [MS-CFB] 2.2 Compound File Header */
  9446. var blob = file.slice(0,512);
  9447. prep_blob(blob, 0);
  9448. /* major version */
  9449. var mv = check_get_mver(blob);
  9450. mver = mv[0];
  9451. switch(mver) {
  9452. case 3: ssz = 512; break; case 4: ssz = 4096; break;
  9453. case 0: if(mv[1] == 0) return parse_zip(file, options);
  9454. /* falls through */
  9455. default: throw new Error("Major Version: Expected 3 or 4 saw " + mver);
  9456. }
  9457. /* reprocess header */
  9458. if(ssz !== 512) { blob = file.slice(0,ssz); prep_blob(blob, 28 /* blob.l */); }
  9459. /* Save header for final object */
  9460. var header = file.slice(0,ssz);
  9461. check_shifts(blob, mver);
  9462. // Number of Directory Sectors
  9463. var dir_cnt = blob.read_shift(4, 'i');
  9464. if(mver === 3 && dir_cnt !== 0) throw new Error('# Directory Sectors: Expected 0 saw ' + dir_cnt);
  9465. // Number of FAT Sectors
  9466. blob.l += 4;
  9467. // First Directory Sector Location
  9468. dir_start = blob.read_shift(4, 'i');
  9469. // Transaction Signature
  9470. blob.l += 4;
  9471. // Mini Stream Cutoff Size
  9472. blob.chk('00100000', 'Mini Stream Cutoff Size: ');
  9473. // First Mini FAT Sector Location
  9474. minifat_start = blob.read_shift(4, 'i');
  9475. // Number of Mini FAT Sectors
  9476. nmfs = blob.read_shift(4, 'i');
  9477. // First DIFAT sector location
  9478. difat_start = blob.read_shift(4, 'i');
  9479. // Number of DIFAT Sectors
  9480. difat_sec_cnt = blob.read_shift(4, 'i');
  9481. // Grab FAT Sector Locations
  9482. for(var q = -1, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */
  9483. q = blob.read_shift(4, 'i');
  9484. if(q<0) break;
  9485. fat_addrs[j] = q;
  9486. }
  9487. /** Break the file up into sectors */
  9488. var sectors = sectorify(file, ssz);
  9489. sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs);
  9490. /** Chains */
  9491. var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz);
  9492. sector_list[dir_start].name = "!Directory";
  9493. if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT";
  9494. sector_list[fat_addrs[0]].name = "!FAT";
  9495. sector_list.fat_addrs = fat_addrs;
  9496. sector_list.ssz = ssz;
  9497. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  9498. var files = {}, Paths = [], FileIndex = [], FullPaths = [];
  9499. read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start);
  9500. build_full_paths(FileIndex, FullPaths, Paths);
  9501. Paths.shift();
  9502. var o = {
  9503. FileIndex: FileIndex,
  9504. FullPaths: FullPaths
  9505. };
  9506. // $FlowIgnore
  9507. if(options && options.raw) o.raw = {header: header, sectors: sectors};
  9508. return o;
  9509. } // parse
  9510. /* [MS-CFB] 2.2 Compound File Header -- read up to major version */
  9511. function check_get_mver(blob) {
  9512. if(blob[blob.l] == 0x50 && blob[blob.l + 1] == 0x4b) return [0, 0];
  9513. // header signature 8
  9514. blob.chk(HEADER_SIGNATURE, 'Header Signature: ');
  9515. // clsid 16
  9516. //blob.chk(HEADER_CLSID, 'CLSID: ');
  9517. blob.l += 16;
  9518. // minor version 2
  9519. var mver = blob.read_shift(2, 'u');
  9520. return [blob.read_shift(2,'u'), mver];
  9521. }
  9522. function check_shifts(blob, mver) {
  9523. var shift = 0x09;
  9524. // Byte Order
  9525. //blob.chk('feff', 'Byte Order: '); // note: some writers put 0xffff
  9526. blob.l += 2;
  9527. // Sector Shift
  9528. switch((shift = blob.read_shift(2))) {
  9529. case 0x09: if(mver != 3) throw new Error('Sector Shift: Expected 9 saw ' + shift); break;
  9530. case 0x0c: if(mver != 4) throw new Error('Sector Shift: Expected 12 saw ' + shift); break;
  9531. default: throw new Error('Sector Shift: Expected 9 or 12 saw ' + shift);
  9532. }
  9533. // Mini Sector Shift
  9534. blob.chk('0600', 'Mini Sector Shift: ');
  9535. // Reserved
  9536. blob.chk('000000000000', 'Reserved: ');
  9537. }
  9538. /** Break the file up into sectors */
  9539. function sectorify(file, ssz) {
  9540. var nsectors = Math.ceil(file.length/ssz)-1;
  9541. var sectors = [];
  9542. for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz);
  9543. sectors[nsectors-1] = file.slice(nsectors*ssz);
  9544. return sectors;
  9545. }
  9546. /* [MS-CFB] 2.6.4 Red-Black Tree */
  9547. function build_full_paths(FI, FP, Paths) {
  9548. var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length;
  9549. var dad = [], q = [];
  9550. for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; }
  9551. for(; j < q.length; ++j) {
  9552. i = q[j];
  9553. L = FI[i].L; R = FI[i].R; C = FI[i].C;
  9554. if(dad[i] === i) {
  9555. if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L];
  9556. if(R !== -1 && dad[R] !== R) dad[i] = dad[R];
  9557. }
  9558. if(C !== -1 /*NOSTREAM*/) dad[C] = i;
  9559. if(L !== -1 && i != dad[i]) { dad[L] = dad[i]; if(q.lastIndexOf(L) < j) q.push(L); }
  9560. if(R !== -1 && i != dad[i]) { dad[R] = dad[i]; if(q.lastIndexOf(R) < j) q.push(R); }
  9561. }
  9562. for(i=1; i < pl; ++i) if(dad[i] === i) {
  9563. if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R];
  9564. else if(L !== -1 && dad[L] !== L) dad[i] = dad[L];
  9565. }
  9566. for(i=1; i < pl; ++i) {
  9567. if(FI[i].type === 0 /* unknown */) continue;
  9568. j = i;
  9569. if(j != dad[j]) do {
  9570. j = dad[j];
  9571. FP[i] = FP[j] + "/" + FP[i];
  9572. } while (j !== 0 && -1 !== dad[j] && j != dad[j]);
  9573. dad[i] = -1;
  9574. }
  9575. FP[0] += "/";
  9576. for(i=1; i < pl; ++i) {
  9577. if(FI[i].type !== 2 /* stream */) FP[i] += "/";
  9578. }
  9579. }
  9580. function get_mfat_entry(entry, payload, mini) {
  9581. var start = entry.start, size = entry.size;
  9582. //return (payload.slice(start*MSSZ, start*MSSZ + size));
  9583. var o = [];
  9584. var idx = start;
  9585. while(mini && size > 0 && idx >= 0) {
  9586. o.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ));
  9587. size -= MSSZ;
  9588. idx = __readInt32LE(mini, idx * 4);
  9589. }
  9590. if(o.length === 0) return (new_buf(0));
  9591. return (bconcat(o).slice(0, entry.size));
  9592. }
  9593. /** Chase down the rest of the DIFAT chain to build a comprehensive list
  9594. DIFAT chains by storing the next sector number as the last 32 bits */
  9595. function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) {
  9596. var q = ENDOFCHAIN;
  9597. if(idx === ENDOFCHAIN) {
  9598. if(cnt !== 0) throw new Error("DIFAT chain shorter than expected");
  9599. } else if(idx !== -1 /*FREESECT*/) {
  9600. var sector = sectors[idx], m = (ssz>>>2)-1;
  9601. if(!sector) return;
  9602. for(var i = 0; i < m; ++i) {
  9603. if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break;
  9604. fat_addrs.push(q);
  9605. }
  9606. sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs);
  9607. }
  9608. }
  9609. /** Follow the linked list of sectors for a given starting point */
  9610. function get_sector_list(sectors, start, fat_addrs, ssz, chkd) {
  9611. var buf = [], buf_chain = [];
  9612. if(!chkd) chkd = [];
  9613. var modulus = ssz - 1, j = 0, jj = 0;
  9614. for(j=start; j>=0;) {
  9615. chkd[j] = true;
  9616. buf[buf.length] = j;
  9617. buf_chain.push(sectors[j]);
  9618. var addr = fat_addrs[Math.floor(j*4/ssz)];
  9619. jj = ((j*4) & modulus);
  9620. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  9621. if(!sectors[addr]) break;
  9622. j = __readInt32LE(sectors[addr], jj);
  9623. }
  9624. return {nodes: buf, data:__toBuffer([buf_chain])};
  9625. }
  9626. /** Chase down the sector linked lists */
  9627. function make_sector_list(sectors, dir_start, fat_addrs, ssz) {
  9628. var sl = sectors.length, sector_list = ([]);
  9629. var chkd = [], buf = [], buf_chain = [];
  9630. var modulus = ssz - 1, i=0, j=0, k=0, jj=0;
  9631. for(i=0; i < sl; ++i) {
  9632. buf = ([]);
  9633. k = (i + dir_start); if(k >= sl) k-=sl;
  9634. if(chkd[k]) continue;
  9635. buf_chain = [];
  9636. var seen = [];
  9637. for(j=k; j>=0;) {
  9638. seen[j] = true;
  9639. chkd[j] = true;
  9640. buf[buf.length] = j;
  9641. buf_chain.push(sectors[j]);
  9642. var addr = fat_addrs[Math.floor(j*4/ssz)];
  9643. jj = ((j*4) & modulus);
  9644. if(ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j + " 4 "+ssz);
  9645. if(!sectors[addr]) break;
  9646. j = __readInt32LE(sectors[addr], jj);
  9647. if(seen[j]) break;
  9648. }
  9649. sector_list[k] = ({nodes: buf, data:__toBuffer([buf_chain])});
  9650. }
  9651. return sector_list;
  9652. }
  9653. /* [MS-CFB] 2.6.1 Compound File Directory Entry */
  9654. function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) {
  9655. var minifat_store = 0, pl = (Paths.length?2:0);
  9656. var sector = sector_list[dir_start].data;
  9657. var i = 0, namelen = 0, name;
  9658. for(; i < sector.length; i+= 128) {
  9659. var blob = sector.slice(i, i+128);
  9660. prep_blob(blob, 64);
  9661. namelen = blob.read_shift(2);
  9662. name = __utf16le(blob,0,namelen-pl);
  9663. Paths.push(name);
  9664. var o = ({
  9665. name: name,
  9666. type: blob.read_shift(1),
  9667. color: blob.read_shift(1),
  9668. L: blob.read_shift(4, 'i'),
  9669. R: blob.read_shift(4, 'i'),
  9670. C: blob.read_shift(4, 'i'),
  9671. clsid: blob.read_shift(16),
  9672. state: blob.read_shift(4, 'i'),
  9673. start: 0,
  9674. size: 0
  9675. });
  9676. var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  9677. if(ctime !== 0) o.ct = read_date(blob, blob.l-8);
  9678. var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2);
  9679. if(mtime !== 0) o.mt = read_date(blob, blob.l-8);
  9680. o.start = blob.read_shift(4, 'i');
  9681. o.size = blob.read_shift(4, 'i');
  9682. if(o.size < 0 && o.start < 0) { o.size = o.type = 0; o.start = ENDOFCHAIN; o.name = ""; }
  9683. if(o.type === 5) { /* root */
  9684. minifat_store = o.start;
  9685. if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData";
  9686. /*minifat_size = o.size;*/
  9687. } else if(o.size >= 4096 /* MSCSZ */) {
  9688. o.storage = 'fat';
  9689. if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz);
  9690. sector_list[o.start].name = o.name;
  9691. o.content = (sector_list[o.start].data.slice(0,o.size));
  9692. } else {
  9693. o.storage = 'minifat';
  9694. if(o.size < 0) o.size = 0;
  9695. else if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN && sector_list[minifat_store]) {
  9696. o.content = get_mfat_entry(o, sector_list[minifat_store].data, (sector_list[mini]||{}).data);
  9697. }
  9698. }
  9699. if(o.content) prep_blob(o.content, 0);
  9700. files[name] = o;
  9701. FileIndex.push(o);
  9702. }
  9703. }
  9704. function read_date(blob, offset) {
  9705. return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000);
  9706. }
  9707. function read_file(filename, options) {
  9708. get_fs();
  9709. return parse(fs.readFileSync(filename), options);
  9710. }
  9711. function read(blob, options) {
  9712. switch(options && options.type || "base64") {
  9713. case "file": return read_file(blob, options);
  9714. case "base64": return parse(s2a(Base64.decode(blob)), options);
  9715. case "binary": return parse(s2a(blob), options);
  9716. }
  9717. return parse(blob, options);
  9718. }
  9719. function init_cfb(cfb, opts) {
  9720. var o = opts || {}, root = o.root || "Root Entry";
  9721. if(!cfb.FullPaths) cfb.FullPaths = [];
  9722. if(!cfb.FileIndex) cfb.FileIndex = [];
  9723. if(cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure");
  9724. if(cfb.FullPaths.length === 0) {
  9725. cfb.FullPaths[0] = root + "/";
  9726. cfb.FileIndex[0] = ({ name: root, type: 5 });
  9727. }
  9728. if(o.CLSID) cfb.FileIndex[0].clsid = o.CLSID;
  9729. seed_cfb(cfb);
  9730. }
  9731. function seed_cfb(cfb) {
  9732. var nm = "\u0001Sh33tJ5";
  9733. if(CFB.find(cfb, "/" + nm)) return;
  9734. var p = new_buf(4); p[0] = 55; p[1] = p[3] = 50; p[2] = 54;
  9735. cfb.FileIndex.push(({ name: nm, type: 2, content:p, size:4, L:69, R:69, C:69 }));
  9736. cfb.FullPaths.push(cfb.FullPaths[0] + nm);
  9737. rebuild_cfb(cfb);
  9738. }
  9739. function rebuild_cfb(cfb, f) {
  9740. init_cfb(cfb);
  9741. var gc = false, s = false;
  9742. for(var i = cfb.FullPaths.length - 1; i >= 0; --i) {
  9743. var _file = cfb.FileIndex[i];
  9744. switch(_file.type) {
  9745. case 0:
  9746. if(s) gc = true;
  9747. else { cfb.FileIndex.pop(); cfb.FullPaths.pop(); }
  9748. break;
  9749. case 1: case 2: case 5:
  9750. s = true;
  9751. if(isNaN(_file.R * _file.L * _file.C)) gc = true;
  9752. if(_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true;
  9753. break;
  9754. default: gc = true; break;
  9755. }
  9756. }
  9757. if(!gc && !f) return;
  9758. var now = new Date(1987, 1, 19), j = 0;
  9759. var data = [];
  9760. for(i = 0; i < cfb.FullPaths.length; ++i) {
  9761. if(cfb.FileIndex[i].type === 0) continue;
  9762. data.push([cfb.FullPaths[i], cfb.FileIndex[i]]);
  9763. }
  9764. for(i = 0; i < data.length; ++i) {
  9765. var dad = dirname(data[i][0]);
  9766. s = false;
  9767. for(j = 0; j < data.length; ++j) if(data[j][0] === dad) s = true;
  9768. if(!s) data.push([dad, ({
  9769. name: filename(dad).replace("/",""),
  9770. type: 1,
  9771. clsid: HEADER_CLSID,
  9772. ct: now, mt: now,
  9773. content: null
  9774. })]);
  9775. }
  9776. data.sort(function(x,y) { return namecmp(x[0], y[0]); });
  9777. cfb.FullPaths = []; cfb.FileIndex = [];
  9778. for(i = 0; i < data.length; ++i) { cfb.FullPaths[i] = data[i][0]; cfb.FileIndex[i] = data[i][1]; }
  9779. for(i = 0; i < data.length; ++i) {
  9780. var elt = cfb.FileIndex[i];
  9781. var nm = cfb.FullPaths[i];
  9782. elt.name = filename(nm).replace("/","");
  9783. elt.L = elt.R = elt.C = -(elt.color = 1);
  9784. elt.size = elt.content ? elt.content.length : 0;
  9785. elt.start = 0;
  9786. elt.clsid = (elt.clsid || HEADER_CLSID);
  9787. if(i === 0) {
  9788. elt.C = data.length > 1 ? 1 : -1;
  9789. elt.size = 0;
  9790. elt.type = 5;
  9791. } else if(nm.slice(-1) == "/") {
  9792. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==nm) break;
  9793. elt.C = j >= data.length ? -1 : j;
  9794. for(j=i+1;j < data.length; ++j) if(dirname(cfb.FullPaths[j])==dirname(nm)) break;
  9795. elt.R = j >= data.length ? -1 : j;
  9796. elt.type = 1;
  9797. } else {
  9798. if(dirname(cfb.FullPaths[i+1]||"") == dirname(nm)) elt.R = i + 1;
  9799. elt.type = 2;
  9800. }
  9801. }
  9802. }
  9803. function _write(cfb, options) {
  9804. var _opts = options || {};
  9805. rebuild_cfb(cfb);
  9806. if(_opts.fileType == 'zip') return write_zip(cfb, _opts);
  9807. var L = (function(cfb){
  9808. var mini_size = 0, fat_size = 0;
  9809. for(var i = 0; i < cfb.FileIndex.length; ++i) {
  9810. var file = cfb.FileIndex[i];
  9811. if(!file.content) continue;
  9812. var flen = file.content.length;
  9813. if(flen > 0){
  9814. if(flen < 0x1000) mini_size += (flen + 0x3F) >> 6;
  9815. else fat_size += (flen + 0x01FF) >> 9;
  9816. }
  9817. }
  9818. var dir_cnt = (cfb.FullPaths.length +3) >> 2;
  9819. var mini_cnt = (mini_size + 7) >> 3;
  9820. var mfat_cnt = (mini_size + 0x7F) >> 7;
  9821. var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt;
  9822. var fat_cnt = (fat_base + 0x7F) >> 7;
  9823. var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  9824. while(((fat_base + fat_cnt + difat_cnt + 0x7F) >> 7) > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt-109)/0x7F);
  9825. var L = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0];
  9826. cfb.FileIndex[0].size = mini_size << 6;
  9827. L[7] = (cfb.FileIndex[0].start=L[0]+L[1]+L[2]+L[3]+L[4]+L[5])+((L[6]+7) >> 3);
  9828. return L;
  9829. })(cfb);
  9830. var o = new_buf(L[7] << 9);
  9831. var i = 0, T = 0;
  9832. {
  9833. for(i = 0; i < 8; ++i) o.write_shift(1, HEADER_SIG[i]);
  9834. for(i = 0; i < 8; ++i) o.write_shift(2, 0);
  9835. o.write_shift(2, 0x003E);
  9836. o.write_shift(2, 0x0003);
  9837. o.write_shift(2, 0xFFFE);
  9838. o.write_shift(2, 0x0009);
  9839. o.write_shift(2, 0x0006);
  9840. for(i = 0; i < 3; ++i) o.write_shift(2, 0);
  9841. o.write_shift(4, 0);
  9842. o.write_shift(4, L[2]);
  9843. o.write_shift(4, L[0] + L[1] + L[2] + L[3] - 1);
  9844. o.write_shift(4, 0);
  9845. o.write_shift(4, 1<<12);
  9846. o.write_shift(4, L[3] ? L[0] + L[1] + L[2] - 1: ENDOFCHAIN);
  9847. o.write_shift(4, L[3]);
  9848. o.write_shift(-4, L[1] ? L[0] - 1: ENDOFCHAIN);
  9849. o.write_shift(4, L[1]);
  9850. for(i = 0; i < 109; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  9851. }
  9852. if(L[1]) {
  9853. for(T = 0; T < L[1]; ++T) {
  9854. for(; i < 236 + T * 127; ++i) o.write_shift(-4, i < L[2] ? L[1] + i : -1);
  9855. o.write_shift(-4, T === L[1] - 1 ? ENDOFCHAIN : T + 1);
  9856. }
  9857. }
  9858. var chainit = function(w) {
  9859. for(T += w; i<T-1; ++i) o.write_shift(-4, i+1);
  9860. if(w) { ++i; o.write_shift(-4, ENDOFCHAIN); }
  9861. };
  9862. T = i = 0;
  9863. for(T+=L[1]; i<T; ++i) o.write_shift(-4, consts.DIFSECT);
  9864. for(T+=L[2]; i<T; ++i) o.write_shift(-4, consts.FATSECT);
  9865. chainit(L[3]);
  9866. chainit(L[4]);
  9867. var j = 0, flen = 0;
  9868. var file = cfb.FileIndex[0];
  9869. for(; j < cfb.FileIndex.length; ++j) {
  9870. file = cfb.FileIndex[j];
  9871. if(!file.content) continue;
  9872. flen = file.content.length;
  9873. if(flen < 0x1000) continue;
  9874. file.start = T;
  9875. chainit((flen + 0x01FF) >> 9);
  9876. }
  9877. chainit((L[6] + 7) >> 3);
  9878. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  9879. T = i = 0;
  9880. for(j = 0; j < cfb.FileIndex.length; ++j) {
  9881. file = cfb.FileIndex[j];
  9882. if(!file.content) continue;
  9883. flen = file.content.length;
  9884. if(!flen || flen >= 0x1000) continue;
  9885. file.start = T;
  9886. chainit((flen + 0x3F) >> 6);
  9887. }
  9888. while(o.l & 0x1FF) o.write_shift(-4, consts.ENDOFCHAIN);
  9889. for(i = 0; i < L[4]<<2; ++i) {
  9890. var nm = cfb.FullPaths[i];
  9891. if(!nm || nm.length === 0) {
  9892. for(j = 0; j < 17; ++j) o.write_shift(4, 0);
  9893. for(j = 0; j < 3; ++j) o.write_shift(4, -1);
  9894. for(j = 0; j < 12; ++j) o.write_shift(4, 0);
  9895. continue;
  9896. }
  9897. file = cfb.FileIndex[i];
  9898. if(i === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN;
  9899. var _nm = (i === 0 && _opts.root) || file.name;
  9900. flen = 2*(_nm.length+1);
  9901. o.write_shift(64, _nm, "utf16le");
  9902. o.write_shift(2, flen);
  9903. o.write_shift(1, file.type);
  9904. o.write_shift(1, file.color);
  9905. o.write_shift(-4, file.L);
  9906. o.write_shift(-4, file.R);
  9907. o.write_shift(-4, file.C);
  9908. if(!file.clsid) for(j = 0; j < 4; ++j) o.write_shift(4, 0);
  9909. else o.write_shift(16, file.clsid, "hex");
  9910. o.write_shift(4, file.state || 0);
  9911. o.write_shift(4, 0); o.write_shift(4, 0);
  9912. o.write_shift(4, 0); o.write_shift(4, 0);
  9913. o.write_shift(4, file.start);
  9914. o.write_shift(4, file.size); o.write_shift(4, 0);
  9915. }
  9916. for(i = 1; i < cfb.FileIndex.length; ++i) {
  9917. file = cfb.FileIndex[i];
  9918. if(file.size >= 0x1000) {
  9919. o.l = (file.start+1) << 9;
  9920. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  9921. for(; j & 0x1FF; ++j) o.write_shift(1, 0);
  9922. }
  9923. }
  9924. for(i = 1; i < cfb.FileIndex.length; ++i) {
  9925. file = cfb.FileIndex[i];
  9926. if(file.size > 0 && file.size < 0x1000) {
  9927. for(j = 0; j < file.size; ++j) o.write_shift(1, file.content[j]);
  9928. for(; j & 0x3F; ++j) o.write_shift(1, 0);
  9929. }
  9930. }
  9931. while(o.l < o.length) o.write_shift(1, 0);
  9932. return o;
  9933. }
  9934. /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */
  9935. function find(cfb, path) {
  9936. var UCFullPaths = cfb.FullPaths.map(function(x) { return x.toUpperCase(); });
  9937. var UCPaths = UCFullPaths.map(function(x) { var y = x.split("/"); return y[y.length - (x.slice(-1) == "/" ? 2 : 1)]; });
  9938. var k = false;
  9939. if(path.charCodeAt(0) === 47 /* "/" */) { k = true; path = UCFullPaths[0].slice(0, -1) + path; }
  9940. else k = path.indexOf("/") !== -1;
  9941. var UCPath = path.toUpperCase();
  9942. var w = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath);
  9943. if(w !== -1) return cfb.FileIndex[w];
  9944. var m = !UCPath.match(chr1);
  9945. UCPath = UCPath.replace(chr0,'');
  9946. if(m) UCPath = UCPath.replace(chr1,'!');
  9947. for(w = 0; w < UCFullPaths.length; ++w) {
  9948. if((m ? UCFullPaths[w].replace(chr1,'!') : UCFullPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  9949. if((m ? UCPaths[w].replace(chr1,'!') : UCPaths[w]).replace(chr0,'') == UCPath) return cfb.FileIndex[w];
  9950. }
  9951. return null;
  9952. }
  9953. /** CFB Constants */
  9954. var MSSZ = 64; /* Mini Sector Size = 1<<6 */
  9955. //var MSCSZ = 4096; /* Mini Stream Cutoff Size */
  9956. /* 2.1 Compound File Sector Numbers and Types */
  9957. var ENDOFCHAIN = -2;
  9958. /* 2.2 Compound File Header */
  9959. var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1';
  9960. var HEADER_SIG = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
  9961. var HEADER_CLSID = '00000000000000000000000000000000';
  9962. var consts = {
  9963. /* 2.1 Compund File Sector Numbers and Types */
  9964. MAXREGSECT: -6,
  9965. DIFSECT: -4,
  9966. FATSECT: -3,
  9967. ENDOFCHAIN: ENDOFCHAIN,
  9968. FREESECT: -1,
  9969. /* 2.2 Compound File Header */
  9970. HEADER_SIGNATURE: HEADER_SIGNATURE,
  9971. HEADER_MINOR_VERSION: '3e00',
  9972. MAXREGSID: -6,
  9973. NOSTREAM: -1,
  9974. HEADER_CLSID: HEADER_CLSID,
  9975. /* 2.6.1 Compound File Directory Entry */
  9976. EntryTypes: ['unknown','storage','stream','lockbytes','property','root']
  9977. };
  9978. function write_file(cfb, filename, options) {
  9979. get_fs();
  9980. var o = _write(cfb, options);
  9981. fs.writeFileSync(filename, o);
  9982. }
  9983. function a2s(o) {
  9984. var out = new Array(o.length);
  9985. for(var i = 0; i < o.length; ++i) out[i] = String.fromCharCode(o[i]);
  9986. return out.join("");
  9987. }
  9988. function write(cfb, options) {
  9989. var o = _write(cfb, options);
  9990. switch(options && options.type) {
  9991. case "file": get_fs(); fs.writeFileSync(options.filename, (o)); return o;
  9992. case "binary": return a2s(o);
  9993. case "base64": return Base64.encode(a2s(o));
  9994. }
  9995. return o;
  9996. }
  9997. /* node < 8.1 zlib does not expose bytesRead, so default to pure JS */
  9998. var _zlib;
  9999. function use_zlib(zlib) { try {
  10000. var InflateRaw = zlib.InflateRaw;
  10001. var InflRaw = new InflateRaw();
  10002. InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag);
  10003. if(InflRaw.bytesRead) _zlib = zlib;
  10004. else throw new Error("zlib does not expose bytesRead");
  10005. } catch(e) {console.error("cannot use native zlib: " + (e.message || e)); } }
  10006. function _inflateRawSync(payload, usz) {
  10007. if(!_zlib) return _inflate(payload, usz);
  10008. var InflateRaw = _zlib.InflateRaw;
  10009. var InflRaw = new InflateRaw();
  10010. var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag);
  10011. payload.l += InflRaw.bytesRead;
  10012. return out;
  10013. }
  10014. function _deflateRawSync(payload) {
  10015. return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload);
  10016. }
  10017. var CLEN_ORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  10018. /* LEN_ID = [ 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285 ]; */
  10019. var LEN_LN = [ 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 ];
  10020. /* DST_ID = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 ]; */
  10021. var DST_LN = [ 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 ];
  10022. function bit_swap_8(n) { var t = (((((n<<1)|(n<<11)) & 0x22110) | (((n<<5)|(n<<15)) & 0x88440))); return ((t>>16) | (t>>8) |t)&0xFF; }
  10023. var use_typed_arrays = typeof Uint8Array !== 'undefined';
  10024. var bitswap8 = use_typed_arrays ? new Uint8Array(1<<8) : [];
  10025. for(var q = 0; q < (1<<8); ++q) bitswap8[q] = bit_swap_8(q);
  10026. function bit_swap_n(n, b) {
  10027. var rev = bitswap8[n & 0xFF];
  10028. if(b <= 8) return rev >>> (8-b);
  10029. rev = (rev << 8) | bitswap8[(n>>8)&0xFF];
  10030. if(b <= 16) return rev >>> (16-b);
  10031. rev = (rev << 8) | bitswap8[(n>>16)&0xFF];
  10032. return rev >>> (24-b);
  10033. }
  10034. /* helpers for unaligned bit reads */
  10035. function read_bits_2(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 6 ? 0 : buf[h+1]<<8))>>>w)& 0x03; }
  10036. function read_bits_3(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 5 ? 0 : buf[h+1]<<8))>>>w)& 0x07; }
  10037. function read_bits_4(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 4 ? 0 : buf[h+1]<<8))>>>w)& 0x0F; }
  10038. function read_bits_5(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 3 ? 0 : buf[h+1]<<8))>>>w)& 0x1F; }
  10039. function read_bits_7(buf, bl) { var w = (bl&7), h = (bl>>>3); return ((buf[h]|(w <= 1 ? 0 : buf[h+1]<<8))>>>w)& 0x7F; }
  10040. /* works up to n = 3 * 8 + 1 = 25 */
  10041. function read_bits_n(buf, bl, n) {
  10042. var w = (bl&7), h = (bl>>>3), f = ((1<<n)-1);
  10043. var v = buf[h] >>> w;
  10044. if(n < 8 - w) return v & f;
  10045. v |= buf[h+1]<<(8-w);
  10046. if(n < 16 - w) return v & f;
  10047. v |= buf[h+2]<<(16-w);
  10048. if(n < 24 - w) return v & f;
  10049. v |= buf[h+3]<<(24-w);
  10050. return v & f;
  10051. }
  10052. /* until ArrayBuffer#realloc is a thing, fake a realloc */
  10053. function realloc(b, sz) {
  10054. var L = b.length, M = 2*L > sz ? 2*L : sz + 5, i = 0;
  10055. if(L >= sz) return b;
  10056. if(has_buf) {
  10057. var o = new_unsafe_buf(M);
  10058. // $FlowIgnore
  10059. if(b.copy) b.copy(o);
  10060. else for(; i < b.length; ++i) o[i] = b[i];
  10061. return o;
  10062. } else if(use_typed_arrays) {
  10063. var a = new Uint8Array(M);
  10064. if(a.set) a.set(b);
  10065. else for(; i < b.length; ++i) a[i] = b[i];
  10066. return a;
  10067. }
  10068. b.length = M;
  10069. return b;
  10070. }
  10071. /* zero-filled arrays for older browsers */
  10072. function zero_fill_array(n) {
  10073. var o = new Array(n);
  10074. for(var i = 0; i < n; ++i) o[i] = 0;
  10075. return o;
  10076. }var _deflate = (function() {
  10077. var _deflateRaw = (function() {
  10078. return function deflateRaw(data, out) {
  10079. var boff = 0;
  10080. while(boff < data.length) {
  10081. var L = Math.min(0xFFFF, data.length - boff);
  10082. var h = boff + L == data.length;
  10083. /* TODO: this is only type 0 stored */
  10084. out.write_shift(1, +h);
  10085. out.write_shift(2, L);
  10086. out.write_shift(2, (~L) & 0xFFFF);
  10087. while(L-- > 0) out[out.l++] = data[boff++];
  10088. }
  10089. return out.l;
  10090. };
  10091. })();
  10092. return function(data) {
  10093. var buf = new_buf(50+Math.floor(data.length*1.1));
  10094. var off = _deflateRaw(data, buf);
  10095. return buf.slice(0, off);
  10096. };
  10097. })();
  10098. /* modified inflate function also moves original read head */
  10099. /* build tree (used for literals and lengths) */
  10100. function build_tree(clens, cmap, MAX) {
  10101. var maxlen = 1, w = 0, i = 0, j = 0, ccode = 0, L = clens.length;
  10102. var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  10103. for(i = 0; i < 32; ++i) bl_count[i] = 0;
  10104. for(i = L; i < MAX; ++i) clens[i] = 0;
  10105. L = clens.length;
  10106. var ctree = use_typed_arrays ? new Uint16Array(L) : zero_fill_array(L); // []
  10107. /* build code tree */
  10108. for(i = 0; i < L; ++i) {
  10109. bl_count[(w = clens[i])]++;
  10110. if(maxlen < w) maxlen = w;
  10111. ctree[i] = 0;
  10112. }
  10113. bl_count[0] = 0;
  10114. for(i = 1; i <= maxlen; ++i) bl_count[i+16] = (ccode = (ccode + bl_count[i-1])<<1);
  10115. for(i = 0; i < L; ++i) {
  10116. ccode = clens[i];
  10117. if(ccode != 0) ctree[i] = bl_count[ccode+16]++;
  10118. }
  10119. /* cmap[maxlen + 4 bits] = (off&15) + (lit<<4) reverse mapping */
  10120. var cleni = 0;
  10121. for(i = 0; i < L; ++i) {
  10122. cleni = clens[i];
  10123. if(cleni != 0) {
  10124. ccode = bit_swap_n(ctree[i], maxlen)>>(maxlen-cleni);
  10125. for(j = (1<<(maxlen + 4 - cleni)) - 1; j>=0; --j)
  10126. cmap[ccode|(j<<cleni)] = (cleni&15) | (i<<4);
  10127. }
  10128. }
  10129. return maxlen;
  10130. }
  10131. var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512);
  10132. var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32);
  10133. if(!use_typed_arrays) {
  10134. for(var i = 0; i < 512; ++i) fix_lmap[i] = 0;
  10135. for(i = 0; i < 32; ++i) fix_dmap[i] = 0;
  10136. }
  10137. (function() {
  10138. var dlens = [];
  10139. var i = 0;
  10140. for(;i<32; i++) dlens.push(5);
  10141. build_tree(dlens, fix_dmap, 32);
  10142. var clens = [];
  10143. i = 0;
  10144. for(; i<=143; i++) clens.push(8);
  10145. for(; i<=255; i++) clens.push(9);
  10146. for(; i<=279; i++) clens.push(7);
  10147. for(; i<=287; i++) clens.push(8);
  10148. build_tree(clens, fix_lmap, 288);
  10149. })();
  10150. var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  10151. var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768);
  10152. var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128);
  10153. var dyn_len_1 = 1, dyn_len_2 = 1;
  10154. /* 5.5.3 Expanding Huffman Codes */
  10155. function dyn(data, boff) {
  10156. /* nomenclature from RFC1951 refers to bit values; these are offset by the implicit constant */
  10157. var _HLIT = read_bits_5(data, boff) + 257; boff += 5;
  10158. var _HDIST = read_bits_5(data, boff) + 1; boff += 5;
  10159. var _HCLEN = read_bits_4(data, boff) + 4; boff += 4;
  10160. var w = 0;
  10161. /* grab and store code lengths */
  10162. var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19);
  10163. var ctree = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
  10164. var maxlen = 1;
  10165. var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  10166. var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8);
  10167. var L = clens.length; /* 19 */
  10168. for(var i = 0; i < _HCLEN; ++i) {
  10169. clens[CLEN_ORDER[i]] = w = read_bits_3(data, boff);
  10170. if(maxlen < w) maxlen = w;
  10171. bl_count[w]++;
  10172. boff += 3;
  10173. }
  10174. /* build code tree */
  10175. var ccode = 0;
  10176. bl_count[0] = 0;
  10177. for(i = 1; i <= maxlen; ++i) next_code[i] = ccode = (ccode + bl_count[i-1])<<1;
  10178. for(i = 0; i < L; ++i) if((ccode = clens[i]) != 0) ctree[i] = next_code[ccode]++;
  10179. /* cmap[7 bits from stream] = (off&7) + (lit<<3) */
  10180. var cleni = 0;
  10181. for(i = 0; i < L; ++i) {
  10182. cleni = clens[i];
  10183. if(cleni != 0) {
  10184. ccode = bitswap8[ctree[i]]>>(8-cleni);
  10185. for(var j = (1<<(7-cleni))-1; j>=0; --j) dyn_cmap[ccode|(j<<cleni)] = (cleni&7) | (i<<3);
  10186. }
  10187. }
  10188. /* read literal and dist codes at once */
  10189. var hcodes = [];
  10190. maxlen = 1;
  10191. for(; hcodes.length < _HLIT + _HDIST;) {
  10192. ccode = dyn_cmap[read_bits_7(data, boff)];
  10193. boff += ccode & 7;
  10194. switch((ccode >>>= 3)) {
  10195. case 16:
  10196. w = 3 + read_bits_2(data, boff); boff += 2;
  10197. ccode = hcodes[hcodes.length - 1];
  10198. while(w-- > 0) hcodes.push(ccode);
  10199. break;
  10200. case 17:
  10201. w = 3 + read_bits_3(data, boff); boff += 3;
  10202. while(w-- > 0) hcodes.push(0);
  10203. break;
  10204. case 18:
  10205. w = 11 + read_bits_7(data, boff); boff += 7;
  10206. while(w -- > 0) hcodes.push(0);
  10207. break;
  10208. default:
  10209. hcodes.push(ccode);
  10210. if(maxlen < ccode) maxlen = ccode;
  10211. break;
  10212. }
  10213. }
  10214. /* build literal / length trees */
  10215. var h1 = hcodes.slice(0, _HLIT), h2 = hcodes.slice(_HLIT);
  10216. for(i = _HLIT; i < 286; ++i) h1[i] = 0;
  10217. for(i = _HDIST; i < 30; ++i) h2[i] = 0;
  10218. dyn_len_1 = build_tree(h1, dyn_lmap, 286);
  10219. dyn_len_2 = build_tree(h2, dyn_dmap, 30);
  10220. return boff;
  10221. }
  10222. /* return [ data, bytesRead ] */
  10223. function inflate(data, usz) {
  10224. /* shortcircuit for empty buffer [0x03, 0x00] */
  10225. if(data[0] == 3 && !(data[1] & 0x3)) { return [new_raw_buf(usz), 2]; }
  10226. /* bit offset */
  10227. var boff = 0;
  10228. /* header includes final bit and type bits */
  10229. var header = 0;
  10230. var outbuf = new_unsafe_buf(usz ? usz : (1<<18));
  10231. var woff = 0;
  10232. var OL = outbuf.length>>>0;
  10233. var max_len_1 = 0, max_len_2 = 0;
  10234. while((header&1) == 0) {
  10235. header = read_bits_3(data, boff); boff += 3;
  10236. if((header >>> 1) == 0) {
  10237. /* Stored block */
  10238. if(boff & 7) boff += 8 - (boff&7);
  10239. /* 2 bytes sz, 2 bytes bit inverse */
  10240. var sz = data[boff>>>3] | data[(boff>>>3)+1]<<8;
  10241. boff += 32;
  10242. /* push sz bytes */
  10243. if(!usz && OL < woff + sz) { outbuf = realloc(outbuf, woff + sz); OL = outbuf.length; }
  10244. if(typeof data.copy === 'function') {
  10245. // $FlowIgnore
  10246. data.copy(outbuf, woff, boff>>>3, (boff>>>3)+sz);
  10247. woff += sz; boff += 8*sz;
  10248. } else while(sz-- > 0) { outbuf[woff++] = data[boff>>>3]; boff += 8; }
  10249. continue;
  10250. } else if((header >>> 1) == 1) {
  10251. /* Fixed Huffman */
  10252. max_len_1 = 9; max_len_2 = 5;
  10253. } else {
  10254. /* Dynamic Huffman */
  10255. boff = dyn(data, boff);
  10256. max_len_1 = dyn_len_1; max_len_2 = dyn_len_2;
  10257. }
  10258. if(!usz && (OL < woff + 32767)) { outbuf = realloc(outbuf, woff + 32767); OL = outbuf.length; }
  10259. for(;;) { // while(true) is apparently out of vogue in modern JS circles
  10260. /* ingest code and move read head */
  10261. var bits = read_bits_n(data, boff, max_len_1);
  10262. var code = (header>>>1) == 1 ? fix_lmap[bits] : dyn_lmap[bits];
  10263. boff += code & 15; code >>>= 4;
  10264. /* 0-255 are literals, 256 is end of block token, 257+ are copy tokens */
  10265. if(((code>>>8)&0xFF) === 0) outbuf[woff++] = code;
  10266. else if(code == 256) break;
  10267. else {
  10268. code -= 257;
  10269. var len_eb = (code < 8) ? 0 : ((code-4)>>2); if(len_eb > 5) len_eb = 0;
  10270. var tgt = woff + LEN_LN[code];
  10271. /* length extra bits */
  10272. if(len_eb > 0) {
  10273. tgt += read_bits_n(data, boff, len_eb);
  10274. boff += len_eb;
  10275. }
  10276. /* dist code */
  10277. bits = read_bits_n(data, boff, max_len_2);
  10278. code = (header>>>1) == 1 ? fix_dmap[bits] : dyn_dmap[bits];
  10279. boff += code & 15; code >>>= 4;
  10280. var dst_eb = (code < 4 ? 0 : (code-2)>>1);
  10281. var dst = DST_LN[code];
  10282. /* dist extra bits */
  10283. if(dst_eb > 0) {
  10284. dst += read_bits_n(data, boff, dst_eb);
  10285. boff += dst_eb;
  10286. }
  10287. /* in the common case, manual byte copy is faster than TA set / Buffer copy */
  10288. if(!usz && OL < tgt) { outbuf = realloc(outbuf, tgt); OL = outbuf.length; }
  10289. while(woff < tgt) { outbuf[woff] = outbuf[woff - dst]; ++woff; }
  10290. }
  10291. }
  10292. }
  10293. return [usz ? outbuf : outbuf.slice(0, woff), (boff+7)>>>3];
  10294. }
  10295. function _inflate(payload, usz) {
  10296. var data = payload.slice(payload.l||0);
  10297. var out = inflate(data, usz);
  10298. payload.l += out[1];
  10299. return out[0];
  10300. }
  10301. function warn_or_throw(wrn, msg) {
  10302. if(wrn) { if(typeof console !== 'undefined') console.error(msg); }
  10303. else throw new Error(msg);
  10304. }
  10305. function parse_zip(file, options) {
  10306. var blob = file;
  10307. prep_blob(blob, 0);
  10308. var FileIndex = [], FullPaths = [];
  10309. var o = {
  10310. FileIndex: FileIndex,
  10311. FullPaths: FullPaths
  10312. };
  10313. init_cfb(o, { root: options.root });
  10314. /* find end of central directory, start just after signature */
  10315. var i = blob.length - 4;
  10316. while((blob[i] != 0x50 || blob[i+1] != 0x4b || blob[i+2] != 0x05 || blob[i+3] != 0x06) && i >= 0) --i;
  10317. blob.l = i + 4;
  10318. /* parse end of central directory */
  10319. blob.l += 4;
  10320. var fcnt = blob.read_shift(2);
  10321. blob.l += 6;
  10322. var start_cd = blob.read_shift(4);
  10323. /* parse central directory */
  10324. blob.l = start_cd;
  10325. for(i = 0; i < fcnt; ++i) {
  10326. /* trust local file header instead of CD entry */
  10327. blob.l += 20;
  10328. var csz = blob.read_shift(4);
  10329. var usz = blob.read_shift(4);
  10330. var namelen = blob.read_shift(2);
  10331. var efsz = blob.read_shift(2);
  10332. var fcsz = blob.read_shift(2);
  10333. blob.l += 8;
  10334. var offset = blob.read_shift(4);
  10335. var EF = parse_extra_field(blob.slice(blob.l+namelen, blob.l+namelen+efsz));
  10336. blob.l += namelen + efsz + fcsz;
  10337. var L = blob.l;
  10338. blob.l = offset + 4;
  10339. parse_local_file(blob, csz, usz, o, EF);
  10340. blob.l = L;
  10341. }
  10342. return o;
  10343. }
  10344. /* head starts just after local file header signature */
  10345. function parse_local_file(blob, csz, usz, o, EF) {
  10346. /* [local file header] */
  10347. blob.l += 2;
  10348. var flags = blob.read_shift(2);
  10349. var meth = blob.read_shift(2);
  10350. var date = parse_dos_date(blob);
  10351. if(flags & 0x2041) throw new Error("Unsupported ZIP encryption");
  10352. var crc32 = blob.read_shift(4);
  10353. var _csz = blob.read_shift(4);
  10354. var _usz = blob.read_shift(4);
  10355. var namelen = blob.read_shift(2);
  10356. var efsz = blob.read_shift(2);
  10357. // TODO: flags & (1<<11) // UTF8
  10358. var name = ""; for(var i = 0; i < namelen; ++i) name += String.fromCharCode(blob[blob.l++]);
  10359. if(efsz) {
  10360. var ef = parse_extra_field(blob.slice(blob.l, blob.l + efsz));
  10361. if((ef[0x5455]||{}).mt) date = ef[0x5455].mt;
  10362. if(((EF||{})[0x5455]||{}).mt) date = EF[0x5455].mt;
  10363. }
  10364. blob.l += efsz;
  10365. /* [encryption header] */
  10366. /* [file data] */
  10367. var data = blob.slice(blob.l, blob.l + _csz);
  10368. switch(meth) {
  10369. case 8: data = _inflateRawSync(blob, _usz); break;
  10370. case 0: break;
  10371. default: throw new Error("Unsupported ZIP Compression method " + meth);
  10372. }
  10373. /* [data descriptor] */
  10374. var wrn = false;
  10375. if(flags & 8) {
  10376. crc32 = blob.read_shift(4);
  10377. if(crc32 == 0x08074b50) { crc32 = blob.read_shift(4); wrn = true; }
  10378. _csz = blob.read_shift(4);
  10379. _usz = blob.read_shift(4);
  10380. }
  10381. if(_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz);
  10382. if(_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz);
  10383. var _crc32 = CRC32.buf(data, 0);
  10384. if((crc32>>0) != (_crc32>>0)) warn_or_throw(wrn, "Bad CRC32 checksum: " + crc32 + " != " + _crc32);
  10385. cfb_add(o, name, data, {unsafe: true, mt: date});
  10386. }
  10387. function write_zip(cfb, options) {
  10388. var _opts = options || {};
  10389. var out = [], cdirs = [];
  10390. var o = new_buf(1);
  10391. var method = (_opts.compression ? 8 : 0), flags = 0;
  10392. var desc = false;
  10393. if(desc) flags |= 8;
  10394. var i = 0, j = 0;
  10395. var start_cd = 0, fcnt = 0;
  10396. var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0];
  10397. var crcs = [];
  10398. var sz_cd = 0;
  10399. for(i = 1; i < cfb.FullPaths.length; ++i) {
  10400. fp = cfb.FullPaths[i].slice(root.length); fi = cfb.FileIndex[i];
  10401. if(!fi.size || !fi.content || fp == "\u0001Sh33tJ5") continue;
  10402. var start = start_cd;
  10403. /* TODO: CP437 filename */
  10404. var namebuf = new_buf(fp.length);
  10405. for(j = 0; j < fp.length; ++j) namebuf.write_shift(1, fp.charCodeAt(j) & 0x7F);
  10406. namebuf = namebuf.slice(0, namebuf.l);
  10407. crcs[fcnt] = CRC32.buf(fi.content, 0);
  10408. var outbuf = fi.content;
  10409. if(method == 8) outbuf = _deflateRawSync(outbuf);
  10410. /* local file header */
  10411. o = new_buf(30);
  10412. o.write_shift(4, 0x04034b50);
  10413. o.write_shift(2, 20);
  10414. o.write_shift(2, flags);
  10415. o.write_shift(2, method);
  10416. /* TODO: last mod file time/date */
  10417. if(fi.mt) write_dos_date(o, fi.mt);
  10418. else o.write_shift(4, 0);
  10419. o.write_shift(-4, (flags & 8) ? 0 : crcs[fcnt]);
  10420. o.write_shift(4, (flags & 8) ? 0 : outbuf.length);
  10421. o.write_shift(4, (flags & 8) ? 0 : fi.content.length);
  10422. o.write_shift(2, namebuf.length);
  10423. o.write_shift(2, 0);
  10424. start_cd += o.length;
  10425. out.push(o);
  10426. start_cd += namebuf.length;
  10427. out.push(namebuf);
  10428. /* TODO: encryption header ? */
  10429. start_cd += outbuf.length;
  10430. out.push(outbuf);
  10431. /* data descriptor */
  10432. if(flags & 8) {
  10433. o = new_buf(12);
  10434. o.write_shift(-4, crcs[fcnt]);
  10435. o.write_shift(4, outbuf.length);
  10436. o.write_shift(4, fi.content.length);
  10437. start_cd += o.l;
  10438. out.push(o);
  10439. }
  10440. /* central directory */
  10441. o = new_buf(46);
  10442. o.write_shift(4, 0x02014b50);
  10443. o.write_shift(2, 0);
  10444. o.write_shift(2, 20);
  10445. o.write_shift(2, flags);
  10446. o.write_shift(2, method);
  10447. o.write_shift(4, 0); /* TODO: last mod file time/date */
  10448. o.write_shift(-4, crcs[fcnt]);
  10449. o.write_shift(4, outbuf.length);
  10450. o.write_shift(4, fi.content.length);
  10451. o.write_shift(2, namebuf.length);
  10452. o.write_shift(2, 0);
  10453. o.write_shift(2, 0);
  10454. o.write_shift(2, 0);
  10455. o.write_shift(2, 0);
  10456. o.write_shift(4, 0);
  10457. o.write_shift(4, start);
  10458. sz_cd += o.l;
  10459. cdirs.push(o);
  10460. sz_cd += namebuf.length;
  10461. cdirs.push(namebuf);
  10462. ++fcnt;
  10463. }
  10464. /* end of central directory */
  10465. o = new_buf(22);
  10466. o.write_shift(4, 0x06054b50);
  10467. o.write_shift(2, 0);
  10468. o.write_shift(2, 0);
  10469. o.write_shift(2, fcnt);
  10470. o.write_shift(2, fcnt);
  10471. o.write_shift(4, sz_cd);
  10472. o.write_shift(4, start_cd);
  10473. o.write_shift(2, 0);
  10474. return bconcat(([bconcat((out)), bconcat(cdirs), o]));
  10475. }
  10476. function cfb_new(opts) {
  10477. var o = ({});
  10478. init_cfb(o, opts);
  10479. return o;
  10480. }
  10481. function cfb_add(cfb, name, content, opts) {
  10482. var unsafe = opts && opts.unsafe;
  10483. if(!unsafe) init_cfb(cfb);
  10484. var file = !unsafe && CFB.find(cfb, name);
  10485. if(!file) {
  10486. var fpath = cfb.FullPaths[0];
  10487. if(name.slice(0, fpath.length) == fpath) fpath = name;
  10488. else {
  10489. if(fpath.slice(-1) != "/") fpath += "/";
  10490. fpath = (fpath + name).replace("//","/");
  10491. }
  10492. file = ({name: filename(name), type: 2});
  10493. cfb.FileIndex.push(file);
  10494. cfb.FullPaths.push(fpath);
  10495. if(!unsafe) CFB.utils.cfb_gc(cfb);
  10496. }
  10497. file.content = (content);
  10498. file.size = content ? content.length : 0;
  10499. if(opts) {
  10500. if(opts.CLSID) file.clsid = opts.CLSID;
  10501. if(opts.mt) file.mt = opts.mt;
  10502. if(opts.ct) file.ct = opts.ct;
  10503. }
  10504. return file;
  10505. }
  10506. function cfb_del(cfb, name) {
  10507. init_cfb(cfb);
  10508. var file = CFB.find(cfb, name);
  10509. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  10510. cfb.FileIndex.splice(j, 1);
  10511. cfb.FullPaths.splice(j, 1);
  10512. return true;
  10513. }
  10514. return false;
  10515. }
  10516. function cfb_mov(cfb, old_name, new_name) {
  10517. init_cfb(cfb);
  10518. var file = CFB.find(cfb, old_name);
  10519. if(file) for(var j = 0; j < cfb.FileIndex.length; ++j) if(cfb.FileIndex[j] == file) {
  10520. cfb.FileIndex[j].name = filename(new_name);
  10521. cfb.FullPaths[j] = new_name;
  10522. return true;
  10523. }
  10524. return false;
  10525. }
  10526. function cfb_gc(cfb) { rebuild_cfb(cfb, true); }
  10527. exports.find = find;
  10528. exports.read = read;
  10529. exports.parse = parse;
  10530. exports.write = write;
  10531. exports.writeFile = write_file;
  10532. exports.utils = {
  10533. cfb_new: cfb_new,
  10534. cfb_add: cfb_add,
  10535. cfb_del: cfb_del,
  10536. cfb_mov: cfb_mov,
  10537. cfb_gc: cfb_gc,
  10538. ReadShift: ReadShift,
  10539. CheckField: CheckField,
  10540. prep_blob: prep_blob,
  10541. bconcat: bconcat,
  10542. use_zlib: use_zlib,
  10543. _deflateRaw: _deflate,
  10544. _inflateRaw: _inflate,
  10545. consts: consts
  10546. };
  10547. return exports;
  10548. })();
  10549. if(typeof require !== 'undefined' && typeof module !== 'undefined' && typeof DO_NOT_EXPORT_CFB === 'undefined') { module.exports = CFB; }
  10550. var _fs;
  10551. if(typeof require !== 'undefined') try { _fs = require('fs'); } catch(e) {}
  10552. /* normalize data for blob ctor */
  10553. function blobify(data) {
  10554. if(typeof data === "string") return s2ab(data);
  10555. if(Array.isArray(data)) return a2u(data);
  10556. return data;
  10557. }
  10558. /* write or download file */
  10559. function write_dl(fname, payload, enc) {
  10560. /*global IE_SaveFile, Blob, navigator, saveAs, document, File, chrome */
  10561. if(typeof _fs !== 'undefined' && _fs.writeFileSync) return enc ? _fs.writeFileSync(fname, payload, enc) : _fs.writeFileSync(fname, payload);
  10562. var data = (enc == "utf8") ? utf8write(payload) : payload;
  10563. if(typeof IE_SaveFile !== 'undefined') return IE_SaveFile(data, fname);
  10564. if(typeof Blob !== 'undefined') {
  10565. var blob = new Blob([blobify(data)], {type:"application/octet-stream"});
  10566. if(typeof navigator !== 'undefined' && navigator.msSaveBlob) return navigator.msSaveBlob(blob, fname);
  10567. if(typeof saveAs !== 'undefined') return saveAs(blob, fname);
  10568. if(typeof URL !== 'undefined' && typeof document !== 'undefined' && document.createElement && URL.createObjectURL) {
  10569. var url = URL.createObjectURL(blob);
  10570. if(typeof chrome === 'object' && typeof (chrome.downloads||{}).download == "function") {
  10571. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  10572. return chrome.downloads.download({ url: url, filename: fname, saveAs: true});
  10573. }
  10574. var a = document.createElement("a");
  10575. if(a.download != null) {
  10576. a.download = fname; a.href = url; document.body.appendChild(a); a.click();
  10577. document.body.removeChild(a);
  10578. if(URL.revokeObjectURL && typeof setTimeout !== 'undefined') setTimeout(function() { URL.revokeObjectURL(url); }, 60000);
  10579. return url;
  10580. }
  10581. }
  10582. }
  10583. // $FlowIgnore
  10584. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  10585. // $FlowIgnore
  10586. var out = File(fname); out.open("w"); out.encoding = "binary";
  10587. if(Array.isArray(payload)) payload = a2s(payload);
  10588. out.write(payload); out.close(); return payload;
  10589. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  10590. throw new Error("cannot save file " + fname);
  10591. }
  10592. /* read binary data from file */
  10593. function read_binary(path) {
  10594. if(typeof _fs !== 'undefined') return _fs.readFileSync(path);
  10595. // $FlowIgnore
  10596. if(typeof $ !== 'undefined' && typeof File !== 'undefined' && typeof Folder !== 'undefined') try { // extendscript
  10597. // $FlowIgnore
  10598. var infile = File(path); infile.open("r"); infile.encoding = "binary";
  10599. var data = infile.read(); infile.close();
  10600. return data;
  10601. } catch(e) { if(!e.message || !e.message.match(/onstruct/)) throw e; }
  10602. throw new Error("Cannot access file " + path);
  10603. }
  10604. function keys(o) {
  10605. var ks = Object.keys(o), o2 = [];
  10606. for(var i = 0; i < ks.length; ++i) if(Object.prototype.hasOwnProperty.call(o, ks[i])) o2.push(ks[i]);
  10607. return o2;
  10608. }
  10609. function evert_key(obj, key) {
  10610. var o = ([]), K = keys(obj);
  10611. for(var i = 0; i !== K.length; ++i) if(o[obj[K[i]][key]] == null) o[obj[K[i]][key]] = K[i];
  10612. return o;
  10613. }
  10614. function evert(obj) {
  10615. var o = ([]), K = keys(obj);
  10616. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i];
  10617. return o;
  10618. }
  10619. function evert_num(obj) {
  10620. var o = ([]), K = keys(obj);
  10621. for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10);
  10622. return o;
  10623. }
  10624. function evert_arr(obj) {
  10625. var o = ([]), K = keys(obj);
  10626. for(var i = 0; i !== K.length; ++i) {
  10627. if(o[obj[K[i]]] == null) o[obj[K[i]]] = [];
  10628. o[obj[K[i]]].push(K[i]);
  10629. }
  10630. return o;
  10631. }
  10632. var basedate = new Date(1899, 11, 30, 0, 0, 0); // 2209161600000
  10633. function datenum(v, date1904) {
  10634. var epoch = v.getTime();
  10635. if(date1904) epoch -= 1462*24*60*60*1000;
  10636. var dnthresh = basedate.getTime() + (v.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  10637. return (epoch - dnthresh) / (24 * 60 * 60 * 1000);
  10638. }
  10639. var refdate = new Date();
  10640. var dnthresh = basedate.getTime() + (refdate.getTimezoneOffset() - basedate.getTimezoneOffset()) * 60000;
  10641. var refoffset = refdate.getTimezoneOffset();
  10642. function numdate(v) {
  10643. var out = new Date();
  10644. out.setTime(v * 24 * 60 * 60 * 1000 + dnthresh);
  10645. if (out.getTimezoneOffset() !== refoffset) {
  10646. out.setTime(out.getTime() + (out.getTimezoneOffset() - refoffset) * 60000);
  10647. }
  10648. return out;
  10649. }
  10650. /* ISO 8601 Duration */
  10651. function parse_isodur(s) {
  10652. var sec = 0, mt = 0, time = false;
  10653. var m = s.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/);
  10654. if(!m) throw new Error("|" + s + "| is not an ISO8601 Duration");
  10655. for(var i = 1; i != m.length; ++i) {
  10656. if(!m[i]) continue;
  10657. mt = 1;
  10658. if(i > 3) time = true;
  10659. switch(m[i].slice(m[i].length-1)) {
  10660. case 'Y':
  10661. throw new Error("Unsupported ISO Duration Field: " + m[i].slice(m[i].length-1));
  10662. case 'D': mt *= 24;
  10663. /* falls through */
  10664. case 'H': mt *= 60;
  10665. /* falls through */
  10666. case 'M':
  10667. if(!time) throw new Error("Unsupported ISO Duration Field: M");
  10668. else mt *= 60;
  10669. /* falls through */
  10670. case 'S': break;
  10671. }
  10672. sec += mt * parseInt(m[i], 10);
  10673. }
  10674. return sec;
  10675. }
  10676. var good_pd_date = new Date('2017-02-19T19:06:09.000Z');
  10677. if(isNaN(good_pd_date.getFullYear())) good_pd_date = new Date('2/19/17');
  10678. var good_pd = good_pd_date.getFullYear() == 2017;
  10679. /* parses a date as a local date */
  10680. function parseDate(str, fixdate) {
  10681. var d = new Date(str);
  10682. if(good_pd) {
  10683. if(fixdate > 0) d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
  10684. else if(fixdate < 0) d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);
  10685. return d;
  10686. }
  10687. if(str instanceof Date) return str;
  10688. if(good_pd_date.getFullYear() == 1917 && !isNaN(d.getFullYear())) {
  10689. var s = d.getFullYear();
  10690. if(str.indexOf("" + s) > -1) return d;
  10691. d.setFullYear(d.getFullYear() + 100); return d;
  10692. }
  10693. var n = str.match(/\d+/g)||["2017","2","19","0","0","0"];
  10694. var out = new Date(+n[0], +n[1] - 1, +n[2], (+n[3]||0), (+n[4]||0), (+n[5]||0));
  10695. if(str.indexOf("Z") > -1) out = new Date(out.getTime() - out.getTimezoneOffset() * 60 * 1000);
  10696. return out;
  10697. }
  10698. function cc2str(arr) {
  10699. var o = "";
  10700. for(var i = 0; i != arr.length; ++i) o += String.fromCharCode(arr[i]);
  10701. return o;
  10702. }
  10703. function dup(o) {
  10704. if(typeof JSON != 'undefined' && !Array.isArray(o)) return JSON.parse(JSON.stringify(o));
  10705. if(typeof o != 'object' || o == null) return o;
  10706. if(o instanceof Date) return new Date(o.getTime());
  10707. var out = {};
  10708. for(var k in o) if(Object.prototype.hasOwnProperty.call(o, k)) out[k] = dup(o[k]);
  10709. return out;
  10710. }
  10711. function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; }
  10712. /* TODO: stress test */
  10713. function fuzzynum(s) {
  10714. var v = Number(s);
  10715. if(!isNaN(v)) return v;
  10716. if(!/\d/.test(s)) return v;
  10717. var wt = 1;
  10718. var ss = s.replace(/([\d]),([\d])/g,"$1$2").replace(/[$]/g,"").replace(/[%]/g, function() { wt *= 100; return "";});
  10719. if(!isNaN(v = Number(ss))) return v / wt;
  10720. ss = ss.replace(/[(](.*)[)]/,function($$, $1) { wt = -wt; return $1;});
  10721. if(!isNaN(v = Number(ss))) return v / wt;
  10722. return v;
  10723. }
  10724. function fuzzydate(s) {
  10725. var o = new Date(s), n = new Date(NaN);
  10726. var y = o.getYear(), m = o.getMonth(), d = o.getDate();
  10727. if(isNaN(d)) return n;
  10728. if(y < 0 || y > 8099) return n;
  10729. if((m > 0 || d > 1) && y != 101) return o;
  10730. if(s.toLowerCase().match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) return o;
  10731. if(s.match(/[^-0-9:,\/\\]/)) return n;
  10732. return o;
  10733. }
  10734. var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5;
  10735. function split_regex(str, re, def) {
  10736. if(safe_split_regex || typeof re == "string") return str.split(re);
  10737. var p = str.split(re), o = [p[0]];
  10738. for(var i = 1; i < p.length; ++i) { o.push(def); o.push(p[i]); }
  10739. return o;
  10740. }
  10741. function getdatastr(data) {
  10742. if(!data) return null;
  10743. if(data.data) return debom(data.data);
  10744. if(data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString('binary'));
  10745. if(data.asBinary) return debom(data.asBinary());
  10746. if(data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(),0)));
  10747. if(data.content && data.type) return debom(cc2str(data.content));
  10748. return null;
  10749. }
  10750. function getdatabin(data) {
  10751. if(!data) return null;
  10752. if(data.data) return char_codes(data.data);
  10753. if(data.asNodeBuffer && has_buf) return data.asNodeBuffer();
  10754. if(data._data && data._data.getContent) {
  10755. var o = data._data.getContent();
  10756. if(typeof o == "string") return char_codes(o);
  10757. return Array.prototype.slice.call(o);
  10758. }
  10759. if(data.content && data.type) return data.content;
  10760. return null;
  10761. }
  10762. function getdata(data) { return (data && data.name.slice(-4) === ".bin") ? getdatabin(data) : getdatastr(data); }
  10763. /* Part 2 Section 10.1.2 "Mapping Content Types" Names are case-insensitive */
  10764. /* OASIS does not comment on filename case sensitivity */
  10765. function safegetzipfile(zip, file) {
  10766. var k = zip.FullPaths || keys(zip.files);
  10767. var f = file.toLowerCase(), g = f.replace(/\//g,'\\');
  10768. for(var i=0; i<k.length; ++i) {
  10769. var n = k[i].toLowerCase();
  10770. if(f == n || g == n) return zip.files[k[i]];
  10771. }
  10772. return null;
  10773. }
  10774. function getzipfile(zip, file) {
  10775. var o = safegetzipfile(zip, file);
  10776. if(o == null) throw new Error("Cannot find file " + file + " in zip");
  10777. return o;
  10778. }
  10779. function getzipdata(zip, file, safe) {
  10780. if(!safe) return getdata(getzipfile(zip, file));
  10781. if(!file) return null;
  10782. try { return getzipdata(zip, file); } catch(e) { return null; }
  10783. }
  10784. function getzipstr(zip, file, safe) {
  10785. if(!safe) return getdatastr(getzipfile(zip, file));
  10786. if(!file) return null;
  10787. try { return getzipstr(zip, file); } catch(e) { return null; }
  10788. }
  10789. function zipentries(zip) {
  10790. var k = zip.FullPaths || keys(zip.files), o = [];
  10791. for(var i = 0; i < k.length; ++i) if(k[i].slice(-1) != '/') o.push(k[i]);
  10792. return o.sort();
  10793. }
  10794. function zip_add_file(zip, path, content) {
  10795. if(zip.FullPaths) CFB.utils.cfb_add(zip, path, content);
  10796. else zip.file(path, content);
  10797. }
  10798. var jszip;
  10799. /*global JSZipSync:true */
  10800. if(typeof JSZipSync !== 'undefined') jszip = JSZipSync;
  10801. if(typeof exports !== 'undefined') {
  10802. if(typeof module !== 'undefined' && module.exports) {
  10803. if(typeof jszip === 'undefined') jszip = undefined;
  10804. }
  10805. }
  10806. function zip_new() {
  10807. if(!jszip) return CFB.utils.cfb_new();
  10808. return new jszip();
  10809. }
  10810. function zip_read(d, o) {
  10811. var zip;
  10812. if(jszip) switch(o.type) {
  10813. case "base64": zip = new jszip(d, { base64:true }); break;
  10814. case "binary": case "array": zip = new jszip(d, { base64:false }); break;
  10815. case "buffer": zip = new jszip(d); break;
  10816. default: throw new Error("Unrecognized type " + o.type);
  10817. }
  10818. else switch(o.type) {
  10819. case "base64": zip = CFB.read(d, { type: "base64" }); break;
  10820. case "binary": zip = CFB.read(d, { type: "binary" }); break;
  10821. case "buffer": case "array": zip = CFB.read(d, { type: "buffer" }); break;
  10822. default: throw new Error("Unrecognized type " + o.type);
  10823. }
  10824. return zip;
  10825. }
  10826. function resolve_path(path, base) {
  10827. if(path.charAt(0) == "/") return path.slice(1);
  10828. var result = base.split('/');
  10829. if(base.slice(-1) != "/") result.pop(); // folder path
  10830. var target = path.split('/');
  10831. while (target.length !== 0) {
  10832. var step = target.shift();
  10833. if (step === '..') result.pop();
  10834. else if (step !== '.') result.push(step);
  10835. }
  10836. return result.join('/');
  10837. }
  10838. var XML_HEADER = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n';
  10839. var attregexg=/([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g;
  10840. var tagregex=/<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'">\s=]+))*\s*[\/\?]?>/mg;
  10841. if(!(XML_HEADER.match(tagregex))) tagregex = /<[^>]*>/g;
  10842. var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/;
  10843. function parsexmltag(tag, skip_root, skip_LC) {
  10844. var z = ({});
  10845. var eq = 0, c = 0;
  10846. for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break;
  10847. if(!skip_root) z[0] = tag.slice(0, eq);
  10848. if(eq === tag.length) return z;
  10849. var m = tag.match(attregexg), j=0, v="", i=0, q="", cc="", quot = 1;
  10850. if(m) for(i = 0; i != m.length; ++i) {
  10851. cc = m[i];
  10852. for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break;
  10853. q = cc.slice(0,c).trim();
  10854. while(cc.charCodeAt(c+1) == 32) ++c;
  10855. quot = ((eq=cc.charCodeAt(c+1)) == 34 || eq == 39) ? 1 : 0;
  10856. v = cc.slice(c+1+quot, cc.length-quot);
  10857. for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break;
  10858. if(j===q.length) {
  10859. if(q.indexOf("_") > 0) q = q.slice(0, q.indexOf("_")); // from ods
  10860. z[q] = v;
  10861. if(!skip_LC) z[q.toLowerCase()] = v;
  10862. }
  10863. else {
  10864. var k = (j===5 && q.slice(0,5)==="xmlns"?"xmlns":"")+q.slice(j+1);
  10865. if(z[k] && q.slice(j-3,j) == "ext") continue; // from ods
  10866. z[k] = v;
  10867. if(!skip_LC) z[k.toLowerCase()] = v;
  10868. }
  10869. }
  10870. return z;
  10871. }
  10872. function strip_ns(x) { return x.replace(nsregex2, "<$1"); }
  10873. var encodings = {
  10874. '&quot;': '"',
  10875. '&apos;': "'",
  10876. '&gt;': '>',
  10877. '&lt;': '<',
  10878. '&amp;': '&'
  10879. };
  10880. var rencoding = evert(encodings);
  10881. //var rencstr = "&<>'\"".split("");
  10882. // TODO: CP remap (need to read file version to determine OS)
  10883. var unescapexml = (function() {
  10884. /* 22.4.2.4 bstr (Basic String) */
  10885. var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig;
  10886. return function unescapexml(text) {
  10887. var s = text + '', i = s.indexOf("<![CDATA[");
  10888. if(i == -1) return s.replace(encregex, function($$, $1) { return encodings[$$]||String.fromCharCode(parseInt($1,$$.indexOf("x")>-1?16:10))||$$; }).replace(coderegex,function(m,c) {return String.fromCharCode(parseInt(c,16));});
  10889. var j = s.indexOf("]]>");
  10890. return unescapexml(s.slice(0, i)) + s.slice(i+9,j) + unescapexml(s.slice(j+3));
  10891. };
  10892. })();
  10893. var decregex=/[&<>'"]/g, charegex = /[\u0000-\u0008\u000b-\u001f]/g;
  10894. function escapexml(text){
  10895. var s = text + '';
  10896. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(charegex,function(s) { return "_x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + "_";});
  10897. }
  10898. function escapexmltag(text){ return escapexml(text).replace(/ /g,"_x0020_"); }
  10899. var htmlcharegex = /[\u0000-\u001f]/g;
  10900. function escapehtml(text){
  10901. var s = text + '';
  10902. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(/\n/g, "<br/>").replace(htmlcharegex,function(s) { return "&#x" + ("000"+s.charCodeAt(0).toString(16)).slice(-4) + ";"; });
  10903. }
  10904. function escapexlml(text){
  10905. var s = text + '';
  10906. return s.replace(decregex, function(y) { return rencoding[y]; }).replace(htmlcharegex,function(s) { return "&#x" + (s.charCodeAt(0).toString(16)).toUpperCase() + ";"; });
  10907. }
  10908. /* TODO: handle codepages */
  10909. var xlml_fixstr = (function() {
  10910. var entregex = /&#(\d+);/g;
  10911. function entrepl($$,$1) { return String.fromCharCode(parseInt($1,10)); }
  10912. return function xlml_fixstr(str) { return str.replace(entregex,entrepl); };
  10913. })();
  10914. var xlml_unfixstr = (function() {
  10915. return function xlml_unfixstr(str) { return str.replace(/(\r\n|[\r\n])/g,"\&#10;"); };
  10916. })();
  10917. function parsexmlbool(value) {
  10918. switch(value) {
  10919. case 1: case true: case '1': case 'true': case 'TRUE': return true;
  10920. /* case '0': case 'false': case 'FALSE':*/
  10921. default: return false;
  10922. }
  10923. }
  10924. var utf8read = function utf8reada(orig) {
  10925. var out = "", i = 0, c = 0, d = 0, e = 0, f = 0, w = 0;
  10926. while (i < orig.length) {
  10927. c = orig.charCodeAt(i++);
  10928. if (c < 128) { out += String.fromCharCode(c); continue; }
  10929. d = orig.charCodeAt(i++);
  10930. if (c>191 && c<224) { f = ((c & 31) << 6); f |= (d & 63); out += String.fromCharCode(f); continue; }
  10931. e = orig.charCodeAt(i++);
  10932. if (c < 240) { out += String.fromCharCode(((c & 15) << 12) | ((d & 63) << 6) | (e & 63)); continue; }
  10933. f = orig.charCodeAt(i++);
  10934. w = (((c & 7) << 18) | ((d & 63) << 12) | ((e & 63) << 6) | (f & 63))-65536;
  10935. out += String.fromCharCode(0xD800 + ((w>>>10)&1023));
  10936. out += String.fromCharCode(0xDC00 + (w&1023));
  10937. }
  10938. return out;
  10939. };
  10940. var utf8write = function(orig) {
  10941. var out = [], i = 0, c = 0, d = 0;
  10942. while(i < orig.length) {
  10943. c = orig.charCodeAt(i++);
  10944. switch(true) {
  10945. case c < 128: out.push(String.fromCharCode(c)); break;
  10946. case c < 2048:
  10947. out.push(String.fromCharCode(192 + (c >> 6)));
  10948. out.push(String.fromCharCode(128 + (c & 63)));
  10949. break;
  10950. case c >= 55296 && c < 57344:
  10951. c -= 55296; d = orig.charCodeAt(i++) - 56320 + (c<<10);
  10952. out.push(String.fromCharCode(240 + ((d >>18) & 7)));
  10953. out.push(String.fromCharCode(144 + ((d >>12) & 63)));
  10954. out.push(String.fromCharCode(128 + ((d >> 6) & 63)));
  10955. out.push(String.fromCharCode(128 + (d & 63)));
  10956. break;
  10957. default:
  10958. out.push(String.fromCharCode(224 + (c >> 12)));
  10959. out.push(String.fromCharCode(128 + ((c >> 6) & 63)));
  10960. out.push(String.fromCharCode(128 + (c & 63)));
  10961. }
  10962. }
  10963. return out.join("");
  10964. };
  10965. if(has_buf) {
  10966. var utf8readb = function utf8readb(data) {
  10967. var out = Buffer.alloc(2*data.length), w, i, j = 1, k = 0, ww=0, c;
  10968. for(i = 0; i < data.length; i+=j) {
  10969. j = 1;
  10970. if((c=data.charCodeAt(i)) < 128) w = c;
  10971. else if(c < 224) { w = (c&31)*64+(data.charCodeAt(i+1)&63); j=2; }
  10972. else if(c < 240) { w=(c&15)*4096+(data.charCodeAt(i+1)&63)*64+(data.charCodeAt(i+2)&63); j=3; }
  10973. else { j = 4;
  10974. w = (c & 7)*262144+(data.charCodeAt(i+1)&63)*4096+(data.charCodeAt(i+2)&63)*64+(data.charCodeAt(i+3)&63);
  10975. w -= 65536; ww = 0xD800 + ((w>>>10)&1023); w = 0xDC00 + (w&1023);
  10976. }
  10977. if(ww !== 0) { out[k++] = ww&255; out[k++] = ww>>>8; ww = 0; }
  10978. out[k++] = w%256; out[k++] = w>>>8;
  10979. }
  10980. return out.slice(0,k).toString('ucs2');
  10981. };
  10982. var corpus = "foo bar baz\u00e2\u0098\u0083\u00f0\u009f\u008d\u00a3";
  10983. if(utf8read(corpus) == utf8readb(corpus)) utf8read = utf8readb;
  10984. var utf8readc = function utf8readc(data) { return Buffer_from(data, 'binary').toString('utf8'); };
  10985. if(utf8read(corpus) == utf8readc(corpus)) utf8read = utf8readc;
  10986. utf8write = function(data) { return Buffer_from(data, 'utf8').toString("binary"); };
  10987. }
  10988. // matches <foo>...</foo> extracts content
  10989. var matchtag = (function() {
  10990. var mtcache = ({});
  10991. return function matchtag(f,g) {
  10992. var t = f+"|"+(g||"");
  10993. if(mtcache[t]) return mtcache[t];
  10994. return (mtcache[t] = new RegExp('<(?:\\w+:)?'+f+'(?: xml:space="preserve")?(?:[^>]*)>([\\s\\S]*?)</(?:\\w+:)?'+f+'>',((g||""))));
  10995. };
  10996. })();
  10997. var htmldecode = (function() {
  10998. var entities = [
  10999. ['nbsp', ' '], ['middot', '·'],
  11000. ['quot', '"'], ['apos', "'"], ['gt', '>'], ['lt', '<'], ['amp', '&']
  11001. ].map(function(x) { return [new RegExp('&' + x[0] + ';', "ig"), x[1]]; });
  11002. return function htmldecode(str) {
  11003. var o = str
  11004. // Remove new lines and spaces from start of content
  11005. .replace(/^[\t\n\r ]+/, "")
  11006. // Remove new lines and spaces from end of content
  11007. .replace(/[\t\n\r ]+$/,"")
  11008. // Added line which removes any white space characters after and before html tags
  11009. .replace(/>\s+/g,">").replace(/\s+</g,"<")
  11010. // Replace remaining new lines and spaces with space
  11011. .replace(/[\t\n\r ]+/g, " ")
  11012. // Replace <br> tags with new lines
  11013. .replace(/<\s*[bB][rR]\s*\/?>/g,"\n")
  11014. // Strip HTML elements
  11015. .replace(/<[^>]*>/g,"");
  11016. for(var i = 0; i < entities.length; ++i) o = o.replace(entities[i][0], entities[i][1]);
  11017. return o;
  11018. };
  11019. })();
  11020. var vtregex = (function(){ var vt_cache = {};
  11021. return function vt_regex(bt) {
  11022. if(vt_cache[bt] !== undefined) return vt_cache[bt];
  11023. return (vt_cache[bt] = new RegExp("<(?:vt:)?" + bt + ">([\\s\\S]*?)</(?:vt:)?" + bt + ">", 'g') );
  11024. };})();
  11025. var vtvregex = /<\/?(?:vt:)?variant>/g, vtmregex = /<(?:vt:)([^>]*)>([\s\S]*)</;
  11026. function parseVector(data, opts) {
  11027. var h = parsexmltag(data);
  11028. var matches = data.match(vtregex(h.baseType))||[];
  11029. var res = [];
  11030. if(matches.length != h.size) {
  11031. if(opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h.size);
  11032. return res;
  11033. }
  11034. matches.forEach(function(x) {
  11035. var v = x.replace(vtvregex,"").match(vtmregex);
  11036. if(v) res.push({v:utf8read(v[2]), t:v[1]});
  11037. });
  11038. return res;
  11039. }
  11040. var wtregex = /(^\s|\s$|\n)/;
  11041. function writetag(f,g) { return '<' + f + (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f + '>'; }
  11042. function wxt_helper(h) { return keys(h).map(function(k) { return " " + k + '="' + h[k] + '"';}).join(""); }
  11043. function writextag(f,g,h) { return '<' + f + ((h != null) ? wxt_helper(h) : "") + ((g != null) ? (g.match(wtregex)?' xml:space="preserve"' : "") + '>' + g + '</' + f : "/") + '>';}
  11044. function write_w3cdtf(d, t) { try { return d.toISOString().replace(/\.\d*/,""); } catch(e) { if(t) throw e; } return ""; }
  11045. function write_vt(s, xlsx) {
  11046. switch(typeof s) {
  11047. case 'string':
  11048. var o = writextag('vt:lpwstr', escapexml(s));
  11049. if(xlsx) o = o.replace(/&quot;/g, "_x0022_");
  11050. return o;
  11051. case 'number': return writextag((s|0)==s?'vt:i4':'vt:r8', escapexml(String(s)));
  11052. case 'boolean': return writextag('vt:bool',s?'true':'false');
  11053. }
  11054. if(s instanceof Date) return writextag('vt:filetime', write_w3cdtf(s));
  11055. throw new Error("Unable to serialize " + s);
  11056. }
  11057. var XMLNS = ({
  11058. 'dc': 'http://purl.org/dc/elements/1.1/',
  11059. 'dcterms': 'http://purl.org/dc/terms/',
  11060. 'dcmitype': 'http://purl.org/dc/dcmitype/',
  11061. 'mx': 'http://schemas.microsoft.com/office/mac/excel/2008/main',
  11062. 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  11063. 'sjs': 'http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties',
  11064. 'vt': 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
  11065. 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
  11066. 'xsd': 'http://www.w3.org/2001/XMLSchema'
  11067. });
  11068. XMLNS.main = [
  11069. 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  11070. 'http://purl.oclc.org/ooxml/spreadsheetml/main',
  11071. 'http://schemas.microsoft.com/office/excel/2006/main',
  11072. 'http://schemas.microsoft.com/office/excel/2006/2'
  11073. ];
  11074. var XLMLNS = ({
  11075. 'o': 'urn:schemas-microsoft-com:office:office',
  11076. 'x': 'urn:schemas-microsoft-com:office:excel',
  11077. 'ss': 'urn:schemas-microsoft-com:office:spreadsheet',
  11078. 'dt': 'uuid:C2F41010-65B3-11d1-A29F-00AA00C14882',
  11079. 'mv': 'http://macVmlSchemaUri',
  11080. 'v': 'urn:schemas-microsoft-com:vml',
  11081. 'html': 'http://www.w3.org/TR/REC-html40'
  11082. });
  11083. function read_double_le(b, idx) {
  11084. var s = 1 - 2 * (b[idx + 7] >>> 7);
  11085. var e = ((b[idx + 7] & 0x7f) << 4) + ((b[idx + 6] >>> 4) & 0x0f);
  11086. var m = (b[idx+6]&0x0f);
  11087. for(var i = 5; i >= 0; --i) m = m * 256 + b[idx + i];
  11088. if(e == 0x7ff) return m == 0 ? (s * Infinity) : NaN;
  11089. if(e == 0) e = -1022;
  11090. else { e -= 1023; m += Math.pow(2,52); }
  11091. return s * Math.pow(2, e - 52) * m;
  11092. }
  11093. function write_double_le(b, v, idx) {
  11094. var bs = ((((v < 0) || (1/v == -Infinity)) ? 1 : 0) << 7), e = 0, m = 0;
  11095. var av = bs ? (-v) : v;
  11096. if(!isFinite(av)) { e = 0x7ff; m = isNaN(v) ? 0x6969 : 0; }
  11097. else if(av == 0) e = m = 0;
  11098. else {
  11099. e = Math.floor(Math.log(av) / Math.LN2);
  11100. m = av * Math.pow(2, 52 - e);
  11101. if((e <= -1023) && (!isFinite(m) || (m < Math.pow(2,52)))) { e = -1022; }
  11102. else { m -= Math.pow(2,52); e+=1023; }
  11103. }
  11104. for(var i = 0; i <= 5; ++i, m/=256) b[idx + i] = m & 0xff;
  11105. b[idx + 6] = ((e & 0x0f) << 4) | (m & 0xf);
  11106. b[idx + 7] = (e >> 4) | bs;
  11107. }
  11108. var __toBuffer = function(bufs) { var x=[],w=10240; for(var i=0;i<bufs[0].length;++i) if(bufs[0][i]) for(var j=0,L=bufs[0][i].length;j<L;j+=w) x.push.apply(x, bufs[0][i].slice(j,j+w)); return x; };
  11109. var ___toBuffer = __toBuffer;
  11110. var __utf16le = function(b,s,e) { var ss=[]; for(var i=s; i<e; i+=2) ss.push(String.fromCharCode(__readUInt16LE(b,i))); return ss.join("").replace(chr0,''); };
  11111. var ___utf16le = __utf16le;
  11112. var __hexlify = function(b,s,l) { var ss=[]; for(var i=s; i<s+l; ++i) ss.push(("0" + b[i].toString(16)).slice(-2)); return ss.join(""); };
  11113. var ___hexlify = __hexlify;
  11114. var __utf8 = function(b,s,e) { var ss=[]; for(var i=s; i<e; i++) ss.push(String.fromCharCode(__readUInt8(b,i))); return ss.join(""); };
  11115. var ___utf8 = __utf8;
  11116. var __lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  11117. var ___lpstr = __lpstr;
  11118. var __cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  11119. var ___cpstr = __cpstr;
  11120. var __lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len-1) : "";};
  11121. var ___lpwstr = __lpwstr;
  11122. var __lpp4, ___lpp4;
  11123. __lpp4 = ___lpp4 = function lpp4_(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf16le(b, i+4,i+4+len) : "";};
  11124. var __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? __utf8(b, i+4,i+4+len) : "";};
  11125. var ___8lpp4 = __8lpp4;
  11126. var __double, ___double;
  11127. __double = ___double = function(b, idx) { return read_double_le(b, idx);};
  11128. var is_buf = function is_buf_a(a) { return Array.isArray(a); };
  11129. if(has_buf) {
  11130. __utf16le = function(b,s,e) { if(!Buffer.isBuffer(b)) return ___utf16le(b,s,e); return b.toString('utf16le',s,e).replace(chr0,'')/*.replace(chr1,'!')*/; };
  11131. __hexlify = function(b,s,l) { return Buffer.isBuffer(b) ? b.toString('hex',s,s+l) : ___hexlify(b,s,l); };
  11132. __lpstr = function lpstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
  11133. __cpstr = function cpstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___cpstr(b, i); var len = b.readUInt32LE(i); return len > 0 ? b.toString('utf8',i+4,i+4+len-1) : "";};
  11134. __lpwstr = function lpwstr_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpwstr(b, i); var len = 2*b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len-1);};
  11135. __lpp4 = function lpp4_b(b, i) { if(!Buffer.isBuffer(b)) return ___lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf16le',i+4,i+4+len);};
  11136. __8lpp4 = function lpp4_8b(b, i) { if(!Buffer.isBuffer(b)) return ___8lpp4(b, i); var len = b.readUInt32LE(i); return b.toString('utf8',i+4,i+4+len);};
  11137. __utf8 = function utf8_b(b, s, e) { return (Buffer.isBuffer(b)) ? b.toString('utf8',s,e) : ___utf8(b,s,e); };
  11138. __toBuffer = function(bufs) { return (bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0])) ? Buffer.concat(bufs[0]) : ___toBuffer(bufs);};
  11139. bconcat = function(bufs) { return Buffer.isBuffer(bufs[0]) ? Buffer.concat(bufs) : [].concat.apply([], bufs); };
  11140. __double = function double_(b, i) { if(Buffer.isBuffer(b)) return b.readDoubleLE(i); return ___double(b,i); };
  11141. is_buf = function is_buf_b(a) { return Buffer.isBuffer(a) || Array.isArray(a); };
  11142. }
  11143. /* from js-xls */
  11144. if(typeof cptable !== 'undefined') {
  11145. __utf16le = function(b,s,e) { return cptable.utils.decode(1200, b.slice(s,e)).replace(chr0, ''); };
  11146. __utf8 = function(b,s,e) { return cptable.utils.decode(65001, b.slice(s,e)); };
  11147. __lpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(current_ansi, b.slice(i+4, i+4+len-1)) : "";};
  11148. __cpstr = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(current_codepage, b.slice(i+4, i+4+len-1)) : "";};
  11149. __lpwstr = function(b,i) { var len = 2*__readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(1200, b.slice(i+4,i+4+len-1)) : "";};
  11150. __lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(1200, b.slice(i+4,i+4+len)) : "";};
  11151. __8lpp4 = function(b,i) { var len = __readUInt32LE(b,i); return len > 0 ? cptable.utils.decode(65001, b.slice(i+4,i+4+len)) : "";};
  11152. }
  11153. var __readUInt8 = function(b, idx) { return b[idx]; };
  11154. var __readUInt16LE = function(b, idx) { return (b[idx+1]*(1<<8))+b[idx]; };
  11155. var __readInt16LE = function(b, idx) { var u = (b[idx+1]*(1<<8))+b[idx]; return (u < 0x8000) ? u : ((0xffff - u + 1) * -1); };
  11156. var __readUInt32LE = function(b, idx) { return b[idx+3]*(1<<24)+(b[idx+2]<<16)+(b[idx+1]<<8)+b[idx]; };
  11157. var __readInt32LE = function(b, idx) { return (b[idx+3]<<24)|(b[idx+2]<<16)|(b[idx+1]<<8)|b[idx]; };
  11158. var __readInt32BE = function(b, idx) { return (b[idx]<<24)|(b[idx+1]<<16)|(b[idx+2]<<8)|b[idx+3]; };
  11159. function ReadShift(size, t) {
  11160. var o="", oI, oR, oo=[], w, vv, i, loc;
  11161. switch(t) {
  11162. case 'dbcs':
  11163. loc = this.l;
  11164. if(has_buf && Buffer.isBuffer(this)) o = this.slice(this.l, this.l+2*size).toString("utf16le");
  11165. else for(i = 0; i < size; ++i) { o+=String.fromCharCode(__readUInt16LE(this, loc)); loc+=2; }
  11166. size *= 2;
  11167. break;
  11168. case 'utf8': o = __utf8(this, this.l, this.l + size); break;
  11169. case 'utf16le': size *= 2; o = __utf16le(this, this.l, this.l + size); break;
  11170. case 'wstr':
  11171. if(typeof cptable !== 'undefined') o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l+2*size));
  11172. else return ReadShift.call(this, size, 'dbcs');
  11173. size = 2 * size; break;
  11174. /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */
  11175. case 'lpstr-ansi': o = __lpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  11176. case 'lpstr-cp': o = __cpstr(this, this.l); size = 4 + __readUInt32LE(this, this.l); break;
  11177. /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */
  11178. case 'lpwstr': o = __lpwstr(this, this.l); size = 4 + 2 * __readUInt32LE(this, this.l); break;
  11179. /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */
  11180. case 'lpp4': size = 4 + __readUInt32LE(this, this.l); o = __lpp4(this, this.l); if(size & 0x02) size += 2; break;
  11181. /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */
  11182. case '8lpp4': size = 4 + __readUInt32LE(this, this.l); o = __8lpp4(this, this.l); if(size & 0x03) size += 4 - (size & 0x03); break;
  11183. case 'cstr': size = 0; o = "";
  11184. while((w=__readUInt8(this, this.l + size++))!==0) oo.push(_getchar(w));
  11185. o = oo.join(""); break;
  11186. case '_wstr': size = 0; o = "";
  11187. while((w=__readUInt16LE(this,this.l +size))!==0){oo.push(_getchar(w));size+=2;}
  11188. size+=2; o = oo.join(""); break;
  11189. /* sbcs and dbcs support continue records in the SST way TODO codepages */
  11190. case 'dbcs-cont': o = ""; loc = this.l;
  11191. for(i = 0; i < size; ++i) {
  11192. if(this.lens && this.lens.indexOf(loc) !== -1) {
  11193. w = __readUInt8(this, loc);
  11194. this.l = loc + 1;
  11195. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  11196. return oo.join("") + vv;
  11197. }
  11198. oo.push(_getchar(__readUInt16LE(this, loc)));
  11199. loc+=2;
  11200. } o = oo.join(""); size *= 2; break;
  11201. case 'cpstr':
  11202. if(typeof cptable !== 'undefined') {
  11203. o = cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size));
  11204. break;
  11205. }
  11206. /* falls through */
  11207. case 'sbcs-cont': o = ""; loc = this.l;
  11208. for(i = 0; i != size; ++i) {
  11209. if(this.lens && this.lens.indexOf(loc) !== -1) {
  11210. w = __readUInt8(this, loc);
  11211. this.l = loc + 1;
  11212. vv = ReadShift.call(this, size-i, w ? 'dbcs-cont' : 'sbcs-cont');
  11213. return oo.join("") + vv;
  11214. }
  11215. oo.push(_getchar(__readUInt8(this, loc)));
  11216. loc+=1;
  11217. } o = oo.join(""); break;
  11218. default:
  11219. switch(size) {
  11220. case 1: oI = __readUInt8(this, this.l); this.l++; return oI;
  11221. case 2: oI = (t === 'i' ? __readInt16LE : __readUInt16LE)(this, this.l); this.l += 2; return oI;
  11222. case 4: case -4:
  11223. if(t === 'i' || ((this[this.l+3] & 0x80)===0)) { oI = ((size > 0) ? __readInt32LE : __readInt32BE)(this, this.l); this.l += 4; return oI; }
  11224. else { oR = __readUInt32LE(this, this.l); this.l += 4; } return oR;
  11225. case 8: case -8:
  11226. if(t === 'f') {
  11227. if(size == 8) oR = __double(this, this.l);
  11228. else oR = __double([this[this.l+7],this[this.l+6],this[this.l+5],this[this.l+4],this[this.l+3],this[this.l+2],this[this.l+1],this[this.l+0]], 0);
  11229. this.l += 8; return oR;
  11230. } else size = 8;
  11231. /* falls through */
  11232. case 16: o = __hexlify(this, this.l, size); break;
  11233. }}
  11234. this.l+=size; return o;
  11235. }
  11236. var __writeUInt32LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); b[idx+2] = ((val >>> 16) & 0xFF); b[idx+3] = ((val >>> 24) & 0xFF); };
  11237. var __writeInt32LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >> 8) & 0xFF); b[idx+2] = ((val >> 16) & 0xFF); b[idx+3] = ((val >> 24) & 0xFF); };
  11238. var __writeUInt16LE = function(b, val, idx) { b[idx] = (val & 0xFF); b[idx+1] = ((val >>> 8) & 0xFF); };
  11239. function WriteShift(t, val, f) {
  11240. var size = 0, i = 0;
  11241. if(f === 'dbcs') {
  11242. for(i = 0; i != val.length; ++i) __writeUInt16LE(this, val.charCodeAt(i), this.l + 2 * i);
  11243. size = 2 * val.length;
  11244. } else if(f === 'sbcs') {
  11245. if(typeof cptable !== 'undefined' && current_ansi == 874) {
  11246. /* TODO: use tables directly, don't encode */
  11247. for(i = 0; i != val.length; ++i) {
  11248. var cppayload = cptable.utils.encode(current_ansi, val.charAt(i));
  11249. this[this.l + i] = cppayload[0];
  11250. }
  11251. } else {
  11252. val = val.replace(/[^\x00-\x7F]/g, "_");
  11253. for(i = 0; i != val.length; ++i) this[this.l + i] = (val.charCodeAt(i) & 0xFF);
  11254. }
  11255. size = val.length;
  11256. } else if(f === 'hex') {
  11257. for(; i < t; ++i) {
  11258. this[this.l++] = (parseInt(val.slice(2*i, 2*i+2), 16)||0);
  11259. } return this;
  11260. } else if(f === 'utf16le') {
  11261. var end = Math.min(this.l + t, this.length);
  11262. for(i = 0; i < Math.min(val.length, t); ++i) {
  11263. var cc = val.charCodeAt(i);
  11264. this[this.l++] = (cc & 0xff);
  11265. this[this.l++] = (cc >> 8);
  11266. }
  11267. while(this.l < end) this[this.l++] = 0;
  11268. return this;
  11269. } else switch(t) {
  11270. case 1: size = 1; this[this.l] = val&0xFF; break;
  11271. case 2: size = 2; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; break;
  11272. case 3: size = 3; this[this.l] = val&0xFF; val >>>= 8; this[this.l+1] = val&0xFF; val >>>= 8; this[this.l+2] = val&0xFF; break;
  11273. case 4: size = 4; __writeUInt32LE(this, val, this.l); break;
  11274. case 8: size = 8; if(f === 'f') { write_double_le(this, val, this.l); break; }
  11275. /* falls through */
  11276. case 16: break;
  11277. case -4: size = 4; __writeInt32LE(this, val, this.l); break;
  11278. }
  11279. this.l += size; return this;
  11280. }
  11281. function CheckField(hexstr, fld) {
  11282. var m = __hexlify(this,this.l,hexstr.length>>1);
  11283. if(m !== hexstr) throw new Error(fld + 'Expected ' + hexstr + ' saw ' + m);
  11284. this.l += hexstr.length>>1;
  11285. }
  11286. function prep_blob(blob, pos) {
  11287. blob.l = pos;
  11288. blob.read_shift = ReadShift;
  11289. blob.chk = CheckField;
  11290. blob.write_shift = WriteShift;
  11291. }
  11292. function parsenoop(blob, length) { blob.l += length; }
  11293. function new_buf(sz) {
  11294. var o = new_raw_buf(sz);
  11295. prep_blob(o, 0);
  11296. return o;
  11297. }
  11298. /* [MS-XLSB] 2.1.4 Record */
  11299. function recordhopper(data, cb, opts) {
  11300. if(!data) return;
  11301. var tmpbyte, cntbyte, length;
  11302. prep_blob(data, data.l || 0);
  11303. var L = data.length, RT = 0, tgt = 0;
  11304. while(data.l < L) {
  11305. RT = data.read_shift(1);
  11306. if(RT & 0x80) RT = (RT & 0x7F) + ((data.read_shift(1) & 0x7F)<<7);
  11307. var R = XLSBRecordEnum[RT] || XLSBRecordEnum[0xFFFF];
  11308. tmpbyte = data.read_shift(1);
  11309. length = tmpbyte & 0x7F;
  11310. for(cntbyte = 1; cntbyte <4 && (tmpbyte & 0x80); ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 0x7F)<<(7*cntbyte);
  11311. tgt = data.l + length;
  11312. var d = (R.f||parsenoop)(data, length, opts);
  11313. data.l = tgt;
  11314. if(cb(d, R.n, RT)) return;
  11315. }
  11316. }
  11317. /* control buffer usage for fixed-length buffers */
  11318. function buf_array() {
  11319. var bufs = [], blksz = has_buf ? 256 : 2048;
  11320. var newblk = function ba_newblk(sz) {
  11321. var o = (new_buf(sz));
  11322. prep_blob(o, 0);
  11323. return o;
  11324. };
  11325. var curbuf = newblk(blksz);
  11326. var endbuf = function ba_endbuf() {
  11327. if(!curbuf) return;
  11328. if(curbuf.length > curbuf.l) { curbuf = curbuf.slice(0, curbuf.l); curbuf.l = curbuf.length; }
  11329. if(curbuf.length > 0) bufs.push(curbuf);
  11330. curbuf = null;
  11331. };
  11332. var next = function ba_next(sz) {
  11333. if(curbuf && (sz < (curbuf.length - curbuf.l))) return curbuf;
  11334. endbuf();
  11335. return (curbuf = newblk(Math.max(sz+1, blksz)));
  11336. };
  11337. var end = function ba_end() {
  11338. endbuf();
  11339. return __toBuffer([bufs]);
  11340. };
  11341. var push = function ba_push(buf) { endbuf(); curbuf = buf; if(curbuf.l == null) curbuf.l = curbuf.length; next(blksz); };
  11342. return ({ next:next, push:push, end:end, _bufs:bufs });
  11343. }
  11344. function write_record(ba, type, payload, length) {
  11345. var t = +XLSBRE[type], l;
  11346. if(isNaN(t)) return; // TODO: throw something here?
  11347. if(!length) length = XLSBRecordEnum[t].p || (payload||[]).length || 0;
  11348. l = 1 + (t >= 0x80 ? 1 : 0) + 1/* + length*/;
  11349. if(length >= 0x80) ++l; if(length >= 0x4000) ++l; if(length >= 0x200000) ++l;
  11350. var o = ba.next(l);
  11351. if(t <= 0x7F) o.write_shift(1, t);
  11352. else {
  11353. o.write_shift(1, (t & 0x7F) + 0x80);
  11354. o.write_shift(1, (t >> 7));
  11355. }
  11356. for(var i = 0; i != 4; ++i) {
  11357. if(length >= 0x80) { o.write_shift(1, (length & 0x7F)+0x80); length >>= 7; }
  11358. else { o.write_shift(1, length); break; }
  11359. }
  11360. if(length > 0 && is_buf(payload)) ba.push(payload);
  11361. }
  11362. /* XLS ranges enforced */
  11363. function shift_cell_xls(cell, tgt, opts) {
  11364. var out = dup(cell);
  11365. if(tgt.s) {
  11366. if(out.cRel) out.c += tgt.s.c;
  11367. if(out.rRel) out.r += tgt.s.r;
  11368. } else {
  11369. if(out.cRel) out.c += tgt.c;
  11370. if(out.rRel) out.r += tgt.r;
  11371. }
  11372. if(!opts || opts.biff < 12) {
  11373. while(out.c >= 0x100) out.c -= 0x100;
  11374. while(out.r >= 0x10000) out.r -= 0x10000;
  11375. }
  11376. return out;
  11377. }
  11378. function shift_range_xls(cell, range, opts) {
  11379. var out = dup(cell);
  11380. out.s = shift_cell_xls(out.s, range.s, opts);
  11381. out.e = shift_cell_xls(out.e, range.s, opts);
  11382. return out;
  11383. }
  11384. function encode_cell_xls(c, biff) {
  11385. if(c.cRel && c.c < 0) { c = dup(c); while(c.c < 0) c.c += (biff > 8) ? 0x4000 : 0x100; }
  11386. if(c.rRel && c.r < 0) { c = dup(c); while(c.r < 0) c.r += (biff > 8) ? 0x100000 : ((biff > 5) ? 0x10000 : 0x4000); }
  11387. var s = encode_cell(c);
  11388. if(!c.cRel && c.cRel != null) s = fix_col(s);
  11389. if(!c.rRel && c.rRel != null) s = fix_row(s);
  11390. return s;
  11391. }
  11392. function encode_range_xls(r, opts) {
  11393. if(r.s.r == 0 && !r.s.rRel) {
  11394. if(r.e.r == (opts.biff >= 12 ? 0xFFFFF : (opts.biff >= 8 ? 0x10000 : 0x4000)) && !r.e.rRel) {
  11395. return (r.s.cRel ? "" : "$") + encode_col(r.s.c) + ":" + (r.e.cRel ? "" : "$") + encode_col(r.e.c);
  11396. }
  11397. }
  11398. if(r.s.c == 0 && !r.s.cRel) {
  11399. if(r.e.c == (opts.biff >= 12 ? 0x3FFF : 0xFF) && !r.e.cRel) {
  11400. return (r.s.rRel ? "" : "$") + encode_row(r.s.r) + ":" + (r.e.rRel ? "" : "$") + encode_row(r.e.r);
  11401. }
  11402. }
  11403. return encode_cell_xls(r.s, opts.biff) + ":" + encode_cell_xls(r.e, opts.biff);
  11404. }
  11405. var OFFCRYPTO = {};
  11406. var make_offcrypto = function(O, _crypto) {
  11407. var crypto;
  11408. if(typeof _crypto !== 'undefined') crypto = _crypto;
  11409. else if(typeof require !== 'undefined') {
  11410. try { crypto = undefined; }
  11411. catch(e) { crypto = null; }
  11412. }
  11413. O.rc4 = function(key, data) {
  11414. var S = new Array(256);
  11415. var c = 0, i = 0, j = 0, t = 0;
  11416. for(i = 0; i != 256; ++i) S[i] = i;
  11417. for(i = 0; i != 256; ++i) {
  11418. j = (j + S[i] + (key[i%key.length]).charCodeAt(0))&255;
  11419. t = S[i]; S[i] = S[j]; S[j] = t;
  11420. }
  11421. // $FlowIgnore
  11422. i = j = 0; var out = new_raw_buf(data.length);
  11423. for(c = 0; c != data.length; ++c) {
  11424. i = (i + 1)&255;
  11425. j = (j + S[i])%256;
  11426. t = S[i]; S[i] = S[j]; S[j] = t;
  11427. out[c] = (data[c] ^ S[(S[i]+S[j])&255]);
  11428. }
  11429. return out;
  11430. };
  11431. O.md5 = function(hex) {
  11432. if(!crypto) throw new Error("Unsupported crypto");
  11433. return crypto.createHash('md5').update(hex).digest('hex');
  11434. };
  11435. };
  11436. /*global crypto:true */
  11437. make_offcrypto(OFFCRYPTO, typeof crypto !== "undefined" ? crypto : undefined);
  11438. function decode_row(rowstr) { return parseInt(unfix_row(rowstr),10) - 1; }
  11439. function encode_row(row) { return "" + (row + 1); }
  11440. function fix_row(cstr) { return cstr.replace(/([A-Z]|^)(\d+)$/,"$1$$$2"); }
  11441. function unfix_row(cstr) { return cstr.replace(/\$(\d+)$/,"$1"); }
  11442. function decode_col(colstr) { var c = unfix_col(colstr), d = 0, i = 0; for(; i !== c.length; ++i) d = 26*d + c.charCodeAt(i) - 64; return d - 1; }
  11443. function encode_col(col) { if(col < 0) throw new Error("invalid column " + col); var s=""; for(++col; col; col=Math.floor((col-1)/26)) s = String.fromCharCode(((col-1)%26) + 65) + s; return s; }
  11444. function fix_col(cstr) { return cstr.replace(/^([A-Z])/,"$$$1"); }
  11445. function unfix_col(cstr) { return cstr.replace(/^\$([A-Z])/,"$1"); }
  11446. function split_cell(cstr) { return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/,"$1,$2").split(","); }
  11447. //function decode_cell(cstr) { var splt = split_cell(cstr); return { c:decode_col(splt[0]), r:decode_row(splt[1]) }; }
  11448. function decode_cell(cstr) {
  11449. var R = 0, C = 0;
  11450. for(var i = 0; i < cstr.length; ++i) {
  11451. var cc = cstr.charCodeAt(i);
  11452. if(cc >= 48 && cc <= 57) R = 10 * R + (cc - 48);
  11453. else if(cc >= 65 && cc <= 90) C = 26 * C + (cc - 64);
  11454. }
  11455. return { c: C - 1, r:R - 1 };
  11456. }
  11457. //function encode_cell(cell) { return encode_col(cell.c) + encode_row(cell.r); }
  11458. function encode_cell(cell) {
  11459. var col = cell.c + 1;
  11460. var s="";
  11461. for(; col; col=((col-1)/26)|0) s = String.fromCharCode(((col-1)%26) + 65) + s;
  11462. return s + (cell.r + 1);
  11463. }
  11464. function decode_range(range) {
  11465. var idx = range.indexOf(":");
  11466. if(idx == -1) return { s: decode_cell(range), e: decode_cell(range) };
  11467. return { s: decode_cell(range.slice(0, idx)), e: decode_cell(range.slice(idx + 1)) };
  11468. }
  11469. function encode_range(cs,ce) {
  11470. if(typeof ce === 'undefined' || typeof ce === 'number') {
  11471. return encode_range(cs.s, cs.e);
  11472. }
  11473. if(typeof cs !== 'string') cs = encode_cell((cs));
  11474. if(typeof ce !== 'string') ce = encode_cell((ce));
  11475. return cs == ce ? cs : cs + ":" + ce;
  11476. }
  11477. function safe_decode_range(range) {
  11478. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  11479. var idx = 0, i = 0, cc = 0;
  11480. var len = range.length;
  11481. for(idx = 0; i < len; ++i) {
  11482. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  11483. idx = 26*idx + cc;
  11484. }
  11485. o.s.c = --idx;
  11486. for(idx = 0; i < len; ++i) {
  11487. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  11488. idx = 10*idx + cc;
  11489. }
  11490. o.s.r = --idx;
  11491. if(i === len || range.charCodeAt(++i) === 58) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
  11492. for(idx = 0; i != len; ++i) {
  11493. if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
  11494. idx = 26*idx + cc;
  11495. }
  11496. o.e.c = --idx;
  11497. for(idx = 0; i != len; ++i) {
  11498. if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
  11499. idx = 10*idx + cc;
  11500. }
  11501. o.e.r = --idx;
  11502. return o;
  11503. }
  11504. function safe_format_cell(cell, v) {
  11505. var q = (cell.t == 'd' && v instanceof Date);
  11506. if(cell.z != null) try { return (cell.w = SSF.format(cell.z, q ? datenum(v) : v)); } catch(e) { }
  11507. try { return (cell.w = SSF.format((cell.XF||{}).numFmtId||(q ? 14 : 0), q ? datenum(v) : v)); } catch(e) { return ''+v; }
  11508. }
  11509. function format_cell(cell, v, o) {
  11510. if(cell == null || cell.t == null || cell.t == 'z') return "";
  11511. if(cell.w !== undefined) return cell.w;
  11512. if(cell.t == 'd' && !cell.z && o && o.dateNF) cell.z = o.dateNF;
  11513. if(v == undefined) return safe_format_cell(cell, cell.v);
  11514. return safe_format_cell(cell, v);
  11515. }
  11516. function sheet_to_workbook(sheet, opts) {
  11517. var n = opts && opts.sheet ? opts.sheet : "Sheet1";
  11518. var sheets = {}; sheets[n] = sheet;
  11519. return { SheetNames: [n], Sheets: sheets };
  11520. }
  11521. function sheet_add_aoa(_ws, data, opts) {
  11522. var o = opts || {};
  11523. var dense = _ws ? Array.isArray(_ws) : o.dense;
  11524. if(DENSE != null && dense == null) dense = DENSE;
  11525. var ws = _ws || (dense ? ([]) : ({}));
  11526. var _R = 0, _C = 0;
  11527. if(ws && o.origin != null) {
  11528. if(typeof o.origin == 'number') _R = o.origin;
  11529. else {
  11530. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  11531. _R = _origin.r; _C = _origin.c;
  11532. }
  11533. if(!ws["!ref"]) ws["!ref"] = "A1:A1";
  11534. }
  11535. var range = ({s: {c:10000000, r:10000000}, e: {c:0, r:0}});
  11536. if(ws['!ref']) {
  11537. var _range = safe_decode_range(ws['!ref']);
  11538. range.s.c = _range.s.c;
  11539. range.s.r = _range.s.r;
  11540. range.e.c = Math.max(range.e.c, _range.e.c);
  11541. range.e.r = Math.max(range.e.r, _range.e.r);
  11542. if(_R == -1) range.e.r = _R = _range.e.r + 1;
  11543. }
  11544. for(var R = 0; R != data.length; ++R) {
  11545. if(!data[R]) continue;
  11546. if(!Array.isArray(data[R])) throw new Error("aoa_to_sheet expects an array of arrays");
  11547. for(var C = 0; C != data[R].length; ++C) {
  11548. if(typeof data[R][C] === 'undefined') continue;
  11549. var cell = ({v: data[R][C] });
  11550. var __R = _R + R, __C = _C + C;
  11551. if(range.s.r > __R) range.s.r = __R;
  11552. if(range.s.c > __C) range.s.c = __C;
  11553. if(range.e.r < __R) range.e.r = __R;
  11554. if(range.e.c < __C) range.e.c = __C;
  11555. if(data[R][C] && typeof data[R][C] === 'object' && !Array.isArray(data[R][C]) && !(data[R][C] instanceof Date)) cell = data[R][C];
  11556. else {
  11557. if(Array.isArray(cell.v)) { cell.f = data[R][C][1]; cell.v = cell.v[0]; }
  11558. if(cell.v === null) { if(cell.f) cell.t = 'n'; else if(!o.sheetStubs) continue; else cell.t = 'z'; }
  11559. else if(typeof cell.v === 'number') cell.t = 'n';
  11560. else if(typeof cell.v === 'boolean') cell.t = 'b';
  11561. else if(cell.v instanceof Date) {
  11562. cell.z = o.dateNF || SSF._table[14];
  11563. if(o.cellDates) { cell.t = 'd'; cell.w = SSF.format(cell.z, datenum(cell.v)); }
  11564. else { cell.t = 'n'; cell.v = datenum(cell.v); cell.w = SSF.format(cell.z, cell.v); }
  11565. }
  11566. else cell.t = 's';
  11567. }
  11568. if(dense) {
  11569. if(!ws[__R]) ws[__R] = [];
  11570. if(ws[__R][__C] && ws[__R][__C].z) cell.z = ws[__R][__C].z;
  11571. ws[__R][__C] = cell;
  11572. } else {
  11573. var cell_ref = encode_cell(({c:__C,r:__R}));
  11574. if(ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z;
  11575. ws[cell_ref] = cell;
  11576. }
  11577. }
  11578. }
  11579. if(range.s.c < 10000000) ws['!ref'] = encode_range(range);
  11580. return ws;
  11581. }
  11582. function aoa_to_sheet(data, opts) { return sheet_add_aoa(null, data, opts); }
  11583. function write_UInt32LE(x, o) {
  11584. if (!o) o = new_buf(4);
  11585. o.write_shift(4, x);
  11586. return o;
  11587. }
  11588. /* [MS-XLSB] 2.5.168 */
  11589. function parse_XLWideString(data) {
  11590. var cchCharacters = data.read_shift(4);
  11591. return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, 'dbcs');
  11592. }
  11593. function write_XLWideString(data, o) {
  11594. var _null = false; if (o == null) { _null = true; o = new_buf(4 + 2 * data.length); }
  11595. o.write_shift(4, data.length);
  11596. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  11597. return _null ? o.slice(0, o.l) : o;
  11598. }
  11599. /* [MS-XLSB] 2.5.91 */
  11600. //function parse_LPWideString(data) {
  11601. // var cchCharacters = data.read_shift(2);
  11602. // return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "utf16le");
  11603. //}
  11604. /* [MS-XLSB] 2.5.143 */
  11605. function parse_StrRun(data) {
  11606. return { ich: data.read_shift(2), ifnt: data.read_shift(2) };
  11607. }
  11608. function write_StrRun(run, o) {
  11609. if (!o) o = new_buf(4);
  11610. o.write_shift(2, run.ich || 0);
  11611. o.write_shift(2, run.ifnt || 0);
  11612. return o;
  11613. }
  11614. /* [MS-XLSB] 2.5.121 */
  11615. function parse_RichStr(data, length) {
  11616. var start = data.l;
  11617. var flags = data.read_shift(1);
  11618. var str = parse_XLWideString(data);
  11619. var rgsStrRun = [];
  11620. var z = ({ t: str, h: str });
  11621. if ((flags & 1) !== 0) { /* fRichStr */
  11622. /* TODO: formatted string */
  11623. var dwSizeStrRun = data.read_shift(4);
  11624. for (var i = 0; i != dwSizeStrRun; ++i) rgsStrRun.push(parse_StrRun(data));
  11625. z.r = rgsStrRun;
  11626. }
  11627. else z.r = [{ ich: 0, ifnt: 0 }];
  11628. //if((flags & 2) !== 0) { /* fExtStr */
  11629. // /* TODO: phonetic string */
  11630. //}
  11631. data.l = start + length;
  11632. return z;
  11633. }
  11634. function write_RichStr(str, o) {
  11635. /* TODO: formatted string */
  11636. var _null = false; if (o == null) { _null = true; o = new_buf(15 + 4 * str.t.length); }
  11637. o.write_shift(1, 0);
  11638. write_XLWideString(str.t, o);
  11639. return _null ? o.slice(0, o.l) : o;
  11640. }
  11641. /* [MS-XLSB] 2.4.328 BrtCommentText (RichStr w/1 run) */
  11642. var parse_BrtCommentText = parse_RichStr;
  11643. function write_BrtCommentText(str, o) {
  11644. /* TODO: formatted string */
  11645. var _null = false; if (o == null) { _null = true; o = new_buf(23 + 4 * str.t.length); }
  11646. o.write_shift(1, 1);
  11647. write_XLWideString(str.t, o);
  11648. o.write_shift(4, 1);
  11649. write_StrRun({ ich: 0, ifnt: 0 }, o);
  11650. return _null ? o.slice(0, o.l) : o;
  11651. }
  11652. /* [MS-XLSB] 2.5.9 */
  11653. function parse_XLSBCell(data) {
  11654. var col = data.read_shift(4);
  11655. var iStyleRef = data.read_shift(2);
  11656. iStyleRef += data.read_shift(1) << 16;
  11657. data.l++; //var fPhShow = data.read_shift(1);
  11658. return { c: col, iStyleRef: iStyleRef };
  11659. }
  11660. function write_XLSBCell(cell, o) {
  11661. if (o == null) o = new_buf(8);
  11662. o.write_shift(-4, cell.c);
  11663. o.write_shift(3, cell.iStyleRef || cell.s);
  11664. o.write_shift(1, 0); /* fPhShow */
  11665. return o;
  11666. }
  11667. /* [MS-XLSB] 2.5.21 */
  11668. var parse_XLSBCodeName = parse_XLWideString;
  11669. var write_XLSBCodeName = write_XLWideString;
  11670. /* [MS-XLSB] 2.5.166 */
  11671. function parse_XLNullableWideString(data) {
  11672. var cchCharacters = data.read_shift(4);
  11673. return cchCharacters === 0 || cchCharacters === 0xFFFFFFFF ? "" : data.read_shift(cchCharacters, 'dbcs');
  11674. }
  11675. function write_XLNullableWideString(data, o) {
  11676. var _null = false; if (o == null) { _null = true; o = new_buf(127); }
  11677. o.write_shift(4, data.length > 0 ? data.length : 0xFFFFFFFF);
  11678. if (data.length > 0) o.write_shift(0, data, 'dbcs');
  11679. return _null ? o.slice(0, o.l) : o;
  11680. }
  11681. /* [MS-XLSB] 2.5.165 */
  11682. var parse_XLNameWideString = parse_XLWideString;
  11683. //var write_XLNameWideString = write_XLWideString;
  11684. /* [MS-XLSB] 2.5.114 */
  11685. var parse_RelID = parse_XLNullableWideString;
  11686. var write_RelID = write_XLNullableWideString;
  11687. /* [MS-XLS] 2.5.217 ; [MS-XLSB] 2.5.122 */
  11688. function parse_RkNumber(data) {
  11689. var b = data.slice(data.l, data.l + 4);
  11690. var fX100 = (b[0] & 1), fInt = (b[0] & 2);
  11691. data.l += 4;
  11692. b[0] &= 0xFC; // b[0] &= ~3;
  11693. var RK = fInt === 0 ? __double([0, 0, 0, 0, b[0], b[1], b[2], b[3]], 0) : __readInt32LE(b, 0) >> 2;
  11694. return fX100 ? (RK / 100) : RK;
  11695. }
  11696. function write_RkNumber(data, o) {
  11697. if (o == null) o = new_buf(4);
  11698. var fX100 = 0, fInt = 0, d100 = data * 100;
  11699. if ((data == (data | 0)) && (data >= -(1 << 29)) && (data < (1 << 29))) { fInt = 1; }
  11700. else if ((d100 == (d100 | 0)) && (d100 >= -(1 << 29)) && (d100 < (1 << 29))) { fInt = 1; fX100 = 1; }
  11701. if (fInt) o.write_shift(-4, ((fX100 ? d100 : data) << 2) + (fX100 + 2));
  11702. else throw new Error("unsupported RkNumber " + data); // TODO
  11703. }
  11704. /* [MS-XLSB] 2.5.117 RfX */
  11705. function parse_RfX(data ) {
  11706. var cell = ({ s: {}, e: {} });
  11707. cell.s.r = data.read_shift(4);
  11708. cell.e.r = data.read_shift(4);
  11709. cell.s.c = data.read_shift(4);
  11710. cell.e.c = data.read_shift(4);
  11711. return cell;
  11712. }
  11713. function write_RfX(r, o) {
  11714. if (!o) o = new_buf(16);
  11715. o.write_shift(4, r.s.r);
  11716. o.write_shift(4, r.e.r);
  11717. o.write_shift(4, r.s.c);
  11718. o.write_shift(4, r.e.c);
  11719. return o;
  11720. }
  11721. /* [MS-XLSB] 2.5.153 UncheckedRfX */
  11722. var parse_UncheckedRfX = parse_RfX;
  11723. var write_UncheckedRfX = write_RfX;
  11724. /* [MS-XLSB] 2.5.155 UncheckedSqRfX */
  11725. //function parse_UncheckedSqRfX(data) {
  11726. // var cnt = data.read_shift(4);
  11727. // var out = [];
  11728. // for(var i = 0; i < cnt; ++i) {
  11729. // var rng = parse_UncheckedRfX(data);
  11730. // out.push(encode_range(rng));
  11731. // }
  11732. // return out.join(",");
  11733. //}
  11734. //function write_UncheckedSqRfX(sqrfx) {
  11735. // var parts = sqrfx.split(/\s*,\s*/);
  11736. // var o = new_buf(4); o.write_shift(4, parts.length);
  11737. // var out = [o];
  11738. // parts.forEach(function(rng) {
  11739. // out.push(write_UncheckedRfX(safe_decode_range(rng)));
  11740. // });
  11741. // return bconcat(out);
  11742. //}
  11743. /* [MS-XLS] 2.5.342 ; [MS-XLSB] 2.5.171 */
  11744. /* TODO: error checking, NaN and Infinity values are not valid Xnum */
  11745. function parse_Xnum(data) {
  11746. if(data.length - data.l < 8) throw "XLS Xnum Buffer underflow";
  11747. return data.read_shift(8, 'f');
  11748. }
  11749. function write_Xnum(data, o) { return (o || new_buf(8)).write_shift(8, data, 'f'); }
  11750. /* [MS-XLSB] 2.4.324 BrtColor */
  11751. function parse_BrtColor(data) {
  11752. var out = {};
  11753. var d = data.read_shift(1);
  11754. //var fValidRGB = d & 1;
  11755. var xColorType = d >>> 1;
  11756. var index = data.read_shift(1);
  11757. var nTS = data.read_shift(2, 'i');
  11758. var bR = data.read_shift(1);
  11759. var bG = data.read_shift(1);
  11760. var bB = data.read_shift(1);
  11761. data.l++; //var bAlpha = data.read_shift(1);
  11762. switch (xColorType) {
  11763. case 0: out.auto = 1; break;
  11764. case 1:
  11765. out.index = index;
  11766. var icv = XLSIcv[index];
  11767. /* automatic pseudo index 81 */
  11768. if (icv) out.rgb = rgb2Hex(icv);
  11769. break;
  11770. case 2:
  11771. /* if(!fValidRGB) throw new Error("invalid"); */
  11772. out.rgb = rgb2Hex([bR, bG, bB]);
  11773. break;
  11774. case 3: out.theme = index; break;
  11775. }
  11776. if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768;
  11777. return out;
  11778. }
  11779. function write_BrtColor(color, o) {
  11780. if (!o) o = new_buf(8);
  11781. if (!color || color.auto) { o.write_shift(4, 0); o.write_shift(4, 0); return o; }
  11782. if (color.index != null) {
  11783. o.write_shift(1, 0x02);
  11784. o.write_shift(1, color.index);
  11785. } else if (color.theme != null) {
  11786. o.write_shift(1, 0x06);
  11787. o.write_shift(1, color.theme);
  11788. } else {
  11789. o.write_shift(1, 0x05);
  11790. o.write_shift(1, 0);
  11791. }
  11792. var nTS = color.tint || 0;
  11793. if (nTS > 0) nTS *= 32767;
  11794. else if (nTS < 0) nTS *= 32768;
  11795. o.write_shift(2, nTS);
  11796. if (!color.rgb || color.theme != null) {
  11797. o.write_shift(2, 0);
  11798. o.write_shift(1, 0);
  11799. o.write_shift(1, 0);
  11800. } else {
  11801. var rgb = (color.rgb || 'FFFFFF');
  11802. if (typeof rgb == 'number') rgb = ("000000" + rgb.toString(16)).slice(-6);
  11803. o.write_shift(1, parseInt(rgb.slice(0, 2), 16));
  11804. o.write_shift(1, parseInt(rgb.slice(2, 4), 16));
  11805. o.write_shift(1, parseInt(rgb.slice(4, 6), 16));
  11806. o.write_shift(1, 0xFF);
  11807. }
  11808. return o;
  11809. }
  11810. /* [MS-XLSB] 2.5.52 */
  11811. function parse_FontFlags(data) {
  11812. var d = data.read_shift(1);
  11813. data.l++;
  11814. var out = {
  11815. fBold: d & 0x01,
  11816. fItalic: d & 0x02,
  11817. fUnderline: d & 0x04,
  11818. fStrikeout: d & 0x08,
  11819. fOutline: d & 0x10,
  11820. fShadow: d & 0x20,
  11821. fCondense: d & 0x40,
  11822. fExtend: d & 0x80
  11823. };
  11824. return out;
  11825. }
  11826. function write_FontFlags(font, o) {
  11827. if (!o) o = new_buf(2);
  11828. var grbit =
  11829. (font.italic ? 0x02 : 0) |
  11830. (font.strike ? 0x08 : 0) |
  11831. (font.outline ? 0x10 : 0) |
  11832. (font.shadow ? 0x20 : 0) |
  11833. (font.condense ? 0x40 : 0) |
  11834. (font.extend ? 0x80 : 0);
  11835. o.write_shift(1, grbit);
  11836. o.write_shift(1, 0);
  11837. return o;
  11838. }
  11839. /* [MS-OLEDS] 2.3.1 and 2.3.2 */
  11840. function parse_ClipboardFormatOrString(o, w) {
  11841. // $FlowIgnore
  11842. var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" };
  11843. var m = o.read_shift(4);
  11844. switch (m) {
  11845. case 0x00000000: return "";
  11846. case 0xffffffff: case 0xfffffffe: return ClipFmt[o.read_shift(4)] || "";
  11847. }
  11848. if (m > 0x190) throw new Error("Unsupported Clipboard: " + m.toString(16));
  11849. o.l -= 4;
  11850. return o.read_shift(0, w == 1 ? "lpstr" : "lpwstr");
  11851. }
  11852. function parse_ClipboardFormatOrAnsiString(o) { return parse_ClipboardFormatOrString(o, 1); }
  11853. function parse_ClipboardFormatOrUnicodeString(o) { return parse_ClipboardFormatOrString(o, 2); }
  11854. /* [MS-OLEPS] 2.2 PropertyType */
  11855. //var VT_EMPTY = 0x0000;
  11856. //var VT_NULL = 0x0001;
  11857. var VT_I2 = 0x0002;
  11858. var VT_I4 = 0x0003;
  11859. //var VT_R4 = 0x0004;
  11860. //var VT_R8 = 0x0005;
  11861. //var VT_CY = 0x0006;
  11862. //var VT_DATE = 0x0007;
  11863. //var VT_BSTR = 0x0008;
  11864. //var VT_ERROR = 0x000A;
  11865. var VT_BOOL = 0x000B;
  11866. var VT_VARIANT = 0x000C;
  11867. //var VT_DECIMAL = 0x000E;
  11868. //var VT_I1 = 0x0010;
  11869. //var VT_UI1 = 0x0011;
  11870. //var VT_UI2 = 0x0012;
  11871. var VT_UI4 = 0x0013;
  11872. //var VT_I8 = 0x0014;
  11873. //var VT_UI8 = 0x0015;
  11874. //var VT_INT = 0x0016;
  11875. //var VT_UINT = 0x0017;
  11876. var VT_LPSTR = 0x001E;
  11877. //var VT_LPWSTR = 0x001F;
  11878. var VT_FILETIME = 0x0040;
  11879. var VT_BLOB = 0x0041;
  11880. //var VT_STREAM = 0x0042;
  11881. //var VT_STORAGE = 0x0043;
  11882. //var VT_STREAMED_Object = 0x0044;
  11883. //var VT_STORED_Object = 0x0045;
  11884. //var VT_BLOB_Object = 0x0046;
  11885. var VT_CF = 0x0047;
  11886. //var VT_CLSID = 0x0048;
  11887. //var VT_VERSIONED_STREAM = 0x0049;
  11888. var VT_VECTOR = 0x1000;
  11889. //var VT_ARRAY = 0x2000;
  11890. var VT_STRING = 0x0050; // 2.3.3.1.11 VtString
  11891. var VT_USTR = 0x0051; // 2.3.3.1.12 VtUnalignedString
  11892. var VT_CUSTOM = [VT_STRING, VT_USTR];
  11893. /* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */
  11894. var DocSummaryPIDDSI = {
  11895. 0x01: { n: 'CodePage', t: VT_I2 },
  11896. 0x02: { n: 'Category', t: VT_STRING },
  11897. 0x03: { n: 'PresentationFormat', t: VT_STRING },
  11898. 0x04: { n: 'ByteCount', t: VT_I4 },
  11899. 0x05: { n: 'LineCount', t: VT_I4 },
  11900. 0x06: { n: 'ParagraphCount', t: VT_I4 },
  11901. 0x07: { n: 'SlideCount', t: VT_I4 },
  11902. 0x08: { n: 'NoteCount', t: VT_I4 },
  11903. 0x09: { n: 'HiddenCount', t: VT_I4 },
  11904. 0x0a: { n: 'MultimediaClipCount', t: VT_I4 },
  11905. 0x0b: { n: 'ScaleCrop', t: VT_BOOL },
  11906. 0x0c: { n: 'HeadingPairs', t: VT_VECTOR | VT_VARIANT },
  11907. 0x0d: { n: 'TitlesOfParts', t: VT_VECTOR | VT_LPSTR },
  11908. 0x0e: { n: 'Manager', t: VT_STRING },
  11909. 0x0f: { n: 'Company', t: VT_STRING },
  11910. 0x10: { n: 'LinksUpToDate', t: VT_BOOL },
  11911. 0x11: { n: 'CharacterCount', t: VT_I4 },
  11912. 0x13: { n: 'SharedDoc', t: VT_BOOL },
  11913. 0x16: { n: 'HyperlinksChanged', t: VT_BOOL },
  11914. 0x17: { n: 'AppVersion', t: VT_I4, p: 'version' },
  11915. 0x18: { n: 'DigSig', t: VT_BLOB },
  11916. 0x1A: { n: 'ContentType', t: VT_STRING },
  11917. 0x1B: { n: 'ContentStatus', t: VT_STRING },
  11918. 0x1C: { n: 'Language', t: VT_STRING },
  11919. 0x1D: { n: 'Version', t: VT_STRING },
  11920. 0xFF: {}
  11921. };
  11922. /* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */
  11923. var SummaryPIDSI = {
  11924. 0x01: { n: 'CodePage', t: VT_I2 },
  11925. 0x02: { n: 'Title', t: VT_STRING },
  11926. 0x03: { n: 'Subject', t: VT_STRING },
  11927. 0x04: { n: 'Author', t: VT_STRING },
  11928. 0x05: { n: 'Keywords', t: VT_STRING },
  11929. 0x06: { n: 'Comments', t: VT_STRING },
  11930. 0x07: { n: 'Template', t: VT_STRING },
  11931. 0x08: { n: 'LastAuthor', t: VT_STRING },
  11932. 0x09: { n: 'RevNumber', t: VT_STRING },
  11933. 0x0A: { n: 'EditTime', t: VT_FILETIME },
  11934. 0x0B: { n: 'LastPrinted', t: VT_FILETIME },
  11935. 0x0C: { n: 'CreatedDate', t: VT_FILETIME },
  11936. 0x0D: { n: 'ModifiedDate', t: VT_FILETIME },
  11937. 0x0E: { n: 'PageCount', t: VT_I4 },
  11938. 0x0F: { n: 'WordCount', t: VT_I4 },
  11939. 0x10: { n: 'CharCount', t: VT_I4 },
  11940. 0x11: { n: 'Thumbnail', t: VT_CF },
  11941. 0x12: { n: 'Application', t: VT_STRING },
  11942. 0x13: { n: 'DocSecurity', t: VT_I4 },
  11943. 0xFF: {}
  11944. };
  11945. /* [MS-OLEPS] 2.18 */
  11946. var SpecialProperties = {
  11947. 0x80000000: { n: 'Locale', t: VT_UI4 },
  11948. 0x80000003: { n: 'Behavior', t: VT_UI4 },
  11949. 0x72627262: {}
  11950. };
  11951. (function() {
  11952. for(var y in SpecialProperties) if(Object.prototype.hasOwnProperty.call(SpecialProperties, y))
  11953. DocSummaryPIDDSI[y] = SummaryPIDSI[y] = SpecialProperties[y];
  11954. })();
  11955. var DocSummaryRE = evert_key(DocSummaryPIDDSI, "n");
  11956. var SummaryRE = evert_key(SummaryPIDSI, "n");
  11957. /* [MS-XLS] 2.4.63 Country/Region codes */
  11958. var CountryEnum = {
  11959. 0x0001: "US", // United States
  11960. 0x0002: "CA", // Canada
  11961. 0x0003: "", // Latin America (except Brazil)
  11962. 0x0007: "RU", // Russia
  11963. 0x0014: "EG", // Egypt
  11964. 0x001E: "GR", // Greece
  11965. 0x001F: "NL", // Netherlands
  11966. 0x0020: "BE", // Belgium
  11967. 0x0021: "FR", // France
  11968. 0x0022: "ES", // Spain
  11969. 0x0024: "HU", // Hungary
  11970. 0x0027: "IT", // Italy
  11971. 0x0029: "CH", // Switzerland
  11972. 0x002B: "AT", // Austria
  11973. 0x002C: "GB", // United Kingdom
  11974. 0x002D: "DK", // Denmark
  11975. 0x002E: "SE", // Sweden
  11976. 0x002F: "NO", // Norway
  11977. 0x0030: "PL", // Poland
  11978. 0x0031: "DE", // Germany
  11979. 0x0034: "MX", // Mexico
  11980. 0x0037: "BR", // Brazil
  11981. 0x003d: "AU", // Australia
  11982. 0x0040: "NZ", // New Zealand
  11983. 0x0042: "TH", // Thailand
  11984. 0x0051: "JP", // Japan
  11985. 0x0052: "KR", // Korea
  11986. 0x0054: "VN", // Viet Nam
  11987. 0x0056: "CN", // China
  11988. 0x005A: "TR", // Turkey
  11989. 0x0069: "JS", // Ramastan
  11990. 0x00D5: "DZ", // Algeria
  11991. 0x00D8: "MA", // Morocco
  11992. 0x00DA: "LY", // Libya
  11993. 0x015F: "PT", // Portugal
  11994. 0x0162: "IS", // Iceland
  11995. 0x0166: "FI", // Finland
  11996. 0x01A4: "CZ", // Czech Republic
  11997. 0x0376: "TW", // Taiwan
  11998. 0x03C1: "LB", // Lebanon
  11999. 0x03C2: "JO", // Jordan
  12000. 0x03C3: "SY", // Syria
  12001. 0x03C4: "IQ", // Iraq
  12002. 0x03C5: "KW", // Kuwait
  12003. 0x03C6: "SA", // Saudi Arabia
  12004. 0x03CB: "AE", // United Arab Emirates
  12005. 0x03CC: "IL", // Israel
  12006. 0x03CE: "QA", // Qatar
  12007. 0x03D5: "IR", // Iran
  12008. 0xFFFF: "US" // United States
  12009. };
  12010. /* [MS-XLS] 2.5.127 */
  12011. var XLSFillPattern = [
  12012. null,
  12013. 'solid',
  12014. 'mediumGray',
  12015. 'darkGray',
  12016. 'lightGray',
  12017. 'darkHorizontal',
  12018. 'darkVertical',
  12019. 'darkDown',
  12020. 'darkUp',
  12021. 'darkGrid',
  12022. 'darkTrellis',
  12023. 'lightHorizontal',
  12024. 'lightVertical',
  12025. 'lightDown',
  12026. 'lightUp',
  12027. 'lightGrid',
  12028. 'lightTrellis',
  12029. 'gray125',
  12030. 'gray0625'
  12031. ];
  12032. function rgbify(arr) { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); }
  12033. /* [MS-XLS] 2.5.161 */
  12034. /* [MS-XLSB] 2.5.75 Icv */
  12035. var _XLSIcv = rgbify([
  12036. /* Color Constants */
  12037. 0x000000,
  12038. 0xFFFFFF,
  12039. 0xFF0000,
  12040. 0x00FF00,
  12041. 0x0000FF,
  12042. 0xFFFF00,
  12043. 0xFF00FF,
  12044. 0x00FFFF,
  12045. /* Overridable Defaults */
  12046. 0x000000,
  12047. 0xFFFFFF,
  12048. 0xFF0000,
  12049. 0x00FF00,
  12050. 0x0000FF,
  12051. 0xFFFF00,
  12052. 0xFF00FF,
  12053. 0x00FFFF,
  12054. 0x800000,
  12055. 0x008000,
  12056. 0x000080,
  12057. 0x808000,
  12058. 0x800080,
  12059. 0x008080,
  12060. 0xC0C0C0,
  12061. 0x808080,
  12062. 0x9999FF,
  12063. 0x993366,
  12064. 0xFFFFCC,
  12065. 0xCCFFFF,
  12066. 0x660066,
  12067. 0xFF8080,
  12068. 0x0066CC,
  12069. 0xCCCCFF,
  12070. 0x000080,
  12071. 0xFF00FF,
  12072. 0xFFFF00,
  12073. 0x00FFFF,
  12074. 0x800080,
  12075. 0x800000,
  12076. 0x008080,
  12077. 0x0000FF,
  12078. 0x00CCFF,
  12079. 0xCCFFFF,
  12080. 0xCCFFCC,
  12081. 0xFFFF99,
  12082. 0x99CCFF,
  12083. 0xFF99CC,
  12084. 0xCC99FF,
  12085. 0xFFCC99,
  12086. 0x3366FF,
  12087. 0x33CCCC,
  12088. 0x99CC00,
  12089. 0xFFCC00,
  12090. 0xFF9900,
  12091. 0xFF6600,
  12092. 0x666699,
  12093. 0x969696,
  12094. 0x003366,
  12095. 0x339966,
  12096. 0x003300,
  12097. 0x333300,
  12098. 0x993300,
  12099. 0x993366,
  12100. 0x333399,
  12101. 0x333333,
  12102. /* Other entries to appease BIFF8/12 */
  12103. 0xFFFFFF, /* 0x40 icvForeground ?? */
  12104. 0x000000, /* 0x41 icvBackground ?? */
  12105. 0x000000, /* 0x42 icvFrame ?? */
  12106. 0x000000, /* 0x43 icv3D ?? */
  12107. 0x000000, /* 0x44 icv3DText ?? */
  12108. 0x000000, /* 0x45 icv3DHilite ?? */
  12109. 0x000000, /* 0x46 icv3DShadow ?? */
  12110. 0x000000, /* 0x47 icvHilite ?? */
  12111. 0x000000, /* 0x48 icvCtlText ?? */
  12112. 0x000000, /* 0x49 icvCtlScrl ?? */
  12113. 0x000000, /* 0x4A icvCtlInv ?? */
  12114. 0x000000, /* 0x4B icvCtlBody ?? */
  12115. 0x000000, /* 0x4C icvCtlFrame ?? */
  12116. 0x000000, /* 0x4D icvCtlFore ?? */
  12117. 0x000000, /* 0x4E icvCtlBack ?? */
  12118. 0x000000, /* 0x4F icvCtlNeutral */
  12119. 0x000000, /* 0x50 icvInfoBk ?? */
  12120. 0x000000 /* 0x51 icvInfoText ?? */
  12121. ]);
  12122. var XLSIcv = dup(_XLSIcv);
  12123. /* [MS-XLSB] 2.5.97.2 */
  12124. var BErr = {
  12125. 0x00: "#NULL!",
  12126. 0x07: "#DIV/0!",
  12127. 0x0F: "#VALUE!",
  12128. 0x17: "#REF!",
  12129. 0x1D: "#NAME?",
  12130. 0x24: "#NUM!",
  12131. 0x2A: "#N/A",
  12132. 0x2B: "#GETTING_DATA",
  12133. 0xFF: "#WTF?"
  12134. };
  12135. var RBErr = evert_num(BErr);
  12136. /* Parts enumerated in OPC spec, MS-XLSB and MS-XLSX2 */
  12137. /* 12.3 Part Summary <SpreadsheetML> */
  12138. /* 14.2 Part Summary <DrawingML> */
  12139. /* [MS-XLSX2] 2.1 Part Enumerations ; [MS-XLSB] 2.1.7 Part Enumeration */
  12140. var ct2type/*{[string]:string}*/ = ({
  12141. /* Workbook */
  12142. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks",
  12143. /* Worksheet */
  12144. "application/vnd.ms-excel.binIndexWs": "TODO", /* Binary Index */
  12145. /* Macrosheet */
  12146. "application/vnd.ms-excel.intlmacrosheet": "TODO",
  12147. "application/vnd.ms-excel.binIndexMs": "TODO", /* Binary Index */
  12148. /* File Properties */
  12149. "application/vnd.openxmlformats-package.core-properties+xml": "coreprops",
  12150. "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops",
  12151. "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops",
  12152. /* Custom Data Properties */
  12153. "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO",
  12154. "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO",
  12155. /* PivotTable */
  12156. "application/vnd.ms-excel.pivotTable": "TODO",
  12157. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO",
  12158. /* Chart Objects */
  12159. "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO",
  12160. /* Chart Colors */
  12161. "application/vnd.ms-office.chartcolorstyle+xml": "TODO",
  12162. /* Chart Style */
  12163. "application/vnd.ms-office.chartstyle+xml": "TODO",
  12164. /* Chart Advanced */
  12165. "application/vnd.ms-office.chartex+xml": "TODO",
  12166. /* Calculation Chain */
  12167. "application/vnd.ms-excel.calcChain": "calcchains",
  12168. "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains",
  12169. /* Printer Settings */
  12170. "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO",
  12171. /* ActiveX */
  12172. "application/vnd.ms-office.activeX": "TODO",
  12173. "application/vnd.ms-office.activeX+xml": "TODO",
  12174. /* Custom Toolbars */
  12175. "application/vnd.ms-excel.attachedToolbars": "TODO",
  12176. /* External Data Connections */
  12177. "application/vnd.ms-excel.connections": "TODO",
  12178. "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO",
  12179. /* External Links */
  12180. "application/vnd.ms-excel.externalLink": "links",
  12181. "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links",
  12182. /* Metadata */
  12183. "application/vnd.ms-excel.sheetMetadata": "TODO",
  12184. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "TODO",
  12185. /* PivotCache */
  12186. "application/vnd.ms-excel.pivotCacheDefinition": "TODO",
  12187. "application/vnd.ms-excel.pivotCacheRecords": "TODO",
  12188. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO",
  12189. "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO",
  12190. /* Query Table */
  12191. "application/vnd.ms-excel.queryTable": "TODO",
  12192. "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO",
  12193. /* Shared Workbook */
  12194. "application/vnd.ms-excel.userNames": "TODO",
  12195. "application/vnd.ms-excel.revisionHeaders": "TODO",
  12196. "application/vnd.ms-excel.revisionLog": "TODO",
  12197. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO",
  12198. "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO",
  12199. "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO",
  12200. /* Single Cell Table */
  12201. "application/vnd.ms-excel.tableSingleCells": "TODO",
  12202. "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO",
  12203. /* Slicer */
  12204. "application/vnd.ms-excel.slicer": "TODO",
  12205. "application/vnd.ms-excel.slicerCache": "TODO",
  12206. "application/vnd.ms-excel.slicer+xml": "TODO",
  12207. "application/vnd.ms-excel.slicerCache+xml": "TODO",
  12208. /* Sort Map */
  12209. "application/vnd.ms-excel.wsSortMap": "TODO",
  12210. /* Table */
  12211. "application/vnd.ms-excel.table": "TODO",
  12212. "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO",
  12213. /* Themes */
  12214. "application/vnd.openxmlformats-officedocument.theme+xml": "themes",
  12215. /* Theme Override */
  12216. "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO",
  12217. /* Timeline */
  12218. "application/vnd.ms-excel.Timeline+xml": "TODO", /* verify */
  12219. "application/vnd.ms-excel.TimelineCache+xml": "TODO", /* verify */
  12220. /* VBA */
  12221. "application/vnd.ms-office.vbaProject": "vba",
  12222. "application/vnd.ms-office.vbaProjectSignature": "vba",
  12223. /* Volatile Dependencies */
  12224. "application/vnd.ms-office.volatileDependencies": "TODO",
  12225. "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO",
  12226. /* Control Properties */
  12227. "application/vnd.ms-excel.controlproperties+xml": "TODO",
  12228. /* Data Model */
  12229. "application/vnd.openxmlformats-officedocument.model+data": "TODO",
  12230. /* Survey */
  12231. "application/vnd.ms-excel.Survey+xml": "TODO",
  12232. /* Drawing */
  12233. "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings",
  12234. "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO",
  12235. "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO",
  12236. "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO",
  12237. "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO",
  12238. "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO",
  12239. /* VML */
  12240. "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO",
  12241. "application/vnd.openxmlformats-package.relationships+xml": "rels",
  12242. "application/vnd.openxmlformats-officedocument.oleObject": "TODO",
  12243. /* Image */
  12244. "image/png": "TODO",
  12245. "sheet": "js"
  12246. });
  12247. var CT_LIST = (function(){
  12248. var o = {
  12249. workbooks: {
  12250. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
  12251. xlsm: "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
  12252. xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.main",
  12253. xlam: "application/vnd.ms-excel.addin.macroEnabled.main+xml",
  12254. xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml"
  12255. },
  12256. strs: { /* Shared Strings */
  12257. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
  12258. xlsb: "application/vnd.ms-excel.sharedStrings"
  12259. },
  12260. comments: { /* Comments */
  12261. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
  12262. xlsb: "application/vnd.ms-excel.comments"
  12263. },
  12264. sheets: { /* Worksheet */
  12265. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  12266. xlsb: "application/vnd.ms-excel.worksheet"
  12267. },
  12268. charts: { /* Chartsheet */
  12269. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml",
  12270. xlsb: "application/vnd.ms-excel.chartsheet"
  12271. },
  12272. dialogs: { /* Dialogsheet */
  12273. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml",
  12274. xlsb: "application/vnd.ms-excel.dialogsheet"
  12275. },
  12276. macros: { /* Macrosheet (Excel 4.0 Macros) */
  12277. xlsx: "application/vnd.ms-excel.macrosheet+xml",
  12278. xlsb: "application/vnd.ms-excel.macrosheet"
  12279. },
  12280. styles: { /* Styles */
  12281. xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
  12282. xlsb: "application/vnd.ms-excel.styles"
  12283. }
  12284. };
  12285. keys(o).forEach(function(k) { ["xlsm", "xlam"].forEach(function(v) { if(!o[k][v]) o[k][v] = o[k].xlsx; }); });
  12286. keys(o).forEach(function(k){ keys(o[k]).forEach(function(v) { ct2type[o[k][v]] = k; }); });
  12287. return o;
  12288. })();
  12289. var type2ct/*{[string]:Array<string>}*/ = evert_arr(ct2type);
  12290. XMLNS.CT = 'http://schemas.openxmlformats.org/package/2006/content-types';
  12291. function new_ct() {
  12292. return ({
  12293. workbooks:[], sheets:[], charts:[], dialogs:[], macros:[],
  12294. rels:[], strs:[], comments:[], links:[],
  12295. coreprops:[], extprops:[], custprops:[], themes:[], styles:[],
  12296. calcchains:[], vba: [], drawings: [],
  12297. TODO:[], xmlns: "" });
  12298. }
  12299. function parse_ct(data) {
  12300. var ct = new_ct();
  12301. if(!data || !data.match) return ct;
  12302. var ctext = {};
  12303. (data.match(tagregex)||[]).forEach(function(x) {
  12304. var y = parsexmltag(x);
  12305. switch(y[0].replace(nsregex,"<")) {
  12306. case '<?xml': break;
  12307. case '<Types': ct.xmlns = y['xmlns' + (y[0].match(/<(\w+):/)||["",""])[1] ]; break;
  12308. case '<Default': ctext[y.Extension] = y.ContentType; break;
  12309. case '<Override':
  12310. if(ct[ct2type[y.ContentType]] !== undefined) ct[ct2type[y.ContentType]].push(y.PartName);
  12311. break;
  12312. }
  12313. });
  12314. if(ct.xmlns !== XMLNS.CT) throw new Error("Unknown Namespace: " + ct.xmlns);
  12315. ct.calcchain = ct.calcchains.length > 0 ? ct.calcchains[0] : "";
  12316. ct.sst = ct.strs.length > 0 ? ct.strs[0] : "";
  12317. ct.style = ct.styles.length > 0 ? ct.styles[0] : "";
  12318. ct.defaults = ctext;
  12319. delete ct.calcchains;
  12320. return ct;
  12321. }
  12322. var CTYPE_XML_ROOT = writextag('Types', null, {
  12323. 'xmlns': XMLNS.CT,
  12324. 'xmlns:xsd': XMLNS.xsd,
  12325. 'xmlns:xsi': XMLNS.xsi
  12326. });
  12327. var CTYPE_DEFAULTS = [
  12328. ['xml', 'application/xml'],
  12329. ['bin', 'application/vnd.ms-excel.sheet.binary.macroEnabled.main'],
  12330. ['vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'],
  12331. ['data', 'application/vnd.openxmlformats-officedocument.model+data'],
  12332. /* from test files */
  12333. ['bmp', 'image/bmp'],
  12334. ['png', 'image/png'],
  12335. ['gif', 'image/gif'],
  12336. ['emf', 'image/x-emf'],
  12337. ['wmf', 'image/x-wmf'],
  12338. ['jpg', 'image/jpeg'], ['jpeg', 'image/jpeg'],
  12339. ['tif', 'image/tiff'], ['tiff', 'image/tiff'],
  12340. ['pdf', 'application/pdf'],
  12341. ['rels', type2ct.rels[0]]
  12342. ].map(function(x) {
  12343. return writextag('Default', null, {'Extension':x[0], 'ContentType': x[1]});
  12344. });
  12345. function write_ct(ct, opts) {
  12346. var o = [], v;
  12347. o[o.length] = (XML_HEADER);
  12348. o[o.length] = (CTYPE_XML_ROOT);
  12349. o = o.concat(CTYPE_DEFAULTS);
  12350. /* only write first instance */
  12351. var f1 = function(w) {
  12352. if(ct[w] && ct[w].length > 0) {
  12353. v = ct[w][0];
  12354. o[o.length] = (writextag('Override', null, {
  12355. 'PartName': (v[0] == '/' ? "":"/") + v,
  12356. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  12357. }));
  12358. }
  12359. };
  12360. /* book type-specific */
  12361. var f2 = function(w) {
  12362. (ct[w]||[]).forEach(function(v) {
  12363. o[o.length] = (writextag('Override', null, {
  12364. 'PartName': (v[0] == '/' ? "":"/") + v,
  12365. 'ContentType': CT_LIST[w][opts.bookType || 'xlsx']
  12366. }));
  12367. });
  12368. };
  12369. /* standard type */
  12370. var f3 = function(t) {
  12371. (ct[t]||[]).forEach(function(v) {
  12372. o[o.length] = (writextag('Override', null, {
  12373. 'PartName': (v[0] == '/' ? "":"/") + v,
  12374. 'ContentType': type2ct[t][0]
  12375. }));
  12376. });
  12377. };
  12378. f1('workbooks');
  12379. f2('sheets');
  12380. f2('charts');
  12381. f3('themes');
  12382. ['strs', 'styles'].forEach(f1);
  12383. ['coreprops', 'extprops', 'custprops'].forEach(f3);
  12384. f3('vba');
  12385. f3('comments');
  12386. f3('drawings');
  12387. if(o.length>2){ o[o.length] = ('</Types>'); o[1]=o[1].replace("/>",">"); }
  12388. return o.join("");
  12389. }
  12390. /* 9.3 Relationships */
  12391. var RELS = ({
  12392. WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  12393. SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
  12394. HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
  12395. VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
  12396. XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath",
  12397. XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing",
  12398. XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink",
  12399. CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",
  12400. CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps",
  12401. VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject"
  12402. });
  12403. /* 9.3.3 Representing Relationships */
  12404. function get_rels_path(file) {
  12405. var n = file.lastIndexOf("/");
  12406. return file.slice(0,n+1) + '_rels/' + file.slice(n+1) + ".rels";
  12407. }
  12408. function parse_rels(data, currentFilePath) {
  12409. var rels = {"!id":{}};
  12410. if (!data) return rels;
  12411. if (currentFilePath.charAt(0) !== '/') {
  12412. currentFilePath = '/'+currentFilePath;
  12413. }
  12414. var hash = {};
  12415. (data.match(tagregex)||[]).forEach(function(x) {
  12416. var y = parsexmltag(x);
  12417. /* 9.3.2.2 OPC_Relationships */
  12418. if (y[0] === '<Relationship') {
  12419. var rel = {}; rel.Type = y.Type; rel.Target = y.Target; rel.Id = y.Id; rel.TargetMode = y.TargetMode;
  12420. var canonictarget = y.TargetMode === 'External' ? y.Target : resolve_path(y.Target, currentFilePath);
  12421. rels[canonictarget] = rel;
  12422. hash[y.Id] = rel;
  12423. }
  12424. });
  12425. rels["!id"] = hash;
  12426. return rels;
  12427. }
  12428. XMLNS.RELS = 'http://schemas.openxmlformats.org/package/2006/relationships';
  12429. var RELS_ROOT = writextag('Relationships', null, {
  12430. //'xmlns:ns0': XMLNS.RELS,
  12431. 'xmlns': XMLNS.RELS
  12432. });
  12433. /* TODO */
  12434. function write_rels(rels) {
  12435. var o = [XML_HEADER, RELS_ROOT];
  12436. keys(rels['!id']).forEach(function(rid) {
  12437. o[o.length] = (writextag('Relationship', null, rels['!id'][rid]));
  12438. });
  12439. if(o.length>2){ o[o.length] = ('</Relationships>'); o[1]=o[1].replace("/>",">"); }
  12440. return o.join("");
  12441. }
  12442. var RELS_EXTERN = [RELS.HLINK, RELS.XPATH, RELS.XMISS];
  12443. function add_rels(rels, rId, f, type, relobj, targetmode) {
  12444. if(!relobj) relobj = {};
  12445. if(!rels['!id']) rels['!id'] = {};
  12446. if(rId < 0) for(rId = 1; rels['!id']['rId' + rId]; ++rId){/* empty */}
  12447. relobj.Id = 'rId' + rId;
  12448. relobj.Type = type;
  12449. relobj.Target = f;
  12450. if(targetmode) relobj.TargetMode = targetmode;
  12451. else if(RELS_EXTERN.indexOf(relobj.Type) > -1) relobj.TargetMode = "External";
  12452. if(rels['!id'][relobj.Id]) throw new Error("Cannot rewrite rId " + rId);
  12453. rels['!id'][relobj.Id] = relobj;
  12454. rels[('/' + relobj.Target).replace("//","/")] = relobj;
  12455. return rId;
  12456. }
  12457. /* Open Document Format for Office Applications (OpenDocument) Version 1.2 */
  12458. /* Part 3 Section 4 Manifest File */
  12459. var CT_ODS = "application/vnd.oasis.opendocument.spreadsheet";
  12460. function parse_manifest(d, opts) {
  12461. var str = xlml_normalize(d);
  12462. var Rn;
  12463. var FEtag;
  12464. while((Rn = xlmlregex.exec(str))) switch(Rn[3]) {
  12465. case 'manifest': break; // 4.2 <manifest:manifest>
  12466. case 'file-entry': // 4.3 <manifest:file-entry>
  12467. FEtag = parsexmltag(Rn[0], false);
  12468. if(FEtag.path == '/' && FEtag.type !== CT_ODS) throw new Error("This OpenDocument is not a spreadsheet");
  12469. break;
  12470. case 'encryption-data': // 4.4 <manifest:encryption-data>
  12471. case 'algorithm': // 4.5 <manifest:algorithm>
  12472. case 'start-key-generation': // 4.6 <manifest:start-key-generation>
  12473. case 'key-derivation': // 4.7 <manifest:key-derivation>
  12474. throw new Error("Unsupported ODS Encryption");
  12475. default: if(opts && opts.WTF) throw Rn;
  12476. }
  12477. }
  12478. function write_manifest(manifest) {
  12479. var o = [XML_HEADER];
  12480. o.push('<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">\n');
  12481. o.push(' <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>\n');
  12482. for(var i = 0; i < manifest.length; ++i) o.push(' <manifest:file-entry manifest:full-path="' + manifest[i][0] + '" manifest:media-type="' + manifest[i][1] + '"/>\n');
  12483. o.push('</manifest:manifest>');
  12484. return o.join("");
  12485. }
  12486. /* Part 3 Section 6 Metadata Manifest File */
  12487. function write_rdf_type(file, res, tag) {
  12488. return [
  12489. ' <rdf:Description rdf:about="' + file + '">\n',
  12490. ' <rdf:type rdf:resource="http://docs.oasis-open.org/ns/office/1.2/meta/' + (tag || "odf") + '#' + res + '"/>\n',
  12491. ' </rdf:Description>\n'
  12492. ].join("");
  12493. }
  12494. function write_rdf_has(base, file) {
  12495. return [
  12496. ' <rdf:Description rdf:about="' + base + '">\n',
  12497. ' <ns0:hasPart xmlns:ns0="http://docs.oasis-open.org/ns/office/1.2/meta/pkg#" rdf:resource="' + file + '"/>\n',
  12498. ' </rdf:Description>\n'
  12499. ].join("");
  12500. }
  12501. function write_rdf(rdf) {
  12502. var o = [XML_HEADER];
  12503. o.push('<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n');
  12504. for(var i = 0; i != rdf.length; ++i) {
  12505. o.push(write_rdf_type(rdf[i][0], rdf[i][1]));
  12506. o.push(write_rdf_has("",rdf[i][0]));
  12507. }
  12508. o.push(write_rdf_type("","Document", "pkg"));
  12509. o.push('</rdf:RDF>');
  12510. return o.join("");
  12511. }
  12512. /* TODO: pull properties */
  12513. var write_meta_ods = (function() {
  12514. var payload = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="http://www.w3.org/1999/xlink" office:version="1.2"><office:meta><meta:generator>Sheet' + 'JS ' + XLSX2.version + '</meta:generator></office:meta></office:document-meta>';
  12515. return function wmo() {
  12516. return payload;
  12517. };
  12518. })();
  12519. /* ECMA-376 Part II 11.1 Core Properties Part */
  12520. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  12521. var CORE_PROPS = [
  12522. ["cp:category", "Category"],
  12523. ["cp:contentStatus", "ContentStatus"],
  12524. ["cp:keywords", "Keywords"],
  12525. ["cp:lastModifiedBy", "LastAuthor"],
  12526. ["cp:lastPrinted", "LastPrinted"],
  12527. ["cp:revision", "RevNumber"],
  12528. ["cp:version", "Version"],
  12529. ["dc:creator", "Author"],
  12530. ["dc:description", "Comments"],
  12531. ["dc:identifier", "Identifier"],
  12532. ["dc:language", "Language"],
  12533. ["dc:subject", "Subject"],
  12534. ["dc:title", "Title"],
  12535. ["dcterms:created", "CreatedDate", 'date'],
  12536. ["dcterms:modified", "ModifiedDate", 'date']
  12537. ];
  12538. XMLNS.CORE_PROPS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
  12539. RELS.CORE_PROPS = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';
  12540. var CORE_PROPS_REGEX = (function() {
  12541. var r = new Array(CORE_PROPS.length);
  12542. for(var i = 0; i < CORE_PROPS.length; ++i) {
  12543. var f = CORE_PROPS[i];
  12544. var g = "(?:"+ f[0].slice(0,f[0].indexOf(":")) +":)"+ f[0].slice(f[0].indexOf(":")+1);
  12545. r[i] = new RegExp("<" + g + "[^>]*>([\\s\\S]*?)<\/" + g + ">");
  12546. }
  12547. return r;
  12548. })();
  12549. function parse_core_props(data) {
  12550. var p = {};
  12551. data = utf8read(data);
  12552. for(var i = 0; i < CORE_PROPS.length; ++i) {
  12553. var f = CORE_PROPS[i], cur = data.match(CORE_PROPS_REGEX[i]);
  12554. if(cur != null && cur.length > 0) p[f[1]] = unescapexml(cur[1]);
  12555. if(f[2] === 'date' && p[f[1]]) p[f[1]] = parseDate(p[f[1]]);
  12556. }
  12557. return p;
  12558. }
  12559. var CORE_PROPS_XML_ROOT = writextag('cp:coreProperties', null, {
  12560. //'xmlns': XMLNS.CORE_PROPS,
  12561. 'xmlns:cp': XMLNS.CORE_PROPS,
  12562. 'xmlns:dc': XMLNS.dc,
  12563. 'xmlns:dcterms': XMLNS.dcterms,
  12564. 'xmlns:dcmitype': XMLNS.dcmitype,
  12565. 'xmlns:xsi': XMLNS.xsi
  12566. });
  12567. function cp_doit(f, g, h, o, p) {
  12568. if(p[f] != null || g == null || g === "") return;
  12569. p[f] = g;
  12570. g = escapexml(g);
  12571. o[o.length] = (h ? writextag(f,g,h) : writetag(f,g));
  12572. }
  12573. function write_core_props(cp, _opts) {
  12574. var opts = _opts || {};
  12575. var o = [XML_HEADER, CORE_PROPS_XML_ROOT], p = {};
  12576. if(!cp && !opts.Props) return o.join("");
  12577. if(cp) {
  12578. if(cp.CreatedDate != null) cp_doit("dcterms:created", typeof cp.CreatedDate === "string" ? cp.CreatedDate : write_w3cdtf(cp.CreatedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
  12579. if(cp.ModifiedDate != null) cp_doit("dcterms:modified", typeof cp.ModifiedDate === "string" ? cp.ModifiedDate : write_w3cdtf(cp.ModifiedDate, opts.WTF), {"xsi:type":"dcterms:W3CDTF"}, o, p);
  12580. }
  12581. for(var i = 0; i != CORE_PROPS.length; ++i) {
  12582. var f = CORE_PROPS[i];
  12583. var v = opts.Props && opts.Props[f[1]] != null ? opts.Props[f[1]] : cp ? cp[f[1]] : null;
  12584. if(v === true) v = "1";
  12585. else if(v === false) v = "0";
  12586. else if(typeof v == "number") v = String(v);
  12587. if(v != null) cp_doit(f[0], v, null, o, p);
  12588. }
  12589. if(o.length>2){ o[o.length] = ('</cp:coreProperties>'); o[1]=o[1].replace("/>",">"); }
  12590. return o.join("");
  12591. }
  12592. /* 15.2.12.3 Extended File Properties Part */
  12593. /* [MS-OSHARED] 2.3.3.2.[1-2].1 (PIDSI/PIDDSI) */
  12594. var EXT_PROPS = [
  12595. ["Application", "Application", "string"],
  12596. ["AppVersion", "AppVersion", "string"],
  12597. ["Company", "Company", "string"],
  12598. ["DocSecurity", "DocSecurity", "string"],
  12599. ["Manager", "Manager", "string"],
  12600. ["HyperlinksChanged", "HyperlinksChanged", "bool"],
  12601. ["SharedDoc", "SharedDoc", "bool"],
  12602. ["LinksUpToDate", "LinksUpToDate", "bool"],
  12603. ["ScaleCrop", "ScaleCrop", "bool"],
  12604. ["HeadingPairs", "HeadingPairs", "raw"],
  12605. ["TitlesOfParts", "TitlesOfParts", "raw"]
  12606. ];
  12607. XMLNS.EXT_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
  12608. RELS.EXT_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties';
  12609. var PseudoPropsPairs = [
  12610. "Worksheets", "SheetNames",
  12611. "NamedRanges", "DefinedNames",
  12612. "Chartsheets", "ChartNames"
  12613. ];
  12614. function load_props_pairs(HP, TOP, props, opts) {
  12615. var v = [];
  12616. if(typeof HP == "string") v = parseVector(HP, opts);
  12617. else for(var j = 0; j < HP.length; ++j) v = v.concat(HP[j].map(function(hp) { return {v:hp}; }));
  12618. var parts = (typeof TOP == "string") ? parseVector(TOP, opts).map(function (x) { return x.v; }) : TOP;
  12619. var idx = 0, len = 0;
  12620. if(parts.length > 0) for(var i = 0; i !== v.length; i += 2) {
  12621. len = +(v[i+1].v);
  12622. switch(v[i].v) {
  12623. case "Worksheets":
  12624. case "工作表":
  12625. case "Листы":
  12626. case "أوراق العمل":
  12627. case "ワークシート":
  12628. case "גליונות עבודה":
  12629. case "Arbeitsblätter":
  12630. case "Çalışma Sayfaları":
  12631. case "Feuilles de calcul":
  12632. case "Fogli di lavoro":
  12633. case "Folhas de cálculo":
  12634. case "Planilhas":
  12635. case "Regneark":
  12636. case "Hojas de cálculo":
  12637. case "Werkbladen":
  12638. props.Worksheets = len;
  12639. props.SheetNames = parts.slice(idx, idx + len);
  12640. break;
  12641. case "Named Ranges":
  12642. case "Rangos con nombre":
  12643. case "名前付き一覧":
  12644. case "Benannte Bereiche":
  12645. case "Navngivne områder":
  12646. props.NamedRanges = len;
  12647. props.DefinedNames = parts.slice(idx, idx + len);
  12648. break;
  12649. case "Charts":
  12650. case "Diagramme":
  12651. props.Chartsheets = len;
  12652. props.ChartNames = parts.slice(idx, idx + len);
  12653. break;
  12654. }
  12655. idx += len;
  12656. }
  12657. }
  12658. function parse_ext_props(data, p, opts) {
  12659. var q = {}; if(!p) p = {};
  12660. data = utf8read(data);
  12661. EXT_PROPS.forEach(function(f) {
  12662. var xml = (data.match(matchtag(f[0]))||[])[1];
  12663. switch(f[2]) {
  12664. case "string": if(xml) p[f[1]] = unescapexml(xml); break;
  12665. case "bool": p[f[1]] = xml === "true"; break;
  12666. case "raw":
  12667. var cur = data.match(new RegExp("<" + f[0] + "[^>]*>([\\s\\S]*?)<\/" + f[0] + ">"));
  12668. if(cur && cur.length > 0) q[f[1]] = cur[1];
  12669. break;
  12670. }
  12671. });
  12672. if(q.HeadingPairs && q.TitlesOfParts) load_props_pairs(q.HeadingPairs, q.TitlesOfParts, p, opts);
  12673. return p;
  12674. }
  12675. var EXT_PROPS_XML_ROOT = writextag('Properties', null, {
  12676. 'xmlns': XMLNS.EXT_PROPS,
  12677. 'xmlns:vt': XMLNS.vt
  12678. });
  12679. function write_ext_props(cp) {
  12680. var o = [], W = writextag;
  12681. if(!cp) cp = {};
  12682. cp.Application = "SheetJS";
  12683. o[o.length] = (XML_HEADER);
  12684. o[o.length] = (EXT_PROPS_XML_ROOT);
  12685. EXT_PROPS.forEach(function(f) {
  12686. if(cp[f[1]] === undefined) return;
  12687. var v;
  12688. switch(f[2]) {
  12689. case 'string': v = escapexml(String(cp[f[1]])); break;
  12690. case 'bool': v = cp[f[1]] ? 'true' : 'false'; break;
  12691. }
  12692. if(v !== undefined) o[o.length] = (W(f[0], v));
  12693. });
  12694. /* TODO: HeadingPairs, TitlesOfParts */
  12695. o[o.length] = (W('HeadingPairs', W('vt:vector', W('vt:variant', '<vt:lpstr>Worksheets</vt:lpstr>')+W('vt:variant', W('vt:i4', String(cp.Worksheets))), {size:2, baseType:"variant"})));
  12696. o[o.length] = (W('TitlesOfParts', W('vt:vector', cp.SheetNames.map(function(s) { return "<vt:lpstr>" + escapexml(s) + "</vt:lpstr>"; }).join(""), {size: cp.Worksheets, baseType:"lpstr"})));
  12697. if(o.length>2){ o[o.length] = ('</Properties>'); o[1]=o[1].replace("/>",">"); }
  12698. return o.join("");
  12699. }
  12700. /* 15.2.12.2 Custom File Properties Part */
  12701. XMLNS.CUST_PROPS = "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties";
  12702. RELS.CUST_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties';
  12703. var custregex = /<[^>]+>[^<]*/g;
  12704. function parse_cust_props(data, opts) {
  12705. var p = {}, name = "";
  12706. var m = data.match(custregex);
  12707. if(m) for(var i = 0; i != m.length; ++i) {
  12708. var x = m[i], y = parsexmltag(x);
  12709. switch(y[0]) {
  12710. case '<?xml': break;
  12711. case '<Properties': break;
  12712. case '<property': name = unescapexml(y.name); break;
  12713. case '</property>': name = null; break;
  12714. default: if (x.indexOf('<vt:') === 0) {
  12715. var toks = x.split('>');
  12716. var type = toks[0].slice(4), text = toks[1];
  12717. /* 22.4.2.32 (CT_Variant). Omit the binary types from 22.4 (Variant Types) */
  12718. switch(type) {
  12719. case 'lpstr': case 'bstr': case 'lpwstr':
  12720. p[name] = unescapexml(text);
  12721. break;
  12722. case 'bool':
  12723. p[name] = parsexmlbool(text);
  12724. break;
  12725. case 'i1': case 'i2': case 'i4': case 'i8': case 'int': case 'uint':
  12726. p[name] = parseInt(text, 10);
  12727. break;
  12728. case 'r4': case 'r8': case 'decimal':
  12729. p[name] = parseFloat(text);
  12730. break;
  12731. case 'filetime': case 'date':
  12732. p[name] = parseDate(text);
  12733. break;
  12734. case 'cy': case 'error':
  12735. p[name] = unescapexml(text);
  12736. break;
  12737. default:
  12738. if(type.slice(-1) == '/') break;
  12739. if(opts.WTF && typeof console !== 'undefined') console.warn('Unexpected', x, type, toks);
  12740. }
  12741. } else if(x.slice(0,2) === "</") {/* empty */
  12742. } else if(opts.WTF) throw new Error(x);
  12743. }
  12744. }
  12745. return p;
  12746. }
  12747. var CUST_PROPS_XML_ROOT = writextag('Properties', null, {
  12748. 'xmlns': XMLNS.CUST_PROPS,
  12749. 'xmlns:vt': XMLNS.vt
  12750. });
  12751. function write_cust_props(cp) {
  12752. var o = [XML_HEADER, CUST_PROPS_XML_ROOT];
  12753. if(!cp) return o.join("");
  12754. var pid = 1;
  12755. keys(cp).forEach(function custprop(k) { ++pid;
  12756. o[o.length] = (writextag('property', write_vt(cp[k], true), {
  12757. 'fmtid': '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}',
  12758. 'pid': pid,
  12759. 'name': escapexml(k)
  12760. }));
  12761. });
  12762. if(o.length>2){ o[o.length] = '</Properties>'; o[1]=o[1].replace("/>",">"); }
  12763. return o.join("");
  12764. }
  12765. /* Common Name -> XLML Name */
  12766. var XLMLDocPropsMap = {
  12767. Title: 'Title',
  12768. Subject: 'Subject',
  12769. Author: 'Author',
  12770. Keywords: 'Keywords',
  12771. Comments: 'Description',
  12772. LastAuthor: 'LastAuthor',
  12773. RevNumber: 'Revision',
  12774. Application: 'AppName',
  12775. /* TotalTime: 'TotalTime', */
  12776. LastPrinted: 'LastPrinted',
  12777. CreatedDate: 'Created',
  12778. ModifiedDate: 'LastSaved',
  12779. /* Pages */
  12780. /* Words */
  12781. /* Characters */
  12782. Category: 'Category',
  12783. /* PresentationFormat */
  12784. Manager: 'Manager',
  12785. Company: 'Company',
  12786. /* Guid */
  12787. /* HyperlinkBase */
  12788. /* Bytes */
  12789. /* Lines */
  12790. /* Paragraphs */
  12791. /* CharactersWithSpaces */
  12792. AppVersion: 'Version',
  12793. ContentStatus: 'ContentStatus', /* NOTE: missing from schema */
  12794. Identifier: 'Identifier', /* NOTE: missing from schema */
  12795. Language: 'Language' /* NOTE: missing from schema */
  12796. };
  12797. var evert_XLMLDPM = evert(XLMLDocPropsMap);
  12798. function xlml_set_prop(Props, tag, val) {
  12799. tag = evert_XLMLDPM[tag] || tag;
  12800. Props[tag] = val;
  12801. }
  12802. function xlml_write_docprops(Props, opts) {
  12803. var o = [];
  12804. keys(XLMLDocPropsMap).map(function(m) {
  12805. for(var i = 0; i < CORE_PROPS.length; ++i) if(CORE_PROPS[i][1] == m) return CORE_PROPS[i];
  12806. for(i = 0; i < EXT_PROPS.length; ++i) if(EXT_PROPS[i][1] == m) return EXT_PROPS[i];
  12807. throw m;
  12808. }).forEach(function(p) {
  12809. if(Props[p[1]] == null) return;
  12810. var m = opts && opts.Props && opts.Props[p[1]] != null ? opts.Props[p[1]] : Props[p[1]];
  12811. switch(p[2]) {
  12812. case 'date': m = new Date(m).toISOString().replace(/\.\d*Z/,"Z"); break;
  12813. }
  12814. if(typeof m == 'number') m = String(m);
  12815. else if(m === true || m === false) { m = m ? "1" : "0"; }
  12816. else if(m instanceof Date) m = new Date(m).toISOString().replace(/\.\d*Z/,"");
  12817. o.push(writetag(XLMLDocPropsMap[p[1]] || p[1], m));
  12818. });
  12819. return writextag('DocumentProperties', o.join(""), {xmlns:XLMLNS.o });
  12820. }
  12821. function xlml_write_custprops(Props, Custprops) {
  12822. var BLACKLIST = ["Worksheets","SheetNames"];
  12823. var T = 'CustomDocumentProperties';
  12824. var o = [];
  12825. if(Props) keys(Props).forEach(function(k) {
  12826. if(!Object.prototype.hasOwnProperty.call(Props, k)) return;
  12827. for(var i = 0; i < CORE_PROPS.length; ++i) if(k == CORE_PROPS[i][1]) return;
  12828. for(i = 0; i < EXT_PROPS.length; ++i) if(k == EXT_PROPS[i][1]) return;
  12829. for(i = 0; i < BLACKLIST.length; ++i) if(k == BLACKLIST[i]) return;
  12830. var m = Props[k];
  12831. var t = "string";
  12832. if(typeof m == 'number') { t = "float"; m = String(m); }
  12833. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  12834. else m = String(m);
  12835. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  12836. });
  12837. if(Custprops) keys(Custprops).forEach(function(k) {
  12838. if(!Object.prototype.hasOwnProperty.call(Custprops, k)) return;
  12839. if(Props && Object.prototype.hasOwnProperty.call(Props, k)) return;
  12840. var m = Custprops[k];
  12841. var t = "string";
  12842. if(typeof m == 'number') { t = "float"; m = String(m); }
  12843. else if(m === true || m === false) { t = "boolean"; m = m ? "1" : "0"; }
  12844. else if(m instanceof Date) { t = "dateTime.tz"; m = m.toISOString(); }
  12845. else m = String(m);
  12846. o.push(writextag(escapexmltag(k), m, {"dt:dt":t}));
  12847. });
  12848. return '<' + T + ' xmlns="' + XLMLNS.o + '">' + o.join("") + '</' + T + '>';
  12849. }
  12850. /* [MS-DTYP] 2.3.3 FILETIME */
  12851. /* [MS-OLEDS] 2.1.3 FILETIME (Packet Version) */
  12852. /* [MS-OLEPS] 2.8 FILETIME (Packet Version) */
  12853. function parse_FILETIME(blob) {
  12854. var dwLowDateTime = blob.read_shift(4), dwHighDateTime = blob.read_shift(4);
  12855. return new Date(((dwHighDateTime/1e7*Math.pow(2,32) + dwLowDateTime/1e7) - 11644473600)*1000).toISOString().replace(/\.000/,"");
  12856. }
  12857. function write_FILETIME(time) {
  12858. var date = (typeof time == "string") ? new Date(Date.parse(time)) : time;
  12859. var t = date.getTime() / 1000 + 11644473600;
  12860. var l = t % Math.pow(2,32), h = (t - l) / Math.pow(2,32);
  12861. l *= 1e7; h *= 1e7;
  12862. var w = (l / Math.pow(2,32)) | 0;
  12863. if(w > 0) { l = l % Math.pow(2,32); h += w; }
  12864. var o = new_buf(8); o.write_shift(4, l); o.write_shift(4, h); return o;
  12865. }
  12866. /* [MS-OSHARED] 2.3.3.1.4 Lpstr */
  12867. function parse_lpstr(blob, type, pad) {
  12868. var start = blob.l;
  12869. var str = blob.read_shift(0, 'lpstr-cp');
  12870. if(pad) while((blob.l - start) & 3) ++blob.l;
  12871. return str;
  12872. }
  12873. /* [MS-OSHARED] 2.3.3.1.6 Lpwstr */
  12874. function parse_lpwstr(blob, type, pad) {
  12875. var str = blob.read_shift(0, 'lpwstr');
  12876. if(pad) blob.l += (4 - ((str.length+1) & 3)) & 3;
  12877. return str;
  12878. }
  12879. /* [MS-OSHARED] 2.3.3.1.11 VtString */
  12880. /* [MS-OSHARED] 2.3.3.1.12 VtUnalignedString */
  12881. function parse_VtStringBase(blob, stringType, pad) {
  12882. if(stringType === 0x1F /*VT_LPWSTR*/) return parse_lpwstr(blob);
  12883. return parse_lpstr(blob, stringType, pad);
  12884. }
  12885. function parse_VtString(blob, t, pad) { return parse_VtStringBase(blob, t, pad === false ? 0: 4); }
  12886. function parse_VtUnalignedString(blob, t) { if(!t) throw new Error("VtUnalignedString must have positive length"); return parse_VtStringBase(blob, t, 0); }
  12887. /* [MS-OSHARED] 2.3.3.1.9 VtVecUnalignedLpstrValue */
  12888. function parse_VtVecUnalignedLpstrValue(blob) {
  12889. var length = blob.read_shift(4);
  12890. var ret = [];
  12891. for(var i = 0; i != length; ++i) ret[i] = blob.read_shift(0, 'lpstr-cp').replace(chr0,'');
  12892. return ret;
  12893. }
  12894. /* [MS-OSHARED] 2.3.3.1.10 VtVecUnalignedLpstr */
  12895. function parse_VtVecUnalignedLpstr(blob) {
  12896. return parse_VtVecUnalignedLpstrValue(blob);
  12897. }
  12898. /* [MS-OSHARED] 2.3.3.1.13 VtHeadingPair */
  12899. function parse_VtHeadingPair(blob) {
  12900. var headingString = parse_TypedPropertyValue(blob, VT_USTR);
  12901. var headerParts = parse_TypedPropertyValue(blob, VT_I4);
  12902. return [headingString, headerParts];
  12903. }
  12904. /* [MS-OSHARED] 2.3.3.1.14 VtVecHeadingPairValue */
  12905. function parse_VtVecHeadingPairValue(blob) {
  12906. var cElements = blob.read_shift(4);
  12907. var out = [];
  12908. for(var i = 0; i != cElements / 2; ++i) out.push(parse_VtHeadingPair(blob));
  12909. return out;
  12910. }
  12911. /* [MS-OSHARED] 2.3.3.1.15 VtVecHeadingPair */
  12912. function parse_VtVecHeadingPair(blob) {
  12913. // NOTE: When invoked, wType & padding were already consumed
  12914. return parse_VtVecHeadingPairValue(blob);
  12915. }
  12916. /* [MS-OLEPS] 2.18.1 Dictionary (uses 2.17, 2.16) */
  12917. function parse_dictionary(blob,CodePage) {
  12918. var cnt = blob.read_shift(4);
  12919. var dict = ({});
  12920. for(var j = 0; j != cnt; ++j) {
  12921. var pid = blob.read_shift(4);
  12922. var len = blob.read_shift(4);
  12923. dict[pid] = blob.read_shift(len, (CodePage === 0x4B0 ?'utf16le':'utf8')).replace(chr0,'').replace(chr1,'!');
  12924. if(CodePage === 0x4B0 && (len % 2)) blob.l += 2;
  12925. }
  12926. if(blob.l & 3) blob.l = (blob.l>>2+1)<<2;
  12927. return dict;
  12928. }
  12929. /* [MS-OLEPS] 2.9 BLOB */
  12930. function parse_BLOB(blob) {
  12931. var size = blob.read_shift(4);
  12932. var bytes = blob.slice(blob.l,blob.l+size);
  12933. blob.l += size;
  12934. if((size & 3) > 0) blob.l += (4 - (size & 3)) & 3;
  12935. return bytes;
  12936. }
  12937. /* [MS-OLEPS] 2.11 ClipboardData */
  12938. function parse_ClipboardData(blob) {
  12939. // TODO
  12940. var o = {};
  12941. o.Size = blob.read_shift(4);
  12942. //o.Format = blob.read_shift(4);
  12943. blob.l += o.Size + 3 - (o.Size - 1) % 4;
  12944. return o;
  12945. }
  12946. /* [MS-OLEPS] 2.15 TypedPropertyValue */
  12947. function parse_TypedPropertyValue(blob, type, _opts) {
  12948. var t = blob.read_shift(2), ret, opts = _opts||{};
  12949. blob.l += 2;
  12950. if(type !== VT_VARIANT)
  12951. if(t !== type && VT_CUSTOM.indexOf(type)===-1) throw new Error('Expected type ' + type + ' saw ' + t);
  12952. switch(type === VT_VARIANT ? t : type) {
  12953. case 0x02 /*VT_I2*/: ret = blob.read_shift(2, 'i'); if(!opts.raw) blob.l += 2; return ret;
  12954. case 0x03 /*VT_I4*/: ret = blob.read_shift(4, 'i'); return ret;
  12955. case 0x0B /*VT_BOOL*/: return blob.read_shift(4) !== 0x0;
  12956. case 0x13 /*VT_UI4*/: ret = blob.read_shift(4); return ret;
  12957. case 0x1E /*VT_LPSTR*/: return parse_lpstr(blob, t, 4).replace(chr0,'');
  12958. case 0x1F /*VT_LPWSTR*/: return parse_lpwstr(blob);
  12959. case 0x40 /*VT_FILETIME*/: return parse_FILETIME(blob);
  12960. case 0x41 /*VT_BLOB*/: return parse_BLOB(blob);
  12961. case 0x47 /*VT_CF*/: return parse_ClipboardData(blob);
  12962. case 0x50 /*VT_STRING*/: return parse_VtString(blob, t, !opts.raw).replace(chr0,'');
  12963. case 0x51 /*VT_USTR*/: return parse_VtUnalignedString(blob, t/*, 4*/).replace(chr0,'');
  12964. case 0x100C /*VT_VECTOR|VT_VARIANT*/: return parse_VtVecHeadingPair(blob);
  12965. case 0x101E /*VT_LPSTR*/: return parse_VtVecUnalignedLpstr(blob);
  12966. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + t);
  12967. }
  12968. }
  12969. function write_TypedPropertyValue(type, value) {
  12970. var o = new_buf(4), p = new_buf(4);
  12971. o.write_shift(4, type == 0x50 ? 0x1F : type);
  12972. switch(type) {
  12973. case 0x03 /*VT_I4*/: p.write_shift(-4, value); break;
  12974. case 0x05 /*VT_I4*/: p = new_buf(8); p.write_shift(8, value, 'f'); break;
  12975. case 0x0B /*VT_BOOL*/: p.write_shift(4, value ? 0x01 : 0x00); break;
  12976. case 0x40 /*VT_FILETIME*/: p = write_FILETIME(value); break;
  12977. case 0x1F /*VT_LPWSTR*/:
  12978. case 0x50 /*VT_STRING*/:
  12979. p = new_buf(4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  12980. p.write_shift(4, value.length + 1);
  12981. p.write_shift(0, value, "dbcs");
  12982. while(p.l != p.length) p.write_shift(1, 0);
  12983. break;
  12984. default: throw new Error("TypedPropertyValue unrecognized type " + type + " " + value);
  12985. }
  12986. return bconcat([o, p]);
  12987. }
  12988. /* [MS-OLEPS] 2.20 PropertySet */
  12989. function parse_PropertySet(blob, PIDSI) {
  12990. var start_addr = blob.l;
  12991. var size = blob.read_shift(4);
  12992. var NumProps = blob.read_shift(4);
  12993. var Props = [], i = 0;
  12994. var CodePage = 0;
  12995. var Dictionary = -1, DictObj = ({});
  12996. for(i = 0; i != NumProps; ++i) {
  12997. var PropID = blob.read_shift(4);
  12998. var Offset = blob.read_shift(4);
  12999. Props[i] = [PropID, Offset + start_addr];
  13000. }
  13001. Props.sort(function(x,y) { return x[1] - y[1]; });
  13002. var PropH = {};
  13003. for(i = 0; i != NumProps; ++i) {
  13004. if(blob.l !== Props[i][1]) {
  13005. var fail = true;
  13006. if(i>0 && PIDSI) switch(PIDSI[Props[i-1][0]].t) {
  13007. case 0x02 /*VT_I2*/: if(blob.l+2 === Props[i][1]) { blob.l+=2; fail = false; } break;
  13008. case 0x50 /*VT_STRING*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  13009. case 0x100C /*VT_VECTOR|VT_VARIANT*/: if(blob.l <= Props[i][1]) { blob.l=Props[i][1]; fail = false; } break;
  13010. }
  13011. if((!PIDSI||i==0) && blob.l <= Props[i][1]) { fail=false; blob.l = Props[i][1]; }
  13012. if(fail) throw new Error("Read Error: Expected address " + Props[i][1] + ' at ' + blob.l + ' :' + i);
  13013. }
  13014. if(PIDSI) {
  13015. var piddsi = PIDSI[Props[i][0]];
  13016. PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, {raw:true});
  13017. if(piddsi.p === 'version') PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 0xFFFF)).slice(-4);
  13018. if(piddsi.n == "CodePage") switch(PropH[piddsi.n]) {
  13019. case 0: PropH[piddsi.n] = 1252;
  13020. /* falls through */
  13021. case 874:
  13022. case 932:
  13023. case 936:
  13024. case 949:
  13025. case 950:
  13026. case 1250:
  13027. case 1251:
  13028. case 1253:
  13029. case 1254:
  13030. case 1255:
  13031. case 1256:
  13032. case 1257:
  13033. case 1258:
  13034. case 10000:
  13035. case 1200:
  13036. case 1201:
  13037. case 1252:
  13038. case 65000: case -536:
  13039. case 65001: case -535:
  13040. set_cp(CodePage = (PropH[piddsi.n]>>>0) & 0xFFFF); break;
  13041. default: throw new Error("Unsupported CodePage: " + PropH[piddsi.n]);
  13042. }
  13043. } else {
  13044. if(Props[i][0] === 0x1) {
  13045. CodePage = PropH.CodePage = (parse_TypedPropertyValue(blob, VT_I2));
  13046. set_cp(CodePage);
  13047. if(Dictionary !== -1) {
  13048. var oldpos = blob.l;
  13049. blob.l = Props[Dictionary][1];
  13050. DictObj = parse_dictionary(blob,CodePage);
  13051. blob.l = oldpos;
  13052. }
  13053. } else if(Props[i][0] === 0) {
  13054. if(CodePage === 0) { Dictionary = i; blob.l = Props[i+1][1]; continue; }
  13055. DictObj = parse_dictionary(blob,CodePage);
  13056. } else {
  13057. var name = DictObj[Props[i][0]];
  13058. var val;
  13059. /* [MS-OSHARED] 2.3.3.2.3.1.2 + PROPVARIANT */
  13060. switch(blob[blob.l]) {
  13061. case 0x41 /*VT_BLOB*/: blob.l += 4; val = parse_BLOB(blob); break;
  13062. case 0x1E /*VT_LPSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  13063. case 0x1F /*VT_LPWSTR*/: blob.l += 4; val = parse_VtString(blob, blob[blob.l-4]).replace(/\u0000+$/,""); break;
  13064. case 0x03 /*VT_I4*/: blob.l += 4; val = blob.read_shift(4, 'i'); break;
  13065. case 0x13 /*VT_UI4*/: blob.l += 4; val = blob.read_shift(4); break;
  13066. case 0x05 /*VT_R8*/: blob.l += 4; val = blob.read_shift(8, 'f'); break;
  13067. case 0x0B /*VT_BOOL*/: blob.l += 4; val = parsebool(blob, 4); break;
  13068. case 0x40 /*VT_FILETIME*/: blob.l += 4; val = parseDate(parse_FILETIME(blob)); break;
  13069. default: throw new Error("unparsed value: " + blob[blob.l]);
  13070. }
  13071. PropH[name] = val;
  13072. }
  13073. }
  13074. }
  13075. blob.l = start_addr + size; /* step ahead to skip padding */
  13076. return PropH;
  13077. }
  13078. var XLSPSSkip = [ "CodePage", "Thumbnail", "_PID_LINKBASE", "_PID_HLINKS", "SystemIdentifier", "FMTID" ].concat(PseudoPropsPairs);
  13079. function guess_property_type(val) {
  13080. switch(typeof val) {
  13081. case "boolean": return 0x0B;
  13082. case "number": return ((val|0)==val) ? 0x03 : 0x05;
  13083. case "string": return 0x1F;
  13084. case "object": if(val instanceof Date) return 0x40; break;
  13085. }
  13086. return -1;
  13087. }
  13088. function write_PropertySet(entries, RE, PIDSI) {
  13089. var hdr = new_buf(8), piao = [], prop = [];
  13090. var sz = 8, i = 0;
  13091. var pr = new_buf(8), pio = new_buf(8);
  13092. pr.write_shift(4, 0x0002);
  13093. pr.write_shift(4, 0x04B0);
  13094. pio.write_shift(4, 0x0001);
  13095. prop.push(pr); piao.push(pio);
  13096. sz += 8 + pr.length;
  13097. if(!RE) {
  13098. pio = new_buf(8);
  13099. pio.write_shift(4, 0);
  13100. piao.unshift(pio);
  13101. var bufs = [new_buf(4)];
  13102. bufs[0].write_shift(4, entries.length);
  13103. for(i = 0; i < entries.length; ++i) {
  13104. var value = entries[i][0];
  13105. pr = new_buf(4 + 4 + 2 * (value.length + 1) + (value.length % 2 ? 0 : 2));
  13106. pr.write_shift(4, i+2);
  13107. pr.write_shift(4, value.length + 1);
  13108. pr.write_shift(0, value, "dbcs");
  13109. while(pr.l != pr.length) pr.write_shift(1, 0);
  13110. bufs.push(pr);
  13111. }
  13112. pr = bconcat(bufs);
  13113. prop.unshift(pr);
  13114. sz += 8 + pr.length;
  13115. }
  13116. for(i = 0; i < entries.length; ++i) {
  13117. if(RE && !RE[entries[i][0]]) continue;
  13118. if(XLSPSSkip.indexOf(entries[i][0]) > -1) continue;
  13119. if(entries[i][1] == null) continue;
  13120. var val = entries[i][1], idx = 0;
  13121. if(RE) {
  13122. idx = +RE[entries[i][0]];
  13123. var pinfo = (PIDSI)[idx];
  13124. if(pinfo.p == "version" && typeof val == "string") {
  13125. var arr = val.split(".");
  13126. val = ((+arr[0])<<16) + ((+arr[1])||0);
  13127. }
  13128. pr = write_TypedPropertyValue(pinfo.t, val);
  13129. } else {
  13130. var T = guess_property_type(val);
  13131. if(T == -1) { T = 0x1F; val = String(val); }
  13132. pr = write_TypedPropertyValue(T, val);
  13133. }
  13134. prop.push(pr);
  13135. pio = new_buf(8);
  13136. pio.write_shift(4, !RE ? 2+i : idx);
  13137. piao.push(pio);
  13138. sz += 8 + pr.length;
  13139. }
  13140. var w = 8 * (prop.length + 1);
  13141. for(i = 0; i < prop.length; ++i) { piao[i].write_shift(4, w); w += prop[i].length; }
  13142. hdr.write_shift(4, sz);
  13143. hdr.write_shift(4, prop.length);
  13144. return bconcat([hdr].concat(piao).concat(prop));
  13145. }
  13146. /* [MS-OLEPS] 2.21 PropertySetStream */
  13147. function parse_PropertySetStream(file, PIDSI, clsid) {
  13148. var blob = file.content;
  13149. if(!blob) return ({});
  13150. prep_blob(blob, 0);
  13151. var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0;
  13152. blob.chk('feff', 'Byte Order: ');
  13153. /*var vers = */blob.read_shift(2); // TODO: check version
  13154. var SystemIdentifier = blob.read_shift(4);
  13155. var CLSID = blob.read_shift(16);
  13156. if(CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID);
  13157. NumSets = blob.read_shift(4);
  13158. if(NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets);
  13159. FMTID0 = blob.read_shift(16); Offset0 = blob.read_shift(4);
  13160. if(NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l);
  13161. else if(NumSets === 2) { FMTID1 = blob.read_shift(16); Offset1 = blob.read_shift(4); }
  13162. var PSet0 = parse_PropertySet(blob, PIDSI);
  13163. var rval = ({ SystemIdentifier: SystemIdentifier });
  13164. for(var y in PSet0) rval[y] = PSet0[y];
  13165. //rval.blob = blob;
  13166. rval.FMTID = FMTID0;
  13167. //rval.PSet0 = PSet0;
  13168. if(NumSets === 1) return rval;
  13169. if(Offset1 - blob.l == 2) blob.l += 2;
  13170. if(blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1);
  13171. var PSet1;
  13172. try { PSet1 = parse_PropertySet(blob, null); } catch(e) {/* empty */}
  13173. for(y in PSet1) rval[y] = PSet1[y];
  13174. rval.FMTID = [FMTID0, FMTID1]; // TODO: verify FMTID0/1
  13175. return rval;
  13176. }
  13177. function write_PropertySetStream(entries, clsid, RE, PIDSI, entries2, clsid2) {
  13178. var hdr = new_buf(entries2 ? 68 : 48);
  13179. var bufs = [hdr];
  13180. hdr.write_shift(2, 0xFFFE);
  13181. hdr.write_shift(2, 0x0000); /* TODO: type 1 props */
  13182. hdr.write_shift(4, 0x32363237);
  13183. hdr.write_shift(16, CFB.utils.consts.HEADER_CLSID, "hex");
  13184. hdr.write_shift(4, (entries2 ? 2 : 1));
  13185. hdr.write_shift(16, clsid, "hex");
  13186. hdr.write_shift(4, (entries2 ? 68 : 48));
  13187. var ps0 = write_PropertySet(entries, RE, PIDSI);
  13188. bufs.push(ps0);
  13189. if(entries2) {
  13190. var ps1 = write_PropertySet(entries2, null, null);
  13191. hdr.write_shift(16, clsid2, "hex");
  13192. hdr.write_shift(4, 68 + ps0.length);
  13193. bufs.push(ps1);
  13194. }
  13195. return bconcat(bufs);
  13196. }
  13197. function parsenoop2(blob, length) { blob.read_shift(length); return null; }
  13198. function writezeroes(n, o) { if(!o) o=new_buf(n); for(var j=0; j<n; ++j) o.write_shift(1, 0); return o; }
  13199. function parslurp(blob, length, cb) {
  13200. var arr = [], target = blob.l + length;
  13201. while(blob.l < target) arr.push(cb(blob, target - blob.l));
  13202. if(target !== blob.l) throw new Error("Slurp error");
  13203. return arr;
  13204. }
  13205. function parsebool(blob, length) { return blob.read_shift(length) === 0x1; }
  13206. function writebool(v, o) { if(!o) o=new_buf(2); o.write_shift(2, +!!v); return o; }
  13207. function parseuint16(blob) { return blob.read_shift(2, 'u'); }
  13208. function writeuint16(v, o) { if(!o) o=new_buf(2); o.write_shift(2, v); return o; }
  13209. function parseuint16a(blob, length) { return parslurp(blob,length,parseuint16);}
  13210. /* --- 2.5 Structures --- */
  13211. /* [MS-XLS] 2.5.10 Bes (boolean or error) */
  13212. function parse_Bes(blob) {
  13213. var v = blob.read_shift(1), t = blob.read_shift(1);
  13214. return t === 0x01 ? v : v === 0x01;
  13215. }
  13216. function write_Bes(v, t, o) {
  13217. if(!o) o = new_buf(2);
  13218. o.write_shift(1, +v);
  13219. o.write_shift(1, ((t == 'e') ? 1 : 0));
  13220. return o;
  13221. }
  13222. /* [MS-XLS] 2.5.240 ShortXLUnicodeString */
  13223. function parse_ShortXLUnicodeString(blob, length, opts) {
  13224. var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1);
  13225. var encoding = 'sbcs-cont';
  13226. var cp = current_codepage;
  13227. if(opts && opts.biff >= 8) current_codepage = 1200;
  13228. if(!opts || opts.biff == 8 ) {
  13229. var fHighByte = blob.read_shift(1);
  13230. if(fHighByte) { encoding = 'dbcs-cont'; }
  13231. } else if(opts.biff == 12) {
  13232. encoding = 'wstr';
  13233. }
  13234. if(opts.biff >= 2 && opts.biff <= 5) encoding = 'cpstr';
  13235. var o = cch ? blob.read_shift(cch, encoding) : "";
  13236. current_codepage = cp;
  13237. return o;
  13238. }
  13239. /* 2.5.293 XLUnicodeRichExtendedString */
  13240. function parse_XLUnicodeRichExtendedString(blob) {
  13241. var cp = current_codepage;
  13242. current_codepage = 1200;
  13243. var cch = blob.read_shift(2), flags = blob.read_shift(1);
  13244. var /*fHighByte = flags & 0x1,*/ fExtSt = flags & 0x4, fRichSt = flags & 0x8;
  13245. var width = 1 + (flags & 0x1); // 0x0 -> utf8, 0x1 -> dbcs
  13246. var cRun = 0, cbExtRst;
  13247. var z = {};
  13248. if(fRichSt) cRun = blob.read_shift(2);
  13249. if(fExtSt) cbExtRst = blob.read_shift(4);
  13250. var encoding = width == 2 ? 'dbcs-cont' : 'sbcs-cont';
  13251. var msg = cch === 0 ? "" : blob.read_shift(cch, encoding);
  13252. if(fRichSt) blob.l += 4 * cRun; //TODO: parse this
  13253. if(fExtSt) blob.l += cbExtRst; //TODO: parse this
  13254. z.t = msg;
  13255. if(!fRichSt) { z.raw = "<t>" + z.t + "</t>"; z.r = z.t; }
  13256. current_codepage = cp;
  13257. return z;
  13258. }
  13259. function write_XLUnicodeRichExtendedString(xlstr) {
  13260. var str = (xlstr.t||""), nfmts = 1;
  13261. var hdr = new_buf(3 + (nfmts > 1 ? 2 : 0));
  13262. hdr.write_shift(2, str.length);
  13263. hdr.write_shift(1, (nfmts > 1 ? 0x08 : 0x00) | 0x01);
  13264. if(nfmts > 1) hdr.write_shift(2, nfmts);
  13265. var otext = new_buf(2 * str.length);
  13266. otext.write_shift(2 * str.length, str, 'utf16le');
  13267. var out = [hdr, otext];
  13268. return bconcat(out);
  13269. }
  13270. /* 2.5.296 XLUnicodeStringNoCch */
  13271. function parse_XLUnicodeStringNoCch(blob, cch, opts) {
  13272. var retval;
  13273. if(opts) {
  13274. if(opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, 'cpstr');
  13275. if(opts.biff >= 12) return blob.read_shift(cch, 'dbcs-cont');
  13276. }
  13277. var fHighByte = blob.read_shift(1);
  13278. if(fHighByte===0) { retval = blob.read_shift(cch, 'sbcs-cont'); }
  13279. else { retval = blob.read_shift(cch, 'dbcs-cont'); }
  13280. return retval;
  13281. }
  13282. /* 2.5.294 XLUnicodeString */
  13283. function parse_XLUnicodeString(blob, length, opts) {
  13284. var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  13285. if(cch === 0) { blob.l++; return ""; }
  13286. return parse_XLUnicodeStringNoCch(blob, cch, opts);
  13287. }
  13288. /* BIFF5 override */
  13289. function parse_XLUnicodeString2(blob, length, opts) {
  13290. if(opts.biff > 5) return parse_XLUnicodeString(blob, length, opts);
  13291. var cch = blob.read_shift(1);
  13292. if(cch === 0) { blob.l++; return ""; }
  13293. return blob.read_shift(cch, (opts.biff <= 4 || !blob.lens ) ? 'cpstr' : 'sbcs-cont');
  13294. }
  13295. /* TODO: BIFF5 and lower, codepage awareness */
  13296. function write_XLUnicodeString(str, opts, o) {
  13297. if(!o) o = new_buf(3 + 2 * str.length);
  13298. o.write_shift(2, str.length);
  13299. o.write_shift(1, 1);
  13300. o.write_shift(31, str, 'utf16le');
  13301. return o;
  13302. }
  13303. /* [MS-XLS] 2.5.61 ControlInfo */
  13304. function parse_ControlInfo(blob) {
  13305. var flags = blob.read_shift(1);
  13306. blob.l++;
  13307. var accel = blob.read_shift(2);
  13308. blob.l += 2;
  13309. return [flags, accel];
  13310. }
  13311. /* [MS-OSHARED] 2.3.7.6 URLMoniker TODO: flags */
  13312. function parse_URLMoniker(blob) {
  13313. var len = blob.read_shift(4), start = blob.l;
  13314. var extra = false;
  13315. if(len > 24) {
  13316. /* look ahead */
  13317. blob.l += len - 24;
  13318. if(blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true;
  13319. blob.l = start;
  13320. }
  13321. var url = blob.read_shift((extra?len-24:len)>>1, 'utf16le').replace(chr0,"");
  13322. if(extra) blob.l += 24;
  13323. return url;
  13324. }
  13325. /* [MS-OSHARED] 2.3.7.8 FileMoniker TODO: all fields */
  13326. function parse_FileMoniker(blob) {
  13327. blob.l += 2; //var cAnti = blob.read_shift(2);
  13328. var ansiPath = blob.read_shift(0, 'lpstr-ansi');
  13329. blob.l += 2; //var endServer = blob.read_shift(2);
  13330. if(blob.read_shift(2) != 0xDEAD) throw new Error("Bad FileMoniker");
  13331. var sz = blob.read_shift(4);
  13332. if(sz === 0) return ansiPath.replace(/\\/g,"/");
  13333. var bytes = blob.read_shift(4);
  13334. if(blob.read_shift(2) != 3) throw new Error("Bad FileMoniker");
  13335. var unicodePath = blob.read_shift(bytes>>1, 'utf16le').replace(chr0,"");
  13336. return unicodePath;
  13337. }
  13338. /* [MS-OSHARED] 2.3.7.2 HyperlinkMoniker TODO: all the monikers */
  13339. function parse_HyperlinkMoniker(blob, length) {
  13340. var clsid = blob.read_shift(16); length -= 16;
  13341. switch(clsid) {
  13342. case "e0c9ea79f9bace118c8200aa004ba90b": return parse_URLMoniker(blob, length);
  13343. case "0303000000000000c000000000000046": return parse_FileMoniker(blob, length);
  13344. default: throw new Error("Unsupported Moniker " + clsid);
  13345. }
  13346. }
  13347. /* [MS-OSHARED] 2.3.7.9 HyperlinkString */
  13348. function parse_HyperlinkString(blob) {
  13349. var len = blob.read_shift(4);
  13350. var o = len > 0 ? blob.read_shift(len, 'utf16le').replace(chr0, "") : "";
  13351. return o;
  13352. }
  13353. /* [MS-OSHARED] 2.3.7.1 Hyperlink Object */
  13354. function parse_Hyperlink(blob, length) {
  13355. var end = blob.l + length;
  13356. var sVer = blob.read_shift(4);
  13357. if(sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer);
  13358. var flags = blob.read_shift(2);
  13359. blob.l += 2;
  13360. var displayName, targetFrameName, moniker, oleMoniker, Loc="", guid, fileTime;
  13361. if(flags & 0x0010) displayName = parse_HyperlinkString(blob, end - blob.l);
  13362. if(flags & 0x0080) targetFrameName = parse_HyperlinkString(blob, end - blob.l);
  13363. if((flags & 0x0101) === 0x0101) moniker = parse_HyperlinkString(blob, end - blob.l);
  13364. if((flags & 0x0101) === 0x0001) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l);
  13365. if(flags & 0x0008) Loc = parse_HyperlinkString(blob, end - blob.l);
  13366. if(flags & 0x0020) guid = blob.read_shift(16);
  13367. if(flags & 0x0040) fileTime = parse_FILETIME(blob/*, 8*/);
  13368. blob.l = end;
  13369. var target = targetFrameName||moniker||oleMoniker||"";
  13370. if(target && Loc) target+="#"+Loc;
  13371. if(!target) target = "#" + Loc;
  13372. var out = ({Target:target});
  13373. if(guid) out.guid = guid;
  13374. if(fileTime) out.time = fileTime;
  13375. if(displayName) out.Tooltip = displayName;
  13376. return out;
  13377. }
  13378. function write_Hyperlink(hl) {
  13379. var out = new_buf(512), i = 0;
  13380. var Target = hl.Target;
  13381. var F = Target.indexOf("#") > -1 ? 0x1f : 0x17;
  13382. switch(Target.charAt(0)) { case "#": F=0x1c; break; case ".": F&=~2; break; }
  13383. out.write_shift(4,2); out.write_shift(4, F);
  13384. var data = [8,6815827,6619237,4849780,83]; for(i = 0; i < data.length; ++i) out.write_shift(4, data[i]);
  13385. if(F == 0x1C) {
  13386. Target = Target.slice(1);
  13387. out.write_shift(4, Target.length + 1);
  13388. for(i = 0; i < Target.length; ++i) out.write_shift(2, Target.charCodeAt(i));
  13389. out.write_shift(2, 0);
  13390. } else if(F & 0x02) {
  13391. data = "e0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  13392. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  13393. out.write_shift(4, 2*(Target.length + 1));
  13394. for(i = 0; i < Target.length; ++i) out.write_shift(2, Target.charCodeAt(i));
  13395. out.write_shift(2, 0);
  13396. } else {
  13397. data = "03 03 00 00 00 00 00 00 c0 00 00 00 00 00 00 46".split(" ");
  13398. for(i = 0; i < data.length; ++i) out.write_shift(1, parseInt(data[i], 16));
  13399. var P = 0;
  13400. while(Target.slice(P*3,P*3+3)=="../"||Target.slice(P*3,P*3+3)=="..\\") ++P;
  13401. out.write_shift(2, P);
  13402. out.write_shift(4, Target.length + 1);
  13403. for(i = 0; i < Target.length; ++i) out.write_shift(1, Target.charCodeAt(i) & 0xFF);
  13404. out.write_shift(1, 0);
  13405. out.write_shift(2, 0xFFFF);
  13406. out.write_shift(2, 0xDEAD);
  13407. for(i = 0; i < 6; ++i) out.write_shift(4, 0);
  13408. }
  13409. return out.slice(0, out.l);
  13410. }
  13411. /* 2.5.178 LongRGBA */
  13412. function parse_LongRGBA(blob) { var r = blob.read_shift(1), g = blob.read_shift(1), b = blob.read_shift(1), a = blob.read_shift(1); return [r,g,b,a]; }
  13413. /* 2.5.177 LongRGB */
  13414. function parse_LongRGB(blob, length) { var x = parse_LongRGBA(blob, length); x[3] = 0; return x; }
  13415. /* [MS-XLS] 2.5.19 */
  13416. function parse_XLSCell(blob) {
  13417. var rw = blob.read_shift(2); // 0-indexed
  13418. var col = blob.read_shift(2);
  13419. var ixfe = blob.read_shift(2);
  13420. return ({r:rw, c:col, ixfe:ixfe});
  13421. }
  13422. function write_XLSCell(R, C, ixfe, o) {
  13423. if(!o) o = new_buf(6);
  13424. o.write_shift(2, R);
  13425. o.write_shift(2, C);
  13426. o.write_shift(2, ixfe||0);
  13427. return o;
  13428. }
  13429. /* [MS-XLS] 2.5.134 */
  13430. function parse_frtHeader(blob) {
  13431. var rt = blob.read_shift(2);
  13432. var flags = blob.read_shift(2); // TODO: parse these flags
  13433. blob.l += 8;
  13434. return {type: rt, flags: flags};
  13435. }
  13436. function parse_OptXLUnicodeString(blob, length, opts) { return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts); }
  13437. /* [MS-XLS] 2.5.344 */
  13438. function parse_XTI(blob, length, opts) {
  13439. var w = opts.biff > 8 ? 4 : 2;
  13440. var iSupBook = blob.read_shift(w), itabFirst = blob.read_shift(w,'i'), itabLast = blob.read_shift(w,'i');
  13441. return [iSupBook, itabFirst, itabLast];
  13442. }
  13443. /* [MS-XLS] 2.5.218 */
  13444. function parse_RkRec(blob) {
  13445. var ixfe = blob.read_shift(2);
  13446. var RK = parse_RkNumber(blob);
  13447. return [ixfe, RK];
  13448. }
  13449. /* [MS-XLS] 2.5.1 */
  13450. function parse_AddinUdf(blob, length, opts) {
  13451. blob.l += 4; length -= 4;
  13452. var l = blob.l + length;
  13453. var udfName = parse_ShortXLUnicodeString(blob, length, opts);
  13454. var cb = blob.read_shift(2);
  13455. l -= blob.l;
  13456. if(cb !== l) throw new Error("Malformed AddinUdf: padding = " + l + " != " + cb);
  13457. blob.l += cb;
  13458. return udfName;
  13459. }
  13460. /* [MS-XLS] 2.5.209 TODO: Check sizes */
  13461. function parse_Ref8U(blob) {
  13462. var rwFirst = blob.read_shift(2);
  13463. var rwLast = blob.read_shift(2);
  13464. var colFirst = blob.read_shift(2);
  13465. var colLast = blob.read_shift(2);
  13466. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  13467. }
  13468. function write_Ref8U(r, o) {
  13469. if(!o) o = new_buf(8);
  13470. o.write_shift(2, r.s.r);
  13471. o.write_shift(2, r.e.r);
  13472. o.write_shift(2, r.s.c);
  13473. o.write_shift(2, r.e.c);
  13474. return o;
  13475. }
  13476. /* [MS-XLS] 2.5.211 */
  13477. function parse_RefU(blob) {
  13478. var rwFirst = blob.read_shift(2);
  13479. var rwLast = blob.read_shift(2);
  13480. var colFirst = blob.read_shift(1);
  13481. var colLast = blob.read_shift(1);
  13482. return {s:{c:colFirst, r:rwFirst}, e:{c:colLast,r:rwLast}};
  13483. }
  13484. /* [MS-XLS] 2.5.207 */
  13485. var parse_Ref = parse_RefU;
  13486. /* [MS-XLS] 2.5.143 */
  13487. function parse_FtCmo(blob) {
  13488. blob.l += 4;
  13489. var ot = blob.read_shift(2);
  13490. var id = blob.read_shift(2);
  13491. var flags = blob.read_shift(2);
  13492. blob.l+=12;
  13493. return [id, ot, flags];
  13494. }
  13495. /* [MS-XLS] 2.5.149 */
  13496. function parse_FtNts(blob) {
  13497. var out = {};
  13498. blob.l += 4;
  13499. blob.l += 16; // GUID TODO
  13500. out.fSharedNote = blob.read_shift(2);
  13501. blob.l += 4;
  13502. return out;
  13503. }
  13504. /* [MS-XLS] 2.5.142 */
  13505. function parse_FtCf(blob) {
  13506. var out = {};
  13507. blob.l += 4;
  13508. blob.cf = blob.read_shift(2);
  13509. return out;
  13510. }
  13511. /* [MS-XLS] 2.5.140 - 2.5.154 and friends */
  13512. function parse_FtSkip(blob) { blob.l += 2; blob.l += blob.read_shift(2); }
  13513. var FtTab = {
  13514. 0x00: parse_FtSkip, /* FtEnd */
  13515. 0x04: parse_FtSkip, /* FtMacro */
  13516. 0x05: parse_FtSkip, /* FtButton */
  13517. 0x06: parse_FtSkip, /* FtGmo */
  13518. 0x07: parse_FtCf, /* FtCf */
  13519. 0x08: parse_FtSkip, /* FtPioGrbit */
  13520. 0x09: parse_FtSkip, /* FtPictFmla */
  13521. 0x0A: parse_FtSkip, /* FtCbls */
  13522. 0x0B: parse_FtSkip, /* FtRbo */
  13523. 0x0C: parse_FtSkip, /* FtSbs */
  13524. 0x0D: parse_FtNts, /* FtNts */
  13525. 0x0E: parse_FtSkip, /* FtSbsFmla */
  13526. 0x0F: parse_FtSkip, /* FtGboData */
  13527. 0x10: parse_FtSkip, /* FtEdoData */
  13528. 0x11: parse_FtSkip, /* FtRboData */
  13529. 0x12: parse_FtSkip, /* FtCblsData */
  13530. 0x13: parse_FtSkip, /* FtLbsData */
  13531. 0x14: parse_FtSkip, /* FtCblsFmla */
  13532. 0x15: parse_FtCmo
  13533. };
  13534. function parse_FtArray(blob, length) {
  13535. var tgt = blob.l + length;
  13536. var fts = [];
  13537. while(blob.l < tgt) {
  13538. var ft = blob.read_shift(2);
  13539. blob.l-=2;
  13540. try {
  13541. fts.push(FtTab[ft](blob, tgt - blob.l));
  13542. } catch(e) { blob.l = tgt; return fts; }
  13543. }
  13544. if(blob.l != tgt) blob.l = tgt; //throw new Error("bad Object Ft-sequence");
  13545. return fts;
  13546. }
  13547. /* --- 2.4 Records --- */
  13548. /* [MS-XLS] 2.4.21 */
  13549. function parse_BOF(blob, length) {
  13550. var o = {BIFFVer:0, dt:0};
  13551. o.BIFFVer = blob.read_shift(2); length -= 2;
  13552. if(length >= 2) { o.dt = blob.read_shift(2); blob.l -= 2; }
  13553. switch(o.BIFFVer) {
  13554. case 0x0600: /* BIFF8 */
  13555. case 0x0500: /* BIFF5 */
  13556. case 0x0400: /* BIFF4 */
  13557. case 0x0300: /* BIFF3 */
  13558. case 0x0200: /* BIFF2 */
  13559. case 0x0002: case 0x0007: /* BIFF2 */
  13560. break;
  13561. default: if(length > 6) throw new Error("Unexpected BIFF Ver " + o.BIFFVer);
  13562. }
  13563. blob.read_shift(length);
  13564. return o;
  13565. }
  13566. function write_BOF(wb, t, o) {
  13567. var h = 0x0600, w = 16;
  13568. switch(o.bookType) {
  13569. case 'biff8': break;
  13570. case 'biff5': h = 0x0500; w = 8; break;
  13571. case 'biff4': h = 0x0004; w = 6; break;
  13572. case 'biff3': h = 0x0003; w = 6; break;
  13573. case 'biff2': h = 0x0002; w = 4; break;
  13574. case 'xla': break;
  13575. default: throw new Error("unsupported BIFF version");
  13576. }
  13577. var out = new_buf(w);
  13578. out.write_shift(2, h);
  13579. out.write_shift(2, t);
  13580. if(w > 4) out.write_shift(2, 0x7262);
  13581. if(w > 6) out.write_shift(2, 0x07CD);
  13582. if(w > 8) {
  13583. out.write_shift(2, 0xC009);
  13584. out.write_shift(2, 0x0001);
  13585. out.write_shift(2, 0x0706);
  13586. out.write_shift(2, 0x0000);
  13587. }
  13588. return out;
  13589. }
  13590. /* [MS-XLS] 2.4.146 */
  13591. function parse_InterfaceHdr(blob, length) {
  13592. if(length === 0) return 0x04b0;
  13593. if((blob.read_shift(2))!==0x04b0){/* empty */}
  13594. return 0x04b0;
  13595. }
  13596. /* [MS-XLS] 2.4.349 */
  13597. function parse_WriteAccess(blob, length, opts) {
  13598. if(opts.enc) { blob.l += length; return ""; }
  13599. var l = blob.l;
  13600. // TODO: make sure XLUnicodeString doesnt overrun
  13601. var UserName = parse_XLUnicodeString2(blob, 0, opts);
  13602. blob.read_shift(length + l - blob.l);
  13603. return UserName;
  13604. }
  13605. function write_WriteAccess(s, opts) {
  13606. var b8 = !opts || opts.biff == 8;
  13607. var o = new_buf(b8 ? 112 : 54);
  13608. o.write_shift(opts.biff == 8 ? 2 : 1, 7);
  13609. if(b8) o.write_shift(1, 0);
  13610. o.write_shift(4, 0x33336853);
  13611. o.write_shift(4, (0x00534A74 | (b8 ? 0 : 0x20000000)));
  13612. while(o.l < o.length) o.write_shift(1, (b8 ? 0 : 32));
  13613. return o;
  13614. }
  13615. /* [MS-XLS] 2.4.351 */
  13616. function parse_WsBool(blob, length, opts) {
  13617. var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0);
  13618. return { fDialog: flags & 0x10 };
  13619. }
  13620. /* [MS-XLS] 2.4.28 */
  13621. function parse_BoundSheet8(blob, length, opts) {
  13622. var pos = blob.read_shift(4);
  13623. var hidden = blob.read_shift(1) & 0x03;
  13624. var dt = blob.read_shift(1);
  13625. switch(dt) {
  13626. case 0: dt = 'Worksheet'; break;
  13627. case 1: dt = 'Macrosheet'; break;
  13628. case 2: dt = 'Chartsheet'; break;
  13629. case 6: dt = 'VBAModule'; break;
  13630. }
  13631. var name = parse_ShortXLUnicodeString(blob, 0, opts);
  13632. if(name.length === 0) name = "Sheet1";
  13633. return { pos:pos, hs:hidden, dt:dt, name:name };
  13634. }
  13635. function write_BoundSheet8(data, opts) {
  13636. var w = (!opts || opts.biff >= 8 ? 2 : 1);
  13637. var o = new_buf(8 + w * data.name.length);
  13638. o.write_shift(4, data.pos);
  13639. o.write_shift(1, data.hs || 0);
  13640. o.write_shift(1, data.dt);
  13641. o.write_shift(1, data.name.length);
  13642. if(opts.biff >= 8) o.write_shift(1, 1);
  13643. o.write_shift(w * data.name.length, data.name, opts.biff < 8 ? 'sbcs' : 'utf16le');
  13644. var out = o.slice(0, o.l);
  13645. out.l = o.l; return out;
  13646. }
  13647. /* [MS-XLS] 2.4.265 TODO */
  13648. function parse_SST(blob, length) {
  13649. var end = blob.l + length;
  13650. var cnt = blob.read_shift(4);
  13651. var ucnt = blob.read_shift(4);
  13652. var strs = ([]);
  13653. for(var i = 0; i != ucnt && blob.l < end; ++i) {
  13654. strs.push(parse_XLUnicodeRichExtendedString(blob));
  13655. }
  13656. strs.Count = cnt; strs.Unique = ucnt;
  13657. return strs;
  13658. }
  13659. function write_SST(sst, opts) {
  13660. var header = new_buf(8);
  13661. header.write_shift(4, sst.Count);
  13662. header.write_shift(4, sst.Unique);
  13663. var strs = [];
  13664. for(var j = 0; j < sst.length; ++j) strs[j] = write_XLUnicodeRichExtendedString(sst[j], opts);
  13665. var o = bconcat([header].concat(strs));
  13666. o.parts = [header.length].concat(strs.map(function(str) { return str.length; }));
  13667. return o;
  13668. }
  13669. /* [MS-XLS] 2.4.107 */
  13670. function parse_ExtSST(blob, length) {
  13671. var extsst = {};
  13672. extsst.dsst = blob.read_shift(2);
  13673. blob.l += length-2;
  13674. return extsst;
  13675. }
  13676. /* [MS-XLS] 2.4.221 TODO: check BIFF2-4 */
  13677. function parse_Row(blob) {
  13678. var z = ({});
  13679. z.r = blob.read_shift(2);
  13680. z.c = blob.read_shift(2);
  13681. z.cnt = blob.read_shift(2) - z.c;
  13682. var miyRw = blob.read_shift(2);
  13683. blob.l += 4; // reserved(2), unused(2)
  13684. var flags = blob.read_shift(1); // various flags
  13685. blob.l += 3; // reserved(8), ixfe(12), flags(4)
  13686. if(flags & 0x07) z.level = flags & 0x07;
  13687. // collapsed: flags & 0x10
  13688. if(flags & 0x20) z.hidden = true;
  13689. if(flags & 0x40) z.hpt = miyRw / 20;
  13690. return z;
  13691. }
  13692. /* [MS-XLS] 2.4.125 */
  13693. function parse_ForceFullCalculation(blob) {
  13694. var header = parse_frtHeader(blob);
  13695. if(header.type != 0x08A3) throw new Error("Invalid Future Record " + header.type);
  13696. var fullcalc = blob.read_shift(4);
  13697. return fullcalc !== 0x0;
  13698. }
  13699. /* [MS-XLS] 2.4.215 rt */
  13700. function parse_RecalcId(blob) {
  13701. blob.read_shift(2);
  13702. return blob.read_shift(4);
  13703. }
  13704. /* [MS-XLS] 2.4.87 */
  13705. function parse_DefaultRowHeight(blob, length, opts) {
  13706. var f = 0;
  13707. if(!(opts && opts.biff == 2)) {
  13708. f = blob.read_shift(2);
  13709. }
  13710. var miyRw = blob.read_shift(2);
  13711. if((opts && opts.biff == 2)) {
  13712. f = 1 - (miyRw >> 15); miyRw &= 0x7fff;
  13713. }
  13714. var fl = {Unsynced:f&1,DyZero:(f&2)>>1,ExAsc:(f&4)>>2,ExDsc:(f&8)>>3};
  13715. return [fl, miyRw];
  13716. }
  13717. /* [MS-XLS] 2.4.345 TODO */
  13718. function parse_Window1(blob) {
  13719. var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2);
  13720. var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2);
  13721. var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2);
  13722. return { Pos: [xWn, yWn], Dim: [dxWn, dyWn], Flags: flags, CurTab: iTabCur,
  13723. FirstTab: iTabFirst, Selected: ctabSel, TabRatio: wTabRatio };
  13724. }
  13725. function write_Window1() {
  13726. var o = new_buf(18);
  13727. o.write_shift(2, 0);
  13728. o.write_shift(2, 0);
  13729. o.write_shift(2, 0x7260);
  13730. o.write_shift(2, 0x44c0);
  13731. o.write_shift(2, 0x38);
  13732. o.write_shift(2, 0);
  13733. o.write_shift(2, 0);
  13734. o.write_shift(2, 1);
  13735. o.write_shift(2, 0x01f4);
  13736. return o;
  13737. }
  13738. /* [MS-XLS] 2.4.346 TODO */
  13739. function parse_Window2(blob, length, opts) {
  13740. if(opts && opts.biff >= 2 && opts.biff < 5) return {};
  13741. var f = blob.read_shift(2);
  13742. return { RTL: f & 0x40 };
  13743. }
  13744. function write_Window2(view) {
  13745. var o = new_buf(18), f = 0x6b6;
  13746. if(view && view.RTL) f |= 0x40;
  13747. o.write_shift(2, f);
  13748. o.write_shift(4, 0);
  13749. o.write_shift(4, 64);
  13750. o.write_shift(4, 0);
  13751. o.write_shift(4, 0);
  13752. return o;
  13753. }
  13754. /* [MS-XLS] 2.4.189 TODO */
  13755. function parse_Pane(/*blob, length, opts*/) {
  13756. }
  13757. /* [MS-XLS] 2.4.122 TODO */
  13758. function parse_Font(blob, length, opts) {
  13759. var o = {
  13760. dyHeight: blob.read_shift(2),
  13761. fl: blob.read_shift(2)
  13762. };
  13763. switch((opts && opts.biff) || 8) {
  13764. case 2: break;
  13765. case 3: case 4: blob.l += 2; break;
  13766. default: blob.l += 10; break;
  13767. }
  13768. o.name = parse_ShortXLUnicodeString(blob, 0, opts);
  13769. return o;
  13770. }
  13771. function write_Font(data, opts) {
  13772. var name = data.name || "Arial";
  13773. var b5 = (opts && (opts.biff == 5)), w = (b5 ? (15 + name.length) : (16 + 2 * name.length));
  13774. var o = new_buf(w);
  13775. o.write_shift(2, (data.sz || 12) * 20);
  13776. o.write_shift(4, 0);
  13777. o.write_shift(2, 400);
  13778. o.write_shift(4, 0);
  13779. o.write_shift(2, 0);
  13780. o.write_shift(1, name.length);
  13781. if(!b5) o.write_shift(1, 1);
  13782. o.write_shift((b5 ? 1 : 2) * name.length, name, (b5 ? "sbcs" : "utf16le"));
  13783. return o;
  13784. }
  13785. /* [MS-XLS] 2.4.149 */
  13786. function parse_LabelSst(blob) {
  13787. var cell = parse_XLSCell(blob);
  13788. cell.isst = blob.read_shift(4);
  13789. return cell;
  13790. }
  13791. function write_LabelSst(R, C, v, os ) {
  13792. var o = new_buf(10);
  13793. write_XLSCell(R, C, os, o);
  13794. o.write_shift(4, v);
  13795. return o;
  13796. }
  13797. /* [MS-XLS] 2.4.148 */
  13798. function parse_Label(blob, length, opts) {
  13799. var target = blob.l + length;
  13800. var cell = parse_XLSCell(blob, 6);
  13801. if(opts.biff == 2) blob.l++;
  13802. var str = parse_XLUnicodeString(blob, target - blob.l, opts);
  13803. cell.val = str;
  13804. return cell;
  13805. }
  13806. function write_Label(R, C, v, os, opts) {
  13807. var b8 = !opts || opts.biff == 8;
  13808. var o = new_buf(6 + 2 + (+b8) + (1 + b8) * v.length);
  13809. write_XLSCell(R, C, os, o);
  13810. o.write_shift(2, v.length);
  13811. if(b8) o.write_shift(1, 1);
  13812. o.write_shift((1 + b8) * v.length, v, b8 ? 'utf16le' : 'sbcs');
  13813. return o;
  13814. }
  13815. /* [MS-XLS] 2.4.126 Number Formats */
  13816. function parse_Format(blob, length, opts) {
  13817. var numFmtId = blob.read_shift(2);
  13818. var fmtstr = parse_XLUnicodeString2(blob, 0, opts);
  13819. return [numFmtId, fmtstr];
  13820. }
  13821. function write_Format(i, f, opts, o) {
  13822. var b5 = (opts && (opts.biff == 5));
  13823. if(!o) o = new_buf(b5 ? (3 + f.length) : (5 + 2 * f.length));
  13824. o.write_shift(2, i);
  13825. o.write_shift((b5 ? 1 : 2), f.length);
  13826. if(!b5) o.write_shift(1, 1);
  13827. o.write_shift((b5 ? 1 : 2) * f.length, f, (b5 ? 'sbcs' : 'utf16le'));
  13828. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  13829. if(out.l == null) out.l = out.length;
  13830. return out;
  13831. }
  13832. var parse_BIFF2Format = parse_XLUnicodeString2;
  13833. /* [MS-XLS] 2.4.90 */
  13834. function parse_Dimensions(blob, length, opts) {
  13835. var end = blob.l + length;
  13836. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  13837. var r = blob.read_shift(w), R = blob.read_shift(w);
  13838. var c = blob.read_shift(2), C = blob.read_shift(2);
  13839. blob.l = end;
  13840. return {s: {r:r, c:c}, e: {r:R, c:C}};
  13841. }
  13842. function write_Dimensions(range, opts) {
  13843. var w = opts.biff == 8 || !opts.biff ? 4 : 2;
  13844. var o = new_buf(2*w + 6);
  13845. o.write_shift(w, range.s.r);
  13846. o.write_shift(w, range.e.r + 1);
  13847. o.write_shift(2, range.s.c);
  13848. o.write_shift(2, range.e.c + 1);
  13849. o.write_shift(2, 0);
  13850. return o;
  13851. }
  13852. /* [MS-XLS] 2.4.220 */
  13853. function parse_RK(blob) {
  13854. var rw = blob.read_shift(2), col = blob.read_shift(2);
  13855. var rkrec = parse_RkRec(blob);
  13856. return {r:rw, c:col, ixfe:rkrec[0], rknum:rkrec[1]};
  13857. }
  13858. /* [MS-XLS] 2.4.175 */
  13859. function parse_MulRk(blob, length) {
  13860. var target = blob.l + length - 2;
  13861. var rw = blob.read_shift(2), col = blob.read_shift(2);
  13862. var rkrecs = [];
  13863. while(blob.l < target) rkrecs.push(parse_RkRec(blob));
  13864. if(blob.l !== target) throw new Error("MulRK read error");
  13865. var lastcol = blob.read_shift(2);
  13866. if(rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch");
  13867. return {r:rw, c:col, C:lastcol, rkrec:rkrecs};
  13868. }
  13869. /* [MS-XLS] 2.4.174 */
  13870. function parse_MulBlank(blob, length) {
  13871. var target = blob.l + length - 2;
  13872. var rw = blob.read_shift(2), col = blob.read_shift(2);
  13873. var ixfes = [];
  13874. while(blob.l < target) ixfes.push(blob.read_shift(2));
  13875. if(blob.l !== target) throw new Error("MulBlank read error");
  13876. var lastcol = blob.read_shift(2);
  13877. if(ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch");
  13878. return {r:rw, c:col, C:lastcol, ixfe:ixfes};
  13879. }
  13880. /* [MS-XLS] 2.5.20 2.5.249 TODO: interpret values here */
  13881. function parse_CellStyleXF(blob, length, style, opts) {
  13882. var o = {};
  13883. var a = blob.read_shift(4), b = blob.read_shift(4);
  13884. var c = blob.read_shift(4), d = blob.read_shift(2);
  13885. o.patternType = XLSFillPattern[c >> 26];
  13886. if(!opts.cellStyles) return o;
  13887. o.alc = a & 0x07;
  13888. o.fWrap = (a >> 3) & 0x01;
  13889. o.alcV = (a >> 4) & 0x07;
  13890. o.fJustLast = (a >> 7) & 0x01;
  13891. o.trot = (a >> 8) & 0xFF;
  13892. o.cIndent = (a >> 16) & 0x0F;
  13893. o.fShrinkToFit = (a >> 20) & 0x01;
  13894. o.iReadOrder = (a >> 22) & 0x02;
  13895. o.fAtrNum = (a >> 26) & 0x01;
  13896. o.fAtrFnt = (a >> 27) & 0x01;
  13897. o.fAtrAlc = (a >> 28) & 0x01;
  13898. o.fAtrBdr = (a >> 29) & 0x01;
  13899. o.fAtrPat = (a >> 30) & 0x01;
  13900. o.fAtrProt = (a >> 31) & 0x01;
  13901. o.dgLeft = b & 0x0F;
  13902. o.dgRight = (b >> 4) & 0x0F;
  13903. o.dgTop = (b >> 8) & 0x0F;
  13904. o.dgBottom = (b >> 12) & 0x0F;
  13905. o.icvLeft = (b >> 16) & 0x7F;
  13906. o.icvRight = (b >> 23) & 0x7F;
  13907. o.grbitDiag = (b >> 30) & 0x03;
  13908. o.icvTop = c & 0x7F;
  13909. o.icvBottom = (c >> 7) & 0x7F;
  13910. o.icvDiag = (c >> 14) & 0x7F;
  13911. o.dgDiag = (c >> 21) & 0x0F;
  13912. o.icvFore = d & 0x7F;
  13913. o.icvBack = (d >> 7) & 0x7F;
  13914. o.fsxButton = (d >> 14) & 0x01;
  13915. return o;
  13916. }
  13917. //function parse_CellXF(blob, length, opts) {return parse_CellStyleXF(blob,length,0, opts);}
  13918. //function parse_StyleXF(blob, length, opts) {return parse_CellStyleXF(blob,length,1, opts);}
  13919. /* [MS-XLS] 2.4.353 TODO: actually do this right */
  13920. function parse_XF(blob, length, opts) {
  13921. var o = {};
  13922. o.ifnt = blob.read_shift(2); o.numFmtId = blob.read_shift(2); o.flags = blob.read_shift(2);
  13923. o.fStyle = (o.flags >> 2) & 0x01;
  13924. length -= 6;
  13925. o.data = parse_CellStyleXF(blob, length, o.fStyle, opts);
  13926. return o;
  13927. }
  13928. function write_XF(data, ixfeP, opts, o) {
  13929. var b5 = (opts && (opts.biff == 5));
  13930. if(!o) o = new_buf(b5 ? 16 : 20);
  13931. o.write_shift(2, 0);
  13932. if(data.style) {
  13933. o.write_shift(2, (data.numFmtId||0));
  13934. o.write_shift(2, 0xFFF4);
  13935. } else {
  13936. o.write_shift(2, (data.numFmtId||0));
  13937. o.write_shift(2, (ixfeP<<4));
  13938. }
  13939. o.write_shift(4, 0);
  13940. o.write_shift(4, 0);
  13941. if(!b5) o.write_shift(4, 0);
  13942. o.write_shift(2, 0);
  13943. return o;
  13944. }
  13945. /* [MS-XLS] 2.4.134 */
  13946. function parse_Guts(blob) {
  13947. blob.l += 4;
  13948. var out = [blob.read_shift(2), blob.read_shift(2)];
  13949. if(out[0] !== 0) out[0]--;
  13950. if(out[1] !== 0) out[1]--;
  13951. if(out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|"));
  13952. return out;
  13953. }
  13954. function write_Guts(guts) {
  13955. var o = new_buf(8);
  13956. o.write_shift(4, 0);
  13957. o.write_shift(2, guts[0] ? guts[0] + 1 : 0);
  13958. o.write_shift(2, guts[1] ? guts[1] + 1 : 0);
  13959. return o;
  13960. }
  13961. /* [MS-XLS] 2.4.24 */
  13962. function parse_BoolErr(blob, length, opts) {
  13963. var cell = parse_XLSCell(blob, 6);
  13964. if(opts.biff == 2) ++blob.l;
  13965. var val = parse_Bes(blob, 2);
  13966. cell.val = val;
  13967. cell.t = (val === true || val === false) ? 'b' : 'e';
  13968. return cell;
  13969. }
  13970. function write_BoolErr(R, C, v, os, opts, t) {
  13971. var o = new_buf(8);
  13972. write_XLSCell(R, C, os, o);
  13973. write_Bes(v, t, o);
  13974. return o;
  13975. }
  13976. /* [MS-XLS] 2.4.180 Number */
  13977. function parse_Number(blob) {
  13978. var cell = parse_XLSCell(blob, 6);
  13979. var xnum = parse_Xnum(blob, 8);
  13980. cell.val = xnum;
  13981. return cell;
  13982. }
  13983. function write_Number(R, C, v, os) {
  13984. var o = new_buf(14);
  13985. write_XLSCell(R, C, os, o);
  13986. write_Xnum(v, o);
  13987. return o;
  13988. }
  13989. var parse_XLHeaderFooter = parse_OptXLUnicodeString; // TODO: parse 2.4.136
  13990. /* [MS-XLS] 2.4.271 */
  13991. function parse_SupBook(blob, length, opts) {
  13992. var end = blob.l + length;
  13993. var ctab = blob.read_shift(2);
  13994. var cch = blob.read_shift(2);
  13995. opts.sbcch = cch;
  13996. if(cch == 0x0401 || cch == 0x3A01) return [cch, ctab];
  13997. if(cch < 0x01 || cch >0xff) throw new Error("Unexpected SupBook type: "+cch);
  13998. var virtPath = parse_XLUnicodeStringNoCch(blob, cch);
  13999. /* TODO: 2.5.277 Virtual Path */
  14000. var rgst = [];
  14001. while(end > blob.l) rgst.push(parse_XLUnicodeString(blob));
  14002. return [cch, ctab, virtPath, rgst];
  14003. }
  14004. /* [MS-XLS] 2.4.105 TODO */
  14005. function parse_ExternName(blob, length, opts) {
  14006. var flags = blob.read_shift(2);
  14007. var body;
  14008. var o = ({
  14009. fBuiltIn: flags & 0x01,
  14010. fWantAdvise: (flags >>> 1) & 0x01,
  14011. fWantPict: (flags >>> 2) & 0x01,
  14012. fOle: (flags >>> 3) & 0x01,
  14013. fOleLink: (flags >>> 4) & 0x01,
  14014. cf: (flags >>> 5) & 0x3FF,
  14015. fIcon: flags >>> 15 & 0x01
  14016. });
  14017. if(opts.sbcch === 0x3A01) body = parse_AddinUdf(blob, length-2, opts);
  14018. //else throw new Error("unsupported SupBook cch: " + opts.sbcch);
  14019. o.body = body || blob.read_shift(length-2);
  14020. if(typeof body === "string") o.Name = body;
  14021. return o;
  14022. }
  14023. /* [MS-XLS] 2.4.150 TODO */
  14024. var XLSLblBuiltIn = [
  14025. "_xlnm.Consolidate_Area",
  14026. "_xlnm.Auto_Open",
  14027. "_xlnm.Auto_Close",
  14028. "_xlnm.Extract",
  14029. "_xlnm.Database",
  14030. "_xlnm.Criteria",
  14031. "_xlnm.Print_Area",
  14032. "_xlnm.Print_Titles",
  14033. "_xlnm.Recorder",
  14034. "_xlnm.Data_Form",
  14035. "_xlnm.Auto_Activate",
  14036. "_xlnm.Auto_Deactivate",
  14037. "_xlnm.Sheet_Title",
  14038. "_xlnm._FilterDatabase"
  14039. ];
  14040. function parse_Lbl(blob, length, opts) {
  14041. var target = blob.l + length;
  14042. var flags = blob.read_shift(2);
  14043. var chKey = blob.read_shift(1);
  14044. var cch = blob.read_shift(1);
  14045. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  14046. var itab = 0;
  14047. if(!opts || opts.biff >= 5) {
  14048. if(opts.biff != 5) blob.l += 2;
  14049. itab = blob.read_shift(2);
  14050. if(opts.biff == 5) blob.l += 2;
  14051. blob.l += 4;
  14052. }
  14053. var name = parse_XLUnicodeStringNoCch(blob, cch, opts);
  14054. if(flags & 0x20) name = XLSLblBuiltIn[name.charCodeAt(0)];
  14055. var npflen = target - blob.l; if(opts && opts.biff == 2) --npflen;
  14056. var rgce = (target == blob.l || cce === 0 || !(npflen > 0)) ? [] : parse_NameParsedFormula(blob, npflen, opts, cce);
  14057. return {
  14058. chKey: chKey,
  14059. Name: name,
  14060. itab: itab,
  14061. rgce: rgce
  14062. };
  14063. }
  14064. /* [MS-XLS] 2.4.106 TODO: verify filename encoding */
  14065. function parse_ExternSheet(blob, length, opts) {
  14066. if(opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts);
  14067. var o = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2);
  14068. while(len-- !== 0) o.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts));
  14069. // [iSupBook, itabFirst, itabLast];
  14070. if(blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target);
  14071. return o;
  14072. }
  14073. function parse_BIFF5ExternSheet(blob, length, opts) {
  14074. if(blob[blob.l + 1] == 0x03) blob[blob.l]++;
  14075. var o = parse_ShortXLUnicodeString(blob, length, opts);
  14076. return o.charCodeAt(0) == 0x03 ? o.slice(1) : o;
  14077. }
  14078. /* [MS-XLS] 2.4.176 TODO: check older biff */
  14079. function parse_NameCmt(blob, length, opts) {
  14080. if(opts.biff < 8) { blob.l += length; return; }
  14081. var cchName = blob.read_shift(2);
  14082. var cchComment = blob.read_shift(2);
  14083. var name = parse_XLUnicodeStringNoCch(blob, cchName, opts);
  14084. var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts);
  14085. return [name, comment];
  14086. }
  14087. /* [MS-XLS] 2.4.260 */
  14088. function parse_ShrFmla(blob, length, opts) {
  14089. var ref = parse_RefU(blob, 6);
  14090. blob.l++;
  14091. var cUse = blob.read_shift(1);
  14092. length -= 8;
  14093. return [parse_SharedParsedFormula(blob, length, opts), cUse, ref];
  14094. }
  14095. /* [MS-XLS] 2.4.4 TODO */
  14096. function parse_Array(blob, length, opts) {
  14097. var ref = parse_Ref(blob, 6);
  14098. /* TODO: fAlwaysCalc */
  14099. switch(opts.biff) {
  14100. case 2: blob.l ++; length -= 7; break;
  14101. case 3: case 4: blob.l += 2; length -= 8; break;
  14102. default: blob.l += 6; length -= 12;
  14103. }
  14104. return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)];
  14105. }
  14106. /* [MS-XLS] 2.4.173 */
  14107. function parse_MTRSettings(blob) {
  14108. var fMTREnabled = blob.read_shift(4) !== 0x00;
  14109. var fUserSetThreadCount = blob.read_shift(4) !== 0x00;
  14110. var cUserThreadCount = blob.read_shift(4);
  14111. return [fMTREnabled, fUserSetThreadCount, cUserThreadCount];
  14112. }
  14113. /* [MS-XLS] 2.5.186 TODO: BIFF5 */
  14114. function parse_NoteSh(blob, length, opts) {
  14115. if(opts.biff < 8) return;
  14116. var row = blob.read_shift(2), col = blob.read_shift(2);
  14117. var flags = blob.read_shift(2), idObj = blob.read_shift(2);
  14118. var stAuthor = parse_XLUnicodeString2(blob, 0, opts);
  14119. if(opts.biff < 8) blob.read_shift(1);
  14120. return [{r:row,c:col}, stAuthor, idObj, flags];
  14121. }
  14122. /* [MS-XLS] 2.4.179 */
  14123. function parse_Note(blob, length, opts) {
  14124. /* TODO: Support revisions */
  14125. return parse_NoteSh(blob, length, opts);
  14126. }
  14127. /* [MS-XLS] 2.4.168 */
  14128. function parse_MergeCells(blob, length) {
  14129. var merges = [];
  14130. var cmcs = blob.read_shift(2);
  14131. while (cmcs--) merges.push(parse_Ref8U(blob,length));
  14132. return merges;
  14133. }
  14134. function write_MergeCells(merges) {
  14135. var o = new_buf(2 + merges.length * 8);
  14136. o.write_shift(2, merges.length);
  14137. for(var i = 0; i < merges.length; ++i) write_Ref8U(merges[i], o);
  14138. return o;
  14139. }
  14140. /* [MS-XLS] 2.4.181 TODO: parse all the things! */
  14141. function parse_Obj(blob, length, opts) {
  14142. if(opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts);
  14143. var cmo = parse_FtCmo(blob, 22); // id, ot, flags
  14144. var fts = parse_FtArray(blob, length-22, cmo[1]);
  14145. return { cmo: cmo, ft:fts };
  14146. }
  14147. /* from older spec */
  14148. var parse_BIFF5OT = [];
  14149. parse_BIFF5OT[0x08] = function(blob, length) {
  14150. var tgt = blob.l + length;
  14151. blob.l += 10; // todo
  14152. var cf = blob.read_shift(2);
  14153. blob.l += 4;
  14154. blob.l += 2; //var cbPictFmla = blob.read_shift(2);
  14155. blob.l += 2;
  14156. blob.l += 2; //var grbit = blob.read_shift(2);
  14157. blob.l += 4;
  14158. var cchName = blob.read_shift(1);
  14159. blob.l += cchName; // TODO: stName
  14160. blob.l = tgt; // TODO: fmla
  14161. return { fmt:cf };
  14162. };
  14163. function parse_BIFF5Obj(blob, length, opts) {
  14164. blob.l += 4; //var cnt = blob.read_shift(4);
  14165. var ot = blob.read_shift(2);
  14166. var id = blob.read_shift(2);
  14167. var grbit = blob.read_shift(2);
  14168. blob.l += 2; //var colL = blob.read_shift(2);
  14169. blob.l += 2; //var dxL = blob.read_shift(2);
  14170. blob.l += 2; //var rwT = blob.read_shift(2);
  14171. blob.l += 2; //var dyT = blob.read_shift(2);
  14172. blob.l += 2; //var colR = blob.read_shift(2);
  14173. blob.l += 2; //var dxR = blob.read_shift(2);
  14174. blob.l += 2; //var rwB = blob.read_shift(2);
  14175. blob.l += 2; //var dyB = blob.read_shift(2);
  14176. blob.l += 2; //var cbMacro = blob.read_shift(2);
  14177. blob.l += 6;
  14178. length -= 36;
  14179. var fts = [];
  14180. fts.push((parse_BIFF5OT[ot]||parsenoop)(blob, length, opts));
  14181. return { cmo: [id, ot, grbit], ft:fts };
  14182. }
  14183. /* [MS-XLS] 2.4.329 TODO: parse properly */
  14184. function parse_TxO(blob, length, opts) {
  14185. var s = blob.l;
  14186. var texts = "";
  14187. try {
  14188. blob.l += 4;
  14189. var ot = (opts.lastobj||{cmo:[0,0]}).cmo[1];
  14190. var controlInfo; // eslint-disable-line no-unused-vars
  14191. if([0,5,7,11,12,14].indexOf(ot) == -1) blob.l += 6;
  14192. else controlInfo = parse_ControlInfo(blob, 6, opts);
  14193. var cchText = blob.read_shift(2);
  14194. /*var cbRuns = */blob.read_shift(2);
  14195. /*var ifntEmpty = */parseuint16(blob, 2);
  14196. var len = blob.read_shift(2);
  14197. blob.l += len;
  14198. //var fmla = parse_ObjFmla(blob, s + length - blob.l);
  14199. for(var i = 1; i < blob.lens.length-1; ++i) {
  14200. if(blob.l-s != blob.lens[i]) throw new Error("TxO: bad continue record");
  14201. var hdr = blob[blob.l];
  14202. var t = parse_XLUnicodeStringNoCch(blob, blob.lens[i+1]-blob.lens[i]-1);
  14203. texts += t;
  14204. if(texts.length >= (hdr ? cchText : 2*cchText)) break;
  14205. }
  14206. if(texts.length !== cchText && texts.length !== cchText*2) {
  14207. throw new Error("cchText: " + cchText + " != " + texts.length);
  14208. }
  14209. blob.l = s + length;
  14210. /* [MS-XLS] 2.5.272 TxORuns */
  14211. // var rgTxoRuns = [];
  14212. // for(var j = 0; j != cbRuns/8-1; ++j) blob.l += 8;
  14213. // var cchText2 = blob.read_shift(2);
  14214. // if(cchText2 !== cchText) throw new Error("TxOLastRun mismatch: " + cchText2 + " " + cchText);
  14215. // blob.l += 6;
  14216. // if(s + length != blob.l) throw new Error("TxO " + (s + length) + ", at " + blob.l);
  14217. return { t: texts };
  14218. } catch(e) { blob.l = s + length; return { t: texts }; }
  14219. }
  14220. /* [MS-XLS] 2.4.140 */
  14221. function parse_HLink(blob, length) {
  14222. var ref = parse_Ref8U(blob, 8);
  14223. blob.l += 16; /* CLSID */
  14224. var hlink = parse_Hyperlink(blob, length-24);
  14225. return [ref, hlink];
  14226. }
  14227. function write_HLink(hl) {
  14228. var O = new_buf(24);
  14229. var ref = decode_cell(hl[0]);
  14230. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  14231. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  14232. var clsid = "d0 c9 ea 79 f9 ba ce 11 8c 82 00 aa 00 4b a9 0b".split(" ");
  14233. for(var i = 0; i < 16; ++i) O.write_shift(1, parseInt(clsid[i], 16));
  14234. return bconcat([O, write_Hyperlink(hl[1])]);
  14235. }
  14236. /* [MS-XLS] 2.4.141 */
  14237. function parse_HLinkTooltip(blob, length) {
  14238. blob.read_shift(2);
  14239. var ref = parse_Ref8U(blob, 8);
  14240. var wzTooltip = blob.read_shift((length-10)/2, 'dbcs-cont');
  14241. wzTooltip = wzTooltip.replace(chr0,"");
  14242. return [ref, wzTooltip];
  14243. }
  14244. function write_HLinkTooltip(hl) {
  14245. var TT = hl[1].Tooltip;
  14246. var O = new_buf(10 + 2 * (TT.length + 1));
  14247. O.write_shift(2, 0x0800);
  14248. var ref = decode_cell(hl[0]);
  14249. O.write_shift(2, ref.r); O.write_shift(2, ref.r);
  14250. O.write_shift(2, ref.c); O.write_shift(2, ref.c);
  14251. for(var i = 0; i < TT.length; ++i) O.write_shift(2, TT.charCodeAt(i));
  14252. O.write_shift(2, 0);
  14253. return O;
  14254. }
  14255. /* [MS-XLS] 2.4.63 */
  14256. function parse_Country(blob) {
  14257. var o = [0,0], d;
  14258. d = blob.read_shift(2); o[0] = CountryEnum[d] || d;
  14259. d = blob.read_shift(2); o[1] = CountryEnum[d] || d;
  14260. return o;
  14261. }
  14262. function write_Country(o) {
  14263. if(!o) o = new_buf(4);
  14264. o.write_shift(2, 0x01);
  14265. o.write_shift(2, 0x01);
  14266. return o;
  14267. }
  14268. /* [MS-XLS] 2.4.50 ClrtClient */
  14269. function parse_ClrtClient(blob) {
  14270. var ccv = blob.read_shift(2);
  14271. var o = [];
  14272. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  14273. return o;
  14274. }
  14275. /* [MS-XLS] 2.4.188 */
  14276. function parse_Palette(blob) {
  14277. var ccv = blob.read_shift(2);
  14278. var o = [];
  14279. while(ccv-->0) o.push(parse_LongRGB(blob, 8));
  14280. return o;
  14281. }
  14282. /* [MS-XLS] 2.4.354 */
  14283. function parse_XFCRC(blob) {
  14284. blob.l += 2;
  14285. var o = {cxfs:0, crc:0};
  14286. o.cxfs = blob.read_shift(2);
  14287. o.crc = blob.read_shift(4);
  14288. return o;
  14289. }
  14290. /* [MS-XLS] 2.4.53 TODO: parse flags */
  14291. /* [MS-XLSB] 2.4.323 TODO: parse flags */
  14292. function parse_ColInfo(blob, length, opts) {
  14293. if(!opts.cellStyles) return parsenoop(blob, length);
  14294. var w = opts && opts.biff >= 12 ? 4 : 2;
  14295. var colFirst = blob.read_shift(w);
  14296. var colLast = blob.read_shift(w);
  14297. var coldx = blob.read_shift(w);
  14298. var ixfe = blob.read_shift(w);
  14299. var flags = blob.read_shift(2);
  14300. if(w == 2) blob.l += 2;
  14301. var o = ({s:colFirst, e:colLast, w:coldx, ixfe:ixfe, flags:flags});
  14302. if(opts.biff >= 5 || !opts.biff) o.level = (flags >> 8) & 0x7;
  14303. return o;
  14304. }
  14305. /* [MS-XLS] 2.4.257 */
  14306. function parse_Setup(blob, length) {
  14307. var o = {};
  14308. if(length < 32) return o;
  14309. blob.l += 16;
  14310. o.header = parse_Xnum(blob, 8);
  14311. o.footer = parse_Xnum(blob, 8);
  14312. blob.l += 2;
  14313. return o;
  14314. }
  14315. /* [MS-XLS] 2.4.261 */
  14316. function parse_ShtProps(blob, length, opts) {
  14317. var def = {area:false};
  14318. if(opts.biff != 5) { blob.l += length; return def; }
  14319. var d = blob.read_shift(1); blob.l += 3;
  14320. if((d & 0x10)) def.area = true;
  14321. return def;
  14322. }
  14323. /* [MS-XLS] 2.4.241 */
  14324. function write_RRTabId(n) {
  14325. var out = new_buf(2 * n);
  14326. for(var i = 0; i < n; ++i) out.write_shift(2, i+1);
  14327. return out;
  14328. }
  14329. var parse_Blank = parse_XLSCell; /* [MS-XLS] 2.4.20 Just the cell */
  14330. var parse_Scl = parseuint16a; /* [MS-XLS] 2.4.247 num, den */
  14331. var parse_String = parse_XLUnicodeString; /* [MS-XLS] 2.4.268 */
  14332. /* --- Specific to versions before BIFF8 --- */
  14333. function parse_ImData(blob) {
  14334. var cf = blob.read_shift(2);
  14335. var env = blob.read_shift(2);
  14336. var lcb = blob.read_shift(4);
  14337. var o = {fmt:cf, env:env, len:lcb, data:blob.slice(blob.l,blob.l+lcb)};
  14338. blob.l += lcb;
  14339. return o;
  14340. }
  14341. /* BIFF2_??? where ??? is the name from [XLS] */
  14342. function parse_BIFF2STR(blob, length, opts) {
  14343. var cell = parse_XLSCell(blob, 6);
  14344. ++blob.l;
  14345. var str = parse_XLUnicodeString2(blob, length-7, opts);
  14346. cell.t = 'str';
  14347. cell.val = str;
  14348. return cell;
  14349. }
  14350. function parse_BIFF2NUM(blob) {
  14351. var cell = parse_XLSCell(blob, 6);
  14352. ++blob.l;
  14353. var num = parse_Xnum(blob, 8);
  14354. cell.t = 'n';
  14355. cell.val = num;
  14356. return cell;
  14357. }
  14358. function write_BIFF2NUM(r, c, val) {
  14359. var out = new_buf(15);
  14360. write_BIFF2Cell(out, r, c);
  14361. out.write_shift(8, val, 'f');
  14362. return out;
  14363. }
  14364. function parse_BIFF2INT(blob) {
  14365. var cell = parse_XLSCell(blob, 6);
  14366. ++blob.l;
  14367. var num = blob.read_shift(2);
  14368. cell.t = 'n';
  14369. cell.val = num;
  14370. return cell;
  14371. }
  14372. function write_BIFF2INT(r, c, val) {
  14373. var out = new_buf(9);
  14374. write_BIFF2Cell(out, r, c);
  14375. out.write_shift(2, val);
  14376. return out;
  14377. }
  14378. function parse_BIFF2STRING(blob) {
  14379. var cch = blob.read_shift(1);
  14380. if(cch === 0) { blob.l++; return ""; }
  14381. return blob.read_shift(cch, 'sbcs-cont');
  14382. }
  14383. /* TODO: convert to BIFF8 font struct */
  14384. function parse_BIFF2FONTXTRA(blob, length) {
  14385. blob.l += 6; // unknown
  14386. blob.l += 2; // font weight "bls"
  14387. blob.l += 1; // charset
  14388. blob.l += 3; // unknown
  14389. blob.l += 1; // font family
  14390. blob.l += length - 13;
  14391. }
  14392. /* TODO: parse rich text runs */
  14393. function parse_RString(blob, length, opts) {
  14394. var end = blob.l + length;
  14395. var cell = parse_XLSCell(blob, 6);
  14396. var cch = blob.read_shift(2);
  14397. var str = parse_XLUnicodeStringNoCch(blob, cch, opts);
  14398. blob.l = end;
  14399. cell.t = 'str';
  14400. cell.val = str;
  14401. return cell;
  14402. }
  14403. /* from js-harb (C) 2014-present SheetJS */
  14404. var DBF = (function() {
  14405. var dbf_codepage_map = {
  14406. /* Code Pages Supported by Visual FoxPro */
  14407. 0x01: 437, 0x02: 850,
  14408. 0x03: 1252, 0x04: 10000,
  14409. 0x64: 852, 0x65: 866,
  14410. 0x66: 865, 0x67: 861,
  14411. 0x68: 895, 0x69: 620,
  14412. 0x6A: 737, 0x6B: 857,
  14413. 0x78: 950, 0x79: 949,
  14414. 0x7A: 936, 0x7B: 932,
  14415. 0x7C: 874, 0x7D: 1255,
  14416. 0x7E: 1256, 0x96: 10007,
  14417. 0x97: 10029, 0x98: 10006,
  14418. 0xC8: 1250, 0xC9: 1251,
  14419. 0xCA: 1254, 0xCB: 1253,
  14420. /* shapefile DBF extension */
  14421. 0x00: 20127, 0x08: 865,
  14422. 0x09: 437, 0x0A: 850,
  14423. 0x0B: 437, 0x0D: 437,
  14424. 0x0E: 850, 0x0F: 437,
  14425. 0x10: 850, 0x11: 437,
  14426. 0x12: 850, 0x13: 932,
  14427. 0x14: 850, 0x15: 437,
  14428. 0x16: 850, 0x17: 865,
  14429. 0x18: 437, 0x19: 437,
  14430. 0x1A: 850, 0x1B: 437,
  14431. 0x1C: 863, 0x1D: 850,
  14432. 0x1F: 852, 0x22: 852,
  14433. 0x23: 852, 0x24: 860,
  14434. 0x25: 850, 0x26: 866,
  14435. 0x37: 850, 0x40: 852,
  14436. 0x4D: 936, 0x4E: 949,
  14437. 0x4F: 950, 0x50: 874,
  14438. 0x57: 1252, 0x58: 1252,
  14439. 0x59: 1252,
  14440. 0xFF: 16969
  14441. };
  14442. var dbf_reverse_map = evert({
  14443. 0x01: 437, 0x02: 850,
  14444. 0x03: 1252, 0x04: 10000,
  14445. 0x64: 852, 0x65: 866,
  14446. 0x66: 865, 0x67: 861,
  14447. 0x68: 895, 0x69: 620,
  14448. 0x6A: 737, 0x6B: 857,
  14449. 0x78: 950, 0x79: 949,
  14450. 0x7A: 936, 0x7B: 932,
  14451. 0x7C: 874, 0x7D: 1255,
  14452. 0x7E: 1256, 0x96: 10007,
  14453. 0x97: 10029, 0x98: 10006,
  14454. 0xC8: 1250, 0xC9: 1251,
  14455. 0xCA: 1254, 0xCB: 1253,
  14456. 0x00: 20127
  14457. });
  14458. var DBF_SUPPORTED_VERSIONS = [0x02, 0x03, 0x30, 0x31, 0x83, 0x8B, 0x8C, 0xF5];
  14459. /* TODO: find an actual specification */
  14460. function dbf_to_aoa(buf, opts) {
  14461. var out = [];
  14462. /* TODO: browser based */
  14463. var d = (new_raw_buf(1));
  14464. switch(opts.type) {
  14465. case 'base64': d = s2a(Base64.decode(buf)); break;
  14466. case 'binary': d = s2a(buf); break;
  14467. case 'buffer':
  14468. case 'array': d = buf; break;
  14469. }
  14470. prep_blob(d, 0);
  14471. /* header */
  14472. var ft = d.read_shift(1);
  14473. var memo = false;
  14474. var vfp = false, l7 = false;
  14475. switch(ft) {
  14476. case 0x02: case 0x03: break;
  14477. case 0x30: vfp = true; memo = true; break;
  14478. case 0x31: vfp = true; break;
  14479. case 0x83: memo = true; break;
  14480. case 0x8B: memo = true; break;
  14481. case 0x8C: memo = true; l7 = true; break;
  14482. case 0xF5: memo = true; break;
  14483. default: throw new Error("DBF Unsupported Version: " + ft.toString(16));
  14484. }
  14485. var /*filedate = new Date(),*/ nrow = 0, fpos = 0;
  14486. if(ft == 0x02) nrow = d.read_shift(2);
  14487. /*filedate = new Date(d.read_shift(1) + 1900, d.read_shift(1) - 1, d.read_shift(1));*/d.l += 3;
  14488. if(ft != 0x02) nrow = d.read_shift(4); if(nrow > 1048576) nrow = 1e6;
  14489. if(ft != 0x02) fpos = d.read_shift(2);
  14490. var rlen = d.read_shift(2);
  14491. var /*flags = 0,*/ current_cp = 1252;
  14492. if(ft != 0x02) {
  14493. d.l+=16;
  14494. /*flags = */d.read_shift(1);
  14495. //if(memo && ((flags & 0x02) === 0)) throw new Error("DBF Flags " + flags.toString(16) + " ft " + ft.toString(16));
  14496. /* codepage present in FoxPro */
  14497. if(d[d.l] !== 0) current_cp = dbf_codepage_map[d[d.l]];
  14498. d.l+=1;
  14499. d.l+=2;
  14500. }
  14501. if(l7) d.l += 36;
  14502. var fields = [], field = ({});
  14503. var hend = fpos - 10 - (vfp ? 264 : 0), ww = l7 ? 32 : 11;
  14504. while(ft == 0x02 ? d.l < d.length && d[d.l] != 0x0d: d.l < hend) {
  14505. field = ({});
  14506. field.name = cptable.utils.decode(current_cp, d.slice(d.l, d.l+ww)).replace(/[\u0000\r\n].*$/g,"");
  14507. d.l += ww;
  14508. field.type = String.fromCharCode(d.read_shift(1));
  14509. if(ft != 0x02 && !l7) field.offset = d.read_shift(4);
  14510. field.len = d.read_shift(1);
  14511. if(ft == 0x02) field.offset = d.read_shift(2);
  14512. field.dec = d.read_shift(1);
  14513. if(field.name.length) fields.push(field);
  14514. if(ft != 0x02) d.l += l7 ? 13 : 14;
  14515. switch(field.type) {
  14516. case 'B': // VFP Double
  14517. if((!vfp || field.len != 8) && opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  14518. break;
  14519. case 'G': // General
  14520. case 'P': // Picture
  14521. if(opts.WTF) console.log('Skipping ' + field.name + ':' + field.type);
  14522. break;
  14523. case 'C': // character
  14524. case 'D': // date
  14525. case 'F': // floating point
  14526. case 'I': // long
  14527. case 'L': // boolean
  14528. case 'M': // memo
  14529. case 'N': // number
  14530. case 'O': // double
  14531. case 'T': // datetime
  14532. case 'Y': // currency
  14533. case '0': // VFP _NullFlags
  14534. case '@': // timestamp
  14535. case '+': // autoincrement
  14536. break;
  14537. default: throw new Error('Unknown Field Type: ' + field.type);
  14538. }
  14539. }
  14540. if(d[d.l] !== 0x0D) d.l = fpos-1;
  14541. else if(ft == 0x02) d.l = 0x209;
  14542. if(ft != 0x02) {
  14543. if(d.read_shift(1) !== 0x0D) throw new Error("DBF Terminator not found " + d.l + " " + d[d.l]);
  14544. d.l = fpos;
  14545. }
  14546. /* data */
  14547. var R = 0, C = 0;
  14548. out[0] = [];
  14549. for(C = 0; C != fields.length; ++C) out[0][C] = fields[C].name;
  14550. while(nrow-- > 0) {
  14551. if(d[d.l] === 0x2A) { d.l+=rlen; continue; }
  14552. ++d.l;
  14553. out[++R] = []; C = 0;
  14554. for(C = 0; C != fields.length; ++C) {
  14555. var dd = d.slice(d.l, d.l+fields[C].len); d.l+=fields[C].len;
  14556. prep_blob(dd, 0);
  14557. var s = cptable.utils.decode(current_cp, dd);
  14558. switch(fields[C].type) {
  14559. case 'C':
  14560. out[R][C] = cptable.utils.decode(current_cp, dd);
  14561. out[R][C] = out[R][C].trim();
  14562. break;
  14563. case 'D':
  14564. if(s.length === 8) out[R][C] = new Date(+s.slice(0,4), +s.slice(4,6)-1, +s.slice(6,8));
  14565. else out[R][C] = s;
  14566. break;
  14567. case 'F': out[R][C] = parseFloat(s.trim()); break;
  14568. case '+': case 'I': out[R][C] = l7 ? dd.read_shift(-4, 'i') ^ 0x80000000 : dd.read_shift(4, 'i'); break;
  14569. case 'L': switch(s.toUpperCase()) {
  14570. case 'Y': case 'T': out[R][C] = true; break;
  14571. case 'N': case 'F': out[R][C] = false; break;
  14572. case ' ': case '?': out[R][C] = false; break; /* NOTE: technically uninitialized */
  14573. default: throw new Error("DBF Unrecognized L:|" + s + "|");
  14574. } break;
  14575. case 'M': /* TODO: handle memo files */
  14576. if(!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16));
  14577. out[R][C] = "##MEMO##" + (l7 ? parseInt(s.trim(), 10): dd.read_shift(4));
  14578. break;
  14579. case 'N': out[R][C] = +s.replace(/\u0000/g,"").trim(); break;
  14580. case '@': out[R][C] = new Date(dd.read_shift(-8, 'f') - 0x388317533400); break;
  14581. case 'T': out[R][C] = new Date((dd.read_shift(4) - 0x253D8C) * 0x5265C00 + dd.read_shift(4)); break;
  14582. case 'Y': out[R][C] = dd.read_shift(4,'i')/1e4; break;
  14583. case 'O': out[R][C] = -dd.read_shift(-8, 'f'); break;
  14584. case 'B': if(vfp && fields[C].len == 8) { out[R][C] = dd.read_shift(8,'f'); break; }
  14585. /* falls through */
  14586. case 'G': case 'P': dd.l += fields[C].len; break;
  14587. case '0':
  14588. if(fields[C].name === '_NullFlags') break;
  14589. /* falls through */
  14590. default: throw new Error("DBF Unsupported data type " + fields[C].type);
  14591. }
  14592. }
  14593. }
  14594. if(ft != 0x02) if(d.l < d.length && d[d.l++] != 0x1A) throw new Error("DBF EOF Marker missing " + (d.l-1) + " of " + d.length + " " + d[d.l-1].toString(16));
  14595. if(opts && opts.sheetRows) out = out.slice(0, opts.sheetRows);
  14596. return out;
  14597. }
  14598. function dbf_to_sheet(buf, opts) {
  14599. var o = opts || {};
  14600. if(!o.dateNF) o.dateNF = "yyyymmdd";
  14601. return aoa_to_sheet(dbf_to_aoa(buf, o), o);
  14602. }
  14603. function dbf_to_workbook(buf, opts) {
  14604. try { return sheet_to_workbook(dbf_to_sheet(buf, opts), opts); }
  14605. catch(e) { if(opts && opts.WTF) throw e; }
  14606. return ({SheetNames:[],Sheets:{}});
  14607. }
  14608. var _RLEN = { 'B': 8, 'C': 250, 'L': 1, 'D': 8, '?': 0, '': 0 };
  14609. function sheet_to_dbf(ws, opts) {
  14610. var o = opts || {};
  14611. if(+o.codepage >= 0) set_cp(+o.codepage);
  14612. if(o.type == "string") throw new Error("Cannot write DBF to JS string");
  14613. var ba = buf_array();
  14614. var aoa = sheet_to_json(ws, {header:1, raw:true, cellDates:true});
  14615. var headers = aoa[0], data = aoa.slice(1);
  14616. var i = 0, j = 0, hcnt = 0, rlen = 1;
  14617. for(i = 0; i < headers.length; ++i) {
  14618. if(i == null) continue;
  14619. ++hcnt;
  14620. if(typeof headers[i] === 'number') headers[i] = headers[i].toString(10);
  14621. if(typeof headers[i] !== 'string') throw new Error("DBF Invalid column name " + headers[i] + " |" + (typeof headers[i]) + "|");
  14622. if(headers.indexOf(headers[i]) !== i) for(j=0; j<1024;++j)
  14623. if(headers.indexOf(headers[i] + "_" + j) == -1) { headers[i] += "_" + j; break; }
  14624. }
  14625. var range = safe_decode_range(ws['!ref']);
  14626. var coltypes = [];
  14627. for(i = 0; i <= range.e.c - range.s.c; ++i) {
  14628. var col = [];
  14629. for(j=0; j < data.length; ++j) {
  14630. if(data[j][i] != null) col.push(data[j][i]);
  14631. }
  14632. if(col.length == 0 || headers[i] == null) { coltypes[i] = '?'; continue; }
  14633. var guess = '', _guess = '';
  14634. for(j = 0; j < col.length; ++j) {
  14635. switch(typeof col[j]) {
  14636. /* TODO: check if L2 compat is desired */
  14637. case 'number': _guess = 'B'; break;
  14638. case 'string': _guess = 'C'; break;
  14639. case 'boolean': _guess = 'L'; break;
  14640. case 'object': _guess = col[j] instanceof Date ? 'D' : 'C'; break;
  14641. default: _guess = 'C';
  14642. }
  14643. guess = guess && guess != _guess ? 'C' : _guess;
  14644. if(guess == 'C') break;
  14645. }
  14646. rlen += _RLEN[guess] || 0;
  14647. coltypes[i] = guess;
  14648. }
  14649. var h = ba.next(32);
  14650. h.write_shift(4, 0x13021130);
  14651. h.write_shift(4, data.length);
  14652. h.write_shift(2, 296 + 32 * hcnt);
  14653. h.write_shift(2, rlen);
  14654. for(i=0; i < 4; ++i) h.write_shift(4, 0);
  14655. h.write_shift(4, 0x00000000 | ((+dbf_reverse_map[current_ansi] || 0x03)<<8));
  14656. for(i = 0, j = 0; i < headers.length; ++i) {
  14657. if(headers[i] == null) continue;
  14658. var hf = ba.next(32);
  14659. var _f = (headers[i].slice(-10) + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").slice(0, 11);
  14660. hf.write_shift(1, _f, "sbcs");
  14661. hf.write_shift(1, coltypes[i] == '?' ? 'C' : coltypes[i], "sbcs");
  14662. hf.write_shift(4, j);
  14663. hf.write_shift(1, _RLEN[coltypes[i]] || 0);
  14664. hf.write_shift(1, 0);
  14665. hf.write_shift(1, 0x02);
  14666. hf.write_shift(4, 0);
  14667. hf.write_shift(1, 0);
  14668. hf.write_shift(4, 0);
  14669. hf.write_shift(4, 0);
  14670. j += _RLEN[coltypes[i]] || 0;
  14671. }
  14672. var hb = ba.next(264);
  14673. hb.write_shift(4, 0x0000000D);
  14674. for(i=0; i < 65;++i) hb.write_shift(4, 0x00000000);
  14675. for(i=0; i < data.length; ++i) {
  14676. var rout = ba.next(rlen);
  14677. rout.write_shift(1, 0);
  14678. for(j=0; j<headers.length; ++j) {
  14679. if(headers[j] == null) continue;
  14680. switch(coltypes[j]) {
  14681. case 'L': rout.write_shift(1, data[i][j] == null ? 0x3F : data[i][j] ? 0x54 : 0x46); break;
  14682. case 'B': rout.write_shift(8, data[i][j]||0, 'f'); break;
  14683. case 'D':
  14684. if(!data[i][j]) rout.write_shift(8, "00000000", "sbcs");
  14685. else {
  14686. rout.write_shift(4, ("0000"+data[i][j].getFullYear()).slice(-4), "sbcs");
  14687. rout.write_shift(2, ("00"+(data[i][j].getMonth()+1)).slice(-2), "sbcs");
  14688. rout.write_shift(2, ("00"+data[i][j].getDate()).slice(-2), "sbcs");
  14689. } break;
  14690. case 'C':
  14691. var _s = String(data[i][j]||"");
  14692. rout.write_shift(1, _s, "sbcs");
  14693. for(hcnt=0; hcnt < 250-_s.length; ++hcnt) rout.write_shift(1, 0x20); break;
  14694. }
  14695. }
  14696. // data
  14697. }
  14698. ba.next(1).write_shift(1, 0x1A);
  14699. return ba.end();
  14700. }
  14701. return {
  14702. versions: DBF_SUPPORTED_VERSIONS,
  14703. to_workbook: dbf_to_workbook,
  14704. to_sheet: dbf_to_sheet,
  14705. from_sheet: sheet_to_dbf
  14706. };
  14707. })();
  14708. var SYLK = (function() {
  14709. /* TODO: stress test sequences */
  14710. var sylk_escapes = ({
  14711. AA:'À', BA:'Á', CA:'Â', DA:195, HA:'Ä', JA:197,
  14712. AE:'È', BE:'É', CE:'Ê', HE:'Ë',
  14713. AI:'Ì', BI:'Í', CI:'Î', HI:'Ï',
  14714. AO:'Ò', BO:'Ó', CO:'Ô', DO:213, HO:'Ö',
  14715. AU:'Ù', BU:'Ú', CU:'Û', HU:'Ü',
  14716. Aa:'à', Ba:'á', Ca:'â', Da:227, Ha:'ä', Ja:229,
  14717. Ae:'è', Be:'é', Ce:'ê', He:'ë',
  14718. Ai:'ì', Bi:'í', Ci:'î', Hi:'ï',
  14719. Ao:'ò', Bo:'ó', Co:'ô', Do:245, Ho:'ö',
  14720. Au:'ù', Bu:'ú', Cu:'û', Hu:'ü',
  14721. KC:'Ç', Kc:'ç', q:'æ', z:'œ', a:'Æ', j:'Œ',
  14722. DN:209, Dn:241, Hy:255,
  14723. S:169, c:170, R:174, B:180,
  14724. 0:176, 1:177, 2:178,
  14725. 3:179, 5:181, 6:182,
  14726. 7:183, Q:185, k:186, b:208, i:216, l:222, s:240, y:248,
  14727. "!":161, '"':162, "#":163, "(":164, "%":165, "'":167, "H ":168,
  14728. "+":171, ";":187, "<":188, "=":189, ">":190, "?":191, "{":223
  14729. });
  14730. var sylk_char_regex = new RegExp("\u001BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g,"\\$1") + "|\\|)", "gm");
  14731. var sylk_char_fn = function(_, $1){ var o = sylk_escapes[$1]; return typeof o == "number" ? _getansi(o) : o; };
  14732. var decode_sylk_char = function($$, $1, $2) { var newcc = (($1.charCodeAt(0) - 0x20)<<4) | ($2.charCodeAt(0) - 0x30); return newcc == 59 ? $$ : _getansi(newcc); };
  14733. sylk_escapes["|"] = 254;
  14734. /* TODO: find an actual specification */
  14735. function sylk_to_aoa(d, opts) {
  14736. switch(opts.type) {
  14737. case 'base64': return sylk_to_aoa_str(Base64.decode(d), opts);
  14738. case 'binary': return sylk_to_aoa_str(d, opts);
  14739. case 'buffer': return sylk_to_aoa_str(d.toString('binary'), opts);
  14740. case 'array': return sylk_to_aoa_str(cc2str(d), opts);
  14741. }
  14742. throw new Error("Unrecognized type " + opts.type);
  14743. }
  14744. function sylk_to_aoa_str(str, opts) {
  14745. var records = str.split(/[\n\r]+/), R = -1, C = -1, ri = 0, rj = 0, arr = [];
  14746. var formats = [];
  14747. var next_cell_format = null;
  14748. var sht = {}, rowinfo = [], colinfo = [], cw = [];
  14749. var Mval = 0, j;
  14750. if(+opts.codepage >= 0) set_cp(+opts.codepage);
  14751. for (; ri !== records.length; ++ri) {
  14752. Mval = 0;
  14753. var rstr=records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn);
  14754. var record=rstr.replace(/;;/g, "\u0000").split(";").map(function(x) { return x.replace(/\u0000/g, ";"); });
  14755. var RT=record[0], val;
  14756. if(rstr.length > 0) switch(RT) {
  14757. case 'ID': break; /* header */
  14758. case 'E': break; /* EOF */
  14759. case 'B': break; /* dimensions */
  14760. case 'O': break; /* options? */
  14761. case 'P':
  14762. if(record[1].charAt(0) == 'P')
  14763. formats.push(rstr.slice(3).replace(/;;/g, ";"));
  14764. break;
  14765. case 'C':
  14766. var C_seen_K = false, C_seen_X = false;
  14767. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  14768. case 'X': C = parseInt(record[rj].slice(1))-1; C_seen_X = true; break;
  14769. case 'Y':
  14770. R = parseInt(record[rj].slice(1))-1; if(!C_seen_X) C = 0;
  14771. for(j = arr.length; j <= R; ++j) arr[j] = [];
  14772. break;
  14773. case 'K':
  14774. val = record[rj].slice(1);
  14775. if(val.charAt(0) === '"') val = val.slice(1,val.length - 1);
  14776. else if(val === 'TRUE') val = true;
  14777. else if(val === 'FALSE') val = false;
  14778. else if(!isNaN(fuzzynum(val))) {
  14779. val = fuzzynum(val);
  14780. if(next_cell_format !== null && SSF.is_date(next_cell_format)) val = numdate(val);
  14781. } else if(!isNaN(fuzzydate(val).getDate())) {
  14782. val = parseDate(val);
  14783. }
  14784. if(typeof cptable !== 'undefined' && typeof val == "string" && ((opts||{}).type != "string") && (opts||{}).codepage) val = cptable.utils.decode(opts.codepage, val);
  14785. C_seen_K = true;
  14786. break;
  14787. case 'E':
  14788. var formula = rc_to_a1(record[rj].slice(1), {r:R,c:C});
  14789. arr[R][C] = [arr[R][C], formula];
  14790. break;
  14791. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  14792. }
  14793. if(C_seen_K) { arr[R][C] = val; next_cell_format = null; }
  14794. break;
  14795. case 'F':
  14796. var F_seen = 0;
  14797. for(rj=1; rj<record.length; ++rj) switch(record[rj].charAt(0)) {
  14798. case 'X': C = parseInt(record[rj].slice(1))-1; ++F_seen; break;
  14799. case 'Y':
  14800. R = parseInt(record[rj].slice(1))-1; /*C = 0;*/
  14801. for(j = arr.length; j <= R; ++j) arr[j] = [];
  14802. break;
  14803. case 'M': Mval = parseInt(record[rj].slice(1)) / 20; break;
  14804. case 'F': break; /* ??? */
  14805. case 'G': break; /* hide grid */
  14806. case 'P':
  14807. next_cell_format = formats[parseInt(record[rj].slice(1))];
  14808. break;
  14809. case 'S': break; /* cell style */
  14810. case 'D': break; /* column */
  14811. case 'N': break; /* font */
  14812. case 'W':
  14813. cw = record[rj].slice(1).split(" ");
  14814. for(j = parseInt(cw[0], 10); j <= parseInt(cw[1], 10); ++j) {
  14815. Mval = parseInt(cw[2], 10);
  14816. colinfo[j-1] = Mval === 0 ? {hidden:true}: {wch:Mval}; process_col(colinfo[j-1]);
  14817. } break;
  14818. case 'C': /* default column format */
  14819. C = parseInt(record[rj].slice(1))-1;
  14820. if(!colinfo[C]) colinfo[C] = {};
  14821. break;
  14822. case 'R': /* row properties */
  14823. R = parseInt(record[rj].slice(1))-1;
  14824. if(!rowinfo[R]) rowinfo[R] = {};
  14825. if(Mval > 0) { rowinfo[R].hpt = Mval; rowinfo[R].hpx = pt2px(Mval); }
  14826. else if(Mval === 0) rowinfo[R].hidden = true;
  14827. break;
  14828. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  14829. }
  14830. if(F_seen < 1) next_cell_format = null; break;
  14831. default: if(opts && opts.WTF) throw new Error("SYLK bad record " + rstr);
  14832. }
  14833. }
  14834. if(rowinfo.length > 0) sht['!rows'] = rowinfo;
  14835. if(colinfo.length > 0) sht['!cols'] = colinfo;
  14836. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  14837. return [arr, sht];
  14838. }
  14839. function sylk_to_sheet(d, opts) {
  14840. var aoasht = sylk_to_aoa(d, opts);
  14841. var aoa = aoasht[0], ws = aoasht[1];
  14842. var o = aoa_to_sheet(aoa, opts);
  14843. keys(ws).forEach(function(k) { o[k] = ws[k]; });
  14844. return o;
  14845. }
  14846. function sylk_to_workbook(d, opts) { return sheet_to_workbook(sylk_to_sheet(d, opts), opts); }
  14847. function write_ws_cell_sylk(cell, ws, R, C) {
  14848. var o = "C;Y" + (R+1) + ";X" + (C+1) + ";K";
  14849. switch(cell.t) {
  14850. case 'n':
  14851. o += (cell.v||0);
  14852. if(cell.f && !cell.F) o += ";E" + a1_to_rc(cell.f, {r:R, c:C}); break;
  14853. case 'b': o += cell.v ? "TRUE" : "FALSE"; break;
  14854. case 'e': o += cell.w || cell.v; break;
  14855. case 'd': o += '"' + (cell.w || cell.v) + '"'; break;
  14856. case 's': o += '"' + cell.v.replace(/"/g,"") + '"'; break;
  14857. }
  14858. return o;
  14859. }
  14860. function write_ws_cols_sylk(out, cols) {
  14861. cols.forEach(function(col, i) {
  14862. var rec = "F;W" + (i+1) + " " + (i+1) + " ";
  14863. if(col.hidden) rec += "0";
  14864. else {
  14865. if(typeof col.width == 'number') col.wpx = width2px(col.width);
  14866. if(typeof col.wpx == 'number') col.wch = px2char(col.wpx);
  14867. if(typeof col.wch == 'number') rec += Math.round(col.wch);
  14868. }
  14869. if(rec.charAt(rec.length - 1) != " ") out.push(rec);
  14870. });
  14871. }
  14872. function write_ws_rows_sylk(out, rows) {
  14873. rows.forEach(function(row, i) {
  14874. var rec = "F;";
  14875. if(row.hidden) rec += "M0;";
  14876. else if(row.hpt) rec += "M" + 20 * row.hpt + ";";
  14877. else if(row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";";
  14878. if(rec.length > 2) out.push(rec + "R" + (i+1));
  14879. });
  14880. }
  14881. function sheet_to_sylk(ws, opts) {
  14882. var preamble = ["ID;PWXL;N;E"], o = [];
  14883. var r = safe_decode_range(ws['!ref']), cell;
  14884. var dense = Array.isArray(ws);
  14885. var RS = "\r\n";
  14886. preamble.push("P;PGeneral");
  14887. preamble.push("F;P0;DG0G8;M255");
  14888. if(ws['!cols']) write_ws_cols_sylk(preamble, ws['!cols']);
  14889. if(ws['!rows']) write_ws_rows_sylk(preamble, ws['!rows']);
  14890. preamble.push("B;Y" + (r.e.r - r.s.r + 1) + ";X" + (r.e.c - r.s.c + 1) + ";D" + [r.s.c,r.s.r,r.e.c,r.e.r].join(" "));
  14891. for(var R = r.s.r; R <= r.e.r; ++R) {
  14892. for(var C = r.s.c; C <= r.e.c; ++C) {
  14893. var coord = encode_cell({r:R,c:C});
  14894. cell = dense ? (ws[R]||[])[C]: ws[coord];
  14895. if(!cell || (cell.v == null && (!cell.f || cell.F))) continue;
  14896. o.push(write_ws_cell_sylk(cell, ws, R, C, opts));
  14897. }
  14898. }
  14899. return preamble.join(RS) + RS + o.join(RS) + RS + "E" + RS;
  14900. }
  14901. return {
  14902. to_workbook: sylk_to_workbook,
  14903. to_sheet: sylk_to_sheet,
  14904. from_sheet: sheet_to_sylk
  14905. };
  14906. })();
  14907. var DIF = (function() {
  14908. function dif_to_aoa(d, opts) {
  14909. switch(opts.type) {
  14910. case 'base64': return dif_to_aoa_str(Base64.decode(d), opts);
  14911. case 'binary': return dif_to_aoa_str(d, opts);
  14912. case 'buffer': return dif_to_aoa_str(d.toString('binary'), opts);
  14913. case 'array': return dif_to_aoa_str(cc2str(d), opts);
  14914. }
  14915. throw new Error("Unrecognized type " + opts.type);
  14916. }
  14917. function dif_to_aoa_str(str, opts) {
  14918. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  14919. for (; ri !== records.length; ++ri) {
  14920. if (records[ri].trim() === 'BOT') { arr[++R] = []; C = 0; continue; }
  14921. if (R < 0) continue;
  14922. var metadata = records[ri].trim().split(",");
  14923. var type = metadata[0], value = metadata[1];
  14924. ++ri;
  14925. var data = records[ri].trim();
  14926. switch (+type) {
  14927. case -1:
  14928. if (data === 'BOT') { arr[++R] = []; C = 0; continue; }
  14929. else if (data !== 'EOD') throw new Error("Unrecognized DIF special command " + data);
  14930. break;
  14931. case 0:
  14932. if(data === 'TRUE') arr[R][C] = true;
  14933. else if(data === 'FALSE') arr[R][C] = false;
  14934. else if(!isNaN(fuzzynum(value))) arr[R][C] = fuzzynum(value);
  14935. else if(!isNaN(fuzzydate(value).getDate())) arr[R][C] = parseDate(value);
  14936. else arr[R][C] = value;
  14937. ++C; break;
  14938. case 1:
  14939. data = data.slice(1,data.length-1);
  14940. arr[R][C++] = data !== '' ? data : null;
  14941. break;
  14942. }
  14943. if (data === 'EOD') break;
  14944. }
  14945. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  14946. return arr;
  14947. }
  14948. function dif_to_sheet(str, opts) { return aoa_to_sheet(dif_to_aoa(str, opts), opts); }
  14949. function dif_to_workbook(str, opts) { return sheet_to_workbook(dif_to_sheet(str, opts), opts); }
  14950. var sheet_to_dif = (function() {
  14951. var push_field = function pf(o, topic, v, n, s) {
  14952. o.push(topic);
  14953. o.push(v + "," + n);
  14954. o.push('"' + s.replace(/"/g,'""') + '"');
  14955. };
  14956. var push_value = function po(o, type, v, s) {
  14957. o.push(type + "," + v);
  14958. o.push(type == 1 ? '"' + s.replace(/"/g,'""') + '"' : s);
  14959. };
  14960. return function sheet_to_dif(ws) {
  14961. var o = [];
  14962. var r = safe_decode_range(ws['!ref']), cell;
  14963. var dense = Array.isArray(ws);
  14964. push_field(o, "TABLE", 0, 1, "sheetjs");
  14965. push_field(o, "VECTORS", 0, r.e.r - r.s.r + 1,"");
  14966. push_field(o, "TUPLES", 0, r.e.c - r.s.c + 1,"");
  14967. push_field(o, "DATA", 0, 0,"");
  14968. for(var R = r.s.r; R <= r.e.r; ++R) {
  14969. push_value(o, -1, 0, "BOT");
  14970. for(var C = r.s.c; C <= r.e.c; ++C) {
  14971. var coord = encode_cell({r:R,c:C});
  14972. cell = dense ? (ws[R]||[])[C] : ws[coord];
  14973. if(!cell) { push_value(o, 1, 0, ""); continue;}
  14974. switch(cell.t) {
  14975. case 'n':
  14976. var val = DIF_XL ? cell.w : cell.v;
  14977. if(!val && cell.v != null) val = cell.v;
  14978. if(val == null) {
  14979. if(DIF_XL && cell.f && !cell.F) push_value(o, 1, 0, "=" + cell.f);
  14980. else push_value(o, 1, 0, "");
  14981. }
  14982. else push_value(o, 0, val, "V");
  14983. break;
  14984. case 'b':
  14985. push_value(o, 0, cell.v ? 1 : 0, cell.v ? "TRUE" : "FALSE");
  14986. break;
  14987. case 's':
  14988. push_value(o, 1, 0, (!DIF_XL || isNaN(cell.v)) ? cell.v : '="' + cell.v + '"');
  14989. break;
  14990. case 'd':
  14991. if(!cell.w) cell.w = SSF.format(cell.z || SSF._table[14], datenum(parseDate(cell.v)));
  14992. if(DIF_XL) push_value(o, 0, cell.w, "V");
  14993. else push_value(o, 1, 0, cell.w);
  14994. break;
  14995. default: push_value(o, 1, 0, "");
  14996. }
  14997. }
  14998. }
  14999. push_value(o, -1, 0, "EOD");
  15000. var RS = "\r\n";
  15001. var oo = o.join(RS);
  15002. //while((oo.length & 0x7F) != 0) oo += "\0";
  15003. return oo;
  15004. };
  15005. })();
  15006. return {
  15007. to_workbook: dif_to_workbook,
  15008. to_sheet: dif_to_sheet,
  15009. from_sheet: sheet_to_dif
  15010. };
  15011. })();
  15012. var ETH = (function() {
  15013. function decode(s) { return s.replace(/\\b/g,"\\").replace(/\\c/g,":").replace(/\\n/g,"\n"); }
  15014. function encode(s) { return s.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g,"\\n"); }
  15015. function eth_to_aoa(str, opts) {
  15016. var records = str.split('\n'), R = -1, C = -1, ri = 0, arr = [];
  15017. for (; ri !== records.length; ++ri) {
  15018. var record = records[ri].trim().split(":");
  15019. if(record[0] !== 'cell') continue;
  15020. var addr = decode_cell(record[1]);
  15021. if(arr.length <= addr.r) for(R = arr.length; R <= addr.r; ++R) if(!arr[R]) arr[R] = [];
  15022. R = addr.r; C = addr.c;
  15023. switch(record[2]) {
  15024. case 't': arr[R][C] = decode(record[3]); break;
  15025. case 'v': arr[R][C] = +record[3]; break;
  15026. case 'vtf': var _f = record[record.length - 1];
  15027. /* falls through */
  15028. case 'vtc':
  15029. switch(record[3]) {
  15030. case 'nl': arr[R][C] = +record[4] ? true : false; break;
  15031. default: arr[R][C] = +record[4]; break;
  15032. }
  15033. if(record[2] == 'vtf') arr[R][C] = [arr[R][C], _f];
  15034. }
  15035. }
  15036. if(opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows);
  15037. return arr;
  15038. }
  15039. function eth_to_sheet(d, opts) { return aoa_to_sheet(eth_to_aoa(d, opts), opts); }
  15040. function eth_to_workbook(d, opts) { return sheet_to_workbook(eth_to_sheet(d, opts), opts); }
  15041. var header = [
  15042. "socialcalc:version:1.5",
  15043. "MIME-Version: 1.0",
  15044. "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave"
  15045. ].join("\n");
  15046. var sep = [
  15047. "--SocialCalcSpreadsheetControlSave",
  15048. "Content-type: text/plain; charset=UTF-8"
  15049. ].join("\n") + "\n";
  15050. /* TODO: the other parts */
  15051. var meta = [
  15052. "# SocialCalc Spreadsheet Control Save",
  15053. "part:sheet"
  15054. ].join("\n");
  15055. var end = "--SocialCalcSpreadsheetControlSave--";
  15056. function sheet_to_eth_data(ws) {
  15057. if(!ws || !ws['!ref']) return "";
  15058. var o = [], oo = [], cell, coord = "";
  15059. var r = decode_range(ws['!ref']);
  15060. var dense = Array.isArray(ws);
  15061. for(var R = r.s.r; R <= r.e.r; ++R) {
  15062. for(var C = r.s.c; C <= r.e.c; ++C) {
  15063. coord = encode_cell({r:R,c:C});
  15064. cell = dense ? (ws[R]||[])[C] : ws[coord];
  15065. if(!cell || cell.v == null || cell.t === 'z') continue;
  15066. oo = ["cell", coord, 't'];
  15067. switch(cell.t) {
  15068. case 's': case 'str': oo.push(encode(cell.v)); break;
  15069. case 'n':
  15070. if(!cell.f) { oo[2]='v'; oo[3]=cell.v; }
  15071. else { oo[2]='vtf'; oo[3]='n'; oo[4]=cell.v; oo[5]=encode(cell.f); }
  15072. break;
  15073. case 'b':
  15074. oo[2] = 'vt'+(cell.f?'f':'c'); oo[3]='nl'; oo[4]=cell.v?"1":"0";
  15075. oo[5] = encode(cell.f||(cell.v?'TRUE':'FALSE'));
  15076. break;
  15077. case 'd':
  15078. var t = datenum(parseDate(cell.v));
  15079. oo[2] = 'vtc'; oo[3] = 'nd'; oo[4] = ""+t;
  15080. oo[5] = cell.w || SSF.format(cell.z || SSF._table[14], t);
  15081. break;
  15082. case 'e': continue;
  15083. }
  15084. o.push(oo.join(":"));
  15085. }
  15086. }
  15087. o.push("sheet:c:" + (r.e.c-r.s.c+1) + ":r:" + (r.e.r-r.s.r+1) + ":tvf:1");
  15088. o.push("valueformat:1:text-wiki");
  15089. //o.push("copiedfrom:" + ws['!ref']); // clipboard only
  15090. return o.join("\n");
  15091. }
  15092. function sheet_to_eth(ws) {
  15093. return [header, sep, meta, sep, sheet_to_eth_data(ws), end].join("\n");
  15094. // return ["version:1.5", sheet_to_eth_data(ws)].join("\n"); // clipboard form
  15095. }
  15096. return {
  15097. to_workbook: eth_to_workbook,
  15098. to_sheet: eth_to_sheet,
  15099. from_sheet: sheet_to_eth
  15100. };
  15101. })();
  15102. var PRN = (function() {
  15103. function set_text_arr(data, arr, R, C, o) {
  15104. if(o.raw) arr[R][C] = data;
  15105. else if(data === 'TRUE') arr[R][C] = true;
  15106. else if(data === 'FALSE') arr[R][C] = false;
  15107. else if(data === ""){/* empty */}
  15108. else if(!isNaN(fuzzynum(data))) arr[R][C] = fuzzynum(data);
  15109. else if(!isNaN(fuzzydate(data).getDate())) arr[R][C] = parseDate(data);
  15110. else arr[R][C] = data;
  15111. }
  15112. function prn_to_aoa_str(f, opts) {
  15113. var o = opts || {};
  15114. var arr = ([]);
  15115. if(!f || f.length === 0) return arr;
  15116. var lines = f.split(/[\r\n]/);
  15117. var L = lines.length - 1;
  15118. while(L >= 0 && lines[L].length === 0) --L;
  15119. var start = 10, idx = 0;
  15120. var R = 0;
  15121. for(; R <= L; ++R) {
  15122. idx = lines[R].indexOf(" ");
  15123. if(idx == -1) idx = lines[R].length; else idx++;
  15124. start = Math.max(start, idx);
  15125. }
  15126. for(R = 0; R <= L; ++R) {
  15127. arr[R] = [];
  15128. /* TODO: confirm that widths are always 10 */
  15129. var C = 0;
  15130. set_text_arr(lines[R].slice(0, start).trim(), arr, R, C, o);
  15131. for(C = 1; C <= (lines[R].length - start)/10 + 1; ++C)
  15132. set_text_arr(lines[R].slice(start+(C-1)*10,start+C*10).trim(),arr,R,C,o);
  15133. }
  15134. if(o.sheetRows) arr = arr.slice(0, o.sheetRows);
  15135. return arr;
  15136. }
  15137. // List of accepted CSV separators
  15138. var guess_seps = {
  15139. 0x2C: ',',
  15140. 0x09: "\t",
  15141. 0x3B: ';'
  15142. };
  15143. // CSV separator weights to be used in case of equal numbers
  15144. var guess_sep_weights = {
  15145. 0x2C: 3,
  15146. 0x09: 2,
  15147. 0x3B: 1
  15148. };
  15149. function guess_sep(str) {
  15150. var cnt = {}, instr = false, end = 0, cc = 0;
  15151. for(;end < str.length;++end) {
  15152. if((cc=str.charCodeAt(end)) == 0x22) instr = !instr;
  15153. else if(!instr && cc in guess_seps) cnt[cc] = (cnt[cc]||0)+1;
  15154. }
  15155. cc = [];
  15156. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  15157. cc.push([ cnt[end], end ]);
  15158. }
  15159. if ( !cc.length ) {
  15160. cnt = guess_sep_weights;
  15161. for(end in cnt) if ( Object.prototype.hasOwnProperty.call(cnt, end) ) {
  15162. cc.push([ cnt[end], end ]);
  15163. }
  15164. }
  15165. cc.sort(function(a, b) { return a[0] - b[0] || guess_sep_weights[a[1]] - guess_sep_weights[b[1]]; });
  15166. return guess_seps[cc.pop()[1]];
  15167. }
  15168. function dsv_to_sheet_str(str, opts) {
  15169. var o = opts || {};
  15170. var sep = "";
  15171. if(DENSE != null && o.dense == null) o.dense = DENSE;
  15172. var ws = o.dense ? ([]) : ({});
  15173. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  15174. if(str.slice(0,4) == "sep=") {
  15175. // If the line ends in \r\n
  15176. if(str.charCodeAt(5) == 13 && str.charCodeAt(6) == 10 ) {
  15177. sep = str.charAt(4); str = str.slice(7);
  15178. }
  15179. // If line ends in \r OR \n
  15180. else if(str.charCodeAt(5) == 13 || str.charCodeAt(5) == 10 ) {
  15181. sep = str.charAt(4); str = str.slice(6);
  15182. }
  15183. }
  15184. else sep = guess_sep(str.slice(0,1024));
  15185. var R = 0, C = 0, v = 0;
  15186. var start = 0, end = 0, sepcc = sep.charCodeAt(0), instr = false, cc=0;
  15187. str = str.replace(/\r\n/mg, "\n");
  15188. var _re = o.dateNF != null ? dateNF_regex(o.dateNF) : null;
  15189. function finish_cell() {
  15190. var s = str.slice(start, end);
  15191. var cell = ({});
  15192. if(s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') s = s.slice(1,-1).replace(/""/g,'"');
  15193. if(s.length === 0) cell.t = 'z';
  15194. else if(o.raw) { cell.t = 's'; cell.v = s; }
  15195. else if(s.trim().length === 0) { cell.t = 's'; cell.v = s; }
  15196. else if(s.charCodeAt(0) == 0x3D) {
  15197. if(s.charCodeAt(1) == 0x22 && s.charCodeAt(s.length - 1) == 0x22) { cell.t = 's'; cell.v = s.slice(2,-1).replace(/""/g,'"'); }
  15198. else if(fuzzyfmla(s)) { cell.t = 'n'; cell.f = s.slice(1); }
  15199. else { cell.t = 's'; cell.v = s; } }
  15200. else if(s == "TRUE") { cell.t = 'b'; cell.v = true; }
  15201. else if(s == "FALSE") { cell.t = 'b'; cell.v = false; }
  15202. else if(!isNaN(v = fuzzynum(s))) { cell.t = 'n'; if(o.cellText !== false) cell.w = s; cell.v = v; }
  15203. else if(!isNaN(fuzzydate(s).getDate()) || _re && s.match(_re)) {
  15204. cell.z = o.dateNF || SSF._table[14];
  15205. var k = 0;
  15206. if(_re && s.match(_re)){ s=dateNF_fix(s, o.dateNF, (s.match(_re)||[])); k=1; }
  15207. if(o.cellDates) { cell.t = 'd'; cell.v = parseDate(s, k); }
  15208. else { cell.t = 'n'; cell.v = datenum(parseDate(s, k)); }
  15209. if(o.cellText !== false) cell.w = SSF.format(cell.z, cell.v instanceof Date ? datenum(cell.v):cell.v);
  15210. if(!o.cellNF) delete cell.z;
  15211. } else {
  15212. cell.t = 's';
  15213. cell.v = s;
  15214. }
  15215. if(cell.t == 'z'){}
  15216. else if(o.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = cell; }
  15217. else ws[encode_cell({c:C,r:R})] = cell;
  15218. start = end+1;
  15219. if(range.e.c < C) range.e.c = C;
  15220. if(range.e.r < R) range.e.r = R;
  15221. if(cc == sepcc) ++C; else { C = 0; ++R; if(o.sheetRows && o.sheetRows <= R) return true; }
  15222. }
  15223. outer: for(;end < str.length;++end) switch((cc=str.charCodeAt(end))) {
  15224. case 0x22: instr = !instr; break;
  15225. case sepcc: case 0x0a: case 0x0d: if(!instr && finish_cell()) break outer; break;
  15226. default: break;
  15227. }
  15228. if(end - start > 0) finish_cell();
  15229. ws['!ref'] = encode_range(range);
  15230. return ws;
  15231. }
  15232. function prn_to_sheet_str(str, opts) {
  15233. if(!(opts && opts.PRN)) return dsv_to_sheet_str(str, opts);
  15234. if(str.slice(0,4) == "sep=") return dsv_to_sheet_str(str, opts);
  15235. if(str.indexOf("\t") >= 0 || str.indexOf(",") >= 0 || str.indexOf(";") >= 0) return dsv_to_sheet_str(str, opts);
  15236. return aoa_to_sheet(prn_to_aoa_str(str, opts), opts);
  15237. }
  15238. function prn_to_sheet(d, opts) {
  15239. var str = "", bytes = opts.type == 'string' ? [0,0,0,0] : firstbyte(d, opts);
  15240. switch(opts.type) {
  15241. case 'base64': str = Base64.decode(d); break;
  15242. case 'binary': str = d; break;
  15243. case 'buffer':
  15244. if(opts.codepage == 65001) str = d.toString('utf8');
  15245. else if(opts.codepage && typeof cptable !== 'undefined') str = cptable.utils.decode(opts.codepage, d);
  15246. else str = d.toString('binary');
  15247. break;
  15248. case 'array': str = cc2str(d); break;
  15249. case 'string': str = d; break;
  15250. default: throw new Error("Unrecognized type " + opts.type);
  15251. }
  15252. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str.slice(3));
  15253. else if((opts.type == 'binary') && typeof cptable !== 'undefined' && opts.codepage) str = cptable.utils.decode(opts.codepage, cptable.utils.encode(1252,str));
  15254. if(str.slice(0,19) == "socialcalc:version:") return ETH.to_sheet(opts.type == 'string' ? str : utf8read(str), opts);
  15255. return prn_to_sheet_str(str, opts);
  15256. }
  15257. function prn_to_workbook(d, opts) { return sheet_to_workbook(prn_to_sheet(d, opts), opts); }
  15258. function sheet_to_prn(ws) {
  15259. var o = [];
  15260. var r = safe_decode_range(ws['!ref']), cell;
  15261. var dense = Array.isArray(ws);
  15262. for(var R = r.s.r; R <= r.e.r; ++R) {
  15263. var oo = [];
  15264. for(var C = r.s.c; C <= r.e.c; ++C) {
  15265. var coord = encode_cell({r:R,c:C});
  15266. cell = dense ? (ws[R]||[])[C] : ws[coord];
  15267. if(!cell || cell.v == null) { oo.push(" "); continue; }
  15268. var w = (cell.w || (format_cell(cell), cell.w) || "").slice(0,10);
  15269. while(w.length < 10) w += " ";
  15270. oo.push(w + (C === 0 ? " " : ""));
  15271. }
  15272. o.push(oo.join(""));
  15273. }
  15274. return o.join("\n");
  15275. }
  15276. return {
  15277. to_workbook: prn_to_workbook,
  15278. to_sheet: prn_to_sheet,
  15279. from_sheet: sheet_to_prn
  15280. };
  15281. })();
  15282. /* Excel defaults to SYLK but warns if data is not valid */
  15283. function read_wb_ID(d, opts) {
  15284. var o = opts || {}, OLD_WTF = !!o.WTF; o.WTF = true;
  15285. try {
  15286. var out = SYLK.to_workbook(d, o);
  15287. o.WTF = OLD_WTF;
  15288. return out;
  15289. } catch(e) {
  15290. o.WTF = OLD_WTF;
  15291. if(!e.message.match(/SYLK bad record ID/) && OLD_WTF) throw e;
  15292. return PRN.to_workbook(d, opts);
  15293. }
  15294. }
  15295. var WK_ = (function() {
  15296. function lotushopper(data, cb, opts) {
  15297. if(!data) return;
  15298. prep_blob(data, data.l || 0);
  15299. var Enum = opts.Enum || WK1Enum;
  15300. while(data.l < data.length) {
  15301. var RT = data.read_shift(2);
  15302. var R = Enum[RT] || Enum[0xFF];
  15303. var length = data.read_shift(2);
  15304. var tgt = data.l + length;
  15305. var d = (R.f||parsenoop)(data, length, opts);
  15306. data.l = tgt;
  15307. if(cb(d, R.n, RT)) return;
  15308. }
  15309. }
  15310. function lotus_to_workbook(d, opts) {
  15311. switch(opts.type) {
  15312. case 'base64': return lotus_to_workbook_buf(s2a(Base64.decode(d)), opts);
  15313. case 'binary': return lotus_to_workbook_buf(s2a(d), opts);
  15314. case 'buffer':
  15315. case 'array': return lotus_to_workbook_buf(d, opts);
  15316. }
  15317. throw "Unsupported type " + opts.type;
  15318. }
  15319. function lotus_to_workbook_buf(d, opts) {
  15320. if(!d) return d;
  15321. var o = opts || {};
  15322. if(DENSE != null && o.dense == null) o.dense = DENSE;
  15323. var s = ((o.dense ? [] : {})), n = "Sheet1", sidx = 0;
  15324. var sheets = {}, snames = [n];
  15325. var refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  15326. var sheetRows = o.sheetRows || 0;
  15327. if(d[2] == 0x02) o.Enum = WK1Enum;
  15328. else if(d[2] == 0x1a) o.Enum = WK3Enum;
  15329. else if(d[2] == 0x0e) { o.Enum = WK3Enum; o.qpro = true; d.l = 0; }
  15330. else throw new Error("Unrecognized LOTUS BOF " + d[2]);
  15331. lotushopper(d, function(val, Rn, RT) {
  15332. if(d[2] == 0x02) switch(RT) {
  15333. case 0x00:
  15334. o.vers = val;
  15335. if(val >= 0x1000) o.qpro = true;
  15336. break;
  15337. case 0x06: refguess = val; break; /* RANGE */
  15338. case 0x0F: /* LABEL */
  15339. if(!o.qpro) val[1].v = val[1].v.slice(1);
  15340. /* falls through */
  15341. case 0x0D: /* INTEGER */
  15342. case 0x0E: /* NUMBER */
  15343. case 0x10: /* FORMULA */
  15344. case 0x33: /* STRING */
  15345. /* TODO: actual translation of the format code */
  15346. if(RT == 0x0E && (val[2] & 0x70) == 0x70 && (val[2] & 0x0F) > 1 && (val[2] & 0x0F) < 15) {
  15347. val[1].z = o.dateNF || SSF._table[14];
  15348. if(o.cellDates) { val[1].t = 'd'; val[1].v = numdate(val[1].v); }
  15349. }
  15350. if(o.dense) {
  15351. if(!s[val[0].r]) s[val[0].r] = [];
  15352. s[val[0].r][val[0].c] = val[1];
  15353. } else s[encode_cell(val[0])] = val[1];
  15354. break;
  15355. } else switch(RT) {
  15356. case 0x16: /* LABEL16 */
  15357. val[1].v = val[1].v.slice(1);
  15358. /* falls through */
  15359. case 0x17: /* NUMBER17 */
  15360. case 0x18: /* NUMBER18 */
  15361. case 0x19: /* FORMULA19 */
  15362. case 0x25: /* NUMBER25 */
  15363. case 0x27: /* NUMBER27 */
  15364. case 0x28: /* FORMULA28 */
  15365. if(val[3] > sidx) {
  15366. s["!ref"] = encode_range(refguess);
  15367. sheets[n] = s;
  15368. s = (o.dense ? [] : {});
  15369. refguess = {s: {r:0, c:0}, e: {r:0, c:0} };
  15370. sidx = val[3]; n = "Sheet" + (sidx + 1);
  15371. snames.push(n);
  15372. }
  15373. if(sheetRows > 0 && val[0].r >= sheetRows) break;
  15374. if(o.dense) {
  15375. if(!s[val[0].r]) s[val[0].r] = [];
  15376. s[val[0].r][val[0].c] = val[1];
  15377. } else s[encode_cell(val[0])] = val[1];
  15378. if(refguess.e.c < val[0].c) refguess.e.c = val[0].c;
  15379. if(refguess.e.r < val[0].r) refguess.e.r = val[0].r;
  15380. break;
  15381. default: break;
  15382. }
  15383. }, o);
  15384. s["!ref"] = encode_range(refguess);
  15385. sheets[n] = s;
  15386. return { SheetNames: snames, Sheets:sheets };
  15387. }
  15388. function parse_RANGE(blob) {
  15389. var o = {s:{c:0,r:0},e:{c:0,r:0}};
  15390. o.s.c = blob.read_shift(2);
  15391. o.s.r = blob.read_shift(2);
  15392. o.e.c = blob.read_shift(2);
  15393. o.e.r = blob.read_shift(2);
  15394. if(o.s.c == 0xFFFF) o.s.c = o.e.c = o.s.r = o.e.r = 0;
  15395. return o;
  15396. }
  15397. function parse_cell(blob, length, opts) {
  15398. var o = [{c:0,r:0}, {t:'n',v:0}, 0];
  15399. if(opts.qpro && opts.vers != 0x5120) {
  15400. o[0].c = blob.read_shift(1);
  15401. blob.l++;
  15402. o[0].r = blob.read_shift(2);
  15403. blob.l+=2;
  15404. } else {
  15405. o[2] = blob.read_shift(1);
  15406. o[0].c = blob.read_shift(2); o[0].r = blob.read_shift(2);
  15407. }
  15408. return o;
  15409. }
  15410. function parse_LABEL(blob, length, opts) {
  15411. var tgt = blob.l + length;
  15412. var o = parse_cell(blob, length, opts);
  15413. o[1].t = 's';
  15414. if(opts.vers == 0x5120) {
  15415. blob.l++;
  15416. var len = blob.read_shift(1);
  15417. o[1].v = blob.read_shift(len, 'utf8');
  15418. return o;
  15419. }
  15420. if(opts.qpro) blob.l++;
  15421. o[1].v = blob.read_shift(tgt - blob.l, 'cstr');
  15422. return o;
  15423. }
  15424. function parse_INTEGER(blob, length, opts) {
  15425. var o = parse_cell(blob, length, opts);
  15426. o[1].v = blob.read_shift(2, 'i');
  15427. return o;
  15428. }
  15429. function parse_NUMBER(blob, length, opts) {
  15430. var o = parse_cell(blob, length, opts);
  15431. o[1].v = blob.read_shift(8, 'f');
  15432. return o;
  15433. }
  15434. function parse_FORMULA(blob, length, opts) {
  15435. var tgt = blob.l + length;
  15436. var o = parse_cell(blob, length, opts);
  15437. /* TODO: formula */
  15438. o[1].v = blob.read_shift(8, 'f');
  15439. if(opts.qpro) blob.l = tgt;
  15440. else {
  15441. var flen = blob.read_shift(2);
  15442. blob.l += flen;
  15443. }
  15444. return o;
  15445. }
  15446. function parse_cell_3(blob) {
  15447. var o = [{c:0,r:0}, {t:'n',v:0}, 0];
  15448. o[0].r = blob.read_shift(2); o[3] = blob[blob.l++]; o[0].c = blob[blob.l++];
  15449. return o;
  15450. }
  15451. function parse_LABEL_16(blob, length) {
  15452. var o = parse_cell_3(blob, length);
  15453. o[1].t = 's';
  15454. o[1].v = blob.read_shift(length - 4, 'cstr');
  15455. return o;
  15456. }
  15457. function parse_NUMBER_18(blob, length) {
  15458. var o = parse_cell_3(blob, length);
  15459. o[1].v = blob.read_shift(2);
  15460. var v = o[1].v >> 1;
  15461. /* TODO: figure out all of the corner cases */
  15462. if(o[1].v & 0x1) {
  15463. switch(v & 0x07) {
  15464. case 1: v = (v >> 3) * 500; break;
  15465. case 2: v = (v >> 3) / 20; break;
  15466. case 4: v = (v >> 3) / 2000; break;
  15467. case 6: v = (v >> 3) / 16; break;
  15468. case 7: v = (v >> 3) / 64; break;
  15469. default: throw "unknown NUMBER_18 encoding " + (v & 0x07);
  15470. }
  15471. }
  15472. o[1].v = v;
  15473. return o;
  15474. }
  15475. function parse_NUMBER_17(blob, length) {
  15476. var o = parse_cell_3(blob, length);
  15477. var v1 = blob.read_shift(4);
  15478. var v2 = blob.read_shift(4);
  15479. var e = blob.read_shift(2);
  15480. if(e == 0xFFFF) { o[1].v = 0; return o; }
  15481. var s = e & 0x8000; e = (e&0x7FFF) - 16446;
  15482. o[1].v = (s*2 - 1) * ((e > 0 ? (v2 << e) : (v2 >>> -e)) + (e > -32 ? (v1 << (e + 32)) : (v1 >>> -(e + 32))));
  15483. return o;
  15484. }
  15485. function parse_FORMULA_19(blob, length) {
  15486. var o = parse_NUMBER_17(blob, 14);
  15487. blob.l += length - 14; /* TODO: formula */
  15488. return o;
  15489. }
  15490. function parse_NUMBER_25(blob, length) {
  15491. var o = parse_cell_3(blob, length);
  15492. var v1 = blob.read_shift(4);
  15493. o[1].v = v1 >> 6;
  15494. return o;
  15495. }
  15496. function parse_NUMBER_27(blob, length) {
  15497. var o = parse_cell_3(blob, length);
  15498. var v1 = blob.read_shift(8,'f');
  15499. o[1].v = v1;
  15500. return o;
  15501. }
  15502. function parse_FORMULA_28(blob, length) {
  15503. var o = parse_NUMBER_27(blob, 14);
  15504. blob.l += length - 10; /* TODO: formula */
  15505. return o;
  15506. }
  15507. var WK1Enum = {
  15508. 0x0000: { n:"BOF", f:parseuint16 },
  15509. 0x0001: { n:"EOF" },
  15510. 0x0002: { n:"CALCMODE" },
  15511. 0x0003: { n:"CALCORDER" },
  15512. 0x0004: { n:"SPLIT" },
  15513. 0x0005: { n:"SYNC" },
  15514. 0x0006: { n:"RANGE", f:parse_RANGE },
  15515. 0x0007: { n:"WINDOW1" },
  15516. 0x0008: { n:"COLW1" },
  15517. 0x0009: { n:"WINTWO" },
  15518. 0x000A: { n:"COLW2" },
  15519. 0x000B: { n:"NAME" },
  15520. 0x000C: { n:"BLANK" },
  15521. 0x000D: { n:"INTEGER", f:parse_INTEGER },
  15522. 0x000E: { n:"NUMBER", f:parse_NUMBER },
  15523. 0x000F: { n:"LABEL", f:parse_LABEL },
  15524. 0x0010: { n:"FORMULA", f:parse_FORMULA },
  15525. 0x0018: { n:"TABLE" },
  15526. 0x0019: { n:"ORANGE" },
  15527. 0x001A: { n:"PRANGE" },
  15528. 0x001B: { n:"SRANGE" },
  15529. 0x001C: { n:"FRANGE" },
  15530. 0x001D: { n:"KRANGE1" },
  15531. 0x0020: { n:"HRANGE" },
  15532. 0x0023: { n:"KRANGE2" },
  15533. 0x0024: { n:"PROTEC" },
  15534. 0x0025: { n:"FOOTER" },
  15535. 0x0026: { n:"HEADER" },
  15536. 0x0027: { n:"SETUP" },
  15537. 0x0028: { n:"MARGINS" },
  15538. 0x0029: { n:"LABELFMT" },
  15539. 0x002A: { n:"TITLES" },
  15540. 0x002B: { n:"SHEETJS" },
  15541. 0x002D: { n:"GRAPH" },
  15542. 0x002E: { n:"NGRAPH" },
  15543. 0x002F: { n:"CALCCOUNT" },
  15544. 0x0030: { n:"UNFORMATTED" },
  15545. 0x0031: { n:"CURSORW12" },
  15546. 0x0032: { n:"WINDOW" },
  15547. 0x0033: { n:"STRING", f:parse_LABEL },
  15548. 0x0037: { n:"PASSWORD" },
  15549. 0x0038: { n:"LOCKED" },
  15550. 0x003C: { n:"QUERY" },
  15551. 0x003D: { n:"QUERYNAME" },
  15552. 0x003E: { n:"PRINT" },
  15553. 0x003F: { n:"PRINTNAME" },
  15554. 0x0040: { n:"GRAPH2" },
  15555. 0x0041: { n:"GRAPHNAME" },
  15556. 0x0042: { n:"ZOOM" },
  15557. 0x0043: { n:"SYMSPLIT" },
  15558. 0x0044: { n:"NSROWS" },
  15559. 0x0045: { n:"NSCOLS" },
  15560. 0x0046: { n:"RULER" },
  15561. 0x0047: { n:"NNAME" },
  15562. 0x0048: { n:"ACOMM" },
  15563. 0x0049: { n:"AMACRO" },
  15564. 0x004A: { n:"PARSE" },
  15565. 0x00FF: { n:"", f:parsenoop }
  15566. };
  15567. var WK3Enum = {
  15568. 0x0000: { n:"BOF" },
  15569. 0x0001: { n:"EOF" },
  15570. 0x0003: { n:"??" },
  15571. 0x0004: { n:"??" },
  15572. 0x0005: { n:"??" },
  15573. 0x0006: { n:"??" },
  15574. 0x0007: { n:"??" },
  15575. 0x0009: { n:"??" },
  15576. 0x000a: { n:"??" },
  15577. 0x000b: { n:"??" },
  15578. 0x000c: { n:"??" },
  15579. 0x000e: { n:"??" },
  15580. 0x000f: { n:"??" },
  15581. 0x0010: { n:"??" },
  15582. 0x0011: { n:"??" },
  15583. 0x0012: { n:"??" },
  15584. 0x0013: { n:"??" },
  15585. 0x0015: { n:"??" },
  15586. 0x0016: { n:"LABEL16", f:parse_LABEL_16},
  15587. 0x0017: { n:"NUMBER17", f:parse_NUMBER_17 },
  15588. 0x0018: { n:"NUMBER18", f:parse_NUMBER_18 },
  15589. 0x0019: { n:"FORMULA19", f:parse_FORMULA_19},
  15590. 0x001a: { n:"??" },
  15591. 0x001b: { n:"??" },
  15592. 0x001c: { n:"??" },
  15593. 0x001d: { n:"??" },
  15594. 0x001e: { n:"??" },
  15595. 0x001f: { n:"??" },
  15596. 0x0021: { n:"??" },
  15597. 0x0025: { n:"NUMBER25", f:parse_NUMBER_25 },
  15598. 0x0027: { n:"NUMBER27", f:parse_NUMBER_27 },
  15599. 0x0028: { n:"FORMULA28", f:parse_FORMULA_28 },
  15600. 0x00FF: { n:"", f:parsenoop }
  15601. };
  15602. return {
  15603. to_workbook: lotus_to_workbook
  15604. };
  15605. })();
  15606. /* 18.4.7 rPr CT_RPrElt */
  15607. function parse_rpr(rpr) {
  15608. var font = {}, m = rpr.match(tagregex), i = 0;
  15609. var pass = false;
  15610. if(m) for(;i!=m.length; ++i) {
  15611. var y = parsexmltag(m[i]);
  15612. switch(y[0].replace(/\w*:/g,"")) {
  15613. /* 18.8.12 condense CT_BooleanProperty */
  15614. /* ** not required . */
  15615. case '<condense': break;
  15616. /* 18.8.17 extend CT_BooleanProperty */
  15617. /* ** not required . */
  15618. case '<extend': break;
  15619. /* 18.8.36 shadow CT_BooleanProperty */
  15620. /* ** not required . */
  15621. case '<shadow':
  15622. if(!y.val) break;
  15623. /* falls through */
  15624. case '<shadow>':
  15625. case '<shadow/>': font.shadow = 1; break;
  15626. case '</shadow>': break;
  15627. /* 18.4.1 charset CT_IntProperty TODO */
  15628. case '<charset':
  15629. if(y.val == '1') break;
  15630. font.cp = CS2CP[parseInt(y.val, 10)];
  15631. break;
  15632. /* 18.4.2 outline CT_BooleanProperty TODO */
  15633. case '<outline':
  15634. if(!y.val) break;
  15635. /* falls through */
  15636. case '<outline>':
  15637. case '<outline/>': font.outline = 1; break;
  15638. case '</outline>': break;
  15639. /* 18.4.5 rFont CT_FontName */
  15640. case '<rFont': font.name = y.val; break;
  15641. /* 18.4.11 sz CT_FontSize */
  15642. case '<sz': font.sz = y.val; break;
  15643. /* 18.4.10 strike CT_BooleanProperty */
  15644. case '<strike':
  15645. if(!y.val) break;
  15646. /* falls through */
  15647. case '<strike>':
  15648. case '<strike/>': font.strike = 1; break;
  15649. case '</strike>': break;
  15650. /* 18.4.13 u CT_UnderlineProperty */
  15651. case '<u':
  15652. if(!y.val) break;
  15653. switch(y.val) {
  15654. case 'double': font.uval = "double"; break;
  15655. case 'singleAccounting': font.uval = "single-accounting"; break;
  15656. case 'doubleAccounting': font.uval = "double-accounting"; break;
  15657. }
  15658. /* falls through */
  15659. case '<u>':
  15660. case '<u/>': font.u = 1; break;
  15661. case '</u>': break;
  15662. /* 18.8.2 b */
  15663. case '<b':
  15664. if(y.val == '0') break;
  15665. /* falls through */
  15666. case '<b>':
  15667. case '<b/>': font.b = 1; break;
  15668. case '</b>': break;
  15669. /* 18.8.26 i */
  15670. case '<i':
  15671. if(y.val == '0') break;
  15672. /* falls through */
  15673. case '<i>':
  15674. case '<i/>': font.i = 1; break;
  15675. case '</i>': break;
  15676. /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */
  15677. case '<color':
  15678. if(y.rgb) font.color = y.rgb.slice(2,8);
  15679. break;
  15680. /* 18.8.18 family ST_FontFamily */
  15681. case '<family': font.family = y.val; break;
  15682. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */
  15683. case '<vertAlign': font.valign = y.val; break;
  15684. /* 18.8.35 scheme CT_FontScheme TODO */
  15685. case '<scheme': break;
  15686. /* 18.2.10 extLst CT_ExtensionList ? */
  15687. case '<extLst': case '<extLst>': case '</extLst>': break;
  15688. case '<ext': pass = true; break;
  15689. case '</ext>': pass = false; break;
  15690. default:
  15691. if(y[0].charCodeAt(1) !== 47 && !pass) throw new Error('Unrecognized rich format ' + y[0]);
  15692. }
  15693. }
  15694. return font;
  15695. }
  15696. var parse_rs = (function() {
  15697. var tregex = matchtag("t"), rpregex = matchtag("rPr");
  15698. /* 18.4.4 r CT_RElt */
  15699. function parse_r(r) {
  15700. /* 18.4.12 t ST_Xstring */
  15701. var t = r.match(tregex)/*, cp = 65001*/;
  15702. if(!t) return {t:"s", v:""};
  15703. var o = ({t:'s', v:unescapexml(t[1])});
  15704. var rpr = r.match(rpregex);
  15705. if(rpr) o.s = parse_rpr(rpr[1]);
  15706. return o;
  15707. }
  15708. var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/;
  15709. return function parse_rs(rs) {
  15710. return rs.replace(rregex,"").split(rend).map(parse_r).filter(function(r) { return r.v; });
  15711. };
  15712. })();
  15713. /* Parse a list of <r> tags */
  15714. var rs_to_html = (function parse_rs_factory() {
  15715. var nlregex = /(\r\n|\n)/g;
  15716. function parse_rpr2(font, intro, outro) {
  15717. var style = [];
  15718. if(font.u) style.push("text-decoration: underline;");
  15719. if(font.uval) style.push("text-underline-style:" + font.uval + ";");
  15720. if(font.sz) style.push("font-size:" + font.sz + "pt;");
  15721. if(font.outline) style.push("text-effect: outline;");
  15722. if(font.shadow) style.push("text-shadow: auto;");
  15723. intro.push('<span style="' + style.join("") + '">');
  15724. if(font.b) { intro.push("<b>"); outro.push("</b>"); }
  15725. if(font.i) { intro.push("<i>"); outro.push("</i>"); }
  15726. if(font.strike) { intro.push("<s>"); outro.push("</s>"); }
  15727. var align = font.valign || "";
  15728. if(align == "superscript" || align == "super") align = "sup";
  15729. else if(align == "subscript") align = "sub";
  15730. if(align != "") { intro.push("<" + align + ">"); outro.push("</" + align + ">"); }
  15731. outro.push("</span>");
  15732. return font;
  15733. }
  15734. /* 18.4.4 r CT_RElt */
  15735. function r_to_html(r) {
  15736. var terms = [[],r.v,[]];
  15737. if(!r.v) return "";
  15738. if(r.s) parse_rpr2(r.s, terms[0], terms[2]);
  15739. return terms[0].join("") + terms[1].replace(nlregex,'<br/>') + terms[2].join("");
  15740. }
  15741. return function parse_rs(rs) {
  15742. return rs.map(r_to_html).join("");
  15743. };
  15744. })();
  15745. /* 18.4.8 si CT_Rst */
  15746. var sitregex = /<(?:\w+:)?t[^>]*>([^<]*)<\/(?:\w+:)?t>/g, sirregex = /<(?:\w+:)?r>/;
  15747. var sirphregex = /<(?:\w+:)?rPh.*?>([\s\S]*?)<\/(?:\w+:)?rPh>/g;
  15748. function parse_si(x, opts) {
  15749. var html = opts ? opts.cellHTML : true;
  15750. var z = {};
  15751. if(!x) return { t: "" };
  15752. //var y;
  15753. /* 18.4.12 t ST_Xstring (Plaintext String) */
  15754. // TODO: is whitespace actually valid here?
  15755. if(x.match(/^\s*<(?:\w+:)?t[^>]*>/)) {
  15756. z.t = unescapexml(utf8read(x.slice(x.indexOf(">")+1).split(/<\/(?:\w+:)?t>/)[0]||""));
  15757. z.r = utf8read(x);
  15758. if(html) z.h = escapehtml(z.t);
  15759. }
  15760. /* 18.4.4 r CT_RElt (Rich Text Run) */
  15761. else if((/*y = */x.match(sirregex))) {
  15762. z.r = utf8read(x);
  15763. z.t = unescapexml(utf8read((x.replace(sirphregex, '').match(sitregex)||[]).join("").replace(tagregex,"")));
  15764. if(html) z.h = rs_to_html(parse_rs(z.r));
  15765. }
  15766. /* 18.4.3 phoneticPr CT_PhoneticPr (TODO: needed for Asian support) */
  15767. /* 18.4.6 rPh CT_PhoneticRun (TODO: needed for Asian support) */
  15768. return z;
  15769. }
  15770. /* 18.4 Shared String Table */
  15771. var sstr0 = /<(?:\w+:)?sst([^>]*)>([\s\S]*)<\/(?:\w+:)?sst>/;
  15772. var sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g;
  15773. var sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/;
  15774. function parse_sst_xml(data, opts) {
  15775. var s = ([]), ss = "";
  15776. if(!data) return s;
  15777. /* 18.4.9 sst CT_Sst */
  15778. var sst = data.match(sstr0);
  15779. if(sst) {
  15780. ss = sst[2].replace(sstr1,"").split(sstr2);
  15781. for(var i = 0; i != ss.length; ++i) {
  15782. var o = parse_si(ss[i].trim(), opts);
  15783. if(o != null) s[s.length] = o;
  15784. }
  15785. sst = parsexmltag(sst[1]); s.Count = sst.count; s.Unique = sst.uniqueCount;
  15786. }
  15787. return s;
  15788. }
  15789. RELS.SST = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
  15790. var straywsregex = /^\s|\s$|[\t\n\r]/;
  15791. function write_sst_xml(sst, opts) {
  15792. if(!opts.bookSST) return "";
  15793. var o = [XML_HEADER];
  15794. o[o.length] = (writextag('sst', null, {
  15795. xmlns: XMLNS.main[0],
  15796. count: sst.Count,
  15797. uniqueCount: sst.Unique
  15798. }));
  15799. for(var i = 0; i != sst.length; ++i) { if(sst[i] == null) continue;
  15800. var s = sst[i];
  15801. var sitag = "<si>";
  15802. if(s.r) sitag += s.r;
  15803. else {
  15804. sitag += "<t";
  15805. if(!s.t) s.t = "";
  15806. if(s.t.match(straywsregex)) sitag += ' xml:space="preserve"';
  15807. sitag += ">" + escapexml(s.t) + "</t>";
  15808. }
  15809. sitag += "</si>";
  15810. o[o.length] = (sitag);
  15811. }
  15812. if(o.length>2){ o[o.length] = ('</sst>'); o[1]=o[1].replace("/>",">"); }
  15813. return o.join("");
  15814. }
  15815. /* [MS-XLSB] 2.4.221 BrtBeginSst */
  15816. function parse_BrtBeginSst(data) {
  15817. return [data.read_shift(4), data.read_shift(4)];
  15818. }
  15819. /* [MS-XLSB] 2.1.7.45 Shared Strings */
  15820. function parse_sst_bin(data, opts) {
  15821. var s = ([]);
  15822. var pass = false;
  15823. recordhopper(data, function hopper_sst(val, R_n, RT) {
  15824. switch(RT) {
  15825. case 0x009F: /* 'BrtBeginSst' */
  15826. s.Count = val[0]; s.Unique = val[1]; break;
  15827. case 0x0013: /* 'BrtSSTItem' */
  15828. s.push(val); break;
  15829. case 0x00A0: /* 'BrtEndSst' */
  15830. return true;
  15831. case 0x0023: /* 'BrtFRTBegin' */
  15832. pass = true; break;
  15833. case 0x0024: /* 'BrtFRTEnd' */
  15834. pass = false; break;
  15835. default:
  15836. if(R_n.indexOf("Begin") > 0){/* empty */}
  15837. else if(R_n.indexOf("End") > 0){/* empty */}
  15838. if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  15839. }
  15840. });
  15841. return s;
  15842. }
  15843. function write_BrtBeginSst(sst, o) {
  15844. if(!o) o = new_buf(8);
  15845. o.write_shift(4, sst.Count);
  15846. o.write_shift(4, sst.Unique);
  15847. return o;
  15848. }
  15849. var write_BrtSSTItem = write_RichStr;
  15850. function write_sst_bin(sst) {
  15851. var ba = buf_array();
  15852. write_record(ba, "BrtBeginSst", write_BrtBeginSst(sst));
  15853. for(var i = 0; i < sst.length; ++i) write_record(ba, "BrtSSTItem", write_BrtSSTItem(sst[i]));
  15854. /* FRTSST */
  15855. write_record(ba, "BrtEndSst");
  15856. return ba.end();
  15857. }
  15858. function _JS2ANSI(str) {
  15859. if(typeof cptable !== 'undefined') return cptable.utils.encode(current_ansi, str);
  15860. var o = [], oo = str.split("");
  15861. for(var i = 0; i < oo.length; ++i) o[i] = oo[i].charCodeAt(0);
  15862. return o;
  15863. }
  15864. /* [MS-OFFCRYPTO] 2.1.4 Version */
  15865. function parse_CRYPTOVersion(blob, length) {
  15866. var o = {};
  15867. o.Major = blob.read_shift(2);
  15868. o.Minor = blob.read_shift(2);
  15869. if(length >= 4) blob.l += length - 4;
  15870. return o;
  15871. }
  15872. /* [MS-OFFCRYPTO] 2.1.5 DataSpaceVersionInfo */
  15873. function parse_DataSpaceVersionInfo(blob) {
  15874. var o = {};
  15875. o.id = blob.read_shift(0, 'lpp4');
  15876. o.R = parse_CRYPTOVersion(blob, 4);
  15877. o.U = parse_CRYPTOVersion(blob, 4);
  15878. o.W = parse_CRYPTOVersion(blob, 4);
  15879. return o;
  15880. }
  15881. /* [MS-OFFCRYPTO] 2.1.6.1 DataSpaceMapEntry Structure */
  15882. function parse_DataSpaceMapEntry(blob) {
  15883. var len = blob.read_shift(4);
  15884. var end = blob.l + len - 4;
  15885. var o = {};
  15886. var cnt = blob.read_shift(4);
  15887. var comps = [];
  15888. /* [MS-OFFCRYPTO] 2.1.6.2 DataSpaceReferenceComponent Structure */
  15889. while(cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, 'lpp4') });
  15890. o.name = blob.read_shift(0, 'lpp4');
  15891. o.comps = comps;
  15892. if(blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end);
  15893. return o;
  15894. }
  15895. /* [MS-OFFCRYPTO] 2.1.6 DataSpaceMap */
  15896. function parse_DataSpaceMap(blob) {
  15897. var o = [];
  15898. blob.l += 4; // must be 0x8
  15899. var cnt = blob.read_shift(4);
  15900. while(cnt-- > 0) o.push(parse_DataSpaceMapEntry(blob));
  15901. return o;
  15902. }
  15903. /* [MS-OFFCRYPTO] 2.1.7 DataSpaceDefinition */
  15904. function parse_DataSpaceDefinition(blob) {
  15905. var o = [];
  15906. blob.l += 4; // must be 0x8
  15907. var cnt = blob.read_shift(4);
  15908. while(cnt-- > 0) o.push(blob.read_shift(0, 'lpp4'));
  15909. return o;
  15910. }
  15911. /* [MS-OFFCRYPTO] 2.1.8 DataSpaceDefinition */
  15912. function parse_TransformInfoHeader(blob) {
  15913. var o = {};
  15914. /*var len = */blob.read_shift(4);
  15915. blob.l += 4; // must be 0x1
  15916. o.id = blob.read_shift(0, 'lpp4');
  15917. o.name = blob.read_shift(0, 'lpp4');
  15918. o.R = parse_CRYPTOVersion(blob, 4);
  15919. o.U = parse_CRYPTOVersion(blob, 4);
  15920. o.W = parse_CRYPTOVersion(blob, 4);
  15921. return o;
  15922. }
  15923. function parse_Primary(blob) {
  15924. /* [MS-OFFCRYPTO] 2.2.6 IRMDSTransformInfo */
  15925. var hdr = parse_TransformInfoHeader(blob);
  15926. /* [MS-OFFCRYPTO] 2.1.9 EncryptionTransformInfo */
  15927. hdr.ename = blob.read_shift(0, '8lpp4');
  15928. hdr.blksz = blob.read_shift(4);
  15929. hdr.cmode = blob.read_shift(4);
  15930. if(blob.read_shift(4) != 0x04) throw new Error("Bad !Primary record");
  15931. return hdr;
  15932. }
  15933. /* [MS-OFFCRYPTO] 2.3.2 Encryption Header */
  15934. function parse_EncryptionHeader(blob, length) {
  15935. var tgt = blob.l + length;
  15936. var o = {};
  15937. o.Flags = (blob.read_shift(4) & 0x3F);
  15938. blob.l += 4;
  15939. o.AlgID = blob.read_shift(4);
  15940. var valid = false;
  15941. switch(o.AlgID) {
  15942. case 0x660E: case 0x660F: case 0x6610: valid = (o.Flags == 0x24); break;
  15943. case 0x6801: valid = (o.Flags == 0x04); break;
  15944. case 0: valid = (o.Flags == 0x10 || o.Flags == 0x04 || o.Flags == 0x24); break;
  15945. default: throw 'Unrecognized encryption algorithm: ' + o.AlgID;
  15946. }
  15947. if(!valid) throw new Error("Encryption Flags/AlgID mismatch");
  15948. o.AlgIDHash = blob.read_shift(4);
  15949. o.KeySize = blob.read_shift(4);
  15950. o.ProviderType = blob.read_shift(4);
  15951. blob.l += 8;
  15952. o.CSPName = blob.read_shift((tgt-blob.l)>>1, 'utf16le');
  15953. blob.l = tgt;
  15954. return o;
  15955. }
  15956. /* [MS-OFFCRYPTO] 2.3.3 Encryption Verifier */
  15957. function parse_EncryptionVerifier(blob, length) {
  15958. var o = {}, tgt = blob.l + length;
  15959. blob.l += 4; // SaltSize must be 0x10
  15960. o.Salt = blob.slice(blob.l, blob.l+16); blob.l += 16;
  15961. o.Verifier = blob.slice(blob.l, blob.l+16); blob.l += 16;
  15962. /*var sz = */blob.read_shift(4);
  15963. o.VerifierHash = blob.slice(blob.l, tgt); blob.l = tgt;
  15964. return o;
  15965. }
  15966. /* [MS-OFFCRYPTO] 2.3.4.* EncryptionInfo Stream */
  15967. function parse_EncryptionInfo(blob) {
  15968. var vers = parse_CRYPTOVersion(blob);
  15969. switch(vers.Minor) {
  15970. case 0x02: return [vers.Minor, parse_EncInfoStd(blob, vers)];
  15971. case 0x03: return [vers.Minor, parse_EncInfoExt(blob, vers)];
  15972. case 0x04: return [vers.Minor, parse_EncInfoAgl(blob, vers)];
  15973. }
  15974. throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor);
  15975. }
  15976. /* [MS-OFFCRYPTO] 2.3.4.5 EncryptionInfo Stream (Standard Encryption) */
  15977. function parse_EncInfoStd(blob) {
  15978. var flags = blob.read_shift(4);
  15979. if((flags & 0x3F) != 0x24) throw new Error("EncryptionInfo mismatch");
  15980. var sz = blob.read_shift(4);
  15981. //var tgt = blob.l + sz;
  15982. var hdr = parse_EncryptionHeader(blob, sz);
  15983. var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
  15984. return { t:"Std", h:hdr, v:verifier };
  15985. }
  15986. /* [MS-OFFCRYPTO] 2.3.4.6 EncryptionInfo Stream (Extensible Encryption) */
  15987. function parse_EncInfoExt() { throw new Error("File is password-protected: ECMA-376 Extensible"); }
  15988. /* [MS-OFFCRYPTO] 2.3.4.10 EncryptionInfo Stream (Agile Encryption) */
  15989. function parse_EncInfoAgl(blob) {
  15990. var KeyData = ["saltSize","blockSize","keyBits","hashSize","cipherAlgorithm","cipherChaining","hashAlgorithm","saltValue"];
  15991. blob.l+=4;
  15992. var xml = blob.read_shift(blob.length - blob.l, 'utf8');
  15993. var o = {};
  15994. xml.replace(tagregex, function xml_agile(x) {
  15995. var y = parsexmltag(x);
  15996. switch(strip_ns(y[0])) {
  15997. case '<?xml': break;
  15998. case '<encryption': case '</encryption>': break;
  15999. case '<keyData': KeyData.forEach(function(k) { o[k] = y[k]; }); break;
  16000. case '<dataIntegrity': o.encryptedHmacKey = y.encryptedHmacKey; o.encryptedHmacValue = y.encryptedHmacValue; break;
  16001. case '<keyEncryptors>': case '<keyEncryptors': o.encs = []; break;
  16002. case '</keyEncryptors>': break;
  16003. case '<keyEncryptor': o.uri = y.uri; break;
  16004. case '</keyEncryptor>': break;
  16005. case '<encryptedKey': o.encs.push(y); break;
  16006. default: throw y[0];
  16007. }
  16008. });
  16009. return o;
  16010. }
  16011. /* [MS-OFFCRYPTO] 2.3.5.1 RC4 CryptoAPI Encryption Header */
  16012. function parse_RC4CryptoHeader(blob, length) {
  16013. var o = {};
  16014. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); length -= 4;
  16015. if(vers.Minor != 2) throw new Error('unrecognized minor version code: ' + vers.Minor);
  16016. if(vers.Major > 4 || vers.Major < 2) throw new Error('unrecognized major version code: ' + vers.Major);
  16017. o.Flags = blob.read_shift(4); length -= 4;
  16018. var sz = blob.read_shift(4); length -= 4;
  16019. o.EncryptionHeader = parse_EncryptionHeader(blob, sz); length -= sz;
  16020. o.EncryptionVerifier = parse_EncryptionVerifier(blob, length);
  16021. return o;
  16022. }
  16023. /* [MS-OFFCRYPTO] 2.3.6.1 RC4 Encryption Header */
  16024. function parse_RC4Header(blob) {
  16025. var o = {};
  16026. var vers = o.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4);
  16027. if(vers.Major != 1 || vers.Minor != 1) throw 'unrecognized version code ' + vers.Major + ' : ' + vers.Minor;
  16028. o.Salt = blob.read_shift(16);
  16029. o.EncryptedVerifier = blob.read_shift(16);
  16030. o.EncryptedVerifierHash = blob.read_shift(16);
  16031. return o;
  16032. }
  16033. /* [MS-OFFCRYPTO] 2.3.7.1 Binary Document Password Verifier Derivation */
  16034. function crypto_CreatePasswordVerifier_Method1(Password) {
  16035. var Verifier = 0x0000, PasswordArray;
  16036. var PasswordDecoded = _JS2ANSI(Password);
  16037. var len = PasswordDecoded.length + 1, i, PasswordByte;
  16038. var Intermediate1, Intermediate2, Intermediate3;
  16039. PasswordArray = new_raw_buf(len);
  16040. PasswordArray[0] = PasswordDecoded.length;
  16041. for(i = 1; i != len; ++i) PasswordArray[i] = PasswordDecoded[i-1];
  16042. for(i = len-1; i >= 0; --i) {
  16043. PasswordByte = PasswordArray[i];
  16044. Intermediate1 = ((Verifier & 0x4000) === 0x0000) ? 0 : 1;
  16045. Intermediate2 = (Verifier << 1) & 0x7FFF;
  16046. Intermediate3 = Intermediate1 | Intermediate2;
  16047. Verifier = Intermediate3 ^ PasswordByte;
  16048. }
  16049. return Verifier ^ 0xCE4B;
  16050. }
  16051. /* [MS-OFFCRYPTO] 2.3.7.2 Binary Document XOR Array Initialization */
  16052. var crypto_CreateXorArray_Method1 = (function() {
  16053. var PadArray = [0xBB, 0xFF, 0xFF, 0xBA, 0xFF, 0xFF, 0xB9, 0x80, 0x00, 0xBE, 0x0F, 0x00, 0xBF, 0x0F, 0x00];
  16054. var InitialCode = [0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3];
  16055. var XorMatrix = [0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09, 0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF, 0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0, 0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40, 0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5, 0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A, 0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9, 0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0, 0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC, 0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10, 0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168, 0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C, 0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD, 0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC, 0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4];
  16056. var Ror = function(Byte) { return ((Byte/2) | (Byte*128)) & 0xFF; };
  16057. var XorRor = function(byte1, byte2) { return Ror(byte1 ^ byte2); };
  16058. var CreateXorKey_Method1 = function(Password) {
  16059. var XorKey = InitialCode[Password.length - 1];
  16060. var CurrentElement = 0x68;
  16061. for(var i = Password.length-1; i >= 0; --i) {
  16062. var Char = Password[i];
  16063. for(var j = 0; j != 7; ++j) {
  16064. if(Char & 0x40) XorKey ^= XorMatrix[CurrentElement];
  16065. Char *= 2; --CurrentElement;
  16066. }
  16067. }
  16068. return XorKey;
  16069. };
  16070. return function(password) {
  16071. var Password = _JS2ANSI(password);
  16072. var XorKey = CreateXorKey_Method1(Password);
  16073. var Index = Password.length;
  16074. var ObfuscationArray = new_raw_buf(16);
  16075. for(var i = 0; i != 16; ++i) ObfuscationArray[i] = 0x00;
  16076. var Temp, PasswordLastChar, PadIndex;
  16077. if((Index & 1) === 1) {
  16078. Temp = XorKey >> 8;
  16079. ObfuscationArray[Index] = XorRor(PadArray[0], Temp);
  16080. --Index;
  16081. Temp = XorKey & 0xFF;
  16082. PasswordLastChar = Password[Password.length - 1];
  16083. ObfuscationArray[Index] = XorRor(PasswordLastChar, Temp);
  16084. }
  16085. while(Index > 0) {
  16086. --Index;
  16087. Temp = XorKey >> 8;
  16088. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  16089. --Index;
  16090. Temp = XorKey & 0xFF;
  16091. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  16092. }
  16093. Index = 15;
  16094. PadIndex = 15 - Password.length;
  16095. while(PadIndex > 0) {
  16096. Temp = XorKey >> 8;
  16097. ObfuscationArray[Index] = XorRor(PadArray[PadIndex], Temp);
  16098. --Index;
  16099. --PadIndex;
  16100. Temp = XorKey & 0xFF;
  16101. ObfuscationArray[Index] = XorRor(Password[Index], Temp);
  16102. --Index;
  16103. --PadIndex;
  16104. }
  16105. return ObfuscationArray;
  16106. };
  16107. })();
  16108. /* [MS-OFFCRYPTO] 2.3.7.3 Binary Document XOR Data Transformation Method 1 */
  16109. var crypto_DecryptData_Method1 = function(password, Data, XorArrayIndex, XorArray, O) {
  16110. /* If XorArray is set, use it; if O is not set, make changes in-place */
  16111. if(!O) O = Data;
  16112. if(!XorArray) XorArray = crypto_CreateXorArray_Method1(password);
  16113. var Index, Value;
  16114. for(Index = 0; Index != Data.length; ++Index) {
  16115. Value = Data[Index];
  16116. Value ^= XorArray[XorArrayIndex];
  16117. Value = ((Value>>5) | (Value<<3)) & 0xFF;
  16118. O[Index] = Value;
  16119. ++XorArrayIndex;
  16120. }
  16121. return [O, XorArrayIndex, XorArray];
  16122. };
  16123. var crypto_MakeXorDecryptor = function(password) {
  16124. var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password);
  16125. return function(Data) {
  16126. var O = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray);
  16127. XorArrayIndex = O[1];
  16128. return O[0];
  16129. };
  16130. };
  16131. /* 2.5.343 */
  16132. function parse_XORObfuscation(blob, length, opts, out) {
  16133. var o = ({ key: parseuint16(blob), verificationBytes: parseuint16(blob) });
  16134. if(opts.password) o.verifier = crypto_CreatePasswordVerifier_Method1(opts.password);
  16135. out.valid = o.verificationBytes === o.verifier;
  16136. if(out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password);
  16137. return o;
  16138. }
  16139. /* 2.4.117 */
  16140. function parse_FilePassHeader(blob, length, oo) {
  16141. var o = oo || {}; o.Info = blob.read_shift(2); blob.l -= 2;
  16142. if(o.Info === 1) o.Data = parse_RC4Header(blob, length);
  16143. else o.Data = parse_RC4CryptoHeader(blob, length);
  16144. return o;
  16145. }
  16146. function parse_FilePass(blob, length, opts) {
  16147. var o = ({ Type: opts.biff >= 8 ? blob.read_shift(2) : 0 }); /* wEncryptionType */
  16148. if(o.Type) parse_FilePassHeader(blob, length-2, o);
  16149. else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o);
  16150. return o;
  16151. }
  16152. var RTF = (function() {
  16153. function rtf_to_sheet(d, opts) {
  16154. switch(opts.type) {
  16155. case 'base64': return rtf_to_sheet_str(Base64.decode(d), opts);
  16156. case 'binary': return rtf_to_sheet_str(d, opts);
  16157. case 'buffer': return rtf_to_sheet_str(d.toString('binary'), opts);
  16158. case 'array': return rtf_to_sheet_str(cc2str(d), opts);
  16159. }
  16160. throw new Error("Unrecognized type " + opts.type);
  16161. }
  16162. function rtf_to_sheet_str(str, opts) {
  16163. var o = opts || {};
  16164. var ws = o.dense ? ([]) : ({});
  16165. var range = ({s: {c:0, r:0}, e: {c:0, r:0}});
  16166. // TODO: parse
  16167. if(!str.match(/\\trowd/)) throw new Error("RTF missing table");
  16168. ws['!ref'] = encode_range(range);
  16169. return ws;
  16170. }
  16171. function rtf_to_workbook(d, opts) { return sheet_to_workbook(rtf_to_sheet(d, opts), opts); }
  16172. /* TODO: this is a stub */
  16173. function sheet_to_rtf(ws) {
  16174. var o = ["{\\rtf1\\ansi"];
  16175. var r = safe_decode_range(ws['!ref']), cell;
  16176. var dense = Array.isArray(ws);
  16177. for(var R = r.s.r; R <= r.e.r; ++R) {
  16178. o.push("\\trowd\\trautofit1");
  16179. for(var C = r.s.c; C <= r.e.c; ++C) o.push("\\cellx" + (C+1));
  16180. o.push("\\pard\\intbl");
  16181. for(C = r.s.c; C <= r.e.c; ++C) {
  16182. var coord = encode_cell({r:R,c:C});
  16183. cell = dense ? (ws[R]||[])[C]: ws[coord];
  16184. if(!cell || cell.v == null && (!cell.f || cell.F)) continue;
  16185. o.push(" " + (cell.w || (format_cell(cell), cell.w)));
  16186. o.push("\\cell");
  16187. }
  16188. o.push("\\pard\\intbl\\row");
  16189. }
  16190. return o.join("") + "}";
  16191. }
  16192. return {
  16193. to_workbook: rtf_to_workbook,
  16194. to_sheet: rtf_to_sheet,
  16195. from_sheet: sheet_to_rtf
  16196. };
  16197. })();
  16198. function hex2RGB(h) {
  16199. var o = h.slice(h[0]==="#"?1:0).slice(0,6);
  16200. return [parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];
  16201. }
  16202. function rgb2Hex(rgb) {
  16203. for(var i=0,o=1; i!=3; ++i) o = o*256 + (rgb[i]>255?255:rgb[i]<0?0:rgb[i]);
  16204. return o.toString(16).toUpperCase().slice(1);
  16205. }
  16206. function rgb2HSL(rgb) {
  16207. var R = rgb[0]/255, G = rgb[1]/255, B=rgb[2]/255;
  16208. var M = Math.max(R, G, B), m = Math.min(R, G, B), C = M - m;
  16209. if(C === 0) return [0, 0, R];
  16210. var H6 = 0, S = 0, L2 = (M + m);
  16211. S = C / (L2 > 1 ? 2 - L2 : L2);
  16212. switch(M){
  16213. case R: H6 = ((G - B) / C + 6)%6; break;
  16214. case G: H6 = ((B - R) / C + 2); break;
  16215. case B: H6 = ((R - G) / C + 4); break;
  16216. }
  16217. return [H6 / 6, S, L2 / 2];
  16218. }
  16219. function hsl2RGB(hsl){
  16220. var H = hsl[0], S = hsl[1], L = hsl[2];
  16221. var C = S * 2 * (L < 0.5 ? L : 1 - L), m = L - C/2;
  16222. var rgb = [m,m,m], h6 = 6*H;
  16223. var X;
  16224. if(S !== 0) switch(h6|0) {
  16225. case 0: case 6: X = C * h6; rgb[0] += C; rgb[1] += X; break;
  16226. case 1: X = C * (2 - h6); rgb[0] += X; rgb[1] += C; break;
  16227. case 2: X = C * (h6 - 2); rgb[1] += C; rgb[2] += X; break;
  16228. case 3: X = C * (4 - h6); rgb[1] += X; rgb[2] += C; break;
  16229. case 4: X = C * (h6 - 4); rgb[2] += C; rgb[0] += X; break;
  16230. case 5: X = C * (6 - h6); rgb[2] += X; rgb[0] += C; break;
  16231. }
  16232. for(var i = 0; i != 3; ++i) rgb[i] = Math.round(rgb[i]*255);
  16233. return rgb;
  16234. }
  16235. /* 18.8.3 bgColor tint algorithm */
  16236. function rgb_tint(hex, tint) {
  16237. if(tint === 0) return hex;
  16238. var hsl = rgb2HSL(hex2RGB(hex));
  16239. if (tint < 0) hsl[2] = hsl[2] * (1 + tint);
  16240. else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint);
  16241. return rgb2Hex(hsl2RGB(hsl));
  16242. }
  16243. /* 18.3.1.13 width calculations */
  16244. /* [MS-OI29500] 2.1.595 Column Width & Formatting */
  16245. var DEF_MDW = 6, MAX_MDW = 15, MIN_MDW = 1, MDW = DEF_MDW;
  16246. function width2px(width) { return Math.floor(( width + (Math.round(128/MDW))/256 )* MDW ); }
  16247. function px2char(px) { return (Math.floor((px - 5)/MDW * 100 + 0.5))/100; }
  16248. function char2width(chr) { return (Math.round((chr * MDW + 5)/MDW*256))/256; }
  16249. //function px2char_(px) { return (((px - 5)/MDW * 100 + 0.5))/100; }
  16250. //function char2width_(chr) { return (((chr * MDW + 5)/MDW*256))/256; }
  16251. function cycle_width(collw) { return char2width(px2char(width2px(collw))); }
  16252. /* XLSX2/XLSB/XLS specify width in units of MDW */
  16253. function find_mdw_colw(collw) {
  16254. var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW;
  16255. if(delta > 0.005) for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) if(Math.abs(collw - cycle_width(collw)) <= delta) { delta = Math.abs(collw - cycle_width(collw)); _MDW = MDW; }
  16256. MDW = _MDW;
  16257. }
  16258. /* XLML specifies width in terms of pixels */
  16259. /*function find_mdw_wpx(wpx) {
  16260. var delta = Infinity, guess = 0, _MDW = MIN_MDW;
  16261. for(MDW=MIN_MDW; MDW<MAX_MDW; ++MDW) {
  16262. guess = char2width_(px2char_(wpx))*256;
  16263. guess = (guess) % 1;
  16264. if(guess > 0.5) guess--;
  16265. if(Math.abs(guess) < delta) { delta = Math.abs(guess); _MDW = MDW; }
  16266. }
  16267. MDW = _MDW;
  16268. }*/
  16269. function process_col(coll) {
  16270. if(coll.width) {
  16271. coll.wpx = width2px(coll.width);
  16272. coll.wch = px2char(coll.wpx);
  16273. coll.MDW = MDW;
  16274. } else if(coll.wpx) {
  16275. coll.wch = px2char(coll.wpx);
  16276. coll.width = char2width(coll.wch);
  16277. coll.MDW = MDW;
  16278. } else if(typeof coll.wch == 'number') {
  16279. coll.width = char2width(coll.wch);
  16280. coll.wpx = width2px(coll.width);
  16281. coll.MDW = MDW;
  16282. }
  16283. if(coll.customWidth) delete coll.customWidth;
  16284. }
  16285. var DEF_PPI = 96, PPI = DEF_PPI;
  16286. function px2pt(px) { return px * 96 / PPI; }
  16287. function pt2px(pt) { return pt * PPI / 96; }
  16288. /* [MS-EXSPXML3] 2.4.54 ST_enmPattern */
  16289. var XLMLPatternTypeMap = {
  16290. "None": "none",
  16291. "Solid": "solid",
  16292. "Gray50": "mediumGray",
  16293. "Gray75": "darkGray",
  16294. "Gray25": "lightGray",
  16295. "HorzStripe": "darkHorizontal",
  16296. "VertStripe": "darkVertical",
  16297. "ReverseDiagStripe": "darkDown",
  16298. "DiagStripe": "darkUp",
  16299. "DiagCross": "darkGrid",
  16300. "ThickDiagCross": "darkTrellis",
  16301. "ThinHorzStripe": "lightHorizontal",
  16302. "ThinVertStripe": "lightVertical",
  16303. "ThinReverseDiagStripe": "lightDown",
  16304. "ThinHorzCross": "lightGrid"
  16305. };
  16306. /* 18.8.5 borders CT_Borders */
  16307. function parse_borders(t, styles, themes, opts) {
  16308. styles.Borders = [];
  16309. var border = {};
  16310. var pass = false;
  16311. (t[0].match(tagregex)||[]).forEach(function(x) {
  16312. var y = parsexmltag(x);
  16313. switch(strip_ns(y[0])) {
  16314. case '<borders': case '<borders>': case '</borders>': break;
  16315. /* 18.8.4 border CT_Border */
  16316. case '<border': case '<border>': case '<border/>':
  16317. border = {};
  16318. if(y.diagonalUp) border.diagonalUp = parsexmlbool(y.diagonalUp);
  16319. if(y.diagonalDown) border.diagonalDown = parsexmlbool(y.diagonalDown);
  16320. styles.Borders.push(border);
  16321. break;
  16322. case '</border>': break;
  16323. /* note: not in spec, appears to be CT_BorderPr */
  16324. case '<left/>': break;
  16325. case '<left': case '<left>': break;
  16326. case '</left>': break;
  16327. /* note: not in spec, appears to be CT_BorderPr */
  16328. case '<right/>': break;
  16329. case '<right': case '<right>': break;
  16330. case '</right>': break;
  16331. /* 18.8.43 top CT_BorderPr */
  16332. case '<top/>': break;
  16333. case '<top': case '<top>': break;
  16334. case '</top>': break;
  16335. /* 18.8.6 bottom CT_BorderPr */
  16336. case '<bottom/>': break;
  16337. case '<bottom': case '<bottom>': break;
  16338. case '</bottom>': break;
  16339. /* 18.8.13 diagonal CT_BorderPr */
  16340. case '<diagonal': case '<diagonal>': case '<diagonal/>': break;
  16341. case '</diagonal>': break;
  16342. /* 18.8.25 horizontal CT_BorderPr */
  16343. case '<horizontal': case '<horizontal>': case '<horizontal/>': break;
  16344. case '</horizontal>': break;
  16345. /* 18.8.44 vertical CT_BorderPr */
  16346. case '<vertical': case '<vertical>': case '<vertical/>': break;
  16347. case '</vertical>': break;
  16348. /* 18.8.37 start CT_BorderPr */
  16349. case '<start': case '<start>': case '<start/>': break;
  16350. case '</start>': break;
  16351. /* 18.8.16 end CT_BorderPr */
  16352. case '<end': case '<end>': case '<end/>': break;
  16353. case '</end>': break;
  16354. /* 18.8.? color CT_Color */
  16355. case '<color': case '<color>':
  16356. break;
  16357. case '<color/>': case '</color>': break;
  16358. /* 18.2.10 extLst CT_ExtensionList ? */
  16359. case '<extLst': case '<extLst>': case '</extLst>': break;
  16360. case '<ext': pass = true; break;
  16361. case '</ext>': pass = false; break;
  16362. default: if(opts && opts.WTF) {
  16363. if(!pass) throw new Error('unrecognized ' + y[0] + ' in borders');
  16364. }
  16365. }
  16366. });
  16367. }
  16368. /* 18.8.21 fills CT_Fills */
  16369. function parse_fills(t, styles, themes, opts) {
  16370. styles.Fills = [];
  16371. var fill = {};
  16372. var pass = false;
  16373. (t[0].match(tagregex)||[]).forEach(function(x) {
  16374. var y = parsexmltag(x);
  16375. switch(strip_ns(y[0])) {
  16376. case '<fills': case '<fills>': case '</fills>': break;
  16377. /* 18.8.20 fill CT_Fill */
  16378. case '<fill>': case '<fill': case '<fill/>':
  16379. fill = {}; styles.Fills.push(fill); break;
  16380. case '</fill>': break;
  16381. /* 18.8.24 gradientFill CT_GradientFill */
  16382. case '<gradientFill>': break;
  16383. case '<gradientFill':
  16384. case '</gradientFill>': styles.Fills.push(fill); fill = {}; break;
  16385. /* 18.8.32 patternFill CT_PatternFill */
  16386. case '<patternFill': case '<patternFill>':
  16387. if(y.patternType) fill.patternType = y.patternType;
  16388. break;
  16389. case '<patternFill/>': case '</patternFill>': break;
  16390. /* 18.8.3 bgColor CT_Color */
  16391. case '<bgColor':
  16392. if(!fill.bgColor) fill.bgColor = {};
  16393. if(y.indexed) fill.bgColor.indexed = parseInt(y.indexed, 10);
  16394. if(y.theme) fill.bgColor.theme = parseInt(y.theme, 10);
  16395. if(y.tint) fill.bgColor.tint = parseFloat(y.tint);
  16396. /* Excel uses ARGB strings */
  16397. if(y.rgb) fill.bgColor.rgb = y.rgb.slice(-6);
  16398. break;
  16399. case '<bgColor/>': case '</bgColor>': break;
  16400. /* 18.8.19 fgColor CT_Color */
  16401. case '<fgColor':
  16402. if(!fill.fgColor) fill.fgColor = {};
  16403. if(y.theme) fill.fgColor.theme = parseInt(y.theme, 10);
  16404. if(y.tint) fill.fgColor.tint = parseFloat(y.tint);
  16405. /* Excel uses ARGB strings */
  16406. if(y.rgb != null) fill.fgColor.rgb = y.rgb.slice(-6);
  16407. break;
  16408. case '<fgColor/>': case '</fgColor>': break;
  16409. /* 18.8.38 stop CT_GradientStop */
  16410. case '<stop': case '<stop/>': break;
  16411. case '</stop>': break;
  16412. /* 18.8.? color CT_Color */
  16413. case '<color': case '<color/>': break;
  16414. case '</color>': break;
  16415. /* 18.2.10 extLst CT_ExtensionList ? */
  16416. case '<extLst': case '<extLst>': case '</extLst>': break;
  16417. case '<ext': pass = true; break;
  16418. case '</ext>': pass = false; break;
  16419. default: if(opts && opts.WTF) {
  16420. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fills');
  16421. }
  16422. }
  16423. });
  16424. }
  16425. /* 18.8.23 fonts CT_Fonts */
  16426. function parse_fonts(t, styles, themes, opts) {
  16427. styles.Fonts = [];
  16428. var font = {};
  16429. var pass = false;
  16430. (t[0].match(tagregex)||[]).forEach(function(x) {
  16431. var y = parsexmltag(x);
  16432. switch(strip_ns(y[0])) {
  16433. case '<fonts': case '<fonts>': case '</fonts>': break;
  16434. /* 18.8.22 font CT_Font */
  16435. case '<font': case '<font>': break;
  16436. case '</font>': case '<font/>':
  16437. styles.Fonts.push(font);
  16438. font = {};
  16439. break;
  16440. /* 18.8.29 name CT_FontName */
  16441. case '<name': if(y.val) font.name = utf8read(y.val); break;
  16442. case '<name/>': case '</name>': break;
  16443. /* 18.8.2 b CT_BooleanProperty */
  16444. case '<b': font.bold = y.val ? parsexmlbool(y.val) : 1; break;
  16445. case '<b/>': font.bold = 1; break;
  16446. /* 18.8.26 i CT_BooleanProperty */
  16447. case '<i': font.italic = y.val ? parsexmlbool(y.val) : 1; break;
  16448. case '<i/>': font.italic = 1; break;
  16449. /* 18.4.13 u CT_UnderlineProperty */
  16450. case '<u':
  16451. switch(y.val) {
  16452. case "none": font.underline = 0x00; break;
  16453. case "single": font.underline = 0x01; break;
  16454. case "double": font.underline = 0x02; break;
  16455. case "singleAccounting": font.underline = 0x21; break;
  16456. case "doubleAccounting": font.underline = 0x22; break;
  16457. } break;
  16458. case '<u/>': font.underline = 1; break;
  16459. /* 18.4.10 strike CT_BooleanProperty */
  16460. case '<strike': font.strike = y.val ? parsexmlbool(y.val) : 1; break;
  16461. case '<strike/>': font.strike = 1; break;
  16462. /* 18.4.2 outline CT_BooleanProperty */
  16463. case '<outline': font.outline = y.val ? parsexmlbool(y.val) : 1; break;
  16464. case '<outline/>': font.outline = 1; break;
  16465. /* 18.8.36 shadow CT_BooleanProperty */
  16466. case '<shadow': font.shadow = y.val ? parsexmlbool(y.val) : 1; break;
  16467. case '<shadow/>': font.shadow = 1; break;
  16468. /* 18.8.12 condense CT_BooleanProperty */
  16469. case '<condense': font.condense = y.val ? parsexmlbool(y.val) : 1; break;
  16470. case '<condense/>': font.condense = 1; break;
  16471. /* 18.8.17 extend CT_BooleanProperty */
  16472. case '<extend': font.extend = y.val ? parsexmlbool(y.val) : 1; break;
  16473. case '<extend/>': font.extend = 1; break;
  16474. /* 18.4.11 sz CT_FontSize */
  16475. case '<sz': if(y.val) font.sz = +y.val; break;
  16476. case '<sz/>': case '</sz>': break;
  16477. /* 18.4.14 vertAlign CT_VerticalAlignFontProperty */
  16478. case '<vertAlign': if(y.val) font.vertAlign = y.val; break;
  16479. case '<vertAlign/>': case '</vertAlign>': break;
  16480. /* 18.8.18 family CT_FontFamily */
  16481. case '<family': if(y.val) font.family = parseInt(y.val,10); break;
  16482. case '<family/>': case '</family>': break;
  16483. /* 18.8.35 scheme CT_FontScheme */
  16484. case '<scheme': if(y.val) font.scheme = y.val; break;
  16485. case '<scheme/>': case '</scheme>': break;
  16486. /* 18.4.1 charset CT_IntProperty */
  16487. case '<charset':
  16488. if(y.val == '1') break;
  16489. y.codepage = CS2CP[parseInt(y.val, 10)];
  16490. break;
  16491. /* 18.?.? color CT_Color */
  16492. case '<color':
  16493. if(!font.color) font.color = {};
  16494. if(y.auto) font.color.auto = parsexmlbool(y.auto);
  16495. if(y.rgb) font.color.rgb = y.rgb.slice(-6);
  16496. else if(y.indexed) {
  16497. font.color.index = parseInt(y.indexed, 10);
  16498. var icv = XLSIcv[font.color.index];
  16499. if(font.color.index == 81) icv = XLSIcv[1];
  16500. if(!icv) throw new Error(x);
  16501. font.color.rgb = icv[0].toString(16) + icv[1].toString(16) + icv[2].toString(16);
  16502. } else if(y.theme) {
  16503. font.color.theme = parseInt(y.theme, 10);
  16504. if(y.tint) font.color.tint = parseFloat(y.tint);
  16505. if(y.theme && themes.themeElements && themes.themeElements.clrScheme) {
  16506. font.color.rgb = rgb_tint(themes.themeElements.clrScheme[font.color.theme].rgb, font.color.tint || 0);
  16507. }
  16508. }
  16509. break;
  16510. case '<color/>': case '</color>': break;
  16511. /* note: sometimes mc:AlternateContent appears bare */
  16512. case '<AlternateContent': pass = true; break;
  16513. case '</AlternateContent>': pass = false; break;
  16514. /* 18.2.10 extLst CT_ExtensionList ? */
  16515. case '<extLst': case '<extLst>': case '</extLst>': break;
  16516. case '<ext': pass = true; break;
  16517. case '</ext>': pass = false; break;
  16518. default: if(opts && opts.WTF) {
  16519. if(!pass) throw new Error('unrecognized ' + y[0] + ' in fonts');
  16520. }
  16521. }
  16522. });
  16523. }
  16524. /* 18.8.31 numFmts CT_NumFmts */
  16525. function parse_numFmts(t, styles, opts) {
  16526. styles.NumberFmt = [];
  16527. var k/*Array<number>*/ = (keys(SSF._table));
  16528. for(var i=0; i < k.length; ++i) styles.NumberFmt[k[i]] = SSF._table[k[i]];
  16529. var m = t[0].match(tagregex);
  16530. if(!m) return;
  16531. for(i=0; i < m.length; ++i) {
  16532. var y = parsexmltag(m[i]);
  16533. switch(strip_ns(y[0])) {
  16534. case '<numFmts': case '</numFmts>': case '<numFmts/>': case '<numFmts>': break;
  16535. case '<numFmt': {
  16536. var f=unescapexml(utf8read(y.formatCode)), j=parseInt(y.numFmtId,10);
  16537. styles.NumberFmt[j] = f;
  16538. if(j>0) {
  16539. if(j > 0x188) {
  16540. for(j = 0x188; j > 0x3c; --j) if(styles.NumberFmt[j] == null) break;
  16541. styles.NumberFmt[j] = f;
  16542. }
  16543. SSF.load(f,j);
  16544. }
  16545. } break;
  16546. case '</numFmt>': break;
  16547. default: if(opts.WTF) throw new Error('unrecognized ' + y[0] + ' in numFmts');
  16548. }
  16549. }
  16550. }
  16551. function write_numFmts(NF) {
  16552. var o = ["<numFmts>"];
  16553. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  16554. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) o[o.length] = (writextag('numFmt',null,{numFmtId:i,formatCode:escapexml(NF[i])}));
  16555. });
  16556. if(o.length === 1) return "";
  16557. o[o.length] = ("</numFmts>");
  16558. o[0] = writextag('numFmts', null, { count:o.length-2 }).replace("/>", ">");
  16559. return o.join("");
  16560. }
  16561. /* 18.8.10 cellXfs CT_CellXfs */
  16562. var cellXF_uint = [ "numFmtId", "fillId", "fontId", "borderId", "xfId" ];
  16563. var cellXF_bool = [ "applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix" ];
  16564. function parse_cellXfs(t, styles, opts) {
  16565. styles.CellXf = [];
  16566. var xf;
  16567. var pass = false;
  16568. (t[0].match(tagregex)||[]).forEach(function(x) {
  16569. var y = parsexmltag(x), i = 0;
  16570. switch(strip_ns(y[0])) {
  16571. case '<cellXfs': case '<cellXfs>': case '<cellXfs/>': case '</cellXfs>': break;
  16572. /* 18.8.45 xf CT_Xf */
  16573. case '<xf': case '<xf/>':
  16574. xf = y;
  16575. delete xf[0];
  16576. for(i = 0; i < cellXF_uint.length; ++i) if(xf[cellXF_uint[i]])
  16577. xf[cellXF_uint[i]] = parseInt(xf[cellXF_uint[i]], 10);
  16578. for(i = 0; i < cellXF_bool.length; ++i) if(xf[cellXF_bool[i]])
  16579. xf[cellXF_bool[i]] = parsexmlbool(xf[cellXF_bool[i]]);
  16580. if(xf.numFmtId > 0x188) {
  16581. for(i = 0x188; i > 0x3c; --i) if(styles.NumberFmt[xf.numFmtId] == styles.NumberFmt[i]) { xf.numFmtId = i; break; }
  16582. }
  16583. styles.CellXf.push(xf); break;
  16584. case '</xf>': break;
  16585. /* 18.8.1 alignment CT_CellAlignment */
  16586. case '<alignment': case '<alignment/>':
  16587. var alignment = {};
  16588. if(y.vertical) alignment.vertical = y.vertical;
  16589. if(y.horizontal) alignment.horizontal = y.horizontal;
  16590. if(y.textRotation != null) alignment.textRotation = y.textRotation;
  16591. if(y.indent) alignment.indent = y.indent;
  16592. if(y.wrapText) alignment.wrapText = parsexmlbool(y.wrapText);
  16593. xf.alignment = alignment;
  16594. break;
  16595. case '</alignment>': break;
  16596. /* 18.8.33 protection CT_CellProtection */
  16597. case '<protection':
  16598. break;
  16599. case '</protection>': case '<protection/>': break;
  16600. /* note: sometimes mc:AlternateContent appears bare */
  16601. case '<AlternateContent': pass = true; break;
  16602. case '</AlternateContent>': pass = false; break;
  16603. /* 18.2.10 extLst CT_ExtensionList ? */
  16604. case '<extLst': case '<extLst>': case '</extLst>': break;
  16605. case '<ext': pass = true; break;
  16606. case '</ext>': pass = false; break;
  16607. default: if(opts && opts.WTF) {
  16608. if(!pass) throw new Error('unrecognized ' + y[0] + ' in cellXfs');
  16609. }
  16610. }
  16611. });
  16612. }
  16613. function write_cellXfs(cellXfs) {
  16614. var o = [];
  16615. o[o.length] = (writextag('cellXfs',null));
  16616. cellXfs.forEach(function(c) {
  16617. o[o.length] = (writextag('xf', null, c));
  16618. });
  16619. o[o.length] = ("</cellXfs>");
  16620. if(o.length === 2) return "";
  16621. o[0] = writextag('cellXfs',null, {count:o.length-2}).replace("/>",">");
  16622. return o.join("");
  16623. }
  16624. /* 18.8 Styles CT_Stylesheet*/
  16625. var parse_sty_xml= (function make_pstyx() {
  16626. var numFmtRegex = /<(?:\w+:)?numFmts([^>]*)>[\S\s]*?<\/(?:\w+:)?numFmts>/;
  16627. var cellXfRegex = /<(?:\w+:)?cellXfs([^>]*)>[\S\s]*?<\/(?:\w+:)?cellXfs>/;
  16628. var fillsRegex = /<(?:\w+:)?fills([^>]*)>[\S\s]*?<\/(?:\w+:)?fills>/;
  16629. var fontsRegex = /<(?:\w+:)?fonts([^>]*)>[\S\s]*?<\/(?:\w+:)?fonts>/;
  16630. var bordersRegex = /<(?:\w+:)?borders([^>]*)>[\S\s]*?<\/(?:\w+:)?borders>/;
  16631. return function parse_sty_xml(data, themes, opts) {
  16632. var styles = {};
  16633. if(!data) return styles;
  16634. data = data.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  16635. /* 18.8.39 styleSheet CT_Stylesheet */
  16636. var t;
  16637. /* 18.8.31 numFmts CT_NumFmts ? */
  16638. if((t=data.match(numFmtRegex))) parse_numFmts(t, styles, opts);
  16639. /* 18.8.23 fonts CT_Fonts ? */
  16640. if((t=data.match(fontsRegex))) parse_fonts(t, styles, themes, opts);
  16641. /* 18.8.21 fills CT_Fills ? */
  16642. if((t=data.match(fillsRegex))) parse_fills(t, styles, themes, opts);
  16643. /* 18.8.5 borders CT_Borders ? */
  16644. if((t=data.match(bordersRegex))) parse_borders(t, styles, themes, opts);
  16645. /* 18.8.9 cellStyleXfs CT_CellStyleXfs ? */
  16646. /* 18.8.8 cellStyles CT_CellStyles ? */
  16647. /* 18.8.10 cellXfs CT_CellXfs ? */
  16648. if((t=data.match(cellXfRegex))) parse_cellXfs(t, styles, opts);
  16649. /* 18.8.15 dxfs CT_Dxfs ? */
  16650. /* 18.8.42 tableStyles CT_TableStyles ? */
  16651. /* 18.8.11 colors CT_Colors ? */
  16652. /* 18.2.10 extLst CT_ExtensionList ? */
  16653. return styles;
  16654. };
  16655. })();
  16656. var STYLES_XML_ROOT = writextag('styleSheet', null, {
  16657. 'xmlns': XMLNS.main[0],
  16658. 'xmlns:vt': XMLNS.vt
  16659. });
  16660. RELS.STY = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
  16661. function write_sty_xml(wb, opts) {
  16662. var o = [XML_HEADER, STYLES_XML_ROOT], w;
  16663. if(wb.SSF && (w = write_numFmts(wb.SSF)) != null) o[o.length] = w;
  16664. o[o.length] = ('<fonts count="1"><font><sz val="12"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>');
  16665. o[o.length] = ('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  16666. o[o.length] = ('<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>');
  16667. o[o.length] = ('<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>');
  16668. if((w = write_cellXfs(opts.cellXfs))) o[o.length] = (w);
  16669. o[o.length] = ('<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>');
  16670. o[o.length] = ('<dxfs count="0"/>');
  16671. o[o.length] = ('<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4"/>');
  16672. if(o.length>2){ o[o.length] = ('</styleSheet>'); o[1]=o[1].replace("/>",">"); }
  16673. return o.join("");
  16674. }
  16675. /* [MS-XLSB] 2.4.657 BrtFmt */
  16676. function parse_BrtFmt(data, length) {
  16677. var numFmtId = data.read_shift(2);
  16678. var stFmtCode = parse_XLWideString(data,length-2);
  16679. return [numFmtId, stFmtCode];
  16680. }
  16681. function write_BrtFmt(i, f, o) {
  16682. if(!o) o = new_buf(6 + 4 * f.length);
  16683. o.write_shift(2, i);
  16684. write_XLWideString(f, o);
  16685. var out = (o.length > o.l) ? o.slice(0, o.l) : o;
  16686. if(o.l == null) o.l = o.length;
  16687. return out;
  16688. }
  16689. /* [MS-XLSB] 2.4.659 BrtFont TODO */
  16690. function parse_BrtFont(data, length, opts) {
  16691. var out = ({});
  16692. out.sz = data.read_shift(2) / 20;
  16693. var grbit = parse_FontFlags(data, 2, opts);
  16694. if(grbit.fItalic) out.italic = 1;
  16695. if(grbit.fCondense) out.condense = 1;
  16696. if(grbit.fExtend) out.extend = 1;
  16697. if(grbit.fShadow) out.shadow = 1;
  16698. if(grbit.fOutline) out.outline = 1;
  16699. if(grbit.fStrikeout) out.strike = 1;
  16700. var bls = data.read_shift(2);
  16701. if(bls === 0x02BC) out.bold = 1;
  16702. switch(data.read_shift(2)) {
  16703. /* case 0: out.vertAlign = "baseline"; break; */
  16704. case 1: out.vertAlign = "superscript"; break;
  16705. case 2: out.vertAlign = "subscript"; break;
  16706. }
  16707. var underline = data.read_shift(1);
  16708. if(underline != 0) out.underline = underline;
  16709. var family = data.read_shift(1);
  16710. if(family > 0) out.family = family;
  16711. var bCharSet = data.read_shift(1);
  16712. if(bCharSet > 0) out.charset = bCharSet;
  16713. data.l++;
  16714. out.color = parse_BrtColor(data, 8);
  16715. switch(data.read_shift(1)) {
  16716. /* case 0: out.scheme = "none": break; */
  16717. case 1: out.scheme = "major"; break;
  16718. case 2: out.scheme = "minor"; break;
  16719. }
  16720. out.name = parse_XLWideString(data, length - 21);
  16721. return out;
  16722. }
  16723. function write_BrtFont(font, o) {
  16724. if(!o) o = new_buf(25+4*32);
  16725. o.write_shift(2, font.sz * 20);
  16726. write_FontFlags(font, o);
  16727. o.write_shift(2, font.bold ? 0x02BC : 0x0190);
  16728. var sss = 0;
  16729. if(font.vertAlign == "superscript") sss = 1;
  16730. else if(font.vertAlign == "subscript") sss = 2;
  16731. o.write_shift(2, sss);
  16732. o.write_shift(1, font.underline || 0);
  16733. o.write_shift(1, font.family || 0);
  16734. o.write_shift(1, font.charset || 0);
  16735. o.write_shift(1, 0);
  16736. write_BrtColor(font.color, o);
  16737. var scheme = 0;
  16738. if(font.scheme == "major") scheme = 1;
  16739. if(font.scheme == "minor") scheme = 2;
  16740. o.write_shift(1, scheme);
  16741. write_XLWideString(font.name, o);
  16742. return o.length > o.l ? o.slice(0, o.l) : o;
  16743. }
  16744. /* [MS-XLSB] 2.4.650 BrtFill */
  16745. var XLSBFillPTNames = [
  16746. "none",
  16747. "solid",
  16748. "mediumGray",
  16749. "darkGray",
  16750. "lightGray",
  16751. "darkHorizontal",
  16752. "darkVertical",
  16753. "darkDown",
  16754. "darkUp",
  16755. "darkGrid",
  16756. "darkTrellis",
  16757. "lightHorizontal",
  16758. "lightVertical",
  16759. "lightDown",
  16760. "lightUp",
  16761. "lightGrid",
  16762. "lightTrellis",
  16763. "gray125",
  16764. "gray0625"
  16765. ];
  16766. var rev_XLSBFillPTNames = (evert(XLSBFillPTNames));
  16767. /* TODO: gradient fill representation */
  16768. var parse_BrtFill = parsenoop;
  16769. function write_BrtFill(fill, o) {
  16770. if(!o) o = new_buf(4*3 + 8*7 + 16*1);
  16771. var fls = rev_XLSBFillPTNames[fill.patternType];
  16772. if(fls == null) fls = 0x28;
  16773. o.write_shift(4, fls);
  16774. var j = 0;
  16775. if(fls != 0x28) {
  16776. /* TODO: custom FG Color */
  16777. write_BrtColor({auto:1}, o);
  16778. /* TODO: custom BG Color */
  16779. write_BrtColor({auto:1}, o);
  16780. for(; j < 12; ++j) o.write_shift(4, 0);
  16781. } else {
  16782. for(; j < 4; ++j) o.write_shift(4, 0);
  16783. for(; j < 12; ++j) o.write_shift(4, 0); /* TODO */
  16784. /* iGradientType */
  16785. /* xnumDegree */
  16786. /* xnumFillToLeft */
  16787. /* xnumFillToRight */
  16788. /* xnumFillToTop */
  16789. /* xnumFillToBottom */
  16790. /* cNumStop */
  16791. /* xfillGradientStop */
  16792. }
  16793. return o.length > o.l ? o.slice(0, o.l) : o;
  16794. }
  16795. /* [MS-XLSB] 2.4.824 BrtXF */
  16796. function parse_BrtXF(data, length) {
  16797. var tgt = data.l + length;
  16798. var ixfeParent = data.read_shift(2);
  16799. var ifmt = data.read_shift(2);
  16800. data.l = tgt;
  16801. return {ixfe:ixfeParent, numFmtId:ifmt };
  16802. }
  16803. function write_BrtXF(data, ixfeP, o) {
  16804. if(!o) o = new_buf(16);
  16805. o.write_shift(2, ixfeP||0);
  16806. o.write_shift(2, data.numFmtId||0);
  16807. o.write_shift(2, 0); /* iFont */
  16808. o.write_shift(2, 0); /* iFill */
  16809. o.write_shift(2, 0); /* ixBorder */
  16810. o.write_shift(1, 0); /* trot */
  16811. o.write_shift(1, 0); /* indent */
  16812. var flow = 0;
  16813. o.write_shift(1, flow); /* flags */
  16814. o.write_shift(1, 0); /* flags */
  16815. o.write_shift(1, 0); /* xfGrbitAtr */
  16816. o.write_shift(1, 0);
  16817. return o;
  16818. }
  16819. /* [MS-XLSB] 2.5.4 Blxf TODO */
  16820. function write_Blxf(data, o) {
  16821. if(!o) o = new_buf(10);
  16822. o.write_shift(1, 0); /* dg */
  16823. o.write_shift(1, 0);
  16824. o.write_shift(4, 0); /* color */
  16825. o.write_shift(4, 0); /* color */
  16826. return o;
  16827. }
  16828. /* [MS-XLSB] 2.4.302 BrtBorder TODO */
  16829. var parse_BrtBorder = parsenoop;
  16830. function write_BrtBorder(border, o) {
  16831. if(!o) o = new_buf(51);
  16832. o.write_shift(1, 0); /* diagonal */
  16833. write_Blxf(null, o); /* top */
  16834. write_Blxf(null, o); /* bottom */
  16835. write_Blxf(null, o); /* left */
  16836. write_Blxf(null, o); /* right */
  16837. write_Blxf(null, o); /* diag */
  16838. return o.length > o.l ? o.slice(0, o.l) : o;
  16839. }
  16840. /* [MS-XLSB] 2.4.763 BrtStyle TODO */
  16841. function write_BrtStyle(style, o) {
  16842. if(!o) o = new_buf(12+4*10);
  16843. o.write_shift(4, style.xfId);
  16844. o.write_shift(2, 1);
  16845. o.write_shift(1, +style.builtinId);
  16846. o.write_shift(1, 0); /* iLevel */
  16847. write_XLNullableWideString(style.name || "", o);
  16848. return o.length > o.l ? o.slice(0, o.l) : o;
  16849. }
  16850. /* [MS-XLSB] 2.4.272 BrtBeginTableStyles */
  16851. function write_BrtBeginTableStyles(cnt, defTableStyle, defPivotStyle) {
  16852. var o = new_buf(4+256*2*4);
  16853. o.write_shift(4, cnt);
  16854. write_XLNullableWideString(defTableStyle, o);
  16855. write_XLNullableWideString(defPivotStyle, o);
  16856. return o.length > o.l ? o.slice(0, o.l) : o;
  16857. }
  16858. /* [MS-XLSB] 2.1.7.50 Styles */
  16859. function parse_sty_bin(data, themes, opts) {
  16860. var styles = {};
  16861. styles.NumberFmt = ([]);
  16862. for(var y in SSF._table) styles.NumberFmt[y] = SSF._table[y];
  16863. styles.CellXf = [];
  16864. styles.Fonts = [];
  16865. var state = [];
  16866. var pass = false;
  16867. recordhopper(data, function hopper_sty(val, R_n, RT) {
  16868. switch(RT) {
  16869. case 0x002C: /* 'BrtFmt' */
  16870. styles.NumberFmt[val[0]] = val[1]; SSF.load(val[1], val[0]);
  16871. break;
  16872. case 0x002B: /* 'BrtFont' */
  16873. styles.Fonts.push(val);
  16874. if(val.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) {
  16875. val.color.rgb = rgb_tint(themes.themeElements.clrScheme[val.color.theme].rgb, val.color.tint || 0);
  16876. }
  16877. break;
  16878. case 0x0401: /* 'BrtKnownFonts' */ break;
  16879. case 0x002D: /* 'BrtFill' */
  16880. break;
  16881. case 0x002E: /* 'BrtBorder' */
  16882. break;
  16883. case 0x002F: /* 'BrtXF' */
  16884. if(state[state.length - 1] == "BrtBeginCellXFs") {
  16885. styles.CellXf.push(val);
  16886. }
  16887. break;
  16888. case 0x0030: /* 'BrtStyle' */
  16889. case 0x01FB: /* 'BrtDXF' */
  16890. case 0x023C: /* 'BrtMRUColor' */
  16891. case 0x01DB: /* 'BrtIndexedColor': */
  16892. break;
  16893. case 0x0493: /* 'BrtDXF14' */
  16894. case 0x0836: /* 'BrtDXF15' */
  16895. case 0x046A: /* 'BrtSlicerStyleElement' */
  16896. case 0x0200: /* 'BrtTableStyleElement' */
  16897. case 0x082F: /* 'BrtTimelineStyleElement' */
  16898. case 0x0C00: /* 'BrtUid' */
  16899. break;
  16900. case 0x0023: /* 'BrtFRTBegin' */
  16901. pass = true; break;
  16902. case 0x0024: /* 'BrtFRTEnd' */
  16903. pass = false; break;
  16904. case 0x0025: /* 'BrtACBegin' */
  16905. state.push(R_n); pass = true; break;
  16906. case 0x0026: /* 'BrtACEnd' */
  16907. state.pop(); pass = false; break;
  16908. default:
  16909. if((R_n||"").indexOf("Begin") > 0) state.push(R_n);
  16910. else if((R_n||"").indexOf("End") > 0) state.pop();
  16911. else if(!pass || (opts.WTF && state[state.length-1] != "BrtACBegin")) throw new Error("Unexpected record " + RT + " " + R_n);
  16912. }
  16913. });
  16914. return styles;
  16915. }
  16916. function write_FMTS_bin(ba, NF) {
  16917. if(!NF) return;
  16918. var cnt = 0;
  16919. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  16920. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) ++cnt;
  16921. });
  16922. if(cnt == 0) return;
  16923. write_record(ba, "BrtBeginFmts", write_UInt32LE(cnt));
  16924. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  16925. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_record(ba, "BrtFmt", write_BrtFmt(i, NF[i]));
  16926. });
  16927. write_record(ba, "BrtEndFmts");
  16928. }
  16929. function write_FONTS_bin(ba) {
  16930. var cnt = 1;
  16931. if(cnt == 0) return;
  16932. write_record(ba, "BrtBeginFonts", write_UInt32LE(cnt));
  16933. write_record(ba, "BrtFont", write_BrtFont({
  16934. sz:12,
  16935. color: {theme:1},
  16936. name: "Calibri",
  16937. family: 2,
  16938. scheme: "minor"
  16939. }));
  16940. /* 1*65491BrtFont [ACFONTS] */
  16941. write_record(ba, "BrtEndFonts");
  16942. }
  16943. function write_FILLS_bin(ba) {
  16944. var cnt = 2;
  16945. if(cnt == 0) return;
  16946. write_record(ba, "BrtBeginFills", write_UInt32LE(cnt));
  16947. write_record(ba, "BrtFill", write_BrtFill({patternType:"none"}));
  16948. write_record(ba, "BrtFill", write_BrtFill({patternType:"gray125"}));
  16949. /* 1*65431BrtFill */
  16950. write_record(ba, "BrtEndFills");
  16951. }
  16952. function write_BORDERS_bin(ba) {
  16953. var cnt = 1;
  16954. if(cnt == 0) return;
  16955. write_record(ba, "BrtBeginBorders", write_UInt32LE(cnt));
  16956. write_record(ba, "BrtBorder", write_BrtBorder({}));
  16957. /* 1*65430BrtBorder */
  16958. write_record(ba, "BrtEndBorders");
  16959. }
  16960. function write_CELLSTYLEXFS_bin(ba) {
  16961. var cnt = 1;
  16962. write_record(ba, "BrtBeginCellStyleXFs", write_UInt32LE(cnt));
  16963. write_record(ba, "BrtXF", write_BrtXF({
  16964. numFmtId: 0,
  16965. fontId: 0,
  16966. fillId: 0,
  16967. borderId: 0
  16968. }, 0xFFFF));
  16969. /* 1*65430(BrtXF *FRT) */
  16970. write_record(ba, "BrtEndCellStyleXFs");
  16971. }
  16972. function write_CELLXFS_bin(ba, data) {
  16973. write_record(ba, "BrtBeginCellXFs", write_UInt32LE(data.length));
  16974. data.forEach(function(c) { write_record(ba, "BrtXF", write_BrtXF(c,0)); });
  16975. /* 1*65430(BrtXF *FRT) */
  16976. write_record(ba, "BrtEndCellXFs");
  16977. }
  16978. function write_STYLES_bin(ba) {
  16979. var cnt = 1;
  16980. write_record(ba, "BrtBeginStyles", write_UInt32LE(cnt));
  16981. write_record(ba, "BrtStyle", write_BrtStyle({
  16982. xfId:0,
  16983. builtinId:0,
  16984. name:"Normal"
  16985. }));
  16986. /* 1*65430(BrtStyle *FRT) */
  16987. write_record(ba, "BrtEndStyles");
  16988. }
  16989. function write_DXFS_bin(ba) {
  16990. var cnt = 0;
  16991. write_record(ba, "BrtBeginDXFs", write_UInt32LE(cnt));
  16992. /* *2147483647(BrtDXF *FRT) */
  16993. write_record(ba, "BrtEndDXFs");
  16994. }
  16995. function write_TABLESTYLES_bin(ba) {
  16996. var cnt = 0;
  16997. write_record(ba, "BrtBeginTableStyles", write_BrtBeginTableStyles(cnt, "TableStyleMedium9", "PivotStyleMedium4"));
  16998. /* *TABLESTYLE */
  16999. write_record(ba, "BrtEndTableStyles");
  17000. }
  17001. function write_COLORPALETTE_bin() {
  17002. return;
  17003. /* BrtBeginColorPalette [INDEXEDCOLORS] [MRUCOLORS] BrtEndColorPalette */
  17004. }
  17005. /* [MS-XLSB] 2.1.7.50 Styles */
  17006. function write_sty_bin(wb, opts) {
  17007. var ba = buf_array();
  17008. write_record(ba, "BrtBeginStyleSheet");
  17009. write_FMTS_bin(ba, wb.SSF);
  17010. write_FONTS_bin(ba, wb);
  17011. write_FILLS_bin(ba, wb);
  17012. write_BORDERS_bin(ba, wb);
  17013. write_CELLSTYLEXFS_bin(ba, wb);
  17014. write_CELLXFS_bin(ba, opts.cellXfs);
  17015. write_STYLES_bin(ba, wb);
  17016. write_DXFS_bin(ba, wb);
  17017. write_TABLESTYLES_bin(ba, wb);
  17018. write_COLORPALETTE_bin(ba, wb);
  17019. /* FRTSTYLESHEET*/
  17020. write_record(ba, "BrtEndStyleSheet");
  17021. return ba.end();
  17022. }
  17023. RELS.THEME = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme";
  17024. /* Even though theme layout is dk1 lt1 dk2 lt2, true order is lt1 dk1 lt2 dk2 */
  17025. var XLSXThemeClrScheme = [
  17026. '</a:lt1>', '</a:dk1>', '</a:lt2>', '</a:dk2>',
  17027. '</a:accent1>', '</a:accent2>', '</a:accent3>',
  17028. '</a:accent4>', '</a:accent5>', '</a:accent6>',
  17029. '</a:hlink>', '</a:folHlink>'
  17030. ];
  17031. /* 20.1.6.2 clrScheme CT_ColorScheme */
  17032. function parse_clrScheme(t, themes, opts) {
  17033. themes.themeElements.clrScheme = [];
  17034. var color = {};
  17035. (t[0].match(tagregex)||[]).forEach(function(x) {
  17036. var y = parsexmltag(x);
  17037. switch(y[0]) {
  17038. /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */
  17039. case '<a:clrScheme': case '</a:clrScheme>': break;
  17040. /* 20.1.2.3.32 srgbClr CT_SRgbColor */
  17041. case '<a:srgbClr':
  17042. color.rgb = y.val; break;
  17043. /* 20.1.2.3.33 sysClr CT_SystemColor */
  17044. case '<a:sysClr':
  17045. color.rgb = y.lastClr; break;
  17046. /* 20.1.4.1.1 accent1 (Accent 1) */
  17047. /* 20.1.4.1.2 accent2 (Accent 2) */
  17048. /* 20.1.4.1.3 accent3 (Accent 3) */
  17049. /* 20.1.4.1.4 accent4 (Accent 4) */
  17050. /* 20.1.4.1.5 accent5 (Accent 5) */
  17051. /* 20.1.4.1.6 accent6 (Accent 6) */
  17052. /* 20.1.4.1.9 dk1 (Dark 1) */
  17053. /* 20.1.4.1.10 dk2 (Dark 2) */
  17054. /* 20.1.4.1.15 folHlink (Followed Hyperlink) */
  17055. /* 20.1.4.1.19 hlink (Hyperlink) */
  17056. /* 20.1.4.1.22 lt1 (Light 1) */
  17057. /* 20.1.4.1.23 lt2 (Light 2) */
  17058. case '<a:dk1>': case '</a:dk1>':
  17059. case '<a:lt1>': case '</a:lt1>':
  17060. case '<a:dk2>': case '</a:dk2>':
  17061. case '<a:lt2>': case '</a:lt2>':
  17062. case '<a:accent1>': case '</a:accent1>':
  17063. case '<a:accent2>': case '</a:accent2>':
  17064. case '<a:accent3>': case '</a:accent3>':
  17065. case '<a:accent4>': case '</a:accent4>':
  17066. case '<a:accent5>': case '</a:accent5>':
  17067. case '<a:accent6>': case '</a:accent6>':
  17068. case '<a:hlink>': case '</a:hlink>':
  17069. case '<a:folHlink>': case '</a:folHlink>':
  17070. if (y[0].charAt(1) === '/') {
  17071. themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y[0])] = color;
  17072. color = {};
  17073. } else {
  17074. color.name = y[0].slice(3, y[0].length - 1);
  17075. }
  17076. break;
  17077. default: if(opts && opts.WTF) throw new Error('Unrecognized ' + y[0] + ' in clrScheme');
  17078. }
  17079. });
  17080. }
  17081. /* 20.1.4.1.18 fontScheme CT_FontScheme */
  17082. function parse_fontScheme() { }
  17083. /* 20.1.4.1.15 fmtScheme CT_StyleMatrix */
  17084. function parse_fmtScheme() { }
  17085. var clrsregex = /<a:clrScheme([^>]*)>[\s\S]*<\/a:clrScheme>/;
  17086. var fntsregex = /<a:fontScheme([^>]*)>[\s\S]*<\/a:fontScheme>/;
  17087. var fmtsregex = /<a:fmtScheme([^>]*)>[\s\S]*<\/a:fmtScheme>/;
  17088. /* 20.1.6.10 themeElements CT_BaseStyles */
  17089. function parse_themeElements(data, themes, opts) {
  17090. themes.themeElements = {};
  17091. var t;
  17092. [
  17093. /* clrScheme CT_ColorScheme */
  17094. ['clrScheme', clrsregex, parse_clrScheme],
  17095. /* fontScheme CT_FontScheme */
  17096. ['fontScheme', fntsregex, parse_fontScheme],
  17097. /* fmtScheme CT_StyleMatrix */
  17098. ['fmtScheme', fmtsregex, parse_fmtScheme]
  17099. ].forEach(function(m) {
  17100. if(!(t=data.match(m[1]))) throw new Error(m[0] + ' not found in themeElements');
  17101. m[2](t, themes, opts);
  17102. });
  17103. }
  17104. var themeltregex = /<a:themeElements([^>]*)>[\s\S]*<\/a:themeElements>/;
  17105. /* 14.2.7 Theme Part */
  17106. function parse_theme_xml(data, opts) {
  17107. /* 20.1.6.9 theme CT_OfficeStyleSheet */
  17108. if(!data || data.length === 0) return parse_theme_xml(write_theme());
  17109. var t;
  17110. var themes = {};
  17111. /* themeElements CT_BaseStyles */
  17112. if(!(t=data.match(themeltregex))) throw new Error('themeElements not found in theme');
  17113. parse_themeElements(t[0], themes, opts);
  17114. themes.raw = data;
  17115. return themes;
  17116. }
  17117. function write_theme(Themes, opts) {
  17118. if(opts && opts.themeXLSX) return opts.themeXLSX;
  17119. if(Themes && typeof Themes.raw == "string") return Themes.raw;
  17120. var o = [XML_HEADER];
  17121. o[o.length] = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">';
  17122. o[o.length] = '<a:themeElements>';
  17123. o[o.length] = '<a:clrScheme name="Office">';
  17124. o[o.length] = '<a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>';
  17125. o[o.length] = '<a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>';
  17126. o[o.length] = '<a:dk2><a:srgbClr val="1F497D"/></a:dk2>';
  17127. o[o.length] = '<a:lt2><a:srgbClr val="EEECE1"/></a:lt2>';
  17128. o[o.length] = '<a:accent1><a:srgbClr val="4F81BD"/></a:accent1>';
  17129. o[o.length] = '<a:accent2><a:srgbClr val="C0504D"/></a:accent2>';
  17130. o[o.length] = '<a:accent3><a:srgbClr val="9BBB59"/></a:accent3>';
  17131. o[o.length] = '<a:accent4><a:srgbClr val="8064A2"/></a:accent4>';
  17132. o[o.length] = '<a:accent5><a:srgbClr val="4BACC6"/></a:accent5>';
  17133. o[o.length] = '<a:accent6><a:srgbClr val="F79646"/></a:accent6>';
  17134. o[o.length] = '<a:hlink><a:srgbClr val="0000FF"/></a:hlink>';
  17135. o[o.length] = '<a:folHlink><a:srgbClr val="800080"/></a:folHlink>';
  17136. o[o.length] = '</a:clrScheme>';
  17137. o[o.length] = '<a:fontScheme name="Office">';
  17138. o[o.length] = '<a:majorFont>';
  17139. o[o.length] = '<a:latin typeface="Cambria"/>';
  17140. o[o.length] = '<a:ea typeface=""/>';
  17141. o[o.length] = '<a:cs typeface=""/>';
  17142. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  17143. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  17144. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  17145. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  17146. o[o.length] = '<a:font script="Arab" typeface="Times New Roman"/>';
  17147. o[o.length] = '<a:font script="Hebr" typeface="Times New Roman"/>';
  17148. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  17149. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  17150. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  17151. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  17152. o[o.length] = '<a:font script="Khmr" typeface="MoolBoran"/>';
  17153. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  17154. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  17155. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  17156. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  17157. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  17158. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  17159. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  17160. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  17161. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  17162. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  17163. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  17164. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  17165. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  17166. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  17167. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  17168. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  17169. o[o.length] = '<a:font script="Viet" typeface="Times New Roman"/>';
  17170. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  17171. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  17172. o[o.length] = '</a:majorFont>';
  17173. o[o.length] = '<a:minorFont>';
  17174. o[o.length] = '<a:latin typeface="Calibri"/>';
  17175. o[o.length] = '<a:ea typeface=""/>';
  17176. o[o.length] = '<a:cs typeface=""/>';
  17177. o[o.length] = '<a:font script="Jpan" typeface="MS Pゴシック"/>';
  17178. o[o.length] = '<a:font script="Hang" typeface="맑은 고딕"/>';
  17179. o[o.length] = '<a:font script="Hans" typeface="宋体"/>';
  17180. o[o.length] = '<a:font script="Hant" typeface="新細明體"/>';
  17181. o[o.length] = '<a:font script="Arab" typeface="Arial"/>';
  17182. o[o.length] = '<a:font script="Hebr" typeface="Arial"/>';
  17183. o[o.length] = '<a:font script="Thai" typeface="Tahoma"/>';
  17184. o[o.length] = '<a:font script="Ethi" typeface="Nyala"/>';
  17185. o[o.length] = '<a:font script="Beng" typeface="Vrinda"/>';
  17186. o[o.length] = '<a:font script="Gujr" typeface="Shruti"/>';
  17187. o[o.length] = '<a:font script="Khmr" typeface="DaunPenh"/>';
  17188. o[o.length] = '<a:font script="Knda" typeface="Tunga"/>';
  17189. o[o.length] = '<a:font script="Guru" typeface="Raavi"/>';
  17190. o[o.length] = '<a:font script="Cans" typeface="Euphemia"/>';
  17191. o[o.length] = '<a:font script="Cher" typeface="Plantagenet Cherokee"/>';
  17192. o[o.length] = '<a:font script="Yiii" typeface="Microsoft Yi Baiti"/>';
  17193. o[o.length] = '<a:font script="Tibt" typeface="Microsoft Himalaya"/>';
  17194. o[o.length] = '<a:font script="Thaa" typeface="MV Boli"/>';
  17195. o[o.length] = '<a:font script="Deva" typeface="Mangal"/>';
  17196. o[o.length] = '<a:font script="Telu" typeface="Gautami"/>';
  17197. o[o.length] = '<a:font script="Taml" typeface="Latha"/>';
  17198. o[o.length] = '<a:font script="Syrc" typeface="Estrangelo Edessa"/>';
  17199. o[o.length] = '<a:font script="Orya" typeface="Kalinga"/>';
  17200. o[o.length] = '<a:font script="Mlym" typeface="Kartika"/>';
  17201. o[o.length] = '<a:font script="Laoo" typeface="DokChampa"/>';
  17202. o[o.length] = '<a:font script="Sinh" typeface="Iskoola Pota"/>';
  17203. o[o.length] = '<a:font script="Mong" typeface="Mongolian Baiti"/>';
  17204. o[o.length] = '<a:font script="Viet" typeface="Arial"/>';
  17205. o[o.length] = '<a:font script="Uigh" typeface="Microsoft Uighur"/>';
  17206. o[o.length] = '<a:font script="Geor" typeface="Sylfaen"/>';
  17207. o[o.length] = '</a:minorFont>';
  17208. o[o.length] = '</a:fontScheme>';
  17209. o[o.length] = '<a:fmtScheme name="Office">';
  17210. o[o.length] = '<a:fillStyleLst>';
  17211. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  17212. o[o.length] = '<a:gradFill rotWithShape="1">';
  17213. o[o.length] = '<a:gsLst>';
  17214. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  17215. o[o.length] = '<a:gs pos="35000"><a:schemeClr val="phClr"><a:tint val="37000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  17216. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="15000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17217. o[o.length] = '</a:gsLst>';
  17218. o[o.length] = '<a:lin ang="16200000" scaled="1"/>';
  17219. o[o.length] = '</a:gradFill>';
  17220. o[o.length] = '<a:gradFill rotWithShape="1">';
  17221. o[o.length] = '<a:gsLst>';
  17222. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="100000"/><a:shade val="100000"/><a:satMod val="130000"/></a:schemeClr></a:gs>';
  17223. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:tint val="50000"/><a:shade val="100000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17224. o[o.length] = '</a:gsLst>';
  17225. o[o.length] = '<a:lin ang="16200000" scaled="0"/>';
  17226. o[o.length] = '</a:gradFill>';
  17227. o[o.length] = '</a:fillStyleLst>';
  17228. o[o.length] = '<a:lnStyleLst>';
  17229. o[o.length] = '<a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000"/><a:satMod val="105000"/></a:schemeClr></a:solidFill><a:prstDash val="solid"/></a:ln>';
  17230. o[o.length] = '<a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  17231. o[o.length] = '<a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="solid"/></a:ln>';
  17232. o[o.length] = '</a:lnStyleLst>';
  17233. o[o.length] = '<a:effectStyleLst>';
  17234. o[o.length] = '<a:effectStyle>';
  17235. o[o.length] = '<a:effectLst>';
  17236. o[o.length] = '<a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="38000"/></a:srgbClr></a:outerShdw>';
  17237. o[o.length] = '</a:effectLst>';
  17238. o[o.length] = '</a:effectStyle>';
  17239. o[o.length] = '<a:effectStyle>';
  17240. o[o.length] = '<a:effectLst>';
  17241. o[o.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  17242. o[o.length] = '</a:effectLst>';
  17243. o[o.length] = '</a:effectStyle>';
  17244. o[o.length] = '<a:effectStyle>';
  17245. o[o.length] = '<a:effectLst>';
  17246. o[o.length] = '<a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw>';
  17247. o[o.length] = '</a:effectLst>';
  17248. o[o.length] = '<a:scene3d><a:camera prst="orthographicFront"><a:rot lat="0" lon="0" rev="0"/></a:camera><a:lightRig rig="threePt" dir="t"><a:rot lat="0" lon="0" rev="1200000"/></a:lightRig></a:scene3d>';
  17249. o[o.length] = '<a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d>';
  17250. o[o.length] = '</a:effectStyle>';
  17251. o[o.length] = '</a:effectStyleLst>';
  17252. o[o.length] = '<a:bgFillStyleLst>';
  17253. o[o.length] = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
  17254. o[o.length] = '<a:gradFill rotWithShape="1">';
  17255. o[o.length] = '<a:gsLst>';
  17256. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="40000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17257. o[o.length] = '<a:gs pos="40000"><a:schemeClr val="phClr"><a:tint val="45000"/><a:shade val="99000"/><a:satMod val="350000"/></a:schemeClr></a:gs>';
  17258. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="20000"/><a:satMod val="255000"/></a:schemeClr></a:gs>';
  17259. o[o.length] = '</a:gsLst>';
  17260. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="-80000" r="50000" b="180000"/></a:path>';
  17261. o[o.length] = '</a:gradFill>';
  17262. o[o.length] = '<a:gradFill rotWithShape="1">';
  17263. o[o.length] = '<a:gsLst>';
  17264. o[o.length] = '<a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="80000"/><a:satMod val="300000"/></a:schemeClr></a:gs>';
  17265. o[o.length] = '<a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="30000"/><a:satMod val="200000"/></a:schemeClr></a:gs>';
  17266. o[o.length] = '</a:gsLst>';
  17267. o[o.length] = '<a:path path="circle"><a:fillToRect l="50000" t="50000" r="50000" b="50000"/></a:path>';
  17268. o[o.length] = '</a:gradFill>';
  17269. o[o.length] = '</a:bgFillStyleLst>';
  17270. o[o.length] = '</a:fmtScheme>';
  17271. o[o.length] = '</a:themeElements>';
  17272. o[o.length] = '<a:objectDefaults>';
  17273. o[o.length] = '<a:spDef>';
  17274. o[o.length] = '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="1"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="3"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="2"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="lt1"/></a:fontRef></a:style>';
  17275. o[o.length] = '</a:spDef>';
  17276. o[o.length] = '<a:lnDef>';
  17277. o[o.length] = '<a:spPr/><a:bodyPr/><a:lstStyle/><a:style><a:lnRef idx="2"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="0"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="1"><a:schemeClr val="accent1"/></a:effectRef><a:fontRef idx="minor"><a:schemeClr val="tx1"/></a:fontRef></a:style>';
  17278. o[o.length] = '</a:lnDef>';
  17279. o[o.length] = '</a:objectDefaults>';
  17280. o[o.length] = '<a:extraClrSchemeLst/>';
  17281. o[o.length] = '</a:theme>';
  17282. return o.join("");
  17283. }
  17284. /* [MS-XLS] 2.4.326 TODO: payload is a zip file */
  17285. function parse_Theme(blob, length, opts) {
  17286. var end = blob.l + length;
  17287. var dwThemeVersion = blob.read_shift(4);
  17288. if(dwThemeVersion === 124226) return;
  17289. if(!opts.cellStyles || !jszip) { blob.l = end; return; }
  17290. var data = blob.slice(blob.l);
  17291. blob.l = end;
  17292. var zip; try { zip = new jszip(data); } catch(e) { return; }
  17293. var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true);
  17294. if(!themeXML) return;
  17295. return parse_theme_xml(themeXML, opts);
  17296. }
  17297. /* 2.5.49 */
  17298. function parse_ColorTheme(blob) { return blob.read_shift(4); }
  17299. /* 2.5.155 */
  17300. function parse_FullColorExt(blob) {
  17301. var o = {};
  17302. o.xclrType = blob.read_shift(2);
  17303. o.nTintShade = blob.read_shift(2);
  17304. switch(o.xclrType) {
  17305. case 0: blob.l += 4; break;
  17306. case 1: o.xclrValue = parse_IcvXF(blob, 4); break;
  17307. case 2: o.xclrValue = parse_LongRGBA(blob, 4); break;
  17308. case 3: o.xclrValue = parse_ColorTheme(blob, 4); break;
  17309. case 4: blob.l += 4; break;
  17310. }
  17311. blob.l += 8;
  17312. return o;
  17313. }
  17314. /* 2.5.164 TODO: read 7 bits*/
  17315. function parse_IcvXF(blob, length) {
  17316. return parsenoop(blob, length);
  17317. }
  17318. /* 2.5.280 */
  17319. function parse_XFExtGradient(blob, length) {
  17320. return parsenoop(blob, length);
  17321. }
  17322. /* [MS-XLS] 2.5.108 */
  17323. function parse_ExtProp(blob) {
  17324. var extType = blob.read_shift(2);
  17325. var cb = blob.read_shift(2) - 4;
  17326. var o = [extType];
  17327. switch(extType) {
  17328. case 0x04: case 0x05: case 0x07: case 0x08:
  17329. case 0x09: case 0x0A: case 0x0B: case 0x0D:
  17330. o[1] = parse_FullColorExt(blob, cb); break;
  17331. case 0x06: o[1] = parse_XFExtGradient(blob, cb); break;
  17332. case 0x0E: case 0x0F: o[1] = blob.read_shift(cb === 1 ? 1 : 2); break;
  17333. default: throw new Error("Unrecognized ExtProp type: " + extType + " " + cb);
  17334. }
  17335. return o;
  17336. }
  17337. /* 2.4.355 */
  17338. function parse_XFExt(blob, length) {
  17339. var end = blob.l + length;
  17340. blob.l += 2;
  17341. var ixfe = blob.read_shift(2);
  17342. blob.l += 2;
  17343. var cexts = blob.read_shift(2);
  17344. var ext = [];
  17345. while(cexts-- > 0) ext.push(parse_ExtProp(blob, end-blob.l));
  17346. return {ixfe:ixfe, ext:ext};
  17347. }
  17348. /* xf is an XF, see parse_XFExt for xfext */
  17349. function update_xfext(xf, xfext) {
  17350. xfext.forEach(function(xfe) {
  17351. switch(xfe[0]) { /* 2.5.108 extPropData */
  17352. case 0x04: break; /* foreground color */
  17353. case 0x05: break; /* background color */
  17354. case 0x06: break; /* gradient fill */
  17355. case 0x07: break; /* top cell border color */
  17356. case 0x08: break; /* bottom cell border color */
  17357. case 0x09: break; /* left cell border color */
  17358. case 0x0a: break; /* right cell border color */
  17359. case 0x0b: break; /* diagonal cell border color */
  17360. case 0x0d: /* text color */
  17361. break;
  17362. case 0x0e: break; /* font scheme */
  17363. case 0x0f: break; /* indentation level */
  17364. }
  17365. });
  17366. }
  17367. /* 18.6 Calculation Chain */
  17368. function parse_cc_xml(data) {
  17369. var d = [];
  17370. if(!data) return d;
  17371. var i = 1;
  17372. (data.match(tagregex)||[]).forEach(function(x) {
  17373. var y = parsexmltag(x);
  17374. switch(y[0]) {
  17375. case '<?xml': break;
  17376. /* 18.6.2 calcChain CT_CalcChain 1 */
  17377. case '<calcChain': case '<calcChain>': case '</calcChain>': break;
  17378. /* 18.6.1 c CT_CalcCell 1 */
  17379. case '<c': delete y[0]; if(y.i) i = y.i; else y.i = i; d.push(y); break;
  17380. }
  17381. });
  17382. return d;
  17383. }
  17384. //function write_cc_xml(data, opts) { }
  17385. /* [MS-XLSB] 2.6.4.1 */
  17386. function parse_BrtCalcChainItem$(data) {
  17387. var out = {};
  17388. out.i = data.read_shift(4);
  17389. var cell = {};
  17390. cell.r = data.read_shift(4);
  17391. cell.c = data.read_shift(4);
  17392. out.r = encode_cell(cell);
  17393. var flags = data.read_shift(1);
  17394. if(flags & 0x2) out.l = '1';
  17395. if(flags & 0x8) out.a = '1';
  17396. return out;
  17397. }
  17398. /* 18.6 Calculation Chain */
  17399. function parse_cc_bin(data, name, opts) {
  17400. var out = [];
  17401. var pass = false;
  17402. recordhopper(data, function hopper_cc(val, R_n, RT) {
  17403. switch(RT) {
  17404. case 0x003F: /* 'BrtCalcChainItem$' */
  17405. out.push(val); break;
  17406. default:
  17407. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  17408. else if((R_n||"").indexOf("End") > 0){/* empty */}
  17409. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  17410. }
  17411. });
  17412. return out;
  17413. }
  17414. //function write_cc_bin(data, opts) { }
  17415. /* 18.14 Supplementary Workbook Data */
  17416. function parse_xlink_xml() {
  17417. //var opts = _opts || {};
  17418. //if(opts.WTF) throw "XLSX2 External Link";
  17419. }
  17420. /* [MS-XLSB] 2.1.7.25 External Link */
  17421. function parse_xlink_bin(data, rel, name, _opts) {
  17422. if(!data) return data;
  17423. var opts = _opts || {};
  17424. var pass = false, end = false;
  17425. recordhopper(data, function xlink_parse(val, R_n, RT) {
  17426. if(end) return;
  17427. switch(RT) {
  17428. case 0x0167: /* 'BrtSupTabs' */
  17429. case 0x016B: /* 'BrtExternTableStart' */
  17430. case 0x016C: /* 'BrtExternTableEnd' */
  17431. case 0x016E: /* 'BrtExternRowHdr' */
  17432. case 0x016F: /* 'BrtExternCellBlank' */
  17433. case 0x0170: /* 'BrtExternCellReal' */
  17434. case 0x0171: /* 'BrtExternCellBool' */
  17435. case 0x0172: /* 'BrtExternCellError' */
  17436. case 0x0173: /* 'BrtExternCellString' */
  17437. case 0x01D8: /* 'BrtExternValueMeta' */
  17438. case 0x0241: /* 'BrtSupNameStart' */
  17439. case 0x0242: /* 'BrtSupNameValueStart' */
  17440. case 0x0243: /* 'BrtSupNameValueEnd' */
  17441. case 0x0244: /* 'BrtSupNameNum' */
  17442. case 0x0245: /* 'BrtSupNameErr' */
  17443. case 0x0246: /* 'BrtSupNameSt' */
  17444. case 0x0247: /* 'BrtSupNameNil' */
  17445. case 0x0248: /* 'BrtSupNameBool' */
  17446. case 0x0249: /* 'BrtSupNameFmla' */
  17447. case 0x024A: /* 'BrtSupNameBits' */
  17448. case 0x024B: /* 'BrtSupNameEnd' */
  17449. break;
  17450. case 0x0023: /* 'BrtFRTBegin' */
  17451. pass = true; break;
  17452. case 0x0024: /* 'BrtFRTEnd' */
  17453. pass = false; break;
  17454. default:
  17455. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  17456. else if((R_n||"").indexOf("End") > 0){/* empty */}
  17457. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT.toString(16) + " " + R_n);
  17458. }
  17459. }, opts);
  17460. }
  17461. /* 20.5 DrawingML - SpreadsheetML Drawing */
  17462. RELS.IMG = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
  17463. RELS.DRAW = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing";
  17464. /* 20.5.2.35 wsDr CT_Drawing */
  17465. function parse_drawing(data, rels) {
  17466. if(!data) return "??";
  17467. /*
  17468. Chartsheet Drawing:
  17469. - 20.5.2.35 wsDr CT_Drawing
  17470. - 20.5.2.1 absoluteAnchor CT_AbsoluteAnchor
  17471. - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame
  17472. - 20.1.2.2.16 graphic CT_GraphicalObject
  17473. - 20.1.2.2.17 graphicData CT_GraphicalObjectData
  17474. - chart reference
  17475. the actual type is based on the URI of the graphicData
  17476. TODO: handle embedded charts and other types of graphics
  17477. */
  17478. var id = (data.match(/<c:chart [^>]*r:id="([^"]*)"/)||["",""])[1];
  17479. return rels['!id'][id].Target;
  17480. }
  17481. /* L.5.5.2 SpreadsheetML Comments + VML Schema */
  17482. var _shapeid = 1024;
  17483. function write_comments_vml(rId, comments) {
  17484. var csize = [21600, 21600];
  17485. /* L.5.2.1.2 Path Attribute */
  17486. var bbox = ["m0,0l0",csize[1],csize[0],csize[1],csize[0],"0xe"].join(",");
  17487. var o = [
  17488. writextag("xml", null, { 'xmlns:v': XLMLNS.v, 'xmlns:o': XLMLNS.o, 'xmlns:x': XLMLNS.x, 'xmlns:mv': XLMLNS.mv }).replace(/\/>/,">"),
  17489. writextag("o:shapelayout", writextag("o:idmap", null, {'v:ext':"edit", 'data':rId}), {'v:ext':"edit"}),
  17490. writextag("v:shapetype", [
  17491. writextag("v:stroke", null, {joinstyle:"miter"}),
  17492. writextag("v:path", null, {gradientshapeok:"t", 'o:connecttype':"rect"})
  17493. ].join(""), {id:"_x0000_t202", 'o:spt':202, coordsize:csize.join(","),path:bbox})
  17494. ];
  17495. while(_shapeid < rId * 1000) _shapeid += 1000;
  17496. comments.forEach(function(x) {
  17497. var c = decode_cell(x[0]);
  17498. var fillopts = {'color2':"#BEFF82", 'type':"gradient"};
  17499. if(fillopts.type == "gradient") fillopts.angle = "-180";
  17500. var fillparm = fillopts.type == "gradient" ? writextag("o:fill", null, {type:"gradientUnscaled", 'v:ext':"view"}) : null;
  17501. var fillxml = writextag('v:fill', fillparm, fillopts);
  17502. var shadata = ({on:"t", 'obscured':"t"});
  17503. ++_shapeid;
  17504. o = o.concat([
  17505. '<v:shape' + wxt_helper({
  17506. id:'_x0000_s' + _shapeid,
  17507. type:"#_x0000_t202",
  17508. style:"position:absolute; margin-left:80pt;margin-top:5pt;width:104pt;height:64pt;z-index:10" + (x[1].hidden ? ";visibility:hidden" : "") ,
  17509. fillcolor:"#ECFAD4",
  17510. strokecolor:"#edeaa1"
  17511. }) + '>',
  17512. fillxml,
  17513. writextag("v:shadow", null, shadata),
  17514. writextag("v:path", null, {'o:connecttype':"none"}),
  17515. '<v:textbox><div style="text-align:left"></div></v:textbox>',
  17516. '<x:ClientData ObjectType="Note">',
  17517. '<x:MoveWithCells/>',
  17518. '<x:SizeWithCells/>',
  17519. /* Part 4 19.4.2.3 Anchor (Anchor) */
  17520. writetag('x:Anchor', [c.c+1, 0, c.r+1, 0, c.c+3, 20, c.r+5, 20].join(",")),
  17521. writetag('x:AutoFill', "False"),
  17522. writetag('x:Row', String(c.r)),
  17523. writetag('x:Column', String(c.c)),
  17524. x[1].hidden ? '' : '<x:Visible/>',
  17525. '</x:ClientData>',
  17526. '</v:shape>'
  17527. ]); });
  17528. o.push('</xml>');
  17529. return o.join("");
  17530. }
  17531. RELS.CMNT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
  17532. function sheet_insert_comments(sheet, comments) {
  17533. var dense = Array.isArray(sheet);
  17534. var cell;
  17535. comments.forEach(function(comment) {
  17536. var r = decode_cell(comment.ref);
  17537. if(dense) {
  17538. if(!sheet[r.r]) sheet[r.r] = [];
  17539. cell = sheet[r.r][r.c];
  17540. } else cell = sheet[comment.ref];
  17541. if (!cell) {
  17542. cell = ({t:"z"});
  17543. if(dense) sheet[r.r][r.c] = cell;
  17544. else sheet[comment.ref] = cell;
  17545. var range = safe_decode_range(sheet["!ref"]||"BDWGO1000001:A1");
  17546. if(range.s.r > r.r) range.s.r = r.r;
  17547. if(range.e.r < r.r) range.e.r = r.r;
  17548. if(range.s.c > r.c) range.s.c = r.c;
  17549. if(range.e.c < r.c) range.e.c = r.c;
  17550. var encoded = encode_range(range);
  17551. if (encoded !== sheet["!ref"]) sheet["!ref"] = encoded;
  17552. }
  17553. if (!cell.c) cell.c = [];
  17554. var o = ({a: comment.author, t: comment.t, r: comment.r});
  17555. if(comment.h) o.h = comment.h;
  17556. cell.c.push(o);
  17557. });
  17558. }
  17559. /* 18.7 Comments */
  17560. function parse_comments_xml(data, opts) {
  17561. /* 18.7.6 CT_Comments */
  17562. if(data.match(/<(?:\w+:)?comments *\/>/)) return [];
  17563. var authors = [];
  17564. var commentList = [];
  17565. var authtag = data.match(/<(?:\w+:)?authors>([\s\S]*)<\/(?:\w+:)?authors>/);
  17566. if(authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x) {
  17567. if(x === "" || x.trim() === "") return;
  17568. var a = x.match(/<(?:\w+:)?author[^>]*>(.*)/);
  17569. if(a) authors.push(a[1]);
  17570. });
  17571. var cmnttag = data.match(/<(?:\w+:)?commentList>([\s\S]*)<\/(?:\w+:)?commentList>/);
  17572. if(cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x) {
  17573. if(x === "" || x.trim() === "") return;
  17574. var cm = x.match(/<(?:\w+:)?comment[^>]*>/);
  17575. if(!cm) return;
  17576. var y = parsexmltag(cm[0]);
  17577. var comment = ({ author: y.authorId && authors[y.authorId] || "sheetjsghost", ref: y.ref, guid: y.guid });
  17578. var cell = decode_cell(y.ref);
  17579. if(opts.sheetRows && opts.sheetRows <= cell.r) return;
  17580. var textMatch = x.match(/<(?:\w+:)?text>([\s\S]*)<\/(?:\w+:)?text>/);
  17581. var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || {r:"",t:"",h:""};
  17582. comment.r = rt.r;
  17583. if(rt.r == "<t></t>") rt.t = rt.h = "";
  17584. comment.t = rt.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  17585. if(opts.cellHTML) comment.h = rt.h;
  17586. commentList.push(comment);
  17587. });
  17588. return commentList;
  17589. }
  17590. var CMNT_XML_ROOT = writextag('comments', null, { 'xmlns': XMLNS.main[0] });
  17591. function write_comments_xml(data) {
  17592. var o = [XML_HEADER, CMNT_XML_ROOT];
  17593. var iauthor = [];
  17594. o.push("<authors>");
  17595. data.forEach(function(x) { x[1].forEach(function(w) { var a = escapexml(w.a);
  17596. if(iauthor.indexOf(a) > -1) return;
  17597. iauthor.push(a);
  17598. o.push("<author>" + a + "</author>");
  17599. }); });
  17600. o.push("</authors>");
  17601. o.push("<commentList>");
  17602. data.forEach(function(d) {
  17603. d[1].forEach(function(c) {
  17604. /* 18.7.3 CT_Comment */
  17605. o.push('<comment ref="' + d[0] + '" authorId="' + iauthor.indexOf(escapexml(c.a)) + '"><text>');
  17606. o.push(writetag("t", c.t == null ? "" : escapexml(c.t)));
  17607. o.push('</text></comment>');
  17608. });
  17609. });
  17610. o.push("</commentList>");
  17611. if(o.length>2) { o[o.length] = ('</comments>'); o[1]=o[1].replace("/>",">"); }
  17612. return o.join("");
  17613. }
  17614. /* [MS-XLSB] 2.4.28 BrtBeginComment */
  17615. function parse_BrtBeginComment(data) {
  17616. var out = {};
  17617. out.iauthor = data.read_shift(4);
  17618. var rfx = parse_UncheckedRfX(data, 16);
  17619. out.rfx = rfx.s;
  17620. out.ref = encode_cell(rfx.s);
  17621. data.l += 16; /*var guid = parse_GUID(data); */
  17622. return out;
  17623. }
  17624. function write_BrtBeginComment(data, o) {
  17625. if(o == null) o = new_buf(36);
  17626. o.write_shift(4, data[1].iauthor);
  17627. write_UncheckedRfX((data[0]), o);
  17628. o.write_shift(4, 0);
  17629. o.write_shift(4, 0);
  17630. o.write_shift(4, 0);
  17631. o.write_shift(4, 0);
  17632. return o;
  17633. }
  17634. /* [MS-XLSB] 2.4.327 BrtCommentAuthor */
  17635. var parse_BrtCommentAuthor = parse_XLWideString;
  17636. function write_BrtCommentAuthor(data) { return write_XLWideString(data.slice(0, 54)); }
  17637. /* [MS-XLSB] 2.1.7.8 Comments */
  17638. function parse_comments_bin(data, opts) {
  17639. var out = [];
  17640. var authors = [];
  17641. var c = {};
  17642. var pass = false;
  17643. recordhopper(data, function hopper_cmnt(val, R_n, RT) {
  17644. switch(RT) {
  17645. case 0x0278: /* 'BrtCommentAuthor' */
  17646. authors.push(val); break;
  17647. case 0x027B: /* 'BrtBeginComment' */
  17648. c = val; break;
  17649. case 0x027D: /* 'BrtCommentText' */
  17650. c.t = val.t; c.h = val.h; c.r = val.r; break;
  17651. case 0x027C: /* 'BrtEndComment' */
  17652. c.author = authors[c.iauthor];
  17653. delete (c).iauthor;
  17654. if(opts.sheetRows && c.rfx && opts.sheetRows <= c.rfx.r) break;
  17655. if(!c.t) c.t = "";
  17656. delete c.rfx; out.push(c); break;
  17657. case 0x0C00: /* 'BrtUid' */
  17658. break;
  17659. case 0x0023: /* 'BrtFRTBegin' */
  17660. pass = true; break;
  17661. case 0x0024: /* 'BrtFRTEnd' */
  17662. pass = false; break;
  17663. case 0x0025: /* 'BrtACBegin' */ break;
  17664. case 0x0026: /* 'BrtACEnd' */ break;
  17665. default:
  17666. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  17667. else if((R_n||"").indexOf("End") > 0){/* empty */}
  17668. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  17669. }
  17670. });
  17671. return out;
  17672. }
  17673. function write_comments_bin(data) {
  17674. var ba = buf_array();
  17675. var iauthor = [];
  17676. write_record(ba, "BrtBeginComments");
  17677. write_record(ba, "BrtBeginCommentAuthors");
  17678. data.forEach(function(comment) {
  17679. comment[1].forEach(function(c) {
  17680. if(iauthor.indexOf(c.a) > -1) return;
  17681. iauthor.push(c.a.slice(0,54));
  17682. write_record(ba, "BrtCommentAuthor", write_BrtCommentAuthor(c.a));
  17683. });
  17684. });
  17685. write_record(ba, "BrtEndCommentAuthors");
  17686. write_record(ba, "BrtBeginCommentList");
  17687. data.forEach(function(comment) {
  17688. comment[1].forEach(function(c) {
  17689. c.iauthor = iauthor.indexOf(c.a);
  17690. var range = {s:decode_cell(comment[0]),e:decode_cell(comment[0])};
  17691. write_record(ba, "BrtBeginComment", write_BrtBeginComment([range, c]));
  17692. if(c.t && c.t.length > 0) write_record(ba, "BrtCommentText", write_BrtCommentText(c));
  17693. write_record(ba, "BrtEndComment");
  17694. delete c.iauthor;
  17695. });
  17696. });
  17697. write_record(ba, "BrtEndCommentList");
  17698. write_record(ba, "BrtEndComments");
  17699. return ba.end();
  17700. }
  17701. var CT_VBA = "application/vnd.ms-office.vbaProject";
  17702. function make_vba_xls(cfb) {
  17703. var newcfb = CFB.utils.cfb_new({root:"R"});
  17704. cfb.FullPaths.forEach(function(p, i) {
  17705. if(p.slice(-1) === "/" || !p.match(/_VBA_PROJECT_CUR/)) return;
  17706. var newpath = p.replace(/^[^\/]*/,"R").replace(/\/_VBA_PROJECT_CUR\u0000*/, "");
  17707. CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i].content);
  17708. });
  17709. return CFB.write(newcfb);
  17710. }
  17711. function fill_vba_xls(cfb, vba) {
  17712. vba.FullPaths.forEach(function(p, i) {
  17713. if(i == 0) return;
  17714. var newpath = p.replace(/[^\/]*[\/]/, "/_VBA_PROJECT_CUR/");
  17715. if(newpath.slice(-1) !== "/") CFB.utils.cfb_add(cfb, newpath, vba.FileIndex[i].content);
  17716. });
  17717. }
  17718. var VBAFMTS = [ "xlsb", "xlsm", "xlam", "biff8", "xla" ];
  17719. RELS.DS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet";
  17720. RELS.MS = "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet";
  17721. /* macro and dialog sheet stubs */
  17722. function parse_ds_bin() { return {'!type':'dialog'}; }
  17723. function parse_ds_xml() { return {'!type':'dialog'}; }
  17724. function parse_ms_bin() { return {'!type':'macro'}; }
  17725. function parse_ms_xml() { return {'!type':'macro'}; }
  17726. /* TODO: it will be useful to parse the function str */
  17727. var rc_to_a1 = (function(){
  17728. var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g;
  17729. var rcbase = ({r:0,c:0});
  17730. function rcfunc($$,$1,$2,$3) {
  17731. var cRel = false, rRel = false;
  17732. if($2.length == 0) rRel = true;
  17733. else if($2.charAt(0) == "[") { rRel = true; $2 = $2.slice(1, -1); }
  17734. if($3.length == 0) cRel = true;
  17735. else if($3.charAt(0) == "[") { cRel = true; $3 = $3.slice(1, -1); }
  17736. var R = $2.length>0?parseInt($2,10)|0:0, C = $3.length>0?parseInt($3,10)|0:0;
  17737. if(cRel) C += rcbase.c; else --C;
  17738. if(rRel) R += rcbase.r; else --R;
  17739. return $1 + (cRel ? "" : "$") + encode_col(C) + (rRel ? "" : "$") + encode_row(R);
  17740. }
  17741. return function rc_to_a1(fstr, base) {
  17742. rcbase = base;
  17743. return fstr.replace(rcregex, rcfunc);
  17744. };
  17745. })();
  17746. var crefregex = /(^|[^._A-Z0-9])([$]?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([$]?)(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})(?![_.\(A-Za-z0-9])/g;
  17747. var a1_to_rc =(function(){
  17748. return function a1_to_rc(fstr, base) {
  17749. return fstr.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  17750. var c = decode_col($3) - ($2 ? 0 : base.c);
  17751. var r = decode_row($5) - ($4 ? 0 : base.r);
  17752. var R = (r == 0 ? "" : !$4 ? "[" + r + "]" : (r+1));
  17753. var C = (c == 0 ? "" : !$2 ? "[" + c + "]" : (c+1));
  17754. return $1 + "R" + R + "C" + C;
  17755. });
  17756. };
  17757. })();
  17758. /* no defined name can collide with a valid cell address A1:XFD1048576 ... except LOG10! */
  17759. function shift_formula_str(f, delta) {
  17760. return f.replace(crefregex, function($0, $1, $2, $3, $4, $5) {
  17761. return $1+($2=="$" ? $2+$3 : encode_col(decode_col($3)+delta.c))+($4=="$" ? $4+$5 : encode_row(decode_row($5) + delta.r));
  17762. });
  17763. }
  17764. function shift_formula_xlsx(f, range, cell) {
  17765. var r = decode_range(range), s = r.s, c = decode_cell(cell);
  17766. var delta = {r:c.r - s.r, c:c.c - s.c};
  17767. return shift_formula_str(f, delta);
  17768. }
  17769. /* TODO: parse formula */
  17770. function fuzzyfmla(f) {
  17771. if(f.length == 1) return false;
  17772. return true;
  17773. }
  17774. function _xlfn(f) {
  17775. return f.replace(/_xlfn\./g,"");
  17776. }
  17777. function parseread1(blob) { blob.l+=1; return; }
  17778. /* [MS-XLS] 2.5.51 */
  17779. function parse_ColRelU(blob, length) {
  17780. var c = blob.read_shift(length == 1 ? 1 : 2);
  17781. return [c & 0x3FFF, (c >> 14) & 1, (c >> 15) & 1];
  17782. }
  17783. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.89 */
  17784. function parse_RgceArea(blob, length, opts) {
  17785. var w = 2;
  17786. if(opts) {
  17787. if(opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts);
  17788. else if(opts.biff == 12) w = 4;
  17789. }
  17790. var r=blob.read_shift(w), R=blob.read_shift(w);
  17791. var c=parse_ColRelU(blob, 2);
  17792. var C=parse_ColRelU(blob, 2);
  17793. return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
  17794. }
  17795. /* BIFF 2-5 encodes flags in the row field */
  17796. function parse_RgceArea_BIFF2(blob) {
  17797. var r=parse_ColRelU(blob, 2), R=parse_ColRelU(blob, 2);
  17798. var c=blob.read_shift(1);
  17799. var C=blob.read_shift(1);
  17800. return { s:{r:r[0], c:c, cRel:r[1], rRel:r[2]}, e:{r:R[0], c:C, cRel:R[1], rRel:R[2]} };
  17801. }
  17802. /* [MS-XLS] 2.5.198.105 ; [MS-XLSB] 2.5.97.90 */
  17803. function parse_RgceAreaRel(blob, length, opts) {
  17804. if(opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts);
  17805. var r=blob.read_shift(opts.biff == 12 ? 4 : 2), R=blob.read_shift(opts.biff == 12 ? 4 : 2);
  17806. var c=parse_ColRelU(blob, 2);
  17807. var C=parse_ColRelU(blob, 2);
  17808. return { s:{r:r, c:c[0], cRel:c[1], rRel:c[2]}, e:{r:R, c:C[0], cRel:C[1], rRel:C[2]} };
  17809. }
  17810. /* [MS-XLS] 2.5.198.109 ; [MS-XLSB] 2.5.97.91 */
  17811. function parse_RgceLoc(blob, length, opts) {
  17812. if(opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts);
  17813. var r = blob.read_shift(opts && opts.biff == 12 ? 4 : 2);
  17814. var c = parse_ColRelU(blob, 2);
  17815. return {r:r, c:c[0], cRel:c[1], rRel:c[2]};
  17816. }
  17817. function parse_RgceLoc_BIFF2(blob) {
  17818. var r = parse_ColRelU(blob, 2);
  17819. var c = blob.read_shift(1);
  17820. return {r:r[0], c:c, cRel:r[1], rRel:r[2]};
  17821. }
  17822. /* [MS-XLS] 2.5.198.107, 2.5.47 */
  17823. function parse_RgceElfLoc(blob) {
  17824. var r = blob.read_shift(2);
  17825. var c = blob.read_shift(2);
  17826. return {r:r, c:c & 0xFF, fQuoted:!!(c & 0x4000), cRel:c>>15, rRel:c>>15 };
  17827. }
  17828. /* [MS-XLS] 2.5.198.111 ; [MS-XLSB] 2.5.97.92 TODO */
  17829. function parse_RgceLocRel(blob, length, opts) {
  17830. var biff = opts && opts.biff ? opts.biff : 8;
  17831. if(biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts);
  17832. var r = blob.read_shift(biff >= 12 ? 4 : 2);
  17833. var cl = blob.read_shift(2);
  17834. var cRel = (cl & 0x4000) >> 14, rRel = (cl & 0x8000) >> 15;
  17835. cl &= 0x3FFF;
  17836. if(rRel == 1) while(r > 0x7FFFF) r -= 0x100000;
  17837. if(cRel == 1) while(cl > 0x1FFF) cl = cl - 0x4000;
  17838. return {r:r,c:cl,cRel:cRel,rRel:rRel};
  17839. }
  17840. function parse_RgceLocRel_BIFF2(blob) {
  17841. var rl = blob.read_shift(2);
  17842. var c = blob.read_shift(1);
  17843. var rRel = (rl & 0x8000) >> 15, cRel = (rl & 0x4000) >> 14;
  17844. rl &= 0x3FFF;
  17845. if(rRel == 1 && rl >= 0x2000) rl = rl - 0x4000;
  17846. if(cRel == 1 && c >= 0x80) c = c - 0x100;
  17847. return {r:rl,c:c,cRel:cRel,rRel:rRel};
  17848. }
  17849. /* [MS-XLS] 2.5.198.27 ; [MS-XLSB] 2.5.97.18 */
  17850. function parse_PtgArea(blob, length, opts) {
  17851. var type = (blob[blob.l++] & 0x60) >> 5;
  17852. var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts);
  17853. return [type, area];
  17854. }
  17855. /* [MS-XLS] 2.5.198.28 ; [MS-XLSB] 2.5.97.19 */
  17856. function parse_PtgArea3d(blob, length, opts) {
  17857. var type = (blob[blob.l++] & 0x60) >> 5;
  17858. var ixti = blob.read_shift(2, 'i');
  17859. var w = 8;
  17860. if(opts) switch(opts.biff) {
  17861. case 5: blob.l += 12; w = 6; break;
  17862. case 12: w = 12; break;
  17863. }
  17864. var area = parse_RgceArea(blob, w, opts);
  17865. return [type, ixti, area];
  17866. }
  17867. /* [MS-XLS] 2.5.198.29 ; [MS-XLSB] 2.5.97.20 */
  17868. function parse_PtgAreaErr(blob, length, opts) {
  17869. var type = (blob[blob.l++] & 0x60) >> 5;
  17870. blob.l += opts && (opts.biff > 8) ? 12 : (opts.biff < 8 ? 6 : 8);
  17871. return [type];
  17872. }
  17873. /* [MS-XLS] 2.5.198.30 ; [MS-XLSB] 2.5.97.21 */
  17874. function parse_PtgAreaErr3d(blob, length, opts) {
  17875. var type = (blob[blob.l++] & 0x60) >> 5;
  17876. var ixti = blob.read_shift(2);
  17877. var w = 8;
  17878. if(opts) switch(opts.biff) {
  17879. case 5: blob.l += 12; w = 6; break;
  17880. case 12: w = 12; break;
  17881. }
  17882. blob.l += w;
  17883. return [type, ixti];
  17884. }
  17885. /* [MS-XLS] 2.5.198.31 ; [MS-XLSB] 2.5.97.22 */
  17886. function parse_PtgAreaN(blob, length, opts) {
  17887. var type = (blob[blob.l++] & 0x60) >> 5;
  17888. var area = parse_RgceAreaRel(blob, length - 1, opts);
  17889. return [type, area];
  17890. }
  17891. /* [MS-XLS] 2.5.198.32 ; [MS-XLSB] 2.5.97.23 */
  17892. function parse_PtgArray(blob, length, opts) {
  17893. var type = (blob[blob.l++] & 0x60) >> 5;
  17894. blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7;
  17895. return [type];
  17896. }
  17897. /* [MS-XLS] 2.5.198.33 ; [MS-XLSB] 2.5.97.24 */
  17898. function parse_PtgAttrBaxcel(blob) {
  17899. var bitSemi = blob[blob.l+1] & 0x01; /* 1 = volatile */
  17900. var bitBaxcel = 1;
  17901. blob.l += 4;
  17902. return [bitSemi, bitBaxcel];
  17903. }
  17904. /* [MS-XLS] 2.5.198.34 ; [MS-XLSB] 2.5.97.25 */
  17905. function parse_PtgAttrChoose(blob, length, opts) {
  17906. blob.l +=2;
  17907. var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  17908. var o = [];
  17909. /* offset is 1 less than the number of elements */
  17910. for(var i = 0; i <= offset; ++i) o.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2));
  17911. return o;
  17912. }
  17913. /* [MS-XLS] 2.5.198.35 ; [MS-XLSB] 2.5.97.26 */
  17914. function parse_PtgAttrGoto(blob, length, opts) {
  17915. var bitGoto = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17916. blob.l += 2;
  17917. return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  17918. }
  17919. /* [MS-XLS] 2.5.198.36 ; [MS-XLSB] 2.5.97.27 */
  17920. function parse_PtgAttrIf(blob, length, opts) {
  17921. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17922. blob.l += 2;
  17923. return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)];
  17924. }
  17925. /* [MS-XLSB] 2.5.97.28 */
  17926. function parse_PtgAttrIfError(blob) {
  17927. var bitIf = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17928. blob.l += 2;
  17929. return [bitIf, blob.read_shift(2)];
  17930. }
  17931. /* [MS-XLS] 2.5.198.37 ; [MS-XLSB] 2.5.97.29 */
  17932. function parse_PtgAttrSemi(blob, length, opts) {
  17933. var bitSemi = (blob[blob.l+1] & 0xFF) ? 1 : 0;
  17934. blob.l += opts && opts.biff == 2 ? 3 : 4;
  17935. return [bitSemi];
  17936. }
  17937. /* [MS-XLS] 2.5.198.40 ; [MS-XLSB] 2.5.97.32 */
  17938. function parse_PtgAttrSpaceType(blob) {
  17939. var type = blob.read_shift(1), cch = blob.read_shift(1);
  17940. return [type, cch];
  17941. }
  17942. /* [MS-XLS] 2.5.198.38 ; [MS-XLSB] 2.5.97.30 */
  17943. function parse_PtgAttrSpace(blob) {
  17944. blob.read_shift(2);
  17945. return parse_PtgAttrSpaceType(blob, 2);
  17946. }
  17947. /* [MS-XLS] 2.5.198.39 ; [MS-XLSB] 2.5.97.31 */
  17948. function parse_PtgAttrSpaceSemi(blob) {
  17949. blob.read_shift(2);
  17950. return parse_PtgAttrSpaceType(blob, 2);
  17951. }
  17952. /* [MS-XLS] 2.5.198.84 ; [MS-XLSB] 2.5.97.68 TODO */
  17953. function parse_PtgRef(blob, length, opts) {
  17954. //var ptg = blob[blob.l] & 0x1F;
  17955. var type = (blob[blob.l] & 0x60)>>5;
  17956. blob.l += 1;
  17957. var loc = parse_RgceLoc(blob, 0, opts);
  17958. return [type, loc];
  17959. }
  17960. /* [MS-XLS] 2.5.198.88 ; [MS-XLSB] 2.5.97.72 TODO */
  17961. function parse_PtgRefN(blob, length, opts) {
  17962. var type = (blob[blob.l] & 0x60)>>5;
  17963. blob.l += 1;
  17964. var loc = parse_RgceLocRel(blob, 0, opts);
  17965. return [type, loc];
  17966. }
  17967. /* [MS-XLS] 2.5.198.85 ; [MS-XLSB] 2.5.97.69 TODO */
  17968. function parse_PtgRef3d(blob, length, opts) {
  17969. var type = (blob[blob.l] & 0x60)>>5;
  17970. blob.l += 1;
  17971. var ixti = blob.read_shift(2); // XtiIndex
  17972. if(opts && opts.biff == 5) blob.l += 12;
  17973. var loc = parse_RgceLoc(blob, 0, opts); // TODO: or RgceLocRel
  17974. return [type, ixti, loc];
  17975. }
  17976. /* [MS-XLS] 2.5.198.62 ; [MS-XLSB] 2.5.97.45 TODO */
  17977. function parse_PtgFunc(blob, length, opts) {
  17978. //var ptg = blob[blob.l] & 0x1F;
  17979. var type = (blob[blob.l] & 0x60)>>5;
  17980. blob.l += 1;
  17981. var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2);
  17982. return [FtabArgc[iftab], Ftab[iftab], type];
  17983. }
  17984. /* [MS-XLS] 2.5.198.63 ; [MS-XLSB] 2.5.97.46 TODO */
  17985. function parse_PtgFuncVar(blob, length, opts) {
  17986. var type = blob[blob.l++];
  17987. var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [(type == 0x58 ? -1 : 0), blob.read_shift(1)]: parsetab(blob);
  17988. return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]];
  17989. }
  17990. function parsetab(blob) {
  17991. return [blob[blob.l+1]>>7, blob.read_shift(2) & 0x7FFF];
  17992. }
  17993. /* [MS-XLS] 2.5.198.41 ; [MS-XLSB] 2.5.97.33 */
  17994. function parse_PtgAttrSum(blob, length, opts) {
  17995. blob.l += opts && opts.biff == 2 ? 3 : 4; return;
  17996. }
  17997. /* [MS-XLS] 2.5.198.58 ; [MS-XLSB] 2.5.97.40 */
  17998. function parse_PtgExp(blob, length, opts) {
  17999. blob.l++;
  18000. if(opts && opts.biff == 12) return [blob.read_shift(4, 'i'), 0];
  18001. var row = blob.read_shift(2);
  18002. var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  18003. return [row, col];
  18004. }
  18005. /* [MS-XLS] 2.5.198.57 ; [MS-XLSB] 2.5.97.39 */
  18006. function parse_PtgErr(blob) { blob.l++; return BErr[blob.read_shift(1)]; }
  18007. /* [MS-XLS] 2.5.198.66 ; [MS-XLSB] 2.5.97.49 */
  18008. function parse_PtgInt(blob) { blob.l++; return blob.read_shift(2); }
  18009. /* [MS-XLS] 2.5.198.42 ; [MS-XLSB] 2.5.97.34 */
  18010. function parse_PtgBool(blob) { blob.l++; return blob.read_shift(1)!==0;}
  18011. /* [MS-XLS] 2.5.198.79 ; [MS-XLSB] 2.5.97.63 */
  18012. function parse_PtgNum(blob) { blob.l++; return parse_Xnum(blob, 8); }
  18013. /* [MS-XLS] 2.5.198.89 ; [MS-XLSB] 2.5.97.74 */
  18014. function parse_PtgStr(blob, length, opts) { blob.l++; return parse_ShortXLUnicodeString(blob, length-1, opts); }
  18015. /* [MS-XLS] 2.5.192.112 + 2.5.192.11{3,4,5,6,7} */
  18016. /* [MS-XLSB] 2.5.97.93 + 2.5.97.9{4,5,6,7} */
  18017. function parse_SerAr(blob, biff) {
  18018. var val = [blob.read_shift(1)];
  18019. if(biff == 12) switch(val[0]) {
  18020. case 0x02: val[0] = 0x04; break; /* SerBool */
  18021. case 0x04: val[0] = 0x10; break; /* SerErr */
  18022. case 0x00: val[0] = 0x01; break; /* SerNum */
  18023. case 0x01: val[0] = 0x02; break; /* SerStr */
  18024. }
  18025. switch(val[0]) {
  18026. case 0x04: /* SerBool -- boolean */
  18027. val[1] = parsebool(blob, 1) ? 'TRUE' : 'FALSE';
  18028. if(biff != 12) blob.l += 7; break;
  18029. case 0x25: /* appears to be an alias */
  18030. case 0x10: /* SerErr -- error */
  18031. val[1] = BErr[blob[blob.l]];
  18032. blob.l += ((biff == 12) ? 4 : 8); break;
  18033. case 0x00: /* SerNil -- honestly, I'm not sure how to reproduce this */
  18034. blob.l += 8; break;
  18035. case 0x01: /* SerNum -- Xnum */
  18036. val[1] = parse_Xnum(blob, 8); break;
  18037. case 0x02: /* SerStr -- XLUnicodeString (<256 chars) */
  18038. val[1] = parse_XLUnicodeString2(blob, 0, {biff:biff > 0 && biff < 8 ? 2 : biff}); break;
  18039. default: throw new Error("Bad SerAr: " + val[0]); /* Unreachable */
  18040. }
  18041. return val;
  18042. }
  18043. /* [MS-XLS] 2.5.198.61 ; [MS-XLSB] 2.5.97.44 */
  18044. function parse_PtgExtraMem(blob, cce, opts) {
  18045. var count = blob.read_shift((opts.biff == 12) ? 4 : 2);
  18046. var out = [];
  18047. for(var i = 0; i != count; ++i) out.push(((opts.biff == 12) ? parse_UncheckedRfX : parse_Ref8U)(blob, 8));
  18048. return out;
  18049. }
  18050. /* [MS-XLS] 2.5.198.59 ; [MS-XLSB] 2.5.97.41 */
  18051. function parse_PtgExtraArray(blob, length, opts) {
  18052. var rows = 0, cols = 0;
  18053. if(opts.biff == 12) {
  18054. rows = blob.read_shift(4); // DRw
  18055. cols = blob.read_shift(4); // DCol
  18056. } else {
  18057. cols = 1 + blob.read_shift(1); //DColByteU
  18058. rows = 1 + blob.read_shift(2); //DRw
  18059. }
  18060. if(opts.biff >= 2 && opts.biff < 8) { --rows; if(--cols == 0) cols = 0x100; }
  18061. // $FlowIgnore
  18062. for(var i = 0, o = []; i != rows && (o[i] = []); ++i)
  18063. for(var j = 0; j != cols; ++j) o[i][j] = parse_SerAr(blob, opts.biff);
  18064. return o;
  18065. }
  18066. /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 */
  18067. function parse_PtgName(blob, length, opts) {
  18068. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18069. var w = (!opts || (opts.biff >= 8)) ? 4 : 2;
  18070. var nameindex = blob.read_shift(w);
  18071. switch(opts.biff) {
  18072. case 2: blob.l += 5; break;
  18073. case 3: case 4: blob.l += 8; break;
  18074. case 5: blob.l += 12; break;
  18075. }
  18076. return [type, 0, nameindex];
  18077. }
  18078. /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 */
  18079. function parse_PtgNameX(blob, length, opts) {
  18080. if(opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts);
  18081. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18082. var ixti = blob.read_shift(2); // XtiIndex
  18083. var nameindex = blob.read_shift(4);
  18084. return [type, ixti, nameindex];
  18085. }
  18086. function parse_PtgNameX_BIFF5(blob) {
  18087. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18088. var ixti = blob.read_shift(2, 'i'); // XtiIndex
  18089. blob.l += 8;
  18090. var nameindex = blob.read_shift(2);
  18091. blob.l += 12;
  18092. return [type, ixti, nameindex];
  18093. }
  18094. /* [MS-XLS] 2.5.198.70 ; [MS-XLSB] 2.5.97.54 */
  18095. function parse_PtgMemArea(blob, length, opts) {
  18096. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18097. blob.l += (opts && opts.biff == 2 ? 3 : 4);
  18098. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  18099. return [type, cce];
  18100. }
  18101. /* [MS-XLS] 2.5.198.72 ; [MS-XLSB] 2.5.97.56 */
  18102. function parse_PtgMemFunc(blob, length, opts) {
  18103. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18104. var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2);
  18105. return [type, cce];
  18106. }
  18107. /* [MS-XLS] 2.5.198.86 ; [MS-XLSB] 2.5.97.69 */
  18108. function parse_PtgRefErr(blob, length, opts) {
  18109. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18110. blob.l += 4;
  18111. if(opts.biff < 8) blob.l--;
  18112. if(opts.biff == 12) blob.l += 2;
  18113. return [type];
  18114. }
  18115. /* [MS-XLS] 2.5.198.87 ; [MS-XLSB] 2.5.97.71 */
  18116. function parse_PtgRefErr3d(blob, length, opts) {
  18117. var type = (blob[blob.l++] & 0x60) >> 5;
  18118. var ixti = blob.read_shift(2);
  18119. var w = 4;
  18120. if(opts) switch(opts.biff) {
  18121. case 5: w = 15; break;
  18122. case 12: w = 6; break;
  18123. }
  18124. blob.l += w;
  18125. return [type, ixti];
  18126. }
  18127. /* [MS-XLS] 2.5.198.71 ; [MS-XLSB] 2.5.97.55 */
  18128. var parse_PtgMemErr = parsenoop;
  18129. /* [MS-XLS] 2.5.198.73 ; [MS-XLSB] 2.5.97.57 */
  18130. var parse_PtgMemNoMem = parsenoop;
  18131. /* [MS-XLS] 2.5.198.92 */
  18132. var parse_PtgTbl = parsenoop;
  18133. function parse_PtgElfLoc(blob, length, opts) {
  18134. blob.l += 2;
  18135. return [parse_RgceElfLoc(blob, 4, opts)];
  18136. }
  18137. function parse_PtgElfNoop(blob) {
  18138. blob.l += 6;
  18139. return [];
  18140. }
  18141. /* [MS-XLS] 2.5.198.46 */
  18142. var parse_PtgElfCol = parse_PtgElfLoc;
  18143. /* [MS-XLS] 2.5.198.47 */
  18144. var parse_PtgElfColS = parse_PtgElfNoop;
  18145. /* [MS-XLS] 2.5.198.48 */
  18146. var parse_PtgElfColSV = parse_PtgElfNoop;
  18147. /* [MS-XLS] 2.5.198.49 */
  18148. var parse_PtgElfColV = parse_PtgElfLoc;
  18149. /* [MS-XLS] 2.5.198.50 */
  18150. function parse_PtgElfLel(blob) {
  18151. blob.l += 2;
  18152. return [parseuint16(blob), blob.read_shift(2) & 0x01];
  18153. }
  18154. /* [MS-XLS] 2.5.198.51 */
  18155. var parse_PtgElfRadical = parse_PtgElfLoc;
  18156. /* [MS-XLS] 2.5.198.52 */
  18157. var parse_PtgElfRadicalLel = parse_PtgElfLel;
  18158. /* [MS-XLS] 2.5.198.53 */
  18159. var parse_PtgElfRadicalS = parse_PtgElfNoop;
  18160. /* [MS-XLS] 2.5.198.54 */
  18161. var parse_PtgElfRw = parse_PtgElfLoc;
  18162. /* [MS-XLS] 2.5.198.55 */
  18163. var parse_PtgElfRwV = parse_PtgElfLoc;
  18164. /* [MS-XLSB] 2.5.97.52 TODO */
  18165. var PtgListRT = [
  18166. "Data",
  18167. "All",
  18168. "Headers",
  18169. "??",
  18170. "?Data2",
  18171. "??",
  18172. "?DataHeaders",
  18173. "??",
  18174. "Totals",
  18175. "??",
  18176. "??",
  18177. "??",
  18178. "?DataTotals",
  18179. "??",
  18180. "??",
  18181. "??",
  18182. "?Current"
  18183. ];
  18184. function parse_PtgList(blob) {
  18185. blob.l += 2;
  18186. var ixti = blob.read_shift(2);
  18187. var flags = blob.read_shift(2);
  18188. var idx = blob.read_shift(4);
  18189. var c = blob.read_shift(2);
  18190. var C = blob.read_shift(2);
  18191. var rt = PtgListRT[(flags >> 2) & 0x1F];
  18192. return {ixti: ixti, coltype:(flags&0x3), rt:rt, idx:idx, c:c, C:C};
  18193. }
  18194. /* [MS-XLS] 2.5.198.91 ; [MS-XLSB] 2.5.97.76 */
  18195. function parse_PtgSxName(blob) {
  18196. blob.l += 2;
  18197. return [blob.read_shift(4)];
  18198. }
  18199. /* [XLS] old spec */
  18200. function parse_PtgSheet(blob, length, opts) {
  18201. blob.l += 5;
  18202. blob.l += 2;
  18203. blob.l += (opts.biff == 2 ? 1 : 4);
  18204. return ["PTGSHEET"];
  18205. }
  18206. function parse_PtgEndSheet(blob, length, opts) {
  18207. blob.l += (opts.biff == 2 ? 4 : 5);
  18208. return ["PTGENDSHEET"];
  18209. }
  18210. function parse_PtgMemAreaN(blob) {
  18211. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18212. var cce = blob.read_shift(2);
  18213. return [type, cce];
  18214. }
  18215. function parse_PtgMemNoMemN(blob) {
  18216. var type = (blob.read_shift(1) >>> 5) & 0x03;
  18217. var cce = blob.read_shift(2);
  18218. return [type, cce];
  18219. }
  18220. function parse_PtgAttrNoop(blob) {
  18221. blob.l += 4;
  18222. return [0, 0];
  18223. }
  18224. /* [MS-XLS] 2.5.198.25 ; [MS-XLSB] 2.5.97.16 */
  18225. var PtgTypes = {
  18226. 0x01: { n:'PtgExp', f:parse_PtgExp },
  18227. 0x02: { n:'PtgTbl', f:parse_PtgTbl },
  18228. 0x03: { n:'PtgAdd', f:parseread1 },
  18229. 0x04: { n:'PtgSub', f:parseread1 },
  18230. 0x05: { n:'PtgMul', f:parseread1 },
  18231. 0x06: { n:'PtgDiv', f:parseread1 },
  18232. 0x07: { n:'PtgPower', f:parseread1 },
  18233. 0x08: { n:'PtgConcat', f:parseread1 },
  18234. 0x09: { n:'PtgLt', f:parseread1 },
  18235. 0x0A: { n:'PtgLe', f:parseread1 },
  18236. 0x0B: { n:'PtgEq', f:parseread1 },
  18237. 0x0C: { n:'PtgGe', f:parseread1 },
  18238. 0x0D: { n:'PtgGt', f:parseread1 },
  18239. 0x0E: { n:'PtgNe', f:parseread1 },
  18240. 0x0F: { n:'PtgIsect', f:parseread1 },
  18241. 0x10: { n:'PtgUnion', f:parseread1 },
  18242. 0x11: { n:'PtgRange', f:parseread1 },
  18243. 0x12: { n:'PtgUplus', f:parseread1 },
  18244. 0x13: { n:'PtgUminus', f:parseread1 },
  18245. 0x14: { n:'PtgPercent', f:parseread1 },
  18246. 0x15: { n:'PtgParen', f:parseread1 },
  18247. 0x16: { n:'PtgMissArg', f:parseread1 },
  18248. 0x17: { n:'PtgStr', f:parse_PtgStr },
  18249. 0x1A: { n:'PtgSheet', f:parse_PtgSheet },
  18250. 0x1B: { n:'PtgEndSheet', f:parse_PtgEndSheet },
  18251. 0x1C: { n:'PtgErr', f:parse_PtgErr },
  18252. 0x1D: { n:'PtgBool', f:parse_PtgBool },
  18253. 0x1E: { n:'PtgInt', f:parse_PtgInt },
  18254. 0x1F: { n:'PtgNum', f:parse_PtgNum },
  18255. 0x20: { n:'PtgArray', f:parse_PtgArray },
  18256. 0x21: { n:'PtgFunc', f:parse_PtgFunc },
  18257. 0x22: { n:'PtgFuncVar', f:parse_PtgFuncVar },
  18258. 0x23: { n:'PtgName', f:parse_PtgName },
  18259. 0x24: { n:'PtgRef', f:parse_PtgRef },
  18260. 0x25: { n:'PtgArea', f:parse_PtgArea },
  18261. 0x26: { n:'PtgMemArea', f:parse_PtgMemArea },
  18262. 0x27: { n:'PtgMemErr', f:parse_PtgMemErr },
  18263. 0x28: { n:'PtgMemNoMem', f:parse_PtgMemNoMem },
  18264. 0x29: { n:'PtgMemFunc', f:parse_PtgMemFunc },
  18265. 0x2A: { n:'PtgRefErr', f:parse_PtgRefErr },
  18266. 0x2B: { n:'PtgAreaErr', f:parse_PtgAreaErr },
  18267. 0x2C: { n:'PtgRefN', f:parse_PtgRefN },
  18268. 0x2D: { n:'PtgAreaN', f:parse_PtgAreaN },
  18269. 0x2E: { n:'PtgMemAreaN', f:parse_PtgMemAreaN },
  18270. 0x2F: { n:'PtgMemNoMemN', f:parse_PtgMemNoMemN },
  18271. 0x39: { n:'PtgNameX', f:parse_PtgNameX },
  18272. 0x3A: { n:'PtgRef3d', f:parse_PtgRef3d },
  18273. 0x3B: { n:'PtgArea3d', f:parse_PtgArea3d },
  18274. 0x3C: { n:'PtgRefErr3d', f:parse_PtgRefErr3d },
  18275. 0x3D: { n:'PtgAreaErr3d', f:parse_PtgAreaErr3d },
  18276. 0xFF: {}
  18277. };
  18278. /* These are duplicated in the PtgTypes table */
  18279. var PtgDupes = {
  18280. 0x40: 0x20, 0x60: 0x20,
  18281. 0x41: 0x21, 0x61: 0x21,
  18282. 0x42: 0x22, 0x62: 0x22,
  18283. 0x43: 0x23, 0x63: 0x23,
  18284. 0x44: 0x24, 0x64: 0x24,
  18285. 0x45: 0x25, 0x65: 0x25,
  18286. 0x46: 0x26, 0x66: 0x26,
  18287. 0x47: 0x27, 0x67: 0x27,
  18288. 0x48: 0x28, 0x68: 0x28,
  18289. 0x49: 0x29, 0x69: 0x29,
  18290. 0x4A: 0x2A, 0x6A: 0x2A,
  18291. 0x4B: 0x2B, 0x6B: 0x2B,
  18292. 0x4C: 0x2C, 0x6C: 0x2C,
  18293. 0x4D: 0x2D, 0x6D: 0x2D,
  18294. 0x4E: 0x2E, 0x6E: 0x2E,
  18295. 0x4F: 0x2F, 0x6F: 0x2F,
  18296. 0x58: 0x22, 0x78: 0x22,
  18297. 0x59: 0x39, 0x79: 0x39,
  18298. 0x5A: 0x3A, 0x7A: 0x3A,
  18299. 0x5B: 0x3B, 0x7B: 0x3B,
  18300. 0x5C: 0x3C, 0x7C: 0x3C,
  18301. 0x5D: 0x3D, 0x7D: 0x3D
  18302. };
  18303. (function(){for(var y in PtgDupes) PtgTypes[y] = PtgTypes[PtgDupes[y]];})();
  18304. var Ptg18 = {
  18305. 0x01: { n:'PtgElfLel', f:parse_PtgElfLel },
  18306. 0x02: { n:'PtgElfRw', f:parse_PtgElfRw },
  18307. 0x03: { n:'PtgElfCol', f:parse_PtgElfCol },
  18308. 0x06: { n:'PtgElfRwV', f:parse_PtgElfRwV },
  18309. 0x07: { n:'PtgElfColV', f:parse_PtgElfColV },
  18310. 0x0A: { n:'PtgElfRadical', f:parse_PtgElfRadical },
  18311. 0x0B: { n:'PtgElfRadicalS', f:parse_PtgElfRadicalS },
  18312. 0x0D: { n:'PtgElfColS', f:parse_PtgElfColS },
  18313. 0x0F: { n:'PtgElfColSV', f:parse_PtgElfColSV },
  18314. 0x10: { n:'PtgElfRadicalLel', f:parse_PtgElfRadicalLel },
  18315. 0x19: { n:'PtgList', f:parse_PtgList },
  18316. 0x1D: { n:'PtgSxName', f:parse_PtgSxName },
  18317. 0xFF: {}
  18318. };
  18319. var Ptg19 = {
  18320. 0x00: { n:'PtgAttrNoop', f:parse_PtgAttrNoop },
  18321. 0x01: { n:'PtgAttrSemi', f:parse_PtgAttrSemi },
  18322. 0x02: { n:'PtgAttrIf', f:parse_PtgAttrIf },
  18323. 0x04: { n:'PtgAttrChoose', f:parse_PtgAttrChoose },
  18324. 0x08: { n:'PtgAttrGoto', f:parse_PtgAttrGoto },
  18325. 0x10: { n:'PtgAttrSum', f:parse_PtgAttrSum },
  18326. 0x20: { n:'PtgAttrBaxcel', f:parse_PtgAttrBaxcel },
  18327. 0x40: { n:'PtgAttrSpace', f:parse_PtgAttrSpace },
  18328. 0x41: { n:'PtgAttrSpaceSemi', f:parse_PtgAttrSpaceSemi },
  18329. 0x80: { n:'PtgAttrIfError', f:parse_PtgAttrIfError },
  18330. 0xFF: {}
  18331. };
  18332. Ptg19[0x21] = Ptg19[0x20];
  18333. /* [MS-XLS] 2.5.198.103 ; [MS-XLSB] 2.5.97.87 */
  18334. function parse_RgbExtra(blob, length, rgce, opts) {
  18335. if(opts.biff < 8) return parsenoop(blob, length);
  18336. var target = blob.l + length;
  18337. var o = [];
  18338. for(var i = 0; i !== rgce.length; ++i) {
  18339. switch(rgce[i][0]) {
  18340. case 'PtgArray': /* PtgArray -> PtgExtraArray */
  18341. rgce[i][1] = parse_PtgExtraArray(blob, 0, opts);
  18342. o.push(rgce[i][1]);
  18343. break;
  18344. case 'PtgMemArea': /* PtgMemArea -> PtgExtraMem */
  18345. rgce[i][2] = parse_PtgExtraMem(blob, rgce[i][1], opts);
  18346. o.push(rgce[i][2]);
  18347. break;
  18348. case 'PtgExp': /* PtgExp -> PtgExtraCol */
  18349. if(opts && opts.biff == 12) {
  18350. rgce[i][1][1] = blob.read_shift(4);
  18351. o.push(rgce[i][1]);
  18352. } break;
  18353. case 'PtgList': /* TODO: PtgList -> PtgExtraList */
  18354. case 'PtgElfRadicalS': /* TODO: PtgElfRadicalS -> PtgExtraElf */
  18355. case 'PtgElfColS': /* TODO: PtgElfColS -> PtgExtraElf */
  18356. case 'PtgElfColSV': /* TODO: PtgElfColSV -> PtgExtraElf */
  18357. throw "Unsupported " + rgce[i][0];
  18358. default: break;
  18359. }
  18360. }
  18361. length = target - blob.l;
  18362. /* note: this is technically an error but Excel disregards */
  18363. //if(target !== blob.l && blob.l !== target - length) throw new Error(target + " != " + blob.l);
  18364. if(length !== 0) o.push(parsenoop(blob, length));
  18365. return o;
  18366. }
  18367. /* [MS-XLS] 2.5.198.104 ; [MS-XLSB] 2.5.97.88 */
  18368. function parse_Rgce(blob, length, opts) {
  18369. var target = blob.l + length;
  18370. var R, id, ptgs = [];
  18371. while(target != blob.l) {
  18372. length = target - blob.l;
  18373. id = blob[blob.l];
  18374. R = PtgTypes[id];
  18375. if(id === 0x18 || id === 0x19) R = (id === 0x18 ? Ptg18 : Ptg19)[blob[blob.l + 1]];
  18376. if(!R || !R.f) { /*ptgs.push*/(parsenoop(blob, length)); }
  18377. else { ptgs.push([R.n, R.f(blob, length, opts)]); }
  18378. }
  18379. return ptgs;
  18380. }
  18381. function stringify_array(f) {
  18382. var o = [];
  18383. for(var i = 0; i < f.length; ++i) {
  18384. var x = f[i], r = [];
  18385. for(var j = 0; j < x.length; ++j) {
  18386. var y = x[j];
  18387. if(y) switch(y[0]) {
  18388. // TODO: handle embedded quotes
  18389. case 0x02:
  18390. r.push('"' + y[1].replace(/"/g,'""') + '"'); break;
  18391. default: r.push(y[1]);
  18392. } else r.push("");
  18393. }
  18394. o.push(r.join(","));
  18395. }
  18396. return o.join(";");
  18397. }
  18398. /* [MS-XLS] 2.2.2 ; [MS-XLSB] 2.2.2 TODO */
  18399. var PtgBinOp = {
  18400. PtgAdd: "+",
  18401. PtgConcat: "&",
  18402. PtgDiv: "/",
  18403. PtgEq: "=",
  18404. PtgGe: ">=",
  18405. PtgGt: ">",
  18406. PtgLe: "<=",
  18407. PtgLt: "<",
  18408. PtgMul: "*",
  18409. PtgNe: "<>",
  18410. PtgPower: "^",
  18411. PtgSub: "-"
  18412. };
  18413. // List of invalid characters needs to be tested further
  18414. var quoteCharacters = new RegExp(/[^\w\u4E00-\u9FFF\u3040-\u30FF]/);
  18415. function formula_quote_sheet_name(sname, opts) {
  18416. if(!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name");
  18417. if (quoteCharacters.test(sname)) return "'" + sname + "'";
  18418. return sname;
  18419. }
  18420. function get_ixti_raw(supbooks, ixti, opts) {
  18421. if(!supbooks) return "SH33TJSERR0";
  18422. if(opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti];
  18423. if(!supbooks.XTI) return "SH33TJSERR6";
  18424. var XTI = supbooks.XTI[ixti];
  18425. if(opts.biff < 8) {
  18426. if(ixti > 10000) ixti-= 65536;
  18427. if(ixti < 0) ixti = -ixti;
  18428. return ixti == 0 ? "" : supbooks.XTI[ixti - 1];
  18429. }
  18430. if(!XTI) return "SH33TJSERR1";
  18431. var o = "";
  18432. if(opts.biff > 8) switch(supbooks[XTI[0]][0]) {
  18433. case 0x0165: /* 'BrtSupSelf' */
  18434. o = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]];
  18435. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  18436. case 0x0166: /* 'BrtSupSame' */
  18437. if(opts.SID != null) return supbooks.SheetNames[opts.SID];
  18438. return "SH33TJSSAME" + supbooks[XTI[0]][0];
  18439. case 0x0163: /* 'BrtSupBookSrc' */
  18440. /* falls through */
  18441. default: return "SH33TJSSRC" + supbooks[XTI[0]][0];
  18442. }
  18443. switch(supbooks[XTI[0]][0][0]) {
  18444. case 0x0401:
  18445. o = XTI[1] == -1 ? "#REF" : (supbooks.SheetNames[XTI[1]] || "SH33TJSERR3");
  18446. return XTI[1] == XTI[2] ? o : o + ":" + supbooks.SheetNames[XTI[2]];
  18447. case 0x3A01: return supbooks[XTI[0]].slice(1).map(function(name) { return name.Name; }).join(";;"); //return "SH33TJSERR8";
  18448. default:
  18449. if(!supbooks[XTI[0]][0][3]) return "SH33TJSERR2";
  18450. o = XTI[1] == -1 ? "#REF" : (supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4");
  18451. return XTI[1] == XTI[2] ? o : o + ":" + supbooks[XTI[0]][0][3][XTI[2]];
  18452. }
  18453. }
  18454. function get_ixti(supbooks, ixti, opts) {
  18455. return formula_quote_sheet_name(get_ixti_raw(supbooks, ixti, opts), opts);
  18456. }
  18457. function stringify_formula(formula/*Array<any>*/, range, cell, supbooks, opts) {
  18458. var biff = (opts && opts.biff) || 8;
  18459. var _range = /*range != null ? range :*/ {s:{c:0, r:0},e:{c:0, r:0}};
  18460. var stack = [], e1, e2, c, ixti=0, nameidx=0, r, sname="";
  18461. if(!formula[0] || !formula[0][0]) return "";
  18462. var last_sp = -1, sp = "";
  18463. for(var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) {
  18464. var f = formula[0][ff];
  18465. switch(f[0]) {
  18466. case 'PtgUminus': /* [MS-XLS] 2.5.198.93 */
  18467. stack.push("-" + stack.pop()); break;
  18468. case 'PtgUplus': /* [MS-XLS] 2.5.198.95 */
  18469. stack.push("+" + stack.pop()); break;
  18470. case 'PtgPercent': /* [MS-XLS] 2.5.198.81 */
  18471. stack.push(stack.pop() + "%"); break;
  18472. case 'PtgAdd': /* [MS-XLS] 2.5.198.26 */
  18473. case 'PtgConcat': /* [MS-XLS] 2.5.198.43 */
  18474. case 'PtgDiv': /* [MS-XLS] 2.5.198.45 */
  18475. case 'PtgEq': /* [MS-XLS] 2.5.198.56 */
  18476. case 'PtgGe': /* [MS-XLS] 2.5.198.64 */
  18477. case 'PtgGt': /* [MS-XLS] 2.5.198.65 */
  18478. case 'PtgLe': /* [MS-XLS] 2.5.198.68 */
  18479. case 'PtgLt': /* [MS-XLS] 2.5.198.69 */
  18480. case 'PtgMul': /* [MS-XLS] 2.5.198.75 */
  18481. case 'PtgNe': /* [MS-XLS] 2.5.198.78 */
  18482. case 'PtgPower': /* [MS-XLS] 2.5.198.82 */
  18483. case 'PtgSub': /* [MS-XLS] 2.5.198.90 */
  18484. e1 = stack.pop(); e2 = stack.pop();
  18485. if(last_sp >= 0) {
  18486. switch(formula[0][last_sp][1][0]) {
  18487. case 0:
  18488. // $FlowIgnore
  18489. sp = fill(" ", formula[0][last_sp][1][1]); break;
  18490. case 1:
  18491. // $FlowIgnore
  18492. sp = fill("\r", formula[0][last_sp][1][1]); break;
  18493. default:
  18494. sp = "";
  18495. // $FlowIgnore
  18496. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  18497. }
  18498. e2 = e2 + sp;
  18499. last_sp = -1;
  18500. }
  18501. stack.push(e2+PtgBinOp[f[0]]+e1);
  18502. break;
  18503. case 'PtgIsect': /* [MS-XLS] 2.5.198.67 */
  18504. e1 = stack.pop(); e2 = stack.pop();
  18505. stack.push(e2+" "+e1);
  18506. break;
  18507. case 'PtgUnion': /* [MS-XLS] 2.5.198.94 */
  18508. e1 = stack.pop(); e2 = stack.pop();
  18509. stack.push(e2+","+e1);
  18510. break;
  18511. case 'PtgRange': /* [MS-XLS] 2.5.198.83 */
  18512. e1 = stack.pop(); e2 = stack.pop();
  18513. stack.push(e2+":"+e1);
  18514. break;
  18515. case 'PtgAttrChoose': /* [MS-XLS] 2.5.198.34 */
  18516. break;
  18517. case 'PtgAttrGoto': /* [MS-XLS] 2.5.198.35 */
  18518. break;
  18519. case 'PtgAttrIf': /* [MS-XLS] 2.5.198.36 */
  18520. break;
  18521. case 'PtgAttrIfError': /* [MS-XLSB] 2.5.97.28 */
  18522. break;
  18523. case 'PtgRef': /* [MS-XLS] 2.5.198.84 */
  18524. c = shift_cell_xls((f[1][1]), _range, opts);
  18525. stack.push(encode_cell_xls(c, biff));
  18526. break;
  18527. case 'PtgRefN': /* [MS-XLS] 2.5.198.88 */
  18528. c = cell ? shift_cell_xls((f[1][1]), cell, opts) : (f[1][1]);
  18529. stack.push(encode_cell_xls(c, biff));
  18530. break;
  18531. case 'PtgRef3d': /* [MS-XLS] 2.5.198.85 */
  18532. ixti = f[1][1]; c = shift_cell_xls((f[1][2]), _range, opts);
  18533. sname = get_ixti(supbooks, ixti, opts);
  18534. var w = sname; /* IE9 fails on defined names */ // eslint-disable-line no-unused-vars
  18535. stack.push(sname + "!" + encode_cell_xls(c, biff));
  18536. break;
  18537. case 'PtgFunc': /* [MS-XLS] 2.5.198.62 */
  18538. case 'PtgFuncVar': /* [MS-XLS] 2.5.198.63 */
  18539. /* f[1] = [argc, func, type] */
  18540. var argc = (f[1][0]), func = (f[1][1]);
  18541. if(!argc) argc = 0;
  18542. argc &= 0x7F;
  18543. var args = argc == 0 ? [] : stack.slice(-argc);
  18544. stack.length -= argc;
  18545. if(func === 'User') func = args.shift();
  18546. stack.push(func + "(" + args.join(",") + ")");
  18547. break;
  18548. case 'PtgBool': /* [MS-XLS] 2.5.198.42 */
  18549. stack.push(f[1] ? "TRUE" : "FALSE"); break;
  18550. case 'PtgInt': /* [MS-XLS] 2.5.198.66 */
  18551. stack.push(f[1]); break;
  18552. case 'PtgNum': /* [MS-XLS] 2.5.198.79 TODO: precision? */
  18553. stack.push(String(f[1])); break;
  18554. case 'PtgStr': /* [MS-XLS] 2.5.198.89 */
  18555. // $FlowIgnore
  18556. stack.push('"' + f[1].replace(/"/g, '""') + '"'); break;
  18557. case 'PtgErr': /* [MS-XLS] 2.5.198.57 */
  18558. stack.push(f[1]); break;
  18559. case 'PtgAreaN': /* [MS-XLS] 2.5.198.31 TODO */
  18560. r = shift_range_xls(f[1][1], cell ? {s:cell} : _range, opts);
  18561. stack.push(encode_range_xls((r), opts));
  18562. break;
  18563. case 'PtgArea': /* [MS-XLS] 2.5.198.27 TODO: fixed points */
  18564. r = shift_range_xls(f[1][1], _range, opts);
  18565. stack.push(encode_range_xls((r), opts));
  18566. break;
  18567. case 'PtgArea3d': /* [MS-XLS] 2.5.198.28 TODO */
  18568. ixti = f[1][1]; r = f[1][2];
  18569. sname = get_ixti(supbooks, ixti, opts);
  18570. stack.push(sname + "!" + encode_range_xls((r), opts));
  18571. break;
  18572. case 'PtgAttrSum': /* [MS-XLS] 2.5.198.41 */
  18573. stack.push("SUM(" + stack.pop() + ")");
  18574. break;
  18575. case 'PtgAttrBaxcel': /* [MS-XLS] 2.5.198.33 */
  18576. case 'PtgAttrSemi': /* [MS-XLS] 2.5.198.37 */
  18577. break;
  18578. case 'PtgName': /* [MS-XLS] 2.5.198.76 ; [MS-XLSB] 2.5.97.60 TODO: revisions */
  18579. /* f[1] = type, 0, nameindex */
  18580. nameidx = (f[1][2]);
  18581. var lbl = (supbooks.names||[])[nameidx-1] || (supbooks[0]||[])[nameidx];
  18582. var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx);
  18583. if(name in XLSXFutureFunctions) name = XLSXFutureFunctions[name];
  18584. stack.push(name);
  18585. break;
  18586. case 'PtgNameX': /* [MS-XLS] 2.5.198.77 ; [MS-XLSB] 2.5.97.61 TODO: revisions */
  18587. /* f[1] = type, ixti, nameindex */
  18588. var bookidx = (f[1][1]); nameidx = (f[1][2]); var externbook;
  18589. /* TODO: Properly handle missing values -- this should be using get_ixti_raw primarily */
  18590. if(opts.biff <= 5) {
  18591. if(bookidx < 0) bookidx = -bookidx;
  18592. if(supbooks[bookidx]) externbook = supbooks[bookidx][nameidx];
  18593. } else {
  18594. var o = "";
  18595. if(((supbooks[bookidx]||[])[0]||[])[0] == 0x3A01){/* empty */}
  18596. else if(((supbooks[bookidx]||[])[0]||[])[0] == 0x0401){
  18597. if(supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) {
  18598. o = supbooks.SheetNames[supbooks[bookidx][nameidx].itab-1] + "!";
  18599. }
  18600. }
  18601. else o = supbooks.SheetNames[nameidx-1]+ "!";
  18602. if(supbooks[bookidx] && supbooks[bookidx][nameidx]) o += supbooks[bookidx][nameidx].Name;
  18603. else if(supbooks[0] && supbooks[0][nameidx]) o += supbooks[0][nameidx].Name;
  18604. else {
  18605. var ixtidata = get_ixti_raw(supbooks, bookidx, opts).split(";;");
  18606. if(ixtidata[nameidx - 1]) o = ixtidata[nameidx - 1]; // TODO: confirm this is correct
  18607. else o += "SH33TJSERRX";
  18608. }
  18609. stack.push(o);
  18610. break;
  18611. }
  18612. if(!externbook) externbook = {Name: "SH33TJSERRY"};
  18613. stack.push(externbook.Name);
  18614. break;
  18615. case 'PtgParen': /* [MS-XLS] 2.5.198.80 */
  18616. var lp = '(', rp = ')';
  18617. if(last_sp >= 0) {
  18618. sp = "";
  18619. switch(formula[0][last_sp][1][0]) {
  18620. // $FlowIgnore
  18621. case 2: lp = fill(" ", formula[0][last_sp][1][1]) + lp; break;
  18622. // $FlowIgnore
  18623. case 3: lp = fill("\r", formula[0][last_sp][1][1]) + lp; break;
  18624. // $FlowIgnore
  18625. case 4: rp = fill(" ", formula[0][last_sp][1][1]) + rp; break;
  18626. // $FlowIgnore
  18627. case 5: rp = fill("\r", formula[0][last_sp][1][1]) + rp; break;
  18628. default:
  18629. // $FlowIgnore
  18630. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]);
  18631. }
  18632. last_sp = -1;
  18633. }
  18634. stack.push(lp + stack.pop() + rp); break;
  18635. case 'PtgRefErr': /* [MS-XLS] 2.5.198.86 */
  18636. stack.push('#REF!'); break;
  18637. case 'PtgRefErr3d': /* [MS-XLS] 2.5.198.87 */
  18638. stack.push('#REF!'); break;
  18639. case 'PtgExp': /* [MS-XLS] 2.5.198.58 TODO */
  18640. c = {c:(f[1][1]),r:(f[1][0])};
  18641. var q = ({c: cell.c, r:cell.r});
  18642. if(supbooks.sharedf[encode_cell(c)]) {
  18643. var parsedf = (supbooks.sharedf[encode_cell(c)]);
  18644. stack.push(stringify_formula(parsedf, _range, q, supbooks, opts));
  18645. }
  18646. else {
  18647. var fnd = false;
  18648. for(e1=0;e1!=supbooks.arrayf.length; ++e1) {
  18649. /* TODO: should be something like range_has */
  18650. e2 = supbooks.arrayf[e1];
  18651. if(c.c < e2[0].s.c || c.c > e2[0].e.c) continue;
  18652. if(c.r < e2[0].s.r || c.r > e2[0].e.r) continue;
  18653. stack.push(stringify_formula(e2[1], _range, q, supbooks, opts));
  18654. fnd = true;
  18655. break;
  18656. }
  18657. if(!fnd) stack.push(f[1]);
  18658. }
  18659. break;
  18660. case 'PtgArray': /* [MS-XLS] 2.5.198.32 TODO */
  18661. stack.push("{" + stringify_array(f[1]) + "}");
  18662. break;
  18663. case 'PtgMemArea': /* [MS-XLS] 2.5.198.70 TODO: confirm this is a non-display */
  18664. //stack.push("(" + f[2].map(encode_range).join(",") + ")");
  18665. break;
  18666. case 'PtgAttrSpace': /* [MS-XLS] 2.5.198.38 */
  18667. case 'PtgAttrSpaceSemi': /* [MS-XLS] 2.5.198.39 */
  18668. last_sp = ff;
  18669. break;
  18670. case 'PtgTbl': /* [MS-XLS] 2.5.198.92 TODO */
  18671. break;
  18672. case 'PtgMemErr': /* [MS-XLS] 2.5.198.71 */
  18673. break;
  18674. case 'PtgMissArg': /* [MS-XLS] 2.5.198.74 */
  18675. stack.push("");
  18676. break;
  18677. case 'PtgAreaErr': /* [MS-XLS] 2.5.198.29 */
  18678. stack.push("#REF!"); break;
  18679. case 'PtgAreaErr3d': /* [MS-XLS] 2.5.198.30 */
  18680. stack.push("#REF!"); break;
  18681. case 'PtgList': /* [MS-XLSB] 2.5.97.52 */
  18682. // $FlowIgnore
  18683. stack.push("Table" + f[1].idx + "[#" + f[1].rt + "]");
  18684. break;
  18685. case 'PtgMemAreaN':
  18686. case 'PtgMemNoMemN':
  18687. case 'PtgAttrNoop':
  18688. case 'PtgSheet':
  18689. case 'PtgEndSheet':
  18690. break;
  18691. case 'PtgMemFunc': /* [MS-XLS] 2.5.198.72 TODO */
  18692. break;
  18693. case 'PtgMemNoMem': /* [MS-XLS] 2.5.198.73 TODO */
  18694. break;
  18695. case 'PtgElfCol': /* [MS-XLS] 2.5.198.46 */
  18696. case 'PtgElfColS': /* [MS-XLS] 2.5.198.47 */
  18697. case 'PtgElfColSV': /* [MS-XLS] 2.5.198.48 */
  18698. case 'PtgElfColV': /* [MS-XLS] 2.5.198.49 */
  18699. case 'PtgElfLel': /* [MS-XLS] 2.5.198.50 */
  18700. case 'PtgElfRadical': /* [MS-XLS] 2.5.198.51 */
  18701. case 'PtgElfRadicalLel': /* [MS-XLS] 2.5.198.52 */
  18702. case 'PtgElfRadicalS': /* [MS-XLS] 2.5.198.53 */
  18703. case 'PtgElfRw': /* [MS-XLS] 2.5.198.54 */
  18704. case 'PtgElfRwV': /* [MS-XLS] 2.5.198.55 */
  18705. throw new Error("Unsupported ELFs");
  18706. case 'PtgSxName': /* [MS-XLS] 2.5.198.91 TODO -- find a test case */
  18707. throw new Error('Unrecognized Formula Token: ' + String(f));
  18708. default: throw new Error('Unrecognized Formula Token: ' + String(f));
  18709. }
  18710. var PtgNonDisp = ['PtgAttrSpace', 'PtgAttrSpaceSemi', 'PtgAttrGoto'];
  18711. if(opts.biff != 3) if(last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) {
  18712. f = formula[0][last_sp];
  18713. var _left = true;
  18714. switch(f[1][0]) {
  18715. /* note: some bad XLSB files omit the PtgParen */
  18716. case 4: _left = false;
  18717. /* falls through */
  18718. case 0:
  18719. // $FlowIgnore
  18720. sp = fill(" ", f[1][1]); break;
  18721. case 5: _left = false;
  18722. /* falls through */
  18723. case 1:
  18724. // $FlowIgnore
  18725. sp = fill("\r", f[1][1]); break;
  18726. default:
  18727. sp = "";
  18728. // $FlowIgnore
  18729. if(opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f[1][0]);
  18730. }
  18731. stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp));
  18732. last_sp = -1;
  18733. }
  18734. }
  18735. if(stack.length > 1 && opts.WTF) throw new Error("bad formula stack");
  18736. return stack[0];
  18737. }
  18738. /* [MS-XLS] 2.5.198.1 TODO */
  18739. function parse_ArrayParsedFormula(blob, length, opts) {
  18740. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  18741. var rgcb, cce = blob.read_shift(len); // length of rgce
  18742. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  18743. var rgce = parse_Rgce(blob, cce, opts);
  18744. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  18745. blob.l = target;
  18746. return [rgce, rgcb];
  18747. }
  18748. /* [MS-XLS] 2.5.198.3 TODO */
  18749. function parse_XLSCellParsedFormula(blob, length, opts) {
  18750. var target = blob.l + length, len = opts.biff == 2 ? 1 : 2;
  18751. var rgcb, cce = blob.read_shift(len); // length of rgce
  18752. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  18753. var rgce = parse_Rgce(blob, cce, opts);
  18754. if(length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts);
  18755. blob.l = target;
  18756. return [rgce, rgcb];
  18757. }
  18758. /* [MS-XLS] 2.5.198.21 */
  18759. function parse_NameParsedFormula(blob, length, opts, cce) {
  18760. var target = blob.l + length;
  18761. var rgce = parse_Rgce(blob, cce, opts);
  18762. var rgcb;
  18763. if(target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts);
  18764. return [rgce, rgcb];
  18765. }
  18766. /* [MS-XLS] 2.5.198.118 TODO */
  18767. function parse_SharedParsedFormula(blob, length, opts) {
  18768. var target = blob.l + length;
  18769. var rgcb, cce = blob.read_shift(2); // length of rgce
  18770. var rgce = parse_Rgce(blob, cce, opts);
  18771. if(cce == 0xFFFF) return [[],parsenoop(blob, length-2)];
  18772. if(length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts);
  18773. return [rgce, rgcb];
  18774. }
  18775. /* [MS-XLS] 2.5.133 TODO: how to emit empty strings? */
  18776. function parse_FormulaValue(blob) {
  18777. var b;
  18778. if(__readUInt16LE(blob,blob.l + 6) !== 0xFFFF) return [parse_Xnum(blob),'n'];
  18779. switch(blob[blob.l]) {
  18780. case 0x00: blob.l += 8; return ["String", 's'];
  18781. case 0x01: b = blob[blob.l+2] === 0x1; blob.l += 8; return [b,'b'];
  18782. case 0x02: b = blob[blob.l+2]; blob.l += 8; return [b,'e'];
  18783. case 0x03: blob.l += 8; return ["",'s'];
  18784. }
  18785. return [];
  18786. }
  18787. function write_FormulaValue(value) {
  18788. if(value == null) {
  18789. // Blank String Value
  18790. var o = new_buf(8);
  18791. o.write_shift(1, 0x03);
  18792. o.write_shift(1, 0);
  18793. o.write_shift(2, 0);
  18794. o.write_shift(2, 0);
  18795. o.write_shift(2, 0xFFFF);
  18796. return o;
  18797. } else if(typeof value == "number") return write_Xnum(value);
  18798. return write_Xnum(0);
  18799. }
  18800. /* [MS-XLS] 2.4.127 TODO */
  18801. function parse_Formula(blob, length, opts) {
  18802. var end = blob.l + length;
  18803. var cell = parse_XLSCell(blob, 6);
  18804. if(opts.biff == 2) ++blob.l;
  18805. var val = parse_FormulaValue(blob,8);
  18806. var flags = blob.read_shift(1);
  18807. if(opts.biff != 2) {
  18808. blob.read_shift(1);
  18809. if(opts.biff >= 5) {
  18810. /*var chn = */blob.read_shift(4);
  18811. }
  18812. }
  18813. var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts);
  18814. return {cell:cell, val:val[0], formula:cbf, shared: (flags >> 3) & 1, tt:val[1]};
  18815. }
  18816. function write_Formula(cell, R, C, opts, os) {
  18817. // Cell
  18818. var o1 = write_XLSCell(R, C, os);
  18819. // FormulaValue
  18820. var o2 = write_FormulaValue(cell.v);
  18821. // flags + cache
  18822. var o3 = new_buf(6);
  18823. var flags = 0x01 | 0x20;
  18824. o3.write_shift(2, flags);
  18825. o3.write_shift(4, 0);
  18826. // CellParsedFormula
  18827. var bf = new_buf(cell.bf.length);
  18828. for(var i = 0; i < cell.bf.length; ++i) bf[i] = cell.bf[i];
  18829. var out = bconcat([o1, o2, o3, bf]);
  18830. return out;
  18831. }
  18832. /* XLSB Parsed Formula records have the same shape */
  18833. function parse_XLSBParsedFormula(data, length, opts) {
  18834. var cce = data.read_shift(4);
  18835. var rgce = parse_Rgce(data, cce, opts);
  18836. var cb = data.read_shift(4);
  18837. var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;
  18838. return [rgce, rgcb];
  18839. }
  18840. /* [MS-XLSB] 2.5.97.1 ArrayParsedFormula */
  18841. var parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula;
  18842. /* [MS-XLSB] 2.5.97.4 CellParsedFormula */
  18843. var parse_XLSBCellParsedFormula = parse_XLSBParsedFormula;
  18844. /* [MS-XLSB] 2.5.97.8 DVParsedFormula */
  18845. //var parse_XLSBDVParsedFormula = parse_XLSBParsedFormula;
  18846. /* [MS-XLSB] 2.5.97.9 FRTParsedFormula */
  18847. //var parse_XLSBFRTParsedFormula = parse_XLSBParsedFormula2;
  18848. /* [MS-XLSB] 2.5.97.12 NameParsedFormula */
  18849. var parse_XLSBNameParsedFormula = parse_XLSBParsedFormula;
  18850. /* [MS-XLSB] 2.5.97.98 SharedParsedFormula */
  18851. var parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula;
  18852. /* [MS-XLS] 2.5.198.4 */
  18853. var Cetab = {
  18854. 0x0000: 'BEEP',
  18855. 0x0001: 'OPEN',
  18856. 0x0002: 'OPEN.LINKS',
  18857. 0x0003: 'CLOSE.ALL',
  18858. 0x0004: 'SAVE',
  18859. 0x0005: 'SAVE.AS',
  18860. 0x0006: 'FILE.DELETE',
  18861. 0x0007: 'PAGE.SETUP',
  18862. 0x0008: 'PRINT',
  18863. 0x0009: 'PRINTER.SETUP',
  18864. 0x000A: 'QUIT',
  18865. 0x000B: 'NEW.WINDOW',
  18866. 0x000C: 'ARRANGE.ALL',
  18867. 0x000D: 'WINDOW.SIZE',
  18868. 0x000E: 'WINDOW.MOVE',
  18869. 0x000F: 'FULL',
  18870. 0x0010: 'CLOSE',
  18871. 0x0011: 'RUN',
  18872. 0x0016: 'SET.PRINT.AREA',
  18873. 0x0017: 'SET.PRINT.TITLES',
  18874. 0x0018: 'SET.PAGE.BREAK',
  18875. 0x0019: 'REMOVE.PAGE.BREAK',
  18876. 0x001A: 'FONT',
  18877. 0x001B: 'DISPLAY',
  18878. 0x001C: 'PROTECT.DOCUMENT',
  18879. 0x001D: 'PRECISION',
  18880. 0x001E: 'A1.R1C1',
  18881. 0x001F: 'CALCULATE.NOW',
  18882. 0x0020: 'CALCULATION',
  18883. 0x0022: 'DATA.FIND',
  18884. 0x0023: 'EXTRACT',
  18885. 0x0024: 'DATA.DELETE',
  18886. 0x0025: 'SET.DATABASE',
  18887. 0x0026: 'SET.CRITERIA',
  18888. 0x0027: 'SORT',
  18889. 0x0028: 'DATA.SERIES',
  18890. 0x0029: 'TABLE',
  18891. 0x002A: 'FORMAT.NUMBER',
  18892. 0x002B: 'ALIGNMENT',
  18893. 0x002C: 'STYLE',
  18894. 0x002D: 'BORDER',
  18895. 0x002E: 'CELL.PROTECTION',
  18896. 0x002F: 'COLUMN.WIDTH',
  18897. 0x0030: 'UNDO',
  18898. 0x0031: 'CUT',
  18899. 0x0032: 'COPY',
  18900. 0x0033: 'PASTE',
  18901. 0x0034: 'CLEAR',
  18902. 0x0035: 'PASTE.SPECIAL',
  18903. 0x0036: 'EDIT.DELETE',
  18904. 0x0037: 'INSERT',
  18905. 0x0038: 'FILL.RIGHT',
  18906. 0x0039: 'FILL.DOWN',
  18907. 0x003D: 'DEFINE.NAME',
  18908. 0x003E: 'CREATE.NAMES',
  18909. 0x003F: 'FORMULA.GOTO',
  18910. 0x0040: 'FORMULA.FIND',
  18911. 0x0041: 'SELECT.LAST.CELL',
  18912. 0x0042: 'SHOW.ACTIVE.CELL',
  18913. 0x0043: 'GALLERY.AREA',
  18914. 0x0044: 'GALLERY.BAR',
  18915. 0x0045: 'GALLERY.COLUMN',
  18916. 0x0046: 'GALLERY.LINE',
  18917. 0x0047: 'GALLERY.PIE',
  18918. 0x0048: 'GALLERY.SCATTER',
  18919. 0x0049: 'COMBINATION',
  18920. 0x004A: 'PREFERRED',
  18921. 0x004B: 'ADD.OVERLAY',
  18922. 0x004C: 'GRIDLINES',
  18923. 0x004D: 'SET.PREFERRED',
  18924. 0x004E: 'AXES',
  18925. 0x004F: 'LEGEND',
  18926. 0x0050: 'ATTACH.TEXT',
  18927. 0x0051: 'ADD.ARROW',
  18928. 0x0052: 'SELECT.CHART',
  18929. 0x0053: 'SELECT.PLOT.AREA',
  18930. 0x0054: 'PATTERNS',
  18931. 0x0055: 'MAIN.CHART',
  18932. 0x0056: 'OVERLAY',
  18933. 0x0057: 'SCALE',
  18934. 0x0058: 'FORMAT.LEGEND',
  18935. 0x0059: 'FORMAT.TEXT',
  18936. 0x005A: 'EDIT.REPEAT',
  18937. 0x005B: 'PARSE',
  18938. 0x005C: 'JUSTIFY',
  18939. 0x005D: 'HIDE',
  18940. 0x005E: 'UNHIDE',
  18941. 0x005F: 'WORKSPACE',
  18942. 0x0060: 'FORMULA',
  18943. 0x0061: 'FORMULA.FILL',
  18944. 0x0062: 'FORMULA.ARRAY',
  18945. 0x0063: 'DATA.FIND.NEXT',
  18946. 0x0064: 'DATA.FIND.PREV',
  18947. 0x0065: 'FORMULA.FIND.NEXT',
  18948. 0x0066: 'FORMULA.FIND.PREV',
  18949. 0x0067: 'ACTIVATE',
  18950. 0x0068: 'ACTIVATE.NEXT',
  18951. 0x0069: 'ACTIVATE.PREV',
  18952. 0x006A: 'UNLOCKED.NEXT',
  18953. 0x006B: 'UNLOCKED.PREV',
  18954. 0x006C: 'COPY.PICTURE',
  18955. 0x006D: 'SELECT',
  18956. 0x006E: 'DELETE.NAME',
  18957. 0x006F: 'DELETE.FORMAT',
  18958. 0x0070: 'VLINE',
  18959. 0x0071: 'HLINE',
  18960. 0x0072: 'VPAGE',
  18961. 0x0073: 'HPAGE',
  18962. 0x0074: 'VSCROLL',
  18963. 0x0075: 'HSCROLL',
  18964. 0x0076: 'ALERT',
  18965. 0x0077: 'NEW',
  18966. 0x0078: 'CANCEL.COPY',
  18967. 0x0079: 'SHOW.CLIPBOARD',
  18968. 0x007A: 'MESSAGE',
  18969. 0x007C: 'PASTE.LINK',
  18970. 0x007D: 'APP.ACTIVATE',
  18971. 0x007E: 'DELETE.ARROW',
  18972. 0x007F: 'ROW.HEIGHT',
  18973. 0x0080: 'FORMAT.MOVE',
  18974. 0x0081: 'FORMAT.SIZE',
  18975. 0x0082: 'FORMULA.REPLACE',
  18976. 0x0083: 'SEND.KEYS',
  18977. 0x0084: 'SELECT.SPECIAL',
  18978. 0x0085: 'APPLY.NAMES',
  18979. 0x0086: 'REPLACE.FONT',
  18980. 0x0087: 'FREEZE.PANES',
  18981. 0x0088: 'SHOW.INFO',
  18982. 0x0089: 'SPLIT',
  18983. 0x008A: 'ON.WINDOW',
  18984. 0x008B: 'ON.DATA',
  18985. 0x008C: 'DISABLE.INPUT',
  18986. 0x008E: 'OUTLINE',
  18987. 0x008F: 'LIST.NAMES',
  18988. 0x0090: 'FILE.CLOSE',
  18989. 0x0091: 'SAVE.WORKBOOK',
  18990. 0x0092: 'DATA.FORM',
  18991. 0x0093: 'COPY.CHART',
  18992. 0x0094: 'ON.TIME',
  18993. 0x0095: 'WAIT',
  18994. 0x0096: 'FORMAT.FONT',
  18995. 0x0097: 'FILL.UP',
  18996. 0x0098: 'FILL.LEFT',
  18997. 0x0099: 'DELETE.OVERLAY',
  18998. 0x009B: 'SHORT.MENUS',
  18999. 0x009F: 'SET.UPDATE.STATUS',
  19000. 0x00A1: 'COLOR.PALETTE',
  19001. 0x00A2: 'DELETE.STYLE',
  19002. 0x00A3: 'WINDOW.RESTORE',
  19003. 0x00A4: 'WINDOW.MAXIMIZE',
  19004. 0x00A6: 'CHANGE.LINK',
  19005. 0x00A7: 'CALCULATE.DOCUMENT',
  19006. 0x00A8: 'ON.KEY',
  19007. 0x00A9: 'APP.RESTORE',
  19008. 0x00AA: 'APP.MOVE',
  19009. 0x00AB: 'APP.SIZE',
  19010. 0x00AC: 'APP.MINIMIZE',
  19011. 0x00AD: 'APP.MAXIMIZE',
  19012. 0x00AE: 'BRING.TO.FRONT',
  19013. 0x00AF: 'SEND.TO.BACK',
  19014. 0x00B9: 'MAIN.CHART.TYPE',
  19015. 0x00BA: 'OVERLAY.CHART.TYPE',
  19016. 0x00BB: 'SELECT.END',
  19017. 0x00BC: 'OPEN.MAIL',
  19018. 0x00BD: 'SEND.MAIL',
  19019. 0x00BE: 'STANDARD.FONT',
  19020. 0x00BF: 'CONSOLIDATE',
  19021. 0x00C0: 'SORT.SPECIAL',
  19022. 0x00C1: 'GALLERY.3D.AREA',
  19023. 0x00C2: 'GALLERY.3D.COLUMN',
  19024. 0x00C3: 'GALLERY.3D.LINE',
  19025. 0x00C4: 'GALLERY.3D.PIE',
  19026. 0x00C5: 'VIEW.3D',
  19027. 0x00C6: 'GOAL.SEEK',
  19028. 0x00C7: 'WORKGROUP',
  19029. 0x00C8: 'FILL.GROUP',
  19030. 0x00C9: 'UPDATE.LINK',
  19031. 0x00CA: 'PROMOTE',
  19032. 0x00CB: 'DEMOTE',
  19033. 0x00CC: 'SHOW.DETAIL',
  19034. 0x00CE: 'UNGROUP',
  19035. 0x00CF: 'OBJECT.PROPERTIES',
  19036. 0x00D0: 'SAVE.NEW.OBJECT',
  19037. 0x00D1: 'SHARE',
  19038. 0x00D2: 'SHARE.NAME',
  19039. 0x00D3: 'DUPLICATE',
  19040. 0x00D4: 'APPLY.STYLE',
  19041. 0x00D5: 'ASSIGN.TO.OBJECT',
  19042. 0x00D6: 'OBJECT.PROTECTION',
  19043. 0x00D7: 'HIDE.OBJECT',
  19044. 0x00D8: 'SET.EXTRACT',
  19045. 0x00D9: 'CREATE.PUBLISHER',
  19046. 0x00DA: 'SUBSCRIBE.TO',
  19047. 0x00DB: 'ATTRIBUTES',
  19048. 0x00DC: 'SHOW.TOOLBAR',
  19049. 0x00DE: 'PRINT.PREVIEW',
  19050. 0x00DF: 'EDIT.COLOR',
  19051. 0x00E0: 'SHOW.LEVELS',
  19052. 0x00E1: 'FORMAT.MAIN',
  19053. 0x00E2: 'FORMAT.OVERLAY',
  19054. 0x00E3: 'ON.RECALC',
  19055. 0x00E4: 'EDIT.SERIES',
  19056. 0x00E5: 'DEFINE.STYLE',
  19057. 0x00F0: 'LINE.PRINT',
  19058. 0x00F3: 'ENTER.DATA',
  19059. 0x00F9: 'GALLERY.RADAR',
  19060. 0x00FA: 'MERGE.STYLES',
  19061. 0x00FB: 'EDITION.OPTIONS',
  19062. 0x00FC: 'PASTE.PICTURE',
  19063. 0x00FD: 'PASTE.PICTURE.LINK',
  19064. 0x00FE: 'SPELLING',
  19065. 0x0100: 'ZOOM',
  19066. 0x0103: 'INSERT.OBJECT',
  19067. 0x0104: 'WINDOW.MINIMIZE',
  19068. 0x0109: 'SOUND.NOTE',
  19069. 0x010A: 'SOUND.PLAY',
  19070. 0x010B: 'FORMAT.SHAPE',
  19071. 0x010C: 'EXTEND.POLYGON',
  19072. 0x010D: 'FORMAT.AUTO',
  19073. 0x0110: 'GALLERY.3D.BAR',
  19074. 0x0111: 'GALLERY.3D.SURFACE',
  19075. 0x0112: 'FILL.AUTO',
  19076. 0x0114: 'CUSTOMIZE.TOOLBAR',
  19077. 0x0115: 'ADD.TOOL',
  19078. 0x0116: 'EDIT.OBJECT',
  19079. 0x0117: 'ON.DOUBLECLICK',
  19080. 0x0118: 'ON.ENTRY',
  19081. 0x0119: 'WORKBOOK.ADD',
  19082. 0x011A: 'WORKBOOK.MOVE',
  19083. 0x011B: 'WORKBOOK.COPY',
  19084. 0x011C: 'WORKBOOK.OPTIONS',
  19085. 0x011D: 'SAVE.WORKSPACE',
  19086. 0x0120: 'CHART.WIZARD',
  19087. 0x0121: 'DELETE.TOOL',
  19088. 0x0122: 'MOVE.TOOL',
  19089. 0x0123: 'WORKBOOK.SELECT',
  19090. 0x0124: 'WORKBOOK.ACTIVATE',
  19091. 0x0125: 'ASSIGN.TO.TOOL',
  19092. 0x0127: 'COPY.TOOL',
  19093. 0x0128: 'RESET.TOOL',
  19094. 0x0129: 'CONSTRAIN.NUMERIC',
  19095. 0x012A: 'PASTE.TOOL',
  19096. 0x012E: 'WORKBOOK.NEW',
  19097. 0x0131: 'SCENARIO.CELLS',
  19098. 0x0132: 'SCENARIO.DELETE',
  19099. 0x0133: 'SCENARIO.ADD',
  19100. 0x0134: 'SCENARIO.EDIT',
  19101. 0x0135: 'SCENARIO.SHOW',
  19102. 0x0136: 'SCENARIO.SHOW.NEXT',
  19103. 0x0137: 'SCENARIO.SUMMARY',
  19104. 0x0138: 'PIVOT.TABLE.WIZARD',
  19105. 0x0139: 'PIVOT.FIELD.PROPERTIES',
  19106. 0x013A: 'PIVOT.FIELD',
  19107. 0x013B: 'PIVOT.ITEM',
  19108. 0x013C: 'PIVOT.ADD.FIELDS',
  19109. 0x013E: 'OPTIONS.CALCULATION',
  19110. 0x013F: 'OPTIONS.EDIT',
  19111. 0x0140: 'OPTIONS.VIEW',
  19112. 0x0141: 'ADDIN.MANAGER',
  19113. 0x0142: 'MENU.EDITOR',
  19114. 0x0143: 'ATTACH.TOOLBARS',
  19115. 0x0144: 'VBAActivate',
  19116. 0x0145: 'OPTIONS.CHART',
  19117. 0x0148: 'VBA.INSERT.FILE',
  19118. 0x014A: 'VBA.PROCEDURE.DEFINITION',
  19119. 0x0150: 'ROUTING.SLIP',
  19120. 0x0152: 'ROUTE.DOCUMENT',
  19121. 0x0153: 'MAIL.LOGON',
  19122. 0x0156: 'INSERT.PICTURE',
  19123. 0x0157: 'EDIT.TOOL',
  19124. 0x0158: 'GALLERY.DOUGHNUT',
  19125. 0x015E: 'CHART.TREND',
  19126. 0x0160: 'PIVOT.ITEM.PROPERTIES',
  19127. 0x0162: 'WORKBOOK.INSERT',
  19128. 0x0163: 'OPTIONS.TRANSITION',
  19129. 0x0164: 'OPTIONS.GENERAL',
  19130. 0x0172: 'FILTER.ADVANCED',
  19131. 0x0175: 'MAIL.ADD.MAILER',
  19132. 0x0176: 'MAIL.DELETE.MAILER',
  19133. 0x0177: 'MAIL.REPLY',
  19134. 0x0178: 'MAIL.REPLY.ALL',
  19135. 0x0179: 'MAIL.FORWARD',
  19136. 0x017A: 'MAIL.NEXT.LETTER',
  19137. 0x017B: 'DATA.LABEL',
  19138. 0x017C: 'INSERT.TITLE',
  19139. 0x017D: 'FONT.PROPERTIES',
  19140. 0x017E: 'MACRO.OPTIONS',
  19141. 0x017F: 'WORKBOOK.HIDE',
  19142. 0x0180: 'WORKBOOK.UNHIDE',
  19143. 0x0181: 'WORKBOOK.DELETE',
  19144. 0x0182: 'WORKBOOK.NAME',
  19145. 0x0184: 'GALLERY.CUSTOM',
  19146. 0x0186: 'ADD.CHART.AUTOFORMAT',
  19147. 0x0187: 'DELETE.CHART.AUTOFORMAT',
  19148. 0x0188: 'CHART.ADD.DATA',
  19149. 0x0189: 'AUTO.OUTLINE',
  19150. 0x018A: 'TAB.ORDER',
  19151. 0x018B: 'SHOW.DIALOG',
  19152. 0x018C: 'SELECT.ALL',
  19153. 0x018D: 'UNGROUP.SHEETS',
  19154. 0x018E: 'SUBTOTAL.CREATE',
  19155. 0x018F: 'SUBTOTAL.REMOVE',
  19156. 0x0190: 'RENAME.OBJECT',
  19157. 0x019C: 'WORKBOOK.SCROLL',
  19158. 0x019D: 'WORKBOOK.NEXT',
  19159. 0x019E: 'WORKBOOK.PREV',
  19160. 0x019F: 'WORKBOOK.TAB.SPLIT',
  19161. 0x01A0: 'FULL.SCREEN',
  19162. 0x01A1: 'WORKBOOK.PROTECT',
  19163. 0x01A4: 'SCROLLBAR.PROPERTIES',
  19164. 0x01A5: 'PIVOT.SHOW.PAGES',
  19165. 0x01A6: 'TEXT.TO.COLUMNS',
  19166. 0x01A7: 'FORMAT.CHARTTYPE',
  19167. 0x01A8: 'LINK.FORMAT',
  19168. 0x01A9: 'TRACER.DISPLAY',
  19169. 0x01AE: 'TRACER.NAVIGATE',
  19170. 0x01AF: 'TRACER.CLEAR',
  19171. 0x01B0: 'TRACER.ERROR',
  19172. 0x01B1: 'PIVOT.FIELD.GROUP',
  19173. 0x01B2: 'PIVOT.FIELD.UNGROUP',
  19174. 0x01B3: 'CHECKBOX.PROPERTIES',
  19175. 0x01B4: 'LABEL.PROPERTIES',
  19176. 0x01B5: 'LISTBOX.PROPERTIES',
  19177. 0x01B6: 'EDITBOX.PROPERTIES',
  19178. 0x01B7: 'PIVOT.REFRESH',
  19179. 0x01B8: 'LINK.COMBO',
  19180. 0x01B9: 'OPEN.TEXT',
  19181. 0x01BA: 'HIDE.DIALOG',
  19182. 0x01BB: 'SET.DIALOG.FOCUS',
  19183. 0x01BC: 'ENABLE.OBJECT',
  19184. 0x01BD: 'PUSHBUTTON.PROPERTIES',
  19185. 0x01BE: 'SET.DIALOG.DEFAULT',
  19186. 0x01BF: 'FILTER',
  19187. 0x01C0: 'FILTER.SHOW.ALL',
  19188. 0x01C1: 'CLEAR.OUTLINE',
  19189. 0x01C2: 'FUNCTION.WIZARD',
  19190. 0x01C3: 'ADD.LIST.ITEM',
  19191. 0x01C4: 'SET.LIST.ITEM',
  19192. 0x01C5: 'REMOVE.LIST.ITEM',
  19193. 0x01C6: 'SELECT.LIST.ITEM',
  19194. 0x01C7: 'SET.CONTROL.VALUE',
  19195. 0x01C8: 'SAVE.COPY.AS',
  19196. 0x01CA: 'OPTIONS.LISTS.ADD',
  19197. 0x01CB: 'OPTIONS.LISTS.DELETE',
  19198. 0x01CC: 'SERIES.AXES',
  19199. 0x01CD: 'SERIES.X',
  19200. 0x01CE: 'SERIES.Y',
  19201. 0x01CF: 'ERRORBAR.X',
  19202. 0x01D0: 'ERRORBAR.Y',
  19203. 0x01D1: 'FORMAT.CHART',
  19204. 0x01D2: 'SERIES.ORDER',
  19205. 0x01D3: 'MAIL.LOGOFF',
  19206. 0x01D4: 'CLEAR.ROUTING.SLIP',
  19207. 0x01D5: 'APP.ACTIVATE.MICROSOFT',
  19208. 0x01D6: 'MAIL.EDIT.MAILER',
  19209. 0x01D7: 'ON.SHEET',
  19210. 0x01D8: 'STANDARD.WIDTH',
  19211. 0x01D9: 'SCENARIO.MERGE',
  19212. 0x01DA: 'SUMMARY.INFO',
  19213. 0x01DB: 'FIND.FILE',
  19214. 0x01DC: 'ACTIVE.CELL.FONT',
  19215. 0x01DD: 'ENABLE.TIPWIZARD',
  19216. 0x01DE: 'VBA.MAKE.ADDIN',
  19217. 0x01E0: 'INSERTDATATABLE',
  19218. 0x01E1: 'WORKGROUP.OPTIONS',
  19219. 0x01E2: 'MAIL.SEND.MAILER',
  19220. 0x01E5: 'AUTOCORRECT',
  19221. 0x01E9: 'POST.DOCUMENT',
  19222. 0x01EB: 'PICKLIST',
  19223. 0x01ED: 'VIEW.SHOW',
  19224. 0x01EE: 'VIEW.DEFINE',
  19225. 0x01EF: 'VIEW.DELETE',
  19226. 0x01FD: 'SHEET.BACKGROUND',
  19227. 0x01FE: 'INSERT.MAP.OBJECT',
  19228. 0x01FF: 'OPTIONS.MENONO',
  19229. 0x0205: 'MSOCHECKS',
  19230. 0x0206: 'NORMAL',
  19231. 0x0207: 'LAYOUT',
  19232. 0x0208: 'RM.PRINT.AREA',
  19233. 0x0209: 'CLEAR.PRINT.AREA',
  19234. 0x020A: 'ADD.PRINT.AREA',
  19235. 0x020B: 'MOVE.BRK',
  19236. 0x0221: 'HIDECURR.NOTE',
  19237. 0x0222: 'HIDEALL.NOTES',
  19238. 0x0223: 'DELETE.NOTE',
  19239. 0x0224: 'TRAVERSE.NOTES',
  19240. 0x0225: 'ACTIVATE.NOTES',
  19241. 0x026C: 'PROTECT.REVISIONS',
  19242. 0x026D: 'UNPROTECT.REVISIONS',
  19243. 0x0287: 'OPTIONS.ME',
  19244. 0x028D: 'WEB.PUBLISH',
  19245. 0x029B: 'NEWWEBQUERY',
  19246. 0x02A1: 'PIVOT.TABLE.CHART',
  19247. 0x02F1: 'OPTIONS.SAVE',
  19248. 0x02F3: 'OPTIONS.SPELL',
  19249. 0x0328: 'HIDEALL.INKANNOTS'
  19250. };
  19251. /* [MS-XLS] 2.5.198.17 */
  19252. /* [MS-XLSB] 2.5.97.10 */
  19253. var Ftab = {
  19254. 0x0000: 'COUNT',
  19255. 0x0001: 'IF',
  19256. 0x0002: 'ISNA',
  19257. 0x0003: 'ISERROR',
  19258. 0x0004: 'SUM',
  19259. 0x0005: 'AVERAGE',
  19260. 0x0006: 'MIN',
  19261. 0x0007: 'MAX',
  19262. 0x0008: 'ROW',
  19263. 0x0009: 'COLUMN',
  19264. 0x000A: 'NA',
  19265. 0x000B: 'NPV',
  19266. 0x000C: 'STDEV',
  19267. 0x000D: 'DOLLAR',
  19268. 0x000E: 'FIXED',
  19269. 0x000F: 'SIN',
  19270. 0x0010: 'COS',
  19271. 0x0011: 'TAN',
  19272. 0x0012: 'ATAN',
  19273. 0x0013: 'PI',
  19274. 0x0014: 'SQRT',
  19275. 0x0015: 'EXP',
  19276. 0x0016: 'LN',
  19277. 0x0017: 'LOG10',
  19278. 0x0018: 'ABS',
  19279. 0x0019: 'INT',
  19280. 0x001A: 'SIGN',
  19281. 0x001B: 'ROUND',
  19282. 0x001C: 'LOOKUP',
  19283. 0x001D: 'INDEX',
  19284. 0x001E: 'REPT',
  19285. 0x001F: 'MID',
  19286. 0x0020: 'LEN',
  19287. 0x0021: 'VALUE',
  19288. 0x0022: 'TRUE',
  19289. 0x0023: 'FALSE',
  19290. 0x0024: 'AND',
  19291. 0x0025: 'OR',
  19292. 0x0026: 'NOT',
  19293. 0x0027: 'MOD',
  19294. 0x0028: 'DCOUNT',
  19295. 0x0029: 'DSUM',
  19296. 0x002A: 'DAVERAGE',
  19297. 0x002B: 'DMIN',
  19298. 0x002C: 'DMAX',
  19299. 0x002D: 'DSTDEV',
  19300. 0x002E: 'VAR',
  19301. 0x002F: 'DVAR',
  19302. 0x0030: 'TEXT',
  19303. 0x0031: 'LINEST',
  19304. 0x0032: 'TREND',
  19305. 0x0033: 'LOGEST',
  19306. 0x0034: 'GROWTH',
  19307. 0x0035: 'GOTO',
  19308. 0x0036: 'HALT',
  19309. 0x0037: 'RETURN',
  19310. 0x0038: 'PV',
  19311. 0x0039: 'FV',
  19312. 0x003A: 'NPER',
  19313. 0x003B: 'PMT',
  19314. 0x003C: 'RATE',
  19315. 0x003D: 'MIRR',
  19316. 0x003E: 'IRR',
  19317. 0x003F: 'RAND',
  19318. 0x0040: 'MATCH',
  19319. 0x0041: 'DATE',
  19320. 0x0042: 'TIME',
  19321. 0x0043: 'DAY',
  19322. 0x0044: 'MONTH',
  19323. 0x0045: 'YEAR',
  19324. 0x0046: 'WEEKDAY',
  19325. 0x0047: 'HOUR',
  19326. 0x0048: 'MINUTE',
  19327. 0x0049: 'SECOND',
  19328. 0x004A: 'NOW',
  19329. 0x004B: 'AREAS',
  19330. 0x004C: 'ROWS',
  19331. 0x004D: 'COLUMNS',
  19332. 0x004E: 'OFFSET',
  19333. 0x004F: 'ABSREF',
  19334. 0x0050: 'RELREF',
  19335. 0x0051: 'ARGUMENT',
  19336. 0x0052: 'SEARCH',
  19337. 0x0053: 'TRANSPOSE',
  19338. 0x0054: 'ERROR',
  19339. 0x0055: 'STEP',
  19340. 0x0056: 'TYPE',
  19341. 0x0057: 'ECHO',
  19342. 0x0058: 'SET.NAME',
  19343. 0x0059: 'CALLER',
  19344. 0x005A: 'DEREF',
  19345. 0x005B: 'WINDOWS',
  19346. 0x005C: 'SERIES',
  19347. 0x005D: 'DOCUMENTS',
  19348. 0x005E: 'ACTIVE.CELL',
  19349. 0x005F: 'SELECTION',
  19350. 0x0060: 'RESULT',
  19351. 0x0061: 'ATAN2',
  19352. 0x0062: 'ASIN',
  19353. 0x0063: 'ACOS',
  19354. 0x0064: 'CHOOSE',
  19355. 0x0065: 'HLOOKUP',
  19356. 0x0066: 'VLOOKUP',
  19357. 0x0067: 'LINKS',
  19358. 0x0068: 'INPUT',
  19359. 0x0069: 'ISREF',
  19360. 0x006A: 'GET.FORMULA',
  19361. 0x006B: 'GET.NAME',
  19362. 0x006C: 'SET.VALUE',
  19363. 0x006D: 'LOG',
  19364. 0x006E: 'EXEC',
  19365. 0x006F: 'CHAR',
  19366. 0x0070: 'LOWER',
  19367. 0x0071: 'UPPER',
  19368. 0x0072: 'PROPER',
  19369. 0x0073: 'LEFT',
  19370. 0x0074: 'RIGHT',
  19371. 0x0075: 'EXACT',
  19372. 0x0076: 'TRIM',
  19373. 0x0077: 'REPLACE',
  19374. 0x0078: 'SUBSTITUTE',
  19375. 0x0079: 'CODE',
  19376. 0x007A: 'NAMES',
  19377. 0x007B: 'DIRECTORY',
  19378. 0x007C: 'FIND',
  19379. 0x007D: 'CELL',
  19380. 0x007E: 'ISERR',
  19381. 0x007F: 'ISTEXT',
  19382. 0x0080: 'ISNUMBER',
  19383. 0x0081: 'ISBLANK',
  19384. 0x0082: 'T',
  19385. 0x0083: 'N',
  19386. 0x0084: 'FOPEN',
  19387. 0x0085: 'FCLOSE',
  19388. 0x0086: 'FSIZE',
  19389. 0x0087: 'FREADLN',
  19390. 0x0088: 'FREAD',
  19391. 0x0089: 'FWRITELN',
  19392. 0x008A: 'FWRITE',
  19393. 0x008B: 'FPOS',
  19394. 0x008C: 'DATEVALUE',
  19395. 0x008D: 'TIMEVALUE',
  19396. 0x008E: 'SLN',
  19397. 0x008F: 'SYD',
  19398. 0x0090: 'DDB',
  19399. 0x0091: 'GET.DEF',
  19400. 0x0092: 'REFTEXT',
  19401. 0x0093: 'TEXTREF',
  19402. 0x0094: 'INDIRECT',
  19403. 0x0095: 'REGISTER',
  19404. 0x0096: 'CALL',
  19405. 0x0097: 'ADD.BAR',
  19406. 0x0098: 'ADD.MENU',
  19407. 0x0099: 'ADD.COMMAND',
  19408. 0x009A: 'ENABLE.COMMAND',
  19409. 0x009B: 'CHECK.COMMAND',
  19410. 0x009C: 'RENAME.COMMAND',
  19411. 0x009D: 'SHOW.BAR',
  19412. 0x009E: 'DELETE.MENU',
  19413. 0x009F: 'DELETE.COMMAND',
  19414. 0x00A0: 'GET.CHART.ITEM',
  19415. 0x00A1: 'DIALOG.BOX',
  19416. 0x00A2: 'CLEAN',
  19417. 0x00A3: 'MDETERM',
  19418. 0x00A4: 'MINVERSE',
  19419. 0x00A5: 'MMULT',
  19420. 0x00A6: 'FILES',
  19421. 0x00A7: 'IPMT',
  19422. 0x00A8: 'PPMT',
  19423. 0x00A9: 'COUNTA',
  19424. 0x00AA: 'CANCEL.KEY',
  19425. 0x00AB: 'FOR',
  19426. 0x00AC: 'WHILE',
  19427. 0x00AD: 'BREAK',
  19428. 0x00AE: 'NEXT',
  19429. 0x00AF: 'INITIATE',
  19430. 0x00B0: 'REQUEST',
  19431. 0x00B1: 'POKE',
  19432. 0x00B2: 'EXECUTE',
  19433. 0x00B3: 'TERMINATE',
  19434. 0x00B4: 'RESTART',
  19435. 0x00B5: 'HELP',
  19436. 0x00B6: 'GET.BAR',
  19437. 0x00B7: 'PRODUCT',
  19438. 0x00B8: 'FACT',
  19439. 0x00B9: 'GET.CELL',
  19440. 0x00BA: 'GET.WORKSPACE',
  19441. 0x00BB: 'GET.WINDOW',
  19442. 0x00BC: 'GET.DOCUMENT',
  19443. 0x00BD: 'DPRODUCT',
  19444. 0x00BE: 'ISNONTEXT',
  19445. 0x00BF: 'GET.NOTE',
  19446. 0x00C0: 'NOTE',
  19447. 0x00C1: 'STDEVP',
  19448. 0x00C2: 'VARP',
  19449. 0x00C3: 'DSTDEVP',
  19450. 0x00C4: 'DVARP',
  19451. 0x00C5: 'TRUNC',
  19452. 0x00C6: 'ISLOGICAL',
  19453. 0x00C7: 'DCOUNTA',
  19454. 0x00C8: 'DELETE.BAR',
  19455. 0x00C9: 'UNREGISTER',
  19456. 0x00CC: 'USDOLLAR',
  19457. 0x00CD: 'FINDB',
  19458. 0x00CE: 'SEARCHB',
  19459. 0x00CF: 'REPLACEB',
  19460. 0x00D0: 'LEFTB',
  19461. 0x00D1: 'RIGHTB',
  19462. 0x00D2: 'MIDB',
  19463. 0x00D3: 'LENB',
  19464. 0x00D4: 'ROUNDUP',
  19465. 0x00D5: 'ROUNDDOWN',
  19466. 0x00D6: 'ASC',
  19467. 0x00D7: 'DBCS',
  19468. 0x00D8: 'RANK',
  19469. 0x00DB: 'ADDRESS',
  19470. 0x00DC: 'DAYS360',
  19471. 0x00DD: 'TODAY',
  19472. 0x00DE: 'VDB',
  19473. 0x00DF: 'ELSE',
  19474. 0x00E0: 'ELSE.IF',
  19475. 0x00E1: 'END.IF',
  19476. 0x00E2: 'FOR.CELL',
  19477. 0x00E3: 'MEDIAN',
  19478. 0x00E4: 'SUMPRODUCT',
  19479. 0x00E5: 'SINH',
  19480. 0x00E6: 'COSH',
  19481. 0x00E7: 'TANH',
  19482. 0x00E8: 'ASINH',
  19483. 0x00E9: 'ACOSH',
  19484. 0x00EA: 'ATANH',
  19485. 0x00EB: 'DGET',
  19486. 0x00EC: 'CREATE.OBJECT',
  19487. 0x00ED: 'VOLATILE',
  19488. 0x00EE: 'LAST.ERROR',
  19489. 0x00EF: 'CUSTOM.UNDO',
  19490. 0x00F0: 'CUSTOM.REPEAT',
  19491. 0x00F1: 'FORMULA.CONVERT',
  19492. 0x00F2: 'GET.LINK.INFO',
  19493. 0x00F3: 'TEXT.BOX',
  19494. 0x00F4: 'INFO',
  19495. 0x00F5: 'GROUP',
  19496. 0x00F6: 'GET.OBJECT',
  19497. 0x00F7: 'DB',
  19498. 0x00F8: 'PAUSE',
  19499. 0x00FB: 'RESUME',
  19500. 0x00FC: 'FREQUENCY',
  19501. 0x00FD: 'ADD.TOOLBAR',
  19502. 0x00FE: 'DELETE.TOOLBAR',
  19503. 0x00FF: 'User',
  19504. 0x0100: 'RESET.TOOLBAR',
  19505. 0x0101: 'EVALUATE',
  19506. 0x0102: 'GET.TOOLBAR',
  19507. 0x0103: 'GET.TOOL',
  19508. 0x0104: 'SPELLING.CHECK',
  19509. 0x0105: 'ERROR.TYPE',
  19510. 0x0106: 'APP.TITLE',
  19511. 0x0107: 'WINDOW.TITLE',
  19512. 0x0108: 'SAVE.TOOLBAR',
  19513. 0x0109: 'ENABLE.TOOL',
  19514. 0x010A: 'PRESS.TOOL',
  19515. 0x010B: 'REGISTER.ID',
  19516. 0x010C: 'GET.WORKBOOK',
  19517. 0x010D: 'AVEDEV',
  19518. 0x010E: 'BETADIST',
  19519. 0x010F: 'GAMMALN',
  19520. 0x0110: 'BETAINV',
  19521. 0x0111: 'BINOMDIST',
  19522. 0x0112: 'CHIDIST',
  19523. 0x0113: 'CHIINV',
  19524. 0x0114: 'COMBIN',
  19525. 0x0115: 'CONFIDENCE',
  19526. 0x0116: 'CRITBINOM',
  19527. 0x0117: 'EVEN',
  19528. 0x0118: 'EXPONDIST',
  19529. 0x0119: 'FDIST',
  19530. 0x011A: 'FINV',
  19531. 0x011B: 'FISHER',
  19532. 0x011C: 'FISHERINV',
  19533. 0x011D: 'FLOOR',
  19534. 0x011E: 'GAMMADIST',
  19535. 0x011F: 'GAMMAINV',
  19536. 0x0120: 'CEILING',
  19537. 0x0121: 'HYPGEOMDIST',
  19538. 0x0122: 'LOGNORMDIST',
  19539. 0x0123: 'LOGINV',
  19540. 0x0124: 'NEGBINOMDIST',
  19541. 0x0125: 'NORMDIST',
  19542. 0x0126: 'NORMSDIST',
  19543. 0x0127: 'NORMINV',
  19544. 0x0128: 'NORMSINV',
  19545. 0x0129: 'STANDARDIZE',
  19546. 0x012A: 'ODD',
  19547. 0x012B: 'PERMUT',
  19548. 0x012C: 'POISSON',
  19549. 0x012D: 'TDIST',
  19550. 0x012E: 'WEIBULL',
  19551. 0x012F: 'SUMXMY2',
  19552. 0x0130: 'SUMX2MY2',
  19553. 0x0131: 'SUMX2PY2',
  19554. 0x0132: 'CHITEST',
  19555. 0x0133: 'CORREL',
  19556. 0x0134: 'COVAR',
  19557. 0x0135: 'FORECAST',
  19558. 0x0136: 'FTEST',
  19559. 0x0137: 'INTERCEPT',
  19560. 0x0138: 'PEARSON',
  19561. 0x0139: 'RSQ',
  19562. 0x013A: 'STEYX',
  19563. 0x013B: 'SLOPE',
  19564. 0x013C: 'TTEST',
  19565. 0x013D: 'PROB',
  19566. 0x013E: 'DEVSQ',
  19567. 0x013F: 'GEOMEAN',
  19568. 0x0140: 'HARMEAN',
  19569. 0x0141: 'SUMSQ',
  19570. 0x0142: 'KURT',
  19571. 0x0143: 'SKEW',
  19572. 0x0144: 'ZTEST',
  19573. 0x0145: 'LARGE',
  19574. 0x0146: 'SMALL',
  19575. 0x0147: 'QUARTILE',
  19576. 0x0148: 'PERCENTILE',
  19577. 0x0149: 'PERCENTRANK',
  19578. 0x014A: 'MODE',
  19579. 0x014B: 'TRIMMEAN',
  19580. 0x014C: 'TINV',
  19581. 0x014E: 'MOVIE.COMMAND',
  19582. 0x014F: 'GET.MOVIE',
  19583. 0x0150: 'CONCATENATE',
  19584. 0x0151: 'POWER',
  19585. 0x0152: 'PIVOT.ADD.DATA',
  19586. 0x0153: 'GET.PIVOT.TABLE',
  19587. 0x0154: 'GET.PIVOT.FIELD',
  19588. 0x0155: 'GET.PIVOT.ITEM',
  19589. 0x0156: 'RADIANS',
  19590. 0x0157: 'DEGREES',
  19591. 0x0158: 'SUBTOTAL',
  19592. 0x0159: 'SUMIF',
  19593. 0x015A: 'COUNTIF',
  19594. 0x015B: 'COUNTBLANK',
  19595. 0x015C: 'SCENARIO.GET',
  19596. 0x015D: 'OPTIONS.LISTS.GET',
  19597. 0x015E: 'ISPMT',
  19598. 0x015F: 'DATEDIF',
  19599. 0x0160: 'DATESTRING',
  19600. 0x0161: 'NUMBERSTRING',
  19601. 0x0162: 'ROMAN',
  19602. 0x0163: 'OPEN.DIALOG',
  19603. 0x0164: 'SAVE.DIALOG',
  19604. 0x0165: 'VIEW.GET',
  19605. 0x0166: 'GETPIVOTDATA',
  19606. 0x0167: 'HYPERLINK',
  19607. 0x0168: 'PHONETIC',
  19608. 0x0169: 'AVERAGEA',
  19609. 0x016A: 'MAXA',
  19610. 0x016B: 'MINA',
  19611. 0x016C: 'STDEVPA',
  19612. 0x016D: 'VARPA',
  19613. 0x016E: 'STDEVA',
  19614. 0x016F: 'VARA',
  19615. 0x0170: 'BAHTTEXT',
  19616. 0x0171: 'THAIDAYOFWEEK',
  19617. 0x0172: 'THAIDIGIT',
  19618. 0x0173: 'THAIMONTHOFYEAR',
  19619. 0x0174: 'THAINUMSOUND',
  19620. 0x0175: 'THAINUMSTRING',
  19621. 0x0176: 'THAISTRINGLENGTH',
  19622. 0x0177: 'ISTHAIDIGIT',
  19623. 0x0178: 'ROUNDBAHTDOWN',
  19624. 0x0179: 'ROUNDBAHTUP',
  19625. 0x017A: 'THAIYEAR',
  19626. 0x017B: 'RTD',
  19627. 0x017C: 'CUBEVALUE',
  19628. 0x017D: 'CUBEMEMBER',
  19629. 0x017E: 'CUBEMEMBERPROPERTY',
  19630. 0x017F: 'CUBERANKEDMEMBER',
  19631. 0x0180: 'HEX2BIN',
  19632. 0x0181: 'HEX2DEC',
  19633. 0x0182: 'HEX2OCT',
  19634. 0x0183: 'DEC2BIN',
  19635. 0x0184: 'DEC2HEX',
  19636. 0x0185: 'DEC2OCT',
  19637. 0x0186: 'OCT2BIN',
  19638. 0x0187: 'OCT2HEX',
  19639. 0x0188: 'OCT2DEC',
  19640. 0x0189: 'BIN2DEC',
  19641. 0x018A: 'BIN2OCT',
  19642. 0x018B: 'BIN2HEX',
  19643. 0x018C: 'IMSUB',
  19644. 0x018D: 'IMDIV',
  19645. 0x018E: 'IMPOWER',
  19646. 0x018F: 'IMABS',
  19647. 0x0190: 'IMSQRT',
  19648. 0x0191: 'IMLN',
  19649. 0x0192: 'IMLOG2',
  19650. 0x0193: 'IMLOG10',
  19651. 0x0194: 'IMSIN',
  19652. 0x0195: 'IMCOS',
  19653. 0x0196: 'IMEXP',
  19654. 0x0197: 'IMARGUMENT',
  19655. 0x0198: 'IMCONJUGATE',
  19656. 0x0199: 'IMAGINARY',
  19657. 0x019A: 'IMREAL',
  19658. 0x019B: 'COMPLEX',
  19659. 0x019C: 'IMSUM',
  19660. 0x019D: 'IMPRODUCT',
  19661. 0x019E: 'SERIESSUM',
  19662. 0x019F: 'FACTDOUBLE',
  19663. 0x01A0: 'SQRTPI',
  19664. 0x01A1: 'QUOTIENT',
  19665. 0x01A2: 'DELTA',
  19666. 0x01A3: 'GESTEP',
  19667. 0x01A4: 'ISEVEN',
  19668. 0x01A5: 'ISODD',
  19669. 0x01A6: 'MROUND',
  19670. 0x01A7: 'ERF',
  19671. 0x01A8: 'ERFC',
  19672. 0x01A9: 'BESSELJ',
  19673. 0x01AA: 'BESSELK',
  19674. 0x01AB: 'BESSELY',
  19675. 0x01AC: 'BESSELI',
  19676. 0x01AD: 'XIRR',
  19677. 0x01AE: 'XNPV',
  19678. 0x01AF: 'PRICEMAT',
  19679. 0x01B0: 'YIELDMAT',
  19680. 0x01B1: 'INTRATE',
  19681. 0x01B2: 'RECEIVED',
  19682. 0x01B3: 'DISC',
  19683. 0x01B4: 'PRICEDISC',
  19684. 0x01B5: 'YIELDDISC',
  19685. 0x01B6: 'TBILLEQ',
  19686. 0x01B7: 'TBILLPRICE',
  19687. 0x01B8: 'TBILLYIELD',
  19688. 0x01B9: 'PRICE',
  19689. 0x01BA: 'YIELD',
  19690. 0x01BB: 'DOLLARDE',
  19691. 0x01BC: 'DOLLARFR',
  19692. 0x01BD: 'NOMINAL',
  19693. 0x01BE: 'EFFECT',
  19694. 0x01BF: 'CUMPRINC',
  19695. 0x01C0: 'CUMIPMT',
  19696. 0x01C1: 'EDATE',
  19697. 0x01C2: 'EOMONTH',
  19698. 0x01C3: 'YEARFRAC',
  19699. 0x01C4: 'COUPDAYBS',
  19700. 0x01C5: 'COUPDAYS',
  19701. 0x01C6: 'COUPDAYSNC',
  19702. 0x01C7: 'COUPNCD',
  19703. 0x01C8: 'COUPNUM',
  19704. 0x01C9: 'COUPPCD',
  19705. 0x01CA: 'DURATION',
  19706. 0x01CB: 'MDURATION',
  19707. 0x01CC: 'ODDLPRICE',
  19708. 0x01CD: 'ODDLYIELD',
  19709. 0x01CE: 'ODDFPRICE',
  19710. 0x01CF: 'ODDFYIELD',
  19711. 0x01D0: 'RANDBETWEEN',
  19712. 0x01D1: 'WEEKNUM',
  19713. 0x01D2: 'AMORDEGRC',
  19714. 0x01D3: 'AMORLINC',
  19715. 0x01D4: 'CONVERT',
  19716. 0x02D4: 'SHEETJS',
  19717. 0x01D5: 'ACCRINT',
  19718. 0x01D6: 'ACCRINTM',
  19719. 0x01D7: 'WORKDAY',
  19720. 0x01D8: 'NETWORKDAYS',
  19721. 0x01D9: 'GCD',
  19722. 0x01DA: 'MULTINOMIAL',
  19723. 0x01DB: 'LCM',
  19724. 0x01DC: 'FVSCHEDULE',
  19725. 0x01DD: 'CUBEKPIMEMBER',
  19726. 0x01DE: 'CUBESET',
  19727. 0x01DF: 'CUBESETCOUNT',
  19728. 0x01E0: 'IFERROR',
  19729. 0x01E1: 'COUNTIFS',
  19730. 0x01E2: 'SUMIFS',
  19731. 0x01E3: 'AVERAGEIF',
  19732. 0x01E4: 'AVERAGEIFS'
  19733. };
  19734. var FtabArgc = {
  19735. 0x0002: 1, /* ISNA */
  19736. 0x0003: 1, /* ISERROR */
  19737. 0x000A: 0, /* NA */
  19738. 0x000F: 1, /* SIN */
  19739. 0x0010: 1, /* COS */
  19740. 0x0011: 1, /* TAN */
  19741. 0x0012: 1, /* ATAN */
  19742. 0x0013: 0, /* PI */
  19743. 0x0014: 1, /* SQRT */
  19744. 0x0015: 1, /* EXP */
  19745. 0x0016: 1, /* LN */
  19746. 0x0017: 1, /* LOG10 */
  19747. 0x0018: 1, /* ABS */
  19748. 0x0019: 1, /* INT */
  19749. 0x001A: 1, /* SIGN */
  19750. 0x001B: 2, /* ROUND */
  19751. 0x001E: 2, /* REPT */
  19752. 0x001F: 3, /* MID */
  19753. 0x0020: 1, /* LEN */
  19754. 0x0021: 1, /* VALUE */
  19755. 0x0022: 0, /* TRUE */
  19756. 0x0023: 0, /* FALSE */
  19757. 0x0026: 1, /* NOT */
  19758. 0x0027: 2, /* MOD */
  19759. 0x0028: 3, /* DCOUNT */
  19760. 0x0029: 3, /* DSUM */
  19761. 0x002A: 3, /* DAVERAGE */
  19762. 0x002B: 3, /* DMIN */
  19763. 0x002C: 3, /* DMAX */
  19764. 0x002D: 3, /* DSTDEV */
  19765. 0x002F: 3, /* DVAR */
  19766. 0x0030: 2, /* TEXT */
  19767. 0x0035: 1, /* GOTO */
  19768. 0x003D: 3, /* MIRR */
  19769. 0x003F: 0, /* RAND */
  19770. 0x0041: 3, /* DATE */
  19771. 0x0042: 3, /* TIME */
  19772. 0x0043: 1, /* DAY */
  19773. 0x0044: 1, /* MONTH */
  19774. 0x0045: 1, /* YEAR */
  19775. 0x0046: 1, /* WEEKDAY */
  19776. 0x0047: 1, /* HOUR */
  19777. 0x0048: 1, /* MINUTE */
  19778. 0x0049: 1, /* SECOND */
  19779. 0x004A: 0, /* NOW */
  19780. 0x004B: 1, /* AREAS */
  19781. 0x004C: 1, /* ROWS */
  19782. 0x004D: 1, /* COLUMNS */
  19783. 0x004F: 2, /* ABSREF */
  19784. 0x0050: 2, /* RELREF */
  19785. 0x0053: 1, /* TRANSPOSE */
  19786. 0x0055: 0, /* STEP */
  19787. 0x0056: 1, /* TYPE */
  19788. 0x0059: 0, /* CALLER */
  19789. 0x005A: 1, /* DEREF */
  19790. 0x005E: 0, /* ACTIVE.CELL */
  19791. 0x005F: 0, /* SELECTION */
  19792. 0x0061: 2, /* ATAN2 */
  19793. 0x0062: 1, /* ASIN */
  19794. 0x0063: 1, /* ACOS */
  19795. 0x0065: 3, /* HLOOKUP */
  19796. 0x0066: 3, /* VLOOKUP */
  19797. 0x0069: 1, /* ISREF */
  19798. 0x006A: 1, /* GET.FORMULA */
  19799. 0x006C: 2, /* SET.VALUE */
  19800. 0x006F: 1, /* CHAR */
  19801. 0x0070: 1, /* LOWER */
  19802. 0x0071: 1, /* UPPER */
  19803. 0x0072: 1, /* PROPER */
  19804. 0x0075: 2, /* EXACT */
  19805. 0x0076: 1, /* TRIM */
  19806. 0x0077: 4, /* REPLACE */
  19807. 0x0079: 1, /* CODE */
  19808. 0x007E: 1, /* ISERR */
  19809. 0x007F: 1, /* ISTEXT */
  19810. 0x0080: 1, /* ISNUMBER */
  19811. 0x0081: 1, /* ISBLANK */
  19812. 0x0082: 1, /* T */
  19813. 0x0083: 1, /* N */
  19814. 0x0085: 1, /* FCLOSE */
  19815. 0x0086: 1, /* FSIZE */
  19816. 0x0087: 1, /* FREADLN */
  19817. 0x0088: 2, /* FREAD */
  19818. 0x0089: 2, /* FWRITELN */
  19819. 0x008A: 2, /* FWRITE */
  19820. 0x008C: 1, /* DATEVALUE */
  19821. 0x008D: 1, /* TIMEVALUE */
  19822. 0x008E: 3, /* SLN */
  19823. 0x008F: 4, /* SYD */
  19824. 0x0090: 4, /* DDB */
  19825. 0x00A1: 1, /* DIALOG.BOX */
  19826. 0x00A2: 1, /* CLEAN */
  19827. 0x00A3: 1, /* MDETERM */
  19828. 0x00A4: 1, /* MINVERSE */
  19829. 0x00A5: 2, /* MMULT */
  19830. 0x00AC: 1, /* WHILE */
  19831. 0x00AF: 2, /* INITIATE */
  19832. 0x00B0: 2, /* REQUEST */
  19833. 0x00B1: 3, /* POKE */
  19834. 0x00B2: 2, /* EXECUTE */
  19835. 0x00B3: 1, /* TERMINATE */
  19836. 0x00B8: 1, /* FACT */
  19837. 0x00BA: 1, /* GET.WORKSPACE */
  19838. 0x00BD: 3, /* DPRODUCT */
  19839. 0x00BE: 1, /* ISNONTEXT */
  19840. 0x00C3: 3, /* DSTDEVP */
  19841. 0x00C4: 3, /* DVARP */
  19842. 0x00C5: 1, /* TRUNC */
  19843. 0x00C6: 1, /* ISLOGICAL */
  19844. 0x00C7: 3, /* DCOUNTA */
  19845. 0x00C9: 1, /* UNREGISTER */
  19846. 0x00CF: 4, /* REPLACEB */
  19847. 0x00D2: 3, /* MIDB */
  19848. 0x00D3: 1, /* LENB */
  19849. 0x00D4: 2, /* ROUNDUP */
  19850. 0x00D5: 2, /* ROUNDDOWN */
  19851. 0x00D6: 1, /* ASC */
  19852. 0x00D7: 1, /* DBCS */
  19853. 0x00E1: 0, /* END.IF */
  19854. 0x00E5: 1, /* SINH */
  19855. 0x00E6: 1, /* COSH */
  19856. 0x00E7: 1, /* TANH */
  19857. 0x00E8: 1, /* ASINH */
  19858. 0x00E9: 1, /* ACOSH */
  19859. 0x00EA: 1, /* ATANH */
  19860. 0x00EB: 3, /* DGET */
  19861. 0x00F4: 1, /* INFO */
  19862. 0x00F7: 4, /* DB */
  19863. 0x00FC: 2, /* FREQUENCY */
  19864. 0x0101: 1, /* EVALUATE */
  19865. 0x0105: 1, /* ERROR.TYPE */
  19866. 0x010F: 1, /* GAMMALN */
  19867. 0x0111: 4, /* BINOMDIST */
  19868. 0x0112: 2, /* CHIDIST */
  19869. 0x0113: 2, /* CHIINV */
  19870. 0x0114: 2, /* COMBIN */
  19871. 0x0115: 3, /* CONFIDENCE */
  19872. 0x0116: 3, /* CRITBINOM */
  19873. 0x0117: 1, /* EVEN */
  19874. 0x0118: 3, /* EXPONDIST */
  19875. 0x0119: 3, /* FDIST */
  19876. 0x011A: 3, /* FINV */
  19877. 0x011B: 1, /* FISHER */
  19878. 0x011C: 1, /* FISHERINV */
  19879. 0x011D: 2, /* FLOOR */
  19880. 0x011E: 4, /* GAMMADIST */
  19881. 0x011F: 3, /* GAMMAINV */
  19882. 0x0120: 2, /* CEILING */
  19883. 0x0121: 4, /* HYPGEOMDIST */
  19884. 0x0122: 3, /* LOGNORMDIST */
  19885. 0x0123: 3, /* LOGINV */
  19886. 0x0124: 3, /* NEGBINOMDIST */
  19887. 0x0125: 4, /* NORMDIST */
  19888. 0x0126: 1, /* NORMSDIST */
  19889. 0x0127: 3, /* NORMINV */
  19890. 0x0128: 1, /* NORMSINV */
  19891. 0x0129: 3, /* STANDARDIZE */
  19892. 0x012A: 1, /* ODD */
  19893. 0x012B: 2, /* PERMUT */
  19894. 0x012C: 3, /* POISSON */
  19895. 0x012D: 3, /* TDIST */
  19896. 0x012E: 4, /* WEIBULL */
  19897. 0x012F: 2, /* SUMXMY2 */
  19898. 0x0130: 2, /* SUMX2MY2 */
  19899. 0x0131: 2, /* SUMX2PY2 */
  19900. 0x0132: 2, /* CHITEST */
  19901. 0x0133: 2, /* CORREL */
  19902. 0x0134: 2, /* COVAR */
  19903. 0x0135: 3, /* FORECAST */
  19904. 0x0136: 2, /* FTEST */
  19905. 0x0137: 2, /* INTERCEPT */
  19906. 0x0138: 2, /* PEARSON */
  19907. 0x0139: 2, /* RSQ */
  19908. 0x013A: 2, /* STEYX */
  19909. 0x013B: 2, /* SLOPE */
  19910. 0x013C: 4, /* TTEST */
  19911. 0x0145: 2, /* LARGE */
  19912. 0x0146: 2, /* SMALL */
  19913. 0x0147: 2, /* QUARTILE */
  19914. 0x0148: 2, /* PERCENTILE */
  19915. 0x014B: 2, /* TRIMMEAN */
  19916. 0x014C: 2, /* TINV */
  19917. 0x0151: 2, /* POWER */
  19918. 0x0156: 1, /* RADIANS */
  19919. 0x0157: 1, /* DEGREES */
  19920. 0x015A: 2, /* COUNTIF */
  19921. 0x015B: 1, /* COUNTBLANK */
  19922. 0x015E: 4, /* ISPMT */
  19923. 0x015F: 3, /* DATEDIF */
  19924. 0x0160: 1, /* DATESTRING */
  19925. 0x0161: 2, /* NUMBERSTRING */
  19926. 0x0168: 1, /* PHONETIC */
  19927. 0x0170: 1, /* BAHTTEXT */
  19928. 0x0171: 1, /* THAIDAYOFWEEK */
  19929. 0x0172: 1, /* THAIDIGIT */
  19930. 0x0173: 1, /* THAIMONTHOFYEAR */
  19931. 0x0174: 1, /* THAINUMSOUND */
  19932. 0x0175: 1, /* THAINUMSTRING */
  19933. 0x0176: 1, /* THAISTRINGLENGTH */
  19934. 0x0177: 1, /* ISTHAIDIGIT */
  19935. 0x0178: 1, /* ROUNDBAHTDOWN */
  19936. 0x0179: 1, /* ROUNDBAHTUP */
  19937. 0x017A: 1, /* THAIYEAR */
  19938. 0x017E: 3, /* CUBEMEMBERPROPERTY */
  19939. 0x0181: 1, /* HEX2DEC */
  19940. 0x0188: 1, /* OCT2DEC */
  19941. 0x0189: 1, /* BIN2DEC */
  19942. 0x018C: 2, /* IMSUB */
  19943. 0x018D: 2, /* IMDIV */
  19944. 0x018E: 2, /* IMPOWER */
  19945. 0x018F: 1, /* IMABS */
  19946. 0x0190: 1, /* IMSQRT */
  19947. 0x0191: 1, /* IMLN */
  19948. 0x0192: 1, /* IMLOG2 */
  19949. 0x0193: 1, /* IMLOG10 */
  19950. 0x0194: 1, /* IMSIN */
  19951. 0x0195: 1, /* IMCOS */
  19952. 0x0196: 1, /* IMEXP */
  19953. 0x0197: 1, /* IMARGUMENT */
  19954. 0x0198: 1, /* IMCONJUGATE */
  19955. 0x0199: 1, /* IMAGINARY */
  19956. 0x019A: 1, /* IMREAL */
  19957. 0x019E: 4, /* SERIESSUM */
  19958. 0x019F: 1, /* FACTDOUBLE */
  19959. 0x01A0: 1, /* SQRTPI */
  19960. 0x01A1: 2, /* QUOTIENT */
  19961. 0x01A4: 1, /* ISEVEN */
  19962. 0x01A5: 1, /* ISODD */
  19963. 0x01A6: 2, /* MROUND */
  19964. 0x01A8: 1, /* ERFC */
  19965. 0x01A9: 2, /* BESSELJ */
  19966. 0x01AA: 2, /* BESSELK */
  19967. 0x01AB: 2, /* BESSELY */
  19968. 0x01AC: 2, /* BESSELI */
  19969. 0x01AE: 3, /* XNPV */
  19970. 0x01B6: 3, /* TBILLEQ */
  19971. 0x01B7: 3, /* TBILLPRICE */
  19972. 0x01B8: 3, /* TBILLYIELD */
  19973. 0x01BB: 2, /* DOLLARDE */
  19974. 0x01BC: 2, /* DOLLARFR */
  19975. 0x01BD: 2, /* NOMINAL */
  19976. 0x01BE: 2, /* EFFECT */
  19977. 0x01BF: 6, /* CUMPRINC */
  19978. 0x01C0: 6, /* CUMIPMT */
  19979. 0x01C1: 2, /* EDATE */
  19980. 0x01C2: 2, /* EOMONTH */
  19981. 0x01D0: 2, /* RANDBETWEEN */
  19982. 0x01D4: 3, /* CONVERT */
  19983. 0x01DC: 2, /* FVSCHEDULE */
  19984. 0x01DF: 1, /* CUBESETCOUNT */
  19985. 0x01E0: 2, /* IFERROR */
  19986. 0xFFFF: 0
  19987. };
  19988. /* [MS-XLSX2] 2.2.3 Functions */
  19989. /* [MS-XLSB] 2.5.97.10 Ftab */
  19990. var XLSXFutureFunctions = {
  19991. "_xlfn.ACOT": "ACOT",
  19992. "_xlfn.ACOTH": "ACOTH",
  19993. "_xlfn.AGGREGATE": "AGGREGATE",
  19994. "_xlfn.ARABIC": "ARABIC",
  19995. "_xlfn.AVERAGEIF": "AVERAGEIF",
  19996. "_xlfn.AVERAGEIFS": "AVERAGEIFS",
  19997. "_xlfn.BASE": "BASE",
  19998. "_xlfn.BETA.DIST": "BETA.DIST",
  19999. "_xlfn.BETA.INV": "BETA.INV",
  20000. "_xlfn.BINOM.DIST": "BINOM.DIST",
  20001. "_xlfn.BINOM.DIST.RANGE": "BINOM.DIST.RANGE",
  20002. "_xlfn.BINOM.INV": "BINOM.INV",
  20003. "_xlfn.BITAND": "BITAND",
  20004. "_xlfn.BITLSHIFT": "BITLSHIFT",
  20005. "_xlfn.BITOR": "BITOR",
  20006. "_xlfn.BITRSHIFT": "BITRSHIFT",
  20007. "_xlfn.BITXOR": "BITXOR",
  20008. "_xlfn.CEILING.MATH": "CEILING.MATH",
  20009. "_xlfn.CEILING.PRECISE": "CEILING.PRECISE",
  20010. "_xlfn.CHISQ.DIST": "CHISQ.DIST",
  20011. "_xlfn.CHISQ.DIST.RT": "CHISQ.DIST.RT",
  20012. "_xlfn.CHISQ.INV": "CHISQ.INV",
  20013. "_xlfn.CHISQ.INV.RT": "CHISQ.INV.RT",
  20014. "_xlfn.CHISQ.TEST": "CHISQ.TEST",
  20015. "_xlfn.COMBINA": "COMBINA",
  20016. "_xlfn.CONCAT": "CONCAT",
  20017. "_xlfn.CONFIDENCE.NORM": "CONFIDENCE.NORM",
  20018. "_xlfn.CONFIDENCE.T": "CONFIDENCE.T",
  20019. "_xlfn.COT": "COT",
  20020. "_xlfn.COTH": "COTH",
  20021. "_xlfn.COUNTIFS": "COUNTIFS",
  20022. "_xlfn.COVARIANCE.P": "COVARIANCE.P",
  20023. "_xlfn.COVARIANCE.S": "COVARIANCE.S",
  20024. "_xlfn.CSC": "CSC",
  20025. "_xlfn.CSCH": "CSCH",
  20026. "_xlfn.DAYS": "DAYS",
  20027. "_xlfn.DECIMAL": "DECIMAL",
  20028. "_xlfn.ECMA.CEILING": "ECMA.CEILING",
  20029. "_xlfn.ERF.PRECISE": "ERF.PRECISE",
  20030. "_xlfn.ERFC.PRECISE": "ERFC.PRECISE",
  20031. "_xlfn.EXPON.DIST": "EXPON.DIST",
  20032. "_xlfn.F.DIST": "F.DIST",
  20033. "_xlfn.F.DIST.RT": "F.DIST.RT",
  20034. "_xlfn.F.INV": "F.INV",
  20035. "_xlfn.F.INV.RT": "F.INV.RT",
  20036. "_xlfn.F.TEST": "F.TEST",
  20037. "_xlfn.FILTERXML": "FILTERXML",
  20038. "_xlfn.FLOOR.MATH": "FLOOR.MATH",
  20039. "_xlfn.FLOOR.PRECISE": "FLOOR.PRECISE",
  20040. "_xlfn.FORECAST.ETS": "FORECAST.ETS",
  20041. "_xlfn.FORECAST.ETS.CONFINT": "FORECAST.ETS.CONFINT",
  20042. "_xlfn.FORECAST.ETS.SEASONALITY": "FORECAST.ETS.SEASONALITY",
  20043. "_xlfn.FORECAST.ETS.STAT": "FORECAST.ETS.STAT",
  20044. "_xlfn.FORECAST.LINEAR": "FORECAST.LINEAR",
  20045. "_xlfn.FORMULATEXT": "FORMULATEXT",
  20046. "_xlfn.GAMMA": "GAMMA",
  20047. "_xlfn.GAMMA.DIST": "GAMMA.DIST",
  20048. "_xlfn.GAMMA.INV": "GAMMA.INV",
  20049. "_xlfn.GAMMALN.PRECISE": "GAMMALN.PRECISE",
  20050. "_xlfn.GAUSS": "GAUSS",
  20051. "_xlfn.HYPGEOM.DIST": "HYPGEOM.DIST",
  20052. "_xlfn.IFERROR": "IFERROR",
  20053. "_xlfn.IFNA": "IFNA",
  20054. "_xlfn.IFS": "IFS",
  20055. "_xlfn.IMCOSH": "IMCOSH",
  20056. "_xlfn.IMCOT": "IMCOT",
  20057. "_xlfn.IMCSC": "IMCSC",
  20058. "_xlfn.IMCSCH": "IMCSCH",
  20059. "_xlfn.IMSEC": "IMSEC",
  20060. "_xlfn.IMSECH": "IMSECH",
  20061. "_xlfn.IMSINH": "IMSINH",
  20062. "_xlfn.IMTAN": "IMTAN",
  20063. "_xlfn.ISFORMULA": "ISFORMULA",
  20064. "_xlfn.ISO.CEILING": "ISO.CEILING",
  20065. "_xlfn.ISOWEEKNUM": "ISOWEEKNUM",
  20066. "_xlfn.LOGNORM.DIST": "LOGNORM.DIST",
  20067. "_xlfn.LOGNORM.INV": "LOGNORM.INV",
  20068. "_xlfn.MAXIFS": "MAXIFS",
  20069. "_xlfn.MINIFS": "MINIFS",
  20070. "_xlfn.MODE.MULT": "MODE.MULT",
  20071. "_xlfn.MODE.SNGL": "MODE.SNGL",
  20072. "_xlfn.MUNIT": "MUNIT",
  20073. "_xlfn.NEGBINOM.DIST": "NEGBINOM.DIST",
  20074. "_xlfn.NETWORKDAYS.INTL": "NETWORKDAYS.INTL",
  20075. "_xlfn.NIGBINOM": "NIGBINOM",
  20076. "_xlfn.NORM.DIST": "NORM.DIST",
  20077. "_xlfn.NORM.INV": "NORM.INV",
  20078. "_xlfn.NORM.S.DIST": "NORM.S.DIST",
  20079. "_xlfn.NORM.S.INV": "NORM.S.INV",
  20080. "_xlfn.NUMBERVALUE": "NUMBERVALUE",
  20081. "_xlfn.PDURATION": "PDURATION",
  20082. "_xlfn.PERCENTILE.EXC": "PERCENTILE.EXC",
  20083. "_xlfn.PERCENTILE.INC": "PERCENTILE.INC",
  20084. "_xlfn.PERCENTRANK.EXC": "PERCENTRANK.EXC",
  20085. "_xlfn.PERCENTRANK.INC": "PERCENTRANK.INC",
  20086. "_xlfn.PERMUTATIONA": "PERMUTATIONA",
  20087. "_xlfn.PHI": "PHI",
  20088. "_xlfn.POISSON.DIST": "POISSON.DIST",
  20089. "_xlfn.QUARTILE.EXC": "QUARTILE.EXC",
  20090. "_xlfn.QUARTILE.INC": "QUARTILE.INC",
  20091. "_xlfn.QUERYSTRING": "QUERYSTRING",
  20092. "_xlfn.RANK.AVG": "RANK.AVG",
  20093. "_xlfn.RANK.EQ": "RANK.EQ",
  20094. "_xlfn.RRI": "RRI",
  20095. "_xlfn.SEC": "SEC",
  20096. "_xlfn.SECH": "SECH",
  20097. "_xlfn.SHEET": "SHEET",
  20098. "_xlfn.SHEETS": "SHEETS",
  20099. "_xlfn.SKEW.P": "SKEW.P",
  20100. "_xlfn.STDEV.P": "STDEV.P",
  20101. "_xlfn.STDEV.S": "STDEV.S",
  20102. "_xlfn.SUMIFS": "SUMIFS",
  20103. "_xlfn.SWITCH": "SWITCH",
  20104. "_xlfn.T.DIST": "T.DIST",
  20105. "_xlfn.T.DIST.2T": "T.DIST.2T",
  20106. "_xlfn.T.DIST.RT": "T.DIST.RT",
  20107. "_xlfn.T.INV": "T.INV",
  20108. "_xlfn.T.INV.2T": "T.INV.2T",
  20109. "_xlfn.T.TEST": "T.TEST",
  20110. "_xlfn.TEXTJOIN": "TEXTJOIN",
  20111. "_xlfn.UNICHAR": "UNICHAR",
  20112. "_xlfn.UNICODE": "UNICODE",
  20113. "_xlfn.VAR.P": "VAR.P",
  20114. "_xlfn.VAR.S": "VAR.S",
  20115. "_xlfn.WEBSERVICE": "WEBSERVICE",
  20116. "_xlfn.WEIBULL.DIST": "WEIBULL.DIST",
  20117. "_xlfn.WORKDAY.INTL": "WORKDAY.INTL",
  20118. "_xlfn.XOR": "XOR",
  20119. "_xlfn.Z.TEST": "Z.TEST"
  20120. };
  20121. /* Part 3 TODO: actually parse formulae */
  20122. function ods_to_csf_formula(f) {
  20123. if(f.slice(0,3) == "of:") f = f.slice(3);
  20124. /* 5.2 Basic Expressions */
  20125. if(f.charCodeAt(0) == 61) {
  20126. f = f.slice(1);
  20127. if(f.charCodeAt(0) == 61) f = f.slice(1);
  20128. }
  20129. f = f.replace(/COM\.MICROSOFT\./g, "");
  20130. /* Part 3 Section 5.8 References */
  20131. f = f.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) { return $1.replace(/\./g,""); });
  20132. /* TODO: something other than this */
  20133. f = f.replace(/\[.(#[A-Z]*[?!])\]/g, "$1");
  20134. return f.replace(/[;~]/g,",").replace(/\|/g,";");
  20135. }
  20136. function csf_to_ods_formula(f) {
  20137. var o = "of:=" + f.replace(crefregex, "$1[.$2$3$4$5]").replace(/\]:\[/g,":");
  20138. /* TODO: something other than this */
  20139. return o.replace(/;/g, "|").replace(/,/g,";");
  20140. }
  20141. function ods_to_csf_3D(r) {
  20142. var a = r.split(":");
  20143. var s = a[0].split(".")[0];
  20144. return [s, a[0].split(".")[1] + (a.length > 1 ? (":" + (a[1].split(".")[1] || a[1].split(".")[0])) : "")];
  20145. }
  20146. function csf_to_ods_3D(r) {
  20147. return r.replace(/\./,"!");
  20148. }
  20149. var strs = {}; // shared strings
  20150. var _ssfopts = {}; // spreadsheet formatting options
  20151. RELS.WS = [
  20152. "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
  20153. "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet"
  20154. ];
  20155. /*global Map */
  20156. var browser_has_Map = typeof Map !== 'undefined';
  20157. function get_sst_id(sst, str, rev) {
  20158. var i = 0, len = sst.length;
  20159. if(rev) {
  20160. if(browser_has_Map ? rev.has(str) : Object.prototype.hasOwnProperty.call(rev, str)) {
  20161. var revarr = browser_has_Map ? rev.get(str) : rev[str];
  20162. for(; i < revarr.length; ++i) {
  20163. if(sst[revarr[i]].t === str) { sst.Count ++; return revarr[i]; }
  20164. }
  20165. }
  20166. } else for(; i < len; ++i) {
  20167. if(sst[i].t === str) { sst.Count ++; return i; }
  20168. }
  20169. sst[len] = ({t:str}); sst.Count ++; sst.Unique ++;
  20170. if(rev) {
  20171. if(browser_has_Map) {
  20172. if(!rev.has(str)) rev.set(str, []);
  20173. rev.get(str).push(len);
  20174. } else {
  20175. if(!Object.prototype.hasOwnProperty.call(rev, str)) rev[str] = [];
  20176. rev[str].push(len);
  20177. }
  20178. }
  20179. return len;
  20180. }
  20181. function col_obj_w(C, col) {
  20182. var p = ({min:C+1,max:C+1});
  20183. /* wch (chars), wpx (pixels) */
  20184. var wch = -1;
  20185. if(col.MDW) MDW = col.MDW;
  20186. if(col.width != null) p.customWidth = 1;
  20187. else if(col.wpx != null) wch = px2char(col.wpx);
  20188. else if(col.wch != null) wch = col.wch;
  20189. if(wch > -1) { p.width = char2width(wch); p.customWidth = 1; }
  20190. else if(col.width != null) p.width = col.width;
  20191. if(col.hidden) p.hidden = true;
  20192. return p;
  20193. }
  20194. function default_margins(margins, mode) {
  20195. if(!margins) return;
  20196. var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3];
  20197. if(mode == 'xlml') defs = [1, 1, 1, 1, 0.5, 0.5];
  20198. if(margins.left == null) margins.left = defs[0];
  20199. if(margins.right == null) margins.right = defs[1];
  20200. if(margins.top == null) margins.top = defs[2];
  20201. if(margins.bottom == null) margins.bottom = defs[3];
  20202. if(margins.header == null) margins.header = defs[4];
  20203. if(margins.footer == null) margins.footer = defs[5];
  20204. }
  20205. function get_cell_style(styles, cell, opts) {
  20206. var z = opts.revssf[cell.z != null ? cell.z : "General"];
  20207. var i = 0x3c, len = styles.length;
  20208. if(z == null && opts.ssf) {
  20209. for(; i < 0x188; ++i) if(opts.ssf[i] == null) {
  20210. SSF.load(cell.z, i);
  20211. // $FlowIgnore
  20212. opts.ssf[i] = cell.z;
  20213. opts.revssf[cell.z] = z = i;
  20214. break;
  20215. }
  20216. }
  20217. for(i = 0; i != len; ++i) if(styles[i].numFmtId === z) return i;
  20218. styles[len] = {
  20219. numFmtId:z,
  20220. fontId:0,
  20221. fillId:0,
  20222. borderId:0,
  20223. xfId:0,
  20224. applyNumberFormat:1
  20225. };
  20226. return len;
  20227. }
  20228. function safe_format(p, fmtid, fillid, opts, themes, styles) {
  20229. try {
  20230. if(opts.cellNF) p.z = SSF._table[fmtid];
  20231. } catch(e) { if(opts.WTF) throw e; }
  20232. if(p.t === 'z') return;
  20233. if(p.t === 'd' && typeof p.v === 'string') p.v = parseDate(p.v);
  20234. if(!opts || opts.cellText !== false) try {
  20235. if(SSF._table[fmtid] == null) SSF.load(SSFImplicit[fmtid] || "General", fmtid);
  20236. if(p.t === 'e') p.w = p.w || BErr[p.v];
  20237. else if(fmtid === 0) {
  20238. if(p.t === 'n') {
  20239. if((p.v|0) === p.v) p.w = SSF._general_int(p.v);
  20240. else p.w = SSF._general_num(p.v);
  20241. }
  20242. else if(p.t === 'd') {
  20243. var dd = datenum(p.v);
  20244. if((dd|0) === dd) p.w = SSF._general_int(dd);
  20245. else p.w = SSF._general_num(dd);
  20246. }
  20247. else if(p.v === undefined) return "";
  20248. else p.w = SSF._general(p.v,_ssfopts);
  20249. }
  20250. else if(p.t === 'd') p.w = SSF.format(fmtid,datenum(p.v),_ssfopts);
  20251. else p.w = SSF.format(fmtid,p.v,_ssfopts);
  20252. } catch(e) { if(opts.WTF) throw e; }
  20253. if(!opts.cellStyles) return;
  20254. if(fillid != null) try {
  20255. p.s = styles.Fills[fillid];
  20256. if (p.s.fgColor && p.s.fgColor.theme && !p.s.fgColor.rgb) {
  20257. p.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.fgColor.theme].rgb, p.s.fgColor.tint || 0);
  20258. if(opts.WTF) p.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p.s.fgColor.theme].rgb;
  20259. }
  20260. if (p.s.bgColor && p.s.bgColor.theme) {
  20261. p.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p.s.bgColor.theme].rgb, p.s.bgColor.tint || 0);
  20262. if(opts.WTF) p.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p.s.bgColor.theme].rgb;
  20263. }
  20264. } catch(e) { if(opts.WTF && styles.Fills) throw e; }
  20265. }
  20266. function check_ws(ws, sname, i) {
  20267. if(ws && ws['!ref']) {
  20268. var range = safe_decode_range(ws['!ref']);
  20269. if(range.e.c < range.s.c || range.e.r < range.s.r) throw new Error("Bad range (" + i + "): " + ws['!ref']);
  20270. }
  20271. }
  20272. function parse_ws_xml_dim(ws, s) {
  20273. var d = safe_decode_range(s);
  20274. if(d.s.r<=d.e.r && d.s.c<=d.e.c && d.s.r>=0 && d.s.c>=0) ws["!ref"] = encode_range(d);
  20275. }
  20276. var mergecregex = /<(?:\w:)?mergeCell ref="[A-Z0-9:]+"\s*[\/]?>/g;
  20277. var sheetdataregex = /<(?:\w+:)?sheetData[^>]*>([\s\S]*)<\/(?:\w+:)?sheetData>/;
  20278. var hlinkregex = /<(?:\w:)?hyperlink [^>]*>/mg;
  20279. var dimregex = /"(\w*:\w*)"/;
  20280. var colregex = /<(?:\w:)?col\b[^>]*[\/]?>/g;
  20281. var afregex = /<(?:\w:)?autoFilter[^>]*([\/]|>([\s\S]*)<\/(?:\w:)?autoFilter)>/g;
  20282. var marginregex= /<(?:\w:)?pageMargins[^>]*\/>/g;
  20283. var sheetprregex = /<(?:\w:)?sheetPr\b(?:[^>a-z][^>]*)?\/>/;
  20284. var svsregex = /<(?:\w:)?sheetViews[^>]*(?:[\/]|>([\s\S]*)<\/(?:\w:)?sheetViews)>/;
  20285. /* 18.3 Worksheets */
  20286. function parse_ws_xml(data, opts, idx, rels, wb, themes, styles) {
  20287. if(!data) return data;
  20288. if(!rels) rels = {'!id':{}};
  20289. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  20290. /* 18.3.1.99 worksheet CT_Worksheet */
  20291. var s = opts.dense ? ([]) : ({});
  20292. var refguess = ({s: {r:2000000, c:2000000}, e: {r:0, c:0} });
  20293. var data1 = "", data2 = "";
  20294. var mtch = data.match(sheetdataregex);
  20295. if(mtch) {
  20296. data1 = data.slice(0, mtch.index);
  20297. data2 = data.slice(mtch.index + mtch[0].length);
  20298. } else data1 = data2 = data;
  20299. /* 18.3.1.82 sheetPr CT_SheetPr */
  20300. var sheetPr = data1.match(sheetprregex);
  20301. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  20302. /* 18.3.1.35 dimension CT_SheetDimension */
  20303. var ridx = (data1.match(/<(?:\w*:)?dimension/)||{index:-1}).index;
  20304. if(ridx > 0) {
  20305. var ref = data1.slice(ridx,ridx+50).match(dimregex);
  20306. if(ref) parse_ws_xml_dim(s, ref[1]);
  20307. }
  20308. /* 18.3.1.88 sheetViews CT_SheetViews */
  20309. var svs = data1.match(svsregex);
  20310. if(svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb);
  20311. /* 18.3.1.17 cols CT_Cols */
  20312. var columns = [];
  20313. if(opts.cellStyles) {
  20314. /* 18.3.1.13 col CT_Col */
  20315. var cols = data1.match(colregex);
  20316. if(cols) parse_ws_xml_cols(columns, cols);
  20317. }
  20318. /* 18.3.1.80 sheetData CT_SheetData ? */
  20319. if(mtch) parse_ws_xml_data(mtch[1], s, opts, refguess, themes, styles);
  20320. /* 18.3.1.2 autoFilter CT_AutoFilter */
  20321. var afilter = data2.match(afregex);
  20322. if(afilter) s['!autofilter'] = parse_ws_xml_autofilter(afilter[0]);
  20323. /* 18.3.1.55 mergeCells CT_MergeCells */
  20324. var merges = [];
  20325. var _merge = data2.match(mergecregex);
  20326. if(_merge) for(ridx = 0; ridx != _merge.length; ++ridx)
  20327. merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("\"")+1));
  20328. /* 18.3.1.48 hyperlinks CT_Hyperlinks */
  20329. var hlink = data2.match(hlinkregex);
  20330. if(hlink) parse_ws_xml_hlinks(s, hlink, rels);
  20331. /* 18.3.1.62 pageMargins CT_PageMargins */
  20332. var margins = data2.match(marginregex);
  20333. if(margins) s['!margins'] = parse_ws_xml_margins(parsexmltag(margins[0]));
  20334. if(!s["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s["!ref"] = encode_range(refguess);
  20335. if(opts.sheetRows > 0 && s["!ref"]) {
  20336. var tmpref = safe_decode_range(s["!ref"]);
  20337. if(opts.sheetRows <= +tmpref.e.r) {
  20338. tmpref.e.r = opts.sheetRows - 1;
  20339. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  20340. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  20341. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  20342. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  20343. s["!fullref"] = s["!ref"];
  20344. s["!ref"] = encode_range(tmpref);
  20345. }
  20346. }
  20347. if(columns.length > 0) s["!cols"] = columns;
  20348. if(merges.length > 0) s["!merges"] = merges;
  20349. return s;
  20350. }
  20351. function write_ws_xml_merges(merges) {
  20352. if(merges.length === 0) return "";
  20353. var o = '<mergeCells count="' + merges.length + '">';
  20354. for(var i = 0; i != merges.length; ++i) o += '<mergeCell ref="' + encode_range(merges[i]) + '"/>';
  20355. return o + '</mergeCells>';
  20356. }
  20357. /* 18.3.1.82-3 sheetPr CT_ChartsheetPr / CT_SheetPr */
  20358. function parse_ws_xml_sheetpr(sheetPr, s, wb, idx) {
  20359. var data = parsexmltag(sheetPr);
  20360. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  20361. if(data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName));
  20362. }
  20363. function write_ws_xml_sheetpr(ws, wb, idx, opts, o) {
  20364. var needed = false;
  20365. var props = {}, payload = null;
  20366. if(opts.bookType !== 'xlsx' && wb.vbaraw) {
  20367. var cname = wb.SheetNames[idx];
  20368. try { if(wb.Workbook) cname = wb.Workbook.Sheets[idx].CodeName || cname; } catch(e) {}
  20369. needed = true;
  20370. props.codeName = utf8write(escapexml(cname));
  20371. }
  20372. if(ws && ws["!outline"]) {
  20373. var outlineprops = {summaryBelow:1, summaryRight:1};
  20374. if(ws["!outline"].above) outlineprops.summaryBelow = 0;
  20375. if(ws["!outline"].left) outlineprops.summaryRight = 0;
  20376. payload = (payload||"") + writextag('outlinePr', null, outlineprops);
  20377. }
  20378. if(!needed && !payload) return;
  20379. o[o.length] = (writextag('sheetPr', payload, props));
  20380. }
  20381. /* 18.3.1.85 sheetProtection CT_SheetProtection */
  20382. var sheetprot_deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
  20383. var sheetprot_deftrue = [
  20384. "formatColumns", "formatRows", "formatCells",
  20385. "insertColumns", "insertRows", "insertHyperlinks",
  20386. "deleteColumns", "deleteRows",
  20387. "sort", "autoFilter", "pivotTables"
  20388. ];
  20389. function write_ws_xml_protection(sp) {
  20390. // algorithmName, hashValue, saltValue, spinCount
  20391. var o = ({sheet:1});
  20392. sheetprot_deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
  20393. sheetprot_deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
  20394. /* TODO: algorithm */
  20395. if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
  20396. return writextag('sheetProtection', null, o);
  20397. }
  20398. function parse_ws_xml_hlinks(s, data, rels) {
  20399. var dense = Array.isArray(s);
  20400. for(var i = 0; i != data.length; ++i) {
  20401. var val = parsexmltag(utf8read(data[i]), true);
  20402. if(!val.ref) return;
  20403. var rel = ((rels || {})['!id']||[])[val.id];
  20404. if(rel) {
  20405. val.Target = rel.Target;
  20406. if(val.location) val.Target += "#"+val.location;
  20407. } else {
  20408. val.Target = "#" + val.location;
  20409. rel = {Target: val.Target, TargetMode: 'Internal'};
  20410. }
  20411. val.Rel = rel;
  20412. if(val.tooltip) { val.Tooltip = val.tooltip; delete val.tooltip; }
  20413. var rng = safe_decode_range(val.ref);
  20414. for(var R=rng.s.r;R<=rng.e.r;++R) for(var C=rng.s.c;C<=rng.e.c;++C) {
  20415. var addr = encode_cell({c:C,r:R});
  20416. if(dense) {
  20417. if(!s[R]) s[R] = [];
  20418. if(!s[R][C]) s[R][C] = {t:"z",v:undefined};
  20419. s[R][C].l = val;
  20420. } else {
  20421. if(!s[addr]) s[addr] = {t:"z",v:undefined};
  20422. s[addr].l = val;
  20423. }
  20424. }
  20425. }
  20426. }
  20427. function parse_ws_xml_margins(margin) {
  20428. var o = {};
  20429. ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k) {
  20430. if(margin[k]) o[k] = parseFloat(margin[k]);
  20431. });
  20432. return o;
  20433. }
  20434. function write_ws_xml_margins(margin) {
  20435. default_margins(margin);
  20436. return writextag('pageMargins', null, margin);
  20437. }
  20438. function parse_ws_xml_cols(columns, cols) {
  20439. var seencol = false;
  20440. for(var coli = 0; coli != cols.length; ++coli) {
  20441. var coll = parsexmltag(cols[coli], true);
  20442. if(coll.hidden) coll.hidden = parsexmlbool(coll.hidden);
  20443. var colm=parseInt(coll.min, 10)-1, colM=parseInt(coll.max,10)-1;
  20444. delete coll.min; delete coll.max; coll.width = +coll.width;
  20445. if(!seencol && coll.width) { seencol = true; find_mdw_colw(coll.width); }
  20446. process_col(coll);
  20447. while(colm <= colM) columns[colm++] = dup(coll);
  20448. }
  20449. }
  20450. function write_ws_xml_cols(ws, cols) {
  20451. var o = ["<cols>"], col;
  20452. for(var i = 0; i != cols.length; ++i) {
  20453. if(!(col = cols[i])) continue;
  20454. o[o.length] = (writextag('col', null, col_obj_w(i, col)));
  20455. }
  20456. o[o.length] = "</cols>";
  20457. return o.join("");
  20458. }
  20459. function parse_ws_xml_autofilter(data) {
  20460. var o = { ref: (data.match(/ref="([^"]*)"/)||[])[1]};
  20461. return o;
  20462. }
  20463. function write_ws_xml_autofilter(data, ws, wb, idx) {
  20464. var ref = typeof data.ref == "string" ? data.ref : encode_range(data.ref);
  20465. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  20466. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  20467. var names = wb.Workbook.Names;
  20468. var range = decode_range(ref);
  20469. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  20470. for(var i = 0; i < names.length; ++i) {
  20471. var name = names[i];
  20472. if(name.Name != '_xlnm._FilterDatabase') continue;
  20473. if(name.Sheet != idx) continue;
  20474. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  20475. }
  20476. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  20477. return writextag("autoFilter", null, {ref:ref});
  20478. }
  20479. /* 18.3.1.88 sheetViews CT_SheetViews */
  20480. /* 18.3.1.87 sheetView CT_SheetView */
  20481. var sviewregex = /<(?:\w:)?sheetView(?:[^>a-z][^>]*)?\/?>/;
  20482. function parse_ws_xml_sheetviews(data, wb) {
  20483. if(!wb.Views) wb.Views = [{}];
  20484. (data.match(sviewregex)||[]).forEach(function(r, i) {
  20485. var tag = parsexmltag(r);
  20486. // $FlowIgnore
  20487. if(!wb.Views[i]) wb.Views[i] = {};
  20488. // $FlowIgnore
  20489. if(+tag.zoomScale) wb.Views[i].zoom = +tag.zoomScale;
  20490. // $FlowIgnore
  20491. if(parsexmlbool(tag.rightToLeft)) wb.Views[i].RTL = true;
  20492. });
  20493. }
  20494. function write_ws_xml_sheetviews(ws, opts, idx, wb) {
  20495. var sview = ({workbookViewId:"0"});
  20496. // $FlowIgnore
  20497. if((((wb||{}).Workbook||{}).Views||[])[0]) sview.rightToLeft = wb.Workbook.Views[0].RTL ? "1" : "0";
  20498. return writextag("sheetViews", writextag("sheetView", null, sview), {});
  20499. }
  20500. function write_ws_xml_cell(cell, ref, ws, opts) {
  20501. if(cell.v === undefined && typeof cell.f !== "string" || cell.t === 'z') return "";
  20502. var vv = "";
  20503. var oldt = cell.t, oldv = cell.v;
  20504. if(cell.t !== "z") switch(cell.t) {
  20505. case 'b': vv = cell.v ? "1" : "0"; break;
  20506. case 'n': vv = ''+cell.v; break;
  20507. case 'e': vv = BErr[cell.v]; break;
  20508. case 'd':
  20509. if(opts && opts.cellDates) vv = parseDate(cell.v, -1).toISOString();
  20510. else {
  20511. cell = dup(cell);
  20512. cell.t = 'n';
  20513. vv = ''+(cell.v = datenum(parseDate(cell.v)));
  20514. }
  20515. if(typeof cell.z === 'undefined') cell.z = SSF._table[14];
  20516. break;
  20517. default: vv = cell.v; break;
  20518. }
  20519. var v = writetag('v', escapexml(vv)), o = ({r:ref});
  20520. /* TODO: cell style */
  20521. var os = get_cell_style(opts.cellXfs, cell, opts);
  20522. if(os !== 0) o.s = os;
  20523. switch(cell.t) {
  20524. case 'n': break;
  20525. case 'd': o.t = "d"; break;
  20526. case 'b': o.t = "b"; break;
  20527. case 'e': o.t = "e"; break;
  20528. case 'z': break;
  20529. default: if(cell.v == null) { delete cell.t; break; }
  20530. if(opts && opts.bookSST) {
  20531. v = writetag('v', ''+get_sst_id(opts.Strings, cell.v, opts.revStrings));
  20532. o.t = "s"; break;
  20533. }
  20534. o.t = "str"; break;
  20535. }
  20536. if(cell.t != oldt) { cell.t = oldt; cell.v = oldv; }
  20537. if(typeof cell.f == "string" && cell.f) {
  20538. var ff = cell.F && cell.F.slice(0, ref.length) == ref ? {t:"array", ref:cell.F} : null;
  20539. v = writextag('f', escapexml(cell.f), ff) + (cell.v != null ? v : "");
  20540. }
  20541. if(cell.l) ws['!links'].push([ref, cell.l]);
  20542. if(cell.c) ws['!comments'].push([ref, cell.c]);
  20543. return writextag('c', v, o);
  20544. }
  20545. var parse_ws_xml_data = (function() {
  20546. var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/;
  20547. var rregex = /r=["']([^"']*)["']/, isregex = /<(?:\w+:)?is>([\S\s]*?)<\/(?:\w+:)?is>/;
  20548. var refregex = /ref=["']([^"']*)["']/;
  20549. var match_v = matchtag("v"), match_f = matchtag("f");
  20550. return function parse_ws_xml_data(sdata, s, opts, guess, themes, styles) {
  20551. var ri = 0, x = "", cells = [], cref = [], idx=0, i=0, cc=0, d="", p;
  20552. var tag, tagr = 0, tagc = 0;
  20553. var sstr, ftag;
  20554. var fmtid = 0, fillid = 0;
  20555. var do_format = Array.isArray(styles.CellXf), cf;
  20556. var arrayf = [];
  20557. var sharedf = [];
  20558. var dense = Array.isArray(s);
  20559. var rows = [], rowobj = {}, rowrite = false;
  20560. var sheetStubs = !!opts.sheetStubs;
  20561. for(var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) {
  20562. x = marr[mt].trim();
  20563. var xlen = x.length;
  20564. if(xlen === 0) continue;
  20565. /* 18.3.1.73 row CT_Row */
  20566. for(ri = 0; ri < xlen; ++ri) if(x.charCodeAt(ri) === 62) break; ++ri;
  20567. tag = parsexmltag(x.slice(0,ri), true);
  20568. tagr = tag.r != null ? parseInt(tag.r, 10) : tagr+1; tagc = -1;
  20569. if(opts.sheetRows && opts.sheetRows < tagr) continue;
  20570. if(guess.s.r > tagr - 1) guess.s.r = tagr - 1;
  20571. if(guess.e.r < tagr - 1) guess.e.r = tagr - 1;
  20572. if(opts && opts.cellStyles) {
  20573. rowobj = {}; rowrite = false;
  20574. if(tag.ht) { rowrite = true; rowobj.hpt = parseFloat(tag.ht); rowobj.hpx = pt2px(rowobj.hpt); }
  20575. if(tag.hidden == "1") { rowrite = true; rowobj.hidden = true; }
  20576. if(tag.outlineLevel != null) { rowrite = true; rowobj.level = +tag.outlineLevel; }
  20577. if(rowrite) rows[tagr-1] = rowobj;
  20578. }
  20579. /* 18.3.1.4 c CT_Cell */
  20580. cells = x.slice(ri).split(cellregex);
  20581. for(var rslice = 0; rslice != cells.length; ++rslice) if(cells[rslice].trim().charAt(0) != "<") break;
  20582. cells = cells.slice(rslice);
  20583. for(ri = 0; ri != cells.length; ++ri) {
  20584. x = cells[ri].trim();
  20585. if(x.length === 0) continue;
  20586. cref = x.match(rregex); idx = ri; i=0; cc=0;
  20587. x = "<c " + (x.slice(0,1)=="<"?">":"") + x;
  20588. if(cref != null && cref.length === 2) {
  20589. idx = 0; d=cref[1];
  20590. for(i=0; i != d.length; ++i) {
  20591. if((cc=d.charCodeAt(i)-64) < 1 || cc > 26) break;
  20592. idx = 26*idx + cc;
  20593. }
  20594. --idx;
  20595. tagc = idx;
  20596. } else ++tagc;
  20597. for(i = 0; i != x.length; ++i) if(x.charCodeAt(i) === 62) break; ++i;
  20598. tag = parsexmltag(x.slice(0,i), true);
  20599. if(!tag.r) tag.r = encode_cell({r:tagr-1, c:tagc});
  20600. d = x.slice(i);
  20601. p = ({t:""});
  20602. if((cref=d.match(match_v))!= null && cref[1] !== '') p.v=unescapexml(cref[1]);
  20603. if(opts.cellFormula) {
  20604. if((cref=d.match(match_f))!= null && cref[1] !== '') {
  20605. /* TODO: match against XLSXFutureFunctions */
  20606. p.f=unescapexml(utf8read(cref[1])).replace(/\r\n/g, "\n");
  20607. if(!opts.xlfn) p.f = _xlfn(p.f);
  20608. if(cref[0].indexOf('t="array"') > -1) {
  20609. p.F = (d.match(refregex)||[])[1];
  20610. if(p.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p.F), p.F]);
  20611. } else if(cref[0].indexOf('t="shared"') > -1) {
  20612. // TODO: parse formula
  20613. ftag = parsexmltag(cref[0]);
  20614. var ___f = unescapexml(utf8read(cref[1]));
  20615. if(!opts.xlfn) ___f = _xlfn(___f);
  20616. sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r];
  20617. }
  20618. } else if((cref=d.match(/<f[^>]*\/>/))) {
  20619. ftag = parsexmltag(cref[0]);
  20620. if(sharedf[ftag.si]) p.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2]/*[0].ref*/, tag.r);
  20621. }
  20622. /* TODO: factor out contains logic */
  20623. var _tag = decode_cell(tag.r);
  20624. for(i = 0; i < arrayf.length; ++i)
  20625. if(_tag.r >= arrayf[i][0].s.r && _tag.r <= arrayf[i][0].e.r)
  20626. if(_tag.c >= arrayf[i][0].s.c && _tag.c <= arrayf[i][0].e.c)
  20627. p.F = arrayf[i][1];
  20628. }
  20629. if(tag.t == null && p.v === undefined) {
  20630. if(p.f || p.F) {
  20631. p.v = 0; p.t = "n";
  20632. } else if(!sheetStubs) continue;
  20633. else p.t = "z";
  20634. }
  20635. else p.t = tag.t || "n";
  20636. if(guess.s.c > tagc) guess.s.c = tagc;
  20637. if(guess.e.c < tagc) guess.e.c = tagc;
  20638. /* 18.18.11 t ST_CellType */
  20639. switch(p.t) {
  20640. case 'n':
  20641. if(p.v == "" || p.v == null) {
  20642. if(!sheetStubs) continue;
  20643. p.t = 'z';
  20644. } else p.v = parseFloat(p.v);
  20645. break;
  20646. case 's':
  20647. if(typeof p.v == 'undefined') {
  20648. if(!sheetStubs) continue;
  20649. p.t = 'z';
  20650. } else {
  20651. sstr = strs[parseInt(p.v, 10)];
  20652. p.v = sstr.t;
  20653. p.r = sstr.r;
  20654. if(opts.cellHTML) p.h = sstr.h;
  20655. }
  20656. break;
  20657. case 'str':
  20658. p.t = "s";
  20659. p.v = (p.v!=null) ? utf8read(p.v) : '';
  20660. if(opts.cellHTML) p.h = escapehtml(p.v);
  20661. break;
  20662. case 'inlineStr':
  20663. cref = d.match(isregex);
  20664. p.t = 's';
  20665. if(cref != null && (sstr = parse_si(cref[1]))) {
  20666. p.v = sstr.t;
  20667. if(opts.cellHTML) p.h = sstr.h;
  20668. } else p.v = "";
  20669. break;
  20670. case 'b': p.v = parsexmlbool(p.v); break;
  20671. case 'd':
  20672. if(opts.cellDates) p.v = parseDate(p.v, 1);
  20673. else { p.v = datenum(parseDate(p.v, 1)); p.t = 'n'; }
  20674. break;
  20675. /* error string in .w, number in .v */
  20676. case 'e':
  20677. if(!opts || opts.cellText !== false) p.w = p.v;
  20678. p.v = RBErr[p.v]; break;
  20679. }
  20680. /* formatting */
  20681. fmtid = fillid = 0;
  20682. cf = null;
  20683. if(do_format && tag.s !== undefined) {
  20684. cf = styles.CellXf[tag.s];
  20685. if(cf != null) {
  20686. if(cf.numFmtId != null) fmtid = cf.numFmtId;
  20687. if(opts.cellStyles) {
  20688. if(cf.fillId != null) fillid = cf.fillId;
  20689. }
  20690. }
  20691. }
  20692. safe_format(p, fmtid, fillid, opts, themes, styles);
  20693. if(opts.cellDates && do_format && p.t == 'n' && SSF.is_date(SSF._table[fmtid])) { p.t = 'd'; p.v = numdate(p.v); }
  20694. if(dense) {
  20695. var _r = decode_cell(tag.r);
  20696. if(!s[_r.r]) s[_r.r] = [];
  20697. s[_r.r][_r.c] = p;
  20698. } else s[tag.r] = p;
  20699. }
  20700. }
  20701. if(rows.length > 0) s['!rows'] = rows;
  20702. }; })();
  20703. function write_ws_xml_data(ws, opts, idx, wb) {
  20704. var o = [], r = [], range = safe_decode_range(ws['!ref']), cell="", ref, rr = "", cols = [], R=0, C=0, rows = ws['!rows'];
  20705. var dense = Array.isArray(ws);
  20706. var params = ({r:rr}), row, height = -1;
  20707. for(C = range.s.c; C <= range.e.c; ++C) cols[C] = encode_col(C);
  20708. for(R = range.s.r; R <= range.e.r; ++R) {
  20709. r = [];
  20710. rr = encode_row(R);
  20711. for(C = range.s.c; C <= range.e.c; ++C) {
  20712. ref = cols[C] + rr;
  20713. var _cell = dense ? (ws[R]||[])[C]: ws[ref];
  20714. if(_cell === undefined) continue;
  20715. if((cell = write_ws_xml_cell(_cell, ref, ws, opts, idx, wb)) != null) r.push(cell);
  20716. }
  20717. if(r.length > 0 || (rows && rows[R])) {
  20718. params = ({r:rr});
  20719. if(rows && rows[R]) {
  20720. row = rows[R];
  20721. if(row.hidden) params.hidden = 1;
  20722. height = -1;
  20723. if (row.hpx) height = px2pt(row.hpx);
  20724. else if (row.hpt) height = row.hpt;
  20725. if (height > -1) { params.ht = height; params.customHeight = 1; }
  20726. if (row.level) { params.outlineLevel = row.level; }
  20727. }
  20728. o[o.length] = (writextag('row', r.join(""), params));
  20729. }
  20730. }
  20731. if(rows) for(; R < rows.length; ++R) {
  20732. if(rows && rows[R]) {
  20733. params = ({r:R+1});
  20734. row = rows[R];
  20735. if(row.hidden) params.hidden = 1;
  20736. height = -1;
  20737. if (row.hpx) height = px2pt(row.hpx);
  20738. else if (row.hpt) height = row.hpt;
  20739. if (height > -1) { params.ht = height; params.customHeight = 1; }
  20740. if (row.level) { params.outlineLevel = row.level; }
  20741. o[o.length] = (writextag('row', "", params));
  20742. }
  20743. }
  20744. return o.join("");
  20745. }
  20746. var WS_XML_ROOT = writextag('worksheet', null, {
  20747. 'xmlns': XMLNS.main[0],
  20748. 'xmlns:r': XMLNS.r
  20749. });
  20750. function write_ws_xml(idx, opts, wb, rels) {
  20751. var o = [XML_HEADER, WS_XML_ROOT];
  20752. var s = wb.SheetNames[idx], sidx = 0, rdata = "";
  20753. var ws = wb.Sheets[s];
  20754. if(ws == null) ws = {};
  20755. var ref = ws['!ref'] || 'A1';
  20756. var range = safe_decode_range(ref);
  20757. if(range.e.c > 0x3FFF || range.e.r > 0xFFFFF) {
  20758. if(opts.WTF) throw new Error("Range " + ref + " exceeds format limit A1:XFD1048576");
  20759. range.e.c = Math.min(range.e.c, 0x3FFF);
  20760. range.e.r = Math.min(range.e.c, 0xFFFFF);
  20761. ref = encode_range(range);
  20762. }
  20763. if(!rels) rels = {};
  20764. ws['!comments'] = [];
  20765. var _drawing = [];
  20766. write_ws_xml_sheetpr(ws, wb, idx, opts, o);
  20767. o[o.length] = (writextag('dimension', null, {'ref': ref}));
  20768. o[o.length] = write_ws_xml_sheetviews(ws, opts, idx, wb);
  20769. /* TODO: store in WB, process styles */
  20770. if(opts.sheetFormat) o[o.length] = (writextag('sheetFormatPr', null, {
  20771. defaultRowHeight:opts.sheetFormat.defaultRowHeight||'16',
  20772. baseColWidth:opts.sheetFormat.baseColWidth||'10',
  20773. outlineLevelRow:opts.sheetFormat.outlineLevelRow||'7'
  20774. }));
  20775. if(ws['!cols'] != null && ws['!cols'].length > 0) o[o.length] = (write_ws_xml_cols(ws, ws['!cols']));
  20776. o[sidx = o.length] = '<sheetData/>';
  20777. ws['!links'] = [];
  20778. if(ws['!ref'] != null) {
  20779. rdata = write_ws_xml_data(ws, opts, idx, wb, rels);
  20780. if(rdata.length > 0) o[o.length] = (rdata);
  20781. }
  20782. if(o.length>sidx+1) { o[o.length] = ('</sheetData>'); o[sidx]=o[sidx].replace("/>",">"); }
  20783. /* sheetCalcPr */
  20784. if(ws['!protect'] != null) o[o.length] = write_ws_xml_protection(ws['!protect']);
  20785. /* protectedRanges */
  20786. /* scenarios */
  20787. if(ws['!autofilter'] != null) o[o.length] = write_ws_xml_autofilter(ws['!autofilter'], ws, wb, idx);
  20788. /* sortState */
  20789. /* dataConsolidate */
  20790. /* customSheetViews */
  20791. if(ws['!merges'] != null && ws['!merges'].length > 0) o[o.length] = (write_ws_xml_merges(ws['!merges']));
  20792. /* phoneticPr */
  20793. /* conditionalFormatting */
  20794. /* dataValidations */
  20795. var relc = -1, rel, rId = -1;
  20796. if(ws['!links'].length > 0) {
  20797. o[o.length] = "<hyperlinks>";
  20798. ws['!links'].forEach(function(l) {
  20799. if(!l[1].Target) return;
  20800. rel = ({"ref":l[0]});
  20801. if(l[1].Target.charAt(0) != "#") {
  20802. rId = add_rels(rels, -1, escapexml(l[1].Target).replace(/#.*$/, ""), RELS.HLINK);
  20803. rel["r:id"] = "rId"+rId;
  20804. }
  20805. if((relc = l[1].Target.indexOf("#")) > -1) rel.location = escapexml(l[1].Target.slice(relc+1));
  20806. if(l[1].Tooltip) rel.tooltip = escapexml(l[1].Tooltip);
  20807. o[o.length] = writextag("hyperlink",null,rel);
  20808. });
  20809. o[o.length] = "</hyperlinks>";
  20810. }
  20811. delete ws['!links'];
  20812. /* printOptions */
  20813. if(ws['!margins'] != null) o[o.length] = write_ws_xml_margins(ws['!margins']);
  20814. /* pageSetup */
  20815. /* headerFooter */
  20816. /* rowBreaks */
  20817. /* colBreaks */
  20818. /* customProperties */
  20819. /* cellWatches */
  20820. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) o[o.length] = writetag("ignoredErrors", writextag("ignoredError", null, {numberStoredAsText:1, sqref:ref}));
  20821. /* smartTags */
  20822. if(_drawing.length > 0) {
  20823. rId = add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  20824. o[o.length] = writextag("drawing", null, {"r:id":"rId" + rId});
  20825. ws['!drawing'] = _drawing;
  20826. }
  20827. if(ws['!comments'].length > 0) {
  20828. rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  20829. o[o.length] = writextag("legacyDrawing", null, {"r:id":"rId" + rId});
  20830. ws['!legacy'] = rId;
  20831. }
  20832. /* legacyDrawingHF */
  20833. /* picture */
  20834. /* oleObjects */
  20835. /* controls */
  20836. /* webPublishItems */
  20837. /* tableParts */
  20838. /* extLst */
  20839. if(o.length>1) { o[o.length] = ('</worksheet>'); o[1]=o[1].replace("/>",">"); }
  20840. return o.join("");
  20841. }
  20842. /* [MS-XLSB] 2.4.726 BrtRowHdr */
  20843. function parse_BrtRowHdr(data, length) {
  20844. var z = ({});
  20845. var tgt = data.l + length;
  20846. z.r = data.read_shift(4);
  20847. data.l += 4; // TODO: ixfe
  20848. var miyRw = data.read_shift(2);
  20849. data.l += 1; // TODO: top/bot padding
  20850. var flags = data.read_shift(1);
  20851. data.l = tgt;
  20852. if(flags & 0x07) z.level = flags & 0x07;
  20853. if(flags & 0x10) z.hidden = true;
  20854. if(flags & 0x20) z.hpt = miyRw / 20;
  20855. return z;
  20856. }
  20857. function write_BrtRowHdr(R, range, ws) {
  20858. var o = new_buf(17+8*16);
  20859. var row = (ws['!rows']||[])[R]||{};
  20860. o.write_shift(4, R);
  20861. o.write_shift(4, 0); /* TODO: ixfe */
  20862. var miyRw = 0x0140;
  20863. if(row.hpx) miyRw = px2pt(row.hpx) * 20;
  20864. else if(row.hpt) miyRw = row.hpt * 20;
  20865. o.write_shift(2, miyRw);
  20866. o.write_shift(1, 0); /* top/bot padding */
  20867. var flags = 0x0;
  20868. if(row.level) flags |= row.level;
  20869. if(row.hidden) flags |= 0x10;
  20870. if(row.hpx || row.hpt) flags |= 0x20;
  20871. o.write_shift(1, flags);
  20872. o.write_shift(1, 0); /* phonetic guide */
  20873. /* [MS-XLSB] 2.5.8 BrtColSpan explains the mechanism */
  20874. var ncolspan = 0, lcs = o.l;
  20875. o.l += 4;
  20876. var caddr = {r:R, c:0};
  20877. for(var i = 0; i < 16; ++i) {
  20878. if((range.s.c > ((i+1) << 10)) || (range.e.c < (i << 10))) continue;
  20879. var first = -1, last = -1;
  20880. for(var j = (i<<10); j < ((i+1)<<10); ++j) {
  20881. caddr.c = j;
  20882. var cell = Array.isArray(ws) ? (ws[caddr.r]||[])[caddr.c] : ws[encode_cell(caddr)];
  20883. if(cell) { if(first < 0) first = j; last = j; }
  20884. }
  20885. if(first < 0) continue;
  20886. ++ncolspan;
  20887. o.write_shift(4, first);
  20888. o.write_shift(4, last);
  20889. }
  20890. var l = o.l;
  20891. o.l = lcs;
  20892. o.write_shift(4, ncolspan);
  20893. o.l = l;
  20894. return o.length > o.l ? o.slice(0, o.l) : o;
  20895. }
  20896. function write_row_header(ba, ws, range, R) {
  20897. var o = write_BrtRowHdr(R, range, ws);
  20898. if((o.length > 17) || (ws['!rows']||[])[R]) write_record(ba, 'BrtRowHdr', o);
  20899. }
  20900. /* [MS-XLSB] 2.4.820 BrtWsDim */
  20901. var parse_BrtWsDim = parse_UncheckedRfX;
  20902. var write_BrtWsDim = write_UncheckedRfX;
  20903. /* [MS-XLSB] 2.4.821 BrtWsFmtInfo */
  20904. function parse_BrtWsFmtInfo() {
  20905. }
  20906. //function write_BrtWsFmtInfo(ws, o) { }
  20907. /* [MS-XLSB] 2.4.823 BrtWsProp */
  20908. function parse_BrtWsProp(data, length) {
  20909. var z = {};
  20910. /* TODO: pull flags */
  20911. data.l += 19;
  20912. z.name = parse_XLSBCodeName(data, length - 19);
  20913. return z;
  20914. }
  20915. function write_BrtWsProp(str, o) {
  20916. if(o == null) o = new_buf(84+4*str.length);
  20917. for(var i = 0; i < 3; ++i) o.write_shift(1,0);
  20918. write_BrtColor({auto:1}, o);
  20919. o.write_shift(-4,-1);
  20920. o.write_shift(-4,-1);
  20921. write_XLSBCodeName(str, o);
  20922. return o.slice(0, o.l);
  20923. }
  20924. /* [MS-XLSB] 2.4.306 BrtCellBlank */
  20925. function parse_BrtCellBlank(data) {
  20926. var cell = parse_XLSBCell(data);
  20927. return [cell];
  20928. }
  20929. function write_BrtCellBlank(cell, ncell, o) {
  20930. if(o == null) o = new_buf(8);
  20931. return write_XLSBCell(ncell, o);
  20932. }
  20933. /* [MS-XLSB] 2.4.307 BrtCellBool */
  20934. function parse_BrtCellBool(data) {
  20935. var cell = parse_XLSBCell(data);
  20936. var fBool = data.read_shift(1);
  20937. return [cell, fBool, 'b'];
  20938. }
  20939. function write_BrtCellBool(cell, ncell, o) {
  20940. if(o == null) o = new_buf(9);
  20941. write_XLSBCell(ncell, o);
  20942. o.write_shift(1, cell.v ? 1 : 0);
  20943. return o;
  20944. }
  20945. /* [MS-XLSB] 2.4.308 BrtCellError */
  20946. function parse_BrtCellError(data) {
  20947. var cell = parse_XLSBCell(data);
  20948. var bError = data.read_shift(1);
  20949. return [cell, bError, 'e'];
  20950. }
  20951. /* [MS-XLSB] 2.4.311 BrtCellIsst */
  20952. function parse_BrtCellIsst(data) {
  20953. var cell = parse_XLSBCell(data);
  20954. var isst = data.read_shift(4);
  20955. return [cell, isst, 's'];
  20956. }
  20957. function write_BrtCellIsst(cell, ncell, o) {
  20958. if(o == null) o = new_buf(12);
  20959. write_XLSBCell(ncell, o);
  20960. o.write_shift(4, ncell.v);
  20961. return o;
  20962. }
  20963. /* [MS-XLSB] 2.4.313 BrtCellReal */
  20964. function parse_BrtCellReal(data) {
  20965. var cell = parse_XLSBCell(data);
  20966. var value = parse_Xnum(data);
  20967. return [cell, value, 'n'];
  20968. }
  20969. function write_BrtCellReal(cell, ncell, o) {
  20970. if(o == null) o = new_buf(16);
  20971. write_XLSBCell(ncell, o);
  20972. write_Xnum(cell.v, o);
  20973. return o;
  20974. }
  20975. /* [MS-XLSB] 2.4.314 BrtCellRk */
  20976. function parse_BrtCellRk(data) {
  20977. var cell = parse_XLSBCell(data);
  20978. var value = parse_RkNumber(data);
  20979. return [cell, value, 'n'];
  20980. }
  20981. function write_BrtCellRk(cell, ncell, o) {
  20982. if(o == null) o = new_buf(12);
  20983. write_XLSBCell(ncell, o);
  20984. write_RkNumber(cell.v, o);
  20985. return o;
  20986. }
  20987. /* [MS-XLSB] 2.4.317 BrtCellSt */
  20988. function parse_BrtCellSt(data) {
  20989. var cell = parse_XLSBCell(data);
  20990. var value = parse_XLWideString(data);
  20991. return [cell, value, 'str'];
  20992. }
  20993. function write_BrtCellSt(cell, ncell, o) {
  20994. if(o == null) o = new_buf(12 + 4 * cell.v.length);
  20995. write_XLSBCell(ncell, o);
  20996. write_XLWideString(cell.v, o);
  20997. return o.length > o.l ? o.slice(0, o.l) : o;
  20998. }
  20999. /* [MS-XLSB] 2.4.653 BrtFmlaBool */
  21000. function parse_BrtFmlaBool(data, length, opts) {
  21001. var end = data.l + length;
  21002. var cell = parse_XLSBCell(data);
  21003. cell.r = opts['!row'];
  21004. var value = data.read_shift(1);
  21005. var o = [cell, value, 'b'];
  21006. if(opts.cellFormula) {
  21007. data.l += 2;
  21008. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21009. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21010. }
  21011. else data.l = end;
  21012. return o;
  21013. }
  21014. /* [MS-XLSB] 2.4.654 BrtFmlaError */
  21015. function parse_BrtFmlaError(data, length, opts) {
  21016. var end = data.l + length;
  21017. var cell = parse_XLSBCell(data);
  21018. cell.r = opts['!row'];
  21019. var value = data.read_shift(1);
  21020. var o = [cell, value, 'e'];
  21021. if(opts.cellFormula) {
  21022. data.l += 2;
  21023. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21024. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21025. }
  21026. else data.l = end;
  21027. return o;
  21028. }
  21029. /* [MS-XLSB] 2.4.655 BrtFmlaNum */
  21030. function parse_BrtFmlaNum(data, length, opts) {
  21031. var end = data.l + length;
  21032. var cell = parse_XLSBCell(data);
  21033. cell.r = opts['!row'];
  21034. var value = parse_Xnum(data);
  21035. var o = [cell, value, 'n'];
  21036. if(opts.cellFormula) {
  21037. data.l += 2;
  21038. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21039. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21040. }
  21041. else data.l = end;
  21042. return o;
  21043. }
  21044. /* [MS-XLSB] 2.4.656 BrtFmlaString */
  21045. function parse_BrtFmlaString(data, length, opts) {
  21046. var end = data.l + length;
  21047. var cell = parse_XLSBCell(data);
  21048. cell.r = opts['!row'];
  21049. var value = parse_XLWideString(data);
  21050. var o = [cell, value, 'str'];
  21051. if(opts.cellFormula) {
  21052. data.l += 2;
  21053. var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts);
  21054. o[3] = stringify_formula(formula, null/*range*/, cell, opts.supbooks, opts);/* TODO */
  21055. }
  21056. else data.l = end;
  21057. return o;
  21058. }
  21059. /* [MS-XLSB] 2.4.682 BrtMergeCell */
  21060. var parse_BrtMergeCell = parse_UncheckedRfX;
  21061. var write_BrtMergeCell = write_UncheckedRfX;
  21062. /* [MS-XLSB] 2.4.107 BrtBeginMergeCells */
  21063. function write_BrtBeginMergeCells(cnt, o) {
  21064. if(o == null) o = new_buf(4);
  21065. o.write_shift(4, cnt);
  21066. return o;
  21067. }
  21068. /* [MS-XLSB] 2.4.662 BrtHLink */
  21069. function parse_BrtHLink(data, length) {
  21070. var end = data.l + length;
  21071. var rfx = parse_UncheckedRfX(data, 16);
  21072. var relId = parse_XLNullableWideString(data);
  21073. var loc = parse_XLWideString(data);
  21074. var tooltip = parse_XLWideString(data);
  21075. var display = parse_XLWideString(data);
  21076. data.l = end;
  21077. var o = ({rfx:rfx, relId:relId, loc:loc, display:display});
  21078. if(tooltip) o.Tooltip = tooltip;
  21079. return o;
  21080. }
  21081. function write_BrtHLink(l, rId) {
  21082. var o = new_buf(50+4*(l[1].Target.length + (l[1].Tooltip || "").length));
  21083. write_UncheckedRfX({s:decode_cell(l[0]), e:decode_cell(l[0])}, o);
  21084. write_RelID("rId" + rId, o);
  21085. var locidx = l[1].Target.indexOf("#");
  21086. var loc = locidx == -1 ? "" : l[1].Target.slice(locidx+1);
  21087. write_XLWideString(loc || "", o);
  21088. write_XLWideString(l[1].Tooltip || "", o);
  21089. write_XLWideString("", o);
  21090. return o.slice(0, o.l);
  21091. }
  21092. /* [MS-XLSB] 2.4.692 BrtPane */
  21093. function parse_BrtPane(/*data, length, opts*/) {
  21094. }
  21095. /* [MS-XLSB] 2.4.6 BrtArrFmla */
  21096. function parse_BrtArrFmla(data, length, opts) {
  21097. var end = data.l + length;
  21098. var rfx = parse_RfX(data, 16);
  21099. var fAlwaysCalc = data.read_shift(1);
  21100. var o = [rfx]; o[2] = fAlwaysCalc;
  21101. if(opts.cellFormula) {
  21102. var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts);
  21103. o[1] = formula;
  21104. } else data.l = end;
  21105. return o;
  21106. }
  21107. /* [MS-XLSB] 2.4.750 BrtShrFmla */
  21108. function parse_BrtShrFmla(data, length, opts) {
  21109. var end = data.l + length;
  21110. var rfx = parse_UncheckedRfX(data, 16);
  21111. var o = [rfx];
  21112. if(opts.cellFormula) {
  21113. var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts);
  21114. o[1] = formula;
  21115. data.l = end;
  21116. } else data.l = end;
  21117. return o;
  21118. }
  21119. /* [MS-XLSB] 2.4.323 BrtColInfo */
  21120. /* TODO: once XLS ColInfo is set, combine the functions */
  21121. function write_BrtColInfo(C, col, o) {
  21122. if(o == null) o = new_buf(18);
  21123. var p = col_obj_w(C, col);
  21124. o.write_shift(-4, C);
  21125. o.write_shift(-4, C);
  21126. o.write_shift(4, (p.width || 10) * 256);
  21127. o.write_shift(4, 0/*ixfe*/); // style
  21128. var flags = 0;
  21129. if(col.hidden) flags |= 0x01;
  21130. if(typeof p.width == 'number') flags |= 0x02;
  21131. if(col.level) flags |= (col.level << 8);
  21132. o.write_shift(2, flags); // bit flag
  21133. return o;
  21134. }
  21135. /* [MS-XLSB] 2.4.678 BrtMargins */
  21136. var BrtMarginKeys = ["left","right","top","bottom","header","footer"];
  21137. function parse_BrtMargins(data) {
  21138. var margins = ({});
  21139. BrtMarginKeys.forEach(function(k) { margins[k] = parse_Xnum(data, 8); });
  21140. return margins;
  21141. }
  21142. function write_BrtMargins(margins, o) {
  21143. if(o == null) o = new_buf(6*8);
  21144. default_margins(margins);
  21145. BrtMarginKeys.forEach(function(k) { write_Xnum((margins)[k], o); });
  21146. return o;
  21147. }
  21148. /* [MS-XLSB] 2.4.299 BrtBeginWsView */
  21149. function parse_BrtBeginWsView(data) {
  21150. var f = data.read_shift(2);
  21151. data.l += 28;
  21152. return { RTL: f & 0x20 };
  21153. }
  21154. function write_BrtBeginWsView(ws, Workbook, o) {
  21155. if(o == null) o = new_buf(30);
  21156. var f = 0x39c;
  21157. if((((Workbook||{}).Views||[])[0]||{}).RTL) f |= 0x20;
  21158. o.write_shift(2, f); // bit flag
  21159. o.write_shift(4, 0);
  21160. o.write_shift(4, 0); // view first row
  21161. o.write_shift(4, 0); // view first col
  21162. o.write_shift(1, 0); // gridline color ICV
  21163. o.write_shift(1, 0);
  21164. o.write_shift(2, 0);
  21165. o.write_shift(2, 100); // zoom scale
  21166. o.write_shift(2, 0);
  21167. o.write_shift(2, 0);
  21168. o.write_shift(2, 0);
  21169. o.write_shift(4, 0); // workbook view id
  21170. return o;
  21171. }
  21172. /* [MS-XLSB] 2.4.309 BrtCellIgnoreEC */
  21173. function write_BrtCellIgnoreEC(ref) {
  21174. var o = new_buf(24);
  21175. o.write_shift(4, 4);
  21176. o.write_shift(4, 1);
  21177. write_UncheckedRfX(ref, o);
  21178. return o;
  21179. }
  21180. /* [MS-XLSB] 2.4.748 BrtSheetProtection */
  21181. function write_BrtSheetProtection(sp, o) {
  21182. if(o == null) o = new_buf(16*4+2);
  21183. o.write_shift(2, sp.password ? crypto_CreatePasswordVerifier_Method1(sp.password) : 0);
  21184. o.write_shift(4, 1); // this record should not be written if no protection
  21185. [
  21186. ["objects", false], // fObjects
  21187. ["scenarios", false], // fScenarios
  21188. ["formatCells", true], // fFormatCells
  21189. ["formatColumns", true], // fFormatColumns
  21190. ["formatRows", true], // fFormatRows
  21191. ["insertColumns", true], // fInsertColumns
  21192. ["insertRows", true], // fInsertRows
  21193. ["insertHyperlinks", true], // fInsertHyperlinks
  21194. ["deleteColumns", true], // fDeleteColumns
  21195. ["deleteRows", true], // fDeleteRows
  21196. ["selectLockedCells", false], // fSelLockedCells
  21197. ["sort", true], // fSort
  21198. ["autoFilter", true], // fAutoFilter
  21199. ["pivotTables", true], // fPivotTables
  21200. ["selectUnlockedCells", false] // fSelUnlockedCells
  21201. ].forEach(function(n) {
  21202. if(n[1]) o.write_shift(4, sp[n[0]] != null && !sp[n[0]] ? 1 : 0);
  21203. else o.write_shift(4, sp[n[0]] != null && sp[n[0]] ? 0 : 1);
  21204. });
  21205. return o;
  21206. }
  21207. function parse_BrtDVal(/*data, length, opts*/) {
  21208. }
  21209. function parse_BrtDVal14(/*data, length, opts*/) {
  21210. }
  21211. /* [MS-XLSB] 2.1.7.61 Worksheet */
  21212. function parse_ws_bin(data, _opts, idx, rels, wb, themes, styles) {
  21213. if(!data) return data;
  21214. var opts = _opts || {};
  21215. if(!rels) rels = {'!id':{}};
  21216. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  21217. var s = (opts.dense ? [] : {});
  21218. var ref;
  21219. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  21220. var state = [];
  21221. var pass = false, end = false;
  21222. var row, p, cf, R, C, addr, sstr, rr, cell;
  21223. var merges = [];
  21224. opts.biff = 12;
  21225. opts['!row'] = 0;
  21226. var ai = 0, af = false;
  21227. var arrayf = [];
  21228. var sharedf = {};
  21229. var supbooks = opts.supbooks || wb.supbooks || ([[]]);
  21230. supbooks.sharedf = sharedf;
  21231. supbooks.arrayf = arrayf;
  21232. supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x) { return x.name; });
  21233. if(!opts.supbooks) {
  21234. opts.supbooks = supbooks;
  21235. if(wb.Names) for(var i = 0; i < wb.Names.length; ++i) supbooks[0][i+1] = wb.Names[i];
  21236. }
  21237. var colinfo = [], rowinfo = [];
  21238. var seencol = false;
  21239. recordhopper(data, function ws_parse(val, R_n, RT) {
  21240. if(end) return;
  21241. switch(RT) {
  21242. case 0x0094: /* 'BrtWsDim' */
  21243. ref = val; break;
  21244. case 0x0000: /* 'BrtRowHdr' */
  21245. row = val;
  21246. if(opts.sheetRows && opts.sheetRows <= row.r) end=true;
  21247. rr = encode_row(R = row.r);
  21248. opts['!row'] = row.r;
  21249. if(val.hidden || val.hpt || val.level != null) {
  21250. if(val.hpt) val.hpx = pt2px(val.hpt);
  21251. rowinfo[val.r] = val;
  21252. }
  21253. break;
  21254. case 0x0002: /* 'BrtCellRk' */
  21255. case 0x0003: /* 'BrtCellError' */
  21256. case 0x0004: /* 'BrtCellBool' */
  21257. case 0x0005: /* 'BrtCellReal' */
  21258. case 0x0006: /* 'BrtCellSt' */
  21259. case 0x0007: /* 'BrtCellIsst' */
  21260. case 0x0008: /* 'BrtFmlaString' */
  21261. case 0x0009: /* 'BrtFmlaNum' */
  21262. case 0x000A: /* 'BrtFmlaBool' */
  21263. case 0x000B: /* 'BrtFmlaError' */
  21264. p = ({t:val[2]});
  21265. switch(val[2]) {
  21266. case 'n': p.v = val[1]; break;
  21267. case 's': sstr = strs[val[1]]; p.v = sstr.t; p.r = sstr.r; break;
  21268. case 'b': p.v = val[1] ? true : false; break;
  21269. case 'e': p.v = val[1]; if(opts.cellText !== false) p.w = BErr[p.v]; break;
  21270. case 'str': p.t = 's'; p.v = val[1]; break;
  21271. }
  21272. if((cf = styles.CellXf[val[0].iStyleRef])) safe_format(p,cf.numFmtId,null,opts, themes, styles);
  21273. C = val[0].c;
  21274. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  21275. else s[encode_col(C) + rr] = p;
  21276. if(opts.cellFormula) {
  21277. af = false;
  21278. for(ai = 0; ai < arrayf.length; ++ai) {
  21279. var aii = arrayf[ai];
  21280. if(row.r >= aii[0].s.r && row.r <= aii[0].e.r)
  21281. if(C >= aii[0].s.c && C <= aii[0].e.c) {
  21282. p.F = encode_range(aii[0]); af = true;
  21283. }
  21284. }
  21285. if(!af && val.length > 3) p.f = val[3];
  21286. }
  21287. if(refguess.s.r > row.r) refguess.s.r = row.r;
  21288. if(refguess.s.c > C) refguess.s.c = C;
  21289. if(refguess.e.r < row.r) refguess.e.r = row.r;
  21290. if(refguess.e.c < C) refguess.e.c = C;
  21291. if(opts.cellDates && cf && p.t == 'n' && SSF.is_date(SSF._table[cf.numFmtId])) {
  21292. var _d = SSF.parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  21293. }
  21294. break;
  21295. case 0x0001: /* 'BrtCellBlank' */
  21296. if(!opts.sheetStubs || pass) break;
  21297. p = ({t:'z',v:undefined});
  21298. C = val[0].c;
  21299. if(opts.dense) { if(!s[R]) s[R] = []; s[R][C] = p; }
  21300. else s[encode_col(C) + rr] = p;
  21301. if(refguess.s.r > row.r) refguess.s.r = row.r;
  21302. if(refguess.s.c > C) refguess.s.c = C;
  21303. if(refguess.e.r < row.r) refguess.e.r = row.r;
  21304. if(refguess.e.c < C) refguess.e.c = C;
  21305. break;
  21306. case 0x00B0: /* 'BrtMergeCell' */
  21307. merges.push(val); break;
  21308. case 0x01EE: /* 'BrtHLink' */
  21309. var rel = rels['!id'][val.relId];
  21310. if(rel) {
  21311. val.Target = rel.Target;
  21312. if(val.loc) val.Target += "#"+val.loc;
  21313. val.Rel = rel;
  21314. } else if(val.relId == '') {
  21315. val.Target = "#" + val.loc;
  21316. }
  21317. for(R=val.rfx.s.r;R<=val.rfx.e.r;++R) for(C=val.rfx.s.c;C<=val.rfx.e.c;++C) {
  21318. if(opts.dense) {
  21319. if(!s[R]) s[R] = [];
  21320. if(!s[R][C]) s[R][C] = {t:'z',v:undefined};
  21321. s[R][C].l = val;
  21322. } else {
  21323. addr = encode_cell({c:C,r:R});
  21324. if(!s[addr]) s[addr] = {t:'z',v:undefined};
  21325. s[addr].l = val;
  21326. }
  21327. }
  21328. break;
  21329. case 0x01AA: /* 'BrtArrFmla' */
  21330. if(!opts.cellFormula) break;
  21331. arrayf.push(val);
  21332. cell = ((opts.dense ? s[R][C] : s[encode_col(C) + rr]));
  21333. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  21334. cell.F = encode_range(val[0]);
  21335. break;
  21336. case 0x01AB: /* 'BrtShrFmla' */
  21337. if(!opts.cellFormula) break;
  21338. sharedf[encode_cell(val[0].s)] = val[1];
  21339. cell = (opts.dense ? s[R][C] : s[encode_col(C) + rr]);
  21340. cell.f = stringify_formula(val[1], refguess, {r:row.r, c:C}, supbooks, opts);
  21341. break;
  21342. /* identical to 'ColInfo' in XLS */
  21343. case 0x003C: /* 'BrtColInfo' */
  21344. if(!opts.cellStyles) break;
  21345. while(val.e >= val.s) {
  21346. colinfo[val.e--] = { width: val.w/256, hidden: !!(val.flags & 0x01), level: val.level };
  21347. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  21348. process_col(colinfo[val.e+1]);
  21349. }
  21350. break;
  21351. case 0x00A1: /* 'BrtBeginAFilter' */
  21352. s['!autofilter'] = { ref:encode_range(val) };
  21353. break;
  21354. case 0x01DC: /* 'BrtMargins' */
  21355. s['!margins'] = val;
  21356. break;
  21357. case 0x0093: /* 'BrtWsProp' */
  21358. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  21359. if(val.name) wb.Sheets[idx].CodeName = val.name;
  21360. break;
  21361. case 0x0089: /* 'BrtBeginWsView' */
  21362. if(!wb.Views) wb.Views = [{}];
  21363. if(!wb.Views[0]) wb.Views[0] = {};
  21364. if(val.RTL) wb.Views[0].RTL = true;
  21365. break;
  21366. case 0x01E5: /* 'BrtWsFmtInfo' */
  21367. break;
  21368. case 0x0040: /* 'BrtDVal' */
  21369. case 0x041D: /* 'BrtDVal14' */
  21370. break;
  21371. case 0x0097: /* 'BrtPane' */
  21372. break;
  21373. case 0x00AF: /* 'BrtAFilterDateGroupItem' */
  21374. case 0x0284: /* 'BrtActiveX' */
  21375. case 0x0271: /* 'BrtBigName' */
  21376. case 0x0232: /* 'BrtBkHim' */
  21377. case 0x018C: /* 'BrtBrk' */
  21378. case 0x0458: /* 'BrtCFIcon' */
  21379. case 0x047A: /* 'BrtCFRuleExt' */
  21380. case 0x01D7: /* 'BrtCFVO' */
  21381. case 0x041A: /* 'BrtCFVO14' */
  21382. case 0x0289: /* 'BrtCellIgnoreEC' */
  21383. case 0x0451: /* 'BrtCellIgnoreEC14' */
  21384. case 0x0031: /* 'BrtCellMeta' */
  21385. case 0x024D: /* 'BrtCellSmartTagProperty' */
  21386. case 0x025F: /* 'BrtCellWatch' */
  21387. case 0x0234: /* 'BrtColor' */
  21388. case 0x041F: /* 'BrtColor14' */
  21389. case 0x00A8: /* 'BrtColorFilter' */
  21390. case 0x00AE: /* 'BrtCustomFilter' */
  21391. case 0x049C: /* 'BrtCustomFilter14' */
  21392. case 0x01F3: /* 'BrtDRef' */
  21393. case 0x01FB: /* 'BrtDXF' */
  21394. case 0x0226: /* 'BrtDrawing' */
  21395. case 0x00AB: /* 'BrtDynamicFilter' */
  21396. case 0x00A7: /* 'BrtFilter' */
  21397. case 0x0499: /* 'BrtFilter14' */
  21398. case 0x00A9: /* 'BrtIconFilter' */
  21399. case 0x049D: /* 'BrtIconFilter14' */
  21400. case 0x0227: /* 'BrtLegacyDrawing' */
  21401. case 0x0228: /* 'BrtLegacyDrawingHF' */
  21402. case 0x0295: /* 'BrtListPart' */
  21403. case 0x027F: /* 'BrtOleObject' */
  21404. case 0x01DE: /* 'BrtPageSetup' */
  21405. case 0x0219: /* 'BrtPhoneticInfo' */
  21406. case 0x01DD: /* 'BrtPrintOptions' */
  21407. case 0x0218: /* 'BrtRangeProtection' */
  21408. case 0x044F: /* 'BrtRangeProtection14' */
  21409. case 0x02A8: /* 'BrtRangeProtectionIso' */
  21410. case 0x0450: /* 'BrtRangeProtectionIso14' */
  21411. case 0x0400: /* 'BrtRwDescent' */
  21412. case 0x0098: /* 'BrtSel' */
  21413. case 0x0297: /* 'BrtSheetCalcProp' */
  21414. case 0x0217: /* 'BrtSheetProtection' */
  21415. case 0x02A6: /* 'BrtSheetProtectionIso' */
  21416. case 0x01F8: /* 'BrtSlc' */
  21417. case 0x0413: /* 'BrtSparkline' */
  21418. case 0x01AC: /* 'BrtTable' */
  21419. case 0x00AA: /* 'BrtTop10Filter' */
  21420. case 0x0C00: /* 'BrtUid' */
  21421. case 0x0032: /* 'BrtValueMeta' */
  21422. case 0x0816: /* 'BrtWebExtension' */
  21423. case 0x0415: /* 'BrtWsFmtInfoEx14' */
  21424. break;
  21425. case 0x0023: /* 'BrtFRTBegin' */
  21426. pass = true; break;
  21427. case 0x0024: /* 'BrtFRTEnd' */
  21428. pass = false; break;
  21429. case 0x0025: /* 'BrtACBegin' */
  21430. state.push(R_n); pass = true; break;
  21431. case 0x0026: /* 'BrtACEnd' */
  21432. state.pop(); pass = false; break;
  21433. default:
  21434. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  21435. else if((R_n||"").indexOf("End") > 0){/* empty */}
  21436. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  21437. }
  21438. }, opts);
  21439. delete opts.supbooks;
  21440. delete opts['!row'];
  21441. if(!s["!ref"] && (refguess.s.r < 2000000 || ref && (ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0))) s["!ref"] = encode_range(ref || refguess);
  21442. if(opts.sheetRows && s["!ref"]) {
  21443. var tmpref = safe_decode_range(s["!ref"]);
  21444. if(opts.sheetRows <= +tmpref.e.r) {
  21445. tmpref.e.r = opts.sheetRows - 1;
  21446. if(tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r;
  21447. if(tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r;
  21448. if(tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c;
  21449. if(tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c;
  21450. s["!fullref"] = s["!ref"];
  21451. s["!ref"] = encode_range(tmpref);
  21452. }
  21453. }
  21454. if(merges.length > 0) s["!merges"] = merges;
  21455. if(colinfo.length > 0) s["!cols"] = colinfo;
  21456. if(rowinfo.length > 0) s["!rows"] = rowinfo;
  21457. return s;
  21458. }
  21459. /* TODO: something useful -- this is a stub */
  21460. function write_ws_bin_cell(ba, cell, R, C, opts, ws) {
  21461. if(cell.v === undefined) return;
  21462. var vv = "";
  21463. switch(cell.t) {
  21464. case 'b': vv = cell.v ? "1" : "0"; break;
  21465. case 'd': // no BrtCellDate :(
  21466. cell = dup(cell);
  21467. cell.z = cell.z || SSF._table[14];
  21468. cell.v = datenum(parseDate(cell.v)); cell.t = 'n';
  21469. break;
  21470. /* falls through */
  21471. case 'n': case 'e': vv = ''+cell.v; break;
  21472. default: vv = cell.v; break;
  21473. }
  21474. var o = ({r:R, c:C});
  21475. /* TODO: cell style */
  21476. o.s = get_cell_style(opts.cellXfs, cell, opts);
  21477. if(cell.l) ws['!links'].push([encode_cell(o), cell.l]);
  21478. if(cell.c) ws['!comments'].push([encode_cell(o), cell.c]);
  21479. switch(cell.t) {
  21480. case 's': case 'str':
  21481. if(opts.bookSST) {
  21482. vv = get_sst_id(opts.Strings, (cell.v), opts.revStrings);
  21483. o.t = "s"; o.v = vv;
  21484. write_record(ba, "BrtCellIsst", write_BrtCellIsst(cell, o));
  21485. } else {
  21486. o.t = "str";
  21487. write_record(ba, "BrtCellSt", write_BrtCellSt(cell, o));
  21488. }
  21489. return;
  21490. case 'n':
  21491. /* TODO: determine threshold for Real vs RK */
  21492. if(cell.v == (cell.v | 0) && cell.v > -1000 && cell.v < 1000) write_record(ba, "BrtCellRk", write_BrtCellRk(cell, o));
  21493. else write_record(ba, "BrtCellReal", write_BrtCellReal(cell, o));
  21494. return;
  21495. case 'b':
  21496. o.t = "b";
  21497. write_record(ba, "BrtCellBool", write_BrtCellBool(cell, o));
  21498. return;
  21499. case 'e': /* TODO: error */ o.t = "e"; break;
  21500. }
  21501. write_record(ba, "BrtCellBlank", write_BrtCellBlank(cell, o));
  21502. }
  21503. function write_CELLTABLE(ba, ws, idx, opts) {
  21504. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  21505. write_record(ba, 'BrtBeginSheetData');
  21506. var dense = Array.isArray(ws);
  21507. var cap = range.e.r;
  21508. if(ws['!rows']) cap = Math.max(range.e.r, ws['!rows'].length - 1);
  21509. for(var R = range.s.r; R <= cap; ++R) {
  21510. rr = encode_row(R);
  21511. /* [ACCELLTABLE] */
  21512. /* BrtRowHdr */
  21513. write_row_header(ba, ws, range, R);
  21514. if(R <= range.e.r) for(var C = range.s.c; C <= range.e.c; ++C) {
  21515. /* *16384CELL */
  21516. if(R === range.s.r) cols[C] = encode_col(C);
  21517. ref = cols[C] + rr;
  21518. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  21519. if(!cell) continue;
  21520. /* write cell */
  21521. write_ws_bin_cell(ba, cell, R, C, opts, ws);
  21522. }
  21523. }
  21524. write_record(ba, 'BrtEndSheetData');
  21525. }
  21526. function write_MERGECELLS(ba, ws) {
  21527. if(!ws || !ws['!merges']) return;
  21528. write_record(ba, 'BrtBeginMergeCells', write_BrtBeginMergeCells(ws['!merges'].length));
  21529. ws['!merges'].forEach(function(m) { write_record(ba, 'BrtMergeCell', write_BrtMergeCell(m)); });
  21530. write_record(ba, 'BrtEndMergeCells');
  21531. }
  21532. function write_COLINFOS(ba, ws) {
  21533. if(!ws || !ws['!cols']) return;
  21534. write_record(ba, 'BrtBeginColInfos');
  21535. ws['!cols'].forEach(function(m, i) { if(m) write_record(ba, 'BrtColInfo', write_BrtColInfo(i, m)); });
  21536. write_record(ba, 'BrtEndColInfos');
  21537. }
  21538. function write_IGNOREECS(ba, ws) {
  21539. if(!ws || !ws['!ref']) return;
  21540. write_record(ba, 'BrtBeginCellIgnoreECs');
  21541. write_record(ba, 'BrtCellIgnoreEC', write_BrtCellIgnoreEC(safe_decode_range(ws['!ref'])));
  21542. write_record(ba, 'BrtEndCellIgnoreECs');
  21543. }
  21544. function write_HLINKS(ba, ws, rels) {
  21545. /* *BrtHLink */
  21546. ws['!links'].forEach(function(l) {
  21547. if(!l[1].Target) return;
  21548. var rId = add_rels(rels, -1, l[1].Target.replace(/#.*$/, ""), RELS.HLINK);
  21549. write_record(ba, "BrtHLink", write_BrtHLink(l, rId));
  21550. });
  21551. delete ws['!links'];
  21552. }
  21553. function write_LEGACYDRAWING(ba, ws, idx, rels) {
  21554. /* [BrtLegacyDrawing] */
  21555. if(ws['!comments'].length > 0) {
  21556. var rId = add_rels(rels, -1, "../drawings/vmlDrawing" + (idx+1) + ".vml", RELS.VML);
  21557. write_record(ba, "BrtLegacyDrawing", write_RelID("rId" + rId));
  21558. ws['!legacy'] = rId;
  21559. }
  21560. }
  21561. function write_AUTOFILTER(ba, ws, wb, idx) {
  21562. if(!ws['!autofilter']) return;
  21563. var data = ws['!autofilter'];
  21564. var ref = typeof data.ref === "string" ? data.ref : encode_range(data.ref);
  21565. /* Update FilterDatabase defined name for the worksheet */
  21566. if(!wb.Workbook) wb.Workbook = ({Sheets:[]});
  21567. if(!wb.Workbook.Names) wb.Workbook.Names = [];
  21568. var names = wb.Workbook.Names;
  21569. var range = decode_range(ref);
  21570. if(range.s.r == range.e.r) { range.e.r = decode_range(ws["!ref"]).e.r; ref = encode_range(range); }
  21571. for(var i = 0; i < names.length; ++i) {
  21572. var name = names[i];
  21573. if(name.Name != '_xlnm._FilterDatabase') continue;
  21574. if(name.Sheet != idx) continue;
  21575. name.Ref = "'" + wb.SheetNames[idx] + "'!" + ref; break;
  21576. }
  21577. if(i == names.length) names.push({ Name: '_xlnm._FilterDatabase', Sheet: idx, Ref: "'" + wb.SheetNames[idx] + "'!" + ref });
  21578. write_record(ba, "BrtBeginAFilter", write_UncheckedRfX(safe_decode_range(ref)));
  21579. /* *FILTERCOLUMN */
  21580. /* [SORTSTATE] */
  21581. /* BrtEndAFilter */
  21582. write_record(ba, "BrtEndAFilter");
  21583. }
  21584. function write_WSVIEWS2(ba, ws, Workbook) {
  21585. write_record(ba, "BrtBeginWsViews");
  21586. { /* 1*WSVIEW2 */
  21587. /* [ACUID] */
  21588. write_record(ba, "BrtBeginWsView", write_BrtBeginWsView(ws, Workbook));
  21589. /* [BrtPane] */
  21590. /* *4BrtSel */
  21591. /* *4SXSELECT */
  21592. /* *FRT */
  21593. write_record(ba, "BrtEndWsView");
  21594. }
  21595. /* *FRT */
  21596. write_record(ba, "BrtEndWsViews");
  21597. }
  21598. function write_WSFMTINFO() {
  21599. /* [ACWSFMTINFO] */
  21600. //write_record(ba, "BrtWsFmtInfo", write_BrtWsFmtInfo(ws));
  21601. }
  21602. function write_SHEETPROTECT(ba, ws) {
  21603. if(!ws['!protect']) return;
  21604. /* [BrtSheetProtectionIso] */
  21605. write_record(ba, "BrtSheetProtection", write_BrtSheetProtection(ws['!protect']));
  21606. }
  21607. function write_ws_bin(idx, opts, wb, rels) {
  21608. var ba = buf_array();
  21609. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  21610. var c = s; try { if(wb && wb.Workbook) c = wb.Workbook.Sheets[idx].CodeName || c; } catch(e) {}
  21611. var r = safe_decode_range(ws['!ref'] || "A1");
  21612. if(r.e.c > 0x3FFF || r.e.r > 0xFFFFF) {
  21613. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:XFD1048576");
  21614. r.e.c = Math.min(r.e.c, 0x3FFF);
  21615. r.e.r = Math.min(r.e.c, 0xFFFFF);
  21616. }
  21617. ws['!links'] = [];
  21618. /* passed back to write_zip and removed there */
  21619. ws['!comments'] = [];
  21620. write_record(ba, "BrtBeginSheet");
  21621. if(wb.vbaraw) write_record(ba, "BrtWsProp", write_BrtWsProp(c));
  21622. write_record(ba, "BrtWsDim", write_BrtWsDim(r));
  21623. write_WSVIEWS2(ba, ws, wb.Workbook);
  21624. write_WSFMTINFO(ba, ws);
  21625. write_COLINFOS(ba, ws, idx, opts, wb);
  21626. write_CELLTABLE(ba, ws, idx, opts, wb);
  21627. /* [BrtSheetCalcProp] */
  21628. write_SHEETPROTECT(ba, ws);
  21629. /* *([BrtRangeProtectionIso] BrtRangeProtection) */
  21630. /* [SCENMAN] */
  21631. write_AUTOFILTER(ba, ws, wb, idx);
  21632. /* [SORTSTATE] */
  21633. /* [DCON] */
  21634. /* [USERSHVIEWS] */
  21635. write_MERGECELLS(ba, ws);
  21636. /* [BrtPhoneticInfo] */
  21637. /* *CONDITIONALFORMATTING */
  21638. /* [DVALS] */
  21639. write_HLINKS(ba, ws, rels);
  21640. /* [BrtPrintOptions] */
  21641. if(ws['!margins']) write_record(ba, "BrtMargins", write_BrtMargins(ws['!margins']));
  21642. /* [BrtPageSetup] */
  21643. /* [HEADERFOOTER] */
  21644. /* [RWBRK] */
  21645. /* [COLBRK] */
  21646. /* *BrtBigName */
  21647. /* [CELLWATCHES] */
  21648. if(!opts || opts.ignoreEC || (opts.ignoreEC == (void 0))) write_IGNOREECS(ba, ws);
  21649. /* [SMARTTAGS] */
  21650. /* [BrtDrawing] */
  21651. write_LEGACYDRAWING(ba, ws, idx, rels);
  21652. /* [BrtLegacyDrawingHF] */
  21653. /* [BrtBkHim] */
  21654. /* [OLEOBJECTS] */
  21655. /* [ACTIVEXCONTROLS] */
  21656. /* [WEBPUBITEMS] */
  21657. /* [LISTPARTS] */
  21658. /* FRTWORKSHEET */
  21659. write_record(ba, "BrtEndSheet");
  21660. return ba.end();
  21661. }
  21662. RELS.CHART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";
  21663. RELS.CHARTEX = "http://schemas.microsoft.com/office/2014/relationships/chartEx";
  21664. function parse_Cache(data) {
  21665. var col = [];
  21666. var num = data.match(/^<c:numCache>/);
  21667. var f;
  21668. /* 21.2.2.150 pt CT_NumVal */
  21669. (data.match(/<c:pt idx="(\d*)">(.*?)<\/c:pt>/mg)||[]).forEach(function(pt) {
  21670. var q = pt.match(/<c:pt idx="(\d*?)"><c:v>(.*)<\/c:v><\/c:pt>/);
  21671. if(!q) return;
  21672. col[+q[1]] = num ? +q[2] : q[2];
  21673. });
  21674. /* 21.2.2.71 formatCode CT_Xstring */
  21675. var nf = unescapexml((data.match(/<c:formatCode>([\s\S]*?)<\/c:formatCode>/) || ["","General"])[1]);
  21676. (data.match(/<c:f>(.*?)<\/c:f>/mg)||[]).forEach(function(F) { f = F.replace(/<.*?>/g,""); });
  21677. return [col, nf, f];
  21678. }
  21679. /* 21.2 DrawingML - Charts */
  21680. function parse_chart(data, name, opts, rels, wb, csheet) {
  21681. var cs = ((csheet || {"!type":"chart"}));
  21682. if(!data) return csheet;
  21683. /* 21.2.2.27 chart CT_Chart */
  21684. var C = 0, R = 0, col = "A";
  21685. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  21686. /* 21.2.2.120 numCache CT_NumData */
  21687. (data.match(/<c:numCache>[\s\S]*?<\/c:numCache>/gm)||[]).forEach(function(nc) {
  21688. var cache = parse_Cache(nc);
  21689. refguess.s.r = refguess.s.c = 0;
  21690. refguess.e.c = C;
  21691. col = encode_col(C);
  21692. cache[0].forEach(function(n,i) {
  21693. cs[col + encode_row(i)] = {t:'n', v:n, z:cache[1] };
  21694. R = i;
  21695. });
  21696. if(refguess.e.r < R) refguess.e.r = R;
  21697. ++C;
  21698. });
  21699. if(C > 0) cs["!ref"] = encode_range(refguess);
  21700. return cs;
  21701. }
  21702. RELS.CS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet";
  21703. var CS_XML_ROOT = writextag('chartsheet', null, {
  21704. 'xmlns': XMLNS.main[0],
  21705. 'xmlns:r': XMLNS.r
  21706. });
  21707. /* 18.3 Worksheets also covers Chartsheets */
  21708. function parse_cs_xml(data, opts, idx, rels, wb) {
  21709. if(!data) return data;
  21710. /* 18.3.1.12 chartsheet CT_ChartSheet */
  21711. if(!rels) rels = {'!id':{}};
  21712. var s = ({'!type':"chart", '!drawel':null, '!rel':""});
  21713. var m;
  21714. /* 18.3.1.83 sheetPr CT_ChartsheetPr */
  21715. var sheetPr = data.match(sheetprregex);
  21716. if(sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s, wb, idx);
  21717. /* 18.3.1.36 drawing CT_Drawing */
  21718. if((m = data.match(/drawing r:id="(.*?)"/))) s['!rel'] = m[1];
  21719. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  21720. return s;
  21721. }
  21722. function write_cs_xml(idx, opts, wb, rels) {
  21723. var o = [XML_HEADER, CS_XML_ROOT];
  21724. o[o.length] = writextag("drawing", null, {"r:id": "rId1"});
  21725. add_rels(rels, -1, "../drawings/drawing" + (idx+1) + ".xml", RELS.DRAW);
  21726. if(o.length>2) { o[o.length] = ('</chartsheet>'); o[1]=o[1].replace("/>",">"); }
  21727. return o.join("");
  21728. }
  21729. /* [MS-XLSB] 2.4.331 BrtCsProp */
  21730. function parse_BrtCsProp(data, length) {
  21731. data.l += 10;
  21732. var name = parse_XLWideString(data, length - 10);
  21733. return { name: name };
  21734. }
  21735. /* [MS-XLSB] 2.1.7.7 Chart Sheet */
  21736. function parse_cs_bin(data, opts, idx, rels, wb) {
  21737. if(!data) return data;
  21738. if(!rels) rels = {'!id':{}};
  21739. var s = {'!type':"chart", '!drawel':null, '!rel':""};
  21740. var state = [];
  21741. var pass = false;
  21742. recordhopper(data, function cs_parse(val, R_n, RT) {
  21743. switch(RT) {
  21744. case 0x0226: /* 'BrtDrawing' */
  21745. s['!rel'] = val; break;
  21746. case 0x028B: /* 'BrtCsProp' */
  21747. if(!wb.Sheets[idx]) wb.Sheets[idx] = {};
  21748. if(val.name) wb.Sheets[idx].CodeName = val.name;
  21749. break;
  21750. case 0x0232: /* 'BrtBkHim' */
  21751. case 0x028C: /* 'BrtCsPageSetup' */
  21752. case 0x029D: /* 'BrtCsProtection' */
  21753. case 0x02A7: /* 'BrtCsProtectionIso' */
  21754. case 0x0227: /* 'BrtLegacyDrawing' */
  21755. case 0x0228: /* 'BrtLegacyDrawingHF' */
  21756. case 0x01DC: /* 'BrtMargins' */
  21757. case 0x0C00: /* 'BrtUid' */
  21758. break;
  21759. case 0x0023: /* 'BrtFRTBegin' */
  21760. pass = true; break;
  21761. case 0x0024: /* 'BrtFRTEnd' */
  21762. pass = false; break;
  21763. case 0x0025: /* 'BrtACBegin' */
  21764. state.push(R_n); break;
  21765. case 0x0026: /* 'BrtACEnd' */
  21766. state.pop(); break;
  21767. default:
  21768. if((R_n||"").indexOf("Begin") > 0) state.push(R_n);
  21769. else if((R_n||"").indexOf("End") > 0) state.pop();
  21770. else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
  21771. }
  21772. }, opts);
  21773. if(rels['!id'][s['!rel']]) s['!drawel'] = rels['!id'][s['!rel']];
  21774. return s;
  21775. }
  21776. function write_cs_bin() {
  21777. var ba = buf_array();
  21778. write_record(ba, "BrtBeginSheet");
  21779. /* [BrtCsProp] */
  21780. /* CSVIEWS */
  21781. /* [[BrtCsProtectionIso] BrtCsProtection] */
  21782. /* [USERCSVIEWS] */
  21783. /* [BrtMargins] */
  21784. /* [BrtCsPageSetup] */
  21785. /* [HEADERFOOTER] */
  21786. /* BrtDrawing */
  21787. /* [BrtLegacyDrawing] */
  21788. /* [BrtLegacyDrawingHF] */
  21789. /* [BrtBkHim] */
  21790. /* [WEBPUBITEMS] */
  21791. /* FRTCHARTSHEET */
  21792. write_record(ba, "BrtEndSheet");
  21793. return ba.end();
  21794. }
  21795. /* 18.2.28 (CT_WorkbookProtection) Defaults */
  21796. var WBPropsDef = [
  21797. ['allowRefreshQuery', false, "bool"],
  21798. ['autoCompressPictures', true, "bool"],
  21799. ['backupFile', false, "bool"],
  21800. ['checkCompatibility', false, "bool"],
  21801. ['CodeName', ''],
  21802. ['date1904', false, "bool"],
  21803. ['defaultThemeVersion', 0, "int"],
  21804. ['filterPrivacy', false, "bool"],
  21805. ['hidePivotFieldList', false, "bool"],
  21806. ['promptedSolutions', false, "bool"],
  21807. ['publishItems', false, "bool"],
  21808. ['refreshAllConnections', false, "bool"],
  21809. ['saveExternalLinkValues', true, "bool"],
  21810. ['showBorderUnselectedTables', true, "bool"],
  21811. ['showInkAnnotation', true, "bool"],
  21812. ['showObjects', 'all'],
  21813. ['showPivotChartFilter', false, "bool"],
  21814. ['updateLinks', 'userSet']
  21815. ];
  21816. /* 18.2.30 (CT_BookView) Defaults */
  21817. var WBViewDef = [
  21818. ['activeTab', 0, "int"],
  21819. ['autoFilterDateGrouping', true, "bool"],
  21820. ['firstSheet', 0, "int"],
  21821. ['minimized', false, "bool"],
  21822. ['showHorizontalScroll', true, "bool"],
  21823. ['showSheetTabs', true, "bool"],
  21824. ['showVerticalScroll', true, "bool"],
  21825. ['tabRatio', 600, "int"],
  21826. ['visibility', 'visible']
  21827. //window{Height,Width}, {x,y}Window
  21828. ];
  21829. /* 18.2.19 (CT_Sheet) Defaults */
  21830. var SheetDef = [
  21831. //['state', 'visible']
  21832. ];
  21833. /* 18.2.2 (CT_CalcPr) Defaults */
  21834. var CalcPrDef = [
  21835. ['calcCompleted', 'true'],
  21836. ['calcMode', 'auto'],
  21837. ['calcOnSave', 'true'],
  21838. ['concurrentCalc', 'true'],
  21839. ['fullCalcOnLoad', 'false'],
  21840. ['fullPrecision', 'true'],
  21841. ['iterate', 'false'],
  21842. ['iterateCount', '100'],
  21843. ['iterateDelta', '0.001'],
  21844. ['refMode', 'A1']
  21845. ];
  21846. /* 18.2.3 (CT_CustomWorkbookView) Defaults */
  21847. /*var CustomWBViewDef = [
  21848. ['autoUpdate', 'false'],
  21849. ['changesSavedWin', 'false'],
  21850. ['includeHiddenRowCol', 'true'],
  21851. ['includePrintSettings', 'true'],
  21852. ['maximized', 'false'],
  21853. ['minimized', 'false'],
  21854. ['onlySync', 'false'],
  21855. ['personalView', 'false'],
  21856. ['showComments', 'commIndicator'],
  21857. ['showFormulaBar', 'true'],
  21858. ['showHorizontalScroll', 'true'],
  21859. ['showObjects', 'all'],
  21860. ['showSheetTabs', 'true'],
  21861. ['showStatusbar', 'true'],
  21862. ['showVerticalScroll', 'true'],
  21863. ['tabRatio', '600'],
  21864. ['xWindow', '0'],
  21865. ['yWindow', '0']
  21866. ];*/
  21867. function push_defaults_array(target, defaults) {
  21868. for(var j = 0; j != target.length; ++j) { var w = target[j];
  21869. for(var i=0; i != defaults.length; ++i) { var z = defaults[i];
  21870. if(w[z[0]] == null) w[z[0]] = z[1];
  21871. else switch(z[2]) {
  21872. case "bool": if(typeof w[z[0]] == "string") w[z[0]] = parsexmlbool(w[z[0]]); break;
  21873. case "int": if(typeof w[z[0]] == "string") w[z[0]] = parseInt(w[z[0]], 10); break;
  21874. }
  21875. }
  21876. }
  21877. }
  21878. function push_defaults(target, defaults) {
  21879. for(var i = 0; i != defaults.length; ++i) { var z = defaults[i];
  21880. if(target[z[0]] == null) target[z[0]] = z[1];
  21881. else switch(z[2]) {
  21882. case "bool": if(typeof target[z[0]] == "string") target[z[0]] = parsexmlbool(target[z[0]]); break;
  21883. case "int": if(typeof target[z[0]] == "string") target[z[0]] = parseInt(target[z[0]], 10); break;
  21884. }
  21885. }
  21886. }
  21887. function parse_wb_defaults(wb) {
  21888. push_defaults(wb.WBProps, WBPropsDef);
  21889. push_defaults(wb.CalcPr, CalcPrDef);
  21890. push_defaults_array(wb.WBView, WBViewDef);
  21891. push_defaults_array(wb.Sheets, SheetDef);
  21892. _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904);
  21893. }
  21894. function safe1904(wb) {
  21895. /* TODO: store date1904 somewhere else */
  21896. if(!wb.Workbook) return "false";
  21897. if(!wb.Workbook.WBProps) return "false";
  21898. return parsexmlbool(wb.Workbook.WBProps.date1904) ? "true" : "false";
  21899. }
  21900. var badchars = "][*?\/\\".split("");
  21901. function check_ws_name(n, safe) {
  21902. if(n.length > 31) { if(safe) return false; throw new Error("Sheet names cannot exceed 31 chars"); }
  21903. var _good = true;
  21904. badchars.forEach(function(c) {
  21905. if(n.indexOf(c) == -1) return;
  21906. if(!safe) throw new Error("Sheet name cannot contain : \\ / ? * [ ]");
  21907. _good = false;
  21908. });
  21909. return _good;
  21910. }
  21911. function check_wb_names(N, S, codes) {
  21912. N.forEach(function(n,i) {
  21913. check_ws_name(n);
  21914. for(var j = 0; j < i; ++j) if(n == N[j]) throw new Error("Duplicate Sheet Name: " + n);
  21915. if(codes) {
  21916. var cn = (S && S[i] && S[i].CodeName) || n;
  21917. if(cn.charCodeAt(0) == 95 && cn.length > 22) throw new Error("Bad Code Name: Worksheet" + cn);
  21918. }
  21919. });
  21920. }
  21921. function check_wb(wb) {
  21922. if(!wb || !wb.SheetNames || !wb.Sheets) throw new Error("Invalid Workbook");
  21923. if(!wb.SheetNames.length) throw new Error("Workbook is empty");
  21924. var Sheets = (wb.Workbook && wb.Workbook.Sheets) || [];
  21925. check_wb_names(wb.SheetNames, Sheets, !!wb.vbaraw);
  21926. for(var i = 0; i < wb.SheetNames.length; ++i) check_ws(wb.Sheets[wb.SheetNames[i]], wb.SheetNames[i], i);
  21927. /* TODO: validate workbook */
  21928. }
  21929. /* 18.2 Workbook */
  21930. var wbnsregex = /<\w+:workbook/;
  21931. function parse_wb_xml(data, opts) {
  21932. if(!data) throw new Error("Could not find file");
  21933. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, Names:[], xmlns: "" };
  21934. var pass = false, xmlns = "xmlns";
  21935. var dname = {}, dnstart = 0;
  21936. data.replace(tagregex, function xml_wb(x, idx) {
  21937. var y = parsexmltag(x);
  21938. switch(strip_ns(y[0])) {
  21939. case '<?xml': break;
  21940. /* 18.2.27 workbook CT_Workbook 1 */
  21941. case '<workbook':
  21942. if(x.match(wbnsregex)) xmlns = "xmlns" + x.match(/<(\w+):/)[1];
  21943. wb.xmlns = y[xmlns];
  21944. break;
  21945. case '</workbook>': break;
  21946. /* 18.2.13 fileVersion CT_FileVersion ? */
  21947. case '<fileVersion': delete y[0]; wb.AppVersion = y; break;
  21948. case '<fileVersion/>': case '</fileVersion>': break;
  21949. /* 18.2.12 fileSharing CT_FileSharing ? */
  21950. case '<fileSharing':
  21951. break;
  21952. case '<fileSharing/>': break;
  21953. /* 18.2.28 workbookPr CT_WorkbookPr ? */
  21954. case '<workbookPr':
  21955. case '<workbookPr/>':
  21956. WBPropsDef.forEach(function(w) {
  21957. if(y[w[0]] == null) return;
  21958. switch(w[2]) {
  21959. case "bool": wb.WBProps[w[0]] = parsexmlbool(y[w[0]]); break;
  21960. case "int": wb.WBProps[w[0]] = parseInt(y[w[0]], 10); break;
  21961. default: wb.WBProps[w[0]] = y[w[0]];
  21962. }
  21963. });
  21964. if(y.codeName) wb.WBProps.CodeName = utf8read(y.codeName);
  21965. break;
  21966. case '</workbookPr>': break;
  21967. /* 18.2.29 workbookProtection CT_WorkbookProtection ? */
  21968. case '<workbookProtection':
  21969. break;
  21970. case '<workbookProtection/>': break;
  21971. /* 18.2.1 bookViews CT_BookViews ? */
  21972. case '<bookViews': case '<bookViews>': case '</bookViews>': break;
  21973. /* 18.2.30 workbookView CT_BookView + */
  21974. case '<workbookView': case '<workbookView/>': delete y[0]; wb.WBView.push(y); break;
  21975. case '</workbookView>': break;
  21976. /* 18.2.20 sheets CT_Sheets 1 */
  21977. case '<sheets': case '<sheets>': case '</sheets>': break; // aggregate sheet
  21978. /* 18.2.19 sheet CT_Sheet + */
  21979. case '<sheet':
  21980. switch(y.state) {
  21981. case "hidden": y.Hidden = 1; break;
  21982. case "veryHidden": y.Hidden = 2; break;
  21983. default: y.Hidden = 0;
  21984. }
  21985. delete y.state;
  21986. y.name = unescapexml(utf8read(y.name));
  21987. delete y[0]; wb.Sheets.push(y); break;
  21988. case '</sheet>': break;
  21989. /* 18.2.15 functionGroups CT_FunctionGroups ? */
  21990. case '<functionGroups': case '<functionGroups/>': break;
  21991. /* 18.2.14 functionGroup CT_FunctionGroup + */
  21992. case '<functionGroup': break;
  21993. /* 18.2.9 externalReferences CT_ExternalReferences ? */
  21994. case '<externalReferences': case '</externalReferences>': case '<externalReferences>': break;
  21995. /* 18.2.8 externalReference CT_ExternalReference + */
  21996. case '<externalReference': break;
  21997. /* 18.2.6 definedNames CT_DefinedNames ? */
  21998. case '<definedNames/>': break;
  21999. case '<definedNames>': case '<definedNames': pass=true; break;
  22000. case '</definedNames>': pass=false; break;
  22001. /* 18.2.5 definedName CT_DefinedName + */
  22002. case '<definedName': {
  22003. dname = {};
  22004. dname.Name = utf8read(y.name);
  22005. if(y.comment) dname.Comment = y.comment;
  22006. if(y.localSheetId) dname.Sheet = +y.localSheetId;
  22007. if(parsexmlbool(y.hidden||"0")) dname.Hidden = true;
  22008. dnstart = idx + x.length;
  22009. } break;
  22010. case '</definedName>': {
  22011. dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx)));
  22012. wb.Names.push(dname);
  22013. } break;
  22014. case '<definedName/>': break;
  22015. /* 18.2.2 calcPr CT_CalcPr ? */
  22016. case '<calcPr': delete y[0]; wb.CalcPr = y; break;
  22017. case '<calcPr/>': delete y[0]; wb.CalcPr = y; break;
  22018. case '</calcPr>': break;
  22019. /* 18.2.16 oleSize CT_OleSize ? (ref required) */
  22020. case '<oleSize': break;
  22021. /* 18.2.4 customWorkbookViews CT_CustomWorkbookViews ? */
  22022. case '<customWorkbookViews>': case '</customWorkbookViews>': case '<customWorkbookViews': break;
  22023. /* 18.2.3 customWorkbookView CT_CustomWorkbookView + */
  22024. case '<customWorkbookView': case '</customWorkbookView>': break;
  22025. /* 18.2.18 pivotCaches CT_PivotCaches ? */
  22026. case '<pivotCaches>': case '</pivotCaches>': case '<pivotCaches': break;
  22027. /* 18.2.17 pivotCache CT_PivotCache ? */
  22028. case '<pivotCache': break;
  22029. /* 18.2.21 smartTagPr CT_SmartTagPr ? */
  22030. case '<smartTagPr': case '<smartTagPr/>': break;
  22031. /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */
  22032. case '<smartTagTypes': case '<smartTagTypes>': case '</smartTagTypes>': break;
  22033. /* 18.2.22 smartTagType CT_SmartTagType ? */
  22034. case '<smartTagType': break;
  22035. /* 18.2.24 webPublishing CT_WebPublishing ? */
  22036. case '<webPublishing': case '<webPublishing/>': break;
  22037. /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */
  22038. case '<fileRecoveryPr': case '<fileRecoveryPr/>': break;
  22039. /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */
  22040. case '<webPublishObjects>': case '<webPublishObjects': case '</webPublishObjects>': break;
  22041. /* 18.2.25 webPublishObject CT_WebPublishObject ? */
  22042. case '<webPublishObject': break;
  22043. /* 18.2.10 extLst CT_ExtensionList ? */
  22044. case '<extLst': case '<extLst>': case '</extLst>': case '<extLst/>': break;
  22045. /* 18.2.7 ext CT_Extension + */
  22046. case '<ext': pass=true; break; //TODO: check with versions of excel
  22047. case '</ext>': pass=false; break;
  22048. /* Others */
  22049. case '<ArchID': break;
  22050. case '<AlternateContent':
  22051. case '<AlternateContent>': pass=true; break;
  22052. case '</AlternateContent>': pass=false; break;
  22053. /* TODO */
  22054. case '<revisionPtr': break;
  22055. default: if(!pass && opts.WTF) throw new Error('unrecognized ' + y[0] + ' in workbook');
  22056. }
  22057. return x;
  22058. });
  22059. if(XMLNS.main.indexOf(wb.xmlns) === -1) throw new Error("Unknown Namespace: " + wb.xmlns);
  22060. parse_wb_defaults(wb);
  22061. return wb;
  22062. }
  22063. var WB_XML_ROOT = writextag('workbook', null, {
  22064. 'xmlns': XMLNS.main[0],
  22065. //'xmlns:mx': XMLNS.mx,
  22066. //'xmlns:s': XMLNS.main[0],
  22067. 'xmlns:r': XMLNS.r
  22068. });
  22069. function write_wb_xml(wb) {
  22070. var o = [XML_HEADER];
  22071. o[o.length] = WB_XML_ROOT;
  22072. var write_names = (wb.Workbook && (wb.Workbook.Names||[]).length > 0);
  22073. /* fileVersion */
  22074. /* fileSharing */
  22075. var workbookPr = ({codeName:"ThisWorkbook"});
  22076. if(wb.Workbook && wb.Workbook.WBProps) {
  22077. WBPropsDef.forEach(function(x) {
  22078. if((wb.Workbook.WBProps[x[0]]) == null) return;
  22079. if((wb.Workbook.WBProps[x[0]]) == x[1]) return;
  22080. workbookPr[x[0]] = (wb.Workbook.WBProps[x[0]]);
  22081. });
  22082. if(wb.Workbook.WBProps.CodeName) { workbookPr.codeName = wb.Workbook.WBProps.CodeName; delete workbookPr.CodeName; }
  22083. }
  22084. o[o.length] = (writextag('workbookPr', null, workbookPr));
  22085. /* workbookProtection */
  22086. var sheets = wb.Workbook && wb.Workbook.Sheets || [];
  22087. var i = 0;
  22088. /* bookViews only written if first worksheet is hidden */
  22089. if(sheets && sheets[0] && !!sheets[0].Hidden) {
  22090. o[o.length] = "<bookViews>";
  22091. for(i = 0; i != wb.SheetNames.length; ++i) {
  22092. if(!sheets[i]) break;
  22093. if(!sheets[i].Hidden) break;
  22094. }
  22095. if(i == wb.SheetNames.length) i = 0;
  22096. o[o.length] = '<workbookView firstSheet="' + i + '" activeTab="' + i + '"/>';
  22097. o[o.length] = "</bookViews>";
  22098. }
  22099. o[o.length] = "<sheets>";
  22100. for(i = 0; i != wb.SheetNames.length; ++i) {
  22101. var sht = ({name:escapexml(wb.SheetNames[i].slice(0,31))});
  22102. sht.sheetId = ""+(i+1);
  22103. sht["r:id"] = "rId"+(i+1);
  22104. if(sheets[i]) switch(sheets[i].Hidden) {
  22105. case 1: sht.state = "hidden"; break;
  22106. case 2: sht.state = "veryHidden"; break;
  22107. }
  22108. o[o.length] = (writextag('sheet',null,sht));
  22109. }
  22110. o[o.length] = "</sheets>";
  22111. /* functionGroups */
  22112. /* externalReferences */
  22113. if(write_names) {
  22114. o[o.length] = "<definedNames>";
  22115. if(wb.Workbook && wb.Workbook.Names) wb.Workbook.Names.forEach(function(n) {
  22116. var d = {name:n.Name};
  22117. if(n.Comment) d.comment = n.Comment;
  22118. if(n.Sheet != null) d.localSheetId = ""+n.Sheet;
  22119. if(n.Hidden) d.hidden = "1";
  22120. if(!n.Ref) return;
  22121. o[o.length] = writextag('definedName', escapexml(n.Ref), d);
  22122. });
  22123. o[o.length] = "</definedNames>";
  22124. }
  22125. /* calcPr */
  22126. /* oleSize */
  22127. /* customWorkbookViews */
  22128. /* pivotCaches */
  22129. /* smartTagPr */
  22130. /* smartTagTypes */
  22131. /* webPublishing */
  22132. /* fileRecoveryPr */
  22133. /* webPublishObjects */
  22134. /* extLst */
  22135. if(o.length>2){ o[o.length] = '</workbook>'; o[1]=o[1].replace("/>",">"); }
  22136. return o.join("");
  22137. }
  22138. /* [MS-XLSB] 2.4.304 BrtBundleSh */
  22139. function parse_BrtBundleSh(data, length) {
  22140. var z = {};
  22141. z.Hidden = data.read_shift(4); //hsState ST_SheetState
  22142. z.iTabID = data.read_shift(4);
  22143. z.strRelID = parse_RelID(data,length-8);
  22144. z.name = parse_XLWideString(data);
  22145. return z;
  22146. }
  22147. function write_BrtBundleSh(data, o) {
  22148. if(!o) o = new_buf(127);
  22149. o.write_shift(4, data.Hidden);
  22150. o.write_shift(4, data.iTabID);
  22151. write_RelID(data.strRelID, o);
  22152. write_XLWideString(data.name.slice(0,31), o);
  22153. return o.length > o.l ? o.slice(0, o.l) : o;
  22154. }
  22155. /* [MS-XLSB] 2.4.815 BrtWbProp */
  22156. function parse_BrtWbProp(data, length) {
  22157. var o = ({});
  22158. var flags = data.read_shift(4);
  22159. o.defaultThemeVersion = data.read_shift(4);
  22160. var strName = (length > 8) ? parse_XLWideString(data) : "";
  22161. if(strName.length > 0) o.CodeName = strName;
  22162. o.autoCompressPictures = !!(flags & 0x10000);
  22163. o.backupFile = !!(flags & 0x40);
  22164. o.checkCompatibility = !!(flags & 0x1000);
  22165. o.date1904 = !!(flags & 0x01);
  22166. o.filterPrivacy = !!(flags & 0x08);
  22167. o.hidePivotFieldList = !!(flags & 0x400);
  22168. o.promptedSolutions = !!(flags & 0x10);
  22169. o.publishItems = !!(flags & 0x800);
  22170. o.refreshAllConnections = !!(flags & 0x40000);
  22171. o.saveExternalLinkValues = !!(flags & 0x80);
  22172. o.showBorderUnselectedTables = !!(flags & 0x04);
  22173. o.showInkAnnotation = !!(flags & 0x20);
  22174. o.showObjects = ["all", "placeholders", "none"][(flags >> 13) & 0x03];
  22175. o.showPivotChartFilter = !!(flags & 0x8000);
  22176. o.updateLinks = ["userSet", "never", "always"][(flags >> 8) & 0x03];
  22177. return o;
  22178. }
  22179. function write_BrtWbProp(data, o) {
  22180. if(!o) o = new_buf(72);
  22181. var flags = 0;
  22182. if(data) {
  22183. /* TODO: mirror parse_BrtWbProp fields */
  22184. if(data.filterPrivacy) flags |= 0x08;
  22185. }
  22186. o.write_shift(4, flags);
  22187. o.write_shift(4, 0);
  22188. write_XLSBCodeName(data && data.CodeName || "ThisWorkbook", o);
  22189. return o.slice(0, o.l);
  22190. }
  22191. function parse_BrtFRTArchID$(data, length) {
  22192. var o = {};
  22193. data.read_shift(4);
  22194. o.ArchID = data.read_shift(4);
  22195. data.l += length - 8;
  22196. return o;
  22197. }
  22198. /* [MS-XLSB] 2.4.687 BrtName */
  22199. function parse_BrtName(data, length, opts) {
  22200. var end = data.l + length;
  22201. data.l += 4; //var flags = data.read_shift(4);
  22202. data.l += 1; //var chKey = data.read_shift(1);
  22203. var itab = data.read_shift(4);
  22204. var name = parse_XLNameWideString(data);
  22205. var formula = parse_XLSBNameParsedFormula(data, 0, opts);
  22206. var comment = parse_XLNullableWideString(data);
  22207. //if(0 /* fProc */) {
  22208. // unusedstring1: XLNullableWideString
  22209. // description: XLNullableWideString
  22210. // helpTopic: XLNullableWideString
  22211. // unusedstring2: XLNullableWideString
  22212. //}
  22213. data.l = end;
  22214. var out = ({Name:name, Ptg:formula});
  22215. if(itab < 0xFFFFFFF) out.Sheet = itab;
  22216. if(comment) out.Comment = comment;
  22217. return out;
  22218. }
  22219. /* [MS-XLSB] 2.1.7.61 Workbook */
  22220. function parse_wb_bin(data, opts) {
  22221. var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
  22222. var state = [];
  22223. var pass = false;
  22224. if(!opts) opts = {};
  22225. opts.biff = 12;
  22226. var Names = [];
  22227. var supbooks = ([[]]);
  22228. supbooks.SheetNames = [];
  22229. supbooks.XTI = [];
  22230. recordhopper(data, function hopper_wb(val, R_n, RT) {
  22231. switch(RT) {
  22232. case 0x009C: /* 'BrtBundleSh' */
  22233. supbooks.SheetNames.push(val.name);
  22234. wb.Sheets.push(val); break;
  22235. case 0x0099: /* 'BrtWbProp' */
  22236. wb.WBProps = val; break;
  22237. case 0x0027: /* 'BrtName' */
  22238. if(val.Sheet != null) opts.SID = val.Sheet;
  22239. val.Ref = stringify_formula(val.Ptg, null, null, supbooks, opts);
  22240. delete opts.SID;
  22241. delete val.Ptg;
  22242. Names.push(val);
  22243. break;
  22244. case 0x040C: /* 'BrtNameExt' */ break;
  22245. case 0x0165: /* 'BrtSupSelf' */
  22246. case 0x0166: /* 'BrtSupSame' */
  22247. case 0x0163: /* 'BrtSupBookSrc' */
  22248. case 0x029B: /* 'BrtSupAddin' */
  22249. if(!supbooks[0].length) supbooks[0] = [RT, val];
  22250. else supbooks.push([RT, val]);
  22251. supbooks[supbooks.length - 1].XTI = [];
  22252. break;
  22253. case 0x016A: /* 'BrtExternSheet' */
  22254. if(supbooks.length === 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  22255. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val);
  22256. supbooks.XTI = supbooks.XTI.concat(val);
  22257. break;
  22258. case 0x0169: /* 'BrtPlaceholderName' */
  22259. break;
  22260. /* case 'BrtModelTimeGroupingCalcCol' */
  22261. case 0x0C00: /* 'BrtUid' */
  22262. case 0x0C01: /* 'BrtRevisionPtr' */
  22263. case 0x0817: /* 'BrtAbsPath15' */
  22264. case 0x0216: /* 'BrtBookProtection' */
  22265. case 0x02A5: /* 'BrtBookProtectionIso' */
  22266. case 0x009E: /* 'BrtBookView' */
  22267. case 0x009D: /* 'BrtCalcProp' */
  22268. case 0x0262: /* 'BrtCrashRecErr' */
  22269. case 0x0802: /* 'BrtDecoupledPivotCacheID' */
  22270. case 0x009B: /* 'BrtFileRecover' */
  22271. case 0x0224: /* 'BrtFileSharing' */
  22272. case 0x02A4: /* 'BrtFileSharingIso' */
  22273. case 0x0080: /* 'BrtFileVersion' */
  22274. case 0x0299: /* 'BrtFnGroup' */
  22275. case 0x0850: /* 'BrtModelRelationship' */
  22276. case 0x084D: /* 'BrtModelTable' */
  22277. case 0x0225: /* 'BrtOleSize' */
  22278. case 0x0805: /* 'BrtPivotTableRef' */
  22279. case 0x0254: /* 'BrtSmartTagType' */
  22280. case 0x081C: /* 'BrtTableSlicerCacheID' */
  22281. case 0x081B: /* 'BrtTableSlicerCacheIDs' */
  22282. case 0x0822: /* 'BrtTimelineCachePivotCacheID' */
  22283. case 0x018D: /* 'BrtUserBookView' */
  22284. case 0x009A: /* 'BrtWbFactoid' */
  22285. case 0x045D: /* 'BrtWbProp14' */
  22286. case 0x0229: /* 'BrtWebOpt' */
  22287. case 0x082B: /* 'BrtWorkBookPr15' */
  22288. break;
  22289. case 0x0023: /* 'BrtFRTBegin' */
  22290. state.push(R_n); pass = true; break;
  22291. case 0x0024: /* 'BrtFRTEnd' */
  22292. state.pop(); pass = false; break;
  22293. case 0x0025: /* 'BrtACBegin' */
  22294. state.push(R_n); pass = true; break;
  22295. case 0x0026: /* 'BrtACEnd' */
  22296. state.pop(); pass = false; break;
  22297. case 0x0010: /* 'BrtFRTArchID$' */ break;
  22298. default:
  22299. if((R_n||"").indexOf("Begin") > 0){/* empty */}
  22300. else if((R_n||"").indexOf("End") > 0){/* empty */}
  22301. else if(!pass || (opts.WTF && state[state.length-1] != "BrtACBegin" && state[state.length-1] != "BrtFRTBegin")) throw new Error("Unexpected record " + RT + " " + R_n);
  22302. }
  22303. }, opts);
  22304. parse_wb_defaults(wb);
  22305. // $FlowIgnore
  22306. wb.Names = Names;
  22307. (wb).supbooks = supbooks;
  22308. return wb;
  22309. }
  22310. function write_BUNDLESHS(ba, wb) {
  22311. write_record(ba, "BrtBeginBundleShs");
  22312. for(var idx = 0; idx != wb.SheetNames.length; ++idx) {
  22313. var viz = wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx] && wb.Workbook.Sheets[idx].Hidden || 0;
  22314. var d = { Hidden: viz, iTabID: idx+1, strRelID: 'rId' + (idx+1), name: wb.SheetNames[idx] };
  22315. write_record(ba, "BrtBundleSh", write_BrtBundleSh(d));
  22316. }
  22317. write_record(ba, "BrtEndBundleShs");
  22318. }
  22319. /* [MS-XLSB] 2.4.649 BrtFileVersion */
  22320. function write_BrtFileVersion(data, o) {
  22321. if(!o) o = new_buf(127);
  22322. for(var i = 0; i != 4; ++i) o.write_shift(4, 0);
  22323. write_XLWideString("SheetJS", o);
  22324. write_XLWideString(XLSX2.version, o);
  22325. write_XLWideString(XLSX2.version, o);
  22326. write_XLWideString("7262", o);
  22327. o.length = o.l;
  22328. return o.length > o.l ? o.slice(0, o.l) : o;
  22329. }
  22330. /* [MS-XLSB] 2.4.301 BrtBookView */
  22331. function write_BrtBookView(idx, o) {
  22332. if(!o) o = new_buf(29);
  22333. o.write_shift(-4, 0);
  22334. o.write_shift(-4, 460);
  22335. o.write_shift(4, 28800);
  22336. o.write_shift(4, 17600);
  22337. o.write_shift(4, 500);
  22338. o.write_shift(4, idx);
  22339. o.write_shift(4, idx);
  22340. var flags = 0x78;
  22341. o.write_shift(1, flags);
  22342. return o.length > o.l ? o.slice(0, o.l) : o;
  22343. }
  22344. function write_BOOKVIEWS(ba, wb) {
  22345. /* required if hidden tab appears before visible tab */
  22346. if(!wb.Workbook || !wb.Workbook.Sheets) return;
  22347. var sheets = wb.Workbook.Sheets;
  22348. var i = 0, vistab = -1, hidden = -1;
  22349. for(; i < sheets.length; ++i) {
  22350. if(!sheets[i] || !sheets[i].Hidden && vistab == -1) vistab = i;
  22351. else if(sheets[i].Hidden == 1 && hidden == -1) hidden = i;
  22352. }
  22353. if(hidden > vistab) return;
  22354. write_record(ba, "BrtBeginBookViews");
  22355. write_record(ba, "BrtBookView", write_BrtBookView(vistab));
  22356. /* 1*(BrtBookView *FRT) */
  22357. write_record(ba, "BrtEndBookViews");
  22358. }
  22359. /* [MS-XLSB] 2.4.305 BrtCalcProp */
  22360. /*function write_BrtCalcProp(data, o) {
  22361. if(!o) o = new_buf(26);
  22362. o.write_shift(4,0); // force recalc
  22363. o.write_shift(4,1);
  22364. o.write_shift(4,0);
  22365. write_Xnum(0, o);
  22366. o.write_shift(-4, 1023);
  22367. o.write_shift(1, 0x33);
  22368. o.write_shift(1, 0x00);
  22369. return o;
  22370. }*/
  22371. /* [MS-XLSB] 2.4.646 BrtFileRecover */
  22372. /*function write_BrtFileRecover(data, o) {
  22373. if(!o) o = new_buf(1);
  22374. o.write_shift(1,0);
  22375. return o;
  22376. }*/
  22377. /* [MS-XLSB] 2.1.7.61 Workbook */
  22378. function write_wb_bin(wb, opts) {
  22379. var ba = buf_array();
  22380. write_record(ba, "BrtBeginBook");
  22381. write_record(ba, "BrtFileVersion", write_BrtFileVersion());
  22382. /* [[BrtFileSharingIso] BrtFileSharing] */
  22383. write_record(ba, "BrtWbProp", write_BrtWbProp(wb.Workbook && wb.Workbook.WBProps || null));
  22384. /* [ACABSPATH] */
  22385. /* [[BrtBookProtectionIso] BrtBookProtection] */
  22386. write_BOOKVIEWS(ba, wb, opts);
  22387. write_BUNDLESHS(ba, wb, opts);
  22388. /* [FNGROUP] */
  22389. /* [EXTERNALS] */
  22390. /* *BrtName */
  22391. /* write_record(ba, "BrtCalcProp", write_BrtCalcProp()); */
  22392. /* [BrtOleSize] */
  22393. /* *(BrtUserBookView *FRT) */
  22394. /* [PIVOTCACHEIDS] */
  22395. /* [BrtWbFactoid] */
  22396. /* [SMARTTAGTYPES] */
  22397. /* [BrtWebOpt] */
  22398. /* write_record(ba, "BrtFileRecover", write_BrtFileRecover()); */
  22399. /* [WEBPUBITEMS] */
  22400. /* [CRERRS] */
  22401. /* FRTWORKBOOK */
  22402. write_record(ba, "BrtEndBook");
  22403. return ba.end();
  22404. }
  22405. function parse_wb(data, name, opts) {
  22406. if(name.slice(-4)===".bin") return parse_wb_bin((data), opts);
  22407. return parse_wb_xml((data), opts);
  22408. }
  22409. function parse_ws(data, name, idx, opts, rels, wb, themes, styles) {
  22410. if(name.slice(-4)===".bin") return parse_ws_bin((data), opts, idx, rels, wb, themes, styles);
  22411. return parse_ws_xml((data), opts, idx, rels, wb, themes, styles);
  22412. }
  22413. function parse_cs(data, name, idx, opts, rels, wb, themes, styles) {
  22414. if(name.slice(-4)===".bin") return parse_cs_bin((data), opts, idx, rels, wb, themes, styles);
  22415. return parse_cs_xml((data), opts, idx, rels, wb, themes, styles);
  22416. }
  22417. function parse_ms(data, name, idx, opts, rels, wb, themes, styles) {
  22418. if(name.slice(-4)===".bin") return parse_ms_bin((data), opts, idx, rels, wb, themes, styles);
  22419. return parse_ms_xml((data), opts, idx, rels, wb, themes, styles);
  22420. }
  22421. function parse_ds(data, name, idx, opts, rels, wb, themes, styles) {
  22422. if(name.slice(-4)===".bin") return parse_ds_bin((data), opts, idx, rels, wb, themes, styles);
  22423. return parse_ds_xml((data), opts, idx, rels, wb, themes, styles);
  22424. }
  22425. function parse_sty(data, name, themes, opts) {
  22426. if(name.slice(-4)===".bin") return parse_sty_bin((data), themes, opts);
  22427. return parse_sty_xml((data), themes, opts);
  22428. }
  22429. function parse_theme(data, name, opts) {
  22430. return parse_theme_xml(data, opts);
  22431. }
  22432. function parse_sst(data, name, opts) {
  22433. if(name.slice(-4)===".bin") return parse_sst_bin((data), opts);
  22434. return parse_sst_xml((data), opts);
  22435. }
  22436. function parse_cmnt(data, name, opts) {
  22437. if(name.slice(-4)===".bin") return parse_comments_bin((data), opts);
  22438. return parse_comments_xml((data), opts);
  22439. }
  22440. function parse_cc(data, name, opts) {
  22441. if(name.slice(-4)===".bin") return parse_cc_bin((data), name, opts);
  22442. return parse_cc_xml((data), name, opts);
  22443. }
  22444. function parse_xlink(data, rel, name, opts) {
  22445. if(name.slice(-4)===".bin") return parse_xlink_bin((data), rel, name, opts);
  22446. return parse_xlink_xml((data), rel, name, opts);
  22447. }
  22448. function write_wb(wb, name, opts) {
  22449. return (name.slice(-4)===".bin" ? write_wb_bin : write_wb_xml)(wb, opts);
  22450. }
  22451. function write_ws(data, name, opts, wb, rels) {
  22452. return (name.slice(-4)===".bin" ? write_ws_bin : write_ws_xml)(data, opts, wb, rels);
  22453. }
  22454. // eslint-disable-next-line no-unused-vars
  22455. function write_cs(data, name, opts, wb, rels) {
  22456. return (name.slice(-4)===".bin" ? write_cs_bin : write_cs_xml)(data, opts, wb, rels);
  22457. }
  22458. function write_sty(data, name, opts) {
  22459. return (name.slice(-4)===".bin" ? write_sty_bin : write_sty_xml)(data, opts);
  22460. }
  22461. function write_sst(data, name, opts) {
  22462. return (name.slice(-4)===".bin" ? write_sst_bin : write_sst_xml)(data, opts);
  22463. }
  22464. function write_cmnt(data, name, opts) {
  22465. return (name.slice(-4)===".bin" ? write_comments_bin : write_comments_xml)(data, opts);
  22466. }
  22467. /*
  22468. function write_cc(data, name:string, opts) {
  22469. return (name.slice(-4)===".bin" ? write_cc_bin : write_cc_xml)(data, opts);
  22470. }
  22471. */
  22472. var attregexg2=/([\w:]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g;
  22473. var attregex2=/([\w:]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/;
  22474. function xlml_parsexmltag(tag, skip_root) {
  22475. var words = tag.split(/\s+/);
  22476. var z = ([]); if(!skip_root) z[0] = words[0];
  22477. if(words.length === 1) return z;
  22478. var m = tag.match(attregexg2), y, j, w, i;
  22479. if(m) for(i = 0; i != m.length; ++i) {
  22480. y = m[i].match(attregex2);
  22481. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  22482. else {
  22483. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  22484. else w = y[1].slice(j+1);
  22485. z[w] = y[2].slice(1,y[2].length-1);
  22486. }
  22487. }
  22488. return z;
  22489. }
  22490. function xlml_parsexmltagobj(tag) {
  22491. var words = tag.split(/\s+/);
  22492. var z = {};
  22493. if(words.length === 1) return z;
  22494. var m = tag.match(attregexg2), y, j, w, i;
  22495. if(m) for(i = 0; i != m.length; ++i) {
  22496. y = m[i].match(attregex2);
  22497. if((j=y[1].indexOf(":")) === -1) z[y[1]] = y[2].slice(1,y[2].length-1);
  22498. else {
  22499. if(y[1].slice(0,6) === "xmlns:") w = "xmlns"+y[1].slice(6);
  22500. else w = y[1].slice(j+1);
  22501. z[w] = y[2].slice(1,y[2].length-1);
  22502. }
  22503. }
  22504. return z;
  22505. }
  22506. // ----
  22507. function xlml_format(format, value) {
  22508. var fmt = XLMLFormatMap[format] || unescapexml(format);
  22509. if(fmt === "General") return SSF._general(value);
  22510. return SSF.format(fmt, value);
  22511. }
  22512. function xlml_set_custprop(Custprops, key, cp, val) {
  22513. var oval = val;
  22514. switch((cp[0].match(/dt:dt="([\w.]+)"/)||["",""])[1]) {
  22515. case "boolean": oval = parsexmlbool(val); break;
  22516. case "i2": case "int": oval = parseInt(val, 10); break;
  22517. case "r4": case "float": oval = parseFloat(val); break;
  22518. case "date": case "dateTime.tz": oval = parseDate(val); break;
  22519. case "i8": case "string": case "fixed": case "uuid": case "bin.base64": break;
  22520. default: throw new Error("bad custprop:" + cp[0]);
  22521. }
  22522. Custprops[unescapexml(key)] = oval;
  22523. }
  22524. function safe_format_xlml(cell, nf, o) {
  22525. if(cell.t === 'z') return;
  22526. if(!o || o.cellText !== false) try {
  22527. if(cell.t === 'e') { cell.w = cell.w || BErr[cell.v]; }
  22528. else if(nf === "General") {
  22529. if(cell.t === 'n') {
  22530. if((cell.v|0) === cell.v) cell.w = SSF._general_int(cell.v);
  22531. else cell.w = SSF._general_num(cell.v);
  22532. }
  22533. else cell.w = SSF._general(cell.v);
  22534. }
  22535. else cell.w = xlml_format(nf||"General", cell.v);
  22536. } catch(e) { if(o.WTF) throw e; }
  22537. try {
  22538. var z = XLMLFormatMap[nf]||nf||"General";
  22539. if(o.cellNF) cell.z = z;
  22540. if(o.cellDates && cell.t == 'n' && SSF.is_date(z)) {
  22541. var _d = SSF.parse_date_code(cell.v); if(_d) { cell.t = 'd'; cell.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  22542. }
  22543. } catch(e) { if(o.WTF) throw e; }
  22544. }
  22545. function process_style_xlml(styles, stag, opts) {
  22546. if(opts.cellStyles) {
  22547. if(stag.Interior) {
  22548. var I = stag.Interior;
  22549. if(I.Pattern) I.patternType = XLMLPatternTypeMap[I.Pattern] || I.Pattern;
  22550. }
  22551. }
  22552. styles[stag.ID] = stag;
  22553. }
  22554. /* TODO: there must exist some form of OSP-blessed spec */
  22555. function parse_xlml_data(xml, ss, data, cell, base, styles, csty, row, arrayf, o) {
  22556. var nf = "General", sid = cell.StyleID, S = {}; o = o || {};
  22557. var interiors = [];
  22558. var i = 0;
  22559. if(sid === undefined && row) sid = row.StyleID;
  22560. if(sid === undefined && csty) sid = csty.StyleID;
  22561. while(styles[sid] !== undefined) {
  22562. if(styles[sid].nf) nf = styles[sid].nf;
  22563. if(styles[sid].Interior) interiors.push(styles[sid].Interior);
  22564. if(!styles[sid].Parent) break;
  22565. sid = styles[sid].Parent;
  22566. }
  22567. switch(data.Type) {
  22568. case 'Boolean':
  22569. cell.t = 'b';
  22570. cell.v = parsexmlbool(xml);
  22571. break;
  22572. case 'String':
  22573. cell.t = 's'; cell.r = xlml_fixstr(unescapexml(xml));
  22574. cell.v = (xml.indexOf("<") > -1 ? unescapexml(ss||xml).replace(/<.*?>/g, "") : cell.r); // todo: BR etc
  22575. break;
  22576. case 'DateTime':
  22577. if(xml.slice(-1) != "Z") xml += "Z";
  22578. cell.v = (parseDate(xml) - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  22579. if(cell.v !== cell.v) cell.v = unescapexml(xml);
  22580. else if(cell.v<60) cell.v = cell.v -1;
  22581. if(!nf || nf == "General") nf = "yyyy-mm-dd";
  22582. /* falls through */
  22583. case 'Number':
  22584. if(cell.v === undefined) cell.v=+xml;
  22585. if(!cell.t) cell.t = 'n';
  22586. break;
  22587. case 'Error': cell.t = 'e'; cell.v = RBErr[xml]; if(o.cellText !== false) cell.w = xml; break;
  22588. default:
  22589. if(xml == "" && ss == "") { cell.t = 'z'; }
  22590. else { cell.t = 's'; cell.v = xlml_fixstr(ss||xml); }
  22591. break;
  22592. }
  22593. safe_format_xlml(cell, nf, o);
  22594. if(o.cellFormula !== false) {
  22595. if(cell.Formula) {
  22596. var fstr = unescapexml(cell.Formula);
  22597. /* strictly speaking, the leading = is required but some writers omit */
  22598. if(fstr.charCodeAt(0) == 61 /* = */) fstr = fstr.slice(1);
  22599. cell.f = rc_to_a1(fstr, base);
  22600. delete cell.Formula;
  22601. if(cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base);
  22602. else if(cell.ArrayRange) {
  22603. cell.F = rc_to_a1(cell.ArrayRange, base);
  22604. arrayf.push([safe_decode_range(cell.F), cell.F]);
  22605. }
  22606. } else {
  22607. for(i = 0; i < arrayf.length; ++i)
  22608. if(base.r >= arrayf[i][0].s.r && base.r <= arrayf[i][0].e.r)
  22609. if(base.c >= arrayf[i][0].s.c && base.c <= arrayf[i][0].e.c)
  22610. cell.F = arrayf[i][1];
  22611. }
  22612. }
  22613. if(o.cellStyles) {
  22614. interiors.forEach(function(x) {
  22615. if(!S.patternType && x.patternType) S.patternType = x.patternType;
  22616. });
  22617. cell.s = S;
  22618. }
  22619. if(cell.StyleID !== undefined) cell.ixfe = cell.StyleID;
  22620. }
  22621. function xlml_clean_comment(comment) {
  22622. comment.t = comment.v || "";
  22623. comment.t = comment.t.replace(/\r\n/g,"\n").replace(/\r/g,"\n");
  22624. comment.v = comment.w = comment.ixfe = undefined;
  22625. }
  22626. function xlml_normalize(d) {
  22627. if(has_buf && Buffer.isBuffer(d)) return d.toString('utf8');
  22628. if(typeof d === 'string') return d;
  22629. /* duktape */
  22630. if(typeof Uint8Array !== 'undefined' && d instanceof Uint8Array) return utf8read(a2s(ab2a(d)));
  22631. throw new Error("Bad input format: expected Buffer or string");
  22632. }
  22633. /* TODO: Everything */
  22634. /* UOS uses CJK in tags */
  22635. var xlmlregex = /<(\/?)([^\s?><!\/:]*:|)([^\s?<>:\/]+)(?:[\s?:\/][^>]*)?>/mg;
  22636. //var xlmlregex = /<(\/?)([a-z0-9]*:|)(\w+)[^>]*>/mg;
  22637. function parse_xlml_xml(d, _opts) {
  22638. var opts = _opts || {};
  22639. make_ssf(SSF);
  22640. var str = debom(xlml_normalize(d));
  22641. if(opts.type == 'binary' || opts.type == 'array' || opts.type == 'base64') {
  22642. if(typeof cptable !== 'undefined') str = cptable.utils.decode(65001, char_codes(str));
  22643. else str = utf8read(str);
  22644. }
  22645. var opening = str.slice(0, 1024).toLowerCase(), ishtml = false;
  22646. if(opening.indexOf("<?xml") == -1) ["html", "table", "head", "meta", "script", "style", "div"].forEach(function(tag) { if(opening.indexOf("<" + tag) >= 0) ishtml = true; });
  22647. if(ishtml) return HTML_.to_workbook(str, opts);
  22648. var Rn;
  22649. var state = [], tmp;
  22650. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  22651. var sheets = {}, sheetnames = [], cursheet = (opts.dense ? [] : {}), sheetname = "";
  22652. var table = {}, cell = ({}), row = {};// eslint-disable-line no-unused-vars
  22653. var dtag = xlml_parsexmltag('<Data ss:Type="String">'), didx = 0;
  22654. var c = 0, r = 0;
  22655. var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  22656. var styles = {}, stag = {};
  22657. var ss = "", fidx = 0;
  22658. var merges = [];
  22659. var Props = {}, Custprops = {}, pidx = 0, cp = [];
  22660. var comments = [], comment = ({});
  22661. var cstys = [], csty, seencol = false;
  22662. var arrayf = [];
  22663. var rowinfo = [], rowobj = {}, cc = 0, rr = 0;
  22664. var Workbook = ({ Sheets:[], WBProps:{date1904:false} }), wsprops = {};
  22665. xlmlregex.lastIndex = 0;
  22666. str = str.replace(/<!--([\s\S]*?)-->/mg,"");
  22667. var raw_Rn3 = "";
  22668. while((Rn = xlmlregex.exec(str))) switch((Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase())) {
  22669. case 'data' /*case 'Data'*/:
  22670. if(raw_Rn3 == "data") {
  22671. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22672. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  22673. break;
  22674. }
  22675. if(state[state.length-1][1]) break;
  22676. if(Rn[1]==='/') parse_xlml_data(str.slice(didx, Rn.index), ss, dtag, state[state.length-1][0]==/*"Comment"*/"comment"?comment:cell, {c:c,r:r}, styles, cstys[c], row, arrayf, opts);
  22677. else { ss = ""; dtag = xlml_parsexmltag(Rn[0]); didx = Rn.index + Rn[0].length; }
  22678. break;
  22679. case 'cell' /*case 'Cell'*/:
  22680. if(Rn[1]==='/'){
  22681. if(comments.length > 0) cell.c = comments;
  22682. if((!opts.sheetRows || opts.sheetRows > r) && cell.v !== undefined) {
  22683. if(opts.dense) {
  22684. if(!cursheet[r]) cursheet[r] = [];
  22685. cursheet[r][c] = cell;
  22686. } else cursheet[encode_col(c) + encode_row(r)] = cell;
  22687. }
  22688. if(cell.HRef) {
  22689. cell.l = ({Target:cell.HRef});
  22690. if(cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip;
  22691. delete cell.HRef; delete cell.HRefScreenTip;
  22692. }
  22693. if(cell.MergeAcross || cell.MergeDown) {
  22694. cc = c + (parseInt(cell.MergeAcross,10)|0);
  22695. rr = r + (parseInt(cell.MergeDown,10)|0);
  22696. merges.push({s:{c:c,r:r},e:{c:cc,r:rr}});
  22697. }
  22698. if(!opts.sheetStubs) { if(cell.MergeAcross) c = cc + 1; else ++c; }
  22699. else if(cell.MergeAcross || cell.MergeDown) {
  22700. for(var cma = c; cma <= cc; ++cma) {
  22701. for(var cmd = r; cmd <= rr; ++cmd) {
  22702. if(cma > c || cmd > r) {
  22703. if(opts.dense) {
  22704. if(!cursheet[cmd]) cursheet[cmd] = [];
  22705. cursheet[cmd][cma] = {t:'z'};
  22706. } else cursheet[encode_col(cma) + encode_row(cmd)] = {t:'z'};
  22707. }
  22708. }
  22709. }
  22710. c = cc + 1;
  22711. }
  22712. else ++c;
  22713. } else {
  22714. cell = xlml_parsexmltagobj(Rn[0]);
  22715. if(cell.Index) c = +cell.Index - 1;
  22716. if(c < refguess.s.c) refguess.s.c = c;
  22717. if(c > refguess.e.c) refguess.e.c = c;
  22718. if(Rn[0].slice(-2) === "/>") ++c;
  22719. comments = [];
  22720. }
  22721. break;
  22722. case 'row' /*case 'Row'*/:
  22723. if(Rn[1]==='/' || Rn[0].slice(-2) === "/>") {
  22724. if(r < refguess.s.r) refguess.s.r = r;
  22725. if(r > refguess.e.r) refguess.e.r = r;
  22726. if(Rn[0].slice(-2) === "/>") {
  22727. row = xlml_parsexmltag(Rn[0]);
  22728. if(row.Index) r = +row.Index - 1;
  22729. }
  22730. c = 0; ++r;
  22731. } else {
  22732. row = xlml_parsexmltag(Rn[0]);
  22733. if(row.Index) r = +row.Index - 1;
  22734. rowobj = {};
  22735. if(row.AutoFitHeight == "0" || row.Height) {
  22736. rowobj.hpx = parseInt(row.Height, 10); rowobj.hpt = px2pt(rowobj.hpx);
  22737. rowinfo[r] = rowobj;
  22738. }
  22739. if(row.Hidden == "1") { rowobj.hidden = true; rowinfo[r] = rowobj; }
  22740. }
  22741. break;
  22742. case 'worksheet' /*case 'Worksheet'*/: /* TODO: read range from FullRows/FullColumns */
  22743. if(Rn[1]==='/'){
  22744. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  22745. sheetnames.push(sheetname);
  22746. if(refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) {
  22747. cursheet["!ref"] = encode_range(refguess);
  22748. if(opts.sheetRows && opts.sheetRows <= refguess.e.r) {
  22749. cursheet["!fullref"] = cursheet["!ref"];
  22750. refguess.e.r = opts.sheetRows - 1;
  22751. cursheet["!ref"] = encode_range(refguess);
  22752. }
  22753. }
  22754. if(merges.length) cursheet["!merges"] = merges;
  22755. if(cstys.length > 0) cursheet["!cols"] = cstys;
  22756. if(rowinfo.length > 0) cursheet["!rows"] = rowinfo;
  22757. sheets[sheetname] = cursheet;
  22758. } else {
  22759. refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
  22760. r = c = 0;
  22761. state.push([Rn[3], false]);
  22762. tmp = xlml_parsexmltag(Rn[0]);
  22763. sheetname = unescapexml(tmp.Name);
  22764. cursheet = (opts.dense ? [] : {});
  22765. merges = [];
  22766. arrayf = [];
  22767. rowinfo = [];
  22768. wsprops = {name:sheetname, Hidden:0};
  22769. Workbook.Sheets.push(wsprops);
  22770. }
  22771. break;
  22772. case 'table' /*case 'Table'*/:
  22773. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22774. else if(Rn[0].slice(-2) == "/>") break;
  22775. else {
  22776. table = xlml_parsexmltag(Rn[0]);
  22777. state.push([Rn[3], false]);
  22778. cstys = []; seencol = false;
  22779. }
  22780. break;
  22781. case 'style' /*case 'Style'*/:
  22782. if(Rn[1]==='/') process_style_xlml(styles, stag, opts);
  22783. else stag = xlml_parsexmltag(Rn[0]);
  22784. break;
  22785. case 'numberformat' /*case 'NumberFormat'*/:
  22786. stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
  22787. if(XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
  22788. for(var ssfidx = 0; ssfidx != 0x188; ++ssfidx) if(SSF._table[ssfidx] == stag.nf) break;
  22789. if(ssfidx == 0x188) for(ssfidx = 0x39; ssfidx != 0x188; ++ssfidx) if(SSF._table[ssfidx] == null) { SSF.load(stag.nf, ssfidx); break; }
  22790. break;
  22791. case 'column' /*case 'Column'*/:
  22792. if(state[state.length-1][0] !== /*'Table'*/'table') break;
  22793. csty = xlml_parsexmltag(Rn[0]);
  22794. if(csty.Hidden) { csty.hidden = true; delete csty.Hidden; }
  22795. if(csty.Width) csty.wpx = parseInt(csty.Width, 10);
  22796. if(!seencol && csty.wpx > 10) {
  22797. seencol = true; MDW = DEF_MDW; //find_mdw_wpx(csty.wpx);
  22798. for(var _col = 0; _col < cstys.length; ++_col) if(cstys[_col]) process_col(cstys[_col]);
  22799. }
  22800. if(seencol) process_col(csty);
  22801. cstys[(csty.Index-1||cstys.length)] = csty;
  22802. for(var i = 0; i < +csty.Span; ++i) cstys[cstys.length] = dup(csty);
  22803. break;
  22804. case 'namedrange' /*case 'NamedRange'*/:
  22805. if(Rn[1]==='/') break;
  22806. if(!Workbook.Names) Workbook.Names = [];
  22807. var _NamedRange = parsexmltag(Rn[0]);
  22808. var _DefinedName = ({
  22809. Name: _NamedRange.Name,
  22810. Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), {r:0, c:0})
  22811. });
  22812. if(Workbook.Sheets.length>0) _DefinedName.Sheet=Workbook.Sheets.length-1;
  22813. Workbook.Names.push(_DefinedName);
  22814. break;
  22815. case 'namedcell' /*case 'NamedCell'*/: break;
  22816. case 'b' /*case 'B'*/: break;
  22817. case 'i' /*case 'I'*/: break;
  22818. case 'u' /*case 'U'*/: break;
  22819. case 's' /*case 'S'*/: break;
  22820. case 'em' /*case 'EM'*/: break;
  22821. case 'h2' /*case 'H2'*/: break;
  22822. case 'h3' /*case 'H3'*/: break;
  22823. case 'sub' /*case 'Sub'*/: break;
  22824. case 'sup' /*case 'Sup'*/: break;
  22825. case 'span' /*case 'Span'*/: break;
  22826. case 'alignment' /*case 'Alignment'*/:
  22827. break;
  22828. case 'borders' /*case 'Borders'*/: break;
  22829. case 'border' /*case 'Border'*/: break;
  22830. case 'font' /*case 'Font'*/:
  22831. if(Rn[0].slice(-2) === "/>") break;
  22832. else if(Rn[1]==="/") ss += str.slice(fidx, Rn.index);
  22833. else fidx = Rn.index + Rn[0].length;
  22834. break;
  22835. case 'interior' /*case 'Interior'*/:
  22836. if(!opts.cellStyles) break;
  22837. stag.Interior = xlml_parsexmltag(Rn[0]);
  22838. break;
  22839. case 'protection' /*case 'Protection'*/: break;
  22840. case 'author' /*case 'Author'*/:
  22841. case 'title' /*case 'Title'*/:
  22842. case 'description' /*case 'Description'*/:
  22843. case 'created' /*case 'Created'*/:
  22844. case 'keywords' /*case 'Keywords'*/:
  22845. case 'subject' /*case 'Subject'*/:
  22846. case 'category' /*case 'Category'*/:
  22847. case 'company' /*case 'Company'*/:
  22848. case 'lastauthor' /*case 'LastAuthor'*/:
  22849. case 'lastsaved' /*case 'LastSaved'*/:
  22850. case 'lastprinted' /*case 'LastPrinted'*/:
  22851. case 'version' /*case 'Version'*/:
  22852. case 'revision' /*case 'Revision'*/:
  22853. case 'totaltime' /*case 'TotalTime'*/:
  22854. case 'hyperlinkbase' /*case 'HyperlinkBase'*/:
  22855. case 'manager' /*case 'Manager'*/:
  22856. case 'contentstatus' /*case 'ContentStatus'*/:
  22857. case 'identifier' /*case 'Identifier'*/:
  22858. case 'language' /*case 'Language'*/:
  22859. case 'appname' /*case 'AppName'*/:
  22860. if(Rn[0].slice(-2) === "/>") break;
  22861. else if(Rn[1]==="/") xlml_set_prop(Props, raw_Rn3, str.slice(pidx, Rn.index));
  22862. else pidx = Rn.index + Rn[0].length;
  22863. break;
  22864. case 'paragraphs' /*case 'Paragraphs'*/: break;
  22865. case 'styles' /*case 'Styles'*/:
  22866. case 'workbook' /*case 'Workbook'*/:
  22867. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22868. else state.push([Rn[3], false]);
  22869. break;
  22870. case 'comment' /*case 'Comment'*/:
  22871. if(Rn[1]==='/'){
  22872. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  22873. xlml_clean_comment(comment);
  22874. comments.push(comment);
  22875. } else {
  22876. state.push([Rn[3], false]);
  22877. tmp = xlml_parsexmltag(Rn[0]);
  22878. comment = ({a:tmp.Author});
  22879. }
  22880. break;
  22881. case 'autofilter' /*case 'AutoFilter'*/:
  22882. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22883. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  22884. var AutoFilter = xlml_parsexmltag(Rn[0]);
  22885. cursheet['!autofilter'] = { ref:rc_to_a1(AutoFilter.Range).replace(/\$/g,"") };
  22886. state.push([Rn[3], true]);
  22887. }
  22888. break;
  22889. case 'name' /*case 'Name'*/: break;
  22890. case 'datavalidation' /*case 'DataValidation'*/:
  22891. if(Rn[1]==='/'){
  22892. if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
  22893. } else {
  22894. if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  22895. }
  22896. break;
  22897. case 'pixelsperinch' /*case 'PixelsPerInch'*/:
  22898. break;
  22899. case 'componentoptions' /*case 'ComponentOptions'*/:
  22900. case 'documentproperties' /*case 'DocumentProperties'*/:
  22901. case 'customdocumentproperties' /*case 'CustomDocumentProperties'*/:
  22902. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/:
  22903. case 'pivottable' /*case 'PivotTable'*/:
  22904. case 'pivotcache' /*case 'PivotCache'*/:
  22905. case 'names' /*case 'Names'*/:
  22906. case 'mapinfo' /*case 'MapInfo'*/:
  22907. case 'pagebreaks' /*case 'PageBreaks'*/:
  22908. case 'querytable' /*case 'QueryTable'*/:
  22909. case 'sorting' /*case 'Sorting'*/:
  22910. case 'schema' /*case 'Schema'*/: //case 'data' /*case 'data'*/:
  22911. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  22912. case 'smarttagtype' /*case 'SmartTagType'*/:
  22913. case 'smarttags' /*case 'SmartTags'*/:
  22914. case 'excelworkbook' /*case 'ExcelWorkbook'*/:
  22915. case 'workbookoptions' /*case 'WorkbookOptions'*/:
  22916. case 'worksheetoptions' /*case 'WorksheetOptions'*/:
  22917. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
  22918. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  22919. break;
  22920. default:
  22921. /* FODS file root is <office:document> */
  22922. if(state.length == 0 && Rn[3] == "document") return parse_fods(str, opts);
  22923. /* UOS file root is <uof:UOF> */
  22924. if(state.length == 0 && Rn[3] == "uof"/*"UOF"*/) return parse_fods(str, opts);
  22925. var seen = true;
  22926. switch(state[state.length-1][0]) {
  22927. /* OfficeDocumentSettings */
  22928. case 'officedocumentsettings' /*case 'OfficeDocumentSettings'*/: switch(Rn[3]) {
  22929. case 'allowpng' /*case 'AllowPNG'*/: break;
  22930. case 'removepersonalinformation' /*case 'RemovePersonalInformation'*/: break;
  22931. case 'downloadcomponents' /*case 'DownloadComponents'*/: break;
  22932. case 'locationofcomponents' /*case 'LocationOfComponents'*/: break;
  22933. case 'colors' /*case 'Colors'*/: break;
  22934. case 'color' /*case 'Color'*/: break;
  22935. case 'index' /*case 'Index'*/: break;
  22936. case 'rgb' /*case 'RGB'*/: break;
  22937. case 'targetscreensize' /*case 'TargetScreenSize'*/: break;
  22938. case 'readonlyrecommended' /*case 'ReadOnlyRecommended'*/: break;
  22939. default: seen = false;
  22940. } break;
  22941. /* ComponentOptions */
  22942. case 'componentoptions' /*case 'ComponentOptions'*/: switch(Rn[3]) {
  22943. case 'toolbar' /*case 'Toolbar'*/: break;
  22944. case 'hideofficelogo' /*case 'HideOfficeLogo'*/: break;
  22945. case 'spreadsheetautofit' /*case 'SpreadsheetAutoFit'*/: break;
  22946. case 'label' /*case 'Label'*/: break;
  22947. case 'caption' /*case 'Caption'*/: break;
  22948. case 'maxheight' /*case 'MaxHeight'*/: break;
  22949. case 'maxwidth' /*case 'MaxWidth'*/: break;
  22950. case 'nextsheetnumber' /*case 'NextSheetNumber'*/: break;
  22951. default: seen = false;
  22952. } break;
  22953. /* ExcelWorkbook */
  22954. case 'excelworkbook' /*case 'ExcelWorkbook'*/: switch(Rn[3]) {
  22955. case 'date1904' /*case 'Date1904'*/:
  22956. Workbook.WBProps.date1904 = true;
  22957. break;
  22958. case 'windowheight' /*case 'WindowHeight'*/: break;
  22959. case 'windowwidth' /*case 'WindowWidth'*/: break;
  22960. case 'windowtopx' /*case 'WindowTopX'*/: break;
  22961. case 'windowtopy' /*case 'WindowTopY'*/: break;
  22962. case 'tabratio' /*case 'TabRatio'*/: break;
  22963. case 'protectstructure' /*case 'ProtectStructure'*/: break;
  22964. case 'protectwindow' /*case 'ProtectWindow'*/: break;
  22965. case 'protectwindows' /*case 'ProtectWindows'*/: break;
  22966. case 'activesheet' /*case 'ActiveSheet'*/: break;
  22967. case 'displayinknotes' /*case 'DisplayInkNotes'*/: break;
  22968. case 'firstvisiblesheet' /*case 'FirstVisibleSheet'*/: break;
  22969. case 'supbook' /*case 'SupBook'*/: break;
  22970. case 'sheetname' /*case 'SheetName'*/: break;
  22971. case 'sheetindex' /*case 'SheetIndex'*/: break;
  22972. case 'sheetindexfirst' /*case 'SheetIndexFirst'*/: break;
  22973. case 'sheetindexlast' /*case 'SheetIndexLast'*/: break;
  22974. case 'dll' /*case 'Dll'*/: break;
  22975. case 'acceptlabelsinformulas' /*case 'AcceptLabelsInFormulas'*/: break;
  22976. case 'donotsavelinkvalues' /*case 'DoNotSaveLinkValues'*/: break;
  22977. case 'iteration' /*case 'Iteration'*/: break;
  22978. case 'maxiterations' /*case 'MaxIterations'*/: break;
  22979. case 'maxchange' /*case 'MaxChange'*/: break;
  22980. case 'path' /*case 'Path'*/: break;
  22981. case 'xct' /*case 'Xct'*/: break;
  22982. case 'count' /*case 'Count'*/: break;
  22983. case 'selectedsheets' /*case 'SelectedSheets'*/: break;
  22984. case 'calculation' /*case 'Calculation'*/: break;
  22985. case 'uncalced' /*case 'Uncalced'*/: break;
  22986. case 'startupprompt' /*case 'StartupPrompt'*/: break;
  22987. case 'crn' /*case 'Crn'*/: break;
  22988. case 'externname' /*case 'ExternName'*/: break;
  22989. case 'formula' /*case 'Formula'*/: break;
  22990. case 'colfirst' /*case 'ColFirst'*/: break;
  22991. case 'collast' /*case 'ColLast'*/: break;
  22992. case 'wantadvise' /*case 'WantAdvise'*/: break;
  22993. case 'boolean' /*case 'Boolean'*/: break;
  22994. case 'error' /*case 'Error'*/: break;
  22995. case 'text' /*case 'Text'*/: break;
  22996. case 'ole' /*case 'OLE'*/: break;
  22997. case 'noautorecover' /*case 'NoAutoRecover'*/: break;
  22998. case 'publishobjects' /*case 'PublishObjects'*/: break;
  22999. case 'donotcalculatebeforesave' /*case 'DoNotCalculateBeforeSave'*/: break;
  23000. case 'number' /*case 'Number'*/: break;
  23001. case 'refmoder1c1' /*case 'RefModeR1C1'*/: break;
  23002. case 'embedsavesmarttags' /*case 'EmbedSaveSmartTags'*/: break;
  23003. default: seen = false;
  23004. } break;
  23005. /* WorkbookOptions */
  23006. case 'workbookoptions' /*case 'WorkbookOptions'*/: switch(Rn[3]) {
  23007. case 'owcversion' /*case 'OWCVersion'*/: break;
  23008. case 'height' /*case 'Height'*/: break;
  23009. case 'width' /*case 'Width'*/: break;
  23010. default: seen = false;
  23011. } break;
  23012. /* WorksheetOptions */
  23013. case 'worksheetoptions' /*case 'WorksheetOptions'*/: switch(Rn[3]) {
  23014. case 'visible' /*case 'Visible'*/:
  23015. if(Rn[0].slice(-2) === "/>"){/* empty */}
  23016. else if(Rn[1]==="/") switch(str.slice(pidx, Rn.index)) {
  23017. case "SheetHidden": wsprops.Hidden = 1; break;
  23018. case "SheetVeryHidden": wsprops.Hidden = 2; break;
  23019. }
  23020. else pidx = Rn.index + Rn[0].length;
  23021. break;
  23022. case 'header' /*case 'Header'*/:
  23023. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  23024. cursheet['!margins'].header = parsexmltag(Rn[0]).Margin;
  23025. break;
  23026. case 'footer' /*case 'Footer'*/:
  23027. if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
  23028. cursheet['!margins'].footer = parsexmltag(Rn[0]).Margin;
  23029. break;
  23030. case 'pagemargins' /*case 'PageMargins'*/:
  23031. var pagemargins = parsexmltag(Rn[0]);
  23032. if(!cursheet['!margins']) default_margins(cursheet['!margins']={},'xlml');
  23033. if(pagemargins.Top) cursheet['!margins'].top = pagemargins.Top;
  23034. if(pagemargins.Left) cursheet['!margins'].left = pagemargins.Left;
  23035. if(pagemargins.Right) cursheet['!margins'].right = pagemargins.Right;
  23036. if(pagemargins.Bottom) cursheet['!margins'].bottom = pagemargins.Bottom;
  23037. break;
  23038. case 'displayrighttoleft' /*case 'DisplayRightToLeft'*/:
  23039. if(!Workbook.Views) Workbook.Views = [];
  23040. if(!Workbook.Views[0]) Workbook.Views[0] = {};
  23041. Workbook.Views[0].RTL = true;
  23042. break;
  23043. case 'freezepanes' /*case 'FreezePanes'*/: break;
  23044. case 'frozennosplit' /*case 'FrozenNoSplit'*/: break;
  23045. case 'splithorizontal' /*case 'SplitHorizontal'*/:
  23046. case 'splitvertical' /*case 'SplitVertical'*/:
  23047. break;
  23048. case 'donotdisplaygridlines' /*case 'DoNotDisplayGridlines'*/:
  23049. break;
  23050. case 'activerow' /*case 'ActiveRow'*/: break;
  23051. case 'activecol' /*case 'ActiveCol'*/: break;
  23052. case 'toprowbottompane' /*case 'TopRowBottomPane'*/: break;
  23053. case 'leftcolumnrightpane' /*case 'LeftColumnRightPane'*/: break;
  23054. case 'unsynced' /*case 'Unsynced'*/: break;
  23055. case 'print' /*case 'Print'*/: break;
  23056. case 'panes' /*case 'Panes'*/: break;
  23057. case 'scale' /*case 'Scale'*/: break;
  23058. case 'pane' /*case 'Pane'*/: break;
  23059. case 'number' /*case 'Number'*/: break;
  23060. case 'layout' /*case 'Layout'*/: break;
  23061. case 'pagesetup' /*case 'PageSetup'*/: break;
  23062. case 'selected' /*case 'Selected'*/: break;
  23063. case 'protectobjects' /*case 'ProtectObjects'*/: break;
  23064. case 'enableselection' /*case 'EnableSelection'*/: break;
  23065. case 'protectscenarios' /*case 'ProtectScenarios'*/: break;
  23066. case 'validprinterinfo' /*case 'ValidPrinterInfo'*/: break;
  23067. case 'horizontalresolution' /*case 'HorizontalResolution'*/: break;
  23068. case 'verticalresolution' /*case 'VerticalResolution'*/: break;
  23069. case 'numberofcopies' /*case 'NumberofCopies'*/: break;
  23070. case 'activepane' /*case 'ActivePane'*/: break;
  23071. case 'toprowvisible' /*case 'TopRowVisible'*/: break;
  23072. case 'leftcolumnvisible' /*case 'LeftColumnVisible'*/: break;
  23073. case 'fittopage' /*case 'FitToPage'*/: break;
  23074. case 'rangeselection' /*case 'RangeSelection'*/: break;
  23075. case 'papersizeindex' /*case 'PaperSizeIndex'*/: break;
  23076. case 'pagelayoutzoom' /*case 'PageLayoutZoom'*/: break;
  23077. case 'pagebreakzoom' /*case 'PageBreakZoom'*/: break;
  23078. case 'filteron' /*case 'FilterOn'*/: break;
  23079. case 'fitwidth' /*case 'FitWidth'*/: break;
  23080. case 'fitheight' /*case 'FitHeight'*/: break;
  23081. case 'commentslayout' /*case 'CommentsLayout'*/: break;
  23082. case 'zoom' /*case 'Zoom'*/: break;
  23083. case 'lefttoright' /*case 'LeftToRight'*/: break;
  23084. case 'gridlines' /*case 'Gridlines'*/: break;
  23085. case 'allowsort' /*case 'AllowSort'*/: break;
  23086. case 'allowfilter' /*case 'AllowFilter'*/: break;
  23087. case 'allowinsertrows' /*case 'AllowInsertRows'*/: break;
  23088. case 'allowdeleterows' /*case 'AllowDeleteRows'*/: break;
  23089. case 'allowinsertcols' /*case 'AllowInsertCols'*/: break;
  23090. case 'allowdeletecols' /*case 'AllowDeleteCols'*/: break;
  23091. case 'allowinserthyperlinks' /*case 'AllowInsertHyperlinks'*/: break;
  23092. case 'allowformatcells' /*case 'AllowFormatCells'*/: break;
  23093. case 'allowsizecols' /*case 'AllowSizeCols'*/: break;
  23094. case 'allowsizerows' /*case 'AllowSizeRows'*/: break;
  23095. case 'nosummaryrowsbelowdetail' /*case 'NoSummaryRowsBelowDetail'*/: break;
  23096. case 'tabcolorindex' /*case 'TabColorIndex'*/: break;
  23097. case 'donotdisplayheadings' /*case 'DoNotDisplayHeadings'*/: break;
  23098. case 'showpagelayoutzoom' /*case 'ShowPageLayoutZoom'*/: break;
  23099. case 'nosummarycolumnsrightdetail' /*case 'NoSummaryColumnsRightDetail'*/: break;
  23100. case 'blackandwhite' /*case 'BlackAndWhite'*/: break;
  23101. case 'donotdisplayzeros' /*case 'DoNotDisplayZeros'*/: break;
  23102. case 'displaypagebreak' /*case 'DisplayPageBreak'*/: break;
  23103. case 'rowcolheadings' /*case 'RowColHeadings'*/: break;
  23104. case 'donotdisplayoutline' /*case 'DoNotDisplayOutline'*/: break;
  23105. case 'noorientation' /*case 'NoOrientation'*/: break;
  23106. case 'allowusepivottables' /*case 'AllowUsePivotTables'*/: break;
  23107. case 'zeroheight' /*case 'ZeroHeight'*/: break;
  23108. case 'viewablerange' /*case 'ViewableRange'*/: break;
  23109. case 'selection' /*case 'Selection'*/: break;
  23110. case 'protectcontents' /*case 'ProtectContents'*/: break;
  23111. default: seen = false;
  23112. } break;
  23113. /* PivotTable */
  23114. case 'pivottable' /*case 'PivotTable'*/: case 'pivotcache' /*case 'PivotCache'*/: switch(Rn[3]) {
  23115. case 'immediateitemsondrop' /*case 'ImmediateItemsOnDrop'*/: break;
  23116. case 'showpagemultipleitemlabel' /*case 'ShowPageMultipleItemLabel'*/: break;
  23117. case 'compactrowindent' /*case 'CompactRowIndent'*/: break;
  23118. case 'location' /*case 'Location'*/: break;
  23119. case 'pivotfield' /*case 'PivotField'*/: break;
  23120. case 'orientation' /*case 'Orientation'*/: break;
  23121. case 'layoutform' /*case 'LayoutForm'*/: break;
  23122. case 'layoutsubtotallocation' /*case 'LayoutSubtotalLocation'*/: break;
  23123. case 'layoutcompactrow' /*case 'LayoutCompactRow'*/: break;
  23124. case 'position' /*case 'Position'*/: break;
  23125. case 'pivotitem' /*case 'PivotItem'*/: break;
  23126. case 'datatype' /*case 'DataType'*/: break;
  23127. case 'datafield' /*case 'DataField'*/: break;
  23128. case 'sourcename' /*case 'SourceName'*/: break;
  23129. case 'parentfield' /*case 'ParentField'*/: break;
  23130. case 'ptlineitems' /*case 'PTLineItems'*/: break;
  23131. case 'ptlineitem' /*case 'PTLineItem'*/: break;
  23132. case 'countofsameitems' /*case 'CountOfSameItems'*/: break;
  23133. case 'item' /*case 'Item'*/: break;
  23134. case 'itemtype' /*case 'ItemType'*/: break;
  23135. case 'ptsource' /*case 'PTSource'*/: break;
  23136. case 'cacheindex' /*case 'CacheIndex'*/: break;
  23137. case 'consolidationreference' /*case 'ConsolidationReference'*/: break;
  23138. case 'filename' /*case 'FileName'*/: break;
  23139. case 'reference' /*case 'Reference'*/: break;
  23140. case 'nocolumngrand' /*case 'NoColumnGrand'*/: break;
  23141. case 'norowgrand' /*case 'NoRowGrand'*/: break;
  23142. case 'blanklineafteritems' /*case 'BlankLineAfterItems'*/: break;
  23143. case 'hidden' /*case 'Hidden'*/: break;
  23144. case 'subtotal' /*case 'Subtotal'*/: break;
  23145. case 'basefield' /*case 'BaseField'*/: break;
  23146. case 'mapchilditems' /*case 'MapChildItems'*/: break;
  23147. case 'function' /*case 'Function'*/: break;
  23148. case 'refreshonfileopen' /*case 'RefreshOnFileOpen'*/: break;
  23149. case 'printsettitles' /*case 'PrintSetTitles'*/: break;
  23150. case 'mergelabels' /*case 'MergeLabels'*/: break;
  23151. case 'defaultversion' /*case 'DefaultVersion'*/: break;
  23152. case 'refreshname' /*case 'RefreshName'*/: break;
  23153. case 'refreshdate' /*case 'RefreshDate'*/: break;
  23154. case 'refreshdatecopy' /*case 'RefreshDateCopy'*/: break;
  23155. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  23156. case 'versionlastupdate' /*case 'VersionLastUpdate'*/: break;
  23157. case 'versionupdateablemin' /*case 'VersionUpdateableMin'*/: break;
  23158. case 'versionrefreshablemin' /*case 'VersionRefreshableMin'*/: break;
  23159. case 'calculation' /*case 'Calculation'*/: break;
  23160. default: seen = false;
  23161. } break;
  23162. /* PageBreaks */
  23163. case 'pagebreaks' /*case 'PageBreaks'*/: switch(Rn[3]) {
  23164. case 'colbreaks' /*case 'ColBreaks'*/: break;
  23165. case 'colbreak' /*case 'ColBreak'*/: break;
  23166. case 'rowbreaks' /*case 'RowBreaks'*/: break;
  23167. case 'rowbreak' /*case 'RowBreak'*/: break;
  23168. case 'colstart' /*case 'ColStart'*/: break;
  23169. case 'colend' /*case 'ColEnd'*/: break;
  23170. case 'rowend' /*case 'RowEnd'*/: break;
  23171. default: seen = false;
  23172. } break;
  23173. /* AutoFilter */
  23174. case 'autofilter' /*case 'AutoFilter'*/: switch(Rn[3]) {
  23175. case 'autofiltercolumn' /*case 'AutoFilterColumn'*/: break;
  23176. case 'autofiltercondition' /*case 'AutoFilterCondition'*/: break;
  23177. case 'autofilterand' /*case 'AutoFilterAnd'*/: break;
  23178. case 'autofilteror' /*case 'AutoFilterOr'*/: break;
  23179. default: seen = false;
  23180. } break;
  23181. /* QueryTable */
  23182. case 'querytable' /*case 'QueryTable'*/: switch(Rn[3]) {
  23183. case 'id' /*case 'Id'*/: break;
  23184. case 'autoformatfont' /*case 'AutoFormatFont'*/: break;
  23185. case 'autoformatpattern' /*case 'AutoFormatPattern'*/: break;
  23186. case 'querysource' /*case 'QuerySource'*/: break;
  23187. case 'querytype' /*case 'QueryType'*/: break;
  23188. case 'enableredirections' /*case 'EnableRedirections'*/: break;
  23189. case 'refreshedinxl9' /*case 'RefreshedInXl9'*/: break;
  23190. case 'urlstring' /*case 'URLString'*/: break;
  23191. case 'htmltables' /*case 'HTMLTables'*/: break;
  23192. case 'connection' /*case 'Connection'*/: break;
  23193. case 'commandtext' /*case 'CommandText'*/: break;
  23194. case 'refreshinfo' /*case 'RefreshInfo'*/: break;
  23195. case 'notitles' /*case 'NoTitles'*/: break;
  23196. case 'nextid' /*case 'NextId'*/: break;
  23197. case 'columninfo' /*case 'ColumnInfo'*/: break;
  23198. case 'overwritecells' /*case 'OverwriteCells'*/: break;
  23199. case 'donotpromptforfile' /*case 'DoNotPromptForFile'*/: break;
  23200. case 'textwizardsettings' /*case 'TextWizardSettings'*/: break;
  23201. case 'source' /*case 'Source'*/: break;
  23202. case 'number' /*case 'Number'*/: break;
  23203. case 'decimal' /*case 'Decimal'*/: break;
  23204. case 'thousandseparator' /*case 'ThousandSeparator'*/: break;
  23205. case 'trailingminusnumbers' /*case 'TrailingMinusNumbers'*/: break;
  23206. case 'formatsettings' /*case 'FormatSettings'*/: break;
  23207. case 'fieldtype' /*case 'FieldType'*/: break;
  23208. case 'delimiters' /*case 'Delimiters'*/: break;
  23209. case 'tab' /*case 'Tab'*/: break;
  23210. case 'comma' /*case 'Comma'*/: break;
  23211. case 'autoformatname' /*case 'AutoFormatName'*/: break;
  23212. case 'versionlastedit' /*case 'VersionLastEdit'*/: break;
  23213. case 'versionlastrefresh' /*case 'VersionLastRefresh'*/: break;
  23214. default: seen = false;
  23215. } break;
  23216. case 'datavalidation' /*case 'DataValidation'*/:
  23217. switch(Rn[3]) {
  23218. case 'range' /*case 'Range'*/: break;
  23219. case 'type' /*case 'Type'*/: break;
  23220. case 'min' /*case 'Min'*/: break;
  23221. case 'max' /*case 'Max'*/: break;
  23222. case 'sort' /*case 'Sort'*/: break;
  23223. case 'descending' /*case 'Descending'*/: break;
  23224. case 'order' /*case 'Order'*/: break;
  23225. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  23226. case 'value' /*case 'Value'*/: break;
  23227. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  23228. case 'errormessage' /*case 'ErrorMessage'*/: break;
  23229. case 'errortitle' /*case 'ErrorTitle'*/: break;
  23230. case 'inputmessage' /*case 'InputMessage'*/: break;
  23231. case 'inputtitle' /*case 'InputTitle'*/: break;
  23232. case 'combohide' /*case 'ComboHide'*/: break;
  23233. case 'inputhide' /*case 'InputHide'*/: break;
  23234. case 'condition' /*case 'Condition'*/: break;
  23235. case 'qualifier' /*case 'Qualifier'*/: break;
  23236. case 'useblank' /*case 'UseBlank'*/: break;
  23237. case 'value1' /*case 'Value1'*/: break;
  23238. case 'value2' /*case 'Value2'*/: break;
  23239. case 'format' /*case 'Format'*/: break;
  23240. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  23241. default: seen = false;
  23242. } break;
  23243. case 'sorting' /*case 'Sorting'*/:
  23244. case 'conditionalformatting' /*case 'ConditionalFormatting'*/:
  23245. switch(Rn[3]) {
  23246. case 'range' /*case 'Range'*/: break;
  23247. case 'type' /*case 'Type'*/: break;
  23248. case 'min' /*case 'Min'*/: break;
  23249. case 'max' /*case 'Max'*/: break;
  23250. case 'sort' /*case 'Sort'*/: break;
  23251. case 'descending' /*case 'Descending'*/: break;
  23252. case 'order' /*case 'Order'*/: break;
  23253. case 'casesensitive' /*case 'CaseSensitive'*/: break;
  23254. case 'value' /*case 'Value'*/: break;
  23255. case 'errorstyle' /*case 'ErrorStyle'*/: break;
  23256. case 'errormessage' /*case 'ErrorMessage'*/: break;
  23257. case 'errortitle' /*case 'ErrorTitle'*/: break;
  23258. case 'cellrangelist' /*case 'CellRangeList'*/: break;
  23259. case 'inputmessage' /*case 'InputMessage'*/: break;
  23260. case 'inputtitle' /*case 'InputTitle'*/: break;
  23261. case 'combohide' /*case 'ComboHide'*/: break;
  23262. case 'inputhide' /*case 'InputHide'*/: break;
  23263. case 'condition' /*case 'Condition'*/: break;
  23264. case 'qualifier' /*case 'Qualifier'*/: break;
  23265. case 'useblank' /*case 'UseBlank'*/: break;
  23266. case 'value1' /*case 'Value1'*/: break;
  23267. case 'value2' /*case 'Value2'*/: break;
  23268. case 'format' /*case 'Format'*/: break;
  23269. default: seen = false;
  23270. } break;
  23271. /* MapInfo (schema) */
  23272. case 'mapinfo' /*case 'MapInfo'*/: case 'schema' /*case 'Schema'*/: case 'data' /*case 'data'*/: switch(Rn[3]) {
  23273. case 'map' /*case 'Map'*/: break;
  23274. case 'entry' /*case 'Entry'*/: break;
  23275. case 'range' /*case 'Range'*/: break;
  23276. case 'xpath' /*case 'XPath'*/: break;
  23277. case 'field' /*case 'Field'*/: break;
  23278. case 'xsdtype' /*case 'XSDType'*/: break;
  23279. case 'filteron' /*case 'FilterOn'*/: break;
  23280. case 'aggregate' /*case 'Aggregate'*/: break;
  23281. case 'elementtype' /*case 'ElementType'*/: break;
  23282. case 'attributetype' /*case 'AttributeType'*/: break;
  23283. /* These are from xsd (XML Schema Definition) */
  23284. case 'schema' /*case 'schema'*/:
  23285. case 'element' /*case 'element'*/:
  23286. case 'complextype' /*case 'complexType'*/:
  23287. case 'datatype' /*case 'datatype'*/:
  23288. case 'all' /*case 'all'*/:
  23289. case 'attribute' /*case 'attribute'*/:
  23290. case 'extends' /*case 'extends'*/: break;
  23291. case 'row' /*case 'row'*/: break;
  23292. default: seen = false;
  23293. } break;
  23294. /* SmartTags (can be anything) */
  23295. case 'smarttags' /*case 'SmartTags'*/: break;
  23296. default: seen = false; break;
  23297. }
  23298. if(seen) break;
  23299. /* CustomDocumentProperties */
  23300. if(Rn[3].match(/!\[CDATA/)) break;
  23301. if(!state[state.length-1][1]) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  23302. if(state[state.length-1][0]===/*'CustomDocumentProperties'*/'customdocumentproperties') {
  23303. if(Rn[0].slice(-2) === "/>") break;
  23304. else if(Rn[1]==="/") xlml_set_custprop(Custprops, raw_Rn3, cp, str.slice(pidx, Rn.index));
  23305. else { cp = Rn; pidx = Rn.index + Rn[0].length; }
  23306. break;
  23307. }
  23308. if(opts.WTF) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
  23309. }
  23310. var out = ({});
  23311. if(!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
  23312. out.SheetNames = sheetnames;
  23313. out.Workbook = Workbook;
  23314. out.SSF = SSF.get_table();
  23315. out.Props = Props;
  23316. out.Custprops = Custprops;
  23317. return out;
  23318. }
  23319. function parse_xlml(data, opts) {
  23320. fix_read_opts(opts=opts||{});
  23321. switch(opts.type||"base64") {
  23322. case "base64": return parse_xlml_xml(Base64.decode(data), opts);
  23323. case "binary": case "buffer": case "file": return parse_xlml_xml(data, opts);
  23324. case "array": return parse_xlml_xml(a2s(data), opts);
  23325. }
  23326. }
  23327. /* TODO */
  23328. function write_props_xlml(wb, opts) {
  23329. var o = [];
  23330. /* DocumentProperties */
  23331. if(wb.Props) o.push(xlml_write_docprops(wb.Props, opts));
  23332. /* CustomDocumentProperties */
  23333. if(wb.Custprops) o.push(xlml_write_custprops(wb.Props, wb.Custprops, opts));
  23334. return o.join("");
  23335. }
  23336. /* TODO */
  23337. function write_wb_xlml() {
  23338. /* OfficeDocumentSettings */
  23339. /* ExcelWorkbook */
  23340. return "";
  23341. }
  23342. /* TODO */
  23343. function write_sty_xlml(wb, opts) {
  23344. /* Styles */
  23345. var styles = ['<Style ss:ID="Default" ss:Name="Normal"><NumberFormat/></Style>'];
  23346. opts.cellXfs.forEach(function(xf, id) {
  23347. var payload = [];
  23348. payload.push(writextag('NumberFormat', null, {"ss:Format": escapexml(SSF._table[xf.numFmtId])}));
  23349. var o = {"ss:ID": "s" + (21+id)};
  23350. styles.push(writextag('Style', payload.join(""), o));
  23351. });
  23352. return writextag("Styles", styles.join(""));
  23353. }
  23354. function write_name_xlml(n) { return writextag("NamedRange", null, {"ss:Name": n.Name, "ss:RefersTo":"=" + a1_to_rc(n.Ref, {r:0,c:0})}); }
  23355. function write_names_xlml(wb) {
  23356. if(!((wb||{}).Workbook||{}).Names) return "";
  23357. var names = wb.Workbook.Names;
  23358. var out = [];
  23359. for(var i = 0; i < names.length; ++i) {
  23360. var n = names[i];
  23361. if(n.Sheet != null) continue;
  23362. if(n.Name.match(/^_xlfn\./)) continue;
  23363. out.push(write_name_xlml(n));
  23364. }
  23365. return writextag("Names", out.join(""));
  23366. }
  23367. function write_ws_xlml_names(ws, opts, idx, wb) {
  23368. if(!ws) return "";
  23369. if(!((wb||{}).Workbook||{}).Names) return "";
  23370. var names = wb.Workbook.Names;
  23371. var out = [];
  23372. for(var i = 0; i < names.length; ++i) {
  23373. var n = names[i];
  23374. if(n.Sheet != idx) continue;
  23375. /*switch(n.Name) {
  23376. case "_": continue;
  23377. }*/
  23378. if(n.Name.match(/^_xlfn\./)) continue;
  23379. out.push(write_name_xlml(n));
  23380. }
  23381. return out.join("");
  23382. }
  23383. /* WorksheetOptions */
  23384. function write_ws_xlml_wsopts(ws, opts, idx, wb) {
  23385. if(!ws) return "";
  23386. var o = [];
  23387. /* NOTE: spec technically allows any order, but stick with implied order */
  23388. /* FitToPage */
  23389. /* DoNotDisplayColHeaders */
  23390. /* DoNotDisplayRowHeaders */
  23391. /* ViewableRange */
  23392. /* Selection */
  23393. /* GridlineColor */
  23394. /* Name */
  23395. /* ExcelWorksheetType */
  23396. /* IntlMacro */
  23397. /* Unsynced */
  23398. /* Selected */
  23399. /* CodeName */
  23400. if(ws['!margins']) {
  23401. o.push("<PageSetup>");
  23402. if(ws['!margins'].header) o.push(writextag("Header", null, {'x:Margin':ws['!margins'].header}));
  23403. if(ws['!margins'].footer) o.push(writextag("Footer", null, {'x:Margin':ws['!margins'].footer}));
  23404. o.push(writextag("PageMargins", null, {
  23405. 'x:Bottom': ws['!margins'].bottom || "0.75",
  23406. 'x:Left': ws['!margins'].left || "0.7",
  23407. 'x:Right': ws['!margins'].right || "0.7",
  23408. 'x:Top': ws['!margins'].top || "0.75"
  23409. }));
  23410. o.push("</PageSetup>");
  23411. }
  23412. /* PageSetup */
  23413. /* DisplayPageBreak */
  23414. /* TransitionExpressionEvaluation */
  23415. /* TransitionFormulaEntry */
  23416. /* Print */
  23417. /* Zoom */
  23418. /* PageLayoutZoom */
  23419. /* PageBreakZoom */
  23420. /* ShowPageBreakZoom */
  23421. /* DefaultRowHeight */
  23422. /* DefaultColumnWidth */
  23423. /* StandardWidth */
  23424. if(wb && wb.Workbook && wb.Workbook.Sheets && wb.Workbook.Sheets[idx]) {
  23425. /* Visible */
  23426. if(wb.Workbook.Sheets[idx].Hidden) o.push(writextag("Visible", (wb.Workbook.Sheets[idx].Hidden == 1 ? "SheetHidden" : "SheetVeryHidden"), {}));
  23427. else {
  23428. /* Selected */
  23429. for(var i = 0; i < idx; ++i) if(wb.Workbook.Sheets[i] && !wb.Workbook.Sheets[i].Hidden) break;
  23430. if(i == idx) o.push("<Selected/>");
  23431. }
  23432. }
  23433. /* LeftColumnVisible */
  23434. if(((((wb||{}).Workbook||{}).Views||[])[0]||{}).RTL) o.push("<DisplayRightToLeft/>");
  23435. /* GridlineColorIndex */
  23436. /* DisplayFormulas */
  23437. /* DoNotDisplayGridlines */
  23438. /* DoNotDisplayHeadings */
  23439. /* DoNotDisplayOutline */
  23440. /* ApplyAutomaticOutlineStyles */
  23441. /* NoSummaryRowsBelowDetail */
  23442. /* NoSummaryColumnsRightDetail */
  23443. /* DoNotDisplayZeros */
  23444. /* ActiveRow */
  23445. /* ActiveColumn */
  23446. /* FilterOn */
  23447. /* RangeSelection */
  23448. /* TopRowVisible */
  23449. /* TopRowBottomPane */
  23450. /* LeftColumnRightPane */
  23451. /* ActivePane */
  23452. /* SplitHorizontal */
  23453. /* SplitVertical */
  23454. /* FreezePanes */
  23455. /* FrozenNoSplit */
  23456. /* TabColorIndex */
  23457. /* Panes */
  23458. /* NOTE: Password not supported in XLML Format */
  23459. if(ws['!protect']) {
  23460. o.push(writetag("ProtectContents", "True"));
  23461. if(ws['!protect'].objects) o.push(writetag("ProtectObjects", "True"));
  23462. if(ws['!protect'].scenarios) o.push(writetag("ProtectScenarios", "True"));
  23463. if(ws['!protect'].selectLockedCells != null && !ws['!protect'].selectLockedCells) o.push(writetag("EnableSelection", "NoSelection"));
  23464. else if(ws['!protect'].selectUnlockedCells != null && !ws['!protect'].selectUnlockedCells) o.push(writetag("EnableSelection", "UnlockedCells"));
  23465. [
  23466. [ "formatCells", "AllowFormatCells" ],
  23467. [ "formatColumns", "AllowSizeCols" ],
  23468. [ "formatRows", "AllowSizeRows" ],
  23469. [ "insertColumns", "AllowInsertCols" ],
  23470. [ "insertRows", "AllowInsertRows" ],
  23471. [ "insertHyperlinks", "AllowInsertHyperlinks" ],
  23472. [ "deleteColumns", "AllowDeleteCols" ],
  23473. [ "deleteRows", "AllowDeleteRows" ],
  23474. [ "sort", "AllowSort" ],
  23475. [ "autoFilter", "AllowFilter" ],
  23476. [ "pivotTables", "AllowUsePivotTables" ]
  23477. ].forEach(function(x) { if(ws['!protect'][x[0]]) o.push("<"+x[1]+"/>"); });
  23478. }
  23479. if(o.length == 0) return "";
  23480. return writextag("WorksheetOptions", o.join(""), {xmlns:XLMLNS.x});
  23481. }
  23482. function write_ws_xlml_comment(comments) {
  23483. return comments.map(function(c) {
  23484. // TODO: formatted text
  23485. var t = xlml_unfixstr(c.t||"");
  23486. var d =writextag("ss:Data", t, {"xmlns":"http://www.w3.org/TR/REC-html40"});
  23487. return writextag("Comment", d, {"ss:Author":c.a});
  23488. }).join("");
  23489. }
  23490. function write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr){
  23491. if(!cell || (cell.v == undefined && cell.f == undefined)) return "";
  23492. var attr = {};
  23493. if(cell.f) attr["ss:Formula"] = "=" + escapexml(a1_to_rc(cell.f, addr));
  23494. if(cell.F && cell.F.slice(0, ref.length) == ref) {
  23495. var end = decode_cell(cell.F.slice(ref.length + 1));
  23496. attr["ss:ArrayRange"] = "RC:R" + (end.r == addr.r ? "" : "[" + (end.r - addr.r) + "]") + "C" + (end.c == addr.c ? "" : "[" + (end.c - addr.c) + "]");
  23497. }
  23498. if(cell.l && cell.l.Target) {
  23499. attr["ss:HRef"] = escapexml(cell.l.Target);
  23500. if(cell.l.Tooltip) attr["x:HRefScreenTip"] = escapexml(cell.l.Tooltip);
  23501. }
  23502. if(ws['!merges']) {
  23503. var marr = ws['!merges'];
  23504. for(var mi = 0; mi != marr.length; ++mi) {
  23505. if(marr[mi].s.c != addr.c || marr[mi].s.r != addr.r) continue;
  23506. if(marr[mi].e.c > marr[mi].s.c) attr['ss:MergeAcross'] = marr[mi].e.c - marr[mi].s.c;
  23507. if(marr[mi].e.r > marr[mi].s.r) attr['ss:MergeDown'] = marr[mi].e.r - marr[mi].s.r;
  23508. }
  23509. }
  23510. var t = "", p = "";
  23511. switch(cell.t) {
  23512. case 'z': if(!opts.sheetStubs) return ""; break;
  23513. case 'n': t = 'Number'; p = String(cell.v); break;
  23514. case 'b': t = 'Boolean'; p = (cell.v ? "1" : "0"); break;
  23515. case 'e': t = 'Error'; p = BErr[cell.v]; break;
  23516. case 'd': t = 'DateTime'; p = new Date(cell.v).toISOString(); if(cell.z == null) cell.z = cell.z || SSF._table[14]; break;
  23517. case 's': t = 'String'; p = escapexlml(cell.v||""); break;
  23518. }
  23519. /* TODO: cell style */
  23520. var os = get_cell_style(opts.cellXfs, cell, opts);
  23521. attr["ss:StyleID"] = "s" + (21+os);
  23522. attr["ss:Index"] = addr.c + 1;
  23523. var _v = (cell.v != null ? p : "");
  23524. var m = cell.t == 'z' ? "" : ('<Data ss:Type="' + t + '">' + _v + '</Data>');
  23525. if((cell.c||[]).length > 0) m += write_ws_xlml_comment(cell.c);
  23526. return writextag("Cell", m, attr);
  23527. }
  23528. function write_ws_xlml_row(R, row) {
  23529. var o = '<Row ss:Index="' + (R+1) + '"';
  23530. if(row) {
  23531. if(row.hpt && !row.hpx) row.hpx = pt2px(row.hpt);
  23532. if(row.hpx) o += ' ss:AutoFitHeight="0" ss:Height="' + row.hpx + '"';
  23533. if(row.hidden) o += ' ss:Hidden="1"';
  23534. }
  23535. return o + '>';
  23536. }
  23537. /* TODO */
  23538. function write_ws_xlml_table(ws, opts, idx, wb) {
  23539. if(!ws['!ref']) return "";
  23540. var range = safe_decode_range(ws['!ref']);
  23541. var marr = ws['!merges'] || [], mi = 0;
  23542. var o = [];
  23543. if(ws['!cols']) ws['!cols'].forEach(function(n, i) {
  23544. process_col(n);
  23545. var w = !!n.width;
  23546. var p = col_obj_w(i, n);
  23547. var k = {"ss:Index":i+1};
  23548. if(w) k['ss:Width'] = width2px(p.width);
  23549. if(n.hidden) k['ss:Hidden']="1";
  23550. o.push(writextag("Column",null,k));
  23551. });
  23552. var dense = Array.isArray(ws);
  23553. for(var R = range.s.r; R <= range.e.r; ++R) {
  23554. var row = [write_ws_xlml_row(R, (ws['!rows']||[])[R])];
  23555. for(var C = range.s.c; C <= range.e.c; ++C) {
  23556. var skip = false;
  23557. for(mi = 0; mi != marr.length; ++mi) {
  23558. if(marr[mi].s.c > C) continue;
  23559. if(marr[mi].s.r > R) continue;
  23560. if(marr[mi].e.c < C) continue;
  23561. if(marr[mi].e.r < R) continue;
  23562. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  23563. break;
  23564. }
  23565. if(skip) continue;
  23566. var addr = {r:R,c:C};
  23567. var ref = encode_cell(addr), cell = dense ? (ws[R]||[])[C] : ws[ref];
  23568. row.push(write_ws_xlml_cell(cell, ref, ws, opts, idx, wb, addr));
  23569. }
  23570. row.push("</Row>");
  23571. if(row.length > 2) o.push(row.join(""));
  23572. }
  23573. return o.join("");
  23574. }
  23575. function write_ws_xlml(idx, opts, wb) {
  23576. var o = [];
  23577. var s = wb.SheetNames[idx];
  23578. var ws = wb.Sheets[s];
  23579. var t = ws ? write_ws_xlml_names(ws, opts, idx, wb) : "";
  23580. if(t.length > 0) o.push("<Names>" + t + "</Names>");
  23581. /* Table */
  23582. t = ws ? write_ws_xlml_table(ws, opts, idx, wb) : "";
  23583. if(t.length > 0) o.push("<Table>" + t + "</Table>");
  23584. /* WorksheetOptions */
  23585. o.push(write_ws_xlml_wsopts(ws, opts, idx, wb));
  23586. return o.join("");
  23587. }
  23588. function write_xlml(wb, opts) {
  23589. if(!opts) opts = {};
  23590. if(!wb.SSF) wb.SSF = SSF.get_table();
  23591. if(wb.SSF) {
  23592. make_ssf(SSF); SSF.load_table(wb.SSF);
  23593. // $FlowIgnore
  23594. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  23595. opts.ssf = wb.SSF;
  23596. opts.cellXfs = [];
  23597. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  23598. }
  23599. var d = [];
  23600. d.push(write_props_xlml(wb, opts));
  23601. d.push(write_wb_xlml(wb, opts));
  23602. d.push("");
  23603. d.push("");
  23604. for(var i = 0; i < wb.SheetNames.length; ++i)
  23605. d.push(writextag("Worksheet", write_ws_xlml(i, opts, wb), {"ss:Name":escapexml(wb.SheetNames[i])}));
  23606. d[2] = write_sty_xlml(wb, opts);
  23607. d[3] = write_names_xlml(wb, opts);
  23608. return XML_HEADER + writextag("Workbook", d.join(""), {
  23609. 'xmlns': XLMLNS.ss,
  23610. 'xmlns:o': XLMLNS.o,
  23611. 'xmlns:x': XLMLNS.x,
  23612. 'xmlns:ss': XLMLNS.ss,
  23613. 'xmlns:dt': XLMLNS.dt,
  23614. 'xmlns:html': XLMLNS.html
  23615. });
  23616. }
  23617. /* [MS-OLEDS] 2.3.8 CompObjStream */
  23618. function parse_compobj(obj) {
  23619. var v = {};
  23620. var o = obj.content;
  23621. /* [MS-OLEDS] 2.3.7 CompObjHeader -- All fields MUST be ignored */
  23622. o.l = 28;
  23623. v.AnsiUserType = o.read_shift(0, "lpstr-ansi");
  23624. v.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o);
  23625. if(o.length - o.l <= 4) return v;
  23626. var m = o.read_shift(4);
  23627. if(m == 0 || m > 40) return v;
  23628. o.l-=4; v.Reserved1 = o.read_shift(0, "lpstr-ansi");
  23629. if(o.length - o.l <= 4) return v;
  23630. m = o.read_shift(4);
  23631. if(m !== 0x71b239f4) return v;
  23632. v.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o);
  23633. m = o.read_shift(4);
  23634. if(m == 0 || m > 40) return v;
  23635. o.l-=4; v.Reserved2 = o.read_shift(0, "lpwstr");
  23636. }
  23637. /*
  23638. Continue logic for:
  23639. - 2.4.58 Continue
  23640. - 2.4.59 ContinueBigName
  23641. - 2.4.60 ContinueFrt
  23642. - 2.4.61 ContinueFrt11
  23643. - 2.4.62 ContinueFrt12
  23644. */
  23645. function slurp(R, blob, length, opts) {
  23646. var l = length;
  23647. var bufs = [];
  23648. var d = blob.slice(blob.l,blob.l+l);
  23649. if(opts && opts.enc && opts.enc.insitu && d.length > 0) switch(R.n) {
  23650. case 'BOF': case 'FilePass': case 'FileLock': case 'InterfaceHdr': case 'RRDInfo': case 'RRDHead': case 'UsrExcl': case 'EOF':
  23651. break;
  23652. case 'BoundSheet8':
  23653. break;
  23654. default:
  23655. opts.enc.insitu(d);
  23656. }
  23657. bufs.push(d);
  23658. blob.l += l;
  23659. var next = (XLSRecordEnum[__readUInt16LE(blob,blob.l)]);
  23660. var start = 0;
  23661. while(next != null && next.n.slice(0,8) === 'Continue') {
  23662. l = __readUInt16LE(blob,blob.l+2);
  23663. start = blob.l + 4;
  23664. if(next.n == 'ContinueFrt') start += 4;
  23665. else if(next.n.slice(0,11) == 'ContinueFrt') {
  23666. start += 12;
  23667. }
  23668. d = blob.slice(start,blob.l+4+l);
  23669. bufs.push(d);
  23670. blob.l += 4+l;
  23671. next = (XLSRecordEnum[__readUInt16LE(blob, blob.l)]);
  23672. }
  23673. var b = (bconcat(bufs));
  23674. prep_blob(b, 0);
  23675. var ll = 0; b.lens = [];
  23676. for(var j = 0; j < bufs.length; ++j) { b.lens.push(ll); ll += bufs[j].length; }
  23677. if(b.length < length) throw "XLS Record " + (R && R.n || "??") + " Truncated: " + b.length + " < " + length;
  23678. return R.f(b, b.length, opts);
  23679. }
  23680. function safe_format_xf(p, opts, date1904) {
  23681. if(p.t === 'z') return;
  23682. if(!p.XF) return;
  23683. var fmtid = 0;
  23684. try {
  23685. fmtid = p.z || p.XF.numFmtId || 0;
  23686. if(opts.cellNF) p.z = SSF._table[fmtid];
  23687. } catch(e) { if(opts.WTF) throw e; }
  23688. if(!opts || opts.cellText !== false) try {
  23689. if(p.t === 'e') { p.w = p.w || BErr[p.v]; }
  23690. else if(fmtid === 0 || fmtid == "General") {
  23691. if(p.t === 'n') {
  23692. if((p.v|0) === p.v) p.w = SSF._general_int(p.v);
  23693. else p.w = SSF._general_num(p.v);
  23694. }
  23695. else p.w = SSF._general(p.v);
  23696. }
  23697. else p.w = SSF.format(fmtid,p.v, {date1904:!!date1904});
  23698. } catch(e) { if(opts.WTF) throw e; }
  23699. if(opts.cellDates && fmtid && p.t == 'n' && SSF.is_date(SSF._table[fmtid] || String(fmtid))) {
  23700. var _d = SSF.parse_date_code(p.v); if(_d) { p.t = 'd'; p.v = new Date(_d.y, _d.m-1,_d.d,_d.H,_d.M,_d.S,_d.u); }
  23701. }
  23702. }
  23703. function make_cell(val, ixfe, t) {
  23704. return ({v:val, ixfe:ixfe, t:t});
  23705. }
  23706. // 2.3.2
  23707. function parse_workbook(blob, options) {
  23708. var wb = ({opts:{}});
  23709. var Sheets = {};
  23710. if(DENSE != null && options.dense == null) options.dense = DENSE;
  23711. var out = ((options.dense ? [] : {}));
  23712. var Directory = {};
  23713. var range = ({});
  23714. var last_formula = null;
  23715. var sst = ([]);
  23716. var cur_sheet = "";
  23717. var Preamble = {};
  23718. var lastcell, last_cell = "", cc, cmnt, rngC, rngR;
  23719. var sharedf = {};
  23720. var arrayf = [];
  23721. var temp_val;
  23722. var country;
  23723. var cell_valid = true;
  23724. var XFs = []; /* XF records */
  23725. var palette = [];
  23726. var Workbook = ({ Sheets:[], WBProps:{date1904:false}, Views:[{}] }), wsprops = {};
  23727. var get_rgb = function getrgb(icv) {
  23728. if(icv < 8) return XLSIcv[icv];
  23729. if(icv < 64) return palette[icv-8] || XLSIcv[icv];
  23730. return XLSIcv[icv];
  23731. };
  23732. var process_cell_style = function pcs(cell, line, options) {
  23733. var xfd = line.XF.data;
  23734. if(!xfd || !xfd.patternType || !options || !options.cellStyles) return;
  23735. line.s = ({});
  23736. line.s.patternType = xfd.patternType;
  23737. var t;
  23738. if((t = rgb2Hex(get_rgb(xfd.icvFore)))) { line.s.fgColor = {rgb:t}; }
  23739. if((t = rgb2Hex(get_rgb(xfd.icvBack)))) { line.s.bgColor = {rgb:t}; }
  23740. };
  23741. var addcell = function addcell(cell, line, options) {
  23742. if(file_depth > 1) return;
  23743. if(options.sheetRows && cell.r >= options.sheetRows) cell_valid = false;
  23744. if(!cell_valid) return;
  23745. if(options.cellStyles && line.XF && line.XF.data) process_cell_style(cell, line, options);
  23746. delete line.ixfe; delete line.XF;
  23747. lastcell = cell;
  23748. last_cell = encode_cell(cell);
  23749. if(!range || !range.s || !range.e) range = {s:{r:0,c:0},e:{r:0,c:0}};
  23750. if(cell.r < range.s.r) range.s.r = cell.r;
  23751. if(cell.c < range.s.c) range.s.c = cell.c;
  23752. if(cell.r + 1 > range.e.r) range.e.r = cell.r + 1;
  23753. if(cell.c + 1 > range.e.c) range.e.c = cell.c + 1;
  23754. if(options.cellFormula && line.f) {
  23755. for(var afi = 0; afi < arrayf.length; ++afi) {
  23756. if(arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue;
  23757. if(arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue;
  23758. line.F = encode_range(arrayf[afi][0]);
  23759. if(arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f;
  23760. if(line.f) line.f = "" + stringify_formula(arrayf[afi][1], range, cell, supbooks, opts);
  23761. break;
  23762. }
  23763. }
  23764. {
  23765. if(options.dense) {
  23766. if(!out[cell.r]) out[cell.r] = [];
  23767. out[cell.r][cell.c] = line;
  23768. } else out[last_cell] = line;
  23769. }
  23770. };
  23771. var opts = ({
  23772. enc: false, // encrypted
  23773. sbcch: 0, // cch in the preceding SupBook
  23774. snames: [], // sheetnames
  23775. sharedf: sharedf, // shared formulae by address
  23776. arrayf: arrayf, // array formulae array
  23777. rrtabid: [], // RRTabId
  23778. lastuser: "", // Last User from WriteAccess
  23779. biff: 8, // BIFF version
  23780. codepage: 0, // CP from CodePage record
  23781. winlocked: 0, // fLockWn from WinProtect
  23782. cellStyles: !!options && !!options.cellStyles,
  23783. WTF: !!options && !!options.wtf
  23784. });
  23785. if(options.password) opts.password = options.password;
  23786. var themes;
  23787. var merges = [];
  23788. var objects = [];
  23789. var colinfo = [], rowinfo = [];
  23790. // eslint-disable-next-line no-unused-vars
  23791. var defwidth = 0, defheight = 0; // twips / MDW respectively
  23792. var seencol = false;
  23793. var supbooks = ([]); // 1-indexed, will hold extern names
  23794. supbooks.SheetNames = opts.snames;
  23795. supbooks.sharedf = opts.sharedf;
  23796. supbooks.arrayf = opts.arrayf;
  23797. supbooks.names = [];
  23798. supbooks.XTI = [];
  23799. var last_Rn = '';
  23800. var file_depth = 0; /* TODO: make a real stack */
  23801. var BIFF2Fmt = 0, BIFF2FmtTable = [];
  23802. var FilterDatabases = []; /* TODO: sort out supbooks and process elsewhere */
  23803. var last_lbl;
  23804. /* explicit override for some broken writers */
  23805. opts.codepage = 1200;
  23806. set_cp(1200);
  23807. var seen_codepage = false;
  23808. while(blob.l < blob.length - 1) {
  23809. var s = blob.l;
  23810. var RecordType = blob.read_shift(2);
  23811. if(RecordType === 0 && last_Rn === 'EOF') break;
  23812. var length = (blob.l === blob.length ? 0 : blob.read_shift(2));
  23813. var R = XLSRecordEnum[RecordType];
  23814. //console.log(RecordType.toString(16), RecordType, R, blob.l, length, blob.length);
  23815. //if(!R) console.log(blob.slice(blob.l, blob.l + length));
  23816. if(R && R.f) {
  23817. if(options.bookSheets) {
  23818. if(last_Rn === 'BoundSheet8' && R.n !== 'BoundSheet8') break;
  23819. }
  23820. last_Rn = R.n;
  23821. if(R.r === 2 || R.r == 12) {
  23822. var rt = blob.read_shift(2); length -= 2;
  23823. if(!opts.enc && rt !== RecordType && (((rt&0xFF)<<8)|(rt>>8)) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType);
  23824. if(R.r == 12){ blob.l += 10; length -= 10; } // skip FRT
  23825. }
  23826. //console.error(R,blob.l,length,blob.length);
  23827. var val = ({});
  23828. if(R.n === 'EOF') val = R.f(blob, length, opts);
  23829. else val = slurp(R, blob, length, opts);
  23830. var Rn = R.n;
  23831. if(file_depth == 0 && Rn != 'BOF') continue;
  23832. /* nested switch statements to workaround V8 128 limit */
  23833. switch(Rn) {
  23834. /* Workbook Options */
  23835. case 'Date1904':
  23836. wb.opts.Date1904 = Workbook.WBProps.date1904 = val; break;
  23837. case 'WriteProtect': wb.opts.WriteProtect = true; break;
  23838. case 'FilePass':
  23839. if(!opts.enc) blob.l = 0;
  23840. opts.enc = val;
  23841. if(!options.password) throw new Error("File is password-protected");
  23842. if(val.valid == null) throw new Error("Encryption scheme unsupported");
  23843. if(!val.valid) throw new Error("Password is incorrect");
  23844. break;
  23845. case 'WriteAccess': opts.lastuser = val; break;
  23846. case 'FileSharing': break; //TODO
  23847. case 'CodePage':
  23848. var cpval = Number(val);
  23849. /* overrides based on test cases */
  23850. switch(cpval) {
  23851. case 0x5212: cpval = 1200; break;
  23852. case 0x8000: cpval = 10000; break;
  23853. case 0x8001: cpval = 1252; break;
  23854. }
  23855. set_cp(opts.codepage = cpval);
  23856. seen_codepage = true;
  23857. break;
  23858. case 'RRTabId': opts.rrtabid = val; break;
  23859. case 'WinProtect': opts.winlocked = val; break;
  23860. case 'Template': break; // TODO
  23861. case 'BookBool': break; // TODO
  23862. case 'UsesELFs': break;
  23863. case 'MTRSettings': break;
  23864. case 'RefreshAll':
  23865. case 'CalcCount':
  23866. case 'CalcDelta':
  23867. case 'CalcIter':
  23868. case 'CalcMode':
  23869. case 'CalcPrecision':
  23870. case 'CalcSaveRecalc':
  23871. wb.opts[Rn] = val; break;
  23872. case 'CalcRefMode': opts.CalcRefMode = val; break; // TODO: implement R1C1
  23873. case 'Uncalced': break;
  23874. case 'ForceFullCalculation': wb.opts.FullCalc = val; break;
  23875. case 'WsBool':
  23876. if(val.fDialog) out["!type"] = "dialog";
  23877. break; // TODO
  23878. case 'XF':
  23879. XFs.push(val); break;
  23880. case 'ExtSST': break; // TODO
  23881. case 'BookExt': break; // TODO
  23882. case 'RichTextStream': break;
  23883. case 'BkHim': break;
  23884. case 'SupBook':
  23885. supbooks.push([val]);
  23886. supbooks[supbooks.length-1].XTI = [];
  23887. break;
  23888. case 'ExternName':
  23889. supbooks[supbooks.length-1].push(val);
  23890. break;
  23891. case 'Index': break; // TODO
  23892. case 'Lbl':
  23893. last_lbl = ({
  23894. Name: val.Name,
  23895. Ref: stringify_formula(val.rgce,range,null,supbooks,opts)
  23896. });
  23897. if(val.itab > 0) last_lbl.Sheet = val.itab - 1;
  23898. supbooks.names.push(last_lbl);
  23899. if(!supbooks[0]) { supbooks[0] = []; supbooks[0].XTI = []; }
  23900. supbooks[supbooks.length-1].push(val);
  23901. if(val.Name == "_xlnm._FilterDatabase" && val.itab > 0)
  23902. if(val.rgce && val.rgce[0] && val.rgce[0][0] && val.rgce[0][0][0] == 'PtgArea3d')
  23903. FilterDatabases[val.itab - 1] = { ref: encode_range(val.rgce[0][0][1][2]) };
  23904. break;
  23905. case 'ExternCount': opts.ExternCount = val; break;
  23906. case 'ExternSheet':
  23907. if(supbooks.length == 0) { supbooks[0] = []; supbooks[0].XTI = []; }
  23908. supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val); supbooks.XTI = supbooks.XTI.concat(val); break;
  23909. case 'NameCmt':
  23910. /* TODO: search for correct name */
  23911. if(opts.biff < 8) break;
  23912. if(last_lbl != null) last_lbl.Comment = val[1];
  23913. break;
  23914. case 'Protect': out["!protect"] = val; break; /* for sheet or book */
  23915. case 'Password': if(val !== 0 && opts.WTF) console.error("Password verifier: " + val); break;
  23916. case 'Prot4Rev': case 'Prot4RevPass': break; /*TODO: Revision Control*/
  23917. case 'BoundSheet8': {
  23918. Directory[val.pos] = val;
  23919. opts.snames.push(val.name);
  23920. } break;
  23921. case 'EOF': {
  23922. if(--file_depth) break;
  23923. if(range.e) {
  23924. if(range.e.r > 0 && range.e.c > 0) {
  23925. range.e.r--; range.e.c--;
  23926. out["!ref"] = encode_range(range);
  23927. if(options.sheetRows && options.sheetRows <= range.e.r) {
  23928. var tmpri = range.e.r;
  23929. range.e.r = options.sheetRows - 1;
  23930. out["!fullref"] = out["!ref"];
  23931. out["!ref"] = encode_range(range);
  23932. range.e.r = tmpri;
  23933. }
  23934. range.e.r++; range.e.c++;
  23935. }
  23936. if(merges.length > 0) out["!merges"] = merges;
  23937. if(objects.length > 0) out["!objects"] = objects;
  23938. if(colinfo.length > 0) out["!cols"] = colinfo;
  23939. if(rowinfo.length > 0) out["!rows"] = rowinfo;
  23940. Workbook.Sheets.push(wsprops);
  23941. }
  23942. if(cur_sheet === "") Preamble = out; else Sheets[cur_sheet] = out;
  23943. out = ((options.dense ? [] : {}));
  23944. } break;
  23945. case 'BOF': {
  23946. if(opts.biff === 8) opts.biff = {
  23947. 0x0009:2,
  23948. 0x0209:3,
  23949. 0x0409:4
  23950. }[RecordType] || {
  23951. 0x0200:2,
  23952. 0x0300:3,
  23953. 0x0400:4,
  23954. 0x0500:5,
  23955. 0x0600:8,
  23956. 0x0002:2,
  23957. 0x0007:2
  23958. }[val.BIFFVer] || 8;
  23959. if(opts.biff == 8 && val.BIFFVer == 0 && val.dt == 16) opts.biff = 2;
  23960. if(file_depth++) break;
  23961. cell_valid = true;
  23962. out = ((options.dense ? [] : {}));
  23963. if(opts.biff < 8 && !seen_codepage) { seen_codepage = true; set_cp(opts.codepage = options.codepage || 1252); }
  23964. if(opts.biff < 5) {
  23965. if(cur_sheet === "") cur_sheet = "Sheet1";
  23966. range = {s:{r:0,c:0},e:{r:0,c:0}};
  23967. /* fake BoundSheet8 */
  23968. var fakebs8 = {pos: blob.l - length, name:cur_sheet};
  23969. Directory[fakebs8.pos] = fakebs8;
  23970. opts.snames.push(cur_sheet);
  23971. }
  23972. else cur_sheet = (Directory[s] || {name:""}).name;
  23973. if(val.dt == 0x20) out["!type"] = "chart";
  23974. if(val.dt == 0x40) out["!type"] = "macro";
  23975. merges = [];
  23976. objects = [];
  23977. opts.arrayf = arrayf = [];
  23978. colinfo = []; rowinfo = [];
  23979. defwidth = defheight = 0;
  23980. seencol = false;
  23981. wsprops = {Hidden:(Directory[s]||{hs:0}).hs, name:cur_sheet };
  23982. } break;
  23983. case 'Number': case 'BIFF2NUM': case 'BIFF2INT': {
  23984. if(out["!type"] == "chart") if(options.dense ? (out[val.r]||[])[val.c]: out[encode_cell({c:val.c, r:val.r})]) ++val.c;
  23985. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe]||{}, v:val.val, t:'n'});
  23986. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  23987. safe_format_xf(temp_val, options, wb.opts.Date1904);
  23988. addcell({c:val.c, r:val.r}, temp_val, options);
  23989. } break;
  23990. case 'BoolErr': {
  23991. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.val, t:val.t});
  23992. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  23993. safe_format_xf(temp_val, options, wb.opts.Date1904);
  23994. addcell({c:val.c, r:val.r}, temp_val, options);
  23995. } break;
  23996. case 'RK': {
  23997. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], v:val.rknum, t:'n'});
  23998. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  23999. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24000. addcell({c:val.c, r:val.r}, temp_val, options);
  24001. } break;
  24002. case 'MulRk': {
  24003. for(var j = val.c; j <= val.C; ++j) {
  24004. var ixfe = val.rkrec[j-val.c][0];
  24005. temp_val= ({ixfe:ixfe, XF:XFs[ixfe], v:val.rkrec[j-val.c][1], t:'n'});
  24006. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24007. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24008. addcell({c:j, r:val.r}, temp_val, options);
  24009. }
  24010. } break;
  24011. case 'Formula': {
  24012. if(val.val == 'String') { last_formula = val; break; }
  24013. temp_val = make_cell(val.val, val.cell.ixfe, val.tt);
  24014. temp_val.XF = XFs[temp_val.ixfe];
  24015. if(options.cellFormula) {
  24016. var _f = val.formula;
  24017. if(_f && _f[0] && _f[0][0] && _f[0][0][0] == 'PtgExp') {
  24018. var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1];
  24019. var _fe = encode_cell({r:_fr, c:_fc});
  24020. if(sharedf[_fe]) temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  24021. else temp_val.F = ((options.dense ? (out[_fr]||[])[_fc]: out[_fe]) || {}).F;
  24022. } else temp_val.f = ""+stringify_formula(val.formula,range,val.cell,supbooks, opts);
  24023. }
  24024. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24025. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24026. addcell(val.cell, temp_val, options);
  24027. last_formula = val;
  24028. } break;
  24029. case 'String': {
  24030. if(last_formula) { /* technically always true */
  24031. last_formula.val = val;
  24032. temp_val = make_cell(val, last_formula.cell.ixfe, 's');
  24033. temp_val.XF = XFs[temp_val.ixfe];
  24034. if(options.cellFormula) {
  24035. temp_val.f = ""+stringify_formula(last_formula.formula, range, last_formula.cell, supbooks, opts);
  24036. }
  24037. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24038. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24039. addcell(last_formula.cell, temp_val, options);
  24040. last_formula = null;
  24041. } else throw new Error("String record expects Formula");
  24042. } break;
  24043. case 'Array': {
  24044. arrayf.push(val);
  24045. var _arraystart = encode_cell(val[0].s);
  24046. cc = options.dense ? (out[val[0].s.r]||[])[val[0].s.c] : out[_arraystart];
  24047. if(options.cellFormula && cc) {
  24048. if(!last_formula) break; /* technically unreachable */
  24049. if(!_arraystart || !cc) break;
  24050. cc.f = ""+stringify_formula(val[1], range, val[0], supbooks, opts);
  24051. cc.F = encode_range(val[0]);
  24052. }
  24053. } break;
  24054. case 'ShrFmla': {
  24055. if(!cell_valid) break;
  24056. if(!options.cellFormula) break;
  24057. if(last_cell) {
  24058. /* TODO: capture range */
  24059. if(!last_formula) break; /* technically unreachable */
  24060. sharedf[encode_cell(last_formula.cell)]= val[0];
  24061. cc = options.dense ? (out[last_formula.cell.r]||[])[last_formula.cell.c] : out[encode_cell(last_formula.cell)];
  24062. (cc||{}).f = ""+stringify_formula(val[0], range, lastcell, supbooks, opts);
  24063. }
  24064. } break;
  24065. case 'LabelSst':
  24066. temp_val=make_cell(sst[val.isst].t, val.ixfe, 's');
  24067. if(sst[val.isst].h) temp_val.h = sst[val.isst].h;
  24068. temp_val.XF = XFs[temp_val.ixfe];
  24069. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24070. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24071. addcell({c:val.c, r:val.r}, temp_val, options);
  24072. break;
  24073. case 'Blank': if(options.sheetStubs) {
  24074. temp_val = ({ixfe: val.ixfe, XF: XFs[val.ixfe], t:'z'});
  24075. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24076. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24077. addcell({c:val.c, r:val.r}, temp_val, options);
  24078. } break;
  24079. case 'MulBlank': if(options.sheetStubs) {
  24080. for(var _j = val.c; _j <= val.C; ++_j) {
  24081. var _ixfe = val.ixfe[_j-val.c];
  24082. temp_val= ({ixfe:_ixfe, XF:XFs[_ixfe], t:'z'});
  24083. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24084. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24085. addcell({c:_j, r:val.r}, temp_val, options);
  24086. }
  24087. } break;
  24088. case 'RString':
  24089. case 'Label': case 'BIFF2STR':
  24090. temp_val=make_cell(val.val, val.ixfe, 's');
  24091. temp_val.XF = XFs[temp_val.ixfe];
  24092. if(BIFF2Fmt > 0) temp_val.z = BIFF2FmtTable[(temp_val.ixfe>>8) & 0x1F];
  24093. safe_format_xf(temp_val, options, wb.opts.Date1904);
  24094. addcell({c:val.c, r:val.r}, temp_val, options);
  24095. break;
  24096. case 'Dimensions': {
  24097. if(file_depth === 1) range = val; /* TODO: stack */
  24098. } break;
  24099. case 'SST': {
  24100. sst = val;
  24101. } break;
  24102. case 'Format': { /* val = [id, fmt] */
  24103. if(opts.biff == 4) {
  24104. BIFF2FmtTable[BIFF2Fmt++] = val[1];
  24105. for(var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if(SSF._table[b4idx] == val[1]) break;
  24106. if(b4idx >= 163) SSF.load(val[1], BIFF2Fmt + 163);
  24107. }
  24108. else SSF.load(val[1], val[0]);
  24109. } break;
  24110. case 'BIFF2FORMAT': {
  24111. BIFF2FmtTable[BIFF2Fmt++] = val;
  24112. for(var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if(SSF._table[b2idx] == val) break;
  24113. if(b2idx >= 163) SSF.load(val, BIFF2Fmt + 163);
  24114. } break;
  24115. case 'MergeCells': merges = merges.concat(val); break;
  24116. case 'Obj': objects[val.cmo[0]] = opts.lastobj = val; break;
  24117. case 'TxO': opts.lastobj.TxO = val; break;
  24118. case 'ImData': opts.lastobj.ImData = val; break;
  24119. case 'HLink': {
  24120. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  24121. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  24122. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  24123. if(cc) cc.l = val[1];
  24124. }
  24125. } break;
  24126. case 'HLinkTooltip': {
  24127. for(rngR = val[0].s.r; rngR <= val[0].e.r; ++rngR)
  24128. for(rngC = val[0].s.c; rngC <= val[0].e.c; ++rngC) {
  24129. cc = options.dense ? (out[rngR]||[])[rngC] : out[encode_cell({c:rngC,r:rngR})];
  24130. if(cc && cc.l) cc.l.Tooltip = val[1];
  24131. }
  24132. } break;
  24133. /* Comments */
  24134. case 'Note': {
  24135. if(opts.biff <= 5 && opts.biff >= 2) break; /* TODO: BIFF5 */
  24136. cc = options.dense ? (out[val[0].r]||[])[val[0].c] : out[encode_cell(val[0])];
  24137. var noteobj = objects[val[2]];
  24138. if(!cc) {
  24139. if(options.dense) {
  24140. if(!out[val[0].r]) out[val[0].r] = [];
  24141. cc = out[val[0].r][val[0].c] = ({t:"z"});
  24142. } else {
  24143. cc = out[encode_cell(val[0])] = ({t:"z"});
  24144. }
  24145. range.e.r = Math.max(range.e.r, val[0].r);
  24146. range.s.r = Math.min(range.s.r, val[0].r);
  24147. range.e.c = Math.max(range.e.c, val[0].c);
  24148. range.s.c = Math.min(range.s.c, val[0].c);
  24149. }
  24150. if(!cc.c) cc.c = [];
  24151. cmnt = {a:val[1],t:noteobj.TxO.t};
  24152. cc.c.push(cmnt);
  24153. } break;
  24154. default: switch(R.n) { /* nested */
  24155. case 'ClrtClient': break;
  24156. case 'XFExt': update_xfext(XFs[val.ixfe], val.ext); break;
  24157. case 'DefColWidth': defwidth = val; break;
  24158. case 'DefaultRowHeight': defheight = val[1]; break; // TODO: flags
  24159. case 'ColInfo': {
  24160. if(!opts.cellStyles) break;
  24161. while(val.e >= val.s) {
  24162. colinfo[val.e--] = { width: val.w/256 };
  24163. if(!seencol) { seencol = true; find_mdw_colw(val.w/256); }
  24164. process_col(colinfo[val.e+1]);
  24165. }
  24166. } break;
  24167. case 'Row': {
  24168. var rowobj = {};
  24169. if(val.level != null) { rowinfo[val.r] = rowobj; rowobj.level = val.level; }
  24170. if(val.hidden) { rowinfo[val.r] = rowobj; rowobj.hidden = true; }
  24171. if(val.hpt) {
  24172. rowinfo[val.r] = rowobj;
  24173. rowobj.hpt = val.hpt; rowobj.hpx = pt2px(val.hpt);
  24174. }
  24175. } break;
  24176. case 'LeftMargin':
  24177. case 'RightMargin':
  24178. case 'TopMargin':
  24179. case 'BottomMargin':
  24180. if(!out['!margins']) default_margins(out['!margins'] = {});
  24181. out['!margins'][Rn.slice(0,-6).toLowerCase()] = val;
  24182. break;
  24183. case 'Setup': // TODO
  24184. if(!out['!margins']) default_margins(out['!margins'] = {});
  24185. out['!margins'].header = val.header;
  24186. out['!margins'].footer = val.footer;
  24187. break;
  24188. case 'Window2': // TODO
  24189. // $FlowIgnore
  24190. if(val.RTL) Workbook.Views[0].RTL = true;
  24191. break;
  24192. case 'Header': break; // TODO
  24193. case 'Footer': break; // TODO
  24194. case 'HCenter': break; // TODO
  24195. case 'VCenter': break; // TODO
  24196. case 'Pls': break; // TODO
  24197. case 'GCW': break;
  24198. case 'LHRecord': break;
  24199. case 'DBCell': break; // TODO
  24200. case 'EntExU2': break; // TODO
  24201. case 'SxView': break; // TODO
  24202. case 'Sxvd': break; // TODO
  24203. case 'SXVI': break; // TODO
  24204. case 'SXVDEx': break; // TODO
  24205. case 'SxIvd': break; // TODO
  24206. case 'SXString': break; // TODO
  24207. case 'Sync': break;
  24208. case 'Addin': break;
  24209. case 'SXDI': break; // TODO
  24210. case 'SXLI': break; // TODO
  24211. case 'SXEx': break; // TODO
  24212. case 'QsiSXTag': break; // TODO
  24213. case 'Selection': break;
  24214. case 'Feat': break;
  24215. case 'FeatHdr': case 'FeatHdr11': break;
  24216. case 'Feature11': case 'Feature12': case 'List12': break;
  24217. case 'Country': country = val; break;
  24218. case 'RecalcId': break;
  24219. case 'DxGCol': break; // TODO: htmlify
  24220. case 'Fbi': case 'Fbi2': case 'GelFrame': break;
  24221. case 'Font': break; // TODO
  24222. case 'XFCRC': break; // TODO
  24223. case 'Style': break; // TODO
  24224. case 'StyleExt': break; // TODO
  24225. case 'Palette': palette = val; break;
  24226. case 'Theme': themes = val; break;
  24227. /* Protection */
  24228. case 'ScenarioProtect': break;
  24229. case 'ObjProtect': break;
  24230. /* Conditional Formatting */
  24231. case 'CondFmt12': break;
  24232. /* Table */
  24233. case 'Table': break; // TODO
  24234. case 'TableStyles': break; // TODO
  24235. case 'TableStyle': break; // TODO
  24236. case 'TableStyleElement': break; // TODO
  24237. /* PivotTable */
  24238. case 'SXStreamID': break; // TODO
  24239. case 'SXVS': break; // TODO
  24240. case 'DConRef': break; // TODO
  24241. case 'SXAddl': break; // TODO
  24242. case 'DConBin': break; // TODO
  24243. case 'DConName': break; // TODO
  24244. case 'SXPI': break; // TODO
  24245. case 'SxFormat': break; // TODO
  24246. case 'SxSelect': break; // TODO
  24247. case 'SxRule': break; // TODO
  24248. case 'SxFilt': break; // TODO
  24249. case 'SxItm': break; // TODO
  24250. case 'SxDXF': break; // TODO
  24251. /* Scenario Manager */
  24252. case 'ScenMan': break;
  24253. /* Data Consolidation */
  24254. case 'DCon': break;
  24255. /* Watched Cell */
  24256. case 'CellWatch': break;
  24257. /* Print Settings */
  24258. case 'PrintRowCol': break;
  24259. case 'PrintGrid': break;
  24260. case 'PrintSize': break;
  24261. case 'XCT': break;
  24262. case 'CRN': break;
  24263. case 'Scl': {
  24264. //console.log("Zoom Level:", val[0]/val[1],val);
  24265. } break;
  24266. case 'SheetExt': {
  24267. /* empty */
  24268. } break;
  24269. case 'SheetExtOptional': {
  24270. /* empty */
  24271. } break;
  24272. /* VBA */
  24273. case 'ObNoMacros': {
  24274. /* empty */
  24275. } break;
  24276. case 'ObProj': {
  24277. /* empty */
  24278. } break;
  24279. case 'CodeName': {
  24280. if(!cur_sheet) Workbook.WBProps.CodeName = val || "ThisWorkbook";
  24281. else wsprops.CodeName = val || wsprops.name;
  24282. } break;
  24283. case 'GUIDTypeLib': {
  24284. /* empty */
  24285. } break;
  24286. case 'WOpt': break; // TODO: WTF?
  24287. case 'PhoneticInfo': break;
  24288. case 'OleObjectSize': break;
  24289. /* Differential Formatting */
  24290. case 'DXF': case 'DXFN': case 'DXFN12': case 'DXFN12List': case 'DXFN12NoCB': break;
  24291. /* Data Validation */
  24292. case 'Dv': case 'DVal': break;
  24293. /* Data Series */
  24294. case 'BRAI': case 'Series': case 'SeriesText': break;
  24295. /* Data Connection */
  24296. case 'DConn': break;
  24297. case 'DbOrParamQry': break;
  24298. case 'DBQueryExt': break;
  24299. case 'OleDbConn': break;
  24300. case 'ExtString': break;
  24301. /* Formatting */
  24302. case 'IFmtRecord': break;
  24303. case 'CondFmt': case 'CF': case 'CF12': case 'CFEx': break;
  24304. /* Explicitly Ignored */
  24305. case 'Excel9File': break;
  24306. case 'Units': break;
  24307. case 'InterfaceHdr': case 'Mms': case 'InterfaceEnd': case 'DSF': break;
  24308. case 'BuiltInFnGroupCount': /* 2.4.30 0x0E or 0x10 but excel 2011 generates 0x11? */ break;
  24309. /* View Stuff */
  24310. case 'Window1': case 'HideObj': case 'GridSet': case 'Guts':
  24311. case 'UserBView': case 'UserSViewBegin': case 'UserSViewEnd': break;
  24312. case 'Pane': break;
  24313. default: switch(R.n) { /* nested */
  24314. /* Chart */
  24315. case 'Dat':
  24316. case 'Begin': case 'End':
  24317. case 'StartBlock': case 'EndBlock':
  24318. case 'Frame': case 'Area':
  24319. case 'Axis': case 'AxisLine': case 'Tick': break;
  24320. case 'AxesUsed':
  24321. case 'CrtLayout12': case 'CrtLayout12A': case 'CrtLink': case 'CrtLine': case 'CrtMlFrt': case 'CrtMlFrtContinue': break;
  24322. case 'LineFormat': case 'AreaFormat':
  24323. case 'Chart': case 'Chart3d': case 'Chart3DBarShape': case 'ChartFormat': case 'ChartFrtInfo': break;
  24324. case 'PlotArea': case 'PlotGrowth': break;
  24325. case 'SeriesList': case 'SerParent': case 'SerAuxTrend': break;
  24326. case 'DataFormat': case 'SerToCrt': case 'FontX': break;
  24327. case 'CatSerRange': case 'AxcExt': case 'SerFmt': break;
  24328. case 'ShtProps': break;
  24329. case 'DefaultText': case 'Text': case 'CatLab': break;
  24330. case 'DataLabExtContents': break;
  24331. case 'Legend': case 'LegendException': break;
  24332. case 'Pie': case 'Scatter': break;
  24333. case 'PieFormat': case 'MarkerFormat': break;
  24334. case 'StartObject': case 'EndObject': break;
  24335. case 'AlRuns': case 'ObjectLink': break;
  24336. case 'SIIndex': break;
  24337. case 'AttachedLabel': case 'YMult': break;
  24338. /* Chart Group */
  24339. case 'Line': case 'Bar': break;
  24340. case 'Surf': break;
  24341. /* Axis Group */
  24342. case 'AxisParent': break;
  24343. case 'Pos': break;
  24344. case 'ValueRange': break;
  24345. /* Pivot Chart */
  24346. case 'SXViewEx9': break; // TODO
  24347. case 'SXViewLink': break;
  24348. case 'PivotChartBits': break;
  24349. case 'SBaseRef': break;
  24350. case 'TextPropsStream': break;
  24351. /* Chart Misc */
  24352. case 'LnExt': break;
  24353. case 'MkrExt': break;
  24354. case 'CrtCoopt': break;
  24355. /* Query Table */
  24356. case 'Qsi': case 'Qsif': case 'Qsir': case 'QsiSXTag': break;
  24357. case 'TxtQry': break;
  24358. /* Filter */
  24359. case 'FilterMode': break;
  24360. case 'AutoFilter': case 'AutoFilterInfo': break;
  24361. case 'AutoFilter12': break;
  24362. case 'DropDownObjIds': break;
  24363. case 'Sort': break;
  24364. case 'SortData': break;
  24365. /* Drawing */
  24366. case 'ShapePropsStream': break;
  24367. case 'MsoDrawing': case 'MsoDrawingGroup': case 'MsoDrawingSelection': break;
  24368. /* Pub Stuff */
  24369. case 'WebPub': case 'AutoWebPub': break;
  24370. /* Print Stuff */
  24371. case 'HeaderFooter': case 'HFPicture': case 'PLV':
  24372. case 'HorizontalPageBreaks': case 'VerticalPageBreaks': break;
  24373. /* Behavioral */
  24374. case 'Backup': case 'CompressPictures': case 'Compat12': break;
  24375. /* Should not Happen */
  24376. case 'Continue': case 'ContinueFrt12': break;
  24377. /* Future Records */
  24378. case 'FrtFontList': case 'FrtWrapper': break;
  24379. default: switch(R.n) { /* nested */
  24380. /* BIFF5 records */
  24381. case 'TabIdConf': case 'Radar': case 'RadarArea': case 'DropBar': case 'Intl': case 'CoordList': case 'SerAuxErrBar': break;
  24382. /* BIFF2-4 records */
  24383. case 'BIFF2FONTCLR': case 'BIFF2FMTCNT': case 'BIFF2FONTXTRA': break;
  24384. case 'BIFF2XF': case 'BIFF3XF': case 'BIFF4XF': break;
  24385. case 'BIFF4FMTCNT': case 'BIFF2ROW': case 'BIFF2WINDOW2': break;
  24386. /* Miscellaneous */
  24387. case 'SCENARIO': case 'DConBin': case 'PicF': case 'DataLabExt':
  24388. case 'Lel': case 'BopPop': case 'BopPopCustom': case 'RealTimeData':
  24389. case 'Name': break;
  24390. case 'LHNGraph': case 'FnGroupName': case 'AddMenu': case 'LPr': break;
  24391. case 'ListObj': case 'ListField': break;
  24392. case 'RRSort': break;
  24393. case 'BigName': break;
  24394. case 'ToolbarHdr': case 'ToolbarEnd': break;
  24395. case 'DDEObjName': break;
  24396. case 'FRTArchId$': break;
  24397. default: if(options.WTF) throw 'Unrecognized Record ' + R.n;
  24398. }}}}
  24399. } else blob.l += length;
  24400. }
  24401. wb.SheetNames=keys(Directory).sort(function(a,b) { return Number(a) - Number(b); }).map(function(x){return Directory[x].name;});
  24402. if(!options.bookSheets) wb.Sheets=Sheets;
  24403. if(wb.Sheets) FilterDatabases.forEach(function(r,i) { wb.Sheets[wb.SheetNames[i]]['!autofilter'] = r; });
  24404. wb.Preamble=Preamble;
  24405. wb.Strings = sst;
  24406. wb.SSF = SSF.get_table();
  24407. if(opts.enc) wb.Encryption = opts.enc;
  24408. if(themes) wb.Themes = themes;
  24409. wb.Metadata = {};
  24410. if(country !== undefined) wb.Metadata.Country = country;
  24411. if(supbooks.names.length > 0) Workbook.Names = supbooks.names;
  24412. wb.Workbook = Workbook;
  24413. return wb;
  24414. }
  24415. /* TODO: split props*/
  24416. var PSCLSID = {
  24417. SI: "e0859ff2f94f6810ab9108002b27b3d9",
  24418. DSI: "02d5cdd59c2e1b10939708002b2cf9ae",
  24419. UDI: "05d5cdd59c2e1b10939708002b2cf9ae"
  24420. };
  24421. function parse_xls_props(cfb, props, o) {
  24422. /* [MS-OSHARED] 2.3.3.2.2 Document Summary Information Property Set */
  24423. var DSI = CFB.find(cfb, '!DocumentSummaryInformation');
  24424. if(DSI && DSI.size > 0) try {
  24425. var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI);
  24426. for(var d in DocSummary) props[d] = DocSummary[d];
  24427. } catch(e) {if(o.WTF) throw e;/* empty */}
  24428. /* [MS-OSHARED] 2.3.3.2.1 Summary Information Property Set*/
  24429. var SI = CFB.find(cfb, '!SummaryInformation');
  24430. if(SI && SI.size > 0) try {
  24431. var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI);
  24432. for(var s in Summary) if(props[s] == null) props[s] = Summary[s];
  24433. } catch(e) {if(o.WTF) throw e;/* empty */}
  24434. if(props.HeadingPairs && props.TitlesOfParts) {
  24435. load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o);
  24436. delete props.HeadingPairs; delete props.TitlesOfParts;
  24437. }
  24438. }
  24439. function write_xls_props(wb, cfb) {
  24440. var DSEntries = [], SEntries = [], CEntries = [];
  24441. var i = 0, Keys;
  24442. if(wb.Props) {
  24443. Keys = keys(wb.Props);
  24444. // $FlowIgnore
  24445. for(i = 0; i < Keys.length; ++i) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Props[Keys[i]]]);
  24446. }
  24447. if(wb.Custprops) {
  24448. Keys = keys(wb.Custprops);
  24449. // $FlowIgnore
  24450. for(i = 0; i < Keys.length; ++i) if(!Object.prototype.hasOwnProperty.call((wb.Props||{}), Keys[i])) (Object.prototype.hasOwnProperty.call(DocSummaryRE, Keys[i]) ? DSEntries : Object.prototype.hasOwnProperty.call(SummaryRE, Keys[i]) ? SEntries : CEntries).push([Keys[i], wb.Custprops[Keys[i]]]);
  24451. }
  24452. var CEntries2 = [];
  24453. for(i = 0; i < CEntries.length; ++i) {
  24454. if(XLSPSSkip.indexOf(CEntries[i][0]) > -1) continue;
  24455. if(CEntries[i][1] == null) continue;
  24456. CEntries2.push(CEntries[i]);
  24457. }
  24458. if(SEntries.length) CFB.utils.cfb_add(cfb, "/\u0005SummaryInformation", write_PropertySetStream(SEntries, PSCLSID.SI, SummaryRE, SummaryPIDSI));
  24459. if(DSEntries.length || CEntries2.length) CFB.utils.cfb_add(cfb, "/\u0005DocumentSummaryInformation", write_PropertySetStream(DSEntries, PSCLSID.DSI, DocSummaryRE, DocSummaryPIDDSI, CEntries2.length ? CEntries2 : null, PSCLSID.UDI));
  24460. }
  24461. function parse_xlscfb(cfb, options) {
  24462. if(!options) options = {};
  24463. fix_read_opts(options);
  24464. reset_cp();
  24465. if(options.codepage) set_ansi(options.codepage);
  24466. var CompObj, WB;
  24467. if(cfb.FullPaths) {
  24468. if(CFB.find(cfb, '/encryption')) throw new Error("File is password-protected");
  24469. CompObj = CFB.find(cfb, '!CompObj');
  24470. WB = CFB.find(cfb, '/Workbook') || CFB.find(cfb, '/Book');
  24471. } else {
  24472. switch(options.type) {
  24473. case 'base64': cfb = s2a(Base64.decode(cfb)); break;
  24474. case 'binary': cfb = s2a(cfb); break;
  24475. case 'buffer': break;
  24476. case 'array': if(!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb); break;
  24477. }
  24478. prep_blob(cfb, 0);
  24479. WB = ({content: cfb});
  24480. }
  24481. var WorkbookP;
  24482. var _data;
  24483. if(CompObj) parse_compobj(CompObj);
  24484. if(options.bookProps && !options.bookSheets) WorkbookP = ({});
  24485. else {
  24486. var T = has_buf ? 'buffer' : 'array';
  24487. if(WB && WB.content) WorkbookP = parse_workbook(WB.content, options);
  24488. /* Quattro Pro 7-8 */
  24489. else if((_data=CFB.find(cfb, 'PerfectOffice_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  24490. /* Quattro Pro 9 */
  24491. else if((_data=CFB.find(cfb, 'NativeContent_MAIN')) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T, options));
  24492. else throw new Error("Cannot find Workbook stream");
  24493. if(options.bookVBA && cfb.FullPaths && CFB.find(cfb, '/_VBA_PROJECT_CUR/VBA/dir')) WorkbookP.vbaraw = make_vba_xls(cfb);
  24494. }
  24495. var props = {};
  24496. if(cfb.FullPaths) parse_xls_props(cfb, props, options);
  24497. WorkbookP.Props = WorkbookP.Custprops = props; /* TODO: split up properties */
  24498. if(options.bookFiles) WorkbookP.cfb = cfb;
  24499. /*WorkbookP.CompObjP = CompObjP; // TODO: storage? */
  24500. return WorkbookP;
  24501. }
  24502. function write_xlscfb(wb, opts) {
  24503. var o = opts || {};
  24504. var cfb = CFB.utils.cfb_new({root:"R"});
  24505. var wbpath = "/Workbook";
  24506. switch(o.bookType || "xls") {
  24507. case "xls": o.bookType = "biff8";
  24508. /* falls through */
  24509. case "xla": if(!o.bookType) o.bookType = "xla";
  24510. /* falls through */
  24511. case "biff8": wbpath = "/Workbook"; o.biff = 8; break;
  24512. case "biff5": wbpath = "/Book"; o.biff = 5; break;
  24513. default: throw new Error("invalid type " + o.bookType + " for XLS CFB");
  24514. }
  24515. CFB.utils.cfb_add(cfb, wbpath, write_biff_buf(wb, o));
  24516. if(o.biff == 8 && (wb.Props || wb.Custprops)) write_xls_props(wb, cfb);
  24517. // TODO: SI, DSI, CO
  24518. if(o.biff == 8 && wb.vbaraw) fill_vba_xls(cfb, CFB.read(wb.vbaraw, {type: typeof wb.vbaraw == "string" ? "binary" : "buffer"}));
  24519. return cfb;
  24520. }
  24521. /* [MS-XLSB] 2.3 Record Enumeration */
  24522. var XLSBRecordEnum = {
  24523. 0x0000: { n:"BrtRowHdr", f:parse_BrtRowHdr },
  24524. 0x0001: { n:"BrtCellBlank", f:parse_BrtCellBlank },
  24525. 0x0002: { n:"BrtCellRk", f:parse_BrtCellRk },
  24526. 0x0003: { n:"BrtCellError", f:parse_BrtCellError },
  24527. 0x0004: { n:"BrtCellBool", f:parse_BrtCellBool },
  24528. 0x0005: { n:"BrtCellReal", f:parse_BrtCellReal },
  24529. 0x0006: { n:"BrtCellSt", f:parse_BrtCellSt },
  24530. 0x0007: { n:"BrtCellIsst", f:parse_BrtCellIsst },
  24531. 0x0008: { n:"BrtFmlaString", f:parse_BrtFmlaString },
  24532. 0x0009: { n:"BrtFmlaNum", f:parse_BrtFmlaNum },
  24533. 0x000A: { n:"BrtFmlaBool", f:parse_BrtFmlaBool },
  24534. 0x000B: { n:"BrtFmlaError", f:parse_BrtFmlaError },
  24535. 0x0010: { n:"BrtFRTArchID$", f:parse_BrtFRTArchID$ },
  24536. 0x0013: { n:"BrtSSTItem", f:parse_RichStr },
  24537. 0x0014: { n:"BrtPCDIMissing" },
  24538. 0x0015: { n:"BrtPCDINumber" },
  24539. 0x0016: { n:"BrtPCDIBoolean" },
  24540. 0x0017: { n:"BrtPCDIError" },
  24541. 0x0018: { n:"BrtPCDIString" },
  24542. 0x0019: { n:"BrtPCDIDatetime" },
  24543. 0x001A: { n:"BrtPCDIIndex" },
  24544. 0x001B: { n:"BrtPCDIAMissing" },
  24545. 0x001C: { n:"BrtPCDIANumber" },
  24546. 0x001D: { n:"BrtPCDIABoolean" },
  24547. 0x001E: { n:"BrtPCDIAError" },
  24548. 0x001F: { n:"BrtPCDIAString" },
  24549. 0x0020: { n:"BrtPCDIADatetime" },
  24550. 0x0021: { n:"BrtPCRRecord" },
  24551. 0x0022: { n:"BrtPCRRecordDt" },
  24552. 0x0023: { n:"BrtFRTBegin" },
  24553. 0x0024: { n:"BrtFRTEnd" },
  24554. 0x0025: { n:"BrtACBegin" },
  24555. 0x0026: { n:"BrtACEnd" },
  24556. 0x0027: { n:"BrtName", f:parse_BrtName },
  24557. 0x0028: { n:"BrtIndexRowBlock" },
  24558. 0x002A: { n:"BrtIndexBlock" },
  24559. 0x002B: { n:"BrtFont", f:parse_BrtFont },
  24560. 0x002C: { n:"BrtFmt", f:parse_BrtFmt },
  24561. 0x002D: { n:"BrtFill", f:parse_BrtFill },
  24562. 0x002E: { n:"BrtBorder", f:parse_BrtBorder },
  24563. 0x002F: { n:"BrtXF", f:parse_BrtXF },
  24564. 0x0030: { n:"BrtStyle" },
  24565. 0x0031: { n:"BrtCellMeta" },
  24566. 0x0032: { n:"BrtValueMeta" },
  24567. 0x0033: { n:"BrtMdb" },
  24568. 0x0034: { n:"BrtBeginFmd" },
  24569. 0x0035: { n:"BrtEndFmd" },
  24570. 0x0036: { n:"BrtBeginMdx" },
  24571. 0x0037: { n:"BrtEndMdx" },
  24572. 0x0038: { n:"BrtBeginMdxTuple" },
  24573. 0x0039: { n:"BrtEndMdxTuple" },
  24574. 0x003A: { n:"BrtMdxMbrIstr" },
  24575. 0x003B: { n:"BrtStr" },
  24576. 0x003C: { n:"BrtColInfo", f:parse_ColInfo },
  24577. 0x003E: { n:"BrtCellRString" },
  24578. 0x003F: { n:"BrtCalcChainItem$", f:parse_BrtCalcChainItem$ },
  24579. 0x0040: { n:"BrtDVal", f:parse_BrtDVal },
  24580. 0x0041: { n:"BrtSxvcellNum" },
  24581. 0x0042: { n:"BrtSxvcellStr" },
  24582. 0x0043: { n:"BrtSxvcellBool" },
  24583. 0x0044: { n:"BrtSxvcellErr" },
  24584. 0x0045: { n:"BrtSxvcellDate" },
  24585. 0x0046: { n:"BrtSxvcellNil" },
  24586. 0x0080: { n:"BrtFileVersion" },
  24587. 0x0081: { n:"BrtBeginSheet" },
  24588. 0x0082: { n:"BrtEndSheet" },
  24589. 0x0083: { n:"BrtBeginBook", f:parsenoop, p:0 },
  24590. 0x0084: { n:"BrtEndBook" },
  24591. 0x0085: { n:"BrtBeginWsViews" },
  24592. 0x0086: { n:"BrtEndWsViews" },
  24593. 0x0087: { n:"BrtBeginBookViews" },
  24594. 0x0088: { n:"BrtEndBookViews" },
  24595. 0x0089: { n:"BrtBeginWsView", f:parse_BrtBeginWsView },
  24596. 0x008A: { n:"BrtEndWsView" },
  24597. 0x008B: { n:"BrtBeginCsViews" },
  24598. 0x008C: { n:"BrtEndCsViews" },
  24599. 0x008D: { n:"BrtBeginCsView" },
  24600. 0x008E: { n:"BrtEndCsView" },
  24601. 0x008F: { n:"BrtBeginBundleShs" },
  24602. 0x0090: { n:"BrtEndBundleShs" },
  24603. 0x0091: { n:"BrtBeginSheetData" },
  24604. 0x0092: { n:"BrtEndSheetData" },
  24605. 0x0093: { n:"BrtWsProp", f:parse_BrtWsProp },
  24606. 0x0094: { n:"BrtWsDim", f:parse_BrtWsDim, p:16 },
  24607. 0x0097: { n:"BrtPane", f:parse_BrtPane },
  24608. 0x0098: { n:"BrtSel" },
  24609. 0x0099: { n:"BrtWbProp", f:parse_BrtWbProp },
  24610. 0x009A: { n:"BrtWbFactoid" },
  24611. 0x009B: { n:"BrtFileRecover" },
  24612. 0x009C: { n:"BrtBundleSh", f:parse_BrtBundleSh },
  24613. 0x009D: { n:"BrtCalcProp" },
  24614. 0x009E: { n:"BrtBookView" },
  24615. 0x009F: { n:"BrtBeginSst", f:parse_BrtBeginSst },
  24616. 0x00A0: { n:"BrtEndSst" },
  24617. 0x00A1: { n:"BrtBeginAFilter", f:parse_UncheckedRfX },
  24618. 0x00A2: { n:"BrtEndAFilter" },
  24619. 0x00A3: { n:"BrtBeginFilterColumn" },
  24620. 0x00A4: { n:"BrtEndFilterColumn" },
  24621. 0x00A5: { n:"BrtBeginFilters" },
  24622. 0x00A6: { n:"BrtEndFilters" },
  24623. 0x00A7: { n:"BrtFilter" },
  24624. 0x00A8: { n:"BrtColorFilter" },
  24625. 0x00A9: { n:"BrtIconFilter" },
  24626. 0x00AA: { n:"BrtTop10Filter" },
  24627. 0x00AB: { n:"BrtDynamicFilter" },
  24628. 0x00AC: { n:"BrtBeginCustomFilters" },
  24629. 0x00AD: { n:"BrtEndCustomFilters" },
  24630. 0x00AE: { n:"BrtCustomFilter" },
  24631. 0x00AF: { n:"BrtAFilterDateGroupItem" },
  24632. 0x00B0: { n:"BrtMergeCell", f:parse_BrtMergeCell },
  24633. 0x00B1: { n:"BrtBeginMergeCells" },
  24634. 0x00B2: { n:"BrtEndMergeCells" },
  24635. 0x00B3: { n:"BrtBeginPivotCacheDef" },
  24636. 0x00B4: { n:"BrtEndPivotCacheDef" },
  24637. 0x00B5: { n:"BrtBeginPCDFields" },
  24638. 0x00B6: { n:"BrtEndPCDFields" },
  24639. 0x00B7: { n:"BrtBeginPCDField" },
  24640. 0x00B8: { n:"BrtEndPCDField" },
  24641. 0x00B9: { n:"BrtBeginPCDSource" },
  24642. 0x00BA: { n:"BrtEndPCDSource" },
  24643. 0x00BB: { n:"BrtBeginPCDSRange" },
  24644. 0x00BC: { n:"BrtEndPCDSRange" },
  24645. 0x00BD: { n:"BrtBeginPCDFAtbl" },
  24646. 0x00BE: { n:"BrtEndPCDFAtbl" },
  24647. 0x00BF: { n:"BrtBeginPCDIRun" },
  24648. 0x00C0: { n:"BrtEndPCDIRun" },
  24649. 0x00C1: { n:"BrtBeginPivotCacheRecords" },
  24650. 0x00C2: { n:"BrtEndPivotCacheRecords" },
  24651. 0x00C3: { n:"BrtBeginPCDHierarchies" },
  24652. 0x00C4: { n:"BrtEndPCDHierarchies" },
  24653. 0x00C5: { n:"BrtBeginPCDHierarchy" },
  24654. 0x00C6: { n:"BrtEndPCDHierarchy" },
  24655. 0x00C7: { n:"BrtBeginPCDHFieldsUsage" },
  24656. 0x00C8: { n:"BrtEndPCDHFieldsUsage" },
  24657. 0x00C9: { n:"BrtBeginExtConnection" },
  24658. 0x00CA: { n:"BrtEndExtConnection" },
  24659. 0x00CB: { n:"BrtBeginECDbProps" },
  24660. 0x00CC: { n:"BrtEndECDbProps" },
  24661. 0x00CD: { n:"BrtBeginECOlapProps" },
  24662. 0x00CE: { n:"BrtEndECOlapProps" },
  24663. 0x00CF: { n:"BrtBeginPCDSConsol" },
  24664. 0x00D0: { n:"BrtEndPCDSConsol" },
  24665. 0x00D1: { n:"BrtBeginPCDSCPages" },
  24666. 0x00D2: { n:"BrtEndPCDSCPages" },
  24667. 0x00D3: { n:"BrtBeginPCDSCPage" },
  24668. 0x00D4: { n:"BrtEndPCDSCPage" },
  24669. 0x00D5: { n:"BrtBeginPCDSCPItem" },
  24670. 0x00D6: { n:"BrtEndPCDSCPItem" },
  24671. 0x00D7: { n:"BrtBeginPCDSCSets" },
  24672. 0x00D8: { n:"BrtEndPCDSCSets" },
  24673. 0x00D9: { n:"BrtBeginPCDSCSet" },
  24674. 0x00DA: { n:"BrtEndPCDSCSet" },
  24675. 0x00DB: { n:"BrtBeginPCDFGroup" },
  24676. 0x00DC: { n:"BrtEndPCDFGroup" },
  24677. 0x00DD: { n:"BrtBeginPCDFGItems" },
  24678. 0x00DE: { n:"BrtEndPCDFGItems" },
  24679. 0x00DF: { n:"BrtBeginPCDFGRange" },
  24680. 0x00E0: { n:"BrtEndPCDFGRange" },
  24681. 0x00E1: { n:"BrtBeginPCDFGDiscrete" },
  24682. 0x00E2: { n:"BrtEndPCDFGDiscrete" },
  24683. 0x00E3: { n:"BrtBeginPCDSDTupleCache" },
  24684. 0x00E4: { n:"BrtEndPCDSDTupleCache" },
  24685. 0x00E5: { n:"BrtBeginPCDSDTCEntries" },
  24686. 0x00E6: { n:"BrtEndPCDSDTCEntries" },
  24687. 0x00E7: { n:"BrtBeginPCDSDTCEMembers" },
  24688. 0x00E8: { n:"BrtEndPCDSDTCEMembers" },
  24689. 0x00E9: { n:"BrtBeginPCDSDTCEMember" },
  24690. 0x00EA: { n:"BrtEndPCDSDTCEMember" },
  24691. 0x00EB: { n:"BrtBeginPCDSDTCQueries" },
  24692. 0x00EC: { n:"BrtEndPCDSDTCQueries" },
  24693. 0x00ED: { n:"BrtBeginPCDSDTCQuery" },
  24694. 0x00EE: { n:"BrtEndPCDSDTCQuery" },
  24695. 0x00EF: { n:"BrtBeginPCDSDTCSets" },
  24696. 0x00F0: { n:"BrtEndPCDSDTCSets" },
  24697. 0x00F1: { n:"BrtBeginPCDSDTCSet" },
  24698. 0x00F2: { n:"BrtEndPCDSDTCSet" },
  24699. 0x00F3: { n:"BrtBeginPCDCalcItems" },
  24700. 0x00F4: { n:"BrtEndPCDCalcItems" },
  24701. 0x00F5: { n:"BrtBeginPCDCalcItem" },
  24702. 0x00F6: { n:"BrtEndPCDCalcItem" },
  24703. 0x00F7: { n:"BrtBeginPRule" },
  24704. 0x00F8: { n:"BrtEndPRule" },
  24705. 0x00F9: { n:"BrtBeginPRFilters" },
  24706. 0x00FA: { n:"BrtEndPRFilters" },
  24707. 0x00FB: { n:"BrtBeginPRFilter" },
  24708. 0x00FC: { n:"BrtEndPRFilter" },
  24709. 0x00FD: { n:"BrtBeginPNames" },
  24710. 0x00FE: { n:"BrtEndPNames" },
  24711. 0x00FF: { n:"BrtBeginPName" },
  24712. 0x0100: { n:"BrtEndPName" },
  24713. 0x0101: { n:"BrtBeginPNPairs" },
  24714. 0x0102: { n:"BrtEndPNPairs" },
  24715. 0x0103: { n:"BrtBeginPNPair" },
  24716. 0x0104: { n:"BrtEndPNPair" },
  24717. 0x0105: { n:"BrtBeginECWebProps" },
  24718. 0x0106: { n:"BrtEndECWebProps" },
  24719. 0x0107: { n:"BrtBeginEcWpTables" },
  24720. 0x0108: { n:"BrtEndECWPTables" },
  24721. 0x0109: { n:"BrtBeginECParams" },
  24722. 0x010A: { n:"BrtEndECParams" },
  24723. 0x010B: { n:"BrtBeginECParam" },
  24724. 0x010C: { n:"BrtEndECParam" },
  24725. 0x010D: { n:"BrtBeginPCDKPIs" },
  24726. 0x010E: { n:"BrtEndPCDKPIs" },
  24727. 0x010F: { n:"BrtBeginPCDKPI" },
  24728. 0x0110: { n:"BrtEndPCDKPI" },
  24729. 0x0111: { n:"BrtBeginDims" },
  24730. 0x0112: { n:"BrtEndDims" },
  24731. 0x0113: { n:"BrtBeginDim" },
  24732. 0x0114: { n:"BrtEndDim" },
  24733. 0x0115: { n:"BrtIndexPartEnd" },
  24734. 0x0116: { n:"BrtBeginStyleSheet" },
  24735. 0x0117: { n:"BrtEndStyleSheet" },
  24736. 0x0118: { n:"BrtBeginSXView" },
  24737. 0x0119: { n:"BrtEndSXVI" },
  24738. 0x011A: { n:"BrtBeginSXVI" },
  24739. 0x011B: { n:"BrtBeginSXVIs" },
  24740. 0x011C: { n:"BrtEndSXVIs" },
  24741. 0x011D: { n:"BrtBeginSXVD" },
  24742. 0x011E: { n:"BrtEndSXVD" },
  24743. 0x011F: { n:"BrtBeginSXVDs" },
  24744. 0x0120: { n:"BrtEndSXVDs" },
  24745. 0x0121: { n:"BrtBeginSXPI" },
  24746. 0x0122: { n:"BrtEndSXPI" },
  24747. 0x0123: { n:"BrtBeginSXPIs" },
  24748. 0x0124: { n:"BrtEndSXPIs" },
  24749. 0x0125: { n:"BrtBeginSXDI" },
  24750. 0x0126: { n:"BrtEndSXDI" },
  24751. 0x0127: { n:"BrtBeginSXDIs" },
  24752. 0x0128: { n:"BrtEndSXDIs" },
  24753. 0x0129: { n:"BrtBeginSXLI" },
  24754. 0x012A: { n:"BrtEndSXLI" },
  24755. 0x012B: { n:"BrtBeginSXLIRws" },
  24756. 0x012C: { n:"BrtEndSXLIRws" },
  24757. 0x012D: { n:"BrtBeginSXLICols" },
  24758. 0x012E: { n:"BrtEndSXLICols" },
  24759. 0x012F: { n:"BrtBeginSXFormat" },
  24760. 0x0130: { n:"BrtEndSXFormat" },
  24761. 0x0131: { n:"BrtBeginSXFormats" },
  24762. 0x0132: { n:"BrtEndSxFormats" },
  24763. 0x0133: { n:"BrtBeginSxSelect" },
  24764. 0x0134: { n:"BrtEndSxSelect" },
  24765. 0x0135: { n:"BrtBeginISXVDRws" },
  24766. 0x0136: { n:"BrtEndISXVDRws" },
  24767. 0x0137: { n:"BrtBeginISXVDCols" },
  24768. 0x0138: { n:"BrtEndISXVDCols" },
  24769. 0x0139: { n:"BrtEndSXLocation" },
  24770. 0x013A: { n:"BrtBeginSXLocation" },
  24771. 0x013B: { n:"BrtEndSXView" },
  24772. 0x013C: { n:"BrtBeginSXTHs" },
  24773. 0x013D: { n:"BrtEndSXTHs" },
  24774. 0x013E: { n:"BrtBeginSXTH" },
  24775. 0x013F: { n:"BrtEndSXTH" },
  24776. 0x0140: { n:"BrtBeginISXTHRws" },
  24777. 0x0141: { n:"BrtEndISXTHRws" },
  24778. 0x0142: { n:"BrtBeginISXTHCols" },
  24779. 0x0143: { n:"BrtEndISXTHCols" },
  24780. 0x0144: { n:"BrtBeginSXTDMPS" },
  24781. 0x0145: { n:"BrtEndSXTDMPs" },
  24782. 0x0146: { n:"BrtBeginSXTDMP" },
  24783. 0x0147: { n:"BrtEndSXTDMP" },
  24784. 0x0148: { n:"BrtBeginSXTHItems" },
  24785. 0x0149: { n:"BrtEndSXTHItems" },
  24786. 0x014A: { n:"BrtBeginSXTHItem" },
  24787. 0x014B: { n:"BrtEndSXTHItem" },
  24788. 0x014C: { n:"BrtBeginMetadata" },
  24789. 0x014D: { n:"BrtEndMetadata" },
  24790. 0x014E: { n:"BrtBeginEsmdtinfo" },
  24791. 0x014F: { n:"BrtMdtinfo" },
  24792. 0x0150: { n:"BrtEndEsmdtinfo" },
  24793. 0x0151: { n:"BrtBeginEsmdb" },
  24794. 0x0152: { n:"BrtEndEsmdb" },
  24795. 0x0153: { n:"BrtBeginEsfmd" },
  24796. 0x0154: { n:"BrtEndEsfmd" },
  24797. 0x0155: { n:"BrtBeginSingleCells" },
  24798. 0x0156: { n:"BrtEndSingleCells" },
  24799. 0x0157: { n:"BrtBeginList" },
  24800. 0x0158: { n:"BrtEndList" },
  24801. 0x0159: { n:"BrtBeginListCols" },
  24802. 0x015A: { n:"BrtEndListCols" },
  24803. 0x015B: { n:"BrtBeginListCol" },
  24804. 0x015C: { n:"BrtEndListCol" },
  24805. 0x015D: { n:"BrtBeginListXmlCPr" },
  24806. 0x015E: { n:"BrtEndListXmlCPr" },
  24807. 0x015F: { n:"BrtListCCFmla" },
  24808. 0x0160: { n:"BrtListTrFmla" },
  24809. 0x0161: { n:"BrtBeginExternals" },
  24810. 0x0162: { n:"BrtEndExternals" },
  24811. 0x0163: { n:"BrtSupBookSrc", f:parse_RelID},
  24812. 0x0165: { n:"BrtSupSelf" },
  24813. 0x0166: { n:"BrtSupSame" },
  24814. 0x0167: { n:"BrtSupTabs" },
  24815. 0x0168: { n:"BrtBeginSupBook" },
  24816. 0x0169: { n:"BrtPlaceholderName" },
  24817. 0x016A: { n:"BrtExternSheet", f:parse_ExternSheet },
  24818. 0x016B: { n:"BrtExternTableStart" },
  24819. 0x016C: { n:"BrtExternTableEnd" },
  24820. 0x016E: { n:"BrtExternRowHdr" },
  24821. 0x016F: { n:"BrtExternCellBlank" },
  24822. 0x0170: { n:"BrtExternCellReal" },
  24823. 0x0171: { n:"BrtExternCellBool" },
  24824. 0x0172: { n:"BrtExternCellError" },
  24825. 0x0173: { n:"BrtExternCellString" },
  24826. 0x0174: { n:"BrtBeginEsmdx" },
  24827. 0x0175: { n:"BrtEndEsmdx" },
  24828. 0x0176: { n:"BrtBeginMdxSet" },
  24829. 0x0177: { n:"BrtEndMdxSet" },
  24830. 0x0178: { n:"BrtBeginMdxMbrProp" },
  24831. 0x0179: { n:"BrtEndMdxMbrProp" },
  24832. 0x017A: { n:"BrtBeginMdxKPI" },
  24833. 0x017B: { n:"BrtEndMdxKPI" },
  24834. 0x017C: { n:"BrtBeginEsstr" },
  24835. 0x017D: { n:"BrtEndEsstr" },
  24836. 0x017E: { n:"BrtBeginPRFItem" },
  24837. 0x017F: { n:"BrtEndPRFItem" },
  24838. 0x0180: { n:"BrtBeginPivotCacheIDs" },
  24839. 0x0181: { n:"BrtEndPivotCacheIDs" },
  24840. 0x0182: { n:"BrtBeginPivotCacheID" },
  24841. 0x0183: { n:"BrtEndPivotCacheID" },
  24842. 0x0184: { n:"BrtBeginISXVIs" },
  24843. 0x0185: { n:"BrtEndISXVIs" },
  24844. 0x0186: { n:"BrtBeginColInfos" },
  24845. 0x0187: { n:"BrtEndColInfos" },
  24846. 0x0188: { n:"BrtBeginRwBrk" },
  24847. 0x0189: { n:"BrtEndRwBrk" },
  24848. 0x018A: { n:"BrtBeginColBrk" },
  24849. 0x018B: { n:"BrtEndColBrk" },
  24850. 0x018C: { n:"BrtBrk" },
  24851. 0x018D: { n:"BrtUserBookView" },
  24852. 0x018E: { n:"BrtInfo" },
  24853. 0x018F: { n:"BrtCUsr" },
  24854. 0x0190: { n:"BrtUsr" },
  24855. 0x0191: { n:"BrtBeginUsers" },
  24856. 0x0193: { n:"BrtEOF" },
  24857. 0x0194: { n:"BrtUCR" },
  24858. 0x0195: { n:"BrtRRInsDel" },
  24859. 0x0196: { n:"BrtRREndInsDel" },
  24860. 0x0197: { n:"BrtRRMove" },
  24861. 0x0198: { n:"BrtRREndMove" },
  24862. 0x0199: { n:"BrtRRChgCell" },
  24863. 0x019A: { n:"BrtRREndChgCell" },
  24864. 0x019B: { n:"BrtRRHeader" },
  24865. 0x019C: { n:"BrtRRUserView" },
  24866. 0x019D: { n:"BrtRRRenSheet" },
  24867. 0x019E: { n:"BrtRRInsertSh" },
  24868. 0x019F: { n:"BrtRRDefName" },
  24869. 0x01A0: { n:"BrtRRNote" },
  24870. 0x01A1: { n:"BrtRRConflict" },
  24871. 0x01A2: { n:"BrtRRTQSIF" },
  24872. 0x01A3: { n:"BrtRRFormat" },
  24873. 0x01A4: { n:"BrtRREndFormat" },
  24874. 0x01A5: { n:"BrtRRAutoFmt" },
  24875. 0x01A6: { n:"BrtBeginUserShViews" },
  24876. 0x01A7: { n:"BrtBeginUserShView" },
  24877. 0x01A8: { n:"BrtEndUserShView" },
  24878. 0x01A9: { n:"BrtEndUserShViews" },
  24879. 0x01AA: { n:"BrtArrFmla", f:parse_BrtArrFmla },
  24880. 0x01AB: { n:"BrtShrFmla", f:parse_BrtShrFmla },
  24881. 0x01AC: { n:"BrtTable" },
  24882. 0x01AD: { n:"BrtBeginExtConnections" },
  24883. 0x01AE: { n:"BrtEndExtConnections" },
  24884. 0x01AF: { n:"BrtBeginPCDCalcMems" },
  24885. 0x01B0: { n:"BrtEndPCDCalcMems" },
  24886. 0x01B1: { n:"BrtBeginPCDCalcMem" },
  24887. 0x01B2: { n:"BrtEndPCDCalcMem" },
  24888. 0x01B3: { n:"BrtBeginPCDHGLevels" },
  24889. 0x01B4: { n:"BrtEndPCDHGLevels" },
  24890. 0x01B5: { n:"BrtBeginPCDHGLevel" },
  24891. 0x01B6: { n:"BrtEndPCDHGLevel" },
  24892. 0x01B7: { n:"BrtBeginPCDHGLGroups" },
  24893. 0x01B8: { n:"BrtEndPCDHGLGroups" },
  24894. 0x01B9: { n:"BrtBeginPCDHGLGroup" },
  24895. 0x01BA: { n:"BrtEndPCDHGLGroup" },
  24896. 0x01BB: { n:"BrtBeginPCDHGLGMembers" },
  24897. 0x01BC: { n:"BrtEndPCDHGLGMembers" },
  24898. 0x01BD: { n:"BrtBeginPCDHGLGMember" },
  24899. 0x01BE: { n:"BrtEndPCDHGLGMember" },
  24900. 0x01BF: { n:"BrtBeginQSI" },
  24901. 0x01C0: { n:"BrtEndQSI" },
  24902. 0x01C1: { n:"BrtBeginQSIR" },
  24903. 0x01C2: { n:"BrtEndQSIR" },
  24904. 0x01C3: { n:"BrtBeginDeletedNames" },
  24905. 0x01C4: { n:"BrtEndDeletedNames" },
  24906. 0x01C5: { n:"BrtBeginDeletedName" },
  24907. 0x01C6: { n:"BrtEndDeletedName" },
  24908. 0x01C7: { n:"BrtBeginQSIFs" },
  24909. 0x01C8: { n:"BrtEndQSIFs" },
  24910. 0x01C9: { n:"BrtBeginQSIF" },
  24911. 0x01CA: { n:"BrtEndQSIF" },
  24912. 0x01CB: { n:"BrtBeginAutoSortScope" },
  24913. 0x01CC: { n:"BrtEndAutoSortScope" },
  24914. 0x01CD: { n:"BrtBeginConditionalFormatting" },
  24915. 0x01CE: { n:"BrtEndConditionalFormatting" },
  24916. 0x01CF: { n:"BrtBeginCFRule" },
  24917. 0x01D0: { n:"BrtEndCFRule" },
  24918. 0x01D1: { n:"BrtBeginIconSet" },
  24919. 0x01D2: { n:"BrtEndIconSet" },
  24920. 0x01D3: { n:"BrtBeginDatabar" },
  24921. 0x01D4: { n:"BrtEndDatabar" },
  24922. 0x01D5: { n:"BrtBeginColorScale" },
  24923. 0x01D6: { n:"BrtEndColorScale" },
  24924. 0x01D7: { n:"BrtCFVO" },
  24925. 0x01D8: { n:"BrtExternValueMeta" },
  24926. 0x01D9: { n:"BrtBeginColorPalette" },
  24927. 0x01DA: { n:"BrtEndColorPalette" },
  24928. 0x01DB: { n:"BrtIndexedColor" },
  24929. 0x01DC: { n:"BrtMargins", f:parse_BrtMargins },
  24930. 0x01DD: { n:"BrtPrintOptions" },
  24931. 0x01DE: { n:"BrtPageSetup" },
  24932. 0x01DF: { n:"BrtBeginHeaderFooter" },
  24933. 0x01E0: { n:"BrtEndHeaderFooter" },
  24934. 0x01E1: { n:"BrtBeginSXCrtFormat" },
  24935. 0x01E2: { n:"BrtEndSXCrtFormat" },
  24936. 0x01E3: { n:"BrtBeginSXCrtFormats" },
  24937. 0x01E4: { n:"BrtEndSXCrtFormats" },
  24938. 0x01E5: { n:"BrtWsFmtInfo", f:parse_BrtWsFmtInfo },
  24939. 0x01E6: { n:"BrtBeginMgs" },
  24940. 0x01E7: { n:"BrtEndMGs" },
  24941. 0x01E8: { n:"BrtBeginMGMaps" },
  24942. 0x01E9: { n:"BrtEndMGMaps" },
  24943. 0x01EA: { n:"BrtBeginMG" },
  24944. 0x01EB: { n:"BrtEndMG" },
  24945. 0x01EC: { n:"BrtBeginMap" },
  24946. 0x01ED: { n:"BrtEndMap" },
  24947. 0x01EE: { n:"BrtHLink", f:parse_BrtHLink },
  24948. 0x01EF: { n:"BrtBeginDCon" },
  24949. 0x01F0: { n:"BrtEndDCon" },
  24950. 0x01F1: { n:"BrtBeginDRefs" },
  24951. 0x01F2: { n:"BrtEndDRefs" },
  24952. 0x01F3: { n:"BrtDRef" },
  24953. 0x01F4: { n:"BrtBeginScenMan" },
  24954. 0x01F5: { n:"BrtEndScenMan" },
  24955. 0x01F6: { n:"BrtBeginSct" },
  24956. 0x01F7: { n:"BrtEndSct" },
  24957. 0x01F8: { n:"BrtSlc" },
  24958. 0x01F9: { n:"BrtBeginDXFs" },
  24959. 0x01FA: { n:"BrtEndDXFs" },
  24960. 0x01FB: { n:"BrtDXF" },
  24961. 0x01FC: { n:"BrtBeginTableStyles" },
  24962. 0x01FD: { n:"BrtEndTableStyles" },
  24963. 0x01FE: { n:"BrtBeginTableStyle" },
  24964. 0x01FF: { n:"BrtEndTableStyle" },
  24965. 0x0200: { n:"BrtTableStyleElement" },
  24966. 0x0201: { n:"BrtTableStyleClient" },
  24967. 0x0202: { n:"BrtBeginVolDeps" },
  24968. 0x0203: { n:"BrtEndVolDeps" },
  24969. 0x0204: { n:"BrtBeginVolType" },
  24970. 0x0205: { n:"BrtEndVolType" },
  24971. 0x0206: { n:"BrtBeginVolMain" },
  24972. 0x0207: { n:"BrtEndVolMain" },
  24973. 0x0208: { n:"BrtBeginVolTopic" },
  24974. 0x0209: { n:"BrtEndVolTopic" },
  24975. 0x020A: { n:"BrtVolSubtopic" },
  24976. 0x020B: { n:"BrtVolRef" },
  24977. 0x020C: { n:"BrtVolNum" },
  24978. 0x020D: { n:"BrtVolErr" },
  24979. 0x020E: { n:"BrtVolStr" },
  24980. 0x020F: { n:"BrtVolBool" },
  24981. 0x0210: { n:"BrtBeginCalcChain$" },
  24982. 0x0211: { n:"BrtEndCalcChain$" },
  24983. 0x0212: { n:"BrtBeginSortState" },
  24984. 0x0213: { n:"BrtEndSortState" },
  24985. 0x0214: { n:"BrtBeginSortCond" },
  24986. 0x0215: { n:"BrtEndSortCond" },
  24987. 0x0216: { n:"BrtBookProtection" },
  24988. 0x0217: { n:"BrtSheetProtection" },
  24989. 0x0218: { n:"BrtRangeProtection" },
  24990. 0x0219: { n:"BrtPhoneticInfo" },
  24991. 0x021A: { n:"BrtBeginECTxtWiz" },
  24992. 0x021B: { n:"BrtEndECTxtWiz" },
  24993. 0x021C: { n:"BrtBeginECTWFldInfoLst" },
  24994. 0x021D: { n:"BrtEndECTWFldInfoLst" },
  24995. 0x021E: { n:"BrtBeginECTwFldInfo" },
  24996. 0x0224: { n:"BrtFileSharing" },
  24997. 0x0225: { n:"BrtOleSize" },
  24998. 0x0226: { n:"BrtDrawing", f:parse_RelID },
  24999. 0x0227: { n:"BrtLegacyDrawing" },
  25000. 0x0228: { n:"BrtLegacyDrawingHF" },
  25001. 0x0229: { n:"BrtWebOpt" },
  25002. 0x022A: { n:"BrtBeginWebPubItems" },
  25003. 0x022B: { n:"BrtEndWebPubItems" },
  25004. 0x022C: { n:"BrtBeginWebPubItem" },
  25005. 0x022D: { n:"BrtEndWebPubItem" },
  25006. 0x022E: { n:"BrtBeginSXCondFmt" },
  25007. 0x022F: { n:"BrtEndSXCondFmt" },
  25008. 0x0230: { n:"BrtBeginSXCondFmts" },
  25009. 0x0231: { n:"BrtEndSXCondFmts" },
  25010. 0x0232: { n:"BrtBkHim" },
  25011. 0x0234: { n:"BrtColor" },
  25012. 0x0235: { n:"BrtBeginIndexedColors" },
  25013. 0x0236: { n:"BrtEndIndexedColors" },
  25014. 0x0239: { n:"BrtBeginMRUColors" },
  25015. 0x023A: { n:"BrtEndMRUColors" },
  25016. 0x023C: { n:"BrtMRUColor" },
  25017. 0x023D: { n:"BrtBeginDVals" },
  25018. 0x023E: { n:"BrtEndDVals" },
  25019. 0x0241: { n:"BrtSupNameStart" },
  25020. 0x0242: { n:"BrtSupNameValueStart" },
  25021. 0x0243: { n:"BrtSupNameValueEnd" },
  25022. 0x0244: { n:"BrtSupNameNum" },
  25023. 0x0245: { n:"BrtSupNameErr" },
  25024. 0x0246: { n:"BrtSupNameSt" },
  25025. 0x0247: { n:"BrtSupNameNil" },
  25026. 0x0248: { n:"BrtSupNameBool" },
  25027. 0x0249: { n:"BrtSupNameFmla" },
  25028. 0x024A: { n:"BrtSupNameBits" },
  25029. 0x024B: { n:"BrtSupNameEnd" },
  25030. 0x024C: { n:"BrtEndSupBook" },
  25031. 0x024D: { n:"BrtCellSmartTagProperty" },
  25032. 0x024E: { n:"BrtBeginCellSmartTag" },
  25033. 0x024F: { n:"BrtEndCellSmartTag" },
  25034. 0x0250: { n:"BrtBeginCellSmartTags" },
  25035. 0x0251: { n:"BrtEndCellSmartTags" },
  25036. 0x0252: { n:"BrtBeginSmartTags" },
  25037. 0x0253: { n:"BrtEndSmartTags" },
  25038. 0x0254: { n:"BrtSmartTagType" },
  25039. 0x0255: { n:"BrtBeginSmartTagTypes" },
  25040. 0x0256: { n:"BrtEndSmartTagTypes" },
  25041. 0x0257: { n:"BrtBeginSXFilters" },
  25042. 0x0258: { n:"BrtEndSXFilters" },
  25043. 0x0259: { n:"BrtBeginSXFILTER" },
  25044. 0x025A: { n:"BrtEndSXFilter" },
  25045. 0x025B: { n:"BrtBeginFills" },
  25046. 0x025C: { n:"BrtEndFills" },
  25047. 0x025D: { n:"BrtBeginCellWatches" },
  25048. 0x025E: { n:"BrtEndCellWatches" },
  25049. 0x025F: { n:"BrtCellWatch" },
  25050. 0x0260: { n:"BrtBeginCRErrs" },
  25051. 0x0261: { n:"BrtEndCRErrs" },
  25052. 0x0262: { n:"BrtCrashRecErr" },
  25053. 0x0263: { n:"BrtBeginFonts" },
  25054. 0x0264: { n:"BrtEndFonts" },
  25055. 0x0265: { n:"BrtBeginBorders" },
  25056. 0x0266: { n:"BrtEndBorders" },
  25057. 0x0267: { n:"BrtBeginFmts" },
  25058. 0x0268: { n:"BrtEndFmts" },
  25059. 0x0269: { n:"BrtBeginCellXFs" },
  25060. 0x026A: { n:"BrtEndCellXFs" },
  25061. 0x026B: { n:"BrtBeginStyles" },
  25062. 0x026C: { n:"BrtEndStyles" },
  25063. 0x0271: { n:"BrtBigName" },
  25064. 0x0272: { n:"BrtBeginCellStyleXFs" },
  25065. 0x0273: { n:"BrtEndCellStyleXFs" },
  25066. 0x0274: { n:"BrtBeginComments" },
  25067. 0x0275: { n:"BrtEndComments" },
  25068. 0x0276: { n:"BrtBeginCommentAuthors" },
  25069. 0x0277: { n:"BrtEndCommentAuthors" },
  25070. 0x0278: { n:"BrtCommentAuthor", f:parse_BrtCommentAuthor },
  25071. 0x0279: { n:"BrtBeginCommentList" },
  25072. 0x027A: { n:"BrtEndCommentList" },
  25073. 0x027B: { n:"BrtBeginComment", f:parse_BrtBeginComment},
  25074. 0x027C: { n:"BrtEndComment" },
  25075. 0x027D: { n:"BrtCommentText", f:parse_BrtCommentText },
  25076. 0x027E: { n:"BrtBeginOleObjects" },
  25077. 0x027F: { n:"BrtOleObject" },
  25078. 0x0280: { n:"BrtEndOleObjects" },
  25079. 0x0281: { n:"BrtBeginSxrules" },
  25080. 0x0282: { n:"BrtEndSxRules" },
  25081. 0x0283: { n:"BrtBeginActiveXControls" },
  25082. 0x0284: { n:"BrtActiveX" },
  25083. 0x0285: { n:"BrtEndActiveXControls" },
  25084. 0x0286: { n:"BrtBeginPCDSDTCEMembersSortBy" },
  25085. 0x0288: { n:"BrtBeginCellIgnoreECs" },
  25086. 0x0289: { n:"BrtCellIgnoreEC" },
  25087. 0x028A: { n:"BrtEndCellIgnoreECs" },
  25088. 0x028B: { n:"BrtCsProp", f:parse_BrtCsProp },
  25089. 0x028C: { n:"BrtCsPageSetup" },
  25090. 0x028D: { n:"BrtBeginUserCsViews" },
  25091. 0x028E: { n:"BrtEndUserCsViews" },
  25092. 0x028F: { n:"BrtBeginUserCsView" },
  25093. 0x0290: { n:"BrtEndUserCsView" },
  25094. 0x0291: { n:"BrtBeginPcdSFCIEntries" },
  25095. 0x0292: { n:"BrtEndPCDSFCIEntries" },
  25096. 0x0293: { n:"BrtPCDSFCIEntry" },
  25097. 0x0294: { n:"BrtBeginListParts" },
  25098. 0x0295: { n:"BrtListPart" },
  25099. 0x0296: { n:"BrtEndListParts" },
  25100. 0x0297: { n:"BrtSheetCalcProp" },
  25101. 0x0298: { n:"BrtBeginFnGroup" },
  25102. 0x0299: { n:"BrtFnGroup" },
  25103. 0x029A: { n:"BrtEndFnGroup" },
  25104. 0x029B: { n:"BrtSupAddin" },
  25105. 0x029C: { n:"BrtSXTDMPOrder" },
  25106. 0x029D: { n:"BrtCsProtection" },
  25107. 0x029F: { n:"BrtBeginWsSortMap" },
  25108. 0x02A0: { n:"BrtEndWsSortMap" },
  25109. 0x02A1: { n:"BrtBeginRRSort" },
  25110. 0x02A2: { n:"BrtEndRRSort" },
  25111. 0x02A3: { n:"BrtRRSortItem" },
  25112. 0x02A4: { n:"BrtFileSharingIso" },
  25113. 0x02A5: { n:"BrtBookProtectionIso" },
  25114. 0x02A6: { n:"BrtSheetProtectionIso" },
  25115. 0x02A7: { n:"BrtCsProtectionIso" },
  25116. 0x02A8: { n:"BrtRangeProtectionIso" },
  25117. 0x02A9: { n:"BrtDValList" },
  25118. 0x0400: { n:"BrtRwDescent" },
  25119. 0x0401: { n:"BrtKnownFonts" },
  25120. 0x0402: { n:"BrtBeginSXTupleSet" },
  25121. 0x0403: { n:"BrtEndSXTupleSet" },
  25122. 0x0404: { n:"BrtBeginSXTupleSetHeader" },
  25123. 0x0405: { n:"BrtEndSXTupleSetHeader" },
  25124. 0x0406: { n:"BrtSXTupleSetHeaderItem" },
  25125. 0x0407: { n:"BrtBeginSXTupleSetData" },
  25126. 0x0408: { n:"BrtEndSXTupleSetData" },
  25127. 0x0409: { n:"BrtBeginSXTupleSetRow" },
  25128. 0x040A: { n:"BrtEndSXTupleSetRow" },
  25129. 0x040B: { n:"BrtSXTupleSetRowItem" },
  25130. 0x040C: { n:"BrtNameExt" },
  25131. 0x040D: { n:"BrtPCDH14" },
  25132. 0x040E: { n:"BrtBeginPCDCalcMem14" },
  25133. 0x040F: { n:"BrtEndPCDCalcMem14" },
  25134. 0x0410: { n:"BrtSXTH14" },
  25135. 0x0411: { n:"BrtBeginSparklineGroup" },
  25136. 0x0412: { n:"BrtEndSparklineGroup" },
  25137. 0x0413: { n:"BrtSparkline" },
  25138. 0x0414: { n:"BrtSXDI14" },
  25139. 0x0415: { n:"BrtWsFmtInfoEx14" },
  25140. 0x0416: { n:"BrtBeginConditionalFormatting14" },
  25141. 0x0417: { n:"BrtEndConditionalFormatting14" },
  25142. 0x0418: { n:"BrtBeginCFRule14" },
  25143. 0x0419: { n:"BrtEndCFRule14" },
  25144. 0x041A: { n:"BrtCFVO14" },
  25145. 0x041B: { n:"BrtBeginDatabar14" },
  25146. 0x041C: { n:"BrtBeginIconSet14" },
  25147. 0x041D: { n:"BrtDVal14", f: parse_BrtDVal14 },
  25148. 0x041E: { n:"BrtBeginDVals14" },
  25149. 0x041F: { n:"BrtColor14" },
  25150. 0x0420: { n:"BrtBeginSparklines" },
  25151. 0x0421: { n:"BrtEndSparklines" },
  25152. 0x0422: { n:"BrtBeginSparklineGroups" },
  25153. 0x0423: { n:"BrtEndSparklineGroups" },
  25154. 0x0425: { n:"BrtSXVD14" },
  25155. 0x0426: { n:"BrtBeginSXView14" },
  25156. 0x0427: { n:"BrtEndSXView14" },
  25157. 0x0428: { n:"BrtBeginSXView16" },
  25158. 0x0429: { n:"BrtEndSXView16" },
  25159. 0x042A: { n:"BrtBeginPCD14" },
  25160. 0x042B: { n:"BrtEndPCD14" },
  25161. 0x042C: { n:"BrtBeginExtConn14" },
  25162. 0x042D: { n:"BrtEndExtConn14" },
  25163. 0x042E: { n:"BrtBeginSlicerCacheIDs" },
  25164. 0x042F: { n:"BrtEndSlicerCacheIDs" },
  25165. 0x0430: { n:"BrtBeginSlicerCacheID" },
  25166. 0x0431: { n:"BrtEndSlicerCacheID" },
  25167. 0x0433: { n:"BrtBeginSlicerCache" },
  25168. 0x0434: { n:"BrtEndSlicerCache" },
  25169. 0x0435: { n:"BrtBeginSlicerCacheDef" },
  25170. 0x0436: { n:"BrtEndSlicerCacheDef" },
  25171. 0x0437: { n:"BrtBeginSlicersEx" },
  25172. 0x0438: { n:"BrtEndSlicersEx" },
  25173. 0x0439: { n:"BrtBeginSlicerEx" },
  25174. 0x043A: { n:"BrtEndSlicerEx" },
  25175. 0x043B: { n:"BrtBeginSlicer" },
  25176. 0x043C: { n:"BrtEndSlicer" },
  25177. 0x043D: { n:"BrtSlicerCachePivotTables" },
  25178. 0x043E: { n:"BrtBeginSlicerCacheOlapImpl" },
  25179. 0x043F: { n:"BrtEndSlicerCacheOlapImpl" },
  25180. 0x0440: { n:"BrtBeginSlicerCacheLevelsData" },
  25181. 0x0441: { n:"BrtEndSlicerCacheLevelsData" },
  25182. 0x0442: { n:"BrtBeginSlicerCacheLevelData" },
  25183. 0x0443: { n:"BrtEndSlicerCacheLevelData" },
  25184. 0x0444: { n:"BrtBeginSlicerCacheSiRanges" },
  25185. 0x0445: { n:"BrtEndSlicerCacheSiRanges" },
  25186. 0x0446: { n:"BrtBeginSlicerCacheSiRange" },
  25187. 0x0447: { n:"BrtEndSlicerCacheSiRange" },
  25188. 0x0448: { n:"BrtSlicerCacheOlapItem" },
  25189. 0x0449: { n:"BrtBeginSlicerCacheSelections" },
  25190. 0x044A: { n:"BrtSlicerCacheSelection" },
  25191. 0x044B: { n:"BrtEndSlicerCacheSelections" },
  25192. 0x044C: { n:"BrtBeginSlicerCacheNative" },
  25193. 0x044D: { n:"BrtEndSlicerCacheNative" },
  25194. 0x044E: { n:"BrtSlicerCacheNativeItem" },
  25195. 0x044F: { n:"BrtRangeProtection14" },
  25196. 0x0450: { n:"BrtRangeProtectionIso14" },
  25197. 0x0451: { n:"BrtCellIgnoreEC14" },
  25198. 0x0457: { n:"BrtList14" },
  25199. 0x0458: { n:"BrtCFIcon" },
  25200. 0x0459: { n:"BrtBeginSlicerCachesPivotCacheIDs" },
  25201. 0x045A: { n:"BrtEndSlicerCachesPivotCacheIDs" },
  25202. 0x045B: { n:"BrtBeginSlicers" },
  25203. 0x045C: { n:"BrtEndSlicers" },
  25204. 0x045D: { n:"BrtWbProp14" },
  25205. 0x045E: { n:"BrtBeginSXEdit" },
  25206. 0x045F: { n:"BrtEndSXEdit" },
  25207. 0x0460: { n:"BrtBeginSXEdits" },
  25208. 0x0461: { n:"BrtEndSXEdits" },
  25209. 0x0462: { n:"BrtBeginSXChange" },
  25210. 0x0463: { n:"BrtEndSXChange" },
  25211. 0x0464: { n:"BrtBeginSXChanges" },
  25212. 0x0465: { n:"BrtEndSXChanges" },
  25213. 0x0466: { n:"BrtSXTupleItems" },
  25214. 0x0468: { n:"BrtBeginSlicerStyle" },
  25215. 0x0469: { n:"BrtEndSlicerStyle" },
  25216. 0x046A: { n:"BrtSlicerStyleElement" },
  25217. 0x046B: { n:"BrtBeginStyleSheetExt14" },
  25218. 0x046C: { n:"BrtEndStyleSheetExt14" },
  25219. 0x046D: { n:"BrtBeginSlicerCachesPivotCacheID" },
  25220. 0x046E: { n:"BrtEndSlicerCachesPivotCacheID" },
  25221. 0x046F: { n:"BrtBeginConditionalFormattings" },
  25222. 0x0470: { n:"BrtEndConditionalFormattings" },
  25223. 0x0471: { n:"BrtBeginPCDCalcMemExt" },
  25224. 0x0472: { n:"BrtEndPCDCalcMemExt" },
  25225. 0x0473: { n:"BrtBeginPCDCalcMemsExt" },
  25226. 0x0474: { n:"BrtEndPCDCalcMemsExt" },
  25227. 0x0475: { n:"BrtPCDField14" },
  25228. 0x0476: { n:"BrtBeginSlicerStyles" },
  25229. 0x0477: { n:"BrtEndSlicerStyles" },
  25230. 0x0478: { n:"BrtBeginSlicerStyleElements" },
  25231. 0x0479: { n:"BrtEndSlicerStyleElements" },
  25232. 0x047A: { n:"BrtCFRuleExt" },
  25233. 0x047B: { n:"BrtBeginSXCondFmt14" },
  25234. 0x047C: { n:"BrtEndSXCondFmt14" },
  25235. 0x047D: { n:"BrtBeginSXCondFmts14" },
  25236. 0x047E: { n:"BrtEndSXCondFmts14" },
  25237. 0x0480: { n:"BrtBeginSortCond14" },
  25238. 0x0481: { n:"BrtEndSortCond14" },
  25239. 0x0482: { n:"BrtEndDVals14" },
  25240. 0x0483: { n:"BrtEndIconSet14" },
  25241. 0x0484: { n:"BrtEndDatabar14" },
  25242. 0x0485: { n:"BrtBeginColorScale14" },
  25243. 0x0486: { n:"BrtEndColorScale14" },
  25244. 0x0487: { n:"BrtBeginSxrules14" },
  25245. 0x0488: { n:"BrtEndSxrules14" },
  25246. 0x0489: { n:"BrtBeginPRule14" },
  25247. 0x048A: { n:"BrtEndPRule14" },
  25248. 0x048B: { n:"BrtBeginPRFilters14" },
  25249. 0x048C: { n:"BrtEndPRFilters14" },
  25250. 0x048D: { n:"BrtBeginPRFilter14" },
  25251. 0x048E: { n:"BrtEndPRFilter14" },
  25252. 0x048F: { n:"BrtBeginPRFItem14" },
  25253. 0x0490: { n:"BrtEndPRFItem14" },
  25254. 0x0491: { n:"BrtBeginCellIgnoreECs14" },
  25255. 0x0492: { n:"BrtEndCellIgnoreECs14" },
  25256. 0x0493: { n:"BrtDxf14" },
  25257. 0x0494: { n:"BrtBeginDxF14s" },
  25258. 0x0495: { n:"BrtEndDxf14s" },
  25259. 0x0499: { n:"BrtFilter14" },
  25260. 0x049A: { n:"BrtBeginCustomFilters14" },
  25261. 0x049C: { n:"BrtCustomFilter14" },
  25262. 0x049D: { n:"BrtIconFilter14" },
  25263. 0x049E: { n:"BrtPivotCacheConnectionName" },
  25264. 0x0800: { n:"BrtBeginDecoupledPivotCacheIDs" },
  25265. 0x0801: { n:"BrtEndDecoupledPivotCacheIDs" },
  25266. 0x0802: { n:"BrtDecoupledPivotCacheID" },
  25267. 0x0803: { n:"BrtBeginPivotTableRefs" },
  25268. 0x0804: { n:"BrtEndPivotTableRefs" },
  25269. 0x0805: { n:"BrtPivotTableRef" },
  25270. 0x0806: { n:"BrtSlicerCacheBookPivotTables" },
  25271. 0x0807: { n:"BrtBeginSxvcells" },
  25272. 0x0808: { n:"BrtEndSxvcells" },
  25273. 0x0809: { n:"BrtBeginSxRow" },
  25274. 0x080A: { n:"BrtEndSxRow" },
  25275. 0x080C: { n:"BrtPcdCalcMem15" },
  25276. 0x0813: { n:"BrtQsi15" },
  25277. 0x0814: { n:"BrtBeginWebExtensions" },
  25278. 0x0815: { n:"BrtEndWebExtensions" },
  25279. 0x0816: { n:"BrtWebExtension" },
  25280. 0x0817: { n:"BrtAbsPath15" },
  25281. 0x0818: { n:"BrtBeginPivotTableUISettings" },
  25282. 0x0819: { n:"BrtEndPivotTableUISettings" },
  25283. 0x081B: { n:"BrtTableSlicerCacheIDs" },
  25284. 0x081C: { n:"BrtTableSlicerCacheID" },
  25285. 0x081D: { n:"BrtBeginTableSlicerCache" },
  25286. 0x081E: { n:"BrtEndTableSlicerCache" },
  25287. 0x081F: { n:"BrtSxFilter15" },
  25288. 0x0820: { n:"BrtBeginTimelineCachePivotCacheIDs" },
  25289. 0x0821: { n:"BrtEndTimelineCachePivotCacheIDs" },
  25290. 0x0822: { n:"BrtTimelineCachePivotCacheID" },
  25291. 0x0823: { n:"BrtBeginTimelineCacheIDs" },
  25292. 0x0824: { n:"BrtEndTimelineCacheIDs" },
  25293. 0x0825: { n:"BrtBeginTimelineCacheID" },
  25294. 0x0826: { n:"BrtEndTimelineCacheID" },
  25295. 0x0827: { n:"BrtBeginTimelinesEx" },
  25296. 0x0828: { n:"BrtEndTimelinesEx" },
  25297. 0x0829: { n:"BrtBeginTimelineEx" },
  25298. 0x082A: { n:"BrtEndTimelineEx" },
  25299. 0x082B: { n:"BrtWorkBookPr15" },
  25300. 0x082C: { n:"BrtPCDH15" },
  25301. 0x082D: { n:"BrtBeginTimelineStyle" },
  25302. 0x082E: { n:"BrtEndTimelineStyle" },
  25303. 0x082F: { n:"BrtTimelineStyleElement" },
  25304. 0x0830: { n:"BrtBeginTimelineStylesheetExt15" },
  25305. 0x0831: { n:"BrtEndTimelineStylesheetExt15" },
  25306. 0x0832: { n:"BrtBeginTimelineStyles" },
  25307. 0x0833: { n:"BrtEndTimelineStyles" },
  25308. 0x0834: { n:"BrtBeginTimelineStyleElements" },
  25309. 0x0835: { n:"BrtEndTimelineStyleElements" },
  25310. 0x0836: { n:"BrtDxf15" },
  25311. 0x0837: { n:"BrtBeginDxfs15" },
  25312. 0x0838: { n:"brtEndDxfs15" },
  25313. 0x0839: { n:"BrtSlicerCacheHideItemsWithNoData" },
  25314. 0x083A: { n:"BrtBeginItemUniqueNames" },
  25315. 0x083B: { n:"BrtEndItemUniqueNames" },
  25316. 0x083C: { n:"BrtItemUniqueName" },
  25317. 0x083D: { n:"BrtBeginExtConn15" },
  25318. 0x083E: { n:"BrtEndExtConn15" },
  25319. 0x083F: { n:"BrtBeginOledbPr15" },
  25320. 0x0840: { n:"BrtEndOledbPr15" },
  25321. 0x0841: { n:"BrtBeginDataFeedPr15" },
  25322. 0x0842: { n:"BrtEndDataFeedPr15" },
  25323. 0x0843: { n:"BrtTextPr15" },
  25324. 0x0844: { n:"BrtRangePr15" },
  25325. 0x0845: { n:"BrtDbCommand15" },
  25326. 0x0846: { n:"BrtBeginDbTables15" },
  25327. 0x0847: { n:"BrtEndDbTables15" },
  25328. 0x0848: { n:"BrtDbTable15" },
  25329. 0x0849: { n:"BrtBeginDataModel" },
  25330. 0x084A: { n:"BrtEndDataModel" },
  25331. 0x084B: { n:"BrtBeginModelTables" },
  25332. 0x084C: { n:"BrtEndModelTables" },
  25333. 0x084D: { n:"BrtModelTable" },
  25334. 0x084E: { n:"BrtBeginModelRelationships" },
  25335. 0x084F: { n:"BrtEndModelRelationships" },
  25336. 0x0850: { n:"BrtModelRelationship" },
  25337. 0x0851: { n:"BrtBeginECTxtWiz15" },
  25338. 0x0852: { n:"BrtEndECTxtWiz15" },
  25339. 0x0853: { n:"BrtBeginECTWFldInfoLst15" },
  25340. 0x0854: { n:"BrtEndECTWFldInfoLst15" },
  25341. 0x0855: { n:"BrtBeginECTWFldInfo15" },
  25342. 0x0856: { n:"BrtFieldListActiveItem" },
  25343. 0x0857: { n:"BrtPivotCacheIdVersion" },
  25344. 0x0858: { n:"BrtSXDI15" },
  25345. 0x0859: { n:"BrtBeginModelTimeGroupings" },
  25346. 0x085A: { n:"BrtEndModelTimeGroupings" },
  25347. 0x085B: { n:"BrtBeginModelTimeGrouping" },
  25348. 0x085C: { n:"BrtEndModelTimeGrouping" },
  25349. 0x085D: { n:"BrtModelTimeGroupingCalcCol" },
  25350. 0x0C00: { n:"BrtUid" },
  25351. 0x0C01: { n:"BrtRevisionPtr" },
  25352. 0x13e7: { n:"BrtBeginCalcFeatures" },
  25353. 0x13e8: { n:"BrtEndCalcFeatures" },
  25354. 0x13e9: { n:"BrtCalcFeature" },
  25355. 0xFFFF: { n:"" }
  25356. };
  25357. var XLSBRE = evert_key(XLSBRecordEnum, 'n');
  25358. /* [MS-XLS] 2.3 Record Enumeration */
  25359. var XLSRecordEnum = {
  25360. 0x0003: { n:"BIFF2NUM", f:parse_BIFF2NUM },
  25361. 0x0004: { n:"BIFF2STR", f:parse_BIFF2STR },
  25362. 0x0006: { n:"Formula", f:parse_Formula },
  25363. 0x0009: { n:'BOF', f:parse_BOF },
  25364. 0x000a: { n:'EOF', f:parsenoop2 },
  25365. 0x000c: { n:"CalcCount", f:parseuint16 },
  25366. 0x000d: { n:"CalcMode", f:parseuint16 },
  25367. 0x000e: { n:"CalcPrecision", f:parsebool },
  25368. 0x000f: { n:"CalcRefMode", f:parsebool },
  25369. 0x0010: { n:"CalcDelta", f:parse_Xnum },
  25370. 0x0011: { n:"CalcIter", f:parsebool },
  25371. 0x0012: { n:"Protect", f:parsebool },
  25372. 0x0013: { n:"Password", f:parseuint16 },
  25373. 0x0014: { n:"Header", f:parse_XLHeaderFooter },
  25374. 0x0015: { n:"Footer", f:parse_XLHeaderFooter },
  25375. 0x0017: { n:"ExternSheet", f:parse_ExternSheet },
  25376. 0x0018: { n:"Lbl", f:parse_Lbl },
  25377. 0x0019: { n:"WinProtect", f:parsebool },
  25378. 0x001a: { n:"VerticalPageBreaks" },
  25379. 0x001b: { n:"HorizontalPageBreaks" },
  25380. 0x001c: { n:"Note", f:parse_Note },
  25381. 0x001d: { n:"Selection" },
  25382. 0x0022: { n:"Date1904", f:parsebool },
  25383. 0x0023: { n:"ExternName", f:parse_ExternName },
  25384. 0x0024: { n:"COLWIDTH" },
  25385. 0x0026: { n:"LeftMargin", f:parse_Xnum },
  25386. 0x0027: { n:"RightMargin", f:parse_Xnum },
  25387. 0x0028: { n:"TopMargin", f:parse_Xnum },
  25388. 0x0029: { n:"BottomMargin", f:parse_Xnum },
  25389. 0x002a: { n:"PrintRowCol", f:parsebool },
  25390. 0x002b: { n:"PrintGrid", f:parsebool },
  25391. 0x002f: { n:"FilePass", f:parse_FilePass },
  25392. 0x0031: { n:"Font", f:parse_Font },
  25393. 0x0033: { n:"PrintSize", f:parseuint16 },
  25394. 0x003c: { n:"Continue" },
  25395. 0x003d: { n:"Window1", f:parse_Window1 },
  25396. 0x0040: { n:"Backup", f:parsebool },
  25397. 0x0041: { n:"Pane", f:parse_Pane },
  25398. 0x0042: { n:'CodePage', f:parseuint16 },
  25399. 0x004d: { n:"Pls" },
  25400. 0x0050: { n:"DCon" },
  25401. 0x0051: { n:"DConRef" },
  25402. 0x0052: { n:"DConName" },
  25403. 0x0055: { n:"DefColWidth", f:parseuint16 },
  25404. 0x0059: { n:"XCT" },
  25405. 0x005a: { n:"CRN" },
  25406. 0x005b: { n:"FileSharing" },
  25407. 0x005c: { n:'WriteAccess', f:parse_WriteAccess },
  25408. 0x005d: { n:"Obj", f:parse_Obj },
  25409. 0x005e: { n:"Uncalced" },
  25410. 0x005f: { n:"CalcSaveRecalc", f:parsebool },
  25411. 0x0060: { n:"Template" },
  25412. 0x0061: { n:"Intl" },
  25413. 0x0063: { n:"ObjProtect", f:parsebool },
  25414. 0x007d: { n:"ColInfo", f:parse_ColInfo },
  25415. 0x0080: { n:"Guts", f:parse_Guts },
  25416. 0x0081: { n:"WsBool", f:parse_WsBool },
  25417. 0x0082: { n:"GridSet", f:parseuint16 },
  25418. 0x0083: { n:"HCenter", f:parsebool },
  25419. 0x0084: { n:"VCenter", f:parsebool },
  25420. 0x0085: { n:'BoundSheet8', f:parse_BoundSheet8 },
  25421. 0x0086: { n:"WriteProtect" },
  25422. 0x008c: { n:"Country", f:parse_Country },
  25423. 0x008d: { n:"HideObj", f:parseuint16 },
  25424. 0x0090: { n:"Sort" },
  25425. 0x0092: { n:"Palette", f:parse_Palette },
  25426. 0x0097: { n:"Sync" },
  25427. 0x0098: { n:"LPr" },
  25428. 0x0099: { n:"DxGCol" },
  25429. 0x009a: { n:"FnGroupName" },
  25430. 0x009b: { n:"FilterMode" },
  25431. 0x009c: { n:"BuiltInFnGroupCount", f:parseuint16 },
  25432. 0x009d: { n:"AutoFilterInfo" },
  25433. 0x009e: { n:"AutoFilter" },
  25434. 0x00a0: { n:"Scl", f:parse_Scl },
  25435. 0x00a1: { n:"Setup", f:parse_Setup },
  25436. 0x00ae: { n:"ScenMan" },
  25437. 0x00af: { n:"SCENARIO" },
  25438. 0x00b0: { n:"SxView" },
  25439. 0x00b1: { n:"Sxvd" },
  25440. 0x00b2: { n:"SXVI" },
  25441. 0x00b4: { n:"SxIvd" },
  25442. 0x00b5: { n:"SXLI" },
  25443. 0x00b6: { n:"SXPI" },
  25444. 0x00b8: { n:"DocRoute" },
  25445. 0x00b9: { n:"RecipName" },
  25446. 0x00bd: { n:"MulRk", f:parse_MulRk },
  25447. 0x00be: { n:"MulBlank", f:parse_MulBlank },
  25448. 0x00c1: { n:'Mms', f:parsenoop2 },
  25449. 0x00c5: { n:"SXDI" },
  25450. 0x00c6: { n:"SXDB" },
  25451. 0x00c7: { n:"SXFDB" },
  25452. 0x00c8: { n:"SXDBB" },
  25453. 0x00c9: { n:"SXNum" },
  25454. 0x00ca: { n:"SxBool", f:parsebool },
  25455. 0x00cb: { n:"SxErr" },
  25456. 0x00cc: { n:"SXInt" },
  25457. 0x00cd: { n:"SXString" },
  25458. 0x00ce: { n:"SXDtr" },
  25459. 0x00cf: { n:"SxNil" },
  25460. 0x00d0: { n:"SXTbl" },
  25461. 0x00d1: { n:"SXTBRGIITM" },
  25462. 0x00d2: { n:"SxTbpg" },
  25463. 0x00d3: { n:"ObProj" },
  25464. 0x00d5: { n:"SXStreamID" },
  25465. 0x00d7: { n:"DBCell" },
  25466. 0x00d8: { n:"SXRng" },
  25467. 0x00d9: { n:"SxIsxoper" },
  25468. 0x00da: { n:"BookBool", f:parseuint16 },
  25469. 0x00dc: { n:"DbOrParamQry" },
  25470. 0x00dd: { n:"ScenarioProtect", f:parsebool },
  25471. 0x00de: { n:"OleObjectSize" },
  25472. 0x00e0: { n:"XF", f:parse_XF },
  25473. 0x00e1: { n:'InterfaceHdr', f:parse_InterfaceHdr },
  25474. 0x00e2: { n:'InterfaceEnd', f:parsenoop2 },
  25475. 0x00e3: { n:"SXVS" },
  25476. 0x00e5: { n:"MergeCells", f:parse_MergeCells },
  25477. 0x00e9: { n:"BkHim" },
  25478. 0x00eb: { n:"MsoDrawingGroup" },
  25479. 0x00ec: { n:"MsoDrawing" },
  25480. 0x00ed: { n:"MsoDrawingSelection" },
  25481. 0x00ef: { n:"PhoneticInfo" },
  25482. 0x00f0: { n:"SxRule" },
  25483. 0x00f1: { n:"SXEx" },
  25484. 0x00f2: { n:"SxFilt" },
  25485. 0x00f4: { n:"SxDXF" },
  25486. 0x00f5: { n:"SxItm" },
  25487. 0x00f6: { n:"SxName" },
  25488. 0x00f7: { n:"SxSelect" },
  25489. 0x00f8: { n:"SXPair" },
  25490. 0x00f9: { n:"SxFmla" },
  25491. 0x00fb: { n:"SxFormat" },
  25492. 0x00fc: { n:"SST", f:parse_SST },
  25493. 0x00fd: { n:"LabelSst", f:parse_LabelSst },
  25494. 0x00ff: { n:"ExtSST", f:parse_ExtSST },
  25495. 0x0100: { n:"SXVDEx" },
  25496. 0x0103: { n:"SXFormula" },
  25497. 0x0122: { n:"SXDBEx" },
  25498. 0x0137: { n:"RRDInsDel" },
  25499. 0x0138: { n:"RRDHead" },
  25500. 0x013b: { n:"RRDChgCell" },
  25501. 0x013d: { n:"RRTabId", f:parseuint16a },
  25502. 0x013e: { n:"RRDRenSheet" },
  25503. 0x013f: { n:"RRSort" },
  25504. 0x0140: { n:"RRDMove" },
  25505. 0x014a: { n:"RRFormat" },
  25506. 0x014b: { n:"RRAutoFmt" },
  25507. 0x014d: { n:"RRInsertSh" },
  25508. 0x014e: { n:"RRDMoveBegin" },
  25509. 0x014f: { n:"RRDMoveEnd" },
  25510. 0x0150: { n:"RRDInsDelBegin" },
  25511. 0x0151: { n:"RRDInsDelEnd" },
  25512. 0x0152: { n:"RRDConflict" },
  25513. 0x0153: { n:"RRDDefName" },
  25514. 0x0154: { n:"RRDRstEtxp" },
  25515. 0x015f: { n:"LRng" },
  25516. 0x0160: { n:"UsesELFs", f:parsebool },
  25517. 0x0161: { n:"DSF", f:parsenoop2 },
  25518. 0x0191: { n:"CUsr" },
  25519. 0x0192: { n:"CbUsr" },
  25520. 0x0193: { n:"UsrInfo" },
  25521. 0x0194: { n:"UsrExcl" },
  25522. 0x0195: { n:"FileLock" },
  25523. 0x0196: { n:"RRDInfo" },
  25524. 0x0197: { n:"BCUsrs" },
  25525. 0x0198: { n:"UsrChk" },
  25526. 0x01a9: { n:"UserBView" },
  25527. 0x01aa: { n:"UserSViewBegin" },
  25528. 0x01ab: { n:"UserSViewEnd" },
  25529. 0x01ac: { n:"RRDUserView" },
  25530. 0x01ad: { n:"Qsi" },
  25531. 0x01ae: { n:"SupBook", f:parse_SupBook },
  25532. 0x01af: { n:"Prot4Rev", f:parsebool },
  25533. 0x01b0: { n:"CondFmt" },
  25534. 0x01b1: { n:"CF" },
  25535. 0x01b2: { n:"DVal" },
  25536. 0x01b5: { n:"DConBin" },
  25537. 0x01b6: { n:"TxO", f:parse_TxO },
  25538. 0x01b7: { n:"RefreshAll", f:parsebool },
  25539. 0x01b8: { n:"HLink", f:parse_HLink },
  25540. 0x01b9: { n:"Lel" },
  25541. 0x01ba: { n:"CodeName", f:parse_XLUnicodeString },
  25542. 0x01bb: { n:"SXFDBType" },
  25543. 0x01bc: { n:"Prot4RevPass", f:parseuint16 },
  25544. 0x01bd: { n:"ObNoMacros" },
  25545. 0x01be: { n:"Dv" },
  25546. 0x01c0: { n:"Excel9File", f:parsenoop2 },
  25547. 0x01c1: { n:"RecalcId", f:parse_RecalcId, r:2},
  25548. 0x01c2: { n:"EntExU2", f:parsenoop2 },
  25549. 0x0200: { n:"Dimensions", f:parse_Dimensions },
  25550. 0x0201: { n:"Blank", f:parse_Blank },
  25551. 0x0203: { n:"Number", f:parse_Number },
  25552. 0x0204: { n:"Label", f:parse_Label },
  25553. 0x0205: { n:"BoolErr", f:parse_BoolErr },
  25554. 0x0206: { n:"Formula", f:parse_Formula },
  25555. 0x0207: { n:"String", f:parse_String },
  25556. 0x0208: { n:'Row', f:parse_Row },
  25557. 0x020b: { n:"Index" },
  25558. 0x0221: { n:"Array", f:parse_Array },
  25559. 0x0225: { n:"DefaultRowHeight", f:parse_DefaultRowHeight },
  25560. 0x0236: { n:"Table" },
  25561. 0x023e: { n:"Window2", f:parse_Window2 },
  25562. 0x027e: { n:"RK", f:parse_RK },
  25563. 0x0293: { n:"Style" },
  25564. 0x0406: { n:"Formula", f:parse_Formula },
  25565. 0x0418: { n:"BigName" },
  25566. 0x041e: { n:"Format", f:parse_Format },
  25567. 0x043c: { n:"ContinueBigName" },
  25568. 0x04bc: { n:"ShrFmla", f:parse_ShrFmla },
  25569. 0x0800: { n:"HLinkTooltip", f:parse_HLinkTooltip },
  25570. 0x0801: { n:"WebPub" },
  25571. 0x0802: { n:"QsiSXTag" },
  25572. 0x0803: { n:"DBQueryExt" },
  25573. 0x0804: { n:"ExtString" },
  25574. 0x0805: { n:"TxtQry" },
  25575. 0x0806: { n:"Qsir" },
  25576. 0x0807: { n:"Qsif" },
  25577. 0x0808: { n:"RRDTQSIF" },
  25578. 0x0809: { n:'BOF', f:parse_BOF },
  25579. 0x080a: { n:"OleDbConn" },
  25580. 0x080b: { n:"WOpt" },
  25581. 0x080c: { n:"SXViewEx" },
  25582. 0x080d: { n:"SXTH" },
  25583. 0x080e: { n:"SXPIEx" },
  25584. 0x080f: { n:"SXVDTEx" },
  25585. 0x0810: { n:"SXViewEx9" },
  25586. 0x0812: { n:"ContinueFrt" },
  25587. 0x0813: { n:"RealTimeData" },
  25588. 0x0850: { n:"ChartFrtInfo" },
  25589. 0x0851: { n:"FrtWrapper" },
  25590. 0x0852: { n:"StartBlock" },
  25591. 0x0853: { n:"EndBlock" },
  25592. 0x0854: { n:"StartObject" },
  25593. 0x0855: { n:"EndObject" },
  25594. 0x0856: { n:"CatLab" },
  25595. 0x0857: { n:"YMult" },
  25596. 0x0858: { n:"SXViewLink" },
  25597. 0x0859: { n:"PivotChartBits" },
  25598. 0x085a: { n:"FrtFontList" },
  25599. 0x0862: { n:"SheetExt" },
  25600. 0x0863: { n:"BookExt", r:12},
  25601. 0x0864: { n:"SXAddl" },
  25602. 0x0865: { n:"CrErr" },
  25603. 0x0866: { n:"HFPicture" },
  25604. 0x0867: { n:'FeatHdr', f:parsenoop2 },
  25605. 0x0868: { n:"Feat" },
  25606. 0x086a: { n:"DataLabExt" },
  25607. 0x086b: { n:"DataLabExtContents" },
  25608. 0x086c: { n:"CellWatch" },
  25609. 0x0871: { n:"FeatHdr11" },
  25610. 0x0872: { n:"Feature11" },
  25611. 0x0874: { n:"DropDownObjIds" },
  25612. 0x0875: { n:"ContinueFrt11" },
  25613. 0x0876: { n:"DConn" },
  25614. 0x0877: { n:"List12" },
  25615. 0x0878: { n:"Feature12" },
  25616. 0x0879: { n:"CondFmt12" },
  25617. 0x087a: { n:"CF12" },
  25618. 0x087b: { n:"CFEx" },
  25619. 0x087c: { n:"XFCRC", f:parse_XFCRC, r:12 },
  25620. 0x087d: { n:"XFExt", f:parse_XFExt, r:12 },
  25621. 0x087e: { n:"AutoFilter12" },
  25622. 0x087f: { n:"ContinueFrt12" },
  25623. 0x0884: { n:"MDTInfo" },
  25624. 0x0885: { n:"MDXStr" },
  25625. 0x0886: { n:"MDXTuple" },
  25626. 0x0887: { n:"MDXSet" },
  25627. 0x0888: { n:"MDXProp" },
  25628. 0x0889: { n:"MDXKPI" },
  25629. 0x088a: { n:"MDB" },
  25630. 0x088b: { n:"PLV" },
  25631. 0x088c: { n:"Compat12", f:parsebool, r:12 },
  25632. 0x088d: { n:"DXF" },
  25633. 0x088e: { n:"TableStyles", r:12 },
  25634. 0x088f: { n:"TableStyle" },
  25635. 0x0890: { n:"TableStyleElement" },
  25636. 0x0892: { n:"StyleExt" },
  25637. 0x0893: { n:"NamePublish" },
  25638. 0x0894: { n:"NameCmt", f:parse_NameCmt, r:12 },
  25639. 0x0895: { n:"SortData" },
  25640. 0x0896: { n:"Theme", f:parse_Theme, r:12 },
  25641. 0x0897: { n:"GUIDTypeLib" },
  25642. 0x0898: { n:"FnGrp12" },
  25643. 0x0899: { n:"NameFnGrp12" },
  25644. 0x089a: { n:"MTRSettings", f:parse_MTRSettings, r:12 },
  25645. 0x089b: { n:"CompressPictures", f:parsenoop2 },
  25646. 0x089c: { n:"HeaderFooter" },
  25647. 0x089d: { n:"CrtLayout12" },
  25648. 0x089e: { n:"CrtMlFrt" },
  25649. 0x089f: { n:"CrtMlFrtContinue" },
  25650. 0x08a3: { n:"ForceFullCalculation", f:parse_ForceFullCalculation },
  25651. 0x08a4: { n:"ShapePropsStream" },
  25652. 0x08a5: { n:"TextPropsStream" },
  25653. 0x08a6: { n:"RichTextStream" },
  25654. 0x08a7: { n:"CrtLayout12A" },
  25655. 0x1001: { n:"Units" },
  25656. 0x1002: { n:"Chart" },
  25657. 0x1003: { n:"Series" },
  25658. 0x1006: { n:"DataFormat" },
  25659. 0x1007: { n:"LineFormat" },
  25660. 0x1009: { n:"MarkerFormat" },
  25661. 0x100a: { n:"AreaFormat" },
  25662. 0x100b: { n:"PieFormat" },
  25663. 0x100c: { n:"AttachedLabel" },
  25664. 0x100d: { n:"SeriesText" },
  25665. 0x1014: { n:"ChartFormat" },
  25666. 0x1015: { n:"Legend" },
  25667. 0x1016: { n:"SeriesList" },
  25668. 0x1017: { n:"Bar" },
  25669. 0x1018: { n:"Line" },
  25670. 0x1019: { n:"Pie" },
  25671. 0x101a: { n:"Area" },
  25672. 0x101b: { n:"Scatter" },
  25673. 0x101c: { n:"CrtLine" },
  25674. 0x101d: { n:"Axis" },
  25675. 0x101e: { n:"Tick" },
  25676. 0x101f: { n:"ValueRange" },
  25677. 0x1020: { n:"CatSerRange" },
  25678. 0x1021: { n:"AxisLine" },
  25679. 0x1022: { n:"CrtLink" },
  25680. 0x1024: { n:"DefaultText" },
  25681. 0x1025: { n:"Text" },
  25682. 0x1026: { n:"FontX", f:parseuint16 },
  25683. 0x1027: { n:"ObjectLink" },
  25684. 0x1032: { n:"Frame" },
  25685. 0x1033: { n:"Begin" },
  25686. 0x1034: { n:"End" },
  25687. 0x1035: { n:"PlotArea" },
  25688. 0x103a: { n:"Chart3d" },
  25689. 0x103c: { n:"PicF" },
  25690. 0x103d: { n:"DropBar" },
  25691. 0x103e: { n:"Radar" },
  25692. 0x103f: { n:"Surf" },
  25693. 0x1040: { n:"RadarArea" },
  25694. 0x1041: { n:"AxisParent" },
  25695. 0x1043: { n:"LegendException" },
  25696. 0x1044: { n:"ShtProps", f:parse_ShtProps },
  25697. 0x1045: { n:"SerToCrt" },
  25698. 0x1046: { n:"AxesUsed" },
  25699. 0x1048: { n:"SBaseRef" },
  25700. 0x104a: { n:"SerParent" },
  25701. 0x104b: { n:"SerAuxTrend" },
  25702. 0x104e: { n:"IFmtRecord" },
  25703. 0x104f: { n:"Pos" },
  25704. 0x1050: { n:"AlRuns" },
  25705. 0x1051: { n:"BRAI" },
  25706. 0x105b: { n:"SerAuxErrBar" },
  25707. 0x105c: { n:"ClrtClient", f:parse_ClrtClient },
  25708. 0x105d: { n:"SerFmt" },
  25709. 0x105f: { n:"Chart3DBarShape" },
  25710. 0x1060: { n:"Fbi" },
  25711. 0x1061: { n:"BopPop" },
  25712. 0x1062: { n:"AxcExt" },
  25713. 0x1063: { n:"Dat" },
  25714. 0x1064: { n:"PlotGrowth" },
  25715. 0x1065: { n:"SIIndex" },
  25716. 0x1066: { n:"GelFrame" },
  25717. 0x1067: { n:"BopPopCustom" },
  25718. 0x1068: { n:"Fbi2" },
  25719. 0x0000: { n:"Dimensions", f:parse_Dimensions },
  25720. 0x0002: { n:"BIFF2INT", f:parse_BIFF2INT },
  25721. 0x0005: { n:"BoolErr", f:parse_BoolErr },
  25722. 0x0007: { n:"String", f:parse_BIFF2STRING },
  25723. 0x0008: { n:"BIFF2ROW" },
  25724. 0x000b: { n:"Index" },
  25725. 0x0016: { n:"ExternCount", f:parseuint16 },
  25726. 0x001e: { n:"BIFF2FORMAT", f:parse_BIFF2Format },
  25727. 0x001f: { n:"BIFF2FMTCNT" }, /* 16-bit cnt of BIFF2FORMAT records */
  25728. 0x0020: { n:"BIFF2COLINFO" },
  25729. 0x0021: { n:"Array", f:parse_Array },
  25730. 0x0025: { n:"DefaultRowHeight", f:parse_DefaultRowHeight },
  25731. 0x0032: { n:"BIFF2FONTXTRA", f:parse_BIFF2FONTXTRA },
  25732. 0x0034: { n:"DDEObjName" },
  25733. 0x003e: { n:"BIFF2WINDOW2" },
  25734. 0x0043: { n:"BIFF2XF" },
  25735. 0x0045: { n:"BIFF2FONTCLR" },
  25736. 0x0056: { n:"BIFF4FMTCNT" }, /* 16-bit cnt, similar to BIFF2 */
  25737. 0x007e: { n:"RK" }, /* Not necessarily same as 0x027e */
  25738. 0x007f: { n:"ImData", f:parse_ImData },
  25739. 0x0087: { n:"Addin" },
  25740. 0x0088: { n:"Edg" },
  25741. 0x0089: { n:"Pub" },
  25742. 0x0091: { n:"Sub" },
  25743. 0x0094: { n:"LHRecord" },
  25744. 0x0095: { n:"LHNGraph" },
  25745. 0x0096: { n:"Sound" },
  25746. 0x00a9: { n:"CoordList" },
  25747. 0x00ab: { n:"GCW" },
  25748. 0x00bc: { n:"ShrFmla" }, /* Not necessarily same as 0x04bc */
  25749. 0x00bf: { n:"ToolbarHdr" },
  25750. 0x00c0: { n:"ToolbarEnd" },
  25751. 0x00c2: { n:"AddMenu" },
  25752. 0x00c3: { n:"DelMenu" },
  25753. 0x00d6: { n:"RString", f:parse_RString },
  25754. 0x00df: { n:"UDDesc" },
  25755. 0x00ea: { n:"TabIdConf" },
  25756. 0x0162: { n:"XL5Modify" },
  25757. 0x01a5: { n:"FileSharing2" },
  25758. 0x0209: { n:'BOF', f:parse_BOF },
  25759. 0x0218: { n:"Lbl", f:parse_Lbl },
  25760. 0x0223: { n:"ExternName", f:parse_ExternName },
  25761. 0x0231: { n:"Font" },
  25762. 0x0243: { n:"BIFF3XF" },
  25763. 0x0409: { n:'BOF', f:parse_BOF },
  25764. 0x0443: { n:"BIFF4XF" },
  25765. 0x086d: { n:"FeatInfo" },
  25766. 0x0873: { n:"FeatInfo11" },
  25767. 0x0881: { n:"SXAddl12" },
  25768. 0x08c0: { n:"AutoWebPub" },
  25769. 0x08c1: { n:"ListObj" },
  25770. 0x08c2: { n:"ListField" },
  25771. 0x08c3: { n:"ListDV" },
  25772. 0x08c4: { n:"ListCondFmt" },
  25773. 0x08c5: { n:"ListCF" },
  25774. 0x08c6: { n:"FMQry" },
  25775. 0x08c7: { n:"FMSQry" },
  25776. 0x08c8: { n:"PLV" },
  25777. 0x08c9: { n:"LnExt" },
  25778. 0x08ca: { n:"MkrExt" },
  25779. 0x08cb: { n:"CrtCoopt" },
  25780. 0x08d6: { n:"FRTArchId$", r:12 },
  25781. 0x7262: {}
  25782. };
  25783. var XLSRE = evert_key(XLSRecordEnum, 'n');
  25784. function write_biff_rec(ba, type, payload, length) {
  25785. var t = +type || +XLSRE[type];
  25786. if(isNaN(t)) return;
  25787. var len = length || (payload||[]).length || 0;
  25788. var o = ba.next(4);
  25789. o.write_shift(2, t);
  25790. o.write_shift(2, len);
  25791. if(len > 0 && is_buf(payload)) ba.push(payload);
  25792. }
  25793. function write_biff_continue(ba, type, payload, length) {
  25794. var len = length || (payload||[]).length || 0;
  25795. if(len <= 8224) return write_biff_rec(ba, type, payload, len);
  25796. var t = +type || +XLSRE[type];
  25797. if(isNaN(t)) return;
  25798. var parts = payload.parts || [], sidx = 0;
  25799. var i = 0, w = 0;
  25800. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  25801. var o = ba.next(4);
  25802. o.write_shift(2, t);
  25803. o.write_shift(2, w);
  25804. ba.push(payload.slice(i, i + w));
  25805. i += w;
  25806. while(i < len) {
  25807. o = ba.next(4);
  25808. o.write_shift(2, 0x3c); // TODO: figure out correct continue type
  25809. w = 0;
  25810. while(w + (parts[sidx] || 8224) <= 8224) { w+= (parts[sidx] || 8224); sidx++; }
  25811. o.write_shift(2, w);
  25812. ba.push(payload.slice(i, i+w)); i+= w;
  25813. }
  25814. }
  25815. function write_BIFF2Cell(out, r, c) {
  25816. if(!out) out = new_buf(7);
  25817. out.write_shift(2, r);
  25818. out.write_shift(2, c);
  25819. out.write_shift(2, 0);
  25820. out.write_shift(1, 0);
  25821. return out;
  25822. }
  25823. function write_BIFF2BERR(r, c, val, t) {
  25824. var out = new_buf(9);
  25825. write_BIFF2Cell(out, r, c);
  25826. if(t == 'e') { out.write_shift(1, val); out.write_shift(1, 1); }
  25827. else { out.write_shift(1, val?1:0); out.write_shift(1, 0); }
  25828. return out;
  25829. }
  25830. /* TODO: codepage, large strings */
  25831. function write_BIFF2LABEL(r, c, val) {
  25832. var out = new_buf(8 + 2*val.length);
  25833. write_BIFF2Cell(out, r, c);
  25834. out.write_shift(1, val.length);
  25835. out.write_shift(val.length, val, 'sbcs');
  25836. return out.l < out.length ? out.slice(0, out.l) : out;
  25837. }
  25838. function write_ws_biff2_cell(ba, cell, R, C) {
  25839. if(cell.v != null) switch(cell.t) {
  25840. case 'd': case 'n':
  25841. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  25842. if((v == (v|0)) && (v >= 0) && (v < 65536))
  25843. write_biff_rec(ba, 0x0002, write_BIFF2INT(R, C, v));
  25844. else
  25845. write_biff_rec(ba, 0x0003, write_BIFF2NUM(R,C, v));
  25846. return;
  25847. case 'b': case 'e': write_biff_rec(ba, 0x0005, write_BIFF2BERR(R, C, cell.v, cell.t)); return;
  25848. /* TODO: codepage, sst */
  25849. case 's': case 'str':
  25850. write_biff_rec(ba, 0x0004, write_BIFF2LABEL(R, C, cell.v));
  25851. return;
  25852. }
  25853. write_biff_rec(ba, 0x0001, write_BIFF2Cell(null, R, C));
  25854. }
  25855. function write_ws_biff2(ba, ws, idx, opts) {
  25856. var dense = Array.isArray(ws);
  25857. var range = safe_decode_range(ws['!ref'] || "A1"), ref, rr = "", cols = [];
  25858. if(range.e.c > 0xFF || range.e.r > 0x3FFF) {
  25859. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  25860. range.e.c = Math.min(range.e.c, 0xFF);
  25861. range.e.r = Math.min(range.e.c, 0x3FFF);
  25862. ref = encode_range(range);
  25863. }
  25864. for(var R = range.s.r; R <= range.e.r; ++R) {
  25865. rr = encode_row(R);
  25866. for(var C = range.s.c; C <= range.e.c; ++C) {
  25867. if(R === range.s.r) cols[C] = encode_col(C);
  25868. ref = cols[C] + rr;
  25869. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  25870. if(!cell) continue;
  25871. /* write cell */
  25872. write_ws_biff2_cell(ba, cell, R, C, opts);
  25873. }
  25874. }
  25875. }
  25876. /* Based on test files */
  25877. function write_biff2_buf(wb, opts) {
  25878. var o = opts || {};
  25879. if(DENSE != null && o.dense == null) o.dense = DENSE;
  25880. var ba = buf_array();
  25881. var idx = 0;
  25882. for(var i=0;i<wb.SheetNames.length;++i) if(wb.SheetNames[i] == o.sheet) idx=i;
  25883. if(idx == 0 && !!o.sheet && wb.SheetNames[0] != o.sheet) throw new Error("Sheet not found: " + o.sheet);
  25884. write_biff_rec(ba, 0x0009, write_BOF(wb, 0x10, o));
  25885. /* ... */
  25886. write_ws_biff2(ba, wb.Sheets[wb.SheetNames[idx]], idx, o, wb);
  25887. /* ... */
  25888. write_biff_rec(ba, 0x000A);
  25889. return ba.end();
  25890. }
  25891. function write_FONTS_biff8(ba, data, opts) {
  25892. write_biff_rec(ba, "Font", write_Font({
  25893. sz:12,
  25894. color: {theme:1},
  25895. name: "Arial",
  25896. family: 2,
  25897. scheme: "minor"
  25898. }, opts));
  25899. }
  25900. function write_FMTS_biff8(ba, NF, opts) {
  25901. if(!NF) return;
  25902. [[5,8],[23,26],[41,44],[/*63*/50,/*66],[164,*/392]].forEach(function(r) {
  25903. for(var i = r[0]; i <= r[1]; ++i) if(NF[i] != null) write_biff_rec(ba, "Format", write_Format(i, NF[i], opts));
  25904. });
  25905. }
  25906. function write_FEAT(ba, ws) {
  25907. /* [MS-XLS] 2.4.112 */
  25908. var o = new_buf(19);
  25909. o.write_shift(4, 0x867); o.write_shift(4, 0); o.write_shift(4, 0);
  25910. o.write_shift(2, 3); o.write_shift(1, 1); o.write_shift(4, 0);
  25911. write_biff_rec(ba, "FeatHdr", o);
  25912. /* [MS-XLS] 2.4.111 */
  25913. o = new_buf(39);
  25914. o.write_shift(4, 0x868); o.write_shift(4, 0); o.write_shift(4, 0);
  25915. o.write_shift(2, 3); o.write_shift(1, 0); o.write_shift(4, 0);
  25916. o.write_shift(2, 1); o.write_shift(4, 4); o.write_shift(2, 0);
  25917. write_Ref8U(safe_decode_range(ws['!ref']||"A1"), o);
  25918. o.write_shift(4, 4);
  25919. write_biff_rec(ba, "Feat", o);
  25920. }
  25921. function write_CELLXFS_biff8(ba, opts) {
  25922. for(var i = 0; i < 16; ++i) write_biff_rec(ba, "XF", write_XF({numFmtId:0, style:true}, 0, opts));
  25923. opts.cellXfs.forEach(function(c) {
  25924. write_biff_rec(ba, "XF", write_XF(c, 0, opts));
  25925. });
  25926. }
  25927. function write_ws_biff8_hlinks(ba, ws) {
  25928. for(var R=0; R<ws['!links'].length; ++R) {
  25929. var HL = ws['!links'][R];
  25930. write_biff_rec(ba, "HLink", write_HLink(HL));
  25931. if(HL[1].Tooltip) write_biff_rec(ba, "HLinkTooltip", write_HLinkTooltip(HL));
  25932. }
  25933. delete ws['!links'];
  25934. }
  25935. function write_ws_biff8_cell(ba, cell, R, C, opts) {
  25936. var os = 16 + get_cell_style(opts.cellXfs, cell, opts);
  25937. if(cell.v == null && !cell.bf) {
  25938. write_biff_rec(ba, "Blank", write_XLSCell(R, C, os));
  25939. return;
  25940. }
  25941. if(cell.bf) write_biff_rec(ba, "Formula", write_Formula(cell, R, C, opts, os));
  25942. else switch(cell.t) {
  25943. case 'd': case 'n':
  25944. var v = cell.t == 'd' ? datenum(parseDate(cell.v)) : cell.v;
  25945. /* TODO: emit RK as appropriate */
  25946. write_biff_rec(ba, "Number", write_Number(R, C, v, os, opts));
  25947. break;
  25948. case 'b': case 'e':
  25949. write_biff_rec(ba, 0x0205, write_BoolErr(R, C, cell.v, os, opts, cell.t));
  25950. break;
  25951. /* TODO: codepage, sst */
  25952. case 's': case 'str':
  25953. if(opts.bookSST) {
  25954. var isst = get_sst_id(opts.Strings, cell.v, opts.revStrings);
  25955. write_biff_rec(ba, "LabelSst", write_LabelSst(R, C, isst, os, opts));
  25956. } else write_biff_rec(ba, "Label", write_Label(R, C, cell.v, os, opts));
  25957. break;
  25958. default:
  25959. write_biff_rec(ba, "Blank", write_XLSCell(R, C, os));
  25960. }
  25961. }
  25962. /* [MS-XLS] 2.1.7.20.5 */
  25963. function write_ws_biff8(idx, opts, wb) {
  25964. var ba = buf_array();
  25965. var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
  25966. var _WB = ((wb||{}).Workbook||{});
  25967. var _sheet = ((_WB.Sheets||[])[idx]||{});
  25968. var dense = Array.isArray(ws);
  25969. var b8 = opts.biff == 8;
  25970. var ref, rr = "", cols = [];
  25971. var range = safe_decode_range(ws['!ref'] || "A1");
  25972. var MAX_ROWS = b8 ? 65536 : 16384;
  25973. if(range.e.c > 0xFF || range.e.r >= MAX_ROWS) {
  25974. if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
  25975. range.e.c = Math.min(range.e.c, 0xFF);
  25976. range.e.r = Math.min(range.e.c, MAX_ROWS-1);
  25977. }
  25978. write_biff_rec(ba, 0x0809, write_BOF(wb, 0x10, opts));
  25979. /* [Uncalced] Index */
  25980. write_biff_rec(ba, "CalcMode", writeuint16(1));
  25981. write_biff_rec(ba, "CalcCount", writeuint16(100));
  25982. write_biff_rec(ba, "CalcRefMode", writebool(true));
  25983. write_biff_rec(ba, "CalcIter", writebool(false));
  25984. write_biff_rec(ba, "CalcDelta", write_Xnum(0.001));
  25985. write_biff_rec(ba, "CalcSaveRecalc", writebool(true));
  25986. write_biff_rec(ba, "PrintRowCol", writebool(false));
  25987. write_biff_rec(ba, "PrintGrid", writebool(false));
  25988. write_biff_rec(ba, "GridSet", writeuint16(1));
  25989. write_biff_rec(ba, "Guts", write_Guts([0,0]));
  25990. /* DefaultRowHeight WsBool [Sync] [LPr] [HorizontalPageBreaks] [VerticalPageBreaks] */
  25991. /* Header (string) */
  25992. /* Footer (string) */
  25993. write_biff_rec(ba, "HCenter", writebool(false));
  25994. write_biff_rec(ba, "VCenter", writebool(false));
  25995. /* ... */
  25996. write_biff_rec(ba, 0x200, write_Dimensions(range, opts));
  25997. /* ... */
  25998. if(b8) ws['!links'] = [];
  25999. for(var R = range.s.r; R <= range.e.r; ++R) {
  26000. rr = encode_row(R);
  26001. for(var C = range.s.c; C <= range.e.c; ++C) {
  26002. if(R === range.s.r) cols[C] = encode_col(C);
  26003. ref = cols[C] + rr;
  26004. var cell = dense ? (ws[R]||[])[C] : ws[ref];
  26005. if(!cell) continue;
  26006. /* write cell */
  26007. write_ws_biff8_cell(ba, cell, R, C, opts);
  26008. if(b8 && cell.l) ws['!links'].push([ref, cell.l]);
  26009. }
  26010. }
  26011. var cname = _sheet.CodeName || _sheet.name || s;
  26012. /* ... */
  26013. if(b8) write_biff_rec(ba, "Window2", write_Window2((_WB.Views||[])[0]));
  26014. /* ... */
  26015. if(b8 && (ws['!merges']||[]).length) write_biff_rec(ba, "MergeCells", write_MergeCells(ws['!merges']));
  26016. /* [LRng] *QUERYTABLE [PHONETICINFO] CONDFMTS */
  26017. if(b8) write_ws_biff8_hlinks(ba, ws);
  26018. /* [DVAL] */
  26019. write_biff_rec(ba, "CodeName", write_XLUnicodeString(cname, opts));
  26020. /* *WebPub *CellWatch [SheetExt] */
  26021. if(b8) write_FEAT(ba, ws);
  26022. /* *FEAT11 *RECORD12 */
  26023. write_biff_rec(ba, "EOF");
  26024. return ba.end();
  26025. }
  26026. /* [MS-XLS] 2.1.7.20.3 */
  26027. function write_biff8_global(wb, bufs, opts) {
  26028. var A = buf_array();
  26029. var _WB = ((wb||{}).Workbook||{});
  26030. var _sheets = (_WB.Sheets||[]);
  26031. var _wb = _WB.WBProps||{};
  26032. var b8 = opts.biff == 8, b5 = opts.biff == 5;
  26033. write_biff_rec(A, 0x0809, write_BOF(wb, 0x05, opts));
  26034. if(opts.bookType == "xla") write_biff_rec(A, "Addin");
  26035. write_biff_rec(A, "InterfaceHdr", b8 ? writeuint16(0x04b0) : null);
  26036. write_biff_rec(A, "Mms", writezeroes(2));
  26037. if(b5) write_biff_rec(A, "ToolbarHdr");
  26038. if(b5) write_biff_rec(A, "ToolbarEnd");
  26039. write_biff_rec(A, "InterfaceEnd");
  26040. write_biff_rec(A, "WriteAccess", write_WriteAccess("SheetJS", opts));
  26041. /* [FileSharing] */
  26042. write_biff_rec(A, "CodePage", writeuint16(b8 ? 0x04b0 : 0x04E4));
  26043. /* *2047 Lel */
  26044. if(b8) write_biff_rec(A, "DSF", writeuint16(0));
  26045. if(b8) write_biff_rec(A, "Excel9File");
  26046. write_biff_rec(A, "RRTabId", write_RRTabId(wb.SheetNames.length));
  26047. if(b8 && wb.vbaraw) write_biff_rec(A, "ObProj");
  26048. /* [ObNoMacros] */
  26049. if(b8 && wb.vbaraw) {
  26050. var cname = _wb.CodeName || "ThisWorkbook";
  26051. write_biff_rec(A, "CodeName", write_XLUnicodeString(cname, opts));
  26052. }
  26053. write_biff_rec(A, "BuiltInFnGroupCount", writeuint16(0x11));
  26054. /* *FnGroupName *FnGrp12 */
  26055. /* *Lbl */
  26056. /* [OleObjectSize] */
  26057. write_biff_rec(A, "WinProtect", writebool(false));
  26058. write_biff_rec(A, "Protect", writebool(false));
  26059. write_biff_rec(A, "Password", writeuint16(0));
  26060. if(b8) write_biff_rec(A, "Prot4Rev", writebool(false));
  26061. if(b8) write_biff_rec(A, "Prot4RevPass", writeuint16(0));
  26062. write_biff_rec(A, "Window1", write_Window1(opts));
  26063. write_biff_rec(A, "Backup", writebool(false));
  26064. write_biff_rec(A, "HideObj", writeuint16(0));
  26065. write_biff_rec(A, "Date1904", writebool(safe1904(wb)=="true"));
  26066. write_biff_rec(A, "CalcPrecision", writebool(true));
  26067. if(b8) write_biff_rec(A, "RefreshAll", writebool(false));
  26068. write_biff_rec(A, "BookBool", writeuint16(0));
  26069. /* ... */
  26070. write_FONTS_biff8(A, wb, opts);
  26071. write_FMTS_biff8(A, wb.SSF, opts);
  26072. write_CELLXFS_biff8(A, opts);
  26073. /* ... */
  26074. if(b8) write_biff_rec(A, "UsesELFs", writebool(false));
  26075. var a = A.end();
  26076. var C = buf_array();
  26077. /* METADATA [MTRSettings] [ForceFullCalculation] */
  26078. if(b8) write_biff_rec(C, "Country", write_Country());
  26079. /* *SUPBOOK *LBL *RTD [RecalcId] *HFPicture *MSODRAWINGGROUP */
  26080. /* BIFF8: [SST *Continue] ExtSST */
  26081. if(b8 && opts.Strings) write_biff_continue(C, "SST", write_SST(opts.Strings, opts));
  26082. /* *WebPub [WOpt] [CrErr] [BookExt] *FeatHdr *DConn [THEME] [CompressPictures] [Compat12] [GUIDTypeLib] */
  26083. write_biff_rec(C, "EOF");
  26084. var c = C.end();
  26085. var B = buf_array();
  26086. var blen = 0, j = 0;
  26087. for(j = 0; j < wb.SheetNames.length; ++j) blen += (b8 ? 12 : 11) + (b8 ? 2 : 1) * wb.SheetNames[j].length;
  26088. var start = a.length + blen + c.length;
  26089. for(j = 0; j < wb.SheetNames.length; ++j) {
  26090. var _sheet = _sheets[j] || ({});
  26091. write_biff_rec(B, "BoundSheet8", write_BoundSheet8({pos:start, hs:_sheet.Hidden||0, dt:0, name:wb.SheetNames[j]}, opts));
  26092. start += bufs[j].length;
  26093. }
  26094. /* 1*BoundSheet8 */
  26095. var b = B.end();
  26096. if(blen != b.length) throw new Error("BS8 " + blen + " != " + b.length);
  26097. var out = [];
  26098. if(a.length) out.push(a);
  26099. if(b.length) out.push(b);
  26100. if(c.length) out.push(c);
  26101. return __toBuffer([out]);
  26102. }
  26103. /* [MS-XLS] 2.1.7.20 Workbook Stream */
  26104. function write_biff8_buf(wb, opts) {
  26105. var o = opts || {};
  26106. var bufs = [];
  26107. if(wb && !wb.SSF) {
  26108. wb.SSF = SSF.get_table();
  26109. }
  26110. if(wb && wb.SSF) {
  26111. make_ssf(SSF); SSF.load_table(wb.SSF);
  26112. // $FlowIgnore
  26113. o.revssf = evert_num(wb.SSF); o.revssf[wb.SSF[65535]] = 0;
  26114. o.ssf = wb.SSF;
  26115. }
  26116. o.Strings = []; o.Strings.Count = 0; o.Strings.Unique = 0;
  26117. fix_write_opts(o);
  26118. o.cellXfs = [];
  26119. get_cell_style(o.cellXfs, {}, {revssf:{"General":0}});
  26120. if(!wb.Props) wb.Props = {};
  26121. for(var i = 0; i < wb.SheetNames.length; ++i) bufs[bufs.length] = write_ws_biff8(i, o, wb);
  26122. bufs.unshift(write_biff8_global(wb, bufs, o));
  26123. return __toBuffer([bufs]);
  26124. }
  26125. function write_biff_buf(wb, opts) {
  26126. var o = opts || {};
  26127. switch(o.biff || 2) {
  26128. case 8: case 5: return write_biff8_buf(wb, opts);
  26129. case 4: case 3: case 2: return write_biff2_buf(wb, opts);
  26130. }
  26131. throw new Error("invalid type " + o.bookType + " for BIFF");
  26132. }
  26133. /* note: browser DOM element cannot see mso- style attrs, must parse */
  26134. var HTML_ = (function() {
  26135. function html_to_sheet(str, _opts) {
  26136. var opts = _opts || {};
  26137. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  26138. var ws = opts.dense ? ([]) : ({});
  26139. str = str.replace(/<!--.*?-->/g, "");
  26140. var mtch = str.match(/<table/i);
  26141. if(!mtch) throw new Error("Invalid HTML: could not find <table>");
  26142. var mtch2 = str.match(/<\/table/i);
  26143. var i = mtch.index, j = mtch2 && mtch2.index || str.length;
  26144. var rows = split_regex(str.slice(i, j), /(:?<tr[^>]*>)/i, "<tr>");
  26145. var R = -1, C = 0, RS = 0, CS = 0;
  26146. var range = {s:{r:10000000, c:10000000},e:{r:0,c:0}};
  26147. var merges = [];
  26148. for(i = 0; i < rows.length; ++i) {
  26149. var row = rows[i].trim();
  26150. var hd = row.slice(0,3).toLowerCase();
  26151. if(hd == "<tr") { ++R; if(opts.sheetRows && opts.sheetRows <= R) { --R; break; } C = 0; continue; }
  26152. if(hd != "<td" && hd != "<th") continue;
  26153. var cells = row.split(/<\/t[dh]>/i);
  26154. for(j = 0; j < cells.length; ++j) {
  26155. var cell = cells[j].trim();
  26156. if(!cell.match(/<t[dh]/i)) continue;
  26157. var m = cell, cc = 0;
  26158. /* TODO: parse styles etc */
  26159. while(m.charAt(0) == "<" && (cc = m.indexOf(">")) > -1) m = m.slice(cc+1);
  26160. for(var midx = 0; midx < merges.length; ++midx) {
  26161. var _merge = merges[midx];
  26162. if(_merge.s.c == C && _merge.s.r < R && R <= _merge.e.r) { C = _merge.e.c + 1; midx = -1; }
  26163. }
  26164. var tag = parsexmltag(cell.slice(0, cell.indexOf(">")));
  26165. CS = tag.colspan ? +tag.colspan : 1;
  26166. if((RS = +tag.rowspan)>1 || CS>1) merges.push({s:{r:R,c:C},e:{r:R + (RS||1) - 1, c:C + CS - 1}});
  26167. var _t = tag.t || "";
  26168. /* TODO: generate stub cells */
  26169. if(!m.length) { C += CS; continue; }
  26170. m = htmldecode(m);
  26171. if(range.s.r > R) range.s.r = R; if(range.e.r < R) range.e.r = R;
  26172. if(range.s.c > C) range.s.c = C; if(range.e.c < C) range.e.c = C;
  26173. if(!m.length) continue;
  26174. var o = {t:'s', v:m};
  26175. if(opts.raw || !m.trim().length || _t == 's'){}
  26176. else if(m === 'TRUE') o = {t:'b', v:true};
  26177. else if(m === 'FALSE') o = {t:'b', v:false};
  26178. else if(!isNaN(fuzzynum(m))) o = {t:'n', v:fuzzynum(m)};
  26179. else if(!isNaN(fuzzydate(m).getDate())) {
  26180. o = ({t:'d', v:parseDate(m)});
  26181. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  26182. o.z = opts.dateNF || SSF._table[14];
  26183. }
  26184. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = o; }
  26185. else ws[encode_cell({r:R, c:C})] = o;
  26186. C += CS;
  26187. }
  26188. }
  26189. ws['!ref'] = encode_range(range);
  26190. if(merges.length) ws["!merges"] = merges;
  26191. return ws;
  26192. }
  26193. function html_to_book(str, opts) {
  26194. return sheet_to_workbook(html_to_sheet(str, opts), opts);
  26195. }
  26196. function make_html_row(ws, r, R, o) {
  26197. var M = (ws['!merges'] ||[]);
  26198. var oo = [];
  26199. for(var C = r.s.c; C <= r.e.c; ++C) {
  26200. var RS = 0, CS = 0;
  26201. for(var j = 0; j < M.length; ++j) {
  26202. if(M[j].s.r > R || M[j].s.c > C) continue;
  26203. if(M[j].e.r < R || M[j].e.c < C) continue;
  26204. if(M[j].s.r < R || M[j].s.c < C) { RS = -1; break; }
  26205. RS = M[j].e.r - M[j].s.r + 1; CS = M[j].e.c - M[j].s.c + 1; break;
  26206. }
  26207. if(RS < 0) continue;
  26208. var coord = encode_cell({r:R,c:C});
  26209. var cell = o.dense ? (ws[R]||[])[C] : ws[coord];
  26210. /* TODO: html entities */
  26211. var w = (cell && cell.v != null) && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || "";
  26212. var sp = ({});
  26213. if(RS > 1) sp.rowspan = RS;
  26214. if(CS > 1) sp.colspan = CS;
  26215. sp.t = cell && cell.t || 'z';
  26216. if(o.editable) w = '<span contenteditable="true">' + w + '</span>';
  26217. sp.id = (o.id || "sjs") + "-" + coord;
  26218. if(sp.t != "z") { sp.v = cell.v; if(cell.z != null) sp.z = cell.z; }
  26219. oo.push(writextag('td', w, sp));
  26220. }
  26221. var preamble = "<tr>";
  26222. return preamble + oo.join("") + "</tr>";
  26223. }
  26224. function make_html_preamble(ws, R, o) {
  26225. var out = [];
  26226. return out.join("") + '<table' + (o && o.id ? ' id="' + o.id + '"' : "") + '>';
  26227. }
  26228. var _BEGIN = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body>';
  26229. var _END = '</body></html>';
  26230. function sheet_to_html(ws, opts/*, wb:?Workbook*/) {
  26231. var o = opts || {};
  26232. var header = o.header != null ? o.header : _BEGIN;
  26233. var footer = o.footer != null ? o.footer : _END;
  26234. var out = [header];
  26235. var r = decode_range(ws['!ref']);
  26236. o.dense = Array.isArray(ws);
  26237. out.push(make_html_preamble(ws, r, o));
  26238. for(var R = r.s.r; R <= r.e.r; ++R) out.push(make_html_row(ws, r, R, o));
  26239. out.push("</table>" + footer);
  26240. return out.join("");
  26241. }
  26242. return {
  26243. to_workbook: html_to_book,
  26244. to_sheet: html_to_sheet,
  26245. _row: make_html_row,
  26246. BEGIN: _BEGIN,
  26247. END: _END,
  26248. _preamble: make_html_preamble,
  26249. from_sheet: sheet_to_html
  26250. };
  26251. })();
  26252. function sheet_add_dom(ws, table, _opts) {
  26253. var opts = _opts || {};
  26254. if(DENSE != null) opts.dense = DENSE;
  26255. var or_R = 0, or_C = 0;
  26256. if(opts.origin != null) {
  26257. if(typeof opts.origin == 'number') or_R = opts.origin;
  26258. else {
  26259. var _origin = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin;
  26260. or_R = _origin.r; or_C = _origin.c;
  26261. }
  26262. }
  26263. var rows = table.getElementsByTagName('tr');
  26264. var sheetRows = Math.min(opts.sheetRows||10000000, rows.length);
  26265. var range = {s:{r:0,c:0},e:{r:or_R,c:or_C}};
  26266. if(ws["!ref"]) {
  26267. var _range = decode_range(ws["!ref"]);
  26268. range.s.r = Math.min(range.s.r, _range.s.r);
  26269. range.s.c = Math.min(range.s.c, _range.s.c);
  26270. range.e.r = Math.max(range.e.r, _range.e.r);
  26271. range.e.c = Math.max(range.e.c, _range.e.c);
  26272. if(or_R == -1) range.e.r = or_R = _range.e.r + 1;
  26273. }
  26274. var merges = [], midx = 0;
  26275. var rowinfo = ws["!rows"] || (ws["!rows"] = []);
  26276. var _R = 0, R = 0, _C = 0, C = 0, RS = 0, CS = 0;
  26277. if(!ws["!cols"]) ws['!cols'] = [];
  26278. for(; _R < rows.length && R < sheetRows; ++_R) {
  26279. var row = rows[_R];
  26280. if (is_dom_element_hidden(row)) {
  26281. if (opts.display) continue;
  26282. rowinfo[R] = {hidden: true};
  26283. }
  26284. var elts = (row.children);
  26285. for(_C = C = 0; _C < elts.length; ++_C) {
  26286. var elt = elts[_C];
  26287. if (opts.display && is_dom_element_hidden(elt)) continue;
  26288. var v = elt.hasAttribute('v') ? elt.getAttribute('v') : htmldecode(elt.innerHTML);
  26289. var z = elt.getAttribute('z');
  26290. for(midx = 0; midx < merges.length; ++midx) {
  26291. var m = merges[midx];
  26292. if(m.s.c == C + or_C && m.s.r < R + or_R && R + or_R <= m.e.r) { C = m.e.c+1 - or_C; midx = -1; }
  26293. }
  26294. /* TODO: figure out how to extract nonstandard mso- style */
  26295. CS = +elt.getAttribute("colspan") || 1;
  26296. if( ((RS = (+elt.getAttribute("rowspan") || 1)))>1 || CS>1) merges.push({s:{r:R + or_R,c:C + or_C},e:{r:R + or_R + (RS||1) - 1, c:C + or_C + (CS||1) - 1}});
  26297. var o = {t:'s', v:v};
  26298. var _t = elt.getAttribute("t") || "";
  26299. if(v != null) {
  26300. if(v.length == 0) o.t = _t || 'z';
  26301. else if(opts.raw || v.trim().length == 0 || _t == "s"){}
  26302. else if(v === 'TRUE') o = {t:'b', v:true};
  26303. else if(v === 'FALSE') o = {t:'b', v:false};
  26304. else if(!isNaN(fuzzynum(v))) o = {t:'n', v:fuzzynum(v)};
  26305. else if(!isNaN(fuzzydate(v).getDate())) {
  26306. o = ({t:'d', v:parseDate(v)});
  26307. if(!opts.cellDates) o = ({t:'n', v:datenum(o.v)});
  26308. o.z = opts.dateNF || SSF._table[14];
  26309. }
  26310. }
  26311. if(o.z === undefined && z != null) o.z = z;
  26312. if(opts.dense) { if(!ws[R + or_R]) ws[R + or_R] = []; ws[R + or_R][C + or_C] = o; }
  26313. else ws[encode_cell({c:C + or_C, r:R + or_R})] = o;
  26314. if(range.e.c < C + or_C) range.e.c = C + or_C;
  26315. C += CS;
  26316. }
  26317. ++R;
  26318. }
  26319. if(merges.length) ws['!merges'] = (ws["!merges"] || []).concat(merges);
  26320. range.e.r = Math.max(range.e.r, R - 1 + or_R);
  26321. ws['!ref'] = encode_range(range);
  26322. if(R >= sheetRows) ws['!fullref'] = encode_range((range.e.r = rows.length-_R+R-1 + or_R,range)); // We can count the real number of rows to parse but we don't to improve the performance
  26323. return ws;
  26324. }
  26325. function parse_dom_table(table, _opts) {
  26326. var opts = _opts || {};
  26327. var ws = opts.dense ? ([]) : ({});
  26328. return sheet_add_dom(ws, table, _opts);
  26329. }
  26330. function table_to_book(table, opts) {
  26331. return sheet_to_workbook(parse_dom_table(table, opts), opts);
  26332. }
  26333. function is_dom_element_hidden(element) {
  26334. var display = '';
  26335. var get_computed_style = get_get_computed_style_function(element);
  26336. if(get_computed_style) display = get_computed_style(element).getPropertyValue('display');
  26337. if(!display) display = element.style.display; // Fallback for cases when getComputedStyle is not available (e.g. an old browser or some Node.js environments) or doesn't work (e.g. if the element is not inserted to a document)
  26338. return display === 'none';
  26339. }
  26340. /* global getComputedStyle */
  26341. function get_get_computed_style_function(element) {
  26342. // The proper getComputedStyle implementation is the one defined in the element window
  26343. if(element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === 'function') return element.ownerDocument.defaultView.getComputedStyle;
  26344. // If it is not available, try to get one from the global namespace
  26345. if(typeof getComputedStyle === 'function') return getComputedStyle;
  26346. return null;
  26347. }
  26348. /* OpenDocument */
  26349. var parse_content_xml = (function() {
  26350. var parse_text_p = function(text) {
  26351. /* 6.1.2 White Space Characters */
  26352. var fixed = text
  26353. .replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ")
  26354. .replace(/<text:s\/>/g," ")
  26355. .replace(/<text:s text:c="(\d+)"\/>/g, function($$,$1) { return Array(parseInt($1,10)+1).join(" "); })
  26356. .replace(/<text:tab[^>]*\/>/g,"\t")
  26357. .replace(/<text:line-break\/>/g,"\n");
  26358. var v = unescapexml(fixed.replace(/<[^>]*>/g,""));
  26359. return [v];
  26360. };
  26361. var number_formats = {
  26362. /* ods name: [short ssf fmt, long ssf fmt] */
  26363. day: ["d", "dd"],
  26364. month: ["m", "mm"],
  26365. year: ["y", "yy"],
  26366. hours: ["h", "hh"],
  26367. minutes: ["m", "mm"],
  26368. seconds: ["s", "ss"],
  26369. "am-pm": ["A/P", "AM/PM"],
  26370. "day-of-week": ["ddd", "dddd"],
  26371. era: ["e", "ee"],
  26372. /* there is no native representation of LO "Q" format */
  26373. quarter: ["\\Qm", "m\\\"th quarter\""]
  26374. };
  26375. return function pcx(d, _opts) {
  26376. var opts = _opts || {};
  26377. if(DENSE != null && opts.dense == null) opts.dense = DENSE;
  26378. var str = xlml_normalize(d);
  26379. var state = [], tmp;
  26380. var tag;
  26381. var NFtag = {name:""}, NF = "", pidx = 0;
  26382. var sheetag;
  26383. var rowtag;
  26384. var Sheets = {}, SheetNames = [];
  26385. var ws = opts.dense ? ([]) : ({});
  26386. var Rn, q;
  26387. var ctag = ({value:""});
  26388. var textp = "", textpidx = 0, textptag;
  26389. var textR = [];
  26390. var R = -1, C = -1, range = {s: {r:1000000,c:10000000}, e: {r:0, c:0}};
  26391. var row_ol = 0;
  26392. var number_format_map = {};
  26393. var merges = [], mrange = {}, mR = 0, mC = 0;
  26394. var rowinfo = [], rowpeat = 1, colpeat = 1;
  26395. var arrayf = [];
  26396. var WB = {Names:[]};
  26397. var atag = ({});
  26398. var _Ref = ["", ""];
  26399. var comments = [], comment = ({});
  26400. var creator = "", creatoridx = 0;
  26401. var isstub = false, intable = false;
  26402. var i = 0;
  26403. xlmlregex.lastIndex = 0;
  26404. str = str.replace(/<!--([\s\S]*?)-->/mg,"").replace(/<!DOCTYPE[^\[]*\[[^\]]*\]>/gm,"");
  26405. while((Rn = xlmlregex.exec(str))) switch((Rn[3]=Rn[3].replace(/_.*$/,""))) {
  26406. case 'table': case '工作表': // 9.1.2 <table:table>
  26407. if(Rn[1]==='/') {
  26408. if(range.e.c >= range.s.c && range.e.r >= range.s.r) ws['!ref'] = encode_range(range);
  26409. else ws['!ref'] = "A1:A1";
  26410. if(opts.sheetRows > 0 && opts.sheetRows <= range.e.r) {
  26411. ws['!fullref'] = ws['!ref'];
  26412. range.e.r = opts.sheetRows - 1;
  26413. ws['!ref'] = encode_range(range);
  26414. }
  26415. if(merges.length) ws['!merges'] = merges;
  26416. if(rowinfo.length) ws["!rows"] = rowinfo;
  26417. sheetag.name = sheetag['名称'] || sheetag.name;
  26418. if(typeof JSON !== 'undefined') JSON.stringify(sheetag);
  26419. SheetNames.push(sheetag.name);
  26420. Sheets[sheetag.name] = ws;
  26421. intable = false;
  26422. }
  26423. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  26424. sheetag = parsexmltag(Rn[0], false);
  26425. R = C = -1;
  26426. range.s.r = range.s.c = 10000000; range.e.r = range.e.c = 0;
  26427. ws = opts.dense ? ([]) : ({}); merges = [];
  26428. rowinfo = [];
  26429. intable = true;
  26430. }
  26431. break;
  26432. case 'table-row-group': // 9.1.9 <table:table-row-group>
  26433. if(Rn[1] === "/") --row_ol; else ++row_ol;
  26434. break;
  26435. case 'table-row': case '行': // 9.1.3 <table:table-row>
  26436. if(Rn[1] === '/') { R+=rowpeat; rowpeat = 1; break; }
  26437. rowtag = parsexmltag(Rn[0], false);
  26438. if(rowtag['行号']) R = rowtag['行号'] - 1; else if(R == -1) R = 0;
  26439. rowpeat = +rowtag['number-rows-repeated'] || 1;
  26440. /* TODO: remove magic */
  26441. if(rowpeat < 10) for(i = 0; i < rowpeat; ++i) if(row_ol > 0) rowinfo[R + i] = {level: row_ol};
  26442. C = -1; break;
  26443. case 'covered-table-cell': // 9.1.5 <table:covered-table-cell>
  26444. if(Rn[1] !== '/') ++C;
  26445. if(opts.sheetStubs) {
  26446. if(opts.dense) { if(!ws[R]) ws[R] = []; ws[R][C] = {t:'z'}; }
  26447. else ws[encode_cell({r:R,c:C})] = {t:'z'};
  26448. }
  26449. textp = ""; textR = [];
  26450. break; /* stub */
  26451. case 'table-cell': case '数据':
  26452. if(Rn[0].charAt(Rn[0].length-2) === '/') {
  26453. ++C;
  26454. ctag = parsexmltag(Rn[0], false);
  26455. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  26456. q = ({t:'z', v:null});
  26457. if(ctag.formula && opts.cellFormula != false) q.f = ods_to_csf_formula(unescapexml(ctag.formula));
  26458. if((ctag['数据类型'] || ctag['value-type']) == "string") {
  26459. q.t = "s"; q.v = unescapexml(ctag['string-value'] || "");
  26460. if(opts.dense) {
  26461. if(!ws[R]) ws[R] = [];
  26462. ws[R][C] = q;
  26463. } else {
  26464. ws[encode_cell({r:R,c:C})] = q;
  26465. }
  26466. }
  26467. C+= colpeat-1;
  26468. } else if(Rn[1]!=='/') {
  26469. ++C;
  26470. colpeat = 1;
  26471. var rptR = rowpeat ? R + rowpeat - 1 : R;
  26472. if(C > range.e.c) range.e.c = C;
  26473. if(C < range.s.c) range.s.c = C;
  26474. if(R < range.s.r) range.s.r = R;
  26475. if(rptR > range.e.r) range.e.r = rptR;
  26476. ctag = parsexmltag(Rn[0], false);
  26477. comments = []; comment = ({});
  26478. q = ({t:ctag['数据类型'] || ctag['value-type'], v:null});
  26479. if(opts.cellFormula) {
  26480. if(ctag.formula) ctag.formula = unescapexml(ctag.formula);
  26481. if(ctag['number-matrix-columns-spanned'] && ctag['number-matrix-rows-spanned']) {
  26482. mR = parseInt(ctag['number-matrix-rows-spanned'],10) || 0;
  26483. mC = parseInt(ctag['number-matrix-columns-spanned'],10) || 0;
  26484. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  26485. q.F = encode_range(mrange);
  26486. arrayf.push([mrange, q.F]);
  26487. }
  26488. if(ctag.formula) q.f = ods_to_csf_formula(ctag.formula);
  26489. else for(i = 0; i < arrayf.length; ++i)
  26490. if(R >= arrayf[i][0].s.r && R <= arrayf[i][0].e.r)
  26491. if(C >= arrayf[i][0].s.c && C <= arrayf[i][0].e.c)
  26492. q.F = arrayf[i][1];
  26493. }
  26494. if(ctag['number-columns-spanned'] || ctag['number-rows-spanned']) {
  26495. mR = parseInt(ctag['number-rows-spanned'],10) || 0;
  26496. mC = parseInt(ctag['number-columns-spanned'],10) || 0;
  26497. mrange = {s: {r:R,c:C}, e:{r:R + mR-1,c:C + mC-1}};
  26498. merges.push(mrange);
  26499. }
  26500. /* 19.675.2 table:number-columns-repeated */
  26501. if(ctag['number-columns-repeated']) colpeat = parseInt(ctag['number-columns-repeated'], 10);
  26502. /* 19.385 office:value-type */
  26503. switch(q.t) {
  26504. case 'boolean': q.t = 'b'; q.v = parsexmlbool(ctag['boolean-value']); break;
  26505. case 'float': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  26506. case 'percentage': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  26507. case 'currency': q.t = 'n'; q.v = parseFloat(ctag.value); break;
  26508. case 'date': q.t = 'd'; q.v = parseDate(ctag['date-value']);
  26509. if(!opts.cellDates) { q.t = 'n'; q.v = datenum(q.v); }
  26510. q.z = 'm/d/yy'; break;
  26511. case 'time': q.t = 'n'; q.v = parse_isodur(ctag['time-value'])/86400; break;
  26512. case 'number': q.t = 'n'; q.v = parseFloat(ctag['数据数值']); break;
  26513. default:
  26514. if(q.t === 'string' || q.t === 'text' || !q.t) {
  26515. q.t = 's';
  26516. if(ctag['string-value'] != null) { textp = unescapexml(ctag['string-value']); textR = []; }
  26517. } else throw new Error('Unsupported value type ' + q.t);
  26518. }
  26519. } else {
  26520. isstub = false;
  26521. if(q.t === 's') {
  26522. q.v = textp || '';
  26523. if(textR.length) q.R = textR;
  26524. isstub = textpidx == 0;
  26525. }
  26526. if(atag.Target) q.l = atag;
  26527. if(comments.length > 0) { q.c = comments; comments = []; }
  26528. if(textp && opts.cellText !== false) q.w = textp;
  26529. if(isstub) { q.t = "z"; delete q.v; }
  26530. if(!isstub || opts.sheetStubs) {
  26531. if(!(opts.sheetRows && opts.sheetRows <= R)) {
  26532. for(var rpt = 0; rpt < rowpeat; ++rpt) {
  26533. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  26534. if(opts.dense) {
  26535. if(!ws[R + rpt]) ws[R + rpt] = [];
  26536. ws[R + rpt][C] = rpt == 0 ? q : dup(q);
  26537. while(--colpeat > 0) ws[R + rpt][C + colpeat] = dup(q);
  26538. } else {
  26539. ws[encode_cell({r:R + rpt,c:C})] = q;
  26540. while(--colpeat > 0) ws[encode_cell({r:R + rpt,c:C + colpeat})] = dup(q);
  26541. }
  26542. if(range.e.c <= C) range.e.c = C;
  26543. }
  26544. }
  26545. }
  26546. colpeat = parseInt(ctag['number-columns-repeated']||"1", 10);
  26547. C += colpeat-1; colpeat = 0;
  26548. q = {};
  26549. textp = ""; textR = [];
  26550. }
  26551. atag = ({});
  26552. break; // 9.1.4 <table:table-cell>
  26553. /* pure state */
  26554. case 'document': // TODO: <office:document> is the root for FODS
  26555. case 'document-content': case '电子表格文档': // 3.1.3.2 <office:document-content>
  26556. case 'spreadsheet': case '主体': // 3.7 <office:spreadsheet>
  26557. case 'scripts': // 3.12 <office:scripts>
  26558. case 'styles': // TODO <office:styles>
  26559. case 'font-face-decls': // 3.14 <office:font-face-decls>
  26560. case 'master-styles': //3.15.4 <office:master-styles> -- relevant for FODS
  26561. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  26562. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
  26563. break;
  26564. case 'annotation': // 14.1 <office:annotation>
  26565. if(Rn[1]==='/'){
  26566. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  26567. comment.t = textp;
  26568. if(textR.length) comment.R = textR;
  26569. comment.a = creator;
  26570. comments.push(comment);
  26571. }
  26572. else if(Rn[0].charAt(Rn[0].length-2) !== '/') {state.push([Rn[3], false]);}
  26573. creator = ""; creatoridx = 0;
  26574. textp = ""; textpidx = 0; textR = [];
  26575. break;
  26576. case 'creator': // 4.3.2.7 <dc:creator>
  26577. if(Rn[1]==='/') { creator = str.slice(creatoridx,Rn.index); }
  26578. else creatoridx = Rn.index + Rn[0].length;
  26579. break;
  26580. /* ignore state */
  26581. case 'meta': case '元数据': // TODO: <office:meta> <uof:元数据> FODS/UOF
  26582. case 'settings': // TODO: <office:settings>
  26583. case 'config-item-set': // TODO: <office:config-item-set>
  26584. case 'config-item-map-indexed': // TODO: <office:config-item-map-indexed>
  26585. case 'config-item-map-entry': // TODO: <office:config-item-map-entry>
  26586. case 'config-item-map-named': // TODO: <office:config-item-map-entry>
  26587. case 'shapes': // 9.2.8 <table:shapes>
  26588. case 'frame': // 10.4.2 <draw:frame>
  26589. case 'text-box': // 10.4.3 <draw:text-box>
  26590. case 'image': // 10.4.4 <draw:image>
  26591. case 'data-pilot-tables': // 9.6.2 <table:data-pilot-tables>
  26592. case 'list-style': // 16.30 <text:list-style>
  26593. case 'form': // 13.13 <form:form>
  26594. case 'dde-links': // 9.8 <table:dde-links>
  26595. case 'event-listeners': // TODO
  26596. case 'chart': // TODO
  26597. if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;}
  26598. else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], false]);
  26599. textp = ""; textpidx = 0; textR = [];
  26600. break;
  26601. case 'scientific-number': // TODO: <number:scientific-number>
  26602. break;
  26603. case 'currency-symbol': // TODO: <number:currency-symbol>
  26604. break;
  26605. case 'currency-style': // TODO: <number:currency-style>
  26606. break;
  26607. case 'number-style': // 16.27.2 <number:number-style>
  26608. case 'percentage-style': // 16.27.9 <number:percentage-style>
  26609. case 'date-style': // 16.27.10 <number:date-style>
  26610. case 'time-style': // 16.27.18 <number:time-style>
  26611. if(Rn[1]==='/'){
  26612. number_format_map[NFtag.name] = NF;
  26613. if((tmp=state.pop())[0]!==Rn[3]) throw "Bad state: "+tmp;
  26614. } else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
  26615. NF = "";
  26616. NFtag = parsexmltag(Rn[0], false);
  26617. state.push([Rn[3], true]);
  26618. } break;
  26619. case 'script': break; // 3.13 <office:script>
  26620. case 'libraries': break; // TODO: <ooo:libraries>
  26621. case 'automatic-styles': break; // 3.15.3 <office:automatic-styles>
  26622. case 'default-style': // TODO: <style:default-style>
  26623. case 'page-layout': break; // TODO: <style:page-layout>
  26624. case 'style': // 16.2 <style:style>
  26625. break;
  26626. case 'map': break; // 16.3 <style:map>
  26627. case 'font-face': break; // 16.21 <style:font-face>
  26628. case 'paragraph-properties': break; // 17.6 <style:paragraph-properties>
  26629. case 'table-properties': break; // 17.15 <style:table-properties>
  26630. case 'table-column-properties': break; // 17.16 <style:table-column-properties>
  26631. case 'table-row-properties': break; // 17.17 <style:table-row-properties>
  26632. case 'table-cell-properties': break; // 17.18 <style:table-cell-properties>
  26633. case 'number': // 16.27.3 <number:number>
  26634. switch(state[state.length-1][0]) {
  26635. case 'time-style':
  26636. case 'date-style':
  26637. tag = parsexmltag(Rn[0], false);
  26638. NF += number_formats[Rn[3]][tag.style==='long'?1:0]; break;
  26639. } break;
  26640. case 'fraction': break; // TODO 16.27.6 <number:fraction>
  26641. case 'day': // 16.27.11 <number:day>
  26642. case 'month': // 16.27.12 <number:month>
  26643. case 'year': // 16.27.13 <number:year>
  26644. case 'era': // 16.27.14 <number:era>
  26645. case 'day-of-week': // 16.27.15 <number:day-of-week>
  26646. case 'week-of-year': // 16.27.16 <number:week-of-year>
  26647. case 'quarter': // 16.27.17 <number:quarter>
  26648. case 'hours': // 16.27.19 <number:hours>
  26649. case 'minutes': // 16.27.20 <number:minutes>
  26650. case 'seconds': // 16.27.21 <number:seconds>
  26651. case 'am-pm': // 16.27.22 <number:am-pm>
  26652. switch(state[state.length-1][0]) {
  26653. case 'time-style':
  26654. case 'date-style':
  26655. tag = parsexmltag(Rn[0], false);
  26656. NF += number_formats[Rn[3]][tag.style==='long'?1:0]; break;
  26657. } break;
  26658. case 'boolean-style': break; // 16.27.23 <number:boolean-style>
  26659. case 'boolean': break; // 16.27.24 <number:boolean>
  26660. case 'text-style': break; // 16.27.25 <number:text-style>
  26661. case 'text': // 16.27.26 <number:text>
  26662. if(Rn[0].slice(-2) === "/>") break;
  26663. else if(Rn[1]==="/") switch(state[state.length-1][0]) {
  26664. case 'number-style':
  26665. case 'date-style':
  26666. case 'time-style':
  26667. NF += str.slice(pidx, Rn.index);
  26668. break;
  26669. }
  26670. else pidx = Rn.index + Rn[0].length;
  26671. break;
  26672. case 'named-range': // 9.4.12 <table:named-range>
  26673. tag = parsexmltag(Rn[0], false);
  26674. _Ref = ods_to_csf_3D(tag['cell-range-address']);
  26675. var nrange = ({Name:tag.name, Ref:_Ref[0] + '!' + _Ref[1]});
  26676. if(intable) nrange.Sheet = SheetNames.length;
  26677. WB.Names.push(nrange);
  26678. break;
  26679. case 'text-content': break; // 16.27.27 <number:text-content>
  26680. case 'text-properties': break; // 16.27.27 <style:text-properties>
  26681. case 'embedded-text': break; // 16.27.4 <number:embedded-text>
  26682. case 'body': case '电子表格': break; // 3.3 16.9.6 19.726.3
  26683. case 'forms': break; // 12.25.2 13.2
  26684. case 'table-column': break; // 9.1.6 <table:table-column>
  26685. case 'table-header-rows': break; // 9.1.7 <table:table-header-rows>
  26686. case 'table-rows': break; // 9.1.12 <table:table-rows>
  26687. /* TODO: outline levels */
  26688. case 'table-column-group': break; // 9.1.10 <table:table-column-group>
  26689. case 'table-header-columns': break; // 9.1.11 <table:table-header-columns>
  26690. case 'table-columns': break; // 9.1.12 <table:table-columns>
  26691. case 'null-date': break; // 9.4.2 <table:null-date> TODO: date1904
  26692. case 'graphic-properties': break; // 17.21 <style:graphic-properties>
  26693. case 'calculation-settings': break; // 9.4.1 <table:calculation-settings>
  26694. case 'named-expressions': break; // 9.4.11 <table:named-expressions>
  26695. case 'label-range': break; // 9.4.9 <table:label-range>
  26696. case 'label-ranges': break; // 9.4.10 <table:label-ranges>
  26697. case 'named-expression': break; // 9.4.13 <table:named-expression>
  26698. case 'sort': break; // 9.4.19 <table:sort>
  26699. case 'sort-by': break; // 9.4.20 <table:sort-by>
  26700. case 'sort-groups': break; // 9.4.22 <table:sort-groups>
  26701. case 'tab': break; // 6.1.4 <text:tab>
  26702. case 'line-break': break; // 6.1.5 <text:line-break>
  26703. case 'span': break; // 6.1.7 <text:span>
  26704. case 'p': case '文本串': // 5.1.3 <text:p>
  26705. if(['master-styles'].indexOf(state[state.length-1][0]) > -1) break;
  26706. if(Rn[1]==='/' && (!ctag || !ctag['string-value'])) {
  26707. var ptp = parse_text_p(str.slice(textpidx,Rn.index), textptag);
  26708. textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0];
  26709. } else { textptag = parsexmltag(Rn[0], false); textpidx = Rn.index + Rn[0].length; }
  26710. break; // <text:p>
  26711. case 's': break; // <text:s>
  26712. case 'database-range': // 9.4.15 <table:database-range>
  26713. if(Rn[1]==='/') break;
  26714. try {
  26715. _Ref = ods_to_csf_3D(parsexmltag(Rn[0])['target-range-address']);
  26716. Sheets[_Ref[0]]['!autofilter'] = { ref:_Ref[1] };
  26717. } catch(e) {/* empty */}
  26718. break;
  26719. case 'date': break; // <*:date>
  26720. case 'object': break; // 10.4.6.2 <draw:object>
  26721. case 'title': case '标题': break; // <*:title> OR <uof:标题>
  26722. case 'desc': break; // <*:desc>
  26723. case 'binary-data': break; // 10.4.5 TODO: b64 blob
  26724. /* 9.2 Advanced Tables */
  26725. case 'table-source': break; // 9.2.6
  26726. case 'scenario': break; // 9.2.6
  26727. case 'iteration': break; // 9.4.3 <table:iteration>
  26728. case 'content-validations': break; // 9.4.4 <table:
  26729. case 'content-validation': break; // 9.4.5 <table:
  26730. case 'help-message': break; // 9.4.6 <table:
  26731. case 'error-message': break; // 9.4.7 <table:
  26732. case 'database-ranges': break; // 9.4.14 <table:database-ranges>
  26733. case 'filter': break; // 9.5.2 <table:filter>
  26734. case 'filter-and': break; // 9.5.3 <table:filter-and>
  26735. case 'filter-or': break; // 9.5.4 <table:filter-or>
  26736. case 'filter-condition': break; // 9.5.5 <table:filter-condition>
  26737. case 'list-level-style-bullet': break; // 16.31 <text:
  26738. case 'list-level-style-number': break; // 16.32 <text:
  26739. case 'list-level-properties': break; // 17.19 <style:
  26740. /* 7.3 Document Fields */
  26741. case 'sender-firstname': // 7.3.6.2
  26742. case 'sender-lastname': // 7.3.6.3
  26743. case 'sender-initials': // 7.3.6.4
  26744. case 'sender-title': // 7.3.6.5
  26745. case 'sender-position': // 7.3.6.6
  26746. case 'sender-email': // 7.3.6.7
  26747. case 'sender-phone-private': // 7.3.6.8
  26748. case 'sender-fax': // 7.3.6.9
  26749. case 'sender-company': // 7.3.6.10
  26750. case 'sender-phone-work': // 7.3.6.11
  26751. case 'sender-street': // 7.3.6.12
  26752. case 'sender-city': // 7.3.6.13
  26753. case 'sender-postal-code': // 7.3.6.14
  26754. case 'sender-country': // 7.3.6.15
  26755. case 'sender-state-or-province': // 7.3.6.16
  26756. case 'author-name': // 7.3.7.1
  26757. case 'author-initials': // 7.3.7.2
  26758. case 'chapter': // 7.3.8
  26759. case 'file-name': // 7.3.9
  26760. case 'template-name': // 7.3.9
  26761. case 'sheet-name': // 7.3.9
  26762. break;
  26763. case 'event-listener':
  26764. break;
  26765. /* TODO: FODS Properties */
  26766. case 'initial-creator':
  26767. case 'creation-date':
  26768. case 'print-date':
  26769. case 'generator':
  26770. case 'document-statistic':
  26771. case 'user-defined':
  26772. case 'editing-duration':
  26773. case 'editing-cycles':
  26774. break;
  26775. /* TODO: FODS Config */
  26776. case 'config-item':
  26777. break;
  26778. /* TODO: style tokens */
  26779. case 'page-number': break; // TODO <text:page-number>
  26780. case 'page-count': break; // TODO <text:page-count>
  26781. case 'time': break; // TODO <text:time>
  26782. /* 9.3 Advanced Table Cells */
  26783. case 'cell-range-source': break; // 9.3.1 <table:
  26784. case 'detective': break; // 9.3.2 <table:
  26785. case 'operation': break; // 9.3.3 <table:
  26786. case 'highlighted-range': break; // 9.3.4 <table:
  26787. /* 9.6 Data Pilot Tables <table: */
  26788. case 'data-pilot-table': // 9.6.3
  26789. case 'source-cell-range': // 9.6.5
  26790. case 'source-service': // 9.6.6
  26791. case 'data-pilot-field': // 9.6.7
  26792. case 'data-pilot-level': // 9.6.8
  26793. case 'data-pilot-subtotals': // 9.6.9
  26794. case 'data-pilot-subtotal': // 9.6.10
  26795. case 'data-pilot-members': // 9.6.11
  26796. case 'data-pilot-member': // 9.6.12
  26797. case 'data-pilot-display-info': // 9.6.13
  26798. case 'data-pilot-sort-info': // 9.6.14
  26799. case 'data-pilot-layout-info': // 9.6.15
  26800. case 'data-pilot-field-reference': // 9.6.16
  26801. case 'data-pilot-groups': // 9.6.17
  26802. case 'data-pilot-group': // 9.6.18
  26803. case 'data-pilot-group-member': // 9.6.19
  26804. break;
  26805. /* 10.3 Drawing Shapes */
  26806. case 'rect': // 10.3.2
  26807. break;
  26808. /* 14.6 DDE Connections */
  26809. case 'dde-connection-decls': // 14.6.2 <text:
  26810. case 'dde-connection-decl': // 14.6.3 <text:
  26811. case 'dde-link': // 14.6.4 <table:
  26812. case 'dde-source': // 14.6.5 <office:
  26813. break;
  26814. case 'properties': break; // 13.7 <form:properties>
  26815. case 'property': break; // 13.8 <form:property>
  26816. case 'a': // 6.1.8 hyperlink
  26817. if(Rn[1]!== '/') {
  26818. atag = parsexmltag(Rn[0], false);
  26819. if(!atag.href) break;
  26820. atag.Target = atag.href; delete atag.href;
  26821. if(atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) {
  26822. _Ref = ods_to_csf_3D(atag.Target.slice(1));
  26823. atag.Target = "#" + _Ref[0] + "!" + _Ref[1];
  26824. }
  26825. }
  26826. break;
  26827. /* non-standard */
  26828. case 'table-protection': break;
  26829. case 'data-pilot-grand-total': break; // <table:
  26830. case 'office-document-common-attrs': break; // bare
  26831. default: switch(Rn[2]) {
  26832. case 'dc:': // TODO: properties
  26833. case 'calcext:': // ignore undocumented extensions
  26834. case 'loext:': // ignore undocumented extensions
  26835. case 'ooo:': // ignore undocumented extensions
  26836. case 'chartooo:': // ignore undocumented extensions
  26837. case 'draw:': // TODO: drawing
  26838. case 'style:': // TODO: styles
  26839. case 'chart:': // TODO: charts
  26840. case 'form:': // TODO: forms
  26841. case 'uof:': // TODO: uof
  26842. case '表:': // TODO: uof
  26843. case '字:': // TODO: uof
  26844. break;
  26845. default: if(opts.WTF) throw new Error(Rn);
  26846. }
  26847. }
  26848. var out = ({
  26849. Sheets: Sheets,
  26850. SheetNames: SheetNames,
  26851. Workbook: WB
  26852. });
  26853. if(opts.bookSheets) delete out.Sheets;
  26854. return out;
  26855. };
  26856. })();
  26857. function parse_ods(zip, opts) {
  26858. opts = opts || ({});
  26859. var ods = !!safegetzipfile(zip, 'objectdata');
  26860. if(ods) parse_manifest(getzipdata(zip, 'META-INF/manifest.xml'), opts);
  26861. var content = getzipstr(zip, 'content.xml');
  26862. if(!content) throw new Error("Missing content.xml in " + (ods ? "ODS" : "UOF")+ " file");
  26863. var wb = parse_content_xml(ods ? content : utf8read(content), opts);
  26864. if(safegetzipfile(zip, 'meta.xml')) wb.Props = parse_core_props(getzipdata(zip, 'meta.xml'));
  26865. return wb;
  26866. }
  26867. function parse_fods(data, opts) {
  26868. return parse_content_xml(data, opts);
  26869. }
  26870. /* OpenDocument */
  26871. var write_styles_ods = (function() {
  26872. var payload = '<office:document-styles ' + wxt_helper({
  26873. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  26874. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  26875. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  26876. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  26877. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  26878. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  26879. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  26880. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  26881. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  26882. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  26883. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  26884. 'office:version': "1.2"
  26885. }) + '></office:document-styles>';
  26886. return function wso() {
  26887. return XML_HEADER + payload;
  26888. };
  26889. })();
  26890. var write_content_ods = (function() {
  26891. /* 6.1.2 White Space Characters */
  26892. var write_text_p = function(text) {
  26893. return escapexml(text)
  26894. .replace(/ +/g, function($$){return '<text:s text:c="'+$$.length+'"/>';})
  26895. .replace(/\t/g, "<text:tab/>")
  26896. .replace(/\n/g, "<text:line-break/>")
  26897. .replace(/^ /, "<text:s/>").replace(/ $/, "<text:s/>");
  26898. };
  26899. var null_cell_xml = ' <table:table-cell />\n';
  26900. var covered_cell_xml = ' <table:covered-table-cell/>\n';
  26901. var write_ws = function(ws, wb, i) {
  26902. /* Section 9 Tables */
  26903. var o = [];
  26904. o.push(' <table:table table:name="' + escapexml(wb.SheetNames[i]) + '" table:style-name="ta1">\n');
  26905. var R=0,C=0, range = decode_range(ws['!ref']);
  26906. var marr = ws['!merges'] || [], mi = 0;
  26907. var dense = Array.isArray(ws);
  26908. for(R = 0; R < range.s.r; ++R) o.push(' <table:table-row></table:table-row>\n');
  26909. for(; R <= range.e.r; ++R) {
  26910. o.push(' <table:table-row>\n');
  26911. for(C=0; C < range.s.c; ++C) o.push(null_cell_xml);
  26912. for(; C <= range.e.c; ++C) {
  26913. var skip = false, ct = {}, textp = "";
  26914. for(mi = 0; mi != marr.length; ++mi) {
  26915. if(marr[mi].s.c > C) continue;
  26916. if(marr[mi].s.r > R) continue;
  26917. if(marr[mi].e.c < C) continue;
  26918. if(marr[mi].e.r < R) continue;
  26919. if(marr[mi].s.c != C || marr[mi].s.r != R) skip = true;
  26920. ct['table:number-columns-spanned'] = (marr[mi].e.c - marr[mi].s.c + 1);
  26921. ct['table:number-rows-spanned'] = (marr[mi].e.r - marr[mi].s.r + 1);
  26922. break;
  26923. }
  26924. if(skip) { o.push(covered_cell_xml); continue; }
  26925. var ref = encode_cell({r:R, c:C}), cell = dense ? (ws[R]||[])[C]: ws[ref];
  26926. if(cell && cell.f) {
  26927. ct['table:formula'] = escapexml(csf_to_ods_formula(cell.f));
  26928. if(cell.F) {
  26929. if(cell.F.slice(0, ref.length) == ref) {
  26930. var _Fref = decode_range(cell.F);
  26931. ct['table:number-matrix-columns-spanned'] = (_Fref.e.c - _Fref.s.c + 1);
  26932. ct['table:number-matrix-rows-spanned'] = (_Fref.e.r - _Fref.s.r + 1);
  26933. }
  26934. }
  26935. }
  26936. if(!cell) { o.push(null_cell_xml); continue; }
  26937. switch(cell.t) {
  26938. case 'b':
  26939. textp = (cell.v ? 'TRUE' : 'FALSE');
  26940. ct['office:value-type'] = "boolean";
  26941. ct['office:boolean-value'] = (cell.v ? 'true' : 'false');
  26942. break;
  26943. case 'n':
  26944. textp = (cell.w||String(cell.v||0));
  26945. ct['office:value-type'] = "float";
  26946. ct['office:value'] = (cell.v||0);
  26947. break;
  26948. case 's': case 'str':
  26949. textp = cell.v == null ? "" : cell.v;
  26950. ct['office:value-type'] = "string";
  26951. break;
  26952. case 'd':
  26953. textp = (cell.w||(parseDate(cell.v).toISOString()));
  26954. ct['office:value-type'] = "date";
  26955. ct['office:date-value'] = (parseDate(cell.v).toISOString());
  26956. ct['table:style-name'] = "ce1";
  26957. break;
  26958. //case 'e':
  26959. default: o.push(null_cell_xml); continue;
  26960. }
  26961. var text_p = write_text_p(textp);
  26962. if(cell.l && cell.l.Target) {
  26963. var _tgt = cell.l.Target; _tgt = _tgt.charAt(0) == "#" ? "#" + csf_to_ods_3D(_tgt.slice(1)) : _tgt;
  26964. text_p = writextag('text:a', text_p, {'xlink:href': _tgt});
  26965. }
  26966. o.push(' ' + writextag('table:table-cell', writextag('text:p', text_p, {}), ct) + '\n');
  26967. }
  26968. o.push(' </table:table-row>\n');
  26969. }
  26970. o.push(' </table:table>\n');
  26971. return o.join("");
  26972. };
  26973. var write_automatic_styles_ods = function(o) {
  26974. o.push(' <office:automatic-styles>\n');
  26975. o.push(' <number:date-style style:name="N37" number:automatic-order="true">\n');
  26976. o.push(' <number:month number:style="long"/>\n');
  26977. o.push(' <number:text>/</number:text>\n');
  26978. o.push(' <number:day number:style="long"/>\n');
  26979. o.push(' <number:text>/</number:text>\n');
  26980. o.push(' <number:year/>\n');
  26981. o.push(' </number:date-style>\n');
  26982. /* table */
  26983. o.push(' <style:style style:name="ta1" style:family="table">\n'); // style:master-page-name="mp1">\n');
  26984. o.push(' <style:table-properties table:display="true" style:writing-mode="lr-tb"/>\n');
  26985. o.push(' </style:style>\n');
  26986. /* table cells, text */
  26987. o.push(' <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Default" style:data-style-name="N37"/>\n');
  26988. /* page-layout */
  26989. o.push(' </office:automatic-styles>\n');
  26990. };
  26991. return function wcx(wb, opts) {
  26992. var o = [XML_HEADER];
  26993. /* 3.1.3.2 */
  26994. var attr = wxt_helper({
  26995. 'xmlns:office': "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
  26996. 'xmlns:table': "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
  26997. 'xmlns:style': "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
  26998. 'xmlns:text': "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
  26999. 'xmlns:draw': "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
  27000. 'xmlns:fo': "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
  27001. 'xmlns:xlink': "http://www.w3.org/1999/xlink",
  27002. 'xmlns:dc': "http://purl.org/dc/elements/1.1/",
  27003. 'xmlns:meta': "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
  27004. 'xmlns:number': "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
  27005. 'xmlns:presentation': "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
  27006. 'xmlns:svg': "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
  27007. 'xmlns:chart': "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
  27008. 'xmlns:dr3d': "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
  27009. 'xmlns:math': "http://www.w3.org/1998/Math/MathML",
  27010. 'xmlns:form': "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
  27011. 'xmlns:script': "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
  27012. 'xmlns:ooo': "http://openoffice.org/2004/office",
  27013. 'xmlns:ooow': "http://openoffice.org/2004/writer",
  27014. 'xmlns:oooc': "http://openoffice.org/2004/calc",
  27015. 'xmlns:dom': "http://www.w3.org/2001/xml-events",
  27016. 'xmlns:xforms': "http://www.w3.org/2002/xforms",
  27017. 'xmlns:xsd': "http://www.w3.org/2001/XMLSchema",
  27018. 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
  27019. 'xmlns:sheet': "urn:oasis:names:tc:opendocument:sh33tjs:1.0",
  27020. 'xmlns:rpt': "http://openoffice.org/2005/report",
  27021. 'xmlns:of': "urn:oasis:names:tc:opendocument:xmlns:of:1.2",
  27022. 'xmlns:xhtml': "http://www.w3.org/1999/xhtml",
  27023. 'xmlns:grddl': "http://www.w3.org/2003/g/data-view#",
  27024. 'xmlns:tableooo': "http://openoffice.org/2009/table",
  27025. 'xmlns:drawooo': "http://openoffice.org/2010/draw",
  27026. 'xmlns:calcext': "urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0",
  27027. 'xmlns:loext': "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
  27028. 'xmlns:field': "urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0",
  27029. 'xmlns:formx': "urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0",
  27030. 'xmlns:css3t': "http://www.w3.org/TR/css3-text/",
  27031. 'office:version': "1.2"
  27032. });
  27033. var fods = wxt_helper({
  27034. 'xmlns:config': "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
  27035. 'office:mimetype': "application/vnd.oasis.opendocument.spreadsheet"
  27036. });
  27037. if(opts.bookType == "fods") o.push('<office:document' + attr + fods + '>\n');
  27038. else o.push('<office:document-content' + attr + '>\n');
  27039. write_automatic_styles_ods(o);
  27040. o.push(' <office:body>\n');
  27041. o.push(' <office:spreadsheet>\n');
  27042. for(var i = 0; i != wb.SheetNames.length; ++i) o.push(write_ws(wb.Sheets[wb.SheetNames[i]], wb, i, opts));
  27043. o.push(' </office:spreadsheet>\n');
  27044. o.push(' </office:body>\n');
  27045. if(opts.bookType == "fods") o.push('</office:document>');
  27046. else o.push('</office:document-content>');
  27047. return o.join("");
  27048. };
  27049. })();
  27050. function write_ods(wb, opts) {
  27051. if(opts.bookType == "fods") return write_content_ods(wb, opts);
  27052. var zip = zip_new();
  27053. var f = "";
  27054. var manifest = [];
  27055. var rdf = [];
  27056. /* Part 3 Section 3.3 MIME Media Type */
  27057. f = "mimetype";
  27058. zip_add_file(zip, f, "application/vnd.oasis.opendocument.spreadsheet");
  27059. /* Part 1 Section 2.2 Documents */
  27060. f = "content.xml";
  27061. zip_add_file(zip, f, write_content_ods(wb, opts));
  27062. manifest.push([f, "text/xml"]);
  27063. rdf.push([f, "ContentFile"]);
  27064. /* TODO: these are hard-coded styles to satiate excel */
  27065. f = "styles.xml";
  27066. zip_add_file(zip, f, write_styles_ods(wb, opts));
  27067. manifest.push([f, "text/xml"]);
  27068. rdf.push([f, "StylesFile"]);
  27069. /* TODO: this is hard-coded to satiate excel */
  27070. f = "meta.xml";
  27071. zip_add_file(zip, f, write_meta_ods());
  27072. manifest.push([f, "text/xml"]);
  27073. rdf.push([f, "MetadataFile"]);
  27074. /* Part 3 Section 6 Metadata Manifest File */
  27075. f = "manifest.rdf";
  27076. zip_add_file(zip, f, write_rdf(rdf/*, opts*/));
  27077. manifest.push([f, "application/rdf+xml"]);
  27078. /* Part 3 Section 4 Manifest File */
  27079. f = "META-INF/manifest.xml";
  27080. zip_add_file(zip, f, write_manifest(manifest/*, opts*/));
  27081. return zip;
  27082. }
  27083. function write_sheet_index(wb, sheet) {
  27084. if(!sheet) return 0;
  27085. var idx = wb.SheetNames.indexOf(sheet);
  27086. if(idx == -1) throw new Error("Sheet not found: " + sheet);
  27087. return idx;
  27088. }
  27089. function write_obj_str(factory) {
  27090. return function write_str(wb, o) {
  27091. var idx = write_sheet_index(wb, o.sheet);
  27092. return factory.from_sheet(wb.Sheets[wb.SheetNames[idx]], o, wb);
  27093. };
  27094. }
  27095. var write_htm_str = write_obj_str(HTML_);
  27096. var write_csv_str = write_obj_str({from_sheet:sheet_to_csv});
  27097. var write_slk_str = write_obj_str(typeof SYLK !== "undefined" ? SYLK : {});
  27098. var write_dif_str = write_obj_str(typeof DIF !== "undefined" ? DIF : {});
  27099. var write_prn_str = write_obj_str(typeof PRN !== "undefined" ? PRN : {});
  27100. var write_rtf_str = write_obj_str(typeof RTF !== "undefined" ? RTF : {});
  27101. var write_txt_str = write_obj_str({from_sheet:sheet_to_txt});
  27102. var write_dbf_buf = write_obj_str(typeof DBF !== "undefined" ? DBF : {});
  27103. var write_eth_str = write_obj_str(typeof ETH !== "undefined" ? ETH : {});
  27104. function fix_opts_func(defaults) {
  27105. return function fix_opts(opts) {
  27106. for(var i = 0; i != defaults.length; ++i) {
  27107. var d = defaults[i];
  27108. if(opts[d[0]] === undefined) opts[d[0]] = d[1];
  27109. if(d[2] === 'n') opts[d[0]] = Number(opts[d[0]]);
  27110. }
  27111. };
  27112. }
  27113. var fix_read_opts = function(opts) {
  27114. fix_opts_func([
  27115. ['cellNF', false], /* emit cell number format string as .z */
  27116. ['cellHTML', true], /* emit html string as .h */
  27117. ['cellFormula', true], /* emit formulae as .f */
  27118. ['cellStyles', false], /* emits style/theme as .s */
  27119. ['cellText', true], /* emit formatted text as .w */
  27120. ['cellDates', false], /* emit date cells with type `d` */
  27121. ['sheetStubs', false], /* emit empty cells */
  27122. ['sheetRows', 0, 'n'], /* read n rows (0 = read all rows) */
  27123. ['bookDeps', false], /* parse calculation chains */
  27124. ['bookSheets', false], /* only try to get sheet names (no Sheets) */
  27125. ['bookProps', false], /* only try to get properties (no Sheets) */
  27126. ['bookFiles', false], /* include raw file structure (keys, files, cfb) */
  27127. ['bookVBA', false], /* include vba raw data (vbaraw) */
  27128. ['password',''], /* password */
  27129. ['WTF', false] /* WTF mode (throws errors) */
  27130. ])(opts);
  27131. };
  27132. var fix_write_opts = fix_opts_func([
  27133. ['cellDates', false], /* write date cells with type `d` */
  27134. ['bookSST', false], /* Generate Shared String Table */
  27135. ['bookType', 'xlsx'], /* Type of workbook (xlsx/m/b) */
  27136. ['compression', false], /* Use file compression */
  27137. ['WTF', false] /* WTF mode (throws errors) */
  27138. ]);
  27139. function get_sheet_type(n) {
  27140. if(RELS.WS.indexOf(n) > -1) return "sheet";
  27141. if(RELS.CS && n == RELS.CS) return "chart";
  27142. if(RELS.DS && n == RELS.DS) return "dialog";
  27143. if(RELS.MS && n == RELS.MS) return "macro";
  27144. return (n && n.length) ? n : "sheet";
  27145. }
  27146. function safe_parse_wbrels(wbrels, sheets) {
  27147. if(!wbrels) return 0;
  27148. try {
  27149. wbrels = sheets.map(function pwbr(w) { if(!w.id) w.id = w.strRelID; return [w.name, wbrels['!id'][w.id].Target, get_sheet_type(wbrels['!id'][w.id].Type)]; });
  27150. } catch(e) { return null; }
  27151. return !wbrels || wbrels.length === 0 ? null : wbrels;
  27152. }
  27153. function safe_parse_sheet(zip, path, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles) {
  27154. try {
  27155. sheetRels[sheet]=parse_rels(getzipstr(zip, relsPath, true), path);
  27156. var data = getzipdata(zip, path);
  27157. var _ws;
  27158. switch(stype) {
  27159. case 'sheet': _ws = parse_ws(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  27160. case 'chart': _ws = parse_cs(data, path, idx, opts, sheetRels[sheet], wb, themes, styles);
  27161. if(!_ws || !_ws['!drawel']) break;
  27162. var dfile = resolve_path(_ws['!drawel'].Target, path);
  27163. var drelsp = get_rels_path(dfile);
  27164. var draw = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile));
  27165. var chartp = resolve_path(draw, dfile);
  27166. var crelsp = get_rels_path(chartp);
  27167. _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws);
  27168. break;
  27169. case 'macro': _ws = parse_ms(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  27170. case 'dialog': _ws = parse_ds(data, path, idx, opts, sheetRels[sheet], wb, themes, styles); break;
  27171. default: throw new Error("Unrecognized sheet type " + stype);
  27172. }
  27173. sheets[sheet] = _ws;
  27174. /* scan rels for comments */
  27175. var comments = [];
  27176. if(sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n) {
  27177. if(sheetRels[sheet][n].Type == RELS.CMNT) {
  27178. var dfile = resolve_path(sheetRels[sheet][n].Target, path);
  27179. comments = parse_cmnt(getzipdata(zip, dfile, true), dfile, opts);
  27180. if(!comments || !comments.length) return;
  27181. sheet_insert_comments(_ws, comments);
  27182. }
  27183. });
  27184. } catch(e) { if(opts.WTF) throw e; }
  27185. }
  27186. function strip_front_slash(x) { return x.charAt(0) == '/' ? x.slice(1) : x; }
  27187. function parse_zip(zip, opts) {
  27188. make_ssf(SSF);
  27189. opts = opts || {};
  27190. fix_read_opts(opts);
  27191. /* OpenDocument Part 3 Section 2.2.1 OpenDocument Package */
  27192. if(safegetzipfile(zip, 'META-INF/manifest.xml')) return parse_ods(zip, opts);
  27193. /* UOC */
  27194. if(safegetzipfile(zip, 'objectdata.xml')) return parse_ods(zip, opts);
  27195. /* Numbers */
  27196. if(safegetzipfile(zip, 'Index/Document.iwa')) throw new Error('Unsupported NUMBERS file');
  27197. var entries = zipentries(zip);
  27198. var dir = parse_ct((getzipstr(zip, '[Content_Types].xml')));
  27199. var xlsb = false;
  27200. var sheets, binname;
  27201. if(dir.workbooks.length === 0) {
  27202. binname = "xl/workbook.xml";
  27203. if(getzipdata(zip,binname, true)) dir.workbooks.push(binname);
  27204. }
  27205. if(dir.workbooks.length === 0) {
  27206. binname = "xl/workbook.bin";
  27207. if(!getzipdata(zip,binname,true)) throw new Error("Could not find workbook");
  27208. dir.workbooks.push(binname);
  27209. xlsb = true;
  27210. }
  27211. if(dir.workbooks[0].slice(-3) == "bin") xlsb = true;
  27212. var themes = ({});
  27213. var styles = ({});
  27214. if(!opts.bookSheets && !opts.bookProps) {
  27215. strs = [];
  27216. if(dir.sst) try { strs=parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); } catch(e) { if(opts.WTF) throw e; }
  27217. if(opts.cellStyles && dir.themes.length) themes = parse_theme(getzipstr(zip, dir.themes[0].replace(/^\//,''), true)||"",dir.themes[0], opts);
  27218. if(dir.style) styles = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts);
  27219. }
  27220. /*var externbooks = */dir.links.map(function(link) {
  27221. try {
  27222. var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link);
  27223. return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts);
  27224. } catch(e) {}
  27225. });
  27226. var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts);
  27227. var props = {}, propdata = "";
  27228. if(dir.coreprops.length) {
  27229. propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true);
  27230. if(propdata) props = parse_core_props(propdata);
  27231. if(dir.extprops.length !== 0) {
  27232. propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true);
  27233. if(propdata) parse_ext_props(propdata, props, opts);
  27234. }
  27235. }
  27236. var custprops = {};
  27237. if(!opts.bookSheets || opts.bookProps) {
  27238. if (dir.custprops.length !== 0) {
  27239. propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true);
  27240. if(propdata) custprops = parse_cust_props(propdata, opts);
  27241. }
  27242. }
  27243. var out = ({});
  27244. if(opts.bookSheets || opts.bookProps) {
  27245. if(wb.Sheets) sheets = wb.Sheets.map(function pluck(x){ return x.name; });
  27246. else if(props.Worksheets && props.SheetNames.length > 0) sheets=props.SheetNames;
  27247. if(opts.bookProps) { out.Props = props; out.Custprops = custprops; }
  27248. if(opts.bookSheets && typeof sheets !== 'undefined') out.SheetNames = sheets;
  27249. if(opts.bookSheets ? out.SheetNames : opts.bookProps) return out;
  27250. }
  27251. sheets = {};
  27252. var deps = {};
  27253. if(opts.bookDeps && dir.calcchain) deps=parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)),dir.calcchain,opts);
  27254. var i=0;
  27255. var sheetRels = ({});
  27256. var path, relsPath;
  27257. {
  27258. var wbsheets = wb.Sheets;
  27259. props.Worksheets = wbsheets.length;
  27260. props.SheetNames = [];
  27261. for(var j = 0; j != wbsheets.length; ++j) {
  27262. props.SheetNames[j] = wbsheets[j].name;
  27263. }
  27264. }
  27265. var wbext = xlsb ? "bin" : "xml";
  27266. var wbrelsi = dir.workbooks[0].lastIndexOf("/");
  27267. var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi+1) + "_rels/" + dir.workbooks[0].slice(wbrelsi+1) + ".rels").replace(/^\//,"");
  27268. if(!safegetzipfile(zip, wbrelsfile)) wbrelsfile = 'xl/_rels/workbook.' + wbext + '.rels';
  27269. var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile);
  27270. if(wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets);
  27271. /* Numbers iOS hack */
  27272. var nmode = (getzipdata(zip,"xl/worksheets/sheet.xml",true))?1:0;
  27273. wsloop: for(i = 0; i != props.Worksheets; ++i) {
  27274. var stype = "sheet";
  27275. if(wbrels && wbrels[i]) {
  27276. path = 'xl/' + (wbrels[i][1]).replace(/[\/]?xl\//, "");
  27277. if(!safegetzipfile(zip, path)) path = wbrels[i][1];
  27278. if(!safegetzipfile(zip, path)) path = wbrelsfile.replace(/_rels\/.*$/,"") + wbrels[i][1];
  27279. stype = wbrels[i][2];
  27280. } else {
  27281. path = 'xl/worksheets/sheet'+(i+1-nmode)+"." + wbext;
  27282. path = path.replace(/sheet0\./,"sheet.");
  27283. }
  27284. relsPath = path.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels");
  27285. if(opts && opts.sheets != null) switch(typeof opts.sheets) {
  27286. case "number": if(i != opts.sheets) continue wsloop; break;
  27287. case "string": if(props.SheetNames[i].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; break;
  27288. default: if(Array.isArray && Array.isArray(opts.sheets)) {
  27289. var snjseen = false;
  27290. for(var snj = 0; snj != opts.sheets.length; ++snj) {
  27291. if(typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i) snjseen=1;
  27292. if(typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i].toLowerCase()) snjseen = 1;
  27293. }
  27294. if(!snjseen) continue wsloop;
  27295. }
  27296. }
  27297. safe_parse_sheet(zip, path, relsPath, props.SheetNames[i], i, sheetRels, sheets, stype, opts, wb, themes, styles);
  27298. }
  27299. out = ({
  27300. Directory: dir,
  27301. Workbook: wb,
  27302. Props: props,
  27303. Custprops: custprops,
  27304. Deps: deps,
  27305. Sheets: sheets,
  27306. SheetNames: props.SheetNames,
  27307. Strings: strs,
  27308. Styles: styles,
  27309. Themes: themes,
  27310. SSF: SSF.get_table()
  27311. });
  27312. if(opts && opts.bookFiles) {
  27313. out.keys = entries;
  27314. out.files = zip.files;
  27315. }
  27316. if(opts && opts.bookVBA) {
  27317. if(dir.vba.length > 0) out.vbaraw = getzipdata(zip,strip_front_slash(dir.vba[0]),true);
  27318. else if(dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, 'xl/vbaProject.bin',true);
  27319. }
  27320. return out;
  27321. }
  27322. /* [MS-OFFCRYPTO] 2.1.1 */
  27323. function parse_xlsxcfb(cfb, _opts) {
  27324. var opts = _opts || {};
  27325. var f = 'Workbook', data = CFB.find(cfb, f);
  27326. try {
  27327. f = '/!DataSpaces/Version';
  27328. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27329. /*var version = */parse_DataSpaceVersionInfo(data.content);
  27330. /* 2.3.4.1 */
  27331. f = '/!DataSpaces/DataSpaceMap';
  27332. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27333. var dsm = parse_DataSpaceMap(data.content);
  27334. if(dsm.length !== 1 || dsm[0].comps.length !== 1 || dsm[0].comps[0].t !== 0 || dsm[0].name !== "StrongEncryptionDataSpace" || dsm[0].comps[0].v !== "EncryptedPackage")
  27335. throw new Error("ECMA-376 Encrypted file bad " + f);
  27336. /* 2.3.4.2 */
  27337. f = '/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace';
  27338. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27339. var seds = parse_DataSpaceDefinition(data.content);
  27340. if(seds.length != 1 || seds[0] != "StrongEncryptionTransform")
  27341. throw new Error("ECMA-376 Encrypted file bad " + f);
  27342. /* 2.3.4.3 */
  27343. f = '/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary';
  27344. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27345. /*var hdr = */parse_Primary(data.content);
  27346. } catch(e) {}
  27347. f = '/EncryptionInfo';
  27348. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27349. var einfo = parse_EncryptionInfo(data.content);
  27350. /* 2.3.4.4 */
  27351. f = '/EncryptedPackage';
  27352. data = CFB.find(cfb, f); if(!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f);
  27353. /*global decrypt_agile */
  27354. if(einfo[0] == 0x04 && typeof decrypt_agile !== 'undefined') return decrypt_agile(einfo[1], data.content, opts.password || "", opts);
  27355. /*global decrypt_std76 */
  27356. if(einfo[0] == 0x02 && typeof decrypt_std76 !== 'undefined') return decrypt_std76(einfo[1], data.content, opts.password || "", opts);
  27357. throw new Error("File is password-protected");
  27358. }
  27359. function write_zip(wb, opts) {
  27360. _shapeid = 1024;
  27361. if(opts.bookType == "ods") return write_ods(wb, opts);
  27362. if(wb && !wb.SSF) {
  27363. wb.SSF = SSF.get_table();
  27364. }
  27365. if(wb && wb.SSF) {
  27366. make_ssf(SSF); SSF.load_table(wb.SSF);
  27367. // $FlowIgnore
  27368. opts.revssf = evert_num(wb.SSF); opts.revssf[wb.SSF[65535]] = 0;
  27369. opts.ssf = wb.SSF;
  27370. }
  27371. opts.rels = {}; opts.wbrels = {};
  27372. opts.Strings = []; opts.Strings.Count = 0; opts.Strings.Unique = 0;
  27373. if(browser_has_Map) opts.revStrings = new Map();
  27374. else { opts.revStrings = {}; opts.revStrings.foo = []; delete opts.revStrings.foo; }
  27375. var wbext = opts.bookType == "xlsb" ? "bin" : "xml";
  27376. var vbafmt = VBAFMTS.indexOf(opts.bookType) > -1;
  27377. var ct = new_ct();
  27378. fix_write_opts(opts = opts || {});
  27379. var zip = zip_new();
  27380. var f = "", rId = 0;
  27381. opts.cellXfs = [];
  27382. get_cell_style(opts.cellXfs, {}, {revssf:{"General":0}});
  27383. if(!wb.Props) wb.Props = {};
  27384. f = "docProps/core.xml";
  27385. zip_add_file(zip, f, write_core_props(wb.Props, opts));
  27386. ct.coreprops.push(f);
  27387. add_rels(opts.rels, 2, f, RELS.CORE_PROPS);
  27388. f = "docProps/app.xml";
  27389. if(wb.Props && wb.Props.SheetNames){/* empty */}
  27390. else if(!wb.Workbook || !wb.Workbook.Sheets) wb.Props.SheetNames = wb.SheetNames;
  27391. else {
  27392. var _sn = [];
  27393. for(var _i = 0; _i < wb.SheetNames.length; ++_i)
  27394. if((wb.Workbook.Sheets[_i]||{}).Hidden != 2) _sn.push(wb.SheetNames[_i]);
  27395. wb.Props.SheetNames = _sn;
  27396. }
  27397. wb.Props.Worksheets = wb.Props.SheetNames.length;
  27398. zip_add_file(zip, f, write_ext_props(wb.Props, opts));
  27399. ct.extprops.push(f);
  27400. add_rels(opts.rels, 3, f, RELS.EXT_PROPS);
  27401. if(wb.Custprops !== wb.Props && keys(wb.Custprops||{}).length > 0) {
  27402. f = "docProps/custom.xml";
  27403. zip_add_file(zip, f, write_cust_props(wb.Custprops, opts));
  27404. ct.custprops.push(f);
  27405. add_rels(opts.rels, 4, f, RELS.CUST_PROPS);
  27406. }
  27407. for(rId=1;rId <= wb.SheetNames.length; ++rId) {
  27408. var wsrels = {'!id':{}};
  27409. var ws = wb.Sheets[wb.SheetNames[rId-1]];
  27410. var _type = (ws || {})["!type"] || "sheet";
  27411. switch(_type) {
  27412. case "chart":
  27413. /* falls through */
  27414. default:
  27415. f = "xl/worksheets/sheet" + rId + "." + wbext;
  27416. zip_add_file(zip, f, write_ws(rId-1, f, opts, wb, wsrels));
  27417. ct.sheets.push(f);
  27418. add_rels(opts.wbrels, -1, "worksheets/sheet" + rId + "." + wbext, RELS.WS[0]);
  27419. }
  27420. if(ws) {
  27421. var comments = ws['!comments'];
  27422. var need_vml = false;
  27423. if(comments && comments.length > 0) {
  27424. var cf = "xl/comments" + rId + "." + wbext;
  27425. zip_add_file(zip, cf, write_cmnt(comments, cf, opts));
  27426. ct.comments.push(cf);
  27427. add_rels(wsrels, -1, "../comments" + rId + "." + wbext, RELS.CMNT);
  27428. need_vml = true;
  27429. }
  27430. if(ws['!legacy']) {
  27431. if(need_vml) zip_add_file(zip, "xl/drawings/vmlDrawing" + (rId) + ".vml", write_comments_vml(rId, ws['!comments']));
  27432. }
  27433. delete ws['!comments'];
  27434. delete ws['!legacy'];
  27435. }
  27436. if(wsrels['!id'].rId1) zip_add_file(zip, get_rels_path(f), write_rels(wsrels));
  27437. }
  27438. if(opts.Strings != null && opts.Strings.length > 0) {
  27439. f = "xl/sharedStrings." + wbext;
  27440. zip_add_file(zip, f, write_sst(opts.Strings, f, opts));
  27441. ct.strs.push(f);
  27442. add_rels(opts.wbrels, -1, "sharedStrings." + wbext, RELS.SST);
  27443. }
  27444. f = "xl/workbook." + wbext;
  27445. zip_add_file(zip, f, write_wb(wb, f, opts));
  27446. ct.workbooks.push(f);
  27447. add_rels(opts.rels, 1, f, RELS.WB);
  27448. /* TODO: something more intelligent with themes */
  27449. f = "xl/theme/theme1.xml";
  27450. zip_add_file(zip, f, write_theme(wb.Themes, opts));
  27451. ct.themes.push(f);
  27452. add_rels(opts.wbrels, -1, "theme/theme1.xml", RELS.THEME);
  27453. /* TODO: something more intelligent with styles */
  27454. f = "xl/styles." + wbext;
  27455. zip_add_file(zip, f, write_sty(wb, f, opts));
  27456. ct.styles.push(f);
  27457. add_rels(opts.wbrels, -1, "styles." + wbext, RELS.STY);
  27458. if(wb.vbaraw && vbafmt) {
  27459. f = "xl/vbaProject.bin";
  27460. zip_add_file(zip, f, wb.vbaraw);
  27461. ct.vba.push(f);
  27462. add_rels(opts.wbrels, -1, "vbaProject.bin", RELS.VBA);
  27463. }
  27464. zip_add_file(zip, "[Content_Types].xml", write_ct(ct, opts));
  27465. zip_add_file(zip, '_rels/.rels', write_rels(opts.rels));
  27466. zip_add_file(zip, 'xl/_rels/workbook.' + wbext + '.rels', write_rels(opts.wbrels));
  27467. delete opts.revssf; delete opts.ssf;
  27468. return zip;
  27469. }
  27470. function firstbyte(f,o) {
  27471. var x = "";
  27472. switch((o||{}).type || "base64") {
  27473. case 'buffer': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  27474. case 'base64': x = Base64.decode(f.slice(0,12)); break;
  27475. case 'binary': x = f; break;
  27476. case 'array': return [f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]];
  27477. default: throw new Error("Unrecognized type " + (o && o.type || "undefined"));
  27478. }
  27479. return [x.charCodeAt(0), x.charCodeAt(1), x.charCodeAt(2), x.charCodeAt(3), x.charCodeAt(4), x.charCodeAt(5), x.charCodeAt(6), x.charCodeAt(7)];
  27480. }
  27481. function read_cfb(cfb, opts) {
  27482. if(CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts);
  27483. return parse_xlscfb(cfb, opts);
  27484. }
  27485. function read_zip(data, opts) {
  27486. var zip, d = data;
  27487. var o = opts||{};
  27488. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  27489. zip = zip_read(d, o);
  27490. return parse_zip(zip, o);
  27491. }
  27492. function read_plaintext(data, o) {
  27493. var i = 0;
  27494. main: while(i < data.length) switch(data.charCodeAt(i)) {
  27495. case 0x0A: case 0x0D: case 0x20: ++i; break;
  27496. case 0x3C: return parse_xlml(data.slice(i),o);
  27497. default: break main;
  27498. }
  27499. return PRN.to_workbook(data, o);
  27500. }
  27501. function read_plaintext_raw(data, o) {
  27502. var str = "", bytes = firstbyte(data, o);
  27503. switch(o.type) {
  27504. case 'base64': str = Base64.decode(data); break;
  27505. case 'binary': str = data; break;
  27506. case 'buffer': str = data.toString('binary'); break;
  27507. case 'array': str = cc2str(data); break;
  27508. default: throw new Error("Unrecognized type " + o.type);
  27509. }
  27510. if(bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) str = utf8read(str);
  27511. return read_plaintext(str, o);
  27512. }
  27513. function read_utf16(data, o) {
  27514. var d = data;
  27515. if(o.type == 'base64') d = Base64.decode(d);
  27516. d = cptable.utils.decode(1200, d.slice(2), 'str');
  27517. o.type = "binary";
  27518. return read_plaintext(d, o);
  27519. }
  27520. function bstrify(data) {
  27521. return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data);
  27522. }
  27523. function read_prn(data, d, o, str) {
  27524. if(str) { o.type = "string"; return PRN.to_workbook(data, o); }
  27525. return PRN.to_workbook(d, o);
  27526. }
  27527. function readSync(data, opts) {
  27528. reset_cp();
  27529. if(typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), opts);
  27530. var d = data, n = [0,0,0,0], str = false;
  27531. var o = opts||{};
  27532. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  27533. _ssfopts = {};
  27534. if(o.dateNF) _ssfopts.dateNF = o.dateNF;
  27535. if(!o.type) o.type = (has_buf && Buffer.isBuffer(data)) ? "buffer" : "base64";
  27536. if(o.type == "file") { o.type = has_buf ? "buffer" : "binary"; d = read_binary(data); }
  27537. if(o.type == "string") { str = true; o.type = "binary"; o.codepage = 65001; d = bstrify(data); }
  27538. if(o.type == 'array' && typeof Uint8Array !== 'undefined' && data instanceof Uint8Array && typeof ArrayBuffer !== 'undefined') {
  27539. // $FlowIgnore
  27540. var ab=new ArrayBuffer(3), vu=new Uint8Array(ab); vu.foo="bar";
  27541. // $FlowIgnore
  27542. if(!vu.foo) {o=dup(o); o.type='array'; return readSync(ab2a(d), o);}
  27543. }
  27544. switch((n = firstbyte(d, o))[0]) {
  27545. case 0xD0: if(n[1] === 0xCF && n[2] === 0x11 && n[3] === 0xE0 && n[4] === 0xA1 && n[5] === 0xB1 && n[6] === 0x1A && n[7] === 0xE1) return read_cfb(CFB.read(d, o), o); break;
  27546. case 0x09: if(n[1] <= 0x04) return parse_xlscfb(d, o); break;
  27547. case 0x3C: return parse_xlml(d, o);
  27548. case 0x49: if(n[1] === 0x44) return read_wb_ID(d, o); break;
  27549. case 0x54: if(n[1] === 0x41 && n[2] === 0x42 && n[3] === 0x4C) return DIF.to_workbook(d, o); break;
  27550. case 0x50: return (n[1] === 0x4B && n[2] < 0x09 && n[3] < 0x09) ? read_zip(d, o) : read_prn(data, d, o, str);
  27551. case 0xEF: return n[3] === 0x3C ? parse_xlml(d, o) : read_prn(data, d, o, str);
  27552. case 0xFF: if(n[1] === 0xFE) { return read_utf16(d, o); } break;
  27553. case 0x00: if(n[1] === 0x00 && n[2] >= 0x02 && n[3] === 0x00) return WK_.to_workbook(d, o); break;
  27554. case 0x03: case 0x83: case 0x8B: case 0x8C: return DBF.to_workbook(d, o);
  27555. case 0x7B: if(n[1] === 0x5C && n[2] === 0x72 && n[3] === 0x74) return RTF.to_workbook(d, o); break;
  27556. case 0x0A: case 0x0D: case 0x20: return read_plaintext_raw(d, o);
  27557. }
  27558. if(DBF.versions.indexOf(n[0]) > -1 && n[2] <= 12 && n[3] <= 31) return DBF.to_workbook(d, o);
  27559. return read_prn(data, d, o, str);
  27560. }
  27561. function readFileSync(filename, opts) {
  27562. var o = opts||{}; o.type = 'file';
  27563. return readSync(filename, o);
  27564. }
  27565. function write_cfb_ctr(cfb, o) {
  27566. switch(o.type) {
  27567. case "base64": case "binary": break;
  27568. case "buffer": case "array": o.type = ""; break;
  27569. case "file": return write_dl(o.file, CFB.write(cfb, {type:has_buf ? 'buffer' : ""}));
  27570. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  27571. default: throw new Error("Unrecognized type " + o.type);
  27572. }
  27573. return CFB.write(cfb, o);
  27574. }
  27575. function write_zip_type(wb, opts) {
  27576. var o = opts||{};
  27577. var z = write_zip(wb, o);
  27578. var oopts = {};
  27579. if(o.compression) oopts.compression = 'DEFLATE';
  27580. if(o.password) oopts.type = has_buf ? "nodebuffer" : "string";
  27581. else switch(o.type) {
  27582. case "base64": oopts.type = "base64"; break;
  27583. case "binary": oopts.type = "string"; break;
  27584. case "string": throw new Error("'string' output type invalid for '" + o.bookType + "' files");
  27585. case "buffer":
  27586. case "file": oopts.type = has_buf ? "nodebuffer" : "string"; break;
  27587. default: throw new Error("Unrecognized type " + o.type);
  27588. }
  27589. var out = z.FullPaths ? CFB.write(z, {fileType:"zip", type: {"nodebuffer": "buffer", "string": "binary"}[oopts.type] || oopts.type}) : z.generate(oopts);
  27590. /*jshint -W083 */
  27591. if(o.password && typeof encrypt_agile !== 'undefined') return write_cfb_ctr(encrypt_agile(out, o.password), o); // eslint-disable-line no-undef
  27592. /*jshint +W083 */
  27593. if(o.type === "file") return write_dl(o.file, out);
  27594. return o.type == "string" ? utf8read(out) : out;
  27595. }
  27596. function write_cfb_type(wb, opts) {
  27597. var o = opts||{};
  27598. var cfb = write_xlscfb(wb, o);
  27599. return write_cfb_ctr(cfb, o);
  27600. }
  27601. function write_string_type(out, opts, bom) {
  27602. if(!bom) bom = "";
  27603. var o = bom + out;
  27604. switch(opts.type) {
  27605. case "base64": return Base64.encode(utf8write(o));
  27606. case "binary": return utf8write(o);
  27607. case "string": return out;
  27608. case "file": return write_dl(opts.file, o, 'utf8');
  27609. case "buffer": {
  27610. if(has_buf) return Buffer_from(o, 'utf8');
  27611. else return write_string_type(o, {type:'binary'}).split("").map(function(c) { return c.charCodeAt(0); });
  27612. }
  27613. }
  27614. throw new Error("Unrecognized type " + opts.type);
  27615. }
  27616. function write_stxt_type(out, opts) {
  27617. switch(opts.type) {
  27618. case "base64": return Base64.encode(out);
  27619. case "binary": return out;
  27620. case "string": return out; /* override in sheet_to_txt */
  27621. case "file": return write_dl(opts.file, out, 'binary');
  27622. case "buffer": {
  27623. if(has_buf) return Buffer_from(out, 'binary');
  27624. else return out.split("").map(function(c) { return c.charCodeAt(0); });
  27625. }
  27626. }
  27627. throw new Error("Unrecognized type " + opts.type);
  27628. }
  27629. /* TODO: test consistency */
  27630. function write_binary_type(out, opts) {
  27631. switch(opts.type) {
  27632. case "string":
  27633. case "base64":
  27634. case "binary":
  27635. var bstr = "";
  27636. // $FlowIgnore
  27637. for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
  27638. return opts.type == 'base64' ? Base64.encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
  27639. case "file": return write_dl(opts.file, out);
  27640. case "buffer": return out;
  27641. default: throw new Error("Unrecognized type " + opts.type);
  27642. }
  27643. }
  27644. function writeSync(wb, opts) {
  27645. reset_cp();
  27646. check_wb(wb);
  27647. var o = opts||{};
  27648. if(o.cellStyles) { o.cellNF = true; o.sheetStubs = true; }
  27649. if(o.type == "array") { o.type = "binary"; var out = (writeSync(wb, o)); o.type = "array"; return s2ab(out); }
  27650. switch(o.bookType || 'xlsb') {
  27651. case 'xml':
  27652. case 'xlml': return write_string_type(write_xlml(wb, o), o);
  27653. case 'slk':
  27654. case 'sylk': return write_string_type(write_slk_str(wb, o), o);
  27655. case 'htm':
  27656. case 'html': return write_string_type(write_htm_str(wb, o), o);
  27657. case 'txt': return write_stxt_type(write_txt_str(wb, o), o);
  27658. case 'csv': return write_string_type(write_csv_str(wb, o), o, "\ufeff");
  27659. case 'dif': return write_string_type(write_dif_str(wb, o), o);
  27660. case 'dbf': return write_binary_type(write_dbf_buf(wb, o), o);
  27661. case 'prn': return write_string_type(write_prn_str(wb, o), o);
  27662. case 'rtf': return write_string_type(write_rtf_str(wb, o), o);
  27663. case 'eth': return write_string_type(write_eth_str(wb, o), o);
  27664. case 'fods': return write_string_type(write_ods(wb, o), o);
  27665. case 'biff2': if(!o.biff) o.biff = 2; /* falls through */
  27666. case 'biff3': if(!o.biff) o.biff = 3; /* falls through */
  27667. case 'biff4': if(!o.biff) o.biff = 4; return write_binary_type(write_biff_buf(wb, o), o);
  27668. case 'biff5': if(!o.biff) o.biff = 5; /* falls through */
  27669. case 'biff8':
  27670. case 'xla':
  27671. case 'xls': if(!o.biff) o.biff = 8; return write_cfb_type(wb, o);
  27672. case 'xlsx':
  27673. case 'xlsm':
  27674. case 'xlam':
  27675. case 'xlsb':
  27676. case 'ods': return write_zip_type(wb, o);
  27677. default: throw new Error ("Unrecognized bookType |" + o.bookType + "|");
  27678. }
  27679. }
  27680. function resolve_book_type(o) {
  27681. if(o.bookType) return;
  27682. var _BT = {
  27683. "xls": "biff8",
  27684. "htm": "html",
  27685. "slk": "sylk",
  27686. "socialcalc": "eth",
  27687. "Sh33tJS": "WTF"
  27688. };
  27689. var ext = o.file.slice(o.file.lastIndexOf(".")).toLowerCase();
  27690. if(ext.match(/^\.[a-z]+$/)) o.bookType = ext.slice(1);
  27691. o.bookType = _BT[o.bookType] || o.bookType;
  27692. }
  27693. function writeFileSync(wb, filename, opts) {
  27694. var o = opts||{}; o.type = 'file';
  27695. o.file = filename;
  27696. resolve_book_type(o);
  27697. return writeSync(wb, o);
  27698. }
  27699. function writeFileAsync(filename, wb, opts, cb) {
  27700. var o = opts||{}; o.type = 'file';
  27701. o.file = filename;
  27702. resolve_book_type(o);
  27703. o.type = 'buffer';
  27704. var _cb = cb; if(!(_cb instanceof Function)) _cb = (opts);
  27705. return _fs.writeFile(filename, writeSync(wb, o), _cb);
  27706. }
  27707. function make_json_row(sheet, r, R, cols, header, hdr, dense, o) {
  27708. var rr = encode_row(R);
  27709. var defval = o.defval, raw = o.raw || !Object.prototype.hasOwnProperty.call(o, "raw");
  27710. var isempty = true;
  27711. var row = (header === 1) ? [] : {};
  27712. if(header !== 1) {
  27713. if(Object.defineProperty) try { Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false}); } catch(e) { row.__rowNum__ = R; }
  27714. else row.__rowNum__ = R;
  27715. }
  27716. if(!dense || sheet[R]) for (var C = r.s.c; C <= r.e.c; ++C) {
  27717. var val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  27718. if(val === undefined || val.t === undefined) {
  27719. if(defval === undefined) continue;
  27720. if(hdr[C] != null) { row[hdr[C]] = defval; }
  27721. continue;
  27722. }
  27723. var v = val.v;
  27724. switch(val.t){
  27725. case 'z': if(v == null) break; continue;
  27726. case 'e': v = void 0; break;
  27727. case 's': case 'd': case 'b': case 'n': break;
  27728. default: throw new Error('unrecognized type ' + val.t);
  27729. }
  27730. if(hdr[C] != null) {
  27731. if(v == null) {
  27732. if(defval !== undefined) row[hdr[C]] = defval;
  27733. else if(raw && v === null) row[hdr[C]] = null;
  27734. else continue;
  27735. } else {
  27736. row[hdr[C]] = raw || (o.rawNumbers && val.t == "n") ? v : format_cell(val,v,o);
  27737. }
  27738. if(v != null) isempty = false;
  27739. }
  27740. }
  27741. return { row: row, isempty: isempty };
  27742. }
  27743. function sheet_to_json(sheet, opts) {
  27744. if(sheet == null || sheet["!ref"] == null) return [];
  27745. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  27746. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  27747. var o = opts || {};
  27748. var range = o.range != null ? o.range : sheet["!ref"];
  27749. if(o.header === 1) header = 1;
  27750. else if(o.header === "A") header = 2;
  27751. else if(Array.isArray(o.header)) header = 3;
  27752. else if(o.header == null) header = 0;
  27753. switch(typeof range) {
  27754. case 'string': r = safe_decode_range(range); break;
  27755. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  27756. default: r = range;
  27757. }
  27758. if(header > 0) offset = 0;
  27759. var rr = encode_row(r.s.r);
  27760. var cols = [];
  27761. var out = [];
  27762. var outi = 0, counter = 0;
  27763. var dense = Array.isArray(sheet);
  27764. var R = r.s.r, C = 0, CC = 0;
  27765. if(dense && !sheet[R]) sheet[R] = [];
  27766. for(C = r.s.c; C <= r.e.c; ++C) {
  27767. cols[C] = encode_col(C);
  27768. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  27769. switch(header) {
  27770. case 1: hdr[C] = C - r.s.c; break;
  27771. case 2: hdr[C] = cols[C]; break;
  27772. case 3: hdr[C] = o.header[C - r.s.c]; break;
  27773. default:
  27774. if(val == null) val = {w: "__EMPTY", t: "s"};
  27775. vv = v = format_cell(val, null, o);
  27776. counter = 0;
  27777. for(CC = 0; CC < hdr.length; ++CC) if(hdr[CC] == vv) vv = v + "_" + (++counter);
  27778. hdr[C] = vv;
  27779. }
  27780. }
  27781. for (R = r.s.r + offset; R <= r.e.r; ++R) {
  27782. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  27783. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) out[outi++] = row.row;
  27784. }
  27785. out.length = outi;
  27786. return out;
  27787. }
  27788. var qreg = /"/g;
  27789. function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
  27790. var isempty = true;
  27791. var row = [], txt = "", rr = encode_row(R);
  27792. for(var C = r.s.c; C <= r.e.c; ++C) {
  27793. if (!cols[C]) continue;
  27794. var val = o.dense ? (sheet[R]||[])[C]: sheet[cols[C] + rr];
  27795. if(val == null) txt = "";
  27796. else if(val.v != null) {
  27797. isempty = false;
  27798. txt = ''+(o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
  27799. for(var i = 0, cc = 0; i !== txt.length; ++i) if((cc = txt.charCodeAt(i)) === fs || cc === rs || cc === 34 || o.forceQuotes) {txt = "\"" + txt.replace(qreg, '""') + "\""; break; }
  27800. if(txt == "ID") txt = '"ID"';
  27801. } else if(val.f != null && !val.F) {
  27802. isempty = false;
  27803. txt = '=' + val.f; if(txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"';
  27804. } else txt = "";
  27805. /* NOTE: Excel CSV does not support array formulae */
  27806. row.push(txt);
  27807. }
  27808. if(o.blankrows === false && isempty) return null;
  27809. return row.join(FS);
  27810. }
  27811. function sheet_to_csv(sheet, opts) {
  27812. var out = [];
  27813. var o = opts == null ? {} : opts;
  27814. if(sheet == null || sheet["!ref"] == null) return "";
  27815. var r = safe_decode_range(sheet["!ref"]);
  27816. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  27817. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  27818. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  27819. var row = "", cols = [];
  27820. o.dense = Array.isArray(sheet);
  27821. var colinfo = o.skipHidden && sheet["!cols"] || [];
  27822. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  27823. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  27824. for(var R = r.s.r; R <= r.e.r; ++R) {
  27825. if ((rowinfo[R]||{}).hidden) continue;
  27826. row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
  27827. if(row == null) { continue; }
  27828. if(o.strip) row = row.replace(endregex,"");
  27829. out.push(row + RS);
  27830. }
  27831. delete o.dense;
  27832. return out.join("");
  27833. }
  27834. function sheet_to_txt(sheet, opts) {
  27835. if(!opts) opts = {}; opts.FS = "\t"; opts.RS = "\n";
  27836. var s = sheet_to_csv(sheet, opts);
  27837. if(typeof cptable == 'undefined' || opts.type == 'string') return s;
  27838. var o = cptable.utils.encode(1200, s, 'str');
  27839. return String.fromCharCode(255) + String.fromCharCode(254) + o;
  27840. }
  27841. function sheet_to_formulae(sheet) {
  27842. var y = "", x, val="";
  27843. if(sheet == null || sheet["!ref"] == null) return [];
  27844. var r = safe_decode_range(sheet['!ref']), rr = "", cols = [], C;
  27845. var cmds = [];
  27846. var dense = Array.isArray(sheet);
  27847. for(C = r.s.c; C <= r.e.c; ++C) cols[C] = encode_col(C);
  27848. for(var R = r.s.r; R <= r.e.r; ++R) {
  27849. rr = encode_row(R);
  27850. for(C = r.s.c; C <= r.e.c; ++C) {
  27851. y = cols[C] + rr;
  27852. x = dense ? (sheet[R]||[])[C] : sheet[y];
  27853. val = "";
  27854. if(x === undefined) continue;
  27855. else if(x.F != null) {
  27856. y = x.F;
  27857. if(!x.f) continue;
  27858. val = x.f;
  27859. if(y.indexOf(":") == -1) y = y + ":" + y;
  27860. }
  27861. if(x.f != null) val = x.f;
  27862. else if(x.t == 'z') continue;
  27863. else if(x.t == 'n' && x.v != null) val = "" + x.v;
  27864. else if(x.t == 'b') val = x.v ? "TRUE" : "FALSE";
  27865. else if(x.w !== undefined) val = "'" + x.w;
  27866. else if(x.v === undefined) continue;
  27867. else if(x.t == 's') val = "'" + x.v;
  27868. else val = ""+x.v;
  27869. cmds[cmds.length] = y + "=" + val;
  27870. }
  27871. }
  27872. return cmds;
  27873. }
  27874. function sheet_add_json(_ws, js, opts) {
  27875. var o = opts || {};
  27876. var offset = +!o.skipHeader;
  27877. var ws = _ws || ({});
  27878. var _R = 0, _C = 0;
  27879. if(ws && o.origin != null) {
  27880. if(typeof o.origin == 'number') _R = o.origin;
  27881. else {
  27882. var _origin = typeof o.origin == "string" ? decode_cell(o.origin) : o.origin;
  27883. _R = _origin.r; _C = _origin.c;
  27884. }
  27885. }
  27886. var cell;
  27887. var range = ({s: {c:0, r:0}, e: {c:_C, r:_R + js.length - 1 + offset}});
  27888. if(ws['!ref']) {
  27889. var _range = safe_decode_range(ws['!ref']);
  27890. range.e.c = Math.max(range.e.c, _range.e.c);
  27891. range.e.r = Math.max(range.e.r, _range.e.r);
  27892. if(_R == -1) { _R = _range.e.r + 1; range.e.r = _R + js.length - 1 + offset; }
  27893. } else {
  27894. if(_R == -1) { _R = 0; range.e.r = js.length - 1 + offset; }
  27895. }
  27896. var hdr = o.header || [], C = 0;
  27897. js.forEach(function (JS, R) {
  27898. keys(JS).forEach(function(k) {
  27899. if((C=hdr.indexOf(k)) == -1) hdr[C=hdr.length] = k;
  27900. var v = JS[k];
  27901. var t = 'z';
  27902. var z = "";
  27903. var ref = encode_cell({c:_C + C,r:_R + R + offset});
  27904. cell = utils.sheet_get_cell(ws, ref);
  27905. if(v && typeof v === 'object' && !(v instanceof Date)){
  27906. ws[ref] = v;
  27907. } else {
  27908. if(typeof v == 'number') t = 'n';
  27909. else if(typeof v == 'boolean') t = 'b';
  27910. else if(typeof v == 'string') t = 's';
  27911. else if(v instanceof Date) {
  27912. t = 'd';
  27913. if(!o.cellDates) { t = 'n'; v = datenum(v); }
  27914. z = (o.dateNF || SSF._table[14]);
  27915. }
  27916. if(!cell) ws[ref] = cell = ({t:t, v:v});
  27917. else {
  27918. cell.t = t; cell.v = v;
  27919. delete cell.w; delete cell.R;
  27920. if(z) cell.z = z;
  27921. }
  27922. if(z) cell.z = z;
  27923. }
  27924. });
  27925. });
  27926. range.e.c = Math.max(range.e.c, _C + hdr.length - 1);
  27927. var __R = encode_row(_R);
  27928. if(offset) for(C = 0; C < hdr.length; ++C) ws[encode_col(C + _C) + __R] = {t:'s', v:hdr[C]};
  27929. ws['!ref'] = encode_range(range);
  27930. return ws;
  27931. }
  27932. function json_to_sheet(js, opts) { return sheet_add_json(null, js, opts); }
  27933. var utils = {
  27934. encode_col: encode_col,
  27935. encode_row: encode_row,
  27936. encode_cell: encode_cell,
  27937. encode_range: encode_range,
  27938. decode_col: decode_col,
  27939. decode_row: decode_row,
  27940. split_cell: split_cell,
  27941. decode_cell: decode_cell,
  27942. decode_range: decode_range,
  27943. format_cell: format_cell,
  27944. get_formulae: sheet_to_formulae,
  27945. make_csv: sheet_to_csv,
  27946. make_json: sheet_to_json,
  27947. make_formulae: sheet_to_formulae,
  27948. sheet_add_aoa: sheet_add_aoa,
  27949. sheet_add_json: sheet_add_json,
  27950. sheet_add_dom: sheet_add_dom,
  27951. aoa_to_sheet: aoa_to_sheet,
  27952. json_to_sheet: json_to_sheet,
  27953. table_to_sheet: parse_dom_table,
  27954. table_to_book: table_to_book,
  27955. sheet_to_csv: sheet_to_csv,
  27956. sheet_to_txt: sheet_to_txt,
  27957. sheet_to_json: sheet_to_json,
  27958. sheet_to_html: HTML_.from_sheet,
  27959. sheet_to_formulae: sheet_to_formulae,
  27960. sheet_to_row_object_array: sheet_to_json
  27961. };
  27962. (function(utils) {
  27963. utils.consts = utils.consts || {};
  27964. function add_consts(R/*Array<any>*/) { R.forEach(function(a){ utils.consts[a[0]] = a[1]; }); }
  27965. function get_default(x, y, z) { return x[y] != null ? x[y] : (x[y] = z); }
  27966. /* get cell, creating a stub if necessary */
  27967. function ws_get_cell_stub(ws, R, C) {
  27968. /* A1 cell address */
  27969. if(typeof R == "string") {
  27970. /* dense */
  27971. if(Array.isArray(ws)) {
  27972. var RC = decode_cell(R);
  27973. if(!ws[RC.r]) ws[RC.r] = [];
  27974. return ws[RC.r][RC.c] || (ws[RC.r][RC.c] = {t:'z'});
  27975. }
  27976. return ws[R] || (ws[R] = {t:'z'});
  27977. }
  27978. /* cell address object */
  27979. if(typeof R != "number") return ws_get_cell_stub(ws, encode_cell(R));
  27980. /* R and C are 0-based indices */
  27981. return ws_get_cell_stub(ws, encode_cell({r:R,c:C||0}));
  27982. }
  27983. utils.sheet_get_cell = ws_get_cell_stub;
  27984. /* find sheet index for given name / validate index */
  27985. function wb_sheet_idx(wb, sh) {
  27986. if(typeof sh == "number") {
  27987. if(sh >= 0 && wb.SheetNames.length > sh) return sh;
  27988. throw new Error("Cannot find sheet # " + sh);
  27989. } else if(typeof sh == "string") {
  27990. var idx = wb.SheetNames.indexOf(sh);
  27991. if(idx > -1) return idx;
  27992. throw new Error("Cannot find sheet name |" + sh + "|");
  27993. } else throw new Error("Cannot find sheet |" + sh + "|");
  27994. }
  27995. /* simple blank workbook object */
  27996. utils.book_new = function() {
  27997. return { SheetNames: [], Sheets: {} };
  27998. };
  27999. /* add a worksheet to the end of a given workbook */
  28000. utils.book_append_sheet = function(wb, ws, name) {
  28001. if(!name) for(var i = 1; i <= 0xFFFF; ++i, name = undefined) if(wb.SheetNames.indexOf(name = "Sheet" + i) == -1) break;
  28002. if(!name || wb.SheetNames.length >= 0xFFFF) throw new Error("Too many worksheets");
  28003. check_ws_name(name);
  28004. if(wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!");
  28005. wb.SheetNames.push(name);
  28006. wb.Sheets[name] = ws;
  28007. };
  28008. /* set sheet visibility (visible/hidden/very hidden) */
  28009. utils.book_set_sheet_visibility = function(wb, sh, vis) {
  28010. get_default(wb,"Workbook",{});
  28011. get_default(wb.Workbook,"Sheets",[]);
  28012. var idx = wb_sheet_idx(wb, sh);
  28013. // $FlowIgnore
  28014. get_default(wb.Workbook.Sheets,idx, {});
  28015. switch(vis) {
  28016. case 0: case 1: case 2: break;
  28017. default: throw new Error("Bad sheet visibility setting " + vis);
  28018. }
  28019. // $FlowIgnore
  28020. wb.Workbook.Sheets[idx].Hidden = vis;
  28021. };
  28022. add_consts([
  28023. ["SHEET_VISIBLE", 0],
  28024. ["SHEET_HIDDEN", 1],
  28025. ["SHEET_VERY_HIDDEN", 2]
  28026. ]);
  28027. /* set number format */
  28028. utils.cell_set_number_format = function(cell, fmt) {
  28029. cell.z = fmt;
  28030. return cell;
  28031. };
  28032. /* set cell hyperlink */
  28033. utils.cell_set_hyperlink = function(cell, target, tooltip) {
  28034. if(!target) {
  28035. delete cell.l;
  28036. } else {
  28037. cell.l = ({ Target: target });
  28038. if(tooltip) cell.l.Tooltip = tooltip;
  28039. }
  28040. return cell;
  28041. };
  28042. utils.cell_set_internal_link = function(cell, range, tooltip) { return utils.cell_set_hyperlink(cell, "#" + range, tooltip); };
  28043. /* add to cell comments */
  28044. utils.cell_add_comment = function(cell, text, author) {
  28045. if(!cell.c) cell.c = [];
  28046. cell.c.push({t:text, a:author||"SheetJS"});
  28047. };
  28048. /* set array formula and flush related cells */
  28049. utils.sheet_set_array_formula = function(ws, range, formula) {
  28050. var rng = typeof range != "string" ? range : safe_decode_range(range);
  28051. var rngstr = typeof range == "string" ? range : encode_range(range);
  28052. for(var R = rng.s.r; R <= rng.e.r; ++R) for(var C = rng.s.c; C <= rng.e.c; ++C) {
  28053. var cell = ws_get_cell_stub(ws, R, C);
  28054. cell.t = 'n';
  28055. cell.F = rngstr;
  28056. delete cell.v;
  28057. if(R == rng.s.r && C == rng.s.c) cell.f = formula;
  28058. }
  28059. return ws;
  28060. };
  28061. return utils;
  28062. })(utils);
  28063. if(has_buf && typeof require != 'undefined') (function() {
  28064. var Readable = {}.Readable;
  28065. var write_csv_stream = function(sheet, opts) {
  28066. var stream = Readable();
  28067. var o = opts == null ? {} : opts;
  28068. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  28069. var r = safe_decode_range(sheet["!ref"]);
  28070. var FS = o.FS !== undefined ? o.FS : ",", fs = FS.charCodeAt(0);
  28071. var RS = o.RS !== undefined ? o.RS : "\n", rs = RS.charCodeAt(0);
  28072. var endregex = new RegExp((FS=="|" ? "\\|" : FS)+"+$");
  28073. var row = "", cols = [];
  28074. o.dense = Array.isArray(sheet);
  28075. var colinfo = o.skipHidden && sheet["!cols"] || [];
  28076. var rowinfo = o.skipHidden && sheet["!rows"] || [];
  28077. for(var C = r.s.c; C <= r.e.c; ++C) if (!((colinfo[C]||{}).hidden)) cols[C] = encode_col(C);
  28078. var R = r.s.r;
  28079. var BOM = false;
  28080. stream._read = function() {
  28081. if(!BOM) { BOM = true; return stream.push("\uFEFF"); }
  28082. while(R <= r.e.r) {
  28083. ++R;
  28084. if ((rowinfo[R-1]||{}).hidden) continue;
  28085. row = make_csv_row(sheet, r, R-1, cols, fs, rs, FS, o);
  28086. if(row != null) {
  28087. if(o.strip) row = row.replace(endregex,"");
  28088. stream.push(row + RS);
  28089. break;
  28090. }
  28091. }
  28092. if(R > r.e.r) return stream.push(null);
  28093. };
  28094. return stream;
  28095. };
  28096. var write_html_stream = function(ws, opts) {
  28097. var stream = Readable();
  28098. var o = opts || {};
  28099. var header = o.header != null ? o.header : HTML_.BEGIN;
  28100. var footer = o.footer != null ? o.footer : HTML_.END;
  28101. stream.push(header);
  28102. var r = decode_range(ws['!ref']);
  28103. o.dense = Array.isArray(ws);
  28104. stream.push(HTML_._preamble(ws, r, o));
  28105. var R = r.s.r;
  28106. var end = false;
  28107. stream._read = function() {
  28108. if(R > r.e.r) {
  28109. if(!end) { end = true; stream.push("</table>" + footer); }
  28110. return stream.push(null);
  28111. }
  28112. while(R <= r.e.r) {
  28113. stream.push(HTML_._row(ws, r, R, o));
  28114. ++R;
  28115. break;
  28116. }
  28117. };
  28118. return stream;
  28119. };
  28120. var write_json_stream = function(sheet, opts) {
  28121. var stream = Readable({objectMode:true});
  28122. if(sheet == null || sheet["!ref"] == null) { stream.push(null); return stream; }
  28123. var val = {t:'n',v:0}, header = 0, offset = 1, hdr = [], v=0, vv="";
  28124. var r = {s:{r:0,c:0},e:{r:0,c:0}};
  28125. var o = opts || {};
  28126. var range = o.range != null ? o.range : sheet["!ref"];
  28127. if(o.header === 1) header = 1;
  28128. else if(o.header === "A") header = 2;
  28129. else if(Array.isArray(o.header)) header = 3;
  28130. switch(typeof range) {
  28131. case 'string': r = safe_decode_range(range); break;
  28132. case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
  28133. default: r = range;
  28134. }
  28135. if(header > 0) offset = 0;
  28136. var rr = encode_row(r.s.r);
  28137. var cols = [];
  28138. var counter = 0;
  28139. var dense = Array.isArray(sheet);
  28140. var R = r.s.r, C = 0, CC = 0;
  28141. if(dense && !sheet[R]) sheet[R] = [];
  28142. for(C = r.s.c; C <= r.e.c; ++C) {
  28143. cols[C] = encode_col(C);
  28144. val = dense ? sheet[R][C] : sheet[cols[C] + rr];
  28145. switch(header) {
  28146. case 1: hdr[C] = C - r.s.c; break;
  28147. case 2: hdr[C] = cols[C]; break;
  28148. case 3: hdr[C] = o.header[C - r.s.c]; break;
  28149. default:
  28150. if(val == null) val = {w: "__EMPTY", t: "s"};
  28151. vv = v = format_cell(val, null, o);
  28152. counter = 0;
  28153. for(CC = 0; CC < hdr.length; ++CC) if(hdr[CC] == vv) vv = v + "_" + (++counter);
  28154. hdr[C] = vv;
  28155. }
  28156. }
  28157. R = r.s.r + offset;
  28158. stream._read = function() {
  28159. if(R > r.e.r) return stream.push(null);
  28160. while(R <= r.e.r) {
  28161. //if ((rowinfo[R-1]||{}).hidden) continue;
  28162. var row = make_json_row(sheet, r, R, cols, header, hdr, dense, o);
  28163. ++R;
  28164. if((row.isempty === false) || (header === 1 ? o.blankrows !== false : !!o.blankrows)) {
  28165. stream.push(row.row);
  28166. break;
  28167. }
  28168. }
  28169. };
  28170. return stream;
  28171. };
  28172. XLSX2.stream = {
  28173. to_json: write_json_stream,
  28174. to_html: write_html_stream,
  28175. to_csv: write_csv_stream
  28176. };
  28177. })();
  28178. if(typeof parse_xlscfb !== "undefined") XLSX2.parse_xlscfb = parse_xlscfb;
  28179. XLSX2.parse_zip = parse_zip;
  28180. XLSX2.read = readSync; //xlsread
  28181. XLSX2.readFile = readFileSync; //readFile
  28182. XLSX2.readFileSync = readFileSync;
  28183. XLSX2.write = writeSync;
  28184. XLSX2.writeFile = writeFileSync;
  28185. XLSX2.writeFileSync = writeFileSync;
  28186. XLSX2.writeFileAsync = writeFileAsync;
  28187. XLSX2.utils = utils;
  28188. XLSX2.SSF = SSF;
  28189. if(typeof CFB !== "undefined") XLSX2.CFB = CFB;
  28190. }
  28191. /*global define */
  28192. if(typeof exports !== 'undefined') make_xlsx_lib(exports);
  28193. else if(typeof module !== 'undefined' && module.exports) make_xlsx_lib(module.exports);
  28194. else if(typeof define === 'function' && define.amd) define(function() { if(!XLSX2.version) make_xlsx_lib(XLSX2); return XLSX2; });
  28195. else make_xlsx_lib(XLSX2);
  28196. /*exported XLS, ODS */
  28197. var XLS = XLSX2, ODS = XLSX2;