cos-wx-sdk-v5.js 438 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["COS"] = factory();
  8. else
  9. root["COS"] = factory();
  10. })(typeof self !== 'undefined' ? self : this, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, {
  50. /******/ configurable: false,
  51. /******/ enumerable: true,
  52. /******/ get: getter
  53. /******/ });
  54. /******/ }
  55. /******/ };
  56. /******/
  57. /******/ // getDefaultExport function for compatibility with non-harmony modules
  58. /******/ __webpack_require__.n = function(module) {
  59. /******/ var getter = module && module.__esModule ?
  60. /******/ function getDefault() { return module['default']; } :
  61. /******/ function getModuleExports() { return module; };
  62. /******/ __webpack_require__.d(getter, 'a', getter);
  63. /******/ return getter;
  64. /******/ };
  65. /******/
  66. /******/ // Object.prototype.hasOwnProperty.call
  67. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  68. /******/
  69. /******/ // __webpack_public_path__
  70. /******/ __webpack_require__.p = "/Users/tianfeng/Documents/项目/sdk/cos-wx-sdk-v5/demo/lib";
  71. /******/
  72. /******/ // Load entry module and return exports
  73. /******/ return __webpack_require__(__webpack_require__.s = 7);
  74. /******/ })
  75. /************************************************************************/
  76. /******/ ([
  77. /* 0 */
  78. /***/ (function(module, exports, __webpack_require__) {
  79. "use strict";
  80. /* WEBPACK VAR INJECTION */(function(global) {
  81. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  82. var md5 = __webpack_require__(9);
  83. var CryptoJS = __webpack_require__(13);
  84. var xml2json = __webpack_require__(14);
  85. var json2xml = __webpack_require__(19);
  86. var base64 = __webpack_require__(4);
  87. var btoa = base64.btoa;
  88. var wxfs = wx.getFileSystemManager();
  89. function camSafeUrlEncode(str) {
  90. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
  91. }
  92. function getObjectKeys(obj, forKey) {
  93. var list = [];
  94. for (var key in obj) {
  95. if (obj.hasOwnProperty(key)) {
  96. list.push(forKey ? camSafeUrlEncode(key).toLowerCase() : key);
  97. }
  98. }
  99. return list.sort(function (a, b) {
  100. a = a.toLowerCase();
  101. b = b.toLowerCase();
  102. return a === b ? 0 : a > b ? 1 : -1;
  103. });
  104. };
  105. /**
  106. * obj转为string
  107. * @param {Object} obj 需要转的对象,必须
  108. * @param {Boolean} lowerCaseKey key是否转为小写,默认false,非必须
  109. * @return {String} data 返回字符串
  110. */
  111. var obj2str = function obj2str(obj, lowerCaseKey) {
  112. var i, key, val;
  113. var list = [];
  114. var keyList = getObjectKeys(obj);
  115. for (i = 0; i < keyList.length; i++) {
  116. key = keyList[i];
  117. val = obj[key] === undefined || obj[key] === null ? '' : '' + obj[key];
  118. key = lowerCaseKey ? camSafeUrlEncode(key).toLowerCase() : camSafeUrlEncode(key);
  119. val = camSafeUrlEncode(val) || '';
  120. list.push(key + '=' + val);
  121. }
  122. return list.join('&');
  123. };
  124. // 可以签入签名的headers
  125. var signHeaders = ['content-disposition', 'content-encoding', 'content-length', 'content-md5', 'expect', 'expires', 'host', 'if-match', 'if-modified-since', 'if-none-match', 'if-unmodified-since', 'origin', 'range', 'response-cache-control', 'response-content-disposition', 'response-content-encoding', 'response-content-language', 'response-content-type', 'response-expires', 'transfer-encoding', 'versionid'];
  126. var getSignHeaderObj = function getSignHeaderObj(headers) {
  127. var signHeaderObj = {};
  128. for (var i in headers) {
  129. var key = i.toLowerCase();
  130. if (key.indexOf('x-cos-') > -1 || signHeaders.indexOf(key) > -1) {
  131. signHeaderObj[i] = headers[i];
  132. }
  133. }
  134. return signHeaderObj;
  135. };
  136. //测试用的key后面可以去掉
  137. var getAuth = function getAuth(opt) {
  138. opt = opt || {};
  139. var SecretId = opt.SecretId;
  140. var SecretKey = opt.SecretKey;
  141. var KeyTime = opt.KeyTime;
  142. var method = (opt.method || opt.Method || 'get').toLowerCase();
  143. var queryParams = clone(opt.Query || opt.params || {});
  144. var headers = getSignHeaderObj(clone(opt.Headers || opt.headers || {}));
  145. var Key = opt.Key || '';
  146. var pathname;
  147. if (opt.UseRawKey) {
  148. pathname = opt.Pathname || opt.pathname || '/' + Key;
  149. } else {
  150. pathname = opt.Pathname || opt.pathname || Key;
  151. pathname.indexOf('/') !== 0 && (pathname = '/' + pathname);
  152. }
  153. // ForceSignHost明确传入false才不加入host签名
  154. var forceSignHost = opt.ForceSignHost === false ? false : true;
  155. // 如果有传入存储桶,那么签名默认加 Host 参与计算,避免跨桶访问
  156. if (!headers.Host && !headers.host && opt.Bucket && opt.Region && forceSignHost) headers.Host = opt.Bucket + '.cos.' + opt.Region + '.myqcloud.com';
  157. if (!SecretId) return console.error('missing param SecretId');
  158. if (!SecretKey) return console.error('missing param SecretKey');
  159. // 签名有效起止时间
  160. var now = Math.round(getSkewTime(opt.SystemClockOffset) / 1000) - 1;
  161. var exp = now;
  162. var Expires = opt.Expires || opt.expires;
  163. if (Expires === undefined) {
  164. exp += 900; // 签名过期时间为当前 + 900s
  165. } else {
  166. exp += Expires * 1 || 0;
  167. }
  168. // 要用到的 Authorization 参数列表
  169. var qSignAlgorithm = 'sha1';
  170. var qAk = SecretId;
  171. var qSignTime = KeyTime || now + ';' + exp;
  172. var qKeyTime = KeyTime || now + ';' + exp;
  173. var qHeaderList = getObjectKeys(headers, true).join(';').toLowerCase();
  174. var qUrlParamList = getObjectKeys(queryParams, true).join(';').toLowerCase();
  175. // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
  176. // 步骤一:计算 SignKey
  177. var signKey = CryptoJS.HmacSHA1(qKeyTime, SecretKey).toString();
  178. // 步骤二:构成 FormatString
  179. var formatString = [method, pathname, util.obj2str(queryParams, true), util.obj2str(headers, true), ''].join('\n');
  180. // 步骤三:计算 StringToSign
  181. var stringToSign = ['sha1', qSignTime, CryptoJS.SHA1(formatString).toString(), ''].join('\n');
  182. // 步骤四:计算 Signature
  183. var qSignature = CryptoJS.HmacSHA1(stringToSign, signKey).toString();
  184. // 步骤五:构造 Authorization
  185. var authorization = ['q-sign-algorithm=' + qSignAlgorithm, 'q-ak=' + qAk, 'q-sign-time=' + qSignTime, 'q-key-time=' + qKeyTime, 'q-header-list=' + qHeaderList, 'q-url-param-list=' + qUrlParamList, 'q-signature=' + qSignature].join('&');
  186. return authorization;
  187. };
  188. var noop = function noop() {};
  189. // 清除对象里值为的 undefined 或 null 的属性
  190. var clearKey = function clearKey(obj) {
  191. var retObj = {};
  192. for (var key in obj) {
  193. if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
  194. retObj[key] = obj[key];
  195. }
  196. }
  197. return retObj;
  198. };
  199. // 获取文件分片
  200. var fileSlice = function fileSlice(FilePath, start, end, callback) {
  201. if (FilePath) {
  202. wxfs.readFile({
  203. filePath: FilePath,
  204. position: start,
  205. length: end - start,
  206. success: function success(res) {
  207. callback(res.data);
  208. },
  209. fail: function fail() {
  210. callback(null);
  211. }
  212. });
  213. } else {
  214. callback(null);
  215. }
  216. };
  217. // 获取文件内容的 MD5
  218. var getBodyMd5 = function getBodyMd5(UploadCheckContentMd5, Body, callback) {
  219. callback = callback || noop;
  220. if (UploadCheckContentMd5) {
  221. if (Body && Body instanceof ArrayBuffer) {
  222. util.getFileMd5(Body, function (err, md5) {
  223. callback(md5);
  224. });
  225. } else {
  226. callback();
  227. }
  228. } else {
  229. callback();
  230. }
  231. };
  232. // 获取文件 md5 值
  233. var getFileMd5 = function getFileMd5(body, callback) {
  234. var hash = md5(body);
  235. callback && callback(hash);
  236. return hash;
  237. };
  238. function clone(obj) {
  239. return map(obj, function (v) {
  240. return (typeof v === 'undefined' ? 'undefined' : _typeof(v)) === 'object' && v !== null ? clone(v) : v;
  241. });
  242. }
  243. function attr(obj, name, defaultValue) {
  244. return obj && name in obj ? obj[name] : defaultValue;
  245. }
  246. function extend(target, source) {
  247. each(source, function (val, key) {
  248. target[key] = source[key];
  249. });
  250. return target;
  251. }
  252. function isArray(arr) {
  253. return arr instanceof Array;
  254. }
  255. function isInArray(arr, item) {
  256. var flag = false;
  257. for (var i = 0; i < arr.length; i++) {
  258. if (item === arr[i]) {
  259. flag = true;
  260. break;
  261. }
  262. }
  263. return flag;
  264. }
  265. function makeArray(arr) {
  266. return isArray(arr) ? arr : [arr];
  267. }
  268. function each(obj, fn) {
  269. for (var i in obj) {
  270. if (obj.hasOwnProperty(i)) {
  271. fn(obj[i], i);
  272. }
  273. }
  274. }
  275. function map(obj, fn) {
  276. var o = isArray(obj) ? [] : {};
  277. for (var i in obj) {
  278. if (obj.hasOwnProperty(i)) {
  279. o[i] = fn(obj[i], i);
  280. }
  281. }
  282. return o;
  283. }
  284. function filter(obj, fn) {
  285. var iaArr = isArray(obj);
  286. var o = iaArr ? [] : {};
  287. for (var i in obj) {
  288. if (obj.hasOwnProperty(i)) {
  289. if (fn(obj[i], i)) {
  290. if (iaArr) {
  291. o.push(obj[i]);
  292. } else {
  293. o[i] = obj[i];
  294. }
  295. }
  296. }
  297. }
  298. return o;
  299. }
  300. var binaryBase64 = function binaryBase64(str) {
  301. var i,
  302. len,
  303. char,
  304. res = '';
  305. for (i = 0, len = str.length / 2; i < len; i++) {
  306. char = parseInt(str[i * 2] + str[i * 2 + 1], 16);
  307. res += String.fromCharCode(char);
  308. }
  309. return btoa(res);
  310. };
  311. var uuid = function uuid() {
  312. var S4 = function S4() {
  313. return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
  314. };
  315. return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
  316. };
  317. var hasMissingParams = function hasMissingParams(apiName, params) {
  318. var Bucket = params.Bucket;
  319. var Region = params.Region;
  320. var Key = params.Key;
  321. if (apiName.indexOf('Bucket') > -1 || apiName === 'deleteMultipleObject' || apiName === 'multipartList' || apiName === 'listObjectVersions') {
  322. if (!Bucket) return 'Bucket';
  323. if (!Region) return 'Region';
  324. } else if (apiName.indexOf('Object') > -1 || apiName.indexOf('multipart') > -1 || apiName === 'sliceUploadFile' || apiName === 'abortUploadTask') {
  325. if (!Bucket) return 'Bucket';
  326. if (!Region) return 'Region';
  327. if (!Key) return 'Key';
  328. }
  329. return false;
  330. };
  331. var formatParams = function formatParams(apiName, params) {
  332. // 复制参数对象
  333. params = extend({}, params);
  334. // 统一处理 Headers
  335. if (apiName !== 'getAuth' && apiName !== 'getV4Auth' && apiName !== 'getObjectUrl') {
  336. var Headers = params.Headers || {};
  337. if (params && (typeof params === 'undefined' ? 'undefined' : _typeof(params)) === 'object') {
  338. (function () {
  339. for (var key in params) {
  340. if (params.hasOwnProperty(key) && key.indexOf('x-cos-') > -1) {
  341. Headers[key] = params[key];
  342. }
  343. }
  344. })();
  345. var headerMap = {
  346. // params headers
  347. 'x-cos-mfa': 'MFA',
  348. 'Content-MD5': 'ContentMD5',
  349. 'Content-Length': 'ContentLength',
  350. 'Content-Type': 'ContentType',
  351. 'Expect': 'Expect',
  352. 'Expires': 'Expires',
  353. 'Cache-Control': 'CacheControl',
  354. 'Content-Disposition': 'ContentDisposition',
  355. 'Content-Encoding': 'ContentEncoding',
  356. 'Range': 'Range',
  357. 'If-Modified-Since': 'IfModifiedSince',
  358. 'If-Unmodified-Since': 'IfUnmodifiedSince',
  359. 'If-Match': 'IfMatch',
  360. 'If-None-Match': 'IfNoneMatch',
  361. 'x-cos-copy-source': 'CopySource',
  362. 'x-cos-copy-source-Range': 'CopySourceRange',
  363. 'x-cos-metadata-directive': 'MetadataDirective',
  364. 'x-cos-copy-source-If-Modified-Since': 'CopySourceIfModifiedSince',
  365. 'x-cos-copy-source-If-Unmodified-Since': 'CopySourceIfUnmodifiedSince',
  366. 'x-cos-copy-source-If-Match': 'CopySourceIfMatch',
  367. 'x-cos-copy-source-If-None-Match': 'CopySourceIfNoneMatch',
  368. 'x-cos-acl': 'ACL',
  369. 'x-cos-grant-read': 'GrantRead',
  370. 'x-cos-grant-write': 'GrantWrite',
  371. 'x-cos-grant-full-control': 'GrantFullControl',
  372. 'x-cos-grant-read-acp': 'GrantReadAcp',
  373. 'x-cos-grant-write-acp': 'GrantWriteAcp',
  374. 'x-cos-storage-class': 'StorageClass',
  375. // SSE-C
  376. 'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm',
  377. 'x-cos-server-side-encryption-customer-key': 'SSECustomerKey',
  378. 'x-cos-server-side-encryption-customer-key-MD5': 'SSECustomerKeyMD5',
  379. // SSE-COS、SSE-KMS
  380. 'x-cos-server-side-encryption': 'ServerSideEncryption',
  381. 'x-cos-server-side-encryption-cos-kms-key-id': 'SSEKMSKeyId',
  382. 'x-cos-server-side-encryption-context': 'SSEContext'
  383. };
  384. util.each(headerMap, function (paramKey, headerKey) {
  385. if (params[paramKey] !== undefined) {
  386. Headers[headerKey] = params[paramKey];
  387. }
  388. });
  389. params.Headers = clearKey(Headers);
  390. }
  391. }
  392. return params;
  393. };
  394. var apiWrapper = function apiWrapper(apiName, apiFn) {
  395. return function (params, callback) {
  396. var self = this;
  397. // 处理参数
  398. if (typeof params === 'function') {
  399. callback = params;
  400. params = {};
  401. }
  402. // 整理参数格式
  403. params = formatParams(apiName, params);
  404. // 代理回调函数
  405. var formatResult = function formatResult(result) {
  406. if (result && result.headers) {
  407. result.headers['x-cos-request-id'] && (result.RequestId = result.headers['x-cos-request-id']);
  408. result.headers['x-ci-request-id'] && (result.RequestId = result.headers['x-ci-request-id']);
  409. result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']);
  410. result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']);
  411. }
  412. return result;
  413. };
  414. var _callback = function _callback(err, data) {
  415. callback && callback(formatResult(err), formatResult(data));
  416. };
  417. var checkParams = function checkParams() {
  418. if (apiName !== 'getService' && apiName !== 'abortUploadTask') {
  419. // 判断参数是否完整
  420. var missingResult = hasMissingParams(apiName, params);
  421. if (missingResult) {
  422. return 'missing param ' + missingResult;
  423. }
  424. // 判断 region 格式
  425. if (params.Region) {
  426. if (params.Region.indexOf('cos.') > -1) {
  427. return 'param Region should not be start with "cos."';
  428. } else if (!/^([a-z\d-]+)$/.test(params.Region)) {
  429. return 'Region format error.';
  430. }
  431. // 判断 region 格式
  432. if (!self.options.CompatibilityMode && params.Region.indexOf('-') === -1 && params.Region !== 'yfb' && params.Region !== 'default' && params.Region !== 'accelerate') {
  433. console.warn('warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224');
  434. }
  435. }
  436. // 兼容不带 AppId 的 Bucket
  437. if (params.Bucket) {
  438. if (!/^([a-z\d-]+)-(\d+)$/.test(params.Bucket)) {
  439. if (params.AppId) {
  440. params.Bucket = params.Bucket + '-' + params.AppId;
  441. } else if (self.options.AppId) {
  442. params.Bucket = params.Bucket + '-' + self.options.AppId;
  443. } else {
  444. return 'Bucket should format as "test-1250000000".';
  445. }
  446. }
  447. if (params.AppId) {
  448. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).');
  449. delete params.AppId;
  450. }
  451. }
  452. // 如果 Key 是 / 开头,强制去掉第一个 /
  453. if (params.Key && params.Key.substr(0, 1) === '/') {
  454. params.Key = params.Key.substr(1);
  455. }
  456. }
  457. };
  458. var errMsg = checkParams();
  459. var isSync = apiName === 'getAuth' || apiName === 'getObjectUrl';
  460. var Promise = global.Promise;
  461. if (!isSync && Promise && !callback) {
  462. return new Promise(function (resolve, reject) {
  463. callback = function callback(err, data) {
  464. err ? reject(err) : resolve(data);
  465. };
  466. if (errMsg) return _callback({ error: errMsg });
  467. apiFn.call(self, params, _callback);
  468. });
  469. } else {
  470. if (errMsg) return _callback({ error: errMsg });
  471. var res = apiFn.call(self, params, _callback);
  472. if (isSync) return res;
  473. }
  474. };
  475. };
  476. var throttleOnProgress = function throttleOnProgress(total, onProgress) {
  477. var self = this;
  478. var size0 = 0;
  479. var size1 = 0;
  480. var time0 = Date.now();
  481. var time1;
  482. var timer;
  483. function update() {
  484. timer = 0;
  485. if (onProgress && typeof onProgress === 'function') {
  486. time1 = Date.now();
  487. var speed = Math.max(0, Math.round((size1 - size0) / ((time1 - time0) / 1000) * 100) / 100) || 0;
  488. var percent;
  489. if (size1 === 0 && total === 0) {
  490. percent = 1;
  491. } else {
  492. percent = Math.floor(size1 / total * 100) / 100 || 0;
  493. }
  494. time0 = time1;
  495. size0 = size1;
  496. try {
  497. onProgress({ loaded: size1, total: total, speed: speed, percent: percent });
  498. } catch (e) {}
  499. }
  500. }
  501. return function (info, immediately) {
  502. if (info) {
  503. size1 = info.loaded;
  504. total = info.total;
  505. }
  506. if (immediately) {
  507. clearTimeout(timer);
  508. update();
  509. } else {
  510. if (timer) return;
  511. timer = setTimeout(update, self.options.ProgressInterval);
  512. }
  513. };
  514. };
  515. var getFileSize = function getFileSize(api, params, callback) {
  516. if (api === 'postObject') {
  517. callback();
  518. } else if (api === 'putObject') {
  519. if (params.Body !== undefined) {
  520. params.ContentLength = params.Body.byteLength;
  521. callback(null, params.ContentLength);
  522. } else {
  523. callback({ error: 'missing param Body' });
  524. }
  525. } else {
  526. if (params.FilePath) {
  527. wxfs.stat({
  528. path: params.FilePath,
  529. success: function success(res) {
  530. var stats = res.stats;
  531. params.FileStat = stats;
  532. params.FileStat.FilePath = params.FilePath;
  533. var size = stats.isDirectory() ? 0 : stats.size;
  534. params.ContentLength = size = size || 0;
  535. callback(null, size);
  536. },
  537. fail: function fail(err) {
  538. callback(err);
  539. }
  540. });
  541. } else {
  542. callback({ error: 'missing param FilePath' });
  543. }
  544. }
  545. };
  546. var getSkewTime = function getSkewTime(offset) {
  547. return Date.now() + (offset || 0);
  548. };
  549. var compareVersion = function compareVersion(v1, v2) {
  550. v1 = v1.split('.');
  551. v2 = v2.split('.');
  552. var len = Math.max(v1.length, v2.length);
  553. while (v1.length < len) {
  554. v1.push('0');
  555. }
  556. while (v2.length < len) {
  557. v2.push('0');
  558. }
  559. for (var i = 0; i < len; i++) {
  560. var num1 = parseInt(v1[i]);
  561. var num2 = parseInt(v2[i]);
  562. if (num1 > num2) {
  563. return 1;
  564. } else if (num1 < num2) {
  565. return -1;
  566. }
  567. }
  568. return 0;
  569. };
  570. var canFileSlice = function () {
  571. var systemInfo = wx.getSystemInfoSync();
  572. var support = compareVersion(systemInfo.SDKVersion, '2.10.0') >= 0;
  573. var needWarning = !support && systemInfo.platform === "devtools";
  574. return function () {
  575. if (needWarning) console.warn('当前小程序版本小于 2.10.0,不支持分片上传,请更新软件。');
  576. needWarning = false;
  577. return support;
  578. };
  579. }();
  580. var isCIHost = function isCIHost(url) {
  581. return (/^https?:\/\/([^/]+\.)?ci\.[^/]+/.test(url)
  582. );
  583. };
  584. var error = function error(err, opt) {
  585. var sourceErr = err;
  586. err.message = err.message || null;
  587. if (typeof opt === 'string') {
  588. err.error = opt;
  589. err.message = opt;
  590. } else if ((typeof opt === 'undefined' ? 'undefined' : _typeof(opt)) === 'object' && opt !== null) {
  591. extend(err, opt);
  592. if (opt.code || opt.name) err.code = opt.code || opt.name;
  593. if (opt.message) err.message = opt.message;
  594. if (opt.stack) err.stack = opt.stack;
  595. }
  596. if (typeof Object.defineProperty === 'function') {
  597. Object.defineProperty(err, 'name', { writable: true, enumerable: false });
  598. Object.defineProperty(err, 'message', { enumerable: true });
  599. }
  600. err.name = opt && opt.name || err.name || err.code || 'Error';
  601. if (!err.code) err.code = err.name;
  602. if (!err.error) err.error = clone(sourceErr); // 兼容老的错误格式
  603. return err;
  604. };
  605. var util = {
  606. noop: noop,
  607. formatParams: formatParams,
  608. apiWrapper: apiWrapper,
  609. xml2json: xml2json,
  610. json2xml: json2xml,
  611. md5: md5,
  612. clearKey: clearKey,
  613. fileSlice: fileSlice,
  614. getBodyMd5: getBodyMd5,
  615. getFileMd5: getFileMd5,
  616. binaryBase64: binaryBase64,
  617. extend: extend,
  618. isArray: isArray,
  619. isInArray: isInArray,
  620. makeArray: makeArray,
  621. each: each,
  622. map: map,
  623. filter: filter,
  624. clone: clone,
  625. attr: attr,
  626. uuid: uuid,
  627. camSafeUrlEncode: camSafeUrlEncode,
  628. throttleOnProgress: throttleOnProgress,
  629. getFileSize: getFileSize,
  630. getSkewTime: getSkewTime,
  631. obj2str: obj2str,
  632. getAuth: getAuth,
  633. compareVersion: compareVersion,
  634. canFileSlice: canFileSlice,
  635. isCIHost: isCIHost,
  636. error: error
  637. };
  638. module.exports = util;
  639. xml2json;
  640. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
  641. /***/ }),
  642. /* 1 */
  643. /***/ (function(module, exports, __webpack_require__) {
  644. "use strict";
  645. /**
  646. * "Shallow freezes" an object to render it immutable.
  647. * Uses `Object.freeze` if available,
  648. * otherwise the immutability is only in the type.
  649. *
  650. * Is used to create "enum like" objects.
  651. *
  652. * @template T
  653. * @param {T} object the object to freeze
  654. * @param {Pick<ObjectConstructor, 'freeze'> = Object} oc `Object` by default,
  655. * allows to inject custom object constructor for tests
  656. * @returns {Readonly<T>}
  657. *
  658. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
  659. */
  660. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  661. function freeze(object, oc) {
  662. if (oc === undefined) {
  663. oc = Object;
  664. }
  665. return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object;
  666. }
  667. /**
  668. * Since we can not rely on `Object.assign` we provide a simplified version
  669. * that is sufficient for our needs.
  670. *
  671. * @param {Object} target
  672. * @param {Object | null | undefined} source
  673. *
  674. * @returns {Object} target
  675. * @throws TypeError if target is not an object
  676. *
  677. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  678. * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign
  679. */
  680. function assign(target, source) {
  681. if (target === null || (typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') {
  682. throw new TypeError('target is not an object');
  683. }
  684. for (var key in source) {
  685. if (Object.prototype.hasOwnProperty.call(source, key)) {
  686. target[key] = source[key];
  687. }
  688. }
  689. return target;
  690. }
  691. /**
  692. * All mime types that are allowed as input to `DOMParser.parseFromString`
  693. *
  694. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN
  695. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec
  696. * @see DOMParser.prototype.parseFromString
  697. */
  698. var MIME_TYPE = freeze({
  699. /**
  700. * `text/html`, the only mime type that triggers treating an XML document as HTML.
  701. *
  702. * @see DOMParser.SupportedType.isHTML
  703. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  704. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  705. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  706. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
  707. */
  708. HTML: 'text/html',
  709. /**
  710. * Helper method to check a mime type if it indicates an HTML document
  711. *
  712. * @param {string} [value]
  713. * @returns {boolean}
  714. *
  715. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  716. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  717. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  718. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */
  719. isHTML: function isHTML(value) {
  720. return value === MIME_TYPE.HTML;
  721. },
  722. /**
  723. * `application/xml`, the standard mime type for XML documents.
  724. *
  725. * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
  726. * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
  727. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  728. */
  729. XML_APPLICATION: 'application/xml',
  730. /**
  731. * `text/html`, an alias for `application/xml`.
  732. *
  733. * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
  734. * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
  735. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  736. */
  737. XML_TEXT: 'text/xml',
  738. /**
  739. * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
  740. * but is parsed as an XML document.
  741. *
  742. * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
  743. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
  744. * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
  745. */
  746. XML_XHTML_APPLICATION: 'application/xhtml+xml',
  747. /**
  748. * `image/svg+xml`,
  749. *
  750. * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
  751. * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
  752. * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
  753. */
  754. XML_SVG_IMAGE: 'image/svg+xml'
  755. });
  756. /**
  757. * Namespaces that are used in this code base.
  758. *
  759. * @see http://www.w3.org/TR/REC-xml-names
  760. */
  761. var NAMESPACE = freeze({
  762. /**
  763. * The XHTML namespace.
  764. *
  765. * @see http://www.w3.org/1999/xhtml
  766. */
  767. HTML: 'http://www.w3.org/1999/xhtml',
  768. /**
  769. * Checks if `uri` equals `NAMESPACE.HTML`.
  770. *
  771. * @param {string} [uri]
  772. *
  773. * @see NAMESPACE.HTML
  774. */
  775. isHTML: function isHTML(uri) {
  776. return uri === NAMESPACE.HTML;
  777. },
  778. /**
  779. * The SVG namespace.
  780. *
  781. * @see http://www.w3.org/2000/svg
  782. */
  783. SVG: 'http://www.w3.org/2000/svg',
  784. /**
  785. * The `xml:` namespace.
  786. *
  787. * @see http://www.w3.org/XML/1998/namespace
  788. */
  789. XML: 'http://www.w3.org/XML/1998/namespace',
  790. /**
  791. * The `xmlns:` namespace
  792. *
  793. * @see https://www.w3.org/2000/xmlns/
  794. */
  795. XMLNS: 'http://www.w3.org/2000/xmlns/'
  796. });
  797. exports.assign = assign;
  798. exports.freeze = freeze;
  799. exports.MIME_TYPE = MIME_TYPE;
  800. exports.NAMESPACE = NAMESPACE;
  801. /***/ }),
  802. /* 2 */
  803. /***/ (function(module, exports, __webpack_require__) {
  804. "use strict";
  805. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  806. var g;
  807. // This works in non-strict mode
  808. g = function () {
  809. return this;
  810. }();
  811. try {
  812. // This works if eval is allowed (see CSP)
  813. g = g || Function("return this")() || (1, eval)("this");
  814. } catch (e) {
  815. // This works if the window reference is available
  816. if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") g = window;
  817. }
  818. // g can still be undefined, but nothing to do about it...
  819. // We return undefined, instead of nothing here, so it's
  820. // easier to handle this case. if(!global) { ...}
  821. module.exports = g;
  822. /***/ }),
  823. /* 3 */
  824. /***/ (function(module, exports, __webpack_require__) {
  825. "use strict";
  826. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  827. var conventions = __webpack_require__(1);
  828. var NAMESPACE = conventions.NAMESPACE;
  829. /**
  830. * A prerequisite for `[].filter`, to drop elements that are empty
  831. * @param {string} input
  832. * @returns {boolean}
  833. */
  834. function notEmptyString(input) {
  835. return input !== '';
  836. }
  837. /**
  838. * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace
  839. * @see https://infra.spec.whatwg.org/#ascii-whitespace
  840. *
  841. * @param {string} input
  842. * @returns {string[]} (can be empty)
  843. */
  844. function splitOnASCIIWhitespace(input) {
  845. // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE
  846. return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [];
  847. }
  848. /**
  849. * Adds element as a key to current if it is not already present.
  850. *
  851. * @param {Record<string, boolean | undefined>} current
  852. * @param {string} element
  853. * @returns {Record<string, boolean | undefined>}
  854. */
  855. function orderedSetReducer(current, element) {
  856. if (!current.hasOwnProperty(element)) {
  857. current[element] = true;
  858. }
  859. return current;
  860. }
  861. /**
  862. * @see https://infra.spec.whatwg.org/#ordered-set
  863. * @param {string} input
  864. * @returns {string[]}
  865. */
  866. function toOrderedSet(input) {
  867. if (!input) return [];
  868. var list = splitOnASCIIWhitespace(input);
  869. return Object.keys(list.reduce(orderedSetReducer, {}));
  870. }
  871. /**
  872. * Uses `list.indexOf` to implement something like `Array.prototype.includes`,
  873. * which we can not rely on being available.
  874. *
  875. * @param {any[]} list
  876. * @returns {function(any): boolean}
  877. */
  878. function arrayIncludes(list) {
  879. return function (element) {
  880. return list && list.indexOf(element) !== -1;
  881. };
  882. }
  883. function copy(src, dest) {
  884. for (var p in src) {
  885. dest[p] = src[p];
  886. }
  887. }
  888. /**
  889. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  890. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  891. */
  892. function _extends(Class, Super) {
  893. var pt = Class.prototype;
  894. if (!(pt instanceof Super)) {
  895. var t = function t() {};
  896. ;
  897. t.prototype = Super.prototype;
  898. t = new t();
  899. copy(pt, t);
  900. Class.prototype = pt = t;
  901. }
  902. if (pt.constructor != Class) {
  903. if (typeof Class != 'function') {
  904. console.error("unknown Class:" + Class);
  905. }
  906. pt.constructor = Class;
  907. }
  908. }
  909. // Node Types
  910. var NodeType = {};
  911. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  912. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  913. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  914. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  915. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  916. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  917. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  918. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  919. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  920. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  921. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  922. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  923. // ExceptionCode
  924. var ExceptionCode = {};
  925. var ExceptionMessage = {};
  926. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
  927. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
  928. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
  929. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
  930. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
  931. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
  932. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
  933. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
  934. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
  935. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10);
  936. //level2
  937. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
  938. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
  939. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
  940. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
  941. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
  942. /**
  943. * DOM Level 2
  944. * Object DOMException
  945. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  946. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  947. */
  948. function DOMException(code, message) {
  949. if (message instanceof Error) {
  950. var error = message;
  951. } else {
  952. error = this;
  953. Error.call(this, ExceptionMessage[code]);
  954. this.message = ExceptionMessage[code];
  955. if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  956. }
  957. error.code = code;
  958. if (message) this.message = this.message + ": " + message;
  959. return error;
  960. };
  961. DOMException.prototype = Error.prototype;
  962. copy(ExceptionCode, DOMException);
  963. /**
  964. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  965. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  966. * The items in the NodeList are accessible via an integral index, starting from 0.
  967. */
  968. function NodeList() {};
  969. NodeList.prototype = {
  970. /**
  971. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  972. * @standard level1
  973. */
  974. length: 0,
  975. /**
  976. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  977. * @standard level1
  978. * @param index unsigned long
  979. * Index into the collection.
  980. * @return Node
  981. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  982. */
  983. item: function item(index) {
  984. return this[index] || null;
  985. },
  986. toString: function toString(isHTML, nodeFilter) {
  987. for (var buf = [], i = 0; i < this.length; i++) {
  988. serializeToString(this[i], buf, isHTML, nodeFilter);
  989. }
  990. return buf.join('');
  991. }
  992. };
  993. function LiveNodeList(node, refresh) {
  994. this._node = node;
  995. this._refresh = refresh;
  996. _updateLiveList(this);
  997. }
  998. function _updateLiveList(list) {
  999. var inc = list._node._inc || list._node.ownerDocument._inc;
  1000. if (list._inc != inc) {
  1001. var ls = list._refresh(list._node);
  1002. //console.log(ls.length)
  1003. __set__(list, 'length', ls.length);
  1004. copy(ls, list);
  1005. list._inc = inc;
  1006. }
  1007. }
  1008. LiveNodeList.prototype.item = function (i) {
  1009. _updateLiveList(this);
  1010. return this[i];
  1011. };
  1012. _extends(LiveNodeList, NodeList);
  1013. /**
  1014. * Objects implementing the NamedNodeMap interface are used
  1015. * to represent collections of nodes that can be accessed by name.
  1016. * Note that NamedNodeMap does not inherit from NodeList;
  1017. * NamedNodeMaps are not maintained in any particular order.
  1018. * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index,
  1019. * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap,
  1020. * and does not imply that the DOM specifies an order to these Nodes.
  1021. * NamedNodeMap objects in the DOM are live.
  1022. * used for attributes or DocumentType entities
  1023. */
  1024. function NamedNodeMap() {};
  1025. function _findNodeIndex(list, node) {
  1026. var i = list.length;
  1027. while (i--) {
  1028. if (list[i] === node) {
  1029. return i;
  1030. }
  1031. }
  1032. }
  1033. function _addNamedNode(el, list, newAttr, oldAttr) {
  1034. if (oldAttr) {
  1035. list[_findNodeIndex(list, oldAttr)] = newAttr;
  1036. } else {
  1037. list[list.length++] = newAttr;
  1038. }
  1039. if (el) {
  1040. newAttr.ownerElement = el;
  1041. var doc = el.ownerDocument;
  1042. if (doc) {
  1043. oldAttr && _onRemoveAttribute(doc, el, oldAttr);
  1044. _onAddAttribute(doc, el, newAttr);
  1045. }
  1046. }
  1047. }
  1048. function _removeNamedNode(el, list, attr) {
  1049. //console.log('remove attr:'+attr)
  1050. var i = _findNodeIndex(list, attr);
  1051. if (i >= 0) {
  1052. var lastIndex = list.length - 1;
  1053. while (i < lastIndex) {
  1054. list[i] = list[++i];
  1055. }
  1056. list.length = lastIndex;
  1057. if (el) {
  1058. var doc = el.ownerDocument;
  1059. if (doc) {
  1060. _onRemoveAttribute(doc, el, attr);
  1061. attr.ownerElement = null;
  1062. }
  1063. }
  1064. } else {
  1065. throw DOMException(NOT_FOUND_ERR, new Error(el.tagName + '@' + attr));
  1066. }
  1067. }
  1068. NamedNodeMap.prototype = {
  1069. length: 0,
  1070. item: NodeList.prototype.item,
  1071. getNamedItem: function getNamedItem(key) {
  1072. // if(key.indexOf(':')>0 || key == 'xmlns'){
  1073. // return null;
  1074. // }
  1075. //console.log()
  1076. var i = this.length;
  1077. while (i--) {
  1078. var attr = this[i];
  1079. //console.log(attr.nodeName,key)
  1080. if (attr.nodeName == key) {
  1081. return attr;
  1082. }
  1083. }
  1084. },
  1085. setNamedItem: function setNamedItem(attr) {
  1086. var el = attr.ownerElement;
  1087. if (el && el != this._ownerElement) {
  1088. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  1089. }
  1090. var oldAttr = this.getNamedItem(attr.nodeName);
  1091. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  1092. return oldAttr;
  1093. },
  1094. /* returns Node */
  1095. setNamedItemNS: function setNamedItemNS(attr) {
  1096. // raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  1097. var el = attr.ownerElement,
  1098. oldAttr;
  1099. if (el && el != this._ownerElement) {
  1100. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  1101. }
  1102. oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
  1103. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  1104. return oldAttr;
  1105. },
  1106. /* returns Node */
  1107. removeNamedItem: function removeNamedItem(key) {
  1108. var attr = this.getNamedItem(key);
  1109. _removeNamedNode(this._ownerElement, this, attr);
  1110. return attr;
  1111. }, // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  1112. //for level2
  1113. removeNamedItemNS: function removeNamedItemNS(namespaceURI, localName) {
  1114. var attr = this.getNamedItemNS(namespaceURI, localName);
  1115. _removeNamedNode(this._ownerElement, this, attr);
  1116. return attr;
  1117. },
  1118. getNamedItemNS: function getNamedItemNS(namespaceURI, localName) {
  1119. var i = this.length;
  1120. while (i--) {
  1121. var node = this[i];
  1122. if (node.localName == localName && node.namespaceURI == namespaceURI) {
  1123. return node;
  1124. }
  1125. }
  1126. return null;
  1127. }
  1128. };
  1129. /**
  1130. * The DOMImplementation interface represents an object providing methods
  1131. * which are not dependent on any particular document.
  1132. * Such an object is returned by the `Document.implementation` property.
  1133. *
  1134. * __The individual methods describe the differences compared to the specs.__
  1135. *
  1136. * @constructor
  1137. *
  1138. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN
  1139. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial)
  1140. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core
  1141. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core
  1142. * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard
  1143. */
  1144. function DOMImplementation() {}
  1145. DOMImplementation.prototype = {
  1146. /**
  1147. * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
  1148. * The different implementations fairly diverged in what kind of features were reported.
  1149. * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
  1150. *
  1151. * @deprecated It is deprecated and modern browsers return true in all cases.
  1152. *
  1153. * @param {string} feature
  1154. * @param {string} [version]
  1155. * @returns {boolean} always true
  1156. *
  1157. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
  1158. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
  1159. * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
  1160. */
  1161. hasFeature: function hasFeature(feature, version) {
  1162. return true;
  1163. },
  1164. /**
  1165. * Creates an XML Document object of the specified type with its document element.
  1166. *
  1167. * __It behaves slightly different from the description in the living standard__:
  1168. * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
  1169. * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
  1170. * - this implementation is not validating names or qualified names
  1171. * (when parsing XML strings, the SAX parser takes care of that)
  1172. *
  1173. * @param {string|null} namespaceURI
  1174. * @param {string} qualifiedName
  1175. * @param {DocumentType=null} doctype
  1176. * @returns {Document}
  1177. *
  1178. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
  1179. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
  1180. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core
  1181. *
  1182. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  1183. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  1184. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  1185. */
  1186. createDocument: function createDocument(namespaceURI, qualifiedName, doctype) {
  1187. var doc = new Document();
  1188. doc.implementation = this;
  1189. doc.childNodes = new NodeList();
  1190. doc.doctype = doctype || null;
  1191. if (doctype) {
  1192. doc.appendChild(doctype);
  1193. }
  1194. if (qualifiedName) {
  1195. var root = doc.createElementNS(namespaceURI, qualifiedName);
  1196. doc.appendChild(root);
  1197. }
  1198. return doc;
  1199. },
  1200. /**
  1201. * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
  1202. *
  1203. * __This behavior is slightly different from the in the specs__:
  1204. * - this implementation is not validating names or qualified names
  1205. * (when parsing XML strings, the SAX parser takes care of that)
  1206. *
  1207. * @param {string} qualifiedName
  1208. * @param {string} [publicId]
  1209. * @param {string} [systemId]
  1210. * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
  1211. * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
  1212. *
  1213. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
  1214. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
  1215. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
  1216. *
  1217. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  1218. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  1219. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  1220. */
  1221. createDocumentType: function createDocumentType(qualifiedName, publicId, systemId) {
  1222. var node = new DocumentType();
  1223. node.name = qualifiedName;
  1224. node.nodeName = qualifiedName;
  1225. node.publicId = publicId || '';
  1226. node.systemId = systemId || '';
  1227. return node;
  1228. }
  1229. };
  1230. /**
  1231. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  1232. */
  1233. function Node() {};
  1234. Node.prototype = {
  1235. firstChild: null,
  1236. lastChild: null,
  1237. previousSibling: null,
  1238. nextSibling: null,
  1239. attributes: null,
  1240. parentNode: null,
  1241. childNodes: null,
  1242. ownerDocument: null,
  1243. nodeValue: null,
  1244. namespaceURI: null,
  1245. prefix: null,
  1246. localName: null,
  1247. // Modified in DOM Level 2:
  1248. insertBefore: function insertBefore(newChild, refChild) {
  1249. //raises
  1250. return _insertBefore(this, newChild, refChild);
  1251. },
  1252. replaceChild: function replaceChild(newChild, oldChild) {
  1253. //raises
  1254. this.insertBefore(newChild, oldChild);
  1255. if (oldChild) {
  1256. this.removeChild(oldChild);
  1257. }
  1258. },
  1259. removeChild: function removeChild(oldChild) {
  1260. return _removeChild(this, oldChild);
  1261. },
  1262. appendChild: function appendChild(newChild) {
  1263. return this.insertBefore(newChild, null);
  1264. },
  1265. hasChildNodes: function hasChildNodes() {
  1266. return this.firstChild != null;
  1267. },
  1268. cloneNode: function cloneNode(deep) {
  1269. return _cloneNode(this.ownerDocument || this, this, deep);
  1270. },
  1271. // Modified in DOM Level 2:
  1272. normalize: function normalize() {
  1273. var child = this.firstChild;
  1274. while (child) {
  1275. var next = child.nextSibling;
  1276. if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
  1277. this.removeChild(next);
  1278. child.appendData(next.data);
  1279. } else {
  1280. child.normalize();
  1281. child = next;
  1282. }
  1283. }
  1284. },
  1285. // Introduced in DOM Level 2:
  1286. isSupported: function isSupported(feature, version) {
  1287. return this.ownerDocument.implementation.hasFeature(feature, version);
  1288. },
  1289. // Introduced in DOM Level 2:
  1290. hasAttributes: function hasAttributes() {
  1291. return this.attributes.length > 0;
  1292. },
  1293. /**
  1294. * Look up the prefix associated to the given namespace URI, starting from this node.
  1295. * **The default namespace declarations are ignored by this method.**
  1296. * See Namespace Prefix Lookup for details on the algorithm used by this method.
  1297. *
  1298. * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._
  1299. *
  1300. * @param {string | null} namespaceURI
  1301. * @returns {string | null}
  1302. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
  1303. * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
  1304. * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
  1305. * @see https://github.com/xmldom/xmldom/issues/322
  1306. */
  1307. lookupPrefix: function lookupPrefix(namespaceURI) {
  1308. var el = this;
  1309. while (el) {
  1310. var map = el._nsMap;
  1311. //console.dir(map)
  1312. if (map) {
  1313. for (var n in map) {
  1314. if (map[n] == namespaceURI) {
  1315. return n;
  1316. }
  1317. }
  1318. }
  1319. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  1320. }
  1321. return null;
  1322. },
  1323. // Introduced in DOM Level 3:
  1324. lookupNamespaceURI: function lookupNamespaceURI(prefix) {
  1325. var el = this;
  1326. while (el) {
  1327. var map = el._nsMap;
  1328. //console.dir(map)
  1329. if (map) {
  1330. if (prefix in map) {
  1331. return map[prefix];
  1332. }
  1333. }
  1334. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  1335. }
  1336. return null;
  1337. },
  1338. // Introduced in DOM Level 3:
  1339. isDefaultNamespace: function isDefaultNamespace(namespaceURI) {
  1340. var prefix = this.lookupPrefix(namespaceURI);
  1341. return prefix == null;
  1342. }
  1343. };
  1344. function _xmlEncoder(c) {
  1345. return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#' + c.charCodeAt() + ';';
  1346. }
  1347. copy(NodeType, Node);
  1348. copy(NodeType, Node.prototype);
  1349. /**
  1350. * @param callback return true for continue,false for break
  1351. * @return boolean true: break visit;
  1352. */
  1353. function _visitNode(node, callback) {
  1354. if (callback(node)) {
  1355. return true;
  1356. }
  1357. if (node = node.firstChild) {
  1358. do {
  1359. if (_visitNode(node, callback)) {
  1360. return true;
  1361. }
  1362. } while (node = node.nextSibling);
  1363. }
  1364. }
  1365. function Document() {}
  1366. function _onAddAttribute(doc, el, newAttr) {
  1367. doc && doc._inc++;
  1368. var ns = newAttr.namespaceURI;
  1369. if (ns === NAMESPACE.XMLNS) {
  1370. //update namespace
  1371. el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
  1372. }
  1373. }
  1374. function _onRemoveAttribute(doc, el, newAttr, remove) {
  1375. doc && doc._inc++;
  1376. var ns = newAttr.namespaceURI;
  1377. if (ns === NAMESPACE.XMLNS) {
  1378. //update namespace
  1379. delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
  1380. }
  1381. }
  1382. /**
  1383. * Updates `el.childNodes`, updating the indexed items and it's `length`.
  1384. * Passing `newChild` means it will be appended.
  1385. * Otherwise it's assumed that an item has been removed,
  1386. * and `el.firstNode` and it's `.nextSibling` are used
  1387. * to walk the current list of child nodes.
  1388. *
  1389. * @param {Document} doc
  1390. * @param {Node} el
  1391. * @param {Node} [newChild]
  1392. * @private
  1393. */
  1394. function _onUpdateChild(doc, el, newChild) {
  1395. if (doc && doc._inc) {
  1396. doc._inc++;
  1397. //update childNodes
  1398. var cs = el.childNodes;
  1399. if (newChild) {
  1400. cs[cs.length++] = newChild;
  1401. } else {
  1402. var child = el.firstChild;
  1403. var i = 0;
  1404. while (child) {
  1405. cs[i++] = child;
  1406. child = child.nextSibling;
  1407. }
  1408. cs.length = i;
  1409. delete cs[cs.length];
  1410. }
  1411. }
  1412. }
  1413. /**
  1414. * Removes the connections between `parentNode` and `child`
  1415. * and any existing `child.previousSibling` or `child.nextSibling`.
  1416. *
  1417. * @see https://github.com/xmldom/xmldom/issues/135
  1418. * @see https://github.com/xmldom/xmldom/issues/145
  1419. *
  1420. * @param {Node} parentNode
  1421. * @param {Node} child
  1422. * @returns {Node} the child that was removed.
  1423. * @private
  1424. */
  1425. function _removeChild(parentNode, child) {
  1426. var previous = child.previousSibling;
  1427. var next = child.nextSibling;
  1428. if (previous) {
  1429. previous.nextSibling = next;
  1430. } else {
  1431. parentNode.firstChild = next;
  1432. }
  1433. if (next) {
  1434. next.previousSibling = previous;
  1435. } else {
  1436. parentNode.lastChild = previous;
  1437. }
  1438. child.parentNode = null;
  1439. child.previousSibling = null;
  1440. child.nextSibling = null;
  1441. _onUpdateChild(parentNode.ownerDocument, parentNode);
  1442. return child;
  1443. }
  1444. /**
  1445. * preformance key(refChild == null)
  1446. */
  1447. function _insertBefore(parentNode, newChild, nextChild) {
  1448. var cp = newChild.parentNode;
  1449. if (cp) {
  1450. cp.removeChild(newChild); //remove and update
  1451. }
  1452. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  1453. var newFirst = newChild.firstChild;
  1454. if (newFirst == null) {
  1455. return newChild;
  1456. }
  1457. var newLast = newChild.lastChild;
  1458. } else {
  1459. newFirst = newLast = newChild;
  1460. }
  1461. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  1462. newFirst.previousSibling = pre;
  1463. newLast.nextSibling = nextChild;
  1464. if (pre) {
  1465. pre.nextSibling = newFirst;
  1466. } else {
  1467. parentNode.firstChild = newFirst;
  1468. }
  1469. if (nextChild == null) {
  1470. parentNode.lastChild = newLast;
  1471. } else {
  1472. nextChild.previousSibling = newLast;
  1473. }
  1474. do {
  1475. newFirst.parentNode = parentNode;
  1476. } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
  1477. _onUpdateChild(parentNode.ownerDocument || parentNode, parentNode);
  1478. //console.log(parentNode.lastChild.nextSibling == null)
  1479. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  1480. newChild.firstChild = newChild.lastChild = null;
  1481. }
  1482. return newChild;
  1483. }
  1484. /**
  1485. * Appends `newChild` to `parentNode`.
  1486. * If `newChild` is already connected to a `parentNode` it is first removed from it.
  1487. *
  1488. * @see https://github.com/xmldom/xmldom/issues/135
  1489. * @see https://github.com/xmldom/xmldom/issues/145
  1490. * @param {Node} parentNode
  1491. * @param {Node} newChild
  1492. * @returns {Node}
  1493. * @private
  1494. */
  1495. function _appendSingleChild(parentNode, newChild) {
  1496. if (newChild.parentNode) {
  1497. newChild.parentNode.removeChild(newChild);
  1498. }
  1499. newChild.parentNode = parentNode;
  1500. newChild.previousSibling = parentNode.lastChild;
  1501. newChild.nextSibling = null;
  1502. if (newChild.previousSibling) {
  1503. newChild.previousSibling.nextSibling = newChild;
  1504. } else {
  1505. parentNode.firstChild = newChild;
  1506. }
  1507. parentNode.lastChild = newChild;
  1508. _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
  1509. return newChild;
  1510. }
  1511. Document.prototype = {
  1512. //implementation : null,
  1513. nodeName: '#document',
  1514. nodeType: DOCUMENT_NODE,
  1515. /**
  1516. * The DocumentType node of the document.
  1517. *
  1518. * @readonly
  1519. * @type DocumentType
  1520. */
  1521. doctype: null,
  1522. documentElement: null,
  1523. _inc: 1,
  1524. insertBefore: function insertBefore(newChild, refChild) {
  1525. //raises
  1526. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  1527. var child = newChild.firstChild;
  1528. while (child) {
  1529. var next = child.nextSibling;
  1530. this.insertBefore(child, refChild);
  1531. child = next;
  1532. }
  1533. return newChild;
  1534. }
  1535. if (this.documentElement == null && newChild.nodeType == ELEMENT_NODE) {
  1536. this.documentElement = newChild;
  1537. }
  1538. return _insertBefore(this, newChild, refChild), newChild.ownerDocument = this, newChild;
  1539. },
  1540. removeChild: function removeChild(oldChild) {
  1541. if (this.documentElement == oldChild) {
  1542. this.documentElement = null;
  1543. }
  1544. return _removeChild(this, oldChild);
  1545. },
  1546. // Introduced in DOM Level 2:
  1547. importNode: function importNode(importedNode, deep) {
  1548. return _importNode(this, importedNode, deep);
  1549. },
  1550. // Introduced in DOM Level 2:
  1551. getElementById: function getElementById(id) {
  1552. var rtv = null;
  1553. _visitNode(this.documentElement, function (node) {
  1554. if (node.nodeType == ELEMENT_NODE) {
  1555. if (node.getAttribute('id') == id) {
  1556. rtv = node;
  1557. return true;
  1558. }
  1559. }
  1560. });
  1561. return rtv;
  1562. },
  1563. /**
  1564. * The `getElementsByClassName` method of `Document` interface returns an array-like object
  1565. * of all child elements which have **all** of the given class name(s).
  1566. *
  1567. * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
  1568. *
  1569. *
  1570. * Warning: This is a live LiveNodeList.
  1571. * Changes in the DOM will reflect in the array as the changes occur.
  1572. * If an element selected by this array no longer qualifies for the selector,
  1573. * it will automatically be removed. Be aware of this for iteration purposes.
  1574. *
  1575. * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
  1576. *
  1577. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  1578. * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
  1579. */
  1580. getElementsByClassName: function getElementsByClassName(classNames) {
  1581. var classNamesSet = toOrderedSet(classNames);
  1582. return new LiveNodeList(this, function (base) {
  1583. var ls = [];
  1584. if (classNamesSet.length > 0) {
  1585. _visitNode(base.documentElement, function (node) {
  1586. if (node !== base && node.nodeType === ELEMENT_NODE) {
  1587. var nodeClassNames = node.getAttribute('class');
  1588. // can be null if the attribute does not exist
  1589. if (nodeClassNames) {
  1590. // before splitting and iterating just compare them for the most common case
  1591. var matches = classNames === nodeClassNames;
  1592. if (!matches) {
  1593. var nodeClassNamesSet = toOrderedSet(nodeClassNames);
  1594. matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
  1595. }
  1596. if (matches) {
  1597. ls.push(node);
  1598. }
  1599. }
  1600. }
  1601. });
  1602. }
  1603. return ls;
  1604. });
  1605. },
  1606. //document factory method:
  1607. createElement: function createElement(tagName) {
  1608. var node = new Element();
  1609. node.ownerDocument = this;
  1610. node.nodeName = tagName;
  1611. node.tagName = tagName;
  1612. node.localName = tagName;
  1613. node.childNodes = new NodeList();
  1614. var attrs = node.attributes = new NamedNodeMap();
  1615. attrs._ownerElement = node;
  1616. return node;
  1617. },
  1618. createDocumentFragment: function createDocumentFragment() {
  1619. var node = new DocumentFragment();
  1620. node.ownerDocument = this;
  1621. node.childNodes = new NodeList();
  1622. return node;
  1623. },
  1624. createTextNode: function createTextNode(data) {
  1625. var node = new Text();
  1626. node.ownerDocument = this;
  1627. node.appendData(data);
  1628. return node;
  1629. },
  1630. createComment: function createComment(data) {
  1631. var node = new Comment();
  1632. node.ownerDocument = this;
  1633. node.appendData(data);
  1634. return node;
  1635. },
  1636. createCDATASection: function createCDATASection(data) {
  1637. var node = new CDATASection();
  1638. node.ownerDocument = this;
  1639. node.appendData(data);
  1640. return node;
  1641. },
  1642. createProcessingInstruction: function createProcessingInstruction(target, data) {
  1643. var node = new ProcessingInstruction();
  1644. node.ownerDocument = this;
  1645. node.tagName = node.target = target;
  1646. node.nodeValue = node.data = data;
  1647. return node;
  1648. },
  1649. createAttribute: function createAttribute(name) {
  1650. var node = new Attr();
  1651. node.ownerDocument = this;
  1652. node.name = name;
  1653. node.nodeName = name;
  1654. node.localName = name;
  1655. node.specified = true;
  1656. return node;
  1657. },
  1658. createEntityReference: function createEntityReference(name) {
  1659. var node = new EntityReference();
  1660. node.ownerDocument = this;
  1661. node.nodeName = name;
  1662. return node;
  1663. },
  1664. // Introduced in DOM Level 2:
  1665. createElementNS: function createElementNS(namespaceURI, qualifiedName) {
  1666. var node = new Element();
  1667. var pl = qualifiedName.split(':');
  1668. var attrs = node.attributes = new NamedNodeMap();
  1669. node.childNodes = new NodeList();
  1670. node.ownerDocument = this;
  1671. node.nodeName = qualifiedName;
  1672. node.tagName = qualifiedName;
  1673. node.namespaceURI = namespaceURI;
  1674. if (pl.length == 2) {
  1675. node.prefix = pl[0];
  1676. node.localName = pl[1];
  1677. } else {
  1678. //el.prefix = null;
  1679. node.localName = qualifiedName;
  1680. }
  1681. attrs._ownerElement = node;
  1682. return node;
  1683. },
  1684. // Introduced in DOM Level 2:
  1685. createAttributeNS: function createAttributeNS(namespaceURI, qualifiedName) {
  1686. var node = new Attr();
  1687. var pl = qualifiedName.split(':');
  1688. node.ownerDocument = this;
  1689. node.nodeName = qualifiedName;
  1690. node.name = qualifiedName;
  1691. node.namespaceURI = namespaceURI;
  1692. node.specified = true;
  1693. if (pl.length == 2) {
  1694. node.prefix = pl[0];
  1695. node.localName = pl[1];
  1696. } else {
  1697. //el.prefix = null;
  1698. node.localName = qualifiedName;
  1699. }
  1700. return node;
  1701. }
  1702. };
  1703. _extends(Document, Node);
  1704. function Element() {
  1705. this._nsMap = {};
  1706. };
  1707. Element.prototype = {
  1708. nodeType: ELEMENT_NODE,
  1709. hasAttribute: function hasAttribute(name) {
  1710. return this.getAttributeNode(name) != null;
  1711. },
  1712. getAttribute: function getAttribute(name) {
  1713. var attr = this.getAttributeNode(name);
  1714. return attr && attr.value || '';
  1715. },
  1716. getAttributeNode: function getAttributeNode(name) {
  1717. return this.attributes.getNamedItem(name);
  1718. },
  1719. setAttribute: function setAttribute(name, value) {
  1720. var attr = this.ownerDocument.createAttribute(name);
  1721. attr.value = attr.nodeValue = "" + value;
  1722. this.setAttributeNode(attr);
  1723. },
  1724. removeAttribute: function removeAttribute(name) {
  1725. var attr = this.getAttributeNode(name);
  1726. attr && this.removeAttributeNode(attr);
  1727. },
  1728. //four real opeartion method
  1729. appendChild: function appendChild(newChild) {
  1730. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  1731. return this.insertBefore(newChild, null);
  1732. } else {
  1733. return _appendSingleChild(this, newChild);
  1734. }
  1735. },
  1736. setAttributeNode: function setAttributeNode(newAttr) {
  1737. return this.attributes.setNamedItem(newAttr);
  1738. },
  1739. setAttributeNodeNS: function setAttributeNodeNS(newAttr) {
  1740. return this.attributes.setNamedItemNS(newAttr);
  1741. },
  1742. removeAttributeNode: function removeAttributeNode(oldAttr) {
  1743. //console.log(this == oldAttr.ownerElement)
  1744. return this.attributes.removeNamedItem(oldAttr.nodeName);
  1745. },
  1746. //get real attribute name,and remove it by removeAttributeNode
  1747. removeAttributeNS: function removeAttributeNS(namespaceURI, localName) {
  1748. var old = this.getAttributeNodeNS(namespaceURI, localName);
  1749. old && this.removeAttributeNode(old);
  1750. },
  1751. hasAttributeNS: function hasAttributeNS(namespaceURI, localName) {
  1752. return this.getAttributeNodeNS(namespaceURI, localName) != null;
  1753. },
  1754. getAttributeNS: function getAttributeNS(namespaceURI, localName) {
  1755. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  1756. return attr && attr.value || '';
  1757. },
  1758. setAttributeNS: function setAttributeNS(namespaceURI, qualifiedName, value) {
  1759. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  1760. attr.value = attr.nodeValue = "" + value;
  1761. this.setAttributeNode(attr);
  1762. },
  1763. getAttributeNodeNS: function getAttributeNodeNS(namespaceURI, localName) {
  1764. return this.attributes.getNamedItemNS(namespaceURI, localName);
  1765. },
  1766. getElementsByTagName: function getElementsByTagName(tagName) {
  1767. return new LiveNodeList(this, function (base) {
  1768. var ls = [];
  1769. _visitNode(base, function (node) {
  1770. if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
  1771. ls.push(node);
  1772. }
  1773. });
  1774. return ls;
  1775. });
  1776. },
  1777. getElementsByTagNameNS: function getElementsByTagNameNS(namespaceURI, localName) {
  1778. return new LiveNodeList(this, function (base) {
  1779. var ls = [];
  1780. _visitNode(base, function (node) {
  1781. if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
  1782. ls.push(node);
  1783. }
  1784. });
  1785. return ls;
  1786. });
  1787. }
  1788. };
  1789. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  1790. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  1791. _extends(Element, Node);
  1792. function Attr() {};
  1793. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  1794. _extends(Attr, Node);
  1795. function CharacterData() {};
  1796. CharacterData.prototype = {
  1797. data: '',
  1798. substringData: function substringData(offset, count) {
  1799. return this.data.substring(offset, offset + count);
  1800. },
  1801. appendData: function appendData(text) {
  1802. text = this.data + text;
  1803. this.nodeValue = this.data = text;
  1804. this.length = text.length;
  1805. },
  1806. insertData: function insertData(offset, text) {
  1807. this.replaceData(offset, 0, text);
  1808. },
  1809. appendChild: function appendChild(newChild) {
  1810. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
  1811. },
  1812. deleteData: function deleteData(offset, count) {
  1813. this.replaceData(offset, count, "");
  1814. },
  1815. replaceData: function replaceData(offset, count, text) {
  1816. var start = this.data.substring(0, offset);
  1817. var end = this.data.substring(offset + count);
  1818. text = start + text + end;
  1819. this.nodeValue = this.data = text;
  1820. this.length = text.length;
  1821. }
  1822. };
  1823. _extends(CharacterData, Node);
  1824. function Text() {};
  1825. Text.prototype = {
  1826. nodeName: "#text",
  1827. nodeType: TEXT_NODE,
  1828. splitText: function splitText(offset) {
  1829. var text = this.data;
  1830. var newText = text.substring(offset);
  1831. text = text.substring(0, offset);
  1832. this.data = this.nodeValue = text;
  1833. this.length = text.length;
  1834. var newNode = this.ownerDocument.createTextNode(newText);
  1835. if (this.parentNode) {
  1836. this.parentNode.insertBefore(newNode, this.nextSibling);
  1837. }
  1838. return newNode;
  1839. }
  1840. };
  1841. _extends(Text, CharacterData);
  1842. function Comment() {};
  1843. Comment.prototype = {
  1844. nodeName: "#comment",
  1845. nodeType: COMMENT_NODE
  1846. };
  1847. _extends(Comment, CharacterData);
  1848. function CDATASection() {};
  1849. CDATASection.prototype = {
  1850. nodeName: "#cdata-section",
  1851. nodeType: CDATA_SECTION_NODE
  1852. };
  1853. _extends(CDATASection, CharacterData);
  1854. function DocumentType() {};
  1855. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  1856. _extends(DocumentType, Node);
  1857. function Notation() {};
  1858. Notation.prototype.nodeType = NOTATION_NODE;
  1859. _extends(Notation, Node);
  1860. function Entity() {};
  1861. Entity.prototype.nodeType = ENTITY_NODE;
  1862. _extends(Entity, Node);
  1863. function EntityReference() {};
  1864. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  1865. _extends(EntityReference, Node);
  1866. function DocumentFragment() {};
  1867. DocumentFragment.prototype.nodeName = "#document-fragment";
  1868. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  1869. _extends(DocumentFragment, Node);
  1870. function ProcessingInstruction() {}
  1871. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  1872. _extends(ProcessingInstruction, Node);
  1873. function XMLSerializer() {}
  1874. XMLSerializer.prototype.serializeToString = function (node, isHtml, nodeFilter) {
  1875. return nodeSerializeToString.call(node, isHtml, nodeFilter);
  1876. };
  1877. Node.prototype.toString = nodeSerializeToString;
  1878. function nodeSerializeToString(isHtml, nodeFilter) {
  1879. var buf = [];
  1880. var refNode = this.nodeType == 9 && this.documentElement || this;
  1881. var prefix = refNode.prefix;
  1882. var uri = refNode.namespaceURI;
  1883. if (uri && prefix == null) {
  1884. //console.log(prefix)
  1885. var prefix = refNode.lookupPrefix(uri);
  1886. if (prefix == null) {
  1887. //isHTML = true;
  1888. var visibleNamespaces = [{ namespace: uri, prefix: null
  1889. //{namespace:uri,prefix:''}
  1890. }];
  1891. }
  1892. }
  1893. serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces);
  1894. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  1895. return buf.join('');
  1896. }
  1897. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  1898. var prefix = node.prefix || '';
  1899. var uri = node.namespaceURI;
  1900. // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
  1901. // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
  1902. // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
  1903. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
  1904. // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
  1905. // > [...] Furthermore, the attribute value [...] must not be an empty string.
  1906. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
  1907. if (!uri) {
  1908. return false;
  1909. }
  1910. if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) {
  1911. return false;
  1912. }
  1913. var i = visibleNamespaces.length;
  1914. while (i--) {
  1915. var ns = visibleNamespaces[i];
  1916. // get namespace prefix
  1917. if (ns.prefix === prefix) {
  1918. return ns.namespace !== uri;
  1919. }
  1920. }
  1921. return true;
  1922. }
  1923. /**
  1924. * Well-formed constraint: No < in Attribute Values
  1925. * > The replacement text of any entity referred to directly or indirectly
  1926. * > in an attribute value must not contain a <.
  1927. * @see https://www.w3.org/TR/xml11/#CleanAttrVals
  1928. * @see https://www.w3.org/TR/xml11/#NT-AttValue
  1929. *
  1930. * Literal whitespace other than space that appear in attribute values
  1931. * are serialized as their entity references, so they will be preserved.
  1932. * (In contrast to whitespace literals in the input which are normalized to spaces)
  1933. * @see https://www.w3.org/TR/xml11/#AVNormalize
  1934. * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes
  1935. */
  1936. function addSerializedAttribute(buf, qualifiedName, value) {
  1937. buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"');
  1938. }
  1939. function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
  1940. if (!visibleNamespaces) {
  1941. visibleNamespaces = [];
  1942. }
  1943. if (nodeFilter) {
  1944. node = nodeFilter(node);
  1945. if (node) {
  1946. if (typeof node == 'string') {
  1947. buf.push(node);
  1948. return;
  1949. }
  1950. } else {
  1951. return;
  1952. }
  1953. //buf.sort.apply(attrs, attributeSorter);
  1954. }
  1955. switch (node.nodeType) {
  1956. case ELEMENT_NODE:
  1957. var attrs = node.attributes;
  1958. var len = attrs.length;
  1959. var child = node.firstChild;
  1960. var nodeName = node.tagName;
  1961. isHTML = NAMESPACE.isHTML(node.namespaceURI) || isHTML;
  1962. var prefixedNodeName = nodeName;
  1963. if (!isHTML && !node.prefix && node.namespaceURI) {
  1964. var defaultNS;
  1965. // lookup current default ns from `xmlns` attribute
  1966. for (var ai = 0; ai < attrs.length; ai++) {
  1967. if (attrs.item(ai).name === 'xmlns') {
  1968. defaultNS = attrs.item(ai).value;
  1969. break;
  1970. }
  1971. }
  1972. if (!defaultNS) {
  1973. // lookup current default ns in visibleNamespaces
  1974. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  1975. var namespace = visibleNamespaces[nsi];
  1976. if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
  1977. defaultNS = namespace.namespace;
  1978. break;
  1979. }
  1980. }
  1981. }
  1982. if (defaultNS !== node.namespaceURI) {
  1983. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  1984. var namespace = visibleNamespaces[nsi];
  1985. if (namespace.namespace === node.namespaceURI) {
  1986. if (namespace.prefix) {
  1987. prefixedNodeName = namespace.prefix + ':' + nodeName;
  1988. }
  1989. break;
  1990. }
  1991. }
  1992. }
  1993. }
  1994. buf.push('<', prefixedNodeName);
  1995. for (var i = 0; i < len; i++) {
  1996. // add namespaces for attributes
  1997. var attr = attrs.item(i);
  1998. if (attr.prefix == 'xmlns') {
  1999. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  2000. } else if (attr.nodeName == 'xmlns') {
  2001. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  2002. }
  2003. }
  2004. for (var i = 0; i < len; i++) {
  2005. var attr = attrs.item(i);
  2006. if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
  2007. var prefix = attr.prefix || '';
  2008. var uri = attr.namespaceURI;
  2009. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  2010. visibleNamespaces.push({ prefix: prefix, namespace: uri });
  2011. }
  2012. serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
  2013. }
  2014. // add namespace for current node
  2015. if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  2016. var prefix = node.prefix || '';
  2017. var uri = node.namespaceURI;
  2018. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  2019. visibleNamespaces.push({ prefix: prefix, namespace: uri });
  2020. }
  2021. if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
  2022. buf.push('>');
  2023. //if is cdata child node
  2024. if (isHTML && /^script$/i.test(nodeName)) {
  2025. while (child) {
  2026. if (child.data) {
  2027. buf.push(child.data);
  2028. } else {
  2029. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  2030. }
  2031. child = child.nextSibling;
  2032. }
  2033. } else {
  2034. while (child) {
  2035. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  2036. child = child.nextSibling;
  2037. }
  2038. }
  2039. buf.push('</', prefixedNodeName, '>');
  2040. } else {
  2041. buf.push('/>');
  2042. }
  2043. // remove added visible namespaces
  2044. //visibleNamespaces.length = startVisibleNamespaces;
  2045. return;
  2046. case DOCUMENT_NODE:
  2047. case DOCUMENT_FRAGMENT_NODE:
  2048. var child = node.firstChild;
  2049. while (child) {
  2050. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  2051. child = child.nextSibling;
  2052. }
  2053. return;
  2054. case ATTRIBUTE_NODE:
  2055. return addSerializedAttribute(buf, node.name, node.value);
  2056. case TEXT_NODE:
  2057. /**
  2058. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  2059. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  2060. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  2061. * `&amp;` and `&lt;` respectively.
  2062. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  2063. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  2064. * when that string is not marking the end of a CDATA section.
  2065. *
  2066. * In the content of elements, character data is any string of characters
  2067. * which does not contain the start-delimiter of any markup
  2068. * and does not include the CDATA-section-close delimiter, `]]>`.
  2069. *
  2070. * @see https://www.w3.org/TR/xml/#NT-CharData
  2071. * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
  2072. */
  2073. return buf.push(node.data.replace(/[<&>]/g, _xmlEncoder));
  2074. case CDATA_SECTION_NODE:
  2075. return buf.push('<![CDATA[', node.data, ']]>');
  2076. case COMMENT_NODE:
  2077. return buf.push("<!--", node.data, "-->");
  2078. case DOCUMENT_TYPE_NODE:
  2079. var pubid = node.publicId;
  2080. var sysid = node.systemId;
  2081. buf.push('<!DOCTYPE ', node.name);
  2082. if (pubid) {
  2083. buf.push(' PUBLIC ', pubid);
  2084. if (sysid && sysid != '.') {
  2085. buf.push(' ', sysid);
  2086. }
  2087. buf.push('>');
  2088. } else if (sysid && sysid != '.') {
  2089. buf.push(' SYSTEM ', sysid, '>');
  2090. } else {
  2091. var sub = node.internalSubset;
  2092. if (sub) {
  2093. buf.push(" [", sub, "]");
  2094. }
  2095. buf.push(">");
  2096. }
  2097. return;
  2098. case PROCESSING_INSTRUCTION_NODE:
  2099. return buf.push("<?", node.target, " ", node.data, "?>");
  2100. case ENTITY_REFERENCE_NODE:
  2101. return buf.push('&', node.nodeName, ';');
  2102. //case ENTITY_NODE:
  2103. //case NOTATION_NODE:
  2104. default:
  2105. buf.push('??', node.nodeName);
  2106. }
  2107. }
  2108. function _importNode(doc, node, deep) {
  2109. var node2;
  2110. switch (node.nodeType) {
  2111. case ELEMENT_NODE:
  2112. node2 = node.cloneNode(false);
  2113. node2.ownerDocument = doc;
  2114. //var attrs = node2.attributes;
  2115. //var len = attrs.length;
  2116. //for(var i=0;i<len;i++){
  2117. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  2118. //}
  2119. case DOCUMENT_FRAGMENT_NODE:
  2120. break;
  2121. case ATTRIBUTE_NODE:
  2122. deep = true;
  2123. break;
  2124. //case ENTITY_REFERENCE_NODE:
  2125. //case PROCESSING_INSTRUCTION_NODE:
  2126. ////case TEXT_NODE:
  2127. //case CDATA_SECTION_NODE:
  2128. //case COMMENT_NODE:
  2129. // deep = false;
  2130. // break;
  2131. //case DOCUMENT_NODE:
  2132. //case DOCUMENT_TYPE_NODE:
  2133. //cannot be imported.
  2134. //case ENTITY_NODE:
  2135. //case NOTATION_NODE:
  2136. //can not hit in level3
  2137. //default:throw e;
  2138. }
  2139. if (!node2) {
  2140. node2 = node.cloneNode(false); //false
  2141. }
  2142. node2.ownerDocument = doc;
  2143. node2.parentNode = null;
  2144. if (deep) {
  2145. var child = node.firstChild;
  2146. while (child) {
  2147. node2.appendChild(_importNode(doc, child, deep));
  2148. child = child.nextSibling;
  2149. }
  2150. }
  2151. return node2;
  2152. }
  2153. //
  2154. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  2155. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  2156. function _cloneNode(doc, node, deep) {
  2157. var node2 = new node.constructor();
  2158. for (var n in node) {
  2159. var v = node[n];
  2160. if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) != 'object') {
  2161. if (v != node2[n]) {
  2162. node2[n] = v;
  2163. }
  2164. }
  2165. }
  2166. if (node.childNodes) {
  2167. node2.childNodes = new NodeList();
  2168. }
  2169. node2.ownerDocument = doc;
  2170. switch (node2.nodeType) {
  2171. case ELEMENT_NODE:
  2172. var attrs = node.attributes;
  2173. var attrs2 = node2.attributes = new NamedNodeMap();
  2174. var len = attrs.length;
  2175. attrs2._ownerElement = node2;
  2176. for (var i = 0; i < len; i++) {
  2177. node2.setAttributeNode(_cloneNode(doc, attrs.item(i), true));
  2178. }
  2179. break;;
  2180. case ATTRIBUTE_NODE:
  2181. deep = true;
  2182. }
  2183. if (deep) {
  2184. var child = node.firstChild;
  2185. while (child) {
  2186. node2.appendChild(_cloneNode(doc, child, deep));
  2187. child = child.nextSibling;
  2188. }
  2189. }
  2190. return node2;
  2191. }
  2192. function __set__(object, key, value) {
  2193. object[key] = value;
  2194. }
  2195. //do dynamic
  2196. try {
  2197. if (Object.defineProperty) {
  2198. var getTextContent = function getTextContent(node) {
  2199. switch (node.nodeType) {
  2200. case ELEMENT_NODE:
  2201. case DOCUMENT_FRAGMENT_NODE:
  2202. var buf = [];
  2203. node = node.firstChild;
  2204. while (node) {
  2205. if (node.nodeType !== 7 && node.nodeType !== 8) {
  2206. buf.push(getTextContent(node));
  2207. }
  2208. node = node.nextSibling;
  2209. }
  2210. return buf.join('');
  2211. default:
  2212. return node.nodeValue;
  2213. }
  2214. };
  2215. Object.defineProperty(LiveNodeList.prototype, 'length', {
  2216. get: function get() {
  2217. _updateLiveList(this);
  2218. return this.$$length;
  2219. }
  2220. });
  2221. Object.defineProperty(Node.prototype, 'textContent', {
  2222. get: function get() {
  2223. return getTextContent(this);
  2224. },
  2225. set: function set(data) {
  2226. switch (this.nodeType) {
  2227. case ELEMENT_NODE:
  2228. case DOCUMENT_FRAGMENT_NODE:
  2229. while (this.firstChild) {
  2230. this.removeChild(this.firstChild);
  2231. }
  2232. if (data || String(data)) {
  2233. this.appendChild(this.ownerDocument.createTextNode(data));
  2234. }
  2235. break;
  2236. default:
  2237. this.data = data;
  2238. this.value = data;
  2239. this.nodeValue = data;
  2240. }
  2241. }
  2242. });
  2243. __set__ = function __set__(object, key, value) {
  2244. //console.log(value)
  2245. object['$$' + key] = value;
  2246. };
  2247. }
  2248. } catch (e) {} //ie8
  2249. //if(typeof require == 'function'){
  2250. exports.DocumentType = DocumentType;
  2251. exports.DOMException = DOMException;
  2252. exports.DOMImplementation = DOMImplementation;
  2253. exports.Element = Element;
  2254. exports.Node = Node;
  2255. exports.NodeList = NodeList;
  2256. exports.XMLSerializer = XMLSerializer;
  2257. //}
  2258. /***/ }),
  2259. /* 4 */
  2260. /***/ (function(module, exports, __webpack_require__) {
  2261. "use strict";
  2262. /*
  2263. * $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $
  2264. *
  2265. * Licensed under the BSD 3-Clause License.
  2266. * http://opensource.org/licenses/BSD-3-Clause
  2267. *
  2268. * References:
  2269. * http://en.wikipedia.org/wiki/Base64
  2270. */
  2271. var Base64 = function (global) {
  2272. global = global || {};
  2273. 'use strict';
  2274. // existing version for noConflict()
  2275. var _Base64 = global.Base64;
  2276. var version = "2.1.9";
  2277. // if node.js, we use Buffer
  2278. var buffer;
  2279. // constants
  2280. var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  2281. var b64tab = function (bin) {
  2282. var t = {};
  2283. for (var i = 0, l = bin.length; i < l; i++) {
  2284. t[bin.charAt(i)] = i;
  2285. }return t;
  2286. }(b64chars);
  2287. var fromCharCode = String.fromCharCode;
  2288. // encoder stuff
  2289. var cb_utob = function cb_utob(c) {
  2290. if (c.length < 2) {
  2291. var cc = c.charCodeAt(0);
  2292. return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | cc >>> 6) + fromCharCode(0x80 | cc & 0x3f) : fromCharCode(0xe0 | cc >>> 12 & 0x0f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);
  2293. } else {
  2294. var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00);
  2295. return fromCharCode(0xf0 | cc >>> 18 & 0x07) + fromCharCode(0x80 | cc >>> 12 & 0x3f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);
  2296. }
  2297. };
  2298. var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
  2299. var utob = function utob(u) {
  2300. return u.replace(re_utob, cb_utob);
  2301. };
  2302. var cb_encode = function cb_encode(ccc) {
  2303. var padlen = [0, 2, 1][ccc.length % 3],
  2304. ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0),
  2305. chars = [b64chars.charAt(ord >>> 18), b64chars.charAt(ord >>> 12 & 63), padlen >= 2 ? '=' : b64chars.charAt(ord >>> 6 & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63)];
  2306. return chars.join('');
  2307. };
  2308. var btoa = global.btoa ? function (b) {
  2309. return global.btoa(b);
  2310. } : function (b) {
  2311. return b.replace(/[\s\S]{1,3}/g, cb_encode);
  2312. };
  2313. var _encode = buffer ? function (u) {
  2314. return (u.constructor === buffer.constructor ? u : new buffer(u)).toString('base64');
  2315. } : function (u) {
  2316. return btoa(utob(u));
  2317. };
  2318. var encode = function encode(u, urisafe) {
  2319. return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\/]/g, function (m0) {
  2320. return m0 == '+' ? '-' : '_';
  2321. }).replace(/=/g, '');
  2322. };
  2323. var encodeURI = function encodeURI(u) {
  2324. return encode(u, true);
  2325. };
  2326. // decoder stuff
  2327. var re_btou = new RegExp(['[\xC0-\xDF][\x80-\xBF]', '[\xE0-\xEF][\x80-\xBF]{2}', '[\xF0-\xF7][\x80-\xBF]{3}'].join('|'), 'g');
  2328. var cb_btou = function cb_btou(cccc) {
  2329. switch (cccc.length) {
  2330. case 4:
  2331. var cp = (0x07 & cccc.charCodeAt(0)) << 18 | (0x3f & cccc.charCodeAt(1)) << 12 | (0x3f & cccc.charCodeAt(2)) << 6 | 0x3f & cccc.charCodeAt(3),
  2332. offset = cp - 0x10000;
  2333. return fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00);
  2334. case 3:
  2335. return fromCharCode((0x0f & cccc.charCodeAt(0)) << 12 | (0x3f & cccc.charCodeAt(1)) << 6 | 0x3f & cccc.charCodeAt(2));
  2336. default:
  2337. return fromCharCode((0x1f & cccc.charCodeAt(0)) << 6 | 0x3f & cccc.charCodeAt(1));
  2338. }
  2339. };
  2340. var btou = function btou(b) {
  2341. return b.replace(re_btou, cb_btou);
  2342. };
  2343. var cb_decode = function cb_decode(cccc) {
  2344. var len = cccc.length,
  2345. padlen = len % 4,
  2346. n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0),
  2347. chars = [fromCharCode(n >>> 16), fromCharCode(n >>> 8 & 0xff), fromCharCode(n & 0xff)];
  2348. chars.length -= [0, 0, 2, 1][padlen];
  2349. return chars.join('');
  2350. };
  2351. var atob = global.atob ? function (a) {
  2352. return global.atob(a);
  2353. } : function (a) {
  2354. return a.replace(/[\s\S]{1,4}/g, cb_decode);
  2355. };
  2356. var _decode = buffer ? function (a) {
  2357. return (a.constructor === buffer.constructor ? a : new buffer(a, 'base64')).toString();
  2358. } : function (a) {
  2359. return btou(atob(a));
  2360. };
  2361. var decode = function decode(a) {
  2362. return _decode(String(a).replace(/[-_]/g, function (m0) {
  2363. return m0 == '-' ? '+' : '/';
  2364. }).replace(/[^A-Za-z0-9\+\/]/g, ''));
  2365. };
  2366. var noConflict = function noConflict() {
  2367. var Base64 = global.Base64;
  2368. global.Base64 = _Base64;
  2369. return Base64;
  2370. };
  2371. // export Base64
  2372. var Base64 = {
  2373. VERSION: version,
  2374. atob: atob,
  2375. btoa: btoa,
  2376. fromBase64: decode,
  2377. toBase64: encode,
  2378. utob: utob,
  2379. encode: encode,
  2380. encodeURI: encodeURI,
  2381. btou: btou,
  2382. decode: decode,
  2383. noConflict: noConflict
  2384. };
  2385. return Base64;
  2386. }();
  2387. module.exports = Base64;
  2388. /***/ }),
  2389. /* 5 */
  2390. /***/ (function(module, exports, __webpack_require__) {
  2391. "use strict";
  2392. var initEvent = function initEvent(cos) {
  2393. var listeners = {};
  2394. var getList = function getList(action) {
  2395. !listeners[action] && (listeners[action] = []);
  2396. return listeners[action];
  2397. };
  2398. cos.on = function (action, callback) {
  2399. getList(action).push(callback);
  2400. };
  2401. cos.off = function (action, callback) {
  2402. var list = getList(action);
  2403. for (var i = list.length - 1; i >= 0; i--) {
  2404. callback === list[i] && list.splice(i, 1);
  2405. }
  2406. };
  2407. cos.emit = function (action, data) {
  2408. var list = getList(action).map(function (cb) {
  2409. return cb;
  2410. });
  2411. for (var i = 0; i < list.length; i++) {
  2412. list[i](data);
  2413. }
  2414. };
  2415. };
  2416. var EventProxy = function EventProxy() {
  2417. initEvent(this);
  2418. };
  2419. module.exports.init = initEvent;
  2420. module.exports.EventProxy = EventProxy;
  2421. /***/ }),
  2422. /* 6 */
  2423. /***/ (function(module, exports, __webpack_require__) {
  2424. "use strict";
  2425. var util = __webpack_require__(0);
  2426. // 按照文件特征值,缓存 UploadId
  2427. var cacheKey = 'cos_sdk_upload_cache';
  2428. var expires = 30 * 24 * 3600;
  2429. var cache;
  2430. var timer;
  2431. var getCache = function getCache() {
  2432. try {
  2433. var val = JSON.parse(wx.getStorageSync(cacheKey));
  2434. } catch (e) {}
  2435. if (!val) val = [];
  2436. return val;
  2437. };
  2438. var setCache = function setCache() {
  2439. try {
  2440. wx.setStorageSync(cacheKey, JSON.stringify(cache));
  2441. } catch (e) {}
  2442. };
  2443. var init = function init() {
  2444. if (cache) return;
  2445. cache = getCache();
  2446. // 清理太老旧的数据
  2447. var changed = false;
  2448. var now = Math.round(Date.now() / 1000);
  2449. for (var i = cache.length - 1; i >= 0; i--) {
  2450. var mtime = cache[i][2];
  2451. if (!mtime || mtime + expires < now) {
  2452. cache.splice(i, 1);
  2453. changed = true;
  2454. }
  2455. }
  2456. changed && setCache();
  2457. };
  2458. // 把缓存存到本地
  2459. var save = function save() {
  2460. if (timer) return;
  2461. timer = setTimeout(function () {
  2462. setCache();
  2463. timer = null;
  2464. }, 400);
  2465. };
  2466. var mod = {
  2467. using: {},
  2468. // 标记 UploadId 正在使用
  2469. setUsing: function setUsing(uuid) {
  2470. mod.using[uuid] = true;
  2471. },
  2472. // 标记 UploadId 已经没在使用
  2473. removeUsing: function removeUsing(uuid) {
  2474. delete mod.using[uuid];
  2475. },
  2476. // 用上传参数生成哈希值
  2477. getFileId: function getFileId(FileStat, ChunkSize, Bucket, Key) {
  2478. if (FileStat.FilePath && FileStat.size && FileStat.lastModifiedTime && ChunkSize) {
  2479. return util.md5([FileStat.FilePath].join('::')) + '-' + util.md5([FileStat.size, FileStat.mode, FileStat.lastAccessedTime, FileStat.lastModifiedTime, ChunkSize, Bucket, Key].join('::'));
  2480. } else {
  2481. return null;
  2482. }
  2483. },
  2484. // 获取文件对应的 UploadId 列表
  2485. getUploadIdList: function getUploadIdList(uuid) {
  2486. if (!uuid) return null;
  2487. init();
  2488. var list = [];
  2489. for (var i = 0; i < cache.length; i++) {
  2490. if (cache[i][0] === uuid) list.push(cache[i][1]);
  2491. }
  2492. return list.length ? list : null;
  2493. },
  2494. // 缓存 UploadId
  2495. saveUploadId: function saveUploadId(uuid, UploadId, limit) {
  2496. init();
  2497. if (!uuid) return;
  2498. // 清理没用的 UploadId
  2499. var part1 = uuid.substr(0, uuid.indexOf('-') + 1);
  2500. for (var i = cache.length - 1; i >= 0; i--) {
  2501. var item = cache[i];
  2502. if (item[0] === uuid && item[1] === UploadId) {
  2503. cache.splice(i, 1);
  2504. } else if (uuid !== item[0] && item[0].indexOf(part1) === 0) {
  2505. // 文件路径相同,但其他信息不同,说明文件改变了或上传参数(存储桶、路径、分片大小)变了,直接清理掉
  2506. cache.splice(i, 1);
  2507. }
  2508. }
  2509. cache.unshift([uuid, UploadId, Math.round(Date.now() / 1000)]);
  2510. if (cache.length > limit) cache.splice(limit);
  2511. save();
  2512. },
  2513. // UploadId 已用完,移除掉
  2514. removeUploadId: function removeUploadId(UploadId) {
  2515. init();
  2516. delete mod.using[UploadId];
  2517. for (var i = cache.length - 1; i >= 0; i--) {
  2518. if (cache[i][1] === UploadId) cache.splice(i, 1);
  2519. }
  2520. save();
  2521. }
  2522. };
  2523. module.exports = mod;
  2524. /***/ }),
  2525. /* 7 */
  2526. /***/ (function(module, exports, __webpack_require__) {
  2527. "use strict";
  2528. var COS = __webpack_require__(8);
  2529. module.exports = COS;
  2530. /***/ }),
  2531. /* 8 */
  2532. /***/ (function(module, exports, __webpack_require__) {
  2533. "use strict";
  2534. var util = __webpack_require__(0);
  2535. var event = __webpack_require__(5);
  2536. var task = __webpack_require__(20);
  2537. var base = __webpack_require__(21);
  2538. var advance = __webpack_require__(27);
  2539. var defaultOptions = {
  2540. SecretId: '',
  2541. SecretKey: '',
  2542. SecurityToken: '', // 使用临时密钥需要注意自行刷新 Token
  2543. ChunkRetryTimes: 2,
  2544. FileParallelLimit: 3,
  2545. ChunkParallelLimit: 3,
  2546. ChunkSize: 1024 * 1024,
  2547. SliceSize: 1024 * 1024,
  2548. CopyChunkParallelLimit: 20,
  2549. CopyChunkSize: 1024 * 1024 * 10,
  2550. CopySliceSize: 1024 * 1024 * 10,
  2551. MaxPartNumber: 10000,
  2552. ProgressInterval: 1000,
  2553. UploadQueueSize: 10000,
  2554. Domain: '',
  2555. ServiceDomain: '',
  2556. Protocol: '',
  2557. CompatibilityMode: false,
  2558. ForcePathStyle: false,
  2559. Timeout: 0, // 单位毫秒,0 代表不设置超时时间
  2560. CorrectClockSkew: true,
  2561. SystemClockOffset: 0, // 单位毫秒,ms
  2562. UploadCheckContentMd5: false,
  2563. UploadIdCacheLimit: 50,
  2564. UseAccelerate: false,
  2565. ForceSignHost: true, // 默认将host加入签名计算,关闭后可能导致越权风险,建议保持为true
  2566. HttpDNSServiceId: '' // HttpDNS 服务商 Id,填写后代表开启 HttpDNS 服务。HttpDNS 用法详见https://developers.weixin.qq.com/miniprogram/dev/framework/ability/HTTPDNS.html
  2567. };
  2568. // 对外暴露的类
  2569. var COS = function COS(options) {
  2570. this.options = util.extend(util.clone(defaultOptions), options || {});
  2571. this.options.FileParallelLimit = Math.max(1, this.options.FileParallelLimit);
  2572. this.options.ChunkParallelLimit = Math.max(1, this.options.ChunkParallelLimit);
  2573. this.options.ChunkRetryTimes = Math.max(0, this.options.ChunkRetryTimes);
  2574. this.options.ChunkSize = Math.max(1024 * 1024, this.options.ChunkSize);
  2575. this.options.CopyChunkParallelLimit = Math.max(1, this.options.CopyChunkParallelLimit);
  2576. this.options.CopyChunkSize = Math.max(1024 * 1024, this.options.CopyChunkSize);
  2577. this.options.CopySliceSize = Math.max(0, this.options.CopySliceSize);
  2578. this.options.MaxPartNumber = Math.max(1024, Math.min(10000, this.options.MaxPartNumber));
  2579. this.options.Timeout = Math.max(0, this.options.Timeout);
  2580. if (this.options.AppId) {
  2581. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").');
  2582. }
  2583. if (this.options.SecretId && this.options.SecretId.indexOf(' ') > -1) {
  2584. console.error('error: SecretId格式错误,请检查');
  2585. console.error('error: SecretId format is incorrect. Please check');
  2586. }
  2587. if (this.options.SecretKey && this.options.SecretKey.indexOf(' ') > -1) {
  2588. console.error('error: SecretKey格式错误,请检查');
  2589. console.error('error: SecretKey format is incorrect. Please check');
  2590. }
  2591. event.init(this);
  2592. task.init(this);
  2593. };
  2594. base.init(COS, task);
  2595. advance.init(COS, task);
  2596. COS.util = {
  2597. md5: util.md5,
  2598. xml2json: util.xml2json,
  2599. json2xml: util.json2xml
  2600. };
  2601. COS.getAuthorization = util.getAuth;
  2602. COS.version = '1.2.1';
  2603. module.exports = COS;
  2604. /***/ }),
  2605. /* 9 */
  2606. /***/ (function(module, exports, __webpack_require__) {
  2607. "use strict";
  2608. /* WEBPACK VAR INJECTION */(function(process, global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;
  2609. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  2610. /* https://github.com/emn178/js-md5 */
  2611. (function () {
  2612. 'use strict';
  2613. var ERROR = 'input is invalid type';
  2614. var WINDOW = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object';
  2615. var root = WINDOW ? window : {};
  2616. if (root.JS_MD5_NO_WINDOW) {
  2617. WINDOW = false;
  2618. }
  2619. var WEB_WORKER = !WINDOW && (typeof self === 'undefined' ? 'undefined' : _typeof(self)) === 'object';
  2620. var NODE_JS = !root.JS_MD5_NO_NODE_JS && (typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && process.versions && process.versions.node;
  2621. if (NODE_JS) {
  2622. root = global;
  2623. } else if (WEB_WORKER) {
  2624. root = self;
  2625. }
  2626. var COMMON_JS = !root.JS_MD5_NO_COMMON_JS && ( false ? 'undefined' : _typeof(module)) === 'object' && module.exports;
  2627. var AMD = "function" === 'function' && __webpack_require__(12);
  2628. var ARRAY_BUFFER = !root.JS_MD5_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
  2629. var HEX_CHARS = '0123456789abcdef'.split('');
  2630. var EXTRA = [128, 32768, 8388608, -2147483648];
  2631. var SHIFT = [0, 8, 16, 24];
  2632. var OUTPUT_TYPES = ['hex', 'array', 'digest', 'buffer', 'arrayBuffer', 'base64'];
  2633. var BASE64_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  2634. var blocks = [],
  2635. buffer8;
  2636. if (ARRAY_BUFFER) {
  2637. var buffer = new ArrayBuffer(68);
  2638. buffer8 = new Uint8Array(buffer);
  2639. blocks = new Uint32Array(buffer);
  2640. }
  2641. if (root.JS_MD5_NO_NODE_JS || !Array.isArray) {
  2642. Array.isArray = function (obj) {
  2643. return Object.prototype.toString.call(obj) === '[object Array]';
  2644. };
  2645. }
  2646. if (ARRAY_BUFFER && (root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
  2647. ArrayBuffer.isView = function (obj) {
  2648. return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
  2649. };
  2650. }
  2651. /**
  2652. * @method hex
  2653. * @memberof md5
  2654. * @description Output hash as hex string
  2655. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2656. * @returns {String} Hex string
  2657. * @example
  2658. * md5.hex('The quick brown fox jumps over the lazy dog');
  2659. * // equal to
  2660. * md5('The quick brown fox jumps over the lazy dog');
  2661. */
  2662. /**
  2663. * @method digest
  2664. * @memberof md5
  2665. * @description Output hash as bytes array
  2666. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2667. * @returns {Array} Bytes array
  2668. * @example
  2669. * md5.digest('The quick brown fox jumps over the lazy dog');
  2670. */
  2671. /**
  2672. * @method array
  2673. * @memberof md5
  2674. * @description Output hash as bytes array
  2675. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2676. * @returns {Array} Bytes array
  2677. * @example
  2678. * md5.array('The quick brown fox jumps over the lazy dog');
  2679. */
  2680. /**
  2681. * @method arrayBuffer
  2682. * @memberof md5
  2683. * @description Output hash as ArrayBuffer
  2684. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2685. * @returns {ArrayBuffer} ArrayBuffer
  2686. * @example
  2687. * md5.arrayBuffer('The quick brown fox jumps over the lazy dog');
  2688. */
  2689. /**
  2690. * @method buffer
  2691. * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.
  2692. * @memberof md5
  2693. * @description Output hash as ArrayBuffer
  2694. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2695. * @returns {ArrayBuffer} ArrayBuffer
  2696. * @example
  2697. * md5.buffer('The quick brown fox jumps over the lazy dog');
  2698. */
  2699. /**
  2700. * @method base64
  2701. * @memberof md5
  2702. * @description Output hash as base64 string
  2703. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2704. * @returns {String} base64 string
  2705. * @example
  2706. * md5.base64('The quick brown fox jumps over the lazy dog');
  2707. */
  2708. var createOutputMethod = function createOutputMethod(outputType) {
  2709. return function (message) {
  2710. return new Md5(true).update(message)[outputType]();
  2711. };
  2712. };
  2713. /**
  2714. * @method create
  2715. * @memberof md5
  2716. * @description Create Md5 object
  2717. * @returns {Md5} Md5 object.
  2718. * @example
  2719. * var hash = md5.create();
  2720. */
  2721. /**
  2722. * @method update
  2723. * @memberof md5
  2724. * @description Create and update Md5 object
  2725. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2726. * @returns {Md5} Md5 object.
  2727. * @example
  2728. * var hash = md5.update('The quick brown fox jumps over the lazy dog');
  2729. * // equal to
  2730. * var hash = md5.create();
  2731. * hash.update('The quick brown fox jumps over the lazy dog');
  2732. */
  2733. var createMethod = function createMethod() {
  2734. var method = createOutputMethod('hex');
  2735. if (NODE_JS) {
  2736. method = nodeWrap(method);
  2737. }
  2738. method.getCtx = method.create = function () {
  2739. return new Md5();
  2740. };
  2741. method.update = function (message) {
  2742. return method.create().update(message);
  2743. };
  2744. for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
  2745. var type = OUTPUT_TYPES[i];
  2746. method[type] = createOutputMethod(type);
  2747. }
  2748. return method;
  2749. };
  2750. var nodeWrap = function nodeWrap(method) {
  2751. var crypto = eval("require('crypto')");
  2752. var Buffer = eval("require('buffer').Buffer");
  2753. var nodeMethod = function nodeMethod(message) {
  2754. if (typeof message === 'string') {
  2755. return crypto.createHash('md5').update(message, 'utf8').digest('hex');
  2756. } else {
  2757. if (message === null || message === undefined) {
  2758. throw ERROR;
  2759. } else if (message.constructor === ArrayBuffer) {
  2760. message = new Uint8Array(message);
  2761. }
  2762. }
  2763. if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer) {
  2764. return crypto.createHash('md5').update(new Buffer(message)).digest('hex');
  2765. } else {
  2766. return method(message);
  2767. }
  2768. };
  2769. return nodeMethod;
  2770. };
  2771. /**
  2772. * Md5 class
  2773. * @class Md5
  2774. * @description This is internal class.
  2775. * @see {@link md5.create}
  2776. */
  2777. function Md5(sharedMemory) {
  2778. if (sharedMemory) {
  2779. blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
  2780. this.blocks = blocks;
  2781. this.buffer8 = buffer8;
  2782. } else {
  2783. if (ARRAY_BUFFER) {
  2784. var buffer = new ArrayBuffer(68);
  2785. this.buffer8 = new Uint8Array(buffer);
  2786. this.blocks = new Uint32Array(buffer);
  2787. } else {
  2788. this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  2789. }
  2790. }
  2791. this.h0 = this.h1 = this.h2 = this.h3 = this.start = this.bytes = this.hBytes = 0;
  2792. this.finalized = this.hashed = false;
  2793. this.first = true;
  2794. }
  2795. /**
  2796. * @method update
  2797. * @memberof Md5
  2798. * @instance
  2799. * @description Update hash
  2800. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  2801. * @returns {Md5} Md5 object.
  2802. * @see {@link md5.update}
  2803. */
  2804. Md5.prototype.update = function (message) {
  2805. if (this.finalized) {
  2806. return;
  2807. }
  2808. var notString,
  2809. type = typeof message === 'undefined' ? 'undefined' : _typeof(message);
  2810. if (type !== 'string') {
  2811. if (type === 'object') {
  2812. if (message === null) {
  2813. throw ERROR;
  2814. } else if (ARRAY_BUFFER && (message.constructor === ArrayBuffer || message.constructor.name === 'ArrayBuffer')) {
  2815. message = new Uint8Array(message);
  2816. } else if (!Array.isArray(message)) {
  2817. if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
  2818. throw ERROR;
  2819. }
  2820. }
  2821. } else {
  2822. throw ERROR;
  2823. }
  2824. notString = true;
  2825. }
  2826. var code,
  2827. index = 0,
  2828. i,
  2829. length = message.length,
  2830. blocks = this.blocks;
  2831. var buffer8 = this.buffer8;
  2832. while (index < length) {
  2833. if (this.hashed) {
  2834. this.hashed = false;
  2835. blocks[0] = blocks[16];
  2836. blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
  2837. }
  2838. if (notString) {
  2839. if (ARRAY_BUFFER) {
  2840. for (i = this.start; index < length && i < 64; ++index) {
  2841. buffer8[i++] = message[index];
  2842. }
  2843. } else {
  2844. for (i = this.start; index < length && i < 64; ++index) {
  2845. blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
  2846. }
  2847. }
  2848. } else {
  2849. if (ARRAY_BUFFER) {
  2850. for (i = this.start; index < length && i < 64; ++index) {
  2851. code = message.charCodeAt(index);
  2852. if (code < 0x80) {
  2853. buffer8[i++] = code;
  2854. } else if (code < 0x800) {
  2855. buffer8[i++] = 0xc0 | code >> 6;
  2856. buffer8[i++] = 0x80 | code & 0x3f;
  2857. } else if (code < 0xd800 || code >= 0xe000) {
  2858. buffer8[i++] = 0xe0 | code >> 12;
  2859. buffer8[i++] = 0x80 | code >> 6 & 0x3f;
  2860. buffer8[i++] = 0x80 | code & 0x3f;
  2861. } else {
  2862. code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
  2863. buffer8[i++] = 0xf0 | code >> 18;
  2864. buffer8[i++] = 0x80 | code >> 12 & 0x3f;
  2865. buffer8[i++] = 0x80 | code >> 6 & 0x3f;
  2866. buffer8[i++] = 0x80 | code & 0x3f;
  2867. }
  2868. }
  2869. } else {
  2870. for (i = this.start; index < length && i < 64; ++index) {
  2871. code = message.charCodeAt(index);
  2872. if (code < 0x80) {
  2873. blocks[i >> 2] |= code << SHIFT[i++ & 3];
  2874. } else if (code < 0x800) {
  2875. blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3];
  2876. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  2877. } else if (code < 0xd800 || code >= 0xe000) {
  2878. blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3];
  2879. blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
  2880. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  2881. } else {
  2882. code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
  2883. blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3];
  2884. blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3];
  2885. blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
  2886. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  2887. }
  2888. }
  2889. }
  2890. }
  2891. this.lastByteIndex = i;
  2892. this.bytes += i - this.start;
  2893. if (i >= 64) {
  2894. this.start = i - 64;
  2895. this.hash();
  2896. this.hashed = true;
  2897. } else {
  2898. this.start = i;
  2899. }
  2900. }
  2901. if (this.bytes > 4294967295) {
  2902. this.hBytes += this.bytes / 4294967296 << 0;
  2903. this.bytes = this.bytes % 4294967296;
  2904. }
  2905. return this;
  2906. };
  2907. Md5.prototype.finalize = function () {
  2908. if (this.finalized) {
  2909. return;
  2910. }
  2911. this.finalized = true;
  2912. var blocks = this.blocks,
  2913. i = this.lastByteIndex;
  2914. blocks[i >> 2] |= EXTRA[i & 3];
  2915. if (i >= 56) {
  2916. if (!this.hashed) {
  2917. this.hash();
  2918. }
  2919. blocks[0] = blocks[16];
  2920. blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
  2921. }
  2922. blocks[14] = this.bytes << 3;
  2923. blocks[15] = this.hBytes << 3 | this.bytes >>> 29;
  2924. this.hash();
  2925. };
  2926. Md5.prototype.hash = function () {
  2927. var a,
  2928. b,
  2929. c,
  2930. d,
  2931. bc,
  2932. da,
  2933. blocks = this.blocks;
  2934. if (this.first) {
  2935. a = blocks[0] - 680876937;
  2936. a = (a << 7 | a >>> 25) - 271733879 << 0;
  2937. d = (-1732584194 ^ a & 2004318071) + blocks[1] - 117830708;
  2938. d = (d << 12 | d >>> 20) + a << 0;
  2939. c = (-271733879 ^ d & (a ^ -271733879)) + blocks[2] - 1126478375;
  2940. c = (c << 17 | c >>> 15) + d << 0;
  2941. b = (a ^ c & (d ^ a)) + blocks[3] - 1316259209;
  2942. b = (b << 22 | b >>> 10) + c << 0;
  2943. } else {
  2944. a = this.h0;
  2945. b = this.h1;
  2946. c = this.h2;
  2947. d = this.h3;
  2948. a += (d ^ b & (c ^ d)) + blocks[0] - 680876936;
  2949. a = (a << 7 | a >>> 25) + b << 0;
  2950. d += (c ^ a & (b ^ c)) + blocks[1] - 389564586;
  2951. d = (d << 12 | d >>> 20) + a << 0;
  2952. c += (b ^ d & (a ^ b)) + blocks[2] + 606105819;
  2953. c = (c << 17 | c >>> 15) + d << 0;
  2954. b += (a ^ c & (d ^ a)) + blocks[3] - 1044525330;
  2955. b = (b << 22 | b >>> 10) + c << 0;
  2956. }
  2957. a += (d ^ b & (c ^ d)) + blocks[4] - 176418897;
  2958. a = (a << 7 | a >>> 25) + b << 0;
  2959. d += (c ^ a & (b ^ c)) + blocks[5] + 1200080426;
  2960. d = (d << 12 | d >>> 20) + a << 0;
  2961. c += (b ^ d & (a ^ b)) + blocks[6] - 1473231341;
  2962. c = (c << 17 | c >>> 15) + d << 0;
  2963. b += (a ^ c & (d ^ a)) + blocks[7] - 45705983;
  2964. b = (b << 22 | b >>> 10) + c << 0;
  2965. a += (d ^ b & (c ^ d)) + blocks[8] + 1770035416;
  2966. a = (a << 7 | a >>> 25) + b << 0;
  2967. d += (c ^ a & (b ^ c)) + blocks[9] - 1958414417;
  2968. d = (d << 12 | d >>> 20) + a << 0;
  2969. c += (b ^ d & (a ^ b)) + blocks[10] - 42063;
  2970. c = (c << 17 | c >>> 15) + d << 0;
  2971. b += (a ^ c & (d ^ a)) + blocks[11] - 1990404162;
  2972. b = (b << 22 | b >>> 10) + c << 0;
  2973. a += (d ^ b & (c ^ d)) + blocks[12] + 1804603682;
  2974. a = (a << 7 | a >>> 25) + b << 0;
  2975. d += (c ^ a & (b ^ c)) + blocks[13] - 40341101;
  2976. d = (d << 12 | d >>> 20) + a << 0;
  2977. c += (b ^ d & (a ^ b)) + blocks[14] - 1502002290;
  2978. c = (c << 17 | c >>> 15) + d << 0;
  2979. b += (a ^ c & (d ^ a)) + blocks[15] + 1236535329;
  2980. b = (b << 22 | b >>> 10) + c << 0;
  2981. a += (c ^ d & (b ^ c)) + blocks[1] - 165796510;
  2982. a = (a << 5 | a >>> 27) + b << 0;
  2983. d += (b ^ c & (a ^ b)) + blocks[6] - 1069501632;
  2984. d = (d << 9 | d >>> 23) + a << 0;
  2985. c += (a ^ b & (d ^ a)) + blocks[11] + 643717713;
  2986. c = (c << 14 | c >>> 18) + d << 0;
  2987. b += (d ^ a & (c ^ d)) + blocks[0] - 373897302;
  2988. b = (b << 20 | b >>> 12) + c << 0;
  2989. a += (c ^ d & (b ^ c)) + blocks[5] - 701558691;
  2990. a = (a << 5 | a >>> 27) + b << 0;
  2991. d += (b ^ c & (a ^ b)) + blocks[10] + 38016083;
  2992. d = (d << 9 | d >>> 23) + a << 0;
  2993. c += (a ^ b & (d ^ a)) + blocks[15] - 660478335;
  2994. c = (c << 14 | c >>> 18) + d << 0;
  2995. b += (d ^ a & (c ^ d)) + blocks[4] - 405537848;
  2996. b = (b << 20 | b >>> 12) + c << 0;
  2997. a += (c ^ d & (b ^ c)) + blocks[9] + 568446438;
  2998. a = (a << 5 | a >>> 27) + b << 0;
  2999. d += (b ^ c & (a ^ b)) + blocks[14] - 1019803690;
  3000. d = (d << 9 | d >>> 23) + a << 0;
  3001. c += (a ^ b & (d ^ a)) + blocks[3] - 187363961;
  3002. c = (c << 14 | c >>> 18) + d << 0;
  3003. b += (d ^ a & (c ^ d)) + blocks[8] + 1163531501;
  3004. b = (b << 20 | b >>> 12) + c << 0;
  3005. a += (c ^ d & (b ^ c)) + blocks[13] - 1444681467;
  3006. a = (a << 5 | a >>> 27) + b << 0;
  3007. d += (b ^ c & (a ^ b)) + blocks[2] - 51403784;
  3008. d = (d << 9 | d >>> 23) + a << 0;
  3009. c += (a ^ b & (d ^ a)) + blocks[7] + 1735328473;
  3010. c = (c << 14 | c >>> 18) + d << 0;
  3011. b += (d ^ a & (c ^ d)) + blocks[12] - 1926607734;
  3012. b = (b << 20 | b >>> 12) + c << 0;
  3013. bc = b ^ c;
  3014. a += (bc ^ d) + blocks[5] - 378558;
  3015. a = (a << 4 | a >>> 28) + b << 0;
  3016. d += (bc ^ a) + blocks[8] - 2022574463;
  3017. d = (d << 11 | d >>> 21) + a << 0;
  3018. da = d ^ a;
  3019. c += (da ^ b) + blocks[11] + 1839030562;
  3020. c = (c << 16 | c >>> 16) + d << 0;
  3021. b += (da ^ c) + blocks[14] - 35309556;
  3022. b = (b << 23 | b >>> 9) + c << 0;
  3023. bc = b ^ c;
  3024. a += (bc ^ d) + blocks[1] - 1530992060;
  3025. a = (a << 4 | a >>> 28) + b << 0;
  3026. d += (bc ^ a) + blocks[4] + 1272893353;
  3027. d = (d << 11 | d >>> 21) + a << 0;
  3028. da = d ^ a;
  3029. c += (da ^ b) + blocks[7] - 155497632;
  3030. c = (c << 16 | c >>> 16) + d << 0;
  3031. b += (da ^ c) + blocks[10] - 1094730640;
  3032. b = (b << 23 | b >>> 9) + c << 0;
  3033. bc = b ^ c;
  3034. a += (bc ^ d) + blocks[13] + 681279174;
  3035. a = (a << 4 | a >>> 28) + b << 0;
  3036. d += (bc ^ a) + blocks[0] - 358537222;
  3037. d = (d << 11 | d >>> 21) + a << 0;
  3038. da = d ^ a;
  3039. c += (da ^ b) + blocks[3] - 722521979;
  3040. c = (c << 16 | c >>> 16) + d << 0;
  3041. b += (da ^ c) + blocks[6] + 76029189;
  3042. b = (b << 23 | b >>> 9) + c << 0;
  3043. bc = b ^ c;
  3044. a += (bc ^ d) + blocks[9] - 640364487;
  3045. a = (a << 4 | a >>> 28) + b << 0;
  3046. d += (bc ^ a) + blocks[12] - 421815835;
  3047. d = (d << 11 | d >>> 21) + a << 0;
  3048. da = d ^ a;
  3049. c += (da ^ b) + blocks[15] + 530742520;
  3050. c = (c << 16 | c >>> 16) + d << 0;
  3051. b += (da ^ c) + blocks[2] - 995338651;
  3052. b = (b << 23 | b >>> 9) + c << 0;
  3053. a += (c ^ (b | ~d)) + blocks[0] - 198630844;
  3054. a = (a << 6 | a >>> 26) + b << 0;
  3055. d += (b ^ (a | ~c)) + blocks[7] + 1126891415;
  3056. d = (d << 10 | d >>> 22) + a << 0;
  3057. c += (a ^ (d | ~b)) + blocks[14] - 1416354905;
  3058. c = (c << 15 | c >>> 17) + d << 0;
  3059. b += (d ^ (c | ~a)) + blocks[5] - 57434055;
  3060. b = (b << 21 | b >>> 11) + c << 0;
  3061. a += (c ^ (b | ~d)) + blocks[12] + 1700485571;
  3062. a = (a << 6 | a >>> 26) + b << 0;
  3063. d += (b ^ (a | ~c)) + blocks[3] - 1894986606;
  3064. d = (d << 10 | d >>> 22) + a << 0;
  3065. c += (a ^ (d | ~b)) + blocks[10] - 1051523;
  3066. c = (c << 15 | c >>> 17) + d << 0;
  3067. b += (d ^ (c | ~a)) + blocks[1] - 2054922799;
  3068. b = (b << 21 | b >>> 11) + c << 0;
  3069. a += (c ^ (b | ~d)) + blocks[8] + 1873313359;
  3070. a = (a << 6 | a >>> 26) + b << 0;
  3071. d += (b ^ (a | ~c)) + blocks[15] - 30611744;
  3072. d = (d << 10 | d >>> 22) + a << 0;
  3073. c += (a ^ (d | ~b)) + blocks[6] - 1560198380;
  3074. c = (c << 15 | c >>> 17) + d << 0;
  3075. b += (d ^ (c | ~a)) + blocks[13] + 1309151649;
  3076. b = (b << 21 | b >>> 11) + c << 0;
  3077. a += (c ^ (b | ~d)) + blocks[4] - 145523070;
  3078. a = (a << 6 | a >>> 26) + b << 0;
  3079. d += (b ^ (a | ~c)) + blocks[11] - 1120210379;
  3080. d = (d << 10 | d >>> 22) + a << 0;
  3081. c += (a ^ (d | ~b)) + blocks[2] + 718787259;
  3082. c = (c << 15 | c >>> 17) + d << 0;
  3083. b += (d ^ (c | ~a)) + blocks[9] - 343485551;
  3084. b = (b << 21 | b >>> 11) + c << 0;
  3085. if (this.first) {
  3086. this.h0 = a + 1732584193 << 0;
  3087. this.h1 = b - 271733879 << 0;
  3088. this.h2 = c - 1732584194 << 0;
  3089. this.h3 = d + 271733878 << 0;
  3090. this.first = false;
  3091. } else {
  3092. this.h0 = this.h0 + a << 0;
  3093. this.h1 = this.h1 + b << 0;
  3094. this.h2 = this.h2 + c << 0;
  3095. this.h3 = this.h3 + d << 0;
  3096. }
  3097. };
  3098. /**
  3099. * @method hex
  3100. * @memberof Md5
  3101. * @instance
  3102. * @description Output hash as hex string
  3103. * @returns {String} Hex string
  3104. * @see {@link md5.hex}
  3105. * @example
  3106. * hash.hex();
  3107. */
  3108. Md5.prototype.hex = function () {
  3109. this.finalize();
  3110. var h0 = this.h0,
  3111. h1 = this.h1,
  3112. h2 = this.h2,
  3113. h3 = this.h3;
  3114. return HEX_CHARS[h0 >> 4 & 0x0F] + HEX_CHARS[h0 & 0x0F] + HEX_CHARS[h0 >> 12 & 0x0F] + HEX_CHARS[h0 >> 8 & 0x0F] + HEX_CHARS[h0 >> 20 & 0x0F] + HEX_CHARS[h0 >> 16 & 0x0F] + HEX_CHARS[h0 >> 28 & 0x0F] + HEX_CHARS[h0 >> 24 & 0x0F] + HEX_CHARS[h1 >> 4 & 0x0F] + HEX_CHARS[h1 & 0x0F] + HEX_CHARS[h1 >> 12 & 0x0F] + HEX_CHARS[h1 >> 8 & 0x0F] + HEX_CHARS[h1 >> 20 & 0x0F] + HEX_CHARS[h1 >> 16 & 0x0F] + HEX_CHARS[h1 >> 28 & 0x0F] + HEX_CHARS[h1 >> 24 & 0x0F] + HEX_CHARS[h2 >> 4 & 0x0F] + HEX_CHARS[h2 & 0x0F] + HEX_CHARS[h2 >> 12 & 0x0F] + HEX_CHARS[h2 >> 8 & 0x0F] + HEX_CHARS[h2 >> 20 & 0x0F] + HEX_CHARS[h2 >> 16 & 0x0F] + HEX_CHARS[h2 >> 28 & 0x0F] + HEX_CHARS[h2 >> 24 & 0x0F] + HEX_CHARS[h3 >> 4 & 0x0F] + HEX_CHARS[h3 & 0x0F] + HEX_CHARS[h3 >> 12 & 0x0F] + HEX_CHARS[h3 >> 8 & 0x0F] + HEX_CHARS[h3 >> 20 & 0x0F] + HEX_CHARS[h3 >> 16 & 0x0F] + HEX_CHARS[h3 >> 28 & 0x0F] + HEX_CHARS[h3 >> 24 & 0x0F];
  3115. };
  3116. /**
  3117. * @method toString
  3118. * @memberof Md5
  3119. * @instance
  3120. * @description Output hash as hex string
  3121. * @returns {String} Hex string
  3122. * @see {@link md5.hex}
  3123. * @example
  3124. * hash.toString();
  3125. */
  3126. Md5.prototype.toString = Md5.prototype.hex;
  3127. /**
  3128. * @method digest
  3129. * @memberof Md5
  3130. * @instance
  3131. * @description Output hash as bytes array
  3132. * @returns {Array} Bytes array
  3133. * @see {@link md5.digest}
  3134. * @example
  3135. * hash.digest();
  3136. */
  3137. Md5.prototype.digest = function () {
  3138. this.finalize();
  3139. var h0 = this.h0,
  3140. h1 = this.h1,
  3141. h2 = this.h2,
  3142. h3 = this.h3;
  3143. return [h0 & 0xFF, h0 >> 8 & 0xFF, h0 >> 16 & 0xFF, h0 >> 24 & 0xFF, h1 & 0xFF, h1 >> 8 & 0xFF, h1 >> 16 & 0xFF, h1 >> 24 & 0xFF, h2 & 0xFF, h2 >> 8 & 0xFF, h2 >> 16 & 0xFF, h2 >> 24 & 0xFF, h3 & 0xFF, h3 >> 8 & 0xFF, h3 >> 16 & 0xFF, h3 >> 24 & 0xFF];
  3144. };
  3145. /**
  3146. * @method array
  3147. * @memberof Md5
  3148. * @instance
  3149. * @description Output hash as bytes array
  3150. * @returns {Array} Bytes array
  3151. * @see {@link md5.array}
  3152. * @example
  3153. * hash.array();
  3154. */
  3155. Md5.prototype.array = Md5.prototype.digest;
  3156. /**
  3157. * @method arrayBuffer
  3158. * @memberof Md5
  3159. * @instance
  3160. * @description Output hash as ArrayBuffer
  3161. * @returns {ArrayBuffer} ArrayBuffer
  3162. * @see {@link md5.arrayBuffer}
  3163. * @example
  3164. * hash.arrayBuffer();
  3165. */
  3166. Md5.prototype.arrayBuffer = function () {
  3167. this.finalize();
  3168. var buffer = new ArrayBuffer(16);
  3169. var blocks = new Uint32Array(buffer);
  3170. blocks[0] = this.h0;
  3171. blocks[1] = this.h1;
  3172. blocks[2] = this.h2;
  3173. blocks[3] = this.h3;
  3174. return buffer;
  3175. };
  3176. /**
  3177. * @method buffer
  3178. * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.
  3179. * @memberof Md5
  3180. * @instance
  3181. * @description Output hash as ArrayBuffer
  3182. * @returns {ArrayBuffer} ArrayBuffer
  3183. * @see {@link md5.buffer}
  3184. * @example
  3185. * hash.buffer();
  3186. */
  3187. Md5.prototype.buffer = Md5.prototype.arrayBuffer;
  3188. /**
  3189. * @method base64
  3190. * @memberof Md5
  3191. * @instance
  3192. * @description Output hash as base64 string
  3193. * @returns {String} base64 string
  3194. * @see {@link md5.base64}
  3195. * @example
  3196. * hash.base64();
  3197. */
  3198. Md5.prototype.base64 = function () {
  3199. var v1,
  3200. v2,
  3201. v3,
  3202. base64Str = '',
  3203. bytes = this.array();
  3204. for (var i = 0; i < 15;) {
  3205. v1 = bytes[i++];
  3206. v2 = bytes[i++];
  3207. v3 = bytes[i++];
  3208. base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + BASE64_ENCODE_CHAR[(v1 << 4 | v2 >>> 4) & 63] + BASE64_ENCODE_CHAR[(v2 << 2 | v3 >>> 6) & 63] + BASE64_ENCODE_CHAR[v3 & 63];
  3209. }
  3210. v1 = bytes[i];
  3211. base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + BASE64_ENCODE_CHAR[v1 << 4 & 63] + '==';
  3212. return base64Str;
  3213. };
  3214. var exports = createMethod();
  3215. if (COMMON_JS) {
  3216. module.exports = exports;
  3217. } else {
  3218. /**
  3219. * @method md5
  3220. * @description Md5 hash function, export to global in browsers.
  3221. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  3222. * @returns {String} md5 hashes
  3223. * @example
  3224. * md5(''); // d41d8cd98f00b204e9800998ecf8427e
  3225. * md5('The quick brown fox jumps over the lazy dog'); // 9e107d9d372bb6826bd81d3542a419d6
  3226. * md5('The quick brown fox jumps over the lazy dog.'); // e4d909c290d0fb1ca068ffaddf22cbd0
  3227. *
  3228. * // It also supports UTF-8 encoding
  3229. * md5('中文'); // a7bac2239fcdcb3a067903d8077c4a07
  3230. *
  3231. * // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer`
  3232. * md5([]); // d41d8cd98f00b204e9800998ecf8427e
  3233. * md5(new Uint8Array([])); // d41d8cd98f00b204e9800998ecf8427e
  3234. */
  3235. root.md5 = exports;
  3236. if (AMD) {
  3237. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
  3238. return exports;
  3239. }).call(exports, __webpack_require__, exports, module),
  3240. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  3241. }
  3242. }
  3243. })();
  3244. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10), __webpack_require__(2), __webpack_require__(11)(module)))
  3245. /***/ }),
  3246. /* 10 */
  3247. /***/ (function(module, exports, __webpack_require__) {
  3248. "use strict";
  3249. // shim for using process in browser
  3250. var process = module.exports = {};
  3251. // cached from whatever global is present so that test runners that stub it
  3252. // don't break things. But we need to wrap it in a try catch in case it is
  3253. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3254. // function because try/catches deoptimize in certain engines.
  3255. var cachedSetTimeout;
  3256. var cachedClearTimeout;
  3257. function defaultSetTimout() {
  3258. throw new Error('setTimeout has not been defined');
  3259. }
  3260. function defaultClearTimeout() {
  3261. throw new Error('clearTimeout has not been defined');
  3262. }
  3263. (function () {
  3264. try {
  3265. if (typeof setTimeout === 'function') {
  3266. cachedSetTimeout = setTimeout;
  3267. } else {
  3268. cachedSetTimeout = defaultSetTimout;
  3269. }
  3270. } catch (e) {
  3271. cachedSetTimeout = defaultSetTimout;
  3272. }
  3273. try {
  3274. if (typeof clearTimeout === 'function') {
  3275. cachedClearTimeout = clearTimeout;
  3276. } else {
  3277. cachedClearTimeout = defaultClearTimeout;
  3278. }
  3279. } catch (e) {
  3280. cachedClearTimeout = defaultClearTimeout;
  3281. }
  3282. })();
  3283. function runTimeout(fun) {
  3284. if (cachedSetTimeout === setTimeout) {
  3285. //normal enviroments in sane situations
  3286. return setTimeout(fun, 0);
  3287. }
  3288. // if setTimeout wasn't available but was latter defined
  3289. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3290. cachedSetTimeout = setTimeout;
  3291. return setTimeout(fun, 0);
  3292. }
  3293. try {
  3294. // when when somebody has screwed with setTimeout but no I.E. maddness
  3295. return cachedSetTimeout(fun, 0);
  3296. } catch (e) {
  3297. try {
  3298. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3299. return cachedSetTimeout.call(null, fun, 0);
  3300. } catch (e) {
  3301. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  3302. return cachedSetTimeout.call(this, fun, 0);
  3303. }
  3304. }
  3305. }
  3306. function runClearTimeout(marker) {
  3307. if (cachedClearTimeout === clearTimeout) {
  3308. //normal enviroments in sane situations
  3309. return clearTimeout(marker);
  3310. }
  3311. // if clearTimeout wasn't available but was latter defined
  3312. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3313. cachedClearTimeout = clearTimeout;
  3314. return clearTimeout(marker);
  3315. }
  3316. try {
  3317. // when when somebody has screwed with setTimeout but no I.E. maddness
  3318. return cachedClearTimeout(marker);
  3319. } catch (e) {
  3320. try {
  3321. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3322. return cachedClearTimeout.call(null, marker);
  3323. } catch (e) {
  3324. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  3325. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3326. return cachedClearTimeout.call(this, marker);
  3327. }
  3328. }
  3329. }
  3330. var queue = [];
  3331. var draining = false;
  3332. var currentQueue;
  3333. var queueIndex = -1;
  3334. function cleanUpNextTick() {
  3335. if (!draining || !currentQueue) {
  3336. return;
  3337. }
  3338. draining = false;
  3339. if (currentQueue.length) {
  3340. queue = currentQueue.concat(queue);
  3341. } else {
  3342. queueIndex = -1;
  3343. }
  3344. if (queue.length) {
  3345. drainQueue();
  3346. }
  3347. }
  3348. function drainQueue() {
  3349. if (draining) {
  3350. return;
  3351. }
  3352. var timeout = runTimeout(cleanUpNextTick);
  3353. draining = true;
  3354. var len = queue.length;
  3355. while (len) {
  3356. currentQueue = queue;
  3357. queue = [];
  3358. while (++queueIndex < len) {
  3359. if (currentQueue) {
  3360. currentQueue[queueIndex].run();
  3361. }
  3362. }
  3363. queueIndex = -1;
  3364. len = queue.length;
  3365. }
  3366. currentQueue = null;
  3367. draining = false;
  3368. runClearTimeout(timeout);
  3369. }
  3370. process.nextTick = function (fun) {
  3371. var args = new Array(arguments.length - 1);
  3372. if (arguments.length > 1) {
  3373. for (var i = 1; i < arguments.length; i++) {
  3374. args[i - 1] = arguments[i];
  3375. }
  3376. }
  3377. queue.push(new Item(fun, args));
  3378. if (queue.length === 1 && !draining) {
  3379. runTimeout(drainQueue);
  3380. }
  3381. };
  3382. // v8 likes predictible objects
  3383. function Item(fun, array) {
  3384. this.fun = fun;
  3385. this.array = array;
  3386. }
  3387. Item.prototype.run = function () {
  3388. this.fun.apply(null, this.array);
  3389. };
  3390. process.title = 'browser';
  3391. process.browser = true;
  3392. process.env = {};
  3393. process.argv = [];
  3394. process.version = ''; // empty string to avoid regexp issues
  3395. process.versions = {};
  3396. function noop() {}
  3397. process.on = noop;
  3398. process.addListener = noop;
  3399. process.once = noop;
  3400. process.off = noop;
  3401. process.removeListener = noop;
  3402. process.removeAllListeners = noop;
  3403. process.emit = noop;
  3404. process.prependListener = noop;
  3405. process.prependOnceListener = noop;
  3406. process.listeners = function (name) {
  3407. return [];
  3408. };
  3409. process.binding = function (name) {
  3410. throw new Error('process.binding is not supported');
  3411. };
  3412. process.cwd = function () {
  3413. return '/';
  3414. };
  3415. process.chdir = function (dir) {
  3416. throw new Error('process.chdir is not supported');
  3417. };
  3418. process.umask = function () {
  3419. return 0;
  3420. };
  3421. /***/ }),
  3422. /* 11 */
  3423. /***/ (function(module, exports, __webpack_require__) {
  3424. "use strict";
  3425. module.exports = function (module) {
  3426. if (!module.webpackPolyfill) {
  3427. module.deprecate = function () {};
  3428. module.paths = [];
  3429. // module.parent = undefined by default
  3430. if (!module.children) module.children = [];
  3431. Object.defineProperty(module, "loaded", {
  3432. enumerable: true,
  3433. get: function get() {
  3434. return module.l;
  3435. }
  3436. });
  3437. Object.defineProperty(module, "id", {
  3438. enumerable: true,
  3439. get: function get() {
  3440. return module.i;
  3441. }
  3442. });
  3443. module.webpackPolyfill = 1;
  3444. }
  3445. return module;
  3446. };
  3447. /***/ }),
  3448. /* 12 */
  3449. /***/ (function(module, exports) {
  3450. /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
  3451. module.exports = __webpack_amd_options__;
  3452. /* WEBPACK VAR INJECTION */}.call(exports, {}))
  3453. /***/ }),
  3454. /* 13 */
  3455. /***/ (function(module, exports, __webpack_require__) {
  3456. "use strict";
  3457. /*
  3458. CryptoJS v3.1.2
  3459. code.google.com/p/crypto-js
  3460. (c) 2009-2013 by Jeff Mott. All rights reserved.
  3461. code.google.com/p/crypto-js/wiki/License
  3462. */
  3463. var CryptoJS = CryptoJS || function (g, l) {
  3464. var e = {},
  3465. d = e.lib = {},
  3466. m = function m() {},
  3467. k = d.Base = { extend: function extend(a) {
  3468. m.prototype = this;var c = new m();a && c.mixIn(a);c.hasOwnProperty("init") || (c.init = function () {
  3469. c.$super.init.apply(this, arguments);
  3470. });c.init.prototype = c;c.$super = this;return c;
  3471. }, create: function create() {
  3472. var a = this.extend();a.init.apply(a, arguments);return a;
  3473. }, init: function init() {}, mixIn: function mixIn(a) {
  3474. for (var c in a) {
  3475. a.hasOwnProperty(c) && (this[c] = a[c]);
  3476. }a.hasOwnProperty("toString") && (this.toString = a.toString);
  3477. }, clone: function clone() {
  3478. return this.init.prototype.extend(this);
  3479. } },
  3480. p = d.WordArray = k.extend({ init: function init(a, c) {
  3481. a = this.words = a || [];this.sigBytes = c != l ? c : 4 * a.length;
  3482. }, toString: function toString(a) {
  3483. return (a || n).stringify(this);
  3484. }, concat: function concat(a) {
  3485. var c = this.words,
  3486. q = a.words,
  3487. f = this.sigBytes;a = a.sigBytes;this.clamp();if (f % 4) for (var b = 0; b < a; b++) {
  3488. c[f + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((f + b) % 4);
  3489. } else if (65535 < q.length) for (b = 0; b < a; b += 4) {
  3490. c[f + b >>> 2] = q[b >>> 2];
  3491. } else c.push.apply(c, q);this.sigBytes += a;return this;
  3492. }, clamp: function clamp() {
  3493. var a = this.words,
  3494. c = this.sigBytes;a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4);a.length = g.ceil(c / 4);
  3495. }, clone: function clone() {
  3496. var a = k.clone.call(this);a.words = this.words.slice(0);return a;
  3497. }, random: function random(a) {
  3498. for (var c = [], b = 0; b < a; b += 4) {
  3499. c.push(4294967296 * g.random() | 0);
  3500. }return new p.init(c, a);
  3501. } }),
  3502. b = e.enc = {},
  3503. n = b.Hex = { stringify: function stringify(a) {
  3504. var c = a.words;a = a.sigBytes;for (var b = [], f = 0; f < a; f++) {
  3505. var d = c[f >>> 2] >>> 24 - 8 * (f % 4) & 255;b.push((d >>> 4).toString(16));b.push((d & 15).toString(16));
  3506. }return b.join("");
  3507. }, parse: function parse(a) {
  3508. for (var c = a.length, b = [], f = 0; f < c; f += 2) {
  3509. b[f >>> 3] |= parseInt(a.substr(f, 2), 16) << 24 - 4 * (f % 8);
  3510. }return new p.init(b, c / 2);
  3511. } },
  3512. j = b.Latin1 = { stringify: function stringify(a) {
  3513. var c = a.words;a = a.sigBytes;for (var b = [], f = 0; f < a; f++) {
  3514. b.push(String.fromCharCode(c[f >>> 2] >>> 24 - 8 * (f % 4) & 255));
  3515. }return b.join("");
  3516. }, parse: function parse(a) {
  3517. for (var c = a.length, b = [], f = 0; f < c; f++) {
  3518. b[f >>> 2] |= (a.charCodeAt(f) & 255) << 24 - 8 * (f % 4);
  3519. }return new p.init(b, c);
  3520. } },
  3521. h = b.Utf8 = { stringify: function stringify(a) {
  3522. try {
  3523. return decodeURIComponent(escape(j.stringify(a)));
  3524. } catch (c) {
  3525. throw Error("Malformed UTF-8 data");
  3526. }
  3527. }, parse: function parse(a) {
  3528. return j.parse(unescape(encodeURIComponent(a)));
  3529. } },
  3530. r = d.BufferedBlockAlgorithm = k.extend({ reset: function reset() {
  3531. this._data = new p.init();this._nDataBytes = 0;
  3532. }, _append: function _append(a) {
  3533. "string" == typeof a && (a = h.parse(a));this._data.concat(a);this._nDataBytes += a.sigBytes;
  3534. }, _process: function _process(a) {
  3535. var c = this._data,
  3536. b = c.words,
  3537. f = c.sigBytes,
  3538. d = this.blockSize,
  3539. e = f / (4 * d),
  3540. e = a ? g.ceil(e) : g.max((e | 0) - this._minBufferSize, 0);a = e * d;f = g.min(4 * a, f);if (a) {
  3541. for (var k = 0; k < a; k += d) {
  3542. this._doProcessBlock(b, k);
  3543. }k = b.splice(0, a);c.sigBytes -= f;
  3544. }return new p.init(k, f);
  3545. }, clone: function clone() {
  3546. var a = k.clone.call(this);
  3547. a._data = this._data.clone();return a;
  3548. }, _minBufferSize: 0 });d.Hasher = r.extend({ cfg: k.extend(), init: function init(a) {
  3549. this.cfg = this.cfg.extend(a);this.reset();
  3550. }, reset: function reset() {
  3551. r.reset.call(this);this._doReset();
  3552. }, update: function update(a) {
  3553. this._append(a);this._process();return this;
  3554. }, finalize: function finalize(a) {
  3555. a && this._append(a);return this._doFinalize();
  3556. }, blockSize: 16, _createHelper: function _createHelper(a) {
  3557. return function (b, d) {
  3558. return new a.init(d).finalize(b);
  3559. };
  3560. }, _createHmacHelper: function _createHmacHelper(a) {
  3561. return function (b, d) {
  3562. return new s.HMAC.init(a, d).finalize(b);
  3563. };
  3564. } });var s = e.algo = {};return e;
  3565. }(Math);
  3566. (function () {
  3567. var g = CryptoJS,
  3568. l = g.lib,
  3569. e = l.WordArray,
  3570. d = l.Hasher,
  3571. m = [],
  3572. l = g.algo.SHA1 = d.extend({ _doReset: function _doReset() {
  3573. this._hash = new e.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
  3574. }, _doProcessBlock: function _doProcessBlock(d, e) {
  3575. for (var b = this._hash.words, n = b[0], j = b[1], h = b[2], g = b[3], l = b[4], a = 0; 80 > a; a++) {
  3576. if (16 > a) m[a] = d[e + a] | 0;else {
  3577. var c = m[a - 3] ^ m[a - 8] ^ m[a - 14] ^ m[a - 16];m[a] = c << 1 | c >>> 31;
  3578. }c = (n << 5 | n >>> 27) + l + m[a];c = 20 > a ? c + ((j & h | ~j & g) + 1518500249) : 40 > a ? c + ((j ^ h ^ g) + 1859775393) : 60 > a ? c + ((j & h | j & g | h & g) - 1894007588) : c + ((j ^ h ^ g) - 899497514);l = g;g = h;h = j << 30 | j >>> 2;j = n;n = c;
  3579. }b[0] = b[0] + n | 0;b[1] = b[1] + j | 0;b[2] = b[2] + h | 0;b[3] = b[3] + g | 0;b[4] = b[4] + l | 0;
  3580. }, _doFinalize: function _doFinalize() {
  3581. var d = this._data,
  3582. e = d.words,
  3583. b = 8 * this._nDataBytes,
  3584. g = 8 * d.sigBytes;e[g >>> 5] |= 128 << 24 - g % 32;e[(g + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296);e[(g + 64 >>> 9 << 4) + 15] = b;d.sigBytes = 4 * e.length;this._process();return this._hash;
  3585. }, clone: function clone() {
  3586. var e = d.clone.call(this);e._hash = this._hash.clone();return e;
  3587. } });g.SHA1 = d._createHelper(l);g.HmacSHA1 = d._createHmacHelper(l);
  3588. })();
  3589. (function () {
  3590. var g = CryptoJS,
  3591. l = g.enc.Utf8;g.algo.HMAC = g.lib.Base.extend({ init: function init(e, d) {
  3592. e = this._hasher = new e.init();"string" == typeof d && (d = l.parse(d));var g = e.blockSize,
  3593. k = 4 * g;d.sigBytes > k && (d = e.finalize(d));d.clamp();for (var p = this._oKey = d.clone(), b = this._iKey = d.clone(), n = p.words, j = b.words, h = 0; h < g; h++) {
  3594. n[h] ^= 1549556828, j[h] ^= 909522486;
  3595. }p.sigBytes = b.sigBytes = k;this.reset();
  3596. }, reset: function reset() {
  3597. var e = this._hasher;e.reset();e.update(this._iKey);
  3598. }, update: function update(e) {
  3599. this._hasher.update(e);return this;
  3600. }, finalize: function finalize(e) {
  3601. var d = this._hasher;e = d.finalize(e);d.reset();return d.finalize(this._oKey.clone().concat(e));
  3602. } });
  3603. })();
  3604. (function () {
  3605. // Shortcuts
  3606. var C = CryptoJS;
  3607. var C_lib = C.lib;
  3608. var WordArray = C_lib.WordArray;
  3609. var C_enc = C.enc;
  3610. /**
  3611. * Base64 encoding strategy.
  3612. */
  3613. var Base64 = C_enc.Base64 = {
  3614. /**
  3615. * Converts a word array to a Base64 string.
  3616. *
  3617. * @param {WordArray} wordArray The word array.
  3618. *
  3619. * @return {string} The Base64 string.
  3620. *
  3621. * @static
  3622. *
  3623. * @example
  3624. *
  3625. * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
  3626. */
  3627. stringify: function stringify(wordArray) {
  3628. // Shortcuts
  3629. var words = wordArray.words;
  3630. var sigBytes = wordArray.sigBytes;
  3631. var map = this._map;
  3632. // Clamp excess bits
  3633. wordArray.clamp();
  3634. // Convert
  3635. var base64Chars = [];
  3636. for (var i = 0; i < sigBytes; i += 3) {
  3637. var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
  3638. var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 0xff;
  3639. var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 0xff;
  3640. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  3641. for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) {
  3642. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 0x3f));
  3643. }
  3644. }
  3645. // Add padding
  3646. var paddingChar = map.charAt(64);
  3647. if (paddingChar) {
  3648. while (base64Chars.length % 4) {
  3649. base64Chars.push(paddingChar);
  3650. }
  3651. }
  3652. return base64Chars.join('');
  3653. },
  3654. /**
  3655. * Converts a Base64 string to a word array.
  3656. *
  3657. * @param {string} base64Str The Base64 string.
  3658. *
  3659. * @return {WordArray} The word array.
  3660. *
  3661. * @static
  3662. *
  3663. * @example
  3664. *
  3665. * var wordArray = CryptoJS.enc.Base64.parse(base64String);
  3666. */
  3667. parse: function parse(base64Str) {
  3668. // Shortcuts
  3669. var base64StrLength = base64Str.length;
  3670. var map = this._map;
  3671. // Ignore padding
  3672. var paddingChar = map.charAt(64);
  3673. if (paddingChar) {
  3674. var paddingIndex = base64Str.indexOf(paddingChar);
  3675. if (paddingIndex != -1) {
  3676. base64StrLength = paddingIndex;
  3677. }
  3678. }
  3679. // Convert
  3680. var words = [];
  3681. var nBytes = 0;
  3682. for (var i = 0; i < base64StrLength; i++) {
  3683. if (i % 4) {
  3684. var bits1 = map.indexOf(base64Str.charAt(i - 1)) << i % 4 * 2;
  3685. var bits2 = map.indexOf(base64Str.charAt(i)) >>> 6 - i % 4 * 2;
  3686. words[nBytes >>> 2] |= (bits1 | bits2) << 24 - nBytes % 4 * 8;
  3687. nBytes++;
  3688. }
  3689. }
  3690. return WordArray.create(words, nBytes);
  3691. },
  3692. _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  3693. };
  3694. })();
  3695. module.exports = CryptoJS;
  3696. /***/ }),
  3697. /* 14 */
  3698. /***/ (function(module, exports, __webpack_require__) {
  3699. "use strict";
  3700. /*
  3701. Copyright 2011-2013 Abdulla Abdurakhmanov
  3702. Original sources are available at https://code.google.com/p/x2js/
  3703. Licensed under the Apache License, Version 2.0 (the "License");
  3704. you may not use this file except in compliance with the License.
  3705. You may obtain a copy of the License at
  3706. http://www.apache.org/licenses/LICENSE-2.0
  3707. Unless required by applicable law or agreed to in writing, software
  3708. distributed under the License is distributed on an "AS IS" BASIS,
  3709. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3710. See the License for the specific language governing permissions and
  3711. limitations under the License.
  3712. */
  3713. var DOMParser = __webpack_require__(15).DOMParser;
  3714. var x2js = function x2js(config) {
  3715. 'use strict';
  3716. var VERSION = "1.2.0";
  3717. config = config || {};
  3718. initConfigDefaults();
  3719. initRequiredPolyfills();
  3720. function initConfigDefaults() {
  3721. if (config.escapeMode === undefined) {
  3722. config.escapeMode = true;
  3723. }
  3724. config.attributePrefix = config.attributePrefix || "_";
  3725. config.arrayAccessForm = config.arrayAccessForm || "none";
  3726. config.emptyNodeForm = config.emptyNodeForm || "text";
  3727. if (config.enableToStringFunc === undefined) {
  3728. config.enableToStringFunc = true;
  3729. }
  3730. config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
  3731. if (config.skipEmptyTextNodesForObj === undefined) {
  3732. config.skipEmptyTextNodesForObj = true;
  3733. }
  3734. if (config.stripWhitespaces === undefined) {
  3735. config.stripWhitespaces = true;
  3736. }
  3737. config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
  3738. if (config.useDoubleQuotes === undefined) {
  3739. config.useDoubleQuotes = false;
  3740. }
  3741. config.xmlElementsFilter = config.xmlElementsFilter || [];
  3742. config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];
  3743. if (config.keepCData === undefined) {
  3744. config.keepCData = false;
  3745. }
  3746. }
  3747. var DOMNodeTypes = {
  3748. ELEMENT_NODE: 1,
  3749. TEXT_NODE: 3,
  3750. CDATA_SECTION_NODE: 4,
  3751. COMMENT_NODE: 8,
  3752. DOCUMENT_NODE: 9
  3753. };
  3754. function initRequiredPolyfills() {}
  3755. function getNodeLocalName(node) {
  3756. var nodeLocalName = node.localName;
  3757. if (nodeLocalName == null) // Yeah, this is IE!!
  3758. nodeLocalName = node.baseName;
  3759. if (nodeLocalName == null || nodeLocalName == "") // =="" is IE too
  3760. nodeLocalName = node.nodeName;
  3761. return nodeLocalName;
  3762. }
  3763. function getNodePrefix(node) {
  3764. return node.prefix;
  3765. }
  3766. function escapeXmlChars(str) {
  3767. if (typeof str == "string") return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');else return str;
  3768. }
  3769. function unescapeXmlChars(str) {
  3770. return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
  3771. }
  3772. function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
  3773. var idx = 0;
  3774. for (; idx < stdFiltersArrayForm.length; idx++) {
  3775. var filterPath = stdFiltersArrayForm[idx];
  3776. if (typeof filterPath === "string") {
  3777. if (filterPath == path) break;
  3778. } else if (filterPath instanceof RegExp) {
  3779. if (filterPath.test(path)) break;
  3780. } else if (typeof filterPath === "function") {
  3781. if (filterPath(obj, name, path)) break;
  3782. }
  3783. }
  3784. return idx != stdFiltersArrayForm.length;
  3785. }
  3786. function toArrayAccessForm(obj, childName, path) {
  3787. switch (config.arrayAccessForm) {
  3788. case "property":
  3789. if (!(obj[childName] instanceof Array)) obj[childName + "_asArray"] = [obj[childName]];else obj[childName + "_asArray"] = obj[childName];
  3790. break;
  3791. /*case "none":
  3792. break;*/
  3793. }
  3794. if (!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
  3795. if (checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
  3796. obj[childName] = [obj[childName]];
  3797. }
  3798. }
  3799. }
  3800. function fromXmlDateTime(prop) {
  3801. // Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
  3802. // Improved to support full spec and optional parts
  3803. var bits = prop.split(/[-T:+Z]/g);
  3804. var d = new Date(bits[0], bits[1] - 1, bits[2]);
  3805. var secondBits = bits[5].split("\.");
  3806. d.setHours(bits[3], bits[4], secondBits[0]);
  3807. if (secondBits.length > 1) d.setMilliseconds(secondBits[1]);
  3808. // Get supplied time zone offset in minutes
  3809. if (bits[6] && bits[7]) {
  3810. var offsetMinutes = bits[6] * 60 + Number(bits[7]);
  3811. var sign = /\d\d-\d\d:\d\d$/.test(prop) ? '-' : '+';
  3812. // Apply the sign
  3813. offsetMinutes = 0 + (sign == '-' ? -1 * offsetMinutes : offsetMinutes);
  3814. // Apply offset and local timezone
  3815. d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset());
  3816. } else if (prop.indexOf("Z", prop.length - 1) !== -1) {
  3817. d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
  3818. }
  3819. // d is now a local time equivalent to the supplied time
  3820. return d;
  3821. }
  3822. function checkFromXmlDateTimePaths(value, childName, fullPath) {
  3823. if (config.datetimeAccessFormPaths.length > 0) {
  3824. var path = fullPath.split("\.#")[0];
  3825. if (checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
  3826. return fromXmlDateTime(value);
  3827. } else return value;
  3828. } else return value;
  3829. }
  3830. function checkXmlElementsFilter(obj, childType, childName, childPath) {
  3831. if (childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
  3832. return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
  3833. } else return true;
  3834. }
  3835. function parseDOMChildren(node, path) {
  3836. if (node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
  3837. var result = new Object();
  3838. var nodeChildren = node.childNodes;
  3839. // Alternative for firstElementChild which is not supported in some environments
  3840. for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
  3841. var child = nodeChildren.item(cidx);
  3842. if (child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
  3843. var childName = getNodeLocalName(child);
  3844. result[childName] = parseDOMChildren(child, childName);
  3845. }
  3846. }
  3847. return result;
  3848. } else if (node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
  3849. var result = new Object();
  3850. result.__cnt = 0;
  3851. var nodeChildren = node.childNodes;
  3852. // Children nodes
  3853. for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
  3854. var child = nodeChildren.item(cidx); // nodeChildren[cidx];
  3855. var childName = getNodeLocalName(child);
  3856. if (child.nodeType != DOMNodeTypes.COMMENT_NODE) {
  3857. var childPath = path + "." + childName;
  3858. if (checkXmlElementsFilter(result, child.nodeType, childName, childPath)) {
  3859. result.__cnt++;
  3860. if (result[childName] == null) {
  3861. result[childName] = parseDOMChildren(child, childPath);
  3862. toArrayAccessForm(result, childName, childPath);
  3863. } else {
  3864. if (result[childName] != null) {
  3865. if (!(result[childName] instanceof Array)) {
  3866. result[childName] = [result[childName]];
  3867. toArrayAccessForm(result, childName, childPath);
  3868. }
  3869. }
  3870. result[childName][result[childName].length] = parseDOMChildren(child, childPath);
  3871. }
  3872. }
  3873. }
  3874. }
  3875. // Attributes
  3876. for (var aidx = 0; aidx < node.attributes.length; aidx++) {
  3877. var attr = node.attributes.item(aidx); // [aidx];
  3878. result.__cnt++;
  3879. result[config.attributePrefix + attr.name] = attr.value;
  3880. }
  3881. // Node namespace prefix
  3882. var nodePrefix = getNodePrefix(node);
  3883. if (nodePrefix != null && nodePrefix != "") {
  3884. result.__cnt++;
  3885. result.__prefix = nodePrefix;
  3886. }
  3887. if (result["#text"] != null) {
  3888. result.__text = result["#text"];
  3889. if (result.__text instanceof Array) {
  3890. result.__text = result.__text.join("\n");
  3891. }
  3892. //if(config.escapeMode)
  3893. // result.__text = unescapeXmlChars(result.__text);
  3894. if (config.stripWhitespaces) result.__text = result.__text.trim();
  3895. delete result["#text"];
  3896. if (config.arrayAccessForm == "property") delete result["#text_asArray"];
  3897. result.__text = checkFromXmlDateTimePaths(result.__text, childName, path + "." + childName);
  3898. }
  3899. if (result["#cdata-section"] != null) {
  3900. result.__cdata = result["#cdata-section"];
  3901. delete result["#cdata-section"];
  3902. if (config.arrayAccessForm == "property") delete result["#cdata-section_asArray"];
  3903. }
  3904. if (result.__cnt == 0 && config.emptyNodeForm == "text") {
  3905. result = '';
  3906. } else if (result.__cnt == 1 && result.__text != null) {
  3907. result = result.__text;
  3908. } else if (result.__cnt == 1 && result.__cdata != null && !config.keepCData) {
  3909. result = result.__cdata;
  3910. } else if (result.__cnt > 1 && result.__text != null && config.skipEmptyTextNodesForObj) {
  3911. if (config.stripWhitespaces && result.__text == "" || result.__text.trim() == "") {
  3912. delete result.__text;
  3913. }
  3914. }
  3915. delete result.__cnt;
  3916. if (config.enableToStringFunc && (result.__text != null || result.__cdata != null)) {
  3917. result.toString = function () {
  3918. return (this.__text != null ? this.__text : '') + (this.__cdata != null ? this.__cdata : '');
  3919. };
  3920. }
  3921. return result;
  3922. } else if (node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
  3923. return node.nodeValue;
  3924. }
  3925. }
  3926. function startTag(jsonObj, element, attrList, closed) {
  3927. var resultStr = "<" + (jsonObj != null && jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + element;
  3928. if (attrList != null) {
  3929. for (var aidx = 0; aidx < attrList.length; aidx++) {
  3930. var attrName = attrList[aidx];
  3931. var attrVal = jsonObj[attrName];
  3932. if (config.escapeMode) attrVal = escapeXmlChars(attrVal);
  3933. resultStr += " " + attrName.substr(config.attributePrefix.length) + "=";
  3934. if (config.useDoubleQuotes) resultStr += '"' + attrVal + '"';else resultStr += "'" + attrVal + "'";
  3935. }
  3936. }
  3937. if (!closed) resultStr += ">";else resultStr += "/>";
  3938. return resultStr;
  3939. }
  3940. function endTag(jsonObj, elementName) {
  3941. return "</" + (jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + elementName + ">";
  3942. }
  3943. function endsWith(str, suffix) {
  3944. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  3945. }
  3946. function jsonXmlSpecialElem(jsonObj, jsonObjField) {
  3947. if (config.arrayAccessForm == "property" && endsWith(jsonObjField.toString(), "_asArray") || jsonObjField.toString().indexOf(config.attributePrefix) == 0 || jsonObjField.toString().indexOf("__") == 0 || jsonObj[jsonObjField] instanceof Function) return true;else return false;
  3948. }
  3949. function jsonXmlElemCount(jsonObj) {
  3950. var elementsCnt = 0;
  3951. if (jsonObj instanceof Object) {
  3952. for (var it in jsonObj) {
  3953. if (jsonXmlSpecialElem(jsonObj, it)) continue;
  3954. elementsCnt++;
  3955. }
  3956. }
  3957. return elementsCnt;
  3958. }
  3959. function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
  3960. return config.jsonPropertiesFilter.length == 0 || jsonObjPath == "" || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
  3961. }
  3962. function parseJSONAttributes(jsonObj) {
  3963. var attrList = [];
  3964. if (jsonObj instanceof Object) {
  3965. for (var ait in jsonObj) {
  3966. if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) {
  3967. attrList.push(ait);
  3968. }
  3969. }
  3970. }
  3971. return attrList;
  3972. }
  3973. function parseJSONTextAttrs(jsonTxtObj) {
  3974. var result = "";
  3975. if (jsonTxtObj.__cdata != null) {
  3976. result += "<![CDATA[" + jsonTxtObj.__cdata + "]]>";
  3977. }
  3978. if (jsonTxtObj.__text != null) {
  3979. if (config.escapeMode) result += escapeXmlChars(jsonTxtObj.__text);else result += jsonTxtObj.__text;
  3980. }
  3981. return result;
  3982. }
  3983. function parseJSONTextObject(jsonTxtObj) {
  3984. var result = "";
  3985. if (jsonTxtObj instanceof Object) {
  3986. result += parseJSONTextAttrs(jsonTxtObj);
  3987. } else if (jsonTxtObj != null) {
  3988. if (config.escapeMode) result += escapeXmlChars(jsonTxtObj);else result += jsonTxtObj;
  3989. }
  3990. return result;
  3991. }
  3992. function getJsonPropertyPath(jsonObjPath, jsonPropName) {
  3993. if (jsonObjPath === "") {
  3994. return jsonPropName;
  3995. } else return jsonObjPath + "." + jsonPropName;
  3996. }
  3997. function parseJSONArray(jsonArrRoot, jsonArrObj, attrList, jsonObjPath) {
  3998. var result = "";
  3999. if (jsonArrRoot.length == 0) {
  4000. result += startTag(jsonArrRoot, jsonArrObj, attrList, true);
  4001. } else {
  4002. for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
  4003. result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
  4004. result += parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath, jsonArrObj));
  4005. result += endTag(jsonArrRoot[arIdx], jsonArrObj);
  4006. }
  4007. }
  4008. return result;
  4009. }
  4010. function parseJSONObject(jsonObj, jsonObjPath) {
  4011. var result = "";
  4012. var elementsCnt = jsonXmlElemCount(jsonObj);
  4013. if (elementsCnt > 0) {
  4014. for (var it in jsonObj) {
  4015. if (jsonXmlSpecialElem(jsonObj, it) || jsonObjPath != "" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath, it))) continue;
  4016. var subObj = jsonObj[it];
  4017. var attrList = parseJSONAttributes(subObj);
  4018. if (subObj == null || subObj == undefined) {
  4019. result += startTag(subObj, it, attrList, true);
  4020. } else if (subObj instanceof Object) {
  4021. if (subObj instanceof Array) {
  4022. result += parseJSONArray(subObj, it, attrList, jsonObjPath);
  4023. } else if (subObj instanceof Date) {
  4024. result += startTag(subObj, it, attrList, false);
  4025. result += subObj.toISOString();
  4026. result += endTag(subObj, it);
  4027. } else {
  4028. var subObjElementsCnt = jsonXmlElemCount(subObj);
  4029. if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) {
  4030. result += startTag(subObj, it, attrList, false);
  4031. result += parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath, it));
  4032. result += endTag(subObj, it);
  4033. } else {
  4034. result += startTag(subObj, it, attrList, true);
  4035. }
  4036. }
  4037. } else {
  4038. result += startTag(subObj, it, attrList, false);
  4039. result += parseJSONTextObject(subObj);
  4040. result += endTag(subObj, it);
  4041. }
  4042. }
  4043. }
  4044. result += parseJSONTextObject(jsonObj);
  4045. return result;
  4046. }
  4047. this.parseXmlString = function (xmlDocStr) {
  4048. // var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
  4049. var isIEParser = false;
  4050. if (xmlDocStr === undefined) {
  4051. return null;
  4052. }
  4053. var xmlDoc;
  4054. if (DOMParser) {
  4055. var parser = new DOMParser();
  4056. var parsererrorNS = null;
  4057. // IE9+ now is here
  4058. if (!isIEParser) {
  4059. try {
  4060. parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
  4061. } catch (err) {
  4062. parsererrorNS = null;
  4063. }
  4064. }
  4065. try {
  4066. xmlDoc = parser.parseFromString(xmlDocStr, "text/xml");
  4067. if (parsererrorNS != null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
  4068. //throw new Error('Error parsing XML: '+xmlDocStr);
  4069. xmlDoc = null;
  4070. }
  4071. } catch (err) {
  4072. xmlDoc = null;
  4073. }
  4074. } else {
  4075. // IE :(
  4076. if (xmlDocStr.indexOf("<?") == 0) {
  4077. xmlDocStr = xmlDocStr.substr(xmlDocStr.indexOf("?>") + 2);
  4078. }
  4079. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  4080. xmlDoc.async = "false";
  4081. xmlDoc.loadXML(xmlDocStr);
  4082. }
  4083. return xmlDoc;
  4084. };
  4085. this.asArray = function (prop) {
  4086. if (prop === undefined || prop == null) return [];else if (prop instanceof Array) return prop;else return [prop];
  4087. };
  4088. this.toXmlDateTime = function (dt) {
  4089. if (dt instanceof Date) return dt.toISOString();else if (typeof dt === 'number') return new Date(dt).toISOString();else return null;
  4090. };
  4091. this.asDateTime = function (prop) {
  4092. if (typeof prop == "string") {
  4093. return fromXmlDateTime(prop);
  4094. } else return prop;
  4095. };
  4096. this.xml2json = function (xmlDoc) {
  4097. return parseDOMChildren(xmlDoc);
  4098. };
  4099. this.xml_str2json = function (xmlDocStr) {
  4100. var xmlDoc = this.parseXmlString(xmlDocStr);
  4101. if (xmlDoc != null) return this.xml2json(xmlDoc);else return null;
  4102. };
  4103. this.json2xml_str = function (jsonObj) {
  4104. return parseJSONObject(jsonObj, "");
  4105. };
  4106. this.json2xml = function (jsonObj) {
  4107. var xmlDocStr = this.json2xml_str(jsonObj);
  4108. return this.parseXmlString(xmlDocStr);
  4109. };
  4110. this.getVersion = function () {
  4111. return VERSION;
  4112. };
  4113. };
  4114. var xml2json = function xml2json(str) {
  4115. if (!str) return null;
  4116. var parser = new DOMParser();
  4117. var xmlDoc = parser.parseFromString(str, "text/xml");
  4118. var x2jsObj = new x2js();
  4119. var data = x2jsObj.xml2json(xmlDoc);
  4120. if (data.html && data.getElementsByTagName('parsererror').length) {
  4121. return null;
  4122. } else {
  4123. return data;
  4124. }
  4125. };
  4126. var json2xml = function json2xml(data) {
  4127. var x2jsObj = new x2js();
  4128. return x2jsObj.json2xml(data);
  4129. };
  4130. module.exports = xml2json;
  4131. /***/ }),
  4132. /* 15 */
  4133. /***/ (function(module, exports, __webpack_require__) {
  4134. "use strict";
  4135. var dom = __webpack_require__(3);
  4136. exports.DOMImplementation = dom.DOMImplementation;
  4137. exports.XMLSerializer = dom.XMLSerializer;
  4138. exports.DOMParser = __webpack_require__(16).DOMParser;
  4139. /***/ }),
  4140. /* 16 */
  4141. /***/ (function(module, exports, __webpack_require__) {
  4142. "use strict";
  4143. var conventions = __webpack_require__(1);
  4144. var dom = __webpack_require__(3);
  4145. var entities = __webpack_require__(17);
  4146. var sax = __webpack_require__(18);
  4147. var DOMImplementation = dom.DOMImplementation;
  4148. var NAMESPACE = conventions.NAMESPACE;
  4149. var ParseError = sax.ParseError;
  4150. var XMLReader = sax.XMLReader;
  4151. /**
  4152. * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends:
  4153. *
  4154. * > XML parsed entities are often stored in computer files which,
  4155. * > for editing convenience, are organized into lines.
  4156. * > These lines are typically separated by some combination
  4157. * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA).
  4158. * >
  4159. * > To simplify the tasks of applications, the XML processor must behave
  4160. * > as if it normalized all line breaks in external parsed entities (including the document entity)
  4161. * > on input, before parsing, by translating all of the following to a single #xA character:
  4162. * >
  4163. * > 1. the two-character sequence #xD #xA
  4164. * > 2. the two-character sequence #xD #x85
  4165. * > 3. the single character #x85
  4166. * > 4. the single character #x2028
  4167. * > 5. any #xD character that is not immediately followed by #xA or #x85.
  4168. *
  4169. * @param {string} input
  4170. * @returns {string}
  4171. */
  4172. function normalizeLineEndings(input) {
  4173. return input.replace(/\r[\n\u0085]/g, '\n').replace(/[\r\u0085\u2028]/g, '\n');
  4174. }
  4175. /**
  4176. * @typedef Locator
  4177. * @property {number} [columnNumber]
  4178. * @property {number} [lineNumber]
  4179. */
  4180. /**
  4181. * @typedef DOMParserOptions
  4182. * @property {DOMHandler} [domBuilder]
  4183. * @property {Function} [errorHandler]
  4184. * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing
  4185. * defaults to `normalizeLineEndings`
  4186. * @property {Locator} [locator]
  4187. * @property {Record<string, string>} [xmlns]
  4188. *
  4189. * @see normalizeLineEndings
  4190. */
  4191. /**
  4192. * The DOMParser interface provides the ability to parse XML or HTML source code
  4193. * from a string into a DOM `Document`.
  4194. *
  4195. * _xmldom is different from the spec in that it allows an `options` parameter,
  4196. * to override the default behavior._
  4197. *
  4198. * @param {DOMParserOptions} [options]
  4199. * @constructor
  4200. *
  4201. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
  4202. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization
  4203. */
  4204. function DOMParser(options) {
  4205. this.options = options || { locator: {} };
  4206. }
  4207. DOMParser.prototype.parseFromString = function (source, mimeType) {
  4208. var options = this.options;
  4209. var sax = new XMLReader();
  4210. var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler
  4211. var errorHandler = options.errorHandler;
  4212. var locator = options.locator;
  4213. var defaultNSMap = options.xmlns || {};
  4214. var isHTML = /\/x?html?$/.test(mimeType); //mimeType.toLowerCase().indexOf('html') > -1;
  4215. var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
  4216. if (locator) {
  4217. domBuilder.setDocumentLocator(locator);
  4218. }
  4219. sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
  4220. sax.domBuilder = options.domBuilder || domBuilder;
  4221. if (isHTML) {
  4222. defaultNSMap[''] = NAMESPACE.HTML;
  4223. }
  4224. defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
  4225. var normalize = options.normalizeLineEndings || normalizeLineEndings;
  4226. if (source && typeof source === 'string') {
  4227. sax.parse(normalize(source), defaultNSMap, entityMap);
  4228. } else {
  4229. sax.errorHandler.error('invalid doc source');
  4230. }
  4231. return domBuilder.doc;
  4232. };
  4233. function buildErrorHandler(errorImpl, domBuilder, locator) {
  4234. if (!errorImpl) {
  4235. if (domBuilder instanceof DOMHandler) {
  4236. return domBuilder;
  4237. }
  4238. errorImpl = domBuilder;
  4239. }
  4240. var errorHandler = {};
  4241. var isCallback = errorImpl instanceof Function;
  4242. locator = locator || {};
  4243. function build(key) {
  4244. var fn = errorImpl[key];
  4245. if (!fn && isCallback) {
  4246. fn = errorImpl.length == 2 ? function (msg) {
  4247. errorImpl(key, msg);
  4248. } : errorImpl;
  4249. }
  4250. errorHandler[key] = fn && function (msg) {
  4251. fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
  4252. } || function () {};
  4253. }
  4254. build('warning');
  4255. build('error');
  4256. build('fatalError');
  4257. return errorHandler;
  4258. }
  4259. //console.log('#\n\n\n\n\n\n\n####')
  4260. /**
  4261. * +ContentHandler+ErrorHandler
  4262. * +LexicalHandler+EntityResolver2
  4263. * -DeclHandler-DTDHandler
  4264. *
  4265. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  4266. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  4267. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  4268. */
  4269. function DOMHandler() {
  4270. this.cdata = false;
  4271. }
  4272. function position(locator, node) {
  4273. node.lineNumber = locator.lineNumber;
  4274. node.columnNumber = locator.columnNumber;
  4275. }
  4276. /**
  4277. * @see org.xml.sax.ContentHandler#startDocument
  4278. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  4279. */
  4280. DOMHandler.prototype = {
  4281. startDocument: function startDocument() {
  4282. this.doc = new DOMImplementation().createDocument(null, null, null);
  4283. if (this.locator) {
  4284. this.doc.documentURI = this.locator.systemId;
  4285. }
  4286. },
  4287. startElement: function startElement(namespaceURI, localName, qName, attrs) {
  4288. var doc = this.doc;
  4289. var el = doc.createElementNS(namespaceURI, qName || localName);
  4290. var len = attrs.length;
  4291. appendElement(this, el);
  4292. this.currentElement = el;
  4293. this.locator && position(this.locator, el);
  4294. for (var i = 0; i < len; i++) {
  4295. var namespaceURI = attrs.getURI(i);
  4296. var value = attrs.getValue(i);
  4297. var qName = attrs.getQName(i);
  4298. var attr = doc.createAttributeNS(namespaceURI, qName);
  4299. this.locator && position(attrs.getLocator(i), attr);
  4300. attr.value = attr.nodeValue = value;
  4301. el.setAttributeNode(attr);
  4302. }
  4303. },
  4304. endElement: function endElement(namespaceURI, localName, qName) {
  4305. var current = this.currentElement;
  4306. var tagName = current.tagName;
  4307. this.currentElement = current.parentNode;
  4308. },
  4309. startPrefixMapping: function startPrefixMapping(prefix, uri) {},
  4310. endPrefixMapping: function endPrefixMapping(prefix) {},
  4311. processingInstruction: function processingInstruction(target, data) {
  4312. var ins = this.doc.createProcessingInstruction(target, data);
  4313. this.locator && position(this.locator, ins);
  4314. appendElement(this, ins);
  4315. },
  4316. ignorableWhitespace: function ignorableWhitespace(ch, start, length) {},
  4317. characters: function characters(chars, start, length) {
  4318. chars = _toString.apply(this, arguments);
  4319. //console.log(chars)
  4320. if (chars) {
  4321. if (this.cdata) {
  4322. var charNode = this.doc.createCDATASection(chars);
  4323. } else {
  4324. var charNode = this.doc.createTextNode(chars);
  4325. }
  4326. if (this.currentElement) {
  4327. this.currentElement.appendChild(charNode);
  4328. } else if (/^\s*$/.test(chars)) {
  4329. this.doc.appendChild(charNode);
  4330. //process xml
  4331. }
  4332. this.locator && position(this.locator, charNode);
  4333. }
  4334. },
  4335. skippedEntity: function skippedEntity(name) {},
  4336. endDocument: function endDocument() {
  4337. this.doc.normalize();
  4338. },
  4339. setDocumentLocator: function setDocumentLocator(locator) {
  4340. if (this.locator = locator) {
  4341. // && !('lineNumber' in locator)){
  4342. locator.lineNumber = 0;
  4343. }
  4344. },
  4345. //LexicalHandler
  4346. comment: function comment(chars, start, length) {
  4347. chars = _toString.apply(this, arguments);
  4348. var comm = this.doc.createComment(chars);
  4349. this.locator && position(this.locator, comm);
  4350. appendElement(this, comm);
  4351. },
  4352. startCDATA: function startCDATA() {
  4353. //used in characters() methods
  4354. this.cdata = true;
  4355. },
  4356. endCDATA: function endCDATA() {
  4357. this.cdata = false;
  4358. },
  4359. startDTD: function startDTD(name, publicId, systemId) {
  4360. var impl = this.doc.implementation;
  4361. if (impl && impl.createDocumentType) {
  4362. var dt = impl.createDocumentType(name, publicId, systemId);
  4363. this.locator && position(this.locator, dt);
  4364. appendElement(this, dt);
  4365. this.doc.doctype = dt;
  4366. }
  4367. },
  4368. /**
  4369. * @see org.xml.sax.ErrorHandler
  4370. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  4371. */
  4372. warning: function warning(error) {
  4373. console.warn('[xmldom warning]\t' + error, _locator(this.locator));
  4374. },
  4375. error: function error(_error) {
  4376. console.error('[xmldom error]\t' + _error, _locator(this.locator));
  4377. },
  4378. fatalError: function fatalError(error) {
  4379. throw new ParseError(error, this.locator);
  4380. }
  4381. };
  4382. function _locator(l) {
  4383. if (l) {
  4384. return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
  4385. }
  4386. }
  4387. function _toString(chars, start, length) {
  4388. if (typeof chars == 'string') {
  4389. return chars.substr(start, length);
  4390. } else {
  4391. //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  4392. if (chars.length >= start + length || start) {
  4393. return new java.lang.String(chars, start, length) + '';
  4394. }
  4395. return chars;
  4396. }
  4397. }
  4398. /*
  4399. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  4400. * used method of org.xml.sax.ext.LexicalHandler:
  4401. * #comment(chars, start, length)
  4402. * #startCDATA()
  4403. * #endCDATA()
  4404. * #startDTD(name, publicId, systemId)
  4405. *
  4406. *
  4407. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  4408. * #endDTD()
  4409. * #startEntity(name)
  4410. * #endEntity(name)
  4411. *
  4412. *
  4413. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  4414. * IGNORED method of org.xml.sax.ext.DeclHandler
  4415. * #attributeDecl(eName, aName, type, mode, value)
  4416. * #elementDecl(name, model)
  4417. * #externalEntityDecl(name, publicId, systemId)
  4418. * #internalEntityDecl(name, value)
  4419. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  4420. * IGNORED method of org.xml.sax.EntityResolver2
  4421. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  4422. * #resolveEntity(publicId, systemId)
  4423. * #getExternalSubset(name, baseURI)
  4424. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  4425. * IGNORED method of org.xml.sax.DTDHandler
  4426. * #notationDecl(name, publicId, systemId) {};
  4427. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  4428. */
  4429. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
  4430. DOMHandler.prototype[key] = function () {
  4431. return null;
  4432. };
  4433. });
  4434. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  4435. function appendElement(hander, node) {
  4436. if (!hander.currentElement) {
  4437. hander.doc.appendChild(node);
  4438. } else {
  4439. hander.currentElement.appendChild(node);
  4440. }
  4441. } //appendChild and setAttributeNS are preformance key
  4442. exports.__DOMHandler = DOMHandler;
  4443. exports.normalizeLineEndings = normalizeLineEndings;
  4444. exports.DOMParser = DOMParser;
  4445. /***/ }),
  4446. /* 17 */
  4447. /***/ (function(module, exports, __webpack_require__) {
  4448. "use strict";
  4449. var freeze = __webpack_require__(1).freeze;
  4450. /**
  4451. * The entities that are predefined in every XML document.
  4452. *
  4453. * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1
  4454. * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0
  4455. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia
  4456. */
  4457. exports.XML_ENTITIES = freeze({ amp: '&', apos: "'", gt: '>', lt: '<', quot: '"' });
  4458. /**
  4459. * A map of currently 241 entities that are detected in an HTML document.
  4460. * They contain all entries from `XML_ENTITIES`.
  4461. *
  4462. * @see XML_ENTITIES
  4463. * @see DOMParser.parseFromString
  4464. * @see DOMImplementation.prototype.createHTMLDocument
  4465. * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec
  4466. * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names
  4467. * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML
  4468. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML)
  4469. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML)
  4470. */
  4471. exports.HTML_ENTITIES = freeze({
  4472. lt: '<',
  4473. gt: '>',
  4474. amp: '&',
  4475. quot: '"',
  4476. apos: "'",
  4477. Agrave: "À",
  4478. Aacute: "Á",
  4479. Acirc: "Â",
  4480. Atilde: "Ã",
  4481. Auml: "Ä",
  4482. Aring: "Å",
  4483. AElig: "Æ",
  4484. Ccedil: "Ç",
  4485. Egrave: "È",
  4486. Eacute: "É",
  4487. Ecirc: "Ê",
  4488. Euml: "Ë",
  4489. Igrave: "Ì",
  4490. Iacute: "Í",
  4491. Icirc: "Î",
  4492. Iuml: "Ï",
  4493. ETH: "Ð",
  4494. Ntilde: "Ñ",
  4495. Ograve: "Ò",
  4496. Oacute: "Ó",
  4497. Ocirc: "Ô",
  4498. Otilde: "Õ",
  4499. Ouml: "Ö",
  4500. Oslash: "Ø",
  4501. Ugrave: "Ù",
  4502. Uacute: "Ú",
  4503. Ucirc: "Û",
  4504. Uuml: "Ü",
  4505. Yacute: "Ý",
  4506. THORN: "Þ",
  4507. szlig: "ß",
  4508. agrave: "à",
  4509. aacute: "á",
  4510. acirc: "â",
  4511. atilde: "ã",
  4512. auml: "ä",
  4513. aring: "å",
  4514. aelig: "æ",
  4515. ccedil: "ç",
  4516. egrave: "è",
  4517. eacute: "é",
  4518. ecirc: "ê",
  4519. euml: "ë",
  4520. igrave: "ì",
  4521. iacute: "í",
  4522. icirc: "î",
  4523. iuml: "ï",
  4524. eth: "ð",
  4525. ntilde: "ñ",
  4526. ograve: "ò",
  4527. oacute: "ó",
  4528. ocirc: "ô",
  4529. otilde: "õ",
  4530. ouml: "ö",
  4531. oslash: "ø",
  4532. ugrave: "ù",
  4533. uacute: "ú",
  4534. ucirc: "û",
  4535. uuml: "ü",
  4536. yacute: "ý",
  4537. thorn: "þ",
  4538. yuml: "ÿ",
  4539. nbsp: '\xA0',
  4540. iexcl: "¡",
  4541. cent: "¢",
  4542. pound: "£",
  4543. curren: "¤",
  4544. yen: "¥",
  4545. brvbar: "¦",
  4546. sect: "§",
  4547. uml: "¨",
  4548. copy: "©",
  4549. ordf: "ª",
  4550. laquo: "«",
  4551. not: "¬",
  4552. shy: "­­",
  4553. reg: "®",
  4554. macr: "¯",
  4555. deg: "°",
  4556. plusmn: "±",
  4557. sup2: "²",
  4558. sup3: "³",
  4559. acute: "´",
  4560. micro: "µ",
  4561. para: "¶",
  4562. middot: "·",
  4563. cedil: "¸",
  4564. sup1: "¹",
  4565. ordm: "º",
  4566. raquo: "»",
  4567. frac14: "¼",
  4568. frac12: "½",
  4569. frac34: "¾",
  4570. iquest: "¿",
  4571. times: "×",
  4572. divide: "÷",
  4573. forall: "∀",
  4574. part: "∂",
  4575. exist: "∃",
  4576. empty: "∅",
  4577. nabla: "∇",
  4578. isin: "∈",
  4579. notin: "∉",
  4580. ni: "∋",
  4581. prod: "∏",
  4582. sum: "∑",
  4583. minus: "−",
  4584. lowast: "∗",
  4585. radic: "√",
  4586. prop: "∝",
  4587. infin: "∞",
  4588. ang: "∠",
  4589. and: "∧",
  4590. or: "∨",
  4591. cap: "∩",
  4592. cup: "∪",
  4593. 'int': "∫",
  4594. there4: "∴",
  4595. sim: "∼",
  4596. cong: "≅",
  4597. asymp: "≈",
  4598. ne: "≠",
  4599. equiv: "≡",
  4600. le: "≤",
  4601. ge: "≥",
  4602. sub: "⊂",
  4603. sup: "⊃",
  4604. nsub: "⊄",
  4605. sube: "⊆",
  4606. supe: "⊇",
  4607. oplus: "⊕",
  4608. otimes: "⊗",
  4609. perp: "⊥",
  4610. sdot: "⋅",
  4611. Alpha: "Α",
  4612. Beta: "Β",
  4613. Gamma: "Γ",
  4614. Delta: "Δ",
  4615. Epsilon: "Ε",
  4616. Zeta: "Ζ",
  4617. Eta: "Η",
  4618. Theta: "Θ",
  4619. Iota: "Ι",
  4620. Kappa: "Κ",
  4621. Lambda: "Λ",
  4622. Mu: "Μ",
  4623. Nu: "Ν",
  4624. Xi: "Ξ",
  4625. Omicron: "Ο",
  4626. Pi: "Π",
  4627. Rho: "Ρ",
  4628. Sigma: "Σ",
  4629. Tau: "Τ",
  4630. Upsilon: "Υ",
  4631. Phi: "Φ",
  4632. Chi: "Χ",
  4633. Psi: "Ψ",
  4634. Omega: "Ω",
  4635. alpha: "α",
  4636. beta: "β",
  4637. gamma: "γ",
  4638. delta: "δ",
  4639. epsilon: "ε",
  4640. zeta: "ζ",
  4641. eta: "η",
  4642. theta: "θ",
  4643. iota: "ι",
  4644. kappa: "κ",
  4645. lambda: "λ",
  4646. mu: "μ",
  4647. nu: "ν",
  4648. xi: "ξ",
  4649. omicron: "ο",
  4650. pi: "π",
  4651. rho: "ρ",
  4652. sigmaf: "ς",
  4653. sigma: "σ",
  4654. tau: "τ",
  4655. upsilon: "υ",
  4656. phi: "φ",
  4657. chi: "χ",
  4658. psi: "ψ",
  4659. omega: "ω",
  4660. thetasym: "ϑ",
  4661. upsih: "ϒ",
  4662. piv: "ϖ",
  4663. OElig: "Œ",
  4664. oelig: "œ",
  4665. Scaron: "Š",
  4666. scaron: "š",
  4667. Yuml: "Ÿ",
  4668. fnof: "ƒ",
  4669. circ: "ˆ",
  4670. tilde: "˜",
  4671. ensp: " ",
  4672. emsp: " ",
  4673. thinsp: " ",
  4674. zwnj: "‌",
  4675. zwj: "‍",
  4676. lrm: "‎",
  4677. rlm: "‏",
  4678. ndash: "–",
  4679. mdash: "—",
  4680. lsquo: "‘",
  4681. rsquo: "’",
  4682. sbquo: "‚",
  4683. ldquo: "“",
  4684. rdquo: "”",
  4685. bdquo: "„",
  4686. dagger: "†",
  4687. Dagger: "‡",
  4688. bull: "•",
  4689. hellip: "…",
  4690. permil: "‰",
  4691. prime: "′",
  4692. Prime: "″",
  4693. lsaquo: "‹",
  4694. rsaquo: "›",
  4695. oline: "‾",
  4696. euro: "€",
  4697. trade: "™",
  4698. larr: "←",
  4699. uarr: "↑",
  4700. rarr: "→",
  4701. darr: "↓",
  4702. harr: "↔",
  4703. crarr: "↵",
  4704. lceil: "⌈",
  4705. rceil: "⌉",
  4706. lfloor: "⌊",
  4707. rfloor: "⌋",
  4708. loz: "◊",
  4709. spades: "♠",
  4710. clubs: "♣",
  4711. hearts: "♥",
  4712. diams: "♦"
  4713. });
  4714. /**
  4715. * @deprecated use `HTML_ENTITIES` instead
  4716. * @see HTML_ENTITIES
  4717. */
  4718. exports.entityMap = exports.HTML_ENTITIES;
  4719. /***/ }),
  4720. /* 18 */
  4721. /***/ (function(module, exports, __webpack_require__) {
  4722. "use strict";
  4723. var NAMESPACE = __webpack_require__(1).NAMESPACE;
  4724. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  4725. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  4726. //[5] Name ::= NameStartChar (NameChar)*
  4727. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; //\u10000-\uEFFFF
  4728. var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  4729. var tagNamePattern = new RegExp('^' + nameStartChar.source + nameChar.source + '*(?:\:' + nameStartChar.source + nameChar.source + '*)?$');
  4730. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  4731. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  4732. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  4733. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  4734. var S_TAG = 0; //tag name offerring
  4735. var S_ATTR = 1; //attr name offerring
  4736. var S_ATTR_SPACE = 2; //attr name end and space offer
  4737. var S_EQ = 3; //=space?
  4738. var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only)
  4739. var S_ATTR_END = 5; //attr value end and no space(quot end)
  4740. var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer)
  4741. var S_TAG_CLOSE = 7; //closed el<el />
  4742. /**
  4743. * Creates an error that will not be caught by XMLReader aka the SAX parser.
  4744. *
  4745. * @param {string} message
  4746. * @param {any?} locator Optional, can provide details about the location in the source
  4747. * @constructor
  4748. */
  4749. function ParseError(message, locator) {
  4750. this.message = message;
  4751. this.locator = locator;
  4752. if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
  4753. }
  4754. ParseError.prototype = new Error();
  4755. ParseError.prototype.name = ParseError.name;
  4756. function XMLReader() {}
  4757. XMLReader.prototype = {
  4758. parse: function parse(source, defaultNSMap, entityMap) {
  4759. var domBuilder = this.domBuilder;
  4760. domBuilder.startDocument();
  4761. _copy(defaultNSMap, defaultNSMap = {});
  4762. _parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
  4763. domBuilder.endDocument();
  4764. }
  4765. };
  4766. function _parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
  4767. function fixedFromCharCode(code) {
  4768. // String.prototype.fromCharCode does not supports
  4769. // > 2 bytes unicode chars directly
  4770. if (code > 0xffff) {
  4771. code -= 0x10000;
  4772. var surrogate1 = 0xd800 + (code >> 10),
  4773. surrogate2 = 0xdc00 + (code & 0x3ff);
  4774. return String.fromCharCode(surrogate1, surrogate2);
  4775. } else {
  4776. return String.fromCharCode(code);
  4777. }
  4778. }
  4779. function entityReplacer(a) {
  4780. var k = a.slice(1, -1);
  4781. if (Object.hasOwnProperty.call(entityMap, k)) {
  4782. return entityMap[k];
  4783. } else if (k.charAt(0) === '#') {
  4784. return fixedFromCharCode(parseInt(k.substr(1).replace('x', '0x')));
  4785. } else {
  4786. errorHandler.error('entity not found:' + a);
  4787. return a;
  4788. }
  4789. }
  4790. function appendText(end) {
  4791. //has some bugs
  4792. if (end > start) {
  4793. var xt = source.substring(start, end).replace(/&#?\w+;/g, entityReplacer);
  4794. locator && position(start);
  4795. domBuilder.characters(xt, 0, end - start);
  4796. start = end;
  4797. }
  4798. }
  4799. function position(p, m) {
  4800. while (p >= lineEnd && (m = linePattern.exec(source))) {
  4801. lineStart = m.index;
  4802. lineEnd = lineStart + m[0].length;
  4803. locator.lineNumber++;
  4804. //console.log('line++:',locator,startPos,endPos)
  4805. }
  4806. locator.columnNumber = p - lineStart + 1;
  4807. }
  4808. var lineStart = 0;
  4809. var lineEnd = 0;
  4810. var linePattern = /.*(?:\r\n?|\n)|.*$/g;
  4811. var locator = domBuilder.locator;
  4812. var parseStack = [{ currentNSMap: defaultNSMapCopy }];
  4813. var closeMap = {};
  4814. var start = 0;
  4815. while (true) {
  4816. try {
  4817. var tagStart = source.indexOf('<', start);
  4818. if (tagStart < 0) {
  4819. if (!source.substr(start).match(/^\s*$/)) {
  4820. var doc = domBuilder.doc;
  4821. var text = doc.createTextNode(source.substr(start));
  4822. doc.appendChild(text);
  4823. domBuilder.currentElement = text;
  4824. }
  4825. return;
  4826. }
  4827. if (tagStart > start) {
  4828. appendText(tagStart);
  4829. }
  4830. switch (source.charAt(tagStart + 1)) {
  4831. case '/':
  4832. var end = source.indexOf('>', tagStart + 3);
  4833. var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, '');
  4834. var config = parseStack.pop();
  4835. if (end < 0) {
  4836. tagName = source.substring(tagStart + 2).replace(/[\s<].*/, '');
  4837. errorHandler.error("end tag name: " + tagName + ' is not complete:' + config.tagName);
  4838. end = tagStart + 1 + tagName.length;
  4839. } else if (tagName.match(/\s</)) {
  4840. tagName = tagName.replace(/[\s<].*/, '');
  4841. errorHandler.error("end tag name: " + tagName + ' maybe not complete');
  4842. end = tagStart + 1 + tagName.length;
  4843. }
  4844. var localNSMap = config.localNSMap;
  4845. var endMatch = config.tagName == tagName;
  4846. var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();
  4847. if (endIgnoreCaseMach) {
  4848. domBuilder.endElement(config.uri, config.localName, tagName);
  4849. if (localNSMap) {
  4850. for (var prefix in localNSMap) {
  4851. domBuilder.endPrefixMapping(prefix);
  4852. }
  4853. }
  4854. if (!endMatch) {
  4855. errorHandler.fatalError("end tag name: " + tagName + ' is not match the current start tagName:' + config.tagName); // No known test case
  4856. }
  4857. } else {
  4858. parseStack.push(config);
  4859. }
  4860. end++;
  4861. break;
  4862. // end elment
  4863. case '?':
  4864. // <?...?>
  4865. locator && position(tagStart);
  4866. end = parseInstruction(source, tagStart, domBuilder);
  4867. break;
  4868. case '!':
  4869. // <!doctype,<![CDATA,<!--
  4870. locator && position(tagStart);
  4871. end = parseDCC(source, tagStart, domBuilder, errorHandler);
  4872. break;
  4873. default:
  4874. locator && position(tagStart);
  4875. var el = new ElementAttributes();
  4876. var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
  4877. //elStartEnd
  4878. var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
  4879. var len = el.length;
  4880. if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
  4881. el.closed = true;
  4882. if (!entityMap.nbsp) {
  4883. errorHandler.warning('unclosed xml attribute');
  4884. }
  4885. }
  4886. if (locator && len) {
  4887. var locator2 = copyLocator(locator, {});
  4888. //try{//attribute position fixed
  4889. for (var i = 0; i < len; i++) {
  4890. var a = el[i];
  4891. position(a.offset);
  4892. a.locator = copyLocator(locator, {});
  4893. }
  4894. domBuilder.locator = locator2;
  4895. if (appendElement(el, domBuilder, currentNSMap)) {
  4896. parseStack.push(el);
  4897. }
  4898. domBuilder.locator = locator;
  4899. } else {
  4900. if (appendElement(el, domBuilder, currentNSMap)) {
  4901. parseStack.push(el);
  4902. }
  4903. }
  4904. if (NAMESPACE.isHTML(el.uri) && !el.closed) {
  4905. end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
  4906. } else {
  4907. end++;
  4908. }
  4909. }
  4910. } catch (e) {
  4911. if (e instanceof ParseError) {
  4912. throw e;
  4913. }
  4914. errorHandler.error('element parse error: ' + e);
  4915. end = -1;
  4916. }
  4917. if (end > start) {
  4918. start = end;
  4919. } else {
  4920. //TODO: 这里有可能sax回退,有位置错误风险
  4921. appendText(Math.max(tagStart, start) + 1);
  4922. }
  4923. }
  4924. }
  4925. function copyLocator(f, t) {
  4926. t.lineNumber = f.lineNumber;
  4927. t.columnNumber = f.columnNumber;
  4928. return t;
  4929. }
  4930. /**
  4931. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  4932. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  4933. */
  4934. function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler) {
  4935. /**
  4936. * @param {string} qname
  4937. * @param {string} value
  4938. * @param {number} startIndex
  4939. */
  4940. function addAttribute(qname, value, startIndex) {
  4941. if (el.attributeNames.hasOwnProperty(qname)) {
  4942. errorHandler.fatalError('Attribute ' + qname + ' redefined');
  4943. }
  4944. el.addValue(qname,
  4945. // @see https://www.w3.org/TR/xml/#AVNormalize
  4946. // since the xmldom sax parser does not "interpret" DTD the following is not implemented:
  4947. // - recursive replacement of (DTD) entity references
  4948. // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA
  4949. value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), startIndex);
  4950. }
  4951. var attrName;
  4952. var value;
  4953. var p = ++start;
  4954. var s = S_TAG; //status
  4955. while (true) {
  4956. var c = source.charAt(p);
  4957. switch (c) {
  4958. case '=':
  4959. if (s === S_ATTR) {
  4960. //attrName
  4961. attrName = source.slice(start, p);
  4962. s = S_EQ;
  4963. } else if (s === S_ATTR_SPACE) {
  4964. s = S_EQ;
  4965. } else {
  4966. //fatalError: equal must after attrName or space after attrName
  4967. throw new Error('attribute equal must after attrName'); // No known test case
  4968. }
  4969. break;
  4970. case '\'':
  4971. case '"':
  4972. if (s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  4973. ) {
  4974. //equal
  4975. if (s === S_ATTR) {
  4976. errorHandler.warning('attribute value must after "="');
  4977. attrName = source.slice(start, p);
  4978. }
  4979. start = p + 1;
  4980. p = source.indexOf(c, start);
  4981. if (p > 0) {
  4982. value = source.slice(start, p);
  4983. addAttribute(attrName, value, start - 1);
  4984. s = S_ATTR_END;
  4985. } else {
  4986. //fatalError: no end quot match
  4987. throw new Error('attribute value no end \'' + c + '\' match');
  4988. }
  4989. } else if (s == S_ATTR_NOQUOT_VALUE) {
  4990. value = source.slice(start, p);
  4991. addAttribute(attrName, value, start);
  4992. errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!');
  4993. start = p + 1;
  4994. s = S_ATTR_END;
  4995. } else {
  4996. //fatalError: no equal before
  4997. throw new Error('attribute value must after "="'); // No known test case
  4998. }
  4999. break;
  5000. case '/':
  5001. switch (s) {
  5002. case S_TAG:
  5003. el.setTagName(source.slice(start, p));
  5004. case S_ATTR_END:
  5005. case S_TAG_SPACE:
  5006. case S_TAG_CLOSE:
  5007. s = S_TAG_CLOSE;
  5008. el.closed = true;
  5009. case S_ATTR_NOQUOT_VALUE:
  5010. case S_ATTR:
  5011. case S_ATTR_SPACE:
  5012. break;
  5013. //case S_EQ:
  5014. default:
  5015. throw new Error("attribute invalid close char('/')"); // No known test case
  5016. }
  5017. break;
  5018. case '':
  5019. //end document
  5020. errorHandler.error('unexpected end of input');
  5021. if (s == S_TAG) {
  5022. el.setTagName(source.slice(start, p));
  5023. }
  5024. return p;
  5025. case '>':
  5026. switch (s) {
  5027. case S_TAG:
  5028. el.setTagName(source.slice(start, p));
  5029. case S_ATTR_END:
  5030. case S_TAG_SPACE:
  5031. case S_TAG_CLOSE:
  5032. break; //normal
  5033. case S_ATTR_NOQUOT_VALUE: //Compatible state
  5034. case S_ATTR:
  5035. value = source.slice(start, p);
  5036. if (value.slice(-1) === '/') {
  5037. el.closed = true;
  5038. value = value.slice(0, -1);
  5039. }
  5040. case S_ATTR_SPACE:
  5041. if (s === S_ATTR_SPACE) {
  5042. value = attrName;
  5043. }
  5044. if (s == S_ATTR_NOQUOT_VALUE) {
  5045. errorHandler.warning('attribute "' + value + '" missed quot(")!');
  5046. addAttribute(attrName, value, start);
  5047. } else {
  5048. if (!NAMESPACE.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)) {
  5049. errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
  5050. }
  5051. addAttribute(value, value, start);
  5052. }
  5053. break;
  5054. case S_EQ:
  5055. throw new Error('attribute value missed!!');
  5056. }
  5057. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  5058. return p;
  5059. /*xml space '\x20' | #x9 | #xD | #xA; */
  5060. case "\x80":
  5061. c = ' ';
  5062. default:
  5063. if (c <= ' ') {
  5064. //space
  5065. switch (s) {
  5066. case S_TAG:
  5067. el.setTagName(source.slice(start, p)); //tagName
  5068. s = S_TAG_SPACE;
  5069. break;
  5070. case S_ATTR:
  5071. attrName = source.slice(start, p);
  5072. s = S_ATTR_SPACE;
  5073. break;
  5074. case S_ATTR_NOQUOT_VALUE:
  5075. var value = source.slice(start, p);
  5076. errorHandler.warning('attribute "' + value + '" missed quot(")!!');
  5077. addAttribute(attrName, value, start);
  5078. case S_ATTR_END:
  5079. s = S_TAG_SPACE;
  5080. break;
  5081. //case S_TAG_SPACE:
  5082. //case S_EQ:
  5083. //case S_ATTR_SPACE:
  5084. // void();break;
  5085. //case S_TAG_CLOSE:
  5086. //ignore warning
  5087. }
  5088. } else {
  5089. //not space
  5090. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  5091. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  5092. switch (s) {
  5093. //case S_TAG:void();break;
  5094. //case S_ATTR:void();break;
  5095. //case S_ATTR_NOQUOT_VALUE:void();break;
  5096. case S_ATTR_SPACE:
  5097. var tagName = el.tagName;
  5098. if (!NAMESPACE.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
  5099. errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
  5100. }
  5101. addAttribute(attrName, attrName, start);
  5102. start = p;
  5103. s = S_ATTR;
  5104. break;
  5105. case S_ATTR_END:
  5106. errorHandler.warning('attribute space is required"' + attrName + '"!!');
  5107. case S_TAG_SPACE:
  5108. s = S_ATTR;
  5109. start = p;
  5110. break;
  5111. case S_EQ:
  5112. s = S_ATTR_NOQUOT_VALUE;
  5113. start = p;
  5114. break;
  5115. case S_TAG_CLOSE:
  5116. throw new Error("elements closed character '/' and '>' must be connected to");
  5117. }
  5118. }
  5119. } //end outer switch
  5120. //console.log('p++',p)
  5121. p++;
  5122. }
  5123. }
  5124. /**
  5125. * @return true if has new namespace define
  5126. */
  5127. function appendElement(el, domBuilder, currentNSMap) {
  5128. var tagName = el.tagName;
  5129. var localNSMap = null;
  5130. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  5131. var i = el.length;
  5132. while (i--) {
  5133. var a = el[i];
  5134. var qName = a.qName;
  5135. var value = a.value;
  5136. var nsp = qName.indexOf(':');
  5137. if (nsp > 0) {
  5138. var prefix = a.prefix = qName.slice(0, nsp);
  5139. var localName = qName.slice(nsp + 1);
  5140. var nsPrefix = prefix === 'xmlns' && localName;
  5141. } else {
  5142. localName = qName;
  5143. prefix = null;
  5144. nsPrefix = qName === 'xmlns' && '';
  5145. }
  5146. //can not set prefix,because prefix !== ''
  5147. a.localName = localName;
  5148. //prefix == null for no ns prefix attribute
  5149. if (nsPrefix !== false) {
  5150. //hack!!
  5151. if (localNSMap == null) {
  5152. localNSMap = {};
  5153. //console.log(currentNSMap,0)
  5154. _copy(currentNSMap, currentNSMap = {});
  5155. //console.log(currentNSMap,1)
  5156. }
  5157. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  5158. a.uri = NAMESPACE.XMLNS;
  5159. domBuilder.startPrefixMapping(nsPrefix, value);
  5160. }
  5161. }
  5162. var i = el.length;
  5163. while (i--) {
  5164. a = el[i];
  5165. var prefix = a.prefix;
  5166. if (prefix) {
  5167. //no prefix attribute has no namespace
  5168. if (prefix === 'xml') {
  5169. a.uri = NAMESPACE.XML;
  5170. }if (prefix !== 'xmlns') {
  5171. a.uri = currentNSMap[prefix || ''];
  5172. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  5173. }
  5174. }
  5175. }
  5176. var nsp = tagName.indexOf(':');
  5177. if (nsp > 0) {
  5178. prefix = el.prefix = tagName.slice(0, nsp);
  5179. localName = el.localName = tagName.slice(nsp + 1);
  5180. } else {
  5181. prefix = null; //important!!
  5182. localName = el.localName = tagName;
  5183. }
  5184. //no prefix element has default namespace
  5185. var ns = el.uri = currentNSMap[prefix || ''];
  5186. domBuilder.startElement(ns, localName, tagName, el);
  5187. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  5188. //localNSMap = null
  5189. if (el.closed) {
  5190. domBuilder.endElement(ns, localName, tagName);
  5191. if (localNSMap) {
  5192. for (prefix in localNSMap) {
  5193. domBuilder.endPrefixMapping(prefix);
  5194. }
  5195. }
  5196. } else {
  5197. el.currentNSMap = currentNSMap;
  5198. el.localNSMap = localNSMap;
  5199. //parseStack.push(el);
  5200. return true;
  5201. }
  5202. }
  5203. function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
  5204. if (/^(?:script|textarea)$/i.test(tagName)) {
  5205. var elEndStart = source.indexOf('</' + tagName + '>', elStartEnd);
  5206. var text = source.substring(elStartEnd + 1, elEndStart);
  5207. if (/[&<]/.test(text)) {
  5208. if (/^script$/i.test(tagName)) {
  5209. //if(!/\]\]>/.test(text)){
  5210. //lexHandler.startCDATA();
  5211. domBuilder.characters(text, 0, text.length);
  5212. //lexHandler.endCDATA();
  5213. return elEndStart;
  5214. //}
  5215. } //}else{//text area
  5216. text = text.replace(/&#?\w+;/g, entityReplacer);
  5217. domBuilder.characters(text, 0, text.length);
  5218. return elEndStart;
  5219. //}
  5220. }
  5221. }
  5222. return elStartEnd + 1;
  5223. }
  5224. function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
  5225. //if(tagName in closeMap){
  5226. var pos = closeMap[tagName];
  5227. if (pos == null) {
  5228. //console.log(tagName)
  5229. pos = source.lastIndexOf('</' + tagName + '>');
  5230. if (pos < elStartEnd) {
  5231. //忘记闭合
  5232. pos = source.lastIndexOf('</' + tagName);
  5233. }
  5234. closeMap[tagName] = pos;
  5235. }
  5236. return pos < elStartEnd;
  5237. //}
  5238. }
  5239. function _copy(source, target) {
  5240. for (var n in source) {
  5241. target[n] = source[n];
  5242. }
  5243. }
  5244. function parseDCC(source, start, domBuilder, errorHandler) {
  5245. //sure start with '<!'
  5246. var next = source.charAt(start + 2);
  5247. switch (next) {
  5248. case '-':
  5249. if (source.charAt(start + 3) === '-') {
  5250. var end = source.indexOf('-->', start + 4);
  5251. //append comment source.substring(4,end)//<!--
  5252. if (end > start) {
  5253. domBuilder.comment(source, start + 4, end - start - 4);
  5254. return end + 3;
  5255. } else {
  5256. errorHandler.error("Unclosed comment");
  5257. return -1;
  5258. }
  5259. } else {
  5260. //error
  5261. return -1;
  5262. }
  5263. default:
  5264. if (source.substr(start + 3, 6) == 'CDATA[') {
  5265. var end = source.indexOf(']]>', start + 9);
  5266. domBuilder.startCDATA();
  5267. domBuilder.characters(source, start + 9, end - start - 9);
  5268. domBuilder.endCDATA();
  5269. return end + 3;
  5270. }
  5271. //<!DOCTYPE
  5272. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  5273. var matchs = split(source, start);
  5274. var len = matchs.length;
  5275. if (len > 1 && /!doctype/i.test(matchs[0][0])) {
  5276. var name = matchs[1][0];
  5277. var pubid = false;
  5278. var sysid = false;
  5279. if (len > 3) {
  5280. if (/^public$/i.test(matchs[2][0])) {
  5281. pubid = matchs[3][0];
  5282. sysid = len > 4 && matchs[4][0];
  5283. } else if (/^system$/i.test(matchs[2][0])) {
  5284. sysid = matchs[3][0];
  5285. }
  5286. }
  5287. var lastMatch = matchs[len - 1];
  5288. domBuilder.startDTD(name, pubid, sysid);
  5289. domBuilder.endDTD();
  5290. return lastMatch.index + lastMatch[0].length;
  5291. }
  5292. }
  5293. return -1;
  5294. }
  5295. function parseInstruction(source, start, domBuilder) {
  5296. var end = source.indexOf('?>', start);
  5297. if (end) {
  5298. var match = source.substring(start, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  5299. if (match) {
  5300. var len = match[0].length;
  5301. domBuilder.processingInstruction(match[1], match[2]);
  5302. return end + 2;
  5303. } else {
  5304. //error
  5305. return -1;
  5306. }
  5307. }
  5308. return -1;
  5309. }
  5310. function ElementAttributes() {
  5311. this.attributeNames = {};
  5312. }
  5313. ElementAttributes.prototype = {
  5314. setTagName: function setTagName(tagName) {
  5315. if (!tagNamePattern.test(tagName)) {
  5316. throw new Error('invalid tagName:' + tagName);
  5317. }
  5318. this.tagName = tagName;
  5319. },
  5320. addValue: function addValue(qName, value, offset) {
  5321. if (!tagNamePattern.test(qName)) {
  5322. throw new Error('invalid attribute:' + qName);
  5323. }
  5324. this.attributeNames[qName] = this.length;
  5325. this[this.length++] = { qName: qName, value: value, offset: offset };
  5326. },
  5327. length: 0,
  5328. getLocalName: function getLocalName(i) {
  5329. return this[i].localName;
  5330. },
  5331. getLocator: function getLocator(i) {
  5332. return this[i].locator;
  5333. },
  5334. getQName: function getQName(i) {
  5335. return this[i].qName;
  5336. },
  5337. getURI: function getURI(i) {
  5338. return this[i].uri;
  5339. },
  5340. getValue: function getValue(i) {
  5341. return this[i].value;
  5342. }
  5343. // ,getIndex:function(uri, localName)){
  5344. // if(localName){
  5345. //
  5346. // }else{
  5347. // var qName = uri
  5348. // }
  5349. // },
  5350. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  5351. // getType:function(uri,localName){}
  5352. // getType:function(i){},
  5353. };
  5354. function split(source, start) {
  5355. var match;
  5356. var buf = [];
  5357. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  5358. reg.lastIndex = start;
  5359. reg.exec(source); //skip <
  5360. while (match = reg.exec(source)) {
  5361. buf.push(match);
  5362. if (match[1]) return buf;
  5363. }
  5364. }
  5365. exports.XMLReader = XMLReader;
  5366. exports.ParseError = ParseError;
  5367. /***/ }),
  5368. /* 19 */
  5369. /***/ (function(module, exports, __webpack_require__) {
  5370. "use strict";
  5371. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  5372. //copyright Ryan Day 2010 <http://ryanday.org>, Joscha Feth 2013 <http://www.feth.com> [MIT Licensed]
  5373. var element_start_char = "a-zA-Z_\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FFF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD";
  5374. var element_non_start_char = "-.0-9\xB7\u0300-\u036F\u203F\u2040";
  5375. var element_replace = new RegExp("^([^" + element_start_char + "])|^((x|X)(m|M)(l|L))|([^" + element_start_char + element_non_start_char + "])", "g");
  5376. var not_safe_in_xml = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm;
  5377. var objKeys = function objKeys(obj) {
  5378. var l = [];
  5379. if (obj instanceof Object) {
  5380. for (var k in obj) {
  5381. if (obj.hasOwnProperty(k)) {
  5382. l.push(k);
  5383. }
  5384. }
  5385. }
  5386. return l;
  5387. };
  5388. var process_to_xml = function process_to_xml(node_data, options) {
  5389. var makeNode = function makeNode(name, content, attributes, level, hasSubNodes) {
  5390. var indent_value = options.indent !== undefined ? options.indent : "\t";
  5391. var indent = options.prettyPrint ? '\n' + new Array(level).join(indent_value) : '';
  5392. if (options.removeIllegalNameCharacters) {
  5393. name = name.replace(element_replace, '_');
  5394. }
  5395. var node = [indent, '<', name, attributes || ''];
  5396. if (content && content.length > 0) {
  5397. node.push('>');
  5398. node.push(content);
  5399. hasSubNodes && node.push(indent);
  5400. node.push('</');
  5401. node.push(name);
  5402. node.push('>');
  5403. } else {
  5404. node.push('/>');
  5405. }
  5406. return node.join('');
  5407. };
  5408. return function fn(node_data, node_descriptor, level) {
  5409. var type = typeof node_data === "undefined" ? "undefined" : _typeof(node_data);
  5410. if (Array.isArray ? Array.isArray(node_data) : node_data instanceof Array) {
  5411. type = 'array';
  5412. } else if (node_data instanceof Date) {
  5413. type = 'date';
  5414. }
  5415. switch (type) {
  5416. //if value is an array create child nodes from values
  5417. case 'array':
  5418. var ret = [];
  5419. node_data.map(function (v) {
  5420. ret.push(fn(v, 1, level + 1));
  5421. //entries that are values of an array are the only ones that can be special node descriptors
  5422. });
  5423. options.prettyPrint && ret.push('\n');
  5424. return ret.join('');
  5425. break;
  5426. case 'date':
  5427. // cast dates to ISO 8601 date (soap likes it)
  5428. return node_data.toJSON ? node_data.toJSON() : node_data + '';
  5429. break;
  5430. case 'object':
  5431. var nodes = [];
  5432. for (var name in node_data) {
  5433. if (node_data.hasOwnProperty(name)) {
  5434. if (node_data[name] instanceof Array) {
  5435. for (var j in node_data[name]) {
  5436. if (node_data[name].hasOwnProperty(j)) nodes.push(makeNode(name, fn(node_data[name][j], 0, level + 1), null, level + 1, objKeys(node_data[name][j]).length));
  5437. }
  5438. } else {
  5439. nodes.push(makeNode(name, fn(node_data[name], 0, level + 1), null, level + 1));
  5440. }
  5441. }
  5442. }
  5443. options.prettyPrint && nodes.length > 0 && nodes.push('\n');
  5444. return nodes.join('');
  5445. break;
  5446. case 'function':
  5447. return node_data();
  5448. break;
  5449. default:
  5450. return options.escape ? esc(node_data) : '' + node_data;
  5451. }
  5452. }(node_data, 0, 0);
  5453. };
  5454. var xml_header = function xml_header(standalone) {
  5455. var ret = ['<?xml version="1.0" encoding="UTF-8"'];
  5456. if (standalone) {
  5457. ret.push(' standalone="yes"');
  5458. }
  5459. ret.push('?>');
  5460. return ret.join('');
  5461. };
  5462. function esc(str) {
  5463. return ('' + str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(not_safe_in_xml, '');
  5464. }
  5465. var json2xml = function json2xml(obj, options) {
  5466. if (!options) {
  5467. options = {
  5468. xmlHeader: {
  5469. standalone: true
  5470. },
  5471. prettyPrint: true,
  5472. indent: " "
  5473. };
  5474. }
  5475. if (typeof obj == 'string') {
  5476. try {
  5477. obj = JSON.parse(obj.toString());
  5478. } catch (e) {
  5479. return false;
  5480. }
  5481. }
  5482. var xmlheader = '';
  5483. var docType = '';
  5484. if (options) {
  5485. if ((typeof options === "undefined" ? "undefined" : _typeof(options)) == 'object') {
  5486. // our config is an object
  5487. if (options.xmlHeader) {
  5488. // the user wants an xml header
  5489. xmlheader = xml_header(!!options.xmlHeader.standalone);
  5490. }
  5491. if (typeof options.docType != 'undefined') {
  5492. docType = '<!DOCTYPE ' + options.docType + '>';
  5493. }
  5494. } else {
  5495. // our config is a boolean value, so just add xml header
  5496. xmlheader = xml_header();
  5497. }
  5498. }
  5499. options = options || {};
  5500. var ret = [xmlheader, options.prettyPrint && docType ? '\n' : '', docType, process_to_xml(obj, options)];
  5501. return ret.join('').replace(/\n{2,}/g, '\n').replace(/\s+$/g, '');
  5502. };
  5503. module.exports = json2xml;
  5504. /***/ }),
  5505. /* 20 */
  5506. /***/ (function(module, exports, __webpack_require__) {
  5507. "use strict";
  5508. var session = __webpack_require__(6);
  5509. var util = __webpack_require__(0);
  5510. var originApiMap = {};
  5511. var transferToTaskMethod = function transferToTaskMethod(apiMap, apiName) {
  5512. originApiMap[apiName] = apiMap[apiName];
  5513. apiMap[apiName] = function (params, callback) {
  5514. if (params.SkipTask) {
  5515. originApiMap[apiName].call(this, params, callback);
  5516. } else {
  5517. this._addTask(apiName, params, callback);
  5518. }
  5519. };
  5520. };
  5521. var initTask = function initTask(cos) {
  5522. var queue = [];
  5523. var tasks = {};
  5524. var uploadingFileCount = 0;
  5525. var nextUploadIndex = 0;
  5526. // 接口返回简略的任务信息
  5527. var formatTask = function formatTask(task) {
  5528. var t = {
  5529. id: task.id,
  5530. Bucket: task.Bucket,
  5531. Region: task.Region,
  5532. Key: task.Key,
  5533. FilePath: task.FilePath,
  5534. state: task.state,
  5535. loaded: task.loaded,
  5536. size: task.size,
  5537. speed: task.speed,
  5538. percent: task.percent,
  5539. hashPercent: task.hashPercent,
  5540. error: task.error
  5541. };
  5542. if (task.FilePath) t.FilePath = task.FilePath;
  5543. return t;
  5544. };
  5545. var emitListUpdate = function () {
  5546. var timer;
  5547. var emit = function emit() {
  5548. timer = 0;
  5549. cos.emit('task-list-update', { list: util.map(queue, formatTask) });
  5550. cos.emit('list-update', { list: util.map(queue, formatTask) });
  5551. };
  5552. return function () {
  5553. if (!timer) timer = setTimeout(emit);
  5554. };
  5555. }();
  5556. var clearQueue = function clearQueue() {
  5557. if (queue.length <= cos.options.UploadQueueSize) return;
  5558. for (var i = 0; i < nextUploadIndex && // 小于当前操作的 index 才清理
  5559. i < queue.length && // 大于队列才清理
  5560. queue.length > cos.options.UploadQueueSize // 如果还太多,才继续清理
  5561. ;) {
  5562. var isActive = queue[i].state === 'waiting' || queue[i].state === 'checking' || queue[i].state === 'uploading';
  5563. if (!queue[i] || !isActive) {
  5564. tasks[queue[i].id] && delete tasks[queue[i].id];
  5565. queue.splice(i, 1);
  5566. nextUploadIndex--;
  5567. } else {
  5568. i++;
  5569. }
  5570. }
  5571. emitListUpdate();
  5572. };
  5573. var startNextTask = function startNextTask() {
  5574. // 检查是否允许增加执行进程
  5575. if (uploadingFileCount >= cos.options.FileParallelLimit) return;
  5576. // 跳过不可执行的任务
  5577. while (queue[nextUploadIndex] && queue[nextUploadIndex].state !== 'waiting') {
  5578. nextUploadIndex++;
  5579. } // 检查是否已遍历结束
  5580. if (nextUploadIndex >= queue.length) return;
  5581. // 上传该遍历到的任务
  5582. var task = queue[nextUploadIndex];
  5583. nextUploadIndex++;
  5584. uploadingFileCount++;
  5585. task.state = 'checking';
  5586. task.params.onTaskStart && task.params.onTaskStart(formatTask(task));
  5587. !task.params.UploadData && (task.params.UploadData = {});
  5588. var apiParams = util.formatParams(task.api, task.params);
  5589. originApiMap[task.api].call(cos, apiParams, function (err, data) {
  5590. if (!cos._isRunningTask(task.id)) return;
  5591. if (task.state === 'checking' || task.state === 'uploading') {
  5592. task.state = err ? 'error' : 'success';
  5593. err && (task.error = err);
  5594. uploadingFileCount--;
  5595. emitListUpdate();
  5596. startNextTask();
  5597. task.callback && task.callback(err, data);
  5598. if (task.state === 'success') {
  5599. if (task.params) {
  5600. delete task.params.UploadData;
  5601. delete task.params.Body;
  5602. delete task.params;
  5603. }
  5604. delete task.callback;
  5605. }
  5606. }
  5607. clearQueue();
  5608. });
  5609. emitListUpdate();
  5610. // 异步执行下一个任务
  5611. setTimeout(startNextTask);
  5612. };
  5613. var killTask = function killTask(id, switchToState) {
  5614. var task = tasks[id];
  5615. if (!task) return;
  5616. var waiting = task && task.state === 'waiting';
  5617. var running = task && (task.state === 'checking' || task.state === 'uploading');
  5618. if (switchToState === 'canceled' && task.state !== 'canceled' || switchToState === 'paused' && waiting || switchToState === 'paused' && running) {
  5619. if (switchToState === 'paused' && task.params.Body && typeof task.params.Body.pipe === 'function') {
  5620. console.error('stream not support pause');
  5621. return;
  5622. }
  5623. task.state = switchToState;
  5624. cos.emit('inner-kill-task', { TaskId: id, toState: switchToState });
  5625. try {
  5626. var UploadId = task && task.params && task.params.UploadData.UploadId;
  5627. } catch (e) {}
  5628. if (switchToState === 'canceled' && UploadId) session.removeUsing(UploadId);
  5629. emitListUpdate();
  5630. if (running) {
  5631. uploadingFileCount--;
  5632. startNextTask();
  5633. }
  5634. if (switchToState === 'canceled') {
  5635. if (task.params) {
  5636. delete task.params.UploadData;
  5637. delete task.params.Body;
  5638. delete task.params;
  5639. }
  5640. delete task.callback;
  5641. }
  5642. }
  5643. clearQueue();
  5644. };
  5645. cos._addTasks = function (taskList) {
  5646. util.each(taskList, function (task) {
  5647. cos._addTask(task.api, task.params, task.callback, true);
  5648. });
  5649. emitListUpdate();
  5650. };
  5651. cos._addTask = function (api, params, callback, ignoreAddEvent) {
  5652. // 如果小程序版本不支持获取文件分片内容,统一转到 postObject 接口上传
  5653. if (api === 'sliceUploadFile' && !util.canFileSlice()) api = 'postObject';
  5654. // 复制参数对象
  5655. params = util.formatParams(api, params);
  5656. // 生成 id
  5657. var id = util.uuid();
  5658. params.TaskId = id;
  5659. params.onTaskReady && params.onTaskReady(id);
  5660. var task = {
  5661. // env
  5662. params: params,
  5663. callback: callback,
  5664. api: api,
  5665. index: queue.length,
  5666. // task
  5667. id: id,
  5668. Bucket: params.Bucket,
  5669. Region: params.Region,
  5670. Key: params.Key,
  5671. FilePath: params.FilePath || '',
  5672. state: 'waiting',
  5673. loaded: 0,
  5674. size: 0,
  5675. speed: 0,
  5676. percent: 0,
  5677. hashPercent: 0,
  5678. error: null
  5679. };
  5680. var onHashProgress = params.onHashProgress;
  5681. params.onHashProgress = function (info) {
  5682. if (!cos._isRunningTask(task.id)) return;
  5683. task.hashPercent = info.percent;
  5684. onHashProgress && onHashProgress(info);
  5685. emitListUpdate();
  5686. };
  5687. var onProgress = params.onProgress;
  5688. params.onProgress = function (info) {
  5689. if (!cos._isRunningTask(task.id)) return;
  5690. task.state === 'checking' && (task.state = 'uploading');
  5691. task.loaded = info.loaded;
  5692. task.size = info.total;
  5693. task.speed = info.speed;
  5694. task.percent = info.percent;
  5695. onProgress && onProgress(info);
  5696. emitListUpdate();
  5697. };
  5698. // 异步获取 filesize
  5699. util.getFileSize(api, params, function (err, size) {
  5700. // 开始处理上传
  5701. if (err) {
  5702. // 如果获取大小出错,不加入队列
  5703. callback(err);
  5704. return;
  5705. }
  5706. // 获取完文件大小再把任务加入队列
  5707. tasks[id] = task;
  5708. queue.push(task);
  5709. task.size = size;
  5710. !ignoreAddEvent && emitListUpdate();
  5711. startNextTask();
  5712. clearQueue();
  5713. });
  5714. return id;
  5715. };
  5716. cos._isRunningTask = function (id) {
  5717. var task = tasks[id];
  5718. return !!(task && (task.state === 'checking' || task.state === 'uploading'));
  5719. };
  5720. cos.getTaskList = function () {
  5721. return util.map(queue, formatTask);
  5722. };
  5723. cos.cancelTask = function (id) {
  5724. killTask(id, 'canceled');
  5725. };
  5726. cos.pauseTask = function (id) {
  5727. killTask(id, 'paused');
  5728. };
  5729. cos.restartTask = function (id) {
  5730. var task = tasks[id];
  5731. if (task && (task.state === 'paused' || task.state === 'error')) {
  5732. task.state = 'waiting';
  5733. emitListUpdate();
  5734. nextUploadIndex = Math.min(nextUploadIndex, task.index);
  5735. startNextTask();
  5736. }
  5737. };
  5738. cos.isUploadRunning = function () {
  5739. return uploadingFileCount || nextUploadIndex < queue.length;
  5740. };
  5741. };
  5742. module.exports.transferToTaskMethod = transferToTaskMethod;
  5743. module.exports.init = initTask;
  5744. /***/ }),
  5745. /* 21 */
  5746. /***/ (function(module, exports, __webpack_require__) {
  5747. "use strict";
  5748. var REQUEST = __webpack_require__(22);
  5749. var base64 = __webpack_require__(4);
  5750. var util = __webpack_require__(0);
  5751. var mime = __webpack_require__(23);
  5752. // Bucket 相关
  5753. /**
  5754. * 获取用户的 bucket 列表
  5755. * @param {Object} params 回调函数,必须,下面为参数列表
  5756. * 无特殊参数
  5757. * @param {Function} callback 回调函数,必须
  5758. */
  5759. function getService(params, callback) {
  5760. if (typeof params === 'function') {
  5761. callback = params;
  5762. params = {};
  5763. }
  5764. var protocol = 'https:';
  5765. var domain = this.options.ServiceDomain;
  5766. var region = params.Region;
  5767. if (domain) {
  5768. domain = domain.replace(/\{\{Region\}\}/ig, region || '').replace(/\{\{.*?\}\}/ig, '');
  5769. if (!/^[a-zA-Z]+:\/\//.test(domain)) {
  5770. domain = protocol + '//' + domain;
  5771. }
  5772. if (domain.slice(-1) === '/') {
  5773. domain = domain.slice(0, -1);
  5774. }
  5775. } else if (region) {
  5776. domain = protocol + '//cos.' + region + '.myqcloud.com';
  5777. } else {
  5778. domain = protocol + '//service.cos.myqcloud.com';
  5779. }
  5780. var SignHost = '';
  5781. var standardHost = region ? 'cos.' + region + '.myqcloud.com' : 'service.cos.myqcloud.com';
  5782. var urlHost = domain.replace(/^https?:\/\/([^/]+)(\/.*)?$/, '$1');
  5783. if (standardHost === urlHost) SignHost = standardHost;
  5784. submitRequest.call(this, {
  5785. Action: 'name/cos:GetService',
  5786. url: domain,
  5787. method: 'GET',
  5788. headers: params.Headers
  5789. }, function (err, data) {
  5790. if (err) return callback(err);
  5791. var buckets = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Buckets && data.ListAllMyBucketsResult.Buckets.Bucket || [];
  5792. buckets = util.isArray(buckets) ? buckets : [buckets];
  5793. var owner = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Owner || {};
  5794. callback(null, {
  5795. Buckets: buckets,
  5796. Owner: owner,
  5797. statusCode: data.statusCode,
  5798. headers: data.headers
  5799. });
  5800. });
  5801. }
  5802. /**
  5803. * 创建 Bucket,并初始化访问权限
  5804. * @param {Object} params 参数对象,必须
  5805. * @param {String} params.Bucket Bucket名称,必须
  5806. * @param {String} params.Region 地域名称,必须
  5807. * @param {String} params.ACL 用户自定义文件权限,可以设置:private,public-read;默认值:private,非必须
  5808. * @param {String} params.GrantRead 赋予被授权者读的权限,格式x-cos-grant-read: uin=" ",uin=" ",非必须
  5809. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式x-cos-grant-write: uin=" ",uin=" ",非必须
  5810. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式x-cos-grant-full-control: uin=" ",uin=" ",非必须
  5811. * @param {Function} callback 回调函数,必须
  5812. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5813. * @return {Object} data 返回的数据
  5814. * @return {String} data.Location 操作地址
  5815. */
  5816. function putBucket(params, callback) {
  5817. var self = this;
  5818. var xml = '';
  5819. if (params['BucketAZConfig']) {
  5820. var CreateBucketConfiguration = {
  5821. BucketAZConfig: params.BucketAZConfig
  5822. };
  5823. xml = util.json2xml({ CreateBucketConfiguration: CreateBucketConfiguration });
  5824. }
  5825. submitRequest.call(this, {
  5826. Action: 'name/cos:PutBucket',
  5827. method: 'PUT',
  5828. Bucket: params.Bucket,
  5829. Region: params.Region,
  5830. headers: params.Headers,
  5831. body: xml
  5832. }, function (err, data) {
  5833. if (err) return callback(err);
  5834. var url = getUrl({
  5835. protocol: self.options.Protocol,
  5836. domain: self.options.Domain,
  5837. bucket: params.Bucket,
  5838. region: params.Region,
  5839. isLocation: true
  5840. });
  5841. callback(null, {
  5842. Location: url,
  5843. statusCode: data.statusCode,
  5844. headers: data.headers
  5845. });
  5846. });
  5847. }
  5848. /**
  5849. * 查看是否存在该Bucket,是否有权限访问
  5850. * @param {Object} params 参数对象,必须
  5851. * @param {String} params.Bucket Bucket名称,必须
  5852. * @param {String} params.Region 地域名称,必须
  5853. * @param {Function} callback 回调函数,必须
  5854. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5855. * @return {Object} data 返回的数据
  5856. * @return {Boolean} data.BucketExist Bucket是否存在
  5857. * @return {Boolean} data.BucketAuth 是否有 Bucket 的访问权限
  5858. */
  5859. function headBucket(params, callback) {
  5860. submitRequest.call(this, {
  5861. Action: 'name/cos:HeadBucket',
  5862. Bucket: params.Bucket,
  5863. Region: params.Region,
  5864. headers: params.Headers,
  5865. method: 'HEAD'
  5866. }, function (err, data) {
  5867. callback(err, data);
  5868. });
  5869. }
  5870. /**
  5871. * 获取 Bucket 下的 object 列表
  5872. * @param {Object} params 参数对象,必须
  5873. * @param {String} params.Bucket Bucket名称,必须
  5874. * @param {String} params.Region 地域名称,必须
  5875. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  5876. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,非必须
  5877. * @param {String} params.Marker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  5878. * @param {String} params.MaxKeys 单次返回最大的条目数量,默认1000,非必须
  5879. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  5880. * @param {Function} callback 回调函数,必须
  5881. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5882. * @return {Object} data 返回的数据
  5883. * @return {Object} data.ListBucketResult 返回的 object 列表信息
  5884. */
  5885. function getBucket(params, callback) {
  5886. var reqParams = {};
  5887. reqParams['prefix'] = params['Prefix'] || '';
  5888. reqParams['delimiter'] = params['Delimiter'];
  5889. reqParams['marker'] = params['Marker'];
  5890. reqParams['max-keys'] = params['MaxKeys'];
  5891. reqParams['encoding-type'] = params['EncodingType'];
  5892. submitRequest.call(this, {
  5893. Action: 'name/cos:GetBucket',
  5894. ResourceKey: reqParams['prefix'],
  5895. method: 'GET',
  5896. Bucket: params.Bucket,
  5897. Region: params.Region,
  5898. headers: params.Headers,
  5899. qs: reqParams
  5900. }, function (err, data) {
  5901. if (err) return callback(err);
  5902. var ListBucketResult = data.ListBucketResult || {};
  5903. var Contents = ListBucketResult.Contents || [];
  5904. var CommonPrefixes = ListBucketResult.CommonPrefixes || [];
  5905. Contents = util.isArray(Contents) ? Contents : [Contents];
  5906. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  5907. var result = util.clone(ListBucketResult);
  5908. util.extend(result, {
  5909. Contents: Contents,
  5910. CommonPrefixes: CommonPrefixes,
  5911. statusCode: data.statusCode,
  5912. headers: data.headers
  5913. });
  5914. callback(null, result);
  5915. });
  5916. }
  5917. /**
  5918. * 删除 Bucket
  5919. * @param {Object} params 参数对象,必须
  5920. * @param {String} params.Bucket Bucket名称,必须
  5921. * @param {String} params.Region 地域名称,必须
  5922. * @param {Function} callback 回调函数,必须
  5923. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5924. * @return {Object} data 返回的数据
  5925. * @return {String} data.Location 操作地址
  5926. */
  5927. function deleteBucket(params, callback) {
  5928. submitRequest.call(this, {
  5929. Action: 'name/cos:DeleteBucket',
  5930. Bucket: params.Bucket,
  5931. Region: params.Region,
  5932. headers: params.Headers,
  5933. method: 'DELETE'
  5934. }, function (err, data) {
  5935. if (err && err.statusCode === 204) {
  5936. return callback(null, { statusCode: err.statusCode });
  5937. } else if (err) {
  5938. return callback(err);
  5939. }
  5940. callback(null, {
  5941. statusCode: data.statusCode,
  5942. headers: data.headers
  5943. });
  5944. });
  5945. }
  5946. /**
  5947. * 设置 Bucket 的 权限列表
  5948. * @param {Object} params 参数对象,必须
  5949. * @param {String} params.Bucket Bucket名称,必须
  5950. * @param {String} params.Region 地域名称,必须
  5951. * @param {String} params.ACL 用户自定义文件权限,可以设置:private,public-read;默认值:private,非必须
  5952. * @param {String} params.GrantRead 赋予被授权者读的权限,格式x-cos-grant-read: uin=" ",uin=" ",非必须
  5953. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式x-cos-grant-write: uin=" ",uin=" ",非必须
  5954. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式x-cos-grant-full-control: uin=" ",uin=" ",非必须
  5955. * @param {Function} callback 回调函数,必须
  5956. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5957. * @return {Object} data 返回的数据
  5958. */
  5959. function putBucketAcl(params, callback) {
  5960. var headers = params.Headers;
  5961. var xml = '';
  5962. if (params['AccessControlPolicy']) {
  5963. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  5964. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  5965. Grants = util.isArray(Grants) ? Grants : [Grants];
  5966. delete AccessControlPolicy.Grant;
  5967. delete AccessControlPolicy.Grants;
  5968. AccessControlPolicy.AccessControlList = { Grant: Grants };
  5969. xml = util.json2xml({ AccessControlPolicy: AccessControlPolicy });
  5970. headers['Content-Type'] = 'application/xml';
  5971. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5972. }
  5973. // Grant Header 去重
  5974. util.each(headers, function (val, key) {
  5975. if (key.indexOf('x-cos-grant-') === 0) {
  5976. headers[key] = uniqGrant(headers[key]);
  5977. }
  5978. });
  5979. submitRequest.call(this, {
  5980. Action: 'name/cos:PutBucketACL',
  5981. method: 'PUT',
  5982. Bucket: params.Bucket,
  5983. Region: params.Region,
  5984. headers: headers,
  5985. action: 'acl',
  5986. body: xml
  5987. }, function (err, data) {
  5988. if (err) return callback(err);
  5989. callback(null, {
  5990. statusCode: data.statusCode,
  5991. headers: data.headers
  5992. });
  5993. });
  5994. }
  5995. /**
  5996. * 获取 Bucket 的 权限列表
  5997. * @param {Object} params 参数对象,必须
  5998. * @param {String} params.Bucket Bucket名称,必须
  5999. * @param {String} params.Region 地域名称,必须
  6000. * @param {Function} callback 回调函数,必须
  6001. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6002. * @return {Object} data 返回的数据
  6003. * @return {Object} data.AccessControlPolicy 访问权限信息
  6004. */
  6005. function getBucketAcl(params, callback) {
  6006. submitRequest.call(this, {
  6007. Action: 'name/cos:GetBucketACL',
  6008. method: 'GET',
  6009. Bucket: params.Bucket,
  6010. Region: params.Region,
  6011. headers: params.Headers,
  6012. action: 'acl'
  6013. }, function (err, data) {
  6014. if (err) return callback(err);
  6015. var AccessControlPolicy = data.AccessControlPolicy || {};
  6016. var Owner = AccessControlPolicy.Owner || {};
  6017. var Grant = AccessControlPolicy.AccessControlList.Grant || [];
  6018. Grant = util.isArray(Grant) ? Grant : [Grant];
  6019. var result = decodeAcl(AccessControlPolicy);
  6020. if (data.headers && data.headers['x-cos-acl']) {
  6021. result.ACL = data.headers['x-cos-acl'];
  6022. }
  6023. result = util.extend(result, {
  6024. Owner: Owner,
  6025. Grants: Grant,
  6026. statusCode: data.statusCode,
  6027. headers: data.headers
  6028. });
  6029. callback(null, result);
  6030. });
  6031. }
  6032. /**
  6033. * 设置 Bucket 的 跨域设置
  6034. * @param {Object} params 参数对象,必须
  6035. * @param {String} params.Bucket Bucket名称,必须
  6036. * @param {String} params.Region 地域名称,必须
  6037. * @param {Object} params.CORSConfiguration 相关的跨域设置,必须
  6038. * @param {Array} params.CORSConfiguration.CORSRules 对应的跨域规则
  6039. * @param {Function} callback 回调函数,必须
  6040. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6041. * @return {Object} data 返回的数据
  6042. */
  6043. function putBucketCors(params, callback) {
  6044. var CORSConfiguration = params['CORSConfiguration'] || {};
  6045. var CORSRules = CORSConfiguration['CORSRules'] || params['CORSRules'] || [];
  6046. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  6047. util.each(CORSRules, function (rule) {
  6048. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {
  6049. var sKey = key + 's';
  6050. var val = rule[sKey] || rule[key] || [];
  6051. delete rule[sKey];
  6052. rule[key] = util.isArray(val) ? val : [val];
  6053. });
  6054. });
  6055. var Conf = { CORSRule: CORSRules };
  6056. if (params.ResponseVary) Conf.ResponseVary = params.ResponseVary;
  6057. var xml = util.json2xml({ CORSConfiguration: Conf });
  6058. var headers = params.Headers;
  6059. headers['Content-Type'] = 'application/xml';
  6060. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6061. submitRequest.call(this, {
  6062. Action: 'name/cos:PutBucketCORS',
  6063. method: 'PUT',
  6064. Bucket: params.Bucket,
  6065. Region: params.Region,
  6066. body: xml,
  6067. action: 'cors',
  6068. headers: headers
  6069. }, function (err, data) {
  6070. if (err) return callback(err);
  6071. callback(null, {
  6072. statusCode: data.statusCode,
  6073. headers: data.headers
  6074. });
  6075. });
  6076. }
  6077. /**
  6078. * 获取 Bucket 的 跨域设置
  6079. * @param {Object} params 参数对象,必须
  6080. * @param {String} params.Bucket Bucket名称,必须
  6081. * @param {String} params.Region 地域名称,必须
  6082. * @param {Function} callback 回调函数,必须
  6083. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6084. * @return {Object} data 返回的数据
  6085. * @return {Object} data.CORSRules Bucket的跨域设置
  6086. */
  6087. function getBucketCors(params, callback) {
  6088. submitRequest.call(this, {
  6089. Action: 'name/cos:GetBucketCORS',
  6090. method: 'GET',
  6091. Bucket: params.Bucket,
  6092. Region: params.Region,
  6093. headers: params.Headers,
  6094. action: 'cors'
  6095. }, function (err, data) {
  6096. if (err) {
  6097. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchCORSConfiguration') {
  6098. var result = {
  6099. CORSRules: [],
  6100. statusCode: err.statusCode
  6101. };
  6102. err.headers && (result.headers = err.headers);
  6103. callback(null, result);
  6104. } else {
  6105. callback(err);
  6106. }
  6107. return;
  6108. }
  6109. var CORSConfiguration = data.CORSConfiguration || {};
  6110. var CORSRules = CORSConfiguration.CORSRules || CORSConfiguration.CORSRule || [];
  6111. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  6112. var ResponseVary = CORSConfiguration.ResponseVary;
  6113. util.each(CORSRules, function (rule) {
  6114. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {
  6115. var sKey = key + 's';
  6116. var val = rule[sKey] || rule[key] || [];
  6117. delete rule[key];
  6118. rule[sKey] = util.isArray(val) ? val : [val];
  6119. });
  6120. });
  6121. callback(null, {
  6122. CORSRules: CORSRules,
  6123. ResponseVary: ResponseVary,
  6124. statusCode: data.statusCode,
  6125. headers: data.headers
  6126. });
  6127. });
  6128. }
  6129. /**
  6130. * 删除 Bucket 的 跨域设置
  6131. * @param {Object} params 参数对象,必须
  6132. * @param {String} params.Bucket Bucket名称,必须
  6133. * @param {String} params.Region 地域名称,必须
  6134. * @param {Function} callback 回调函数,必须
  6135. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6136. * @return {Object} data 返回的数据
  6137. */
  6138. function deleteBucketCors(params, callback) {
  6139. submitRequest.call(this, {
  6140. Action: 'name/cos:DeleteBucketCORS',
  6141. method: 'DELETE',
  6142. Bucket: params.Bucket,
  6143. Region: params.Region,
  6144. headers: params.Headers,
  6145. action: 'cors'
  6146. }, function (err, data) {
  6147. if (err && err.statusCode === 204) {
  6148. return callback(null, { statusCode: err.statusCode });
  6149. } else if (err) {
  6150. return callback(err);
  6151. }
  6152. callback(null, {
  6153. statusCode: data.statusCode || err.statusCode,
  6154. headers: data.headers
  6155. });
  6156. });
  6157. }
  6158. /**
  6159. * 获取 Bucket 的 地域信息
  6160. * @param {Object} params 参数对象,必须
  6161. * @param {String} params.Bucket Bucket名称,必须
  6162. * @param {String} params.Region 地域名称,必须
  6163. * @param {Function} callback 回调函数,必须
  6164. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6165. * @return {Object} data 返回数据,包含地域信息 LocationConstraint
  6166. */
  6167. function getBucketLocation(params, callback) {
  6168. submitRequest.call(this, {
  6169. Action: 'name/cos:GetBucketLocation',
  6170. method: 'GET',
  6171. Bucket: params.Bucket,
  6172. Region: params.Region,
  6173. headers: params.Headers,
  6174. action: 'location'
  6175. }, function (err, data) {
  6176. if (err) return callback(err);
  6177. callback(null, data);
  6178. });
  6179. }
  6180. function putBucketPolicy(params, callback) {
  6181. var Policy = params['Policy'];
  6182. var PolicyStr = Policy;
  6183. try {
  6184. if (typeof Policy === 'string') {
  6185. Policy = JSON.parse(PolicyStr);
  6186. } else {
  6187. PolicyStr = JSON.stringify(Policy);
  6188. }
  6189. } catch (e) {
  6190. callback({ error: 'Policy format error' });
  6191. }
  6192. var headers = params.Headers;
  6193. headers['Content-Type'] = 'application/json';
  6194. headers['Content-MD5'] = util.binaryBase64(util.md5(PolicyStr));
  6195. submitRequest.call(this, {
  6196. Action: 'name/cos:PutBucketPolicy',
  6197. method: 'PUT',
  6198. Bucket: params.Bucket,
  6199. Region: params.Region,
  6200. action: 'policy',
  6201. body: PolicyStr,
  6202. headers: headers,
  6203. json: true
  6204. }, function (err, data) {
  6205. if (err && err.statusCode === 204) {
  6206. return callback(null, { statusCode: err.statusCode });
  6207. } else if (err) {
  6208. return callback(err);
  6209. }
  6210. callback(null, {
  6211. statusCode: data.statusCode,
  6212. headers: data.headers
  6213. });
  6214. });
  6215. }
  6216. /**
  6217. * 获取 Bucket 的读取权限策略
  6218. * @param {Object} params 参数对象,必须
  6219. * @param {String} params.Bucket Bucket名称,必须
  6220. * @param {String} params.Region 地域名称,必须
  6221. * @param {Function} callback 回调函数,必须
  6222. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6223. * @return {Object} data 返回数据
  6224. */
  6225. function getBucketPolicy(params, callback) {
  6226. submitRequest.call(this, {
  6227. Action: 'name/cos:GetBucketPolicy',
  6228. method: 'GET',
  6229. Bucket: params.Bucket,
  6230. Region: params.Region,
  6231. headers: params.Headers,
  6232. action: 'policy',
  6233. rawBody: true
  6234. }, function (err, data) {
  6235. if (err) {
  6236. if (err.statusCode && err.statusCode === 403) {
  6237. return callback({ ErrorStatus: 'Access Denied' });
  6238. }
  6239. if (err.statusCode && err.statusCode === 405) {
  6240. return callback({ ErrorStatus: 'Method Not Allowed' });
  6241. }
  6242. if (err.statusCode && err.statusCode === 404) {
  6243. return callback({ ErrorStatus: 'Policy Not Found' });
  6244. }
  6245. return callback(err);
  6246. }
  6247. var Policy = {};
  6248. try {
  6249. Policy = JSON.parse(data.body);
  6250. } catch (e) {}
  6251. callback(null, {
  6252. Policy: Policy,
  6253. statusCode: data.statusCode,
  6254. headers: data.headers
  6255. });
  6256. });
  6257. }
  6258. /**
  6259. * 删除 Bucket 的 跨域设置
  6260. * @param {Object} params 参数对象,必须
  6261. * @param {String} params.Bucket Bucket名称,必须
  6262. * @param {String} params.Region 地域名称,必须
  6263. * @param {Function} callback 回调函数,必须
  6264. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6265. * @return {Object} data 返回的数据
  6266. */
  6267. function deleteBucketPolicy(params, callback) {
  6268. submitRequest.call(this, {
  6269. Action: 'name/cos:DeleteBucketPolicy',
  6270. method: 'DELETE',
  6271. Bucket: params.Bucket,
  6272. Region: params.Region,
  6273. headers: params.Headers,
  6274. action: 'policy'
  6275. }, function (err, data) {
  6276. if (err && err.statusCode === 204) {
  6277. return callback(null, { statusCode: err.statusCode });
  6278. } else if (err) {
  6279. return callback(err);
  6280. }
  6281. callback(null, {
  6282. statusCode: data.statusCode || err.statusCode,
  6283. headers: data.headers
  6284. });
  6285. });
  6286. }
  6287. /**
  6288. * 设置 Bucket 的标签
  6289. * @param {Object} params 参数对象,必须
  6290. * @param {String} params.Bucket Bucket名称,必须
  6291. * @param {String} params.Region 地域名称,必须
  6292. * @param {Array} params.TagSet 标签设置,必须
  6293. * @param {Function} callback 回调函数,必须
  6294. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6295. * @return {Object} data 返回数据
  6296. */
  6297. function putBucketTagging(params, callback) {
  6298. var Tagging = params['Tagging'] || {};
  6299. var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];
  6300. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  6301. var xml = util.json2xml({ Tagging: { TagSet: { Tag: Tags } } });
  6302. var headers = params.Headers;
  6303. headers['Content-Type'] = 'application/xml';
  6304. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6305. submitRequest.call(this, {
  6306. Action: 'name/cos:PutBucketTagging',
  6307. method: 'PUT',
  6308. Bucket: params.Bucket,
  6309. Region: params.Region,
  6310. body: xml,
  6311. action: 'tagging',
  6312. headers: headers
  6313. }, function (err, data) {
  6314. if (err && err.statusCode === 204) {
  6315. return callback(null, { statusCode: err.statusCode });
  6316. } else if (err) {
  6317. return callback(err);
  6318. }
  6319. callback(null, {
  6320. statusCode: data.statusCode,
  6321. headers: data.headers
  6322. });
  6323. });
  6324. }
  6325. /**
  6326. * 获取 Bucket 的标签设置
  6327. * @param {Object} params 参数对象,必须
  6328. * @param {String} params.Bucket Bucket名称,必须
  6329. * @param {String} params.Region 地域名称,必须
  6330. * @param {Function} callback 回调函数,必须
  6331. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6332. * @return {Object} data 返回数据
  6333. */
  6334. function getBucketTagging(params, callback) {
  6335. submitRequest.call(this, {
  6336. Action: 'name/cos:GetBucketTagging',
  6337. method: 'GET',
  6338. Bucket: params.Bucket,
  6339. Region: params.Region,
  6340. headers: params.Headers,
  6341. action: 'tagging'
  6342. }, function (err, data) {
  6343. if (err) {
  6344. if (err.statusCode === 404 && err.error && (err.error === "Not Found" || err.error.Code === 'NoSuchTagSet')) {
  6345. var result = {
  6346. Tags: [],
  6347. statusCode: err.statusCode
  6348. };
  6349. err.headers && (result.headers = err.headers);
  6350. callback(null, result);
  6351. } else {
  6352. callback(err);
  6353. }
  6354. return;
  6355. }
  6356. var Tags = [];
  6357. try {
  6358. Tags = data.Tagging.TagSet.Tag || [];
  6359. } catch (e) {}
  6360. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  6361. callback(null, {
  6362. Tags: Tags,
  6363. statusCode: data.statusCode,
  6364. headers: data.headers
  6365. });
  6366. });
  6367. }
  6368. /**
  6369. * 删除 Bucket 的 标签设置
  6370. * @param {Object} params 参数对象,必须
  6371. * @param {String} params.Bucket Bucket名称,必须
  6372. * @param {String} params.Region 地域名称,必须
  6373. * @param {Function} callback 回调函数,必须
  6374. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6375. * @return {Object} data 返回的数据
  6376. */
  6377. function deleteBucketTagging(params, callback) {
  6378. submitRequest.call(this, {
  6379. Action: 'name/cos:DeleteBucketTagging',
  6380. method: 'DELETE',
  6381. Bucket: params.Bucket,
  6382. Region: params.Region,
  6383. headers: params.Headers,
  6384. action: 'tagging'
  6385. }, function (err, data) {
  6386. if (err && err.statusCode === 204) {
  6387. return callback(null, { statusCode: err.statusCode });
  6388. } else if (err) {
  6389. return callback(err);
  6390. }
  6391. callback(null, {
  6392. statusCode: data.statusCode,
  6393. headers: data.headers
  6394. });
  6395. });
  6396. }
  6397. function putBucketLifecycle(params, callback) {
  6398. var LifecycleConfiguration = params['LifecycleConfiguration'] || {};
  6399. var Rules = LifecycleConfiguration.Rules || params.Rules || [];
  6400. Rules = util.clone(Rules);
  6401. var xml = util.json2xml({ LifecycleConfiguration: { Rule: Rules } });
  6402. var headers = params.Headers;
  6403. headers['Content-Type'] = 'application/xml';
  6404. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6405. submitRequest.call(this, {
  6406. Action: 'name/cos:PutBucketLifecycle',
  6407. method: 'PUT',
  6408. Bucket: params.Bucket,
  6409. Region: params.Region,
  6410. body: xml,
  6411. action: 'lifecycle',
  6412. headers: headers
  6413. }, function (err, data) {
  6414. if (err && err.statusCode === 204) {
  6415. return callback(null, { statusCode: err.statusCode });
  6416. } else if (err) {
  6417. return callback(err);
  6418. }
  6419. callback(null, {
  6420. statusCode: data.statusCode,
  6421. headers: data.headers
  6422. });
  6423. });
  6424. }
  6425. function getBucketLifecycle(params, callback) {
  6426. submitRequest.call(this, {
  6427. Action: 'name/cos:GetBucketLifecycle',
  6428. method: 'GET',
  6429. Bucket: params.Bucket,
  6430. Region: params.Region,
  6431. headers: params.Headers,
  6432. action: 'lifecycle'
  6433. }, function (err, data) {
  6434. if (err) {
  6435. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchLifecycleConfiguration') {
  6436. var result = {
  6437. Rules: [],
  6438. statusCode: err.statusCode
  6439. };
  6440. err.headers && (result.headers = err.headers);
  6441. callback(null, result);
  6442. } else {
  6443. callback(err);
  6444. }
  6445. return;
  6446. }
  6447. var Rules = [];
  6448. try {
  6449. Rules = data.LifecycleConfiguration.Rule || [];
  6450. } catch (e) {}
  6451. Rules = util.clone(util.isArray(Rules) ? Rules : [Rules]);
  6452. callback(null, {
  6453. Rules: Rules,
  6454. statusCode: data.statusCode,
  6455. headers: data.headers
  6456. });
  6457. });
  6458. }
  6459. function deleteBucketLifecycle(params, callback) {
  6460. submitRequest.call(this, {
  6461. Action: 'name/cos:DeleteBucketLifecycle',
  6462. method: 'DELETE',
  6463. Bucket: params.Bucket,
  6464. Region: params.Region,
  6465. headers: params.Headers,
  6466. action: 'lifecycle'
  6467. }, function (err, data) {
  6468. if (err && err.statusCode === 204) {
  6469. return callback(null, { statusCode: err.statusCode });
  6470. } else if (err) {
  6471. return callback(err);
  6472. }
  6473. callback(null, {
  6474. statusCode: data.statusCode,
  6475. headers: data.headers
  6476. });
  6477. });
  6478. }
  6479. function putBucketVersioning(params, callback) {
  6480. if (!params['VersioningConfiguration']) {
  6481. callback({ error: 'missing param VersioningConfiguration' });
  6482. return;
  6483. }
  6484. var VersioningConfiguration = params['VersioningConfiguration'] || {};
  6485. var xml = util.json2xml({ VersioningConfiguration: VersioningConfiguration });
  6486. var headers = params.Headers;
  6487. headers['Content-Type'] = 'application/xml';
  6488. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6489. submitRequest.call(this, {
  6490. Action: 'name/cos:PutBucketVersioning',
  6491. method: 'PUT',
  6492. Bucket: params.Bucket,
  6493. Region: params.Region,
  6494. body: xml,
  6495. action: 'versioning',
  6496. headers: headers
  6497. }, function (err, data) {
  6498. if (err && err.statusCode === 204) {
  6499. return callback(null, { statusCode: err.statusCode });
  6500. } else if (err) {
  6501. return callback(err);
  6502. }
  6503. callback(null, {
  6504. statusCode: data.statusCode,
  6505. headers: data.headers
  6506. });
  6507. });
  6508. }
  6509. function getBucketVersioning(params, callback) {
  6510. submitRequest.call(this, {
  6511. Action: 'name/cos:GetBucketVersioning',
  6512. method: 'GET',
  6513. Bucket: params.Bucket,
  6514. Region: params.Region,
  6515. headers: params.Headers,
  6516. action: 'versioning'
  6517. }, function (err, data) {
  6518. if (!err) {
  6519. !data.VersioningConfiguration && (data.VersioningConfiguration = {});
  6520. }
  6521. callback(err, data);
  6522. });
  6523. }
  6524. function putBucketReplication(params, callback) {
  6525. var ReplicationConfiguration = util.clone(params.ReplicationConfiguration);
  6526. var xml = util.json2xml({ ReplicationConfiguration: ReplicationConfiguration });
  6527. xml = xml.replace(/<(\/?)Rules>/ig, '<$1Rule>');
  6528. xml = xml.replace(/<(\/?)Tags>/ig, '<$1Tag>');
  6529. var headers = params.Headers;
  6530. headers['Content-Type'] = 'application/xml';
  6531. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6532. submitRequest.call(this, {
  6533. Action: 'name/cos:PutBucketReplication',
  6534. method: 'PUT',
  6535. Bucket: params.Bucket,
  6536. Region: params.Region,
  6537. body: xml,
  6538. action: 'replication',
  6539. headers: headers
  6540. }, function (err, data) {
  6541. if (err && err.statusCode === 204) {
  6542. return callback(null, { statusCode: err.statusCode });
  6543. } else if (err) {
  6544. return callback(err);
  6545. }
  6546. callback(null, {
  6547. statusCode: data.statusCode,
  6548. headers: data.headers
  6549. });
  6550. });
  6551. }
  6552. function getBucketReplication(params, callback) {
  6553. submitRequest.call(this, {
  6554. Action: 'name/cos:GetBucketReplication',
  6555. method: 'GET',
  6556. Bucket: params.Bucket,
  6557. Region: params.Region,
  6558. headers: params.Headers,
  6559. action: 'replication'
  6560. }, function (err, data) {
  6561. if (err) {
  6562. if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'ReplicationConfigurationnotFoundError')) {
  6563. var result = {
  6564. ReplicationConfiguration: { Rules: [] },
  6565. statusCode: err.statusCode
  6566. };
  6567. err.headers && (result.headers = err.headers);
  6568. callback(null, result);
  6569. } else {
  6570. callback(err);
  6571. }
  6572. return;
  6573. }
  6574. if (!err) {
  6575. !data.ReplicationConfiguration && (data.ReplicationConfiguration = {});
  6576. }
  6577. if (data.ReplicationConfiguration.Rule) {
  6578. data.ReplicationConfiguration.Rules = data.ReplicationConfiguration.Rule;
  6579. delete data.ReplicationConfiguration.Rule;
  6580. }
  6581. callback(err, data);
  6582. });
  6583. }
  6584. function deleteBucketReplication(params, callback) {
  6585. submitRequest.call(this, {
  6586. Action: 'name/cos:DeleteBucketReplication',
  6587. method: 'DELETE',
  6588. Bucket: params.Bucket,
  6589. Region: params.Region,
  6590. headers: params.Headers,
  6591. action: 'replication'
  6592. }, function (err, data) {
  6593. if (err && err.statusCode === 204) {
  6594. return callback(null, { statusCode: err.statusCode });
  6595. } else if (err) {
  6596. return callback(err);
  6597. }
  6598. callback(null, {
  6599. statusCode: data.statusCode,
  6600. headers: data.headers
  6601. });
  6602. });
  6603. }
  6604. /**
  6605. * 设置 Bucket 静态网站配置信息
  6606. * @param {Object} params 参数对象,必须
  6607. * @param {String} params.Bucket Bucket名称,必须
  6608. * @param {String} params.Region 地域名称,必须
  6609. * @param {Object} params.WebsiteConfiguration 地域名称,必须
  6610. * @param {Object} WebsiteConfiguration.IndexDocument 索引文档,必须
  6611. * @param {Object} WebsiteConfiguration.ErrorDocument 错误文档,非必须
  6612. * @param {Object} WebsiteConfiguration.RedirectAllRequestsTo 重定向所有请求,非必须
  6613. * @param {Array} params.RoutingRules 重定向规则,非必须
  6614. * @param {Function} callback 回调函数,必须
  6615. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6616. * @return {Object} data 返回数据
  6617. */
  6618. function putBucketWebsite(params, callback) {
  6619. if (!params['WebsiteConfiguration']) {
  6620. callback({ error: 'missing param WebsiteConfiguration' });
  6621. return;
  6622. }
  6623. var WebsiteConfiguration = util.clone(params['WebsiteConfiguration'] || {});
  6624. var RoutingRules = WebsiteConfiguration['RoutingRules'] || WebsiteConfiguration['RoutingRule'] || [];
  6625. RoutingRules = util.isArray(RoutingRules) ? RoutingRules : [RoutingRules];
  6626. delete WebsiteConfiguration.RoutingRule;
  6627. delete WebsiteConfiguration.RoutingRules;
  6628. if (RoutingRules.length) WebsiteConfiguration.RoutingRules = { RoutingRule: RoutingRules };
  6629. var xml = util.json2xml({ WebsiteConfiguration: WebsiteConfiguration });
  6630. var headers = params.Headers;
  6631. headers['Content-Type'] = 'application/xml';
  6632. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6633. submitRequest.call(this, {
  6634. Action: 'name/cos:PutBucketWebsite',
  6635. method: 'PUT',
  6636. Bucket: params.Bucket,
  6637. Region: params.Region,
  6638. body: xml,
  6639. action: 'website',
  6640. headers: headers
  6641. }, function (err, data) {
  6642. if (err && err.statusCode === 204) {
  6643. return callback(null, { statusCode: err.statusCode });
  6644. } else if (err) {
  6645. return callback(err);
  6646. }
  6647. callback(null, {
  6648. statusCode: data.statusCode,
  6649. headers: data.headers
  6650. });
  6651. });
  6652. }
  6653. /**
  6654. * 获取 Bucket 的静态网站配置信息
  6655. * @param {Object} params 参数对象,必须
  6656. * @param {String} params.Bucket Bucket名称,必须
  6657. * @param {String} params.Region 地域名称,必须
  6658. * @param {Function} callback 回调函数,必须
  6659. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6660. * @return {Object} data 返回数据
  6661. */
  6662. function getBucketWebsite(params, callback) {
  6663. submitRequest.call(this, {
  6664. Action: 'name/cos:GetBucketWebsite',
  6665. method: 'GET',
  6666. Bucket: params.Bucket,
  6667. Region: params.Region,
  6668. Key: params.Key,
  6669. headers: params.Headers,
  6670. action: 'website'
  6671. }, function (err, data) {
  6672. if (err) {
  6673. if (err.statusCode === 404 && err.error.Code === 'NoSuchWebsiteConfiguration') {
  6674. var result = {
  6675. WebsiteConfiguration: {},
  6676. statusCode: err.statusCode
  6677. };
  6678. err.headers && (result.headers = err.headers);
  6679. callback(null, result);
  6680. } else {
  6681. callback(err);
  6682. }
  6683. return;
  6684. }
  6685. var WebsiteConfiguration = data.WebsiteConfiguration || {};
  6686. if (WebsiteConfiguration['RoutingRules']) {
  6687. var RoutingRules = util.clone(WebsiteConfiguration['RoutingRules'].RoutingRule || []);
  6688. RoutingRules = util.makeArray(RoutingRules);
  6689. WebsiteConfiguration.RoutingRules = RoutingRules;
  6690. }
  6691. callback(null, {
  6692. WebsiteConfiguration: WebsiteConfiguration,
  6693. statusCode: data.statusCode,
  6694. headers: data.headers
  6695. });
  6696. });
  6697. }
  6698. /**
  6699. * 删除 Bucket 的静态网站配置
  6700. * @param {Object} params 参数对象,必须
  6701. * @param {String} params.Bucket Bucket名称,必须
  6702. * @param {String} params.Region 地域名称,必须
  6703. * @param {Function} callback 回调函数,必须
  6704. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6705. * @return {Object} data 返回数据
  6706. */
  6707. function deleteBucketWebsite(params, callback) {
  6708. submitRequest.call(this, {
  6709. Action: 'name/cos:DeleteBucketWebsite',
  6710. method: 'DELETE',
  6711. Bucket: params.Bucket,
  6712. Region: params.Region,
  6713. headers: params.Headers,
  6714. action: 'website'
  6715. }, function (err, data) {
  6716. if (err && err.statusCode === 204) {
  6717. return callback(null, { statusCode: err.statusCode });
  6718. } else if (err) {
  6719. return callback(err);
  6720. }
  6721. callback(null, {
  6722. statusCode: data.statusCode,
  6723. headers: data.headers
  6724. });
  6725. });
  6726. }
  6727. /**
  6728. * 设置 Bucket 的防盗链白名单或者黑名单
  6729. * @param {Object} params 参数对象,必须
  6730. * @param {String} params.Bucket Bucket名称,必须
  6731. * @param {String} params.Region 地域名称,必须
  6732. * @param {Object} params.RefererConfiguration 地域名称,必须
  6733. * @param {String} RefererConfiguration.Status 是否开启防盗链,枚举值:Enabled、Disabled
  6734. * @param {String} RefererConfiguration.RefererType 防盗链类型,枚举值:Black-List、White-List,必须
  6735. * @param {Array} RefererConfiguration.DomianList.Domain 生效域名,必须
  6736. * @param {String} RefererConfiguration.EmptyReferConfiguration ,非必须
  6737. * @param {Function} callback 回调函数,必须
  6738. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6739. * @return {Object} data 返回数据
  6740. */
  6741. function putBucketReferer(params, callback) {
  6742. if (!params['RefererConfiguration']) {
  6743. callback({ error: 'missing param RefererConfiguration' });
  6744. return;
  6745. }
  6746. var RefererConfiguration = util.clone(params['RefererConfiguration'] || {});
  6747. var DomainList = RefererConfiguration['DomainList'] || {};
  6748. var Domains = DomainList['Domains'] || DomainList['Domain'] || [];
  6749. Domains = util.isArray(Domains) ? Domains : [Domains];
  6750. if (Domains.length) RefererConfiguration.DomainList = { Domain: Domains };
  6751. var xml = util.json2xml({ RefererConfiguration: RefererConfiguration });
  6752. var headers = params.Headers;
  6753. headers['Content-Type'] = 'application/xml';
  6754. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6755. submitRequest.call(this, {
  6756. Action: 'name/cos:PutBucketReferer',
  6757. method: 'PUT',
  6758. Bucket: params.Bucket,
  6759. Region: params.Region,
  6760. body: xml,
  6761. action: 'referer',
  6762. headers: headers
  6763. }, function (err, data) {
  6764. if (err && err.statusCode === 204) {
  6765. return callback(null, { statusCode: err.statusCode });
  6766. } else if (err) {
  6767. return callback(err);
  6768. }
  6769. callback(null, {
  6770. statusCode: data.statusCode,
  6771. headers: data.headers
  6772. });
  6773. });
  6774. }
  6775. /**
  6776. * 获取 Bucket 的防盗链白名单或者黑名单
  6777. * @param {Object} params 参数对象,必须
  6778. * @param {String} params.Bucket Bucket名称,必须
  6779. * @param {String} params.Region 地域名称,必须
  6780. * @param {Function} callback 回调函数,必须
  6781. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6782. * @return {Object} data 返回数据
  6783. */
  6784. function getBucketReferer(params, callback) {
  6785. submitRequest.call(this, {
  6786. Action: 'name/cos:GetBucketReferer',
  6787. method: 'GET',
  6788. Bucket: params.Bucket,
  6789. Region: params.Region,
  6790. Key: params.Key,
  6791. headers: params.Headers,
  6792. action: 'referer'
  6793. }, function (err, data) {
  6794. if (err) {
  6795. if (err.statusCode === 404 && err.error.Code === 'NoSuchRefererConfiguration') {
  6796. var result = {
  6797. WebsiteConfiguration: {},
  6798. statusCode: err.statusCode
  6799. };
  6800. err.headers && (result.headers = err.headers);
  6801. callback(null, result);
  6802. } else {
  6803. callback(err);
  6804. }
  6805. return;
  6806. }
  6807. var RefererConfiguration = data.RefererConfiguration || {};
  6808. if (RefererConfiguration['DomainList']) {
  6809. var Domains = util.makeArray(RefererConfiguration['DomainList'].Domain || []);
  6810. RefererConfiguration.DomainList = { Domains: Domains };
  6811. }
  6812. callback(null, {
  6813. RefererConfiguration: RefererConfiguration,
  6814. statusCode: data.statusCode,
  6815. headers: data.headers
  6816. });
  6817. });
  6818. }
  6819. /**
  6820. * 设置 Bucket 自定义域名
  6821. * @param {Object} params 参数对象,必须
  6822. * @param {String} params.Bucket Bucket名称,必须
  6823. * @param {String} params.Region 地域名称,必须
  6824. * @param {Function} callback 回调函数,必须
  6825. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6826. * @return {Object} data 返回数据
  6827. */
  6828. function putBucketDomain(params, callback) {
  6829. var DomainConfiguration = params['DomainConfiguration'] || {};
  6830. var DomainRule = DomainConfiguration.DomainRule || params.DomainRule || [];
  6831. DomainRule = util.clone(DomainRule);
  6832. var xml = util.json2xml({ DomainConfiguration: { DomainRule: DomainRule } });
  6833. var headers = params.Headers;
  6834. headers['Content-Type'] = 'application/xml';
  6835. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6836. submitRequest.call(this, {
  6837. Action: 'name/cos:PutBucketDomain',
  6838. method: 'PUT',
  6839. Bucket: params.Bucket,
  6840. Region: params.Region,
  6841. body: xml,
  6842. action: 'domain',
  6843. headers: headers
  6844. }, function (err, data) {
  6845. if (err && err.statusCode === 204) {
  6846. return callback(null, { statusCode: err.statusCode });
  6847. } else if (err) {
  6848. return callback(err);
  6849. }
  6850. callback(null, {
  6851. statusCode: data.statusCode,
  6852. headers: data.headers
  6853. });
  6854. });
  6855. }
  6856. /**
  6857. * 获取 Bucket 的自定义域名
  6858. * @param {Object} params 参数对象,必须
  6859. * @param {String} params.Bucket Bucket名称,必须
  6860. * @param {String} params.Region 地域名称,必须
  6861. * @param {Function} callback 回调函数,必须
  6862. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6863. * @return {Object} data 返回数据
  6864. */
  6865. function getBucketDomain(params, callback) {
  6866. submitRequest.call(this, {
  6867. Action: 'name/cos:GetBucketDomain',
  6868. method: 'GET',
  6869. Bucket: params.Bucket,
  6870. Region: params.Region,
  6871. headers: params.Headers,
  6872. action: 'domain'
  6873. }, function (err, data) {
  6874. if (err) return callback(err);
  6875. var DomainRule = [];
  6876. try {
  6877. DomainRule = data.DomainConfiguration.DomainRule || [];
  6878. } catch (e) {}
  6879. DomainRule = util.clone(util.isArray(DomainRule) ? DomainRule : [DomainRule]);
  6880. callback(null, {
  6881. DomainRule: DomainRule,
  6882. statusCode: data.statusCode,
  6883. headers: data.headers
  6884. });
  6885. });
  6886. }
  6887. /**
  6888. * 删除 Bucket 自定义域名
  6889. * @param {Object} params 参数对象,必须
  6890. * @param {String} params.Bucket Bucket名称,必须
  6891. * @param {String} params.Region 地域名称,必须
  6892. * @param {Function} callback 回调函数,必须
  6893. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6894. * @return {Object} data 返回数据
  6895. */
  6896. function deleteBucketDomain(params, callback) {
  6897. submitRequest.call(this, {
  6898. Action: 'name/cos:DeleteBucketDomain',
  6899. method: 'DELETE',
  6900. Bucket: params.Bucket,
  6901. Region: params.Region,
  6902. headers: params.Headers,
  6903. action: 'domain'
  6904. }, function (err, data) {
  6905. if (err && err.statusCode === 204) {
  6906. return callback(null, { statusCode: err.statusCode });
  6907. } else if (err) {
  6908. return callback(err);
  6909. }
  6910. callback(null, {
  6911. statusCode: data.statusCode,
  6912. headers: data.headers
  6913. });
  6914. });
  6915. }
  6916. /**
  6917. * 设置 Bucket 的回源
  6918. * @param {Object} params 参数对象,必须
  6919. * @param {String} params.Bucket Bucket名称,必须
  6920. * @param {String} params.Region 地域名称,必须
  6921. * @param {Function} callback 回调函数,必须
  6922. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6923. * @return {Object} data 返回数据
  6924. */
  6925. function putBucketOrigin(params, callback) {
  6926. var OriginConfiguration = params['OriginConfiguration'] || {};
  6927. var OriginRule = OriginConfiguration.OriginRule || params.OriginRule || [];
  6928. OriginRule = util.clone(OriginRule);
  6929. var xml = util.json2xml({ OriginConfiguration: { OriginRule: OriginRule } });
  6930. var headers = params.Headers;
  6931. headers['Content-Type'] = 'application/xml';
  6932. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6933. submitRequest.call(this, {
  6934. Action: 'name/cos:PutBucketOrigin',
  6935. method: 'PUT',
  6936. Bucket: params.Bucket,
  6937. Region: params.Region,
  6938. body: xml,
  6939. action: 'origin',
  6940. headers: headers
  6941. }, function (err, data) {
  6942. if (err && err.statusCode === 204) {
  6943. return callback(null, { statusCode: err.statusCode });
  6944. } else if (err) {
  6945. return callback(err);
  6946. }
  6947. callback(null, {
  6948. statusCode: data.statusCode,
  6949. headers: data.headers
  6950. });
  6951. });
  6952. }
  6953. /**
  6954. * 获取 Bucket 的回源
  6955. * @param {Object} params 参数对象,必须
  6956. * @param {String} params.Bucket Bucket名称,必须
  6957. * @param {String} params.Region 地域名称,必须
  6958. * @param {Function} callback 回调函数,必须
  6959. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6960. * @return {Object} data 返回数据
  6961. */
  6962. function getBucketOrigin(params, callback) {
  6963. submitRequest.call(this, {
  6964. Action: 'name/cos:GetBucketOrigin',
  6965. method: 'GET',
  6966. Bucket: params.Bucket,
  6967. Region: params.Region,
  6968. headers: params.Headers,
  6969. action: 'origin'
  6970. }, function (err, data) {
  6971. if (err) return callback(err);
  6972. var OriginRule = [];
  6973. try {
  6974. OriginRule = data.OriginConfiguration.OriginRule || [];
  6975. } catch (e) {}
  6976. OriginRule = util.clone(util.isArray(OriginRule) ? OriginRule : [OriginRule]);
  6977. callback(null, {
  6978. OriginRule: OriginRule,
  6979. statusCode: data.statusCode,
  6980. headers: data.headers
  6981. });
  6982. });
  6983. }
  6984. /**
  6985. * 删除 Bucket 的回源
  6986. * @param {Object} params 参数对象,必须
  6987. * @param {String} params.Bucket Bucket名称,必须
  6988. * @param {String} params.Region 地域名称,必须
  6989. * @param {Function} callback 回调函数,必须
  6990. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6991. * @return {Object} data 返回数据
  6992. */
  6993. function deleteBucketOrigin(params, callback) {
  6994. submitRequest.call(this, {
  6995. Action: 'name/cos:DeleteBucketOrigin',
  6996. method: 'DELETE',
  6997. Bucket: params.Bucket,
  6998. Region: params.Region,
  6999. headers: params.Headers,
  7000. action: 'origin'
  7001. }, function (err, data) {
  7002. if (err && err.statusCode === 204) {
  7003. return callback(null, { statusCode: err.statusCode });
  7004. } else if (err) {
  7005. return callback(err);
  7006. }
  7007. callback(null, {
  7008. statusCode: data.statusCode,
  7009. headers: data.headers
  7010. });
  7011. });
  7012. }
  7013. /**
  7014. * 设置 Bucket 的日志记录
  7015. * @param {Object} params 参数对象,必须
  7016. * @param {String} params.Bucket Bucket名称,必须
  7017. * @param {String} params.Region 地域名称,必须
  7018. * @param {(Object|String)} params.BucketLoggingStatus 说明日志记录配置的状态,如果无子节点信息则意为关闭日志记录,必须
  7019. * @param {Function} callback 回调函数,必须
  7020. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7021. * @return {Object} data 返回数据
  7022. */
  7023. function putBucketLogging(params, callback) {
  7024. var xml = util.json2xml({
  7025. BucketLoggingStatus: params['BucketLoggingStatus'] || ''
  7026. });
  7027. var headers = params.Headers;
  7028. headers['Content-Type'] = 'application/xml';
  7029. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7030. submitRequest.call(this, {
  7031. Action: 'name/cos:PutBucketLogging',
  7032. method: 'PUT',
  7033. Bucket: params.Bucket,
  7034. Region: params.Region,
  7035. body: xml,
  7036. action: 'logging',
  7037. headers: headers
  7038. }, function (err, data) {
  7039. if (err && err.statusCode === 204) {
  7040. return callback(null, { statusCode: err.statusCode });
  7041. } else if (err) {
  7042. return callback(err);
  7043. }
  7044. callback(null, {
  7045. statusCode: data.statusCode,
  7046. headers: data.headers
  7047. });
  7048. });
  7049. }
  7050. /**
  7051. * 获取 Bucket 的日志记录
  7052. * @param {Object} params 参数对象,必须
  7053. * @param {String} params.Bucket Bucket名称,必须
  7054. * @param {String} params.Region 地域名称,必须
  7055. * @param {Function} callback 回调函数,必须
  7056. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7057. * @return {Object} data 返回数据
  7058. */
  7059. function getBucketLogging(params, callback) {
  7060. submitRequest.call(this, {
  7061. Action: 'name/cos:GetBucketLogging',
  7062. method: 'GET',
  7063. Bucket: params.Bucket,
  7064. Region: params.Region,
  7065. headers: params.Headers,
  7066. action: 'logging'
  7067. }, function (err, data) {
  7068. if (err) return callback(err);
  7069. delete data.BucketLoggingStatus._xmlns;
  7070. callback(null, {
  7071. BucketLoggingStatus: data.BucketLoggingStatus,
  7072. statusCode: data.statusCode,
  7073. headers: data.headers
  7074. });
  7075. });
  7076. }
  7077. /**
  7078. * 创建/编辑 Bucket 的清单任务
  7079. * @param {Object} params 参数对象,必须
  7080. * @param {String} params.Bucket Bucket名称,必须
  7081. * @param {String} params.Region 地域名称,必须
  7082. * @param {String} params.Id 清单任务的名称,必须
  7083. * @param {Object} params.InventoryConfiguration 包含清单的配置参数,必须
  7084. * @param {Function} callback 回调函数,必须
  7085. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7086. * @return {Object} data 返回数据
  7087. */
  7088. function putBucketInventory(params, callback) {
  7089. var InventoryConfiguration = util.clone(params['InventoryConfiguration']);
  7090. if (InventoryConfiguration.OptionalFields) {
  7091. var Field = InventoryConfiguration.OptionalFields || [];
  7092. InventoryConfiguration.OptionalFields = {
  7093. Field: Field
  7094. };
  7095. }
  7096. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  7097. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  7098. if (Object.keys(Encryption).indexOf('SSECOS') > -1) {
  7099. Encryption['SSE-COS'] = Encryption['SSECOS'];
  7100. delete Encryption['SSECOS'];
  7101. }
  7102. }
  7103. var xml = util.json2xml({
  7104. InventoryConfiguration: InventoryConfiguration
  7105. });
  7106. var headers = params.Headers;
  7107. headers['Content-Type'] = 'application/xml';
  7108. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7109. submitRequest.call(this, {
  7110. Action: 'name/cos:PutBucketInventory',
  7111. method: 'PUT',
  7112. Bucket: params.Bucket,
  7113. Region: params.Region,
  7114. body: xml,
  7115. action: 'inventory',
  7116. qs: {
  7117. id: params['Id']
  7118. },
  7119. headers: headers
  7120. }, function (err, data) {
  7121. if (err && err.statusCode === 204) {
  7122. return callback(null, { statusCode: err.statusCode });
  7123. } else if (err) {
  7124. return callback(err);
  7125. }
  7126. callback(null, {
  7127. statusCode: data.statusCode,
  7128. headers: data.headers
  7129. });
  7130. });
  7131. }
  7132. /**
  7133. * 获取 Bucket 的清单任务信息
  7134. * @param {Object} params 参数对象,必须
  7135. * @param {String} params.Bucket Bucket名称,必须
  7136. * @param {String} params.Region 地域名称,必须
  7137. * @param {String} params.Id 清单任务的名称,必须
  7138. * @param {Function} callback 回调函数,必须
  7139. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7140. * @return {Object} data 返回数据
  7141. */
  7142. function getBucketInventory(params, callback) {
  7143. submitRequest.call(this, {
  7144. Action: 'name/cos:GetBucketInventory',
  7145. method: 'GET',
  7146. Bucket: params.Bucket,
  7147. Region: params.Region,
  7148. headers: params.Headers,
  7149. action: 'inventory',
  7150. qs: {
  7151. id: params['Id']
  7152. }
  7153. }, function (err, data) {
  7154. if (err) return callback(err);
  7155. var InventoryConfiguration = data['InventoryConfiguration'];
  7156. if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {
  7157. var Field = InventoryConfiguration.OptionalFields.Field;
  7158. if (!util.isArray(Field)) {
  7159. Field = [Field];
  7160. }
  7161. InventoryConfiguration.OptionalFields = Field;
  7162. }
  7163. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  7164. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  7165. if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {
  7166. Encryption['SSECOS'] = Encryption['SSE-COS'];
  7167. delete Encryption['SSE-COS'];
  7168. }
  7169. }
  7170. callback(null, {
  7171. InventoryConfiguration: InventoryConfiguration,
  7172. statusCode: data.statusCode,
  7173. headers: data.headers
  7174. });
  7175. });
  7176. }
  7177. /**
  7178. * 获取 Bucket 的清单任务信息
  7179. * @param {Object} params 参数对象,必须
  7180. * @param {String} params.Bucket Bucket名称,必须
  7181. * @param {String} params.Region 地域名称,必须
  7182. * @param {String} params.ContinuationToken 当 COS 响应体中 IsTruncated 为 true,且 NextContinuationToken 节点中存在参数值时,您可以将这个参数作为 continuation-token 参数值,以获取下一页的清单任务信息,非必须
  7183. * @param {Function} callback 回调函数,必须
  7184. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7185. * @return {Object} data 返回数据
  7186. */
  7187. function listBucketInventory(params, callback) {
  7188. submitRequest.call(this, {
  7189. Action: 'name/cos:ListBucketInventory',
  7190. method: 'GET',
  7191. Bucket: params.Bucket,
  7192. Region: params.Region,
  7193. headers: params.Headers,
  7194. action: 'inventory',
  7195. qs: {
  7196. 'continuation-token': params['ContinuationToken']
  7197. }
  7198. }, function (err, data) {
  7199. if (err) return callback(err);
  7200. var ListInventoryConfigurationResult = data['ListInventoryConfigurationResult'];
  7201. var InventoryConfigurations = ListInventoryConfigurationResult.InventoryConfiguration || [];
  7202. InventoryConfigurations = util.isArray(InventoryConfigurations) ? InventoryConfigurations : [InventoryConfigurations];
  7203. delete ListInventoryConfigurationResult['InventoryConfiguration'];
  7204. util.each(InventoryConfigurations, function (InventoryConfiguration) {
  7205. if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {
  7206. var Field = InventoryConfiguration.OptionalFields.Field;
  7207. if (!util.isArray(Field)) {
  7208. Field = [Field];
  7209. }
  7210. InventoryConfiguration.OptionalFields = Field;
  7211. }
  7212. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  7213. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  7214. if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {
  7215. Encryption['SSECOS'] = Encryption['SSE-COS'];
  7216. delete Encryption['SSE-COS'];
  7217. }
  7218. }
  7219. });
  7220. ListInventoryConfigurationResult.InventoryConfigurations = InventoryConfigurations;
  7221. util.extend(ListInventoryConfigurationResult, {
  7222. statusCode: data.statusCode,
  7223. headers: data.headers
  7224. });
  7225. callback(null, ListInventoryConfigurationResult);
  7226. });
  7227. }
  7228. /**
  7229. * 删除 Bucket 的清单任务
  7230. * @param {Object} params 参数对象,必须
  7231. * @param {String} params.Bucket Bucket名称,必须
  7232. * @param {String} params.Region 地域名称,必须
  7233. * @param {String} params.Id 清单任务的名称,必须
  7234. * @param {Function} callback 回调函数,必须
  7235. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7236. * @return {Object} data 返回数据
  7237. */
  7238. function deleteBucketInventory(params, callback) {
  7239. submitRequest.call(this, {
  7240. Action: 'name/cos:DeleteBucketInventory',
  7241. method: 'DELETE',
  7242. Bucket: params.Bucket,
  7243. Region: params.Region,
  7244. headers: params.Headers,
  7245. action: 'inventory',
  7246. qs: {
  7247. id: params['Id']
  7248. }
  7249. }, function (err, data) {
  7250. if (err && err.statusCode === 204) {
  7251. return callback(null, { statusCode: err.statusCode });
  7252. } else if (err) {
  7253. return callback(err);
  7254. }
  7255. callback(null, {
  7256. statusCode: data.statusCode,
  7257. headers: data.headers
  7258. });
  7259. });
  7260. }
  7261. /* 全球加速 */
  7262. function putBucketAccelerate(params, callback) {
  7263. if (!params['AccelerateConfiguration']) {
  7264. callback({ error: 'missing param AccelerateConfiguration' });
  7265. return;
  7266. }
  7267. var configuration = { AccelerateConfiguration: params.AccelerateConfiguration || {} };
  7268. var xml = util.json2xml(configuration);
  7269. var headers = {};
  7270. headers['Content-Type'] = 'application/xml';
  7271. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7272. submitRequest.call(this, {
  7273. Interface: 'putBucketAccelerate',
  7274. Action: 'name/cos:PutBucketAccelerate',
  7275. method: 'PUT',
  7276. Bucket: params.Bucket,
  7277. Region: params.Region,
  7278. body: xml,
  7279. action: 'accelerate',
  7280. headers: headers
  7281. }, function (err, data) {
  7282. if (err) return callback(err);
  7283. callback(null, {
  7284. statusCode: data.statusCode,
  7285. headers: data.headers
  7286. });
  7287. });
  7288. }
  7289. function getBucketAccelerate(params, callback) {
  7290. submitRequest.call(this, {
  7291. Interface: 'getBucketAccelerate',
  7292. Action: 'name/cos:GetBucketAccelerate',
  7293. method: 'GET',
  7294. Bucket: params.Bucket,
  7295. Region: params.Region,
  7296. action: 'accelerate'
  7297. }, function (err, data) {
  7298. if (!err) {
  7299. !data.AccelerateConfiguration && (data.AccelerateConfiguration = {});
  7300. }
  7301. callback(err, data);
  7302. });
  7303. }
  7304. // Object 相关
  7305. /**
  7306. * 取回对应Object的元数据,Head的权限与Get的权限一致
  7307. * @param {Object} params 参数对象,必须
  7308. * @param {String} params.Bucket Bucket名称,必须
  7309. * @param {String} params.Region 地域名称,必须
  7310. * @param {String} params.Key 文件名称,必须
  7311. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  7312. * @param {Function} callback 回调函数,必须
  7313. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7314. * @return {Object} data 为指定 object 的元数据,如果设置了 IfModifiedSince ,且文件未修改,则返回一个对象,NotModified 属性为 true
  7315. * @return {Boolean} data.NotModified 是否在 IfModifiedSince 时间点之后未修改该 object,则为 true
  7316. */
  7317. function headObject(params, callback) {
  7318. submitRequest.call(this, {
  7319. Action: 'name/cos:HeadObject',
  7320. method: 'HEAD',
  7321. Bucket: params.Bucket,
  7322. Region: params.Region,
  7323. Key: params.Key,
  7324. VersionId: params.VersionId,
  7325. headers: params.Headers
  7326. }, function (err, data) {
  7327. if (err) {
  7328. var statusCode = err.statusCode;
  7329. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  7330. return callback(null, {
  7331. NotModified: true,
  7332. statusCode: statusCode
  7333. });
  7334. }
  7335. return callback(err);
  7336. }
  7337. data.ETag = util.attr(data.headers, 'etag', '');
  7338. callback(null, data);
  7339. });
  7340. }
  7341. function listObjectVersions(params, callback) {
  7342. var reqParams = {};
  7343. reqParams['prefix'] = params['Prefix'] || '';
  7344. reqParams['delimiter'] = params['Delimiter'];
  7345. reqParams['key-marker'] = params['KeyMarker'];
  7346. reqParams['version-id-marker'] = params['VersionIdMarker'];
  7347. reqParams['max-keys'] = params['MaxKeys'];
  7348. reqParams['encoding-type'] = params['EncodingType'];
  7349. submitRequest.call(this, {
  7350. Action: 'name/cos:GetBucketObjectVersions',
  7351. ResourceKey: reqParams['prefix'],
  7352. method: 'GET',
  7353. Bucket: params.Bucket,
  7354. Region: params.Region,
  7355. headers: params.Headers,
  7356. qs: reqParams,
  7357. action: 'versions'
  7358. }, function (err, data) {
  7359. if (err) return callback(err);
  7360. var ListVersionsResult = data.ListVersionsResult || {};
  7361. var DeleteMarkers = ListVersionsResult.DeleteMarker || [];
  7362. DeleteMarkers = util.isArray(DeleteMarkers) ? DeleteMarkers : [DeleteMarkers];
  7363. var Versions = ListVersionsResult.Version || [];
  7364. Versions = util.isArray(Versions) ? Versions : [Versions];
  7365. var result = util.clone(ListVersionsResult);
  7366. delete result.DeleteMarker;
  7367. delete result.Version;
  7368. util.extend(result, {
  7369. DeleteMarkers: DeleteMarkers,
  7370. Versions: Versions,
  7371. statusCode: data.statusCode,
  7372. headers: data.headers
  7373. });
  7374. callback(null, result);
  7375. });
  7376. }
  7377. /**
  7378. * 下载 object
  7379. * @param {Object} params 参数对象,必须
  7380. * @param {String} params.Bucket Bucket名称,必须
  7381. * @param {String} params.Region 地域名称,必须
  7382. * @param {String} params.Key 文件名称,必须
  7383. * @param {WriteStream} params.Output 文件写入流,非必须
  7384. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  7385. * @param {String} params.IfUnmodifiedSince 如果文件修改时间早于或等于指定时间,才返回文件内容。否则返回 412 (precondition failed),非必须
  7386. * @param {String} params.IfMatch 当 ETag 与指定的内容一致,才返回文件。否则返回 412 (precondition failed),非必须
  7387. * @param {String} params.IfNoneMatch 当 ETag 与指定的内容不一致,才返回文件。否则返回304 (not modified),非必须
  7388. * @param {String} params.ResponseContentType 设置返回头部中的 Content-Type 参数,非必须
  7389. * @param {String} params.ResponseContentLanguage 设置返回头部中的 Content-Language 参数,非必须
  7390. * @param {String} params.ResponseExpires 设置返回头部中的 Content-Expires 参数,非必须
  7391. * @param {String} params.ResponseCacheControl 设置返回头部中的 Cache-Control 参数,非必须
  7392. * @param {String} params.ResponseContentDisposition 设置返回头部中的 Content-Disposition 参数,非必须
  7393. * @param {String} params.ResponseContentEncoding 设置返回头部中的 Content-Encoding 参数,非必须
  7394. * @param {Function} callback 回调函数,必须
  7395. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7396. * @param {Object} data 为对应的 object 数据,包括 body 和 headers
  7397. */
  7398. function getObject(params, callback) {
  7399. var reqParams = params.Query || {};
  7400. var reqParamsStr = params.QueryString || '';
  7401. reqParams['response-content-type'] = params['ResponseContentType'];
  7402. reqParams['response-content-language'] = params['ResponseContentLanguage'];
  7403. reqParams['response-expires'] = params['ResponseExpires'];
  7404. reqParams['response-cache-control'] = params['ResponseCacheControl'];
  7405. reqParams['response-content-disposition'] = params['ResponseContentDisposition'];
  7406. reqParams['response-content-encoding'] = params['ResponseContentEncoding'];
  7407. // 如果用户自己传入了 output
  7408. submitRequest.call(this, {
  7409. Action: 'name/cos:GetObject',
  7410. method: 'GET',
  7411. Bucket: params.Bucket,
  7412. Region: params.Region,
  7413. Key: params.Key,
  7414. VersionId: params.VersionId,
  7415. headers: params.Headers,
  7416. qs: reqParams,
  7417. qsStr: reqParamsStr,
  7418. rawBody: true
  7419. }, function (err, data) {
  7420. if (err) {
  7421. var statusCode = err.statusCode;
  7422. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  7423. return callback(null, {
  7424. NotModified: true
  7425. });
  7426. }
  7427. return callback(err);
  7428. }
  7429. callback(null, {
  7430. Body: data.body,
  7431. ETag: util.attr(data.headers, 'etag', ''),
  7432. statusCode: data.statusCode,
  7433. headers: data.headers
  7434. });
  7435. });
  7436. }
  7437. /**
  7438. * 上传 object
  7439. * @param {Object} params 参数对象,必须
  7440. * @param {String} params.Bucket Bucket名称,必须
  7441. * @param {String} params.Region 地域名称,必须
  7442. * @param {String} params.Key 文件名称,必须
  7443. * @param {String} params.Body 上传文件的内容,只支持字符串
  7444. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  7445. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存,非必须
  7446. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  7447. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),必须
  7448. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  7449. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  7450. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  7451. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须
  7452. * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须
  7453. * @param {String} params.GrantRead 赋予被授权者读的权限,格式 x-cos-grant-read: uin=" ",uin=" ",非必须
  7454. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式 x-cos-grant-write: uin=" ",uin=" ",非必须
  7455. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式 x-cos-grant-full-control: uin=" ",uin=" ",非必须
  7456. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7457. * @param {Function} params.onProgress 上传进度回调函数
  7458. * @param {Function} callback 回调函数,必须
  7459. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7460. * @return {Object} data 为对应的 object 数据
  7461. * @return {String} data.ETag 为对应上传文件的 ETag 值
  7462. */
  7463. function putObject(params, callback) {
  7464. var self = this;
  7465. var FileSize = params.ContentLength;
  7466. var onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  7467. // 特殊处理 Cache-Control、Content-Type,避免代理更改这两个字段导致写入到 Object 属性里
  7468. var headers = params.Headers;
  7469. if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';
  7470. if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = mime.getType(params.Key) || 'application/octet-stream';
  7471. util.getBodyMd5(self.options.UploadCheckContentMd5, params.Body, function (md5) {
  7472. if (md5) headers['Content-MD5'] = util.binaryBase64(md5);
  7473. if (params.ContentLength !== undefined) headers['Content-Length'] = params.ContentLength;
  7474. onProgress(null, true); // 任务状态开始 uploading
  7475. submitRequest.call(self, {
  7476. Action: 'name/cos:PutObject',
  7477. TaskId: params.TaskId,
  7478. method: 'PUT',
  7479. Bucket: params.Bucket,
  7480. Region: params.Region,
  7481. Key: params.Key,
  7482. headers: params.Headers,
  7483. qs: params.Query,
  7484. body: params.Body,
  7485. onProgress: onProgress
  7486. }, function (err, data) {
  7487. if (err) {
  7488. onProgress(null, true);
  7489. return callback(err);
  7490. }
  7491. onProgress({ loaded: FileSize, total: FileSize }, true);
  7492. var url = getUrl({
  7493. ForcePathStyle: self.options.ForcePathStyle,
  7494. protocol: self.options.Protocol,
  7495. domain: self.options.Domain,
  7496. bucket: params.Bucket,
  7497. region: !self.options.UseAccelerate ? params.Region : 'accelerate',
  7498. object: params.Key
  7499. });
  7500. url = url.substr(url.indexOf('://') + 3);
  7501. data.Location = url;
  7502. data.ETag = util.attr(data.headers, 'etag', '');
  7503. callback(null, data);
  7504. });
  7505. });
  7506. }
  7507. /**
  7508. * 上传 object
  7509. * @param {Object} params 参数对象,必须
  7510. * @param {String} params.Bucket Bucket名称,必须
  7511. * @param {String} params.Region 地域名称,必须
  7512. * @param {String} params.Key 文件名称,必须
  7513. * @param {FilePath} params.FilePath 要上传的文件路径
  7514. * @param {Function} params.onProgress 上传进度回调函数
  7515. * @param {Function} callback 回调函数,必须
  7516. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7517. * @return {Object} data 为对应的 object 数据
  7518. * @return {String} data.ETag 为对应上传文件的 ETag 值
  7519. */
  7520. function postObject(params, callback) {
  7521. var self = this;
  7522. var headers = {};
  7523. var filePath = params.FilePath;
  7524. if (!filePath) {
  7525. callback({ error: 'missing param FilePath' });
  7526. return;
  7527. }
  7528. headers['Cache-Control'] = params['CacheControl'];
  7529. headers['Content-Disposition'] = params['ContentDisposition'];
  7530. headers['Content-Encoding'] = params['ContentEncoding'];
  7531. headers['Content-MD5'] = params['ContentMD5'];
  7532. headers['Content-Length'] = params['ContentLength'];
  7533. headers['Content-Type'] = params['ContentType'];
  7534. headers['Expect'] = params['Expect'];
  7535. headers['Expires'] = params['Expires'];
  7536. headers['x-cos-acl'] = params['ACL'];
  7537. headers['x-cos-grant-read'] = params['GrantRead'];
  7538. headers['x-cos-grant-write'] = params['GrantWrite'];
  7539. headers['x-cos-grant-full-control'] = params['GrantFullControl'];
  7540. headers['x-cos-storage-class'] = params['StorageClass'];
  7541. headers['x-cos-mime-limit'] = params['MimeLimit'];
  7542. headers['x-cos-traffic-limit'] = params['TrafficLimit'];
  7543. // SSE-C
  7544. headers['x-cos-server-side-encryption-customer-algorithm'] = params['SSECustomerAlgorithm'];
  7545. headers['x-cos-server-side-encryption-customer-key'] = params['SSECustomerKey'];
  7546. headers['x-cos-server-side-encryption-customer-key-MD5'] = params['SSECustomerKeyMD5'];
  7547. // SSE-COS、SSE-KMS
  7548. headers['x-cos-server-side-encryption'] = params['ServerSideEncryption'];
  7549. headers['x-cos-server-side-encryption-cos-kms-key-id'] = params['SSEKMSKeyId'];
  7550. headers['x-cos-server-side-encryption-context'] = params['SSEContext'];
  7551. // 删除 Content-Length 避免签名错误
  7552. delete headers['Content-Length'];
  7553. delete headers['content-length'];
  7554. for (var key in params) {
  7555. if (key.indexOf('x-cos-meta-') > -1) {
  7556. headers[key] = params[key];
  7557. }
  7558. }
  7559. var onProgress = util.throttleOnProgress.call(self, headers['Content-Length'], params.onProgress);
  7560. submitRequest.call(this, {
  7561. Action: 'name/cos:PostObject',
  7562. method: 'POST',
  7563. Bucket: params.Bucket,
  7564. Region: params.Region,
  7565. Key: params.Key,
  7566. headers: headers,
  7567. qs: params.Query,
  7568. filePath: filePath,
  7569. TaskId: params.TaskId,
  7570. onProgress: onProgress
  7571. }, function (err, data) {
  7572. onProgress(null, true);
  7573. if (err) return callback(err);
  7574. if (data && data.headers) {
  7575. var headers = data.headers;
  7576. var ETag = headers.etag || headers.Etag || headers.ETag || '';
  7577. var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
  7578. var url = getUrl({
  7579. ForcePathStyle: self.options.ForcePathStyle,
  7580. protocol: self.options.Protocol,
  7581. domain: self.options.Domain,
  7582. bucket: params.Bucket,
  7583. region: params.Region,
  7584. object: params.Key.replace(/\$\{filename\}/g, filename),
  7585. isLocation: true
  7586. });
  7587. return callback(null, {
  7588. Location: url,
  7589. statusCode: data.statusCode,
  7590. headers: headers,
  7591. ETag: ETag
  7592. });
  7593. }
  7594. callback(null, data);
  7595. });
  7596. }
  7597. /**
  7598. * 删除 object
  7599. * @param {Object} params 参数对象,必须
  7600. * @param {String} params.Bucket Bucket名称,必须
  7601. * @param {String} params.Region 地域名称,必须
  7602. * @param {String} params.Key object名称,必须
  7603. * @param {Function} callback 回调函数,必须
  7604. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7605. * @param {Object} data 删除操作成功之后返回的数据
  7606. */
  7607. function deleteObject(params, callback) {
  7608. submitRequest.call(this, {
  7609. Action: 'name/cos:DeleteObject',
  7610. method: 'DELETE',
  7611. Bucket: params.Bucket,
  7612. Region: params.Region,
  7613. Key: params.Key,
  7614. headers: params.Headers,
  7615. VersionId: params.VersionId
  7616. }, function (err, data) {
  7617. if (err) {
  7618. var statusCode = err.statusCode;
  7619. if (statusCode && statusCode === 204) {
  7620. return callback(null, { statusCode: statusCode });
  7621. } else if (statusCode && statusCode === 404) {
  7622. return callback(null, { BucketNotFound: true, statusCode: statusCode });
  7623. } else {
  7624. return callback(err);
  7625. }
  7626. }
  7627. callback(null, {
  7628. statusCode: data.statusCode,
  7629. headers: data.headers
  7630. });
  7631. });
  7632. }
  7633. /**
  7634. * 获取 object 的 权限列表
  7635. * @param {Object} params 参数对象,必须
  7636. * @param {String} params.Bucket Bucket名称,必须
  7637. * @param {String} params.Region 地域名称,必须
  7638. * @param {String} params.Key object名称,必须
  7639. * @param {Function} callback 回调函数,必须
  7640. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7641. * @return {Object} data 返回的数据
  7642. * @return {Object} data.AccessControlPolicy 权限列表
  7643. */
  7644. function getObjectAcl(params, callback) {
  7645. submitRequest.call(this, {
  7646. Action: 'name/cos:GetObjectACL',
  7647. method: 'GET',
  7648. Bucket: params.Bucket,
  7649. Region: params.Region,
  7650. Key: params.Key,
  7651. headers: params.Headers,
  7652. action: 'acl'
  7653. }, function (err, data) {
  7654. if (err) return callback(err);
  7655. var AccessControlPolicy = data.AccessControlPolicy || {};
  7656. var Owner = AccessControlPolicy.Owner || {};
  7657. var Grant = AccessControlPolicy.AccessControlList && AccessControlPolicy.AccessControlList.Grant || [];
  7658. Grant = util.isArray(Grant) ? Grant : [Grant];
  7659. var result = decodeAcl(AccessControlPolicy);
  7660. if (data.headers && data.headers['x-cos-acl']) {
  7661. result.ACL = data.headers['x-cos-acl'];
  7662. }
  7663. result = util.extend(result, {
  7664. Owner: Owner,
  7665. Grants: Grant,
  7666. statusCode: data.statusCode,
  7667. headers: data.headers
  7668. });
  7669. callback(null, result);
  7670. });
  7671. }
  7672. /**
  7673. * 设置 object 的 权限列表
  7674. * @param {Object} params 参数对象,必须
  7675. * @param {String} params.Bucket Bucket名称,必须
  7676. * @param {String} params.Region 地域名称,必须
  7677. * @param {String} params.Key object名称,必须
  7678. * @param {Function} callback 回调函数,必须
  7679. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7680. * @return {Object} data 返回的数据
  7681. */
  7682. function putObjectAcl(params, callback) {
  7683. var headers = params.Headers;
  7684. var xml = '';
  7685. if (params['AccessControlPolicy']) {
  7686. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  7687. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  7688. Grants = util.isArray(Grants) ? Grants : [Grants];
  7689. delete AccessControlPolicy.Grant;
  7690. delete AccessControlPolicy.Grants;
  7691. AccessControlPolicy.AccessControlList = { Grant: Grants };
  7692. xml = util.json2xml({ AccessControlPolicy: AccessControlPolicy });
  7693. headers['Content-Type'] = 'application/xml';
  7694. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7695. }
  7696. // Grant Header 去重
  7697. util.each(headers, function (val, key) {
  7698. if (key.indexOf('x-cos-grant-') === 0) {
  7699. headers[key] = uniqGrant(headers[key]);
  7700. }
  7701. });
  7702. submitRequest.call(this, {
  7703. Action: 'name/cos:PutObjectACL',
  7704. method: 'PUT',
  7705. Bucket: params.Bucket,
  7706. Region: params.Region,
  7707. Key: params.Key,
  7708. action: 'acl',
  7709. headers: headers,
  7710. body: xml
  7711. }, function (err, data) {
  7712. if (err) return callback(err);
  7713. callback(null, {
  7714. statusCode: data.statusCode,
  7715. headers: data.headers
  7716. });
  7717. });
  7718. }
  7719. /**
  7720. * Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
  7721. * @param {Object} params 参数对象,必须
  7722. * @param {String} params.Bucket Bucket名称,必须
  7723. * @param {String} params.Region 地域名称,必须
  7724. * @param {String} params.Key object名称,必须
  7725. * @param {Function} callback 回调函数,必须
  7726. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7727. * @return {Object} data 返回的数据
  7728. */
  7729. function optionsObject(params, callback) {
  7730. var headers = params.Headers;
  7731. headers['Origin'] = params['Origin'];
  7732. headers['Access-Control-Request-Method'] = params['AccessControlRequestMethod'];
  7733. headers['Access-Control-Request-Headers'] = params['AccessControlRequestHeaders'];
  7734. submitRequest.call(this, {
  7735. Action: 'name/cos:OptionsObject',
  7736. method: 'OPTIONS',
  7737. Bucket: params.Bucket,
  7738. Region: params.Region,
  7739. Key: params.Key,
  7740. headers: headers
  7741. }, function (err, data) {
  7742. if (err) {
  7743. if (err.statusCode && err.statusCode === 403) {
  7744. return callback(null, {
  7745. OptionsForbidden: true,
  7746. statusCode: err.statusCode
  7747. });
  7748. }
  7749. return callback(err);
  7750. }
  7751. var headers = data.headers || {};
  7752. callback(null, {
  7753. AccessControlAllowOrigin: headers['access-control-allow-origin'],
  7754. AccessControlAllowMethods: headers['access-control-allow-methods'],
  7755. AccessControlAllowHeaders: headers['access-control-allow-headers'],
  7756. AccessControlExposeHeaders: headers['access-control-expose-headers'],
  7757. AccessControlMaxAge: headers['access-control-max-age'],
  7758. statusCode: data.statusCode,
  7759. headers: data.headers
  7760. });
  7761. });
  7762. }
  7763. /**
  7764. * @param {Object} 参数列表
  7765. * @param {String} Bucket Bucket 名称
  7766. * @param {String} Region 地域名称
  7767. * @param {String} Key 文件名称
  7768. * @param {String} CopySource 源文件URL绝对路径,可以通过versionid子资源指定历史版本
  7769. * @param {String} ACL 允许用户自定义文件权限。有效值:private,public-read默认值:private。
  7770. * @param {String} GrantRead 赋予被授权者读的权限,格式 x-cos-grant-read: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  7771. * @param {String} GrantWrite 赋予被授权者写的权限,格式 x-cos-grant-write: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  7772. * @param {String} GrantFullControl 赋予被授权者读写权限,格式 x-cos-grant-full-control: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  7773. * @param {String} MetadataDirective 是否拷贝元数据,枚举值:Copy, Replaced,默认值Copy。假如标记为Copy,忽略Header中的用户元数据信息直接复制;假如标记为Replaced,按Header信息修改元数据。当目标路径和原路径一致,即用户试图修改元数据时,必须为Replaced
  7774. * @param {String} CopySourceIfModifiedSince 当Object在指定时间后被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-None-Match一起使用,与其他条件联合使用返回冲突。
  7775. * @param {String} CopySourceIfUnmodifiedSince 当Object在指定时间后未被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-Match一起使用,与其他条件联合使用返回冲突。
  7776. * @param {String} CopySourceIfMatch 当Object的ETag和给定一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Unmodified-Since一起使用,与其他条件联合使用返回冲突。
  7777. * @param {String} CopySourceIfNoneMatch 当Object的ETag和给定不一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Modified-Since一起使用,与其他条件联合使用返回冲突。
  7778. * @param {String} StorageClass 存储级别,枚举值:存储级别,枚举值:Standard, Standard_IA,Archive;默认值:Standard
  7779. * @param {String} CacheControl 指定所有缓存机制在整个请求/响应链中必须服从的指令。
  7780. * @param {String} ContentDisposition MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件
  7781. * @param {String} ContentEncoding HTTP 中用来对「采用何种编码格式传输正文」进行协定的一对头部字段
  7782. * @param {String} ContentLength 设置响应消息的实体内容的大小,单位为字节
  7783. * @param {String} ContentType RFC 2616 中定义的 HTTP 请求内容类型(MIME),例如text/plain
  7784. * @param {String} Expect 请求的特定的服务器行为
  7785. * @param {String} Expires 响应过期的日期和时间
  7786. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7787. * @param {String} ContentLanguage 指定内容语言
  7788. * @param {String} x-cos-meta-* 允许用户自定义的头部信息,将作为 Object 元数据返回。大小限制2K。
  7789. */
  7790. function putObjectCopy(params, callback) {
  7791. // 特殊处理 Cache-Control
  7792. var headers = params.Headers;
  7793. if (!headers['Cache-Control'] && !!headers['cache-control']) headers['Cache-Control'] = '';
  7794. var CopySource = params.CopySource || '';
  7795. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  7796. if (!m) {
  7797. callback({ error: 'CopySource format error' });
  7798. return;
  7799. }
  7800. var SourceBucket = m[1];
  7801. var SourceRegion = m[3];
  7802. var SourceKey = decodeURIComponent(m[4]);
  7803. submitRequest.call(this, {
  7804. Scope: [{
  7805. action: 'name/cos:GetObject',
  7806. bucket: SourceBucket,
  7807. region: SourceRegion,
  7808. prefix: SourceKey
  7809. }, {
  7810. action: 'name/cos:PutObject',
  7811. bucket: params.Bucket,
  7812. region: params.Region,
  7813. prefix: params.Key
  7814. }],
  7815. method: 'PUT',
  7816. Bucket: params.Bucket,
  7817. Region: params.Region,
  7818. Key: params.Key,
  7819. VersionId: params.VersionId,
  7820. headers: params.Headers
  7821. }, function (err, data) {
  7822. if (err) return callback(err);
  7823. var result = util.clone(data.CopyObjectResult || {});
  7824. util.extend(result, {
  7825. statusCode: data.statusCode,
  7826. headers: data.headers
  7827. });
  7828. callback(null, result);
  7829. });
  7830. }
  7831. function uploadPartCopy(params, callback) {
  7832. var CopySource = params.CopySource || '';
  7833. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  7834. if (!m) {
  7835. callback({ error: 'CopySource format error' });
  7836. return;
  7837. }
  7838. var SourceBucket = m[1];
  7839. var SourceRegion = m[3];
  7840. var SourceKey = decodeURIComponent(m[4]);
  7841. submitRequest.call(this, {
  7842. Scope: [{
  7843. action: 'name/cos:GetObject',
  7844. bucket: SourceBucket,
  7845. region: SourceRegion,
  7846. prefix: SourceKey
  7847. }, {
  7848. action: 'name/cos:PutObject',
  7849. bucket: params.Bucket,
  7850. region: params.Region,
  7851. prefix: params.Key
  7852. }],
  7853. method: 'PUT',
  7854. Bucket: params.Bucket,
  7855. Region: params.Region,
  7856. Key: params.Key,
  7857. VersionId: params.VersionId,
  7858. qs: {
  7859. partNumber: params['PartNumber'],
  7860. uploadId: params['UploadId']
  7861. },
  7862. headers: params.Headers
  7863. }, function (err, data) {
  7864. if (err) return callback(err);
  7865. var result = util.clone(data.CopyPartResult || {});
  7866. util.extend(result, {
  7867. statusCode: data.statusCode,
  7868. headers: data.headers
  7869. });
  7870. callback(null, result);
  7871. });
  7872. }
  7873. function deleteMultipleObject(params, callback) {
  7874. var Objects = params.Objects || [];
  7875. var Quiet = params.Quiet;
  7876. Objects = util.isArray(Objects) ? Objects : [Objects];
  7877. var xml = util.json2xml({ Delete: { Object: Objects, Quiet: Quiet || false } });
  7878. var headers = params.Headers;
  7879. headers['Content-Type'] = 'application/xml';
  7880. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7881. var Scope = util.map(Objects, function (v) {
  7882. return {
  7883. action: 'name/cos:DeleteObject',
  7884. bucket: params.Bucket,
  7885. region: params.Region,
  7886. prefix: v.Key
  7887. };
  7888. });
  7889. submitRequest.call(this, {
  7890. Scope: Scope,
  7891. method: 'POST',
  7892. Bucket: params.Bucket,
  7893. Region: params.Region,
  7894. body: xml,
  7895. action: 'delete',
  7896. headers: headers
  7897. }, function (err, data) {
  7898. if (err) return callback(err);
  7899. var DeleteResult = data.DeleteResult || {};
  7900. var Deleted = DeleteResult.Deleted || [];
  7901. var Errors = DeleteResult.Error || [];
  7902. Deleted = util.isArray(Deleted) ? Deleted : [Deleted];
  7903. Errors = util.isArray(Errors) ? Errors : [Errors];
  7904. var result = util.clone(DeleteResult);
  7905. util.extend(result, {
  7906. Error: Errors,
  7907. Deleted: Deleted,
  7908. statusCode: data.statusCode,
  7909. headers: data.headers
  7910. });
  7911. callback(null, result);
  7912. });
  7913. }
  7914. function restoreObject(params, callback) {
  7915. var headers = params.Headers;
  7916. if (!params['RestoreRequest']) {
  7917. callback({ error: 'missing param RestoreRequest' });
  7918. return;
  7919. }
  7920. var RestoreRequest = params.RestoreRequest || {};
  7921. var xml = util.json2xml({ RestoreRequest: RestoreRequest });
  7922. headers['Content-Type'] = 'application/xml';
  7923. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7924. submitRequest.call(this, {
  7925. Action: 'name/cos:RestoreObject',
  7926. method: 'POST',
  7927. Bucket: params.Bucket,
  7928. Region: params.Region,
  7929. Key: params.Key,
  7930. VersionId: params.VersionId,
  7931. body: xml,
  7932. action: 'restore',
  7933. headers: headers
  7934. }, function (err, data) {
  7935. callback(err, data);
  7936. });
  7937. }
  7938. /**
  7939. * 设置 Object 的标签
  7940. * @param {Object} params 参数对象,必须
  7941. * @param {String} params.Bucket Object名称,必须
  7942. * @param {String} params.Region 地域名称,必须
  7943. * @param {Array} params.TagSet 标签设置,必须
  7944. * @param {Function} callback 回调函数,必须
  7945. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7946. * @return {Object} data 返回数据
  7947. */
  7948. function putObjectTagging(params, callback) {
  7949. var Tagging = params['Tagging'] || {};
  7950. var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];
  7951. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  7952. var xml = util.json2xml({ Tagging: { TagSet: { Tag: Tags } } });
  7953. var headers = params.Headers;
  7954. headers['Content-Type'] = 'application/xml';
  7955. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7956. submitRequest.call(this, {
  7957. Interface: 'putObjectTagging',
  7958. Action: 'name/cos:PutObjectTagging',
  7959. method: 'PUT',
  7960. Bucket: params.Bucket,
  7961. Key: params.Key,
  7962. Region: params.Region,
  7963. body: xml,
  7964. action: 'tagging',
  7965. headers: headers,
  7966. VersionId: params.VersionId
  7967. }, function (err, data) {
  7968. if (err && err.statusCode === 204) {
  7969. return callback(null, { statusCode: err.statusCode });
  7970. } else if (err) {
  7971. return callback(err);
  7972. }
  7973. callback(null, {
  7974. statusCode: data.statusCode,
  7975. headers: data.headers
  7976. });
  7977. });
  7978. }
  7979. /**
  7980. * 获取 Object 的标签设置
  7981. * @param {Object} params 参数对象,必须
  7982. * @param {String} params.Bucket Bucket名称,必须
  7983. * @param {String} params.Region 地域名称,必须
  7984. * @param {Function} callback 回调函数,必须
  7985. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7986. * @return {Object} data 返回数据
  7987. */
  7988. function getObjectTagging(params, callback) {
  7989. submitRequest.call(this, {
  7990. Interface: 'getObjectTagging',
  7991. Action: 'name/cos:GetObjectTagging',
  7992. method: 'GET',
  7993. Key: params.Key,
  7994. Bucket: params.Bucket,
  7995. Region: params.Region,
  7996. headers: params.Headers,
  7997. action: 'tagging',
  7998. VersionId: params.VersionId
  7999. }, function (err, data) {
  8000. if (err) {
  8001. if (err.statusCode === 404 && err.error && (err.error === "Not Found" || err.error.Code === 'NoSuchTagSet')) {
  8002. var result = {
  8003. Tags: [],
  8004. statusCode: err.statusCode
  8005. };
  8006. err.headers && (result.headers = err.headers);
  8007. callback(null, result);
  8008. } else {
  8009. callback(err);
  8010. }
  8011. return;
  8012. }
  8013. var Tags = [];
  8014. try {
  8015. Tags = data.Tagging.TagSet.Tag || [];
  8016. } catch (e) {}
  8017. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  8018. callback(null, {
  8019. Tags: Tags,
  8020. statusCode: data.statusCode,
  8021. headers: data.headers
  8022. });
  8023. });
  8024. }
  8025. /**
  8026. * 删除 Object 的 标签设置
  8027. * @param {Object} params 参数对象,必须
  8028. * @param {String} params.Bucket Object名称,必须
  8029. * @param {String} params.Region 地域名称,必须
  8030. * @param {Function} callback 回调函数,必须
  8031. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  8032. * @return {Object} data 返回的数据
  8033. */
  8034. function deleteObjectTagging(params, callback) {
  8035. submitRequest.call(this, {
  8036. Interface: 'deleteObjectTagging',
  8037. Action: 'name/cos:DeleteObjectTagging',
  8038. method: 'DELETE',
  8039. Bucket: params.Bucket,
  8040. Region: params.Region,
  8041. Key: params.Key,
  8042. headers: params.Headers,
  8043. action: 'tagging',
  8044. VersionId: params.VersionId
  8045. }, function (err, data) {
  8046. if (err && err.statusCode === 204) {
  8047. return callback(null, { statusCode: err.statusCode });
  8048. } else if (err) {
  8049. return callback(err);
  8050. }
  8051. callback(null, {
  8052. statusCode: data.statusCode,
  8053. headers: data.headers
  8054. });
  8055. });
  8056. }
  8057. // 分块上传
  8058. /**
  8059. * 初始化分块上传
  8060. * @param {Object} params 参数对象,必须
  8061. * @param {String} params.Bucket Bucket名称,必须
  8062. * @param {String} params.Region 地域名称,必须
  8063. * @param {String} params.Key object名称,必须
  8064. * @param {String} params.UploadId object名称,必须
  8065. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  8066. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存 ,非必须
  8067. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  8068. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  8069. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  8070. * @param {String} params.ACL 允许用户自定义文件权限,非必须
  8071. * @param {String} params.GrantRead 赋予被授权者读的权限 ,非必须
  8072. * @param {String} params.GrantWrite 赋予被授权者写的权限 ,非必须
  8073. * @param {String} params.GrantFullControl 赋予被授权者读写权限 ,非必须
  8074. * @param {String} params.StorageClass 设置Object的存储级别,枚举值:Standard,Standard_IA,Archive,非必须
  8075. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  8076. * @param {Function} callback 回调函数,必须
  8077. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8078. * @return {Object} data 返回的数据
  8079. */
  8080. function multipartInit(params, callback) {
  8081. var self = this;
  8082. var headers = params.Headers;
  8083. // 特殊处理 Cache-Control、Content-Type
  8084. if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';
  8085. if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = mime.getType(params.Key) || 'application/octet-stream';
  8086. submitRequest.call(self, {
  8087. Action: 'name/cos:InitiateMultipartUpload',
  8088. method: 'POST',
  8089. Bucket: params.Bucket,
  8090. Region: params.Region,
  8091. Key: params.Key,
  8092. action: 'uploads',
  8093. headers: params.Headers,
  8094. qs: params.Query
  8095. }, function (err, data) {
  8096. if (err) return callback(err);
  8097. data = util.clone(data || {});
  8098. if (data && data.InitiateMultipartUploadResult) {
  8099. return callback(null, util.extend(data.InitiateMultipartUploadResult, {
  8100. statusCode: data.statusCode,
  8101. headers: data.headers
  8102. }));
  8103. }
  8104. callback(null, data);
  8105. });
  8106. }
  8107. /**
  8108. * 分块上传
  8109. * @param {Object} params 参数对象,必须
  8110. * @param {String} params.Bucket Bucket名称,必须
  8111. * @param {String} params.Region 地域名称,必须
  8112. * @param {String} params.Key object名称,必须
  8113. * @param {String} params.Body 上传文件对象或字符串
  8114. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),非必须
  8115. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  8116. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  8117. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验值,非必须
  8118. * @param {Function} callback 回调函数,必须
  8119. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8120. * @return {Object} data 返回的数据
  8121. * @return {Object} data.ETag 返回的文件分块 sha1 值
  8122. */
  8123. function multipartUpload(params, callback) {
  8124. var self = this;
  8125. util.getFileSize('multipartUpload', params, function () {
  8126. util.getBodyMd5(self.options.UploadCheckContentMd5, params.Body, function (md5) {
  8127. if (md5) params.Headers['Content-MD5'] = util.binaryBase64(md5);
  8128. submitRequest.call(self, {
  8129. Action: 'name/cos:UploadPart',
  8130. TaskId: params.TaskId,
  8131. method: 'PUT',
  8132. Bucket: params.Bucket,
  8133. Region: params.Region,
  8134. Key: params.Key,
  8135. qs: {
  8136. partNumber: params['PartNumber'],
  8137. uploadId: params['UploadId']
  8138. },
  8139. headers: params.Headers,
  8140. onProgress: params.onProgress,
  8141. body: params.Body || null
  8142. }, function (err, data) {
  8143. if (err) return callback(err);
  8144. callback(null, {
  8145. ETag: util.attr(data.headers, 'etag', {}),
  8146. statusCode: data.statusCode,
  8147. headers: data.headers
  8148. });
  8149. });
  8150. });
  8151. });
  8152. }
  8153. /**
  8154. * 完成分块上传
  8155. * @param {Object} params 参数对象,必须
  8156. * @param {String} params.Bucket Bucket名称,必须
  8157. * @param {String} params.Region 地域名称,必须
  8158. * @param {String} params.Key object名称,必须
  8159. * @param {Array} params.Parts 分块信息列表,必须
  8160. * @param {String} params.Parts[i].PartNumber 块编号,必须
  8161. * @param {String} params.Parts[i].ETag 分块的 sha1 校验值
  8162. * @param {Function} callback 回调函数,必须
  8163. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8164. * @return {Object} data 返回的数据
  8165. * @return {Object} data.CompleteMultipartUpload 完成分块上传后的文件信息,包括Location, Bucket, Key 和 ETag
  8166. */
  8167. function multipartComplete(params, callback) {
  8168. var self = this;
  8169. var UploadId = params.UploadId;
  8170. var Parts = params['Parts'];
  8171. for (var i = 0, len = Parts.length; i < len; i++) {
  8172. if (Parts[i]['ETag'].indexOf('"') === 0) {
  8173. continue;
  8174. }
  8175. Parts[i]['ETag'] = '"' + Parts[i]['ETag'] + '"';
  8176. }
  8177. var xml = util.json2xml({ CompleteMultipartUpload: { Part: Parts } });
  8178. var headers = params.Headers;
  8179. headers['Content-Type'] = 'application/xml';
  8180. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  8181. submitRequest.call(this, {
  8182. Action: 'name/cos:CompleteMultipartUpload',
  8183. method: 'POST',
  8184. Bucket: params.Bucket,
  8185. Region: params.Region,
  8186. Key: params.Key,
  8187. qs: {
  8188. uploadId: UploadId
  8189. },
  8190. body: xml,
  8191. headers: headers
  8192. }, function (err, data) {
  8193. if (err) return callback(err);
  8194. var url = getUrl({
  8195. ForcePathStyle: self.options.ForcePathStyle,
  8196. protocol: self.options.Protocol,
  8197. domain: self.options.Domain,
  8198. bucket: params.Bucket,
  8199. region: params.Region,
  8200. object: params.Key,
  8201. isLocation: true
  8202. });
  8203. var CompleteMultipartUploadResult = data.CompleteMultipartUploadResult || {};
  8204. var result = util.extend(CompleteMultipartUploadResult, {
  8205. Location: url,
  8206. statusCode: data.statusCode,
  8207. headers: data.headers
  8208. });
  8209. callback(null, result);
  8210. });
  8211. }
  8212. /**
  8213. * 分块上传任务列表查询
  8214. * @param {Object} params 参数对象,必须
  8215. * @param {String} params.Bucket Bucket名称,必须
  8216. * @param {String} params.Region 地域名称,必须
  8217. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,定义为Common Prefix,然后列出所有Common Prefix。如果没有Prefix,则从路径起点开始,非必须
  8218. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  8219. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  8220. * @param {String} params.MaxUploads 单次返回最大的条目数量,默认1000,非必须
  8221. * @param {String} params.KeyMarker 与upload-id-marker一起使用 </Br>当upload-id-marker未被指定时,ObjectName字母顺序大于key-marker的条目将被列出 </Br>当upload-id-marker被指定时,ObjectName字母顺序大于key-marker的条目被列出,ObjectName字母顺序等于key-marker同时UploadId大于upload-id-marker的条目将被列出,非必须
  8222. * @param {String} params.UploadIdMarker 与key-marker一起使用 </Br>当key-marker未被指定时,upload-id-marker将被忽略 </Br>当key-marker被指定时,ObjectName字母顺序大于key-marker的条目被列出,ObjectName字母顺序等于key-marker同时UploadId大于upload-id-marker的条目将被列出,非必须
  8223. * @param {Function} callback 回调函数,必须
  8224. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8225. * @return {Object} data 返回的数据
  8226. * @return {Object} data.ListMultipartUploadsResult 分块上传任务信息
  8227. */
  8228. function multipartList(params, callback) {
  8229. var reqParams = {};
  8230. reqParams['delimiter'] = params['Delimiter'];
  8231. reqParams['encoding-type'] = params['EncodingType'];
  8232. reqParams['prefix'] = params['Prefix'] || '';
  8233. reqParams['max-uploads'] = params['MaxUploads'];
  8234. reqParams['key-marker'] = params['KeyMarker'];
  8235. reqParams['upload-id-marker'] = params['UploadIdMarker'];
  8236. reqParams = util.clearKey(reqParams);
  8237. submitRequest.call(this, {
  8238. Action: 'name/cos:ListMultipartUploads',
  8239. ResourceKey: reqParams['prefix'],
  8240. method: 'GET',
  8241. Bucket: params.Bucket,
  8242. Region: params.Region,
  8243. headers: params.Headers,
  8244. qs: reqParams,
  8245. action: 'uploads'
  8246. }, function (err, data) {
  8247. if (err) return callback(err);
  8248. if (data && data.ListMultipartUploadsResult) {
  8249. var Upload = data.ListMultipartUploadsResult.Upload || [];
  8250. var CommonPrefixes = data.ListMultipartUploadsResult.CommonPrefixes || [];
  8251. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  8252. Upload = util.isArray(Upload) ? Upload : [Upload];
  8253. data.ListMultipartUploadsResult.Upload = Upload;
  8254. data.ListMultipartUploadsResult.CommonPrefixes = CommonPrefixes;
  8255. }
  8256. var result = util.clone(data.ListMultipartUploadsResult || {});
  8257. util.extend(result, {
  8258. statusCode: data.statusCode,
  8259. headers: data.headers
  8260. });
  8261. callback(null, result);
  8262. });
  8263. }
  8264. /**
  8265. * 上传的分块列表查询
  8266. * @param {Object} params 参数对象,必须
  8267. * @param {String} params.Bucket Bucket名称,必须
  8268. * @param {String} params.Region 地域名称,必须
  8269. * @param {String} params.Key object名称,必须
  8270. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  8271. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  8272. * @param {String} params.MaxParts 单次返回最大的条目数量,默认1000,非必须
  8273. * @param {String} params.PartNumberMarker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  8274. * @param {Function} callback 回调函数,必须
  8275. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8276. * @return {Object} data 返回的数据
  8277. * @return {Object} data.ListMultipartUploadsResult 分块信息
  8278. */
  8279. function multipartListPart(params, callback) {
  8280. var reqParams = {};
  8281. reqParams['uploadId'] = params['UploadId'];
  8282. reqParams['encoding-type'] = params['EncodingType'];
  8283. reqParams['max-parts'] = params['MaxParts'];
  8284. reqParams['part-number-marker'] = params['PartNumberMarker'];
  8285. submitRequest.call(this, {
  8286. Action: 'name/cos:ListParts',
  8287. method: 'GET',
  8288. Bucket: params.Bucket,
  8289. Region: params.Region,
  8290. Key: params.Key,
  8291. headers: params.Headers,
  8292. qs: reqParams
  8293. }, function (err, data) {
  8294. if (err) return callback(err);
  8295. var ListPartsResult = data.ListPartsResult || {};
  8296. var Part = ListPartsResult.Part || [];
  8297. Part = util.isArray(Part) ? Part : [Part];
  8298. ListPartsResult.Part = Part;
  8299. var result = util.clone(ListPartsResult);
  8300. util.extend(result, {
  8301. statusCode: data.statusCode,
  8302. headers: data.headers
  8303. });
  8304. callback(null, result);
  8305. });
  8306. }
  8307. /**
  8308. * 抛弃分块上传
  8309. * @param {Object} params 参数对象,必须
  8310. * @param {String} params.Bucket Bucket名称,必须
  8311. * @param {String} params.Region 地域名称,必须
  8312. * @param {String} params.Key object名称,必须
  8313. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  8314. * @param {Function} callback 回调函数,必须
  8315. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8316. * @return {Object} data 返回的数据
  8317. */
  8318. function multipartAbort(params, callback) {
  8319. var reqParams = {};
  8320. reqParams['uploadId'] = params['UploadId'];
  8321. submitRequest.call(this, {
  8322. Action: 'name/cos:AbortMultipartUpload',
  8323. method: 'DELETE',
  8324. Bucket: params.Bucket,
  8325. Region: params.Region,
  8326. Key: params.Key,
  8327. headers: params.Headers,
  8328. qs: reqParams
  8329. }, function (err, data) {
  8330. if (err) return callback(err);
  8331. callback(null, {
  8332. statusCode: data.statusCode,
  8333. headers: data.headers
  8334. });
  8335. });
  8336. }
  8337. /**
  8338. * 追加上传
  8339. * @param {Object} params 参数对象,必须
  8340. * @param {String} params.Bucket Bucket名称,必须
  8341. * @param {String} params.Region 地域名称,必须
  8342. * @param {String} params.Key object名称,必须
  8343. * @param {String} params.Body 上传文件的内容,只支持字符串
  8344. * @param {Number} params.Position 追加操作的起始点,单位为字节,必须
  8345. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  8346. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存,非必须
  8347. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  8348. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),必须
  8349. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  8350. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  8351. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  8352. * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须
  8353. * @param {String} params.GrantRead 赋予被授权者读取对象的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  8354. * @param {String} params.GrantReadAcp 赋予被授权者读取对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  8355. * @param {String} params.GrantWriteAcp 赋予被授权者写入对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  8356. * @param {String} params.GrantFullControl 赋予被授权者操作对象的所有权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  8357. * @param {String} params.StorageClass 设置对象的存储级别,枚举值:STANDARD、STANDARD_IA、ARCHIVE,默认值:STANDARD,非必须
  8358. * @param {String} params.x-cos-meta-* 允许用户自定义的头部信息,将作为对象的元数据保存。大小限制2KB,非必须
  8359. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须
  8360. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  8361. * @param {Function} callback 回调函数,必须
  8362. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8363. * @return {Object} data 返回的数据
  8364. */
  8365. function appendObject(params, callback) {
  8366. submitRequest.call(this, {
  8367. Action: 'name/cos:AppendObject',
  8368. method: 'POST',
  8369. Bucket: params.Bucket,
  8370. Region: params.Region,
  8371. action: 'append',
  8372. Key: params.Key,
  8373. body: params.Body,
  8374. qs: {
  8375. position: params.Position
  8376. },
  8377. headers: params.Headers
  8378. }, function (err, data) {
  8379. if (err) return callback(err);
  8380. callback(null, data);
  8381. });
  8382. }
  8383. /**
  8384. * cos 内置请求
  8385. * @param {Object} params 参数对象,必须
  8386. * @param {String} params.Bucket Bucket名称,必须
  8387. * @param {String} params.Region 地域名称,必须
  8388. * @param {String} params.Key object名称,必须
  8389. * @param {Function} callback 回调函数,必须
  8390. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8391. * @return {Object} data 返回的数据
  8392. */
  8393. function request(params, callback) {
  8394. submitRequest.call(this, {
  8395. method: params.Method,
  8396. Bucket: params.Bucket,
  8397. Region: params.Region,
  8398. Key: params.Key,
  8399. action: params.Action,
  8400. headers: params.Headers,
  8401. qs: params.Query,
  8402. body: params.Body,
  8403. Url: params.Url,
  8404. rawBody: params.RawBody
  8405. }, function (err, data) {
  8406. if (err) return callback(err);
  8407. if (data && data.body) {
  8408. data.Body = data.body;
  8409. delete data.body;
  8410. }
  8411. callback(err, data);
  8412. });
  8413. }
  8414. /**
  8415. * 获取签名
  8416. * @param {Object} params 参数对象,必须
  8417. * @param {String} params.Method 请求方法,必须
  8418. * @param {String} params.Key object名称,必须
  8419. * @param {String} params.Expires 名超时时间,单位秒,可选
  8420. * @return {String} data 返回签名字符串
  8421. */
  8422. function getAuth(params) {
  8423. var self = this;
  8424. return util.getAuth({
  8425. SecretId: params.SecretId || this.options.SecretId || '',
  8426. SecretKey: params.SecretKey || this.options.SecretKey || '',
  8427. Bucket: params.Bucket,
  8428. Region: params.Region,
  8429. Method: params.Method,
  8430. Key: params.Key,
  8431. Query: params.Query,
  8432. Headers: params.Headers,
  8433. Expires: params.Expires,
  8434. SystemClockOffset: self.options.SystemClockOffset
  8435. });
  8436. }
  8437. /**
  8438. * 获取文件下载链接
  8439. * @param {Object} params 参数对象,必须
  8440. * @param {String} params.Bucket Bucket名称,必须
  8441. * @param {String} params.Region 地域名称,必须
  8442. * @param {String} params.Key object名称,必须
  8443. * @param {String} params.Method 请求的方法,可选
  8444. * @param {String} params.Expires 签名超时时间,单位秒,可选
  8445. * @param {Function} callback 回调函数,必须
  8446. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  8447. * @return {Object} data 返回的数据
  8448. */
  8449. function getObjectUrl(params, callback) {
  8450. var self = this;
  8451. var useAccelerate = params.UseAccelerate === undefined ? self.options.UseAccelerate : params.UseAccelerate;
  8452. var url = getUrl({
  8453. ForcePathStyle: self.options.ForcePathStyle,
  8454. protocol: params.Protocol || self.options.Protocol,
  8455. domain: params.Domain || self.options.Domain,
  8456. bucket: params.Bucket,
  8457. region: useAccelerate ? 'accelerate' : params.Region,
  8458. object: params.Key
  8459. });
  8460. var queryParamsStr = '';
  8461. if (params.Query) {
  8462. queryParamsStr += util.obj2str(params.Query);
  8463. }
  8464. if (params.QueryString) {
  8465. queryParamsStr += (queryParamsStr ? '&' : '') + params.QueryString;
  8466. }
  8467. var syncUrl = url;
  8468. if (params.Sign !== undefined && !params.Sign) {
  8469. queryParamsStr && (syncUrl += '?' + queryParamsStr);
  8470. callback(null, { Url: syncUrl });
  8471. return syncUrl;
  8472. }
  8473. // 签名加上 Host,避免跨桶访问
  8474. var SignHost = getSignHost.call(this, { Bucket: params.Bucket, Region: params.Region, UseAccelerate: params.UseAccelerate, Url: url });
  8475. var AuthData = getAuthorizationAsync.call(this, {
  8476. Action: (params.Method || '').toUpperCase() === 'PUT' ? 'name/cos:PutObject' : 'name/cos:GetObject',
  8477. Bucket: params.Bucket || '',
  8478. Region: params.Region || '',
  8479. Method: params.Method || 'get',
  8480. Key: params.Key,
  8481. Expires: params.Expires,
  8482. Headers: params.Headers,
  8483. Query: params.Query,
  8484. SignHost: SignHost,
  8485. ForceSignHost: params.ForceSignHost === false ? false : self.options.ForceSignHost // getObjectUrl支持传参ForceSignHost
  8486. }, function (err, AuthData) {
  8487. if (!callback) return;
  8488. if (err) {
  8489. callback(err);
  8490. return;
  8491. }
  8492. // 兼容万象url qUrlParamList需要再encode一次
  8493. var replaceUrlParamList = function replaceUrlParamList(url) {
  8494. var urlParams = url.match(/q-url-param-list.*?(?=&)/g)[0];
  8495. var encodedParams = 'q-url-param-list=' + encodeURIComponent(urlParams.replace(/q-url-param-list=/, '')).toLowerCase();
  8496. var reg = new RegExp(urlParams, 'g');
  8497. var replacedUrl = url.replace(reg, encodedParams);
  8498. return replacedUrl;
  8499. };
  8500. var signUrl = url;
  8501. signUrl += '?' + (AuthData.Authorization.indexOf('q-signature') > -1 ? replaceUrlParamList(AuthData.Authorization) : 'sign=' + encodeURIComponent(AuthData.Authorization));
  8502. AuthData.SecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.SecurityToken);
  8503. AuthData.ClientIP && (signUrl += '&clientIP=' + AuthData.ClientIP);
  8504. AuthData.ClientUA && (signUrl += '&clientUA=' + AuthData.ClientUA);
  8505. AuthData.Token && (signUrl += '&token=' + AuthData.Token);
  8506. queryParamsStr && (signUrl += '&' + queryParamsStr);
  8507. setTimeout(function () {
  8508. callback(null, { Url: signUrl });
  8509. });
  8510. });
  8511. if (AuthData) {
  8512. syncUrl += '?' + AuthData.Authorization + (AuthData.SecurityToken ? '&x-cos-security-token=' + AuthData.SecurityToken : '');
  8513. queryParamsStr && (syncUrl += '&' + queryParamsStr);
  8514. } else {
  8515. queryParamsStr && (syncUrl += '?' + queryParamsStr);
  8516. }
  8517. return syncUrl;
  8518. }
  8519. /**
  8520. * 私有方法
  8521. */
  8522. function decodeAcl(AccessControlPolicy) {
  8523. var result = {
  8524. GrantFullControl: [],
  8525. GrantWrite: [],
  8526. GrantRead: [],
  8527. GrantReadAcp: [],
  8528. GrantWriteAcp: [],
  8529. ACL: ''
  8530. };
  8531. var GrantMap = {
  8532. 'FULL_CONTROL': 'GrantFullControl',
  8533. 'WRITE': 'GrantWrite',
  8534. 'READ': 'GrantRead',
  8535. 'READ_ACP': 'GrantReadAcp',
  8536. 'WRITE_ACP': 'GrantWriteAcp'
  8537. };
  8538. var AccessControlList = AccessControlPolicy && AccessControlPolicy.AccessControlList || {};
  8539. var Grant = AccessControlList.Grant;
  8540. if (Grant) {
  8541. Grant = util.isArray(Grant) ? Grant : [Grant];
  8542. }
  8543. var PublicAcl = { READ: 0, WRITE: 0, FULL_CONTROL: 0 };
  8544. Grant && Grant.length && util.each(Grant, function (item) {
  8545. if (item.Grantee.ID === 'qcs::cam::anyone:anyone' || item.Grantee.URI === 'http://cam.qcloud.com/groups/global/AllUsers') {
  8546. PublicAcl[item.Permission] = 1;
  8547. } else if (item.Grantee.ID !== AccessControlPolicy.Owner.ID) {
  8548. result[GrantMap[item.Permission]].push('id="' + item.Grantee.ID + '"');
  8549. }
  8550. });
  8551. if (PublicAcl.FULL_CONTROL || PublicAcl.WRITE && PublicAcl.READ) {
  8552. result.ACL = 'public-read-write';
  8553. } else if (PublicAcl.READ) {
  8554. result.ACL = 'public-read';
  8555. } else {
  8556. result.ACL = 'private';
  8557. }
  8558. util.each(GrantMap, function (item) {
  8559. result[item] = uniqGrant(result[item].join(','));
  8560. });
  8561. return result;
  8562. }
  8563. // Grant 去重
  8564. function uniqGrant(str) {
  8565. var arr = str.split(',');
  8566. var exist = {};
  8567. var i, item;
  8568. for (i = 0; i < arr.length;) {
  8569. item = arr[i].trim();
  8570. if (exist[item]) {
  8571. arr.splice(i, 1);
  8572. } else {
  8573. exist[item] = true;
  8574. arr[i] = item;
  8575. i++;
  8576. }
  8577. }
  8578. return arr.join(',');
  8579. }
  8580. // 生成操作 url
  8581. function getUrl(params) {
  8582. var longBucket = params.bucket;
  8583. var shortBucket = longBucket.substr(0, longBucket.lastIndexOf('-'));
  8584. var appId = longBucket.substr(longBucket.lastIndexOf('-') + 1);
  8585. var domain = params.domain;
  8586. var region = params.region;
  8587. var object = params.object;
  8588. var protocol = 'https:';
  8589. if (!domain) {
  8590. if (['cn-south', 'cn-south-2', 'cn-north', 'cn-east', 'cn-southwest', 'sg'].indexOf(region) > -1) {
  8591. domain = '{Region}.myqcloud.com';
  8592. } else {
  8593. domain = 'cos.{Region}.myqcloud.com';
  8594. }
  8595. if (!params.ForcePathStyle) {
  8596. domain = '{Bucket}.' + domain;
  8597. }
  8598. }
  8599. domain = domain.replace(/\{\{AppId\}\}/ig, appId).replace(/\{\{Bucket\}\}/ig, shortBucket).replace(/\{\{Region\}\}/ig, region).replace(/\{\{.*?\}\}/ig, '');
  8600. domain = domain.replace(/\{AppId\}/ig, appId).replace(/\{BucketName\}/ig, shortBucket).replace(/\{Bucket\}/ig, longBucket).replace(/\{Region\}/ig, region).replace(/\{.*?\}/ig, '');
  8601. if (!/^[a-zA-Z]+:\/\//.test(domain)) {
  8602. domain = protocol + '//' + domain;
  8603. }
  8604. // 去掉域名最后的斜杆
  8605. if (domain.slice(-1) === '/') {
  8606. domain = domain.slice(0, -1);
  8607. }
  8608. var url = domain;
  8609. if (params.ForcePathStyle) {
  8610. url += '/' + longBucket;
  8611. }
  8612. url += '/';
  8613. if (object) {
  8614. url += util.camSafeUrlEncode(object).replace(/%2F/g, '/');
  8615. }
  8616. if (params.isLocation) {
  8617. url = url.replace(/^https?:\/\//, '');
  8618. }
  8619. return url;
  8620. }
  8621. var getSignHost = function getSignHost(opt) {
  8622. if (!opt.Bucket || !opt.Region) return '';
  8623. var useAccelerate = opt.UseAccelerate === undefined ? this.options.UseAccelerate : opt.UseAccelerate;
  8624. var url = opt.Url || getUrl({
  8625. ForcePathStyle: this.options.ForcePathStyle,
  8626. protocol: this.options.Protocol,
  8627. domain: this.options.Domain,
  8628. bucket: opt.Bucket,
  8629. region: useAccelerate ? 'accelerate' : opt.Region
  8630. });
  8631. var urlHost = url.replace(/^https?:\/\/([^/]+)(\/.*)?$/, '$1');
  8632. var standardHostReg = new RegExp('^([a-z\\d-]+-\\d+\\.)?(cos|cosv6|ci|pic)\\.([a-z\\d-]+)\\.myqcloud\\.com$');
  8633. if (standardHostReg.test(urlHost)) return urlHost;
  8634. return '';
  8635. };
  8636. // 异步获取签名
  8637. function getAuthorizationAsync(params, callback) {
  8638. var headers = util.clone(params.Headers);
  8639. var headerHost = '';
  8640. util.each(headers, function (v, k) {
  8641. (v === '' || ['content-type', 'cache-control'].indexOf(k.toLowerCase()) > -1) && delete headers[k];
  8642. if (k.toLowerCase() === 'host') headerHost = v;
  8643. });
  8644. // ForceSignHost明确传入false才不加入host签名
  8645. var forceSignHost = params.ForceSignHost === false ? false : true;
  8646. // Host 加入签名计算
  8647. if (!headerHost && params.SignHost && forceSignHost) headers.Host = params.SignHost;
  8648. // 获取凭证的回调,避免用户 callback 多次
  8649. var cbDone = false;
  8650. var cb = function cb(err, AuthData) {
  8651. if (cbDone) return;
  8652. cbDone = true;
  8653. if (AuthData && AuthData.XCosSecurityToken && !AuthData.SecurityToken) {
  8654. AuthData = util.clone(AuthData);
  8655. AuthData.SecurityToken = AuthData.XCosSecurityToken;
  8656. delete AuthData.XCosSecurityToken;
  8657. }
  8658. callback && callback(err, AuthData);
  8659. };
  8660. var self = this;
  8661. var Bucket = params.Bucket || '';
  8662. var Region = params.Region || '';
  8663. // PathName
  8664. var KeyName = params.Action === 'name/cos:PostObject' || !params.Key ? '' : params.Key;
  8665. if (self.options.ForcePathStyle && Bucket) {
  8666. KeyName = Bucket + '/' + KeyName;
  8667. }
  8668. var Pathname = '/' + KeyName;
  8669. // Action、ResourceKey
  8670. var StsData = {};
  8671. var Scope = params.Scope;
  8672. if (!Scope) {
  8673. var Action = params.Action || '';
  8674. var ResourceKey = params.ResourceKey || params.Key || '';
  8675. Scope = params.Scope || [{
  8676. action: Action,
  8677. bucket: Bucket,
  8678. region: Region,
  8679. prefix: ResourceKey
  8680. }];
  8681. }
  8682. var ScopeKey = util.md5(JSON.stringify(Scope));
  8683. // STS
  8684. self._StsCache = self._StsCache || [];
  8685. (function () {
  8686. var i, AuthData;
  8687. for (i = self._StsCache.length - 1; i >= 0; i--) {
  8688. AuthData = self._StsCache[i];
  8689. var compareTime = Math.round(util.getSkewTime(self.options.SystemClockOffset) / 1000) + 30;
  8690. if (AuthData.StartTime && compareTime < AuthData.StartTime || compareTime >= AuthData.ExpiredTime) {
  8691. self._StsCache.splice(i, 1);
  8692. continue;
  8693. }
  8694. if (!AuthData.ScopeLimit || AuthData.ScopeLimit && AuthData.ScopeKey === ScopeKey) {
  8695. StsData = AuthData;
  8696. break;
  8697. }
  8698. }
  8699. })();
  8700. var calcAuthByTmpKey = function calcAuthByTmpKey() {
  8701. var KeyTime = '';
  8702. if (StsData.StartTime && params.Expires) {
  8703. KeyTime = StsData.StartTime + ';' + (StsData.StartTime + params.Expires * 1);
  8704. } else if (StsData.StartTime && StsData.ExpiredTime) {
  8705. KeyTime = StsData.StartTime + ';' + StsData.ExpiredTime;
  8706. }
  8707. var Authorization = util.getAuth({
  8708. SecretId: StsData.TmpSecretId,
  8709. SecretKey: StsData.TmpSecretKey,
  8710. Method: params.Method,
  8711. Pathname: Pathname,
  8712. Query: params.Query,
  8713. Headers: headers,
  8714. Expires: params.Expires,
  8715. SystemClockOffset: self.options.SystemClockOffset,
  8716. KeyTime: KeyTime,
  8717. ForceSignHost: forceSignHost
  8718. });
  8719. var AuthData = {
  8720. Authorization: Authorization,
  8721. SecurityToken: StsData.SecurityToken || StsData.XCosSecurityToken || '',
  8722. Token: StsData.Token || '',
  8723. ClientIP: StsData.ClientIP || '',
  8724. ClientUA: StsData.ClientUA || ''
  8725. };
  8726. cb(null, AuthData);
  8727. };
  8728. var checkAuthError = function checkAuthError(AuthData) {
  8729. if (AuthData.Authorization) {
  8730. // 检查签名格式
  8731. var formatAllow = false;
  8732. var auth = AuthData.Authorization;
  8733. if (auth) {
  8734. if (auth.indexOf(' ') > -1) {
  8735. formatAllow = false;
  8736. } else if (auth.indexOf('q-sign-algorithm=') > -1 && auth.indexOf('q-ak=') > -1 && auth.indexOf('q-sign-time=') > -1 && auth.indexOf('q-key-time=') > -1 && auth.indexOf('q-url-param-list=') > -1) {
  8737. formatAllow = true;
  8738. } else {
  8739. try {
  8740. auth = atob(auth);
  8741. if (auth.indexOf('a=') > -1 && auth.indexOf('k=') > -1 && auth.indexOf('t=') > -1 && auth.indexOf('r=') > -1 && auth.indexOf('b=') > -1) {
  8742. formatAllow = true;
  8743. }
  8744. } catch (e) {}
  8745. }
  8746. }
  8747. if (!formatAllow) return util.error(new Error('getAuthorization callback params format error'));
  8748. } else {
  8749. if (!AuthData.TmpSecretId) return util.error(new Error('getAuthorization callback params missing "TmpSecretId"'));
  8750. if (!AuthData.TmpSecretKey) return util.error(new Error('getAuthorization callback params missing "TmpSecretKey"'));
  8751. if (!AuthData.SecurityToken && !AuthData.XCosSecurityToken) return util.error(new Error('getAuthorization callback params missing "SecurityToken"'));
  8752. if (!AuthData.ExpiredTime) return util.error(new Error('getAuthorization callback params missing "ExpiredTime"'));
  8753. if (AuthData.ExpiredTime && AuthData.ExpiredTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits'));
  8754. if (AuthData.StartTime && AuthData.StartTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime'));
  8755. }
  8756. return false;
  8757. };
  8758. // 先判断是否有临时密钥
  8759. if (StsData.ExpiredTime && StsData.ExpiredTime - util.getSkewTime(self.options.SystemClockOffset) / 1000 > 60) {
  8760. // 如果缓存的临时密钥有效,并还有超过60秒有效期就直接使用
  8761. calcAuthByTmpKey();
  8762. } else if (self.options.getAuthorization) {
  8763. // 外部计算签名或获取临时密钥
  8764. self.options.getAuthorization.call(self, {
  8765. Bucket: Bucket,
  8766. Region: Region,
  8767. Method: params.Method,
  8768. Key: KeyName,
  8769. Pathname: Pathname,
  8770. Query: params.Query,
  8771. Headers: headers,
  8772. Scope: Scope,
  8773. SystemClockOffset: self.options.SystemClockOffset,
  8774. ForceSignHost: forceSignHost
  8775. }, function (AuthData) {
  8776. if (typeof AuthData === 'string') {
  8777. AuthData = { Authorization: AuthData };
  8778. }
  8779. var AuthError = checkAuthError(AuthData);
  8780. if (AuthError) return cb(AuthError);
  8781. if (AuthData.Authorization) {
  8782. cb(null, AuthData);
  8783. } else {
  8784. StsData = AuthData || {};
  8785. StsData.Scope = Scope;
  8786. StsData.ScopeKey = ScopeKey;
  8787. self._StsCache.push(StsData);
  8788. calcAuthByTmpKey();
  8789. }
  8790. });
  8791. } else if (self.options.getSTS) {
  8792. // 外部获取临时密钥
  8793. self.options.getSTS.call(self, {
  8794. Bucket: Bucket,
  8795. Region: Region
  8796. }, function (data) {
  8797. StsData = data || {};
  8798. StsData.Scope = Scope;
  8799. StsData.ScopeKey = ScopeKey;
  8800. if (!StsData.TmpSecretId) StsData.TmpSecretId = StsData.SecretId;
  8801. if (!StsData.TmpSecretKey) StsData.TmpSecretKey = StsData.SecretKey;
  8802. var AuthError = checkAuthError(StsData);
  8803. if (AuthError) return cb(AuthError);
  8804. self._StsCache.push(StsData);
  8805. calcAuthByTmpKey();
  8806. });
  8807. } else {
  8808. // 内部计算获取签名
  8809. return function () {
  8810. var Authorization = util.getAuth({
  8811. SecretId: params.SecretId || self.options.SecretId,
  8812. SecretKey: params.SecretKey || self.options.SecretKey,
  8813. Method: params.Method,
  8814. Pathname: Pathname,
  8815. Query: params.Query,
  8816. Headers: headers,
  8817. Expires: params.Expires,
  8818. SystemClockOffset: self.options.SystemClockOffset,
  8819. ForceSignHost: forceSignHost
  8820. });
  8821. var AuthData = {
  8822. Authorization: Authorization,
  8823. SecurityToken: self.options.SecurityToken || self.options.XCosSecurityToken
  8824. };
  8825. cb(null, AuthData);
  8826. return AuthData;
  8827. }();
  8828. }
  8829. return '';
  8830. }
  8831. // 调整时间偏差
  8832. function allowRetry(err) {
  8833. var allowRetry = false;
  8834. var isTimeError = false;
  8835. var serverDate = err.headers && (err.headers.date || err.headers.Date) || err.error && err.error.ServerTime;
  8836. try {
  8837. var errorCode = err.error.Code;
  8838. var errorMessage = err.error.Message;
  8839. if (errorCode === 'RequestTimeTooSkewed' || errorCode === 'AccessDenied' && errorMessage === 'Request has expired') {
  8840. isTimeError = true;
  8841. }
  8842. } catch (e) {}
  8843. if (err) {
  8844. if (isTimeError && serverDate) {
  8845. var serverTime = Date.parse(serverDate);
  8846. if (this.options.CorrectClockSkew && Math.abs(util.getSkewTime(this.options.SystemClockOffset) - serverTime) >= 30000) {
  8847. console.error('error: Local time is too skewed.');
  8848. this.options.SystemClockOffset = serverTime - Date.now();
  8849. allowRetry = true;
  8850. }
  8851. } else if (Math.floor(err.statusCode / 100) === 5) {
  8852. allowRetry = true;
  8853. }
  8854. }
  8855. return allowRetry;
  8856. }
  8857. // 获取签名并发起请求
  8858. function submitRequest(params, callback) {
  8859. var self = this;
  8860. // 处理 headers
  8861. !params.headers && (params.headers = {});
  8862. // 处理 query
  8863. !params.qs && (params.qs = {});
  8864. params.VersionId && (params.qs.versionId = params.VersionId);
  8865. params.qs = util.clearKey(params.qs);
  8866. // 清理 undefined 和 null 字段
  8867. params.headers && (params.headers = util.clearKey(params.headers));
  8868. params.qs && (params.qs = util.clearKey(params.qs));
  8869. var Query = util.clone(params.qs);
  8870. params.action && (Query[params.action] = '');
  8871. var paramsUrl = params.url || params.Url;
  8872. var SignHost = params.SignHost || getSignHost.call(this, { Bucket: params.Bucket, Region: params.Region, Url: paramsUrl });
  8873. var next = function next(tryTimes) {
  8874. var oldClockOffset = self.options.SystemClockOffset;
  8875. getAuthorizationAsync.call(self, {
  8876. Bucket: params.Bucket || '',
  8877. Region: params.Region || '',
  8878. Method: params.method,
  8879. Key: params.Key,
  8880. Query: Query,
  8881. Headers: params.headers,
  8882. SignHost: SignHost,
  8883. Action: params.Action,
  8884. ResourceKey: params.ResourceKey,
  8885. Scope: params.Scope,
  8886. ForceSignHost: self.options.ForceSignHost
  8887. }, function (err, AuthData) {
  8888. if (err) {
  8889. callback(err);
  8890. return;
  8891. }
  8892. params.AuthData = AuthData;
  8893. _submitRequest.call(self, params, function (err, data) {
  8894. if (err && tryTimes < 2 && (oldClockOffset !== self.options.SystemClockOffset || allowRetry.call(self, err))) {
  8895. if (params.headers) {
  8896. delete params.headers.Authorization;
  8897. delete params.headers['token'];
  8898. delete params.headers['clientIP'];
  8899. delete params.headers['clientUA'];
  8900. delete params.headers['x-cos-security-token'];
  8901. }
  8902. next(tryTimes + 1);
  8903. } else {
  8904. callback(err, data);
  8905. }
  8906. });
  8907. });
  8908. };
  8909. next(1);
  8910. }
  8911. // 发起请求
  8912. function _submitRequest(params, callback) {
  8913. var self = this;
  8914. var TaskId = params.TaskId;
  8915. if (TaskId && !self._isRunningTask(TaskId)) return;
  8916. var bucket = params.Bucket;
  8917. var region = params.Region;
  8918. var object = params.Key;
  8919. var method = params.method || 'GET';
  8920. var url = params.url || params.Url;
  8921. var body = params.body;
  8922. var json = params.json;
  8923. var rawBody = params.rawBody;
  8924. var httpDNSServiceId = self.options.HttpDNSServiceId;
  8925. // url
  8926. if (self.options.UseAccelerate) {
  8927. region = 'accelerate';
  8928. }
  8929. url = url || getUrl({
  8930. ForcePathStyle: self.options.ForcePathStyle,
  8931. protocol: self.options.Protocol,
  8932. domain: self.options.Domain,
  8933. bucket: bucket,
  8934. region: region,
  8935. object: object
  8936. });
  8937. if (params.action) {
  8938. url = url + '?' + params.action;
  8939. }
  8940. if (params.qsStr) {
  8941. if (url.indexOf('?') > -1) {
  8942. url = url + '&' + params.qsStr;
  8943. } else {
  8944. url = url + '?' + params.qsStr;
  8945. }
  8946. }
  8947. var opt = {
  8948. method: method,
  8949. url: url,
  8950. headers: params.headers,
  8951. qs: params.qs,
  8952. filePath: params.filePath,
  8953. body: body,
  8954. json: json,
  8955. httpDNSServiceId: httpDNSServiceId
  8956. };
  8957. // 兼容ci接口
  8958. var token = 'x-cos-security-token';
  8959. if (util.isCIHost(url)) {
  8960. token = 'x-ci-security-token';
  8961. }
  8962. // 获取签名
  8963. opt.headers.Authorization = params.AuthData.Authorization;
  8964. params.AuthData.Token && (opt.headers['token'] = params.AuthData.Token);
  8965. params.AuthData.ClientIP && (opt.headers['clientIP'] = params.AuthData.ClientIP);
  8966. params.AuthData.ClientUA && (opt.headers['clientUA'] = params.AuthData.ClientUA);
  8967. params.AuthData.SecurityToken && (opt.headers[token] = params.AuthData.SecurityToken);
  8968. // 清理 undefined 和 null 字段
  8969. opt.headers && (opt.headers = util.clearKey(opt.headers));
  8970. opt = util.clearKey(opt);
  8971. // progress
  8972. if (params.onProgress && typeof params.onProgress === 'function') {
  8973. opt.onProgress = function (e) {
  8974. if (TaskId && !self._isRunningTask(TaskId)) return;
  8975. var loaded = e ? e.loaded : 0;
  8976. params.onProgress({ loaded: loaded, total: e.total });
  8977. };
  8978. }
  8979. if (this.options.Timeout) {
  8980. opt.timeout = this.options.Timeout;
  8981. }
  8982. self.options.ForcePathStyle && (opt.pathStyle = self.options.ForcePathStyle);
  8983. self.emit('before-send', opt);
  8984. var sender = REQUEST(opt, function (err, response, body) {
  8985. if (err === 'abort') return;
  8986. // 返回内容添加 状态码 和 headers
  8987. var hasReturned;
  8988. var cb = function cb(err, data) {
  8989. TaskId && self.off('inner-kill-task', killTask);
  8990. if (hasReturned) return;
  8991. hasReturned = true;
  8992. var attrs = {};
  8993. response && response.statusCode && (attrs.statusCode = response.statusCode);
  8994. response && response.headers && (attrs.headers = response.headers);
  8995. if (err) {
  8996. err = util.extend(err || {}, attrs);
  8997. callback(err, null);
  8998. } else {
  8999. data = util.extend(data || {}, attrs);
  9000. callback(null, data);
  9001. }
  9002. sender = null;
  9003. };
  9004. // 请求错误,发生网络错误
  9005. if (err) {
  9006. cb({ error: err });
  9007. return;
  9008. }
  9009. // 不对 body 进行转换,body 直接挂载返回
  9010. var jsonRes;
  9011. if (rawBody) {
  9012. jsonRes = {};
  9013. jsonRes.body = body;
  9014. } else {
  9015. try {
  9016. jsonRes = body && body.indexOf('<') > -1 && body.indexOf('>') > -1 && util.xml2json(body) || {};
  9017. } catch (e) {
  9018. jsonRes = body || {};
  9019. }
  9020. }
  9021. // 请求返回码不为 200
  9022. var statusCode = response.statusCode;
  9023. var statusSuccess = Math.floor(statusCode / 100) === 2; // 200 202 204 206
  9024. if (!statusSuccess) {
  9025. cb({ error: jsonRes.Error || jsonRes });
  9026. return;
  9027. }
  9028. if (jsonRes.Error) {
  9029. cb({ error: jsonRes.Error });
  9030. return;
  9031. }
  9032. cb(null, jsonRes);
  9033. });
  9034. // kill task
  9035. var killTask = function killTask(data) {
  9036. if (data.TaskId === TaskId) {
  9037. sender && sender.abort && sender.abort();
  9038. self.off('inner-kill-task', killTask);
  9039. }
  9040. };
  9041. TaskId && self.on('inner-kill-task', killTask);
  9042. }
  9043. var API_MAP = {
  9044. // Bucket 相关方法
  9045. getService: getService, // Bucket
  9046. putBucket: putBucket,
  9047. headBucket: headBucket, // Bucket
  9048. getBucket: getBucket,
  9049. deleteBucket: deleteBucket,
  9050. putBucketAcl: putBucketAcl, // BucketACL
  9051. getBucketAcl: getBucketAcl,
  9052. putBucketCors: putBucketCors, // BucketCors
  9053. getBucketCors: getBucketCors,
  9054. deleteBucketCors: deleteBucketCors,
  9055. getBucketLocation: getBucketLocation, // BucketLocation
  9056. getBucketPolicy: getBucketPolicy, // BucketPolicy
  9057. putBucketPolicy: putBucketPolicy,
  9058. deleteBucketPolicy: deleteBucketPolicy,
  9059. putBucketTagging: putBucketTagging, // BucketTagging
  9060. getBucketTagging: getBucketTagging,
  9061. deleteBucketTagging: deleteBucketTagging,
  9062. putBucketLifecycle: putBucketLifecycle, // BucketLifecycle
  9063. getBucketLifecycle: getBucketLifecycle,
  9064. deleteBucketLifecycle: deleteBucketLifecycle,
  9065. putBucketVersioning: putBucketVersioning, // BucketVersioning
  9066. getBucketVersioning: getBucketVersioning,
  9067. putBucketReplication: putBucketReplication, // BucketReplication
  9068. getBucketReplication: getBucketReplication,
  9069. deleteBucketReplication: deleteBucketReplication,
  9070. putBucketWebsite: putBucketWebsite, // BucketWebsite
  9071. getBucketWebsite: getBucketWebsite,
  9072. deleteBucketWebsite: deleteBucketWebsite,
  9073. putBucketReferer: putBucketReferer, // BucketReferer
  9074. getBucketReferer: getBucketReferer,
  9075. putBucketDomain: putBucketDomain, // BucketDomain
  9076. getBucketDomain: getBucketDomain,
  9077. deleteBucketDomain: deleteBucketDomain,
  9078. putBucketOrigin: putBucketOrigin, // BucketOrigin
  9079. getBucketOrigin: getBucketOrigin,
  9080. deleteBucketOrigin: deleteBucketOrigin,
  9081. putBucketLogging: putBucketLogging, // BucketLogging
  9082. getBucketLogging: getBucketLogging,
  9083. putBucketInventory: putBucketInventory, // BucketInventory
  9084. getBucketInventory: getBucketInventory,
  9085. listBucketInventory: listBucketInventory,
  9086. deleteBucketInventory: deleteBucketInventory,
  9087. putBucketAccelerate: putBucketAccelerate,
  9088. getBucketAccelerate: getBucketAccelerate,
  9089. // Object 相关方法
  9090. getObject: getObject,
  9091. headObject: headObject,
  9092. listObjectVersions: listObjectVersions,
  9093. putObject: putObject,
  9094. postObject: postObject,
  9095. deleteObject: deleteObject,
  9096. getObjectAcl: getObjectAcl,
  9097. putObjectAcl: putObjectAcl,
  9098. optionsObject: optionsObject,
  9099. putObjectCopy: putObjectCopy,
  9100. deleteMultipleObject: deleteMultipleObject,
  9101. restoreObject: restoreObject,
  9102. putObjectTagging: putObjectTagging,
  9103. getObjectTagging: getObjectTagging,
  9104. deleteObjectTagging: deleteObjectTagging,
  9105. appendObject: appendObject,
  9106. // 分块上传相关方法
  9107. uploadPartCopy: uploadPartCopy,
  9108. multipartInit: multipartInit,
  9109. multipartUpload: multipartUpload,
  9110. multipartComplete: multipartComplete,
  9111. multipartList: multipartList,
  9112. multipartListPart: multipartListPart,
  9113. multipartAbort: multipartAbort,
  9114. // 工具方法
  9115. request: request,
  9116. getObjectUrl: getObjectUrl,
  9117. getAuth: getAuth
  9118. };
  9119. module.exports.init = function (COS, task) {
  9120. task.transferToTaskMethod(API_MAP, 'postObject');
  9121. task.transferToTaskMethod(API_MAP, 'putObject');
  9122. util.each(API_MAP, function (fn, apiName) {
  9123. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  9124. });
  9125. };
  9126. /***/ }),
  9127. /* 22 */
  9128. /***/ (function(module, exports, __webpack_require__) {
  9129. "use strict";
  9130. function camSafeUrlEncode(str) {
  9131. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
  9132. }
  9133. function getObjectKeys(obj, forKey) {
  9134. var list = [];
  9135. for (var key in obj) {
  9136. if (obj.hasOwnProperty(key)) {
  9137. list.push(forKey ? camSafeUrlEncode(key).toLowerCase() : key);
  9138. }
  9139. }
  9140. return list.sort(function (a, b) {
  9141. a = a.toLowerCase();
  9142. b = b.toLowerCase();
  9143. return a === b ? 0 : a > b ? 1 : -1;
  9144. });
  9145. };
  9146. var obj2str = function obj2str(obj, lowerCaseKey) {
  9147. var i, key, val;
  9148. var list = [];
  9149. var keyList = getObjectKeys(obj);
  9150. for (i = 0; i < keyList.length; i++) {
  9151. key = keyList[i];
  9152. val = obj[key] === undefined || obj[key] === null ? '' : '' + obj[key];
  9153. key = lowerCaseKey ? camSafeUrlEncode(key).toLowerCase() : camSafeUrlEncode(key);
  9154. val = camSafeUrlEncode(val) || '';
  9155. list.push(key + '=' + val);
  9156. }
  9157. return list.join('&');
  9158. };
  9159. var request = function request(params, callback) {
  9160. var filePath = params.filePath;
  9161. var headers = params.headers || {};
  9162. var url = params.url || params.Url;
  9163. var method = params.method;
  9164. var onProgress = params.onProgress;
  9165. var httpDNSServiceId = params.httpDNSServiceId;
  9166. var requestTask;
  9167. var cb = function cb(err, response) {
  9168. var H = response.header;
  9169. var headers = {};
  9170. if (H) for (var key in H) {
  9171. if (H.hasOwnProperty(key)) headers[key.toLowerCase()] = H[key];
  9172. }
  9173. callback(err, { statusCode: response.statusCode, headers: headers }, response.data);
  9174. };
  9175. if (filePath) {
  9176. var fileKey;
  9177. var m = url.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/);
  9178. if (params.pathStyle) {
  9179. fileKey = decodeURIComponent(m[3] || '');
  9180. url = m[1] + m[2];
  9181. } else {
  9182. fileKey = decodeURIComponent(m[2] + m[3] || '');
  9183. url = m[1];
  9184. }
  9185. // 整理 postObject 参数
  9186. var formData = {
  9187. 'key': fileKey,
  9188. 'success_action_status': 200,
  9189. 'Signature': headers.Authorization
  9190. };
  9191. var headerKeys = ['Cache-Control', 'Content-Type', 'Content-Disposition', 'Content-Encoding', 'Expires', 'x-cos-storage-class', 'x-cos-security-token', 'x-ci-security-token'];
  9192. for (var i in params.headers) {
  9193. if (params.headers.hasOwnProperty(i) && (i.indexOf('x-cos-meta-') > -1 || headerKeys.indexOf(i) > -1)) {
  9194. formData[i] = params.headers[i];
  9195. }
  9196. }
  9197. headers['x-cos-acl'] && (formData.acl = headers['x-cos-acl']);
  9198. !formData['Content-Type'] && (formData['Content-Type'] = '');
  9199. requestTask = wx.uploadFile({
  9200. url: url,
  9201. method: method,
  9202. name: 'file',
  9203. header: headers,
  9204. filePath: filePath,
  9205. formData: formData,
  9206. timeout: params.timeout,
  9207. success: function success(response) {
  9208. cb(null, response);
  9209. },
  9210. fail: function fail(response) {
  9211. cb(response.errMsg, response);
  9212. }
  9213. });
  9214. requestTask.onProgressUpdate(function (res) {
  9215. onProgress && onProgress({
  9216. loaded: res.totalBytesSent,
  9217. total: res.totalBytesExpectedToSend,
  9218. progress: res.progress / 100
  9219. });
  9220. });
  9221. } else {
  9222. var qsStr = params.qs && obj2str(params.qs) || '';
  9223. if (qsStr) {
  9224. url += (url.indexOf('?') > -1 ? '&' : '?') + qsStr;
  9225. }
  9226. headers['Content-Length'] && delete headers['Content-Length'];
  9227. var requestParams = {
  9228. url: url,
  9229. method: method,
  9230. header: headers,
  9231. dataType: 'text',
  9232. data: params.body,
  9233. timeout: params.timeout,
  9234. success: function success(response) {
  9235. cb(null, response);
  9236. },
  9237. fail: function fail(response) {
  9238. cb(response.errMsg, response);
  9239. }
  9240. };
  9241. if (httpDNSServiceId) {
  9242. Object.assign(requestParams, {
  9243. enableHttpDNS: true,
  9244. httpDNSServiceId: httpDNSServiceId
  9245. });
  9246. }
  9247. requestTask = wx.request(requestParams);
  9248. }
  9249. return requestTask;
  9250. };
  9251. module.exports = request;
  9252. /***/ }),
  9253. /* 23 */
  9254. /***/ (function(module, exports, __webpack_require__) {
  9255. "use strict";
  9256. var Mime = __webpack_require__(24);
  9257. module.exports = new Mime(__webpack_require__(25), __webpack_require__(26));
  9258. /***/ }),
  9259. /* 24 */
  9260. /***/ (function(module, exports, __webpack_require__) {
  9261. "use strict";
  9262. /**
  9263. * @param typeMap [Object] Map of MIME type -> Array[extensions]
  9264. * @param ...
  9265. */
  9266. function Mime() {
  9267. this._types = Object.create(null);
  9268. this._extensions = Object.create(null);
  9269. for (var i = 0; i < arguments.length; i++) {
  9270. this.define(arguments[i]);
  9271. }
  9272. this.define = this.define.bind(this);
  9273. this.getType = this.getType.bind(this);
  9274. this.getExtension = this.getExtension.bind(this);
  9275. }
  9276. /**
  9277. * Define mimetype -> extension mappings. Each key is a mime-type that maps
  9278. * to an array of extensions associated with the type. The first extension is
  9279. * used as the default extension for the type.
  9280. *
  9281. * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
  9282. *
  9283. * If a type declares an extension that has already been defined, an error will
  9284. * be thrown. To suppress this error and force the extension to be associated
  9285. * with the new type, pass `force`=true. Alternatively, you may prefix the
  9286. * extension with "*" to map the type to extension, without mapping the
  9287. * extension to the type.
  9288. *
  9289. * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
  9290. *
  9291. *
  9292. * @param map (Object) type definitions
  9293. * @param force (Boolean) if true, force overriding of existing definitions
  9294. */
  9295. Mime.prototype.define = function (typeMap, force) {
  9296. for (var type in typeMap) {
  9297. var extensions = typeMap[type].map(function (t) {
  9298. return t.toLowerCase();
  9299. });
  9300. type = type.toLowerCase();
  9301. for (var i = 0; i < extensions.length; i++) {
  9302. var ext = extensions[i];
  9303. // '*' prefix = not the preferred type for this extension. So fixup the
  9304. // extension, and skip it.
  9305. if (ext[0] === '*') {
  9306. continue;
  9307. }
  9308. if (!force && ext in this._types) {
  9309. throw new Error('Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".');
  9310. }
  9311. this._types[ext] = type;
  9312. }
  9313. // Use first extension as default
  9314. if (force || !this._extensions[type]) {
  9315. var _ext = extensions[0];
  9316. this._extensions[type] = _ext[0] !== '*' ? _ext : _ext.substr(1);
  9317. }
  9318. }
  9319. };
  9320. /**
  9321. * Lookup a mime type based on extension
  9322. */
  9323. Mime.prototype.getType = function (path) {
  9324. path = String(path);
  9325. var last = path.replace(/^.*[/\\]/, '').toLowerCase();
  9326. var ext = last.replace(/^.*\./, '').toLowerCase();
  9327. var hasPath = last.length < path.length;
  9328. var hasDot = ext.length < last.length - 1;
  9329. return (hasDot || !hasPath) && this._types[ext] || null;
  9330. };
  9331. /**
  9332. * Return file extension associated with a mime type
  9333. */
  9334. Mime.prototype.getExtension = function (type) {
  9335. type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
  9336. return type && this._extensions[type.toLowerCase()] || null;
  9337. };
  9338. module.exports = Mime;
  9339. /***/ }),
  9340. /* 25 */
  9341. /***/ (function(module, exports, __webpack_require__) {
  9342. "use strict";
  9343. module.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] };
  9344. /***/ }),
  9345. /* 26 */
  9346. /***/ (function(module, exports, __webpack_require__) {
  9347. "use strict";
  9348. module.exports = { "application/prs.cww": ["cww"], "application/vnd.1000minds.decision-model+xml": ["1km"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.keynote": ["key"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.numbers": ["numbers"], "application/vnd.apple.pages": ["pages"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.balsamiq.bmml+xml": ["bmml"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.citationstyles.style+xml": ["csl"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dbf": ["dbf"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mapbox-vector-tile": ["mvt"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["*stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.ac+xml": ["*ac"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openblox.game+xml": ["obgx"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openstreetmap.data+xml": ["osm"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.rar": ["rar"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.software602.filler.form+xml": ["fo"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.syncml.dmddf+xml": ["ddf"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": ["*dmg"], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": ["*bdoc"], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["*deb", "udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": ["*iso"], "application/x-iwork-keynote-sffkey": ["*key"], "application/x-iwork-numbers-sffnumbers": ["*numbers"], "application/x-iwork-pages-sffpages": ["*pages"], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-keepass2": ["kdbx"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": ["*exe"], "application/x-msdownload": ["*exe", "*dll", "com", "bat", "*msi"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["*wmf", "*wmz", "*emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": ["*prc", "*pdb"], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["*rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["*obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["*xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": ["*m4a"], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": ["*ra"], "audio/x-wav": ["*wav"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "image/prs.btif": ["btif"], "image/prs.pti": ["pti"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.airzip.accelerator.azv": ["azv"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": ["*sub"], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.microsoft.icon": ["ico"], "image/vnd.ms-dds": ["dds"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.pco.b16": ["b16"], "image/vnd.tencent.tap": ["tap"], "image/vnd.valve.source.texture": ["vtf"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/vnd.zbrush.pcx": ["pcx"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["*ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": ["*bmp"], "image/x-pcx": ["*pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/vnd.wfa.wsc": ["wsc"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.opengex": ["ogex"], "model/vnd.parasolid.transmit.binary": ["x_b"], "model/vnd.parasolid.transmit.text": ["x_t"], "model/vnd.sap.vds": ["vds"], "model/vnd.usdz+zip": ["usdz"], "model/vnd.valve.source.compiled-map": ["bsp"], "model/vnd.vtu": ["vtu"], "text/prs.lines.tag": ["dsc"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": ["*org"], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] };
  9349. /***/ }),
  9350. /* 27 */
  9351. /***/ (function(module, exports, __webpack_require__) {
  9352. "use strict";
  9353. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  9354. var session = __webpack_require__(6);
  9355. var Async = __webpack_require__(28);
  9356. var EventProxy = __webpack_require__(5).EventProxy;
  9357. var util = __webpack_require__(0);
  9358. // 文件分块上传全过程,暴露的分块上传接口
  9359. function sliceUploadFile(params, callback) {
  9360. var self = this;
  9361. // 如果小程序版本不支持获取文件分片内容,统一转到 postObject 接口上传
  9362. if (!util.canFileSlice()) {
  9363. params.SkipTask = true;
  9364. self.postObject(params, callback);
  9365. return;
  9366. }
  9367. var ep = new EventProxy();
  9368. var TaskId = params.TaskId;
  9369. var Bucket = params.Bucket;
  9370. var Region = params.Region;
  9371. var Key = params.Key;
  9372. var FilePath = params.FilePath;
  9373. var ChunkSize = params.ChunkSize || params.SliceSize || self.options.ChunkSize;
  9374. var AsyncLimit = params.AsyncLimit;
  9375. var StorageClass = params.StorageClass;
  9376. var ServerSideEncryption = params.ServerSideEncryption;
  9377. var FileSize;
  9378. var onProgress;
  9379. var onHashProgress = params.onHashProgress;
  9380. // 上传过程中出现错误,返回错误
  9381. ep.on('error', function (err) {
  9382. if (!self._isRunningTask(TaskId)) return;
  9383. var _err = {
  9384. UploadId: params.UploadData.UploadId || '',
  9385. err: err
  9386. };
  9387. return callback(_err);
  9388. });
  9389. // 上传分块完成,开始 uploadSliceComplete 操作
  9390. ep.on('upload_complete', function (UploadCompleteData) {
  9391. var _UploadCompleteData = util.extend({
  9392. UploadId: params.UploadData.UploadId || ''
  9393. }, UploadCompleteData);
  9394. callback(null, _UploadCompleteData);
  9395. });
  9396. // 上传分块完成,开始 uploadSliceComplete 操作
  9397. ep.on('upload_slice_complete', function (UploadData) {
  9398. uploadSliceComplete.call(self, {
  9399. Bucket: Bucket,
  9400. Region: Region,
  9401. Key: Key,
  9402. UploadId: UploadData.UploadId,
  9403. SliceList: UploadData.SliceList
  9404. }, function (err, data) {
  9405. if (!self._isRunningTask(TaskId)) return;
  9406. session.removeUsing(UploadData.UploadId);
  9407. if (err) {
  9408. onProgress(null, true);
  9409. return ep.emit('error', err);
  9410. }
  9411. session.removeUploadId(UploadData.UploadId);
  9412. onProgress({ loaded: FileSize, total: FileSize }, true);
  9413. ep.emit('upload_complete', data);
  9414. });
  9415. });
  9416. // 获取 UploadId 完成,开始上传每个分片
  9417. ep.on('get_upload_data_finish', function (UploadData) {
  9418. // 处理 UploadId 缓存
  9419. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key);
  9420. uuid && session.saveUploadId(uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // 缓存 UploadId
  9421. session.setUsing(UploadData.UploadId); // 标记 UploadId 为正在使用
  9422. // 获取 UploadId
  9423. onProgress(null, true); // 任务状态开始 uploading
  9424. uploadSliceList.call(self, {
  9425. TaskId: TaskId,
  9426. Bucket: Bucket,
  9427. Region: Region,
  9428. Key: Key,
  9429. FilePath: FilePath,
  9430. FileSize: FileSize,
  9431. SliceSize: ChunkSize,
  9432. AsyncLimit: AsyncLimit,
  9433. ServerSideEncryption: ServerSideEncryption,
  9434. UploadData: UploadData,
  9435. onProgress: onProgress
  9436. }, function (err, data) {
  9437. if (!self._isRunningTask(TaskId)) return;
  9438. if (err) {
  9439. onProgress(null, true);
  9440. return ep.emit('error', err);
  9441. }
  9442. ep.emit('upload_slice_complete', data);
  9443. });
  9444. });
  9445. // 开始获取文件 UploadId,里面会视情况计算 ETag,并比对,保证文件一致性,也优化上传
  9446. ep.on('get_file_size_finish', function () {
  9447. onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  9448. if (params.UploadData.UploadId) {
  9449. ep.emit('get_upload_data_finish', params.UploadData);
  9450. } else {
  9451. var _params = util.extend({
  9452. TaskId: TaskId,
  9453. Bucket: Bucket,
  9454. Region: Region,
  9455. Key: Key,
  9456. Headers: params.Headers,
  9457. StorageClass: StorageClass,
  9458. FilePath: FilePath,
  9459. FileSize: FileSize,
  9460. SliceSize: ChunkSize,
  9461. onHashProgress: onHashProgress
  9462. }, params);
  9463. getUploadIdAndPartList.call(self, _params, function (err, UploadData) {
  9464. if (!self._isRunningTask(TaskId)) return;
  9465. if (err) return ep.emit('error', err);
  9466. params.UploadData.UploadId = UploadData.UploadId;
  9467. params.UploadData.PartList = UploadData.PartList;
  9468. ep.emit('get_upload_data_finish', params.UploadData);
  9469. });
  9470. }
  9471. });
  9472. // 获取上传文件大小
  9473. FileSize = params.ContentLength;
  9474. delete params.ContentLength;
  9475. !params.Headers && (params.Headers = {});
  9476. util.each(params.Headers, function (item, key) {
  9477. if (key.toLowerCase() === 'content-length') {
  9478. delete params.Headers[key];
  9479. }
  9480. });
  9481. // 控制分片大小
  9482. (function () {
  9483. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  9484. var AutoChunkSize = 1024 * 1024;
  9485. for (var i = 0; i < SIZE.length; i++) {
  9486. AutoChunkSize = SIZE[i] * 1024 * 1024;
  9487. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  9488. }
  9489. params.ChunkSize = params.SliceSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  9490. })();
  9491. // 开始上传
  9492. if (FileSize === 0) {
  9493. params.Body = '';
  9494. params.ContentLength = 0;
  9495. params.SkipTask = true;
  9496. self.putObject(params, function (err, data) {
  9497. if (err) {
  9498. return callback(err);
  9499. }
  9500. callback(null, data);
  9501. });
  9502. } else {
  9503. ep.emit('get_file_size_finish');
  9504. }
  9505. }
  9506. // 获取上传任务的 UploadId
  9507. function getUploadIdAndPartList(params, callback) {
  9508. var TaskId = params.TaskId;
  9509. var Bucket = params.Bucket;
  9510. var Region = params.Region;
  9511. var Key = params.Key;
  9512. var StorageClass = params.StorageClass;
  9513. var self = this;
  9514. // 计算 ETag
  9515. var ETagMap = {};
  9516. var FileSize = params.FileSize;
  9517. var SliceSize = params.SliceSize;
  9518. var SliceCount = Math.ceil(FileSize / SliceSize);
  9519. var FinishSliceCount = 0;
  9520. var FinishSize = 0;
  9521. var onHashProgress = util.throttleOnProgress.call(self, FileSize, params.onHashProgress);
  9522. var getChunkETag = function getChunkETag(PartNumber, callback) {
  9523. var start = SliceSize * (PartNumber - 1);
  9524. var end = Math.min(start + SliceSize, FileSize);
  9525. var ChunkSize = end - start;
  9526. if (ETagMap[PartNumber]) {
  9527. callback(null, {
  9528. PartNumber: PartNumber,
  9529. ETag: ETagMap[PartNumber],
  9530. Size: ChunkSize
  9531. });
  9532. } else {
  9533. util.fileSlice(params.FilePath, start, end, function (chunkItem) {
  9534. try {
  9535. var md5 = util.getFileMd5(chunkItem);
  9536. } catch (err) {
  9537. return callback(err);
  9538. }
  9539. var ETag = '"' + md5 + '"';
  9540. ETagMap[PartNumber] = ETag;
  9541. FinishSliceCount += 1;
  9542. FinishSize += ChunkSize;
  9543. callback(null, {
  9544. PartNumber: PartNumber,
  9545. ETag: ETag,
  9546. Size: ChunkSize
  9547. });
  9548. onHashProgress({ loaded: FinishSize, total: FileSize });
  9549. });
  9550. }
  9551. };
  9552. // 通过和文件的 md5 对比,判断 UploadId 是否可用
  9553. var isAvailableUploadList = function isAvailableUploadList(PartList, callback) {
  9554. var PartCount = PartList.length;
  9555. // 如果没有分片,通过
  9556. if (PartCount === 0) {
  9557. return callback(null, true);
  9558. }
  9559. // 检查分片数量
  9560. if (PartCount > SliceCount) {
  9561. return callback(null, false);
  9562. }
  9563. // 检查分片大小
  9564. if (PartCount > 1) {
  9565. var PartSliceSize = Math.max(PartList[0].Size, PartList[1].Size);
  9566. if (PartSliceSize !== SliceSize) {
  9567. return callback(null, false);
  9568. }
  9569. }
  9570. // 逐个分片计算并检查 ETag 是否一致
  9571. var next = function next(index) {
  9572. if (index < PartCount) {
  9573. var Part = PartList[index];
  9574. getChunkETag(Part.PartNumber, function (err, chunk) {
  9575. if (chunk && chunk.ETag === Part.ETag && chunk.Size === Part.Size) {
  9576. next(index + 1);
  9577. } else {
  9578. callback(null, false);
  9579. }
  9580. });
  9581. } else {
  9582. callback(null, true);
  9583. }
  9584. };
  9585. next(0);
  9586. };
  9587. var ep = new EventProxy();
  9588. ep.on('error', function (errData) {
  9589. if (!self._isRunningTask(TaskId)) return;
  9590. return callback(errData);
  9591. });
  9592. // 存在 UploadId
  9593. ep.on('upload_id_available', function (UploadData) {
  9594. // 转换成 map
  9595. var map = {};
  9596. var list = [];
  9597. util.each(UploadData.PartList, function (item) {
  9598. map[item.PartNumber] = item;
  9599. });
  9600. for (var PartNumber = 1; PartNumber <= SliceCount; PartNumber++) {
  9601. var item = map[PartNumber];
  9602. if (item) {
  9603. item.PartNumber = PartNumber;
  9604. item.Uploaded = true;
  9605. } else {
  9606. item = {
  9607. PartNumber: PartNumber,
  9608. ETag: null,
  9609. Uploaded: false
  9610. };
  9611. }
  9612. list.push(item);
  9613. }
  9614. UploadData.PartList = list;
  9615. callback(null, UploadData);
  9616. });
  9617. // 不存在 UploadId, 初始化生成 UploadId
  9618. ep.on('no_available_upload_id', function () {
  9619. if (!self._isRunningTask(TaskId)) return;
  9620. var _params = util.extend({
  9621. Bucket: Bucket,
  9622. Region: Region,
  9623. Key: Key,
  9624. Headers: util.clone(params.Headers),
  9625. Query: util.clone(params.Query),
  9626. StorageClass: StorageClass
  9627. }, params);
  9628. self.multipartInit(_params, function (err, data) {
  9629. if (!self._isRunningTask(TaskId)) return;
  9630. if (err) return ep.emit('error', err);
  9631. var UploadId = data.UploadId;
  9632. if (!UploadId) {
  9633. return callback({ Message: 'no upload id' });
  9634. }
  9635. ep.emit('upload_id_available', { UploadId: UploadId, PartList: [] });
  9636. });
  9637. });
  9638. // 如果已存在 UploadId,找一个可以用的 UploadId
  9639. ep.on('has_and_check_upload_id', function (UploadIdList) {
  9640. // 串行地,找一个内容一致的 UploadId
  9641. UploadIdList = UploadIdList.reverse();
  9642. Async.eachLimit(UploadIdList, 1, function (UploadId, asyncCallback) {
  9643. if (!self._isRunningTask(TaskId)) return;
  9644. // 如果正在上传,跳过
  9645. if (session.using[UploadId]) {
  9646. asyncCallback(); // 检查下一个 UploadId
  9647. return;
  9648. }
  9649. // 判断 UploadId 是否可用
  9650. wholeMultipartListPart.call(self, {
  9651. Bucket: Bucket,
  9652. Region: Region,
  9653. Key: Key,
  9654. UploadId: UploadId
  9655. }, function (err, PartListData) {
  9656. if (!self._isRunningTask(TaskId)) return;
  9657. if (err) {
  9658. session.removeUsing(UploadId);
  9659. return ep.emit('error', err);
  9660. }
  9661. var PartList = PartListData.PartList;
  9662. PartList.forEach(function (item) {
  9663. item.PartNumber *= 1;
  9664. item.Size *= 1;
  9665. item.ETag = item.ETag || '';
  9666. });
  9667. isAvailableUploadList(PartList, function (err, isAvailable) {
  9668. if (!self._isRunningTask(TaskId)) return;
  9669. if (err) return ep.emit('error', err);
  9670. if (isAvailable) {
  9671. asyncCallback({
  9672. UploadId: UploadId,
  9673. PartList: PartList
  9674. }); // 马上结束
  9675. } else {
  9676. asyncCallback(); // 检查下一个 UploadId
  9677. }
  9678. });
  9679. });
  9680. }, function (AvailableUploadData) {
  9681. if (!self._isRunningTask(TaskId)) return;
  9682. onHashProgress(null, true);
  9683. if (AvailableUploadData && AvailableUploadData.UploadId) {
  9684. ep.emit('upload_id_available', AvailableUploadData);
  9685. } else {
  9686. ep.emit('no_available_upload_id');
  9687. }
  9688. });
  9689. });
  9690. // 在本地缓存找可用的 UploadId
  9691. ep.on('seek_local_avail_upload_id', function (RemoteUploadIdList) {
  9692. // 在本地找可用的 UploadId
  9693. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key);
  9694. var LocalUploadIdList = session.getUploadIdList(uuid);
  9695. if (!uuid || !LocalUploadIdList) {
  9696. ep.emit('has_and_check_upload_id', RemoteUploadIdList);
  9697. return;
  9698. }
  9699. var next = function next(index) {
  9700. // 如果本地找不到可用 UploadId,再一个个遍历校验远端
  9701. if (index >= LocalUploadIdList.length) {
  9702. ep.emit('has_and_check_upload_id', RemoteUploadIdList);
  9703. return;
  9704. }
  9705. var UploadId = LocalUploadIdList[index];
  9706. // 如果不在远端 UploadId 列表里,跳过并删除
  9707. if (!util.isInArray(RemoteUploadIdList, UploadId)) {
  9708. session.removeUploadId(UploadId);
  9709. next(index + 1);
  9710. return;
  9711. }
  9712. // 如果正在上传,跳过
  9713. if (session.using[UploadId]) {
  9714. next(index + 1);
  9715. return;
  9716. }
  9717. // 判断 UploadId 是否存在线上
  9718. wholeMultipartListPart.call(self, {
  9719. Bucket: Bucket,
  9720. Region: Region,
  9721. Key: Key,
  9722. UploadId: UploadId
  9723. }, function (err, PartListData) {
  9724. if (!self._isRunningTask(TaskId)) return;
  9725. if (err) {
  9726. // 如果 UploadId 获取会出错,跳过并删除
  9727. session.removeUploadId(UploadId);
  9728. next(index + 1);
  9729. } else {
  9730. // 找到可用 UploadId
  9731. ep.emit('upload_id_available', {
  9732. UploadId: UploadId,
  9733. PartList: PartListData.PartList
  9734. });
  9735. }
  9736. });
  9737. };
  9738. next(0);
  9739. });
  9740. // 获取线上 UploadId 列表
  9741. ep.on('get_remote_upload_id_list', function () {
  9742. // 获取符合条件的 UploadId 列表,因为同一个文件可以有多个上传任务。
  9743. wholeMultipartList.call(self, {
  9744. Bucket: Bucket,
  9745. Region: Region,
  9746. Key: Key
  9747. }, function (err, data) {
  9748. if (!self._isRunningTask(TaskId)) return;
  9749. if (err) {
  9750. return ep.emit('error', err);
  9751. }
  9752. // 整理远端 UploadId 列表
  9753. var RemoteUploadIdList = util.filter(data.UploadList, function (item) {
  9754. return item.Key === Key && (!StorageClass || item.StorageClass.toUpperCase() === StorageClass.toUpperCase());
  9755. }).reverse().map(function (item) {
  9756. return item.UploadId || item.UploadID;
  9757. });
  9758. if (RemoteUploadIdList.length) {
  9759. ep.emit('seek_local_avail_upload_id', RemoteUploadIdList);
  9760. } else {
  9761. // 远端没有 UploadId,清理缓存的 UploadId
  9762. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key),
  9763. LocalUploadIdList;
  9764. if (uuid && (LocalUploadIdList = session.getUploadIdList(uuid))) {
  9765. util.each(LocalUploadIdList, function (UploadId) {
  9766. session.removeUploadId(UploadId);
  9767. });
  9768. }
  9769. ep.emit('no_available_upload_id');
  9770. }
  9771. });
  9772. });
  9773. // 开始找可用 UploadId
  9774. ep.emit('get_remote_upload_id_list');
  9775. }
  9776. // 获取符合条件的全部上传任务 (条件包括 Bucket, Region, Prefix)
  9777. function wholeMultipartList(params, callback) {
  9778. var self = this;
  9779. var UploadList = [];
  9780. var sendParams = {
  9781. Bucket: params.Bucket,
  9782. Region: params.Region,
  9783. Prefix: params.Key
  9784. };
  9785. var next = function next() {
  9786. self.multipartList(sendParams, function (err, data) {
  9787. if (err) return callback(err);
  9788. UploadList.push.apply(UploadList, data.Upload || []);
  9789. if (data.IsTruncated === 'true') {
  9790. // 列表不完整
  9791. sendParams.KeyMarker = data.NextKeyMarker;
  9792. sendParams.UploadIdMarker = data.NextUploadIdMarker;
  9793. next();
  9794. } else {
  9795. callback(null, { UploadList: UploadList });
  9796. }
  9797. });
  9798. };
  9799. next();
  9800. }
  9801. // 获取指定上传任务的分块列表
  9802. function wholeMultipartListPart(params, callback) {
  9803. var self = this;
  9804. var PartList = [];
  9805. var sendParams = {
  9806. Bucket: params.Bucket,
  9807. Region: params.Region,
  9808. Key: params.Key,
  9809. UploadId: params.UploadId
  9810. };
  9811. var next = function next() {
  9812. self.multipartListPart(sendParams, function (err, data) {
  9813. if (err) return callback(err);
  9814. PartList.push.apply(PartList, data.Part || []);
  9815. if (data.IsTruncated === 'true') {
  9816. // 列表不完整
  9817. sendParams.PartNumberMarker = data.NextPartNumberMarker;
  9818. next();
  9819. } else {
  9820. callback(null, { PartList: PartList });
  9821. }
  9822. });
  9823. };
  9824. next();
  9825. }
  9826. // 上传文件分块,包括
  9827. /*
  9828. UploadId (上传任务编号)
  9829. AsyncLimit (并发量),
  9830. SliceList (上传的分块数组),
  9831. FilePath (本地文件的位置),
  9832. SliceSize (文件分块大小)
  9833. FileSize (文件大小)
  9834. onProgress (上传成功之后的回调函数)
  9835. */
  9836. function uploadSliceList(params, cb) {
  9837. var self = this;
  9838. var TaskId = params.TaskId;
  9839. var Bucket = params.Bucket;
  9840. var Region = params.Region;
  9841. var Key = params.Key;
  9842. var UploadData = params.UploadData;
  9843. var FileSize = params.FileSize;
  9844. var SliceSize = params.SliceSize;
  9845. var ChunkParallel = Math.min(params.AsyncLimit || self.options.ChunkParallelLimit || 1, 256);
  9846. var FilePath = params.FilePath;
  9847. var SliceCount = Math.ceil(FileSize / SliceSize);
  9848. var FinishSize = 0;
  9849. var ServerSideEncryption = params.ServerSideEncryption;
  9850. var needUploadSlices = util.filter(UploadData.PartList, function (SliceItem) {
  9851. if (SliceItem['Uploaded']) {
  9852. FinishSize += SliceItem['PartNumber'] >= SliceCount ? FileSize % SliceSize || SliceSize : SliceSize;
  9853. }
  9854. return !SliceItem['Uploaded'];
  9855. });
  9856. var _onProgress2 = params.onProgress;
  9857. Async.eachLimit(needUploadSlices, ChunkParallel, function (SliceItem, asyncCallback) {
  9858. if (!self._isRunningTask(TaskId)) return;
  9859. var PartNumber = SliceItem['PartNumber'];
  9860. var currentSize = Math.min(FileSize, SliceItem['PartNumber'] * SliceSize) - (SliceItem['PartNumber'] - 1) * SliceSize;
  9861. var preAddSize = 0;
  9862. uploadSliceItem.call(self, {
  9863. TaskId: TaskId,
  9864. Bucket: Bucket,
  9865. Region: Region,
  9866. Key: Key,
  9867. SliceSize: SliceSize,
  9868. FileSize: FileSize,
  9869. PartNumber: PartNumber,
  9870. ServerSideEncryption: ServerSideEncryption,
  9871. FilePath: FilePath,
  9872. UploadData: UploadData,
  9873. onProgress: function onProgress(data) {
  9874. FinishSize += data.loaded - preAddSize;
  9875. preAddSize = data.loaded;
  9876. _onProgress2({ loaded: FinishSize, total: FileSize });
  9877. }
  9878. }, function (err, data) {
  9879. if (!self._isRunningTask(TaskId)) return;
  9880. if (err) {
  9881. FinishSize -= preAddSize;
  9882. } else {
  9883. FinishSize += currentSize - preAddSize;
  9884. SliceItem.ETag = data.ETag;
  9885. }
  9886. _onProgress2({ loaded: FinishSize, total: FileSize });
  9887. asyncCallback(err || null, data);
  9888. });
  9889. }, function (err) {
  9890. if (!self._isRunningTask(TaskId)) return;
  9891. if (err) return cb(err);
  9892. cb(null, {
  9893. UploadId: UploadData.UploadId,
  9894. SliceList: UploadData.PartList
  9895. });
  9896. });
  9897. }
  9898. // 上传指定分片
  9899. function uploadSliceItem(params, callback) {
  9900. var self = this;
  9901. var TaskId = params.TaskId;
  9902. var Bucket = params.Bucket;
  9903. var Region = params.Region;
  9904. var Key = params.Key;
  9905. var FileSize = params.FileSize;
  9906. var FilePath = params.FilePath;
  9907. var PartNumber = params.PartNumber * 1;
  9908. var SliceSize = params.SliceSize;
  9909. var ServerSideEncryption = params.ServerSideEncryption;
  9910. var UploadData = params.UploadData;
  9911. var ChunkRetryTimes = self.options.ChunkRetryTimes + 1;
  9912. var Headers = params.Headers || {};
  9913. var start = SliceSize * (PartNumber - 1);
  9914. var ContentLength = SliceSize;
  9915. var end = start + SliceSize;
  9916. if (end > FileSize) {
  9917. end = FileSize;
  9918. ContentLength = end - start;
  9919. }
  9920. var headersWhiteList = ['x-cos-traffic-limit', 'x-cos-mime-limit'];
  9921. var headers = {};
  9922. util.each(Headers, function (v, k) {
  9923. if (headersWhiteList.indexOf(k) > -1) {
  9924. headers[k] = v;
  9925. }
  9926. });
  9927. util.fileSlice(FilePath, start, end, function (Body) {
  9928. var md5 = util.getFileMd5(Body);
  9929. var contentMd5 = md5 ? util.binaryBase64(md5) : null;
  9930. var PartItem = UploadData.PartList[PartNumber - 1];
  9931. Async.retry(ChunkRetryTimes, function (tryCallback) {
  9932. if (!self._isRunningTask(TaskId)) return;
  9933. self.multipartUpload({
  9934. TaskId: TaskId,
  9935. Bucket: Bucket,
  9936. Region: Region,
  9937. Key: Key,
  9938. ContentLength: ContentLength,
  9939. PartNumber: PartNumber,
  9940. UploadId: UploadData.UploadId,
  9941. ServerSideEncryption: ServerSideEncryption,
  9942. Body: Body,
  9943. Headers: headers,
  9944. onProgress: params.onProgress,
  9945. ContentMD5: contentMd5
  9946. }, function (err, data) {
  9947. if (!self._isRunningTask(TaskId)) return;
  9948. if (err) {
  9949. return tryCallback(err);
  9950. } else {
  9951. PartItem.Uploaded = true;
  9952. return tryCallback(null, data);
  9953. }
  9954. });
  9955. }, function (err, data) {
  9956. if (!self._isRunningTask(TaskId)) return;
  9957. return callback(err, data);
  9958. });
  9959. });
  9960. }
  9961. // 完成分块上传
  9962. function uploadSliceComplete(params, callback) {
  9963. var Bucket = params.Bucket;
  9964. var Region = params.Region;
  9965. var Key = params.Key;
  9966. var UploadId = params.UploadId;
  9967. var SliceList = params.SliceList;
  9968. var self = this;
  9969. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  9970. var Parts = SliceList.map(function (item) {
  9971. return {
  9972. PartNumber: item.PartNumber,
  9973. ETag: item.ETag
  9974. };
  9975. });
  9976. // 完成上传的请求也做重试
  9977. Async.retry(ChunkRetryTimes, function (tryCallback) {
  9978. self.multipartComplete({
  9979. Bucket: Bucket,
  9980. Region: Region,
  9981. Key: Key,
  9982. UploadId: UploadId,
  9983. Parts: Parts
  9984. }, tryCallback);
  9985. }, function (err, data) {
  9986. callback(err, data);
  9987. });
  9988. }
  9989. // 抛弃分块上传任务
  9990. /*
  9991. AsyncLimit (抛弃上传任务的并发量),
  9992. UploadId (上传任务的编号,当 Level 为 task 时候需要)
  9993. Level (抛弃分块上传任务的级别,task : 抛弃指定的上传任务,file : 抛弃指定的文件对应的上传任务,其他值 :抛弃指定Bucket 的全部上传任务)
  9994. */
  9995. function abortUploadTask(params, callback) {
  9996. var Bucket = params.Bucket;
  9997. var Region = params.Region;
  9998. var Key = params.Key;
  9999. var UploadId = params.UploadId;
  10000. var Level = params.Level || 'task';
  10001. var AsyncLimit = params.AsyncLimit;
  10002. var self = this;
  10003. var ep = new EventProxy();
  10004. ep.on('error', function (errData) {
  10005. return callback(errData);
  10006. });
  10007. // 已经获取到需要抛弃的任务列表
  10008. ep.on('get_abort_array', function (AbortArray) {
  10009. abortUploadTaskArray.call(self, {
  10010. Bucket: Bucket,
  10011. Region: Region,
  10012. Key: Key,
  10013. Headers: params.Headers,
  10014. AsyncLimit: AsyncLimit,
  10015. AbortArray: AbortArray
  10016. }, function (err, data) {
  10017. if (err) {
  10018. return callback(err);
  10019. }
  10020. callback(null, data);
  10021. });
  10022. });
  10023. if (Level === 'bucket') {
  10024. // Bucket 级别的任务抛弃,抛弃该 Bucket 下的全部上传任务
  10025. wholeMultipartList.call(self, {
  10026. Bucket: Bucket,
  10027. Region: Region
  10028. }, function (err, data) {
  10029. if (err) {
  10030. return callback(err);
  10031. }
  10032. ep.emit('get_abort_array', data.UploadList || []);
  10033. });
  10034. } else if (Level === 'file') {
  10035. // 文件级别的任务抛弃,抛弃该文件的全部上传任务
  10036. if (!Key) return callback({ error: 'abort_upload_task_no_key' });
  10037. wholeMultipartList.call(self, {
  10038. Bucket: Bucket,
  10039. Region: Region,
  10040. Key: Key
  10041. }, function (err, data) {
  10042. if (err) {
  10043. return callback(err);
  10044. }
  10045. ep.emit('get_abort_array', data.UploadList || []);
  10046. });
  10047. } else if (Level === 'task') {
  10048. // 单个任务级别的任务抛弃,抛弃指定 UploadId 的上传任务
  10049. if (!UploadId) return callback({ error: 'abort_upload_task_no_id' });
  10050. if (!Key) return callback({ error: 'abort_upload_task_no_key' });
  10051. ep.emit('get_abort_array', [{
  10052. Key: Key,
  10053. UploadId: UploadId
  10054. }]);
  10055. } else {
  10056. return callback({ error: 'abort_unknown_level' });
  10057. }
  10058. }
  10059. // 批量抛弃分块上传任务
  10060. function abortUploadTaskArray(params, callback) {
  10061. var Bucket = params.Bucket;
  10062. var Region = params.Region;
  10063. var Key = params.Key;
  10064. var AbortArray = params.AbortArray;
  10065. var AsyncLimit = params.AsyncLimit || 1;
  10066. var self = this;
  10067. var index = 0;
  10068. var resultList = new Array(AbortArray.length);
  10069. Async.eachLimit(AbortArray, AsyncLimit, function (AbortItem, callback) {
  10070. var eachIndex = index;
  10071. if (Key && Key !== AbortItem.Key) {
  10072. resultList[eachIndex] = { error: { KeyNotMatch: true } };
  10073. callback(null);
  10074. return;
  10075. }
  10076. var UploadId = AbortItem.UploadId || AbortItem.UploadID;
  10077. self.multipartAbort({
  10078. Bucket: Bucket,
  10079. Region: Region,
  10080. Key: AbortItem.Key,
  10081. Headers: params.Headers,
  10082. UploadId: UploadId
  10083. }, function (err) {
  10084. var task = {
  10085. Bucket: Bucket,
  10086. Region: Region,
  10087. Key: AbortItem.Key,
  10088. UploadId: UploadId
  10089. };
  10090. resultList[eachIndex] = { error: err, task: task };
  10091. callback(null);
  10092. });
  10093. index++;
  10094. }, function (err) {
  10095. if (err) {
  10096. return callback(err);
  10097. }
  10098. var successList = [];
  10099. var errorList = [];
  10100. for (var i = 0, len = resultList.length; i < len; i++) {
  10101. var item = resultList[i];
  10102. if (item['task']) {
  10103. if (item['error']) {
  10104. errorList.push(item['task']);
  10105. } else {
  10106. successList.push(item['task']);
  10107. }
  10108. }
  10109. }
  10110. return callback(null, {
  10111. successList: successList,
  10112. errorList: errorList
  10113. });
  10114. });
  10115. }
  10116. // 高级上传
  10117. function uploadFile(params, callback) {
  10118. var self = this;
  10119. // 判断多大的文件使用分片上传
  10120. var SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;
  10121. var taskList = [];
  10122. var FileSize = params.FileSize;
  10123. var fileInfo = { TaskId: '' };
  10124. // 整理 option,用于返回给回调
  10125. util.each(params, function (v, k) {
  10126. if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object' && typeof v !== 'function') {
  10127. fileInfo[k] = v;
  10128. }
  10129. });
  10130. // 处理文件 TaskReady
  10131. var _onTaskReady = params.onTaskReady;
  10132. params.onTaskReady = function (tid) {
  10133. fileInfo.TaskId = tid;
  10134. _onTaskReady && _onTaskReady(tid);
  10135. };
  10136. // 处理文件完成
  10137. var _onFileFinish = params.onFileFinish;
  10138. var onFileFinish = function onFileFinish(err, data) {
  10139. _onFileFinish && _onFileFinish(err, data, fileInfo);
  10140. callback && callback(err, data);
  10141. };
  10142. // 添加上传任务
  10143. var api = FileSize > SliceSize ? 'sliceUploadFile' : 'postObject';
  10144. taskList.push({
  10145. api: api,
  10146. params: params,
  10147. callback: onFileFinish
  10148. });
  10149. self._addTasks(taskList);
  10150. }
  10151. // 批量上传文件
  10152. function uploadFiles(params, callback) {
  10153. var self = this;
  10154. // 判断多大的文件使用分片上传
  10155. var SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;
  10156. // 汇总返回进度
  10157. var TotalSize = 0;
  10158. var TotalFinish = 0;
  10159. var onTotalProgress = util.throttleOnProgress.call(self, TotalFinish, params.onProgress);
  10160. // 汇总返回回调
  10161. var unFinishCount = params.files.length;
  10162. var _onTotalFileFinish = params.onFileFinish;
  10163. var resultList = Array(unFinishCount);
  10164. var onTotalFileFinish = function onTotalFileFinish(err, data, options) {
  10165. onTotalProgress(null, true);
  10166. _onTotalFileFinish && _onTotalFileFinish(err, data, options);
  10167. resultList[options.Index] = {
  10168. options: options,
  10169. error: err,
  10170. data: data
  10171. };
  10172. if (--unFinishCount <= 0 && callback) {
  10173. callback(null, {
  10174. files: resultList
  10175. });
  10176. }
  10177. };
  10178. // 开始处理每个文件
  10179. var taskList = [];
  10180. util.each(params.files, function (fileParams, index) {
  10181. var FileSize = fileParams.FileSize;
  10182. var fileInfo = { Index: index, TaskId: '' };
  10183. // 更新文件总大小
  10184. TotalSize += FileSize;
  10185. // 整理 option,用于返回给回调
  10186. util.each(fileParams, function (v, k) {
  10187. if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) !== 'object' && typeof v !== 'function') {
  10188. fileInfo[k] = v;
  10189. }
  10190. });
  10191. // 处理单个文件 TaskReady
  10192. var _onTaskReady = fileParams.onTaskReady;
  10193. fileParams.onTaskReady = function (tid) {
  10194. fileInfo.TaskId = tid;
  10195. _onTaskReady && _onTaskReady(tid);
  10196. };
  10197. // 处理单个文件进度
  10198. var PreAddSize = 0;
  10199. var _onProgress = fileParams.onProgress;
  10200. fileParams.onProgress = function (info) {
  10201. TotalFinish = TotalFinish - PreAddSize + info.loaded;
  10202. PreAddSize = info.loaded;
  10203. _onProgress && _onProgress(info);
  10204. onTotalProgress({ loaded: TotalFinish, total: TotalSize });
  10205. };
  10206. // 处理单个文件完成
  10207. var _onFileFinish = fileParams.onFileFinish;
  10208. var onFileFinish = function onFileFinish(err, data) {
  10209. _onFileFinish && _onFileFinish(err, data);
  10210. onTotalFileFinish && onTotalFileFinish(err, data, fileInfo);
  10211. };
  10212. // 添加上传任务
  10213. var api = FileSize > SliceSize ? 'sliceUploadFile' : 'postObject';
  10214. taskList.push({
  10215. api: api,
  10216. params: fileParams,
  10217. callback: onFileFinish
  10218. });
  10219. });
  10220. self._addTasks(taskList);
  10221. }
  10222. // 分片复制文件
  10223. function sliceCopyFile(params, callback) {
  10224. var ep = new EventProxy();
  10225. var self = this;
  10226. var Bucket = params.Bucket;
  10227. var Region = params.Region;
  10228. var Key = params.Key;
  10229. var CopySource = params.CopySource;
  10230. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  10231. if (!m) {
  10232. callback({ error: 'CopySource format error' });
  10233. return;
  10234. }
  10235. var SourceBucket = m[1];
  10236. var SourceRegion = m[3];
  10237. var SourceKey = decodeURIComponent(m[4]);
  10238. var CopySliceSize = params.CopySliceSize === undefined ? self.options.CopySliceSize : params.CopySliceSize;
  10239. CopySliceSize = Math.max(0, CopySliceSize);
  10240. var ChunkSize = params.CopyChunkSize || this.options.CopyChunkSize;
  10241. var ChunkParallel = this.options.CopyChunkParallelLimit;
  10242. var FinishSize = 0;
  10243. var FileSize;
  10244. var _onProgress3;
  10245. // 分片复制完成,开始 multipartComplete 操作
  10246. ep.on('copy_slice_complete', function (UploadData) {
  10247. self.multipartComplete({
  10248. Bucket: Bucket,
  10249. Region: Region,
  10250. Key: Key,
  10251. UploadId: UploadData.UploadId,
  10252. Parts: UploadData.PartList
  10253. }, function (err, data) {
  10254. if (err) {
  10255. _onProgress3(null, true);
  10256. return callback(err);
  10257. }
  10258. _onProgress3({ loaded: FileSize, total: FileSize }, true);
  10259. callback(null, data);
  10260. });
  10261. });
  10262. ep.on('get_copy_data_finish', function (UploadData) {
  10263. Async.eachLimit(UploadData.PartList, ChunkParallel, function (SliceItem, asyncCallback) {
  10264. var PartNumber = SliceItem.PartNumber;
  10265. var CopySourceRange = SliceItem.CopySourceRange;
  10266. var currentSize = SliceItem.end - SliceItem.start;
  10267. var preAddSize = 0;
  10268. copySliceItem.call(self, {
  10269. Bucket: Bucket,
  10270. Region: Region,
  10271. Key: Key,
  10272. CopySource: CopySource,
  10273. UploadId: UploadData.UploadId,
  10274. PartNumber: PartNumber,
  10275. CopySourceRange: CopySourceRange,
  10276. onProgress: function onProgress(data) {
  10277. FinishSize += data.loaded - preAddSize;
  10278. preAddSize = data.loaded;
  10279. _onProgress3({ loaded: FinishSize, total: FileSize });
  10280. }
  10281. }, function (err, data) {
  10282. if (err) {
  10283. return asyncCallback(err);
  10284. }
  10285. _onProgress3({ loaded: FinishSize, total: FileSize });
  10286. FinishSize += currentSize - preAddSize;
  10287. SliceItem.ETag = data.ETag;
  10288. asyncCallback(err || null, data);
  10289. });
  10290. }, function (err) {
  10291. if (err) {
  10292. _onProgress3(null, true);
  10293. return callback(err);
  10294. }
  10295. ep.emit('copy_slice_complete', UploadData);
  10296. });
  10297. });
  10298. ep.on('get_file_size_finish', function (SourceHeaders) {
  10299. // 控制分片大小
  10300. (function () {
  10301. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  10302. var AutoChunkSize = 1024 * 1024;
  10303. for (var i = 0; i < SIZE.length; i++) {
  10304. AutoChunkSize = SIZE[i] * 1024 * 1024;
  10305. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  10306. }
  10307. params.ChunkSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  10308. var ChunkCount = Math.ceil(FileSize / ChunkSize);
  10309. var list = [];
  10310. for (var partNumber = 1; partNumber <= ChunkCount; partNumber++) {
  10311. var start = (partNumber - 1) * ChunkSize;
  10312. var end = partNumber * ChunkSize < FileSize ? partNumber * ChunkSize - 1 : FileSize - 1;
  10313. var item = {
  10314. PartNumber: partNumber,
  10315. start: start,
  10316. end: end,
  10317. CopySourceRange: "bytes=" + start + "-" + end
  10318. };
  10319. list.push(item);
  10320. }
  10321. params.PartList = list;
  10322. })();
  10323. var TargetHeader;
  10324. if (params.Headers['x-cos-metadata-directive'] === 'Replaced') {
  10325. TargetHeader = params.Headers;
  10326. } else {
  10327. TargetHeader = SourceHeaders;
  10328. }
  10329. TargetHeader['x-cos-storage-class'] = params.Headers['x-cos-storage-class'] || SourceHeaders['x-cos-storage-class'];
  10330. TargetHeader = util.clearKey(TargetHeader);
  10331. /**
  10332. * 对于归档存储的对象,如果未恢复副本,则不允许 Copy
  10333. */
  10334. if (SourceHeaders['x-cos-storage-class'] === 'ARCHIVE' || SourceHeaders['x-cos-storage-class'] === 'DEEP_ARCHIVE') {
  10335. var restoreHeader = SourceHeaders['x-cos-restore'];
  10336. if (!restoreHeader || restoreHeader === 'ongoing-request="true"') {
  10337. callback({ error: 'Unrestored archive object is not allowed to be copied' });
  10338. return;
  10339. }
  10340. }
  10341. /**
  10342. * 去除一些无用的头部,规避 multipartInit 出错
  10343. * 这些头部通常是在 putObjectCopy 时才使用
  10344. */
  10345. delete TargetHeader['x-cos-copy-source'];
  10346. delete TargetHeader['x-cos-metadata-directive'];
  10347. delete TargetHeader['x-cos-copy-source-If-Modified-Since'];
  10348. delete TargetHeader['x-cos-copy-source-If-Unmodified-Since'];
  10349. delete TargetHeader['x-cos-copy-source-If-Match'];
  10350. delete TargetHeader['x-cos-copy-source-If-None-Match'];
  10351. self.multipartInit({
  10352. Bucket: Bucket,
  10353. Region: Region,
  10354. Key: Key,
  10355. Headers: TargetHeader
  10356. }, function (err, data) {
  10357. if (err) {
  10358. return callback(err);
  10359. }
  10360. params.UploadId = data.UploadId;
  10361. ep.emit('get_copy_data_finish', params);
  10362. });
  10363. });
  10364. // 获取远端复制源文件的大小
  10365. self.headObject({
  10366. Bucket: SourceBucket,
  10367. Region: SourceRegion,
  10368. Key: SourceKey
  10369. }, function (err, data) {
  10370. if (err) {
  10371. if (err.statusCode && err.statusCode === 404) {
  10372. callback({ ErrorStatus: SourceKey + ' Not Exist' });
  10373. } else {
  10374. callback(err);
  10375. }
  10376. return;
  10377. }
  10378. FileSize = params.FileSize = data.headers['content-length'];
  10379. if (FileSize === undefined || !FileSize) {
  10380. callback({ error: 'get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.' });
  10381. return;
  10382. }
  10383. _onProgress3 = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  10384. // 开始上传
  10385. if (FileSize <= CopySliceSize) {
  10386. if (!params.Headers['x-cos-metadata-directive']) {
  10387. params.Headers['x-cos-metadata-directive'] = 'Copy';
  10388. }
  10389. self.putObjectCopy(params, function (err, data) {
  10390. if (err) {
  10391. _onProgress3(null, true);
  10392. return callback(err);
  10393. }
  10394. _onProgress3({ loaded: FileSize, total: FileSize }, true);
  10395. callback(err, data);
  10396. });
  10397. } else {
  10398. var resHeaders = data.headers;
  10399. var SourceHeaders = {
  10400. 'Cache-Control': resHeaders['cache-control'],
  10401. 'Content-Disposition': resHeaders['content-disposition'],
  10402. 'Content-Encoding': resHeaders['content-encoding'],
  10403. 'Content-Type': resHeaders['content-type'],
  10404. 'Expires': resHeaders['expires'],
  10405. 'x-cos-storage-class': resHeaders['x-cos-storage-class']
  10406. };
  10407. util.each(resHeaders, function (v, k) {
  10408. var metaPrefix = 'x-cos-meta-';
  10409. if (k.indexOf(metaPrefix) === 0 && k.length > metaPrefix.length) {
  10410. SourceHeaders[k] = v;
  10411. }
  10412. });
  10413. ep.emit('get_file_size_finish', SourceHeaders);
  10414. }
  10415. });
  10416. }
  10417. // 复制指定分片
  10418. function copySliceItem(params, callback) {
  10419. var TaskId = params.TaskId;
  10420. var Bucket = params.Bucket;
  10421. var Region = params.Region;
  10422. var Key = params.Key;
  10423. var CopySource = params.CopySource;
  10424. var UploadId = params.UploadId;
  10425. var PartNumber = params.PartNumber * 1;
  10426. var CopySourceRange = params.CopySourceRange;
  10427. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  10428. var self = this;
  10429. Async.retry(ChunkRetryTimes, function (tryCallback) {
  10430. self.uploadPartCopy({
  10431. TaskId: TaskId,
  10432. Bucket: Bucket,
  10433. Region: Region,
  10434. Key: Key,
  10435. CopySource: CopySource,
  10436. UploadId: UploadId,
  10437. PartNumber: PartNumber,
  10438. CopySourceRange: CopySourceRange,
  10439. onProgress: params.onProgress
  10440. }, function (err, data) {
  10441. tryCallback(err || null, data);
  10442. });
  10443. }, function (err, data) {
  10444. return callback(err, data);
  10445. });
  10446. }
  10447. var API_MAP = {
  10448. sliceUploadFile: sliceUploadFile,
  10449. abortUploadTask: abortUploadTask,
  10450. uploadFile: uploadFile,
  10451. uploadFiles: uploadFiles,
  10452. sliceCopyFile: sliceCopyFile
  10453. };
  10454. module.exports.init = function (COS, task) {
  10455. task.transferToTaskMethod(API_MAP, 'sliceUploadFile');
  10456. util.each(API_MAP, function (fn, apiName) {
  10457. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  10458. });
  10459. };
  10460. /***/ }),
  10461. /* 28 */
  10462. /***/ (function(module, exports, __webpack_require__) {
  10463. "use strict";
  10464. var eachLimit = function eachLimit(arr, limit, iterator, callback) {
  10465. callback = callback || function () {};
  10466. if (!arr.length || limit <= 0) {
  10467. return callback();
  10468. }
  10469. var completed = 0;
  10470. var started = 0;
  10471. var running = 0;
  10472. (function replenish() {
  10473. if (completed >= arr.length) {
  10474. return callback();
  10475. }
  10476. while (running < limit && started < arr.length) {
  10477. started += 1;
  10478. running += 1;
  10479. iterator(arr[started - 1], function (err) {
  10480. if (err) {
  10481. callback(err);
  10482. callback = function callback() {};
  10483. } else {
  10484. completed += 1;
  10485. running -= 1;
  10486. if (completed >= arr.length) {
  10487. callback();
  10488. } else {
  10489. replenish();
  10490. }
  10491. }
  10492. });
  10493. }
  10494. })();
  10495. };
  10496. var retry = function retry(times, iterator, callback) {
  10497. var next = function next(index) {
  10498. iterator(function (err, data) {
  10499. if (err && index < times) {
  10500. next(index + 1);
  10501. } else {
  10502. callback(err, data);
  10503. }
  10504. });
  10505. };
  10506. if (times < 1) {
  10507. callback();
  10508. } else {
  10509. next(1);
  10510. }
  10511. };
  10512. var async = {
  10513. eachLimit: eachLimit,
  10514. retry: retry
  10515. };
  10516. module.exports = async;
  10517. /***/ })
  10518. /******/ ]);
  10519. });